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 __commonJS = (cb, mod) => function __require() {
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
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/colors/lib/styles.js
var require_styles = __commonJS({
  "node_modules/colors/lib/styles.js"(exports2, module2) {
    var styles2 = {};
    module2["exports"] = styles2;
    var codes = {
      reset: [0, 0],
      bold: [1, 22],
      dim: [2, 22],
      italic: [3, 23],
      underline: [4, 24],
      inverse: [7, 27],
      hidden: [8, 28],
      strikethrough: [9, 29],
      black: [30, 39],
      red: [31, 39],
      green: [32, 39],
      yellow: [33, 39],
      blue: [34, 39],
      magenta: [35, 39],
      cyan: [36, 39],
      white: [37, 39],
      gray: [90, 39],
      grey: [90, 39],
      brightRed: [91, 39],
      brightGreen: [92, 39],
      brightYellow: [93, 39],
      brightBlue: [94, 39],
      brightMagenta: [95, 39],
      brightCyan: [96, 39],
      brightWhite: [97, 39],
      bgBlack: [40, 49],
      bgRed: [41, 49],
      bgGreen: [42, 49],
      bgYellow: [43, 49],
      bgBlue: [44, 49],
      bgMagenta: [45, 49],
      bgCyan: [46, 49],
      bgWhite: [47, 49],
      bgGray: [100, 49],
      bgGrey: [100, 49],
      bgBrightRed: [101, 49],
      bgBrightGreen: [102, 49],
      bgBrightYellow: [103, 49],
      bgBrightBlue: [104, 49],
      bgBrightMagenta: [105, 49],
      bgBrightCyan: [106, 49],
      bgBrightWhite: [107, 49],
      // legacy styles for colors pre v1.0.0
      blackBG: [40, 49],
      redBG: [41, 49],
      greenBG: [42, 49],
      yellowBG: [43, 49],
      blueBG: [44, 49],
      magentaBG: [45, 49],
      cyanBG: [46, 49],
      whiteBG: [47, 49]
    };
    Object.keys(codes).forEach(function(key) {
      var val = codes[key];
      var style = styles2[key] = [];
      style.open = "\x1B[" + val[0] + "m";
      style.close = "\x1B[" + val[1] + "m";
    });
  }
});

// node_modules/colors/lib/system/has-flag.js
var require_has_flag = __commonJS({
  "node_modules/colors/lib/system/has-flag.js"(exports2, module2) {
    "use strict";
    module2.exports = function(flag, argv) {
      argv = argv || process.argv;
      var terminatorPos = argv.indexOf("--");
      var prefix = /^-{1,2}/.test(flag) ? "" : "--";
      var pos = argv.indexOf(prefix + flag);
      return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos);
    };
  }
});

// node_modules/colors/lib/system/supports-colors.js
var require_supports_colors = __commonJS({
  "node_modules/colors/lib/system/supports-colors.js"(exports2, module2) {
    "use strict";
    var os2 = require("os");
    var hasFlag = require_has_flag();
    var env = process.env;
    var forceColor = void 0;
    if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false")) {
      forceColor = false;
    } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) {
      forceColor = true;
    }
    if ("FORCE_COLOR" in env) {
      forceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0;
    }
    function translateLevel(level) {
      if (level === 0) {
        return false;
      }
      return {
        level,
        hasBasic: true,
        has256: level >= 2,
        has16m: level >= 3
      };
    }
    function supportsColor(stream) {
      if (forceColor === false) {
        return 0;
      }
      if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) {
        return 3;
      }
      if (hasFlag("color=256")) {
        return 2;
      }
      if (stream && !stream.isTTY && forceColor !== true) {
        return 0;
      }
      var min = forceColor ? 1 : 0;
      if (process.platform === "win32") {
        var osRelease = os2.release().split(".");
        if (Number(process.versions.node.split(".")[0]) >= 8 && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
          return Number(osRelease[2]) >= 14931 ? 3 : 2;
        }
        return 1;
      }
      if ("CI" in env) {
        if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI"].some(function(sign) {
          return sign in env;
        }) || env.CI_NAME === "codeship") {
          return 1;
        }
        return min;
      }
      if ("TEAMCITY_VERSION" in env) {
        return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
      }
      if ("TERM_PROGRAM" in env) {
        var version = parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
        switch (env.TERM_PROGRAM) {
          case "iTerm.app":
            return version >= 3 ? 3 : 2;
          case "Hyper":
            return 3;
          case "Apple_Terminal":
            return 2;
        }
      }
      if (/-256(color)?$/i.test(env.TERM)) {
        return 2;
      }
      if (/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
        return 1;
      }
      if ("COLORTERM" in env) {
        return 1;
      }
      if (env.TERM === "dumb") {
        return min;
      }
      return min;
    }
    function getSupportLevel(stream) {
      var level = supportsColor(stream);
      return translateLevel(level);
    }
    module2.exports = {
      supportsColor: getSupportLevel,
      stdout: getSupportLevel(process.stdout),
      stderr: getSupportLevel(process.stderr)
    };
  }
});

// node_modules/colors/lib/custom/trap.js
var require_trap = __commonJS({
  "node_modules/colors/lib/custom/trap.js"(exports2, module2) {
    module2["exports"] = function runTheTrap(text, options2) {
      var result = "";
      text = text || "Run the trap, drop the bass";
      text = text.split("");
      var trap = {
        a: ["@", "\u0104", "\u023A", "\u0245", "\u0394", "\u039B", "\u0414"],
        b: ["\xDF", "\u0181", "\u0243", "\u026E", "\u03B2", "\u0E3F"],
        c: ["\xA9", "\u023B", "\u03FE"],
        d: ["\xD0", "\u018A", "\u0500", "\u0501", "\u0502", "\u0503"],
        e: [
          "\xCB",
          "\u0115",
          "\u018E",
          "\u0258",
          "\u03A3",
          "\u03BE",
          "\u04BC",
          "\u0A6C"
        ],
        f: ["\u04FA"],
        g: ["\u0262"],
        h: ["\u0126", "\u0195", "\u04A2", "\u04BA", "\u04C7", "\u050A"],
        i: ["\u0F0F"],
        j: ["\u0134"],
        k: ["\u0138", "\u04A0", "\u04C3", "\u051E"],
        l: ["\u0139"],
        m: ["\u028D", "\u04CD", "\u04CE", "\u0520", "\u0521", "\u0D69"],
        n: ["\xD1", "\u014B", "\u019D", "\u0376", "\u03A0", "\u048A"],
        o: [
          "\xD8",
          "\xF5",
          "\xF8",
          "\u01FE",
          "\u0298",
          "\u047A",
          "\u05DD",
          "\u06DD",
          "\u0E4F"
        ],
        p: ["\u01F7", "\u048E"],
        q: ["\u09CD"],
        r: ["\xAE", "\u01A6", "\u0210", "\u024C", "\u0280", "\u042F"],
        s: ["\xA7", "\u03DE", "\u03DF", "\u03E8"],
        t: ["\u0141", "\u0166", "\u0373"],
        u: ["\u01B1", "\u054D"],
        v: ["\u05D8"],
        w: ["\u0428", "\u0460", "\u047C", "\u0D70"],
        x: ["\u04B2", "\u04FE", "\u04FC", "\u04FD"],
        y: ["\xA5", "\u04B0", "\u04CB"],
        z: ["\u01B5", "\u0240"]
      };
      text.forEach(function(c) {
        c = c.toLowerCase();
        var chars = trap[c] || [" "];
        var rand = Math.floor(Math.random() * chars.length);
        if (typeof trap[c] !== "undefined") {
          result += trap[c][rand];
        } else {
          result += c;
        }
      });
      return result;
    };
  }
});

// node_modules/colors/lib/custom/zalgo.js
var require_zalgo = __commonJS({
  "node_modules/colors/lib/custom/zalgo.js"(exports2, module2) {
    module2["exports"] = function zalgo(text, options2) {
      text = text || "   he is here   ";
      var soul = {
        "up": [
          "\u030D",
          "\u030E",
          "\u0304",
          "\u0305",
          "\u033F",
          "\u0311",
          "\u0306",
          "\u0310",
          "\u0352",
          "\u0357",
          "\u0351",
          "\u0307",
          "\u0308",
          "\u030A",
          "\u0342",
          "\u0313",
          "\u0308",
          "\u034A",
          "\u034B",
          "\u034C",
          "\u0303",
          "\u0302",
          "\u030C",
          "\u0350",
          "\u0300",
          "\u0301",
          "\u030B",
          "\u030F",
          "\u0312",
          "\u0313",
          "\u0314",
          "\u033D",
          "\u0309",
          "\u0363",
          "\u0364",
          "\u0365",
          "\u0366",
          "\u0367",
          "\u0368",
          "\u0369",
          "\u036A",
          "\u036B",
          "\u036C",
          "\u036D",
          "\u036E",
          "\u036F",
          "\u033E",
          "\u035B",
          "\u0346",
          "\u031A"
        ],
        "down": [
          "\u0316",
          "\u0317",
          "\u0318",
          "\u0319",
          "\u031C",
          "\u031D",
          "\u031E",
          "\u031F",
          "\u0320",
          "\u0324",
          "\u0325",
          "\u0326",
          "\u0329",
          "\u032A",
          "\u032B",
          "\u032C",
          "\u032D",
          "\u032E",
          "\u032F",
          "\u0330",
          "\u0331",
          "\u0332",
          "\u0333",
          "\u0339",
          "\u033A",
          "\u033B",
          "\u033C",
          "\u0345",
          "\u0347",
          "\u0348",
          "\u0349",
          "\u034D",
          "\u034E",
          "\u0353",
          "\u0354",
          "\u0355",
          "\u0356",
          "\u0359",
          "\u035A",
          "\u0323"
        ],
        "mid": [
          "\u0315",
          "\u031B",
          "\u0300",
          "\u0301",
          "\u0358",
          "\u0321",
          "\u0322",
          "\u0327",
          "\u0328",
          "\u0334",
          "\u0335",
          "\u0336",
          "\u035C",
          "\u035D",
          "\u035E",
          "\u035F",
          "\u0360",
          "\u0362",
          "\u0338",
          "\u0337",
          "\u0361",
          " \u0489"
        ]
      };
      var all = [].concat(soul.up, soul.down, soul.mid);
      function randomNumber(range) {
        var r = Math.floor(Math.random() * range);
        return r;
      }
      function isChar(character) {
        var bool = false;
        all.filter(function(i) {
          bool = i === character;
        });
        return bool;
      }
      function heComes(text2, options3) {
        var result = "";
        var counts;
        var l;
        options3 = options3 || {};
        options3["up"] = typeof options3["up"] !== "undefined" ? options3["up"] : true;
        options3["mid"] = typeof options3["mid"] !== "undefined" ? options3["mid"] : true;
        options3["down"] = typeof options3["down"] !== "undefined" ? options3["down"] : true;
        options3["size"] = typeof options3["size"] !== "undefined" ? options3["size"] : "maxi";
        text2 = text2.split("");
        for (l in text2) {
          if (isChar(l)) {
            continue;
          }
          result = result + text2[l];
          counts = { "up": 0, "down": 0, "mid": 0 };
          switch (options3.size) {
            case "mini":
              counts.up = randomNumber(8);
              counts.mid = randomNumber(2);
              counts.down = randomNumber(8);
              break;
            case "maxi":
              counts.up = randomNumber(16) + 3;
              counts.mid = randomNumber(4) + 1;
              counts.down = randomNumber(64) + 3;
              break;
            default:
              counts.up = randomNumber(8) + 1;
              counts.mid = randomNumber(6) / 2;
              counts.down = randomNumber(8) + 1;
              break;
          }
          var arr = ["up", "mid", "down"];
          for (var d in arr) {
            var index = arr[d];
            for (var i = 0; i <= counts[index]; i++) {
              if (options3[index]) {
                result = result + soul[index][randomNumber(soul[index].length)];
              }
            }
          }
        }
        return result;
      }
      return heComes(text, options2);
    };
  }
});

// node_modules/colors/lib/maps/america.js
var require_america = __commonJS({
  "node_modules/colors/lib/maps/america.js"(exports2, module2) {
    module2["exports"] = function(colors11) {
      return function(letter, i, exploded) {
        if (letter === " ") return letter;
        switch (i % 3) {
          case 0:
            return colors11.red(letter);
          case 1:
            return colors11.white(letter);
          case 2:
            return colors11.blue(letter);
        }
      };
    };
  }
});

// node_modules/colors/lib/maps/zebra.js
var require_zebra = __commonJS({
  "node_modules/colors/lib/maps/zebra.js"(exports2, module2) {
    module2["exports"] = function(colors11) {
      return function(letter, i, exploded) {
        return i % 2 === 0 ? letter : colors11.inverse(letter);
      };
    };
  }
});

// node_modules/colors/lib/maps/rainbow.js
var require_rainbow = __commonJS({
  "node_modules/colors/lib/maps/rainbow.js"(exports2, module2) {
    module2["exports"] = function(colors11) {
      var rainbowColors = ["red", "yellow", "green", "blue", "magenta"];
      return function(letter, i, exploded) {
        if (letter === " ") {
          return letter;
        } else {
          return colors11[rainbowColors[i++ % rainbowColors.length]](letter);
        }
      };
    };
  }
});

// node_modules/colors/lib/maps/random.js
var require_random = __commonJS({
  "node_modules/colors/lib/maps/random.js"(exports2, module2) {
    module2["exports"] = function(colors11) {
      var available = [
        "underline",
        "inverse",
        "grey",
        "yellow",
        "red",
        "green",
        "blue",
        "white",
        "cyan",
        "magenta",
        "brightYellow",
        "brightRed",
        "brightGreen",
        "brightBlue",
        "brightWhite",
        "brightCyan",
        "brightMagenta"
      ];
      return function(letter, i, exploded) {
        return letter === " " ? letter : colors11[available[Math.round(Math.random() * (available.length - 2))]](letter);
      };
    };
  }
});

