0.14.0 • Published 3 years ago

eslint-plugin-sonarjs v0.14.0

Weekly downloads
167,078
License
LGPL-3.0
Repository
github
Last release
3 years ago

eslint-plugin-sonarjs npm version

eslint-plugin-sonarjs is an ESLint plugin maintained by Sonar, designed to help developers write Clean Code. This plugin exposes to ESLint users all original JS/TS rules from SonarJS, an analyzer for JavaScript and TypeScript within the Sonar ecosystem. This plugin offers general-purpose rules for detecting code smells and bugs, as well as rules for other aspects of code quality, including testing, accessibility, and more. Additionally, it enhances code security by providing rules to report potential security vulnerabilities.

This ESLint plugin does not contain all the rules from the SonarQube JS/TS analyzer. Aside of the rules available here, SonarQube uses rules from other ESLint plugins (some used as they are, some others have been modified). We recommend installing those ESLint plugins and enabling those rules if you are looking for similar results to SonarQube using ESLint.

If you are a SonarQube or SonarCloud user, to lint your code locally, we suggest using SonarLint IDE extension (available for VSCode, JetBrains IDEs and Eclipse). You can connect SonarLint to your SonarQube/SonarCloud project to synchronize rules configuration, issue statuses, etc.

Table of Contents

Changelog

Prerequisites

The prerequisites for using this plugin depend on the ESLint version you are using:

  • For ESLint 8, you need Node.js version >= 16.
  • For ESLint 9, you need Node.js version that complies with (^18.18.0 || ^20.9.0 || >=21).

Installation

First, ensure that your project is configured with ESLint. If it is not, please follow the ESLint instructions to set it up.

To install eslint-plugin-sonarjs, use the following npm command (or yarn equivalent):

npm install eslint-plugin-sonarjs --save-dev # locally
npm install eslint-plugin-sonarjs -g         # globally

Usage

The usage of eslint-plugin-sonarjs depends on the ESLint version used by your project.

For ESLint 9

This plugin provides a single configuration named recommended. This configuration enables most of the rules except for a few exceptions, and the rules are enabled with the error severity. You can enable the recommended configuration in your eslint.config.js file:

import sonarjs from 'eslint-plugin-sonarjs';

export default [sonarjs.configs.recommended];

If you don't use the recommended configuration, you need to declare the plugin manually in the plugins field. Enable or disable rules using the rules field:

import sonarjs from 'eslint-plugin-sonarjs';
export default [
  {
    plugins: { sonarjs },
    rules: {
      'sonarjs/no-implicit-dependencies': 'error',
    },
  },
];

For ESLint 8

We include a recommended-legacy configuration to be backward compatible with ESLint v8, equivalent to the recommended configuration for ESLint 9.

Add sonarjs to your .eslintrc file:

{
  "plugins": ["sonarjs"],
  "extends": ["plugin:sonarjs/recommended-legacy"]
}

You can enable some rules manually:

{
  "rules": {
    "sonarjs/cognitive-complexity": "error",
    "sonarjs/no-identical-expressions": "error"
  }
}

TypeScript ESLint parser

Several rules are designed for linting both JavaScript and TypeScript code, and some even rely on type checking through TypeScript. Therefore, you will need to install the @typescript-eslint/parser dependency and instruct ESLint to use this parser through the parserOptions property.

SonarLint

As an alternative to using this ESLint plugin, you can use SonarLint. SonarLint is an IDE extension that helps you detect and fix quality issues as you write code. It provides a broader set of rules compared to the ESLint plugin, improved versions of ESLint rules, and additional features that enhance your linting experience.

Feedback

If you have any questions, encounter any bugs, or have feature requests, please reach out to us through the Sonar Community Forum. Your messages will reach the maintainers of this GitHub repository.

Rules

💼 Configurations enabled in.\ ✅ Set in the recommended configuration.\ 🔧 Automatically fixable by the --fix CLI option.\ 💡 Manually fixable by editor suggestions.\ 💭 Requires type information.\ ❌ Deprecated.

