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

JS-59: Create rule S7059 (no-async-constructor): Constructors should not contain asynchronous operations #4798

Merged
merged 10 commits into from
Sep 9, 2024
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"console:src/components/NodeSelector/NodeSelector.tsx": [
45
]
}
69 changes: 69 additions & 0 deletions its/ruling/src/test/expected/jsts/desktop/typescript-S7059.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
{
"desktop:app/src/crash/crash-app.tsx": [
97
],
"desktop:app/src/lib/databases/github-user-database.ts": [
69,
73,
81,
86,
90
],
"desktop:app/src/lib/databases/issues-database.ts": [
18,
22
],
"desktop:app/src/lib/databases/pull-request-database.ts": [
89,
93,
97,
105,
108,
112,
116,
121,
135
],
"desktop:app/src/lib/databases/repositories-database.ts": [
107,
113,
121,
123,
127,
131,
135,
139,
140
],
"desktop:app/src/lib/stats/stats-store.ts": [
423
],
"desktop:app/src/lib/stores/accounts-store.ts": [
63
],
"desktop:app/src/lib/stores/app-store.ts": [
527,
528
],
"desktop:app/src/lib/stores/commit-status-store.ts": [
167
vdiez marked this conversation as resolved.
Show resolved Hide resolved
],
"desktop:app/src/lib/stores/pull-request-coordinator.ts": [
62
],
"desktop:app/src/ui/add-repository/create-repository.tsx": [
142
],
"desktop:app/src/ui/app.tsx": [
231
],
"desktop:app/src/ui/check-runs/ci-check-run-rerun-dialog.tsx": [
61
],
"desktop:app/src/ui/clone-repository/clone-repository.tsx": [
183
],
"desktop:app/src/ui/preferences/appearance.tsx": [
71
]
}
27 changes: 27 additions & 0 deletions packages/jsts/src/rules/S7059/cb.fixture.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
async function fetchData() {
return Promise.resolve();
}

class MyClass {
constructor() {
this.init = () => this.data = fetchData(); // compliant, declarations are not executed
this.data = null;
}

async initialize() {
this.data = await fetchData();
}
}

(async () => {
const myObject = new MyClass();
await myObject.initialize();
})();


class MyClass {
constructor() {
console.log('correct');
Promise.resolve().then(() => this.data = fetchData()); //Noncompliant
}
}
28 changes: 28 additions & 0 deletions packages/jsts/src/rules/S7059/cb.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/*
* SonarQube JavaScript Plugin
* Copyright (C) 2011-2024 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
import { check } from '../../../tests/tools';
import { rule } from './';
import path from 'path';

const sonarId = path.basename(__dirname);

describe('Rule S7059', () => {
check(sonarId, rule, __dirname);
});
20 changes: 20 additions & 0 deletions packages/jsts/src/rules/S7059/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/*
* SonarQube JavaScript Plugin
* Copyright (C) 2011-2024 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
export { rule } from './rule';
33 changes: 33 additions & 0 deletions packages/jsts/src/rules/S7059/meta.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/*
* SonarQube JavaScript Plugin
* Copyright (C) 2011-2024 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/

// DO NOT EDIT! This file is autogenerated by "npm run generate-meta"

export const meta = {
type: 'suggestion',
docs: {
description: 'Constructors should not contain asynchronous operations',
recommended: true,
url: 'https://sonarsource.github.io/rspec/#/rspec/S7059/javascript',
requiresTypeChecking: false,
},
};

export const sonarKey = 'S7059';
93 changes: 93 additions & 0 deletions packages/jsts/src/rules/S7059/rule.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
/*
* SonarQube JavaScript Plugin
* Copyright (C) 2011-2024 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
// https://sonarsource.github.io/rspec/#/rspec/S7059/javascript

import { Rule } from 'eslint';
import { isRequiredParserServices, generateMeta, isThenable, isFunctionNode } from '../helpers';
import * as estree from 'estree';
import { meta } from './meta';
import { AST_NODE_TYPES } from '@typescript-eslint/utils';

const flaggedStatements = new Set();

export const rule: Rule.RuleModule = {
meta: generateMeta(meta as Rule.RuleMetaData, {
messages: {
noAsyncConstructor: 'Refactor this asynchronous operation outside of the constructor.',
},
}),
create(context: Rule.RuleContext) {
const services = context.sourceCode.parserServices;
if (!isRequiredParserServices(services)) {
return {};
}

/**
* Given a Promise call, get the parent statement of the async call.
* We want to ensure that it is inside a constructor, but not part of a function declaration:
* constructor() {
* foo();
* }
* and not
* constructor() {
* myFunction = () => { foo() }
* }
* @param node : promise call
*/
function asyncStatementInsideConstructor(node: estree.Expression) {
let classConstructor: estree.MethodDefinition | undefined;
let statement: estree.Statement | undefined;
context.sourceCode.getAncestors(node).forEach(node => {
if (node.type === AST_NODE_TYPES.MethodDefinition && node.kind === 'constructor') {
classConstructor = node;
}
if (classConstructor && node.type.endsWith('Statement')) {
statement = node as estree.Statement;
}
// If we find a function declaration it should not be considered as part of the constructor
if (classConstructor && statement && isFunctionNode(node)) {
statement = undefined;
classConstructor = undefined;
}
vdiez marked this conversation as resolved.
Show resolved Hide resolved
});
return statement;
}