// node_modules/colors/lib/colors.js
var require_colors = __commonJS({
  "node_modules/colors/lib/colors.js"(exports2, module2) {
    var colors11 = {};
    module2["exports"] = colors11;
    colors11.themes = {};
    var util2 = require("util");
    var ansiStyles = colors11.styles = require_styles();
    var defineProps = Object.defineProperties;
    var newLineRegex = new RegExp(/[\r\n]+/g);
    colors11.supportsColor = require_supports_colors().supportsColor;
    if (typeof colors11.enabled === "undefined") {
      colors11.enabled = colors11.supportsColor() !== false;
    }
    colors11.enable = function() {
      colors11.enabled = true;
    };
    colors11.disable = function() {
      colors11.enabled = false;
    };
    colors11.stripColors = colors11.strip = function(str) {
      return ("" + str).replace(/\x1B\[\d+m/g, "");
    };
    var stylize = colors11.stylize = function stylize2(str, style) {
      if (!colors11.enabled) {
        return str + "";
      }
      var styleMap = ansiStyles[style];
      if (!styleMap && style in colors11) {
        return colors11[style](str);
      }
      return styleMap.open + str + styleMap.close;
    };
    var matchOperatorsRe2 = /[|\\{}()[\]^$+*?.]/g;
    var escapeStringRegexp = function(str) {
      if (typeof str !== "string") {
        throw new TypeError("Expected a string");
      }
      return str.replace(matchOperatorsRe2, "\\$&");
    };
    function build(_styles) {
      var builder = function builder2() {
        return applyStyle.apply(builder2, arguments);
      };
      builder._styles = _styles;
      builder.__proto__ = proto;
      return builder;
    }
    var styles2 = function() {
      var ret = {};
      ansiStyles.grey = ansiStyles.gray;
      Object.keys(ansiStyles).forEach(function(key) {
        ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), "g");
        ret[key] = {
          get: function() {
            return build(this._styles.concat(key));
          }
        };
      });
      return ret;
    }();
    var proto = defineProps(function colors12() {
    }, styles2);
    function applyStyle() {
      var args = Array.prototype.slice.call(arguments);
      var str = args.map(function(arg) {
        if (arg != null && arg.constructor === String) {
          return arg;
        } else {
          return util2.inspect(arg);
        }
      }).join(" ");
      if (!colors11.enabled || !str) {
        return str;
      }
      var newLinesPresent = str.indexOf("\n") != -1;
      var nestedStyles = this._styles;
      var i = nestedStyles.length;
      while (i--) {
        var code = ansiStyles[nestedStyles[i]];
        str = code.open + str.replace(code.closeRe, code.open) + code.close;
        if (newLinesPresent) {
          str = str.replace(newLineRegex, function(match) {
            return code.close + match + code.open;
          });
        }
      }
      return str;
    }
    colors11.setTheme = function(theme) {
      if (typeof theme === "string") {
        console.log("colors.setTheme now only accepts an object, not a string.  If you are trying to set a theme from a file, it is now your (the caller's) responsibility to require the file.  The old syntax looked like colors.setTheme(__dirname + '/../themes/generic-logging.js'); The new syntax looks like colors.setTheme(require(__dirname + '/../themes/generic-logging.js'));");
        return;
      }
      for (var style in theme) {
        (function(style2) {
          colors11[style2] = function(str) {
            if (typeof theme[style2] === "object") {
              var out = str;
              for (var i in theme[style2]) {
                out = colors11[theme[style2][i]](out);
              }
              return out;
            }
            return colors11[theme[style2]](str);
          };
        })(style);
      }
    };
    function init() {
      var ret = {};
      Object.keys(styles2).forEach(function(name) {
        ret[name] = {
          get: function() {
            return build([name]);
          }
        };
      });
      return ret;
    }
    var sequencer = function sequencer2(map2, str) {
      var exploded = str.split("");
      exploded = exploded.map(map2);
      return exploded.join("");
    };
    colors11.trap = require_trap();
    colors11.zalgo = require_zalgo();
    colors11.maps = {};
    colors11.maps.america = require_america()(colors11);
    colors11.maps.zebra = require_zebra()(colors11);
    colors11.maps.rainbow = require_rainbow()(colors11);
    colors11.maps.random = require_random()(colors11);
    for (map in colors11.maps) {
      (function(map2) {
        colors11[map2] = function(str) {
          return sequencer(colors11.maps[map2], str);
        };
      })(map);
    }
    var map;
    defineProps(colors11, init());
  }
});

// node_modules/colors/safe.js
var require_safe = __commonJS({
  "node_modules/colors/safe.js"(exports2, module2) {
    var colors11 = require_colors();
    module2["exports"] = colors11;
  }
});

// node_modules/isexe/dist/cjs/posix.js
var require_posix = __commonJS({
  "node_modules/isexe/dist/cjs/posix.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.sync = exports2.isexe = void 0;
    var fs_1 = require("fs");
    var promises_1 = require("fs/promises");
    var isexe = async (path9, options2 = {}) => {
      const { ignoreErrors = false } = options2;
      try {
        return checkStat(await (0, promises_1.stat)(path9), options2);
      } catch (e) {
        const er = e;
        if (ignoreErrors || er.code === "EACCES")
          return false;
        throw er;
      }
    };
    exports2.isexe = isexe;
    var sync = (path9, options2 = {}) => {
      const { ignoreErrors = false } = options2;
      try {
        return checkStat((0, fs_1.statSync)(path9), options2);
      } catch (e) {
        const er = e;
        if (ignoreErrors || er.code === "EACCES")
          return false;
        throw er;
      }
    };
    exports2.sync = sync;
    var checkStat = (stat, options2) => stat.isFile() && checkMode(stat, options2);
    var checkMode = (stat, options2) => {
      var _a, _b, _c, _d, _e, _f, _g, _h;
      const myUid = (_b = options2.uid) != null ? _b : (_a = process.getuid) == null ? void 0 : _a.call(process);
      const myGroups = (_e = (_d = options2.groups) != null ? _d : (_c = process.getgroups) == null ? void 0 : _c.call(process)) != null ? _e : [];
      const myGid = (_h = (_g = options2.gid) != null ? _g : (_f = process.getgid) == null ? void 0 : _f.call(process)) != null ? _h : myGroups[0];
      if (myUid === void 0 || myGid === void 0) {
        throw new Error("cannot get uid or gid");
      }
      const groups = /* @__PURE__ */ new Set([myGid, ...myGroups]);
      const mod = stat.mode;
      const uid = stat.uid;
      const gid = stat.gid;
      const u = parseInt("100", 8);
      const g = parseInt("010", 8);
      const o = parseInt("001", 8);
      const ug = u | g;
      return !!(mod & o || mod & g && groups.has(gid) || mod & u && uid === myUid || mod & ug && myUid === 0);
    };
  }
});

// node_modules/isexe/dist/cjs/win32.js
var require_win32 = __commonJS({
  "node_modules/isexe/dist/cjs/win32.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.sync = exports2.isexe = void 0;
    var fs_1 = require("fs");
    var promises_1 = require("fs/promises");
    var isexe = async (path9, options2 = {}) => {
      const { ignoreErrors = false } = options2;
      try {
        return checkStat(await (0, promises_1.stat)(path9), path9, options2);
      } catch (e) {
        const er = e;
        if (ignoreErrors || er.code === "EACCES")
          return false;
        throw er;
      }
    };
    exports2.isexe = isexe;
    var sync = (path9, options2 = {}) => {
      const { ignoreErrors = false } = options2;
      try {
        return checkStat((0, fs_1.statSync)(path9), path9, options2);
      } catch (e) {
        const er = e;
        if (ignoreErrors || er.code === "EACCES")
          return false;
        throw er;
      }
    };
    exports2.sync = sync;
    var checkPathExt = (path9, options2) => {
      const { pathExt = process.env.PATHEXT || "" } = options2;
      const peSplit = pathExt.split(";");
      if (peSplit.indexOf("") !== -1) {
        return true;
      }
      for (let i = 0; i < peSplit.length; i++) {
        const p = peSplit[i].toLowerCase();
        const ext = path9.substring(path9.length - p.length).toLowerCase();
        if (p && ext === p) {
          return true;
        }
      }
      return false;
    };
    var checkStat = (stat, path9, options2) => stat.isFile() && checkPathExt(path9, options2);
  }
});

// node_modules/isexe/dist/cjs/options.js
var require_options = __commonJS({
  "node_modules/isexe/dist/cjs/options.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
  }
});

// node_modules/isexe/dist/cjs/index.js
var require_cjs = __commonJS({
  "node_modules/isexe/dist/cjs/index.js"(exports2) {
    "use strict";
    var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    } : function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    });
    var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    } : function(o, v) {
      o["default"] = v;
    });
    var __importStar = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
      }
      __setModuleDefault(result, mod);
      return result;
    };
    var __exportStar = exports2 && exports2.__exportStar || function(m, exports3) {
      for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m, p);
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.sync = exports2.isexe = exports2.posix = exports2.win32 = void 0;
    var posix = __importStar(require_posix());
    exports2.posix = posix;
    var win32 = __importStar(require_win32());
    exports2.win32 = win32;
    __exportStar(require_options(), exports2);
    var platform = process.env._ISEXE_TEST_PLATFORM_ || process.platform;
    var impl = platform === "win32" ? win32 : posix;
    exports2.isexe = impl.isexe;
    exports2.sync = impl.sync;
  }
});

// node_modules/which/lib/index.js
var require_lib = __commonJS({
  "node_modules/which/lib/index.js"(exports2, module2) {
    var { isexe, sync: isexeSync } = require_cjs();
    var { join, delimiter, sep, posix } = require("path");
    var isWindows = process.platform === "win32";
    var rSlash = new RegExp(`[${posix.sep}${sep === posix.sep ? "" : sep}]`.replace(/(\\)/g, "\\$1"));
    var rRel = new RegExp(`^\\.${rSlash.source}`);
    var getNotFoundError = (cmd) => Object.assign(new Error(`not found: ${cmd}`), { code: "ENOENT" });
    var getPathInfo = (cmd, {
      path: optPath = process.env.PATH,
      pathExt: optPathExt = process.env.PATHEXT,
      delimiter: optDelimiter = delimiter
    }) => {
      const pathEnv = cmd.match(rSlash) ? [""] : [
        // windows always checks the cwd first
        ...isWindows ? [process.cwd()] : [],
        ...(optPath || /* istanbul ignore next: very unusual */
        "").split(optDelimiter)
      ];
      if (isWindows) {
        const pathExtExe = optPathExt || [".EXE", ".CMD", ".BAT", ".COM"].join(optDelimiter);
        const pathExt = pathExtExe.split(optDelimiter).flatMap((item) => [item, item.toLowerCase()]);
        if (cmd.includes(".") && pathExt[0] !== "") {
          pathExt.unshift("");
        }
        return { pathEnv, pathExt, pathExtExe };
      }
      return { pathEnv, pathExt: [""] };
    };
    var getPathPart = (raw, cmd) => {
      const pathPart = /^".*"$/.test(raw) ? raw.slice(1, -1) : raw;
      const prefix = !pathPart && rRel.test(cmd) ? cmd.slice(0, 2) : "";
      return prefix + join(pathPart, cmd);
    };
    var which2 = async (cmd, opt = {}) => {
      const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
      const found = [];
      for (const envPart of pathEnv) {
        const p = getPathPart(envPart, cmd);
        for (const ext of pathExt) {
          const withExt = p + ext;
          const is = await isexe(withExt, { pathExt: pathExtExe, ignoreErrors: true });
          if (is) {
            if (!opt.all) {
              return withExt;
            }
            found.push(withExt);
          }
        }
      }
      if (opt.all && found.length) {
        return found;
      }
      if (opt.nothrow) {
        return null;
      }
      throw getNotFoundError(cmd);
    };
    var whichSync = (cmd, opt = {}) => {
      const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
      const found = [];
      for (const pathEnvPart of pathEnv) {
        const p = getPathPart(pathEnvPart, cmd);
        for (const ext of pathExt) {
          const withExt = p + ext;
          const is = isexeSync(withExt, { pathExt: pathExtExe, ignoreErrors: true });
          if (is) {
            if (!opt.all) {
              return withExt;
            }
            found.push(withExt);
          }
        }
      }
      if (opt.all && found.length) {
        return found;
      }
      if (opt.nothrow) {
        return null;
      }
      throw getNotFoundError(cmd);
    };
    module2.exports = which2;
    which2.sync = whichSync;
  }
});

// node_modules/minimatch/lib/path.js
var require_path = __commonJS({
  "node_modules/minimatch/lib/path.js"(exports2, module2) {
    var isWindows = typeof process === "object" && process && process.platform === "win32";
    module2.exports = isWindows ? { sep: "\\" } : { sep: "/" };
  }
});

// node_modules/balanced-match/index.js
var require_balanced_match = __commonJS({
  "node_modules/balanced-match/index.js"(exports2, module2) {
    "use strict";
    module2.exports = balanced;
    function balanced(a, b, str) {
      if (a instanceof RegExp) a = maybeMatch(a, str);
      if (b instanceof RegExp) b = maybeMatch(b, str);
      var r = range(a, b, str);
      return r && {
        start: r[0],
        end: r[1],
        pre: str.slice(0, r[0]),
        body: str.slice(r[0] + a.length, r[1]),
        post: str.slice(r[1] + b.length)
      };
    }
    function maybeMatch(reg, str) {
      var m = str.match(reg);
      return m ? m[0] : null;
    }
    balanced.range = range;
    function range(a, b, str) {
      var begs, beg, left, right, result;
      var ai = str.indexOf(a);
      var bi = str.indexOf(b, ai + 1);
      var i = ai;
      if (ai >= 0 && bi > 0) {
        if (a === b) {
          return [ai, bi];
        }
        begs = [];
        left = str.length;
        while (i >= 0 && !result) {
          if (i == ai) {
            begs.push(i);
            ai = str.indexOf(a, i + 1);
          } else if (begs.length == 1) {
            result = [begs.pop(), bi];
          } else {
            beg = begs.pop();
            if (beg < left) {
              left = beg;
              right = bi;
            }
            bi = str.indexOf(b, i + 1);
          }
          i = ai < bi && ai >= 0 ? ai : bi;
        }
        if (begs.length) {
          result = [left, right];
        }
      }
      return result;
    }
  }
});

