forked from ember-cli/eslint-plugin-ember
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathno-array-prototype-extensions.js
More file actions
862 lines (770 loc) · 28.6 KB
/
no-array-prototype-extensions.js
File metadata and controls
862 lines (770 loc) · 28.6 KB
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
'use strict';
const { getName, getNodeOrNodeFromVariable } = require('../utils/utils');
const { isClassPropertyOrPropertyDefinition } = require('../utils/types');
const { getImportIdentifier } = require('../utils/import');
const { insertImportDeclaration } = require('../utils/fixer');
const Stack = require('../utils/stack');
const ERROR_MESSAGE = "Don't use Ember's array prototype extensions";
const TOKEN_TYPES = {
PUNCTUATOR: 'Punctuator',
};
const EXTENSION_METHODS = new Set([
/**
* https://api.emberjs.com/ember/release/classes/EmberArray
* EmberArray methods excluding native functions like reduce, filter etc.
* */
'any',
'compact',
'filterBy',
'findBy',
'getEach',
'invoke',
'isAny',
'isEvery',
'mapBy',
'objectAt',
'objectsAt',
'reject',
'rejectBy',
'setEach',
'sortBy',
'toArray',
'uniq',
'uniqBy',
'without',
/**
* https://api.emberjs.com/ember/release/classes/MutableArray
* MutableArray methods excluding `replace`. `replace` is handled differently as it's also part of String.prototype.
* */
'addObject',
'addObjects',
'clear',
'insertAt',
'popObject',
'pushObject',
'pushObjects',
'removeAt',
'removeObject',
'removeObjects',
'reverseObjects',
'setObjects',
'shiftObject',
'unshiftObject',
'unshiftObjects',
]);
const REPLACE_METHOD = 'replace';
/**
* https://api.emberjs.com/ember/release/classes/EmberArray
* EmberArray properties excluding native props: [], length.
* */
const EXTENSION_PROPERTIES = new Set(['lastObject', 'firstObject']);
/**
* Ignore these function calls.
*/
const KNOWN_NON_ARRAY_FUNCTION_CALLS = new Set([
// Promise.reject()
'window.Promise.reject()',
'Promise.reject()',
// RSVP.reject
'RSVP.reject()',
'RSVP.Promise.reject()',
'Ember.RSVP.reject()',
'Ember.RSVP.Promise.reject()',
// Promise.any()
'window.Promise.any()',
'Promise.any()',
// *storage.clear()
'window.localStorage.clear()',
'window.sessionStorage.clear()',
'localStorage.clear()',
'sessionStorage.clear()',
]);
/**
* Ignore these function calls using RegExps.
*/
const KNOWN_NON_ARRAY_FUNCTION_CALLS_REGEXP = new Set([
// ember-cli-mirage
/\.server\.schema\.(.*)\.findBy\(\)/,
]);
/**
* Ignore objects of these names.
*/
const KNOWN_NON_ARRAY_OBJECTS = new Set([
// lodash
'_',
'lodash',
// jquery
'$()',
'jQuery()',
'jquery()',
]);
/**
* Ignore variables initialized to instances of these classes.
*/
const KNOWN_NON_ARRAY_CLASSES = new Set([
// These Set/Map data structure classes have an overlapping clear() method.
'Set',
'Map',
'WeakSet',
'WeakMap',
// https://github.com/tracked-tools/tracked-built-ins
'TrackedSet',
'TrackedMap',
'TrackedWeakSet',
'TrackedWeakMap',
]);
/**
* Ignore certain function calls made on variables containing certain words as they are likely to be instances of non-array classes.
* Words stored in lowercase.
*/
const FN_NAMES_TO_KNOWN_NON_ARRAY_WORDS = new Map([
// These Promise-related objects have an overlapping reject() method.
['reject', new Set(['deferred', 'promise'])],
// These Set/Map data structure classes have an overlapping clear() method.
['clear', new Set(['set', 'map'])],
]);
/**
* Return the (lowercase) list of words in a variable name of various casings (camelCase, PascalCase, snake_case, UPPER_CASE).
* @param {string} name - variable name
* @returns {string[]} list of (lowercase) words in the variable name
*/
function variableNameToWords(name) {
if (name.includes('_')) {
// snake_case, UPPER_CASE.
return name.toLowerCase().trim().split('_');
}
if (name === name.toUpperCase()) {
// Single word.
return [name.toLowerCase()];
}
// camelCase, PascalCase.
return name
.replaceAll(/([A-Z])/g, ' $1')
.toLowerCase()
.trim()
.split(' ');
}
/**
* Returns the fixing object if it can be fixable otherwise returns an empty array.
*
* @param {Object} callExpressionNode The call expression AST node.
* @param {Object} fixer The ESLint fixer object which will be used to apply fixes.
* @param {Object} context The ESlint context object which contains some helper utils
* @param {Object} [options] An object that contains additional information
* @param {String} [options.importedGetName] The name of the imported get specifier from @ember/object package
* @param {String} [options.importedSetName] The name of the imported set specifier from @ember/object package
* @param {String} [options.importedCompareName] The name of the imported compare specifier from @ember/utils package
* @returns {Object|[]}
*/
// eslint-disable-next-line complexity
function applyFix(callExpressionNode, fixer, context, options = {}) {
const calleeProp = callExpressionNode.callee.property;
const propertyName = calleeProp.name;
const calleeObj = callExpressionNode.callee.object;
const callArgs = callExpressionNode.arguments;
const sourceCode = context.sourceCode ?? context.getSourceCode();
// Get the open parenthesis immediately after the callee name
const openParenToken = sourceCode.getTokenAfter(calleeProp, {
filter(token) {
return token.type === TOKEN_TYPES.PUNCTUATOR && token.value === '(';
},
});
// Get the close parenthesis from the end of the callExpressionNode
const closeParenToken = sourceCode.getLastToken(callExpressionNode, {
filter(token) {
return token.type === TOKEN_TYPES.PUNCTUATOR && token.value === ')';
},
});
switch (propertyName) {
case 'any': {
return fixer.replaceText(calleeProp, 'some');
}
case 'compact': {
const fixes = [];
if (openParenToken && closeParenToken && callArgs.length === 0) {
fixes.push(
fixer.replaceText(calleeProp, 'filter'),
// Replacing the content starting from open parenthesis to close parenthesis
fixer.replaceTextRange(
[openParenToken.range[0], closeParenToken.range[1]],
'(item => item !== undefined && item !== null)'
)
);
}
return fixes;
}
case 'filterBy':
case 'findBy':
case 'isAny':
case 'isEvery': {
const fixes = [];
if (callArgs.length > 0 && callArgs.length < 3) {
const hasSecondArg = callArgs.length > 1;
const firstArg = callArgs[0];
const secondArg = callArgs[1];
let replacementMethod;
switch (propertyName) {
case 'findBy': {
replacementMethod = 'find';
break;
}
case 'isAny': {
replacementMethod = 'some';
break;
}
case 'isEvery': {
replacementMethod = 'every';
break;
}
default: {
replacementMethod = 'filter';
}
}
// default to `get` if the `get` hasn't already been imported.
const importedGetName = options.importedGetName ?? 'get';
fixes.push(
fixer.replaceText(calleeProp, replacementMethod),
// Replacing the content starting from open parenthesis to close parenthesis
// If the findBy contains two arguments, the property (first argument) value will be compared against the second argument
// If the filterBy contains only one argument, the property's truthy value is used to filter
fixer.replaceTextRange(
[openParenToken.range[0], closeParenToken.range[1]],
`(item => ${importedGetName}(item, ${sourceCode.getText(firstArg)})${
hasSecondArg ? ` === ${sourceCode.getText(secondArg)}` : ''
})`
)
);
// Add `get` import statement only if it is not imported already
if (!options.importedGetName) {
fixes.push(insertImportDeclaration(sourceCode, fixer, '@ember/object', importedGetName));
}
}
return fixes;
}
case 'invoke': {
const fixes = [];
if (callArgs.length > 0) {
const argText = sourceCode.getText(callArgs[0]);
const restOfArgs = callArgs
.slice(1)
.map((arg) => sourceCode.getText(arg))
.join(', ');
// default to `get` if the `get` hasn't already been imported.
const importedGetName = options.importedGetName ?? 'get';
fixes.push(
fixer.replaceText(calleeProp, 'map'),
// Replacing the content starting from open parenthesis to close parenthesis
fixer.replaceTextRange(
[openParenToken.range[0], closeParenToken.range[1]],
`(item => ${importedGetName}(item, ${argText})?.(${restOfArgs}))`
)
);
// Add `get` import statement only if it is not imported already
if (!options.importedGetName) {
fixes.push(insertImportDeclaration(sourceCode, fixer, '@ember/object', importedGetName));
}
}
return fixes;
}
case 'mapBy':
case 'getEach': {
if (callArgs.length === 1) {
const argText = sourceCode.getText(callArgs[0]);
const fixes = [];
// default to `get` if the `get` hasn't already been imported.
const importedGetName = options.importedGetName ?? 'get';
fixes.push(
fixer.replaceText(calleeProp, 'map'),
// Replacing the content starting from open parenthesis to close parenthesis
fixer.replaceTextRange(
[openParenToken.range[0], closeParenToken.range[1]],
`(item => ${importedGetName}(item, ${argText}))`
)
);
// Add `get` import statement only if it is not imported already
if (!options.importedGetName) {
fixes.push(insertImportDeclaration(sourceCode, fixer, '@ember/object', importedGetName));
}
return fixes;
}
return [];
}
case 'objectAt': {
if (callArgs.length === 1) {
return [
fixer.insertTextBefore(
callExpressionNode,
`${sourceCode.getText(calleeObj)}${
callExpressionNode.callee.optional ? '?.' : ''
}[${sourceCode.getText(callArgs[0])}]`
),
fixer.remove(callExpressionNode),
];
}
return [];
}
case 'objectsAt': {
if (callArgs.length > 0) {
return [
fixer.insertTextBefore(
callExpressionNode,
`[${callArgs
.map((arg) => sourceCode.getText(arg))
.join(', ')}].map((ind) => ${sourceCode.getText(calleeObj)}[ind])`
),
fixer.remove(callExpressionNode),
];
}
return [];
}
case 'reject': {
if (callArgs.length > 0 && callArgs.length < 3) {
return [
fixer.replaceText(calleeProp, 'filter'),
// TODO: Switch to `Reflect.apply` once Ember v3 LTS support ends: https://emberjs.com/releases/lts/
fixer.replaceText(
callArgs[0],
`function(...args) { return !(${sourceCode.getText(callArgs[0])}).apply(this, args); }`
),
];
}
return [];
}
case 'rejectBy': {
const fixes = [];
if (callArgs.length > 0 && callArgs.length < 3) {
const hasSecondArg = callArgs.length > 1;
const firstArg = callArgs[0];
const secondArg = callArgs[1];
// default to `get` if the `get` hasn't already been imported.
const importedGetName = options.importedGetName ?? 'get';
fixes.push(
fixer.replaceText(calleeProp, 'filter'),
// Replacing the content starting from open parenthesis to close parenthesis
// If the findBy contains two arguments, the property (first argument) value will be compared against the second argument
// If the filterBy contains only one argument, the property's truthy value is used to filter
fixer.replaceTextRange(
[openParenToken.range[0], closeParenToken.range[1]],
hasSecondArg
? `(item => ${importedGetName}(item, ${sourceCode.getText(
firstArg
)}) !== ${sourceCode.getText(secondArg)})`
: `(item => !${importedGetName}(item, ${sourceCode.getText(firstArg)}))`
)
);
// Add `get` import statement only if it is not imported already
if (!options.importedGetName) {
fixes.push(insertImportDeclaration(sourceCode, fixer, '@ember/object', importedGetName));
}
}
return fixes;
}
case 'setEach': {
const fixes = [];
if (callArgs.length === 2) {
// default to `set` if the `set` hasn't already been imported.
const importedSetName = options.importedSetName ?? 'set';
fixes.push(
fixer.replaceText(calleeProp, 'forEach'),
// Replacing the content starting from open parenthesis to close parenthesis
fixer.replaceTextRange(
[openParenToken.range[0], closeParenToken.range[1]],
`(item => ${importedSetName}(item, ${callArgs
.map((arg) => sourceCode.getText(arg))
.join(', ')}))`
)
);
// Add `set` import statement only if it is not imported already
if (!options.importedSetName) {
fixes.push(insertImportDeclaration(sourceCode, fixer, '@ember/object', importedSetName));
}
return fixes;
}
return [];
}
case 'sortBy': {
const fixes = [];
if (callArgs.length > 0) {
// default to `compare` if the `compare` hasn't already been imported.
const importedCompareName = options.importedCompareName ?? 'compare';
// default to `compare` if the `compare` hasn't already been imported.
const importedGetName = options.importedGetName ?? 'get';
const argsText = callArgs.map((arg) => sourceCode.getText(arg)).join(', ');
let sortFn;
const comparisonFnInString = (key) =>
`${importedCompareName}(${importedGetName}(a, ${key}), ${importedGetName}(b, ${key}))`;
if (callArgs.length === 1 && callArgs[0].type !== 'SpreadElement') {
sortFn =
callArgs[0].type === 'Identifier' || callArgs[0].type === 'Literal'
? `(a, b) => ${comparisonFnInString(argsText)}`
: `(a, b) => {
const key = ${argsText};
return ${comparisonFnInString('key')};
}`;
} else {
// Loop through keys if there are more than one argument
sortFn = `(a, b) => {
for (const key of [${argsText}]) {
const compareValue = ${comparisonFnInString('key')};
if (compareValue) {
return compareValue;
}
}
return 0;
}`;
}
fixes.push(
// Duplicate array
fixer.replaceText(calleeObj, `[...${sourceCode.getText(calleeObj)}]`),
fixer.replaceText(calleeProp, 'sort'),
// Replacing the content starting from open parenthesis to close parenthesis
fixer.replaceTextRange([openParenToken.range[0], closeParenToken.range[1]], `(${sortFn})`)
);
// Add `get` import statement only if it is not imported already
if (!options.importedGetName) {
fixes.push(insertImportDeclaration(sourceCode, fixer, '@ember/object', importedGetName));
}
// Add `compare` import statement only if it is not imported already
if (!options.importedCompareName) {
fixes.push(
insertImportDeclaration(sourceCode, fixer, '@ember/utils', importedCompareName)
);
}
}
return fixes;
}
case 'toArray': {
if (callArgs.length === 0) {
return [
fixer.insertTextBefore(callExpressionNode, `[...${sourceCode.getText(calleeObj)}]`),
fixer.remove(callExpressionNode),
];
}
return [];
}
case 'uniq': {
if (callArgs.length === 0) {
return [
fixer.insertTextBefore(
callExpressionNode,
`[...new Set(${sourceCode.getText(calleeObj)})]`
),
fixer.remove(callExpressionNode),
];
}
return [];
}
case 'uniqBy': {
const fixes = [];
if (callArgs.length === 1) {
const argInString = sourceCode.getText(callArgs[0]);
// default to `get` if the `get` hasn't already been imported.
const importedGetName = options.importedGetName ?? 'get';
let isFunctionArg;
let isLiteralArg;
switch (callArgs[0].type) {
case 'ArrowFunctionExpression':
case 'FunctionExpression': {
isFunctionArg = true;
break;
}
case 'Literal': {
isLiteralArg = true;
break;
}
default: {
break;
}
}
const uniqByFn = `([uniqArr, itemsSet, getterFn], item) => {
const val = getterFn(item);
if (!itemsSet.has(val)) {
itemsSet.add(val);
uniqArr.push(item);
}
return [uniqArr, itemsSet, getterFn];
}`;
let getterFnInText;
if (isLiteralArg) {
getterFnInText = `(item) => ${importedGetName}(item, ${argInString})`;
} else if (isFunctionArg) {
getterFnInText = argInString;
} else {
getterFnInText = `typeof ${argInString} === 'function' ? ${argInString} : (item) => ${importedGetName}(item, ${argInString})`;
}
const reducerInitialValueArr = ['[]', 'new Set()', getterFnInText];
fixes.push(
fixer.replaceText(calleeProp, 'reduce'),
// Replacing the content starting from open parenthesis to close parenthesis
fixer.replaceTextRange(
[openParenToken.range[0], closeParenToken.range[1]],
`(${uniqByFn}, [${reducerInitialValueArr.join(', ')}])[0]`
)
);
// Add `get` import statement only if it is not imported already
if (!options.importedGetName) {
fixes.push(insertImportDeclaration(sourceCode, fixer, '@ember/object', importedGetName));
}
return fixes;
}
return [];
}
case 'without': {
if (callArgs.length === 1) {
const argText = sourceCode.getText(callArgs[0]);
const calleeObjText = sourceCode.getText(calleeObj);
return [
// As per https://api.emberjs.com/ember/release/classes/EmberArray/methods/mapBy?anchor=without
// when the passed value doesn't not exist in the array, it returns the original array
// Hence we first check for the existence of the passed value in the array before calling filter on array
// Used indexOf instead of includes since v3.x of ember is committed to supporting IE11
// as per the ember browser support policy (https://emberjs.com/browser-support/)
// TODO: Switch to includes once Ember v3 LTS support ends: https://emberjs.com/releases/lts/
fixer.replaceText(calleeProp, `indexOf(${argText}) > -1 ? ${calleeObjText}.filter`),
fixer.insertTextAfter(closeParenToken, ` : ${calleeObjText})`),
// Replacing the content starting from open parenthesis to close parenthesis
fixer.replaceTextRange(
[openParenToken.range[0], closeParenToken.range[1]],
`(item => item !== ${argText})`
),
fixer.insertTextBefore(callExpressionNode, '('),
];
}
return [];
}
default: {
return [];
}
}
}
/**
* Check for a call on `this.store` which we can assume is the Ember Data store service.
* We don't check for an initialization as the service could be implicitly injected: https://github.com/ember-cli/eslint-plugin-ember/blob/master/docs/rules/no-implicit-injections.md
*/
function isThisStoreCall(node) {
return (
node.type === 'CallExpression' &&
node.callee.type === 'MemberExpression' &&
node.callee.object.type === 'MemberExpression' &&
node.callee.object.object.type === 'ThisExpression' &&
node.callee.object.property.type === 'Identifier' &&
node.callee.object.property.name === 'store' &&
node.callee.property.type === 'Identifier' // Any function call on the store service.
);
}
//----------------------------------------------------------------------------------------------
// General rule - Don't use Ember's array prototype extensions like .any(), .pushObject() or .firstObject
//----------------------------------------------------------------------------------------------
/** @type {import('eslint').Rule.RuleModule} */
module.exports = {
meta: {
type: 'suggestion',
docs: {
description: "disallow usage of Ember's `Array` prototype extensions",
category: 'Deprecations',
recommended: false,
url: 'https://github.com/ember-cli/eslint-plugin-ember/tree/master/docs/rules/no-array-prototype-extensions.md',
},
fixable: 'code',
schema: [],
messages: {
main: ERROR_MESSAGE,
},
},
create(context) {
const sourceCode = context.sourceCode ?? context.getSourceCode();
const { scopeManager } = sourceCode;
let importedGetName;
let importedSetName;
let importedCompareName;
let importedEmberArrayName;
// Track some information about the current class we're inside.
const classStack = new Stack();
return {
ImportDeclaration(node) {
if (node.source.value === '@ember/object') {
importedGetName = importedGetName || getImportIdentifier(node, '@ember/object', 'get');
importedSetName = importedSetName || getImportIdentifier(node, '@ember/object', 'set');
}
if (node.source.value === '@ember/utils') {
importedCompareName =
importedCompareName || getImportIdentifier(node, '@ember/utils', 'compare');
}
if (node.source.value === '@ember/array') {
importedEmberArrayName =
importedEmberArrayName || getImportIdentifier(node, '@ember/array', 'A');
}
},
/**
* Cover cases when `EXTENSION_METHODS` is getting called.
* Example: something.filterBy();
* @param {Object} node
*/
// eslint-disable-next-line complexity
CallExpression(node) {
// Skip case: filterBy();
if (node.callee.type !== 'MemberExpression') {
return;
}
// Skip case: this.filterBy(); super.filterBy();
if (['ThisExpression', 'Super'].includes(node.callee.object.type)) {
return;
}
if (node.callee.property.type !== 'Identifier') {
return;
}
const name = getName(node, true);
const nameParts = name.split('.');
if (
KNOWN_NON_ARRAY_FUNCTION_CALLS.has(name) ||
KNOWN_NON_ARRAY_OBJECTS.has(nameParts.at(-2))
) {
// Ignore any known non-array objects/function calls to reduce false positives.
return;
}
for (const expression of KNOWN_NON_ARRAY_FUNCTION_CALLS_REGEXP) {
// Ignore any known non-array function calls matching a regular expression to reduce false positives.
if (expression.test(name)) {
return;
}
}
for (const functionName of FN_NAMES_TO_KNOWN_NON_ARRAY_WORDS.keys()) {
const words = FN_NAMES_TO_KNOWN_NON_ARRAY_WORDS.get(functionName);
if (
nameParts.at(-1) === `${functionName}()` &&
variableNameToWords(nameParts.at(-2)).some((word) => words.has(word))
) {
// We found a function call on a variable whose name contains a word that indicates this variable is not an array.
return;
}
}
const nodeInitializedTo = getNodeOrNodeFromVariable(node.callee.object, scopeManager);
if (
nodeInitializedTo.type === 'NewExpression' &&
nodeInitializedTo.callee.type === 'Identifier' &&
KNOWN_NON_ARRAY_CLASSES.has(nodeInitializedTo.callee.name)
) {
// Ignore when we can tell the variable was initialized to an instance of a non-array class.
// Example: const foo = new Set();
return;
}
if (
(nodeInitializedTo.type === 'AwaitExpression' &&
isThisStoreCall(nodeInitializedTo.argument)) ||
isThisStoreCall(nodeInitializedTo)
) {
// Found call on the Ember Data this.store class.
return;
}
if (
node.callee.type === 'MemberExpression' &&
node.callee.object.type === 'MemberExpression' &&
node.callee.object.object.type === 'ThisExpression' &&
['Identifier', 'PrivateIdentifier', 'PrivateName'].includes(
node.callee.object.property.type
) &&
classStack.peek() &&
classStack.peek().classPropertiesToIgnore.has(
node.callee.object.property.type === 'Identifier'
? node.callee.object.property.name
: `#${node.callee.object.property.name}` // Add # for private properties to avoid confusing public/private properties.
)
) {
// Ignore when we can tell the class property was initialized to an instance of a non-array class.
// Example:
/*
class MyClass {
foo = new Set();
myFunc() { this.foo.clear() }
}
*/
return;
}
// Direct usage of `@ember/array` is allowed.
if (
node.type === 'CallExpression' &&
importedEmberArrayName &&
nodeInitializedTo.type === 'CallExpression' &&
nodeInitializedTo.callee.type === 'Identifier' &&
importedEmberArrayName === nodeInitializedTo.callee.name
) {
return;
}
if (EXTENSION_METHODS.has(node.callee.property.name)) {
context.report({
node,
messageId: 'main',
fix(fixer) {
return applyFix(node, fixer, context, {
importedCompareName,
importedGetName,
importedSetName,
});
},
});
}
// Example: someArray.replace(1, 2, [1, 2, 3]);
// We can differentiate String.prototype.replace and Array.prototype.replace by arguments length
// String.prototype.replace can only have 2 arguments, Array.prototype.replace needs to have exact 3 arguments
if (node.callee.property.name === REPLACE_METHOD && node.arguments.length === 3) {
context.report({ node, messageId: 'main' });
}
},
/**
* Cover cases when `EXTENSION_PROPERTIES` is accessed like:
* foo.firstObject;
* bar.lastObject.bar;
* @param {Object} node
*/
MemberExpression(node) {
// Skip case when EXTENSION_PROPERTIES is accessed through callee.
// Example: something.firstObject()
if (node.parent.type === 'CallExpression') {
return;
}
if (node.property.type !== 'Identifier') {
return;
}
if (EXTENSION_PROPERTIES.has(node.property.name)) {
context.report({ node, messageId: 'main' });
}
},
/**
* Cover cases when `EXTENSION_PROPERTIES` is accessed through literals like:
* get(something, 'foo.firstObject');
* set(something, 'lastObject.bar', 'something');
* @param {Object} node
*/
Literal(node) {
// Generate regexp for extension properties.
// new RegExp(`${[...EXTENSION_PROPERTIES].map(prop => `(\.|^)${prop}(\.|$)`).join('|')}`) won't generate \. correctly
const regexp = /(\.|^)firstObject(\.|$)|(\.|^)lastObject(\.|$)/;
if (typeof node.value === 'string' && regexp.test(node.value)) {
context.report({ node, messageId: 'main' });
}
},
ClassDeclaration(node) {
// Keep track of class properties to ignore because we know they were initialized to an instance of a non-array class.
const classPropertiesToIgnore = new Set(
node.body.body
.filter(
(n) =>
// ClassProperty / ClassPrivateProperty / PrivateName are for ESLint v7.
(isClassPropertyOrPropertyDefinition(n) || n.type === 'ClassPrivateProperty') &&
['Identifier', 'PrivateIdentifier', 'PrivateName'].includes(n.key.type) &&
n.value &&
n.value.type === 'NewExpression' &&
n.value.callee.type === 'Identifier' &&
KNOWN_NON_ARRAY_CLASSES.has(n.value.callee.name)
)
.map((n) => (n.key.type === 'Identifier' ? n.key.name : `#${n.key.name}`)) // Add # for private properties to avoid confusing public/private properties.
);
classStack.push({ node, classPropertiesToIgnore });
},
'ClassDeclaration:exit'() {
// Leaving the current class.
classStack.pop();
},
};
},
};