node_modules

This commit is contained in:
saeid
2019-07-15 13:07:31 +04:30
parent d3735c6d30
commit ce1a3ebf9c
35713 changed files with 3639219 additions and 1 deletions
+22
View File
@@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2015 Toru Nagashima
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+156
View File
@@ -0,0 +1,156 @@
# eslint-plugin-node
[![npm version](https://img.shields.io/npm/v/eslint-plugin-node.svg)](https://www.npmjs.com/package/eslint-plugin-node)
[![Downloads/month](https://img.shields.io/npm/dm/eslint-plugin-node.svg)](http://www.npmtrends.com/eslint-plugin-node)
[![Build Status](https://travis-ci.org/mysticatea/eslint-plugin-node.svg?branch=master)](https://travis-ci.org/mysticatea/eslint-plugin-node)
[![Coverage Status](https://codecov.io/gh/mysticatea/eslint-plugin-node/branch/master/graph/badge.svg)](https://codecov.io/gh/mysticatea/eslint-plugin-node)
[![Dependency Status](https://david-dm.org/mysticatea/eslint-plugin-node.svg)](https://david-dm.org/mysticatea/eslint-plugin-node)
Additional ESLint's rules for Node.js
## 💿 Install & Usage
```
$ npm install --save-dev eslint eslint-plugin-node
```
- Requires Node.js `>=6.0.0`
- Requires ESLint `>=4.19.1` (`plugin:node/recommended` preset requires `>=5.0.0`)
**Note:** It recommends a use of [the "engines" field of package.json](https://docs.npmjs.com/files/package.json#engines). The "engines" field is used by `node/no-unsupported-features/*` rules.
**.eslintrc.json** (An example)
```json
{
"extends": ["eslint:recommended", "plugin:node/recommended"],
"rules": {
"node/exports-style": ["error", "module.exports"],
"node/prefer-global/buffer": ["error", "always"],
"node/prefer-global/console": ["error", "always"],
"node/prefer-global/process": ["error", "always"],
"node/prefer-global/url-search-params": ["error", "always"],
"node/prefer-global/url": ["error", "always"]
}
}
```
**package.json** (An example)
```json
{
"name": "your-module",
"version": "1.0.0",
"engines": {
"node": ">=6.0.0"
}
}
```
## 📖 Rules
- ⭐️ - the mark of recommended rules.
- ✒️ - the mark of fixable rules.
<!--RULES_TABLE_START-->
### Possible Errors
| Rule ID | Description | |
|:--------|:------------|:--:|
| [node/no-extraneous-import](./docs/rules/no-extraneous-import.md) | disallow `import` declarations of extraneous packages | |
| [node/no-extraneous-require](./docs/rules/no-extraneous-require.md) | disallow `require()` expressions of extraneous packages | ⭐️ |
| [node/no-missing-import](./docs/rules/no-missing-import.md) | disallow `import` declarations of missing files | |
| [node/no-missing-require](./docs/rules/no-missing-require.md) | disallow `require()` expressions of missing files | ⭐️ |
| [node/no-unpublished-bin](./docs/rules/no-unpublished-bin.md) | disallow 'bin' files which are ignored by npm | ⭐️ |
| [node/no-unpublished-import](./docs/rules/no-unpublished-import.md) | disallow `import` declarations of private things | |
| [node/no-unpublished-require](./docs/rules/no-unpublished-require.md) | disallow `require()` expressions of private things | ⭐️ |
| [node/no-unsupported-features/es-builtins](./docs/rules/no-unsupported-features/es-builtins.md) | disallow unsupported ECMAScript built-ins on the specified version | ⭐️ |
| [node/no-unsupported-features/es-syntax](./docs/rules/no-unsupported-features/es-syntax.md) | disallow unsupported ECMAScript syntax on the specified version | ⭐️ |
| [node/no-unsupported-features/node-builtins](./docs/rules/no-unsupported-features/node-builtins.md) | disallow unsupported Node.js built-in APIs on the specified version | ⭐️ |
| [node/process-exit-as-throw](./docs/rules/process-exit-as-throw.md) | make `process.exit()` expressions the same code path as `throw` | ⭐️ |
| [node/shebang](./docs/rules/shebang.md) | enforce the correct usage of shebang | ⭐️✒️ |
### Best Practices
| Rule ID | Description | |
|:--------|:------------|:--:|
| [node/no-deprecated-api](./docs/rules/no-deprecated-api.md) | disallow deprecated APIs | ⭐️ |
### Stylistic Issues
| Rule ID | Description | |
|:--------|:------------|:--:|
| [node/exports-style](./docs/rules/exports-style.md) | enforce either `module.exports` or `exports` | |
| [node/prefer-global/buffer](./docs/rules/prefer-global/buffer.md) | enforce either `Buffer` or `require("buffer").Buffer` | |
| [node/prefer-global/console](./docs/rules/prefer-global/console.md) | enforce either `console` or `require("console")` | |
| [node/prefer-global/process](./docs/rules/prefer-global/process.md) | enforce either `process` or `require("process")` | |
| [node/prefer-global/text-decoder](./docs/rules/prefer-global/text-decoder.md) | enforce either `TextDecoder` or `require("util").TextDecoder` | |
| [node/prefer-global/text-encoder](./docs/rules/prefer-global/text-encoder.md) | enforce either `TextEncoder` or `require("util").TextEncoder` | |
| [node/prefer-global/url-search-params](./docs/rules/prefer-global/url-search-params.md) | enforce either `URLSearchParams` or `require("url").URLSearchParams` | |
| [node/prefer-global/url](./docs/rules/prefer-global/url.md) | enforce either `URL` or `require("url").URL` | |
### Deprecated rules
These rules have been deprecated in accordance with the [deprecation policy](https://eslint.org/docs/user-guide/rule-deprecation), and replaced by newer rules:
| Rule ID | Replaced by |
|:--------|:------------|
| [node/no-hide-core-modules](./docs/rules/no-hide-core-modules.md) | (nothing) |
| [node/no-unsupported-features](./docs/rules/no-unsupported-features.md) | [node/no-unsupported-features/es-syntax](./docs/rules/no-unsupported-features/es-syntax.md) and [node/no-unsupported-features/es-builtins](./docs/rules/no-unsupported-features/es-builtins.md) |
<!--RULES_TABLE_END-->
## 🔧 Configs
This plugin provides `plugin:node/recommended` preset config.
This preset config:
- enables the environment of ES2015 (ES6) and Node.js.
- enables rules which are given :star: in the above table.
- enables [no-process-exit](http://eslint.org/docs/rules/no-process-exit) rule because [the official document](https://nodejs.org/api/process.html#process_process_exit_code) does not recommend a use of `process.exit()`.
- adds `{ecmaVersion: 2019}` into `parserOptions`.
- adds `Atomics` and `SharedArrayBuffer` into `globals`.
- adds this plugin into `plugins`.
## 👫 FAQ
- Q: The `no-missing-import` / `no-missing-require` rules don't work with nested folders in SublimeLinter-eslint
- A: See [context.getFilename() in rule returns relative path](https://github.com/roadhump/SublimeLinter-eslint#contextgetfilename-in-rule-returns-relative-path) in the SublimeLinter-eslint FAQ.
## 🚥 Semantic Versioning Policy
`eslint-plugin-node` follows [semantic versioning](http://semver.org/) and [ESLint's Semantic Versioning Policy](https://github.com/eslint/eslint#semantic-versioning-policy).
- Patch release (intended to not break your lint build)
- A bug fix in a rule that results in it reporting fewer errors.
- Improvements to documentation.
- Non-user-facing changes such as refactoring code, adding, deleting, or modifying tests, and increasing test coverage.
- Re-releasing after a failed release (i.e., publishing a release that doesn't work for anyone).
- Minor release (might break your lint build)
- A bug fix in a rule that results in it reporting more errors.
- A new rule is created.
- A new option to an existing rule is created.
- An existing rule is deprecated.
- Major release (likely to break your lint build)
- A support for old Node version is dropped.
- A support for old ESLint version is dropped.
- An existing rule is changed in it reporting more errors.
- An existing rule is removed.
- An existing option of a rule is removed.
- An existing config is updated.
## 📰 Changelog
- [GitHub Releases](https://github.com/mysticatea/eslint-plugin-node/releases)
## 💎 Contributing
Welcome contributing!
Please use GitHub's Issues/PRs.
### Development Tools
- `npm test` runs tests and measures coverage.
- `npm run coverage` shows the coverage result of `npm test` command.
- `npm run clean` removes the coverage result of `npm test` command.
+40
View File
@@ -0,0 +1,40 @@
{
"parserOptions": {
"ecmaVersion": 2019
},
"env": {
"es6": true,
"node": true
},
"globals": {
"Atomics": false,
"SharedArrayBuffer": false
},
"plugins": [
"node"
],
"rules": {
"no-process-exit": "error",
"node/exports-style": "off",
"node/no-deprecated-api": "error",
"node/no-extraneous-import": "off",
"node/no-extraneous-require": "error",
"node/no-missing-import": "off",
"node/no-missing-require": "error",
"node/no-unpublished-bin": "error",
"node/no-unpublished-import": "off",
"node/no-unpublished-require": "error",
"node/no-unsupported-features/es-builtins": "error",
"node/no-unsupported-features/es-syntax": "error",
"node/no-unsupported-features/node-builtins": "error",
"node/prefer-global/buffer": "off",
"node/prefer-global/console": "off",
"node/prefer-global/process": "off",
"node/prefer-global/text-decoder": "off",
"node/prefer-global/text-encoder": "off",
"node/prefer-global/url-search-params": "off",
"node/prefer-global/url": "off",
"node/process-exit-as-throw": "error",
"node/shebang": "error"
}
}
+35
View File
@@ -0,0 +1,35 @@
/* DON'T EDIT THIS FILE. This is generated by 'scripts/update-lib-index.js' */
"use strict"
module.exports = {
configs: {
recommended: require("./configs/recommended.json"),
},
rules: {
"exports-style": require("./rules/exports-style"),
"no-deprecated-api": require("./rules/no-deprecated-api"),
"no-extraneous-import": require("./rules/no-extraneous-import"),
"no-extraneous-require": require("./rules/no-extraneous-require"),
"no-missing-import": require("./rules/no-missing-import"),
"no-missing-require": require("./rules/no-missing-require"),
"no-unpublished-bin": require("./rules/no-unpublished-bin"),
"no-unpublished-import": require("./rules/no-unpublished-import"),
"no-unpublished-require": require("./rules/no-unpublished-require"),
"no-unsupported-features/es-builtins": require("./rules/no-unsupported-features/es-builtins"),
"no-unsupported-features/es-syntax": require("./rules/no-unsupported-features/es-syntax"),
"no-unsupported-features/node-builtins": require("./rules/no-unsupported-features/node-builtins"),
"prefer-global/buffer": require("./rules/prefer-global/buffer"),
"prefer-global/console": require("./rules/prefer-global/console"),
"prefer-global/process": require("./rules/prefer-global/process"),
"prefer-global/text-decoder": require("./rules/prefer-global/text-decoder"),
"prefer-global/text-encoder": require("./rules/prefer-global/text-encoder"),
"prefer-global/url-search-params": require("./rules/prefer-global/url-search-params"),
"prefer-global/url": require("./rules/prefer-global/url"),
"process-exit-as-throw": require("./rules/process-exit-as-throw"),
shebang: require("./rules/shebang"),
// Deprecated rules.
"no-hide-core-modules": require("./rules/no-hide-core-modules"),
"no-unsupported-features": require("./rules/no-unsupported-features"),
},
}
+297
View File
@@ -0,0 +1,297 @@
/**
* @author Toru Nagashima
* See LICENSE file in root directory for full license.
*/
"use strict"
/*istanbul ignore next */
/**
* This function is copied from https://github.com/eslint/eslint/blob/2355f8d0de1d6732605420d15ddd4f1eee3c37b6/lib/ast-utils.js#L648-L684
*
* @param {ASTNode} node - The node to get.
* @returns {string|null} The property name if static. Otherwise, null.
* @private
*/
function getStaticPropertyName(node) {
let prop = null
switch (node && node.type) {
case "Property":
case "MethodDefinition":
prop = node.key
break
case "MemberExpression":
prop = node.property
break
// no default
}
switch (prop && prop.type) {
case "Literal":
return String(prop.value)
case "TemplateLiteral":
if (prop.expressions.length === 0 && prop.quasis.length === 1) {
return prop.quasis[0].value.cooked
}
break
case "Identifier":
if (!node.computed) {
return prop.name
}
break
// no default
}
return null
}
/**
* Checks whether the given node is assignee or not.
*
* @param {ASTNode} node - The node to check.
* @returns {boolean} `true` if the node is assignee.
*/
function isAssignee(node) {
return (
node.parent.type === "AssignmentExpression" && node.parent.left === node
)
}
/**
* Gets the top assignment expression node if the given node is an assignee.
*
* This is used to distinguish 2 assignees belong to the same assignment.
* If the node is not an assignee, this returns null.
*
* @param {ASTNode} leafNode - The node to get.
* @returns {ASTNode|null} The top assignment expression node, or null.
*/
function getTopAssignment(leafNode) {
let node = leafNode
// Skip MemberExpressions.
while (
node.parent.type === "MemberExpression" &&
node.parent.object === node
) {
node = node.parent
}
// Check assignments.
if (!isAssignee(node)) {
return null
}
// Find the top.
while (node.parent.type === "AssignmentExpression") {
node = node.parent
}
return node
}
/**
* Gets top assignment nodes of the given node list.
*
* @param {ASTNode[]} nodes - The node list to get.
* @returns {ASTNode[]} Gotten top assignment nodes.
*/
function createAssignmentList(nodes) {
return nodes.map(getTopAssignment).filter(Boolean)
}
/**
* Gets the reference of `module.exports` from the given scope.
*
* @param {escope.Scope} scope - The scope to get.
* @returns {ASTNode[]} Gotten MemberExpression node list.
*/
function getModuleExportsNodes(scope) {
const variable = scope.set.get("module")
if (variable == null) {
return []
}
return variable.references
.map(reference => reference.identifier.parent)
.filter(
node =>
node.type === "MemberExpression" &&
getStaticPropertyName(node) === "exports"
)
}
/**
* Gets the reference of `exports` from the given scope.
*
* @param {escope.Scope} scope - The scope to get.
* @returns {ASTNode[]} Gotten Identifier node list.
*/
function getExportsNodes(scope) {
const variable = scope.set.get("exports")
if (variable == null) {
return []
}
return variable.references.map(reference => reference.identifier)
}
module.exports = {
meta: {
docs: {
description: "enforce either `module.exports` or `exports`",
category: "Stylistic Issues",
recommended: false,
url:
"https://github.com/mysticatea/eslint-plugin-node/blob/v8.0.1/docs/rules/exports-style.md",
},
type: "suggestion",
fixable: null,
schema: [
{
//
enum: ["module.exports", "exports"],
},
{
type: "object",
properties: { allowBatchAssign: { type: "boolean" } },
additionalProperties: false,
},
],
},
create(context) {
const mode = context.options[0] || "module.exports"
const batchAssignAllowed = Boolean(
context.options[1] != null && context.options[1].allowBatchAssign
)
const sourceCode = context.getSourceCode()
/**
* Gets the location info of reports.
*
* exports = foo
* ^^^^^^^^^
*
* module.exports = foo
* ^^^^^^^^^^^^^^^^
*
* @param {ASTNode} node - The node of `exports`/`module.exports`.
* @returns {Location} The location info of reports.
*/
function getLocation(node) {
const token = sourceCode.getTokenAfter(node)
return {
start: node.loc.start,
end: token.loc.end,
}
}
/**
* Enforces `module.exports`.
* This warns references of `exports`.
*
* @returns {void}
*/
function enforceModuleExports() {
const globalScope = context.getScope()
const exportsNodes = getExportsNodes(globalScope)
const assignList = batchAssignAllowed
? createAssignmentList(getModuleExportsNodes(globalScope))
: []
for (const node of exportsNodes) {
// Skip if it's a batch assignment.
if (
assignList.length > 0 &&
assignList.indexOf(getTopAssignment(node)) !== -1
) {
continue
}
// Report.
context.report({
node,
loc: getLocation(node),
message:
"Unexpected access to 'exports'. Use 'module.exports' instead.",
})
}
}
/**
* Enforces `exports`.
* This warns references of `module.exports`.
*
* @returns {void}
*/
function enforceExports() {
const globalScope = context.getScope()
const exportsNodes = getExportsNodes(globalScope)
const moduleExportsNodes = getModuleExportsNodes(globalScope)
const assignList = batchAssignAllowed
? createAssignmentList(exportsNodes)
: []
const batchAssignList = []
for (const node of moduleExportsNodes) {
// Skip if it's a batch assignment.
if (assignList.length > 0) {
const found = assignList.indexOf(getTopAssignment(node))
if (found !== -1) {
batchAssignList.push(assignList[found])
assignList.splice(found, 1)
continue
}
}
// Report.
context.report({
node,
loc: getLocation(node),
message:
"Unexpected access to 'module.exports'. Use 'exports' instead.",
})
}
// Disallow direct assignment to `exports`.
for (const node of exportsNodes) {
// Skip if it's not assignee.
if (!isAssignee(node)) {
continue
}
// Check if it's a batch assignment.
if (batchAssignList.indexOf(getTopAssignment(node)) !== -1) {
continue
}
// Report.
context.report({
node,
loc: getLocation(node),
message:
"Unexpected assignment to 'exports'. Don't modify 'exports' itself.",
})
}
}
return {
"Program:exit"() {
switch (mode) {
case "module.exports":
enforceModuleExports()
break
case "exports":
enforceExports()
break
// no default
}
},
}
},
}
+560
View File
@@ -0,0 +1,560 @@
/**
* @author Toru Nagashima
* See LICENSE file in root directory for full license.
*/
"use strict"
const { CALL, CONSTRUCT, READ, ReferenceTracker } = require("eslint-utils")
const enumeratePropertyNames = require("../util/enumerate-property-names")
const modules = {
_linklist: {
[READ]: { since: "5.0.0", replacedBy: null },
},
assert: {
deepEqual: {
[READ]: {
since: "10.0.0",
replacedBy:
"'assert.deepStrictEqual' or 'assert.strict.deepEqual'",
},
},
equal: {
[READ]: {
since: "10.0.0",
replacedBy: "'assert.strictEqual' or 'assert.strict.equal'",
},
},
notDeepEqual: {
[READ]: {
since: "10.0.0",
replacedBy:
"'assert.notDeepStrictEqual' or 'assert.strict.notDeepEqual'",
},
},
notEqual: {
[READ]: {
since: "10.0.0",
replacedBy:
"'assert.notStrictEqual' or 'assert.strict.notEqual'",
},
},
},
//eslint-disable-next-line camelcase
async_hooks: {
currentId: {
[READ]: {
since: "8.2.0",
replacedBy: "'async_hooks.executionAsyncId()'",
},
},
triggerId: {
[READ]: {
since: "8.2.0",
replacedBy: "'async_hooks.triggerAsyncId()'",
},
},
},
buffer: {
Buffer: {
[CONSTRUCT]: {
since: "6.0.0",
replacedBy: "'buffer.Buffer.alloc()' or 'buffer.Buffer.from()'",
},
[CALL]: {
since: "6.0.0",
replacedBy: "'buffer.Buffer.alloc()' or 'buffer.Buffer.from()'",
},
},
SlowBuffer: {
[READ]: {
since: "6.0.0",
replacedBy: "'buffer.Buffer.allocUnsafeSlow()'",
},
},
},
constants: {
[READ]: {
since: "6.3.0",
replacedBy: "'constants' property of each module",
},
},
crypto: {
_toBuf: {
[READ]: { since: "11.0.0", replacedBy: null },
},
Credentials: {
[READ]: { since: "0.12.0", replacedBy: "'tls.SecureContext'" },
},
DEFAULT_ENCODING: {
[READ]: { since: "10.0.0", replacedBy: null },
},
createCipher: {
[READ]: {
since: "10.0.0",
replacedBy: "'crypto.createCipheriv()'",
},
},
createCredentials: {
[READ]: {
since: "0.12.0",
replacedBy: "'tls.createSecureContext()'",
},
},
createDecipher: {
[READ]: {
since: "10.0.0",
replacedBy: "'crypto.createDecipheriv()'",
},
},
fips: {
[READ]: {
since: "10.0.0",
replacedBy: "'crypto.getFips()' and 'crypto.setFips()'",
},
},
prng: {
[READ]: { since: "11.0.0", replacedBy: "'crypto.randomBytes()'" },
},
pseudoRandomBytes: {
[READ]: { since: "11.0.0", replacedBy: "'crypto.randomBytes()'" },
},
rng: {
[READ]: { since: "11.0.0", replacedBy: "'crypto.randomBytes()'" },
},
},
domain: {
[READ]: { since: "4.0.0", replacedBy: null },
},
events: {
EventEmitter: {
listenerCount: {
[READ]: {
since: "4.0.0",
replacedBy: "'events.EventEmitter#listenerCount()'",
},
},
},
listenerCount: {
[READ]: {
since: "4.0.0",
replacedBy: "'events.EventEmitter#listenerCount()'",
},
},
},
freelist: {
[READ]: { since: "4.0.0", replacedBy: null },
},
fs: {
SyncWriteStream: {
[READ]: { since: "4.0.0", replacedBy: null },
},
exists: {
[READ]: {
since: "4.0.0",
replacedBy: "'fs.stat()' or 'fs.access()'",
},
},
lchmod: {
[READ]: { since: "0.4.0", replacedBy: null },
},
lchmodSync: {
[READ]: { since: "0.4.0", replacedBy: null },
},
lchown: {
[READ]: { since: "0.4.0", replacedBy: null },
},
lchownSync: {
[READ]: { since: "0.4.0", replacedBy: null },
},
},
http: {
createClient: {
[READ]: { since: "0.10.0", replacedBy: "'http.request()'" },
},
},
module: {
Module: {
requireRepl: {
[READ]: { since: "6.0.0", replacedBy: "'require(\"repl\")'" },
},
_debug: {
[READ]: { since: "9.0.0", replacedBy: null },
},
},
requireRepl: {
[READ]: { since: "6.0.0", replacedBy: "'require(\"repl\")'" },
},
_debug: {
[READ]: { since: "9.0.0", replacedBy: null },
},
},
os: {
getNetworkInterfaces: {
[READ]: { since: "0.6.0", replacedBy: "'os.networkInterfaces()'" },
},
tmpDir: {
[READ]: { since: "7.0.0", replacedBy: "'os.tmpdir()'" },
},
},
path: {
_makeLong: {
[READ]: { since: "9.0.0", replacedBy: "'path.toNamespacedPath()'" },
},
},
process: {
EventEmitter: {
[READ]: { since: "0.6.0", replacedBy: "'require(\"events\")'" },
},
assert: {
[READ]: { since: "10.0.0", replacedBy: "'require(\"assert\")'" },
},
binding: {
[READ]: { since: "10.9.0", replacedBy: null },
},
env: {
NODE_REPL_HISTORY_FILE: {
[READ]: { since: "4.0.0", replacedBy: "'NODE_REPL_HISTORY'" },
},
},
},
punycode: {
[READ]: {
since: "7.0.0",
replacedBy: "'https://www.npmjs.com/package/punycode'",
},
},
readline: {
codePointAt: {
[READ]: { since: "4.0.0", replacedBy: null },
},
getStringWidth: {
[READ]: { since: "6.0.0", replacedBy: null },
},
isFullWidthCodePoint: {
[READ]: { since: "6.0.0", replacedBy: null },
},
stripVTControlCharacters: {
[READ]: { since: "6.0.0", replacedBy: null },
},
},
// safe-buffer.Buffer function/constructror is just a re-export of buffer.Buffer
// and should be deprecated likewise.
"safe-buffer": {
Buffer: {
[CONSTRUCT]: {
since: "6.0.0",
replacedBy: "'buffer.Buffer.alloc()' or 'buffer.Buffer.from()'",
},
[CALL]: {
since: "6.0.0",
replacedBy: "'buffer.Buffer.alloc()' or 'buffer.Buffer.from()'",
},
},
SlowBuffer: {
[READ]: {
since: "6.0.0",
replacedBy: "'buffer.Buffer.allocUnsafeSlow()'",
},
},
},
sys: {
[READ]: { since: "0.3.0", replacedBy: "'util' module" },
},
timers: {
enroll: {
[READ]: {
since: "10.0.0",
replacedBy: "'setTimeout()' or 'setInterval()'",
},
},
unenroll: {
[READ]: {
since: "10.0.0",
replacedBy: "'clearTimeout()' or 'clearInterval()'",
},
},
},
tls: {
CleartextStream: {
[READ]: { since: "0.10.0", replacedBy: null },
},
CryptoStream: {
[READ]: { since: "0.12.0", replacedBy: "'tls.TLSSocket'" },
},
SecurePair: {
[READ]: { since: "6.0.0", replacedBy: "'tls.TLSSocket'" },
},
convertNPNProtocols: {
[READ]: { since: "10.0.0", replacedBy: null },
},
createSecurePair: {
[READ]: { since: "6.0.0", replacedBy: "'tls.TLSSocket'" },
},
parseCertString: {
[READ]: { since: "8.6.0", replacedBy: "'querystring.parse()'" },
},
},
tty: {
setRawMode: {
[READ]: {
since: "0.10.0",
replacedBy:
"'tty.ReadStream#setRawMode()' (e.g. 'process.stdin.setRawMode()')",
},
},
},
url: {
parse: {
[READ]: { since: "11.0.0", replacedBy: "'url.URL' constructor" },
},
resolve: {
[READ]: { since: "11.0.0", replacedBy: "'url.URL' constructor" },
},
},
util: {
debug: {
[READ]: { since: "0.12.0", replacedBy: "'console.error()'" },
},
error: {
[READ]: { since: "0.12.0", replacedBy: "'console.error()'" },
},
isArray: {
[READ]: { since: "4.0.0", replacedBy: "'Array.isArray()'" },
},
isBoolean: {
[READ]: { since: "4.0.0", replacedBy: null },
},
isBuffer: {
[READ]: { since: "4.0.0", replacedBy: "'Buffer.isBuffer()'" },
},
isDate: {
[READ]: { since: "4.0.0", replacedBy: null },
},
isError: {
[READ]: { since: "4.0.0", replacedBy: null },
},
isFunction: {
[READ]: { since: "4.0.0", replacedBy: null },
},
isNull: {
[READ]: { since: "4.0.0", replacedBy: null },
},
isNullOrUndefined: {
[READ]: { since: "4.0.0", replacedBy: null },
},
isNumber: {
[READ]: { since: "4.0.0", replacedBy: null },
},
isObject: {
[READ]: { since: "4.0.0", replacedBy: null },
},
isPrimitive: {
[READ]: { since: "4.0.0", replacedBy: null },
},
isRegExp: {
[READ]: { since: "4.0.0", replacedBy: null },
},
isString: {
[READ]: { since: "4.0.0", replacedBy: null },
},
isSymbol: {
[READ]: { since: "4.0.0", replacedBy: null },
},
isUndefined: {
[READ]: { since: "4.0.0", replacedBy: null },
},
log: {
[READ]: { since: "6.0.0", replacedBy: "a third party module" },
},
print: {
[READ]: { since: "0.12.0", replacedBy: "'console.log()'" },
},
pump: {
[READ]: { since: "0.10.0", replacedBy: "'stream.Readable#pipe()'" },
},
puts: {
[READ]: { since: "0.12.0", replacedBy: "'console.log()'" },
},
_extend: {
[READ]: { since: "6.0.0", replacedBy: "'Object.assign()'" },
},
},
vm: {
runInDebugContext: {
[READ]: { since: "8.0.0", replacedBy: null },
},
},
}
const globals = {
Buffer: {
[CONSTRUCT]: {
since: "6.0.0",
replacedBy: "'Buffer.alloc()' or 'Buffer.from()'",
},
[CALL]: {
since: "6.0.0",
replacedBy: "'Buffer.alloc()' or 'Buffer.from()'",
},
},
COUNTER_NET_SERVER_CONNECTION: {
[READ]: { since: "11.0.0", replacedBy: null },
},
COUNTER_NET_SERVER_CONNECTION_CLOSE: {
[READ]: { since: "11.0.0", replacedBy: null },
},
COUNTER_HTTP_SERVER_REQUEST: {
[READ]: { since: "11.0.0", replacedBy: null },
},
COUNTER_HTTP_SERVER_RESPONSE: {
[READ]: { since: "11.0.0", replacedBy: null },
},
COUNTER_HTTP_CLIENT_REQUEST: {
[READ]: { since: "11.0.0", replacedBy: null },
},
COUNTER_HTTP_CLIENT_RESPONSE: {
[READ]: { since: "11.0.0", replacedBy: null },
},
GLOBAL: {
[READ]: { since: "6.0.0", replacedBy: "'global'" },
},
Intl: {
v8BreakIterator: {
[READ]: { since: "7.0.0", replacedBy: null },
},
},
require: {
extensions: {
[READ]: {
since: "0.12.0",
replacedBy: "compiling them ahead of time",
},
},
},
root: {
[READ]: { since: "6.0.0", replacedBy: "'global'" },
},
process: modules.process,
}
/**
* Makes a replacement message.
*
* @param {string|null} replacedBy - The text of substitute way.
* @returns {string} Replacement message.
*/
function toReplaceMessage(replacedBy) {
return replacedBy ? `. Use ${replacedBy} instead` : ""
}
/**
* Convert a given path to name.
* @param {symbol} type The report type.
* @param {string[]} path The property access path.
* @returns {string} The name.
*/
function toName(type, path) {
const baseName = path.join(".")
return type === ReferenceTracker.CALL
? `${baseName}()`
: type === ReferenceTracker.CONSTRUCT
? `new ${baseName}()`
: baseName
}
module.exports = {
meta: {
docs: {
description: "disallow deprecated APIs",
category: "Best Practices",
recommended: true,
url:
"https://github.com/mysticatea/eslint-plugin-node/blob/v8.0.1/docs/rules/no-deprecated-api.md",
},
type: "problem",
fixable: null,
schema: [
{
type: "object",
properties: {
ignoreModuleItems: {
type: "array",
items: {
enum: Array.from(enumeratePropertyNames(modules)),
},
additionalItems: false,
uniqueItems: true,
},
ignoreGlobalItems: {
type: "array",
items: {
enum: Array.from(enumeratePropertyNames(globals)),
},
additionalItems: false,
uniqueItems: true,
},
// Deprecated since v4.2.0
ignoreIndirectDependencies: { type: "boolean" },
},
additionalProperties: false,
},
],
},
create(context) {
const options = context.options[0] || {}
const ignoredModuleItems = new Set(options.ignoreModuleItems || [])
const ignoredGlobalItems = new Set(options.ignoreGlobalItems || [])
/**
* Reports a use of a deprecated API.
*
* @param {ASTNode} node - A node to report.
* @param {string} name - The name of a deprecated API.
* @param {{since: number, replacedBy: string}} info - Information of the API.
* @returns {void}
*/
function reportItem(node, name, info) {
context.report({
node,
loc: node.loc,
message:
"{{name}} was deprecated since v{{version}}{{replace}}.",
data: {
name,
version: info.since,
replace: toReplaceMessage(info.replacedBy),
},
})
}
return {
"Program:exit"() {
const tracker = new ReferenceTracker(context.getScope(), {
mode: "legacy",
})
for (const report of tracker.iterateGlobalReferences(globals)) {
const { node, path, type, info } = report
const name = toName(type, path)
if (!ignoredGlobalItems.has(name)) {
reportItem(node, `'${name}'`, info)
}
}
for (const report of [
...tracker.iterateCjsReferences(modules),
...tracker.iterateEsmReferences(modules),
]) {
const { node, path, type, info } = report
const name = toName(type, path)
const suffix = path.length === 1 ? " module" : ""
if (!ignoredModuleItems.has(name)) {
reportItem(node, `'${name}'${suffix}`, info)
}
}
},
}
},
}
+53
View File
@@ -0,0 +1,53 @@
/**
* @author Toru Nagashima
* See LICENSE file in root directory for full license.
*/
"use strict"
const checkExtraneous = require("../util/check-extraneous")
const getAllowModules = require("../util/get-allow-modules")
const getConvertPath = require("../util/get-convert-path")
const getImportTargets = require("../util/get-import-export-targets")
const getResolvePaths = require("../util/get-resolve-paths")
module.exports = {
meta: {
docs: {
description:
"disallow `import` declarations of extraneous packages",
category: "Possible Errors",
recommended: false,
url:
"https://github.com/mysticatea/eslint-plugin-node/blob/v8.0.1/docs/rules/no-extraneous-import.md",
},
type: "problem",
fixable: null,
schema: [
{
type: "object",
properties: {
allowModules: getAllowModules.schema,
convertPath: getConvertPath.schema,
resolvePaths: getResolvePaths.schema,
},
additionalProperties: false,
},
],
},
create(context) {
const filePath = context.getFilename()
if (filePath === "<input>") {
return {}
}
return {
"Program:exit"(node) {
checkExtraneous(
context,
filePath,
getImportTargets(context, node, false)
)
},
}
},
}
+53
View File
@@ -0,0 +1,53 @@
/**
* @author Toru Nagashima
* See LICENSE file in root directory for full license.
*/
"use strict"
const checkExtraneous = require("../util/check-extraneous")
const getAllowModules = require("../util/get-allow-modules")
const getConvertPath = require("../util/get-convert-path")
const getRequireTargets = require("../util/get-require-targets")
const getResolvePaths = require("../util/get-resolve-paths")
module.exports = {
meta: {
docs: {
description:
"disallow `require()` expressions of extraneous packages",
category: "Possible Errors",
recommended: true,
url:
"https://github.com/mysticatea/eslint-plugin-node/blob/v8.0.1/docs/rules/no-extraneous-require.md",
},
type: "problem",
fixable: null,
schema: [
{
type: "object",
properties: {
allowModules: getAllowModules.schema,
convertPath: getConvertPath.schema,
resolvePaths: getResolvePaths.schema,
},
additionalProperties: false,
},
],
},
create(context) {
const filePath = context.getFilename()
if (filePath === "<input>") {
return {}
}
return {
"Program:exit"() {
checkExtraneous(
context,
filePath,
getRequireTargets(context, false)
)
},
}
},
}
+144
View File
@@ -0,0 +1,144 @@
/**
* @author Toru Nagashima
* See LICENSE file in root directory for full license.
*
* @deprecated since v4.2.0
* This rule was based on an invalid assumption.
* No meaning.
*/
"use strict"
const path = require("path")
const resolve = require("resolve")
const getPackageJson = require("../util/get-package-json")
const getRequireTargets = require("../util/get-require-targets")
const getImportExportTargets = require("../util/get-import-export-targets")
const CORE_MODULES = new Set([
"assert",
"buffer",
"child_process",
"cluster",
"console",
"constants",
"crypto",
"dgram",
"dns",
/* "domain", */ "events",
"fs",
"http",
"https",
"module",
"net",
"os",
"path",
/* "punycode", */ "querystring",
"readline",
"repl",
"stream",
"string_decoder",
"timers",
"tls",
"tty",
"url",
"util",
"vm",
"zlib",
])
const BACK_SLASH = /\\/gu
module.exports = {
meta: {
docs: {
description:
"disallow third-party modules which are hiding core modules",
category: "Possible Errors",
recommended: false,
url:
"https://github.com/mysticatea/eslint-plugin-node/blob/v8.0.1/docs/rules/no-hide-core-modules.md",
},
type: "problem",
deprecated: true,
fixable: null,
schema: [
{
type: "object",
properties: {
allow: {
type: "array",
items: { enum: Array.from(CORE_MODULES) },
additionalItems: false,
uniqueItems: true,
},
ignoreDirectDependencies: { type: "boolean" },
ignoreIndirectDependencies: { type: "boolean" },
},
additionalProperties: false,
},
],
},
create(context) {
if (context.getFilename() === "<input>") {
return {}
}
const filePath = path.resolve(context.getFilename())
const dirPath = path.dirname(filePath)
const packageJson = getPackageJson(filePath)
const deps = new Set(
[].concat(
Object.keys((packageJson && packageJson.dependencies) || {}),
Object.keys((packageJson && packageJson.devDependencies) || {})
)
)
const options = context.options[0] || {}
const allow = options.allow || []
const ignoreDirectDependencies = Boolean(
options.ignoreDirectDependencies
)
const ignoreIndirectDependencies = Boolean(
options.ignoreIndirectDependencies
)
return {
"Program:exit"(node) {
const targets = []
.concat(
getRequireTargets(context, true),
getImportExportTargets(context, node, true)
)
.filter(t => CORE_MODULES.has(t.moduleName))
for (const target of targets) {
const name = target.moduleName
const allowed =
allow.indexOf(name) !== -1 ||
(ignoreDirectDependencies && deps.has(name)) ||
(ignoreIndirectDependencies && !deps.has(name))
if (allowed) {
continue
}
const resolved = resolve.sync(name, { basedir: dirPath })
const isCore = resolved === name
if (isCore) {
continue
}
context.report({
node: target.node,
loc: target.node.loc,
message:
"Unexpected import of third-party module '{{name}}'.",
data: {
name: path
.relative(dirPath, resolved)
.replace(BACK_SLASH, "/"),
},
})
}
},
}
},
}
+48
View File
@@ -0,0 +1,48 @@
/**
* @author Toru Nagashima
* See LICENSE file in root directory for full license.
*/
"use strict"
const checkExistence = require("../util/check-existence")
const getAllowModules = require("../util/get-allow-modules")
const getImportExportTargets = require("../util/get-import-export-targets")
const getResolvePaths = require("../util/get-resolve-paths")
const getTryExtensions = require("../util/get-try-extensions")
module.exports = {
meta: {
docs: {
description: "disallow `import` declarations of missing files",
category: "Possible Errors",
recommended: false,
url:
"https://github.com/mysticatea/eslint-plugin-node/blob/v8.0.1/docs/rules/no-missing-import.md",
},
type: "problem",
fixable: null,
schema: [
{
type: "object",
properties: {
allowModules: getAllowModules.schema,
tryExtensions: getTryExtensions.schema,
resolvePaths: getResolvePaths.schema,
},
additionalProperties: false,
},
],
},
create(context) {
const filePath = context.getFilename()
if (filePath === "<input>") {
return {}
}
return {
"Program:exit"(node) {
checkExistence(context, getImportExportTargets(context, node))
},
}
},
}
+48
View File
@@ -0,0 +1,48 @@
/**
* @author Toru Nagashima
* See LICENSE file in root directory for full license.
*/
"use strict"
const checkExistence = require("../util/check-existence")
const getAllowModules = require("../util/get-allow-modules")
const getRequireTargets = require("../util/get-require-targets")
const getResolvePaths = require("../util/get-resolve-paths")
const getTryExtensions = require("../util/get-try-extensions")
module.exports = {
meta: {
docs: {
description: "disallow `require()` expressions of missing files",
category: "Possible Errors",
recommended: true,
url:
"https://github.com/mysticatea/eslint-plugin-node/blob/v8.0.1/docs/rules/no-missing-require.md",
},
type: "problem",
fixable: null,
schema: [
{
type: "object",
properties: {
allowModules: getAllowModules.schema,
tryExtensions: getTryExtensions.schema,
resolvePaths: getResolvePaths.schema,
},
additionalProperties: false,
},
],
},
create(context) {
const filePath = context.getFilename()
if (filePath === "<input>") {
return {}
}
return {
"Program:exit"() {
checkExistence(context, getRequireTargets(context))
},
}
},
}
+97
View File
@@ -0,0 +1,97 @@
/**
* @author Toru Nagashima
* See LICENSE file in root directory for full license.
*/
"use strict"
const path = require("path")
const getConvertPath = require("../util/get-convert-path")
const getNpmignore = require("../util/get-npmignore")
const getPackageJson = require("../util/get-package-json")
/**
* Checks whether or not a given path is a `bin` file.
*
* @param {string} filePath - A file path to check.
* @param {string|object|undefined} binField - A value of the `bin` field of `package.json`.
* @param {string} basedir - A directory path that `package.json` exists.
* @returns {boolean} `true` if the file is a `bin` file.
*/
function isBinFile(filePath, binField, basedir) {
if (!binField) {
return false
}
if (typeof binField === "string") {
return filePath === path.resolve(basedir, binField)
}
return Object.keys(binField).some(
key => filePath === path.resolve(basedir, binField[key])
)
}
module.exports = {
meta: {
docs: {
description: "disallow 'bin' files which are ignored by npm",
category: "Possible Errors",
recommended: true,
url:
"https://github.com/mysticatea/eslint-plugin-node/blob/v8.0.1/docs/rules/no-unpublished-bin.md",
},
type: "problem",
fixable: null,
schema: [
{
type: "object",
properties: {
//
convertPath: getConvertPath.schema,
},
},
],
},
create(context) {
return {
Program(node) {
// Check file path.
let rawFilePath = context.getFilename()
if (rawFilePath === "<input>") {
return
}
rawFilePath = path.resolve(rawFilePath)
// Find package.json
const p = getPackageJson(rawFilePath)
if (!p) {
return
}
// Convert by convertPath option
const basedir = path.dirname(p.filePath)
const relativePath = getConvertPath(context)(
path.relative(basedir, rawFilePath).replace(/\\/gu, "/")
)
const filePath = path.join(basedir, relativePath)
// Check this file is bin.
if (!isBinFile(filePath, p.bin, basedir)) {
return
}
// Check ignored or not
const npmignore = getNpmignore(filePath)
if (!npmignore.match(relativePath)) {
return
}
// Report.
context.report({
node,
message:
"npm ignores '{{name}}'. Check 'files' field of 'package.json' or '.npmignore'.",
data: { name: relativePath },
})
},
}
},
}
+54
View File
@@ -0,0 +1,54 @@
/**
* @author Toru Nagashima
* See LICENSE file in root directory for full license.
*/
"use strict"
const checkPublish = require("../util/check-publish")
const getAllowModules = require("../util/get-allow-modules")
const getConvertPath = require("../util/get-convert-path")
const getImportExportTargets = require("../util/get-import-export-targets")
const getResolvePaths = require("../util/get-resolve-paths")
const getTryExtensions = require("../util/get-try-extensions")
module.exports = {
meta: {
docs: {
description: "disallow `import` declarations of private things",
category: "Possible Errors",
recommended: false,
url:
"https://github.com/mysticatea/eslint-plugin-node/blob/v8.0.1/docs/rules/no-unpublished-import.md",
},
type: "problem",
fixable: null,
schema: [
{
type: "object",
properties: {
allowModules: getAllowModules.schema,
convertPath: getConvertPath.schema,
resolvePaths: getResolvePaths.schema,
tryExtensions: getTryExtensions.schema,
},
additionalProperties: false,
},
],
},
create(context) {
const filePath = context.getFilename()
if (filePath === "<input>") {
return {}
}
return {
"Program:exit"(node) {
checkPublish(
context,
filePath,
getImportExportTargets(context, node)
)
},
}
},
}
+50
View File
@@ -0,0 +1,50 @@
/**
* @author Toru Nagashima
* See LICENSE file in root directory for full license.
*/
"use strict"
const checkPublish = require("../util/check-publish")
const getAllowModules = require("../util/get-allow-modules")
const getConvertPath = require("../util/get-convert-path")
const getRequireTargets = require("../util/get-require-targets")
const getResolvePaths = require("../util/get-resolve-paths")
const getTryExtensions = require("../util/get-try-extensions")
module.exports = {
meta: {
docs: {
description: "disallow `require()` expressions of private things",
category: "Possible Errors",
recommended: true,
url:
"https://github.com/mysticatea/eslint-plugin-node/blob/v8.0.1/docs/rules/no-unpublished-require.md",
},
type: "problem",
fixable: null,
schema: [
{
type: "object",
properties: {
allowModules: getAllowModules.schema,
convertPath: getConvertPath.schema,
resolvePaths: getResolvePaths.schema,
tryExtensions: getTryExtensions.schema,
},
additionalProperties: false,
},
],
},
create(context) {
const filePath = context.getFilename()
if (filePath === "<input>") {
return {}
}
return {
"Program:exit"() {
checkPublish(context, filePath, getRequireTargets(context))
},
}
},
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,167 @@
/**
* @author Toru Nagashima
* See LICENSE file in root directory for full license.
*/
"use strict"
const { READ } = require("eslint-utils")
const checkUnsupportedBuiltins = require("../../util/check-unsupported-builtins")
const enumeratePropertyNames = require("../../util/enumerate-property-names")
const trackMap = {
globals: {
Array: {
from: { [READ]: { supported: "4.0.0" } },
of: { [READ]: { supported: "4.0.0" } },
},
Map: {
[READ]: { supported: "0.12.0" },
},
Math: {
acosh: { [READ]: { supported: "0.12.0" } },
asinh: { [READ]: { supported: "0.12.0" } },
atanh: { [READ]: { supported: "0.12.0" } },
cbrt: { [READ]: { supported: "0.12.0" } },
clz32: { [READ]: { supported: "0.12.0" } },
cosh: { [READ]: { supported: "0.12.0" } },
expm1: { [READ]: { supported: "0.12.0" } },
fround: { [READ]: { supported: "0.12.0" } },
hypot: { [READ]: { supported: "0.12.0" } },
imul: { [READ]: { supported: "0.12.0" } },
log10: { [READ]: { supported: "0.12.0" } },
log1p: { [READ]: { supported: "0.12.0" } },
log2: { [READ]: { supported: "0.12.0" } },
sign: { [READ]: { supported: "0.12.0" } },
sinh: { [READ]: { supported: "0.12.0" } },
tanh: { [READ]: { supported: "0.12.0" } },
trunc: { [READ]: { supported: "0.12.0" } },
},
Number: {
EPSILON: { [READ]: { supported: "0.12.0" } },
isFinite: { [READ]: { supported: "0.10.0" } },
isInteger: { [READ]: { supported: "0.12.0" } },
isNaN: { [READ]: { supported: "0.10.0" } },
isSafeInteger: { [READ]: { supported: "0.12.0" } },
MAX_SAFE_INTEGER: { [READ]: { supported: "0.12.0" } },
MIN_SAFE_INTEGER: { [READ]: { supported: "0.12.0" } },
parseFloat: { [READ]: { supported: "0.12.0" } },
parseInt: { [READ]: { supported: "0.12.0" } },
},
Object: {
assign: { [READ]: { supported: "4.0.0" } },
getOwnPropertySymbols: { [READ]: { supported: "0.12.0" } },
is: { [READ]: { supported: "0.10.0" } },
setPrototypeOf: { [READ]: { supported: "0.12.0" } },
values: { [READ]: { supported: "7.0.0" } },
entries: { [READ]: { supported: "7.0.0" } },
getOwnPropertyDescriptors: { [READ]: { supported: "7.0.0" } },
},
Promise: {
[READ]: { supported: "0.12.0" },
},
Proxy: {
[READ]: { supported: "6.0.0" },
},
Reflect: {
[READ]: { supported: "6.0.0" },
},
Set: {
[READ]: { supported: "0.12.0" },
},
String: {
fromCodePoint: { [READ]: { supported: "4.0.0" } },
raw: { [READ]: { supported: "4.0.0" } },
},
Symbol: {
[READ]: { supported: "0.12.0" },
},
Int8Array: {
[READ]: { supported: "0.10.0" },
},
Uint8Array: {
[READ]: { supported: "0.10.0" },
},
Uint8ClampedArray: {
[READ]: { supported: "0.10.0" },
},
Int16Array: {
[READ]: { supported: "0.10.0" },
},
Uint16Array: {
[READ]: { supported: "0.10.0" },
},
Int32Array: {
[READ]: { supported: "0.10.0" },
},
Uint32Array: {
[READ]: { supported: "0.10.0" },
},
Float32Array: {
[READ]: { supported: "0.10.0" },
},
Float64Array: {
[READ]: { supported: "0.10.0" },
},
DataView: {
[READ]: { supported: "0.10.0" },
},
WeakMap: {
[READ]: { supported: "0.12.0" },
},
WeakSet: {
[READ]: { supported: "0.12.0" },
},
Atomics: {
[READ]: { supported: "8.10.0" },
},
SharedArrayBuffer: {
[READ]: { supported: "8.10.0" },
},
},
}
module.exports = {
meta: {
docs: {
description:
"disallow unsupported ECMAScript built-ins on the specified version",
category: "Possible Errors",
recommended: true,
url:
"https://github.com/mysticatea/eslint-plugin-node/blob/v8.0.1/docs/rules/no-unsupported-features/es-builtins.md",
},
type: "problem",
fixable: null,
schema: [
{
type: "object",
properties: {
version: {
type: "string",
},
ignores: {
type: "array",
items: {
enum: Array.from(
enumeratePropertyNames(trackMap.globals)
),
},
uniqueItems: true,
},
},
additionalProperties: false,
},
],
messages: {
unsupported:
"The '{{name}}' is not supported until Node.js {{supported}}. The configured version range is '{{version}}'.",
},
},
create(context) {
return {
"Program:exit"() {
checkUnsupportedBuiltins(context, trackMap)
},
}
},
}
@@ -0,0 +1,628 @@
/**
* @author Toru Nagashima
* See LICENSE file in root directory for full license.
*/
"use strict"
const { rules: esRules } = require("eslint-plugin-es")
const { getInnermostScope } = require("eslint-utils")
const { Range } = require("semver") //eslint-disable-line no-unused-vars
const getConfiguredNodeVersion = require("../../util/get-configured-node-version")
const getSemverRange = require("../../util/get-semver-range")
const getOrSet = /^(?:g|s)et$/u
const features = {
//--------------------------------------------------------------------------
// ES2015
//--------------------------------------------------------------------------
arrowFunctions: {
ruleId: "no-arrow-functions",
cases: [
{
supported: "4.0.0",
messageId: "no-arrow-functions",
},
],
},
binaryNumericLiterals: {
ruleId: "no-binary-numeric-literals",
cases: [
{
supported: "4.0.0",
messageId: "no-binary-numeric-literals",
},
],
},
blockScopedFunctions: {
ruleId: "no-block-scoped-functions",
cases: [
{
supported: "6.0.0",
test: info => !info.isStrict,
messageId: "no-block-scoped-functions-sloppy",
},
{
supported: "4.0.0",
messageId: "no-block-scoped-functions-strict",
},
],
},
blockScopedVariables: {
ruleId: "no-block-scoped-variables",
cases: [
{
supported: "6.0.0",
test: info => !info.isStrict,
messageId: "no-block-scoped-variables-sloppy",
},
{
supported: "4.0.0",
messageId: "no-block-scoped-variables-strict",
},
],
},
classes: {
ruleId: "no-classes",
cases: [
{
supported: "6.0.0",
test: info => !info.isStrict,
messageId: "no-classes-sloppy",
},
{
supported: "4.0.0",
messageId: "no-classes-strict",
},
],
},
computedProperties: {
ruleId: "no-computed-properties",
cases: [
{
supported: "4.0.0",
messageId: "no-computed-properties",
},
],
},
defaultParameters: {
ruleId: "no-default-parameters",
cases: [
{
supported: "6.0.0",
messageId: "no-default-parameters",
},
],
},
destructuring: {
ruleId: "no-destructuring",
cases: [
{
supported: "6.0.0",
messageId: "no-destructuring",
},
],
},
forOfLoops: {
ruleId: "no-for-of-loops",
cases: [
{
supported: "0.12.0",
messageId: "no-for-of-loops",
},
],
},
generators: {
ruleId: "no-generators",
cases: [
{
supported: "4.0.0",
messageId: "no-generators",
},
],
},
modules: {
ruleId: "no-modules",
cases: [
{
supported: null,
messageId: "no-modules",
},
],
},
"new.target": {
ruleId: "no-new-target",
cases: [
{
supported: "5.0.0",
messageId: "no-new-target",
},
],
},
objectSuperProperties: {
ruleId: "no-object-super-properties",
cases: [
{
supported: "4.0.0",
messageId: "no-object-super-properties",
},
],
},
octalNumericLiterals: {
ruleId: "no-octal-numeric-literals",
cases: [
{
supported: "4.0.0",
messageId: "no-octal-numeric-literals",
},
],
},
propertyShorthands: {
ruleId: "no-property-shorthands",
cases: [
{
supported: "6.0.0",
test: info =>
info.node.shorthand && getOrSet.test(info.node.key.name),
messageId: "no-property-shorthands-getset",
},
{
supported: "4.0.0",
messageId: "no-property-shorthands",
},
],
},
regexpU: {
ruleId: "no-regexp-u-flag",
cases: [
{
supported: "6.0.0",
messageId: "no-regexp-u-flag",
},
],
},
regexpY: {
ruleId: "no-regexp-y-flag",
cases: [
{
supported: "6.0.0",
messageId: "no-regexp-y-flag",
},
],
},
restParameters: {
ruleId: "no-rest-parameters",
cases: [
{
supported: "6.0.0",
messageId: "no-rest-parameters",
},
],
},
spreadElements: {
ruleId: "no-spread-elements",
cases: [
{
supported: "5.0.0",
messageId: "no-spread-elements",
},
],
},
templateLiterals: {
ruleId: "no-template-literals",
cases: [
{
supported: "4.0.0",
messageId: "no-template-literals",
},
],
},
unicodeCodePointEscapes: {
ruleId: "no-unicode-codepoint-escapes",
cases: [
{
supported: "4.0.0",
messageId: "no-unicode-codepoint-escapes",
},
],
},
//--------------------------------------------------------------------------
// ES2016
//--------------------------------------------------------------------------
exponentialOperators: {
ruleId: "no-exponential-operators",
cases: [
{
supported: "7.0.0",
messageId: "no-exponential-operators",
},
],
},
//--------------------------------------------------------------------------
// ES2017
//--------------------------------------------------------------------------
asyncFunctions: {
ruleId: "no-async-functions",
cases: [
{
supported: "7.6.0",
messageId: "no-async-functions",
},
],
},
trailingCommasInFunctions: {
ruleId: "no-trailing-function-commas",
cases: [
{
supported: "8.0.0",
messageId: "no-trailing-function-commas",
},
],
},
//--------------------------------------------------------------------------
// ES2018
//--------------------------------------------------------------------------
asyncIteration: {
ruleId: "no-async-iteration",
cases: [
{
supported: "10.0.0",
messageId: "no-async-iteration",
},
],
},
malformedTemplateLiterals: {
ruleId: "no-malformed-template-literals",
cases: [
{
supported: "8.10.0",
messageId: "no-malformed-template-literals",
},
],
},
regexpLookbehind: {
ruleId: "no-regexp-lookbehind-assertions",
cases: [
{
supported: "8.10.0",
messageId: "no-regexp-lookbehind-assertions",
},
],
},
regexpNamedCaptureGroups: {
ruleId: "no-regexp-named-capture-groups",
cases: [
{
supported: "10.0.0",
messageId: "no-regexp-named-capture-groups",
},
],
},
regexpS: {
ruleId: "no-regexp-s-flag",
cases: [
{
supported: "8.10.0",
messageId: "no-regexp-s-flag",
},
],
},
regexpUnicodeProperties: {
ruleId: "no-regexp-unicode-property-escapes",
cases: [
{
supported: "10.0.0",
messageId: "no-regexp-unicode-property-escapes",
},
],
},
restSpreadProperties: {
ruleId: "no-rest-spread-properties",
cases: [
{
supported: "8.3.0",
messageId: "no-rest-spread-properties",
},
],
},
//--------------------------------------------------------------------------
// ES2019
//--------------------------------------------------------------------------
jsonSuperset: {
ruleId: "no-json-superset",
cases: [
{
supported: "10.0.0",
messageId: "no-json-superset",
},
],
},
optionalCatchBinding: {
ruleId: "no-optional-catch-binding",
cases: [
{
supported: "10.0.0",
messageId: "no-optional-catch-binding",
},
],
},
}
const keywords = Object.keys(features)
/**
* Parses the options.
* @param {RuleContext} context The rule context.
* @returns {{version:Range,ignores:Set<string>}} Parsed value.
*/
function parseOptions(context) {
const raw = context.options[0] || {}
const filePath = context.getFilename()
const version = getConfiguredNodeVersion(raw.version, filePath)
const ignores = new Set(raw.ignores || [])
return Object.freeze({ version, ignores })
}
/**
* Find the scope that a given node belongs to.
* @param {Scope} initialScope The initial scope to find.
* @param {Node} node The AST node.
* @returns {Scope} The scope that the node belongs to.
*/
function nomalizeScope(initialScope, node) {
let scope = getInnermostScope(initialScope, node)
while (scope && scope.block === node) {
scope = scope.upper
}
return scope
}
/**
* Merge two visitors.
* @param {Visitor} x The visitor which is assigned.
* @param {Visitor} y The visitor which is assigning.
* @returns {Visitor} `x`.
*/
function merge(x, y) {
for (const key of Object.keys(y)) {
if (typeof x[key] === "function") {
if (x[key]._handlers == null) {
const fs = [x[key], y[key]]
x[key] = dispatch.bind(null, fs)
x[key]._handlers = fs
} else {
x[key]._handlers.push(y[key])
}
} else {
x[key] = y[key]
}
}
return x
}
/**
* Dispatch all given functions with a node.
* @param {function[]} handlers The function list to call.
* @param {Node} node The AST node to be handled.
* @returns {void}
*/
function dispatch(handlers, node) {
for (const h of handlers) {
h(node)
}
}
/**
* Define the visitor object as merging the rules of eslint-plugin-es.
* @param {RuleContext} context The rule context.
* @param {{version:Range,ignores:Set<string>}} options The options.
* @returns {object} The defined visitor.
*/
function defineVisitor(context, options) {
const testInfoPrototype = {
get isStrict() {
return nomalizeScope(context.getScope(), this.node).isStrict
},
}
/**
* Check whether a given case object is full-supported on the configured node version.
* @param {{supported:string}} aCase The case object to check.
* @returns {boolean} `true` if it's supporting.
*/
function isNotSupportingVersion(aCase) {
return (
!aCase.supported ||
options.version.intersects(getSemverRange(`<${aCase.supported}`))
)
}
/**
* Define the predicate function to check whether a given case object is supported on the configured node version.
* @param {Node} node The node which is reported.
* @returns {function(aCase:{supported:string}):boolean} The predicate function.
*/
function isNotSupportingOn(node) {
return aCase =>
isNotSupportingVersion(aCase) &&
(!aCase.test || aCase.test({ node, __proto__: testInfoPrototype }))
}
return (
keywords
// Omit full-supported features and ignored features by options
// because this rule never reports those.
.filter(
keyword =>
!options.ignores.has(keyword) &&
features[keyword].cases.some(isNotSupportingVersion)
)
// Merge remaining features with overriding `context.report()`.
.reduce((visitor, keyword) => {
const { ruleId, cases } = features[keyword]
const rule = esRules[ruleId]
const thisContext = {
__proto__: context,
// Override `context.report()` then:
// - ignore if it's supported.
// - override reporting messages.
report(descriptor) {
// Set additional information.
if (descriptor.data) {
descriptor.data.version = options.version.raw
} else {
descriptor.data = { version: options.version.raw }
}
descriptor.fix = undefined
// Test and report.
const node = descriptor.node
const hitCase = cases.find(isNotSupportingOn(node))
if (hitCase) {
descriptor.messageId = hitCase.messageId
descriptor.data.supported = hitCase.supported
super.report(descriptor)
}
},
}
return merge(visitor, rule.create(thisContext))
}, {})
)
}
module.exports = {
meta: {
docs: {
description:
"disallow unsupported ECMAScript syntax on the specified version",
category: "Possible Errors",
recommended: true,
url:
"https://github.com/mysticatea/eslint-plugin-node/blob/v8.0.1/docs/rules/no-unsupported-features/es-syntax.md",
},
type: "problem",
fixable: null,
schema: [
{
type: "object",
properties: {
version: {
type: "string",
},
ignores: {
type: "array",
items: {
enum: Object.keys(features),
},
uniqueItems: true,
},
},
additionalProperties: false,
},
],
messages: {
//------------------------------------------------------------------
// ES2015
//------------------------------------------------------------------
"no-arrow-functions":
"Arrow functions are not supported until Node.js {{supported}}. The configured version range is '{{version}}'.",
"no-binary-numeric-literals":
"Binary numeric literals are not supported until Node.js {{supported}}. The configured version range is '{{version}}'.",
"no-block-scoped-functions-strict":
"Block-scoped functions in strict mode are not supported until Node.js {{supported}}. The configured version range is '{{version}}'.",
"no-block-scoped-functions-sloppy":
"Block-scoped functions in non-strict mode are not supported until Node.js {{supported}}. The configured version range is '{{version}}'.",
"no-block-scoped-variables-strict":
"Block-scoped variables in strict mode are not supported until Node.js {{supported}}. The configured version range is '{{version}}'.",
"no-block-scoped-variables-sloppy":
"Block-scoped variables in non-strict mode are not supported until Node.js {{supported}}. The configured version range is '{{version}}'.",
"no-classes-strict":
"Classes in strict mode are not supported until Node.js {{supported}}. The configured version range is '{{version}}'.",
"no-classes-sloppy":
"Classes in non-strict mode are not supported until Node.js {{supported}}. The configured version range is '{{version}}'.",
"no-computed-properties":
"Computed properties are not supported until Node.js {{supported}}. The configured version range is '{{version}}'.",
"no-default-parameters":
"Default parameters are not supported until Node.js {{supported}}. The configured version range is '{{version}}'.",
"no-destructuring":
"Destructuring is not supported until Node.js {{supported}}. The configured version range is '{{version}}'.",
"no-for-of-loops":
"'for-of' loops are not supported until Node.js {{supported}}. The configured version range is '{{version}}'.",
"no-generators":
"Generator functions are not supported until Node.js {{supported}}. The configured version range is '{{version}}'.",
"no-modules":
"Import and export declarations are not supported yet.",
"no-new-target":
"'new.target' is not supported until Node.js {{supported}}. The configured version range is '{{version}}'.",
"no-object-super-properties":
"'super' in object literals is not supported until Node.js {{supported}}. The configured version range is '{{version}}'.",
"no-octal-numeric-literals":
"Octal numeric literals are not supported until Node.js {{supported}}. The configured version range is '{{version}}'.",
"no-property-shorthands":
"Property shorthands are not supported until Node.js {{supported}}. The configured version range is '{{version}}'.",
"no-property-shorthands-getset":
"Property shorthands of 'get' and 'set' are not supported until Node.js {{supported}}. The configured version range is '{{version}}'.",
"no-regexp-u-flag":
"RegExp 'u' flag is not supported until Node.js {{supported}}. The configured version range is '{{version}}'.",
"no-regexp-y-flag":
"RegExp 'y' flag is not supported until Node.js {{supported}}. The configured version range is '{{version}}'.",
"no-rest-parameters":
"Rest parameters are not supported until Node.js {{supported}}. The configured version range is '{{version}}'.",
"no-spread-elements":
"Spread elements are not supported until Node.js {{supported}}. The configured version range is '{{version}}'.",
"no-template-literals":
"Template literals are not supported until Node.js {{supported}}. The configured version range is '{{version}}'.",
"no-unicode-codepoint-escapes":
"Unicode code point escapes are not supported until Node.js {{supported}}. The configured version range is '{{version}}'.",
//------------------------------------------------------------------
// ES2016
//------------------------------------------------------------------
"no-exponential-operators":
"Exponential operators are not supported until Node.js {{supported}}. The configured version range is '{{version}}'.",
//------------------------------------------------------------------
// ES2017
//------------------------------------------------------------------
"no-async-functions":
"Async functions are not supported until Node.js {{supported}}. The configured version range is '{{version}}'.",
"no-trailing-function-commas":
"Trailing commas in function syntax are not supported until Node.js {{supported}}. The configured version range is '{{version}}'.",
//------------------------------------------------------------------
// ES2018
//------------------------------------------------------------------
"no-async-iteration":
"Async iteration is not supported until Node.js {{supported}}. The configured version range is '{{version}}'.",
"no-malformed-template-literals":
"Malformed template literals are not supported until Node.js {{supported}}. The configured version range is '{{version}}'.",
"no-regexp-lookbehind-assertions":
"RegExp lookbehind assertions are not supported until Node.js {{supported}}. The configured version range is '{{version}}'.",
"no-regexp-named-capture-groups":
"RegExp named capture groups are not supported until Node.js {{supported}}. The configured version range is '{{version}}'.",
"no-regexp-s-flag":
"RegExp 's' flag is not supported until Node.js {{supported}}. The configured version range is '{{version}}'.",
"no-regexp-unicode-property-escapes":
"RegExp Unicode property escapes are not supported until Node.js {{supported}}. The configured version range is '{{version}}'.",
"no-rest-spread-properties":
"Rest/spread properties are not supported until Node.js {{supported}}. The configured version range is '{{version}}'.",
//------------------------------------------------------------------
// ES2019
//------------------------------------------------------------------
"no-json-superset":
"'\\u{{code}}' in string literals is not supported until Node.js {{supported}}. The configured version range is '{{version}}'.",
"no-optional-catch-binding":
"The omission of 'catch' binding is not supported until Node.js {{supported}}. The configured version range is '{{version}}'.",
},
},
create(context) {
return defineVisitor(context, parseOptions(context))
},
}
@@ -0,0 +1,276 @@
/**
* @author Toru Nagashima
* See LICENSE file in root directory for full license.
*/
"use strict"
const { READ } = require("eslint-utils")
const checkUnsupportedBuiltins = require("../../util/check-unsupported-builtins")
const enumeratePropertyNames = require("../../util/enumerate-property-names")
/*eslint-disable camelcase */
const trackMap = {
globals: {
queueMicrotask: { [READ]: { supported: "11.0.0" } },
require: {
resolve: {
paths: { [READ]: { supported: "8.9.0" } },
},
},
},
modules: {
assert: {
strict: {
[READ]: { supported: "9.9.0" },
doesNotReject: { [READ]: { supported: "10.0.0" } },
rejects: { [READ]: { supported: "10.0.0" } },
},
deepStrictEqual: { [READ]: { supported: "4.0.0" } },
doesNotReject: { [READ]: { supported: "10.0.0" } },
notDeepStrictEqual: { [READ]: { supported: "4.0.0" } },
rejects: { [READ]: { supported: "10.0.0" } },
},
async_hooks: {
[READ]: { supported: "8.0.0" },
createHook: { [READ]: { supported: "8.1.0" } },
},
buffer: {
Buffer: {
alloc: { [READ]: { supported: "4.5.0" } },
allocUnsafe: { [READ]: { supported: "4.5.0" } },
allocUnsafeSlow: { [READ]: { supported: "4.5.0" } },
from: { [READ]: { supported: "4.5.0" } },
},
kMaxLength: { [READ]: { supported: "3.0.0" } },
transcode: { [READ]: { supported: "7.1.0" } },
constants: { [READ]: { supported: "8.2.0" } },
},
child_process: {
ChildProcess: { [READ]: { supported: "2.2.0" } },
},
console: {
clear: { [READ]: { supported: "8.3.0" } },
count: { [READ]: { supported: "8.3.0" } },
countReset: { [READ]: { supported: "8.3.0" } },
debug: { [READ]: { supported: "8.0.0" } },
dirxml: { [READ]: { supported: "8.0.0" } },
group: { [READ]: { supported: "8.5.0" } },
groupCollapsed: { [READ]: { supported: "8.5.0" } },
groupEnd: { [READ]: { supported: "8.5.0" } },
table: { [READ]: { supported: "10.0.0" } },
markTimeline: { [READ]: { supported: "8.0.0" } },
profile: { [READ]: { supported: "8.0.0" } },
profileEnd: { [READ]: { supported: "8.0.0" } },
timeLog: { [READ]: { supported: "10.7.0" } },
timeStamp: { [READ]: { supported: "8.0.0" } },
timeline: { [READ]: { supported: "8.0.0" } },
timelineEnd: { [READ]: { supported: "8.0.0" } },
},
crypto: {
Certificate: {
exportChallenge: { [READ]: { supported: "9.0.0" } },
exportPublicKey: { [READ]: { supported: "9.0.0" } },
verifySpkac: { [READ]: { supported: "9.0.0" } },
},
constants: { [READ]: { supported: "6.3.0" } },
fips: { [READ]: { supported: "6.0.0" } },
generateKeyPair: { [READ]: { supported: "10.12.0" } },
generateKeyPairSync: { [READ]: { supported: "10.12.0" } },
getCurves: { [READ]: { supported: "2.3.0" } },
getFips: { [READ]: { supported: "10.0.0" } },
privateEncrypt: { [READ]: { supported: "1.1.0" } },
publicDecrypt: { [READ]: { supported: "1.1.0" } },
randomFillSync: { [READ]: { supported: "7.10.0" } },
randomFill: { [READ]: { supported: "7.10.0" } },
scrypt: { [READ]: { supported: "10.5.0" } },
scryptSync: { [READ]: { supported: "10.5.0" } },
setFips: { [READ]: { supported: "10.0.0" } },
timingSafeEqual: { [READ]: { supported: "6.6.0" } },
},
dns: {
Resolver: { [READ]: { supported: "8.3.0" } },
resolvePtr: { [READ]: { supported: "6.0.0" } },
promises: {
[READ]: { supported: "10.6.0" },
},
},
fs: {
Dirent: { [READ]: { supported: "10.10.0" } },
copyFile: { [READ]: { supported: "8.5.0" } },
copyFileSync: { [READ]: { supported: "8.5.0" } },
mkdtemp: { [READ]: { supported: "5.10.0" } },
mkdtempSync: { [READ]: { supported: "5.10.0" } },
realpath: {
native: { [READ]: { supported: "9.2.0" } },
},
realpathSync: {
native: { [READ]: { supported: "9.2.0" } },
},
promises: {
[READ]: { supported: "10.1.0" },
},
},
http2: {
[READ]: { supported: "8.4.0" },
},
inspector: {
[READ]: { supported: "8.0.0" },
},
module: {
builtinModules: { [READ]: { supported: "9.3.0" } },
},
os: {
constants: {
[READ]: { supported: "6.3.0" },
priority: { [READ]: { supported: "10.10.0" } },
},
getPriority: { [READ]: { supported: "10.10.0" } },
homedir: { [READ]: { supported: "2.3.0" } },
setPriority: { [READ]: { supported: "10.10.0" } },
userInfo: { [READ]: { supported: "6.0.0" } },
},
path: {
toNamespacedPath: { [READ]: { supported: "9.0.0" } },
},
perf_hooks: {
[READ]: { supported: "8.5.0" },
},
process: {
allowedNodeEnvironmentFlags: { [READ]: { supported: "10.10.0" } },
argv0: { [READ]: { supported: "6.4.0" } },
channel: { [READ]: { supported: "7.1.0" } },
cpuUsage: { [READ]: { supported: "6.1.0" } },
emitWarning: { [READ]: { supported: "6.0.0" } },
getegid: { [READ]: { supported: "2.0.0" } },
geteuid: { [READ]: { supported: "2.0.0" } },
hasUncaughtExceptionCaptureCallback: {
[READ]: { supported: "9.3.0" },
},
hrtime: {
bigint: { [READ]: { supported: "10.7.0" } },
},
ppid: { [READ]: { supported: "9.2.0" } },
release: { [READ]: { supported: "3.0.0" } },
setegid: { [READ]: { supported: "2.0.0" } },
seteuid: { [READ]: { supported: "2.0.0" } },
setUncaughtExceptionCaptureCallback: {
[READ]: { supported: "9.3.0" },
},
},
stream: {
finished: { [READ]: { supported: "10.0.0" } },
pipeline: { [READ]: { supported: "10.0.0" } },
},
trace_events: {
[READ]: { supported: "10.0.0" },
},
url: {
URL: { [READ]: { supported: "7.0.0" } },
URLSearchParams: { [READ]: { supported: "7.5.0" } },
domainToASCII: { [READ]: { supported: "7.4.0" } },
domainToUnicode: { [READ]: { supported: "7.4.0" } },
},
util: {
callbackify: { [READ]: { supported: "8.2.0" } },
formatWithOptions: { [READ]: { supported: "10.0.0" } },
getSystemErrorName: { [READ]: { supported: "9.7.0" } },
inspect: {
custom: { [READ]: { supported: "6.6.0" } },
defaultOptions: { [READ]: { supported: "6.4.0" } },
},
isDeepStrictEqual: { [READ]: { supported: "9.0.0" } },
promisify: { [READ]: { supported: "8.0.0" } },
TextDecoder: { [READ]: { supported: "8.3.0" } },
TextEncoder: { [READ]: { supported: "8.3.0" } },
types: {
[READ]: { supported: "10.0.0" },
isBoxedPrimitive: { [READ]: { supported: "10.11.0" } },
},
},
v8: {
[READ]: { supported: "1.0.0" },
cachedDataVersionTag: { [READ]: { supported: "8.0.0" } },
getHeapSpaceStatistics: { [READ]: { supported: "6.0.0" } },
serialize: { [READ]: { supported: "8.0.0" } },
deserialize: { [READ]: { supported: "8.0.0" } },
Serializer: { [READ]: { supported: "8.0.0" } },
Deserializer: { [READ]: { supported: "8.0.0" } },
DefaultSerializer: { [READ]: { supported: "8.0.0" } },
DefaultDeserializer: { [READ]: { supported: "8.0.0" } },
},
vm: {
Module: { [READ]: { supported: "9.6.0" } },
compileFunction: { [READ]: { supported: "10.10.0" } },
},
worker_threads: {
[READ]: { supported: "10.5.0" },
},
},
}
Object.assign(trackMap.globals, {
Buffer: trackMap.modules.buffer.Buffer,
TextDecoder: Object.assign({}, trackMap.modules.util.TextDecoder, {
[READ]: { supported: "11.0.0" },
}),
TextEncoder: Object.assign({}, trackMap.modules.util.TextEncoder, {
[READ]: { supported: "11.0.0" },
}),
URL: Object.assign({}, trackMap.modules.url.URL, {
[READ]: { supported: "10.0.0" },
}),
URLSearchParams: Object.assign({}, trackMap.modules.url.URLSearchParams, {
[READ]: { supported: "10.0.0" },
}),
console: trackMap.modules.console,
process: trackMap.modules.process,
})
/*eslint-enable camelcase */
module.exports = {
meta: {
docs: {
description:
"disallow unsupported Node.js built-in APIs on the specified version",
category: "Possible Errors",
recommended: true,
url:
"https://github.com/mysticatea/eslint-plugin-node/blob/v8.0.1/docs/rules/no-unsupported-features/node-builtins.md",
},
type: "problem",
fixable: null,
schema: [
{
type: "object",
properties: {
version: {
type: "string",
},
ignores: {
type: "array",
items: {
enum: Array.from(
new Set([
...enumeratePropertyNames(trackMap.globals),
...enumeratePropertyNames(trackMap.modules),
])
),
},
uniqueItems: true,
},
},
additionalProperties: false,
},
],
messages: {
unsupported:
"The '{{name}}' is not supported until Node.js {{supported}}. The configured version range is '{{version}}'.",
},
},
create(context) {
return {
"Program:exit"() {
checkUnsupportedBuiltins(context, trackMap)
},
}
},
}
+49
View File
@@ -0,0 +1,49 @@
/**
* @author Toru Nagashima
* See LICENSE file in root directory for full license.
*/
"use strict"
const { READ } = require("eslint-utils")
const checkForPreferGlobal = require("../../util/check-prefer-global")
const trackMap = {
globals: {
Buffer: { [READ]: true },
},
modules: {
buffer: {
Buffer: { [READ]: true },
},
},
}
module.exports = {
meta: {
docs: {
description:
'enforce either `Buffer` or `require("buffer").Buffer`',
category: "Stylistic Issues",
recommended: false,
url:
"https://github.com/mysticatea/eslint-plugin-node/blob/v8.0.1/docs/rules/prefer-global/buffer.md",
},
type: "suggestion",
fixable: null,
schema: [{ enum: ["always", "never"] }],
messages: {
preferGlobal:
"Unexpected use of 'require(\"buffer\").Buffer'. Use the global variable 'Buffer' instead.",
preferModule:
"Unexpected use of the global variable 'Buffer'. Use 'require(\"buffer\").Buffer' instead.",
},
},
create(context) {
return {
"Program:exit"() {
checkForPreferGlobal(context, trackMap)
},
}
},
}
+46
View File
@@ -0,0 +1,46 @@
/**
* @author Toru Nagashima
* See LICENSE file in root directory for full license.
*/
"use strict"
const { READ } = require("eslint-utils")
const checkForPreferGlobal = require("../../util/check-prefer-global")
const trackMap = {
globals: {
console: { [READ]: true },
},
modules: {
console: { [READ]: true },
},
}
module.exports = {
meta: {
docs: {
description: 'enforce either `console` or `require("console")`',
category: "Stylistic Issues",
recommended: false,
url:
"https://github.com/mysticatea/eslint-plugin-node/blob/v8.0.1/docs/rules/prefer-global/console.md",
},
type: "suggestion",
fixable: null,
schema: [{ enum: ["always", "never"] }],
messages: {
preferGlobal:
"Unexpected use of 'require(\"console\")'. Use the global variable 'console' instead.",
preferModule:
"Unexpected use of the global variable 'console'. Use 'require(\"console\")' instead.",
},
},
create(context) {
return {
"Program:exit"() {
checkForPreferGlobal(context, trackMap)
},
}
},
}
+46
View File
@@ -0,0 +1,46 @@
/**
* @author Toru Nagashima
* See LICENSE file in root directory for full license.
*/
"use strict"
const { READ } = require("eslint-utils")
const checkForPreferGlobal = require("../../util/check-prefer-global")
const trackMap = {
globals: {
process: { [READ]: true },
},
modules: {
process: { [READ]: true },
},
}
module.exports = {
meta: {
docs: {
description: 'enforce either `process` or `require("process")`',
category: "Stylistic Issues",
recommended: false,
url:
"https://github.com/mysticatea/eslint-plugin-node/blob/v8.0.1/docs/rules/prefer-global/process.md",
},
type: "suggestion",
fixable: null,
schema: [{ enum: ["always", "never"] }],
messages: {
preferGlobal:
"Unexpected use of 'require(\"process\")'. Use the global variable 'process' instead.",
preferModule:
"Unexpected use of the global variable 'process'. Use 'require(\"process\")' instead.",
},
},
create(context) {
return {
"Program:exit"() {
checkForPreferGlobal(context, trackMap)
},
}
},
}
@@ -0,0 +1,49 @@
/**
* @author Toru Nagashima
* See LICENSE file in root directory for full license.
*/
"use strict"
const { READ } = require("eslint-utils")
const checkForPreferGlobal = require("../../util/check-prefer-global")
const trackMap = {
globals: {
TextDecoder: { [READ]: true },
},
modules: {
util: {
TextDecoder: { [READ]: true },
},
},
}
module.exports = {
meta: {
docs: {
description:
'enforce either `TextDecoder` or `require("util").TextDecoder`',
category: "Stylistic Issues",
recommended: false,
url:
"https://github.com/mysticatea/eslint-plugin-node/blob/v8.0.1/docs/rules/prefer-global/text-decoder.md",
},
type: "suggestion",
fixable: null,
schema: [{ enum: ["always", "never"] }],
messages: {
preferGlobal:
"Unexpected use of 'require(\"util\").TextDecoder'. Use the global variable 'TextDecoder' instead.",
preferModule:
"Unexpected use of the global variable 'TextDecoder'. Use 'require(\"util\").TextDecoder' instead.",
},
},
create(context) {
return {
"Program:exit"() {
checkForPreferGlobal(context, trackMap)
},
}
},
}
@@ -0,0 +1,49 @@
/**
* @author Toru Nagashima
* See LICENSE file in root directory for full license.
*/
"use strict"
const { READ } = require("eslint-utils")
const checkForPreferGlobal = require("../../util/check-prefer-global")
const trackMap = {
globals: {
TextEncoder: { [READ]: true },
},
modules: {
util: {
TextEncoder: { [READ]: true },
},
},
}
module.exports = {
meta: {
docs: {
description:
'enforce either `TextEncoder` or `require("util").TextEncoder`',
category: "Stylistic Issues",
recommended: false,
url:
"https://github.com/mysticatea/eslint-plugin-node/blob/v8.0.1/docs/rules/prefer-global/text-encoder.md",
},
type: "suggestion",
fixable: null,
schema: [{ enum: ["always", "never"] }],
messages: {
preferGlobal:
"Unexpected use of 'require(\"util\").TextEncoder'. Use the global variable 'TextEncoder' instead.",
preferModule:
"Unexpected use of the global variable 'TextEncoder'. Use 'require(\"util\").TextEncoder' instead.",
},
},
create(context) {
return {
"Program:exit"() {
checkForPreferGlobal(context, trackMap)
},
}
},
}
@@ -0,0 +1,49 @@
/**
* @author Toru Nagashima
* See LICENSE file in root directory for full license.
*/
"use strict"
const { READ } = require("eslint-utils")
const checkForPreferGlobal = require("../../util/check-prefer-global")
const trackMap = {
globals: {
URLSearchParams: { [READ]: true },
},
modules: {
url: {
URLSearchParams: { [READ]: true },
},
},
}
module.exports = {
meta: {
docs: {
description:
'enforce either `URLSearchParams` or `require("url").URLSearchParams`',
category: "Stylistic Issues",
recommended: false,
url:
"https://github.com/mysticatea/eslint-plugin-node/blob/v8.0.1/docs/rules/prefer-global/url-search-params.md",
},
type: "suggestion",
fixable: null,
schema: [{ enum: ["always", "never"] }],
messages: {
preferGlobal:
"Unexpected use of 'require(\"url\").URLSearchParams'. Use the global variable 'URLSearchParams' instead.",
preferModule:
"Unexpected use of the global variable 'URLSearchParams'. Use 'require(\"url\").URLSearchParams' instead.",
},
},
create(context) {
return {
"Program:exit"() {
checkForPreferGlobal(context, trackMap)
},
}
},
}
+48
View File
@@ -0,0 +1,48 @@
/**
* @author Toru Nagashima
* See LICENSE file in root directory for full license.
*/
"use strict"
const { READ } = require("eslint-utils")
const checkForPreferGlobal = require("../../util/check-prefer-global")
const trackMap = {
globals: {
URL: { [READ]: true },
},
modules: {
url: {
URL: { [READ]: true },
},
},
}
module.exports = {
meta: {
docs: {
description: 'enforce either `URL` or `require("url").URL`',
category: "Stylistic Issues",
recommended: false,
url:
"https://github.com/mysticatea/eslint-plugin-node/blob/v8.0.1/docs/rules/prefer-global/url.md",
},
type: "suggestion",
fixable: null,
schema: [{ enum: ["always", "never"] }],
messages: {
preferGlobal:
"Unexpected use of 'require(\"url\").URL'. Use the global variable 'URL' instead.",
preferModule:
"Unexpected use of the global variable 'URL'. Use 'require(\"url\").URL' instead.",
},
},
create(context) {
return {
"Program:exit"() {
checkForPreferGlobal(context, trackMap)
},
}
},
}
+157
View File
@@ -0,0 +1,157 @@
/**
* @author Toru Nagashima
* See LICENSE file in root directory for full license.
*/
"use strict"
const CodePathAnalyzer = safeRequire(
"eslint/lib/code-path-analysis/code-path-analyzer"
)
const CodePath = safeRequire("eslint/lib/code-path-analysis/code-path")
const CodePathSegment = safeRequire(
"eslint/lib/code-path-analysis/code-path-segment"
)
const originalLeaveNode =
CodePathAnalyzer && CodePathAnalyzer.prototype.leaveNode
/**
* Imports a specific module.
*
* @param {string} moduleName - A module name to import.
* @returns {object|null} The imported object, or null.
*/
function safeRequire(moduleName) {
try {
return require(moduleName)
} catch (_err) {
return null
}
}
/* istanbul ignore next */
/**
* Copied from https://github.com/eslint/eslint/blob/16fad5880bb70e9dddbeab8ed0f425ae51f5841f/lib/code-path-analysis/code-path-analyzer.js#L137
*
* @param {CodePathAnalyzer} analyzer - The instance.
* @param {ASTNode} node - The current AST node.
* @returns {void}
*/
function forwardCurrentToHead(analyzer, node) {
const codePath = analyzer.codePath
const state = CodePath.getState(codePath)
const currentSegments = state.currentSegments
const headSegments = state.headSegments
const end = Math.max(currentSegments.length, headSegments.length)
let i = 0
let currentSegment = null
let headSegment = null
// Fires leaving events.
for (i = 0; i < end; ++i) {
currentSegment = currentSegments[i]
headSegment = headSegments[i]
if (currentSegment !== headSegment && currentSegment) {
if (currentSegment.reachable) {
analyzer.emitter.emit(
"onCodePathSegmentEnd",
currentSegment,
node
)
}
}
}
// Update state.
state.currentSegments = headSegments
// Fires entering events.
for (i = 0; i < end; ++i) {
currentSegment = currentSegments[i]
headSegment = headSegments[i]
if (currentSegment !== headSegment && headSegment) {
CodePathSegment.markUsed(headSegment)
if (headSegment.reachable) {
analyzer.emitter.emit(
"onCodePathSegmentStart",
headSegment,
node
)
}
}
}
}
/**
* Checks whether a given node is `process.exit()` or not.
*
* @param {ASTNode} node - A node to check.
* @returns {boolean} `true` if the node is `process.exit()`.
*/
function isProcessExit(node) {
return (
node.type === "CallExpression" &&
node.callee.type === "MemberExpression" &&
node.callee.computed === false &&
node.callee.object.type === "Identifier" &&
node.callee.object.name === "process" &&
node.callee.property.type === "Identifier" &&
node.callee.property.name === "exit"
)
}
/**
* The function to override `CodePathAnalyzer.prototype.leaveNode` in order to
* address `process.exit()` as throw.
*
* @this CodePathAnalyzer
* @param {ASTNode} node - A node to be left.
* @returns {void}
*/
function overrideLeaveNode(node) {
if (isProcessExit(node)) {
this.currentNode = node
forwardCurrentToHead(this, node)
CodePath.getState(this.codePath).makeThrow()
this.original.leaveNode(node)
this.currentNode = null
} else {
originalLeaveNode.call(this, node)
}
}
const visitor =
CodePathAnalyzer == null
? {}
: {
Program: function installProcessExitAsThrow() {
CodePathAnalyzer.prototype.leaveNode = overrideLeaveNode
},
"Program:exit": function restoreProcessExitAsThrow() {
CodePathAnalyzer.prototype.leaveNode = originalLeaveNode
},
}
module.exports = {
meta: {
docs: {
description:
"make `process.exit()` expressions the same code path as `throw`",
category: "Possible Errors",
recommended: true,
url:
"https://github.com/mysticatea/eslint-plugin-node/blob/v8.0.1/docs/rules/process-exit-as-throw.md",
},
type: "problem",
fixable: null,
schema: [],
supported: CodePathAnalyzer != null,
},
create() {
return visitor
},
}
+155
View File
@@ -0,0 +1,155 @@
/**
* @author Toru Nagashima
* See LICENSE file in root directory for full license.
*/
"use strict"
const path = require("path")
const getConvertPath = require("../util/get-convert-path")
const getPackageJson = require("../util/get-package-json")
const NODE_SHEBANG = "#!/usr/bin/env node\n"
const SHEBANG_PATTERN = /^(#!.+?)?(\r)?\n/u
const NODE_SHEBANG_PATTERN = /#!\/usr\/bin\/env node(?: [^\r\n]+?)?\n/u
/**
* Checks whether or not a given path is a `bin` file.
*
* @param {string} filePath - A file path to check.
* @param {string|object|undefined} binField - A value of the `bin` field of `package.json`.
* @param {string} basedir - A directory path that `package.json` exists.
* @returns {boolean} `true` if the file is a `bin` file.
*/
function isBinFile(filePath, binField, basedir) {
if (!binField) {
return false
}
if (typeof binField === "string") {
return filePath === path.resolve(basedir, binField)
}
return Object.keys(binField).some(
key => filePath === path.resolve(basedir, binField[key])
)
}
/**
* Gets the shebang line (includes a line ending) from a given code.
*
* @param {SourceCode} sourceCode - A source code object to check.
* @returns {{length: number, bom: boolean, shebang: string, cr: boolean}}
* shebang's information.
* `retv.shebang` is an empty string if shebang doesn't exist.
*/
function getShebangInfo(sourceCode) {
const m = SHEBANG_PATTERN.exec(sourceCode.text)
return {
bom: sourceCode.hasBOM,
cr: Boolean(m && m[2]),
length: (m && m[0].length) || 0,
shebang: (m && m[1] && `${m[1]}\n`) || "",
}
}
module.exports = {
meta: {
docs: {
description: "enforce the correct usage of shebang",
category: "Possible Errors",
recommended: true,
url:
"https://github.com/mysticatea/eslint-plugin-node/blob/v8.0.1/docs/rules/shebang.md",
},
type: "problem",
fixable: "code",
schema: [
{
type: "object",
properties: {
//
convertPath: getConvertPath.schema,
},
additionalProperties: false,
},
],
},
create(context) {
const sourceCode = context.getSourceCode()
let filePath = context.getFilename()
if (filePath === "<input>") {
return {}
}
filePath = path.resolve(filePath)
const p = getPackageJson(filePath)
if (!p) {
return {}
}
const basedir = path.dirname(p.filePath)
filePath = path.join(
basedir,
getConvertPath(context)(
path.relative(basedir, filePath).replace(/\\/gu, "/")
)
)
const needsShebang = isBinFile(filePath, p.bin, basedir)
const info = getShebangInfo(sourceCode)
return {
Program(node) {
if (
needsShebang
? NODE_SHEBANG_PATTERN.test(info.shebang)
: !info.shebang
) {
// Good the shebang target.
// Checks BOM and \r.
if (needsShebang && info.bom) {
context.report({
node,
message: "This file must not have Unicode BOM.",
fix(fixer) {
return fixer.removeRange([-1, 0])
},
})
}
if (needsShebang && info.cr) {
context.report({
node,
message:
"This file must have Unix linebreaks (LF).",
fix(fixer) {
const index = sourceCode.text.indexOf("\r")
return fixer.removeRange([index, index + 1])
},
})
}
} else if (needsShebang) {
// Shebang is lacking.
context.report({
node,
message:
'This file needs shebang "#!/usr/bin/env node".',
fix(fixer) {
return fixer.replaceTextRange(
[-1, info.length],
NODE_SHEBANG
)
},
})
} else {
// Shebang is extra.
context.report({
node,
message: "This file needs no shebang.",
fix(fixer) {
return fixer.removeRange([0, info.length])
},
})
}
},
}
},
}
+58
View File
@@ -0,0 +1,58 @@
/**
* @author Toru Nagashima
* See LICENSE file in root directory for full license.
*/
"use strict"
const SKIP_TIME = 5000
/**
* The class of cache.
* The cache will dispose of each value if the value has not been accessed
* during 5 seconds.
*/
module.exports = class Cache {
/**
* Initialize this cache instance.
*/
constructor() {
this.map = new Map()
}
/**
* Get the cached value of the given key.
* @param {any} key The key to get.
* @returns {any} The cached value or null.
*/
get(key) {
const entry = this.map.get(key)
const now = Date.now()
if (entry) {
if (entry.expire > now) {
entry.expire = now + SKIP_TIME
return entry.value
}
this.map.delete(key)
}
return null
}
/**
* Set the value of the given key.
* @param {any} key The key to set.
* @param {any} value The value to set.
* @returns {void}
*/
set(key, value) {
const entry = this.map.get(key)
const expire = Date.now() + SKIP_TIME
if (entry) {
entry.value = value
entry.expire = expire
} else {
this.map.set(key, { value, expire })
}
}
}
+40
View File
@@ -0,0 +1,40 @@
/**
* @author Toru Nagashima
* See LICENSE file in root directory for full license.
*/
"use strict"
const exists = require("./exists")
const getAllowModules = require("./get-allow-modules")
/**
* Checks whether or not each requirement target exists.
*
* It looks up the target according to the logic of Node.js.
* See Also: https://nodejs.org/api/modules.html
*
* @param {RuleContext} context - A context to report.
* @param {ImportTarget[]} targets - A list of target information to check.
* @returns {void}
*/
module.exports = function checkForExistence(context, targets) {
const allowed = new Set(getAllowModules(context))
for (const target of targets) {
const missingModule =
target.moduleName != null &&
!allowed.has(target.moduleName) &&
target.filePath == null
const missingFile =
target.moduleName == null && !exists(target.filePath)
if (missingModule || missingFile) {
context.report({
node: target.node,
loc: target.node.loc,
message: '"{{name}}" is not found.',
data: target,
})
}
}
}
+52
View File
@@ -0,0 +1,52 @@
/**
* @author Toru Nagashima
* See LICENSE file in root directory for full license.
*/
"use strict"
const getAllowModules = require("./get-allow-modules")
const getPackageJson = require("./get-package-json")
/**
* Checks whether or not each requirement target is published via package.json.
*
* It reads package.json and checks the target exists in `dependencies`.
*
* @param {RuleContext} context - A context to report.
* @param {string} filePath - The current file path.
* @param {ImportTarget[]} targets - A list of target information to check.
* @returns {void}
*/
module.exports = function checkForExtraneous(context, filePath, targets) {
const packageInfo = getPackageJson(filePath)
if (!packageInfo) {
return
}
const allowed = new Set(getAllowModules(context))
const dependencies = new Set(
[].concat(
Object.keys(packageInfo.dependencies || {}),
Object.keys(packageInfo.devDependencies || {}),
Object.keys(packageInfo.peerDependencies || {}),
Object.keys(packageInfo.optionalDependencies || {})
)
)
for (const target of targets) {
const extraneous =
target.moduleName != null &&
target.filePath != null &&
!dependencies.has(target.moduleName) &&
!allowed.has(target.moduleName)
if (extraneous) {
context.report({
node: target.node,
loc: target.node.loc,
message: '"{{moduleName}}" is extraneous.',
data: target,
})
}
}
}
+63
View File
@@ -0,0 +1,63 @@
/**
* @author Toru Nagashima
* See LICENSE file in root directory for full license.
*/
"use strict"
const { ReferenceTracker } = require("eslint-utils")
/**
* Verifier for `prefer-global/*` rules.
*/
class Verifier {
/**
* Initialize this instance.
* @param {RuleContext} context The rule context to report.
* @param {{modules:object,globals:object}} trackMap The track map.
*/
constructor(context, trackMap) {
this.context = context
this.trackMap = trackMap
this.verify =
context.options[0] === "never"
? this.verifyToPreferModules
: this.verifyToPreferGlobals
}
/**
* Verify the code to suggest the use of globals.
* @returns {void}
*/
verifyToPreferGlobals() {
const { context, trackMap } = this
const tracker = new ReferenceTracker(context.getScope(), {
mode: "legacy",
})
for (const { node } of [
...tracker.iterateCjsReferences(trackMap.modules),
...tracker.iterateEsmReferences(trackMap.modules),
]) {
context.report({ node, messageId: "preferGlobal" })
}
}
/**
* Verify the code to suggest the use of modules.
* @returns {void}
*/
verifyToPreferModules() {
const { context, trackMap } = this
const tracker = new ReferenceTracker(context.getScope())
for (const { node } of tracker.iterateGlobalReferences(
trackMap.globals
)) {
context.report({ node, messageId: "preferModule" })
}
}
}
module.exports = function checkForPreferGlobal(context, trackMap) {
new Verifier(context, trackMap).verify()
}
+71
View File
@@ -0,0 +1,71 @@
/**
* @author Toru Nagashima
* See LICENSE file in root directory for full license.
*/
"use strict"
const path = require("path")
const getAllowModules = require("./get-allow-modules")
const getConvertPath = require("./get-convert-path")
const getNpmignore = require("./get-npmignore")
const getPackageJson = require("./get-package-json")
/**
* Checks whether or not each requirement target is published via package.json.
*
* It reads package.json and checks the target exists in `dependencies`.
*
* @param {RuleContext} context - A context to report.
* @param {string} filePath - The current file path.
* @param {ImportTarget[]} targets - A list of target information to check.
* @returns {void}
*/
module.exports = function checkForPublish(context, filePath, targets) {
const packageInfo = getPackageJson(filePath)
if (!packageInfo) {
return
}
const allowed = new Set(getAllowModules(context))
const convertPath = getConvertPath(context)
const basedir = path.dirname(packageInfo.filePath)
// eslint-disable-next-line func-style, require-jsdoc
const toRelative = fullPath => {
const retv = path.relative(basedir, fullPath).replace(/\\/gu, "/")
return convertPath(retv)
}
const npmignore = getNpmignore(filePath)
const devDependencies = new Set(
Object.keys(packageInfo.devDependencies || {})
)
const dependencies = new Set(
[].concat(
Object.keys(packageInfo.dependencies || {}),
Object.keys(packageInfo.peerDependencies || {}),
Object.keys(packageInfo.optionalDependencies || {})
)
)
if (!npmignore.match(toRelative(filePath))) {
// This file is published, so this cannot import private files.
for (const target of targets) {
const isPrivateFile =
target.moduleName == null &&
npmignore.match(toRelative(target.filePath))
const isDevPackage =
target.moduleName != null &&
devDependencies.has(target.moduleName) &&
!dependencies.has(target.moduleName) &&
!allowed.has(target.moduleName)
if (isPrivateFile || isDevPackage) {
context.report({
node: target.node,
loc: target.node.loc,
message: '"{{name}}" is not published.',
data: { name: target.moduleName || target.name },
})
}
}
}
}
+61
View File
@@ -0,0 +1,61 @@
/**
* @author Toru Nagashima
* See LICENSE file in root directory for full license.
*/
"use strict"
const { Range } = require("semver") //eslint-disable-line no-unused-vars
const { ReferenceTracker } = require("eslint-utils")
const getConfiguredNodeVersion = require("./get-configured-node-version")
const getSemverRange = require("./get-semver-range")
/**
* Parses the options.
* @param {RuleContext} context The rule context.
* @returns {{version:Range,ignores:Set<string>}} Parsed value.
*/
function parseOptions(context) {
const raw = context.options[0] || {}
const filePath = context.getFilename()
const version = getConfiguredNodeVersion(raw.version, filePath)
const ignores = new Set(raw.ignores || [])
return Object.freeze({ version, ignores })
}
/**
* Verify the code to report unsupported APIs.
* @param {RuleContext} context The rule context.
* @param {{modules:object,globals:object}} trackMap The map for APIs to report.
* @returns {void}
*/
module.exports = function checkUnsupportedBuiltins(context, trackMap) {
const options = parseOptions(context)
const tracker = new ReferenceTracker(context.getScope(), {
mode: "legacy",
})
const references = [
...tracker.iterateCjsReferences(trackMap.modules || {}),
...tracker.iterateEsmReferences(trackMap.modules || {}),
...tracker.iterateGlobalReferences(trackMap.globals || {}),
]
for (const { node, path, info } of references) {
const name = path.join(".")
const supported = options.version.intersects(
getSemverRange(`<${info.supported}`)
)
if (supported && !options.ignores.has(name)) {
context.report({
node,
messageId: "unsupported",
data: {
name,
supported: info.supported,
version: options.version.raw,
},
})
}
}
}
+39
View File
@@ -0,0 +1,39 @@
/**
* @author Toru Nagashima <https://github.com/mysticatea>
* See LICENSE file in root directory for full license.
*/
"use strict"
const { CALL, CONSTRUCT, READ } = require("eslint-utils")
/**
* Enumerate property names of a given object recursively.
* @param {object} trackMap The map for APIs to enumerate.
* @param {string[]|undefined} path The path to the current map.
* @returns {IterableIterator<string>} The property names of the map.
*/
function* enumeratePropertyNames(trackMap, path = []) {
for (const key of Object.keys(trackMap)) {
const value = trackMap[key]
if (typeof value !== "object") {
continue
}
path.push(key)
if (value[CALL]) {
yield `${path.join(".")}()`
}
if (value[CONSTRUCT]) {
yield `new ${path.join(".")}()`
}
if (value[READ]) {
yield path.join(".")
}
yield* enumeratePropertyNames(value, path)
path.pop()
}
}
module.exports = enumeratePropertyNames
+58
View File
@@ -0,0 +1,58 @@
/**
* @author Toru Nagashima
* See LICENSE file in root directory for full license.
*/
"use strict"
const fs = require("fs")
const path = require("path")
const Cache = require("./cache")
const ROOT = /^(?:[/.]|\.\.|[A-Z]:\\|\\\\)(?:[/\\]\.\.)*$/u
const cache = new Cache()
/**
* Check whether the file exists or not.
* @param {string} filePath The file path to check.
* @returns {boolean} `true` if the file exists.
*/
function existsCaseSensitive(filePath) {
let dirPath = filePath
while (dirPath !== "" && !ROOT.test(dirPath)) {
const fileName = path.basename(dirPath)
dirPath = path.dirname(dirPath)
if (fs.readdirSync(dirPath).indexOf(fileName) === -1) {
return false
}
}
return true
}
/**
* Checks whether or not the file of a given path exists.
*
* @param {string} filePath - A file path to check.
* @returns {boolean} `true` if the file of a given path exists.
*/
module.exports = function exists(filePath) {
let result = cache.get(filePath)
if (result == null) {
try {
const relativePath = path.relative(process.cwd(), filePath)
result =
fs.statSync(relativePath).isFile() &&
existsCaseSensitive(relativePath)
} catch (error) {
if (error.code !== "ENOENT") {
throw error
}
result = false
}
cache.set(filePath, result)
}
return result
}
+47
View File
@@ -0,0 +1,47 @@
/**
* @author Toru Nagashima
* See LICENSE file in root directory for full license.
*/
"use strict"
const DEFAULT_VALUE = Object.freeze([])
/**
* Gets `allowModules` property from a given option object.
*
* @param {object|undefined} option - An option object to get.
* @returns {string[]|null} The `allowModules` value, or `null`.
*/
function get(option) {
if (option && option.allowModules && Array.isArray(option.allowModules)) {
return option.allowModules.map(String)
}
return null
}
/**
* Gets "allowModules" setting.
*
* 1. This checks `options` property, then returns it if exists.
* 2. This checks `settings.node` property, then returns it if exists.
* 3. This returns `[]`.
*
* @param {RuleContext} context - The rule context.
* @returns {string[]} A list of extensions.
*/
module.exports = function getAllowModules(context) {
return (
get(context.options && context.options[0]) ||
get(context.settings && context.settings.node) ||
DEFAULT_VALUE
)
}
module.exports.schema = {
type: "array",
items: {
type: "string",
pattern: "^(?:@[a-zA-Z0-9_\\-.]+/)?[a-zA-Z0-9_\\-.]+$",
},
uniqueItems: true,
}
@@ -0,0 +1,39 @@
/**
* @author Toru Nagashima <https://github.com/mysticatea>
* See LICENSE file in root directory for full license.
*/
"use strict"
const { Range } = require("semver") //eslint-disable-line no-unused-vars
const getPackageJson = require("./get-package-json")
const getSemverRange = require("./get-semver-range")
/**
* Get the `engines.node` field of package.json.
* @param {string} filename The path to the current linting file.
* @returns {Range|null} The range object of the `engines.node` field.
*/
function getEnginesNode(filename) {
const info = getPackageJson(filename)
return getSemverRange(info && info.engines && info.engines.node)
}
/**
* Gets version configuration.
*
* 1. Parse a given version then return it if it's valid.
* 2. Look package.json up and parse `engines.node` then return it if it's valid.
* 3. Return `>=6.0.0`.
*
* @param {string|undefined} version The version range text.
* @param {string} filename The path to the current linting file.
* This will be used to look package.json up if `version` is not a valid version range.
* @returns {Range} The configured version range.
*/
module.exports = function getConfiguredNodeVersion(version, filename) {
return (
getSemverRange(version) ||
getEnginesNode(filename) ||
getSemverRange(">=6.0.0")
)
}
+189
View File
@@ -0,0 +1,189 @@
/**
* @author Toru Nagashima
* See LICENSE file in root directory for full license.
*/
"use strict"
const Minimatch = require("minimatch").Minimatch
/**
* @param {any} x - An any value.
* @returns {any} Always `x`.
*/
function identity(x) {
return x
}
/**
* Converts old-style value to new-style value.
*
* @param {any} x - The value to convert.
* @returns {({include: string[], exclude: string[], replace: string[]})[]} Normalized value.
*/
function normalizeValue(x) {
if (Array.isArray(x)) {
return x
}
return Object.keys(x).map(pattern => ({
include: [pattern],
exclude: [],
replace: x[pattern],
}))
}
/**
* Ensures the given value is a string array.
*
* @param {any} x - The value to ensure.
* @returns {string[]} The string array.
*/
function toStringArray(x) {
if (Array.isArray(x)) {
return x.map(String)
}
return []
}
/**
* Creates the function which checks whether a file path is matched with the given pattern or not.
*
* @param {string[]} includePatterns - The glob patterns to include files.
* @param {string[]} excludePatterns - The glob patterns to exclude files.
* @returns {function} Created predicate function.
*/
function createMatch(includePatterns, excludePatterns) {
const include = includePatterns.map(pattern => new Minimatch(pattern))
const exclude = excludePatterns.map(pattern => new Minimatch(pattern))
return filePath =>
include.some(m => m.match(filePath)) &&
!exclude.some(m => m.match(filePath))
}
/**
* Creates a function which replaces a given path.
*
* @param {RegExp} fromRegexp - A `RegExp` object to replace.
* @param {string} toStr - A new string to replace.
* @returns {function} A function which replaces a given path.
*/
function defineConvert(fromRegexp, toStr) {
return filePath => filePath.replace(fromRegexp, toStr)
}
/**
* Combines given converters.
* The result function converts a given path with the first matched converter.
*
* @param {{match: function, convert: function}} converters - A list of converters to combine.
* @returns {function} A function which replaces a given path.
*/
function combine(converters) {
return filePath => {
for (const converter of converters) {
if (converter.match(filePath)) {
return converter.convert(filePath)
}
}
return filePath
}
}
/**
* Parses `convertPath` property from a given option object.
*
* @param {object|undefined} option - An option object to get.
* @returns {function|null} A function which converts a path., or `null`.
*/
function parse(option) {
if (
!option ||
!option.convertPath ||
typeof option.convertPath !== "object"
) {
return null
}
const converters = []
for (const pattern of normalizeValue(option.convertPath)) {
const include = toStringArray(pattern.include)
const exclude = toStringArray(pattern.exclude)
const fromRegexp = new RegExp(String(pattern.replace[0])) //eslint-disable-line require-unicode-regexp
const toStr = String(pattern.replace[1])
converters.push({
match: createMatch(include, exclude),
convert: defineConvert(fromRegexp, toStr),
})
}
return combine(converters)
}
/**
* Gets "convertPath" setting.
*
* 1. This checks `options` property, then returns it if exists.
* 2. This checks `settings.node` property, then returns it if exists.
* 3. This returns a function of identity.
*
* @param {RuleContext} context - The rule context.
* @returns {function} A function which converts a path.
*/
module.exports = function getConvertPath(context) {
return (
parse(context.options && context.options[0]) ||
parse(context.settings && context.settings.node) ||
identity
)
}
/**
* JSON Schema for `convertPath` option.
*/
module.exports.schema = {
anyOf: [
{
type: "object",
properties: {},
patternProperties: {
"^.+$": {
type: "array",
items: { type: "string" },
minItems: 2,
maxItems: 2,
},
},
additionalProperties: false,
},
{
type: "array",
items: {
type: "object",
properties: {
include: {
type: "array",
items: { type: "string" },
minItems: 1,
uniqueItems: true,
},
exclude: {
type: "array",
items: { type: "string" },
uniqueItems: true,
},
replace: {
type: "array",
items: { type: "string" },
minItems: 2,
maxItems: 2,
},
},
additionalProperties: false,
required: ["include", "replace"],
},
minItems: 1,
},
],
}
+52
View File
@@ -0,0 +1,52 @@
/**
* @author Toru Nagashima
* See LICENSE file in root directory for full license.
*/
"use strict"
const path = require("path")
const resolve = require("resolve")
const getResolvePaths = require("./get-resolve-paths")
const getTryExtensions = require("./get-try-extensions")
const ImportTarget = require("./import-target")
const stripImportPathParams = require("./strip-import-path-params")
const MODULE_TYPE = /^(?:Import|Export(?:Named|Default|All))Declaration$/u
/**
* Gets a list of `import`/`export` declaration targets.
*
* Core modules of Node.js (e.g. `fs`, `http`) are excluded.
*
* @param {RuleContext} context - The rule context.
* @param {ASTNode} programNode - The node of Program.
* @param {boolean} includeCore - The flag to include core modules.
* @returns {ImportTarget[]} A list of found target's information.
*/
module.exports = function getImportExportTargets(
context,
programNode,
includeCore
) {
const retv = []
const basedir = path.dirname(path.resolve(context.getFilename()))
const paths = getResolvePaths(context)
const extensions = getTryExtensions(context)
const options = { basedir, paths, extensions }
for (const statement of programNode.body) {
// Skip if it's not a module declaration.
if (!MODULE_TYPE.test(statement.type)) {
continue
}
// Gets the target module.
const node = statement.source
const name = node && stripImportPathParams(node.value)
if (name && (includeCore || !resolve.isCore(name))) {
retv.push(new ImportTarget(node, name, options))
}
}
return retv
}
+184
View File
@@ -0,0 +1,184 @@
/**
* @author Toru Nagashima
* See LICENSE file in root directory for full license.
*/
"use strict"
const fs = require("fs")
const path = require("path")
const ignore = require("ignore")
const Cache = require("./cache")
const exists = require("./exists")
const getPackageJson = require("./get-package-json")
const cache = new Cache()
const SLASH_AT_BEGIN_AND_END = /^!?\/+|^!|\/+$/gu
const PARENT_RELATIVE_PATH = /^\.\./u
const NEVER_IGNORED = /^(?:readme\.[^.]*|(?:licen[cs]e|changes|changelog|history)(?:\.[^.]*)?)$/iu
/**
* Checks whether or not a given file name is a relative path to a ancestor
* directory.
*
* @param {string} filePath - A file name to check.
* @returns {boolean} `true` if the file name is a relative path to a ancestor
* directory.
*/
function isAncestorFiles(filePath) {
return PARENT_RELATIVE_PATH.test(filePath)
}
/**
* @param {function} f - A function.
* @param {function} g - A function.
* @returns {function} A logical-and function of `f` and `g`.
*/
function and(f, g) {
return filePath => f(filePath) && g(filePath)
}
/**
* @param {function} f - A function.
* @param {function} g - A function.
* @param {function|null} h - A function.
* @returns {function} A logical-or function of `f`, `g`, and `h`.
*/
function or(f, g, h) {
return filePath => f(filePath) || g(filePath) || (h && h(filePath))
}
/**
* @param {function} f - A function.
* @returns {function} A logical-not function of `f`.
*/
function not(f) {
return filePath => !f(filePath)
}
/**
* Creates a function which checks whether or not a given file is ignoreable.
*
* @param {object} p - An object of package.json.
* @returns {function} A function which checks whether or not a given file is ignoreable.
*/
function filterNeverIgnoredFiles(p) {
const basedir = path.dirname(p.filePath)
const mainFilePath =
typeof p.main === "string" ? path.join(basedir, p.main) : null
return filePath =>
path.join(basedir, filePath) !== mainFilePath &&
filePath !== "package.json" &&
!NEVER_IGNORED.test(path.relative(basedir, filePath))
}
/**
* Creates a function which checks whether or not a given file should be ignored.
*
* @param {string[]|null} files - File names of whitelist.
* @returns {function|null} A function which checks whether or not a given file should be ignored.
*/
function parseWhiteList(files) {
if (!files || !Array.isArray(files)) {
return null
}
const ig = ignore()
const igN = ignore()
let hasN = false
for (const file of files) {
if (typeof file === "string" && file) {
const body = file.replace(SLASH_AT_BEGIN_AND_END, "")
if (file.startsWith("!")) {
igN.add(`${body}`)
igN.add(`${body}/**`)
hasN = true
} else {
ig.add(`/${body}`)
ig.add(`/${body}/**`)
}
}
}
return hasN
? or(ig.createFilter(), not(igN.createFilter()))
: ig.createFilter()
}
/**
* Creates a function which checks whether or not a given file should be ignored.
*
* @param {string} basedir - The directory path "package.json" exists.
* @param {boolean} filesFieldExists - `true` if `files` field of `package.json` exists.
* @returns {function|null} A function which checks whether or not a given file should be ignored.
*/
function parseNpmignore(basedir, filesFieldExists) {
let filePath = path.join(basedir, ".npmignore")
if (!exists(filePath)) {
if (filesFieldExists) {
return null
}
filePath = path.join(basedir, ".gitignore")
if (!exists(filePath)) {
return null
}
}
const ig = ignore()
ig.add(fs.readFileSync(filePath, "utf8"))
return not(ig.createFilter())
}
/**
* Gets an object to check whether a given path should be ignored or not.
* The object is created from:
*
* - `files` field of `package.json`
* - `.npmignore`
*
* @param {string} startPath - A file path to lookup.
* @returns {object}
* An object to check whther or not a given path should be ignored.
* The object has a method `match`.
* `match` returns `true` if a given file path should be ignored.
*/
module.exports = function getNpmignore(startPath) {
const retv = { match: isAncestorFiles }
const p = getPackageJson(startPath)
if (p) {
const data = cache.get(p.filePath)
if (data) {
return data
}
const filesIgnore = parseWhiteList(p.files)
const npmignoreIgnore = parseNpmignore(
path.dirname(p.filePath),
Boolean(filesIgnore)
)
if (filesIgnore && npmignoreIgnore) {
retv.match = and(
filterNeverIgnoredFiles(p),
or(isAncestorFiles, filesIgnore, npmignoreIgnore)
)
} else if (filesIgnore) {
retv.match = and(
filterNeverIgnoredFiles(p),
or(isAncestorFiles, filesIgnore)
)
} else if (npmignoreIgnore) {
retv.match = and(
filterNeverIgnoredFiles(p),
or(isAncestorFiles, npmignoreIgnore)
)
}
cache.set(p.filePath, retv)
}
return retv
}
+75
View File
@@ -0,0 +1,75 @@
/**
* @author Toru Nagashima
* See LICENSE file in root directory for full license.
*/
"use strict"
const fs = require("fs")
const path = require("path")
const Cache = require("./cache")
const cache = new Cache()
/**
* Reads the `package.json` data in a given path.
*
* Don't cache the data.
*
* @param {string} dir - The path to a directory to read.
* @returns {object|null} The read `package.json` data, or null.
*/
function readPackageJson(dir) {
const filePath = path.join(dir, "package.json")
try {
const text = fs.readFileSync(filePath, "utf8")
const data = JSON.parse(text)
if (typeof data === "object" && data !== null) {
data.filePath = filePath
return data
}
} catch (_err) {
// do nothing.
}
return null
}
/**
* Gets a `package.json` data.
* The data is cached if found, then it's used after.
*
* @param {string} startPath - A file path to lookup.
* @returns {object|null} A found `package.json` data or `null`.
* This object have additional property `filePath`.
*/
module.exports = function getPackageJson(startPath) {
const startDir = path.dirname(path.resolve(startPath))
let dir = startDir
let prevDir = ""
let data = null
do {
data = cache.get(dir)
if (data) {
if (dir !== startDir) {
cache.set(startDir, data)
}
return data
}
data = readPackageJson(dir)
if (data) {
cache.set(dir, data)
cache.set(startDir, data)
return data
}
// Go to next.
prevDir = dir
dir = path.resolve(dir, "..")
} while (dir !== prevDir)
cache.set(startDir, null)
return null
}
+75
View File
@@ -0,0 +1,75 @@
/**
* @author Toru Nagashima
* See LICENSE file in root directory for full license.
*/
"use strict"
const path = require("path")
const { getStringIfConstant } = require("eslint-utils")
const resolve = require("resolve")
const getResolvePaths = require("./get-resolve-paths")
const getTryExtensions = require("./get-try-extensions")
const ImportTarget = require("./import-target")
const stripImportPathParams = require("./strip-import-path-params")
/**
* Checks whether or not a given node is a callee.
*
* @param {ASTNode} node - A node to check.
* @returns {boolean} `true` if the node is a callee.
*/
function isCallee(node) {
return node.parent.type === "CallExpression" && node.parent.callee === node
}
/**
* Gets references of "require".
*
* @param {escope.Scope} scope - The global scope.
* @returns {escope.Reference[]} References of "require".
*/
function getReferencesOfRequire(scope) {
const variable = scope.set.get("require")
if (!variable) {
// Not found.
return []
}
return variable.references
}
/**
* Gets a list of `require()` targets.
*
* Core modules of Node.js (e.g. `fs`, `http`) are excluded.
*
* @param {RuleContext} context - The rule context.
* @param {boolean} includeCore - The flag to include core modules.
* @returns {ImportTarget[]} A list of found target's information.
*/
module.exports = function getRequireTargets(context, includeCore) {
const retv = []
const basedir = path.dirname(path.resolve(context.getFilename()))
const paths = getResolvePaths(context)
const references = getReferencesOfRequire(context.getScope())
const extensions = getTryExtensions(context)
const options = { basedir, paths, extensions }
for (const reference of references) {
const node = reference.identifier
// Skips if it's not a call of `require`.
if (!isCallee(node)) {
continue
}
// Gets the target module.
const targetNode = node.parent.arguments[0]
const rawName = getStringIfConstant(targetNode)
const name = rawName && stripImportPathParams(rawName)
if (name && (includeCore || !resolve.isCore(name))) {
retv.push(new ImportTarget(targetNode, name, options))
}
}
return retv
}
+44
View File
@@ -0,0 +1,44 @@
/**
* @author Toru Nagashima
* See LICENSE file in root directory for full license.
*/
"use strict"
const DEFAULT_VALUE = Object.freeze([])
/**
* Gets `resolvePaths` property from a given option object.
*
* @param {object|undefined} option - An option object to get.
* @returns {string[]|null} The `allowModules` value, or `null`.
*/
function get(option) {
if (option && option.resolvePaths && Array.isArray(option.resolvePaths)) {
return option.resolvePaths.map(String)
}
return null
}
/**
* Gets "resolvePaths" setting.
*
* 1. This checks `options` property, then returns it if exists.
* 2. This checks `settings.node` property, then returns it if exists.
* 3. This returns `[]`.
*
* @param {RuleContext} context - The rule context.
* @returns {string[]} A list of extensions.
*/
module.exports = function getResolvePaths(context) {
return (
get(context.options && context.options[0]) ||
get(context.settings && context.settings.node) ||
DEFAULT_VALUE
)
}
module.exports.schema = {
type: "array",
items: { type: "string" },
uniqueItems: true,
}
+30
View File
@@ -0,0 +1,30 @@
/**
* @author Toru Nagashima <https://github.com/mysticatea>
* See LICENSE file in root directory for full license.
*/
"use strict"
const { Range } = require("semver")
const cache = new Map()
/**
* Get the `semver.Range` object of a given range text.
* @param {string} x The text expression for a semver range.
* @returns {Range|null} The range object of a given range text.
* It's null if the `x` is not a valid range text.
*/
module.exports = function getSemverRange(x) {
const s = String(x)
let ret = cache.get(s) || null
if (!ret) {
try {
ret = new Range(s)
} catch (_error) {
// Ignore parsing error.
}
cache.set(s, ret)
}
return ret
}
+47
View File
@@ -0,0 +1,47 @@
/**
* @author Toru Nagashima
* See LICENSE file in root directory for full license.
*/
"use strict"
const DEFAULT_VALUE = Object.freeze([".js", ".json", ".node"])
/**
* Gets `tryExtensions` property from a given option object.
*
* @param {object|undefined} option - An option object to get.
* @returns {string[]|null} The `tryExtensions` value, or `null`.
*/
function get(option) {
if (option && option.tryExtensions && Array.isArray(option.tryExtensions)) {
return option.tryExtensions.map(String)
}
return null
}
/**
* Gets "tryExtensions" setting.
*
* 1. This checks `options` property, then returns it if exists.
* 2. This checks `settings.node` property, then returns it if exists.
* 3. This returns `[".js", ".json", ".node"]`.
*
* @param {RuleContext} context - The rule context.
* @returns {string[]} A list of extensions.
*/
module.exports = function getTryExtensions(context) {
return (
get(context.options && context.options[0]) ||
get(context.settings && context.settings.node) ||
DEFAULT_VALUE
)
}
module.exports.schema = {
type: "array",
items: {
type: "string",
pattern: "^\\.",
},
uniqueItems: true,
}
+85
View File
@@ -0,0 +1,85 @@
/**
* @author Toru Nagashima
* See LICENSE file in root directory for full license.
*/
"use strict"
const path = require("path")
const resolve = require("resolve")
/**
* Resolve the given id to file paths.
* @param {boolean} isModule The flag which indicates this id is a module.
* @param {string} id The id to resolve.
* @param {object} options The options of node-resolve module.
* It requires `options.basedir`.
* @returns {string|null} The resolved path.
*/
function getFilePath(isModule, id, options) {
try {
return resolve.sync(id, options)
} catch (_err) {
if (isModule) {
return null
}
return path.resolve(options.basedir, id)
}
}
/**
* Gets the module name of a given path.
*
* e.g. `eslint/lib/ast-utils` -> `eslint`
*
* @param {string} nameOrPath - A path to get.
* @returns {string} The module name of the path.
*/
function getModuleName(nameOrPath) {
let end = nameOrPath.indexOf("/")
if (end !== -1 && nameOrPath[0] === "@") {
end = nameOrPath.indexOf("/", 1 + end)
}
return end === -1 ? nameOrPath : nameOrPath.slice(0, end)
}
/**
* Information of an import target.
*/
module.exports = class ImportTarget {
/**
* Initialize this instance.
* @param {ASTNode} node - The node of a `require()` or a module declaraiton.
* @param {string} name - The name of an import target.
* @param {object} options - The options of `node-resolve` module.
*/
constructor(node, name, options) {
const isModule = !/^(?:[./\\]|\w+:)/u.test(name)
/**
* The node of a `require()` or a module declaraiton.
* @type {ASTNode}
*/
this.node = node
/**
* The name of this import target.
* @type {string}
*/
this.name = name
/**
* The full path of this import target.
* If the target is a module and it does not exist then this is `null`.
* @type {string|null}
*/
this.filePath = getFilePath(isModule, name, options)
/**
* The module name of this import target.
* If the target is a relative path then this is `null`.
* @type {string|null}
*/
this.moduleName = isModule ? getModuleName(name) : null
}
}
+10
View File
@@ -0,0 +1,10 @@
/**
* @author Toru Nagashima
* See LICENSE file in root directory for full license.
*/
"use strict"
module.exports = function stripImportPathParams(path) {
const i = path.indexOf("!")
return i === -1 ? path : path.slice(0, i)
}
+32
View File
@@ -0,0 +1,32 @@
# `node-ignore` 5 ChangeLog
# 5.x
## 2018-08-14, Version 5.0.1
- **PATCH**: fixes for windows.
- **PATCH**: improves tests for typescript and windows.
## 2018-08-13, Version 5.0.0
- **SEMVER-MAJOR**: [#20](https://github.com/kaelzhang/node-ignore/issues/20): it will throw if an invalid pathname passes into `.ignores(pathname)`, see [Upgrade 4.x -> 5.x](https://github.com/kaelzhang/node-ignore#upgrade-4x---5x).
- **FEATURE**: [#31](https://github.com/kaelzhang/node-ignore/issues/31): adds a new method [`.test(pathname)`](https://github.com/kaelzhang/node-ignore#testpathname-pathname-since-500).
- **BENCHMARK**: improves performance by 26%.
# 4.x
## 2018-08-12, Version 4.0.6
- **PATCH**: `Object.prototype` methods will not ruin the result any more.
## ~ 2018-08-09, Version 4.0.1 - 4.0.5
- **PATCH**: updates README.md about frequent asked quesions from github issues.
## 2018-06-22, Version 4.0.0
- **SEMVER-MAJOR**: Drop support for node < 6 by default.
- **FEATURE**: supports the missing character ranges and sets, such as `*.[a-z]` and `*.[jJ][pP][gG]`
- **FEATURE**: new option: `ignorecase` to make `ignore` case insensitive.
- **FEATURE**: supports question mark which matches a single character.
- **PATCH**: fixes typescript declaration.
+21
View File
@@ -0,0 +1,21 @@
Copyright (c) 2013 Kael Zhang <i@kael.me>, contributors
http://kael.me/
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+373
View File
@@ -0,0 +1,373 @@
<table><thead>
<tr>
<th>Linux</th>
<th>OS X</th>
<th>Windows</th>
<th>Coverage</th>
<th>Downloads</th>
</tr>
</thead><tbody><tr>
<td colspan="2" align="center">
<a href="https://travis-ci.org/kaelzhang/node-ignore">
<img
src="https://travis-ci.org/kaelzhang/node-ignore.svg?branch=master"
alt="Build Status" /></a>
</td>
<td align="center">
<a href="https://ci.appveyor.com/project/kaelzhang/node-ignore">
<img
src="https://ci.appveyor.com/api/projects/status/github/kaelzhang/node-ignore?branch=master&svg=true"
alt="Windows Build Status" /></a>
</td>
<td align="center">
<a href="https://codecov.io/gh/kaelzhang/node-ignore">
<img
src="https://codecov.io/gh/kaelzhang/node-ignore/branch/master/graph/badge.svg"
alt="Coverage Status" /></a>
</td>
<td align="center">
<a href="https://www.npmjs.org/package/ignore">
<img
src="http://img.shields.io/npm/dm/ignore.svg"
alt="npm module downloads per month" /></a>
</td>
</tr></tbody></table>
# ignore
`ignore` is a manager, filter and parser which implemented in pure JavaScript according to the .gitignore [spec](http://git-scm.com/docs/gitignore).
Pay attention that [`minimatch`](https://www.npmjs.org/package/minimatch) does not work in the gitignore way. To filter filenames according to .gitignore file, I recommend this module.
##### Tested on
- Linux + Node: `0.8` - `7.x`
- Windows + Node: `0.10` - `7.x`, node < `0.10` is not tested due to the lack of support of appveyor.
Actually, `ignore` does not rely on any versions of node specially.
Since `4.0.0`, ignore will no longer support `node < 6` by default, to use in node < 6, `require('ignore/legacy')`. For details, see [CHANGELOG](https://github.com/kaelzhang/node-ignore/blob/master/CHANGELOG.md).
## Table Of Main Contents
- [Usage](#usage)
- [`Pathname` Conventions](#pathname-conventions)
- See Also:
- [`glob-gitignore`](https://www.npmjs.com/package/glob-gitignore) matches files using patterns and filters them according to gitignore rules.
- [Upgrade Guide](#upgrade-guide)
## Usage
```js
import ignore from 'ignore'
const ig = ignore().add(['.abc/*', '!.abc/d/'])
```
### Filter the given paths
```js
const paths = [
'.abc/a.js', // filtered out
'.abc/d/e.js' // included
]
ig.filter(paths) // ['.abc/d/e.js']
ig.ignores('.abc/a.js') // true
```
### As the filter function
```js
paths.filter(ig.createFilter()); // ['.abc/d/e.js']
```
### Win32 paths will be handled
```js
ig.filter(['.abc\\a.js', '.abc\\d\\e.js'])
// if the code above runs on windows, the result will be
// ['.abc\\d\\e.js']
```
## Why another ignore?
- `ignore` is a standalone module, and is much simpler so that it could easy work with other programs, unlike [isaacs](https://npmjs.org/~isaacs)'s [fstream-ignore](https://npmjs.org/package/fstream-ignore) which must work with the modules of the fstream family.
- `ignore` only contains utility methods to filter paths according to the specified ignore rules, so
- `ignore` never try to find out ignore rules by traversing directories or fetching from git configurations.
- `ignore` don't cares about sub-modules of git projects.
- Exactly according to [gitignore man page](http://git-scm.com/docs/gitignore), fixes some known matching issues of fstream-ignore, such as:
- '`/*.js`' should only match '`a.js`', but not '`abc/a.js`'.
- '`**/foo`' should match '`foo`' anywhere.
- Prevent re-including a file if a parent directory of that file is excluded.
- Handle trailing whitespaces:
- `'a '`(one space) should not match `'a '`(two spaces).
- `'a \ '` matches `'a '`
- All test cases are verified with the result of `git check-ignore`.
# Methods
## .add(pattern: string | Ignore): this
## .add(patterns: Array<string | Ignore>): this
- **pattern** `String | Ignore` An ignore pattern string, or the `Ignore` instance
- **patterns** `Array<String | Ignore>` Array of ignore patterns.
Adds a rule or several rules to the current manager.
Returns `this`
Notice that a line starting with `'#'`(hash) is treated as a comment. Put a backslash (`'\'`) in front of the first hash for patterns that begin with a hash, if you want to ignore a file with a hash at the beginning of the filename.
```js
ignore().add('#abc').ignores('#abc') // false
ignore().add('\#abc').ignores('#abc') // true
```
`pattern` could either be a line of ignore pattern or a string of multiple ignore patterns, which means we could just `ignore().add()` the content of a ignore file:
```js
ignore()
.add(fs.readFileSync(filenameOfGitignore).toString())
.filter(filenames)
```
`pattern` could also be an `ignore` instance, so that we could easily inherit the rules of another `Ignore` instance.
## <strike>.addIgnoreFile(path)</strike>
REMOVED in `3.x` for now.
To upgrade `ignore@2.x` up to `3.x`, use
```js
import fs from 'fs'
if (fs.existsSync(filename)) {
ignore().add(fs.readFileSync(filename).toString())
}
```
instead.
## .filter(paths: Array&lt;Pathname&gt;): Array&lt;Pathname&gt;
```ts
type Pathname = string
```
Filters the given array of pathnames, and returns the filtered array.
- **paths** `Array.<Pathname>` The array of `pathname`s to be filtered.
### `Pathname` Conventions:
#### 1. `Pathname` should be a `path.relative()`d pathname
`Pathname` should be a string that have been `path.join()`ed, or the return value of `path.relative()` to the current directory,
```js
// WRONG, an error will be thrown
ig.ignores('./abc')
// WRONG, for it will never happen, and an error will be thrown
// If the gitignore rule locates at the root directory,
// `'/abc'` should be changed to `'abc'`.
// ```
// path.relative('/', '/abc') -> 'abc'
// ```
ig.ignores('/abc')
// Right
ig.ignores('abc')
// Right
ig.ignores(path.join('./abc')) // path.join('./abc') -> 'abc'
```
In other words, each `Pathname` here should be a relative path to the directory of the gitignore rules.
Suppose the dir structure is:
```
/path/to/your/repo
|-- a
| |-- a.js
|
|-- .b
|
|-- .c
|-- .DS_store
```
Then the `paths` might be like this:
```js
[
'a/a.js'
'.b',
'.c/.DS_store'
]
```
#### 2. filenames and dirnames
`node-ignore` does NO `fs.stat` during path matching, so for the example below:
```js
// First, we add a ignore pattern to ignore a directory
ig.add('config/')
// `ig` does NOT know if 'config', in the real world,
// is a normal file, directory or something.
ig.ignores('config')
// `ig` treats `config` as a file, so it returns `false`
ig.ignores('config/')
// returns `true`
```
Specially for people who develop some library based on `node-ignore`, it is important to understand that.
Usually, you could use [`glob`](http://npmjs.org/package/glob) with `option.mark = true` to fetch the structure of the current directory:
```js
import glob from 'glob'
glob('**', {
// Adds a / character to directory matches.
mark: true
}, (err, files) => {
if (err) {
return console.error(err)
}
let filtered = ignore().add(patterns).filter(files)
console.log(filtered)
})
```
## .ignores(pathname: Pathname): boolean
> new in 3.2.0
Returns `Boolean` whether `pathname` should be ignored.
```js
ig.ignores('.abc/a.js') // true
```
## .createFilter()
Creates a filter function which could filter an array of paths with `Array.prototype.filter`.
Returns `function(path)` the filter function.
## .test(pathname: Pathname) since 5.0.0
Returns `TestResult`
```ts
interface TestResult {
ignored: boolean
// true if the `pathname` is finally unignored by some negative pattern
unignored: boolean
}
```
- `{ignored: true, unignored: false}`: the `pathname` is ignored
- `{ignored: false, unignored: true}`: the `pathname` is unignored
- `{ignored: false, unignored: false}`: the `pathname` is never matched by any ignore rules.
## `options.ignorecase` since 4.0.0
Similar as the `core.ignorecase` option of [git-config](https://git-scm.com/docs/git-config), `node-ignore` will be case insensitive if `options.ignorecase` is set to `true` (the default value), otherwise case sensitive.
```js
const ig = ignore({
ignorecase: false
})
ig.add('*.png')
ig.ignores('*.PNG') // false
```
## static `ignore.isPathValid(pathname): boolean` since 5.0.0
Check whether the `pathname` is valid according to the [convention](#1-pathname-should-be-a-pathrelatived-pathname).
```js
ignore.isPathValid('./foo') // false
```
****
# Upgrade Guide
## Upgrade 4.x -> 5.x
Since `5.0.0`, if an invalid `Pathname` passed into `ig.ignores()`, an error will be thrown, while `ignore < 5.0.0` did not make sure what the return value was, as well as
```ts
.ignores(pathname: Pathname): boolean
.filter(pathnames: Array<Pathname>): Array<Pathname>
.createFilter(): (pathname: Pathname) => boolean
.test(pathname: Pathname): {ignored: boolean, unignored: boolean}
```
See the convention [here](#1-pathname-should-be-a-pathrelatived-pathname) for details.
If there are invalid pathnames, the conversion and filtration should be done by users.
```js
import {isPathValid} from 'ignore' // introduced in 5.0.0
const paths = [
// invalid
//////////////////
'',
false,
'../foo',
'.',
//////////////////
// valid
'foo'
]
.filter(isValidPath)
ig.filter(paths)
```
## Upgrade 3.x -> 4.x
Since `4.0.0`, `ignore` will no longer support node < 6, to use `ignore` in node < 6:
```js
var ignore = require('ignore/legacy')
```
## Upgrade 2.x -> 3.x
- All `options` of 2.x are unnecessary and removed, so just remove them.
- `ignore()` instance is no longer an [`EventEmitter`](nodejs.org/api/events.html), and all events are unnecessary and removed.
- `.addIgnoreFile()` is removed, see the [.addIgnoreFile](#addignorefilepath) section for details.
****
# Collaborators
- [@whitecolor](https://github.com/whitecolor) *Alex*
- [@SamyPesse](https://github.com/SamyPesse) *Samy Pessé*
- [@azproduction](https://github.com/azproduction) *Mikhail Davydov*
- [@TrySound](https://github.com/TrySound) *Bogdan Chadkin*
- [@JanMattner](https://github.com/JanMattner) *Jan Mattner*
- [@ntwb](https://github.com/ntwb) *Stephen Edgar*
- [@kasperisager](https://github.com/kasperisager) *Kasper Isager*
- [@sandersn](https://github.com/sandersn) *Nathan Shively-Sanders*
+63
View File
@@ -0,0 +1,63 @@
type Pathname = string
interface TestResult {
ignored: boolean
unignored: boolean
}
interface Ignore {
/**
* Adds a rule rules to the current manager.
* @param {string | Ignore} pattern
* @returns IgnoreBase
*/
add(pattern: string | Ignore): this
/**
* Adds several rules to the current manager.
* @param {string[]} patterns
* @returns IgnoreBase
*/
add(patterns: (string | Ignore)[]): this
/**
* Filters the given array of pathnames, and returns the filtered array.
* NOTICE that each path here should be a relative path to the root of your repository.
* @param paths the array of paths to be filtered.
* @returns The filtered array of paths
*/
filter(pathnames: Pathname[]): Pathname[]
/**
* Creates a filter function which could filter
* an array of paths with Array.prototype.filter.
*/
createFilter(): (pathname: Pathname) => boolean
/**
* Returns Boolean whether pathname should be ignored.
* @param {string} pathname a path to check
* @returns boolean
*/
ignores(pathname: Pathname): boolean
/**
* Returns whether pathname should be ignored or unignored
* @param {string} pathname a path to check
* @returns TestResult
*/
test(pathname: Pathname): TestResult
}
interface Options {
ignorecase?: boolean
}
/**
* Creates new ignore manager.
*/
declare function ignore(options?: Options): Ignore
declare namespace ignore {
export function isPathValid (pathname: string): boolean
}
export default ignore
+574
View File
@@ -0,0 +1,574 @@
// A simple implementation of make-array
function makeArray (subject) {
return Array.isArray(subject)
? subject
: [subject]
}
const REGEX_TEST_BLANK_LINE = /^\s+$/
const REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/
const REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/
const REGEX_SPLITALL_CRLF = /\r?\n/g
// /foo,
// ./foo,
// ../foo,
// .
// ..
const REGEX_TEST_INVALID_PATH = /^\.*\/|^\.+$/
const SLASH = '/'
const KEY_IGNORE = typeof Symbol !== 'undefined'
? Symbol.for('node-ignore')
/* istanbul ignore next */
: 'node-ignore'
const define = (object, key, value) =>
Object.defineProperty(object, key, {value})
const REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g
// Sanitize the range of a regular expression
// The cases are complicated, see test cases for details
const sanitizeRange = range => range.replace(
REGEX_REGEXP_RANGE,
(match, from, to) => from.charCodeAt(0) <= to.charCodeAt(0)
? match
// Invalid range (out of order) which is ok for gitignore rules but
// fatal for JavaScript regular expression, so eliminate it.
: ''
)
// > If the pattern ends with a slash,
// > it is removed for the purpose of the following description,
// > but it would only find a match with a directory.
// > In other words, foo/ will match a directory foo and paths underneath it,
// > but will not match a regular file or a symbolic link foo
// > (this is consistent with the way how pathspec works in general in Git).
// '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`'
// -> ignore-rules will not deal with it, because it costs extra `fs.stat` call
// you could use option `mark: true` with `glob`
// '`foo/`' should not continue with the '`..`'
const DEFAULT_REPLACER_PREFIX = [
// > Trailing spaces are ignored unless they are quoted with backslash ("\")
[
// (a\ ) -> (a )
// (a ) -> (a)
// (a \ ) -> (a )
/\\?\s+$/,
match => match.indexOf('\\') === 0
? ' '
: ''
],
// replace (\ ) with ' '
[
/\\\s/g,
() => ' '
],
// Escape metacharacters
// which is written down by users but means special for regular expressions.
// > There are 12 characters with special meanings:
// > - the backslash \,
// > - the caret ^,
// > - the dollar sign $,
// > - the period or dot .,
// > - the vertical bar or pipe symbol |,
// > - the question mark ?,
// > - the asterisk or star *,
// > - the plus sign +,
// > - the opening parenthesis (,
// > - the closing parenthesis ),
// > - and the opening square bracket [,
// > - the opening curly brace {,
// > These special characters are often called "metacharacters".
[
/[\\^$.|*+(){]/g,
match => `\\${match}`
],
[
// > [abc] matches any character inside the brackets
// > (in this case a, b, or c);
/\[([^\]/]*)($|\])/g,
(match, p1, p2) => p2 === ']'
? `[${sanitizeRange(p1)}]`
: `\\${match}`
],
[
// > a question mark (?) matches a single character
/(?!\\)\?/g,
() => '[^/]'
],
// leading slash
[
// > A leading slash matches the beginning of the pathname.
// > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c".
// A leading slash matches the beginning of the pathname
/^\//,
() => '^'
],
// replace special metacharacter slash after the leading slash
[
/\//g,
() => '\\/'
],
[
// > A leading "**" followed by a slash means match in all directories.
// > For example, "**/foo" matches file or directory "foo" anywhere,
// > the same as pattern "foo".
// > "**/foo/bar" matches file or directory "bar" anywhere that is directly
// > under directory "foo".
// Notice that the '*'s have been replaced as '\\*'
/^\^*\\\*\\\*\\\//,
// '**/foo' <-> 'foo'
() => '^(?:.*\\/)?'
]
]
const DEFAULT_REPLACER_SUFFIX = [
// starting
[
// there will be no leading '/'
// (which has been replaced by section "leading slash")
// If starts with '**', adding a '^' to the regular expression also works
/^(?=[^^])/,
function startingReplacer () {
return !/\/(?!$)/.test(this)
// > If the pattern does not contain a slash /,
// > Git treats it as a shell glob pattern
// Actually, if there is only a trailing slash,
// git also treats it as a shell glob pattern
? '(?:^|\\/)'
// > Otherwise, Git treats the pattern as a shell glob suitable for
// > consumption by fnmatch(3)
: '^'
}
],
// two globstars
[
// Use lookahead assertions so that we could match more than one `'/**'`
/\\\/\\\*\\\*(?=\\\/|$)/g,
// Zero, one or several directories
// should not use '*', or it will be replaced by the next replacer
// Check if it is not the last `'/**'`
(_, index, str) => index + 6 < str.length
// case: /**/
// > A slash followed by two consecutive asterisks then a slash matches
// > zero or more directories.
// > For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on.
// '/**/'
? '(?:\\/[^\\/]+)*'
// case: /**
// > A trailing `"/**"` matches everything inside.
// #21: everything inside but it should not include the current folder
: '\\/.+'
],
// intermediate wildcards
[
// Never replace escaped '*'
// ignore rule '\*' will match the path '*'
// 'abc.*/' -> go
// 'abc.*' -> skip this rule
/(^|[^\\]+)\\\*(?=.+)/g,
// '*.js' matches '.js'
// '*.js' doesn't match 'abc'
(_, p1) => `${p1}[^\\/]*`
],
// trailing wildcard
[
/(\^|\\\/)?\\\*$/,
(_, p1) => {
const prefix = p1
// '\^':
// '/*' does not match ''
// '/*' does not match everything
// '\\\/':
// 'abc/*' does not match 'abc/'
? `${p1}[^/]+`
// 'a*' matches 'a'
// 'a*' matches 'aa'
: '[^/]*'
return `${prefix}(?=$|\\/$)`
}
],
[
// unescape
/\\\\\\/g,
() => '\\'
]
]
const POSITIVE_REPLACERS = [
...DEFAULT_REPLACER_PREFIX,
// 'f'
// matches
// - /f(end)
// - /f/
// - (start)f(end)
// - (start)f/
// doesn't match
// - oof
// - foo
// pseudo:
// -> (^|/)f(/|$)
// ending
[
// 'js' will not match 'js.'
// 'ab' will not match 'abc'
/(?:[^*/])$/,
// 'js*' will not match 'a.js'
// 'js/' will not match 'a.js'
// 'js' will match 'a.js' and 'a.js/'
match => `${match}(?=$|\\/)`
],
...DEFAULT_REPLACER_SUFFIX
]
const NEGATIVE_REPLACERS = [
...DEFAULT_REPLACER_PREFIX,
// #24, #38
// The MISSING rule of [gitignore docs](https://git-scm.com/docs/gitignore)
// A negative pattern without a trailing wildcard should not
// re-include the things inside that directory.
// eg:
// ['node_modules/*', '!node_modules']
// should ignore `node_modules/a.js`
[
/(?:[^*])$/,
match => `${match}(?=$|\\/$)`
],
...DEFAULT_REPLACER_SUFFIX
]
// A simple cache, because an ignore rule only has only one certain meaning
const regexCache = Object.create(null)
// @param {pattern}
const makeRegex = (pattern, negative, ignorecase) => {
const r = regexCache[pattern]
if (r) {
return r
}
const replacers = negative
? NEGATIVE_REPLACERS
: POSITIVE_REPLACERS
const source = replacers.reduce(
(prev, current) => prev.replace(current[0], current[1].bind(pattern)),
pattern
)
return regexCache[pattern] = ignorecase
? new RegExp(source, 'i')
: new RegExp(source)
}
const isString = subject => typeof subject === 'string'
// > A blank line matches no files, so it can serve as a separator for readability.
const checkPattern = pattern => pattern
&& isString(pattern)
&& !REGEX_TEST_BLANK_LINE.test(pattern)
// > A line starting with # serves as a comment.
&& pattern.indexOf('#') !== 0
const splitPattern = pattern => pattern.split(REGEX_SPLITALL_CRLF)
class IgnoreRule {
constructor (
origin,
pattern,
negative,
regex
) {
this.origin = origin
this.pattern = pattern
this.negative = negative
this.regex = regex
}
}
const createRule = (pattern, ignorecase) => {
const origin = pattern
let negative = false
// > An optional prefix "!" which negates the pattern;
if (pattern.indexOf('!') === 0) {
negative = true
pattern = pattern.substr(1)
}
pattern = pattern
// > Put a backslash ("\") in front of the first "!" for patterns that
// > begin with a literal "!", for example, `"\!important!.txt"`.
.replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, '!')
// > Put a backslash ("\") in front of the first hash for patterns that
// > begin with a hash.
.replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, '#')
const regex = makeRegex(pattern, negative, ignorecase)
return new IgnoreRule(
origin,
pattern,
negative,
regex
)
}
const throwError = (message, Ctor) => {
throw new Ctor(message)
}
const returnFalse = () => false
const checkPath = (path, doThrow) => {
if (!isString(path)) {
return doThrow(
`path must be a string, but got \`${path}\``,
TypeError
)
}
// We don't know if we should ignore '', so throw
if (!path) {
return doThrow(`path must not be empty`, TypeError)
}
//
if (REGEX_TEST_INVALID_PATH.test(path)) {
const r = '`path.relative()`d'
return doThrow(
`path should be a ${r} string, but got "${path}"`,
RangeError
)
}
return true
}
class Ignore {
constructor ({
ignorecase = true
} = {}) {
this._rules = []
this._ignorecase = ignorecase
define(this, KEY_IGNORE, true)
this._initCache()
}
_initCache () {
this._ignoreCache = Object.create(null)
this._testCache = Object.create(null)
}
_addPattern (pattern) {
// #32
if (pattern && pattern[KEY_IGNORE]) {
this._rules = this._rules.concat(pattern._rules)
this._added = true
return
}
if (checkPattern(pattern)) {
const rule = createRule(pattern, this._ignorecase)
this._added = true
this._rules.push(rule)
}
}
// @param {Array<string> | string | Ignore} pattern
add (pattern) {
this._added = false
makeArray(
isString(pattern)
? splitPattern(pattern)
: pattern
).forEach(this._addPattern, this)
// Some rules have just added to the ignore,
// making the behavior changed.
if (this._added) {
this._initCache()
}
return this
}
// legacy
addPattern (pattern) {
return this.add(pattern)
}
// | ignored : unignored
// negative | 0:0 | 0:1 | 1:0 | 1:1
// -------- | ------- | ------- | ------- | --------
// 0 | TEST | TEST | SKIP | X
// 1 | TESTIF | SKIP | TEST | X
// - SKIP: always skip
// - TEST: always test
// - TESTIF: only test if checkUnignored
// - X: that never happen
// @param {boolean} whether should check if the path is unignored,
// setting `checkUnignored` to `false` could reduce additional
// path matching.
// @returns {TestResult} true if a file is ignored
_testOne (path, checkUnignored) {
let ignored = false
let unignored = false
this._rules.forEach(rule => {
const {negative} = rule
if (
unignored === negative && ignored !== unignored
|| negative && !ignored && !unignored && !checkUnignored
) {
return
}
const matched = rule.regex.test(path)
if (matched) {
ignored = !negative
unignored = negative
}
})
return {
ignored,
unignored
}
}
// @returns {TestResult}
_test (path, cache, checkUnignored, slices) {
checkPath(path, throwError)
if (path in cache) {
return cache[path]
}
if (!slices) {
// path/to/a.js
// ['path', 'to', 'a.js']
slices = path.split(SLASH)
}
slices.pop()
// If the path has no parent directory, just test it
if (!slices.length) {
return cache[path] = this._testOne(path, checkUnignored)
}
const parent = this._test(
slices.join(SLASH) + SLASH,
cache,
checkUnignored,
slices
)
// If the path contains a parent directory, check the parent first
return cache[path] = parent.ignored
// > It is not possible to re-include a file if a parent directory of
// > that file is excluded.
? parent
: this._testOne(path, checkUnignored)
}
ignores (path) {
return this._test(path, this._ignoreCache, false).ignored
}
createFilter () {
return path => !this.ignores(path)
}
filter (paths) {
return makeArray(paths).filter(this.createFilter())
}
// @returns {TestResult}
test (path) {
return this._test(path, this._testCache, true)
}
}
const factory = options => new Ignore(options)
const isPathValid = path => checkPath(path, returnFalse)
factory.isPathValid = isPathValid
// Fixes typescript
factory.default = factory
module.exports = factory
// Windows
// --------------------------------------------------------------
/* istanbul ignore if */
if (
// Detect `process` so that it can run in browsers.
typeof process !== 'undefined'
&& (
process.env && process.env.IGNORE_TEST_WIN32
|| process.platform === 'win32'
)
) {
const test = Ignore.prototype._test
/* eslint no-control-regex: "off" */
const makePosix = str => /^\\\\\?\\/.test(str)
|| /["<>|\u0000-\u001F]+/u.test(str)
? str
: str.replace(/\\/g, '/')
Ignore.prototype._test = function testWin32 (path, ...args) {
path = makePosix(path)
return test.call(this, path, ...args)
}
factory.isPathValid = path => path
? isPathValid(makePosix(path))
: isPathValid(path)
}
+471
View File
@@ -0,0 +1,471 @@
"use strict";
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
// A simple implementation of make-array
function makeArray(subject) {
return Array.isArray(subject) ? subject : [subject];
}
var REGEX_TEST_BLANK_LINE = /^\s+$/;
var REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/;
var REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/;
var REGEX_SPLITALL_CRLF = /\r?\n/g; // /foo,
// ./foo,
// ../foo,
// .
// ..
var REGEX_TEST_INVALID_PATH = /^\.*\/|^\.+$/;
var SLASH = '/';
var KEY_IGNORE = typeof Symbol !== 'undefined' ? Symbol.for('node-ignore')
/* istanbul ignore next */
: 'node-ignore';
var define = function define(object, key, value) {
return Object.defineProperty(object, key, {
value: value
});
};
var REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g; // Sanitize the range of a regular expression
// The cases are complicated, see test cases for details
var sanitizeRange = function sanitizeRange(range) {
return range.replace(REGEX_REGEXP_RANGE, function (match, from, to) {
return from.charCodeAt(0) <= to.charCodeAt(0) ? match // Invalid range (out of order) which is ok for gitignore rules but
// fatal for JavaScript regular expression, so eliminate it.
: '';
});
}; // > If the pattern ends with a slash,
// > it is removed for the purpose of the following description,
// > but it would only find a match with a directory.
// > In other words, foo/ will match a directory foo and paths underneath it,
// > but will not match a regular file or a symbolic link foo
// > (this is consistent with the way how pathspec works in general in Git).
// '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`'
// -> ignore-rules will not deal with it, because it costs extra `fs.stat` call
// you could use option `mark: true` with `glob`
// '`foo/`' should not continue with the '`..`'
var DEFAULT_REPLACER_PREFIX = [// > Trailing spaces are ignored unless they are quoted with backslash ("\")
[// (a\ ) -> (a )
// (a ) -> (a)
// (a \ ) -> (a )
/\\?\s+$/, function (match) {
return match.indexOf('\\') === 0 ? ' ' : '';
}], // replace (\ ) with ' '
[/\\\s/g, function () {
return ' ';
}], // Escape metacharacters
// which is written down by users but means special for regular expressions.
// > There are 12 characters with special meanings:
// > - the backslash \,
// > - the caret ^,
// > - the dollar sign $,
// > - the period or dot .,
// > - the vertical bar or pipe symbol |,
// > - the question mark ?,
// > - the asterisk or star *,
// > - the plus sign +,
// > - the opening parenthesis (,
// > - the closing parenthesis ),
// > - and the opening square bracket [,
// > - the opening curly brace {,
// > These special characters are often called "metacharacters".
[/[\\^$.|*+(){]/g, function (match) {
return "\\".concat(match);
}], [// > [abc] matches any character inside the brackets
// > (in this case a, b, or c);
/\[([^\]/]*)($|\])/g, function (match, p1, p2) {
return p2 === ']' ? "[".concat(sanitizeRange(p1), "]") : "\\".concat(match);
}], [// > a question mark (?) matches a single character
/(?!\\)\?/g, function () {
return '[^/]';
}], // leading slash
[// > A leading slash matches the beginning of the pathname.
// > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c".
// A leading slash matches the beginning of the pathname
/^\//, function () {
return '^';
}], // replace special metacharacter slash after the leading slash
[/\//g, function () {
return '\\/';
}], [// > A leading "**" followed by a slash means match in all directories.
// > For example, "**/foo" matches file or directory "foo" anywhere,
// > the same as pattern "foo".
// > "**/foo/bar" matches file or directory "bar" anywhere that is directly
// > under directory "foo".
// Notice that the '*'s have been replaced as '\\*'
/^\^*\\\*\\\*\\\//, // '**/foo' <-> 'foo'
function () {
return '^(?:.*\\/)?';
}]];
var DEFAULT_REPLACER_SUFFIX = [// starting
[// there will be no leading '/'
// (which has been replaced by section "leading slash")
// If starts with '**', adding a '^' to the regular expression also works
/^(?=[^^])/, function startingReplacer() {
return !/\/(?!$)/.test(this) // > If the pattern does not contain a slash /,
// > Git treats it as a shell glob pattern
// Actually, if there is only a trailing slash,
// git also treats it as a shell glob pattern
? '(?:^|\\/)' // > Otherwise, Git treats the pattern as a shell glob suitable for
// > consumption by fnmatch(3)
: '^';
}], // two globstars
[// Use lookahead assertions so that we could match more than one `'/**'`
/\\\/\\\*\\\*(?=\\\/|$)/g, // Zero, one or several directories
// should not use '*', or it will be replaced by the next replacer
// Check if it is not the last `'/**'`
function (_, index, str) {
return index + 6 < str.length // case: /**/
// > A slash followed by two consecutive asterisks then a slash matches
// > zero or more directories.
// > For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on.
// '/**/'
? '(?:\\/[^\\/]+)*' // case: /**
// > A trailing `"/**"` matches everything inside.
// #21: everything inside but it should not include the current folder
: '\\/.+';
}], // intermediate wildcards
[// Never replace escaped '*'
// ignore rule '\*' will match the path '*'
// 'abc.*/' -> go
// 'abc.*' -> skip this rule
/(^|[^\\]+)\\\*(?=.+)/g, // '*.js' matches '.js'
// '*.js' doesn't match 'abc'
function (_, p1) {
return "".concat(p1, "[^\\/]*");
}], // trailing wildcard
[/(\^|\\\/)?\\\*$/, function (_, p1) {
var prefix = p1 // '\^':
// '/*' does not match ''
// '/*' does not match everything
// '\\\/':
// 'abc/*' does not match 'abc/'
? "".concat(p1, "[^/]+") // 'a*' matches 'a'
// 'a*' matches 'aa'
: '[^/]*';
return "".concat(prefix, "(?=$|\\/$)");
}], [// unescape
/\\\\\\/g, function () {
return '\\';
}]];
var POSITIVE_REPLACERS = [].concat(DEFAULT_REPLACER_PREFIX, [// 'f'
// matches
// - /f(end)
// - /f/
// - (start)f(end)
// - (start)f/
// doesn't match
// - oof
// - foo
// pseudo:
// -> (^|/)f(/|$)
// ending
[// 'js' will not match 'js.'
// 'ab' will not match 'abc'
/(?:[^*/])$/, // 'js*' will not match 'a.js'
// 'js/' will not match 'a.js'
// 'js' will match 'a.js' and 'a.js/'
function (match) {
return "".concat(match, "(?=$|\\/)");
}]], DEFAULT_REPLACER_SUFFIX);
var NEGATIVE_REPLACERS = [].concat(DEFAULT_REPLACER_PREFIX, [// #24, #38
// The MISSING rule of [gitignore docs](https://git-scm.com/docs/gitignore)
// A negative pattern without a trailing wildcard should not
// re-include the things inside that directory.
// eg:
// ['node_modules/*', '!node_modules']
// should ignore `node_modules/a.js`
[/(?:[^*])$/, function (match) {
return "".concat(match, "(?=$|\\/$)");
}]], DEFAULT_REPLACER_SUFFIX); // A simple cache, because an ignore rule only has only one certain meaning
var regexCache = Object.create(null); // @param {pattern}
var makeRegex = function makeRegex(pattern, negative, ignorecase) {
var r = regexCache[pattern];
if (r) {
return r;
}
var replacers = negative ? NEGATIVE_REPLACERS : POSITIVE_REPLACERS;
var source = replacers.reduce(function (prev, current) {
return prev.replace(current[0], current[1].bind(pattern));
}, pattern);
return regexCache[pattern] = ignorecase ? new RegExp(source, 'i') : new RegExp(source);
};
var isString = function isString(subject) {
return typeof subject === 'string';
}; // > A blank line matches no files, so it can serve as a separator for readability.
var checkPattern = function checkPattern(pattern) {
return pattern && isString(pattern) && !REGEX_TEST_BLANK_LINE.test(pattern) // > A line starting with # serves as a comment.
&& pattern.indexOf('#') !== 0;
};
var splitPattern = function splitPattern(pattern) {
return pattern.split(REGEX_SPLITALL_CRLF);
};
var IgnoreRule = function IgnoreRule(origin, pattern, negative, regex) {
_classCallCheck(this, IgnoreRule);
this.origin = origin;
this.pattern = pattern;
this.negative = negative;
this.regex = regex;
};
var createRule = function createRule(pattern, ignorecase) {
var origin = pattern;
var negative = false; // > An optional prefix "!" which negates the pattern;
if (pattern.indexOf('!') === 0) {
negative = true;
pattern = pattern.substr(1);
}
pattern = pattern // > Put a backslash ("\") in front of the first "!" for patterns that
// > begin with a literal "!", for example, `"\!important!.txt"`.
.replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, '!') // > Put a backslash ("\") in front of the first hash for patterns that
// > begin with a hash.
.replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, '#');
var regex = makeRegex(pattern, negative, ignorecase);
return new IgnoreRule(origin, pattern, negative, regex);
};
var throwError = function throwError(message, Ctor) {
throw new Ctor(message);
};
var returnFalse = function returnFalse() {
return false;
};
var checkPath = function checkPath(path, doThrow) {
if (!isString(path)) {
return doThrow("path must be a string, but got `".concat(path, "`"), TypeError);
} // We don't know if we should ignore '', so throw
if (!path) {
return doThrow("path must not be empty", TypeError);
} //
if (REGEX_TEST_INVALID_PATH.test(path)) {
var r = '`path.relative()`d';
return doThrow("path should be a ".concat(r, " string, but got \"").concat(path, "\""), RangeError);
}
return true;
};
var Ignore =
/*#__PURE__*/
function () {
function Ignore() {
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
_ref$ignorecase = _ref.ignorecase,
ignorecase = _ref$ignorecase === void 0 ? true : _ref$ignorecase;
_classCallCheck(this, Ignore);
this._rules = [];
this._ignorecase = ignorecase;
define(this, KEY_IGNORE, true);
this._initCache();
}
_createClass(Ignore, [{
key: "_initCache",
value: function _initCache() {
this._ignoreCache = Object.create(null);
this._testCache = Object.create(null);
}
}, {
key: "_addPattern",
value: function _addPattern(pattern) {
// #32
if (pattern && pattern[KEY_IGNORE]) {
this._rules = this._rules.concat(pattern._rules);
this._added = true;
return;
}
if (checkPattern(pattern)) {
var rule = createRule(pattern, this._ignorecase);
this._added = true;
this._rules.push(rule);
}
} // @param {Array<string> | string | Ignore} pattern
}, {
key: "add",
value: function add(pattern) {
this._added = false;
makeArray(isString(pattern) ? splitPattern(pattern) : pattern).forEach(this._addPattern, this); // Some rules have just added to the ignore,
// making the behavior changed.
if (this._added) {
this._initCache();
}
return this;
} // legacy
}, {
key: "addPattern",
value: function addPattern(pattern) {
return this.add(pattern);
} // | ignored : unignored
// negative | 0:0 | 0:1 | 1:0 | 1:1
// -------- | ------- | ------- | ------- | --------
// 0 | TEST | TEST | SKIP | X
// 1 | TESTIF | SKIP | TEST | X
// - SKIP: always skip
// - TEST: always test
// - TESTIF: only test if checkUnignored
// - X: that never happen
// @param {boolean} whether should check if the path is unignored,
// setting `checkUnignored` to `false` could reduce additional
// path matching.
// @returns {TestResult} true if a file is ignored
}, {
key: "_testOne",
value: function _testOne(path, checkUnignored) {
var ignored = false;
var unignored = false;
this._rules.forEach(function (rule) {
var negative = rule.negative;
if (unignored === negative && ignored !== unignored || negative && !ignored && !unignored && !checkUnignored) {
return;
}
var matched = rule.regex.test(path);
if (matched) {
ignored = !negative;
unignored = negative;
}
});
return {
ignored: ignored,
unignored: unignored
};
} // @returns {TestResult}
}, {
key: "_test",
value: function _test(path, cache, checkUnignored, slices) {
checkPath(path, throwError);
if (path in cache) {
return cache[path];
}
if (!slices) {
// path/to/a.js
// ['path', 'to', 'a.js']
slices = path.split(SLASH);
}
slices.pop(); // If the path has no parent directory, just test it
if (!slices.length) {
return cache[path] = this._testOne(path, checkUnignored);
}
var parent = this._test(slices.join(SLASH) + SLASH, cache, checkUnignored, slices); // If the path contains a parent directory, check the parent first
return cache[path] = parent.ignored // > It is not possible to re-include a file if a parent directory of
// > that file is excluded.
? parent : this._testOne(path, checkUnignored);
}
}, {
key: "ignores",
value: function ignores(path) {
return this._test(path, this._ignoreCache, false).ignored;
}
}, {
key: "createFilter",
value: function createFilter() {
var _this = this;
return function (path) {
return !_this.ignores(path);
};
}
}, {
key: "filter",
value: function filter(paths) {
return makeArray(paths).filter(this.createFilter());
} // @returns {TestResult}
}, {
key: "test",
value: function test(path) {
return this._test(path, this._testCache, true);
}
}]);
return Ignore;
}();
var factory = function factory(options) {
return new Ignore(options);
};
var isPathValid = function isPathValid(path) {
return checkPath(path, returnFalse);
};
factory.isPathValid = isPathValid; // Fixes typescript
factory.default = factory;
module.exports = factory; // Windows
// --------------------------------------------------------------
/* istanbul ignore if */
if ( // Detect `process` so that it can run in browsers.
typeof process !== 'undefined' && (process.env && process.env.IGNORE_TEST_WIN32 || process.platform === 'win32')) {
var test = Ignore.prototype._test;
/* eslint no-control-regex: "off" */
var makePosix = function makePosix(str) {
return /^\\\\\?\\/.test(str) || /[\0-\x1F"<>\|]+/.test(str) ? str : str.replace(/\\/g, '/');
};
Ignore.prototype._test = function testWin32(path) {
path = makePosix(path);
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
return test.call.apply(test, [this, path].concat(args));
};
factory.isPathValid = function (path) {
return path ? isPathValid(makePosix(path)) : isPathValid(path);
};
}
+97
View File
@@ -0,0 +1,97 @@
{
"_from": "ignore@^5.0.2",
"_id": "ignore@5.0.6",
"_inBundle": false,
"_integrity": "sha512-/+hp3kUf/Csa32ktIaj0OlRqQxrgs30n62M90UBpNd9k+ENEch5S+hmbW3DtcJGz3sYFTh4F3A6fQ0q7KWsp4w==",
"_location": "/eslint-plugin-node/ignore",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "ignore@^5.0.2",
"name": "ignore",
"escapedName": "ignore",
"rawSpec": "^5.0.2",
"saveSpec": null,
"fetchSpec": "^5.0.2"
},
"_requiredBy": [
"/eslint-plugin-node"
],
"_resolved": "https://registry.npmjs.org/ignore/-/ignore-5.0.6.tgz",
"_shasum": "562dacc7ec27d672dde433aa683c543b24c17694",
"_spec": "ignore@^5.0.2",
"_where": "D:\\Atom\\Git\\Laravel_CSSd\\node_modules\\eslint-plugin-node",
"author": {
"name": "kael"
},
"bugs": {
"url": "https://github.com/kaelzhang/node-ignore/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "Ignore is a manager and filter for .gitignore rules, the one used by eslint, gitbook and many others.",
"devDependencies": {
"@babel/cli": "^7.2.3",
"@babel/core": "^7.3.4",
"@babel/preset-env": "^7.3.4",
"codecov": "^3.2.0",
"debug": "^4.1.1",
"eslint": "^5.15.2",
"eslint-config-ostai": "^2.0.0",
"eslint-plugin-import": "^2.16.0",
"mkdirp": "^0.5.1",
"pre-suf": "^1.1.1",
"rimraf": "^2.6.3",
"spawn-sync": "^2.0.0",
"tap": "^12.6.0",
"tmp": "0.0.33",
"typescript": "^3.3.3333"
},
"engines": {
"node": ">= 4"
},
"files": [
"legacy.js",
"index.js",
"index.d.ts",
"LICENSE-MIT"
],
"homepage": "https://github.com/kaelzhang/node-ignore#readme",
"keywords": [
"ignore",
".gitignore",
"gitignore",
"npmignore",
"rules",
"manager",
"filter",
"regexp",
"regex",
"fnmatch",
"glob",
"asterisks",
"regular-expression"
],
"license": "MIT",
"name": "ignore",
"repository": {
"type": "git",
"url": "git+ssh://git@github.com/kaelzhang/node-ignore.git"
},
"scripts": {
"build": "babel -o legacy.js index.js",
"posttest": "tap --coverage-report=html && codecov",
"prepublishOnly": "npm run build",
"test": "npm run test-no-report",
"test-no-report": "npm run test:lint && npm run test:tsc && npm run test:ts && npm run test:cases",
"test:cases": "tap test/*.js --coverage",
"test:git": "tap test/git-check-ignore.js",
"test:ignore": "tap test/ignore.js",
"test:lint": "eslint .",
"test:others": "tap test/others.js",
"test:ts": "node ./test/ts/simple.js",
"test:tsc": "tsc ./test/ts/simple.ts"
},
"version": "5.0.6"
}
+96
View File
@@ -0,0 +1,96 @@
{
"_from": "eslint-plugin-node@^8.0.1",
"_id": "eslint-plugin-node@8.0.1",
"_inBundle": false,
"_integrity": "sha512-ZjOjbjEi6jd82rIpFSgagv4CHWzG9xsQAVp1ZPlhRnnYxcTgENUVBvhYmkQ7GvT1QFijUSo69RaiOJKhMu6i8w==",
"_location": "/eslint-plugin-node",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "eslint-plugin-node@^8.0.1",
"name": "eslint-plugin-node",
"escapedName": "eslint-plugin-node",
"rawSpec": "^8.0.1",
"saveSpec": null,
"fetchSpec": "^8.0.1"
},
"_requiredBy": [
"#DEV:/"
],
"_resolved": "https://registry.npmjs.org/eslint-plugin-node/-/eslint-plugin-node-8.0.1.tgz",
"_shasum": "55ae3560022863d141fa7a11799532340a685964",
"_spec": "eslint-plugin-node@^8.0.1",
"_where": "D:\\Atom\\Git\\Laravel_CSSd",
"author": {
"name": "Toru Nagashima"
},
"bugs": {
"url": "https://github.com/mysticatea/eslint-plugin-node/issues"
},
"bundleDependencies": false,
"dependencies": {
"eslint-plugin-es": "^1.3.1",
"eslint-utils": "^1.3.1",
"ignore": "^5.0.2",
"minimatch": "^3.0.4",
"resolve": "^1.8.1",
"semver": "^5.5.0"
},
"deprecated": false,
"description": "Additional ESLint's rules for Node.js",
"devDependencies": {
"@mysticatea/eslint-plugin": "^7.0.0",
"codecov": "^3.0.4",
"eslint": "^5.8.0",
"fast-glob": "^2.2.2",
"mocha": "^5.2.0",
"nyc": "^12.0.2",
"opener": "^1.4.3",
"rimraf": "^2.6.1"
},
"engines": {
"node": ">=6"
},
"files": [
"lib"
],
"homepage": "https://github.com/mysticatea/eslint-plugin-node#readme",
"keywords": [
"eslint",
"eslintplugin",
"eslint-plugin",
"node",
"nodejs",
"ecmascript",
"shebang",
"file",
"path",
"import",
"require"
],
"license": "MIT",
"main": "lib/index.js",
"name": "eslint-plugin-node",
"peerDependencies": {
"eslint": ">=4.19.1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/mysticatea/eslint-plugin-node.git"
},
"scripts": {
"build": "node scripts/update.js",
"clean": "rimraf .nyc_output coverage",
"codecov": "nyc report -r lcovonly && codecov",
"coverage": "nyc report -r lcov && opener ./coverage/lcov-report/index.html",
"lint": "eslint lib scripts tests/lib .eslintrc.js",
"postversion": "git push && git push --tags",
"preversion": "npm t && npm run -s build",
"test": "nyc npm run -s test:_mocha",
"test:_mocha": "_mocha tests/lib/**/*.js --reporter progress",
"version": "eslint lib/rules --fix && git add lib/rules",
"watch": "npm run test:_mocha -- --watch --growl"
},
"version": "8.0.1"
}