"use strict";
/* --------------------------------------------------------------------------------------------
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for license information.
 * ------------------------------------------------------------------------------------------ */

require("core-js/modules/es.symbol.js");

require("core-js/modules/es.symbol.description.js");

require("core-js/modules/es.symbol.iterator.js");

require("core-js/modules/es.function.name.js");

require("core-js/modules/es.array.from.js");

require("core-js/modules/es.promise.js");

require("regenerator-runtime/runtime.js");

require("core-js/modules/es.array.iterator.js");

require("core-js/modules/es.object.to-string.js");

require("core-js/modules/es.set.js");

require("core-js/modules/es.string.iterator.js");

require("core-js/modules/web.dom-collections.iterator.js");

require("core-js/modules/es.map.js");

require("core-js/modules/es.array.filter.js");

require("core-js/modules/web.dom-collections.for-each.js");

require("core-js/modules/es.object.entries.js");

require("core-js/modules/es.string.starts-with.js");

require("core-js/modules/es.regexp.exec.js");

require("core-js/modules/es.string.replace.js");

require("core-js/modules/es.array.sort.js");

require("core-js/modules/es.regexp.constructor.js");

require("core-js/modules/es.regexp.to-string.js");

require("core-js/modules/es.array.slice.js");

require("core-js/modules/es.object.keys.js");

require("core-js/modules/es.array.concat.js");

require("core-js/modules/es.number.is-nan.js");

require("core-js/modules/es.number.constructor.js");

require("core-js/modules/es.object.assign.js");

require("core-js/modules/es.array.join.js");

require("core-js/modules/es.string.trim.js");

function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e2) { throw _e2; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e3) { didErr = true; err = _e3; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ESLint = exports.CodeActions = exports.RuleSeverities = exports.SaveRuleConfigs = exports.Fixes = exports.ESLintModule = exports.SuggestionsProblem = exports.FixableProblem = exports.Problem = exports.RuleMetaData = exports.ESLintError = exports.TextDocumentSettings = void 0;

var fs = require("fs");

var path = require("path");

var crypto = require("crypto");

var child_process_1 = require("child_process");

var semverParse = require("semver/functions/parse");

var semverGte = require("semver/functions/gte");

var node_1 = require("vscode-languageserver/node");

var vscode_uri_1 = require("vscode-uri");

var customMessages_1 = require("./shared/customMessages");

var settings_1 = require("./shared/settings");

var Is = require("./is");

var linkedMap_1 = require("./linkedMap");

var paths_1 = require("./paths");

var languageDefaults_1 = require("./languageDefaults");

var TextDocumentSettings;

(function (TextDocumentSettings) {
  function hasLibrary(settings) {
    return settings.library !== undefined;
  }

  TextDocumentSettings.hasLibrary = hasLibrary;
})(TextDocumentSettings || (exports.TextDocumentSettings = TextDocumentSettings = {}));

var ESLintError;

(function (ESLintError) {
  function isNoConfigFound(error) {
    var candidate = error;
    return candidate.messageTemplate === 'no-config-found' || candidate.message === 'No ESLint configuration found.';
  }

  ESLintError.isNoConfigFound = isNoConfigFound;
})(ESLintError || (exports.ESLintError = ESLintError = {}));

var RuleMetaData;

(function (RuleMetaData) {
  // For unused eslint-disable comments, ESLint does not include a rule ID
  // nor any other metadata (although they do provide a fix). In order to
  // provide code actions for these, we create a fake rule ID and metadata.
  RuleMetaData.unusedDisableDirectiveId = 'unused-disable-directive';
  var unusedDisableDirectiveMeta = {
    docs: {
      url: 'https://eslint.org/docs/latest/use/configure/rules#report-unused-eslint-disable-comments'
    },
    type: 'directive'
  };
  var handled = new Set();
  var ruleId2Meta = new Map([[RuleMetaData.unusedDisableDirectiveId, unusedDisableDirectiveMeta]]);

  function capture(eslint, reports) {
    var rulesMetaData;

    if (eslint.isCLIEngine) {
      var toHandle = reports.filter(function (report) {
        return !handled.has(report.filePath);
      });

      if (toHandle.length === 0) {
        return;
      }

      rulesMetaData = typeof eslint.getRulesMetaForResults === 'function' ? eslint.getRulesMetaForResults(toHandle) : undefined;
      toHandle.forEach(function (report) {
        return handled.add(report.filePath);
      });
    } else {
      rulesMetaData = typeof eslint.getRulesMetaForResults === 'function' ? eslint.getRulesMetaForResults(reports) : undefined;
    }

    if (rulesMetaData === undefined) {
      return undefined;
    }

    Object.entries(rulesMetaData).forEach(function (_ref) {
      var _ref2 = _slicedToArray(_ref, 2),
          key = _ref2[0],
          meta = _ref2[1];

      if (ruleId2Meta.has(key)) {
        return;
      }

      if (meta && meta.docs && Is.string(meta.docs.url)) {
        ruleId2Meta.set(key, meta);
      }
    });
  }

  RuleMetaData.capture = capture;

  function clear() {
    handled.clear();
    ruleId2Meta.clear();
    ruleId2Meta.set(RuleMetaData.unusedDisableDirectiveId, unusedDisableDirectiveMeta);
  }

  RuleMetaData.clear = clear;

  function getUrl(ruleId) {
    var _ruleId2Meta$get, _ruleId2Meta$get$docs;

    return (_ruleId2Meta$get = ruleId2Meta.get(ruleId)) === null || _ruleId2Meta$get === void 0 ? void 0 : (_ruleId2Meta$get$docs = _ruleId2Meta$get.docs) === null || _ruleId2Meta$get$docs === void 0 ? void 0 : _ruleId2Meta$get$docs.url;
  }

  RuleMetaData.getUrl = getUrl;

  function getType(ruleId) {
    var _ruleId2Meta$get2;

    return (_ruleId2Meta$get2 = ruleId2Meta.get(ruleId)) === null || _ruleId2Meta$get2 === void 0 ? void 0 : _ruleId2Meta$get2.type;
  }

  RuleMetaData.getType = getType;

  function hasRuleId(ruleId) {
    return ruleId2Meta.has(ruleId);
  }

  RuleMetaData.hasRuleId = hasRuleId;

  function isUnusedDisableDirectiveProblem(problem) {
    return problem.ruleId === null && problem.message.startsWith('Unused eslint-disable directive');
  }

  RuleMetaData.isUnusedDisableDirectiveProblem = isUnusedDisableDirectiveProblem;
})(RuleMetaData || (exports.RuleMetaData = RuleMetaData = {}));

var Problem;

(function (Problem) {
  function isFixable(problem) {
    return problem.edit !== undefined;
  }

  Problem.isFixable = isFixable;

  function hasSuggestions(problem) {
    return problem.suggestions !== undefined;
  }

  Problem.hasSuggestions = hasSuggestions;
})(Problem || (exports.Problem = Problem = {}));

var FixableProblem;

(function (FixableProblem) {
  function createTextEdit(document, editInfo) {
    return node_1.TextEdit.replace(node_1.Range.create(document.positionAt(editInfo.edit.range[0]), document.positionAt(editInfo.edit.range[1])), editInfo.edit.text || '');
  }

  FixableProblem.createTextEdit = createTextEdit;
})(FixableProblem || (exports.FixableProblem = FixableProblem = {}));

var SuggestionsProblem;

(function (SuggestionsProblem) {
  function createTextEdit(document, suggestion) {
    return node_1.TextEdit.replace(node_1.Range.create(document.positionAt(suggestion.fix.range[0]), document.positionAt(suggestion.fix.range[1])), suggestion.fix.text || '');
  }

  SuggestionsProblem.createTextEdit = createTextEdit;
})(SuggestionsProblem || (exports.SuggestionsProblem = SuggestionsProblem = {}));

var ESLintClass;

(function (ESLintClass) {
  function getConfigType(eslint) {
    if (eslint.isCLIEngine === true) {
      return 'eslintrc';
    }

    var configType = eslint.constructor.configType;
    return configType !== null && configType !== void 0 ? configType : 'eslintrc';
  }

  ESLintClass.getConfigType = getConfigType;
})(ESLintClass || (ESLintClass = {}));

var ESLintModule;

(function (ESLintModule) {
  function hasLoadESLint(value) {
    return value.loadESLint !== undefined;
  }

  ESLintModule.hasLoadESLint = hasLoadESLint;

  function hasESLintClass(value) {
    return value.ESLint !== undefined;
  }

  ESLintModule.hasESLintClass = hasESLintClass;

  function hasCLIEngine(value) {
    return value.CLIEngine !== undefined;
  }

  ESLintModule.hasCLIEngine = hasCLIEngine;

  function isFlatConfig(value) {
    var candidate = value;
    return candidate.ESLint !== undefined && candidate.isFlatConfig === true;
  }

  ESLintModule.isFlatConfig = isFlatConfig;
})(ESLintModule || (exports.ESLintModule = ESLintModule = {}));

var RuleData;

(function (RuleData) {
  function hasMetaType(value) {
    return value !== undefined && value.type !== undefined;
  }

  RuleData.hasMetaType = hasMetaType;
})(RuleData || (RuleData = {}));

var CLIEngine;

(function (CLIEngine) {
  function hasRule(value) {
    return value.getRules !== undefined;
  }

  CLIEngine.hasRule = hasRule;
})(CLIEngine || (CLIEngine = {}));
/**
 * ESLint class emulator using CLI Engine.
 */


var ESLintClassEmulator = /*#__PURE__*/function () {
  function ESLintClassEmulator(cli) {
    _classCallCheck(this, ESLintClassEmulator);

    this.cli = cli;
  }

  _createClass(ESLintClassEmulator, [{
    key: "isCLIEngine",
    get: function get() {
      return true;
    }
  }, {
    key: "lintText",
    value: function () {
      var _lintText = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(content, options) {
        return regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                return _context.abrupt("return", this.cli.executeOnText(content, options.filePath, options.warnIgnored).results);

              case 1:
              case "end":
                return _context.stop();
            }
          }
        }, _callee, this);
      }));

      function lintText(_x, _x2) {
        return _lintText.apply(this, arguments);
      }

      return lintText;
    }()
  }, {
    key: "isPathIgnored",
    value: function () {
      var _isPathIgnored = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(path) {
        return regeneratorRuntime.wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                return _context2.abrupt("return", this.cli.isPathIgnored(path));

              case 1:
              case "end":
                return _context2.stop();
            }
          }
        }, _callee2, this);
      }));

      function isPathIgnored(_x3) {
        return _isPathIgnored.apply(this, arguments);
      }

      return isPathIgnored;
    }()
  }, {
    key: "getRulesMetaForResults",
    value: function getRulesMetaForResults(_results) {
      if (!CLIEngine.hasRule(this.cli)) {
        return undefined;
      }

      var rules = {};

      var _iterator = _createForOfIteratorHelper(this.cli.getRules()),
          _step;

      try {
        for (_iterator.s(); !(_step = _iterator.n()).done;) {
          var _step$value = _slicedToArray(_step.value, 2),
              name = _step$value[0],
              rule = _step$value[1];

          if (rule.meta !== undefined) {
            rules[name] = rule.meta;
          }
        }
      } catch (err) {
        _iterator.e(err);
      } finally {
        _iterator.f();
      }

      return rules;
    }
  }, {
    key: "calculateConfigForFile",
    value: function () {
      var _calculateConfigForFile = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3(path) {
        return regeneratorRuntime.wrap(function _callee3$(_context3) {
          while (1) {
            switch (_context3.prev = _context3.next) {
              case 0:
                return _context3.abrupt("return", typeof this.cli.getConfigForFile === 'function' ? this.cli.getConfigForFile(path) : undefined);

              case 1:
              case "end":
                return _context3.stop();
            }
          }
        }, _callee3, this);
      }));

      function calculateConfigForFile(_x4) {
        return _calculateConfigForFile.apply(this, arguments);
      }

      return calculateConfigForFile;
    }()
  }]);

  return ESLintClassEmulator;
}();
/**
 * Class for dealing with Fixes.
 */