// node_modules/brace-expansion/index.js
var require_brace_expansion = __commonJS({
  "node_modules/brace-expansion/index.js"(exports2, module2) {
    var balanced = require_balanced_match();
    module2.exports = expandTop;
    var escSlash = "\0SLASH" + Math.random() + "\0";
    var escOpen = "\0OPEN" + Math.random() + "\0";
    var escClose = "\0CLOSE" + Math.random() + "\0";
    var escComma = "\0COMMA" + Math.random() + "\0";
    var escPeriod = "\0PERIOD" + Math.random() + "\0";
    function numeric(str) {
      return parseInt(str, 10) == str ? parseInt(str, 10) : str.charCodeAt(0);
    }
    function escapeBraces(str) {
      return str.split("\\\\").join(escSlash).split("\\{").join(escOpen).split("\\}").join(escClose).split("\\,").join(escComma).split("\\.").join(escPeriod);
    }
    function unescapeBraces(str) {
      return str.split(escSlash).join("\\").split(escOpen).join("{").split(escClose).join("}").split(escComma).join(",").split(escPeriod).join(".");
    }
    function parseCommaParts(str) {
      if (!str)
        return [""];
      var parts = [];
      var m = balanced("{", "}", str);
      if (!m)
        return str.split(",");
      var pre = m.pre;
      var body = m.body;
      var post = m.post;
      var p = pre.split(",");
      p[p.length - 1] += "{" + body + "}";
      var postParts = parseCommaParts(post);
      if (post.length) {
        p[p.length - 1] += postParts.shift();
        p.push.apply(p, postParts);
      }
      parts.push.apply(parts, p);
      return parts;
    }
    function expandTop(str) {
      if (!str)
        return [];
      if (str.substr(0, 2) === "{}") {
        str = "\\{\\}" + str.substr(2);
      }
      return expand(escapeBraces(str), true).map(unescapeBraces);
    }
    function embrace(str) {
      return "{" + str + "}";
    }
    function isPadded(el) {
      return /^-?0\d/.test(el);
    }
    function lte(i, y) {
      return i <= y;
    }
    function gte(i, y) {
      return i >= y;
    }
    function expand(str, isTop) {
      var expansions = [];
      var m = balanced("{", "}", str);
      if (!m) return [str];
      var pre = m.pre;
      var post = m.post.length ? expand(m.post, false) : [""];
      if (/\$$/.test(m.pre)) {
        for (var k = 0; k < post.length; k++) {
          var expansion = pre + "{" + m.body + "}" + post[k];
          expansions.push(expansion);
        }
      } else {
        var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
        var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
        var isSequence = isNumericSequence || isAlphaSequence;
        var isOptions = m.body.indexOf(",") >= 0;
        if (!isSequence && !isOptions) {
          if (m.post.match(/,.*\}/)) {
            str = m.pre + "{" + m.body + escClose + m.post;
            return expand(str);
          }
          return [str];
        }
        var n;
        if (isSequence) {
          n = m.body.split(/\.\./);
        } else {
          n = parseCommaParts(m.body);
          if (n.length === 1) {
            n = expand(n[0], false).map(embrace);
            if (n.length === 1) {
              return post.map(function(p) {
                return m.pre + n[0] + p;
              });
            }
          }
        }
        var N;
        if (isSequence) {
          var x = numeric(n[0]);
          var y = numeric(n[1]);
          var width = Math.max(n[0].length, n[1].length);
          var incr = n.length == 3 ? Math.abs(numeric(n[2])) : 1;
          var test = lte;
          var reverse = y < x;
          if (reverse) {
            incr *= -1;
            test = gte;
          }
          var pad2 = n.some(isPadded);
          N = [];
          for (var i = x; test(i, y); i += incr) {
            var c;
            if (isAlphaSequence) {
              c = String.fromCharCode(i);
              if (c === "\\")
                c = "";
            } else {
              c = String(i);
              if (pad2) {
                var need = width - c.length;
                if (need > 0) {
                  var z = new Array(need + 1).join("0");
                  if (i < 0)
                    c = "-" + z + c.slice(1);
                  else
                    c = z + c;
                }
              }
            }
            N.push(c);
          }
        } else {
          N = [];
          for (var j = 0; j < n.length; j++) {
            N.push.apply(N, expand(n[j], false));
          }
        }
        for (var j = 0; j < N.length; j++) {
          for (var k = 0; k < post.length; k++) {
            var expansion = pre + N[j] + post[k];
            if (!isTop || isSequence || expansion)
              expansions.push(expansion);
          }
        }
      }
      return expansions;
    }
  }
});

// node_modules/minimatch/minimatch.js
var require_minimatch = __commonJS({
  "node_modules/minimatch/minimatch.js"(exports2, module2) {
    var minimatch4 = module2.exports = (p, pattern, options2 = {}) => {
      assertValidPattern(pattern);
      if (!options2.nocomment && pattern.charAt(0) === "#") {
        return false;
      }
      return new Minimatch(pattern, options2).match(p);
    };
    module2.exports = minimatch4;
    var path9 = require_path();
    minimatch4.sep = path9.sep;
    var GLOBSTAR = Symbol("globstar **");
    minimatch4.GLOBSTAR = GLOBSTAR;
    var expand = require_brace_expansion();
    var plTypes = {
      "!": { open: "(?:(?!(?:", close: "))[^/]*?)" },
      "?": { open: "(?:", close: ")?" },
      "+": { open: "(?:", close: ")+" },
      "*": { open: "(?:", close: ")*" },
      "@": { open: "(?:", close: ")" }
    };
    var qmark = "[^/]";
    var star = qmark + "*?";
    var twoStarDot = "(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?";
    var twoStarNoDot = "(?:(?!(?:\\/|^)\\.).)*?";
    var charSet = (s) => s.split("").reduce((set, c) => {
      set[c] = true;
      return set;
    }, {});
    var reSpecials = charSet("().*{}+?[]^$\\!");
    var addPatternStartSet = charSet("[.(");
    var slashSplit = /\/+/;
    minimatch4.filter = (pattern, options2 = {}) => (p, i, list) => minimatch4(p, pattern, options2);
    var ext = (a, b = {}) => {
      const t = {};
      Object.keys(a).forEach((k) => t[k] = a[k]);
      Object.keys(b).forEach((k) => t[k] = b[k]);
      return t;
    };
    minimatch4.defaults = (def) => {
      if (!def || typeof def !== "object" || !Object.keys(def).length) {
        return minimatch4;
      }
      const orig = minimatch4;
      const m = (p, pattern, options2) => orig(p, pattern, ext(def, options2));
      m.Minimatch = class Minimatch extends orig.Minimatch {
        constructor(pattern, options2) {
          super(pattern, ext(def, options2));
        }
      };
      m.Minimatch.defaults = (options2) => orig.defaults(ext(def, options2)).Minimatch;
      m.filter = (pattern, options2) => orig.filter(pattern, ext(def, options2));
      m.defaults = (options2) => orig.defaults(ext(def, options2));
      m.makeRe = (pattern, options2) => orig.makeRe(pattern, ext(def, options2));
      m.braceExpand = (pattern, options2) => orig.braceExpand(pattern, ext(def, options2));
      m.match = (list, pattern, options2) => orig.match(list, pattern, ext(def, options2));
      return m;
    };
    minimatch4.braceExpand = (pattern, options2) => braceExpand(pattern, options2);
    var braceExpand = (pattern, options2 = {}) => {
      assertValidPattern(pattern);
      if (options2.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
        return [pattern];
      }
      return expand(pattern);
    };
    var MAX_PATTERN_LENGTH = 1024 * 64;
    var assertValidPattern = (pattern) => {
      if (typeof pattern !== "string") {
        throw new TypeError("invalid pattern");
      }
      if (pattern.length > MAX_PATTERN_LENGTH) {
        throw new TypeError("pattern is too long");
      }
    };
    var SUBPARSE = Symbol("subparse");
    minimatch4.makeRe = (pattern, options2) => new Minimatch(pattern, options2 || {}).makeRe();
    minimatch4.match = (list, pattern, options2 = {}) => {
      const mm = new Minimatch(pattern, options2);
      list = list.filter((f) => mm.match(f));
      if (mm.options.nonull && !list.length) {
        list.push(pattern);
      }
      return list;
    };
    var globUnescape = (s) => s.replace(/\\(.)/g, "$1");
    var charUnescape = (s) => s.replace(/\\([^-\]])/g, "$1");
    var regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
    var braExpEscape = (s) => s.replace(/[[\]\\]/g, "\\$&");
    var Minimatch = class {
      constructor(pattern, options2) {
        assertValidPattern(pattern);
        if (!options2) options2 = {};
        this.options = options2;
        this.set = [];
        this.pattern = pattern;
        this.windowsPathsNoEscape = !!options2.windowsPathsNoEscape || options2.allowWindowsEscape === false;
        if (this.windowsPathsNoEscape) {
          this.pattern = this.pattern.replace(/\\/g, "/");
        }
        this.regexp = null;
        this.negate = false;
        this.comment = false;
        this.empty = false;
        this.partial = !!options2.partial;
        this.make();
      }
      debug() {
      }
      make() {
        const pattern = this.pattern;
        const options2 = this.options;
        if (!options2.nocomment && pattern.charAt(0) === "#") {
          this.comment = true;
          return;
        }
        if (!pattern) {
          this.empty = true;
          return;
        }
        this.parseNegate();
        let set = this.globSet = this.braceExpand();
        if (options2.debug) this.debug = (...args) => console.error(...args);
        this.debug(this.pattern, set);
        set = this.globParts = set.map((s) => s.split(slashSplit));
        this.debug(this.pattern, set);
        set = set.map((s, si, set2) => s.map(this.parse, this));
        this.debug(this.pattern, set);
        set = set.filter((s) => s.indexOf(false) === -1);
        this.debug(this.pattern, set);
        this.set = set;
      }
      parseNegate() {
        if (this.options.nonegate) return;
        const pattern = this.pattern;
        let negate = false;
        let negateOffset = 0;
        for (let i = 0; i < pattern.length && pattern.charAt(i) === "!"; i++) {
          negate = !negate;
          negateOffset++;
        }
        if (negateOffset) this.pattern = pattern.slice(negateOffset);
        this.negate = negate;
      }
      // set partial to true to test if, for example,
      // "/a/b" matches the start of "/*/b/*/d"
      // Partial means, if you run out of file before you run
      // out of pattern, then that's fine, as long as all
      // the parts match.
      matchOne(file, pattern, partial) {
        var options2 = this.options;
        this.debug(
          "matchOne",
          { "this": this, file, pattern }
        );
        this.debug("matchOne", file.length, pattern.length);
        for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
          this.debug("matchOne loop");
          var p = pattern[pi];
          var f = file[fi];
          this.debug(pattern, p, f);
          if (p === false) return false;
          if (p === GLOBSTAR) {
            this.debug("GLOBSTAR", [pattern, p, f]);
            var fr = fi;
            var pr = pi + 1;
            if (pr === pl) {
              this.debug("** at the end");
              for (; fi < fl; fi++) {
                if (file[fi] === "." || file[fi] === ".." || !options2.dot && file[fi].charAt(0) === ".") return false;
              }
              return true;
            }
            while (fr < fl) {
              var swallowee = file[fr];
              this.debug("\nglobstar while", file, fr, pattern, pr, swallowee);
              if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
                this.debug("globstar found match!", fr, fl, swallowee);
                return true;
              } else {
                if (swallowee === "." || swallowee === ".." || !options2.dot && swallowee.charAt(0) === ".") {
                  this.debug("dot detected!", file, fr, pattern, pr);
                  break;
                }
                this.debug("globstar swallow a segment, and continue");
                fr++;
              }
            }
            if (partial) {
              this.debug("\n>>> no match, partial?", file, fr, pattern, pr);
              if (fr === fl) return true;
            }
            return false;
          }
          var hit;
          if (typeof p === "string") {
            hit = f === p;
            this.debug("string match", p, f, hit);
          } else {
            hit = f.match(p);
            this.debug("pattern match", p, f, hit);
          }
          if (!hit) return false;
        }
        if (fi === fl && pi === pl) {
          return true;
        } else if (fi === fl) {
          return partial;
        } else if (pi === pl) {
          return fi === fl - 1 && file[fi] === "";
        }
        throw new Error("wtf?");
      }
      braceExpand() {
        return braceExpand(this.pattern, this.options);
      }
      parse(pattern, isSub) {
        assertValidPattern(pattern);
        const options2 = this.options;
        if (pattern === "**") {
          if (!options2.noglobstar)
            return GLOBSTAR;
          else
            pattern = "*";
        }
        if (pattern === "") return "";
        let re = "";
        let hasMagic = !!options2.nocase;
        let escaping = false;
        const patternListStack = [];
        const negativeLists = [];
        let stateChar;
        let inClass = false;
        let reClassStart = -1;
        let classStart = -1;
        let cs;
        let pl;
        let sp;
        const patternStart = pattern.charAt(0) === "." ? "" : options2.dot ? "(?!(?:^|\\/)\\.{1,2}(?:$|\\/))" : "(?!\\.)";
        const clearStateChar = () => {
          if (stateChar) {
            switch (stateChar) {
              case "*":
                re += star;
                hasMagic = true;
                break;
              case "?":
                re += qmark;
                hasMagic = true;
                break;
              default:
                re += "\\" + stateChar;
                break;
            }
            this.debug("clearStateChar %j %j", stateChar, re);
            stateChar = false;
          }
        };
        for (let i = 0, c; i < pattern.length && (c = pattern.charAt(i)); i++) {
          this.debug("%s	%s %s %j", pattern, i, re, c);
          if (escaping) {
            if (c === "/") {
              return false;
            }
            if (reSpecials[c]) {
              re += "\\";
            }
            re += c;
            escaping = false;
            continue;
          }
          switch (c) {
            /* istanbul ignore next */
            case "/": {
              return false;
            }
            case "\\":
              if (inClass && pattern.charAt(i + 1) === "-") {
                re += c;
                continue;
              }
              clearStateChar();
              escaping = true;
              continue;
            // the various stateChar values
            // for the "extglob" stuff.
            case "?":
            case "*":
            case "+":
            case "@":
            case "!":
              this.debug("%s	%s %s %j <-- stateChar", pattern, i, re, c);
              if (inClass) {
                this.debug("  in class");
                if (c === "!" && i === classStart + 1) c = "^";
                re += c;
                continue;
              }
              this.debug("call clearStateChar %j", stateChar);
              clearStateChar();
              stateChar = c;
              if (options2.noext) clearStateChar();
              continue;
            case "(":
              if (inClass) {
                re += "(";
                continue;
              }
              if (!stateChar) {
                re += "\\(";
                continue;
              }
              patternListStack.push({
                type: stateChar,
                start: i - 1,
                reStart: re.length,
                open: plTypes[stateChar].open,
                close: plTypes[stateChar].close
              });
              re += stateChar === "!" ? "(?:(?!(?:" : "(?:";
              this.debug("plType %j %j", stateChar, re);
              stateChar = false;
              continue;
            case ")":
              if (inClass || !patternListStack.length) {
                re += "\\)";
                continue;
              }
              clearStateChar();
              hasMagic = true;
              pl = patternListStack.pop();
              re += pl.close;
              if (pl.type === "!") {
                negativeLists.push(pl);
              }
              pl.reEnd = re.length;
              continue;
            case "|":
              if (inClass || !patternListStack.length) {
                re += "\\|";
                continue;
              }
              clearStateChar();
              re += "|";
              continue;
            // these are mostly the same in regexp and glob
            case "[":
              clearStateChar();
              if (inClass) {
                re += "\\" + c;
                continue;
              }
              inClass = true;
              classStart = i;
              reClassStart = re.length;
              re += c;
              continue;
            case "]":
              if (i === classStart + 1 || !inClass) {
                re += "\\" + c;
                continue;
              }
              cs = pattern.substring(classStart + 1, i);
              try {
                RegExp("[" + braExpEscape(charUnescape(cs)) + "]");
                re += c;
              } catch (er) {
                re = re.substring(0, reClassStart) + "(?:$.)";
              }
              hasMagic = true;
              inClass = false;
              continue;
            default:
              clearStateChar();
              if (reSpecials[c] && !(c === "^" && inClass)) {
                re += "\\";
              }
              re += c;
              break;
          }
        }
        if (inClass) {
          cs = pattern.slice(classStart + 1);
          sp = this.parse(cs, SUBPARSE);
          re = re.substring(0, reClassStart) + "\\[" + sp[0];
          hasMagic = hasMagic || sp[1];
        }
        for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
          let tail;
          tail = re.slice(pl.reStart + pl.open.length);
          this.debug("setting tail", re, pl);
          tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, (_, $1, $2) => {
            if (!$2) {
              $2 = "\\";
            }
            return $1 + $1 + $2 + "|";
          });
          this.debug("tail=%j\n   %s", tail, tail, pl, re);
          const t = pl.type === "*" ? star : pl.type === "?" ? qmark : "\\" + pl.type;
          hasMagic = true;
          re = re.slice(0, pl.reStart) + t + "\\(" + tail;
        }
        clearStateChar();
        if (escaping) {
          re += "\\\\";
        }
        const addPatternStart = addPatternStartSet[re.charAt(0)];
        for (let n = negativeLists.length - 1; n > -1; n--) {
          const nl = negativeLists[n];
          const nlBefore = re.slice(0, nl.reStart);
          const nlFirst = re.slice(nl.reStart, nl.reEnd - 8);
          let nlAfter = re.slice(nl.reEnd);
          const nlLast = re.slice(nl.reEnd - 8, nl.reEnd) + nlAfter;
          const openParensBefore = nlBefore.split("(").length - 1;
          let cleanAfter = nlAfter;
          for (let i = 0; i < openParensBefore; i++) {
            cleanAfter = cleanAfter.replace(/\)[+*?]?/, "");
          }
          nlAfter = cleanAfter;
          const dollar = nlAfter === "" && isSub !== SUBPARSE ? "$" : "";
          re = nlBefore + nlFirst + nlAfter + dollar + nlLast;
        }
        if (re !== "" && hasMagic) {
          re = "(?=.)" + re;
        }
        if (addPatternStart) {
          re = patternStart + re;
        }
        if (isSub === SUBPARSE) {
          return [re, hasMagic];
        }
        if (!hasMagic) {
          return globUnescape(pattern);
        }
        const flags = options2.nocase ? "i" : "";
        try {
          return Object.assign(new RegExp("^" + re + "$", flags), {
            _glob: pattern,
            _src: re
          });
        } catch (er) {
          return new RegExp("$.");
        }
      }
      makeRe() {
        if (this.regexp || this.regexp === false) return this.regexp;
        const set = this.set;
        if (!set.length) {
          this.regexp = false;
          return this.regexp;
        }
        const options2 = this.options;
        const twoStar = options2.noglobstar ? star : options2.dot ? twoStarDot : twoStarNoDot;
        const flags = options2.nocase ? "i" : "";
        let re = set.map((pattern) => {
          pattern = pattern.map(
            (p) => typeof p === "string" ? regExpEscape(p) : p === GLOBSTAR ? GLOBSTAR : p._src
          ).reduce((set2, p) => {
            if (!(set2[set2.length - 1] === GLOBSTAR && p === GLOBSTAR)) {
              set2.push(p);
            }
            return set2;
          }, []);
          pattern.forEach((p, i) => {
            if (p !== GLOBSTAR || pattern[i - 1] === GLOBSTAR) {
              return;
            }
            if (i === 0) {
              if (pattern.length > 1) {
                pattern[i + 1] = "(?:\\/|" + twoStar + "\\/)?" + pattern[i + 1];
              } else {
                pattern[i] = twoStar;
              }
            } else if (i === pattern.length - 1) {
              pattern[i - 1] += "(?:\\/|" + twoStar + ")?";
            } else {
              pattern[i - 1] += "(?:\\/|\\/" + twoStar + "\\/)" + pattern[i + 1];
              pattern[i + 1] = GLOBSTAR;
            }
          });
          return pattern.filter((p) => p !== GLOBSTAR).join("/");
        }).join("|");
        re = "^(?:" + re + ")$";
        if (this.negate) re = "^(?!" + re + ").*$";
        try {
          this.regexp = new RegExp(re, flags);
        } catch (ex) {
          this.regexp = false;
        }
        return this.regexp;
      }
      match(f, partial = this.partial) {
        this.debug("match", f, this.pattern);
        if (this.comment) return false;
        if (this.empty) return f === "";
        if (f === "/" && partial) return true;
        const options2 = this.options;
        if (path9.sep !== "/") {
          f = f.split(path9.sep).join("/");
        }
        f = f.split(slashSplit);
        this.debug(this.pattern, "split", f);
        const set = this.set;
        this.debug(this.pattern, "set", set);
        let filename;
        for (let i = f.length - 1; i >= 0; i--) {
          filename = f[i];
          if (filename) break;
        }
        for (let i = 0; i < set.length; i++) {
          const pattern = set[i];
          let file = f;
          if (options2.matchBase && pattern.length === 1) {
            file = [filename];
          }
          const hit = this.matchOne(file, pattern, partial);
          if (hit) {
            if (options2.flipNegate) return true;
            return !this.negate;
          }
        }
        if (options2.flipNegate) return false;
        return this.negate;
      }
      static defaults(def) {
        return minimatch4.defaults(def).Minimatch;
      }
    };
    minimatch4.Minimatch = Minimatch;
  }
});

