eslint-typegen
Version:
Generate types from ESLint rule schemas automatically, with auto-completion and type-checking for rule options.
56 lines (52 loc) • 1.83 kB
JavaScript
import { existsSync } from 'node:fs';
import fs from 'node:fs/promises';
import { hash } from 'ohash';
import { flatConfigsToPlugins, pluginsToRulesDTS } from './core.mjs';
import 'json-schema-to-typescript-lite';
const version = "2.0.0";
async function typegen(configs, options = {}) {
const {
includeCoreRules = true,
dtsPath = "eslint-typegen.d.ts"
} = options;
const resolved = await configs;
let configsInput = resolved;
if (includeCoreRules) {
const { builtinRules } = await import('eslint/use-at-your-own-risk');
configsInput = [
{
plugins: {
"": { rules: Object.fromEntries(builtinRules.entries()) }
}
},
...configsInput
];
}
const plugins = await flatConfigsToPlugins(configsInput, options);
const configNames = configsInput.flatMap((c) => c.name).filter(Boolean);
const hashSource = [
// version of eslint-typegen
version,
// plugins name and version
...Object.entries(plugins).map(([n, p]) => [p.meta?.name, p.meta?.version].filter(Boolean).join("@") || p.name || n).sort(),
// config names
...configNames
].join(" ");
const hash$1 = hash(hashSource);
const previousHash = existsSync(dtsPath) ? (await fs.readFile(dtsPath, "utf-8")).match(/\/\* eslint-typegen-hash: (\S*) \*\//)?.[1]?.trim() : undefined;
if (previousHash !== hash$1) {
const dts = [
"/* This file is generated by eslint-typegen, for augmenting rules types in ESLint */",
"/* You might want to include this file in tsconfig.json but excluded from git */",
`/* eslint-typegen-hash: ${hash$1} */`,
"",
await pluginsToRulesDTS(plugins, {
...options,
configNames
})
].join("\n");
fs.writeFile(dtsPath, dts, "utf-8");
}
return resolved;
}
export { typegen as default };