Name                                Description💼🔧💡💭
anchor-precedenceAlternatives in regular expressions should be grouped when used with anchors💭
argument-typeArguments to built-in functions should match documented types💭
arguments-orderParameters should be passed in the correct order💭
arguments-usage"arguments" should not be accessed directly
array-callback-without-returnCallbacks of array methods should have return statements💭
array-constructorArray constructors should not be used💡
arrow-function-conventionBraces and parentheses should be used consistently with arrow functions
assertions-in-testsTests should include assertions
aws-apigateway-public-apiCreating public APIs is security-sensitive
aws-ec2-rds-dms-publicAllowing public network access to cloud resources is security-sensitive
aws-ec2-unencrypted-ebs-volumeUsing unencrypted EBS volumes is security-sensitive
aws-efs-unencryptedUsing unencrypted EFS file systems is security-sensitive
aws-iam-all-privilegesPolicies granting all privileges are security-sensitive
aws-iam-all-resources-accessiblePolicies granting access to all resources of an account are security-sensitive
aws-iam-privilege-escalationAWS IAM policies should limit the scope of permissions given
aws-iam-public-accessPolicies authorizing public access to resources are security-sensitive
aws-opensearchservice-domainUsing unencrypted Elasticsearch domains is security-sensitive
aws-rds-unencrypted-databasesUsing unencrypted RDS DB resources is security-sensitive
aws-restricted-ip-admin-accessAdministration services access should be restricted to specific IP addresses
aws-s3-bucket-granted-accessGranting access to S3 buckets to all or authenticated users is security-sensitive
aws-s3-bucket-insecure-httpAuthorizing HTTP communications with S3 buckets is security-sensitive
aws-s3-bucket-public-accessAllowing public ACLs or policies on a S3 bucket is security-sensitive
aws-s3-bucket-server-encryptionDisabling server-side encryption of S3 buckets is security-sensitive
aws-s3-bucket-versioningDisabling versioning of S3 buckets is security-sensitive
aws-sagemaker-unencrypted-notebookUsing unencrypted SageMaker notebook instances is security-sensitive
aws-sns-unencrypted-topicsUsing unencrypted SNS topics is security-sensitive
aws-sqs-unencrypted-queueUsing unencrypted SQS queues is security-sensitive
bitwise-operatorsBitwise operators should not be used in boolean contexts
block-scoped-varVariables should be used in the blocks where they are declared
bool-param-defaultOptional boolean parameters should have default value
call-argument-lineFunction call arguments should not start on new lines
certificate-transparencyDisabling Certificate Transparency monitoring is security-sensitive
chai-determinate-assertionChai assertions should have only one reason to succeed
class-nameClass names should comply with a naming convention
class-prototypeClass methods should be used instead of "prototype" assignments💭
code-evalDynamically executing code is security-sensitive
cognitive-complexityCognitive Complexity of functions should not be too high
comma-or-logical-or-caseComma and logical OR operators should not be used in switch cases
comment-regexTrack comments matching a regular expression
concise-regexRegular expression quantifiers and character classes should be used concisely💭
conditional-indentationA conditionally executed single line should be denoted by indentation
confidential-information-loggingAllowing confidential information to be logged is security-sensitive
constructor-for-side-effectsObjects should not be created to be dropped immediately without being used
content-lengthAllowing requests with excessive content length is security-sensitive
content-security-policyDisabling content security policy fetch directives is security-sensitive
cookie-no-httponlyCreating cookies without the "HttpOnly" flag is security-sensitive
cookiesWriting cookies is security-sensitive
corsHaving a permissive Cross-Origin Resource Sharing policy is security-sensitive
csrfDisabling CSRF protections is security-sensitive
cyclomatic-complexityCyclomatic Complexity of functions should not be too high
declarations-in-global-scopeVariables and functions should not be declared in the global scope
deprecationDeprecated APIs should not be used💭
destructuring-assignment-syntaxDestructuring syntax should be used for assignments
different-types-comparisonStrict equality operators should not be used with dissimilar types💡💭
disabled-auto-escapingDisabling auto-escaping in template engines is security-sensitive💭
disabled-resource-integrityUsing remote artifacts without integrity checks is security-sensitive💭
disabled-timeoutDisabling Mocha timeouts should be explicit
dns-prefetchingAllowing browsers to perform DNS prefetching is security-sensitive
duplicates-in-character-classCharacter classes in regular expressions should not contain the same character twice💭
elseif-without-else"if ... else if" constructs should end with "else" clauses
empty-string-repetitionRepeated patterns in regular expressions should not match the empty string💭
encryptionEncrypting data is security-sensitive
encryption-secure-modeEncryption algorithms should be used with secure mode and padding scheme
enforce-trailing-commaTrailing commas should be used🔧
existing-groupsReplacement strings should reference existing regular expression groups💭
expression-complexityExpressions should not be too complex
file-headerTrack lack of copyright and license headers
file-name-differ-from-classDefault export names and file names should match
file-permissionsSetting loose POSIX file permissions is security-sensitive
file-uploadsFile uploads should be restricted
fixme-tagTrack uses of "FIXME" tags
for-in"for...in" loops should filter properties before acting on them
for-loop-increment-signA "for" loop update clause should move the counter in the right direction
frame-ancestorsDisabling content security policy frame-ancestors directive is security-sensitive
function-inside-loopFunctions should not be defined inside loops
function-nameFunction and method names should comply with a naming convention
function-return-typeFunctions should always return the same type💭
future-reserved-wordsFuture reserved words should not be used as identifiers
generator-without-yieldGenerators should explicitly "yield" a value
hashingUsing weak hashing algorithms is security-sensitive
hidden-filesStatically serving hidden files is security-sensitive
in-operator-type-error"in" should not be used with primitive types💭
inconsistent-function-callFunctions should be called consistently with or without "new"
index-of-compare-to-positive-number"indexOf" checks should not be for positive numbers💭
insecure-cookieCreating cookies without the "secure" flag is security-sensitive
insecure-jwt-tokenJWT should be signed and verified with strong cipher algorithms
inverted-assertion-argumentsAssertion arguments should be passed in the correct order💡
jsx-no-leaked-renderReact components should not render non-boolean condition values💡💭
label-positionOnly "while", "do", "for" and "switch" statements should be labelled
link-with-target-blankAuthorizing an opened window to access back to the originating window is security-sensitive
max-linesFiles should not have too many lines of code
max-lines-per-functionFunctions should not have too many lines of code
max-switch-cases"switch" statements should not have too many "case" clauses
max-union-sizeUnion types should not have too many elements
misplaced-loop-counter"for" loop increment clauses should modify the loops' counters
nested-control-flowControl flow statements "if", "for", "while", "switch" and "try" should not be nested too deeply
new-operator-misuse"new" should only be used with functions and classes💭
no-all-duplicated-branchesAll branches in a conditional structure should not have exactly the same implementation
no-alphabetical-sort"Array.prototype.sort()" and "Array.prototype.toSorted()" should use a compare function💡💭
no-angular-bypass-sanitizationDisabling Angular built-in sanitization is security-sensitive
no-array-delete"delete" should not be used on arrays💭
no-associative-arraysArray indexes should be numeric💭
no-async-constructorConstructors should not contain asynchronous operations
no-built-in-overrideBuilt-in objects should not be overridden
no-case-label-in-switch"switch" statements should not contain non-case labels
no-clear-text-protocolsUsing clear-text protocols is security-sensitive
no-code-after-doneTests should not execute any code after "done()" is called
no-collapsible-ifMergeable "if" statements should be combined
no-collection-size-mischeckCollection size and array length comparisons should make sense💡💭
no-commented-codeSections of code should not be commented out💡
no-control-regexRegular expressions should not contain control characters💭
no-dead-storeUnused assignments should be removed
no-delete-var"delete" should be used only with object properties
no-duplicate-in-compositeUnion and intersection types should not include duplicated constituents💡
no-duplicate-stringString literals should not be duplicated
no-duplicated-branchesTwo branches in a conditional structure should not have exactly the same implementation
no-element-overwriteCollection elements should not be replaced unconditionally
no-empty-after-reluctantReluctant quantifiers in regular expressions should be followed by an expression that can't match the empty string💭
no-empty-alternativesAlternation in regular expressions should not contain empty alternatives💭
no-empty-character-classEmpty character classes should not be used💭
no-empty-collectionEmpty collections should not be accessed or iterated
no-empty-groupRegular expressions should not contain empty groups💭
no-empty-test-fileTest files should contain at least one test case
no-equals-in-for-terminationEquality operators should not be used in "for" loop termination conditions
no-exclusive-testsExclusive tests should not be commited to version control💡
no-extra-argumentsFunction calls should not pass extra arguments
no-fallthroughSwitch cases should end with an unconditional "break" statement
no-for-in-iterable"for in" should not be used with iterables💭
no-function-declaration-in-blockFunction declarations should not be made within blocks
no-global-thisThe global "this" object should not be used💡
no-globals-shadowingSpecial identifiers should not be bound or assigned
no-gratuitous-expressionsBoolean expressions should not be gratuitous
no-hardcoded-ipUsing hardcoded IP addresses is security-sensitive
no-hardcoded-passwordsHard-coded passwords are security-sensitive
no-hardcoded-secretsHard-coded secrets are security-sensitive
no-hook-setter-in-bodyReact's useState hook should not be used directly in the render function or body of a component
no-identical-conditions"if/else if" chains and "switch" cases should not have the same condition
no-identical-expressionsIdentical expressions should not be used on both sides of a binary operator
no-identical-functionsFunctions should not have identical implementations
no-ignored-exceptionsExceptions should not be ignored
no-ignored-returnReturn values from functions without side effects should not be ignored💭
no-implicit-dependenciesDependencies should be explicit
no-implicit-globalVariables should be declared explicitly
no-in-misuse"in" should not be used on arrays💡💭
no-incomplete-assertionsAssertions should be complete
no-inconsistent-returnsFunctions should use "return" consistently
no-incorrect-string-concatStrings and non-strings should not be added💭
no-internal-api-useUsers should not use internal APIs
no-intrusive-permissionsUsing intrusive permissions is security-sensitive
no-invalid-await"await" should only be used with promises💭
no-invalid-regexpRegular expressions should be syntactically valid💭
no-invariant-returnsFunction returns should not be invariant
no-inverted-boolean-checkBoolean checks should not be inverted🔧💡
no-ip-forwardForwarding client IP address is security-sensitive
no-labelsLabels should not be used
no-literal-callLiterals should not be used as functions
no-mime-sniffAllowing browsers to sniff MIME types is security-sensitive
no-misleading-array-reverseArray-mutating methods should not be used misleadingly💡💭
no-misleading-character-classUnicode Grapheme Clusters should be avoided inside regex character classes💡💭
no-mixed-contentAllowing mixed-content is security-sensitive
no-nested-assignmentAssignments should not be made from within sub-expressions
no-nested-conditionalTernary operators should not be nested
no-nested-functionsFunctions should not be nested too deeply
no-nested-incdecIncrement (++) and decrement (--) operators should not be used in a method call or mixed with other operators in an expression
no-nested-switch"switch" statements should not be nested
no-nested-template-literalsTemplate literals should not be nested
no-one-iteration-loopLoops with at most one iteration should be refactored
no-os-command-from-pathSearching OS commands in PATH is security-sensitive
no-parameter-reassignmentInitial values of parameters, caught exceptions, and loop variables should not be ignored
no-primitive-wrappersWrapper objects should not be used for primitive types💡
no-redundant-assignmentsAssignments should not be redundant
no-redundant-booleanBoolean literals should not be used in comparisons
no-redundant-jumpJump statements should not be redundant💡
no-redundant-optionalOptional property declarations should not use both '?' and 'undefined' syntax💡💭
no-redundant-parenthesesRedundant pairs of parentheses should be removed💡
no-reference-errorVariables should be defined before being used
no-referrer-policyDisabling strict HTTP no-referrer policy is security-sensitive
no-regex-spacesRegular expressions should not contain multiple spaces💡💭
no-require-or-define"import" should be used to include external code💭
no-return-type-anyPrimitive return types should be used💭
no-same-argument-assertAssertions should not be given twice the same argument
no-same-line-conditionalConditionals should start on new lines💡
no-selector-parameterMethods should not contain selector parameters💭
no-skipped-testsTests should not be skipped without providing a reason
no-small-switch"if" statements should be preferred over "switch" when simpler
no-sonar-commentsTrack uses of "NOSONAR" comments
no-tabTabulation characters should not be used
no-table-as-layoutHTML "<table>" should not be used for layout purposes
no-try-promisePromise rejections should not be caught by "try" blocks💭
no-undefined-argument"undefined" should not be passed as the value of optional parameters💡💭
no-undefined-assignment"undefined" should not be assigned
no-unenclosed-multiline-blockMultiline blocks should be enclosed in curly braces
no-uniq-keyJSX list components keys should match up between renders
no-unsafe-unzipExpanding archive files without controlling resource consumption is security-sensitive
no-unthrown-errorErrors should not be created without being thrown💡
no-unused-collectionCollection contents should be used
no-unused-function-argumentUnused function parameters should be removed💡
no-unused-varsUnused local variables and functions should be removed
no-use-of-empty-return-valueThe return value of void functions should not be used
no-useless-catch"catch" clauses should do more than rethrow
no-useless-incrementValues should not be uselessly incremented
no-useless-intersectionType intersections should use meaningful types💭
no-useless-react-setstateReact state setter function should not be called with its matching state variable
no-variable-usage-before-declarationVariables declared with "var" should be declared before they are used
no-vue-bypass-sanitizationDisabling Vue.js built-in escaping is security-sensitive
no-weak-cipherCipher algorithms should be robust
no-weak-keysCryptographic keys should be robust
no-wildcard-importWildcard imports should not be used
non-existent-operatorNon-existent operators '=+', '=-' and '=!' should not be used💡
non-number-in-arithmetic-expressionArithmetic operators should only have numbers as operands💭
null-dereferenceProperties of variables with "null" or "undefined" values should not be accessed💭
object-alt-content"" tags should provide an alternative content
operation-returning-nanArithmetic operations should not result in "NaN"💭
os-commandUsing shell interpreter when executing OS commands is security-sensitive
post-messageOrigins should be verified during cross-origin communications💭
prefer-default-last"default" clauses should be last
prefer-immediate-returnLocal variables should not be declared and then immediately returned or thrown🔧
prefer-object-literalObject literal syntax should be used
prefer-promise-shorthandShorthand promises should be used💡
prefer-read-only-propsReact props should be read-only💡💭
prefer-regexp-exec"RegExp.exec()" should be preferred over "String.match()"💡💭
prefer-single-boolean-returnReturn of boolean expressions should not be wrapped into an "if-then-else" statement💡
prefer-type-guardType predicates should be used💡
prefer-whileA "while" loop should be used instead of a "for" loop🔧
process-argvUsing command line arguments is security-sensitive
production-debugDelivering code in production with debug features activated is security-sensitive
pseudo-randomUsing pseudorandom number generators (
@jiralite/eslint-config-neon@kushki/eslint@oscarltz/eslint@indiealistic/eslint-config-ids@happ/eslint-config@happ/eslint-plugin@alfabank/eslint-config-siteeslint-rules-node@nbfe/config@nbfe/flow@dnb-org/eslint-config@infinitebrahmanuniverse/nolb-eslint-plugin-s@kushki/eslint-config@dankeu/eslint-config@dankeu/eslint-config-basicvul-configs@everything-registry/sub-chunk-1614@atlantjs.dev/eslint-coreeslint-config-luksoiamphoto-ms-linter@finale-lua/eslint-config@thatdev/lib-dev@kyfe/kye-crm-git-checkereslint-config-zohymoar-js-devildella-test-commonseslint-config-ethang-testeslint-config-bayathyai-eslintswix-eslint-custom-rulesweb-ui-deps@dorabag/eslint-config@dobettest/scaffold@dsoaress/eslint-config@codeday/eslint-config@codeartz/eslint-config@component-hook/eslint-plugin@condorhero/eslint-config-basic@commutatus/eslint-config@cyber-walrus/eslint-config@cyber-walrus/eslint-plugin@colussi/eslint-config@daily-paper/eslint-config@digitalex/eslint-config@datacamp/eslint-config@dev-jo/authentication-lib@developer-kit/eslint-config@denchooo/dev-tools@demartini/eslint-config@cactus-tech/eslint-config@byndyusoft/eslint-config@boehringer-ingelheim/eslint-config@bodrick/eslint-config@belgattitude/eslint-config-bases@bence.a.toth/eslint-config@poyoho/eslint-plugin-config@pequity/eslint-config@rubiin/eslint-configeslint-plugin-c0debreweslint-config-x-feeslint-config-rel1cx@team-triniti/eslint-plugin-triniti-conventionsjs2me-eslint-config@atlantjs.dev/guardian@jterrazz/eslint-config-common@devastion/eslint-plugin-configs@andreapontrandolfo/eslint-config@alexvyber/eslint-config@hcywka/eslint-config-node@hcywka/eslint-config-react@dlwlrma/eslint-plugin-angular@dlwlrma/eslint-plugin-angular-testing@panmenghan/starter@bayathy/eslint-config@arters/eslint-config@aidenlx/eslint-config@arquivei/eslint-config@arlequins/eslint-config-typescript@arlequins/eslint-config-typescript-sveltejs@armit/eslint-config-bases@aramazanov/eslint-config@angular-ru/eslint@angular-ru/eslint-config@angular-ru/eslint-config-enterprise@antagosoft/eslint-config-base@antagosoft/eslint-config-react@antagosoft/eslint-config-vue@anireact/eslint-config@andrskr/eslint-config@ansearch/config@anolilab/eslint-config@atlascommunity/eslint-config@astahmer/eslint-config-ts@atomspace/eslint@authentiqagency/eslint-config@arianrhodsandlot/eslint-config@averay/codeformat@autoguru/eslint-plugin@adobe/aio-cli-plugin-api-mesh@adobe-apimesh/mesh-builder
3.0.2

3 months ago

3.0.1

5 months ago

3.0.0

6 months ago

2.0.4

7 months ago

2.0.3

8 months ago

2.0.2

9 months ago

2.0.1

9 months ago

2.0.0

9 months ago

2.0.1-alpha.0

9 months ago

2.0.1-alpha.1

9 months ago

2.0.1-alpha.2

9 months ago

1.0.4-alpha.2

10 months ago

1.0.4

10 months ago

2.0.0-alpha.0

10 months ago

1.0.4-alpha.1

10 months ago

1.0.4-alpha.0

10 months ago

1.0.2

1 year ago

1.0.3

1 year ago

1.0.0

1 year ago

0.25.1

1 year ago

0.25.0

1 year ago

0.24.0

1 year ago

0.23.0

2 years ago

0.22.0

2 years ago

0.21.0

2 years ago

0.20.0

2 years ago

0.19.0

2 years ago

0.18.0

2 years ago

0.16.0

3 years ago

0.17.0

2 years ago

0.14.0

3 years ago

0.15.0

3 years ago

0.13.0

3 years ago

0.11.0

3 years ago

0.12.0

3 years ago

0.10.0

4 years ago

0.9.1

4 years ago

0.9.0

4 years ago

0.7.1-117

4 years ago

0.7.1-116

4 years ago

0.8.0-125

4 years ago

0.7.0

4 years ago

0.6.0

4 years ago

0.5.0

6 years ago

0.5.0-internal

6 years ago

0.4.0

6 years ago

0.3.0

6 years ago

0.3.0-2

6 years ago

0.3.0-1

6 years ago

0.3.0-0

6 years ago

0.2.0

7 years ago

0.1.1

7 years ago

0.1.0

7 years ago

0.1.0-0

7 years ago