@virmator/lint 14.26.1 → 14.27.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/configs/eslint.config.base.ts +36 -0
  2. package/dist/rules/error-name-as-class-field.lint.d.ts +3 -0
  3. package/dist/rules/error-name-as-class-field.lint.js +165 -0
  4. package/dist/rules/no-raw-date.lint.d.ts +3 -0
  5. package/dist/rules/no-raw-date.lint.js +42 -0
  6. package/dist/rules/no-readonly-primitive.lint.d.ts +3 -0
  7. package/dist/rules/no-readonly-primitive.lint.js +68 -0
  8. package/dist/rules/no-relative-import-outside-package.lint.js +5 -2
  9. package/dist/rules/no-should-in-test-description.lint.d.ts +3 -0
  10. package/dist/rules/no-should-in-test-description.lint.js +84 -0
  11. package/dist/rules/no-underscore-variable.lint.d.ts +3 -0
  12. package/dist/rules/no-underscore-variable.lint.js +60 -0
  13. package/dist/rules/prefer-arrow-object-block-body.lint.d.ts +3 -0
  14. package/dist/rules/prefer-arrow-object-block-body.lint.js +51 -0
  15. package/dist/rules/prefer-ensure-error.lint.d.ts +3 -0
  16. package/dist/rules/prefer-ensure-error.lint.js +74 -0
  17. package/dist/rules/prefer-if-else-chain.lint.js +5 -0
  18. package/dist/rules/prefer-map-enum-to-object.lint.d.ts +3 -0
  19. package/dist/rules/prefer-map-enum-to-object.lint.js +68 -0
  20. package/dist/rules/prefer-params-object.lint.d.ts +3 -0
  21. package/dist/rules/prefer-params-object.lint.js +117 -0
  22. package/dist/rules/prefer-protected-over-private.lint.d.ts +3 -0
  23. package/dist/rules/prefer-protected-over-private.lint.js +53 -0
  24. package/dist/rules/prefer-remove-duplicates.lint.d.ts +3 -0
  25. package/dist/rules/prefer-remove-duplicates.lint.js +142 -0
  26. package/dist/rules/prefer-to-sorted.lint.d.ts +3 -0
  27. package/dist/rules/prefer-to-sorted.lint.js +58 -0
  28. package/package.json +2 -2
  29. package/src/rules/error-name-as-class-field.lint.ts +211 -0
  30. package/src/rules/no-raw-date.lint.ts +52 -0
  31. package/src/rules/no-readonly-primitive.lint.ts +85 -0
  32. package/src/rules/no-relative-import-outside-package.lint.ts +7 -2
  33. package/src/rules/no-should-in-test-description.lint.ts +106 -0
  34. package/src/rules/no-underscore-variable.lint.ts +73 -0
  35. package/src/rules/prefer-arrow-object-block-body.lint.ts +66 -0
  36. package/src/rules/prefer-ensure-error.lint.ts +91 -0
  37. package/src/rules/prefer-if-else-chain.lint.ts +5 -0
  38. package/src/rules/prefer-map-enum-to-object.lint.ts +86 -0
  39. package/src/rules/prefer-params-object.lint.ts +190 -0
  40. package/src/rules/prefer-protected-over-private.lint.ts +71 -0
  41. package/src/rules/prefer-remove-duplicates.lint.ts +225 -0
  42. package/src/rules/prefer-to-sorted.lint.ts +79 -0