// src/index.ts
var index_exports = {};
__export(index_exports, {
  activate: () => activate
});
module.exports = __toCommonJS(index_exports);
var import_coc14 = require("coc.nvim");

// src/buffers.ts
var import_coc = require("coc.nvim");
var import_safe = __toESM(require_safe());
var regex = /^\s*(\d+)(.+?)"(.+?)".*/;
var BufferList = class extends import_coc.BasicList {
  constructor(nvim) {
    super(nvim);
    this.name = "buffers";
    this.defaultAction = "open";
    this.description = "get buffer list";
    this.addAction("open", async (item) => {
      let { bufnr } = item.data;
      await nvim.command(`buffer ${bufnr}`);
    });
    this.addAction("drop", async (item) => {
      let { bufnr, visible } = item.data;
      if (visible) {
        let info = await nvim.call("getbufinfo", bufnr);
        if (info.length && info[0].windows.length) {
          let winid = info[0].windows[0];
          await nvim.call("win_gotoid", winid);
          return;
        }
      }
      await nvim.command(`buffer ${bufnr}`);
    });
    this.addAction("split", async (item) => {
      let { bufnr } = item.data;
      await nvim.command(`sb ${bufnr}`);
    });
    this.addAction("tabe", async (item) => {
      let { bufname } = item.data;
      let escaped = await nvim.call("fnameescape", bufname);
      await nvim.command(`tabe ${escaped}`);
    });
    this.addAction("vsplit", async (item) => {
      let { bufname } = item.data;
      let escaped = await nvim.call("fnameescape", bufname);
      await nvim.command(`vs ${escaped}`);
    });
    this.addAction("delete", async (item) => {
      let { bufnr, bufname, isArgs } = item.data;
      await nvim.command(`bdelete ${bufnr}`);
      if (isArgs) {
        await nvim.command(`argdelete ${bufname}`);
      }
    }, { persist: true, reload: true });
    this.addAction("wipe", async (item) => {
      let { bufnr } = item.data;
      await nvim.command(`bwipeout ${bufnr}`);
    }, { persist: true, reload: true });
    this.addAction("preview", async (item, context) => {
      let { nvim: nvim2 } = this;
      let { bufname, bufnr } = item.data;
      let lines = await nvim2.call("getbufline", [bufnr, 1, 200]);
      let filetype = await nvim2.call("getbufvar", [bufnr, "&filetype", "txt"]);
      if (lines.length == 0) {
        lines = [`Unable to get lines for buffer ${bufname}, add 'set hidden' in your vimrc.`];
      }
      await this.preview({
        filetype,
        bufname,
        lines,
        sketch: true
      }, context);
    });
  }
  async loadItems(context) {
    const { nvim } = this;
    const bufnrAlt = Number(await nvim.call("bufnr", "#"));
    const content = await nvim.call("execute", "ls");
    const isArgs = context.args.indexOf("--args") !== -1;
    const isPWD = context.args.indexOf("--pwd") !== -1;
    const args = isArgs ? await nvim.eval("map(argv(), 'bufnr(v:val)')") : [];
    return content.split(/\n/).reduce((res, line) => {
      const ms = line.match(regex);
      if (!ms) return res;
      const bufnr = Number(ms[1]);
      const bufname = ms[3];
      if (isArgs && args.indexOf(bufnr) === -1) return res;
      if (isPWD && (bufname[0] === "/" || bufname[0] === "~")) return res;
      const item = {
        label: ` ${import_safe.default.magenta(ms[1])}${import_safe.default.america(ms[2])}${ms[3]}`,
        filterText: bufname,
        sortText: ms[1],
        data: {
          bufnr,
          bufname,
          visible: ms[2].indexOf("a") !== -1,
          isArgs
        }
      };
      return bufnr === bufnrAlt ? [item, ...res] : [...res, item];
    }, []);
  }
};

// src/changes.ts
var import_safe2 = __toESM(require_safe());
var regex2 = /^[^\d]*(\d+)[^\d]+(\d+)[^\d]+(\d+)[^\w]+(.*)$/;
var ChangeList = class {
  constructor(nvim) {
    this.nvim = nvim;
    this.name = "changes";
    this.description = "changes list";
    this.defaultAction = "jump";
    this.actions = [];
    this.actions.push({
      name: "jump",
      execute: (item) => {
        if (Array.isArray(item)) return;
        nvim.command(`normal! ${item.data.lnum}G${item.data.col}|zz`, true);
      }
    });
  }
  async loadItems(_context) {
    const { nvim } = this;
    let list = await nvim.eval('split(execute("changes"), "\n")');
    list = list.slice(1);
    list = list.filter((s) => regex2.test(s));
    return list.map((line) => {
      let [, change, lnum, col, text] = line.match(regex2);
      return {
        label: `${import_safe2.default.magenta(change)}	${import_safe2.default.grey(lnum)}	${import_safe2.default.grey(col)}	${text}`,
        filterText: text,
        data: { lnum, col }
      };
    });
  }
};

// src/cmdhistory.ts
var regex3 = /^\s*\d+\s+(.*)$/;
var Cmdhistory = class {
  constructor(nvim) {
    this.nvim = nvim;
    this.name = "cmdhistory";
    this.description = "history of vim commands";
    this.defaultAction = "execute";
    this.actions = [];
    this.actions.push({
      name: "execute",
      execute: async (item) => {
        if (Array.isArray(item)) return;
        nvim.command(item.data.cmd, true);
      }
    });
  }
  async loadItems(_context) {
    let { nvim } = this;
    let list = await nvim.eval(`split(execute("history cmd"),"
")`);
    list = list.slice(1);
    let res = [];
    for (let line of list) {
      let ms = line.match(regex3);
      if (ms) {
        let [, cmd] = ms;
        res.push({
          label: cmd,
          filterText: cmd,
          data: {
            cmd
          }
        });
      }
    }
    return res;
  }
};

// src/colors.ts
var import_coc2 = require("coc.nvim");
var import_path = __toESM(require("path"));
var Colors = class extends import_coc2.BasicList {
  constructor(nvim) {
    super(nvim);
    this.name = "colors";
    this.description = "color schemes";
    this.defaultAction = "set";
    this.actions = [];
    this.addLocationActions();
    this.addAction("set", (item) => {
      if (Array.isArray(item)) return;
      nvim.command(`colorscheme ${item.data.name}`, true);
    });
  }
  async loadItems(_context) {
    let { nvim } = this;
    let colors11 = await nvim.eval('split(globpath(&rtp, "colors/*.vim"),"\n")');
    let hasPackages = await nvim.call("has", ["packages"]);
    if (hasPackages) {
      let packageColors = await nvim.eval('split(globpath(&packpath, "pack/*/opt/*/colors/*.vim"),"\n")');
      colors11.push(...packageColors);
    }
    return colors11.map((file) => {
      let name = import_path.default.basename(file, ".vim");
      return {
        label: `${name}	${file}`,
        filterText: name,
        data: { name },
        location: import_coc2.Uri.file(file).toString()
      };
    });
  }
  doHighlight() {
    let { nvim } = this;
    nvim.pauseNotification();
    nvim.command("syntax match CocColorsName /\\v^[^\\t]+/ contained containedin=CocColorsLine", true);
    nvim.command("syntax match CocColorsFile /\\t.*$/ contained containedin=CocColorsLine", true);
    nvim.command("highlight default link CocColorsName Identifier", true);
    nvim.command("highlight default link CocColorsFile Comment", true);
    nvim.resumeNotification(false, true);
  }
};

// src/commands.ts
var import_safe3 = __toESM(require_safe());
var import_fs = __toESM(require("fs"));
var import_util = __toESM(require("util"));

// src/util/index.ts
var import_which = __toESM(require_lib());
var import_path2 = __toESM(require("path"));
function executable(cmd) {
  try {
    import_which.default.sync(cmd);
  } catch (e) {
    return false;
  }
  return true;
}
function characterIndex(content, byteIndex2) {
  let buf = Buffer.from(content, "utf8");
  return buf.slice(0, byteIndex2).toString("utf8").length;
}
function wait(ms) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(void 0);
    }, ms);
  });
}
function pad(n, total) {
  let l = total - n.length;
  if (l <= 0) return "";
  return new Array(l).fill(" ").join("");
}
function distinct(array, keyFn) {
  if (!keyFn) {
    return array.filter((element, position) => {
      return array.indexOf(element) === position;
    });
  }
  const seen = /* @__PURE__ */ Object.create(null);
  return array.filter((elem) => {
    const key = keyFn(elem);
    if (seen[key]) {
      return false;
    }
    seen[key] = true;
    return true;
  });
}
function isParentFolder(folder, filepath) {
  let rel = import_path2.default.relative(folder, filepath);
  return !rel.startsWith("..");
}

