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 8 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
]
}
50 changes: 50 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,50 @@
{
"desktop:app/src/crash/crash-app.tsx": [
97
],
"desktop:app/src/lib/databases/github-user-database.ts": [
69
],
"desktop:app/src/lib/databases/issues-database.ts": [
18
],
"desktop:app/src/lib/databases/pull-request-database.ts": [
89
vdiez marked this conversation as resolved.
Show resolved Hide resolved
],
"desktop:app/src/lib/databases/repositories-database.ts": [
107
],
"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
],
"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": [
54
],
"desktop:app/src/main-process/ordered-webrequest.ts": [
146
],
"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
]
}
25 changes: 25 additions & 0 deletions packages/jsts/src/rules/S7059/cb.fixture.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
async function fetchData() {
return Promise.resolve();
}

class MyClass {
constructor() {
this.data = null;
}

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

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


class MyClass {
constructor() {
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';
71 changes: 71 additions & 0 deletions packages/jsts/src/rules/S7059/rule.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
/*
* 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 } from '../helpers';
import * as estree from 'estree';
import { meta } from './meta';
import { AST_NODE_TYPES } from '@typescript-eslint/utils';

const flaggedConstructors = 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 {};
}
function isPromiseLike(expr: estree.Expression) {
return isThenable(expr, services);
}

function containingConstructor(node: estree.Expression) {
return context.sourceCode.getAncestors(node).find(node => {
return (
node.type === AST_NODE_TYPES.MethodDefinition &&
node.key.type === AST_NODE_TYPES.Identifier &&
node.key.name === 'constructor'
);
});
}

return {
CallExpression(node: estree.CallExpression) {
const classConstructor = containingConstructor(node);
if (classConstructor && isPromiseLike(node) && !flaggedConstructors.has(classConstructor)) {
flaggedConstructors.add(classConstructor);
context.report({
node: node as estree.Node,
vdiez marked this conversation as resolved.
Show resolved Hide resolved
messageId: 'noAsyncConstructor',
});
}
},
'Program:exit'() {
flaggedConstructors.clear();
vdiez marked this conversation as resolved.
Show resolved Hide resolved
},
};
},
};
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 {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
<h2>Why is this an issue?</h2>
<p>Constructors should not be asynchronous because they are meant to initialize an instance of a class synchronously. While you can technically run a
promise in a constructor, the instance will be returned before the asynchronous operation completes, which can lead to potential issues if the rest of
your code expects the object to be fully initialized. While returning the promise may seem the solution for this problem, it is not standard practice
and can lead to unexpected behavior. Returning a promise (or, in general, any object from another class) from a constructor can be misleading and is
considered a bad practice as this leads to unexpected results with inheritance and the <code>instanceof</code> operator.</p>
<pre>
class MyClass {
constructor() {
Promise.resolve().then(() =&gt; this.data = fetchData()); // Noncompliant, this.data will be undefined in the new instance
}
}
</pre>
<h2>How to fix it</h2>
<p>Create an asynchronous method that performs the necessary asynchronous operations after the object has been constructed</p>
<pre>
class MyClass {
constructor() {
this.data = null;
}

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

(async () =&gt; {
const myObject = new MyClass();
await myObject.initialize();
})();
</pre>
<p>Otherwise, you can use a factory function that returns a promise resolving to an instance of the class after performing the asynchronous
operations.</p>
<pre>
class MyClass {
constructor(data) {
this.data = data;
}

static async create() {
const data = await fetchData();
return new MyClass(data);
}
}

(async () =&gt; {
const myObject = await MyClass.create();
})();
</pre>
<p>Using an asynchronous factory function or an initialization method provides a more conventional, readable, and maintainable approach to handling
asynchronous initialization in JavaScript.</p>
<h2>Resources</h2>
<h3>Documentation</h3>
<ul>
<li> MDN web docs - <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new">new</a> </li>
<li> MDN web docs - <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a> </li>
<li> MDN web docs - <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof">instanceof</a> </li>
<li> MDN web docs - <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain">Inheritance and the
prototype chain</a> </li>
</ul>

Loading