var Fixes = /*#__PURE__*/function () {
  function Fixes(edits) {
    _classCallCheck(this, Fixes);

    this.edits = edits;
  }

  _createClass(Fixes, [{
    key: "isEmpty",
    value: function isEmpty() {
      return this.edits.size === 0;
    }
  }, {
    key: "getDocumentVersion",
    value: function getDocumentVersion() {
      if (this.isEmpty()) {
        throw new Error('No edits recorded.');
      }

      return this.edits.values().next().value.documentVersion;
    }
  }, {
    key: "getScoped",
    value: function getScoped(diagnostics) {
      var result = [];

      var _iterator2 = _createForOfIteratorHelper(diagnostics),
          _step2;

      try {
        for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
          var diagnostic = _step2.value;
          var key = Diagnostics.computeKey(diagnostic);
          var editInfo = this.edits.get(key);

          if (editInfo) {
            result.push(editInfo);
          }
        }
      } catch (err) {
        _iterator2.e(err);
      } finally {
        _iterator2.f();
      }

      return result;
    }
  }, {
    key: "getAllSorted",
    value: function getAllSorted() {
      var result = [];

      var _iterator3 = _createForOfIteratorHelper(this.edits.values()),
          _step3;

      try {
        for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
          var value = _step3.value;

          if (Problem.isFixable(value)) {
            result.push(value);
          }
        }
      } catch (err) {
        _iterator3.e(err);
      } finally {
        _iterator3.f();
      }

      return result.sort(function (a, b) {
        var d0 = a.edit.range[0] - b.edit.range[0];

        if (d0 !== 0) {
          return d0;
        } // Both edits have now the same start offset.
        // Length of a and length of b


        var al = a.edit.range[1] - a.edit.range[0];
        var bl = b.edit.range[1] - b.edit.range[0]; // Both has the same start offset and length.

        if (al === bl) {
          return 0;
        }

        if (al === 0) {
          return -1;
        }

        if (bl === 0) {
          return 1;
        }

        return al - bl;
      });
    }
  }, {
    key: "getApplicable",
    value: function getApplicable() {
      var sorted = this.getAllSorted();

      if (sorted.length <= 1) {
        return sorted;
      }

      var result = [];
      var last = sorted[0];
      result.push(last);

      for (var i = 1; i < sorted.length; i++) {
        var current = sorted[i];

        if (!Fixes.overlaps(last, current) && !Fixes.sameRange(last, current)) {
          result.push(current);
          last = current;
        }
      }

      return result;
    }
  }], [{
    key: "overlaps",
    value: function overlaps(a, b) {
      return a !== undefined && a.edit.range[1] > b.edit.range[0];
    }
  }, {
    key: "sameRange",
    value: function sameRange(a, b) {
      return a.edit.range[0] === b.edit.range[0] && a.edit.range[1] === b.edit.range[1];
    }
  }]);

  return Fixes;
}();

exports.Fixes = Fixes;
/**
 * Manages the special save rule configurations done in the VS Code settings.
 */

var SaveRuleConfigs;

