From 99fd4befbea3176efc165e9dd9f6dd62cb57feff Mon Sep 17 00:00:00 2001 From: Toru Nagashima Date: Fri, 14 May 2021 15:54:06 +0900 Subject: [PATCH] =?UTF-8?q?=F0=9F=8E=A8=20use=20prettier?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .eslintrc.yml | 24 ++- .esmrc | 5 - .esmrc.json | 5 + .github/FUNDING.yml | 2 +- .nycrc | 5 - .nycrc.yml | 7 + .prettierrc.yml | 6 + .vscode/extensions.json | 4 +- .vscode/settings.json | 32 +++- docs/README.md | 2 +- docs/api/ast-utils.md | 176 ++++++++--------- docs/api/scope-utils.md | 281 ++++++++++++++-------------- docs/api/token-utils.md | 44 ++--- package.json | 7 +- rollup.config.js | 7 +- src/get-function-head-location.js | 4 +- src/get-static-value.js | 22 +-- src/has-side-effect.js | 8 +- src/is-parenthesized.js | 6 +- src/reference-tracker.js | 25 ++- test/find-variable.js | 18 +- test/get-function-head-location.js | 106 +++++------ test/get-function-name-with-kind.js | 136 +++++++------- test/get-innermost-scope.js | 39 ++-- test/get-property-name.js | 4 +- test/get-static-value.js | 17 +- test/get-string-if-constant.js | 2 +- test/has-side-effect.js | 8 +- test/is-parenthesized.js | 12 +- test/pattern-matcher.js | 18 +- test/reference-tracker.js | 54 +++--- test/token-predicate.js | 4 +- 32 files changed, 559 insertions(+), 531 deletions(-) delete mode 100644 .esmrc create mode 100644 .esmrc.json delete mode 100644 .nycrc create mode 100644 .nycrc.yml create mode 100644 .prettierrc.yml diff --git a/.eslintrc.yml b/.eslintrc.yml index abcafd7..91d3883 100644 --- a/.eslintrc.yml +++ b/.eslintrc.yml @@ -1,15 +1,19 @@ root: true extends: -- plugin:@mysticatea/es2015 + - plugin:@mysticatea/es2020 + +rules: + "@mysticatea/prettier": "off" overrides: -- files: - - src/**/*.js - - test/**/*.js - extends: plugin:@mysticatea/+modules - rules: - init-declarations: "off" - "@mysticatea/node/no-unsupported-features/es-syntax": - - error - - ignores: [modules] + - files: + - src/**/*.js + - test/**/*.js + extends: + - plugin:@mysticatea/+modules + rules: + init-declarations: "off" + "@mysticatea/node/no-unsupported-features/es-syntax": + - error + - ignores: [modules] diff --git a/.esmrc b/.esmrc deleted file mode 100644 index 92f1436..0000000 --- a/.esmrc +++ /dev/null @@ -1,5 +0,0 @@ -{ - "cache": true, - "debug": true, - "sourceMap": true -} diff --git a/.esmrc.json b/.esmrc.json new file mode 100644 index 0000000..be756c7 --- /dev/null +++ b/.esmrc.json @@ -0,0 +1,5 @@ +{ + "cache": true, + "debug": true, + "sourceMap": true +} diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml index ce763b1..334485e 100644 --- a/.github/FUNDING.yml +++ b/.github/FUNDING.yml @@ -1,2 +1,2 @@ github: -- mysticatea + - mysticatea diff --git a/.nycrc b/.nycrc deleted file mode 100644 index 9ca13b9..0000000 --- a/.nycrc +++ /dev/null @@ -1,5 +0,0 @@ -{ - "include": ["src/**/*.js"], - "reporter": ["lcov", "text-summary"], - "require": ["esm"] -} diff --git a/.nycrc.yml b/.nycrc.yml new file mode 100644 index 0000000..623c5b6 --- /dev/null +++ b/.nycrc.yml @@ -0,0 +1,7 @@ +include: + - src/**/*.js +reporter: + - lcov + - text-summary +require: + - esm diff --git a/.prettierrc.yml b/.prettierrc.yml new file mode 100644 index 0000000..e28d597 --- /dev/null +++ b/.prettierrc.yml @@ -0,0 +1,6 @@ +overrides: + - files: ["*.js"] + options: + tabWidth: 4 + semi: false + trailingComma: all diff --git a/.vscode/extensions.json b/.vscode/extensions.json index 12ffc20..1d7ac85 100644 --- a/.vscode/extensions.json +++ b/.vscode/extensions.json @@ -1,5 +1,3 @@ { - "recommendations": [ - "dbaeumer.vscode-eslint" - ] + "recommendations": ["dbaeumer.vscode-eslint", "esbenp.prettier-vscode"] } diff --git a/.vscode/settings.json b/.vscode/settings.json index 7952687..4b95f95 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,9 +1,27 @@ { - "[javascript]": { - "editor.formatOnSave": false, - "editor.formatOnType": false, - "editor.codeActionsOnSave": { - "source.fixAll": true - } - } + "[javascript]": { + "editor.defaultFormatter": "esbenp.prettier-vscode", + "editor.formatOnSave": true, + "editor.codeActionsOnSave": ["source.organizeImports", "source.fixAll"] + }, + "[json]": { + "editor.defaultFormatter": "esbenp.prettier-vscode", + "editor.formatOnSave": true, + "editor.codeActionsOnSave": [] + }, + "[jsonc]": { + "editor.defaultFormatter": "esbenp.prettier-vscode", + "editor.formatOnSave": true, + "editor.codeActionsOnSave": [] + }, + "[yaml]": { + "editor.defaultFormatter": "esbenp.prettier-vscode", + "editor.formatOnSave": true, + "editor.codeActionsOnSave": [] + }, + "[markdown]": { + "editor.defaultFormatter": "esbenp.prettier-vscode", + "editor.formatOnSave": true, + "editor.codeActionsOnSave": [] + } } diff --git a/docs/README.md b/docs/README.md index 1f85bdf..83313e2 100644 --- a/docs/README.md +++ b/docs/README.md @@ -25,7 +25,7 @@ npm install eslint-utils ## 📖 Usage ```js -const utils = require("eslint-utils") +const utils = require("eslint-utils"); // use it to define rules... ``` diff --git a/docs/api/ast-utils.md b/docs/api/ast-utils.md index be0fd11..4fe746d 100644 --- a/docs/api/ast-utils.md +++ b/docs/api/ast-utils.md @@ -1,11 +1,11 @@ # AST utilities ----- +--- ## getFunctionHeadLocation ```js -const loc = utils.getFunctionHeadLocation(node, sourceCode) +const loc = utils.getFunctionHeadLocation(node, sourceCode); ``` Get the proper location of a given function node to report. @@ -147,10 +147,10 @@ Get the proper location of a given function node to report. ### Parameters - Name | Type | Description -:-----|:-----|:------------ -node | Node | The function node to get the location. This should be any of `FunctionDeclaration`, `FunctionExpression`, and `ArrowFunctionExpression` node. -sourceCode | SourceCode | The source code object to get tokens. +| Name | Type | Description | +| :--------- | :--------- | :-------------------------------------------------------------------------------------------------------------------------------------------- | +| node | Node | The function node to get the location. This should be any of `FunctionDeclaration`, `FunctionExpression`, and `ArrowFunctionExpression` node. | +| sourceCode | SourceCode | The source code object to get tokens. | ### Return value @@ -179,12 +179,12 @@ module.exports = { } ``` ----- +--- ## getFunctionNameWithKind ```js -const name = utils.getFunctionNameWithKind(node) +const name = utils.getFunctionNameWithKind(node); ``` Get the name and kind of a given function node. @@ -274,10 +274,10 @@ Get the name and kind of a given function node. ### Parameters - Name | Type | Description -:-----|:-----|:------------ -node | Node | The function node to get the name and kind. This should be any of `FunctionDeclaration`, `FunctionExpression`, and `ArrowFunctionExpression` node. -sourceCode | SourceCode | Optional. The source code object to get the text of computed property keys. +| Name | Type | Description | +| :--------- | :--------- | :------------------------------------------------------------------------------------------------------------------------------------------------- | +| node | Node | The function node to get the name and kind. This should be any of `FunctionDeclaration`, `FunctionExpression`, and `ArrowFunctionExpression` node. | +| sourceCode | SourceCode | Optional. The source code object to get the text of computed property keys. | ### Return value @@ -306,13 +306,13 @@ module.exports = { } ``` ----- +--- ## getPropertyName ```js -const name = utils.getPropertyName(node) -const name = utils.getPropertyName(node, initialScope) +const name = utils.getPropertyName(node); +const name = utils.getPropertyName(node, initialScope); ``` Get the property name of a given property node. @@ -321,10 +321,10 @@ If the node is a computed property, this tries to compute the property name by t ### Parameters - Name | Type | Description -:-----|:-----|:------------ -node | Node | The node to get that name. This shuld be any of `MemberExpression`, `Property`, `MethodDefinition`, and `PropertyDefinition` node. -initialScope | Scope or undefined | Optional. The scope object to find variables. +| Name | Type | Description | +| :----------- | :----------------- | :--------------------------------------------------------------------------------------------------------------------------------- | +| node | Node | The node to get that name. This shuld be any of `MemberExpression`, `Property`, `MethodDefinition`, and `PropertyDefinition` node. | +| initialScope | Scope or undefined | Optional. The scope object to find variables. | ### Return value @@ -348,20 +348,20 @@ module.exports = { } ``` ----- +--- ## getStaticValue ```js -const ret1 = utils.getStaticValue(node) -const ret2 = utils.getStaticValue(node, initialScope) +const ret1 = utils.getStaticValue(node); +const ret2 = utils.getStaticValue(node, initialScope); ``` Get the value of a given node if it can decide the value statically. If the 2nd parameter `initialScope` was given, this function tries to resolve identifier references which are in the given node as much as possible. In the resolving way, it does on the assumption that built-in global objects have not been modified. -For example, it considers `Symbol.iterator`, ``String.raw`hello` ``, and `Object.freeze({a: 1}).a` as static. +For example, it considers `Symbol.iterator`, `` String.raw`hello` ``, and `Object.freeze({a: 1}).a` as static. For another complex example, this function can evaluate the following cases on AST: @@ -376,10 +376,10 @@ const aMap = Object.freeze({ ### Parameters - Name | Type | Description -:-----|:-----|:------------ -node | Node | The node to get that the value. -initialScope | Scope or undefined | Optional. The scope object to find variables. +| Name | Type | Description | +| :----------- | :----------------- | :-------------------------------------------- | +| node | Node | The node to get that the value. | +| initialScope | Scope or undefined | Optional. The scope object to find variables. | ### Return value @@ -408,13 +408,13 @@ module.exports = { } ``` ----- +--- ## getStringIfConstant ```js -const str1 = utils.getStringIfConstant(node) -const str2 = utils.getStringIfConstant(node, initialScope) +const str1 = utils.getStringIfConstant(node); +const str2 = utils.getStringIfConstant(node, initialScope); ``` Get the string value of a given node. @@ -424,22 +424,22 @@ I.e., this is the same as below: ```js function getStringIfConstant(node, initialScope) { - const evaluated = getStaticValue(node, initialScope) - return evaluated && String(evaluated.value) + const evaluated = getStaticValue(node, initialScope); + return evaluated && String(evaluated.value); } ``` ----- +--- ## hasSideEffect ```js -const ret = utils.hasSideEffect(node, sourceCode, options) +const ret = utils.hasSideEffect(node, sourceCode, options); ``` Check whether a given node has any side effect or not. -The side effect means that it *may* modify a certain variable or object member. This function considers the node which contains the following types as the node which has side effects: +The side effect means that it _may_ modify a certain variable or object member. This function considers the node which contains the following types as the node which has side effects: - `AssignmentExpression` - `AwaitExpression` @@ -450,23 +450,23 @@ The side effect means that it *may* modify a certain variable or object member. - `UpdateExpression` - `YieldExpression` - When `options.considerGetters` is `true`: - - `MemberExpression` + - `MemberExpression` - When `options.considerImplicitTypeConversion` is `true`: - - `BinaryExpression` (`[operator = "==" | "!=" | "<" | "<=" | ">" | ">=" | "<<" | ">>" | ">>>" | "+" | "-" | "*" | "/" | "%" | "|" | "^" | "&" | "in"]`) - - `MemberExpression` (`[computed = true]`) - - `MethodDefinition` (`[computed = true]`) - - `Property` (`[computed = true]`) - - `PropertyDefinition` (`[computed = true]`) - - `UnaryExpression` (`[operator = "-" | "+" | "!" | "~"]`) + - `BinaryExpression` (`[operator = "==" | "!=" | "<" | "<=" | ">" | ">=" | "<<" | ">>" | ">>>" | "+" | "-" | "*" | "/" | "%" | "|" | "^" | "&" | "in"]`) + - `MemberExpression` (`[computed = true]`) + - `MethodDefinition` (`[computed = true]`) + - `Property` (`[computed = true]`) + - `PropertyDefinition` (`[computed = true]`) + - `UnaryExpression` (`[operator = "-" | "+" | "!" | "~"]`) ### Parameters - Name | Type | Description -:-----|:-----|:------------ -node | Node | The node to check. -sourceCode | SourceCode | The source code object to get visitor keys. -options.considerGetters | boolean | Default is `false`. If `true` then it considers member accesses as the node which has side effects. -options.considerImplicitTypeConversion | boolean | Default is `false`. If `true` then it considers implicit type conversion as the node which has side effects. +| Name | Type | Description | +| :------------------------------------- | :--------- | :----------------------------------------------------------------------------------------------------------- | +| node | Node | The node to check. | +| sourceCode | SourceCode | The source code object to get visitor keys. | +| options.considerGetters | boolean | Default is `false`. If `true` then it considers member accesses as the node which has side effects. | +| options.considerImplicitTypeConversion | boolean | Default is `false`. If `true` then it considers implicit type conversion as the node which has side effects. | ### Return value @@ -492,13 +492,13 @@ module.exports = { } ``` ----- +--- ## isParenthesized ```js -const ret1 = utils.isParenthesized(times, node, sourceCode) -const ret2 = utils.isParenthesized(node, sourceCode) +const ret1 = utils.isParenthesized(times, node, sourceCode); +const ret2 = utils.isParenthesized(node, sourceCode); ``` Check whether a given node is parenthesized or not. @@ -509,29 +509,35 @@ This function detects it correctly even if it's parenthesized by specific syntax // those `a` are not parenthesized. f(a); new C(a); -if (a) {} -switch (a) {} +if (a) { +} +switch (a) { +} while (a) {} do {} while (a); -with (a) {} +with (a) { +} // those `b` are parenthesized. -f((b)); -new C((b)); -if ((b)) {} -switch ((b)) {} -while ((b)) {} -do {} while ((b)); -with ((b)) {} +f(b); +new C(b); +if (b) { +} +switch (b) { +} +while (b) {} +do {} while (b); +with (b) { +} ``` ### Parameters - Name | Type | Description -:-----|:-----|:------------ -times | number | Optional. The number of redundant parenthesized. Default is `1`. -node | Node | The node to check. -sourceCode | SourceCode | The source code object to get tokens. +| Name | Type | Description | +| :--------- | :--------- | :--------------------------------------------------------------- | +| times | number | Optional. The number of redundant parenthesized. Default is `1`. | +| node | Node | The node to check. | +| sourceCode | SourceCode | The source code object to get tokens. | ### Return value @@ -559,12 +565,12 @@ module.exports = { } ``` ----- +--- ## PatternMatcher class ```js -const matcher = new utils.PatternMatcher(pattern, options) +const matcher = new utils.PatternMatcher(pattern, options); ``` The class to find a pattern in strings as handling escape sequences. @@ -573,24 +579,24 @@ It ignores the found pattern if it's escaped with `\`. ### Parameters - Name | Type | Description -:-----|:-----|:------------ -pattern | RegExp | The regular expression pattern to find. -options.escaped | boolean | Optional. Default is `false`. If `true` then this matches to escaped patterns. +| Name | Type | Description | +| :-------------- | :------ | :----------------------------------------------------------------------------- | +| pattern | RegExp | The regular expression pattern to find. | +| options.escaped | boolean | Optional. Default is `false`. If `true` then this matches to escaped patterns. | ## matcher.execAll ```js -const iterator = matcher.execAll(str) +const iterator = matcher.execAll(str); ``` Iterate all matched parts in a given string. ### Parameters - Name | Type | Description -:-----|:-----|:------------ -str | string | The string to find this pattern. +| Name | Type | Description | +| :--- | :----- | :------------------------------- | +| str | string | The string to find this pattern. | ### Return value @@ -626,16 +632,16 @@ module.exports = { ## matcher.test ```js -const matched = matcher.test(str) +const matched = matcher.test(str); ``` Check whether this pattern matches a given string or not. ### Parameters - Name | Type | Description -:-----|:-----|:------------ -str | string | The string to find this pattern. +| Name | Type | Description | +| :--- | :----- | :------------------------------- | +| str | string | The string to find this pattern. | ### Return value @@ -667,17 +673,17 @@ module.exports = { ## matcher[Symbol.replace] ```js -const replacedStr = str.replace(matcher, replacer) +const replacedStr = str.replace(matcher, replacer); ``` Replace all matched parts by a given replacer. ### Parameters - Name | Type | Description -:-----|:-----|:------------ -str | string | The string to be replaced. -replacer | string or function | The string or function to replace each matched part. This is the same as the 2nd parameter of [String.prototype.replace](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace). +| Name | Type | Description | +| :------- | :----------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| str | string | The string to be replaced. | +| replacer | string or function | The string or function to replace each matched part. This is the same as the 2nd parameter of [String.prototype.replace](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace). | ### Return value diff --git a/docs/api/scope-utils.md b/docs/api/scope-utils.md index 88be37d..3507db9 100644 --- a/docs/api/scope-utils.md +++ b/docs/api/scope-utils.md @@ -3,17 +3,17 @@ ## findVariable ```js -const variable = utils.findVariable(initialScope, name) +const variable = utils.findVariable(initialScope, name); ``` Get the variable of a given name. ### Parameters - Name | Type | Description -:-----|:-----|:------------ -initialScope | Scope | The scope object to start finding variables. -name | string or Node | The variable name to find. This can be an Identifier node. +| Name | Type | Description | +| :----------- | :------------- | :--------------------------------------------------------- | +| initialScope | Scope | The scope object to start finding variables. | +| name | string or Node | The variable name to find. This can be an Identifier node. | ### Return value @@ -35,20 +35,21 @@ module.exports = { }, } ``` + ## getInnermostScope ```js -const scope = utils.getInnermostScope(initialScope, node) +const scope = utils.getInnermostScope(initialScope, node); ``` Get the innermost scope which contains a given node. ### Parameters - Name | Type | Description -:-----|:-----|:------------ -initialScope | Scope | The scope to start finding. -node | Node | The node to find the innermost scope. +| Name | Type | Description | +| :----------- | :---- | :------------------------------------ | +| initialScope | Scope | The scope to start finding. | +| node | Node | The node to find the innermost scope. | ### Return value @@ -76,7 +77,7 @@ module.exports = { ## ReferenceTracker class ```js -const tracker = new utils.ReferenceTracker(globalScope, options) +const tracker = new utils.ReferenceTracker(globalScope, options); ``` The tracker for references. @@ -84,16 +85,16 @@ This provides reference tracking for global variables, CommonJS modules, and ES ### Parameters - Name | Type | Description -:-----|:-----|:------------ -globalScope | Scope | The global scope. -options.mode | `"strict"` or `"legacy"` | The mode which determines how the `tracker.iterateEsmReferences()` method scans CommonJS modules. If this is `"strict"`, the method binds CommonJS modules to the default export. Otherwise, the method binds CommonJS modules to both the default export and named exports. Optional. Default is `"strict"`. -options.globalObjectNames | string[] | The name list of Global Object. Optional. Default is `["global", "globalThis", "self", "window"]`. +| Name | Type | Description | +| :------------------------ | :----------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| globalScope | Scope | The global scope. | +| options.mode | `"strict"` or `"legacy"` | The mode which determines how the `tracker.iterateEsmReferences()` method scans CommonJS modules. If this is `"strict"`, the method binds CommonJS modules to the default export. Otherwise, the method binds CommonJS modules to both the default export and named exports. Optional. Default is `"strict"`. | +| options.globalObjectNames | string[] | The name list of Global Object. Optional. Default is `["global", "globalThis", "self", "window"]`. | ## tracker.iterateGlobalReferences ```js -const it = tracker.iterateGlobalReferences(traceMap) +const it = tracker.iterateGlobalReferences(traceMap); ``` Iterate the references that the given `traceMap` determined. @@ -101,65 +102,67 @@ This method starts to search from global variables. ### Parameters - Name | Type | Description -:-----|:-----|:------------ -traceMap | object | The object which determines global variables and properties it iterates. +| Name | Type | Description | +| :------- | :----- | :----------------------------------------------------------------------- | +| traceMap | object | The object which determines global variables and properties it iterates. | ### Return value The Iterator which iterates the reference of global variables. Every reference is the object that has the following properties. - Name | Type | Description -:-----|:-----|:------------ -node | Node | The node of the reference. -path | string[] | The path of the reference. For example, if it's the access of `console.log` then `["console", "log"]`. -type | symbol | The reference type. If this is `ReferenceTracker.READ` then it read the variable (or property). If this is `ReferenceTracker.CALL` then it called the variable (or property). If this is `ReferenceTracker.CONSTRUCT` then it called the variable (or property) with the `new` operator. -entry | any | The property value of any of `ReferenceTracker.READ`, `ReferenceTracker.CALL`, and `ReferenceTracker.CONSTRUCT`. +| Name | Type | Description | +| :---- | :------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| node | Node | The node of the reference. | +| path | string[] | The path of the reference. For example, if it's the access of `console.log` then `["console", "log"]`. | +| type | symbol | The reference type. If this is `ReferenceTracker.READ` then it read the variable (or property). If this is `ReferenceTracker.CALL` then it called the variable (or property). If this is `ReferenceTracker.CONSTRUCT` then it called the variable (or property) with the `new` operator. | +| entry | any | The property value of any of `ReferenceTracker.READ`, `ReferenceTracker.CALL`, and `ReferenceTracker.CONSTRUCT`. | ### Examples ```js -const { ReferenceTracker } = require("eslint-utils") +const { ReferenceTracker } = require("eslint-utils"); module.exports = { - meta: {}, - create(context) { - return { - "Program:exit"() { - const tracker = new ReferenceTracker(context.getScope()) - const traceMap = { - // Find `console.log`, `console.info`, `console.warn`, and `console.error`. - console: { - log: { [ReferenceTracker.READ]: true }, - info: { [ReferenceTracker.READ]: true }, - warn: { [ReferenceTracker.READ]: true }, - error: { [ReferenceTracker.READ]: true }, - }, - // Find `Buffer()` and `new Buffer()`. - Buffer: { - [ReferenceTracker.CALL]: true, - [ReferenceTracker.CONSTRUCT]: true, - }, - } - - for (const { node, path } of tracker.iterateGlobalReferences(traceMap)) { - context.report({ - node, - message: "disallow {{name}}.", - data: { name: path.join(".") }, - }) - } - }, + meta: {}, + create(context) { + return { + "Program:exit"() { + const tracker = new ReferenceTracker(context.getScope()); + const traceMap = { + // Find `console.log`, `console.info`, `console.warn`, and `console.error`. + console: { + log: { [ReferenceTracker.READ]: true }, + info: { [ReferenceTracker.READ]: true }, + warn: { [ReferenceTracker.READ]: true }, + error: { [ReferenceTracker.READ]: true }, + }, + // Find `Buffer()` and `new Buffer()`. + Buffer: { + [ReferenceTracker.CALL]: true, + [ReferenceTracker.CONSTRUCT]: true, + }, + }; + + for (const { node, path } of tracker.iterateGlobalReferences( + traceMap + )) { + context.report({ + node, + message: "disallow {{name}}.", + data: { name: path.join(".") }, + }); } - }, -} + }, + }; + }, +}; ``` ## tracker.iterateCjsReferences ```js -const it = tracker.iterateCjsReferences(traceMap) +const it = tracker.iterateCjsReferences(traceMap); ``` Iterate the references that the given `traceMap` determined. @@ -167,66 +170,66 @@ This method starts to search from `require()` expression. ### Parameters - Name | Type | Description -:-----|:-----|:------------ -traceMap | object | The object which determines modules it iterates. +| Name | Type | Description | +| :------- | :----- | :----------------------------------------------- | +| traceMap | object | The object which determines modules it iterates. | ### Return value The Iterator which iterates the reference of modules. Every reference is the object that has the following properties. - Name | Type | Description -:-----|:-----|:------------ -node | Node | The node of the reference. -path | string[] | The path of the reference. For example, if it's the access of `fs.exists` then `["fs", "exists"]`. -type | symbol | The reference type. If this is `ReferenceTracker.READ` then it read the variable (or property). If this is `ReferenceTracker.CALL` then it called the variable (or property). If this is `ReferenceTracker.CONSTRUCT` then it called the variable (or property) with the `new` operator. -entry | any | The property value of any of `ReferenceTracker.READ`, `ReferenceTracker.CALL`, and `ReferenceTracker.CONSTRUCT`. +| Name | Type | Description | +| :---- | :------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| node | Node | The node of the reference. | +| path | string[] | The path of the reference. For example, if it's the access of `fs.exists` then `["fs", "exists"]`. | +| type | symbol | The reference type. If this is `ReferenceTracker.READ` then it read the variable (or property). If this is `ReferenceTracker.CALL` then it called the variable (or property). If this is `ReferenceTracker.CONSTRUCT` then it called the variable (or property) with the `new` operator. | +| entry | any | The property value of any of `ReferenceTracker.READ`, `ReferenceTracker.CALL`, and `ReferenceTracker.CONSTRUCT`. | ### Examples ```js -const { ReferenceTracker } = require("eslint-utils") +const { ReferenceTracker } = require("eslint-utils"); module.exports = { - meta: {}, - create(context) { - return { - "Program:exit"() { - const tracker = new ReferenceTracker(context.getScope()) - const traceMap = { - // Find `Buffer()` and `new Buffer()` of `buffer` module. - buffer: { - Buffer: { - [ReferenceTracker.CALL]: true, - [ReferenceTracker.CONSTRUCT]: true, - }, - }, - // Find `exists` of `fs` module. - fs: { - exists: { - [ReferenceTracker.READ]: true, - }, - }, - } - - for (const { node, path } of tracker.iterateCjsReferences(traceMap)) { - context.report({ - node, - message: "disallow {{name}}.", - data: { name: path.join(".") }, - }) - } + meta: {}, + create(context) { + return { + "Program:exit"() { + const tracker = new ReferenceTracker(context.getScope()); + const traceMap = { + // Find `Buffer()` and `new Buffer()` of `buffer` module. + buffer: { + Buffer: { + [ReferenceTracker.CALL]: true, + [ReferenceTracker.CONSTRUCT]: true, }, + }, + // Find `exists` of `fs` module. + fs: { + exists: { + [ReferenceTracker.READ]: true, + }, + }, + }; + + for (const { node, path } of tracker.iterateCjsReferences(traceMap)) { + context.report({ + node, + message: "disallow {{name}}.", + data: { name: path.join(".") }, + }); } - }, -} + }, + }; + }, +}; ``` ## tracker.iterateEsmReferences ```js -const it = tracker.iterateEsmReferences(traceMap) +const it = tracker.iterateEsmReferences(traceMap); ``` Iterate the references that the given `traceMap` determined. @@ -234,58 +237,58 @@ This method starts to search from `import`/`export` declarations. ### Parameters - Name | Type | Description -:-----|:-----|:------------ -traceMap | object | The object which determines modules it iterates. +| Name | Type | Description | +| :------- | :----- | :----------------------------------------------- | +| traceMap | object | The object which determines modules it iterates. | ### Return value The Iterator which iterates the reference of modules. Every reference is the object that has the following properties. - Name | Type | Description -:-----|:-----|:------------ -node | Node | The node of the reference. -path | string[] | The path of the reference. For example, if it's the access of `fs.exists` then `["fs", "exists"]`. -type | symbol | The reference type. If this is `ReferenceTracker.READ` then it read the variable (or property). If this is `ReferenceTracker.CALL` then it called the variable (or property). If this is `ReferenceTracker.CONSTRUCT` then it called the variable (or property) with the `new` operator. -entry | any | The property value of any of `ReferenceTracker.READ`, `ReferenceTracker.CALL`, and `ReferenceTracker.CONSTRUCT`. +| Name | Type | Description | +| :---- | :------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| node | Node | The node of the reference. | +| path | string[] | The path of the reference. For example, if it's the access of `fs.exists` then `["fs", "exists"]`. | +| type | symbol | The reference type. If this is `ReferenceTracker.READ` then it read the variable (or property). If this is `ReferenceTracker.CALL` then it called the variable (or property). If this is `ReferenceTracker.CONSTRUCT` then it called the variable (or property) with the `new` operator. | +| entry | any | The property value of any of `ReferenceTracker.READ`, `ReferenceTracker.CALL`, and `ReferenceTracker.CONSTRUCT`. | ### Examples ```js -const { ReferenceTracker } = require("eslint-utils") +const { ReferenceTracker } = require("eslint-utils"); module.exports = { - meta: {}, - create(context) { - return { - "Program:exit"() { - const tracker = new ReferenceTracker(context.getScope()) - const traceMap = { - // Find `Buffer()` and `new Buffer()` of `buffer` module. - buffer: { - Buffer: { - [ReferenceTracker.CALL]: true, - [ReferenceTracker.CONSTRUCT]: true, - }, - }, - // Find `exists` of `fs` module. - fs: { - exists: { - [ReferenceTracker.READ]: true, - }, - }, - } - - for (const { node, path } of tracker.iterateEsmReferences(traceMap)) { - context.report({ - node, - message: "disallow {{name}}.", - data: { name: path.join(".") }, - }) - } + meta: {}, + create(context) { + return { + "Program:exit"() { + const tracker = new ReferenceTracker(context.getScope()); + const traceMap = { + // Find `Buffer()` and `new Buffer()` of `buffer` module. + buffer: { + Buffer: { + [ReferenceTracker.CALL]: true, + [ReferenceTracker.CONSTRUCT]: true, + }, + }, + // Find `exists` of `fs` module. + fs: { + exists: { + [ReferenceTracker.READ]: true, }, + }, + }; + + for (const { node, path } of tracker.iterateEsmReferences(traceMap)) { + context.report({ + node, + message: "disallow {{name}}.", + data: { name: path.join(".") }, + }); } - }, -} + }, + }; + }, +}; ``` diff --git a/docs/api/token-utils.md b/docs/api/token-utils.md index 1a252ce..7ee31bc 100644 --- a/docs/api/token-utils.md +++ b/docs/api/token-utils.md @@ -3,8 +3,8 @@ ## isArrowToken / isNotArrowToken ```js -utils.isArrowToken(token) -utils.isNotArrowToken(token) +utils.isArrowToken(token); +utils.isNotArrowToken(token); ``` Check whether a given token is a `=>` token or not. @@ -31,8 +31,8 @@ module.exports = { ## isClosingBraceToken / isNotClosingBraceToken ```js -utils.isClosingBraceToken(token) -utils.isNotClosingBraceToken(token) +utils.isClosingBraceToken(token); +utils.isNotClosingBraceToken(token); ``` Check whether a given token is a `}` token or not. @@ -40,8 +40,8 @@ Check whether a given token is a `}` token or not. ## isClosingBracketToken / isNotClosingBracketToken ```js -utils.isClosingBracketToken(token) -utils.isNotClosingBracketToken(token) +utils.isClosingBracketToken(token); +utils.isNotClosingBracketToken(token); ``` Check whether a given token is a `]` token or not. @@ -49,8 +49,8 @@ Check whether a given token is a `]` token or not. ## isClosingParenToken / isNotClosingParenToken ```js -utils.isClosingParenToken(token) -utils.isNotClosingParenToken(token) +utils.isClosingParenToken(token); +utils.isNotClosingParenToken(token); ``` Check whether a given token is a `)` token or not. @@ -58,8 +58,8 @@ Check whether a given token is a `)` token or not. ## isColonToken / isNotColonToken ```js -utils.isColonToken(token) -utils.isNotColonToken(token) +utils.isColonToken(token); +utils.isNotColonToken(token); ``` Check whether a given token is a `:` token or not. @@ -67,8 +67,8 @@ Check whether a given token is a `:` token or not. ## isCommaToken / isNotCommaToken ```js -utils.isCommaToken(token) -utils.isNotCommaToken(token) +utils.isCommaToken(token); +utils.isNotCommaToken(token); ``` Check whether a given token is a `,` token or not. @@ -76,8 +76,8 @@ Check whether a given token is a `,` token or not. ## isCommentToken / isNotCommentToken ```js -utils.isCommentToken(token) -utils.isNotCommentToken(token) +utils.isCommentToken(token); +utils.isNotCommentToken(token); ``` Check whether a given token is a comment token or not. @@ -85,8 +85,8 @@ Check whether a given token is a comment token or not. ## isOpeningBraceToken / isNotOpeningBraceToken ```js -utils.isOpeningBraceToken(token) -utils.isNotOpeningBraceToken(token) +utils.isOpeningBraceToken(token); +utils.isNotOpeningBraceToken(token); ``` Check whether a given token is a `{` token or not. @@ -94,8 +94,8 @@ Check whether a given token is a `{` token or not. ## isOpeningBracketToken / isNotOpeningBracketToken ```js -utils.isOpeningBracketToken(token) -utils.isNotOpeningBracketToken(token) +utils.isOpeningBracketToken(token); +utils.isNotOpeningBracketToken(token); ``` Check whether a given token is a `[` token or not. @@ -103,8 +103,8 @@ Check whether a given token is a `[` token or not. ## isOpeningParenToken / isNotOpeningParenToken ```js -utils.isOpeningParenToken(token) -utils.isNotOpeningParenToken(token) +utils.isOpeningParenToken(token); +utils.isNotOpeningParenToken(token); ``` Check whether a given token is a `(` token or not. @@ -112,8 +112,8 @@ Check whether a given token is a `(` token or not. ## isSemicolonToken / isNotSemicolonToken ```js -utils.isSemicolonToken(token) -utils.isNotSemicolonToken(token) +utils.isSemicolonToken(token); +utils.isNotSemicolonToken(token); ``` Check whether a given token is a `;` token or not. diff --git a/package.json b/package.json index 286e715..0439b2b 100644 --- a/package.json +++ b/package.json @@ -32,6 +32,7 @@ "npm-run-all": "^4.1.5", "nyc": "^14.1.1", "opener": "^1.5.1", + "prettier": "~2.3.0", "rimraf": "^3.0.0", "rollup": "^1.25.0", "rollup-plugin-sourcemaps": "^0.4.2", @@ -50,8 +51,10 @@ "coverage": "opener ./coverage/lcov-report/index.html", "docs:build": "vuepress build docs", "docs:watch": "vuepress dev docs", - "lint": "eslint src test", - "test": "run-s lint build test:mocha", + "format": "npm run -s format:prettier -- --write", + "format:prettier": "prettier docs/.vuepress/config.js src/**/*.js test/**/*.js rollup.config.js .vscode/*.json *.json .github/**/*.yml *.yml docs/**/*.md *.md", + "lint": "eslint docs/.vuepress/config.js src test rollup.config.js", + "test": "run-s \"format:prettier -- --check\" lint build test:mocha", "test:mocha": "nyc mocha --reporter dot \"test/*.js\"", "preversion": "npm test && npm run -s build", "postversion": "git push && git push --tags", diff --git a/rollup.config.js b/rollup.config.js index 069f8e1..f8ec7bb 100644 --- a/rollup.config.js +++ b/rollup.config.js @@ -3,6 +3,7 @@ * See LICENSE file in root directory for full license. */ import sourcemaps from "rollup-plugin-sourcemaps" +import packageInfo from "./package.json" /** * Define the output configuration. @@ -13,14 +14,14 @@ function config(ext) { return { input: "src/index.js", output: { + exports: ext === ".mjs" ? undefined : "named", file: `index${ext}`, format: ext === ".mjs" ? "es" : "cjs", sourcemap: true, - banner: - "/*! @author Toru Nagashima */", + banner: "/*! @author Toru Nagashima */", }, plugins: [sourcemaps()], - external: Object.keys(require("./package.json").dependencies), + external: Object.keys(packageInfo.dependencies), } } diff --git a/src/get-function-head-location.js b/src/get-function-head-location.js index 956b8c4..4f45481 100644 --- a/src/get-function-head-location.js +++ b/src/get-function-head-location.js @@ -41,7 +41,7 @@ export function getFunctionHeadLocation(node, sourceCode) { } return { - start: Object.assign({}, start), - end: Object.assign({}, end), + start: { ...start }, + end: { ...end }, } } diff --git a/src/get-static-value.js b/src/get-static-value.js index a169832..f3a3643 100644 --- a/src/get-static-value.js +++ b/src/get-static-value.js @@ -1,4 +1,4 @@ -/* globals BigInt, globalThis, global, self, window */ +/* globals globalThis, global, self, window */ import { findVariable } from "./find-variable" @@ -61,7 +61,7 @@ const builtinNames = Object.freeze( "unescape", "WeakMap", "WeakSet", - ]) + ]), ) const callAllowed = new Set( [ @@ -79,8 +79,8 @@ const callAllowed = new Set( isNaN, isPrototypeOf, ...Object.getOwnPropertyNames(Math) - .map(k => Math[k]) - .filter(f => typeof f === "function"), + .map((k) => Math[k]) + .filter((f) => typeof f === "function"), Number, Number.isFinite, Number.isNaN, @@ -104,7 +104,7 @@ const callAllowed = new Set( Symbol.for, Symbol.keyFor, unescape, - ].filter(f => typeof f === "function") + ].filter((f) => typeof f === "function"), ) const callPassThrough = new Set([ Object.freeze, @@ -262,7 +262,7 @@ const operations = Object.freeze({ } const property = getStaticPropertyNameValue( calleeNode, - initialScope + initialScope, ) if (property != null) { @@ -419,7 +419,7 @@ const operations = Object.freeze({ } const key = getStaticPropertyNameValue( propertyNode, - initialScope + initialScope, ) const value = getStaticValueR(propertyNode.value, initialScope) if (key == null || value == null) { @@ -432,7 +432,7 @@ const operations = Object.freeze({ ) { const argument = getStaticValueR( propertyNode.argument, - initialScope + initialScope, ) if (argument == null) { return null @@ -455,13 +455,13 @@ const operations = Object.freeze({ const tag = getStaticValueR(node.tag, initialScope) const expressions = getElementValues( node.quasi.expressions, - initialScope + initialScope, ) if (tag != null && expressions != null) { const func = tag.value - const strings = node.quasi.quasis.map(q => q.value.cooked) - strings.raw = node.quasi.quasis.map(q => q.value.raw) + const strings = node.quasi.quasis.map((q) => q.value.cooked) + strings.raw = node.quasi.quasis.map((q) => q.value.raw) if (func === String.raw) { return { value: func(strings, ...expressions) } diff --git a/src/has-side-effect.js b/src/has-side-effect.js index 4063184..188f1ca 100644 --- a/src/has-side-effect.js +++ b/src/has-side-effect.js @@ -20,7 +20,7 @@ const typeConversionBinaryOps = Object.freeze( "^", "&", "in", - ]) + ]), ) const typeConversionUnaryOps = Object.freeze(new Set(["-", "+", "!", "~"])) @@ -164,7 +164,7 @@ const visitor = Object.freeze( YieldExpression() { return true }, - }) + }), ) /** @@ -180,11 +180,11 @@ const visitor = Object.freeze( export function hasSideEffect( node, sourceCode, - { considerGetters = false, considerImplicitTypeConversion = false } = {} + { considerGetters = false, considerImplicitTypeConversion = false } = {}, ) { return visitor.$visit( node, { considerGetters, considerImplicitTypeConversion }, - sourceCode.visitorKeys || evk.KEYS + sourceCode.visitorKeys || evk.KEYS, ) } diff --git a/src/is-parenthesized.js b/src/is-parenthesized.js index 45563a4..69ec3a3 100644 --- a/src/is-parenthesized.js +++ b/src/is-parenthesized.js @@ -16,7 +16,7 @@ function getParentSyntaxParen(node, sourceCode) { if (parent.arguments.length === 1 && parent.arguments[0] === node) { return sourceCode.getTokenAfter( parent.callee, - isOpeningParenToken + isOpeningParenToken, ) } return null @@ -25,7 +25,7 @@ function getParentSyntaxParen(node, sourceCode) { if (parent.test === node) { return sourceCode.getTokenAfter( parent.body, - isOpeningParenToken + isOpeningParenToken, ) } return null @@ -76,7 +76,7 @@ function getParentSyntaxParen(node, sourceCode) { export function isParenthesized( timesOrNode, nodeOrSourceCode, - optionalSourceCode + optionalSourceCode, ) { let times, node, sourceCode, maybeLeftParen, maybeRightParen if (typeof timesOrNode === "number") { diff --git a/src/reference-tracker.js b/src/reference-tracker.js index f88e0e3..faa7130 100644 --- a/src/reference-tracker.js +++ b/src/reference-tracker.js @@ -21,7 +21,7 @@ function isModifiedGlobal(variable) { return ( variable == null || variable.defs.length !== 0 || - variable.references.some(r => r.isWrite()) + variable.references.some((r) => r.isWrite()) ) } @@ -65,7 +65,7 @@ export class ReferenceTracker { { mode = "strict", globalObjectNames = ["global", "globalThis", "self", "window"], - } = {} + } = {}, ) { this.variableStack = [] this.globalScope = globalScope @@ -92,7 +92,7 @@ export class ReferenceTracker { variable, path, nextTraceMap, - true + true, ) } @@ -108,7 +108,7 @@ export class ReferenceTracker { variable, path, traceMap, - false + false, ) } } @@ -185,11 +185,8 @@ export class ReferenceTracker { esm ? nextTraceMap : this.mode === "legacy" - ? Object.assign( - { default: nextTraceMap }, - nextTraceMap - ) - : { default: nextTraceMap } + ? { default: nextTraceMap, ...nextTraceMap } + : { default: nextTraceMap }, ) if (esm) { @@ -275,7 +272,7 @@ export class ReferenceTracker { yield* this._iteratePropertyReferences( parent, path, - nextTraceMap + nextTraceMap, ) } return @@ -332,7 +329,7 @@ export class ReferenceTracker { variable, path, traceMap, - false + false, ) } return @@ -358,7 +355,7 @@ export class ReferenceTracker { yield* this._iterateLhsReferences( property.value, nextPath, - nextTraceMap + nextTraceMap, ) } return @@ -401,7 +398,7 @@ export class ReferenceTracker { findVariable(this.globalScope, specifierNode.local), path, nextTraceMap, - false + false, ) return @@ -412,7 +409,7 @@ export class ReferenceTracker { findVariable(this.globalScope, specifierNode.local), path, traceMap, - false + false, ) return } diff --git a/test/find-variable.js b/test/find-variable.js index d198607..6d884e6 100644 --- a/test/find-variable.js +++ b/test/find-variable.js @@ -7,7 +7,7 @@ describe("The 'findVariable' function", () => { const linter = new eslint.Linter() let variable = null - linter.defineRule("test", context => ({ + linter.defineRule("test", (context) => ({ [selector](node) { variable = findVariable(context.getScope(), withString || node) }, @@ -24,21 +24,21 @@ describe("The 'findVariable' function", () => { it("from the same scope.", () => { const variable = getVariable( "let a; foo(a)", - "CallExpression Identifier[name='a']" + "CallExpression Identifier[name='a']", ) assert.strictEqual(variable.name, "a") }) it("from nested blocks.", () => { const variable = getVariable( "let a; if (b) { foo(a) }", - "CallExpression Identifier[name='a']" + "CallExpression Identifier[name='a']", ) assert.strictEqual(variable.name, "a") }) it("from function blocks.", () => { const variable = getVariable( "let a; function f() { foo(a) }", - "CallExpression Identifier[name='a']" + "CallExpression Identifier[name='a']", ) assert.strictEqual(variable.name, "a") }) @@ -49,7 +49,7 @@ describe("The 'findVariable' function", () => { const variable = getVariable( "let a; foo(a)", "CallExpression Identifier[name='a']", - "a" + "a", ) assert.strictEqual(variable.name, "a") }) @@ -57,7 +57,7 @@ describe("The 'findVariable' function", () => { const variable = getVariable( "let a; if (b) { foo(a) }", "CallExpression Identifier[name='a']", - "a" + "a", ) assert.strictEqual(variable.name, "a") }) @@ -65,7 +65,7 @@ describe("The 'findVariable' function", () => { const variable = getVariable( "let a; function f() { foo(a) }", "CallExpression Identifier[name='a']", - "a" + "a", ) assert.strictEqual(variable.name, "a") }) @@ -75,7 +75,7 @@ describe("The 'findVariable' function", () => { const variable = getVariable( "let a; function f() { foo(a) }", "CallExpression Identifier[name='a']", - "Object" + "Object", ) assert.strictEqual(variable.name, "Object") }) @@ -84,7 +84,7 @@ describe("The 'findVariable' function", () => { const variable = getVariable( "let a; function f() { foo(a) }", "CallExpression Identifier[name='a']", - "x" + "x", ) assert.strictEqual(variable, null) }) diff --git a/test/get-function-head-location.js b/test/get-function-head-location.js index 575819a..885f27f 100644 --- a/test/get-function-head-location.js +++ b/test/get-function-head-location.js @@ -4,53 +4,51 @@ import semver from "semver" import { getFunctionHeadLocation } from "../src/" describe("The 'getFunctionHeadLocation' function", () => { - const expectedResults = Object.assign( - { - "function foo() {}": [0, 12], - "(function foo() {})": [1, 13], - "(function() {})": [1, 9], - "function* foo() {}": [0, 13], - "(function* foo() {})": [1, 14], - "(function*() {})": [1, 10], - "() => {}": [3, 5], - "async () => {}": [9, 11], - "({ foo: function foo() {} })": [3, 20], - "({ foo: function() {} })": [3, 16], - "({ foo: () => {} })": [11, 13], - "({ ['foo']: function() {} })": [3, 20], - "({ [foo]: function() {} })": [3, 18], - "({ foo() {} })": [3, 6], - "({ foo: function* foo() {} })": [3, 21], - "({ foo: function*() {} })": [3, 17], - "({ ['foo']: function*() {} })": [3, 21], - "({ [foo]: function*() {} })": [3, 19], - "({ *foo() {} })": [3, 7], - "({ foo: async function foo() {} })": [3, 26], - "({ foo: async function() {} })": [3, 22], - "({ ['foo']: async function() {} })": [3, 26], - "({ [foo]: async function() {} })": [3, 24], - "({ async foo() {} })": [3, 12], - "({ get foo() {} })": [3, 10], - "({ set foo(a) {} })": [3, 10], - "class A { constructor() {} }": [10, 21], - "class A { foo() {} }": [10, 13], - "class A { *foo() {} }": [10, 14], - "class A { async foo() {} }": [10, 19], - "class A { ['foo']() {} }": [10, 17], - "class A { *['foo']() {} }": [10, 18], - "class A { async ['foo']() {} }": [10, 23], - "class A { [foo]() {} }": [10, 15], - "class A { *[foo]() {} }": [10, 16], - "class A { async [foo]() {} }": [10, 21], - "class A { get foo() {} }": [10, 17], - "class A { set foo(a) {} }": [10, 17], - "class A { static foo() {} }": [10, 20], - "class A { static *foo() {} }": [10, 21], - "class A { static async foo() {} }": [10, 26], - "class A { static get foo() {} }": [10, 24], - "class A { static set foo(a) {} }": [10, 24], - }, - semver.gte(eslint.Linter.version, "7.0.0") + const expectedResults = { + "function foo() {}": [0, 12], + "(function foo() {})": [1, 13], + "(function() {})": [1, 9], + "function* foo() {}": [0, 13], + "(function* foo() {})": [1, 14], + "(function*() {})": [1, 10], + "() => {}": [3, 5], + "async () => {}": [9, 11], + "({ foo: function foo() {} })": [3, 20], + "({ foo: function() {} })": [3, 16], + "({ foo: () => {} })": [11, 13], + "({ ['foo']: function() {} })": [3, 20], + "({ [foo]: function() {} })": [3, 18], + "({ foo() {} })": [3, 6], + "({ foo: function* foo() {} })": [3, 21], + "({ foo: function*() {} })": [3, 17], + "({ ['foo']: function*() {} })": [3, 21], + "({ [foo]: function*() {} })": [3, 19], + "({ *foo() {} })": [3, 7], + "({ foo: async function foo() {} })": [3, 26], + "({ foo: async function() {} })": [3, 22], + "({ ['foo']: async function() {} })": [3, 26], + "({ [foo]: async function() {} })": [3, 24], + "({ async foo() {} })": [3, 12], + "({ get foo() {} })": [3, 10], + "({ set foo(a) {} })": [3, 10], + "class A { constructor() {} }": [10, 21], + "class A { foo() {} }": [10, 13], + "class A { *foo() {} }": [10, 14], + "class A { async foo() {} }": [10, 19], + "class A { ['foo']() {} }": [10, 17], + "class A { *['foo']() {} }": [10, 18], + "class A { async ['foo']() {} }": [10, 23], + "class A { [foo]() {} }": [10, 15], + "class A { *[foo]() {} }": [10, 16], + "class A { async [foo]() {} }": [10, 21], + "class A { get foo() {} }": [10, 17], + "class A { set foo(a) {} }": [10, 17], + "class A { static foo() {} }": [10, 20], + "class A { static *foo() {} }": [10, 21], + "class A { static async foo() {} }": [10, 26], + "class A { static get foo() {} }": [10, 24], + "class A { static set foo(a) {} }": [10, 24], + ...(semver.gte(eslint.Linter.version, "7.0.0") ? { "class A { #foo() {} }": [10, 14], "class A { *#foo() {} }": [10, 15], @@ -87,8 +85,8 @@ describe("The 'getFunctionHeadLocation' function", () => { "class A { static #foo = function*() {} }": [10, 33], "class A { static #foo = async function() {} }": [10, 38], } - : {} - ) + : {}), + } for (const key of Object.keys(expectedResults)) { const expectedLoc = { @@ -103,16 +101,16 @@ describe("The 'getFunctionHeadLocation' function", () => { } it(`should return "${JSON.stringify( - expectedLoc + expectedLoc, )}" for "${key}".`, () => { const linter = new eslint.Linter() let actualLoc = null - linter.defineRule("test", context => ({ + linter.defineRule("test", (context) => ({ ":function"(node) { actualLoc = getFunctionHeadLocation( node, - context.getSourceCode() + context.getSourceCode(), ) }, })) @@ -127,13 +125,13 @@ describe("The 'getFunctionHeadLocation' function", () => { }, }, "test.js", - true + true, ) assert.strictEqual( messages.length, 0, - messages[0] && messages[0].message + messages[0] && messages[0].message, ) assert.deepStrictEqual(actualLoc, expectedLoc) }) diff --git a/test/get-function-name-with-kind.js b/test/get-function-name-with-kind.js index f4cebe3..4da4455 100644 --- a/test/get-function-name-with-kind.js +++ b/test/get-function-name-with-kind.js @@ -4,70 +4,68 @@ import semver from "semver" import { getFunctionNameWithKind } from "../src/" describe("The 'getFunctionNameWithKind' function", () => { - const expectedResults = Object.assign( - { - "function foo() {}": "function 'foo'", - "(function foo() {})": "function 'foo'", - "(function() {})": "function", - "function* foo() {}": "generator function 'foo'", - "(function* foo() {})": "generator function 'foo'", - "(function*() {})": "generator function", - "() => {}": "arrow function", - "async () => {}": "async arrow function", - "const foo = () => {}": "arrow function 'foo'", - "const foo = async () => {}": "async arrow function 'foo'", - "foo = () => {}": "arrow function 'foo'", - "foo = async () => {}": "async arrow function 'foo'", - "foo.bar = () => {}": "arrow function", - "foo.bar = async () => {}": "async arrow function", - "const foo = function() {}": "function 'foo'", - "const foo = function* () {}": "generator function 'foo'", - "const foo = async function() {}": "async function 'foo'", - "foo = function() {}": "function 'foo'", - "foo = function* () {}": "generator function 'foo'", - "foo = async function() {}": "async function 'foo'", - "const foo = function bar() {}": "function 'bar'", - "foo = function bar() {}": "function 'bar'", - "foo.bar = function() {}": "function", - "foo.bar = function* () {}": "generator function", - "foo.bar = async function() {}": "async function", - "({ foo: function foo() {} })": "method 'foo'", - "({ foo: function() {} })": "method 'foo'", - "({ ['foo']: function() {} })": "method 'foo'", - "({ [foo]: function() {} })": "method [foo]", - "({ foo() {} })": "method 'foo'", - "({ foo: function* foo() {} })": "generator method 'foo'", - "({ foo: function*() {} })": "generator method 'foo'", - "({ ['foo']: function*() {} })": "generator method 'foo'", - "({ [foo]: function*() {} })": "generator method [foo]", - "({ *foo() {} })": "generator method 'foo'", - "({ foo: async function foo() {} })": "async method 'foo'", - "({ foo: async function() {} })": "async method 'foo'", - "({ ['foo']: async function() {} })": "async method 'foo'", - "({ [foo]: async function() {} })": "async method [foo]", - "({ async foo() {} })": "async method 'foo'", - "({ get foo() {} })": "getter 'foo'", - "({ set foo(a) {} })": "setter 'foo'", - "class A { constructor() {} }": "constructor", - "class A { foo() {} }": "method 'foo'", - "class A { *foo() {} }": "generator method 'foo'", - "class A { async foo() {} }": "async method 'foo'", - "class A { ['foo']() {} }": "method 'foo'", - "class A { *['foo']() {} }": "generator method 'foo'", - "class A { async ['foo']() {} }": "async method 'foo'", - "class A { [foo]() {} }": "method [foo]", - "class A { *[foo]() {} }": "generator method [foo]", - "class A { async [foo]() {} }": "async method [foo]", - "class A { get foo() {} }": "getter 'foo'", - "class A { set foo(a) {} }": "setter 'foo'", - "class A { static foo() {} }": "static method 'foo'", - "class A { static *foo() {} }": "static generator method 'foo'", - "class A { static async foo() {} }": "static async method 'foo'", - "class A { static get foo() {} }": "static getter 'foo'", - "class A { static set foo(a) {} }": "static setter 'foo'", - }, + const expectedResults = { + "function foo() {}": "function 'foo'", + "(function foo() {})": "function 'foo'", + "(function() {})": "function", + "function* foo() {}": "generator function 'foo'", + "(function* foo() {})": "generator function 'foo'", + "(function*() {})": "generator function", + "() => {}": "arrow function", + "async () => {}": "async arrow function", + "const foo = () => {}": "arrow function 'foo'", + "const foo = async () => {}": "async arrow function 'foo'", + "foo = () => {}": "arrow function 'foo'", + "foo = async () => {}": "async arrow function 'foo'", + "foo.bar = () => {}": "arrow function", + "foo.bar = async () => {}": "async arrow function", + "const foo = function() {}": "function 'foo'", + "const foo = function* () {}": "generator function 'foo'", + "const foo = async function() {}": "async function 'foo'", + "foo = function() {}": "function 'foo'", + "foo = function* () {}": "generator function 'foo'", + "foo = async function() {}": "async function 'foo'", + "const foo = function bar() {}": "function 'bar'", + "foo = function bar() {}": "function 'bar'", + "foo.bar = function() {}": "function", + "foo.bar = function* () {}": "generator function", + "foo.bar = async function() {}": "async function", + "({ foo: function foo() {} })": "method 'foo'", + "({ foo: function() {} })": "method 'foo'", + "({ ['foo']: function() {} })": "method 'foo'", + "({ [foo]: function() {} })": "method [foo]", + "({ foo() {} })": "method 'foo'", + "({ foo: function* foo() {} })": "generator method 'foo'", + "({ foo: function*() {} })": "generator method 'foo'", + "({ ['foo']: function*() {} })": "generator method 'foo'", + "({ [foo]: function*() {} })": "generator method [foo]", + "({ *foo() {} })": "generator method 'foo'", + "({ foo: async function foo() {} })": "async method 'foo'", + "({ foo: async function() {} })": "async method 'foo'", + "({ ['foo']: async function() {} })": "async method 'foo'", + "({ [foo]: async function() {} })": "async method [foo]", + "({ async foo() {} })": "async method 'foo'", + "({ get foo() {} })": "getter 'foo'", + "({ set foo(a) {} })": "setter 'foo'", + "class A { constructor() {} }": "constructor", + "class A { foo() {} }": "method 'foo'", + "class A { *foo() {} }": "generator method 'foo'", + "class A { async foo() {} }": "async method 'foo'", + "class A { ['foo']() {} }": "method 'foo'", + "class A { *['foo']() {} }": "generator method 'foo'", + "class A { async ['foo']() {} }": "async method 'foo'", + "class A { [foo]() {} }": "method [foo]", + "class A { *[foo]() {} }": "generator method [foo]", + "class A { async [foo]() {} }": "async method [foo]", + "class A { get foo() {} }": "getter 'foo'", + "class A { set foo(a) {} }": "setter 'foo'", + "class A { static foo() {} }": "static method 'foo'", + "class A { static *foo() {} }": "static generator method 'foo'", + "class A { static async foo() {} }": "static async method 'foo'", + "class A { static get foo() {} }": "static getter 'foo'", + "class A { static set foo(a) {} }": "static setter 'foo'", - semver.gte(eslint.Linter.version, "7.0.0") + ...(semver.gte(eslint.Linter.version, "7.0.0") ? { "class A { #foo() {} }": "private method #foo", "class A { '#foo'() {} }": "method '#foo'", @@ -122,8 +120,8 @@ describe("The 'getFunctionNameWithKind' function", () => { "class A { static #foo = async function() {} }": "static private async method #foo", } - : {} - ) + : {}), + } for (const key of Object.keys(expectedResults)) { const expectedResult1 = expectedResults[key].replace(/\s+\[.+?\]/gu, "") @@ -150,7 +148,7 @@ describe("The 'getFunctionNameWithKind' function", () => { assert.strictEqual( messages.length, 0, - messages[0] && messages[0].message + messages[0] && messages[0].message, ) assert.strictEqual(actualResult, expectedResult1) }) @@ -159,11 +157,11 @@ describe("The 'getFunctionNameWithKind' function", () => { const linter = new eslint.Linter() let actualResult = null - linter.defineRule("test", context => ({ + linter.defineRule("test", (context) => ({ ":function"(node) { actualResult = getFunctionNameWithKind( node, - context.getSourceCode() + context.getSourceCode(), ) }, })) @@ -179,7 +177,7 @@ describe("The 'getFunctionNameWithKind' function", () => { assert.strictEqual( messages.length, 0, - messages[0] && messages[0].message + messages[0] && messages[0].message, ) assert.strictEqual(actualResult, expectedResult2) }) diff --git a/test/get-innermost-scope.js b/test/get-innermost-scope.js index 27e7e91..e4ecc6d 100644 --- a/test/get-innermost-scope.js +++ b/test/get-innermost-scope.js @@ -8,50 +8,50 @@ describe("The 'getInnermostScope' function", () => { { code: "let a = 0", parserOptions: {}, - selectNode: node => node, - selectScope: scope => scope, + selectNode: (node) => node, + selectScope: (scope) => scope, }, { code: "let a = 0", parserOptions: { ecmaFeatures: { globalReturn: true } }, - selectNode: node => node, - selectScope: scope => scope.childScopes[0], + selectNode: (node) => node, + selectScope: (scope) => scope.childScopes[0], }, { code: "let a = 0", parserOptions: { sourceType: "module" }, - selectNode: node => node, - selectScope: scope => scope.childScopes[0], + selectNode: (node) => node, + selectScope: (scope) => scope.childScopes[0], }, { code: "a; { b; { c; } d; } e;", parserOptions: {}, - selectNode: node => node.body[0], - selectScope: scope => scope, + selectNode: (node) => node.body[0], + selectScope: (scope) => scope, }, { code: "a; { b; { c; } d; } e;", parserOptions: {}, - selectNode: node => node.body[2], - selectScope: scope => scope, + selectNode: (node) => node.body[2], + selectScope: (scope) => scope, }, { code: "a; { b; { c; } d; } e;", parserOptions: {}, - selectNode: node => node.body[1].body[0], - selectScope: scope => scope.childScopes[0], + selectNode: (node) => node.body[1].body[0], + selectScope: (scope) => scope.childScopes[0], }, { code: "a; { b; { c; } d; } e;", parserOptions: {}, - selectNode: node => node.body[1].body[2], - selectScope: scope => scope.childScopes[0], + selectNode: (node) => node.body[1].body[2], + selectScope: (scope) => scope.childScopes[0], }, { code: "a; { b; { c; } d; } e;", parserOptions: {}, - selectNode: node => node.body[1].body[1].body[0], - selectScope: scope => scope.childScopes[0].childScopes[0], + selectNode: (node) => node.body[1].body[1].body[0], + selectScope: (scope) => scope.childScopes[0].childScopes[0], }, ]) { it(`should return the innermost scope (${++i})`, () => { @@ -59,7 +59,7 @@ describe("The 'getInnermostScope' function", () => { let actualScope = null let expectedScope = null - linter.defineRule("test", context => ({ + linter.defineRule("test", (context) => ({ Program(node) { const scope = context.getScope() actualScope = getInnermostScope(scope, selectNode(node)) @@ -67,10 +67,7 @@ describe("The 'getInnermostScope' function", () => { }, })) linter.verify(code, { - parserOptions: Object.assign( - { ecmaVersion: 2018 }, - parserOptions - ), + parserOptions: { ecmaVersion: 2018, ...parserOptions }, rules: { test: "error" }, }) diff --git a/test/get-property-name.js b/test/get-property-name.js index d2c36bc..afaef3e 100644 --- a/test/get-property-name.js +++ b/test/get-property-name.js @@ -61,7 +61,7 @@ describe("The 'getPropertyName' function", () => { let actual = null linter.defineRule("test", () => ({ "Property,PropertyDefinition,MethodDefinition,MemberExpression"( - node + node, ) { actual = getPropertyName(node) }, @@ -77,7 +77,7 @@ describe("The 'getPropertyName' function", () => { assert.strictEqual( messages.length, 0, - messages[0] && messages[0].message + messages[0] && messages[0].message, ) assert.strictEqual(actual, expected) }) diff --git a/test/get-static-value.js b/test/get-static-value.js index 1d5a5d1..62d878e 100644 --- a/test/get-static-value.js +++ b/test/get-static-value.js @@ -130,18 +130,15 @@ const aMap = Object.freeze({ expected: null, }, { - code: - '({}.constructor.constructor("return process.env.npm_name")())', + code: '({}.constructor.constructor("return process.env.npm_name")())', expected: null, }, { - code: - 'JSON.stringify({a:1}, new {}.constructor.constructor("console.log(\\"code injected\\"); process.exit(1)"), 2)', + code: 'JSON.stringify({a:1}, new {}.constructor.constructor("console.log(\\"code injected\\"); process.exit(1)"), 2)', expected: null, }, { - code: - 'Object.create(null, {a:{get:new {}.constructor.constructor("console.log(\\"code injected\\"); process.exit(1)")}}).a', + code: 'Object.create(null, {a:{get:new {}.constructor.constructor("console.log(\\"code injected\\"); process.exit(1)")}}).a', expected: null, }, { @@ -244,7 +241,7 @@ const aMap = Object.freeze({ }, { code: "({'a': 1, 1e+1: 2, 2n: 3})", - expected: { value: { a: 1, "10": 2, "2": 3 } }, + expected: { value: { a: 1, 10: 2, 2: 3 } }, }, ] : []), @@ -295,11 +292,11 @@ const aMap = Object.freeze({ const linter = new eslint.Linter() let actual = null - linter.defineRule("test", context => ({ + linter.defineRule("test", (context) => ({ ExpressionStatement(node) { actual = getStaticValue( node, - noScope ? null : context.getScope() + noScope ? null : context.getScope(), ) }, })) @@ -318,7 +315,7 @@ const aMap = Object.freeze({ assert.strictEqual( messages.length, 0, - messages[0] && messages[0].message + messages[0] && messages[0].message, ) if (actual == null) { assert.strictEqual(actual, expected) diff --git a/test/get-string-if-constant.js b/test/get-string-if-constant.js index b100410..d2afc58 100644 --- a/test/get-string-if-constant.js +++ b/test/get-string-if-constant.js @@ -51,7 +51,7 @@ describe("The 'getStringIfConstant' function", () => { const linter = new eslint.Linter() let actual = null - linter.defineRule("test", context => ({ + linter.defineRule("test", (context) => ({ "Program > ExpressionStatement > *"(node) { actual = getStringIfConstant(node, context.getScope()) }, diff --git a/test/has-side-effect.js b/test/has-side-effect.js index 7ec2197..0542abf 100644 --- a/test/has-side-effect.js +++ b/test/has-side-effect.js @@ -317,17 +317,17 @@ describe("The 'hasSideEffect' function", () => { }, ]) { it(`should return ${expected} on the code \`${code}\` and the options \`${JSON.stringify( - options + options, )}\``, () => { const linter = new eslint.Linter() let actual = null - linter.defineRule("test", context => ({ + linter.defineRule("test", (context) => ({ Program(node) { actual = hasSideEffect( dp.get(node, key), context.getSourceCode(), - options + options, ) }, })) @@ -346,7 +346,7 @@ describe("The 'hasSideEffect' function", () => { assert.strictEqual( messages.length, 0, - messages[0] && messages[0].message + messages[0] && messages[0].message, ) assert.strictEqual(actual, expected) }) diff --git a/test/is-parenthesized.js b/test/is-parenthesized.js index 72ac66b..7ca49eb 100644 --- a/test/is-parenthesized.js +++ b/test/is-parenthesized.js @@ -216,11 +216,11 @@ describe("The 'isParenthesized' function", () => { const linter = new eslint.Linter() let actual = null - linter.defineRule("test", context => ({ + linter.defineRule("test", (context) => ({ Program(node) { actual = isParenthesized( dotProp.get(node, key), - context.getSourceCode() + context.getSourceCode(), ) }, })) @@ -233,7 +233,7 @@ describe("The 'isParenthesized' function", () => { assert.strictEqual( messages.length, 0, - messages[0] && messages[0].message + messages[0] && messages[0].message, ) assert.strictEqual(actual, expected[key]) }) @@ -291,12 +291,12 @@ describe("The 'isParenthesized' function", () => { const linter = new eslint.Linter() let actual = null - linter.defineRule("test", context => ({ + linter.defineRule("test", (context) => ({ Program(node) { actual = isParenthesized( 2, dotProp.get(node, key), - context.getSourceCode() + context.getSourceCode(), ) }, })) @@ -309,7 +309,7 @@ describe("The 'isParenthesized' function", () => { assert.strictEqual( messages.length, 0, - messages[0] && messages[0].message + messages[0] && messages[0].message, ) assert.strictEqual(actual, expected[key]) }) diff --git a/test/pattern-matcher.js b/test/pattern-matcher.js index f679397..5c3b76c 100644 --- a/test/pattern-matcher.js +++ b/test/pattern-matcher.js @@ -44,7 +44,7 @@ describe("The 'PatternMatcher' class:", () => { ]) { assert.throws( () => new PatternMatcher(value), - /^TypeError: 'pattern' should be a RegExp instance\.$/u + /^TypeError: 'pattern' should be a RegExp instance\.$/u, ) } }) @@ -53,7 +53,7 @@ describe("The 'PatternMatcher' class:", () => { for (const value of [/foo/u, /bar/imu]) { assert.throws( () => new PatternMatcher(value), - /^Error: 'pattern' should contains 'g' flag\.$/u + /^Error: 'pattern' should contains 'g' flag\.$/u, ) } }) @@ -98,23 +98,23 @@ describe("The 'PatternMatcher' class:", () => { newRegExpExecArray( ["foo"], 1, - String.raw`-foo\foofooabcfoo-` + String.raw`-foo\foofooabcfoo-`, ), newRegExpExecArray( ["foo"], 8, - String.raw`-foo\foofooabcfoo-` + String.raw`-foo\foofooabcfoo-`, ), newRegExpExecArray( ["foo"], 14, - String.raw`-foo\foofooabcfoo-` + String.raw`-foo\foofooabcfoo-`, ), ], }, ]) { it(`should return ${JSON.stringify( - expected + expected, )} in ${JSON.stringify(str)}.`, () => { const matcher = new PatternMatcher(/foo/gu) const actual = Array.from(matcher.execAll(str)) @@ -137,7 +137,7 @@ describe("The 'PatternMatcher' class:", () => { }, ]) { it(`should return ${JSON.stringify( - expected + expected, )} in ${JSON.stringify(str)}.`, () => { const matcher = new PatternMatcher(/(\w)(\d)/gu) const actual = Array.from(matcher.execAll(str)) @@ -211,7 +211,7 @@ describe("The 'PatternMatcher' class:", () => { }, ]) { it(`should return ${JSON.stringify( - expected + expected, )} in ${JSON.stringify(str)}.`, () => { const matcher = new PatternMatcher(/foo/gu, { escaped: true, @@ -285,7 +285,7 @@ describe("The 'PatternMatcher' class:", () => { }, ]) { it(`should return ${expected} in ${JSON.stringify( - str + str, )} and ${JSON.stringify(replacer)}.`, () => { const matcher = new PatternMatcher(pattern || /[a-c]/gu) const actual = str.replace(matcher, replacer) diff --git a/test/reference-tracker.js b/test/reference-tracker.js index 6ad797e..65378d3 100644 --- a/test/reference-tracker.js +++ b/test/reference-tracker.js @@ -523,20 +523,20 @@ describe("The 'ReferenceTracker' class:", () => { const linter = new eslint.Linter() let actual = null - linter.defineRule("test", context => ({ + linter.defineRule("test", (context) => ({ "Program:exit"() { const tracker = new ReferenceTracker(context.getScope()) actual = Array.from( - tracker.iterateGlobalReferences(traceMap) - ).map(x => + tracker.iterateGlobalReferences(traceMap), + ).map((x) => Object.assign(x, { - node: Object.assign( - { type: x.node.type }, - x.node.optional + node: { + type: x.node.type, + ...(x.node.optional ? { optional: x.node.optional } - : {} - ), - }) + : {}), + }, + }), ) }, })) @@ -695,20 +695,20 @@ describe("The 'ReferenceTracker' class:", () => { const linter = new eslint.Linter() let actual = null - linter.defineRule("test", context => ({ + linter.defineRule("test", (context) => ({ "Program:exit"() { const tracker = new ReferenceTracker(context.getScope()) actual = Array.from( - tracker.iterateCjsReferences(traceMap) - ).map(x => + tracker.iterateCjsReferences(traceMap), + ).map((x) => Object.assign(x, { - node: Object.assign( - { type: x.node.type }, - x.node.optional + node: { + type: x.node.type, + ...(x.node.optional ? { optional: x.node.optional } - : {} - ), - }) + : {}), + }, + }), ) }, })) @@ -977,20 +977,20 @@ describe("The 'ReferenceTracker' class:", () => { const linter = new eslint.Linter() let actual = null - linter.defineRule("test", context => ({ + linter.defineRule("test", (context) => ({ "Program:exit"() { const tracker = new ReferenceTracker(context.getScope()) actual = Array.from( - tracker.iterateEsmReferences(traceMap) - ).map(x => + tracker.iterateEsmReferences(traceMap), + ).map((x) => Object.assign(x, { - node: Object.assign( - { type: x.node.type }, - x.node.optional + node: { + type: x.node.type, + ...(x.node.optional ? { optional: x.node.optional } - : {} - ), - }) + : {}), + }, + }), ) }, })) diff --git a/test/token-predicate.js b/test/token-predicate.js index 1805fa8..fc9fa07 100644 --- a/test/token-predicate.js +++ b/test/token-predicate.js @@ -138,7 +138,7 @@ describe("The predicate functions for tokens", () => { describe(`'is${baseName}'`, () => { for (const [token, expected] of patterns) { it(`should return ${expected} if ${JSON.stringify( - token + token, )} was given.`, () => { assert.strictEqual(positive(token), expected) }) @@ -148,7 +148,7 @@ describe("The predicate functions for tokens", () => { describe(`'isNot${baseName}'`, () => { for (const [token, expected] of patterns) { it(`should return ${!expected} if ${JSON.stringify( - token + token, )} was given.`, () => { assert.strictEqual(negative(token), !expected) })