|
| 1 | +// @ts-check |
| 2 | +import * as eslint from 'eslint' |
| 3 | + |
| 4 | +// eslint-disable-next-line @typescript-eslint/no-namespace -- ignore |
| 5 | +export namespace ESLint { |
| 6 | + export type LintResult = eslint.ESLint.LintResult |
| 7 | +} |
| 8 | +export const ESLint = eslint.ESLint || getESLintClassForV6() |
| 9 | + |
| 10 | +function getESLintClassForV6(): typeof eslint.ESLint { |
| 11 | + class ESLintForV6 { |
| 12 | + private engine: eslint.CLIEngine |
| 13 | + static get version() { |
| 14 | + return eslint.CLIEngine.version |
| 15 | + } |
| 16 | + |
| 17 | + constructor(options?: eslint.ESLint.Options) { |
| 18 | + const { |
| 19 | + overrideConfig: { plugins, globals, rules, ...overrideConfig } = { |
| 20 | + plugins: [], |
| 21 | + globals: {}, |
| 22 | + rules: {} |
| 23 | + }, |
| 24 | + fix, |
| 25 | + reportUnusedDisableDirectives, |
| 26 | + plugins: pluginsMap, |
| 27 | + ...otherOptions |
| 28 | + } = options || {} |
| 29 | + const newOptions: eslint.CLIEngine.Options = { |
| 30 | + fix: Boolean(fix), |
| 31 | + reportUnusedDisableDirectives: reportUnusedDisableDirectives |
| 32 | + ? reportUnusedDisableDirectives !== 'off' |
| 33 | + : undefined, |
| 34 | + ...otherOptions, |
| 35 | + |
| 36 | + globals: globals |
| 37 | + ? Object.keys(globals).filter(n => globals[n]) |
| 38 | + : undefined, |
| 39 | + plugins: plugins || [], |
| 40 | + rules: rules |
| 41 | + ? Object.entries(rules).reduce((o, [ruleId, opt]) => { |
| 42 | + if (opt) { |
| 43 | + o[ruleId] = opt |
| 44 | + } |
| 45 | + return o |
| 46 | + }, {} as NonNullable<eslint.CLIEngine.Options['rules']>) |
| 47 | + : undefined, |
| 48 | + ...overrideConfig |
| 49 | + } |
| 50 | + this.engine = new eslint.CLIEngine(newOptions) |
| 51 | + |
| 52 | + for (const [name, plugin] of Object.entries(pluginsMap || {})) { |
| 53 | + this.engine.addPlugin(name, plugin) |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + async lintText( |
| 58 | + ...params: Parameters<eslint.ESLint['lintText']> |
| 59 | + ): ReturnType<eslint.ESLint['lintText']> { |
| 60 | + const result = this.engine.executeOnText(params[0], params[1]?.filePath) |
| 61 | + return result.results |
| 62 | + } |
| 63 | + |
| 64 | + async lintFiles( |
| 65 | + ...params: Parameters<eslint.ESLint['lintFiles']> |
| 66 | + ): ReturnType<eslint.ESLint['lintFiles']> { |
| 67 | + const result = this.engine.executeOnFiles( |
| 68 | + Array.isArray(params[0]) ? params[0] : [params[0]] |
| 69 | + ) |
| 70 | + return result.results |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | + const eslintClass = ESLintForV6 as never |
| 75 | + return eslintClass |
| 76 | +} |
0 commit comments