@pob/eslint-config 67.4.0 → 67.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,121 @@
1
+ import { execFile } from "node:child_process";
2
+ import { readFileSync, readdirSync } from "node:fs";
3
+ import path from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { promisify } from "node:util";
6
+
7
+ const execFileAsync = promisify(execFile);
8
+
9
+ // the bin used by projects, which also locates tsgolint for type-aware rules
10
+ const oxlintBinPath = fileURLToPath(
11
+ new URL("./bin/oxlint.js", import.meta.resolve("@pob/root/package.json")),
12
+ );
13
+
14
+ export const oxlintConfigsDir = fileURLToPath(
15
+ new URL("../../oxlint/", import.meta.url),
16
+ );
17
+
18
+ /**
19
+ * Runs oxlint in `cwd` and parses its JSON output.
20
+ *
21
+ * @param {string} cwd
22
+ * @param {string[]} args
23
+ * @returns {Promise<any>}
24
+ */
25
+ const execOxlint = async (cwd, args) => {
26
+ try {
27
+ const { stdout } = await execFileAsync(
28
+ process.execPath,
29
+ [oxlintBinPath, ...args],
30
+ { cwd, maxBuffer: 16 * 1024 * 1024 },
31
+ );
32
+ return JSON.parse(stdout);
33
+ } catch (error) {
34
+ const { code, stdout } = /** @type {{ code: unknown; stdout: string }} */ (
35
+ error
36
+ );
37
+ // oxlint exits with code 1 when it reports errors
38
+ if (code !== 1) throw error;
39
+ return JSON.parse(stdout);
40
+ }
41
+ };
42
+
43
+ /**
44
+ * @typedef {{
45
+ * code?: string;
46
+ * message: string;
47
+ * severity: string;
48
+ * filename: string;
49
+ * labels: { span: { line: number } }[];
50
+ * }} OxlintDiagnostic
51
+ */
52
+
53
+ /**
54
+ * Lints `cwd` with the .oxlintrc.json it contains.
55
+ *
56
+ * @param {string} cwd
57
+ * @returns {Promise<OxlintDiagnostic[]>}
58
+ */
59
+ export const lintWithOxlint = async (cwd) => {
60
+ const { diagnostics } = await execOxlint(cwd, ["-f", "json"]);
61
+ return diagnostics;
62
+ };
63
+
64
+ /**
65
+ * Rules implemented by the installed oxlint, as `plugin/rule`.
66
+ *
67
+ * @param {string} cwd
68
+ * @returns {Promise<{ name: string; typeAware: boolean }[]>}
69
+ */
70
+ export const listOxlintRules = async (cwd) => {
71
+ /** @type {{ scope: string; value: string; type_aware: boolean }[]} */
72
+ const rules = await execOxlint(cwd, ["--rules", "-f", "json"]);
73
+ return rules.map(({ scope, value, type_aware: typeAware }) => ({
74
+ name: `${scope}/${value}`,
75
+ typeAware,
76
+ }));
77
+ };
78
+
79
+ /**
80
+ * `plugin/rule` name, as listed by `oxlint --rules`. Core rules can be written
81
+ * without the `eslint/` prefix in configs and directives.
82
+ *
83
+ * @param {string} ruleName
84
+ */
85
+ export const toCanonicalOxlintRuleName = (ruleName) =>
86
+ ruleName.includes("/") ? ruleName : `eslint/${ruleName}`;
87
+
88
+ /**
89
+ * @param {unknown} ruleEntry
90
+ */
91
+ const isRuleEnabled = (ruleEntry) => {
92
+ const severity = Array.isArray(ruleEntry) ? ruleEntry[0] : ruleEntry;
93
+ return severity !== "off" && severity !== "allow" && severity !== 0;
94
+ };
95
+
96
+ /**
97
+ * Rules enabled in `oxlint/*.json` (including `overrides`), as `plugin/rule`.
98
+ *
99
+ * @returns {string[]}
100
+ */
101
+ export const getEnabledOxlintConfigRules = () => {
102
+ const ruleNames = new Set();
103
+ for (const fileName of readdirSync(oxlintConfigsDir)) {
104
+ if (!fileName.endsWith(".json")) continue;
105
+ /** @type {{ rules?: Record<string, unknown>; overrides?: { rules?: Record<string, unknown> }[] }} */
106
+ const config = JSON.parse(
107
+ readFileSync(path.join(oxlintConfigsDir, fileName), "utf8"),
108
+ );
109
+ for (const rules of [
110
+ config.rules,
111
+ ...(config.overrides ?? []).map((override) => override.rules),
112
+ ]) {
113
+ for (const [ruleName, ruleEntry] of Object.entries(rules ?? {})) {
114
+ if (isRuleEnabled(ruleEntry)) {
115
+ ruleNames.add(toCanonicalOxlintRuleName(ruleName));
116
+ }
117
+ }
118
+ }
119
+ }
120
+ return [...ruleNames].toSorted();
121
+ };
@@ -0,0 +1,128 @@
1
+ import tseslint from "typescript-eslint";
2
+
3
+ /** oxlint plugin name → eslint rule name prefix */
4
+ const eslintRulePrefixes = new Map([
5
+ ["eslint", ""],
6
+ ["typescript", "@typescript-eslint/"],
7
+ ["unicorn", "unicorn/"],
8
+ ["import", "import-x/"],
9
+ ["node", "n/"],
10
+ ["react", "react/"],
11
+ ["jsx_a11y", "jsx-a11y/"],
12
+ ]);
13
+
14
+ /** oxlint plugins without eslint equivalent in @pob/eslint-config */
15
+ const oxlintOnlyPlugins = new Set(["oxc", "promise", "vitest"]);
16
+
17
+ /** oxlint implements eslint-plugin-react-hooks rules in its react plugin */
18
+ const reactHooksRules = new Set(["rules-of-hooks", "exhaustive-deps"]);
19
+
20
+ const typescriptEslintRules =
21
+ /** @type {import("eslint").ESLint.Plugin} */ (tseslint.plugin).rules ?? {};
22
+
23
+ /**
24
+ * eslint core rule → typescript-eslint rules extending it. Type-aware ones are
25
+ * not listed: oxlint's core rule does not replace them (see T1 in
26
+ * docs/oxlint-migration.md).
27
+ *
28
+ * @type {Map<string, string[]>}
29
+ */
30
+ const typescriptExtensionRules = new Map();
31
+ for (const [ruleName, rule] of Object.entries(typescriptEslintRules)) {
32
+ const docs =
33
+ /** @type {{ extendsBaseRule?: boolean | string; requiresTypeChecking?: boolean } | undefined} */ (
34
+ rule.meta?.docs
35
+ );
36
+ if (!docs?.extendsBaseRule || docs.requiresTypeChecking) continue;
37
+ const baseRuleName =
38
+ docs.extendsBaseRule === true ? ruleName : docs.extendsBaseRule;
39
+ typescriptExtensionRules.set(baseRuleName, [
40
+ ...(typescriptExtensionRules.get(baseRuleName) ?? []),
41
+ `@typescript-eslint/${ruleName}`,
42
+ ]);
43
+ }
44
+
45
+ /**
46
+ * Returns the eslint rule names checked by an oxlint rule, to turn them off in
47
+ * eslint. Rules of plugins other than eslint core must be prefixed with their
48
+ * oxlint plugin name (`typescript/`, `unicorn/`, ...).
49
+ *
50
+ * @param {string} oxlintRuleName
51
+ * @returns {string[]}
52
+ */
53
+ export const oxlintToEslintRuleNames = (oxlintRuleName) => {
54
+ const slashIndex = oxlintRuleName.indexOf("/");
55
+ const pluginName =
56
+ slashIndex === -1 ? "eslint" : oxlintRuleName.slice(0, slashIndex);
57
+ const ruleName = oxlintRuleName.slice(slashIndex + 1);
58
+
59
+ if (oxlintOnlyPlugins.has(pluginName)) return [];
60
+ if (pluginName === "eslint") {
61
+ return [ruleName, ...(typescriptExtensionRules.get(ruleName) ?? [])];
62
+ }
63
+ if (pluginName === "react" && reactHooksRules.has(ruleName)) {
64
+ return [`react-hooks/${ruleName}`];
65
+ }
66
+ const prefix = eslintRulePrefixes.get(pluginName);
67
+ if (prefix === undefined) {
68
+ throw new Error(
69
+ `Unknown oxlint plugin "${pluginName}" in rule "${oxlintRuleName}"`,
70
+ );
71
+ }
72
+ return [`${prefix}${ruleName}`];
73
+ };
74
+
75
+ /**
76
+ * Rules of an oxlint config, including its overrides.
77
+ *
78
+ * @param {{ rules?: Record<string, unknown>; overrides?: { rules?: Record<string, unknown> }[] }} config
79
+ * @returns {string[]}
80
+ */
81
+ export const getOxlintConfigRuleNames = (config) => [
82
+ ...Object.keys(config.rules ?? {}),
83
+ ...(config.overrides ?? []).flatMap((override) =>
84
+ Object.keys(override.rules ?? {}),
85
+ ),
86
+ ];
87
+
88
+ const unusedDisableDirectiveRegExp =
89
+ /^Unused eslint-disable directive \(no problems were reported from (.+)\)\.$/;
90
+
91
+ /**
92
+ * Rules named by eslint's "Unused eslint-disable directive" report, undefined
93
+ * for other messages.
94
+ *
95
+ * @param {import("eslint").Linter.LintMessage} message
96
+ * @returns {string[] | undefined}
97
+ */
98
+ export const getUnusedDisableDirectiveRuleNames = (message) => {
99
+ if (message.ruleId !== null) return undefined;
100
+ const match = unusedDisableDirectiveRegExp.exec(message.message);
101
+ if (!match) return undefined;
102
+ return [...match[1].matchAll(/'([^']+)'/g)].map(([, ruleName]) => ruleName);
103
+ };
104
+
105
+ /**
106
+ * Drops eslint's "Unused eslint-disable directive" reports for rules checked
107
+ * by oxlint, so projects keep their `eslint-disable` comments of moved rules:
108
+ * oxlint honors them, and `eslint --fix` no longer deletes them. Unused
109
+ * directives of other rules are still reported and fixed.
110
+ *
111
+ * @param {Set<string>} oxlintEslintRuleNames eslint names of the rules checked
112
+ * by oxlint
113
+ * @returns {import("eslint").Linter.Processor}
114
+ */
115
+ export const createOxlintDisableDirectivesProcessor = (
116
+ oxlintEslintRuleNames,
117
+ ) => ({
118
+ meta: { name: "@pob/eslint-config/oxlint-disable-directives" },
119
+ supportsAutofix: true,
120
+ preprocess: (text) => [text],
121
+ postprocess: (messageLists) =>
122
+ messageLists.flat().filter((message) => {
123
+ const ruleNames = getUnusedDisableDirectiveRuleNames(message);
124
+ return !ruleNames?.every((ruleName) =>
125
+ oxlintEslintRuleNames.has(ruleName),
126
+ );
127
+ }),
128
+ });
@@ -0,0 +1,187 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { Linter } from "eslint";
3
+ import { builtinRules } from "eslint/use-at-your-own-risk";
4
+ import importPlugin from "eslint-plugin-import-x";
5
+ import nodePlugin from "eslint-plugin-n";
6
+ import eslintPluginUnicorn from "eslint-plugin-unicorn";
7
+ import tseslint from "typescript-eslint";
8
+ import oxlintBaseConfig from "../../oxlint/base.json" with { type: "json" };
9
+ import oxlintTypescriptConfig from "../../oxlint/typescript.json" with { type: "json" };
10
+ import {
11
+ createOxlintDisableDirectivesProcessor,
12
+ getOxlintConfigRuleNames,
13
+ getUnusedDisableDirectiveRuleNames,
14
+ oxlintToEslintRuleNames,
15
+ } from "./oxlint.js";
16
+
17
+ /** @type {import("eslint").Linter.Config} */
18
+ const baseConfig = {
19
+ linterOptions: { reportUnusedDisableDirectives: "error" },
20
+ rules: { "no-debugger": "off", "no-unreachable": "error" },
21
+ };
22
+
23
+ describe("getUnusedDisableDirectiveRuleNames", () => {
24
+ // fails if an eslint upgrade rewords the message the processor relies on
25
+ it.each([
26
+ ["no-debugger", ["no-debugger"]],
27
+ ["no-debugger, no-console", ["no-debugger", "no-console"]],
28
+ [
29
+ "no-debugger, no-console, no-alert",
30
+ ["no-debugger", "no-console", "no-alert"],
31
+ ],
32
+ ])(
33
+ "parses eslint's report for eslint-disable-next-line %s",
34
+ (ruleNames, expected) => {
35
+ const messages = new Linter().verify(
36
+ `// eslint-disable-next-line ${ruleNames}\nexport const a = 1;\n`,
37
+ baseConfig,
38
+ );
39
+ expect(messages).toHaveLength(1);
40
+ expect(getUnusedDisableDirectiveRuleNames(messages[0])).toEqual(expected);
41
+ },
42
+ );
43
+
44
+ it("ignores other messages", () => {
45
+ const messages = new Linter().verify(
46
+ "export function f() {\n return;\n f();\n}\n",
47
+ baseConfig,
48
+ );
49
+ expect(messages.map(({ ruleId }) => ruleId)).toEqual(["no-unreachable"]);
50
+ expect(getUnusedDisableDirectiveRuleNames(messages[0])).toBeUndefined();
51
+ });
52
+ });
53
+
54
+ describe("createOxlintDisableDirectivesProcessor", () => {
55
+ /** @type {import("eslint").Linter.Config[]} */
56
+ const configs = [
57
+ baseConfig,
58
+ {
59
+ files: ["**/*.js"],
60
+ processor: createOxlintDisableDirectivesProcessor(
61
+ new Set(["no-debugger"]),
62
+ ),
63
+ },
64
+ ];
65
+ const source = [
66
+ "// eslint-disable-next-line no-debugger",
67
+ "export const a = 1;",
68
+ "// eslint-disable-next-line no-unreachable",
69
+ "export const b = 1;",
70
+ "",
71
+ ].join("\n");
72
+
73
+ it("drops unused directive reports of rules checked by oxlint only", () => {
74
+ const messages = new Linter().verify(source, configs, "file.js");
75
+ expect(
76
+ messages.map((message) => getUnusedDisableDirectiveRuleNames(message)),
77
+ ).toEqual([["no-unreachable"]]);
78
+ });
79
+
80
+ it("keeps the comments of rules checked by oxlint on --fix", () => {
81
+ const { output } = new Linter().verifyAndFix(source, configs, "file.js");
82
+ // eslint's fix leaves the indentation of the removed comment
83
+ expect(output.split("\n").map((line) => line.trim())).toEqual([
84
+ "// eslint-disable-next-line no-debugger",
85
+ "export const a = 1;",
86
+ "",
87
+ "export const b = 1;",
88
+ "",
89
+ ]);
90
+ });
91
+ });
92
+
93
+ describe("oxlintToEslintRuleNames", () => {
94
+ it.each([
95
+ ["no-debugger", ["no-debugger"]],
96
+ ["eslint/no-debugger", ["no-debugger"]],
97
+ ["typescript/no-explicit-any", ["@typescript-eslint/no-explicit-any"]],
98
+ ["unicorn/prefer-node-protocol", ["unicorn/prefer-node-protocol"]],
99
+ ["import/no-cycle", ["import-x/no-cycle"]],
100
+ ["node/no-path-concat", ["n/no-path-concat"]],
101
+ ["jsx_a11y/alt-text", ["jsx-a11y/alt-text"]],
102
+ ["react/jsx-key", ["react/jsx-key"]],
103
+ ["react/rules-of-hooks", ["react-hooks/rules-of-hooks"]],
104
+ ["react/exhaustive-deps", ["react-hooks/exhaustive-deps"]],
105
+ ["oxc/no-map-spread", []],
106
+ ["promise/valid-params", []],
107
+ ["vitest/no-focused-tests", []],
108
+ ])("maps %s", (oxlintRuleName, eslintRuleNames) => {
109
+ expect(oxlintToEslintRuleNames(oxlintRuleName)).toEqual(eslintRuleNames);
110
+ });
111
+
112
+ it.each([
113
+ ["no-unused-vars", ["no-unused-vars", "@typescript-eslint/no-unused-vars"]],
114
+ [
115
+ "eslint/no-redeclare",
116
+ ["no-redeclare", "@typescript-eslint/no-redeclare"],
117
+ ],
118
+ [
119
+ "no-useless-constructor",
120
+ ["no-useless-constructor", "@typescript-eslint/no-useless-constructor"],
121
+ ],
122
+ ])(
123
+ "maps extension rule %s to the core and typescript-eslint rules",
124
+ (oxlintRuleName, eslintRuleNames) => {
125
+ expect(oxlintToEslintRuleNames(oxlintRuleName)).toEqual(eslintRuleNames);
126
+ },
127
+ );
128
+
129
+ it.each([
130
+ ["require-await"],
131
+ ["dot-notation"],
132
+ ["no-implied-eval"],
133
+ ["no-throw-literal"],
134
+ ])("keeps type-aware extension rules of %s in eslint", (oxlintRuleName) => {
135
+ expect(oxlintToEslintRuleNames(oxlintRuleName)).toEqual([oxlintRuleName]);
136
+ });
137
+
138
+ it("throws on unknown plugins", () => {
139
+ expect(() => oxlintToEslintRuleNames("jsdoc/check-tag-names")).toThrow(
140
+ 'Unknown oxlint plugin "jsdoc" in rule "jsdoc/check-tag-names"',
141
+ );
142
+ });
143
+ });
144
+
145
+ describe("getOxlintConfigRuleNames", () => {
146
+ it("lists the rules of the config and of its overrides", () => {
147
+ expect(
148
+ getOxlintConfigRuleNames({
149
+ rules: { "no-debugger": "error" },
150
+ overrides: [
151
+ { rules: { "typescript/no-namespace": "error" } },
152
+ { rules: {} },
153
+ ],
154
+ }),
155
+ ).toEqual(["no-debugger", "typescript/no-namespace"]);
156
+ });
157
+ });
158
+
159
+ describe("oxlint/*.json", () => {
160
+ /** @type {[string, unknown][]} */
161
+ const plugins = [
162
+ ["@typescript-eslint/", tseslint.plugin],
163
+ ["unicorn/", eslintPluginUnicorn],
164
+ ["import-x/", importPlugin],
165
+ ["n/", nodePlugin],
166
+ ];
167
+ const eslintRuleNames = new Set([
168
+ ...builtinRules.keys(),
169
+ ...plugins.flatMap(([prefix, plugin]) =>
170
+ Object.keys(
171
+ /** @type {import("eslint").ESLint.Plugin} */ (plugin).rules ?? {},
172
+ ).map((ruleName) => `${prefix}${ruleName}`),
173
+ ),
174
+ ]);
175
+
176
+ it.each([
177
+ ...new Set(
178
+ [oxlintBaseConfig, oxlintTypescriptConfig].flatMap((config) =>
179
+ getOxlintConfigRuleNames(config),
180
+ ),
181
+ ),
182
+ ])("%s turns off existing eslint rules", (oxlintRuleName) => {
183
+ const mapped = oxlintToEslintRuleNames(oxlintRuleName);
184
+ expect(mapped.length).toBeGreaterThan(0);
185
+ expect(mapped.filter((name) => !eslintRuleNames.has(name))).toEqual([]);
186
+ });
187
+ });
@@ -0,0 +1,11 @@
1
+ {
2
+ "overrides": [
3
+ {
4
+ "files": ["**/*.{ts,cts,mts,tsx}"],
5
+ "rules": {
6
+ "typescript/explicit-function-return-type": "off",
7
+ "typescript/explicit-module-boundary-types": "off"
8
+ }
9
+ }
10
+ ]
11
+ }
@@ -0,0 +1,14 @@
1
+ {
2
+ "overrides": [
3
+ {
4
+ "files": ["**/*.{ts,cts,mts,tsx}"],
5
+ "rules": {
6
+ "typescript/no-unsafe-argument": "warn",
7
+ "typescript/no-unsafe-assignment": "warn",
8
+ "typescript/no-unsafe-call": "warn",
9
+ "typescript/no-unsafe-member-access": "warn",
10
+ "typescript/no-unsafe-return": "warn"
11
+ }
12
+ }
13
+ ]
14
+ }
@@ -0,0 +1,14 @@
1
+ {
2
+ "overrides": [
3
+ {
4
+ "files": ["**/*.{ts,cts,mts,tsx}"],
5
+ "rules": {
6
+ "typescript/no-unsafe-argument": "off",
7
+ "typescript/no-unsafe-assignment": "off",
8
+ "typescript/no-unsafe-call": "off",
9
+ "typescript/no-unsafe-member-access": "off",
10
+ "typescript/no-unsafe-return": "off"
11
+ }
12
+ }
13
+ ]
14
+ }
@@ -0,0 +1,11 @@
1
+ {
2
+ "overrides": [
3
+ {
4
+ "files": ["**/*.{ts,cts,mts,tsx}"],
5
+ "rules": {
6
+ "typescript/explicit-function-return-type": "off",
7
+ "typescript/explicit-module-boundary-types": "off"
8
+ }
9
+ }
10
+ ]
11
+ }
@@ -0,0 +1,68 @@
1
+ {
2
+ "categories": {
3
+ "correctness": "off"
4
+ },
5
+ "rules": {
6
+ "default-param-last": "error",
7
+ "max-params": [
8
+ "warn",
9
+ {
10
+ "max": 3
11
+ }
12
+ ],
13
+ "no-array-constructor": "error",
14
+ "no-debugger": "error",
15
+ "no-dupe-class-members": "error",
16
+ "no-empty-function": [
17
+ "error",
18
+ {
19
+ "allow": ["arrowFunctions", "functions", "methods"]
20
+ }
21
+ ],
22
+ "no-loop-func": "error",
23
+ "no-unused-expressions": [
24
+ "error",
25
+ {
26
+ "allowShortCircuit": false,
27
+ "allowTaggedTemplates": false,
28
+ "allowTernary": false,
29
+ "enforceForJSX": false,
30
+ "ignoreDirectives": false
31
+ }
32
+ ],
33
+ "no-unused-vars": [
34
+ "error",
35
+ {
36
+ "args": "none",
37
+ "caughtErrors": "none",
38
+ "ignoreClassWithStaticInitBlock": false,
39
+ "ignoreRestSiblings": true,
40
+ "ignoreUsingDeclarations": false,
41
+ "reportUsedIgnorePattern": false,
42
+ "vars": "all"
43
+ }
44
+ ],
45
+ "no-use-before-define": [
46
+ "error",
47
+ {
48
+ "allowNamedExports": false,
49
+ "classes": true,
50
+ "enums": true,
51
+ "functions": true,
52
+ "ignoreTypeReferences": true,
53
+ "typedefs": true,
54
+ "variables": true
55
+ }
56
+ ],
57
+ "no-useless-constructor": "error",
58
+ "require-await": "error"
59
+ },
60
+ "overrides": [
61
+ {
62
+ "files": ["**/*.{ts,cts,mts,tsx}"],
63
+ "rules": {
64
+ "require-await": "off"
65
+ }
66
+ }
67
+ ]
68
+ }