|
| 1 | +/** |
| 2 | + * Generates the `oxlint-plugin-eslint` package source files. |
| 3 | + * |
| 4 | + * This script produces: |
| 5 | + * |
| 6 | + * 1. `rules/<name>.cjs` - One file for each ESLint core rule, that re-exports the rule's `create` function. |
| 7 | + * 2. `index.ts` - Exports all rules as a `Record<string, CreateRule>`. |
| 8 | + * This is the `rules` property of the `oxlint-plugin-eslint` plugin. |
| 9 | + * 3. `rule_names.ts` - Exports a list of all rule names, which is used in TSDown config. |
| 10 | + * |
| 11 | + * `index.ts` uses a split eager/lazy strategy so that `registerPlugin` can read each rule's `meta` |
| 12 | + * without loading the rule module itself: |
| 13 | + * |
| 14 | + * - `meta` is serialized and inlined at build time. |
| 15 | + * `registerPlugin` needs it at plugin registration time (for `fixable`, `hasSuggestions`, `schema`, |
| 16 | + * `defaultOptions`, `messages`), so it must be available immediately without requiring the rule module. |
| 17 | + * |
| 18 | + * - `create` is deferred via a cached `require` call. |
| 19 | + * The rule module is only loaded the first time `create` is called (i.e. when the rule actually runs at lint time). |
| 20 | + * A top-level variable per rule caches the loaded function so subsequent calls skip the `require` call. |
| 21 | + * |
| 22 | + * Build-time validations: |
| 23 | + * - Each rule object must only have `meta` and `create` properties. |
| 24 | + * - `meta` values are walked to ensure they contain no functions |
| 25 | + * (which would be serialized as executable code by `serialize-javascript`). |
| 26 | + */ |
| 27 | + |
| 28 | +import { readdirSync, mkdirSync, writeFileSync, rmSync } from "node:fs"; |
| 29 | +import { join as pathJoin, basename, relative as pathRelative } from "node:path"; |
| 30 | +import { createRequire } from "node:module"; |
| 31 | +import { execFileSync } from "node:child_process"; |
| 32 | +import serialize from "serialize-javascript"; |
| 33 | + |
| 34 | +import type { CreateRule } from "../src-js/plugins/load.ts"; |
| 35 | +import type { RuleMeta } from "../src-js/plugins/rule_meta.ts"; |
| 36 | + |
| 37 | +const require = createRequire(import.meta.url); |
| 38 | + |
| 39 | +const oxlintDirPath = pathJoin(import.meta.dirname, ".."); |
| 40 | +const rootDirPath = pathJoin(oxlintDirPath, "../.."); |
| 41 | +const eslintRulesDir = pathJoin(require.resolve("eslint/package.json"), "../lib/rules"); |
| 42 | +const generatedDirPath = pathJoin(oxlintDirPath, "src-js/generated/plugin-eslint"); |
| 43 | +const generatedRulesDirPath = pathJoin(generatedDirPath, "rules"); |
| 44 | + |
| 45 | +export default function generatePluginEslint(): void { |
| 46 | + // Get all ESLint rule names (exclude `index.js` which is the registry, not a rule) |
| 47 | + const ruleNames = readdirSync(eslintRulesDir) |
| 48 | + .filter((filename) => filename.endsWith(".js") && filename !== "index.js") |
| 49 | + .map((filename) => basename(filename, ".js")) |
| 50 | + .sort(); |
| 51 | + |
| 52 | + // oxlint-disable-next-line no-console |
| 53 | + console.log(`Found ${ruleNames.length} ESLint rules`); |
| 54 | + |
| 55 | + // Wipe and recreate generated directories |
| 56 | + rmSync(generatedDirPath, { recursive: true, force: true }); |
| 57 | + mkdirSync(generatedRulesDirPath, { recursive: true }); |
| 58 | + |
| 59 | + // Generate a CJS wrapper file for each rule |
| 60 | + for (const ruleName of ruleNames) { |
| 61 | + const relPath = pathRelative(generatedRulesDirPath, pathJoin(eslintRulesDir, `${ruleName}.js`)); |
| 62 | + const content = `module.exports = require(${JSON.stringify(relPath)}).create;\n`; |
| 63 | + writeFileSync(pathJoin(generatedRulesDirPath, `${ruleName}.cjs`), content); |
| 64 | + } |
| 65 | + |
| 66 | + // Generate the plugin rules index. |
| 67 | + // `meta` is inlined so it's available at registration time without loading the rule module. |
| 68 | + // `create` is deferred via a cached `require` so the rule module is only loaded on first use. |
| 69 | + const indexLines = [ |
| 70 | + ` |
| 71 | + import { createRequire } from "node:module"; |
| 72 | +
|
| 73 | + import type { CreateRule } from "../../plugins/load.ts"; |
| 74 | +
|
| 75 | + type CreateFn = CreateRule["create"]; |
| 76 | +
|
| 77 | + var require = createRequire(import.meta.url); |
| 78 | + `, |
| 79 | + ]; |
| 80 | + |
| 81 | + // Generate a `let` declaration for each rule's cached `create` function. |
| 82 | + // These are initially `null` and populated on first call. |
| 83 | + for (let i = 0; i < ruleNames.length; i++) { |
| 84 | + indexLines.push(`var create${i}: CreateFn | null = null;`); |
| 85 | + } |
| 86 | + |
| 87 | + indexLines.push("", "export default {"); |
| 88 | + |
| 89 | + for (let i = 0; i < ruleNames.length; i++) { |
| 90 | + const ruleName = ruleNames[i]; |
| 91 | + const rulePath = pathJoin(eslintRulesDir, `${ruleName}.js`); |
| 92 | + const rule: CreateRule = require(rulePath); |
| 93 | + |
| 94 | + // Validate that the rule only has expected top-level properties. |
| 95 | + // If ESLint adds new properties in a future version, we want to find out at build time. |
| 96 | + const unexpectedKeys = Object.keys(rule).filter((key) => key !== "meta" && key !== "create"); |
| 97 | + if (unexpectedKeys.length > 0) { |
| 98 | + throw new Error( |
| 99 | + `Unexpected properties on rule \`${ruleName}\`: ${unexpectedKeys.join(", ")}. ` + |
| 100 | + "Expected only `meta` and `create`.", |
| 101 | + ); |
| 102 | + } |
| 103 | + |
| 104 | + // Reduce `meta` to only the properties Oxlint uses, with consistent shape and property order. |
| 105 | + // We discard e.g. `deprecated` and `docs` properties. This reduces code size. |
| 106 | + // Default values match what `registerPlugin` assumes when a property is absent. |
| 107 | + const { meta } = rule; |
| 108 | + const reducedMeta: RuleMeta = { |
| 109 | + messages: meta?.messages ?? undefined, |
| 110 | + fixable: meta?.fixable ?? null, |
| 111 | + hasSuggestions: meta?.hasSuggestions ?? false, |
| 112 | + schema: meta?.schema ?? undefined, |
| 113 | + defaultOptions: meta?.defaultOptions ?? undefined, |
| 114 | + }; |
| 115 | + |
| 116 | + // Check for function values in `reducedMeta`, which would be unexpected and likely a bug. |
| 117 | + // `serialize-javascript` would serialize them as executable code, so catch this at build time. |
| 118 | + assertNoFunctions(reducedMeta, `eslint/lib/rules/${ruleName}.js`, "meta"); |
| 119 | + |
| 120 | + const metaCode = serialize(reducedMeta, { unsafe: true }); |
| 121 | + |
| 122 | + indexLines.push(` |
| 123 | + ${JSON.stringify(ruleName)}: { |
| 124 | + meta: ${metaCode}, |
| 125 | + create(context) { |
| 126 | + if (create${i} === null) create${i} = require("./rules/${ruleName}.cjs") as CreateFn; |
| 127 | + return create${i}(context); |
| 128 | + }, |
| 129 | + }, |
| 130 | + `); |
| 131 | + } |
| 132 | + indexLines.push("} satisfies Record<string, CreateRule>;\n"); |
| 133 | + |
| 134 | + const indexFilePath = pathJoin(generatedDirPath, "index.ts"); |
| 135 | + writeFileSync(indexFilePath, indexLines.join("\n")); |
| 136 | + |
| 137 | + // Format generated index file with oxfmt to clean up unnecessary quotes around property names. |
| 138 | + // This isn't necessary, as it gets minified and bundled anyway, but it makes generated code easier to read |
| 139 | + // when debugging. |
| 140 | + execFileSync("pnpm", ["exec", "oxfmt", "--write", indexFilePath], { cwd: rootDirPath }); |
| 141 | + |
| 142 | + // Generate the rule_names.ts file for use in tsdown config |
| 143 | + const ruleNamesCode = [ |
| 144 | + "export default [", |
| 145 | + ...ruleNames.map((name) => ` ${JSON.stringify(name)},`), |
| 146 | + "] as const;\n", |
| 147 | + ].join("\n"); |
| 148 | + |
| 149 | + writeFileSync(pathJoin(generatedDirPath, "rule_names.ts"), ruleNamesCode); |
| 150 | + |
| 151 | + // oxlint-disable-next-line no-console |
| 152 | + console.log("Generated plugin-eslint files."); |
| 153 | +} |
| 154 | + |
| 155 | +/** |
| 156 | + * Walk an object tree and throw if any function values are found. |
| 157 | + */ |
| 158 | +function assertNoFunctions(value: unknown, rulePath: string, path: string): void { |
| 159 | + if (typeof value === "function") { |
| 160 | + throw new Error( |
| 161 | + `Unexpected function value in \`${path}\` of rule \`${rulePath}\`. ` + |
| 162 | + "Rule meta objects must be static data.", |
| 163 | + ); |
| 164 | + } |
| 165 | + if (typeof value === "object" && value !== null) { |
| 166 | + for (const [key, child] of Object.entries(value)) { |
| 167 | + assertNoFunctions(child, rulePath, `${path}.${key}`); |
| 168 | + } |
| 169 | + } |
| 170 | +} |
0 commit comments