|
1 | | -import { ESLintUtils } from '@typescript-eslint/utils' |
| 1 | +import type { ESLintUtils, TSESLint } from '@typescript-eslint/utils' |
2 | 2 |
|
| 3 | +import { applyDefault } from './apply-default.js' |
3 | 4 | import { docsUrl } from './docs-url.js' |
4 | 5 |
|
| 6 | +/** |
| 7 | + * Creates reusable function to create rules with default options and docs URLs. |
| 8 | + * |
| 9 | + * @param urlCreator Creates a documentation URL for a given rule name. |
| 10 | + * @returns Function to create a rule with the docs URL format. |
| 11 | + */ |
| 12 | +export function RuleCreator<PluginDocs = unknown>( |
| 13 | + urlCreator: (ruleName: string) => string, |
| 14 | +) { |
| 15 | + // This function will get much easier to call when this is merged https://github.com/Microsoft/TypeScript/pull/26349 |
| 16 | + // TODO - when the above PR lands; add type checking for the context.report `data` property |
| 17 | + return function createNamedRule< |
| 18 | + Options extends readonly unknown[], |
| 19 | + MessageIds extends string, |
| 20 | + >({ |
| 21 | + meta, |
| 22 | + name, |
| 23 | + ...rule |
| 24 | + }: Readonly< |
| 25 | + ESLintUtils.RuleWithMetaAndName<Options, MessageIds, PluginDocs> |
| 26 | + >): TSESLint.RuleModule<MessageIds, Options, PluginDocs> { |
| 27 | + return createRule_<Options, MessageIds, PluginDocs>({ |
| 28 | + meta: { |
| 29 | + ...meta, |
| 30 | + docs: { |
| 31 | + ...meta.docs, |
| 32 | + url: urlCreator(name), |
| 33 | + }, |
| 34 | + }, |
| 35 | + ...rule, |
| 36 | + }) |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +function createRule_< |
| 41 | + Options extends readonly unknown[], |
| 42 | + MessageIds extends string, |
| 43 | + PluginDocs = unknown, |
| 44 | +>({ |
| 45 | + create, |
| 46 | + defaultOptions, |
| 47 | + meta, |
| 48 | +}: Readonly< |
| 49 | + ESLintUtils.RuleWithMeta<Options, MessageIds, PluginDocs> |
| 50 | +>): TSESLint.RuleModule<MessageIds, Options, PluginDocs> { |
| 51 | + return { |
| 52 | + create( |
| 53 | + context: Readonly<TSESLint.RuleContext<MessageIds, Options>>, |
| 54 | + ): TSESLint.RuleListener { |
| 55 | + const optionsWithDefault = applyDefault(defaultOptions, context.options) |
| 56 | + return create(context, optionsWithDefault) |
| 57 | + }, |
| 58 | + defaultOptions, |
| 59 | + meta, |
| 60 | + } |
| 61 | +} |
| 62 | + |
5 | 63 | export interface ImportXPluginDocs { |
6 | 64 | /** The category the rule falls under */ |
7 | 65 | category?: string |
8 | 66 |
|
9 | 67 | recommended?: true |
10 | 68 | } |
11 | 69 |
|
12 | | -export const createRule = ESLintUtils.RuleCreator<ImportXPluginDocs>(docsUrl) |
| 70 | +export const createRule = RuleCreator<ImportXPluginDocs>(docsUrl) |
0 commit comments