eslint-plugin-ts-data-forge 0.8.6 → 0.9.0

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 (64) hide show
  1. package/README.md +20 -19
  2. package/dist/plugin.d.mts +2 -0
  3. package/dist/plugin.d.mts.map +1 -1
  4. package/dist/plugin.mjs +1 -0
  5. package/dist/plugin.mjs.map +1 -1
  6. package/dist/rule-types.d.mts +16 -1
  7. package/dist/rule-types.d.mts.map +1 -1
  8. package/dist/rule-types.mjs.map +1 -1
  9. package/dist/rules/ast-utils.d.mts +21 -2
  10. package/dist/rules/ast-utils.d.mts.map +1 -1
  11. package/dist/rules/ast-utils.mjs +51 -4
  12. package/dist/rules/ast-utils.mjs.map +1 -1
  13. package/dist/rules/constants.d.mts +2 -0
  14. package/dist/rules/constants.d.mts.map +1 -1
  15. package/dist/rules/constants.mjs +9 -0
  16. package/dist/rules/constants.mjs.map +1 -1
  17. package/dist/rules/mutable-result.d.mts +10 -0
  18. package/dist/rules/mutable-result.d.mts.map +1 -0
  19. package/dist/rules/mutable-result.mjs +145 -0
  20. package/dist/rules/mutable-result.mjs.map +1 -0
  21. package/dist/rules/prefer-arr-generate.d.mts +57 -0
  22. package/dist/rules/prefer-arr-generate.d.mts.map +1 -0
  23. package/dist/rules/prefer-arr-generate.mjs +588 -0
  24. package/dist/rules/prefer-arr-generate.mjs.map +1 -0
  25. package/dist/rules/prefer-arr-uniq.d.mts.map +1 -1
  26. package/dist/rules/prefer-arr-uniq.mjs +2 -149
  27. package/dist/rules/prefer-arr-uniq.mjs.map +1 -1
  28. package/dist/rules/prefer-canonical-array-slicing.d.mts.map +1 -1
  29. package/dist/rules/prefer-canonical-array-slicing.mjs +47 -28
  30. package/dist/rules/prefer-canonical-array-slicing.mjs.map +1 -1
  31. package/dist/rules/prefer-is-non-null-object.d.mts.map +1 -1
  32. package/dist/rules/prefer-is-non-null-object.mjs +110 -40
  33. package/dist/rules/prefer-is-non-null-object.mjs.map +1 -1
  34. package/dist/rules/prefer-is-record-and-has-key.d.mts.map +1 -1
  35. package/dist/rules/prefer-is-record-and-has-key.mjs +102 -45
  36. package/dist/rules/prefer-is-record-and-has-key.mjs.map +1 -1
  37. package/dist/rules/prefer-range-for-loop.d.mts.map +1 -1
  38. package/dist/rules/prefer-range-for-loop.mjs +97 -16
  39. package/dist/rules/prefer-range-for-loop.mjs.map +1 -1
  40. package/dist/rules/rules.d.mts +1 -0
  41. package/dist/rules/rules.d.mts.map +1 -1
  42. package/dist/rules/rules.mjs +2 -0
  43. package/dist/rules/rules.mjs.map +1 -1
  44. package/package.json +11 -11
  45. package/src/plugin.mts +1 -0
  46. package/src/rule-types.mts +17 -1
  47. package/src/rules/ast-utils.mts +72 -5
  48. package/src/rules/constants.mts +12 -0
  49. package/src/rules/mutable-result.mts +204 -0
  50. package/src/rules/prefer-arr-generate.mts +918 -0
  51. package/src/rules/prefer-arr-generate.test.mts +967 -0
  52. package/src/rules/prefer-arr-is-bounded-length-array.test.mts +19 -0
  53. package/src/rules/prefer-arr-is-max-length-array.test.mts +8 -0
  54. package/src/rules/prefer-arr-is-min-length-array.test.mts +8 -0
  55. package/src/rules/prefer-arr-uniq.mts +2 -207
  56. package/src/rules/prefer-canonical-array-slicing.mts +57 -40
  57. package/src/rules/prefer-canonical-array-slicing.test.mts +55 -0
  58. package/src/rules/prefer-is-non-null-object.mts +160 -57
  59. package/src/rules/prefer-is-non-null-object.test.mts +138 -0
  60. package/src/rules/prefer-is-record-and-has-key.mts +148 -67
  61. package/src/rules/prefer-is-record-and-has-key.test.mts +118 -23
  62. package/src/rules/prefer-range-for-loop.mts +142 -21
  63. package/src/rules/prefer-range-for-loop.test.mts +127 -5
  64. package/src/rules/rules.mts +2 -0