return {
CallExpression(node: estree.CallExpression) {
if (!isThenable(node, services)) {
return;
}
// we want to raise on the parent statement
const statement = asyncStatementInsideConstructor(node);
if (statement && !flaggedStatements.has(statement)) {
flaggedStatements.add(statement);
context.report({
node: statement,
messageId: 'noAsyncConstructor',
});
}
},
'Program:exit'() {
flaggedStatements.clear();
},
};
},
};
2 changes: 2 additions & 0 deletions packages/jsts/src/rules/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,7 @@ import { rule as S6268 } from './S6268'; // no-angular-bypass-sanitization
import { rule as S2870 } from './S2870'; // no-array-delete
import { rule as S6479 } from './S6479'; // no-array-index-key
import { rule as S3579 } from './S3579'; // no-associative-arrays
import { rule as S7059 } from './S7059'; // no-async-constructor
import { rule as S6551 } from './S6551'; // no-base-to-string
import { rule as S2424 } from './S2424'; // no-built-in-override
import { rule as S1219 } from './S1219'; // no-case-label-in-switch
Expand Down Expand Up @@ -779,6 +780,7 @@ const bridgeRules: { [key: string]: Rule.RuleModule } = {
S6957,
S6958,
S6959,
S7059,
S878: eslintRules['no-sequences'],
S881,
S888,
Expand Down
2 changes: 2 additions & 0 deletions packages/jsts/src/rules/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -349,6 +349,7 @@ import { rule as S5689 } from './S5689';
import { rule as S2755 } from './S2755';
import { rule as S4817 } from './S4817';
import type { Rule, Linter } from 'eslint';
import { rule as S7059 } from './S7059';

export const rules: Record<string, Rule.RuleModule> = {
'accessor-pairs': S2376,
Expand Down Expand Up @@ -466,6 +467,7 @@ export const rules: Record<string, Rule.RuleModule> = {
'no-array-delete': S2870,
'no-array-index-key': S6479,
'no-associative-arrays': S3579,
'no-async-constructor': S7059,
'no-base-to-string': S6551,
'no-built-in-override': S2424,
'no-case-label-in-switch': S1219,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,7 @@ public static List<Class<? extends JavaScriptCheck>> getAllChecks() {
NoAriaHiddenOnFocusableCheck.class,
NoArrayDeleteCheck.class,
NoArrayIndexKeyCheck.class,
NoAsyncConstructorCheck.class,
NoBaseToStringCheck.class,
NoCaseDeclarationsCheck.class,
NoChildrenPropCheck.class,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/*
* SonarQube JavaScript Plugin
* Copyright (C) 2011-2024 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.javascript.checks;

import org.sonar.check.Rule;
import org.sonar.plugins.javascript.api.Check;
import org.sonar.plugins.javascript.api.JavaScriptRule;
import org.sonar.plugins.javascript.api.TypeScriptRule;

@TypeScriptRule
@JavaScriptRule
@Rule(key = "S7059")
public class NoAsyncConstructorCheck extends Check {
}
Loading