// src/commands.ts
var regex4 = /^\|:(\S+)\|\t(\S+)\t(.*)$/;
var Commands = class {
  constructor(nvim) {
    this.nvim = nvim;
    this.name = "vimcommands";
    this.description = "command list";
    this.defaultAction = "execute";
    this.actions = [];
    this.actions.push({
      name: "execute",
      execute: async (item) => {
        if (Array.isArray(item)) return;
        let { command, shabang, hasArgs } = item.data;
        if (!hasArgs) {
          nvim.command(command, true);
        } else {
          const feedableCommand = `:${command}${shabang ? "" : " "}`;
          const mode = await nvim.call("mode");
          const isInsertMode = mode.startsWith("i");
          if (isInsertMode) {
            nvim.command(`call feedkeys("\\<C-O>${feedableCommand}", 'n')`, true);
          } else {
            await nvim.feedKeys(feedableCommand, "n", true);
          }
        }
      }
    });
    this.actions.push({
      name: "open",
      execute: async (item) => {
        if (Array.isArray(item)) return;
        let { command } = item.data;
        if (!/^[A-Z]/.test(command)) return;
        let res = await nvim.eval(`split(execute("verbose command ${command}"),"
")[2]`);
        if (/Last\sset\sfrom/.test(res)) {
          let [filepath, _, line] = res.replace(/^\s+Last\sset\sfrom\s+/, "").split(/\s+/);
          if (line) {
            nvim.command(`edit +${line} ${filepath}`, true);
          } else {
            nvim.command(`edit +/${command} ${filepath}`, true);
          }
        }
      }
    });
  }
  async loadItems(_context) {
    let { nvim } = this;
    let list = await nvim.eval('split(execute("command"),"\n")');
    list = list.slice(1);
    let res = [];
    for (let str of list) {
      let name = str.slice(4).match(/\S+/)[0];
      let end = str.slice(4 + name.length);
      res.push({
        label: str.slice(0, 4) + import_safe3.default.magenta(name) + end,
        filterText: name,
        data: {
          command: name,
          shabang: str.startsWith("!"),
          hasArgs: !end.match(/^\s*0\s/)
        }
      });
    }
    let help = await nvim.eval(`globpath($VIMRUNTIME, 'doc/index.txt')`);
    if (help && import_fs.default.existsSync(help)) {
      let content = await import_util.default.promisify(import_fs.default.readFile)(help, "utf8");
      for (let line of content.split(/\r?\n/)) {
        let ms = line.match(regex4);
        if (ms) {
          let [, cmd, chars, description] = ms;
          res.push({
            label: `    ${import_safe3.default.magenta(cmd)}${pad(cmd, 20)}${chars}${pad(chars, 30)}${description}`,
            filterText: cmd,
            data: {
              command: cmd,
              shabang: false,
              hasArgs: true
            }
          });
        }
      }
    }
    return res;
  }
};

// src/files.ts
var import_child_process = require("child_process");
var import_coc3 = require("coc.nvim");
var import_events = require("events");
var import_fs2 = __toESM(require("fs"));
var import_minimatch = __toESM(require_minimatch());
var import_path3 = __toESM(require("path"));
var import_readline = __toESM(require("readline"));
var Task = class extends import_events.EventEmitter {
  constructor() {
    super(...arguments);
    this.processes = [];
  }
  start(cmd, args, cwds, patterns) {
    let remain = cwds.length;
    let config = import_coc3.workspace.getConfiguration("list.source.files");
    let filterByName = config.get("filterByName", false);
    for (let cwd of cwds) {
      let process2 = (0, import_child_process.spawn)(cmd, args, { cwd });
      this.processes.push(process2);
      process2.on("error", (e) => {
        this.emit("error", e.message);
      });
      const rl = import_readline.default.createInterface(process2.stdout);
      const range = import_coc3.Range.create(0, 0, 0, 0);
      let hasPattern = patterns.length > 0;
      process2.stderr.on("data", (chunk) => {
        console.error(chunk.toString("utf8"));
      });
      rl.on("line", (line) => {
        let file = line;
        if (file.indexOf(cwd) < 0) {
          file = import_path3.default.join(cwd, line);
        }
        if (hasPattern && patterns.some((p) => (0, import_minimatch.default)(file, p))) return;
        let location = import_coc3.Location.create(import_coc3.Uri.file(file).toString(), range);
        if (!filterByName) {
          this.emit("data", {
            label: line,
            sortText: file,
            location
          });
        } else {
          let name = import_path3.default.basename(file);
          this.emit("data", {
            label: `${name}	${line}`,
            sortText: file,
            filterText: name,
            location
          });
        }
      });
      rl.on("close", () => {
        remain = remain - 1;
        if (remain == 0) {
          this.emit("end");
        }
      });
    }
  }
  dispose() {
    for (let process2 of this.processes) {
      if (!process2.killed) {
        process2.kill();
      }
    }
  }
};
var FilesList = class extends import_coc3.BasicList {
  constructor(nvim) {
    super(nvim);
    this.name = "files";
    this.defaultAction = "open";
    this.description = "Search files by rg or ag";
    this.detail = `Install ripgrep in your $PATH to have best experience.
Files is searched from current cwd by default.
Provide directory names as arguments to search other directories.
Use 'list.source.files.command' configuration for custom search command.
Use 'list.source.files.args' configuration for custom command arguments.
Note that rg ignore hidden files by default.`;
    this.options = [{
      name: "-F, -folder",
      description: "Search files from current workspace folder instead of cwd."
    }, {
      name: "-W, -workspace",
      description: "Search files from all workspace folders instead of cwd."
    }];
    this.addLocationActions();
  }
  getArgs(args, defaultArgs) {
    return args.length ? args : defaultArgs;
  }
  getCommand() {
    let config = import_coc3.workspace.getConfiguration("list.source.files");
    let cmd = config.get("command", "");
    let args = config.get("args", []);
    if (!cmd) {
      if (executable("rg")) {
        return { cmd: "rg", args: this.getArgs(args, ["--color", "never", "--files"]) };
      } else if (executable("ag")) {
        return { cmd: "ag", args: this.getArgs(args, ["-f", "-g", ".", "--nocolor"]) };
      } else if (process.platform == "win32") {
        return { cmd: "dir", args: this.getArgs(args, ["/a-D", "/S", "/B"]) };
      } else if (executable("find")) {
        return { cmd: "find", args: this.getArgs(args, [".", "-type", "f"]) };
      } else {
        throw new Error("Unable to find command for files list.");
        return null;
      }
    } else {
      return { cmd, args };
    }
  }
  async loadItems(context) {
    let { nvim } = this;
    let { window: window3, args } = context;
    let options2 = this.parseArguments(args);
    let res = this.getCommand();
    if (!res) return null;
    let used = res.args.concat(["-F", "-folder", "-W", "-workspace"]);
    let extraArgs = args.filter((s) => used.indexOf(s) == -1);
    let cwds;
    let dirArgs = [];
    let searchArgs = [];
    if (options2.folder) {
      cwds = [import_coc3.workspace.rootPath];
    } else if (options2.workspace) {
      cwds = import_coc3.workspace.workspaceFolders.map((f) => import_coc3.Uri.parse(f.uri).fsPath);
    } else {
      if (extraArgs.length > 0) {
        for (let i = 0; i < extraArgs.length; i++) {
          let d = await nvim.call("expand", extraArgs[i]);
          try {
            if (import_fs2.default.lstatSync(d).isDirectory()) {
              dirArgs.push(d);
            } else {
              searchArgs.push(d);
            }
          } catch (e) {
            searchArgs.push(d);
          }
        }
      }
      if (dirArgs.length > 0) {
        cwds = dirArgs;
      } else {
        let valid = await window3.valid;
        if (valid) {
          cwds = [await nvim.call("getcwd", window3.id)];
        } else {
          cwds = [await nvim.call("getcwd")];
        }
      }
    }
    let task = new Task();
    let excludePatterns = this.getConfig().get("excludePatterns", []);
    task.start(res.cmd, res.args.concat(searchArgs), cwds, excludePatterns);
    return task;
  }
  doHighlight() {
    let config = import_coc3.workspace.getConfiguration("list.source.files");
    let filterByName = config.get("filterByName", false);
    if (filterByName) {
      let { nvim } = this;
      nvim.pauseNotification();
      nvim.command("syntax match CocFilesFile /\\t.*$/ contained containedin=CocFilesLine", true);
      nvim.command("highlight default link CocFilesFile Comment", true);
      nvim.resumeNotification(false, true);
    }
  }
};

// src/filetypes.ts
var Filetypes = class {
  constructor(nvim) {
    this.nvim = nvim;
    this.name = "filetypes";
    this.description = "available filetypes";
    this.defaultAction = "set";
    this.actions = [];
    this.actions.push({
      name: "set",
      execute: (item) => {
        if (Array.isArray(item)) {
          for (let i of item) {
            nvim.command(`setf ${i.label}`, true);
          }
        } else {
          nvim.command(`setf ${item.label}`, true);
        }
      }
    });
  }
  async loadItems(_context) {
    let { nvim } = this;
    let filetypes = await nvim.eval(`sort(map(split(globpath(&rtp, 'syntax/*.vim'), '
'),'fnamemodify(v:val, ":t:r")'))`);
    filetypes = distinct(filetypes);
    return filetypes.map((filetype) => {
      return { label: filetype };
    });
  }
};

// src/grep.ts
var import_child_process2 = require("child_process");
var import_coc4 = require("coc.nvim");
var import_events2 = require("events");
var import_minimatch2 = __toESM(require_minimatch());
var import_path4 = __toESM(require("path"));
var import_readline2 = __toESM(require("readline"));
var import_coc5 = require("coc.nvim");

// src/util/ansiparse.ts
var foregroundColors = {
  30: "black",
  31: "red",
  32: "green",
  33: "yellow",
  34: "blue",
  35: "magenta",
  36: "cyan",
  37: "white",
  90: "grey"
};
var backgroundColors = {
  40: "black",
  41: "red",
  42: "green",
  43: "yellow",
  44: "blue",
  45: "magenta",
  46: "cyan",
  47: "white"
};
var styles = {
  1: "bold",
  3: "italic",
  4: "underline"
};
function ansiparse(str) {
  let matchingControl = null;
  let matchingData = null;
  let matchingText = "";
  let ansiState = [];
  let result = [];
  let state = {};
  let eraseChar;
  eraseChar = () => {
    let index;
    let text;
    if (matchingText.length) {
      matchingText = matchingText.substr(0, matchingText.length - 1);
    } else if (result.length) {
      index = result.length - 1;
      text = result[index].text;
      if (text.length === 1) {
        result.pop();
      } else {
        result[index].text = text.substr(0, text.length - 1);
      }
    }
  };
  for (let i = 0; i < str.length; i++) {
    if (matchingControl != null) {
      if (matchingControl == "\x1B" && str[i] == "[") {
        if (matchingText) {
          state.text = matchingText;
          result.push(state);
          state = {};
          matchingText = "";
        }
        matchingControl = null;
        matchingData = "";
      } else {
        matchingText += matchingControl + str[i];
        matchingControl = null;
      }
      continue;
    } else if (matchingData != null) {
      if (str[i] == ";") {
        ansiState.push(matchingData);
        matchingData = "";
      } else if (str[i] == "m" || str[i] == "K") {
        ansiState.push(matchingData);
        matchingData = null;
        matchingText = "";
        ansiState.forEach((ansiCode) => {
          if (foregroundColors[ansiCode]) {
            state.foreground = foregroundColors[ansiCode];
          } else if (backgroundColors[ansiCode]) {
            state.background = backgroundColors[ansiCode];
          } else if (ansiCode == 39) {
            delete state.foreground;
          } else if (ansiCode == 49) {
            delete state.background;
          } else if (styles[ansiCode]) {
            state[styles[ansiCode]] = true;
          } else if (ansiCode == 22) {
            state.bold = false;
          } else if (ansiCode == 23) {
            state.italic = false;
          } else if (ansiCode == 24) {
            state.underline = false;
          }
        });
        ansiState = [];
      } else {
        matchingData += str[i];
      }
      continue;
    }
    if (str[i] == "\x1B") {
      matchingControl = str[i];
    } else if (str[i] == "\b") {
      eraseChar();
    } else {
      matchingText += str[i];
    }
  }
  if (matchingText) {
    state.text = matchingText + (matchingControl ? matchingControl : "");
    result.push(state);
  }
  return result;
}

// src/util/option.ts
var options = [];
function defineOptions(s, l, ag, rg) {
  options.push([s, l, ag, rg]);
}
defineOptions("-S", "-smartcase", "--smart-case", "--smart-case");
defineOptions("-i", "-ignorecase", "--ignore-case", "--ignore-case");
defineOptions("-l", "-literal", "--fixed-strings", "--fixed-strings");
defineOptions("-w", "-word", "--word-regexp", "--word-regexp");
defineOptions("-e", "-regex", "", "--regexp");
defineOptions("-u", "-skip-vcs-ignores", "--skip-vcs-ignores", "--no-ignore-vcs");
defineOptions("-t", "-extension", null, null);
function getOption(opt, command) {
  let idx = opt.length == 2 ? 0 : 1;
  let o = options.find((o2) => o2[idx] == opt);
  if (!o) return opt;
  return command === "ag" ? o[2] : o[3];
}
function convertOptions(list, command, defaultLiteral = false) {
  let useLiteral = defaultLiteral && list.find((o) => {
    return ["-e", "-regex", "-w", "-word", "-l", "-literal"].indexOf(o) != -1;
  }) == null;
  let res = [];
  if (useLiteral) list.unshift("-l");
  for (let idx = 0; idx < list.length; idx++) {
    let s = list[idx];
    if (/^-/.test(s)) {
      if (s === "-t" || s === "-extension") {
        let f = list[idx + 1];
        if (!f || /^-/.test(f)) continue;
        if (command == "rg") {
          res.push("--glob", `*.${f}`);
        } else {
          res.push("-G", `*.${f}`);
        }
        idx++;
      } else {
        res.push(getOption(s, command));
      }
    } else {
      res.push(s);
    }
  }
  if (command === "ag" && list.indexOf("-S") === -1 && list.indexOf("-smartcase") === -1) {
    res.unshift("-s");
  }
  return res;
}

