Skip to content

Commit

Permalink
feat: add support for ignoring sync methods from certain locations (#392
Browse files Browse the repository at this point in the history
)

Co-authored-by: Sebastian Good <[email protected]>
  • Loading branch information
RebeccaStevens and scagood authored Feb 12, 2025
1 parent 4efe60f commit 5544f20
Show file tree
Hide file tree
Showing 18 changed files with 543 additions and 9 deletions.
57 changes: 57 additions & 0 deletions docs/rules/no-sync.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ fs.readFileSync(somePath).toString();
#### ignores

You can `ignore` specific function names using this option.
Additionally, if you are using TypeScript you can optionally specify where the function is declared.

Examples of **incorrect** code for this rule with the `{ ignores: ['readFileSync'] }` option:

Expand All @@ -78,6 +79,62 @@ Examples of **correct** code for this rule with the `{ ignores: ['readFileSync']
fs.readFileSync(somePath);
```

##### Advanced (TypeScript only)

You can provide a list of specifiers to ignore. Specifiers are typed as follows:

```ts
type Specifier =
| string
| {
from: "file";
path?: string;
name?: string[];
}
| {
from: "package";
package?: string;
name?: string[];
}
| {
from: "lib";
name?: string[];
}
```
###### From a file
Examples of **correct** code for this rule with the ignore file specifier:
```js
/*eslint n/no-sync: ["error", { ignores: [{ from: 'file', path: './foo.ts' }]}] */

import { fooSync } from "./foo"
fooSync()
```

###### From a package

Examples of **correct** code for this rule with the ignore package specifier:

```js
/*eslint n/no-sync: ["error", { ignores: [{ from: 'package', package: 'effect' }]}] */

import { Effect } from "effect"
const value = Effect.runSync(Effect.succeed(42))
```

###### From the TypeScript library

Examples of **correct** code for this rule with the ignore lib specifier:

```js
/*eslint n/no-sync: ["error", { ignores: [{ from: 'lib' }]}] */

const stylesheet = new CSSStyleSheet()
stylesheet.replaceSync("body { font-size: 1.4em; } p { color: red; }")
```

## 🔎 Implementation

- [Rule source](../../lib/rules/no-sync.js)
Expand Down
114 changes: 110 additions & 4 deletions lib/rules/no-sync.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,14 @@
*/
"use strict"

const typeMatchesSpecifier =
/** @type {import('ts-declaration-location').default} */ (
/** @type {unknown} */ (require("ts-declaration-location"))
)
const getTypeOfNode = require("../util/get-type-of-node")
const getParserServices = require("../util/get-parser-services")
const getFullTypeName = require("../util/get-full-type-name")