@@ -7,6 +7,8 @@ import {
7
7
  buildNamedImportFix,
8
8
  getImportDeclarations,
9
9
  getNamedImports,
10
+ getRangeWithParens,
11
+ parenthesesDepth,
10
12
  skipTypeWrappers,
11
13
  } from 'eslint-rule-forge';
12
14
  import { TS_DATA_FORGE_MODULE } from './constants.mjs';
@@ -20,7 +22,7 @@ export const preferIsNonNullObject: TSESLint.RuleModule<MessageIds, Options> = {
20
22
  type: 'suggestion',
21
23
  docs: {
22
24
  description:
23
- 'Replace `typeof u === "object" && u !== null` with `isNonNullObject(u)` from ts-data-forge.',
25
+ 'Replace `typeof u === "object" && u !== null`, in either order and anywhere in an `&&` chain, with `isNonNullObject(u)` from ts-data-forge.',
24
26
  },
25
27
  fixable: 'code',
26
28
  schema: [],
@@ -40,41 +42,39 @@ export const preferIsNonNullObject: TSESLint.RuleModule<MessageIds, Options> = {
40
42
  TS_DATA_FORGE_MODULE,
41
43
  );
42
44
 
43
- const mut_nodesToFix: {
44
- node: TSESTree.LogicalExpression;
45
- identifierName: string;
46
- }[] = [];
45
+ const mut_pairsToFix: NonNullObjectPair[] = [];
47
46
 
48
47
  return {
49
48
  LogicalExpression: (node) => {
50
- const identifierName = getNonNullObjectIdentifierName(node);
51
-
52
- if (identifierName === undefined) {
49
+ // A chain is read once, from its outermost `&&`.
50
+ if (node.operator !== '&&' || isChainOperand(sourceCode, node)) {
53
51
  return;
54
52
  }
55
53
 
56
- mut_nodesToFix.push({ node, identifierName });
54
+ mut_pairsToFix.push(...findNonNullObjectPairs(sourceCode, node));
57
55
  },
58
56
  'Program:exit': () => {
59
- // Check if isNonNullObject is already imported
60
57
  const hasIsNonNullObjectImport =
61
58
  getNamedImports(tsDataForgeImports).includes('isNonNullObject');
62
59
 
63
- // Note: We add import only for the first node to avoid conflicts when
64
- // multiple fixes try to insert at the same position. This means if the
65
- // first node is disabled via eslint-disable comment, no import will be
66
- // added.
60
+ // The import fix lives on the first report only:
61
+ // `insertTextBefore(program, …)` produces overlapping ranges
62
+ // otherwise and only one of them would survive a pass. A first report
63
+ // silenced by an `eslint-disable` comment therefore takes the import
64
+ // with it.
67
65
  for (const [
68
66
  index,
69
- { node, identifierName },
70
- ] of mut_nodesToFix.entries()) {
67
+ { range, identifierName },
68
+ ] of mut_pairsToFix.entries()) {
71
69
  context.report({
72
- node,
70
+ loc: {
71
+ start: sourceCode.getLocFromIndex(range[0]),
72
+ end: sourceCode.getLocFromIndex(range[1]),
73
+ },
73
74
  messageId: 'useIsNonNullObject',
74
75
  fix: (fixer) => {
75
76
  const replacement = `isNonNullObject(${identifierName})`;
76
77
 
77
- // Add import only for the first node and only if not already imported
78
78
  const importFixes =
79
79
  index === 0 && !hasIsNonNullObjectImport
80
80
  ? buildNamedImportFix(fixer, program, TS_DATA_FORGE_MODULE, [
@@ -82,7 +82,10 @@ export const preferIsNonNullObject: TSESLint.RuleModule<MessageIds, Options> = {
82
82
  ])
83
83
  : [];
84
84
 
85
- return [...importFixes, fixer.replaceText(node, replacement)];
85
+ return [
86
+ ...importFixes,
87
+ fixer.replaceTextRange(range, replacement),
88
+ ];
86
89
  },
87
90
  });
88
91
  }
@@ -93,39 +96,123 @@ export const preferIsNonNullObject: TSESLint.RuleModule<MessageIds, Options> = {
93
96
  } as const;
94
97
 
95
98
  /**
96
- * The name of the value checked by `typeof u === 'object' && u !== null`, or
97
- * `undefined`. Every operand is read through type wrappers:
98
- * `(u satisfies unknown) !== null` and `u! !== null` check the same `u`.
99
+ * A `typeof u === 'object'` and a `u !== null` next to each other in an `&&`
100
+ * chain, as the source range from the first to the second (parentheses
101
+ * included) and the name of `u`.
99
102
  */
100
- const getNonNullObjectIdentifierName = (
101
- // AST nodes hold mutable child arrays, so they are not deeply readonly.
103
+ type NonNullObjectPair = Readonly<{
104
+ range: TSESTree.Range;
105
+ identifierName: string;
106
+ }>;
107
+
108
+ /**
109
+ * Whether `node` is an operand of an enclosing `&&` chain: a `&&` written
110
+ * directly under another one, without parentheses.
111
+ */
112
+ const isChainOperand = (
113
+ // eslint-disable-next-line @typescript-eslint/prefer-readonly-parameter-types
114
+ sourceCode: TSESLint.SourceCode,
102
115
  // eslint-disable-next-line @typescript-eslint/prefer-readonly-parameter-types
103
116
  node: TSESTree.LogicalExpression,
104
- ): string | undefined => {
105
- if (node.operator !== '&&') {
106
- return undefined;
107
- }
117
+ ): boolean =>
118
+ node.parent.type === AST_NODE_TYPES.LogicalExpression &&
119
+ node.parent.operator === '&&' &&
120
+ parenthesesDepth(sourceCode, node) === 0;
108
121
 
109
- const leftIdentifierName = getTypeofObjectIdentifierName(node.left);
122
+ /**
123
+ * Every non-overlapping pair in the `&&` chain `node` heads, left to right. The
124
+ * two halves may come in either order, and the pair may have operands before
125
+ * and after it: `a && u !== null && typeof u === 'object' && b`. They have to
126
+ * be next to each other, so that the pair is one range of the source.
127
+ */
128
+ const findNonNullObjectPairs = (
129
+ // eslint-disable-next-line @typescript-eslint/prefer-readonly-parameter-types
130
+ sourceCode: TSESLint.SourceCode,
131
+ // eslint-disable-next-line @typescript-eslint/prefer-readonly-parameter-types
132
+ node: TSESTree.LogicalExpression,
133
+ ): readonly NonNullObjectPair[] => {
134
+ const operands = chainOperands(sourceCode, node);
135
+
136
+ const pairsFrom = (index: number): readonly NonNullObjectPair[] => {
137
+ const first = operands[index];
138
+
139
+ const second = operands[index + 1];
110
140
 
111
- const rightIdentifierName = getNonNullCheckIdentifierName(node.right);
141
+ if (first === undefined || second === undefined) {
142
+ return [];
143
+ }
112
144
 
113
- return leftIdentifierName === undefined ||
114
- rightIdentifierName === undefined ||
115
- leftIdentifierName !== rightIdentifierName
116
- ? undefined
117
- : leftIdentifierName;
145
+ const identifierName =
146
+ pairIdentifierName(first, second) ?? pairIdentifierName(second, first);
147
+
148
+ return identifierName === undefined
149
+ ? pairsFrom(index + 1)
150
+ : [
151
+ {
152
+ range: [
153
+ getRangeWithParens(sourceCode, first)[0],
154
+ getRangeWithParens(sourceCode, second)[1],
155
+ ],
156
+ identifierName,
157
+ },
158
+ ...pairsFrom(index + 2),
159
+ ];
160
+ };
161
+
162
+ return pairsFrom(0);
118
163
  };
119
164
 
120
- const getTypeofObjectIdentifierName = (
165
+ /**
166
+ * The operands of the `&&` chain `node`, left to right. A parenthesized `&&`
167
+ * is one operand: its halves cannot be replaced without its parentheses.
168
+ */
169
+ const chainOperands = (
170
+ // eslint-disable-next-line @typescript-eslint/prefer-readonly-parameter-types
171
+ sourceCode: TSESLint.SourceCode,
172
+ // eslint-disable-next-line @typescript-eslint/prefer-readonly-parameter-types
173
+ node: TSESTree.LogicalExpression,
174
+ ): readonly TSESTree.Expression[] =>
175
+ [node.left, node.right].flatMap((operand) =>
176
+ operand.type === AST_NODE_TYPES.LogicalExpression &&
177
+ operand.operator === '&&' &&
178
+ parenthesesDepth(sourceCode, operand) === 0
179
+ ? chainOperands(sourceCode, operand)
180
+ : [operand],
181
+ );
182
+
183
+ // Every operand below is read through its type wrappers: `typeof (u satisfies
184
+ // unknown) === 'object' && u! !== null` is the same check.
185
+
186
+ /**
187
+ * The name of `u` when `typeofCheck` is `typeof u === 'object'` and
188
+ * `nullCheck` is `u !== null` for the same `u`.
189
+ */
190
+ const pairIdentifierName = (
191
+ // eslint-disable-next-line @typescript-eslint/prefer-readonly-parameter-types
192
+ typeofCheck: TSESTree.Expression,
121
193
  // eslint-disable-next-line @typescript-eslint/prefer-readonly-parameter-types
122
- node: TSESTree.Expression,
194
+ nullCheck: TSESTree.Expression,
123
195
  ): string | undefined => {
124
- if (node.type !== AST_NODE_TYPES.BinaryExpression) {
125
- return undefined;
126
- }
196
+ const identifierName = getTypeofObjectIdentifierName(
197
+ skipTypeWrappers(typeofCheck),
198
+ );
127
199
 
128
- if (node.operator !== '===') {
200
+ return identifierName !== undefined &&
201
+ identifierName ===
202
+ getNonNullCheckIdentifierName(skipTypeWrappers(nullCheck))
203
+ ? identifierName
204
+ : undefined;
205
+ };
206
+
207
+ /** `u` of `typeof u === 'object'`, in either operand order. */
208
+ const getTypeofObjectIdentifierName = (
209
+ // eslint-disable-next-line @typescript-eslint/prefer-readonly-parameter-types
210
+ node: TSESTree.Node,
211
+ ): string | undefined => {
212
+ if (
213
+ node.type !== AST_NODE_TYPES.BinaryExpression ||
214
+ node.operator !== '==='
215
+ ) {
129
216
  return undefined;
130
217
  }
131
218
 
@@ -133,31 +220,39 @@ const getTypeofObjectIdentifierName = (
133
220
 
134
221
  const right = skipTypeWrappers(node.right);
135
222
 
223
+ const typeofSide = isLiteralOf(right, 'object')
224
+ ? left
225
+ : isLiteralOf(left, 'object')
226
+ ? right
227
+ : undefined;
228
+
136
229
  if (
137
- left.type !== AST_NODE_TYPES.UnaryExpression ||
138
- left.operator !== 'typeof' ||
139
- right.type !== AST_NODE_TYPES.Literal ||
140
- right.value !== 'object'
230
+ typeofSide?.type !== AST_NODE_TYPES.UnaryExpression ||
231
+ typeofSide.operator !== 'typeof'
141
232
  ) {
142
233
  return undefined;
143
234
  }
144
235
 
145
- const argument = skipTypeWrappers(left.argument);
236
+ const argument = skipTypeWrappers(typeofSide.argument);
146
237
 
147
238
  return argument.type === AST_NODE_TYPES.Identifier
148
239
  ? argument.name
149
240
  : undefined;
150
241
  };
151
242
 
243
+ /**
244
+ * `u` of `u !== null`, in either operand order. `u != null` also excludes
245
+ * `undefined`, which `typeof u === 'object'` has already excluded, so it is
246
+ * the same check here.
247
+ */
152
248
  const getNonNullCheckIdentifierName = (
153
249
  // eslint-disable-next-line @typescript-eslint/prefer-readonly-parameter-types
154
- node: TSESTree.Expression,
250
+ node: TSESTree.Node,
155
251
  ): string | undefined => {
156
- if (node.type !== AST_NODE_TYPES.BinaryExpression) {
157
- return undefined;
158
- }
159
-
160
- if (node.operator !== '!==') {
252
+ if (
253
+ node.type !== AST_NODE_TYPES.BinaryExpression ||
254
+ (node.operator !== '!==' && node.operator !== '!=')
255
+ ) {
161
256
  return undefined;
162
257
  }
163
258
 
@@ -165,9 +260,17 @@ const getNonNullCheckIdentifierName = (
165
260
 
166
261
  const right = skipTypeWrappers(node.right);
167
262
 
168
- return left.type !== AST_NODE_TYPES.Identifier ||
169
- right.type !== AST_NODE_TYPES.Literal ||
170
- right.value !== null
171
- ? undefined
172
- : left.name;
263
+ const checked = isLiteralOf(right, null)
264
+ ? left
265
+ : isLiteralOf(left, null)
266
+ ? right
267
+ : undefined;
268
+
269
+ return checked?.type === AST_NODE_TYPES.Identifier ? checked.name : undefined;
173
270
  };
271
+
272
+ const isLiteralOf = (
273
+ // eslint-disable-next-line @typescript-eslint/prefer-readonly-parameter-types
274
+ node: TSESTree.Node,
275
+ value: string | null,
276
+ ): boolean => node.type === AST_NODE_TYPES.Literal && node.value === value;
@@ -193,6 +193,144 @@ describe('prefer-is-non-null-object through type wrappers', () => {
193
193
  { messageId: 'useIsNonNullObject' },
194
194
  ],
195
195
  },
196
+ {
197
+ name: 'both halves wrapped as a whole',
198
+ code: dedent`
199
+ import { isNonNullObject } from 'ts-data-forge';
200
+ declare const u: unknown;
201
+ const ok =
202
+ ((typeof u === 'object') satisfies boolean) &&
203
+ ((u !== null) as boolean);
204
+ `,
205
+ output: dedent`
206
+ import { isNonNullObject } from 'ts-data-forge';
207
+ declare const u: unknown;
208
+ const ok =
209
+ isNonNullObject(u);
210
+ `,
211
+ errors: [{ messageId: 'useIsNonNullObject' }],
212
+ },
196
213
  ],
197
214
  });
198
215
  }, 20000);
216
+
217
+ describe('prefer-is-non-null-object in other forms', () => {
218
+ tester.run('prefer-is-non-null-object', preferIsNonNullObject, {
219
+ valid: [
220
+ {
221
+ name: 'the two halves joined by `||`',
222
+ code: dedent`
223
+ declare const u: unknown;
224
+ const ok = typeof u === 'object' || u !== null;
225
+ `,
226
+ },
227
+ {
228
+ name: 'the two halves not next to each other in the chain',
229
+ code: dedent`
230
+ declare const u: unknown;
231
+ declare const a: boolean;
232
+ const ok = typeof u === 'object' && a && u !== null;
233
+ `,
234
+ },
235
+ {
236
+ name: 'an undefined check is not a null check',
237
+ code: dedent`
238
+ declare const u: unknown;
239
+ const ok = u !== undefined && typeof u === 'object';
240
+ `,
241
+ },
242
+ {
243
+ name: 'the halves split by parentheses',
244
+ code: dedent`
245
+ declare const u: unknown;
246
+ declare const b: boolean;
247
+ const ok = typeof u === 'object' && (u !== null && b);
248
+ `,
249
+ },
250
+ ],
251
+ invalid: [
252
+ {
253
+ name: 'the halves in reverse order',
254
+ code: dedent`
255
+ declare const u: unknown;
256
+ const ok = u !== null && typeof u === 'object';
257
+ `,
258
+ output: dedent`
259
+ import { isNonNullObject } from 'ts-data-forge';
260
+ declare const u: unknown;
261
+ const ok = isNonNullObject(u);
262
+ `,
263
+ errors: [{ messageId: 'useIsNonNullObject' }],
264
+ },
265
+ {
266
+ name: 'each comparison with its operands swapped',
267
+ code: dedent`
268
+ declare const u: unknown;
269
+ const ok = 'object' === typeof u && null !== u;
270
+ `,
271
+ output: dedent`
272
+ import { isNonNullObject } from 'ts-data-forge';
273
+ declare const u: unknown;
274
+ const ok = isNonNullObject(u);
275
+ `,
276
+ errors: [{ messageId: 'useIsNonNullObject' }],
277
+ },
278
+ {
279
+ name: '`!= null`, which typeof has already made the same check',
280
+ code: dedent`
281
+ declare const u: unknown;
282
+ const ok = typeof u === 'object' && u != null;
283
+ `,
284
+ output: dedent`
285
+ import { isNonNullObject } from 'ts-data-forge';
286
+ declare const u: unknown;
287
+ const ok = isNonNullObject(u);
288
+ `,
289
+ errors: [{ messageId: 'useIsNonNullObject' }],
290
+ },
291
+ {
292
+ name: 'the pair at the start, the end and the middle of a longer chain',
293
+ code: dedent`
294
+ declare const u: unknown;
295
+ declare const a: boolean;
296
+ declare const b: boolean;
297
+ const x = typeof u === 'object' && u !== null && 'k' in u;
298
+ const y = a && typeof u === 'object' && u !== null;
299
+ const z = a && u !== null && (typeof u === 'object') && b;
300
+ `,
301
+ output: dedent`
302
+ import { isNonNullObject } from 'ts-data-forge';
303
+ declare const u: unknown;
304
+ declare const a: boolean;
305
+ declare const b: boolean;
306
+ const x = isNonNullObject(u) && 'k' in u;
307
+ const y = a && isNonNullObject(u);
308
+ const z = a && isNonNullObject(u) && b;
309
+ `,
310
+ errors: [
311
+ { messageId: 'useIsNonNullObject' },
312
+ { messageId: 'useIsNonNullObject' },
313
+ { messageId: 'useIsNonNullObject' },
314
+ ],
315
+ },
316
+ {
317
+ name: 'two pairs in one chain',
318
+ code: dedent`
319
+ declare const u: unknown;
320
+ declare const v: unknown;
321
+ const ok = typeof u === 'object' && u !== null && v !== null && typeof v === 'object';
322
+ `,
323
+ output: dedent`
324
+ import { isNonNullObject } from 'ts-data-forge';
325
+ declare const u: unknown;
326
+ declare const v: unknown;
327
+ const ok = isNonNullObject(u) && isNonNullObject(v);
328
+ `,
329
+ errors: [
330
+ { messageId: 'useIsNonNullObject' },
331
+ { messageId: 'useIsNonNullObject' },
332
+ ],
333
+ },
334
+ ],
335
+ });
336
+ });