This commit is contained in:
2022-07-21 03:28:35 +00:00
parent d7c883d6df
commit 51b34b0e1d
30103 changed files with 4152204 additions and 23 deletions
+3
View File
@@ -0,0 +1,3 @@
---
rules:
no-console: 1
+103
View File
@@ -0,0 +1,103 @@
# Change Log
All notable changes to this module will be documented in this file.
This project adheres to [Semantic Versioning](http://semver.org/).
This change log adheres to standards from [Keep a CHANGELOG](http://keepachangelog.com).
## Unreleased
## v2.6.0 - 2020-03-28
### Added
[New] Print more helpful info if parsing fails ([#1671], thanks [@kaiyoma])
## v2.5.2 - 2020-01-12
### Fixed
- Makes the loader resolution more tolerant ([#1606], thanks [@arcanis])
- Use `createRequire` instead of `createRequireFromPath` if available ([#1602], thanks [@iamnapo])
## v2.5.1 - 2020-01-11
### Fixed
- Uses createRequireFromPath to resolve loaders ([#1591], thanks [@arcanis])
- report the error stack on a resolution error ([#599], thanks [@sompylasar])
## v2.5.0 - 2019-12-07
### Added
- support `parseForESLint` from custom parser ([#1435], thanks [@JounQin])
### Changed
- Avoid superfluous calls and code ([#1551], thanks [@brettz9])
## v2.4.1 - 2019-07-19
### Fixed
- Improve parse perf when using `@typescript-eslint/parser` ([#1409], thanks [@bradzacher])
- Improve support for TypeScript declare structures ([#1356], thanks [@christophercurrie])
## v2.4.0 - 2019-04-13
### Added
- no-useless-path-segments: Add noUselessIndex option ([#1290], thanks [@timkraut])
### Fixed
- Fix overwriting of dynamic import() CallExpression ([`no-cycle`], [`no-relative-parent-import`], [`no-unresolved`], [`no-useless-path-segments`]) ([#1218], [#1166], [#1035], thanks [@vikr01])
## v2.3.0 - 2019-01-22
### Fixed
- use `process.hrtime()` for cache dates ([#1160], thanks [@hulkish])
## v2.2.0 - 2018-03-29
### Changed
- `parse`: attach node locations by default.
- `moduleVisitor`: visitor now gets the full `import` statement node as a second
argument, so rules may report against the full statement / `require` call instead
of only the string literal node.
## v2.1.1 - 2017-06-22
Re-releasing v2.1.0 after vetting (again) and unable to reproduce issue.
## v2.1.0 - 2017-06-02 [YANKED]
Yanked due to critical issue with cache key resulting from #839.
### Added
- `parse` now additionally passes `filePath` to `parser` in `parserOptions` like `eslint` core does
## v2.0.0 - 2016-11-07
### Changed
- `unambiguous` no longer exposes fast test regex
### Fixed
- `unambiguous.test()` regex is now properly in multiline mode
[#1671]: https://github.com/benmosher/eslint-plugin-import/pull/1671
[#1606]: https://github.com/benmosher/eslint-plugin-import/pull/1606
[#1602]: https://github.com/benmosher/eslint-plugin-import/pull/1602
[#1591]: https://github.com/benmosher/eslint-plugin-import/pull/1591
[#1551]: https://github.com/benmosher/eslint-plugin-import/pull/1551
[#1435]: https://github.com/benmosher/eslint-plugin-import/pull/1435
[#1409]: https://github.com/benmosher/eslint-plugin-import/pull/1409
[#1356]: https://github.com/benmosher/eslint-plugin-import/pull/1356
[#1290]: https://github.com/benmosher/eslint-plugin-import/pull/1290
[#1218]: https://github.com/benmosher/eslint-plugin-import/pull/1218
[#1166]: https://github.com/benmosher/eslint-plugin-import/issues/1166
[#1160]: https://github.com/benmosher/eslint-plugin-import/pull/1160
[#1035]: https://github.com/benmosher/eslint-plugin-import/issues/1035
[#599]: https://github.com/benmosher/eslint-plugin-import/pull/599
[@hulkish]: https://github.com/hulkish
[@timkraut]: https://github.com/timkraut
[@vikr01]: https://github.com/vikr01
[@bradzacher]: https://github.com/bradzacher
[@christophercurrie]: https://github.com/christophercurrie
[@brettz9]: https://github.com/brettz9
[@JounQin]: https://github.com/JounQin
[@arcanis]: https://github.com/arcanis
[@sompylasar]: https://github.com/sompylasar
[@iamnapo]: https://github.com/iamnapo
[@kaiyoma]: https://github.com/kaiyoma
+22
View File
@@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2015 Ben Mosher
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.
+47
View File
@@ -0,0 +1,47 @@
'use strict'
exports.__esModule = true
const log = require('debug')('eslint-module-utils:ModuleCache')
class ModuleCache {
constructor(map) {
this.map = map || new Map()
}
/**
* returns value for returning inline
* @param {[type]} cacheKey [description]
* @param {[type]} result [description]
*/
set(cacheKey, result) {
this.map.set(cacheKey, { result, lastSeen: process.hrtime() })
log('setting entry for', cacheKey)
return result
}
get(cacheKey, settings) {
if (this.map.has(cacheKey)) {
const f = this.map.get(cacheKey)
// check freshness
if (process.hrtime(f.lastSeen)[0] < settings.lifetime) return f.result
} else log('cache miss for', cacheKey)
// cache miss
return undefined
}
}
ModuleCache.getSettings = function (settings) {
const cacheSettings = Object.assign({
lifetime: 30, // seconds
}, settings['import/cache'])
// parse infinity
if (cacheSettings.lifetime === '∞' || cacheSettings.lifetime === 'Infinity') {
cacheSettings.lifetime = Infinity
}
return cacheSettings
}
exports.default = ModuleCache
+14
View File
@@ -0,0 +1,14 @@
'use strict'
exports.__esModule = true
exports.default = function declaredScope(context, name) {
let references = context.getScope().references
, i
for (i = 0; i < references.length; i++) {
if (references[i].identifier.name === name) {
break
}
}
if (!references[i]) return undefined
return references[i].resolved.scope.type
}
+59
View File
@@ -0,0 +1,59 @@
/**
* utilities for hashing config objects.
* basically iteratively updates hash with a JSON-like format
*/
'use strict'
exports.__esModule = true
const createHash = require('crypto').createHash
const stringify = JSON.stringify
function hashify(value, hash) {
if (!hash) hash = createHash('sha256')
if (value instanceof Array) {
hashArray(value, hash)
} else if (value instanceof Object) {
hashObject(value, hash)
} else {
hash.update(stringify(value) || 'undefined')
}
return hash
}
exports.default = hashify
function hashArray(array, hash) {
if (!hash) hash = createHash('sha256')
hash.update('[')
for (let i = 0; i < array.length; i++) {
hashify(array[i], hash)
hash.update(',')
}
hash.update(']')
return hash
}
hashify.array = hashArray
exports.hashArray = hashArray
function hashObject(object, hash) {
if (!hash) hash = createHash('sha256')
hash.update('{')
Object.keys(object).sort().forEach(key => {
hash.update(stringify(key))
hash.update(':')
hashify(object[key], hash)
hash.update(',')
})
hash.update('}')
return hash
}
hashify.object = hashObject
exports.hashObject = hashObject
+60
View File
@@ -0,0 +1,60 @@
'use strict'
exports.__esModule = true
const extname = require('path').extname
const log = require('debug')('eslint-plugin-import:utils:ignore')
// one-shot memoized
let cachedSet, lastSettings
function validExtensions(context) {
if (cachedSet && context.settings === lastSettings) {
return cachedSet
}
lastSettings = context.settings
cachedSet = makeValidExtensionSet(context.settings)
return cachedSet
}
function makeValidExtensionSet(settings) {
// start with explicit JS-parsed extensions
const exts = new Set(settings['import/extensions'] || [ '.js' ])
// all alternate parser extensions are also valid
if ('import/parsers' in settings) {
for (let parser in settings['import/parsers']) {
const parserSettings = settings['import/parsers'][parser]
if (!Array.isArray(parserSettings)) {
throw new TypeError('"settings" for ' + parser + ' must be an array')
}
parserSettings.forEach(ext => exts.add(ext))
}
}
return exts
}
exports.getFileExtensions = makeValidExtensionSet
exports.default = function ignore(path, context) {
// check extension whitelist first (cheap)
if (!hasValidExtension(path, context)) return true
if (!('import/ignore' in context.settings)) return false
const ignoreStrings = context.settings['import/ignore']
for (let i = 0; i < ignoreStrings.length; i++) {
const regex = new RegExp(ignoreStrings[i])
if (regex.test(path)) {
log(`ignoring ${path}, matched pattern /${ignoreStrings[i]}/`)
return true
}
}
return false
}
function hasValidExtension(path, context) {
return validExtensions(context).has(extname(path))
}
exports.hasValidExtension = hasValidExtension
+30
View File
@@ -0,0 +1,30 @@
'use strict'
exports.__esModule = true
const Module = require('module')
const path = require('path')
// borrowed from babel-eslint
function createModule(filename) {
const mod = new Module(filename)
mod.filename = filename
mod.paths = Module._nodeModulePaths(path.dirname(filename))
return mod
}
exports.default = function moduleRequire(p) {
try {
// attempt to get espree relative to eslint
const eslintPath = require.resolve('eslint')
const eslintModule = createModule(eslintPath)
return require(Module._resolveFilename(p, eslintModule))
} catch(err) { /* ignore */ }
try {
// try relative to entry point
return require.main.require(p)
} catch(err) { /* ignore */ }
// finally, try from here
return require(p)
}
+141
View File
@@ -0,0 +1,141 @@
'use strict'
exports.__esModule = true
/**
* Returns an object of node visitors that will call
* 'visitor' with every discovered module path.
*
* todo: correct function prototype for visitor
* @param {Function(String)} visitor [description]
* @param {[type]} options [description]
* @return {object}
*/
exports.default = function visitModules(visitor, options) {
// if esmodule is not explicitly disabled, it is assumed to be enabled
options = Object.assign({ esmodule: true }, options)
let ignoreRegExps = []
if (options.ignore != null) {
ignoreRegExps = options.ignore.map(p => new RegExp(p))
}
function checkSourceValue(source, importer) {
if (source == null) return //?
// handle ignore
if (ignoreRegExps.some(re => re.test(source.value))) return
// fire visitor
visitor(source, importer)
}
// for import-y declarations
function checkSource(node) {
checkSourceValue(node.source, node)
}
// for esmodule dynamic `import()` calls
function checkImportCall(node) {
if (node.callee.type !== 'Import') return
if (node.arguments.length !== 1) return
const modulePath = node.arguments[0]
if (modulePath.type !== 'Literal') return
if (typeof modulePath.value !== 'string') return
checkSourceValue(modulePath, node)
}
// for CommonJS `require` calls
// adapted from @mctep: http://git.io/v4rAu
function checkCommon(call) {
if (call.callee.type !== 'Identifier') return
if (call.callee.name !== 'require') return
if (call.arguments.length !== 1) return
const modulePath = call.arguments[0]
if (modulePath.type !== 'Literal') return
if (typeof modulePath.value !== 'string') return
checkSourceValue(modulePath, call)
}
function checkAMD(call) {
if (call.callee.type !== 'Identifier') return
if (call.callee.name !== 'require' &&
call.callee.name !== 'define') return
if (call.arguments.length !== 2) return
const modules = call.arguments[0]
if (modules.type !== 'ArrayExpression') return
for (let element of modules.elements) {
if (element.type !== 'Literal') continue
if (typeof element.value !== 'string') continue
if (element.value === 'require' ||
element.value === 'exports') continue // magic modules: http://git.io/vByan
checkSourceValue(element, element)
}
}
const visitors = {}
if (options.esmodule) {
Object.assign(visitors, {
'ImportDeclaration': checkSource,
'ExportNamedDeclaration': checkSource,
'ExportAllDeclaration': checkSource,
'CallExpression': checkImportCall,
})
}
if (options.commonjs || options.amd) {
const currentCallExpression = visitors['CallExpression']
visitors['CallExpression'] = function (call) {
if (currentCallExpression) currentCallExpression(call)
if (options.commonjs) checkCommon(call)
if (options.amd) checkAMD(call)
}
}
return visitors
}
/**
* make an options schema for the module visitor, optionally
* adding extra fields.
*/
function makeOptionsSchema(additionalProperties) {
const base = {
'type': 'object',
'properties': {
'commonjs': { 'type': 'boolean' },
'amd': { 'type': 'boolean' },
'esmodule': { 'type': 'boolean' },
'ignore': {
'type': 'array',
'minItems': 1,
'items': { 'type': 'string' },
'uniqueItems': true,
},
},
'additionalProperties': false,
}
if (additionalProperties){
for (let key in additionalProperties) {
base.properties[key] = additionalProperties[key]
}
}
return base
}
exports.makeOptionsSchema = makeOptionsSchema
/**
* json schema object for options parameter. can be used to build
* rule options schema object.
* @type {Object}
*/
exports.optionsSchema = makeOptionsSchema()
+48
View File
@@ -0,0 +1,48 @@
'use strict';
const path = require('path');
const locatePath = require('locate-path');
module.exports = (filename, opts) => {
opts = opts || {};
const startDir = path.resolve(opts.cwd || '');
const root = path.parse(startDir).root;
const filenames = [].concat(filename);
return new Promise(resolve => {
(function find(dir) {
locatePath(filenames, {cwd: dir}).then(file => {
if (file) {
resolve(path.join(dir, file));
} else if (dir === root) {
resolve(null);
} else {
find(path.dirname(dir));
}
});
})(startDir);
});
};
module.exports.sync = (filename, opts) => {
opts = opts || {};
let dir = path.resolve(opts.cwd || '');
const root = path.parse(dir).root;
const filenames = [].concat(filename);
// eslint-disable-next-line no-constant-condition
while (true) {
const file = locatePath.sync(filenames, {cwd: dir});
if (file) {
return path.join(dir, file);
} else if (dir === root) {
return null;
}
dir = path.dirname(dir);
}
};
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
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.
+89
View File
@@ -0,0 +1,89 @@
{
"_args": [
[
"find-up@2.1.0",
"/home/node/nuxt"
]
],
"_development": true,
"_from": "find-up@2.1.0",
"_id": "find-up@2.1.0",
"_inBundle": false,
"_integrity": "sha1-RdG35QbHF93UgndaK3eSCjwMV6c=",
"_location": "/eslint-module-utils/find-up",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "find-up@2.1.0",
"name": "find-up",
"escapedName": "find-up",
"rawSpec": "2.1.0",
"saveSpec": null,
"fetchSpec": "2.1.0"
},
"_requiredBy": [
"/eslint-module-utils/pkg-dir"
],
"_resolved": "https://registry.npmjs.org/find-up/-/find-up-2.1.0.tgz",
"_spec": "2.1.0",
"_where": "/home/node/nuxt",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"bugs": {
"url": "https://github.com/sindresorhus/find-up/issues"
},
"dependencies": {
"locate-path": "^2.0.0"
},
"description": "Find a file by walking up parent directories",
"devDependencies": {
"ava": "*",
"tempfile": "^1.1.1",
"xo": "*"
},
"engines": {
"node": ">=4"
},
"files": [
"index.js"
],
"homepage": "https://github.com/sindresorhus/find-up#readme",
"keywords": [
"find",
"up",
"find-up",
"findup",
"look-up",
"look",
"file",
"search",
"match",
"package",
"resolve",
"parent",
"parents",
"folder",
"directory",
"dir",
"walk",
"walking",
"path"
],
"license": "MIT",
"name": "find-up",
"repository": {
"type": "git",
"url": "git+https://github.com/sindresorhus/find-up.git"
},
"scripts": {
"test": "xo && ava"
},
"version": "2.1.0",
"xo": {
"esnext": true
}
}
+85
View File
@@ -0,0 +1,85 @@
# find-up [![Build Status: Linux and macOS](https://travis-ci.org/sindresorhus/find-up.svg?branch=master)](https://travis-ci.org/sindresorhus/find-up) [![Build Status: Windows](https://ci.appveyor.com/api/projects/status/l0cyjmvh5lq72vq2/branch/master?svg=true)](https://ci.appveyor.com/project/sindresorhus/find-up/branch/master)
> Find a file by walking up parent directories
## Install
```
$ npm install --save find-up
```
## Usage
```
/
└── Users
└── sindresorhus
├── unicorn.png
└── foo
└── bar
├── baz
└── example.js
```
```js
// example.js
const findUp = require('find-up');
findUp('unicorn.png').then(filepath => {
console.log(filepath);
//=> '/Users/sindresorhus/unicorn.png'
});
findUp(['rainbow.png', 'unicorn.png']).then(filepath => {
console.log(filepath);
//=> '/Users/sindresorhus/unicorn.png'
});
```
## API
### findUp(filename, [options])
Returns a `Promise` for the filepath or `null`.
### findUp([filenameA, filenameB], [options])
Returns a `Promise` for the first filepath found (by respecting the order) or `null`.
### findUp.sync(filename, [options])
Returns a filepath or `null`.
### findUp.sync([filenameA, filenameB], [options])
Returns the first filepath found (by respecting the order) or `null`.
#### filename
Type: `string`
Filename of the file to find.
#### options
##### cwd
Type: `string`<br>
Default: `process.cwd()`
Directory to start from.
## Related
- [find-up-cli](https://github.com/sindresorhus/find-up-cli) - CLI for this module
- [pkg-up](https://github.com/sindresorhus/pkg-up) - Find the closest package.json file
- [pkg-dir](https://github.com/sindresorhus/pkg-dir) - Find the root directory of an npm package
## License
MIT © [Sindre Sorhus](https://sindresorhus.com)
+24
View File
@@ -0,0 +1,24 @@
'use strict';
const path = require('path');
const pathExists = require('path-exists');
const pLocate = require('p-locate');
module.exports = (iterable, opts) => {
opts = Object.assign({
cwd: process.cwd()
}, opts);
return pLocate(iterable, el => pathExists(path.resolve(opts.cwd, el)), opts);
};
module.exports.sync = (iterable, opts) => {
opts = Object.assign({
cwd: process.cwd()
}, opts);
for (const el of iterable) {
if (pathExists.sync(path.resolve(opts.cwd, el))) {
return el;
}
}
};
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
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.
+83
View File
@@ -0,0 +1,83 @@
{
"_args": [
[
"locate-path@2.0.0",
"/home/node/nuxt"
]
],
"_development": true,
"_from": "locate-path@2.0.0",
"_id": "locate-path@2.0.0",
"_inBundle": false,
"_integrity": "sha1-K1aLJl7slExtnA3pw9u7ygNUzY4=",
"_location": "/eslint-module-utils/locate-path",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "locate-path@2.0.0",
"name": "locate-path",
"escapedName": "locate-path",
"rawSpec": "2.0.0",
"saveSpec": null,
"fetchSpec": "2.0.0"
},
"_requiredBy": [
"/eslint-module-utils/find-up"
],
"_resolved": "https://registry.npmjs.org/locate-path/-/locate-path-2.0.0.tgz",
"_spec": "2.0.0",
"_where": "/home/node/nuxt",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"bugs": {
"url": "https://github.com/sindresorhus/locate-path/issues"
},
"dependencies": {
"p-locate": "^2.0.0",
"path-exists": "^3.0.0"
},
"description": "Get the first path that exists on disk of multiple paths",
"devDependencies": {
"ava": "*",
"xo": "*"
},
"engines": {
"node": ">=4"
},
"files": [
"index.js"
],
"homepage": "https://github.com/sindresorhus/locate-path#readme",
"keywords": [
"locate",
"path",
"paths",
"file",
"files",
"exists",
"find",
"finder",
"search",
"searcher",
"array",
"iterable",
"iterator"
],
"license": "MIT",
"name": "locate-path",
"repository": {
"type": "git",
"url": "git+https://github.com/sindresorhus/locate-path.git"
},
"scripts": {
"test": "xo && ava"
},
"version": "2.0.0",
"xo": {
"esnext": true
}
}
+99
View File
@@ -0,0 +1,99 @@
# locate-path [![Build Status](https://travis-ci.org/sindresorhus/locate-path.svg?branch=master)](https://travis-ci.org/sindresorhus/locate-path)
> Get the first path that exists on disk of multiple paths
## Install
```
$ npm install --save locate-path
```
## Usage
Here we find the first file that exists on disk, in array order.
```js
const locatePath = require('locate-path');
const files = [
'unicorn.png',
'rainbow.png', // only this one actually exists on disk
'pony.png'
];
locatePath(files).then(foundPath => {
console.log(foundPath);
//=> 'rainbow'
});
```
## API
### locatePath(input, [options])
Returns a `Promise` for the first path that exists or `undefined` if none exists.
#### input
Type: `Iterable<string>`
Paths to check.
#### options
Type: `Object`
##### concurrency
Type: `number`<br>
Default: `Infinity`<br>
Minimum: `1`
Number of concurrently pending promises.
##### preserveOrder
Type: `boolean`<br>
Default: `true`
Preserve `input` order when searching.
Disable this to improve performance if you don't care about the order.
##### cwd
Type: `string`<br>
Default: `process.cwd()`
Current working directory.
### locatePath.sync(input, [options])
Returns the first path that exists or `undefined` if none exists.
#### input
Type: `Iterable<string>`
Paths to check.
#### options
Type: `Object`
##### cwd
Same as above.
## Related
- [path-exists](https://github.com/sindresorhus/path-exists) - Check if a path exists
## License
MIT © [Sindre Sorhus](https://sindresorhus.com)
+42
View File
@@ -0,0 +1,42 @@
'use strict';
const pTry = require('p-try');
module.exports = concurrency => {
if (concurrency < 1) {
throw new TypeError('Expected `concurrency` to be a number from 1 and up');
}
const queue = [];
let activeCount = 0;
const next = () => {
activeCount--;
if (queue.length > 0) {
queue.shift()();
}
};
return fn => new Promise((resolve, reject) => {
const run = () => {
activeCount++;
pTry(fn).then(
val => {
resolve(val);
next();
},
err => {
reject(err);
next();
}
);
};
if (activeCount < concurrency) {
run();
} else {
queue.push(run);
}
});
};
+9
View File
@@ -0,0 +1,9 @@
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
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.
+85
View File
@@ -0,0 +1,85 @@
{
"_args": [
[
"p-limit@1.3.0",
"/home/node/nuxt"
]
],
"_development": true,
"_from": "p-limit@1.3.0",
"_id": "p-limit@1.3.0",
"_inBundle": false,
"_integrity": "sha512-vvcXsLAJ9Dr5rQOPk7toZQZJApBl2K4J6dANSsEuh6QI41JYcsS/qhTGa9ErIUUgK3WNQoJYvylxvjqmiqEA9Q==",
"_location": "/eslint-module-utils/p-limit",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "p-limit@1.3.0",
"name": "p-limit",
"escapedName": "p-limit",
"rawSpec": "1.3.0",
"saveSpec": null,
"fetchSpec": "1.3.0"
},
"_requiredBy": [
"/eslint-module-utils/p-locate"
],
"_resolved": "https://registry.npmjs.org/p-limit/-/p-limit-1.3.0.tgz",
"_spec": "1.3.0",
"_where": "/home/node/nuxt",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"bugs": {
"url": "https://github.com/sindresorhus/p-limit/issues"
},
"dependencies": {
"p-try": "^1.0.0"
},
"description": "Run multiple promise-returning & async functions with limited concurrency",
"devDependencies": {
"ava": "*",
"delay": "^2.0.0",
"in-range": "^1.0.0",
"random-int": "^1.0.0",
"time-span": "^2.0.0",
"xo": "*"
},
"engines": {
"node": ">=4"
},
"files": [
"index.js"
],
"homepage": "https://github.com/sindresorhus/p-limit#readme",
"keywords": [
"promise",
"limit",
"limited",
"concurrency",
"throttle",
"throat",
"rate",
"batch",
"ratelimit",
"task",
"queue",
"async",
"await",
"promises",
"bluebird"
],
"license": "MIT",
"name": "p-limit",
"repository": {
"type": "git",
"url": "git+https://github.com/sindresorhus/p-limit.git"
},
"scripts": {
"test": "xo && ava"
},
"version": "1.3.0"
}
+69
View File
@@ -0,0 +1,69 @@
# p-limit [![Build Status](https://travis-ci.org/sindresorhus/p-limit.svg?branch=master)](https://travis-ci.org/sindresorhus/p-limit)
> Run multiple promise-returning & async functions with limited concurrency
## Install
```
$ npm install p-limit
```
## Usage
```js
const pLimit = require('p-limit');
const limit = pLimit(1);
const input = [
limit(() => fetchSomething('foo')),
limit(() => fetchSomething('bar')),
limit(() => doSomething())
];
(async () => {
// Only one promise is run at once
const result = await Promise.all(input);
console.log(result);
})();
```
## API
### pLimit(concurrency)
Returns a `limit` function.
#### concurrency
Type: `number`<br>
Minimum: `1`
Concurrency limit.
### limit(fn)
Returns the promise returned by calling `fn`.
#### fn
Type: `Function`
Promise-returning/async function.
## Related
- [p-queue](https://github.com/sindresorhus/p-queue) - Promise queue with concurrency control
- [p-throttle](https://github.com/sindresorhus/p-throttle) - Throttle promise-returning & async functions
- [p-debounce](https://github.com/sindresorhus/p-debounce) - Debounce promise-returning & async functions
- [p-all](https://github.com/sindresorhus/p-all) - Run promise-returning & async functions concurrently with optional limited concurrency
- [More…](https://github.com/sindresorhus/promise-fun)
## License
MIT © [Sindre Sorhus](https://sindresorhus.com)
+31
View File
@@ -0,0 +1,31 @@
'use strict';
const pLimit = require('p-limit');
class EndError extends Error {
constructor(value) {
super();
this.value = value;
}
}
// the input can also be a promise, so we `Promise.all()` them both
const finder = el => Promise.all(el).then(val => val[1] === true && Promise.reject(new EndError(val[0])));
module.exports = (iterable, tester, opts) => {
opts = Object.assign({
concurrency: Infinity,
preserveOrder: true
}, opts);
const limit = pLimit(opts.concurrency);
// start all the promises concurrently with optional limit
const items = Array.from(iterable).map(el => [el, limit(() => Promise.resolve(el).then(tester))]);
// check the promises either serially or concurrently
const checkLimit = pLimit(opts.preserveOrder ? 1 : Infinity);
return Promise.all(items.map(el => checkLimit(() => finder(el))))
.then(() => {})
.catch(err => err instanceof EndError ? err.value : Promise.reject(err));
};
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
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.
+90
View File
@@ -0,0 +1,90 @@
{
"_args": [
[
"p-locate@2.0.0",
"/home/node/nuxt"
]
],
"_development": true,
"_from": "p-locate@2.0.0",
"_id": "p-locate@2.0.0",
"_inBundle": false,
"_integrity": "sha1-IKAQOyIqcMj9OcwuWAaA893l7EM=",
"_location": "/eslint-module-utils/p-locate",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "p-locate@2.0.0",
"name": "p-locate",
"escapedName": "p-locate",
"rawSpec": "2.0.0",
"saveSpec": null,
"fetchSpec": "2.0.0"
},
"_requiredBy": [
"/eslint-module-utils/locate-path"
],
"_resolved": "https://registry.npmjs.org/p-locate/-/p-locate-2.0.0.tgz",
"_spec": "2.0.0",
"_where": "/home/node/nuxt",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"bugs": {
"url": "https://github.com/sindresorhus/p-locate/issues"
},
"dependencies": {
"p-limit": "^1.1.0"
},
"description": "Get the first fulfilled promise that satisfies the provided testing function",
"devDependencies": {
"ava": "*",
"delay": "^1.3.1",
"in-range": "^1.0.0",
"time-span": "^1.0.0",
"xo": "*"
},
"engines": {
"node": ">=4"
},
"files": [
"index.js"
],
"homepage": "https://github.com/sindresorhus/p-locate#readme",
"keywords": [
"promise",
"locate",
"find",
"finder",
"search",
"searcher",
"test",
"array",
"collection",
"iterable",
"iterator",
"race",
"fulfilled",
"fastest",
"async",
"await",
"promises",
"bluebird"
],
"license": "MIT",
"name": "p-locate",
"repository": {
"type": "git",
"url": "git+https://github.com/sindresorhus/p-locate.git"
},
"scripts": {
"test": "xo && ava"
},
"version": "2.0.0",
"xo": {
"esnext": true
}
}
+86
View File
@@ -0,0 +1,86 @@
# p-locate [![Build Status](https://travis-ci.org/sindresorhus/p-locate.svg?branch=master)](https://travis-ci.org/sindresorhus/p-locate)
> Get the first fulfilled promise that satisfies the provided testing function
Think of it like an async version of [`Array#find`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/find).
## Install
```
$ npm install --save p-locate
```
## Usage
Here we find the first file that exists on disk, in array order.
```js
const pathExists = require('path-exists');
const pLocate = require('p-locate');
const files = [
'unicorn.png',
'rainbow.png', // only this one actually exists on disk
'pony.png'
];
pLocate(files, file => pathExists(file)).then(foundPath => {
console.log(foundPath);
//=> 'rainbow'
});
```
*The above is just an example. Use [`locate-path`](https://github.com/sindresorhus/locate-path) if you need this.*
## API
### pLocate(input, tester, [options])
Returns a `Promise` that is fulfilled when `tester` resolves to `true` or the iterable is done, or rejects if any of the promises reject. The fulfilled value is the current iterable value or `undefined` if `tester` never resolved to `true`.
#### input
Type: `Iterable<Promise|any>`
#### tester(element)
Type: `Function`
Expected to return a `Promise<boolean>` or boolean.
#### options
Type: `Object`
##### concurrency
Type: `number`<br>
Default: `Infinity`<br>
Minimum: `1`
Number of concurrently pending promises returned by `tester`.
##### preserveOrder
Type: `boolean`<br>
Default: `true`
Preserve `input` order when searching.
Disable this to improve performance if you don't care about the order.
## Related
- [p-map](https://github.com/sindresorhus/p-map) - Map over promises concurrently
- [p-filter](https://github.com/sindresorhus/p-filter) - Filter promises concurrently
- [p-any](https://github.com/sindresorhus/p-any) - Wait for any promise to be fulfilled
- [More…](https://github.com/sindresorhus/promise-fun)
## License
MIT © [Sindre Sorhus](https://sindresorhus.com)
+4
View File
@@ -0,0 +1,4 @@
'use strict';
module.exports = cb => new Promise(resolve => {
resolve(cb());
});
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
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.
+79
View File
@@ -0,0 +1,79 @@
{
"_args": [
[
"p-try@1.0.0",
"/home/node/nuxt"
]
],
"_development": true,
"_from": "p-try@1.0.0",
"_id": "p-try@1.0.0",
"_inBundle": false,
"_integrity": "sha1-y8ec26+P1CKOE/Yh8rGiN8GyB7M=",
"_location": "/eslint-module-utils/p-try",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "p-try@1.0.0",
"name": "p-try",
"escapedName": "p-try",
"rawSpec": "1.0.0",
"saveSpec": null,
"fetchSpec": "1.0.0"
},
"_requiredBy": [
"/eslint-module-utils/p-limit"
],
"_resolved": "https://registry.npmjs.org/p-try/-/p-try-1.0.0.tgz",
"_spec": "1.0.0",
"_where": "/home/node/nuxt",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"bugs": {
"url": "https://github.com/sindresorhus/p-try/issues"
},
"description": "`Promise#try()` ponyfill - Starts a promise chain",
"devDependencies": {
"ava": "*",
"xo": "*"
},
"engines": {
"node": ">=4"
},
"files": [
"index.js"
],
"homepage": "https://github.com/sindresorhus/p-try#readme",
"keywords": [
"promise",
"try",
"resolve",
"function",
"catch",
"async",
"await",
"promises",
"settled",
"ponyfill",
"polyfill",
"shim",
"bluebird"
],
"license": "MIT",
"name": "p-try",
"repository": {
"type": "git",
"url": "git+https://github.com/sindresorhus/p-try.git"
},
"scripts": {
"test": "xo && ava"
},
"version": "1.0.0",
"xo": {
"esnext": true
}
}
+38
View File
@@ -0,0 +1,38 @@
# p-try [![Build Status](https://travis-ci.org/sindresorhus/p-try.svg?branch=master)](https://travis-ci.org/sindresorhus/p-try)
> [`Promise#try()`](https://github.com/ljharb/proposal-promise-try) [ponyfill](https://ponyfill.com) - Starts a promise chain
[How is it useful?](http://cryto.net/~joepie91/blog/2016/05/11/what-is-promise-try-and-why-does-it-matter/)
## Install
```
$ npm install --save p-try
```
## Usage
```js
const pTry = require('p-try');
pTry(() => {
return synchronousFunctionThatMightThrow();
}).then(value => {
console.log(value);
}).catch(error => {
console.error(error);
});
```
## Related
- [p-finally](https://github.com/sindresorhus/p-finally) - `Promise#finally()` ponyfill - Invoked when the promise is settled regardless of outcome
- [More…](https://github.com/sindresorhus/promise-fun)
## License
MIT © [Sindre Sorhus](https://sindresorhus.com)
+10
View File
@@ -0,0 +1,10 @@
'use strict';
const path = require('path');
const findUp = require('find-up');
module.exports = cwd => findUp('package.json', {cwd}).then(fp => fp ? path.dirname(fp) : null);
module.exports.sync = cwd => {
const fp = findUp.sync('package.json', {cwd});
return fp ? path.dirname(fp) : null;
};
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
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.
+89
View File
@@ -0,0 +1,89 @@
{
"_args": [
[
"pkg-dir@2.0.0",
"/home/node/nuxt"
]
],
"_development": true,
"_from": "pkg-dir@2.0.0",
"_id": "pkg-dir@2.0.0",
"_inBundle": false,
"_integrity": "sha1-9tXREJ4Z1j7fQo4L1X4Sd3YVM0s=",
"_location": "/eslint-module-utils/pkg-dir",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "pkg-dir@2.0.0",
"name": "pkg-dir",
"escapedName": "pkg-dir",
"rawSpec": "2.0.0",
"saveSpec": null,
"fetchSpec": "2.0.0"
},
"_requiredBy": [
"/eslint-module-utils"
],
"_resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-2.0.0.tgz",
"_spec": "2.0.0",
"_where": "/home/node/nuxt",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"bugs": {
"url": "https://github.com/sindresorhus/pkg-dir/issues"
},
"dependencies": {
"find-up": "^2.1.0"
},
"description": "Find the root directory of a Node.js project or npm package",
"devDependencies": {
"ava": "*",
"xo": "*"
},
"engines": {
"node": ">=4"
},
"files": [
"index.js"
],
"homepage": "https://github.com/sindresorhus/pkg-dir#readme",
"keywords": [
"package",
"json",
"root",
"npm",
"entry",
"find",
"up",
"find-up",
"findup",
"look-up",
"look",
"file",
"search",
"match",
"resolve",
"parent",
"parents",
"folder",
"directory",
"dir",
"walk",
"walking",
"path"
],
"license": "MIT",
"name": "pkg-dir",
"repository": {
"type": "git",
"url": "git+https://github.com/sindresorhus/pkg-dir.git"
},
"scripts": {
"test": "xo && ava"
},
"version": "2.0.0"
}
+64
View File
@@ -0,0 +1,64 @@
# pkg-dir [![Build Status](https://travis-ci.org/sindresorhus/pkg-dir.svg?branch=master)](https://travis-ci.org/sindresorhus/pkg-dir)
> Find the root directory of a Node.js project or npm package
## Install
```
$ npm install --save pkg-dir
```
## Usage
```
/
└── Users
└── sindresorhus
└── foo
├── package.json
└── bar
├── baz
└── example.js
```
```js
// example.js
const pkgDir = require('pkg-dir');
pkgDir(__dirname).then(rootDir => {
console.log(rootDir);
//=> '/Users/sindresorhus/foo'
});
```
## API
### pkgDir([cwd])
Returns a `Promise` for either the project root path or `null` if it couldn't be found.
### pkgDir.sync([cwd])
Returns the project root path or `null`.
#### cwd
Type: `string`<br>
Default: `process.cwd()`
Directory to start from.
## Related
- [pkg-dir-cli](https://github.com/sindresorhus/pkg-dir-cli) - CLI for this module
- [pkg-up](https://github.com/sindresorhus/pkg-up) - Find the closest package.json file
- [find-up](https://github.com/sindresorhus/find-up) - Find a file by walking up parent directories
## License
MIT © [Sindre Sorhus](https://sindresorhus.com)
+66
View File
@@ -0,0 +1,66 @@
{
"_args": [
[
"eslint-module-utils@2.6.0",
"/home/node/nuxt"
]
],
"_development": true,
"_from": "eslint-module-utils@2.6.0",
"_id": "eslint-module-utils@2.6.0",
"_inBundle": false,
"_integrity": "sha512-6j9xxegbqe8/kZY8cYpcp0xhbK0EgJlg3g9mib3/miLaExuuwc3n5UEfSnU6hWMbT0FAYVvDbL9RrRgpUeQIvA==",
"_location": "/eslint-module-utils",
"_phantomChildren": {
"path-exists": "3.0.0"
},
"_requested": {
"type": "version",
"registry": true,
"raw": "eslint-module-utils@2.6.0",
"name": "eslint-module-utils",
"escapedName": "eslint-module-utils",
"rawSpec": "2.6.0",
"saveSpec": null,
"fetchSpec": "2.6.0"
},
"_requiredBy": [
"/eslint-plugin-import"
],
"_resolved": "https://registry.npmjs.org/eslint-module-utils/-/eslint-module-utils-2.6.0.tgz",
"_spec": "2.6.0",
"_where": "/home/node/nuxt",
"author": {
"name": "Ben Mosher",
"email": "me@benmosher.com"
},
"bugs": {
"url": "https://github.com/benmosher/eslint-plugin-import/issues"
},
"dependencies": {
"debug": "^2.6.9",
"pkg-dir": "^2.0.0"
},
"description": "Core utilities to support eslint-plugin-import and other module-related plugins.",
"engines": {
"node": ">=4"
},
"homepage": "https://github.com/benmosher/eslint-plugin-import#readme",
"keywords": [
"eslint-plugin-import",
"eslint",
"modules",
"esmodules"
],
"license": "MIT",
"name": "eslint-module-utils",
"repository": {
"type": "git",
"url": "git+https://github.com/benmosher/eslint-plugin-import.git"
},
"scripts": {
"prepublishOnly": "cp ../{LICENSE,.npmrc} ./",
"test": "echo \"Error: no test specified\" && exit 1"
},
"version": "2.6.0"
}
+82
View File
@@ -0,0 +1,82 @@
'use strict'
exports.__esModule = true
const moduleRequire = require('./module-require').default
const extname = require('path').extname
const log = require('debug')('eslint-plugin-import:parse')
exports.default = function parse(path, content, context) {
if (context == null) throw new Error('need context to parse properly')
let parserOptions = context.parserOptions
const parserPath = getParserPath(path, context)
if (!parserPath) throw new Error('parserPath is required!')
// hack: espree blows up with frozen options
parserOptions = Object.assign({}, parserOptions)
parserOptions.ecmaFeatures = Object.assign({}, parserOptions.ecmaFeatures)
// always include comments and tokens (for doc parsing)
parserOptions.comment = true
parserOptions.attachComment = true // keeping this for backward-compat with older parsers
parserOptions.tokens = true
// attach node locations
parserOptions.loc = true
parserOptions.range = true
// provide the `filePath` like eslint itself does, in `parserOptions`
// https://github.com/eslint/eslint/blob/3ec436ee/lib/linter.js#L637
parserOptions.filePath = path
// @typescript-eslint/parser will parse the entire project with typechecking if you provide
// "project" or "projects" in parserOptions. Removing these options means the parser will
// only parse one file in isolate mode, which is much, much faster.
// https://github.com/benmosher/eslint-plugin-import/issues/1408#issuecomment-509298962
delete parserOptions.project
delete parserOptions.projects
// require the parser relative to the main module (i.e., ESLint)
const parser = moduleRequire(parserPath)
if (typeof parser.parseForESLint === 'function') {
let ast
try {
ast = parser.parseForESLint(content, parserOptions).ast
} catch (e) {
console.warn()
console.warn('Error while parsing ' + parserOptions.filePath)
console.warn('Line ' + e.lineNumber + ', column ' + e.column + ': ' + e.message)
}
if (!ast || typeof ast !== 'object') {
console.warn(
'`parseForESLint` from parser `' +
parserPath +
'` is invalid and will just be ignored'
)
} else {
return ast
}
}
return parser.parse(content, parserOptions)
}
function getParserPath(path, context) {
const parsers = context.settings['import/parsers']
if (parsers != null) {
const extension = extname(path)
for (let parserPath in parsers) {
if (parsers[parserPath].indexOf(extension) > -1) {
// use this alternate parser
log('using alt parser:', parserPath)
return parserPath
}
}
}
// default to use ESLint parser
return context.parserPath
}
+241
View File
@@ -0,0 +1,241 @@
'use strict'
exports.__esModule = true
const pkgDir = require('pkg-dir')
const fs = require('fs')
const Module = require('module')
const path = require('path')
const hashObject = require('./hash').hashObject
, ModuleCache = require('./ModuleCache').default
const CASE_SENSITIVE_FS = !fs.existsSync(path.join(__dirname, 'reSOLVE.js'))
exports.CASE_SENSITIVE_FS = CASE_SENSITIVE_FS
const ERROR_NAME = 'EslintPluginImportResolveError'
const fileExistsCache = new ModuleCache()
// Polyfill Node's `Module.createRequireFromPath` if not present (added in Node v10.12.0)
// Use `Module.createRequire` if available (added in Node v12.2.0)
const createRequire = Module.createRequire || Module.createRequireFromPath || function (filename) {
const mod = new Module(filename, null)
mod.filename = filename
mod.paths = Module._nodeModulePaths(path.dirname(filename))
mod._compile(`module.exports = require;`, filename)
return mod.exports
}
function tryRequire(target, sourceFile) {
let resolved
try {
// Check if the target exists
if (sourceFile != null) {
try {
resolved = createRequire(path.resolve(sourceFile)).resolve(target)
} catch (e) {
resolved = require.resolve(target)
}
} else {
resolved = require.resolve(target)
}
} catch(e) {
// If the target does not exist then just return undefined
return undefined
}
// If the target exists then return the loaded module
return require(resolved)
}
// http://stackoverflow.com/a/27382838
exports.fileExistsWithCaseSync = function fileExistsWithCaseSync(filepath, cacheSettings) {
// don't care if the FS is case-sensitive
if (CASE_SENSITIVE_FS) return true
// null means it resolved to a builtin
if (filepath === null) return true
if (filepath.toLowerCase() === process.cwd().toLowerCase()) return true
const parsedPath = path.parse(filepath)
, dir = parsedPath.dir
let result = fileExistsCache.get(filepath, cacheSettings)
if (result != null) return result
// base case
if (dir === '' || parsedPath.root === filepath) {
result = true
} else {
const filenames = fs.readdirSync(dir)
if (filenames.indexOf(parsedPath.base) === -1) {
result = false
} else {
result = fileExistsWithCaseSync(dir, cacheSettings)
}
}
fileExistsCache.set(filepath, result)
return result
}
function relative(modulePath, sourceFile, settings) {
return fullResolve(modulePath, sourceFile, settings).path
}
function fullResolve(modulePath, sourceFile, settings) {
// check if this is a bonus core module
const coreSet = new Set(settings['import/core-modules'])
if (coreSet.has(modulePath)) return { found: true, path: null }
const sourceDir = path.dirname(sourceFile)
, cacheKey = sourceDir + hashObject(settings).digest('hex') + modulePath
const cacheSettings = ModuleCache.getSettings(settings)
const cachedPath = fileExistsCache.get(cacheKey, cacheSettings)
if (cachedPath !== undefined) return { found: true, path: cachedPath }
function cache(resolvedPath) {
fileExistsCache.set(cacheKey, resolvedPath)
}
function withResolver(resolver, config) {
function v1() {
try {
const resolved = resolver.resolveImport(modulePath, sourceFile, config)
if (resolved === undefined) return { found: false }
return { found: true, path: resolved }
} catch (err) {
return { found: false }
}
}
function v2() {
return resolver.resolve(modulePath, sourceFile, config)
}
switch (resolver.interfaceVersion) {
case 2:
return v2()
default:
case 1:
return v1()
}
}
const configResolvers = (settings['import/resolver']
|| { 'node': settings['import/resolve'] }) // backward compatibility
const resolvers = resolverReducer(configResolvers, new Map())
for (let pair of resolvers) {
let name = pair[0]
, config = pair[1]
const resolver = requireResolver(name, sourceFile)
, resolved = withResolver(resolver, config)
if (!resolved.found) continue
// else, counts
cache(resolved.path)
return resolved
}
// failed
// cache(undefined)
return { found: false }
}
exports.relative = relative
function resolverReducer(resolvers, map) {
if (resolvers instanceof Array) {
resolvers.forEach(r => resolverReducer(r, map))
return map
}
if (typeof resolvers === 'string') {
map.set(resolvers, null)
return map
}
if (typeof resolvers === 'object') {
for (let key in resolvers) {
map.set(key, resolvers[key])
}
return map
}
const err = new Error('invalid resolver config')
err.name = ERROR_NAME
throw err
}
function getBaseDir(sourceFile) {
return pkgDir.sync(sourceFile) || process.cwd()
}
function requireResolver(name, sourceFile) {
// Try to resolve package with conventional name
let resolver = tryRequire(`eslint-import-resolver-${name}`, sourceFile) ||
tryRequire(name, sourceFile) ||
tryRequire(path.resolve(getBaseDir(sourceFile), name))
if (!resolver) {
const err = new Error(`unable to load resolver "${name}".`)
err.name = ERROR_NAME
throw err
}
if (!isResolverValid(resolver)) {
const err = new Error(`${name} with invalid interface loaded as resolver`)
err.name = ERROR_NAME
throw err
}
return resolver
}
function isResolverValid(resolver) {
if (resolver.interfaceVersion === 2) {
return resolver.resolve && typeof resolver.resolve === 'function'
} else {
return resolver.resolveImport && typeof resolver.resolveImport === 'function'
}
}
const erroredContexts = new Set()
/**
* Given
* @param {string} p - module path
* @param {object} context - ESLint context
* @return {string} - the full module filesystem path;
* null if package is core;
* undefined if not found
*/
function resolve(p, context) {
try {
return relative( p
, context.getFilename()
, context.settings
)
} catch (err) {
if (!erroredContexts.has(context)) {
// The `err.stack` string starts with `err.name` followed by colon and `err.message`.
// We're filtering out the default `err.name` because it adds little value to the message.
let errMessage = err.message
if (err.name !== ERROR_NAME && err.stack) {
errMessage = err.stack.replace(/^Error: /, '')
}
context.report({
message: `Resolve error: ${errMessage}`,
loc: { line: 1, column: 0 },
})
erroredContexts.add(context)
}
}
}
resolve.relative = relative
exports.default = resolve
+30
View File
@@ -0,0 +1,30 @@
'use strict'
exports.__esModule = true
const pattern = /(^|;)\s*(export|import)((\s+\w)|(\s*[{*=]))/m
/**
* detect possible imports/exports without a full parse.
*
* A negative test means that a file is definitely _not_ a module.
* A positive test means it _could_ be.
*
* Not perfect, just a fast way to disqualify large non-ES6 modules and
* avoid a parse.
* @type {RegExp}
*/
exports.test = function isMaybeUnambiguousModule(content) {
return pattern.test(content)
}
// future-/Babel-proof at the expense of being a little loose
const unambiguousNodeType = /^(?:(?:Exp|Imp)ort.*Declaration|TSExportAssignment)$/
/**
* Given an AST, return true if the AST unambiguously represents a module.
* @param {Program node} ast
* @return {Boolean}
*/
exports.isModule = function isUnambiguousModule(ast) {
return ast.body.some(node => unambiguousNodeType.test(node.type))
}