(function (SaveRuleConfigs) {
  var saveRuleConfigCache = new linkedMap_1.LRUCache(128);

  function get(_x5, _x6) {
    return _get.apply(this, arguments);
  }

  function _get() {
    _get = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee5(uri, settings) {
      var filePath, result, rules;
      return regeneratorRuntime.wrap(function _callee5$(_context5) {
        while (1) {
          switch (_context5.prev = _context5.next) {
            case 0:
              filePath = SaveRuleConfigs.inferFilePath(uri);
              result = saveRuleConfigCache.get(uri);

              if (!(filePath === undefined || result === null)) {
                _context5.next = 4;
                break;
              }

              return _context5.abrupt("return", undefined);

            case 4:
              if (!(result !== undefined)) {
                _context5.next = 6;
                break;
              }

              return _context5.abrupt("return", result);

            case 6:
              rules = settings.codeActionOnSave.rules;
              _context5.next = 9;
              return ESLint.withClass( /*#__PURE__*/function () {
                var _ref3 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4(eslint) {
                  var config, offRules, onRules, _i2, _Object$keys, ruleId;

                  return regeneratorRuntime.wrap(function _callee4$(_context4) {
                    while (1) {
                      switch (_context4.prev = _context4.next) {
                        case 0:
                          if (!(rules === undefined || eslint.isCLIEngine)) {
                            _context4.next = 2;
                            break;
                          }

                          return _context4.abrupt("return", undefined);

                        case 2:
                          _context4.next = 4;
                          return eslint.calculateConfigForFile(filePath);

                        case 4:
                          config = _context4.sent;

                          if (!(config === undefined || config.rules === undefined || config.rules.length === 0)) {
                            _context4.next = 7;
                            break;
                          }

                          return _context4.abrupt("return", undefined);

                        case 7:
                          offRules = new Set();
                          onRules = new Set();

                          if (rules.length === 0) {
                            Object.keys(config.rules).forEach(function (ruleId) {
                              return offRules.add(ruleId);
                            });
                          } else {
                            for (_i2 = 0, _Object$keys = Object.keys(config.rules); _i2 < _Object$keys.length; _i2++) {
                              ruleId = _Object$keys[_i2];

                              if (isOff(ruleId, rules)) {
                                offRules.add(ruleId);
                              } else {
                                onRules.add(ruleId);
                              }
                            }
                          }

                          return _context4.abrupt("return", offRules.size > 0 ? {
                            offRules: offRules,
                            onRules: onRules
                          } : undefined);

                        case 11:
                        case "end":
                          return _context4.stop();
                      }
                    }
                  }, _callee4);
                }));

                return function (_x7) {
                  return _ref3.apply(this, arguments);
                };
              }(), settings);

            case 9:
              result = _context5.sent;

              if (!(result === undefined || result === null)) {
                _context5.next = 15;
                break;
              }

              saveRuleConfigCache.set(uri, null);
              return _context5.abrupt("return", undefined);

            case 15:
              saveRuleConfigCache.set(uri, result);
              return _context5.abrupt("return", result);

            case 17:
            case "end":
              return _context5.stop();
          }
        }
      }, _callee5);
    }));
    return _get.apply(this, arguments);
  }

  SaveRuleConfigs.get = get;

  function remove(key) {
    return saveRuleConfigCache.delete(key);
  }

  SaveRuleConfigs.remove = remove;

  function clear() {
    saveRuleConfigCache.clear();
  }

  SaveRuleConfigs.clear = clear;

  function isOff(ruleId, matchers) {
    var _iterator4 = _createForOfIteratorHelper(matchers),
        _step4;

    try {
      for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
        var matcher = _step4.value;

        if (matcher.startsWith('!') && new RegExp("^".concat(matcher.slice(1).replace(/\*/g, '.*'), "$"), 'g').test(ruleId)) {
          return true;
        } else if (new RegExp("^".concat(matcher.replace(/\*/g, '.*'), "$"), 'g').test(ruleId)) {
          return false;
        }
      }
    } catch (err) {
      _iterator4.e(err);
    } finally {
      _iterator4.f();
    }

    return true;
  }
})(SaveRuleConfigs || (exports.SaveRuleConfigs = SaveRuleConfigs = {}));
/**
 * Manages rule severity overrides done using VS Code settings.
 */


var RuleSeverities;

(function (RuleSeverities) {
  var ruleSeverityCache = new linkedMap_1.LRUCache(1024);

  function getOverride(ruleId, customizations, isFixable) {
    var result = ruleSeverityCache.get(ruleId);

    if (result === null) {
      return undefined;
    }

    if (result !== undefined) {
      return result;
    }

    var _iterator5 = _createForOfIteratorHelper(customizations),
        _step5;

    try {
      for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
        var customization = _step5.value;

        if ( // Rule name should match
        asteriskMatches(customization.rule, ruleId) && ( // Fixable flag should match the fixability of the rule if it's defined
        customization.fixable === undefined || customization.fixable === isFixable)) {
          result = customization.severity;
        }
      }
    } catch (err) {
      _iterator5.e(err);
    } finally {
      _iterator5.f();
    }

    if (result === undefined) {
      ruleSeverityCache.set(ruleId, null);
      return undefined;
    }

    ruleSeverityCache.set(ruleId, result);
    return result;
  }

  RuleSeverities.getOverride = getOverride;

  function clear() {
    ruleSeverityCache.clear();
  }

  RuleSeverities.clear = clear;

  function asteriskMatches(matcher, ruleId) {
    return matcher.startsWith('!') ? !new RegExp("^".concat(matcher.slice(1).replace(/\*/g, '.*'), "$"), 'g').test(ruleId) : new RegExp("^".concat(matcher.replace(/\*/g, '.*'), "$"), 'g').test(ruleId);
  }
})(RuleSeverities || (exports.RuleSeverities = RuleSeverities = {}));
/**
 * Creates LSP Diagnostics and captures code action information.
 */


var Diagnostics;

(function (Diagnostics) {
  function computeKey(diagnostic) {
    var _message;

    var range = diagnostic.range;
    var message;

    if (diagnostic.message) {
      var hash = crypto.createHash('sha256');
      hash.update(diagnostic.message);
      message = hash.digest('base64');
    }

    return "[".concat(range.start.line, ",").concat(range.start.character, ",").concat(range.end.line, ",").concat(range.end.character, "]-").concat(diagnostic.code, "-").concat((_message = message) !== null && _message !== void 0 ? _message : '');
  }

  Diagnostics.computeKey = computeKey;

  function create(settings, problem, document) {
    var message = problem.message;
    var startLine = typeof problem.line !== 'number' || Number.isNaN(problem.line) ? 0 : Math.max(0, problem.line - 1);
    var startChar = typeof problem.column !== 'number' || Number.isNaN(problem.column) ? 0 : Math.max(0, problem.column - 1);
    var endLine = typeof problem.endLine !== 'number' || Number.isNaN(problem.endLine) ? startLine : Math.max(0, problem.endLine - 1);
    var endChar = typeof problem.endColumn !== 'number' || Number.isNaN(problem.endColumn) ? startChar : Math.max(0, problem.endColumn - 1);

    if (settings.problems.shortenToSingleLine && endLine !== startLine) {
      var startLineText = document.getText({
        start: {
          line: startLine,
          character: 0
        },
        end: {
          line: startLine,
          character: node_1.uinteger.MAX_VALUE
        }
      });
      endLine = startLine;
      endChar = startLineText.length;
    }

    var override = RuleSeverities.getOverride(problem.ruleId, settings.rulesCustomizations, problem.fix !== undefined);
    var result = {
      message: message,
      severity: convertSeverityToDiagnosticWithOverride(problem.severity, override),
      source: 'eslint',
      range: {
        start: {
          line: startLine,
          character: startChar
        },
        end: {
          line: endLine,
          character: endChar
        }
      }
    };

    if (problem.ruleId) {
      var url = RuleMetaData.getUrl(problem.ruleId);
      result.code = problem.ruleId;

      if (url !== undefined) {
        result.codeDescription = {
          href: url
        };
      }

      if (problem.ruleId === 'no-unused-vars') {
        result.tags = [node_1.DiagnosticTag.Unnecessary];
      }
    }

    return [result, override];
  }

  Diagnostics.create = create;

  function adjustSeverityForOverride(severity, severityOverride) {
    switch (severityOverride) {
      case settings_1.RuleSeverity.off:
      case settings_1.RuleSeverity.info:
      case settings_1.RuleSeverity.warn:
      case settings_1.RuleSeverity.error:
        return severityOverride;

      case settings_1.RuleSeverity.downgrade:
        switch (convertSeverityToDiagnostic(severity)) {
          case node_1.DiagnosticSeverity.Error:
            return settings_1.RuleSeverity.warn;

          case node_1.DiagnosticSeverity.Warning:
          case node_1.DiagnosticSeverity.Information:
            return settings_1.RuleSeverity.info;
        }

      case settings_1.RuleSeverity.upgrade:
        switch (convertSeverityToDiagnostic(severity)) {
          case node_1.DiagnosticSeverity.Information:
            return settings_1.RuleSeverity.warn;

          case node_1.DiagnosticSeverity.Warning:
          case node_1.DiagnosticSeverity.Error:
            return settings_1.RuleSeverity.error;
        }

      default:
        return severity;
    }
  }

  function convertSeverityToDiagnostic(severity) {
    // RuleSeverity concerns an overridden rule. A number is direct from ESLint.
    switch (severity) {
      // Eslint 1 is warning
      case 1:
      case settings_1.RuleSeverity.warn:
        return node_1.DiagnosticSeverity.Warning;

      case 2:
      case settings_1.RuleSeverity.error:
        return node_1.DiagnosticSeverity.Error;

      case settings_1.RuleSeverity.info:
        return node_1.DiagnosticSeverity.Information;

      default:
        return node_1.DiagnosticSeverity.Error;
    }
  }

  function convertSeverityToDiagnosticWithOverride(severity, severityOverride) {
    return convertSeverityToDiagnostic(adjustSeverityForOverride(severity, severityOverride));
  }
})(Diagnostics || (Diagnostics = {}));
/**
 * Capture information necessary to compute code actions.
 */


