Skip to content

Commit 50df5ba

Browse files
committed
fix(no-unsafe-references): Add arguments after existing array elements
1 parent b4ef27c commit 50df5ba

File tree

1 file changed

+17
-6
lines changed

1 file changed

+17
-6
lines changed

src/rules/no-unsafe-references.ts

+17-6
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { AST, Rule, Scope, SourceCode } from 'eslint';
22
import * as ESTree from 'estree';
3-
import { isFunction, isPageMethod } from '../utils/ast';
3+
import { getStringValue, isFunction, isPageMethod } from '../utils/ast';
44
import { getSourceCode, truthy } from '../utils/misc';
55

66
/** Collect all variable references in the parent scopes recursively. */
@@ -30,15 +30,21 @@ function addArgument(
3030

3131
// If there are at least two arguments, we can add the references after the
3232
// last element of the second argument, which should be an array.
33-
const arr = node.arguments.at(-1);
34-
if (!arr || arr.type !== 'ArrayExpression') return;
33+
const arg = node.arguments.at(-1);
34+
if (!arg) return;
35+
36+
// If the second argument is not an array, we have to replace it with an array
37+
// containing the existing argument and the new references.
38+
if (arg.type !== 'ArrayExpression') {
39+
return fixer.replaceText(arg, `[${getStringValue(arg)}, ${refs}]`);
40+
}
3541

3642
// It's possible the array is provided but empty, in which case we can just
3743
// replace it with the references.
38-
const lastItem = arr.elements.at(-1);
44+
const lastItem = arg.elements.at(-1);
3945
return lastItem
4046
? fixer.insertTextAfter(lastItem, `, ${refs}`)
41-
: fixer.replaceText(arr, `[${refs}]`);
47+
: fixer.replaceText(arg, `[${refs}]`);
4248
}
4349

4450
/** Get the opening parenthesis of the function. */
@@ -62,7 +68,12 @@ function addParam(
6268
// If the function has params, add the reference after the last one
6369
const lastParam = node.params.at(-1);
6470
if (lastParam) {
65-
return fixer.insertTextAfter(lastParam, `, ${refs}`);
71+
// If the last param is an array, add the reference after the last element
72+
// otherwise, replace the last param with an array containing the existing
73+
// param and the references.
74+
return lastParam.type === 'ArrayPattern'
75+
? fixer.insertTextAfter(lastParam.elements.at(-1)!, `, ${refs}`)
76+
: fixer.replaceText(lastParam, `[${getStringValue(lastParam)}, ${refs}]`);
6677
}
6778

6879
// If the function has no params, add the reference after the opening parenthesis

0 commit comments

Comments
 (0)