// src/grep.ts
var lineRegex = /^(.+?):(\d+):(\d+):(.*)/;
var controlCode = "\x1B";
var Task2 = class extends import_events2.EventEmitter {
  constructor(interactive) {
    super();
    this.interactive = interactive;
    this.processes = [];
    this.lines = 0;
  }
  start(text, cmd, args, cwds, patterns, maxLines) {
    for (let cwd of cwds) {
      let remain = cwds.length;
      let process2 = (0, import_child_process2.spawn)(cmd, args, { cwd });
      process2.on("error", (e) => {
        this.emit("error", e.message);
      });
      process2.stderr.on("data", (chunk) => {
        let parts = ansiparse(chunk.toString("utf8"));
        let escaped = parts.reduce((s, curr) => s + curr.text, "");
        console.error(escaped);
      });
      const rl = import_readline2.default.createInterface(process2.stdout);
      let hasPattern = patterns.length > 0;
      rl.on("line", (line) => {
        if (this.interactive && maxLines > 0 && this.lines >= maxLines) return;
        let ms;
        let escaped;
        if (line.indexOf(controlCode) !== -1) {
          let parts = ansiparse(line);
          escaped = parts.reduce((s, curr) => s + curr.text, "");
          ms = escaped.match(lineRegex);
        } else {
          ms = line.match(lineRegex);
          escaped = line;
        }
        if (!ms) return;
        let file = ms[1];
        if (!import_path4.default.isAbsolute(file)) {
          file = import_path4.default.join(cwd, ms[1]);
        }
        if (hasPattern && patterns.some((p) => (0, import_minimatch2.default)(file, p))) return;
        this.emit("data", {
          label: line,
          filterText: this.interactive ? "" : escaped,
          location: {
            text,
            uri: file,
            line: ms[4]
          }
        });
        this.lines++;
      });
      rl.on("close", () => {
        remain = remain - 1;
        if (remain == 0) {
          this.emit("end");
        }
      });
    }
  }
  dispose() {
    for (let process2 of this.processes) {
      if (!process2.killed) {
        process2.kill();
      }
    }
  }
};
var GrepList = class extends import_coc4.BasicList {
  constructor(nvim) {
    super(nvim);
    this.interactive = true;
    this.description = "grep text by rg or ag";
    this.name = "grep";
    this.defaultAction = "open";
    this.detail = `Literal match is used by default.
To use interactive mode, add '-I' or '--interactive' to LIST OPTIONS.
To change colors, checkout 'man rg' or 'man ag'.
To search from workspace folders instead of cwd, use '-folder' or '-workspace' argument.
Grep source provide some uniformed options to ease differences between rg and ag.`;
    this.options = [{
      name: "-S, -smartcase",
      description: "Use smartcase match."
    }, {
      name: "-i, -ignorecase",
      description: "Use ignorecase match."
    }, {
      name: "-l, -literal",
      description: "Treat the pattern as a literal string, used when -regex is not used."
    }, {
      name: "-w, -word",
      description: "Use word match."
    }, {
      name: "-e, -regex",
      description: "Use regex match."
    }, {
      name: "-u, -skip-vcs-ignores",
      description: "Don't respect version control ignore files(.gitignore, etc.)"
    }, {
      name: "-t, -extension EXTENSION",
      description: "Grep files with specified extension only, could be used multiple times.",
      hasValue: true
    }, {
      name: "-F, -folder",
      description: "Grep files from current workspace folder instead of cwd."
    }, {
      name: "-W, -workspace",
      description: "Grep files from all workspace folders instead of cwd."
    }];
    this.addLocationActions();
  }
  async loadItems(context) {
    let { nvim } = this;
    let { interactive } = context.options;
    let config = import_coc4.workspace.getConfiguration("list.source.grep");
    let cmd = config.get("command", "rg");
    let args = config.get("args", []).slice();
    let useLiteral = config.get("useLiteral", true);
    let maxLines = config.get("maxLines", 0);
    if (cmd == "rg") {
      let maxColumns = config.get("maxColumns", 300);
      args.push("--color", "always", "--max-columns", maxColumns.toString(), "--vimgrep");
    } else if (cmd == "ag") {
      args.push("--color", "--vimgrep");
    }
    if (!executable(cmd)) throw new Error(`Command '${cmd}' not found on $PATH`);
    if (interactive && !context.input) return [];
    args.push(...context.args);
    if (context.input) {
      if (interactive && context.input.indexOf(" ") != -1) {
        let input = context.input.split(/\s+/).join(".*");
        if (!args.includes("-regex") && !args.includes("-e")) {
          args.push("-regex");
        }
        args.push(input);
      } else {
        args.push(context.input);
      }
    }
    let patterns = config.get("excludePatterns", []);
    let { window: window3 } = context;
    let cwds;
    if (args.indexOf("-F") != -1 || args.indexOf("-folder") != -1) {
      cwds = [import_coc4.workspace.rootPath];
    } else if (args.indexOf("-W") != -1 || args.indexOf("-workspace") != -1) {
      cwds = import_coc4.workspace.workspaceFolders.map((f) => import_coc5.Uri.parse(f.uri).fsPath);
    } else {
      let valid = await window3.valid;
      if (valid) {
        cwds = [await nvim.call("getcwd", window3.id)];
      } else {
        cwds = [await nvim.call("getcwd")];
      }
    }
    let task = new Task2(interactive);
    if (cmd == "rg" || cmd == "ag") {
      args = convertOptions(args, cmd, useLiteral);
      args = args.filter((s) => ["-F", "-folder", "-W", "-workspace"].indexOf(s) == -1);
    }
    let text = "";
    if (!interactive) {
      const regexPattern = /[\\^$.|?*+(){}[\]]/;
      const last = args.slice(-1)[0];
      if (!regexPattern.test(last)) {
        text = last;
      }
    }
    if (!args.includes("--")) {
      args.push("--", "./");
    }
    task.start(text, cmd, args, cwds, patterns, maxLines);
    return task;
  }
};

