Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(eslint-plugin): [no-implied-eval] don't report when Function is imported #2348

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
20 changes: 18 additions & 2 deletions packages/eslint-plugin/src/rules/no-implied-eval.ts
Expand Up @@ -35,6 +35,7 @@ export default util.createRule({
defaultOptions: [],
create(context) {
const parserServices = util.getParserServices(context);
const program = parserServices.program;
const checker = parserServices.program.getTypeChecker();

function getCalleeName(
Expand Down Expand Up @@ -113,14 +114,29 @@ export default util.createRule({
function checkImpliedEval(
node: TSESTree.NewExpression | TSESTree.CallExpression,
): void {
const tsNode = parserServices.esTreeNodeToTSNodeMap.get(node.callee);
const type = checker.getTypeAtLocation(tsNode);

const calleeName = getCalleeName(node.callee);
if (calleeName === null) {
return;
}

if (calleeName === FUNCTION_CONSTRUCTOR) {
context.report({ node, messageId: 'noFunctionConstructor' });
return;
const symbol = type.getSymbol();
if (symbol) {
const declarations = symbol.getDeclarations() ?? [];
for (const declaration of declarations) {
const sourceFile = declaration.getSourceFile();
if (program.isSourceFileDefaultLibrary(sourceFile)) {
context.report({ node, messageId: 'noFunctionConstructor' });
return;
}
}
} else {
context.report({ node, messageId: 'noFunctionConstructor' });
return;
}
}

if (node.arguments.length === 0) {
Expand Down
3 changes: 3 additions & 0 deletions packages/eslint-plugin/tests/fixtures/class.ts
Expand Up @@ -8,3 +8,6 @@ export const console = { log() {} };
export class Reducable {
reduce() {}
}

// used by no-implied-eval test function imports
export class Function {}
5 changes: 5 additions & 0 deletions packages/eslint-plugin/tests/rules/no-implied-eval.test.ts
Expand Up @@ -6,6 +6,7 @@ const ruleTester = new RuleTester({
parserOptions: {
tsconfigRootDir: rootDir,
ecmaVersion: 2015,
sourceType: 'module',
project: './tsconfig.json',
},
parser: '@typescript-eslint/parser',
Expand Down Expand Up @@ -241,6 +242,10 @@ const fn = (foo: () => void) => {
execScript(foo);
};
`,
`
import { Function } from './class';
new Function('foo');
`,
],

invalid: [
Expand Down