# Rule Implementation Patterns The general anatomy of an ESLint rule in this repo. For specialized implementations, see [`rule-implementation-patterns-term-based.md`](./rule-implementation-patterns-term-based.md) (text prechecks and version gating) and [`rule-implementation-patterns-fact-based.md`](./rule-implementation-patterns-fact-based.md) (collect → resolve → infer → report pipelines). ## Directory Structure Every rule lives in its own directory under a domain plugin: ``` plugins/eslint-plugin-react-/src/rules// ├── .ts # The rule ├── .spec.ts # Tests ├── .mdx # Documentation page ├── CHANGELOG.md # Rule-specific changelog └── lib.ts # Optional helpers for complex rules ``` Complex rules keep shared helpers in `lib.ts`; fact-based rules add pattern-specific layers (`collect.ts`, `origins.ts`, ...). Some rules also carry `.spec.md` / `.spec.diff.md` snapshots or helper unit tests (`lib.test.ts`, `collect.test.ts`, ...). `scripts/90-scaffold-rule.ts` generates the `.ts`, `.spec.ts`, and `.mdx` files and registers the rule (`CHANGELOG.md` is added by hand); `scripts/20-check-rules.ts` (`node --run check:rules`) validates registration, presets, and docs badges. Cross-rule listeners and other shared rule infrastructure live in the plugin's `src/utils/` directory (ex: `create-implicit-prop-listener.ts`, `create-rule.ts`), not in a rule's `lib.ts`. Files under `src/utils/` are not rule entry points: `scripts/20-check-rules.ts` only globs `src/rules//.ts`. ## Rule File Skeleton ```ts import { createRule } from "@/utils/create-rule"; import { type RuleContext, type RuleFeature, type RuleListener } from "@eslint-react/eslint"; export const RULE_NAME = "no-forward-ref"; export const RULE_FEATURES = ["MOD"] as const satisfies RuleFeature[]; export type MessageID = "default" | "suggest"; export default createRule<[], MessageID>({ meta: { type: "suggestion", docs: { description: "Replaces usage of 'forwardRef' with passing 'ref' as a prop." }, fixable: "code", hasSuggestions: true, messages: { default: "In React 19, 'forwardRef' is no longer necessary. Pass 'ref' as a prop instead.", suggest: "Replace 'forwardRef' with passing 'ref' as a prop.", }, schema: [], }, name: RULE_NAME, create, }); export function create(context: RuleContext): RuleListener { if (!context.sourceCode.text.includes("forwardRef")) return {}; // fast path: zero AST work return { CallExpression(node) { // ...check and report }, }; } ``` Conventions: - `createRule` comes from `@/utils/create-rule` in each domain plugin — `ESLintUtils.RuleCreator` bound to `https://eslint-react.xyz/docs/rules/` (all plugins except `react-x` prefix the rule name in the URL). - `RULE_NAME`, `RULE_FEATURES`, and the `MessageID` union are top-level exports; `check:rules` imports each rule module and reads the two constants (`MessageID` is type-only). - `meta.type` is `"suggestion"` for most rules, `"problem"` when the flagged code is likely a bug. Prechecks and version gating behind the `{}` fast path are covered in the term-based doc. ## Options An `Options` tuple with an optional first element, a plain type-annotated schema (`const schema: [JSONSchema4] = [...]`) referenced from `meta.schema`, and a placeholder `meta.defaultOptions: [{}]` (satisfies `eslint-plugin/require-meta-default-options`; keeps `["error", undefined]` valid; no real defaults). At the top of `create`, read options directly and capture defaults with `??`: `const options = context.options[0] ?? {}; const allowEmptyFragment = options.allowEmptyFragment ?? false;`. No `RuleOptions` alias, spread copy, or `??=` mutation; locals keep values non-optional in visitor closures. Keep the schema initializer plain (`as const satisfies` hides it from `eslint-plugin-eslint-plugin`). Optionless rules omit the options type and `meta.defaultOptions` and use `schema: []`; any non-empty schema earns `CFG` (see [`rule-feature-system.md`](./rule-feature-system.md)). Upstream ports keeping upstream option handling (e.g. `exhaustive-deps`, `rules-of-hooks`) are exempt. ## Reporting - Most single-message rules use `messageId: "default"` (a few use a descriptive ID, e.g. `"invalid-id-name"`); multi-message rules use descriptive kebab-case IDs. Use `data` interpolation to personalize messages. - Auto-fixable rules set `meta.fixable: "code"` and pass `fix(fixer)` to `context.report` (`FIX` feature; codemod-style rules like `no-forward-ref` carry `MOD` instead); transforms needing confirmation use `meta.hasSuggestions: true` + a `suggest` array. - Report on the smallest precise node. ## Visitor Strategies Ordered roughly from cheapest to heaviest: 1. **Immediate single-node visitor** — inspect the node and report inline (`no-forward-ref`). 2. **Ancestor lookup** — `Traverse.findParent(node, Check.isFunction)` from `@eslint-react/ast` (`no-unstable-default-props`). 3. **Collector + `Program:exit`** — a collector from `@eslint-react/core`, composed with `merge` from `@eslint-react/eslint`, correlated in `Program:exit`: ```ts const { api, visitor } = core.getFunctionComponentCollector(context); return merge(visitor, { "Program:exit"(program) { for (const { node: component } of api.getAllComponents(program)) { /* ...validate and report */ } }, }); ``` 4. **Code-path analysis** — ESLint's CFG events (`onCodePathStart`, ...) for control flow (`rules-of-hooks`). 5. **Import-tracking** — `createImportLookup` from `@eslint-react/var` matches `hydrate(...)` and `ReactDOM.hydrate(...)` alike. 6. **Type-aware** — `ESLintUtils.getParserServices` (`TSC` feature, disabled by the `disable-type-checked` preset). When evidence must be correlated across distant sites (provenance, multi-site reports), escalate to the fact-based pipeline in [`rule-implementation-patterns-fact-based.md`](./rule-implementation-patterns-fact-based.md). ## Tests Specs sit next to the rule as `.spec.ts` and use the shared tester from `@local/testkit`: ```ts import { ruleTester } from "@local/testkit"; import tsx from "dedent"; // template tag; valid cases may be bare dedent strings import rule, { RULE_NAME } from "./no-forward-ref"; ruleTester.run(RULE_NAME, rule, { invalid: [ { code: tsx`import { forwardRef } from 'react' ...`, errors: [{ messageId: "default", suggestions: [{ messageId: "suggest", output: tsx`...` }] }], settings: { "react-x": { version: "19.0.0" } }, // React settings (version, importSource, ...) per case }, ], valid: [tsx`...`], }); ``` Type-aware rules use `ruleTesterWithTypes`. Rules sensitive to the JSX runtime or `jsxImportSource` use `createRuleTesterForTsconfig(name)`, where `name` is a key of the `tsconfigFixtures` registry in `@local/testkit` (`"react-jsx"`, `"react-classic"`, `"react-native"`, `"preserve"`, `"preact"`); each key maps to a tsconfig fixture under `testing/samples`. Anything not covered by the presets can be built with `createRuleTester(options)`. ## Registration Each domain plugin hand-maintains a rules record in `src/plugin.ts`. The meta package `plugins/eslint-plugin/src/plugin.ts` composes the domain plugins (`react-debug` excluded), prefixing rule names (`jsx-`, `dom-`, ...) via `padKeysLeft` — `react-x` rules are registered both unprefixed and with the `x-` prefix. Presets live in `plugins/eslint-plugin/src/configs/` as (mostly static) `Linter.RulesRecord`s; `check:rules` verifies that every registered rule is accounted for and that preset hierarchies hold. ## Documentation Files - `.mdx` — frontmatter (`title`, `description`), full rule name, `Features` badges matching `RULE_FEATURES` (validated by `check:rules`), `Presets` list, `Rule Details`, `Examples` with `🔴 Problem` / `🟢 Recommended` blocks (optionally `🔵 OK`), and a `Resources` section. - `CHANGELOG.md` — Keep-a-Changelog format scoped to the rule; new rules end with an "Initial release of the `` rule" entry.