// src/helptags.ts
var import_coc6 = require("coc.nvim");
var import_fs3 = __toESM(require("fs"));
var import_path5 = __toESM(require("path"));
var Helptags = class extends import_coc6.BasicList {
  constructor(nvim) {
    super(nvim);
    this.name = "helptags";
    this.description = "helptags of vim";
    this.defaultAction = "show";
    this.addAction("show", (item) => {
      nvim.command(`help ${item.data.name}`, true);
    });
    this.addLocationActions();
  }
  async loadItems(_context) {
    let rtp = import_coc6.workspace.env.runtimepath;
    if (!rtp) return [];
    let folders = rtp.split(",");
    let result = [];
    let cwd = await this.nvim.call("getcwd");
    await Promise.all(folders.map((folder) => {
      return new Promise((resolve) => {
        let file = import_path5.default.join(folder, "doc/tags");
        import_fs3.default.readFile(file, "utf8", (err, content) => {
          if (err) return resolve();
          let lines = content.split(/\r?\n/);
          for (let line of lines) {
            if (line) {
              let [name, filepath, regex9] = line.split("	");
              let fullpath = import_path5.default.join(folder, "doc", filepath);
              let uri = import_coc6.Uri.file(fullpath).toString();
              let file2 = isParentFolder(cwd, fullpath) ? import_path5.default.relative(cwd, fullpath) : fullpath;
              result.push({
                label: `${name}	${file2}`,
                filterText: name,
                location: {
                  uri,
                  line: regex9.replace(/^\//, "").replace(/\$\//, ""),
                  text: name
                },
                data: { name }
              });
            }
          }
          resolve();
        });
      });
    }));
    return result;
  }
  doHighlight() {
    let { nvim } = this;
    nvim.pauseNotification();
    nvim.command("syntax match CocHelptagsName /\\v^[^\\t]+/ contained containedin=CocHelptagsLine", true);
    nvim.command("syntax match CocHelptagsFile /\\t.*$/ contained containedin=CocHelptagsLine", true);
    nvim.command("highlight default link CocHelptagsName Identifier", true);
    nvim.command("highlight default link CocHelptagsFile Comment", true);
    nvim.resumeNotification(false, true);
  }
};

// src/lines.ts
var import_coc7 = require("coc.nvim");
var Lines = class extends import_coc7.BasicList {
  constructor(nvim) {
    super(nvim);
    this.name = "lines";
    this.searchHighlight = false;
    this.interactive = true;
    this.description = "match lines of current buffer by regexp";
    this.detail = `Patterns are separated by space, pattern starts with '!' means nagitive.`;
    this.addLocationActions();
  }
  async loadItems(context) {
    let { input, buffer } = context;
    if (!context.options.interactive) {
      throw new Error("lines list works on interactive mode only.");
    }
    if (input.trim() === "") return [];
    let doc = import_coc7.workspace.getDocument(buffer.id);
    if (!doc) return [];
    let lines = doc.getLines();
    let result = [];
    let inputs = input.trim().split(/\s+/);
    let flags = context.options.ignorecase ? "iu" : "u";
    let patterns = [];
    let nagitives = [];
    for (let s of inputs) {
      try {
        let nagitive = s.startsWith("!");
        let re = new RegExp(nagitive ? s.slice(1) : s, flags);
        if (nagitive) {
          nagitives.push(re);
        } else {
          patterns.push(re);
        }
      } catch (_e) {
      }
    }
    if (patterns.length == 0 && nagitives.length == 0) return [];
    let hasNagitive = nagitives.length > 0;
    let total = lines.length.toString().length;
    let lnum = 0;
    for (let line of lines) {
      lnum = lnum + 1;
      if (hasNagitive && nagitives.some((r) => r.test(line))) {
        continue;
      }
      let ranges = [];
      for (let pattern of patterns) {
        let ms = line.match(pattern);
        if (ms == null) continue;
        ranges.push([ms.index, ms.index + ms[0].length]);
      }
      if (ranges.length != patterns.length) {
        continue;
      }
      let range = import_coc7.Range.create(lnum - 1, ranges[0][0], lnum - 1, ranges[0][1]);
      let pre = `${lnum}${pad(lnum.toString(), total)}`;
      let pl = pre.length;
      let ansiHighlights = ranges.map((r) => {
        return {
          span: [byteIndex(line, r[0]) + pl + 1, byteIndex(line, r[1]) + pl + 1],
          hlGroup: "CocListFgRed"
        };
      });
      ansiHighlights.push({
        span: [0, pl],
        hlGroup: "CocListFgMagenta"
      });
      result.push({
        ansiHighlights,
        label: `${pre} ${line}`,
        location: import_coc7.Location.create(doc.uri, range),
        filterText: ""
      });
    }
    return result;
  }
};
function byteIndex(content, index) {
  let s = content.slice(0, index);
  return Buffer.byteLength(s);
}

// src/locationlist.ts
var import_coc8 = require("coc.nvim");
var LocationList = class extends import_coc8.BasicList {
  constructor(nvim) {
    super(nvim);
    this.name = "locationlist";
    this.defaultAction = "open";
    this.description = "locationlist of current window";
    this.addLocationActions();
  }
  async loadItems(context) {
    let { nvim } = this;
    let { window: window3 } = context;
    let valid = await window3.valid;
    if (!valid) return [];
    let list = await nvim.call("getloclist", [window3.id]);
    if (list.length == 0) return [];
    let res = [];
    let buf = await context.window.buffer;
    let bufnr = buf.id;
    let ignoreFilepath = list.every((o) => o.bufnr && bufnr && o.bufnr == bufnr);
    for (let item of list) {
      let { bufnr: bufnr2, col, text, type, lnum } = item;
      if (type == "E") {
        type = "Error";
      } else if (type == "W") {
        type = "Warning";
      }
      let bufname = await nvim.call("bufname", bufnr2);
      let fullpath = await nvim.call("fnamemodify", [bufname, ":p"]);
      let uri = import_coc8.Uri.file(fullpath).toString();
      let line = await import_coc8.workspace.getLine(uri, lnum - 1);
      let pos = import_coc8.Position.create(lnum - 1, characterIndex(line, col - 1));
      res.push({
        label: `${ignoreFilepath ? "" : bufname} |${type ? type + " " : ""}${lnum} col ${col}| ${text}`,
        location: import_coc8.Location.create(uri, import_coc8.Range.create(pos, pos)),
        filterText: `${ignoreFilepath ? "" : bufname}${text}`
      });
    }
    return res;
  }
  doHighlight() {
    let { nvim } = this;
    nvim.pauseNotification();
    nvim.command("syntax match CocLocationlistName /\\v^[^|]+/ contained containedin=CocLocationlistLine", true);
    nvim.command("syntax match CocLocationlistPosition /\\v\\|\\w*\\s?\\d+\\scol\\s\\d+\\|/ contained containedin=CocLocationlistLine", true);
    nvim.command("syntax match CocLocationlistError /Error/ contained containedin=CocLocationlistPosition", true);
    nvim.command("syntax match CocLocationlistWarning /Warning/ contained containedin=CocLocationlistPosition", true);
    nvim.command("highlight default link CocLocationlistName Directory", true);
    nvim.command("highlight default link CocLocationlistPosition LineNr", true);
    nvim.command("highlight default link CocLocationlistError Error", true);
    nvim.command("highlight default link CocLocationlistWarning WarningMsg", true);
    nvim.resumeNotification().catch((_e) => {
    });
  }
};

// src/maps.ts
var import_safe4 = __toESM(require_safe());
var regex5 = /^(\S+)\s+(\S+)\s+(.*)$/;
var Maps = class {
  constructor(nvim) {
    this.nvim = nvim;
    this.name = "maps";
    this.description = "key mappings";
    this.defaultAction = "open";
    this.actions = [];
    this.options = [{
      name: "-mode=[i,n,v,x,s]",
      description: "Filter mappings by mode."
    }];
    this.actions.push({
      name: "open",
      execute: async (item) => {
        if (Array.isArray(item)) return;
        let { mode, key } = item.data;
        let cmd = JSON.stringify(`verbose ${mode}map ${key}`);
        let res = await nvim.eval(`split(execute(${cmd}),"
")[-1]`);
        if (/Last\sset\sfrom/.test(res)) {
          let [filepath, _, line] = res.replace(/^\s+Last\sset\sfrom\s+/, "").split(/\s+/);
          if (line) {
            nvim.command(`edit +${line} ${filepath}`, true);
          } else {
            nvim.command(`edit +/${key} ${filepath}`, true);
          }
        }
      }
    });
  }
  async loadItems(context) {
    let { nvim } = this;
    let mode = "";
    for (let arg of context.args) {
      if (arg.startsWith("-mode=")) {
        mode = arg.replace("-mode=", "");
      }
    }
    let list = await nvim.eval(`split(execute("verbose ${mode}map"),"
")`);
    let res = [];
    for (let line of list) {
      let ms = line.match(regex5);
      if (ms) {
        let [, mode2, key, more] = ms;
        res.push({
          label: ` ${import_safe4.default.magenta(mode2)}	${import_safe4.default.blue(key)}	${more}`,
          filterText: `${key} ${more}`,
          data: {
            mode: mode2,
            key
          }
        });
      }
    }
    return res;
  }
};

// src/marks.ts
var import_safe5 = __toESM(require_safe());
var regex6 = /^\s*(\S)\s+(\d+)\s+(\d+)\s*(.*)$/;
var Marks = class {
  constructor(nvim) {
    this.nvim = nvim;
    this.name = "marks";
    this.description = "marks list";
    this.defaultAction = "jump";
    this.actions = [];
    this.actions.push({
      name: "jump",
      execute: (item) => {
        if (Array.isArray(item)) return;
        nvim.command("normal! `" + item.data.name + "zz", true);
      }
    });
  }
  async loadItems(_context) {
    let { nvim } = this;
    let list = await nvim.eval('split(execute("marks"), "\n")');
    list = list.slice(1);
    list = list.filter((s) => regex6.test(s));
    return list.map((line) => {
      let [, name, lnum, col, text] = line.match(regex6);
      return {
        label: `${import_safe5.default.magenta(name)}	${text}	${import_safe5.default.grey(lnum)}	${import_safe5.default.grey(col)}`,
        filterText: name + " " + text,
        data: { name }
      };
    });
  }
};

// src/mru.ts
var import_coc9 = require("coc.nvim");
var import_fs4 = __toESM(require("fs"));
var import_minimatch3 = __toESM(require_minimatch());
var import_path6 = __toESM(require("path"));
var MruList = class extends import_coc9.BasicList {
  constructor(nvim) {
    super(nvim);
    this.name = "mru";
    this.defaultAction = "open";
    this.description = "most recent used files in current cwd";
    this.detail = `Use command 'mru.validate' to remove files that not exists any more.`;
    this.options = [{
      name: "-A",
      description: "Show all recent files instead of filter by cwd."
    }];
    this.promise = Promise.resolve(void 0);
    this.mru = import_coc9.workspace.createMru("mru");
    this.addLocationActions();
    this.addAction(
      "delete",
      async (item, _context) => {
        let filepath = import_coc9.Uri.parse(item.data.uri).fsPath;
        await this.mru.remove(filepath);
      },
      { reload: true, persist: true }
    );
    this.addAction(
      "clean",
      async () => {
        await this.mru.clean();
      },
      { reload: true, persist: true }
    );
    this.disposables.push(import_coc9.commands.registerCommand("mru.validate", async () => {
      let files = await this.mru.load();
      for (let file of files) {
        if (!import_fs4.default.existsSync(file)) {
          await this.mru.remove(file);
        }
      }
    }));
    for (let doc of import_coc9.workspace.documents) {
      this.addRecentFile(doc);
    }
    import_coc9.workspace.onDidOpenTextDocument(async (textDocument) => {
      await wait(50);
      let doc = import_coc9.workspace.getDocument(textDocument.uri);
      if (doc) this.addRecentFile(doc);
    }, null, this.disposables);
    import_coc9.events.on("BufEnter", (bufnr) => {
      let doc = import_coc9.workspace.getDocument(bufnr);
      if (doc) this.addRecentFile(doc);
    }, null, this.disposables);
  }
  addRecentFile(doc) {
    this.promise = this.promise.then(() => {
      return this._addRecentFile(doc);
    }, () => {
      return this._addRecentFile(doc);
    });
  }
  async _addRecentFile(doc) {
    let uri = import_coc9.Uri.parse(doc.uri);
    if (uri.scheme !== "file" || doc.buftype != "") return;
    if (doc.filetype == "netrw") return;
    if (doc.uri.indexOf("NERD_tree") !== -1) return;
    let parts = uri.fsPath.split(import_path6.default.sep);
    if (parts.indexOf(".git") !== -1 || parts.length == 0) return;
    let preview = await this.nvim.eval(`getwinvar(bufwinnr(${doc.bufnr}), '&previewwindow')`);
    if (preview == 1) return;
    let filepath = uri.fsPath;
    let patterns = this.config.get("source.mru.excludePatterns", []);
    if (patterns.some((p) => (0, import_minimatch3.default)(filepath, p))) return;
    await this.mru.add(filepath);
  }
  async loadItems(context) {
    let cwd = await this.nvim.call("getcwd");
    let findAll = context.args.indexOf("-A") !== -1;
    let files = await this.mru.load();
    let config = import_coc9.workspace.getConfiguration("list.source.mru");
    let filterByName = config.get("filterByName", false);
    const range = import_coc9.Range.create(0, 0, 0, 0);
    if (!findAll) files = files.filter((file) => isParentFolder(cwd, file));
    return files.map((file, i) => {
      let uri = import_coc9.Uri.file(file).toString();
      let location = import_coc9.Location.create(uri.toString(), range);
      if (!filterByName) {
        return {
          label: findAll ? file : import_path6.default.relative(cwd, file),
          data: { uri },
          sortText: String.fromCharCode(i),
          location
        };
      } else {
        let name = import_path6.default.basename(file);
        file = findAll ? file : import_path6.default.relative(cwd, file);
        return {
          label: `${name}	${file}`,
          data: { uri },
          sortText: String.fromCharCode(i),
          filterText: name,
          location
        };
      }
    });
  }
  doHighlight() {
    let config = import_coc9.workspace.getConfiguration("list.source.mru");
    let filterByName = config.get("filterByName", false);
    if (filterByName) {
      let { nvim } = this;
      nvim.pauseNotification();
      nvim.command("syntax match CocMruFile /\\t.*$/ contained containedin=CocMruLine", true);
      nvim.command("highlight default link CocMruFile Comment", true);
      nvim.resumeNotification(false, true);
    }
  }
};

// src/quickfix.ts
var import_coc10 = require("coc.nvim");
var QuickfixList = class extends import_coc10.BasicList {
  constructor(nvim) {
    super(nvim);
    this.name = "quickfix";
    this.defaultAction = "open";
    this.description = "quickfix list";
    this.addLocationActions();
  }
  async loadItems(context) {
    let { nvim } = this;
    let { window: window3 } = context;
    let list = await nvim.call("getqflist");
    if (list.length == 0) return [];
    let res = [];
    let bufnr;
    let valid = await window3.valid;
    if (valid) {
      let buf = await window3.buffer;
      bufnr = buf.id;
    }
    let ignoreFilepath = list.every((o) => o.bufnr && bufnr && o.bufnr == bufnr);
    for (let item of list) {
      let { bufnr: bufnr2, col, text, type, lnum } = item;
      if (type == "E") {
        type = "Error";
      } else if (type == "W") {
        type = "Warning";
      }
      let bufname = await nvim.call("bufname", bufnr2);
      let fullpath = await nvim.call("fnamemodify", [bufname, ":p"]);
      let uri = import_coc10.Uri.file(fullpath).toString();
      let line = await import_coc10.workspace.getLine(uri, lnum - 1);
      let pos = import_coc10.Position.create(lnum - 1, characterIndex(line, col - 1));
      res.push({
        label: `${ignoreFilepath ? "" : bufname} |${type ? type + " " : ""}${lnum} col ${col}| ${text}`,
        location: import_coc10.Location.create(uri, import_coc10.Range.create(pos, pos)),
        filterText: `${ignoreFilepath ? "" : bufname}${text}`
      });
    }
    return res;
  }
  doHighlight() {
    let { nvim } = this;
    nvim.pauseNotification();
    nvim.command("syntax match CocQuickfixName /\\v^[^|]+/ contained containedin=CocQuickfixLine", true);
    nvim.command("syntax match CocQuickfixPosition /\\v\\|\\w*\\s?\\d+\\scol\\s\\d+\\|/ contained containedin=CocQuickfixLine", true);
    nvim.command("syntax match CocQuickfixError /Error/ contained containedin=CocQuickfixPosition", true);
    nvim.command("syntax match CocQuickfixWarning /Warning/ contained containedin=CocQuickfixPosition", true);
    nvim.command("highlight default link CocQuickfixName Directory", true);
    nvim.command("highlight default link CocQuickfixPosition LineNr", true);
    nvim.command("highlight default link CocQuickfixError Error", true);
    nvim.command("highlight default link CocQuickfixWarning WarningMsg", true);
    nvim.resumeNotification().catch((_e) => {
    });
  }
};

// src/registers.ts
var import_safe6 = __toESM(require_safe());
var regex7 = /^[^\w]*(\w)[^\w|"]+(".)[^\w]+(.*)$/;
var Registers = class {
  constructor(nvim) {
    this.nvim = nvim;
    this.name = "registers";
    this.description = "registers list";
    this.defaultAction = "append";
    this.actions = [];
    this.actions.push({
      name: "append",
      execute: (item) => {
        if (Array.isArray(item)) return;
        nvim.command("normal! " + item.data.name + "p", true);
      }
    });
    this.actions.push({
      name: "prepend",
      execute: (item) => {
        if (Array.isArray(item)) return;
        nvim.command("normal! " + item.data.name + "P", true);
      }
    });
  }
  async loadItems(_context) {
    const { nvim } = this;
    let list = await nvim.eval('split(execute("registers"), "\n")');
    list = list.slice(1);
    list = list.filter((s) => regex7.test(s));
    return list.map((line) => {
      let [, type, name, content] = line.match(regex7);
      return {
        label: `${import_safe6.default.grey(type)}	${import_safe6.default.magenta(name)}	${content}`,
        filterText: content,
        data: { name }
      };
    });
  }
};

// src/searchhistory.ts
var regex8 = /^\s*\d+\s+(.*)$/;
var Searchhistory = class {
  constructor(nvim) {
    this.nvim = nvim;
    this.name = "searchhistory";
    this.description = "search history";
    this.defaultAction = "feedkeys";
    this.actions = [];
    this.actions.push({
      name: "feedkeys",
      execute: async (item) => {
        if (Array.isArray(item)) return;
        nvim.call("feedkeys", [`/${item.data.cmd}`, "n"], true);
      }
    });
  }
  async loadItems(_context) {
    let { nvim } = this;
    let list = await nvim.eval(`split(execute("history search"),"
")`);
    list = list.slice(1);
    let res = [];
    for (let line of list) {
      let ms = line.match(regex8);
      if (ms) {
        let [, cmd] = ms;
        res.push({
          label: cmd,
          filterText: cmd,
          data: {
            cmd
          }
        });
      }
    }
    return res;
  }
};

// src/session.ts
var import_coc11 = require("coc.nvim");
var import_fs5 = __toESM(require("fs"));
var import_os = __toESM(require("os"));
var import_path7 = __toESM(require("path"));
var import_util11 = require("util");
var SessionList = class extends import_coc11.BasicList {
  constructor(nvim, extensionPath, saveOnVimLeave) {
    super(nvim);
    this.extensionPath = extensionPath;
    this.name = "sessions";
    this.defaultAction = "load";
    this.description = "session list";
    this.detail = `After session load, coc service would be restarted.`;
    this.mru = import_coc11.workspace.createMru("sessions");
    this.addLocationActions();
    this.addAction("delete", async (item) => {
      let filepath = item.data.filepath;
      await this.mru.remove(filepath);
      await (0, import_util11.promisify)(import_fs5.default.unlink)(filepath);
    }, { reload: true, persist: true });
    this.addAction("load", async (item, _context) => {
      let filepath = item.data.filepath;
      await this.loadSession(filepath);
    });
    this.disposables.push(import_coc11.commands.registerCommand("session.save", async (name) => {
      setTimeout(async () => {
        if (!name) {
          name = await nvim.getVvar("this_session");
          if (!name) {
            let defaultValue = import_path7.default.basename(import_coc11.workspace.rootPath);
            name = await import_coc11.window.requestInput("session name", defaultValue);
            if (!name) return;
          }
        }
        if (!name.endsWith(".vim")) name = name + ".vim";
        let escaped;
        if (!import_path7.default.isAbsolute(name)) {
          let folder = this.getSessionFolder();
          escaped = await nvim.call("fnameescape", [import_path7.default.join(folder, name)]);
        } else {
          escaped = await nvim.call("fnameescape", [name]);
          name = import_path7.default.basename(name, ".vim");
        }
        await nvim.command(`silent mksession! ${escaped}`);
        import_coc11.window.showMessage(`Saved session: ${name}`, "more");
      }, 50);
    }));
    this.disposables.push(import_coc11.commands.registerCommand("session.load", async (name) => {
      if (!name) {
        let folder = this.getSessionFolder();
        let files = await (0, import_util11.promisify)(import_fs5.default.readdir)(folder, { encoding: "utf8" });
        files = files.filter((p) => p.endsWith(".vim"));
        files = files.map((p) => import_path7.default.basename(p, ".vim"));
        let idx = await import_coc11.window.showQuickpick(files, "choose session:");
        if (idx == -1) return;
        name = files[idx];
      }
      let filepath;
      if (import_path7.default.isAbsolute(name)) {
        filepath = name;
      } else {
        let folder = this.getSessionFolder();
        filepath = import_path7.default.join(folder, name.endsWith(".vim") ? name : `${name}.vim`);
      }
      setTimeout(async () => {
        await this.loadSession(filepath);
      }, 30);
    }));
    this.disposables.push(import_coc11.commands.registerCommand("session.restart", async () => {
      if (!import_coc11.workspace.isNvim || process.env.TERM_PROGRAM != "iTerm.app") {
        import_coc11.window.showMessage("Sorry, restart support iTerm and neovim only.", "warning");
        return;
      }
      let filepath = await this.nvim.getVvar("this_session");
      if (!filepath) {
        let folder = this.getSessionFolder();
        filepath = import_path7.default.join(folder, "default.vim");
      }
      await nvim.command(`silent mksession! ${filepath}`);
      let cwd = await nvim.call("getcwd");
      let cmd = `${import_path7.default.join(this.extensionPath, "nvimstart")} ${filepath} ${cwd}`;
      nvim.call("jobstart", [cmd, { detach: 1 }], true);
      nvim.command("silent! wa | silent quitall!", true);
    }));
    if (saveOnVimLeave) {
      this.disposables.push(import_coc11.workspace.registerAutocmd({
        event: "VimLeavePre",
        request: true,
        callback: async () => {
          let curr = await this.nvim.getVvar("this_session");
          if (!curr) {
            let folder = this.getSessionFolder();
            curr = import_path7.default.join(folder, "default.vim");
          } else {
            if (!import_path7.default.isAbsolute(curr)) return;
            let folder = import_path7.default.dirname(curr);
            if (!import_fs5.default.existsSync(folder)) return;
          }
          nvim.command(`silent! mksession! ${curr}`, true);
        }
      }));
    }
  }
  async loadSession(filepath) {
    let { nvim } = this;
    let config = import_coc11.workspace.getConfiguration("session");
    let restart = config.get("restartOnSessionLoad", false);
    if (restart && import_coc11.workspace.isNvim && process.env.TERM_PROGRAM.startsWith("iTerm.app")) {
      let content = await (0, import_util11.promisify)(import_fs5.default.readFile)(filepath, "utf8");
      let line = content.split(/\r?\n/).find((s) => s.startsWith("cd "));
      let cwd = line.replace(/^cd\s+/, "");
      let cmd = `${import_path7.default.join(this.extensionPath, "nvimstart")} ${filepath} ${cwd}`;
      nvim.call("jobstart", [cmd, { detach: 1 }], true);
      nvim.command("silent! wa | silent quitall!", true);
    } else {
      await this.mru.add(filepath);
      let escaped = await nvim.call("fnameescape", [filepath]);
      nvim.pauseNotification();
      nvim.command("noautocmd silent! %bwipeout!", true);
      nvim.command(`silent! source ${escaped}`, true);
      nvim.command("CocRestart", true);
      await nvim.resumeNotification(false, true);
    }
  }
  getSessionFolder() {
    let config = import_coc11.workspace.getConfiguration("session");
    let directory = config.get("directory", "");
    directory = directory.replace(/^~/, import_os.default.homedir());
    const isWin = process.platform === "win32";
    if (!directory) {
      const folder = isWin ? "vimfiles/sessions" : ".vim/sessions";
      directory = import_path7.default.join(import_os.default.homedir(), folder);
    }
    if (!import_fs5.default.existsSync(directory)) {
      import_fs5.default.mkdirSync(directory, { recursive: true });
      if (isWin) {
        let folder = import_path7.default.join(import_os.default.homedir(), ".vim/sessions");
        if (import_fs5.default.existsSync(folder)) {
          let stat = import_fs5.default.lstatSync(folder);
          if (stat && stat.isDirectory()) {
            let files = import_fs5.default.readdirSync(folder);
            for (let file of files) {
              if (file.endsWith(".vim")) {
                let dest = import_path7.default.join(import_os.default.homedir(), "vimfiles/sessions", file);
                import_fs5.default.copyFileSync(import_path7.default.join(folder, file), dest);
              }
            }
          }
        }
      }
    }
    return directory;
  }
  async loadItems(_context) {
    let folder = this.getSessionFolder();
    let files = await (0, import_util11.promisify)(import_fs5.default.readdir)(folder, { encoding: "utf8" });
    files = files.filter((p) => p.endsWith(".vim"));
    let range = import_coc11.Range.create(0, 0, 0, 0);
    let curr = await this.nvim.getVvar("this_session");
    let arr = await Promise.all(files.map((file) => {
      let filepath = import_path7.default.join(folder, file);
      return (0, import_util11.promisify)(import_fs5.default.stat)(filepath).then((stat) => {
        return {
          atime: stat.atime,
          filepath
        };
      });
    }));
    arr.sort((a, b) => {
      return a.atime.getTime() - b.atime.getTime();
    });
    files = arr.map((o) => o.filepath);
    return files.map((filepath) => {
      let uri = import_coc11.Uri.file(filepath).toString();
      let location = import_coc11.Location.create(uri, range);
      let name = import_path7.default.basename(filepath, ".vim");
      let active = curr && curr == filepath;
      return {
        label: `${active ? "*" : " "} ${name}	${filepath}`,
        data: { filepath },
        location
      };
    });
  }
  doHighlight() {
    let { nvim } = this;
    nvim.pauseNotification();
    nvim.command("syntax match CocSessionsActivited /\\v^\\*/ contained containedin=CocSessionsLine", true);
    nvim.command("syntax match CocSessionsName /\\v%3c\\S+/ contained containedin=CocSessionsLine", true);
    nvim.command("syntax match CocSessionsRoot /\\v\\t[^\\t]*$/ contained containedin=CocSessionsLine", true);
    nvim.command("highlight default link CocSessionsActivited Special", true);
    nvim.command("highlight default link CocSessionsName Type", true);
    nvim.command("highlight default link CocSessionsRoot Comment", true);
    nvim.resumeNotification().catch((_e) => {
    });
  }
};

// src/tags.ts
var import_coc12 = require("coc.nvim");
var import_safe7 = __toESM(require_safe());
var import_events3 = require("events");
var import_fs6 = __toESM(require("fs"));
var import_path8 = __toESM(require("path"));
var import_readline3 = __toESM(require("readline"));
var FileTask = class extends import_events3.EventEmitter {
  constructor() {
    super();
    this.streams = [];
  }
  start(files, cwd) {
    let count = files.length;
    for (let file of files) {
      let filepath = import_path8.default.isAbsolute(file) ? file : import_path8.default.join(cwd, file);
      if (!import_fs6.default.existsSync(filepath)) continue;
      let stream = import_fs6.default.createReadStream(filepath, { encoding: "utf8" });
      this.streams.push(stream);
      const rl = import_readline3.default.createInterface({
        input: stream
      });
      let dirname = import_path8.default.dirname(filepath);
      rl.on("line", (line) => {
        if (line.startsWith("!")) return;
        let [name, file2, pattern] = line.split("	");
        if (!pattern) return;
        let fullpath = import_path8.default.join(dirname, file2);
        let uri = import_coc12.Uri.file(fullpath).toString();
        let relativeFile = isParentFolder(cwd, fullpath) ? import_path8.default.relative(cwd, fullpath) : fullpath;
        this.emit("data", {
          label: `${import_safe7.default.blue(name)} ${import_safe7.default.grey(relativeFile)}`,
          filterText: name,
          location: {
            uri,
            line: pattern.replace(/^\/\^/, "").replace(/\$\/;?"?$/, ""),
            text: name
          }
        });
      });
      rl.on("error", (e) => {
        count = count - 1;
        this.emit("error", e.message);
      });
      rl.on("close", () => {
        count = count - 1;
        if (count == 0) {
          this.emit("end");
        }
      });
    }
  }
  dispose() {
    for (let stream of this.streams) {
      stream.close();
    }
  }
};
var Helptags2 = class extends import_coc12.BasicList {
  constructor(nvim) {
    super(nvim);
    this.name = "tags";
    this.description = "search from tags";
    this.defaultAction = "open";
    this.addLocationActions();
    this.disposables.push(import_coc12.commands.registerCommand("tags.generate", async () => {
      let config = import_coc12.workspace.getConfiguration("list.source.tags");
      let cmd = config.get("command", "ctags -R .");
      let res = await import_coc12.window.runTerminalCommand(cmd);
      if (res.success) import_coc12.window.showMessage("tagfile generated");
    }));
  }
  async loadItems(_context) {
    let { nvim } = this;
    let cwd = await nvim.call("getcwd");
    let tagfiles = await nvim.call("tagfiles");
    if (!tagfiles || tagfiles.length == 0) {
      throw new Error('no tag files found, use ":CocCommand tags.generate" to generate tagfile.');
    }
    let task = new FileTask();
    task.start(tagfiles, cwd);
    return task;
  }
};

// src/windows.ts
var import_safe8 = __toESM(require_safe());
var Windows = class {
  constructor(nvim) {
    this.nvim = nvim;
    this.name = "windows";
    this.description = "windows list";
    this.defaultAction = "jump";
    this.actions = [];
    this.actions.push({
      name: "jump",
      execute: (item) => {
        if (Array.isArray(item)) return;
        nvim.call("win_gotoid", item.data.id, true);
      }
    });
  }
  async loadItems(_context) {
    let { nvim } = this;
    let wins = await nvim.call("getwininfo");
    let res = [];
    for (let win of wins) {
      let bufname = await nvim.call("bufname", win.bufnr);
      res.push({
        label: `${import_safe8.default.yellow(win.tabnr.toString())}	${import_safe8.default.yellow(win.winnr.toString())}	${bufname}`,
        data: { id: win.winid }
      });
    }
    return res;
  }
};

// src/words.ts
var import_coc13 = require("coc.nvim");
var import_safe9 = __toESM(require_safe());
var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
var Words = class extends import_coc13.BasicList {
  constructor(nvim) {
    super(nvim);
    this.name = "words";
    this.searchHighlight = false;
    this.interactive = true;
    this.description = "word matches of current buffer";
    this.options = [{
      name: "-w, -word",
      description: "Match word boundary."
    }];
    this.addLocationActions();
  }
  async loadItems(context) {
    let { input, window: window3 } = context;
    if (!input) return [];
    let valid = await window3.valid;
    if (!valid) return [];
    let buf = await window3.buffer;
    let doc = import_coc13.workspace.getDocument(buf.id);
    if (!doc) return;
    let { args } = context;
    let wordMatch = args.indexOf("-w") !== -1 || args.indexOf("-word") !== -1;
    let content = doc.getDocumentContent();
    let result = [];
    let lnum = 1;
    let total = doc.lineCount.toString().length;
    let flags = context.options.ignorecase ? "iu" : "u";
    let source = input.replace(matchOperatorsRe, "\\$&");
    if (wordMatch) source = `\\b${source}\\b`;
    let regex9 = new RegExp(source, flags);
    let replaceRegex = new RegExp(source, flags + "g");
    for (let line of content.split("\n")) {
      let ms = line.match(regex9);
      if (ms) {
        let range = import_coc13.Range.create(lnum - 1, ms.index, lnum - 1, ms.index + input.length);
        let pre = `${import_safe9.default.magenta(lnum.toString())}${pad(lnum.toString(), total)}`;
        let text = line.replace(replaceRegex, (match) => {
          return import_safe9.default.red(match);
        });
        result.push({
          label: `${pre} ${text}`,
          location: import_coc13.Location.create(doc.uri, range),
          filterText: ""
        });
      }
      lnum = lnum + 1;
    }
    return result;
  }
};

// src/functions.ts
var import_safe10 = __toESM(require_safe());
var Functions = class {
  constructor(nvim) {
    this.nvim = nvim;
    this.name = "functions";
    this.description = "function list";
    this.defaultAction = "open";
    this.actions = [];
    this.actions.push({
      name: "open",
      execute: async (item) => {
        if (Array.isArray(item)) return;
        let { funcname } = item.data;
        let res = await nvim.eval(`split(execute("verbose function ${funcname}"),"
")[1]`);
        let [filepath, _, line] = res.replace(/^\s+Last\sset\sfrom\s+/, "").split(/\s+/);
        if (line) {
          nvim.command(`edit +${line} ${filepath}`, true);
        } else {
          nvim.command(`edit +/${funcname} ${filepath}`, true);
        }
      }
    });
  }
  async loadItems(_context) {
    let { nvim } = this;
    let list = await nvim.eval('split(execute("function"),"\n")');
    list = list.slice(1);
    let res = [];
    for (let str of list) {
      let name = str.slice(8).split(/\(/)[0];
      let end = str.slice(8 + name.length);
      res.push({
        label: str.slice(0, 8) + import_safe10.default.magenta(name) + end,
        filterText: name,
        data: {
          funcname: name
        }
      });
    }
    return res;
  }
};

// src/index.ts
async function activate(context) {
  let { subscriptions } = context;
  let config = import_coc14.workspace.getConfiguration(void 0, null);
  let disabled = config.get("lists.disabledLists", []);
  let { nvim } = import_coc14.workspace;
  function isDisabled(name) {
    return disabled.indexOf(name) !== -1;
  }
  if (!isDisabled("lines")) {
    subscriptions.push(import_coc14.listManager.registerList(new Lines(nvim)));
  }
  if (!isDisabled("session")) {
    let saveOnVimLeave = config.get("session.saveOnVimLeave", true);
    subscriptions.push(import_coc14.listManager.registerList(new SessionList(nvim, context.extensionPath, saveOnVimLeave)));
  }
  if (!isDisabled("cmdhistory")) {
    subscriptions.push(import_coc14.listManager.registerList(new Cmdhistory(nvim)));
  }
  if (!isDisabled("searchhistory")) {
    subscriptions.push(import_coc14.listManager.registerList(new Searchhistory(nvim)));
  }
  if (!isDisabled("vimcommands")) {
    subscriptions.push(import_coc14.listManager.registerList(new Commands(nvim)));
  }
  if (!isDisabled("maps")) {
    subscriptions.push(import_coc14.listManager.registerList(new Maps(nvim)));
  }
  if (!isDisabled("colors")) {
    subscriptions.push(import_coc14.listManager.registerList(new Colors(nvim)));
  }
  if (!isDisabled("windows")) {
    subscriptions.push(import_coc14.listManager.registerList(new Windows(nvim)));
  }
  if (!isDisabled("marks")) {
    subscriptions.push(import_coc14.listManager.registerList(new Marks(nvim)));
  }
  if (!isDisabled("filetypes")) {
    subscriptions.push(import_coc14.listManager.registerList(new Filetypes(nvim)));
  }
  if (!isDisabled("files")) {
    subscriptions.push(import_coc14.listManager.registerList(new FilesList(nvim)));
  }
  if (!isDisabled("tags")) {
    subscriptions.push(import_coc14.listManager.registerList(new Helptags2(nvim)));
  }
  if (!isDisabled("helptags")) {
    subscriptions.push(import_coc14.listManager.registerList(new Helptags(nvim)));
  }
  if (!isDisabled("registers")) {
    subscriptions.push(import_coc14.listManager.registerList(new Registers(nvim)));
  }
  if (!isDisabled("buffers")) {
    subscriptions.push(import_coc14.listManager.registerList(new BufferList(nvim)));
  }
  if (!isDisabled("changes")) {
    subscriptions.push(import_coc14.listManager.registerList(new ChangeList(nvim)));
  }
  if (!isDisabled("grep")) {
    subscriptions.push(import_coc14.listManager.registerList(new GrepList(nvim)));
  }
  if (!isDisabled("LocationList")) {
    subscriptions.push(import_coc14.listManager.registerList(new LocationList(nvim)));
  }
  if (!isDisabled("mru")) {
    subscriptions.push(import_coc14.listManager.registerList(new MruList(nvim)));
  }
  if (!isDisabled("quickfix")) {
    subscriptions.push(import_coc14.listManager.registerList(new QuickfixList(nvim)));
  }
  if (!isDisabled("words")) {
    subscriptions.push(import_coc14.listManager.registerList(new Words(nvim)));
  }
  if (!isDisabled("functions")) {
    subscriptions.push(import_coc14.listManager.registerList(new Functions(nvim)));
  }
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  activate
});