const selectors = [
// fs.readFileSync()
// readFileSync.call(null, 'path')
Expand Down Expand Up @@ -32,7 +40,56 @@ module.exports = {
},
ignores: {
type: "array",
items: { type: "string" },
items: {
oneOf: [
{ type: "string" },
{
type: "object",
properties: {
from: { const: "file" },
path: {
type: "string",
},
name: {
type: "array",
items: {
type: "string",
},
},
},
additionalProperties: false,
},
{
type: "object",
properties: {
from: { const: "lib" },
name: {
type: "array",
items: {
type: "string",
},
},
},
additionalProperties: false,
},
{
type: "object",
properties: {
from: { const: "package" },
package: {
type: "string",
},
name: {
type: "array",
items: {
type: "string",
},
},
},
additionalProperties: false,
},
],
},
default: [],
},
},
Expand All @@ -57,15 +114,64 @@ module.exports = {
* @returns {void}
*/
[selector.join(",")](node) {
if (ignores.includes(node.name)) {
return
const parserServices = getParserServices(context)

/**
* @type {import('typescript').Type | undefined | null}
*/
let type = undefined

/**
* @type {string | undefined | null}
*/
let fullName = undefined

for (const ignore of ignores) {
if (typeof ignore === "string") {
if (ignore === node.name) {
return
}

continue
}

if (
parserServices === null ||
parserServices.program === null
) {
throw new Error(
'TypeScript parser services not available. Rule "n/no-sync" is configured to use "ignores" option with a non-string value. This requires TypeScript parser services to be available.'
)
}

type =
type === undefined
? getTypeOfNode(node, parserServices)
: type

fullName =
fullName === undefined
? getFullTypeName(type)
: fullName

if (
typeMatchesSpecifier(
parserServices.program,
ignore,
type
) &&
(ignore.name === undefined ||
ignore.name.includes(fullName ?? node.name))
) {
return
}
}

context.report({
node: node.parent,
messageId: "noSync",
data: {
propertyName: node.name,
propertyName: fullName ?? node.name,
},
})
},
Expand Down
47 changes: 47 additions & 0 deletions lib/util/get-full-type-name.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
"use strict"

const ts = (() => {
try {
// eslint-disable-next-line n/no-unpublished-require
return require("typescript")
} catch {
return null
}
})()

/**
* @param {import('typescript').Type | null} type
* @returns {string | null}
*/
module.exports = function getFullTypeName(type) {
if (ts === null || type === null) {
return null
}

/**
* @type {string[]}
*/
let nameParts = []
let currentSymbol = type.getSymbol()
while (currentSymbol !== undefined) {
if (
currentSymbol.valueDeclaration?.kind === ts.SyntaxKind.SourceFile ||
currentSymbol.valueDeclaration?.kind ===
ts.SyntaxKind.ModuleDeclaration
) {
break
}

nameParts.unshift(currentSymbol.getName())
currentSymbol =
/** @type {import('typescript').Symbol & {parent: import('typescript').Symbol | undefined}} */ (
currentSymbol
).parent
}

if (nameParts.length === 0) {
return null
}

return nameParts.join(".")
}
24 changes: 24 additions & 0 deletions lib/util/get-parser-services.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
"use strict"

const {
getParserServices: getParserServicesFromTsEslint,
} = require("@typescript-eslint/utils/eslint-utils")

/**
* Get the TypeScript parser services.
* If TypeScript isn't present, returns `null`.
*
* @param {import('eslint').Rule.RuleContext} context - rule context
* @returns {import('@typescript-eslint/parser').ParserServices | null}
*/
module.exports = function getParserServices(context) {
// Not using tseslint parser?
if (
context.sourceCode.parserServices?.esTreeNodeToTSNodeMap == null ||
context.sourceCode.parserServices.tsNodeToESTreeNodeMap == null
) {
return null
}

return getParserServicesFromTsEslint(/** @type {any} */ (context), true)
}
21 changes: 21 additions & 0 deletions lib/util/get-type-of-node.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
"use strict"

/**
* Get the type of a node.
* If TypeScript isn't present, returns `null`.
*
* @param {import('estree').Node} node - A node
* @param {import('@typescript-eslint/parser').ParserServices} parserServices - A parserServices
* @returns {import('typescript').Type | null}
*/
module.exports = function getTypeOfNode(node, parserServices) {
const { esTreeNodeToTSNodeMap, program } = parserServices
if (program === null) {
return null
}
const tsNode = esTreeNodeToTSNodeMap.get(/** @type {any} */ (node))
const checker = program.getTypeChecker()
const nodeType = checker.getTypeAtLocation(tsNode)
const constrained = checker.getBaseConstraintOfType(nodeType)
return constrained ?? nodeType
}
10 changes: 6 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,21 +17,23 @@
},
"dependencies": {
"@eslint-community/eslint-utils": "^4.4.1",
"@typescript-eslint/utils": "^8.21.0",
"enhanced-resolve": "^5.17.1",
"eslint-plugin-es-x": "^7.8.0",
"get-tsconfig": "^4.8.1",
"globals": "^15.11.0",
"ignore": "^5.3.2",
"minimatch": "^9.0.5",
"semver": "^7.6.3"
"semver": "^7.6.3",
"ts-declaration-location": "^1.0.5"
},
"devDependencies": {
"@eslint/js": "^9.14.0",
"@types/eslint": "^9.6.1",
"@types/estree": "^1.0.6",
"@types/node": "^20.17.5",
"@typescript-eslint/parser": "^8.12.2",
"@typescript-eslint/typescript-estree": "^8.12.2",
"@typescript-eslint/parser": "^8.21.0",
"@typescript-eslint/typescript-estree": "^8.21.0",
"eslint": "^9.14.0",
"eslint-config-prettier": "^9.1.0",
"eslint-doc-generator": "^1.7.1",
Expand All @@ -51,7 +53,7 @@
"rimraf": "^5.0.10",
"ts-ignore-import": "^4.0.1",
"type-fest": "^4.26.1",
"typescript": "~5.6"
"typescript": "^5.7"
},
"scripts": {
"build": "node scripts/update",
Expand Down
1 change: 1 addition & 0 deletions tests/fixtures/no-sync/base/file.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
// File needs to exists
10 changes: 10 additions & 0 deletions tests/fixtures/no-sync/base/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"compilerOptions": {
"target": "ESNext",
"module": "ESNext",
"moduleResolution": "Bundler",
"strict": true,
"skipLibCheck": true
},
"include": ["**/*"]
}
1 change: 1 addition & 0 deletions tests/fixtures/no-sync/file.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
// File needs to exists
1 change: 1 addition & 0 deletions tests/fixtures/no-sync/ignore-package/file.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
// File needs to exists

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Empty file.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions tests/fixtures/no-sync/ignore-package/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"name": "test",
"version": "0.0.0",
"dependencies": {
"aaa": "0.0.0"
}
}
10 changes: 10 additions & 0 deletions tests/fixtures/no-sync/ignore-package/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"compilerOptions": {
"target": "ESNext",
"module": "ESNext",
"moduleResolution": "Bundler",
"strict": true,
"skipLibCheck": true
},
"include": ["**/*"]
}
10 changes: 10 additions & 0 deletions tests/fixtures/no-sync/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"compilerOptions": {
"target": "ESNext",
"module": "ESNext",
"moduleResolution": "Bundler",
"strict": true,
"skipLibCheck": true
},
"include": ["**/*"]
}
Loading

0 comments on commit 5544f20

Please sign in to comment.