@@ -0,0 +1,211 @@
1
+ import {type Rule} from 'eslint';
2
+ import type {AssignmentExpression, Class, Node} from 'estree';
3
+
4
+ const functionNodeTypes = [
5
+ 'FunctionExpression',
6
+ 'FunctionDeclaration',
7
+ 'ArrowFunctionExpression',
8
+ ];
9
+
10
+ /**
11
+ * Determine whether a class extends an `Error`-like superclass: an `Identifier` whose name ends in
12
+ * `Error` (e.g. `Error`, `MyCustomError`).
13
+ */
14
+ function extendsErrorLike(node: Readonly<Class>) {
15
+ return (
16
+ !!node.superClass &&
17
+ node.superClass.type === 'Identifier' &&
18
+ node.superClass.name.endsWith('Error')
19
+ );
20
+ }
21
+
22
+ function isClassNode(node: Readonly<Node>): node is Class {
23
+ return node.type === 'ClassDeclaration' || node.type === 'ClassExpression';
24
+ }
25
+
26
+ /** Determine whether an assignment target is the `this.name` member expression. */
27
+ function isThisNameMember(node: AssignmentExpression['left']) {
28
+ return (
29
+ node.type === 'MemberExpression' &&
30
+ node.object.type === 'ThisExpression' &&
31
+ !node.computed &&
32
+ node.property.type === 'Identifier' &&
33
+ node.property.name === 'name'
34
+ );
35
+ }
36
+
37
+ /** Determine whether a class already declares a (non-computed) `name` member. */
38
+ function hasNameMember(node: Readonly<Class>) {
39
+ return node.body.body.some(
40
+ (member) =>
41
+ (member.type === 'PropertyDefinition' || member.type === 'MethodDefinition') &&
42
+ !member.computed &&
43
+ member.key.type === 'Identifier' &&
44
+ member.key.name === 'name',
45
+ );
46
+ }
47
+
48
+ const rule: Rule.RuleModule = {
49
+ meta: {
50
+ type: 'suggestion',
51
+ fixable: 'code',
52
+ messages: {
53
+ errorNameAsClassField:
54
+ 'Override `name` as a class field (`public override readonly name = ...`) instead of assigning `this.name` in the constructor.',
55
+ missingErrorNameField:
56
+ 'Declare `name` as a class field (`public override readonly name = ...`) on every `Error` subclass so instances are identifiable in logs.',
57
+ },
58
+ schema: [],
59
+ },
60
+ create(context) {
61
+ /**
62
+ * Classes whose own instance has `this.name` assigned somewhere in their body (constructor,
63
+ * method, or nested arrow). The missing-`name` check skips these: such a class manages
64
+ * `name` imperatively, so inserting a `readonly` field could conflict (an arrow's `this` is
65
+ * the instance, so its `this.name = ...` would write to the new `readonly` field). Only the
66
+ * _nearest_ enclosing class is recorded: a `this.name` inside a nested class targets that
67
+ * inner instance, not the outer one, so it must not suppress the outer class's report.
68
+ */
69
+ const classesAssigningThisName = new Set<Node>();
70
+
71
+ function checkMissingNameField(node: Class & Rule.NodeParentExtension) {
72
+ if (
73
+ !extendsErrorLike(node) ||
74
+ hasNameMember(node) ||
75
+ classesAssigningThisName.has(node)
76
+ ) {
77
+ return;
78
+ }
79
+
80
+ const className = node.id?.name;
81
+ context.report({
82
+ node: node.id ?? node,
83
+ messageId: 'missingErrorNameField',
84
+ /**
85
+ * Only autofix when the class name is derivable (named declarations and named class
86
+ * expressions). Anonymous class expressions are reported without a fix.
87
+ */
88
+ fix: className
89
+ ? (fixer) => {
90
+ const openBrace = context.sourceCode.getFirstToken(node.body);
91
+ if (!openBrace) {
92
+ return null;
93
+ }
94
+ return fixer.insertTextAfter(
95
+ openBrace,
96
+ `\n public override readonly name = '${className}';`,
97
+ );
98
+ }
99
+ : undefined,
100
+ });
101
+ }
102
+
103
+ return {
104
+ AssignmentExpression(node: AssignmentExpression & Rule.NodeParentExtension) {
105
+ if (!isThisNameMember(node.left)) {
106
+ return;
107
+ }
108
+
109
+ const ancestors = context.sourceCode.getAncestors(node);
110
+ const nearestEnclosingClass = ancestors.findLast(isClassNode);
111
+ if (nearestEnclosingClass) {
112
+ classesAssigningThisName.add(nearestEnclosingClass);
113
+ }
114
+
115
+ /**
116
+ * Gate the report on the assignment's _closest enclosing function_: it must be the
117
+ * class constructor itself. Tracking only a constructor-depth flag would wrongly
118
+ * flag `this.name` assignments inside nested functions/methods declared within the
119
+ * constructor body (e.g. a nested `class Inner { method() { this.name = 'x'; }
120
+ * }`).
121
+ */
122
+ const enclosingFunctionIndex = ancestors.findLastIndex((ancestor) =>
123
+ functionNodeTypes.includes(ancestor.type),
124
+ );
125
+ if (enclosingFunctionIndex < 0) {
126
+ return;
127
+ }
128
+
129
+ const methodDefinition = ancestors[enclosingFunctionIndex - 1];
130
+ if (
131
+ methodDefinition?.type !== 'MethodDefinition' ||
132
+ methodDefinition.kind !== 'constructor'
133
+ ) {
134
+ return;
135
+ }
136
+
137
+ const classBody = ancestors[enclosingFunctionIndex - 2];
138
+ const classNode = ancestors[enclosingFunctionIndex - 3];
139
+ if (
140
+ !classBody ||
141
+ !classNode ||
142
+ !isClassNode(classNode) ||
143
+ !extendsErrorLike(classNode)
144
+ ) {
145
+ return;
146
+ }
147
+
148
+ const enclosingFunction = ancestors[enclosingFunctionIndex];
149
+ const statement = node.parent;
150
+ /**
151
+ * Only offer an autofix when the conversion is provably safe: the assignment is a
152
+ * standalone top-level statement of the constructor body (not nested in a
153
+ * conditional/loop, so no control flow is lost), its value is a literal (so the
154
+ * field initializer cannot capture a constructor parameter or local, which run
155
+ * after field initialization), and the class does not already declare a `name`
156
+ * member (otherwise inserting a field would duplicate it). Anything else is
157
+ * reported without a fix.
158
+ */
159
+ const canAutofix =
160
+ statement.type === 'ExpressionStatement' &&
161
+ statement.parent.type === 'BlockStatement' &&
162
+ statement.parent.parent === enclosingFunction &&
163
+ node.right.type === 'Literal' &&
164
+ !hasNameMember(classNode);
165
+
166
+ context.report({
167
+ node,
168
+ messageId: 'errorNameAsClassField',
169
+ fix: canAutofix
170
+ ? (fixer) => {
171
+ const openBrace = context.sourceCode.getFirstToken(classBody);
172
+ const tokenBeforeStatement =
173
+ context.sourceCode.getTokenBefore(statement);
174
+ const statementRange = statement.range;
175
+ /**
176
+ * Bail out (report without fixing) when required tokens are missing,
177
+ * or when a comment sits between the previous token and the
178
+ * assignment: such a comment falls inside the removal range and would
179
+ * be silently deleted (e.g. `super(); // keep`).
180
+ */
181
+ if (
182
+ !openBrace ||
183
+ !tokenBeforeStatement ||
184
+ !statementRange ||
185
+ context.sourceCode.getCommentsBefore(statement).length > 0
186
+ ) {
187
+ return null;
188
+ }
189
+ const valueText = context.sourceCode.getText(node.right);
190
+ return [
191
+ fixer.insertTextAfter(
192
+ openBrace,
193
+ `\n public override readonly name = ${valueText};`,
194
+ ),
195
+ fixer.removeRange([
196
+ tokenBeforeStatement.range[1],
197
+ statementRange[1],
198
+ ]),
199
+ ];
200
+ }
201
+ : undefined,
202
+ });
203
+ },
204
+
205
+ 'ClassDeclaration:exit': checkMissingNameField,
206
+ 'ClassExpression:exit': checkMissingNameField,
207
+ };
208
+ },
209
+ };
210
+
211
+ export default rule;
@@ -0,0 +1,52 @@
1
+ import {type Rule} from 'eslint';
2
+ import type {NewExpression} from 'estree';
3
+
4
+ const rule: Rule.RuleModule = {
5
+ meta: {
6
+ type: 'problem',
7
+ messages: {
8
+ rawDate:
9
+ 'Do not use `new Date`. Use date-vir utilities (e.g. `createFullDate`, `getNowInUtcTimezone`, `createUtcFullDate`) instead.',
10
+ },
11
+ schema: [],
12
+ },
13
+ create(context) {
14
+ return {
15
+ NewExpression(node: NewExpression & Rule.NodeParentExtension) {
16
+ const callee = node.callee;
17
+ /**
18
+ * Catch `new Date()` and the global-namespace forms `new globalThis.Date()` and
19
+ * `new globalThis['Date']()`, since all construct the built-in Date. A `new
20
+ * namespace.Date()` on some other object is left alone: that is a different,
21
+ * user-defined constructor. Dynamic access through a variable (e.g. `new
22
+ * globalThis[propertyName]()`) is not statically determinable and is intentionally
23
+ * not flagged.
24
+ */
25
+ const isGlobalThisDate =
26
+ callee.type === 'MemberExpression' &&
27
+ callee.object.type === 'Identifier' &&
28
+ callee.object.name === 'globalThis' &&
29
+ ((!callee.computed &&
30
+ callee.property.type === 'Identifier' &&
31
+ callee.property.name === 'Date') ||
32
+ (callee.computed &&
33
+ callee.property.type === 'Literal' &&
34
+ callee.property.value === 'Date'));
35
+
36
+ const constructsRawDate =
37
+ (callee.type === 'Identifier' && callee.name === 'Date') || isGlobalThisDate;
38
+
39
+ if (!constructsRawDate) {
40
+ return;
41
+ }
42
+
43
+ context.report({
44
+ node,
45
+ messageId: 'rawDate',
46
+ });
47
+ },
48
+ };
49
+ },
50
+ };
51
+
52
+ export default rule;
@@ -0,0 +1,85 @@
1
+ import {type Rule} from 'eslint';
2
+
3
+ /**
4
+ * Primitive keyword type node names (plus `TSLiteralType` for literal types like `'a'` or `42`)
5
+ * that have no meaningful `Readonly<>` wrapping.
6
+ */
7
+ const primitiveTypeNodeTypes = [
8
+ 'TSStringKeyword',
9
+ 'TSNumberKeyword',
10
+ 'TSBooleanKeyword',
11
+ 'TSBigIntKeyword',
12
+ 'TSSymbolKeyword',
13
+ 'TSNullKeyword',
14
+ 'TSUndefinedKeyword',
15
+ 'TSLiteralType',
16
+ ];
17
+
18
+ const rule: Rule.RuleModule = {
19
+ meta: {
20
+ type: 'suggestion',
21
+ fixable: 'code',
22
+ messages: {
23
+ noReadonlyPrimitive:
24
+ 'Do not wrap a primitive type in `Readonly<>` - it has no effect. Use the bare primitive type.',
25
+ },
26
+ schema: [],
27
+ },
28
+ create(context) {
29
+ return {
30
+ TSTypeReference(node: Rule.Node) {
31
+ const tsNode = node as unknown as {
32
+ typeName: {type: string; name?: string};
33
+ typeArguments?: {params: Rule.Node[]};
34
+ typeParameters?: {params: Rule.Node[]};
35
+ };
36
+
37
+ if (tsNode.typeName.type !== 'Identifier' || tsNode.typeName.name !== 'Readonly') {
38
+ return;
39
+ }
40
+
41
+ /**
42
+ * `@typescript-eslint/parser` exposes a type reference's type arguments as
43
+ * `typeArguments` on current versions but historically used `typeParameters`; read
44
+ * both so the rule is resilient across parser versions (matching
45
+ * `no-readonly-inputs`).
46
+ */
47
+ const typeArguments = tsNode.typeArguments || tsNode.typeParameters;
48
+ if (!typeArguments || typeArguments.params.length !== 1) {
49
+ return;
50
+ }
51
+
52
+ const innerType = typeArguments.params[0];
53
+ if (!innerType) {
54
+ return;
55
+ }
56
+
57
+ /**
58
+ * Unwrap `TSParenthesizedType` if present so `Readonly<(string)>` is flagged and
59
+ * fixed to the bare `string` (matching `prefer-array-element-type`).
60
+ */
61
+ const innerTypeRecord = innerType as unknown as Record<string, unknown>;
62
+ const unwrappedInnerType =
63
+ innerTypeRecord.type === 'TSParenthesizedType' && innerTypeRecord.typeAnnotation
64
+ ? (innerTypeRecord.typeAnnotation as Rule.Node)
65
+ : innerType;
66
+
67
+ if (!primitiveTypeNodeTypes.includes(unwrappedInnerType.type)) {
68
+ return;
69
+ }
70
+
71
+ const innerTypeText = context.sourceCode.getText(unwrappedInnerType);
72
+
73
+ context.report({
74
+ node,
75
+ messageId: 'noReadonlyPrimitive',
76
+ fix(fixer) {
77
+ return fixer.replaceText(node, innerTypeText);
78
+ },
79
+ });
80
+ },
81
+ };
82
+ },
83
+ };
84
+
85
+ export default rule;
@@ -45,7 +45,7 @@ function isRelativeImport(specifier: string): boolean {
45
45
  );
