All files / packages/configs/src/eslint/rules lookupTableShape.ts

100% Statements 3/3
100% Branches 0/0
100% Functions 0/0
100% Lines 3/3

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34      2x   2x   2x                                                    
import { selectorRule } from "./selectorRule.ts";
 
const TOP =
    ":matches(Program, ExportNamedDeclaration) > VariableDeclaration[kind='const'] > VariableDeclarator";
 
const OPEN_KEY = "/^TS(String|Number)Keyword$/";
 
const lookupTableShape = selectorRule({
    description:
        "Require a module-scope lookup table keyed by a closed union to be `UPPER_SNAKE = { … } as const satisfies Record<K, V>`.",
    bans: {
        annotated: {
            selector: `${TOP}[id.typeAnnotation.typeAnnotation.typeName.name='Record']:not([id.typeAnnotation.typeAnnotation.typeArguments.params.0.type=${OPEN_KEY}])`,
            message:
                "Declare a lookup table as `NAME = { … } as const satisfies Record<K, V>`, not with a type annotation.",
        },
        partial: {
            selector: `${TOP}[id.typeAnnotation.typeAnnotation.typeName.name='Partial'][id.typeAnnotation.typeAnnotation.typeArguments.params.0.typeName.name='Record']:not([id.typeAnnotation.typeAnnotation.typeArguments.params.0.typeArguments.params.0.type=${OPEN_KEY}])`,
            message:
                "Spell out every key and declare it as `NAME = { … } as const satisfies Record<K, V>`; a partial table can't be indexed by `K`.",
        },
        asConst: {
            selector: `${TOP} > TSSatisfiesExpression[typeAnnotation.typeName.name='Record'][expression.type='ObjectExpression']`,
            message: "Add `as const` before `satisfies Record<K, V>`.",
        },
        name: {
            selector: `${TOP}[id.name!=/^[A-Z][A-Z0-9_]*$/][init.type='TSSatisfiesExpression'][init.typeAnnotation.typeName.name='Record']`,
            message: "Name a lookup table in UPPER_SNAKE_CASE.",
        },
    },
});
 
export default lookupTableShape;