forked from mysticatea/eslint-plugin-node
-
-
Notifications
You must be signed in to change notification settings - Fork 47
Add n/prefer-node-protocol rule #183
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
aladdin-add
merged 8 commits into
eslint-community:master
from
yinm:feat/add-rule-for-prefer-node-protocol
Feb 19, 2024
Merged
Changes from 6 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
7de8c8c
feat: add `n/prefer-node-protocol` rule
yinm eb9afdb
feat: support `require` function
yinm d243dc3
docs: add `export` examples
yinm dc1bcbc
feat: enable or disable this rule by supported Node.js version
yinm a73ef36
refactor: use `visit-require` and `visit-import`
yinm db9747f
fix: avoid type error by non-string types
yinm 03024dd
refactor: use `moduleStyle` for simplicity
yinm e992de9
chore: update to false for avoiding a breaking change
yinm File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,73 @@ | ||
# Enforce using the `node:` protocol when importing Node.js builtin modules (`n/prefer-node-protocol`) | ||
|
||
🔧 This rule is automatically fixable by the [`--fix` CLI option](https://eslint.org/docs/latest/user-guide/command-line-interface#--fix). | ||
|
||
<!-- end auto-generated rule header --> | ||
|
||
Older built-in Node modules such as fs now can be imported via either their name or `node:` + their name: | ||
|
||
```js | ||
import fs from "fs" | ||
import fs from "node:fs" | ||
``` | ||
|
||
The prefixed versions are nice because they can't be overridden by user modules and are similarly formatted to prefix-only modules such as node:test. | ||
|
||
Note that Node.js support for this feature began in: | ||
|
||
> v16.0.0, v14.18.0 (`require()`) | ||
> v14.13.1, v12.20.0 (`import`) | ||
|
||
## 📖 Rule Details | ||
|
||
This rule enforces that `node:` protocol is prepended to built-in Node modules when importing or exporting built-in Node modules. | ||
|
||
👍 Examples of **correct** code for this rule: | ||
|
||
```js | ||
/*eslint n/prefer-node-protocol: error */ | ||
|
||
import fs from "node:fs" | ||
|
||
export { promises } from "node:fs" | ||
|
||
const fs = require("node:fs") | ||
``` | ||
|
||
👎 Examples of **incorrect** code for this rule: | ||
|
||
```js | ||
/*eslint n/prefer-node-protocol: error */ | ||
|
||
import fs from "fs" | ||
|
||
export { promises } from "fs" | ||
|
||
const fs = require("fs") | ||
``` | ||
|
||
### Configured Node.js version range | ||
|
||
[Configured Node.js version range](../../../README.md#configured-nodejs-version-range) | ||
|
||
### Options | ||
|
||
```json | ||
{ | ||
"n/prefer-node-protocol": ["error", { | ||
"version": ">=16.0.0", | ||
}] | ||
} | ||
``` | ||
|
||
#### version | ||
|
||
As mentioned above, this rule reads the [`engines`] field of `package.json`. | ||
But, you can overwrite the version by `version` option. | ||
|
||
The `version` option accepts [the valid version range of `node-semver`](https://github.com/npm/node-semver#range-grammar). | ||
|
||
## 🔎 Implementation | ||
|
||
- [Rule source](../../lib/rules/prefer-node-protocol.js) | ||
- [Test source](../../tests/lib/rules/prefer-node-protocol.js) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
@@ -0,0 +1,151 @@ | ||||||
/** | ||||||
* @author Yusuke Iinuma | ||||||
* See LICENSE file in root directory for full license. | ||||||
*/ | ||||||
"use strict" | ||||||
|
||||||
const isBuiltinModule = require("is-builtin-module") | ||||||
const getConfiguredNodeVersion = require("../util/get-configured-node-version") | ||||||
const getSemverRange = require("../util/get-semver-range") | ||||||
const visitImport = require("../util/visit-import") | ||||||
const visitRequire = require("../util/visit-require") | ||||||
const mergeVisitorsInPlace = require("../util/merge-visitors-in-place") | ||||||
|
||||||
const messageId = "preferNodeProtocol" | ||||||
|
||||||
module.exports = { | ||||||
meta: { | ||||||
docs: { | ||||||
description: | ||||||
"enforce using the `node:` protocol when importing Node.js builtin modules.", | ||||||
recommended: true, | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. the
Suggested change
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Thank you for your review 🙏 |
||||||
url: "https://github.com/eslint-community/eslint-plugin-n/blob/HEAD/docs/rules/prefer-node-protocol.md", | ||||||
}, | ||||||
fixable: "code", | ||||||
messages: { | ||||||
[messageId]: "Prefer `node:{{moduleName}}` over `{{moduleName}}`.", | ||||||
}, | ||||||
schema: [ | ||||||
{ | ||||||
type: "object", | ||||||
properties: { | ||||||
version: getConfiguredNodeVersion.schema, | ||||||
}, | ||||||
additionalProperties: false, | ||||||
}, | ||||||
], | ||||||
type: "suggestion", | ||||||
}, | ||||||
create(context) { | ||||||
scagood marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||
function isCallExpression(node, { name, argumentsLength }) { | ||||||
if (node?.type !== "CallExpression") { | ||||||
return false | ||||||
} | ||||||
|
||||||
if (node.optional) { | ||||||
return false | ||||||
} | ||||||
|
||||||
if (node.arguments.length !== argumentsLength) { | ||||||
return false | ||||||
} | ||||||
|
||||||
if ( | ||||||
node.callee.type !== "Identifier" || | ||||||
node.callee.name !== name | ||||||
) { | ||||||
return false | ||||||
} | ||||||
|
||||||
return true | ||||||
} | ||||||
|
||||||
function isStringLiteral(node) { | ||||||
return node?.type === "Literal" && typeof node.type === "string" | ||||||
} | ||||||
|
||||||
function isStaticRequire(node) { | ||||||
return ( | ||||||
isCallExpression(node, { | ||||||
name: "require", | ||||||
argumentsLength: 1, | ||||||
}) && isStringLiteral(node.arguments[0]) | ||||||
) | ||||||
} | ||||||
|
||||||
function isEnablingThisRule(context, node) { | ||||||
const version = getConfiguredNodeVersion(context) | ||||||
|
||||||
const supportedVersionForEsm = "^12.20.0 || >= 14.13.1" | ||||||
// Only check Node.js version because this rule is meaningless if configured Node.js version doesn't match semver range. | ||||||
if (!version.intersects(getSemverRange(supportedVersionForEsm))) { | ||||||
return false | ||||||
} | ||||||
|
||||||
const supportedVersionForCjs = "^14.18.0 || >= 16.0.0" | ||||||
// Only check when using `require` | ||||||
if ( | ||||||
isStaticRequire(node.parent) && | ||||||
scagood marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||
node.parent.arguments[0] === node && | ||||||
!version.intersects(getSemverRange(supportedVersionForCjs)) | ||||||
) { | ||||||
return false | ||||||
} | ||||||
|
||||||
return true | ||||||
} | ||||||
|
||||||
const targets = [] | ||||||
return [ | ||||||
visitImport(context, { includeCore: true }, importTargets => { | ||||||
targets.push(...importTargets) | ||||||
}), | ||||||
visitRequire(context, { includeCore: true }, requireTargets => { | ||||||
targets.push( | ||||||
...requireTargets.filter(target => | ||||||
isStaticRequire(target.node.parent) | ||||||
) | ||||||
scagood marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||
) | ||||||
}), | ||||||
{ | ||||||
"Program:exit"() { | ||||||
for (const { node } of targets) { | ||||||
if (!isEnablingThisRule(context, node)) { | ||||||
return | ||||||
} | ||||||
|
||||||
if (node.type === "TemplateLiteral") { | ||||||
continue | ||||||
} | ||||||
|
||||||
const { value } = node | ||||||
if ( | ||||||
typeof value !== "string" || | ||||||
value.startsWith("node:") || | ||||||
!isBuiltinModule(value) || | ||||||
!isBuiltinModule(`node:${value}`) | ||||||
) { | ||||||
return | ||||||
} | ||||||
|
||||||
context.report({ | ||||||
node, | ||||||
messageId, | ||||||
fix(fixer) { | ||||||
const firstCharacterIndex = node.range[0] + 1 | ||||||
return fixer.replaceTextRange( | ||||||
[firstCharacterIndex, firstCharacterIndex], | ||||||
"node:" | ||||||
) | ||||||
}, | ||||||
}) | ||||||
} | ||||||
}, | ||||||
}, | ||||||
].reduce( | ||||||
(mergedVisitor, thisVisitor) => | ||||||
mergeVisitorsInPlace(mergedVisitor, thisVisitor), | ||||||
{} | ||||||
) | ||||||
}, | ||||||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.