46
46
  }
47
47
 
48
- function isWithinDir(target: string, baseDir: string): boolean {
48
+ function isWithinDir({target, baseDir}: Readonly<{target: string; baseDir: string}>): boolean {
49
49
  if (target === baseDir) {
50
50
  return true;
51
51
  }
@@ -74,7 +74,12 @@ function checkImport(
74
74
  }
75
75
 
76
76
  const resolvedImport = resolve(fileDir, importPath);
77
- if (isWithinDir(resolvedImport, packageInfo.dir)) {
77
+ if (
78
+ isWithinDir({
79
+ target: resolvedImport,
80
+ baseDir: packageInfo.dir,
81
+ })
82
+ ) {
78
83
  return;
79
84
  }
80
85
 
@@ -0,0 +1,106 @@
1
+ import {type Rule} from 'eslint';
2
+ import type {CallExpression, Node, Property} from 'estree';
3
+
4
+ const testFunctionNames = [
5
+ 'it',
6
+ 'test',
7
+ 'describe',
8
+ ];
9
+
10
+ /**
11
+ * Extracts the base identifier name of a test call's callee, supporting both bare identifiers
12
+ * (`it`) and member expressions (`it.only`, `test.skip`).
13
+ */
14
+ function getCalleeBaseName(callee: CallExpression['callee']): string | undefined {
15
+ if (callee.type === 'Identifier') {
16
+ return callee.name;
17
+ } else if (callee.type === 'MemberExpression' && callee.object.type === 'Identifier') {
18
+ return callee.object.name;
19
+ }
20
+
21
+ return undefined;
22
+ }
23
+
24
+ /**
25
+ * Reads a statically-known string from a node, supporting both string literals and template
26
+ * literals with no interpolations. Returns `undefined` for anything dynamic.
27
+ */
28
+ function getStaticStringValue(node: Node | undefined): string | undefined {
29
+ if (node?.type === 'Literal' && typeof node.value === 'string') {
30
+ return node.value;
31
+ } else if (
32
+ node?.type === 'TemplateLiteral' &&
33
+ node.expressions.length === 0 &&
34
+ node.quasis[0]
35
+ ) {
36
+ return node.quasis[0].value.cooked ?? undefined;
37
+ }
38
+ return undefined;
39
+ }
40
+
41
+ function startsWithShould(value: string | undefined): boolean {
42
+ return value != undefined && /^should\b/i.test(value);
43
+ }
44
+
45
+ /** Whether a property's key is the `it` description key used by `itCases`-style test tables. */
46
+ function isItDescriptionKey(property: Readonly<Property>): boolean {
47
+ if (property.computed) {
48
+ return false;
49
+ }
50
+ return (
51
+ (property.key.type === 'Identifier' && property.key.name === 'it') ||
52
+ (property.key.type === 'Literal' && property.key.value === 'it')
53
+ );
54
+ }
55
+
56
+ const rule: Rule.RuleModule = {
57
+ meta: {
58
+ type: 'suggestion',
59
+ messages: {
60
+ noShould:
61
+ "Write the test description in declarative present tense without a leading 'should' (e.g. 'strips maiden name' not 'should strip maiden name').",
62
+ },
63
+ schema: [],
64
+ },
65
+ create(context) {
66
+ return {
67
+ CallExpression(node: CallExpression & Rule.NodeParentExtension) {
68
+ const baseName = getCalleeBaseName(node.callee);
69
+
70
+ if (!baseName || !testFunctionNames.includes(baseName)) {
71
+ return;
72
+ }
73
+
74
+ const firstArgument = node.arguments[0];
75
+
76
+ if (
77
+ !firstArgument ||
78
+ firstArgument.type === 'SpreadElement' ||
79
+ !startsWithShould(getStaticStringValue(firstArgument))
80
+ ) {
81
+ return;
82
+ }
83
+
84
+ context.report({
85
+ node: firstArgument,
86
+ messageId: 'noShould',
87
+ });
88
+ },
89
+ Property(node: Property & Rule.NodeParentExtension) {
90
+ if (
91
+ !isItDescriptionKey(node) ||
92
+ !startsWithShould(getStaticStringValue(node.value))
93
+ ) {
94
+ return;
95
+ }
96
+
97
+ context.report({
98
+ node: node.value,
99
+ messageId: 'noShould',
100
+ });
101
+ },
102
+ };
103
+ },
104
+ };
105
+
106
+ export default rule;
@@ -0,0 +1,73 @@
1
+ import {type Rule} from 'eslint';
2
+ import type {Node} from 'estree';
3
+
4
+ /**
5
+ * Recursively reports any binding `Identifier` named exactly `_` reachable from a binding pattern.
6
+ * Walks into destructuring patterns (object/array), default values (`AssignmentPattern`), and rest
7
+ * elements (`RestElement`) so placeholders like `{a: _}`, `[_]`, `_ = 1`, and `..._` are caught.
8
+ * Only binding positions are visited - object-pattern property keys are skipped (only the value
9
+ * side is a binding), and non-binding nodes (e.g. member-expression assignment targets) are
10
+ * ignored.
11
+ */
12
+ function reportUnderscoresInPattern(
13
+ context: Readonly<Rule.RuleContext>,
14
+ node: Readonly<Node> | null | undefined,
15
+ ) {
16
+ if (!node) {
17
+ return;
18
+ }
19
+
20
+ if (node.type === 'Identifier') {
21
+ if (node.name === '_') {
22
+ context.report({
23
+ node,
24
+ messageId: 'underscoreVariable',
25
+ });
26
+ }
27
+ } else if (node.type === 'AssignmentPattern') {
28
+ reportUnderscoresInPattern(context, node.left);
29
+ } else if (node.type === 'RestElement') {
30
+ reportUnderscoresInPattern(context, node.argument);
31
+ } else if (node.type === 'ArrayPattern') {
32
+ node.elements.forEach((element) => reportUnderscoresInPattern(context, element));
33
+ } else if (node.type === 'ObjectPattern') {
34
+ node.properties.forEach((property) => {
35
+ reportUnderscoresInPattern(
36
+ context,
37
+ property.type === 'RestElement' ? property.argument : property.value,
38
+ );
39
+ });
40
+ }
41
+ }
42
+
43
+ const rule: Rule.RuleModule = {
44
+ meta: {
45
+ type: 'suggestion',
46
+ messages: {
47
+ underscoreVariable:
48
+ 'Do not use a standalone `_` as a variable or parameter name; give it a brief descriptive name (e.g. `unusedReason`).',
49
+ },
50
+ schema: [],
51
+ },
52
+ create(context) {
53
+ return {
54
+ VariableDeclarator(node: Rule.Node & {type: 'VariableDeclarator'}) {
55
+ reportUnderscoresInPattern(context, node.id);
56
+ },
57
+ 'FunctionDeclaration, FunctionExpression, ArrowFunctionExpression'(
58
+ node: Rule.Node & {
59
+ params: Node[];
60
+ },
61
+ ) {
62
+ node.params.forEach((param) => {
63
+ reportUnderscoresInPattern(context, param);
64
+ });
65
+ },
66
+ CatchClause(node: Rule.Node & {type: 'CatchClause'}) {
67
+ reportUnderscoresInPattern(context, node.param);
68
+ },
69
+ };
70
+ },
71
+ };
72
+
73
+ export default rule;
@@ -0,0 +1,66 @@
1
+ import {type Rule} from 'eslint';
2
+ import type {ArrowFunctionExpression} from 'estree';
3
+
4
+ const rule: Rule.RuleModule = {
5
+ meta: {
6
+ type: 'suggestion',
7
+ fixable: 'code',
8
+ messages: {
9
+ preferBlockBody:
10
+ 'Use a block body with an explicit `return` instead of the parenthesized object shorthand `() => ({...})`.',
11
+ },
12
+ schema: [],
13
+ },
14
+ create(context) {
15
+ const sourceCode = context.sourceCode;
16
+
17
+ return {
18
+ ArrowFunctionExpression(node: ArrowFunctionExpression & Rule.NodeParentExtension) {
19
+ /**
20
+ * `() => ({ ... })` parses with an `ObjectExpression` body; the wrapping parens are
21
+ * not represented as a node. A block body (`() => { ... }`) parses as a
22
+ * `BlockStatement` and must not be flagged.
23
+ */
24
+ if (node.body.type !== 'ObjectExpression') {
25
+ return;
26
+ }
27
+
28
+ context.report({
29
+ node: node.body,
30
+ messageId: 'preferBlockBody',
31
+ fix(fixer) {
32
+ const objectText = sourceCode.getText(node.body);
33
+
34
+ /**
35
+ * The object body is always wrapped in parentheses in source (the parser
36
+ * requires them to disambiguate from a block body), but those parens are
37
+ * not AST nodes. Expand the replacement to swallow the surrounding `(` and
38
+ * `)` tokens so the rewrite does not leave stray parentheses behind.
39
+ */
40
+ const openParen = sourceCode.getTokenBefore(node.body);
41
+ const closeParen = sourceCode.getTokenAfter(node.body);
42
+
43
+ if (
44
+ !openParen ||
45
+ !closeParen ||
46
+ openParen.value !== '(' ||
47
+ closeParen.value !== ')'
48
+ ) {
49
+ return null;
50
+ }
51
+
52
+ return fixer.replaceTextRange(
53
+ [
54
+ openParen.range[0],
55
+ closeParen.range[1],
56
+ ],
57
+ `{ return ${objectText}; }`,
58
+ );
59
+ },
60
+ });
61
+ },
62
+ };
63
+ },
64
+ };
65
+
66
+ export default rule;