var CodeActions;

(function (CodeActions) {
  var codeActions = new Map();

  function get(uri) {
    return codeActions.get(uri);
  }

  CodeActions.get = get;

  function set(uri, value) {
    codeActions.set(uri, value);
  }

  CodeActions.set = set;

  function remove(uri) {
    return codeActions.delete(uri);
  }

  CodeActions.remove = remove;

  function record(document, diagnostic, problem) {
    if (!problem.ruleId) {
      return;
    }

    var uri = document.uri;
    var edits = CodeActions.get(uri);

    if (edits === undefined) {
      edits = new Map();
      CodeActions.set(uri, edits);
    }

    edits.set(Diagnostics.computeKey(diagnostic), {
      label: "Fix this ".concat(problem.ruleId, " problem"),
      documentVersion: document.version,
      ruleId: problem.ruleId,
      line: problem.line,
      diagnostic: diagnostic,
      edit: problem.fix,
      suggestions: problem.suggestions
    });
  }

  CodeActions.record = record;
})(CodeActions || (exports.CodeActions = CodeActions = {}));
/**
 * Wrapper round the ESLint npm module.
 */


var ESLint;

(function (ESLint) {
  var connection;
  var documents;
  var inferFilePath;
  var loadNodeModule;

  var languageId2ParserRegExp = function createLanguageId2ParserRegExp() {
    var result = new Map();
    var typescript = /\/@typescript-eslint\/parser\//;
    var babelESLint = /\/babel-eslint\/lib\/index.js$/;
    var vueESLint = /\/vue-eslint-parser\/index.js$/;
    result.set('typescript', [typescript, babelESLint, vueESLint]);
    result.set('typescriptreact', [typescript, babelESLint, vueESLint]);
    var angular = /\/@angular-eslint\/template-parser\//;
    result.set('html', [angular]);
    return result;
  }();

  var languageId2ParserOptions = function createLanguageId2ParserOptionsRegExp() {
    var result = new Map();
    var vue = /vue-eslint-parser\/.*\.js$/;
    var typescriptEslintParser = /@typescript-eslint\/parser\/.*\.js$/;
    result.set('typescript', {
      regExps: [vue],
      parsers: new Set(['@typescript-eslint/parser']),
      parserRegExps: [typescriptEslintParser]
    });
    return result;
  }();

  var languageId2PluginName = new Map([['astro', 'astro'], ['html', 'html'], ['json', 'jsonc'], ['json5', 'jsonc'], ['jsonc', 'jsonc'], ['mdx', 'mdx'], ['vue', 'vue'], ['markdown', 'markdown']]);
  var defaultLanguageIds = new Set(['javascript', 'javascriptreact']);
  var projectFolderIndicators = [{
    fileName: 'eslint.config.js',
    isRoot: true,
    isFlatConfig: true
  }, {
    fileName: 'eslint.config.cjs',
    isRoot: true,
    isFlatConfig: true
  }, {
    fileName: 'eslint.config.mjs',
    isRoot: true,
    isFlatConfig: true
  }, {
    fileName: 'package.json',
    isRoot: true,
    isFlatConfig: false
  }, {
    fileName: '.eslintignore',
    isRoot: true,
    isFlatConfig: false
  }, {
    fileName: '.eslintrc',
    isRoot: false,
    isFlatConfig: false
  }, {
    fileName: '.eslintrc.json',
    isRoot: false,
    isFlatConfig: false
  }, {
    fileName: '.eslintrc.js',
    isRoot: false,
    isFlatConfig: false
  }, {
    fileName: '.eslintrc.yaml',
    isRoot: false,
    isFlatConfig: false
  }, {
    fileName: '.eslintrc.yml',
    isRoot: false,
    isFlatConfig: false
  }];
  var path2Library = new Map();
  var document2Settings = new Map();
  var formatterRegistrations = new Map();

  function initialize($connection, $documents, $inferFilePath, $loadNodeModule) {
    connection = $connection;
    documents = $documents;
    inferFilePath = $inferFilePath;
    loadNodeModule = $loadNodeModule;
  }

  ESLint.initialize = initialize;

  function removeSettings(key) {
    return document2Settings.delete(key);
  }

  ESLint.removeSettings = removeSettings;

  function clearSettings() {
    document2Settings.clear();
  }

  ESLint.clearSettings = clearSettings;

  function unregisterAsFormatter(document) {
    var unregister = formatterRegistrations.get(document.uri);

    if (unregister !== undefined) {
      void unregister.then(function (disposable) {
        return disposable.dispose();
      });
      formatterRegistrations.delete(document.uri);
    }
  }

  ESLint.unregisterAsFormatter = unregisterAsFormatter;

  function clearFormatters() {
    var _iterator6 = _createForOfIteratorHelper(formatterRegistrations.values()),
        _step6;

    try {
      for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
        var unregistration = _step6.value;
        void unregistration.then(function (disposable) {
          return disposable.dispose();
        });
      }
    } catch (err) {
      _iterator6.e(err);
    } finally {
      _iterator6.f();
    }

    formatterRegistrations.clear();
  }

  ESLint.clearFormatters = clearFormatters;

  function resolveSettings(document) {
    var uri = document.uri;
    var resultPromise = document2Settings.get(uri);

    if (resultPromise) {
      return resultPromise;
    }

    resultPromise = connection.workspace.getConfiguration({
      scopeUri: uri,
      section: ''
    }).then(function (configuration) {
      var _configuration$workin;

      var settings = Object.assign({}, configuration, {
        silent: false,
        library: undefined,
        resolvedGlobalPackageManagerPath: undefined
      }, {
        workingDirectory: undefined
      });

      if (settings.validate === settings_1.Validate.off) {
        return settings;
      }

      settings.resolvedGlobalPackageManagerPath = GlobalPaths.get(settings.packageManager);
      var filePath = inferFilePath(document);
      var workspaceFolderPath = settings.workspaceFolder !== undefined ? inferFilePath(settings.workspaceFolder.uri) : undefined;
      var assumeFlatConfig = false;
      var hasUserDefinedWorkingDirectories = configuration.workingDirectory !== undefined;
      var workingDirectoryConfig = (_configuration$workin = configuration.workingDirectory) !== null && _configuration$workin !== void 0 ? _configuration$workin : {
        mode: settings_1.ModeEnum.location
      };

      if (settings_1.ModeItem.is(workingDirectoryConfig)) {
        var candidate;

        if (workingDirectoryConfig.mode === settings_1.ModeEnum.location) {
          if (workspaceFolderPath !== undefined) {
            var _findWorkingDirectory = findWorkingDirectory(workspaceFolderPath, filePath),
                _findWorkingDirectory2 = _slicedToArray(_findWorkingDirectory, 2),
                configLocation = _findWorkingDirectory2[0],
                isFlatConfig = _findWorkingDirectory2[1];

            if (isFlatConfig && settings.useFlatConfig !== false) {
              candidate = configLocation;
              assumeFlatConfig = true;
            } else {
              candidate = workspaceFolderPath;
            }
          } else if (filePath !== undefined && !(0, paths_1.isUNC)(filePath)) {
            candidate = path.dirname(filePath);
          }
        } else if (workingDirectoryConfig.mode === settings_1.ModeEnum.auto) {
          if (workspaceFolderPath !== undefined) {
            candidate = findWorkingDirectory(workspaceFolderPath, filePath)[0];
          } else if (filePath !== undefined && !(0, paths_1.isUNC)(filePath)) {
            candidate = path.dirname(filePath);
          }
        }

        if (candidate !== undefined && fs.existsSync(candidate)) {
          settings.workingDirectory = {
            directory: candidate
          };
        }
      } else {
        settings.workingDirectory = workingDirectoryConfig;
      }

      var nodePath;

      if (settings.nodePath !== null) {
        nodePath = settings.nodePath;

        if (!path.isAbsolute(nodePath) && workspaceFolderPath !== undefined) {
          nodePath = path.join(workspaceFolderPath, nodePath);
        }
      }

      var moduleResolveWorkingDirectory;

      if (!hasUserDefinedWorkingDirectories && filePath !== undefined) {
        moduleResolveWorkingDirectory = path.dirname(filePath);
      }

      if (moduleResolveWorkingDirectory === undefined && settings.workingDirectory !== undefined && !settings.workingDirectory['!cwd']) {
        moduleResolveWorkingDirectory = settings.workingDirectory.directory;
      }

      var promise; // During Flat Config is considered experimental,
      // we need to import FlatESLint from 'eslint/use-at-your-own-risk'.
      // See: https://eslint.org/blog/2022/08/new-config-system-part-3/

      var eslintPath = settings.experimental.useFlatConfig ? 'eslint/use-at-your-own-risk' : 'eslint';

      if (nodePath !== undefined) {
        promise = node_1.Files.resolve(eslintPath, nodePath, nodePath, trace).then(undefined, function () {
          return node_1.Files.resolve(eslintPath, settings.resolvedGlobalPackageManagerPath, moduleResolveWorkingDirectory, trace);
        });
      } else {
        promise = node_1.Files.resolve(eslintPath, settings.resolvedGlobalPackageManagerPath, moduleResolveWorkingDirectory, trace);
      }

      settings.silent = settings.validate === settings_1.Validate.probe;
      return promise.then( /*#__PURE__*/function () {
        var _ref4 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee9(libraryPath) {
          var library, lib, esLintVersion, _filePath, parserRegExps, pluginName, parserOptions, _yield$ESLint$withCla, _yield$ESLint$withCla2, isIgnored, configType, _settings$workingDire, _yield$ESLint$withCla3, _yield$ESLint$withCla4, eslintConfig, _configType, _settings$workingDire2, parser, _eslintConfig$parserO, _iterator7, _step7, regExp, _iterator9, _step9, name, params, Uri, isFile, pattern, filter, options, _filePath2;

          return regeneratorRuntime.wrap(function _callee9$(_context9) {
            while (1) {
              switch (_context9.prev = _context9.next) {
                case 0:
                  library = path2Library.get(libraryPath);

                  if (library === undefined) {
                    if (settings.experimental.useFlatConfig) {
                      lib = loadNodeModule(libraryPath);

                      if (lib === undefined) {
                        settings.validate = settings_1.Validate.off;

                        if (!settings.silent) {
                          connection.console.error("Failed to load eslint library from ".concat(libraryPath, ". If you are using ESLint v8.21 or earlier, try upgrading it. For newer versions, try disabling the 'eslint.experimental.useFlatConfig' setting. See the output panel for more information."));
                        }
                      } else if (lib.FlatESLint === undefined) {
                        settings.validate = settings_1.Validate.off;
                        connection.console.error("The eslint library loaded from ".concat(libraryPath, " doesn't export a FlatESLint class."));
                      } else {
                        connection.console.info("ESLint library loaded from: ".concat(libraryPath)); // pretend to be a regular eslint endpoint

                        library = {
                          ESLint: lib.FlatESLint,
                          isFlatConfig: true,
                          CLIEngine: undefined
                        };
                        settings.library = library;
                        path2Library.set(libraryPath, library);
                      }
                    } else {
                      library = loadNodeModule(libraryPath);

                      if (library === undefined) {
                        settings.validate = settings_1.Validate.off;

                        if (!settings.silent) {
                          connection.console.error("Failed to load eslint library from ".concat(libraryPath, ". See output panel for more information."));
                        }
                      } else if (library.CLIEngine === undefined && library.ESLint === undefined) {
                        settings.validate = settings_1.Validate.off;
                        connection.console.error("The eslint library loaded from ".concat(libraryPath, " doesn't export neither a CLIEngine nor an ESLint class. You need at least eslint@1.0.0"));
                      } else {
                        connection.console.info("ESLint library loaded from: ".concat(libraryPath));
                        settings.library = library;
                        path2Library.set(libraryPath, library);
                      }
                    }

                    if (library !== undefined && ESLintModule.hasESLintClass(library) && typeof library.ESLint.version === 'string') {
                      esLintVersion = semverParse(library.ESLint.version);

                      if (esLintVersion !== null) {
                        if (semverGte(esLintVersion, '8.57.0') && settings.experimental.useFlatConfig === true) {
                          connection.console.info("ESLint version ".concat(library.ESLint.version, " supports flat config without experimental opt-in. The 'eslint.experimental.useFlatConfig' setting can be removed."));
                        } else if (semverGte(esLintVersion, '10.0.0') && (settings.experimental.useFlatConfig === false || settings.useFlatConfig === false)) {
                          connection.console.info("ESLint version ".concat(library.ESLint.version, " only supports flat configs. Setting is ignored."));
                        }
                      }
                    }
                  } else {
                    settings.library = library;
                  }

                  if (!(settings.validate === settings_1.Validate.probe && TextDocumentSettings.hasLibrary(settings))) {
                    _context9.next = 83;
                    break;
                  }

                  settings.validate = settings_1.Validate.off;
                  _filePath = ESLint.getFilePath(document, settings);

                  if (!(_filePath !== undefined)) {
                    _context9.next = 82;
                    break;
                  }

                  parserRegExps = languageId2ParserRegExp.get(document.languageId);
                  pluginName = languageId2PluginName.get(document.languageId);
                  parserOptions = languageId2ParserOptions.get(document.languageId);

                  if (!defaultLanguageIds.has(document.languageId)) {
                    _context9.next = 28;
                    break;
                  }

                  _context9.prev = 10;
                  _context9.next = 13;
                  return ESLint.withClass( /*#__PURE__*/function () {
                    var _ref5 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee6(eslintClass) {
                      return regeneratorRuntime.wrap(function _callee6$(_context6) {
                        while (1) {
                          switch (_context6.prev = _context6.next) {
                            case 0:
                              _context6.next = 2;
                              return eslintClass.isPathIgnored(_filePath);

                            case 2:
                              _context6.t0 = _context6.sent;
                              _context6.t1 = ESLintClass.getConfigType(eslintClass);
                              return _context6.abrupt("return", [_context6.t0, _context6.t1]);

                            case 5:
                            case "end":
                              return _context6.stop();
                          }
                        }
                      }, _callee6);
                    }));

                    return function (_x9) {
                      return _ref5.apply(this, arguments);
                    };
                  }(), settings);

                case 13:
                  _yield$ESLint$withCla = _context9.sent;
                  _yield$ESLint$withCla2 = _slicedToArray(_yield$ESLint$withCla, 2);
                  isIgnored = _yield$ESLint$withCla2[0];
                  configType = _yield$ESLint$withCla2[1];

                  if (isIgnored === false) {
                    settings.validate = settings_1.Validate.on;

                    if (assumeFlatConfig && configType === 'eslintrc') {
                      connection.console.info("Expected to use flat configuration from directory ".concat((_settings$workingDire = settings.workingDirectory) === null || _settings$workingDire === void 0 ? void 0 : _settings$workingDire.directory, " but loaded eslintrc config."));
                    }
                  }

                  _context9.next = 26;
                  break;

                case 20:
                  _context9.prev = 20;
                  _context9.t0 = _context9["catch"](10);
                  settings.validate = settings_1.Validate.off;
                  _context9.next = 25;
                  return connection.sendNotification(customMessages_1.StatusNotification.type, {
                    uri: uri,
                    state: customMessages_1.Status.error
                  });

                case 25:
                  connection.console.error("Calculating config file for ".concat(uri, ") failed.\n").concat(_context9.t0 instanceof Error ? _context9.t0.stack : ''));

                case 26:
                  _context9.next = 82;
                  break;

                case 28:
                  if (!(parserRegExps !== undefined || pluginName !== undefined || parserOptions !== undefined)) {
                    _context9.next = 82;
                    break;
                  }

                  _context9.next = 31;
                  return ESLint.withClass( /*#__PURE__*/function () {
                    var _ref6 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee7(eslintClass) {
                      return regeneratorRuntime.wrap(function _callee7$(_context7) {
                        while (1) {
                          switch (_context7.prev = _context7.next) {
                            case 0:
                              _context7.prev = 0;
                              _context7.next = 3;
                              return eslintClass.isPathIgnored(_filePath);

                            case 3:
                              if (!_context7.sent) {
                                _context7.next = 7;
                                break;
                              }

                              return _context7.abrupt("return", [undefined, undefined]);

                            case 7:
                              _context7.next = 9;
                              return eslintClass.calculateConfigForFile(_filePath);

                            case 9:
                              _context7.t0 = _context7.sent;
                              _context7.t1 = ESLintClass.getConfigType(eslintClass);
                              return _context7.abrupt("return", [_context7.t0, _context7.t1]);

                            case 12:
                              _context7.next = 25;
                              break;

                            case 14:
                              _context7.prev = 14;
                              _context7.t2 = _context7["catch"](0);
                              _context7.prev = 16;
                              _context7.next = 19;
                              return connection.sendNotification(customMessages_1.StatusNotification.type, {
                                uri: uri,
                                state: customMessages_1.Status.error
                              });

                            case 19:
                              connection.console.error("Calculating config file for ".concat(uri, ") failed.\n").concat(_context7.t2 instanceof Error ? _context7.t2.stack : ''));
                              _context7.next = 24;
                              break;

                            case 22:
                              _context7.prev = 22;
                              _context7.t3 = _context7["catch"](16);

                            case 24:
                              return _context7.abrupt("return", [undefined, undefined]);

                            case 25:
                            case "end":
                              return _context7.stop();
                          }
                        }
                      }, _callee7, null, [[0, 14], [16, 22]]);
                    }));

                    return function (_x10) {
                      return _ref6.apply(this, arguments);
                    };
                  }(), settings);

                case 31:
                  _yield$ESLint$withCla3 = _context9.sent;
                  _yield$ESLint$withCla4 = _slicedToArray(_yield$ESLint$withCla3, 2);
                  eslintConfig = _yield$ESLint$withCla4[0];
                  _configType = _yield$ESLint$withCla4[1];

                  if (!(eslintConfig !== undefined)) {
                    _context9.next = 82;
                    break;
                  }

                  if (assumeFlatConfig && _configType === 'eslintrc') {
                    connection.console.info("Expected to use flat configuration from directory ".concat((_settings$workingDire2 = settings.workingDirectory) === null || _settings$workingDire2 === void 0 ? void 0 : _settings$workingDire2.directory, " but loaded eslintrc config."));
                  }

                  if (!(_configType === 'flat' || ESLintModule.isFlatConfig(settings.library))) {
                    _context9.next = 41;
                    break;
                  }

                  // We have a flat configuration. This means that the config file needs to
                  // have a section per file extension we want to validate. If there is none than
                  // `calculateConfigForFile` will return no config since the config options without
                  // a `files` property only applies to `**/*.js, **/*.cjs, and **/*.mjs` by default
                  // See https://eslint.org/docs/latest/user-guide/configuring/configuration-files-new#specifying-files-and-ignores
                  // This means since we have found a configuration for the given file we assume that
                  // that configuration is correctly pointing to a parser.
                  settings.validate = settings_1.Validate.on;
                  _context9.next = 82;
                  break;

                case 41:
                  parser = eslintConfig.parser !== null ? (0, paths_1.normalizePath)(eslintConfig.parser) : undefined;

                  if (!(parser !== undefined)) {
                    _context9.next = 63;
                    break;
                  }

                  if (!(parserRegExps !== undefined)) {
                    _context9.next = 62;
                    break;
                  }

                  _iterator7 = _createForOfIteratorHelper(parserRegExps);
                  _context9.prev = 45;

                  _iterator7.s();

                case 47:
                  if ((_step7 = _iterator7.n()).done) {
                    _context9.next = 54;
                    break;
                  }

                  regExp = _step7.value;

                  if (!regExp.test(parser)) {
                    _context9.next = 52;
                    break;
                  }

                  settings.validate = settings_1.Validate.on;
                  return _context9.abrupt("break", 54);

                case 52:
                  _context9.next = 47;
                  break;

                case 54:
                  _context9.next = 59;
                  break;

                case 56:
                  _context9.prev = 56;
                  _context9.t1 = _context9["catch"](45);

                  _iterator7.e(_context9.t1);

                case 59:
                  _context9.prev = 59;

                  _iterator7.f();

                  return _context9.finish(59);

                case 62:
                  if (settings.validate !== settings_1.Validate.on && parserOptions !== undefined && typeof ((_eslintConfig$parserO = eslintConfig.parserOptions) === null || _eslintConfig$parserO === void 0 ? void 0 : _eslintConfig$parserO.parser) === 'string') {
                    (function () {
                      var eslintConfigParserOptionsParser = (0, paths_1.normalizePath)(eslintConfig.parserOptions.parser);

                      var _iterator8 = _createForOfIteratorHelper(parserOptions.regExps),
                          _step8;

                      try {
                        for (_iterator8.s(); !(_step8 = _iterator8.n()).done;) {
                          var _regExp = _step8.value;

                          if (_regExp.test(parser) && (parserOptions.parsers.has(eslintConfig.parserOptions.parser) || parserOptions.parserRegExps !== undefined && parserOptions.parserRegExps.some(function (parserRegExp) {
                            return parserRegExp.test(eslintConfigParserOptionsParser);
                          }))) {
                            settings.validate = settings_1.Validate.on;
                            break;
                          }
                        }
                      } catch (err) {
                        _iterator8.e(err);
                      } finally {
                        _iterator8.f();
                      }
                    })();
                  }

                case 63:
                  if (!(settings.validate !== settings_1.Validate.on && Array.isArray(eslintConfig.plugins) && eslintConfig.plugins.length > 0 && pluginName !== undefined)) {
                    _context9.next = 82;
                    break;
                  }

                  _iterator9 = _createForOfIteratorHelper(eslintConfig.plugins);
                  _context9.prev = 65;

                  _iterator9.s();

                case 67:
                  if ((_step9 = _iterator9.n()).done) {
                    _context9.next = 74;
                    break;
                  }

                  name = _step9.value;

                  if (!(name === pluginName)) {
                    _context9.next = 72;
                    break;
                  }

                  settings.validate = settings_1.Validate.on;
                  return _context9.abrupt("break", 74);

                case 72:
                  _context9.next = 67;
                  break;

                case 74:
                  _context9.next = 79;
                  break;

                case 76:
                  _context9.prev = 76;
                  _context9.t2 = _context9["catch"](65);

                  _iterator9.e(_context9.t2);

                case 79:
                  _context9.prev = 79;

                  _iterator9.f();

                  return _context9.finish(79);

                case 82:
                  if (settings.validate === settings_1.Validate.off) {
                    params = {
                      textDocument: {
                        uri: document.uri
                      }
                    };
                    void connection.sendRequest(customMessages_1.ProbeFailedRequest.type, params);
                  }

                case 83:
                  if (!(settings.validate === settings_1.Validate.on)) {
                    _context9.next = 99;
                    break;
                  }

                  settings.silent = false;

                  if (!(settings.format && TextDocumentSettings.hasLibrary(settings) && !formatterRegistrations.has(uri))) {
                    _context9.next = 99;
                    break;
                  }

                  Uri = vscode_uri_1.URI.parse(uri);
                  isFile = Uri.scheme === 'file';
                  pattern = isFile ? Uri.fsPath.replace(/\\/g, '/') : Uri.fsPath;
                  pattern = pattern.replace(/[\[\]\{\}]/g, '?');
                  filter = {
                    scheme: Uri.scheme,
                    pattern: pattern
                  };
                  options = {
                    documentSelector: [filter]
                  };

                  if (isFile) {
                    _context9.next = 96;
                    break;
                  }

                  formatterRegistrations.set(uri, connection.client.register(node_1.DocumentFormattingRequest.type, options));
                  _context9.next = 99;
                  break;

                case 96:
                  _filePath2 = inferFilePath(uri);
                  _context9.next = 99;
                  return ESLint.withClass( /*#__PURE__*/function () {
                    var _ref7 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee8(eslintClass) {
                      return regeneratorRuntime.wrap(function _callee8$(_context8) {
                        while (1) {
                          switch (_context8.prev = _context8.next) {
                            case 0:
                              _context8.next = 2;
                              return eslintClass.isPathIgnored(_filePath2);

                            case 2:
                              if (_context8.sent) {
                                _context8.next = 4;
                                break;
                              }

                              formatterRegistrations.set(uri, connection.client.register(node_1.DocumentFormattingRequest.type, options));

                            case 4:
                            case "end":
                              return _context8.stop();
                          }
                        }
                      }, _callee8);
                    }));

                    return function (_x11) {
                      return _ref7.apply(this, arguments);
                    };
                  }(), settings);

                case 99:
                  return _context9.abrupt("return", settings);

                case 100:
                case "end":
                  return _context9.stop();
              }
            }
          }, _callee9, null, [[10, 20], [45, 56, 59, 62], [65, 76, 79, 82]]);
        }));

        return function (_x8) {
          return _ref4.apply(this, arguments);
        };
      }(), function () {
        settings.validate = settings_1.Validate.off;

        if (!settings.silent) {
          void connection.sendRequest(customMessages_1.NoESLintLibraryRequest.type, {
            source: {
              uri: document.uri
            }
          });
        }

        return settings;
      });
    });
    document2Settings.set(uri, resultPromise);
    return resultPromise;
  }

  ESLint.resolveSettings = resolveSettings;

  function newClass(_x12, _x13, _x14) {
    return _newClass.apply(this, arguments);
  }

  function _newClass() {
    _newClass = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee10(library, newOptions, settings) {
      return regeneratorRuntime.wrap(function _callee10$(_context10) {
        while (1) {
          switch (_context10.prev = _context10.next) {
            case 0:
              if (!ESLintModule.hasLoadESLint(library)) {
                _context10.next = 6;
                break;
              }

              _context10.next = 3;
              return library.loadESLint({
                useFlatConfig: settings.useFlatConfig
              });

            case 3:
              _context10.t0 = _context10.sent;
              _context10.t1 = newOptions;
              return _context10.abrupt("return", new _context10.t0(_context10.t1));

            case 6:
              if (!(ESLintModule.hasESLintClass(library) && settings.useESLintClass)) {
                _context10.next = 8;
                break;
              }

              return _context10.abrupt("return", new library.ESLint(newOptions));

            case 8:
              if (!ESLintModule.hasCLIEngine(library)) {
                _context10.next = 10;
                break;
              }

              return _context10.abrupt("return", new ESLintClassEmulator(new library.CLIEngine(newOptions)));

            case 10:
              return _context10.abrupt("return", new library.ESLint(newOptions));

            case 11:
            case "end":
              return _context10.stop();
          }
        }
      }, _callee10);
    }));
    return _newClass.apply(this, arguments);
  }

  ESLint.newClass = newClass;

  function withClass(_x15, _x16, _x17) {
    return _withClass.apply(this, arguments);
  }

  function _withClass() {
    _withClass = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee11(func, settings, options) {
      var newOptions, cwd, newCWD, eslintClass;
      return regeneratorRuntime.wrap(function _callee11$(_context11) {
        while (1) {
          switch (_context11.prev = _context11.next) {
            case 0:
              newOptions = options === undefined ? Object.assign(Object.create(null), settings.options) : Object.assign(Object.create(null), settings.options, options);
              cwd = process.cwd();
              _context11.prev = 2;

              if (settings.workingDirectory) {
                // A lot of libs are sensitive to drive letter casing and assume a
                // upper case drive letter. Make sure we support that correctly.
                newCWD = normalizeWorkingDirectory(settings.workingDirectory.directory);
                newOptions.cwd = newCWD;

                if (settings.workingDirectory['!cwd'] !== true && fs.existsSync(newCWD)) {
                  process.chdir(newCWD);
                }
              }

              _context11.next = 6;
              return newClass(settings.library, newOptions, settings);

            case 6:
              eslintClass = _context11.sent;
              _context11.next = 9;
              return func(eslintClass);

            case 9:
              return _context11.abrupt("return", _context11.sent);

            case 10:
              _context11.prev = 10;

              if (cwd !== process.cwd()) {
                process.chdir(cwd);
              }

              return _context11.finish(10);

            case 13:
            case "end":
              return _context11.stop();
          }
        }
      }, _callee11, null, [[2,, 10, 13]]);
    }));
    return _withClass.apply(this, arguments);
  }

  ESLint.withClass = withClass;

  function normalizeWorkingDirectory(value) {
    var result = (0, paths_1.normalizeDriveLetter)(value);

    if (result.length === 0) {
      return result;
    }

    return result[result.length - 1] === path.sep ? result.substring(0, result.length - 1) : result;
  }

  function getFilePath(document, settings) {
    if (document === undefined) {
      return undefined;
    }

    var uri = vscode_uri_1.URI.parse(document.uri);

    if (uri.scheme !== 'file') {
      if (settings.workspaceFolder !== undefined) {
        var ext = languageDefaults_1.default.getExtension(document.languageId);
        var workspacePath = inferFilePath(settings.workspaceFolder.uri);

        if (workspacePath !== undefined && ext !== undefined) {
          return path.join(workspacePath, "test.".concat(ext));
        }
      }

      return undefined;
    } else {
      return inferFilePath(uri);
    }
  }

  ESLint.getFilePath = getFilePath;
  var validFixTypes = new Set(['problem', 'suggestion', 'layout', 'directive']);

  function validate(_x18, _x19) {
    return _validate.apply(this, arguments);
  }

  function _validate() {
    _validate = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee13(document, settings) {
      var newOptions, fixTypes, _iterator11, _step11, item, content, uri, file;

      return regeneratorRuntime.wrap(function _callee13$(_context13) {
        while (1) {
          switch (_context13.prev = _context13.next) {
            case 0:
              newOptions = Object.assign(Object.create(null), settings.options);
              fixTypes = undefined;

              if (Array.isArray(newOptions.fixTypes) && newOptions.fixTypes.length > 0) {
                fixTypes = new Set();
                _iterator11 = _createForOfIteratorHelper(newOptions.fixTypes);

                try {
                  for (_iterator11.s(); !(_step11 = _iterator11.n()).done;) {
                    item = _step11.value;

                    if (validFixTypes.has(item)) {
                      fixTypes.add(item);
                    }
                  }
                } catch (err) {
                  _iterator11.e(err);
                } finally {
                  _iterator11.f();
                }

                if (fixTypes.size === 0) {
                  fixTypes = undefined;
                }
              }

              content = document.getText();
              uri = document.uri;
              file = getFilePath(document, settings);
              return _context13.abrupt("return", withClass( /*#__PURE__*/function () {
                var _ref8 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee12(eslintClass) {
                  var reportResults, diagnostics, docReport;
                  return regeneratorRuntime.wrap(function _callee12$(_context12) {
                    while (1) {
                      switch (_context12.prev = _context12.next) {
                        case 0:
                          CodeActions.remove(uri);
                          _context12.next = 3;
                          return eslintClass.lintText(content, {
                            filePath: file,
                            warnIgnored: settings.onIgnoredFiles !== settings_1.ESLintSeverity.off
                          });

                        case 3:
                          reportResults = _context12.sent;
                          RuleMetaData.capture(eslintClass, reportResults);
                          diagnostics = [];

                          if (reportResults && Array.isArray(reportResults) && reportResults.length > 0) {
                            docReport = reportResults[0];

                            if (docReport.messages && Array.isArray(docReport.messages)) {
                              docReport.messages.forEach(function (problem) {
                                if (problem) {
                                  var _Diagnostics$create = Diagnostics.create(settings, problem, document),
                                      _Diagnostics$create2 = _slicedToArray(_Diagnostics$create, 2),
                                      diagnostic = _Diagnostics$create2[0],
                                      override = _Diagnostics$create2[1];

                                  if (!(override === settings_1.RuleSeverity.off || settings.quiet && diagnostic.severity === node_1.DiagnosticSeverity.Warning)) {
                                    diagnostics.push(diagnostic);
                                  }

                                  if (fixTypes !== undefined && problem.ruleId !== undefined && problem.fix !== undefined) {
                                    var type = RuleMetaData.getType(problem.ruleId);

                                    if (type !== undefined && fixTypes.has(type)) {
                                      CodeActions.record(document, diagnostic, problem);
                                    }
                                  } else {
                                    if (RuleMetaData.isUnusedDisableDirectiveProblem(problem)) {
                                      problem.ruleId = RuleMetaData.unusedDisableDirectiveId;
                                    }

                                    CodeActions.record(document, diagnostic, problem);
                                  }
                                }
                              });
                            }
                          }

                          return _context12.abrupt("return", diagnostics);

                        case 8:
                        case "end":
                          return _context12.stop();
                      }
                    }
                  }, _callee12);
                }));

                return function (_x20) {
                  return _ref8.apply(this, arguments);
                };
              }(), settings));

            case 7:
            case "end":
              return _context13.stop();
          }
        }
      }, _callee13);
    }));
    return _validate.apply(this, arguments);
  }

  ESLint.validate = validate;

  function trace(message, verbose) {
    connection.tracer.log(message, verbose);
  }
  /**
   * Global paths for the different package managers
   */


  var GlobalPaths;

  (function (GlobalPaths) {
    var globalPaths = {
      yarn: {
        cache: undefined,
        get: function get() {
          return node_1.Files.resolveGlobalYarnPath(trace);
        }
      },
      npm: {
        cache: undefined,
        get: function get() {
          return node_1.Files.resolveGlobalNodePath(trace);
        }
      },
      pnpm: {
        cache: undefined,
        get: function get() {
          var pnpmPath = (0, child_process_1.execSync)('pnpm root -g').toString().trim();
          return pnpmPath;
        }
      }
    };

    function get(packageManager) {
      var pm = globalPaths[packageManager];

      if (pm) {
        if (pm.cache === undefined) {
          pm.cache = pm.get();
        }

        return pm.cache;
      }

      return undefined;
    }

    GlobalPaths.get = get;
  })(GlobalPaths || (GlobalPaths = {}));

  function findWorkingDirectory(workspaceFolder, file) {
    if (file === undefined || (0, paths_1.isUNC)(file)) {
      return [workspaceFolder, false];
    } // Don't probe for something in node modules folder.


    if (file.indexOf("".concat(path.sep, "node_modules").concat(path.sep)) !== -1) {
      return [workspaceFolder, false];
    }

    var result = workspaceFolder;
    var flatConfig = false;
    var directory = path.dirname(file);

    outer: while (directory !== undefined && directory.startsWith(workspaceFolder)) {
      var _iterator10 = _createForOfIteratorHelper(projectFolderIndicators),
          _step10;

      try {
        for (_iterator10.s(); !(_step10 = _iterator10.n()).done;) {
          var _step10$value = _step10.value,
              fileName = _step10$value.fileName,
              isRoot = _step10$value.isRoot,
              isFlatConfig = _step10$value.isFlatConfig;

          if (fs.existsSync(path.join(directory, fileName))) {
            result = directory;
            flatConfig = isFlatConfig;

            if (isRoot) {
              break outer;
            } else {
              break;
            }
          }
        }
      } catch (err) {
        _iterator10.e(err);
      } finally {
        _iterator10.f();
      }

      var parent = path.dirname(directory);
      directory = parent !== directory ? parent : undefined;
    }

    return [result, flatConfig];
  }

  ESLint.findWorkingDirectory = findWorkingDirectory;
  var ErrorHandlers;

  (function (ErrorHandlers) {
    ErrorHandlers.single = [tryHandleNoConfig, tryHandleConfigError, tryHandleMissingModule, showErrorMessage];

    function getMessage(err, document) {
      var result = undefined;

      if (typeof err.message === 'string' || err.message instanceof String) {
        result = err.message;
        result = result.replace(/\r?\n/g, ' ');

        if (/^CLI: /.test(result)) {
          result = result.substr(5);
        }
      } else {
        result = "An unknown error occurred while validating document: ".concat(document.uri);
      }

      return result;
    }

    ErrorHandlers.getMessage = getMessage;
    var noConfigReported = new Map();

    function clearNoConfigReported() {
      noConfigReported.clear();
    }

    ErrorHandlers.clearNoConfigReported = clearNoConfigReported;

    function tryHandleNoConfig(error, document, library) {
      if (!ESLintError.isNoConfigFound(error)) {
        return undefined;
      }

      if (!noConfigReported.has(document.uri)) {
        connection.sendRequest(customMessages_1.NoConfigRequest.type, {
          message: getMessage(error, document),
          document: {
            uri: document.uri
          }
        }).then(undefined, function () {});
        noConfigReported.set(document.uri, library);
      }

      return customMessages_1.Status.warn;
    }

    var configErrorReported = new Map();

    function getConfigErrorReported(key) {
      return configErrorReported.get(key);
    }

    ErrorHandlers.getConfigErrorReported = getConfigErrorReported;

    function removeConfigErrorReported(key) {
      return configErrorReported.delete(key);
    }

    ErrorHandlers.removeConfigErrorReported = removeConfigErrorReported;

    function tryHandleConfigError(error, document, library, settings) {
      if (!error.message) {
        return undefined;
      }

      function handleFileName(filename) {
        if (!configErrorReported.has(filename)) {
          connection.console.error(getMessage(error, document));

          if (!documents.get(vscode_uri_1.URI.file(filename).toString())) {
            connection.window.showInformationMessage(getMessage(error, document));
          }

          configErrorReported.set(filename, {
            library: library,
            settings: settings
          });
        }

        return customMessages_1.Status.warn;
      }

      var matches = /Cannot read config file:\s+(.*)\nError:\s+(.*)/.exec(error.message);

      if (matches && matches.length === 3) {
        return handleFileName(matches[1]);
      }

      matches = /(.*):\n\s*Configuration for rule \"(.*)\" is /.exec(error.message);

      if (matches && matches.length === 3) {
        return handleFileName(matches[1]);
      }

      matches = /Cannot find module '([^']*)'\nReferenced from:\s+(.*)/.exec(error.message);

      if (matches && matches.length === 3) {
        return handleFileName(matches[2]);
      }

      return undefined;
    }

    var missingModuleReported = new Map();

    function clearMissingModuleReported() {
      missingModuleReported.clear();
    }

    ErrorHandlers.clearMissingModuleReported = clearMissingModuleReported;

    function tryHandleMissingModule(error, document, library) {
      if (!error.message) {
        return undefined;
      }

      function handleMissingModule(plugin, module, error) {
        if (!missingModuleReported.has(plugin)) {
          var fsPath = inferFilePath(document);
          missingModuleReported.set(plugin, library);

          if (error.messageTemplate === 'plugin-missing') {
            connection.console.error(['', "".concat(error.message.toString()), "Happened while validating ".concat(fsPath ? fsPath : document.uri), "This can happen for a couple of reasons:", "1. The plugin name is spelled incorrectly in an ESLint configuration file (e.g. .eslintrc).", "2. If ESLint is installed globally, then make sure ".concat(module, " is installed globally as well."), "3. If ESLint is installed locally, then ".concat(module, " isn't installed correctly."), '', "Consider running eslint --debug ".concat(fsPath ? fsPath : document.uri, " from a terminal to obtain a trace about the configuration files used.")].join('\n'));
          } else {
            connection.console.error(["".concat(error.message.toString()), "Happened while validating ".concat(fsPath ? fsPath : document.uri)].join('\n'));
          }
        }

        return customMessages_1.Status.warn;
      }

      var matches = /Failed to load plugin (.*): Cannot find module (.*)/.exec(error.message);

      if (matches && matches.length === 3) {
        return handleMissingModule(matches[1], matches[2], error);
      }

      return undefined;
    }

    function showErrorMessage(error, document) {
      if (Is.string(error.stack)) {
        connection.console.error('An unexpected error occurred:');
        connection.console.error(error.stack);
      } else {
        connection.console.error("An unexpected error occurred: ".concat(getMessage(error, document), "."));
      }

      return customMessages_1.Status.error;
    }
  })(ErrorHandlers = ESLint.ErrorHandlers || (ESLint.ErrorHandlers = {}));
})(ESLint || (exports.ESLint = ESLint = {}));