load-plugin 2.3.0 → 4.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (5) hide show
  1. package/index.d.ts +40 -0
  2. package/index.js +149 -69
  3. package/package.json +37 -27
  4. package/readme.md +67 -41
  5. package/browser.js +0 -12
package/index.d.ts ADDED
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Load the plugin found using `resolvePlugin`.
3
+ *
4
+ * @param {string} name The name to import.
5
+ * @param {LoadOptions} [options]
6
+ * @returns {Promise<unknown>}
7
+ */
8
+ export function loadPlugin(
9
+ name: string,
10
+ options?: LoadOptions
11
+ ): Promise<unknown>
12
+ /**
13
+ * Find a plugin.
14
+ *
15
+ * See also:
16
+ * * https://docs.npmjs.com/files/folders#node-modules
17
+ * * https://github.com/sindresorhus/resolve-from
18
+ *
19
+ * Uses the standard node module loading strategy to find `$name` in each given
20
+ * `cwd` (and optionally the global `node_modules` directory).
21
+ *
22
+ * If a prefix is given and `$name` is not a path, `$prefix-$name` is also
23
+ * searched (preferring these over non-prefixed modules).
24
+ *
25
+ * @param {string} name
26
+ * @param {ResolveOptions} [options]
27
+ * @returns {Promise.<string>}
28
+ */
29
+ export function resolvePlugin(
30
+ name: string,
31
+ options?: ResolveOptions
32
+ ): Promise<string>
33
+ export type ResolveOptions = {
34
+ prefix?: string
35
+ cwd?: string | string[]
36
+ global?: boolean
37
+ }
38
+ export type LoadOptions = ResolveOptions & {
39
+ key?: string | false
40
+ }
package/index.js CHANGED
@@ -1,82 +1,140 @@
1
- 'use strict'
2
-
3
- var fs = require('fs')
4
- var path = require('path')
5
- var resolve = require('resolve-from').silent
6
- var npmPrefix = require('npm-prefix')()
1
+ /**
2
+ * @typedef ResolveOptions
3
+ * @property {string} [prefix]
4
+ * @property {string|string[]} [cwd]
5
+ * @property {boolean} [global]
6
+ */
7
+
8
+ /**
9
+ * @typedef {ResolveOptions & {key?: string|false}} LoadOptions
10
+ */
11
+
12
+ import fs from 'fs'
13
+ import {pathToFileURL, fileURLToPath} from 'url'
14
+ import path from 'path'
15
+ import {resolve as esmResolve} from 'import-meta-resolve'
16
+ import libNpmConfig from 'libnpmconfig'
17
+
18
+ const electron = process.versions.electron !== undefined
19
+ const windows = process.platform === 'win32'
20
+
21
+ const argv = process.argv[1] || /* c8 ignore next */ ''
22
+ const nvm = process.env.NVM_BIN
23
+ const appData = process.env.APPDATA
24
+
25
+ /* c8 ignore next */
26
+ const globalsLibrary = windows ? '' : 'lib'
27
+
28
+ /** @type {{prefix?: string}} */
29
+ let builtinNpmConfig
30
+
31
+ // The prefix config defaults to the location where node is installed.
32
+ // On Windows, this is in a place called `%AppData%`, which we have to
33
+ // pass to `libnpmconfig` explicitly:
34
+ /* c8 ignore next 4 */
35
+ if (windows && appData) {
36
+ builtinNpmConfig = {prefix: path.join(appData, 'npm')}
37
+ }
7
38
 
8
- module.exports = loadPlugin
9
- loadPlugin.resolve = resolvePlugin
39
+ /**
40
+ * Note: `libnpmconfig` uses `figgy-pudding` which is slated for archival.
41
+ * Either `libnpmconfig` will switch to an alternative or we’ll have to.
42
+ * @type {string}
43
+ */
44
+ let npmPrefix = libNpmConfig.read(null, builtinNpmConfig).prefix
45
+
46
+ // If there is no prefix defined, use the defaults
47
+ // See: <https://github.com/eush77/npm-prefix/blob/master/index.js>
48
+ /* c8 ignore next 5 */
49
+ if (!npmPrefix) {
50
+ npmPrefix = windows
51
+ ? path.dirname(process.execPath)
52
+ : path.resolve(process.execPath, '../..')
53
+ }
10
54
 
11
- var electron = process.versions.electron !== undefined
12
- var argv = process.argv[1] || /* istanbul ignore next */ ''
13
- var nvm = process.env.NVM_BIN
14
- var globally = electron || argv.indexOf(npmPrefix) === 0
15
- var windows = process.platform === 'win32'
16
- var prefix = windows ? /* istanbul ignore next */ '' : 'lib'
17
- var globals = path.resolve(npmPrefix, prefix, 'node_modules')
55
+ const globalsDefault = electron || argv.indexOf(npmPrefix) === 0
56
+ let globalDir = path.resolve(npmPrefix, globalsLibrary, 'node_modules')
18
57
 
19
58
  // If we’re in Electron, we’re running in a modified Node that cannot really
20
- // install global node modules. To find the actual modules, the user has to
21
- // either set `prefix` in their `.npmrc` (which is picked up by `npm-prefix`).
59
+ // install global node modules.
60
+ // To find the actual modules, the user has to set `prefix` somewhere in an
61
+ // `.npmrc` (which is picked up by `libnpmconfig`).
22
62
  // Most people don’t do that, and some use NVM instead to manage different
23
- // versions of Node. Luckily NVM leaks some environment variables that we can
24
- // pick up on to try and detect the actual modules.
25
- /* istanbul ignore next */
26
- if (electron && nvm && !fs.existsSync(globals)) {
27
- globals = path.resolve(nvm, '..', prefix, 'node_modules')
63
+ // versions of Node.
64
+ // Luckily NVM leaks some environment variables that we can pick up on to try
65
+ // and detect the actual modules.
66
+ /* c8 ignore next 3 */
67
+ if (electron && nvm && !fs.existsSync(globalDir)) {
68
+ globalDir = path.resolve(nvm, '..', globalsLibrary, 'node_modules')
28
69
  }
29
70
 
30
- // Load the plug-in found using `resolvePlugin`.
31
- function loadPlugin(name, options) {
32
- return require(resolvePlugin(name, options) || name)
71
+ /**
72
+ * Load the plugin found using `resolvePlugin`.
73
+ *
74
+ * @param {string} name The name to import.
75
+ * @param {LoadOptions} [options]
76
+ * @returns {Promise<unknown>}
77
+ */
78
+ export async function loadPlugin(name, options = {}) {
79
+ const {key = 'default', ...rest} = options
80
+ const fp = await resolvePlugin(name, rest)
81
+ /** @type {Object.<string, unknown>} */
82
+ // Bug with coverage on Node@12.
83
+ /* c8 ignore next 3 */
84
+ const mod = await import(pathToFileURL(fp).href)
85
+ return key === false ? mod : mod[key]
33
86
  }
34
87
 
35
- // Find a plugin.
36
- //
37
- // See also:
38
- // <https://docs.npmjs.com/files/folders#node-modules>
39
- // <https://github.com/sindresorhus/resolve-from>
40
- //
41
- // Uses the standard node module loading strategy to find $name in each given
42
- // `cwd` (and optionally the global `node_modules` directory).
43
- //
44
- // If a prefix is given and $name is not a path, `$prefix-$name` is also
45
- // searched (preferring these over non-prefixed modules).
46
- function resolvePlugin(name, options) {
47
- var settings = options || {}
48
- var prefix = settings.prefix
49
- var cwd = settings.cwd
50
- var filePath
51
- var sources
52
- var length
53
- var index
54
- var plugin
55
- var slash
56
- var scope = ''
57
-
58
- if (cwd && typeof cwd === 'object') {
59
- sources = cwd.concat()
60
- } else {
61
- sources = [cwd || process.cwd()]
62
- }
88
+ /**
89
+ * Find a plugin.
90
+ *
91
+ * See also:
92
+ * * https://docs.npmjs.com/files/folders#node-modules
93
+ * * https://github.com/sindresorhus/resolve-from
94
+ *
95
+ * Uses the standard node module loading strategy to find `$name` in each given
96
+ * `cwd` (and optionally the global `node_modules` directory).
97
+ *
98
+ * If a prefix is given and `$name` is not a path, `$prefix-$name` is also
99
+ * searched (preferring these over non-prefixed modules).
100
+ *
101
+ * @param {string} name
102
+ * @param {ResolveOptions} [options]
103
+ * @returns {Promise.<string>}
104
+ */
105
+ export async function resolvePlugin(name, options = {}) {
106
+ const prefix = options.prefix
107
+ ? options.prefix +
108
+ (options.prefix.charAt(options.prefix.length - 1) === '-' ? '' : '-')
109
+ : undefined
110
+ const cwd = options.cwd
111
+ const globals =
112
+ options.global === undefined || options.global === null
113
+ ? globalsDefault
114
+ : options.global
115
+ const sources = Array.isArray(cwd) ? cwd.concat() : [cwd || process.cwd()]
116
+ /** @type {string} */
117
+ let plugin
118
+ /** @type {Error} */
119
+ let lastError
63
120
 
64
121
  // Non-path.
65
122
  if (name.charAt(0) !== '.') {
66
- if (settings.global == null ? globally : settings.global) {
67
- sources.push(globals)
123
+ if (globals) {
124
+ sources.push(globalDir)
68
125
  }
69
126
 
127
+ let scope = ''
128
+
70
129
  // Unprefix module.
71
130
  if (prefix) {
72
- prefix = prefix.charAt(prefix.length - 1) === '-' ? prefix : prefix + '-'
73
-
74
131
  // Scope?
75
132
  if (name.charAt(0) === '@') {
76
- slash = name.indexOf('/')
133
+ const slash = name.indexOf('/')
77
134
 
78
- // Let’s keep the algorithm simple. No need to care if this is a
79
- // “valid” scope (I think?). But we do check for the slash.
135
+ // Let’s keep the algorithm simple.
136
+ // No need to care if this is a “valid” scope (I think?).
137
+ // But we do check for the slash.
80
138
  if (slash !== -1) {
81
139
  scope = name.slice(0, slash + 1)
82
140
  name = name.slice(slash + 1)
@@ -91,17 +149,39 @@ function resolvePlugin(name, options) {
91
149
  }
92
150
  }
93
151
 
94
- length = sources.length
95
- index = -1
152
+ let index = -1
153
+ /** @type {string} */
154
+ let fp
96
155
 
97
- while (++index < length) {
98
- cwd = sources[index]
99
- filePath = (plugin && resolve(cwd, plugin)) || resolve(cwd, name)
156
+ while (++index < sources.length) {
157
+ fp = plugin && (await attempt(sources[index], plugin))
158
+ if (fp) return fp
100
159
 
101
- if (filePath) {
102
- return filePath
103
- }
160
+ fp = await attempt(sources[index], name)
161
+ if (fp) return fp
104
162
  }
105
163
 
106
- return null
164
+ // There’s always an error.
165
+ // Bug with coverage on Node@12.
166
+ /* c8 ignore next 8 */
167
+ throw lastError
168
+
169
+ /**
170
+ * @param {string} base
171
+ * @param {string} name
172
+ * @returns {Promise<string>}
173
+ */
174
+ async function attempt(base, name) {
175
+ try {
176
+ // `import-meta-resolve` resolves from files, whereas `load-plugin` works
177
+ // on folders, which is why we add a `/` at the end.
178
+ return fileURLToPath(
179
+ await esmResolve(name, pathToFileURL(base).href + '/')
180
+ )
181
+ // Bug with coverage on Node@12.
182
+ /* c8 ignore next 1 */
183
+ } catch (error) {
184
+ lastError = error
185
+ }
186
+ }
107
187
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "load-plugin",
3
- "version": "2.3.0",
3
+ "version": "4.0.1",
4
4
  "description": "Load a submodule, plugin, or file",
5
5
  "license": "MIT",
6
6
  "keywords": [
@@ -11,34 +11,46 @@
11
11
  ],
12
12
  "repository": "wooorm/load-plugin",
13
13
  "bugs": "https://github.com/wooorm/load-plugin/issues",
14
- "author": "Titus Wormer <tituswormer@gmail.com> (http://wooorm.com)",
14
+ "funding": {
15
+ "type": "github",
16
+ "url": "https://github.com/sponsors/wooorm"
17
+ },
18
+ "author": "Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)",
15
19
  "contributors": [
16
- "Titus Wormer <tituswormer@gmail.com> (http://wooorm.com)"
20
+ "Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)"
17
21
  ],
22
+ "sideEffects": false,
23
+ "type": "module",
18
24
  "main": "index.js",
19
- "browser": "browser.js",
25
+ "types": "index.d.ts",
20
26
  "files": [
21
- "browser",
27
+ "index.d.ts",
22
28
  "index.js"
23
29
  ],
24
30
  "dependencies": {
25
- "npm-prefix": "^1.2.0",
26
- "resolve-from": "^4.0.0"
31
+ "import-meta-resolve": "^1.0.0",
32
+ "libnpmconfig": "^1.0.0"
27
33
  },
28
34
  "devDependencies": {
29
- "nyc": "^13.0.0",
30
- "prettier": "^1.12.0",
31
- "remark-cli": "^6.0.0",
32
- "remark-lint": "^6.0.0",
33
- "remark-preset-wooorm": "^4.0.0",
34
- "tape": "^4.0.0",
35
- "xo": "^0.23.0"
35
+ "@types/tape": "^4.0.0",
36
+ "c8": "^7.0.0",
37
+ "prettier": "^2.0.0",
38
+ "remark-cli": "^9.0.0",
39
+ "remark-lint": "^8.0.0",
40
+ "remark-preset-wooorm": "^8.0.0",
41
+ "rimraf": "^3.0.0",
42
+ "tape": "^5.0.0",
43
+ "type-coverage": "^2.0.0",
44
+ "typescript": "^4.0.0",
45
+ "xo": "^0.39.0"
36
46
  },
37
47
  "scripts": {
38
- "format": "remark . -qfo && prettier --write \"**/*.js\" && xo --fix",
39
- "test-api": "node test",
40
- "test-coverage": "nyc --reporter lcov tape test/index.js",
41
- "test": "npm run format && npm run test-coverage"
48
+ "prepack": "npm run build && npm run format",
49
+ "build": "rimraf \"{test/**,}*.d.ts\" && tsc && type-coverage",
50
+ "format": "remark . -qfo && prettier . -w --loglevel warn && xo --fix",
51
+ "test-api": "node test/index.js",
52
+ "test-coverage": "c8 --check-coverage --branches 100 --functions 100 --lines 100 --statements 100 --reporter lcov node test/index.js",
53
+ "test": "npm run build && npm run format && npm run test-coverage"
42
54
  },
43
55
  "prettier": {
44
56
  "tabWidth": 2,
@@ -50,21 +62,19 @@
50
62
  },
51
63
  "xo": {
52
64
  "prettier": true,
53
- "esnext": false,
54
65
  "rules": {
55
- "no-eq-null": "off",
56
- "eqeqeq": "off"
66
+ "no-await-in-loop": "off"
57
67
  }
58
68
  },
59
- "nyc": {
60
- "check-coverage": true,
61
- "lines": 100,
62
- "functions": 100,
63
- "branches": 100
64
- },
65
69
  "remarkConfig": {
66
70
  "plugins": [
67
71
  "preset-wooorm"
68
72
  ]
73
+ },
74
+ "typeCoverage": {
75
+ "atLeast": 100,
76
+ "detail": true,
77
+ "strict": true,
78
+ "ignoreCatch": true
69
79
  }
70
80
  }
package/readme.md CHANGED
@@ -1,51 +1,64 @@
1
- # load-plugin [![Build Status][travis-badge]][travis] [![Coverage Status][codecov-badge]][codecov]
1
+ # load-plugin
2
+
3
+ [![Build][build-badge]][build]
4
+ [![Coverage][coverage-badge]][coverage]
5
+ [![Downloads][downloads-badge]][downloads]
2
6
 
3
7
  Load a submodule, plugin, or file.
4
8
  Like Node’s `require` and `require.resolve`, but from one or more places, and
5
9
  optionally global too.
6
10
 
7
- ## Installation
11
+ ## Install
12
+
13
+ This package is [ESM only](https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c):
14
+ Node 12+ is needed to use it and it must be `import`ed instead of `require`d.
8
15
 
9
16
  [npm][]:
10
17
 
11
- ```bash
18
+ ```sh
12
19
  npm install load-plugin
13
20
  ```
14
21
 
15
- When bundled for the browser, a small [file][browser] is included to warn that,
16
- when any of the below functions are invoked, the action is unsupported.
17
-
18
- ## Usage
22
+ ## Use
19
23
 
20
24
  Say we’re in this project (with dependencies installed):
21
25
 
22
- ```javascript
23
- var load = require('load-plugin')
26
+ ```js
27
+ import {loadPlugin, resolvePlugin} from 'load-plugin'
24
28
 
25
- load.resolve('lint', {prefix: 'remark'})
26
- // => '/Users/tilde/projects/oss/load-plugin/node_modules/remark-lint/index.js'
29
+ main()
27
30
 
28
- load.resolve('@babel/function-name', {prefix: 'helper'})
29
- // => '/Users/tilde/projects/oss/load-plugin/node_modules/@babel/helper-function-name/index.js'
31
+ async function main() {
32
+ await resolvePlugin('lint', {prefix: 'remark'})
33
+ // => '/Users/tilde/projects/oss/load-plugin/node_modules/remark-lint/index.js'
30
34
 
31
- load.resolve('./index.js', {prefix: 'remark'})
32
- // => '/Users/tilde/projects/oss/load-plugin/index.js'
35
+ await resolvePlugin('@babel/function-name', {prefix: 'helper'})
36
+ // => '/Users/tilde/projects/oss/load-plugin/node_modules/@babel/helper-function-name/lib/index.js'
33
37
 
34
- load.require('lint', {prefix: 'remark'})
35
- // => [Function: lint]
38
+ await resolvePlugin('./index.js', {prefix: 'remark'})
39
+ // => '/Users/tilde/projects/oss/load-plugin/index.js'
40
+
41
+ await loadPlugin('lint', {prefix: 'remark'})
42
+ // => [Function: lint]
43
+ }
36
44
  ```
37
45
 
38
46
  ## API
39
47
 
48
+ This package exports the following identifiers: `loadPlugin`, `resolvePlugin`.
49
+ There is no default export.
50
+
40
51
  ### `loadPlugin(name[, options])`
41
52
 
42
- Uses the standard node module loading strategy to require `name` in each given
43
- `cwd` (and optionally the global `node_modules` directory).
53
+ Uses Node’s [resolution algorithm][algo] (through
54
+ [`import-meta-resolve`][import-meta-resolve]) to load CJS and ESM packages and
55
+ files to import `name` in each given `cwd` (and optionally the global
56
+ `node_modules` directory).
44
57
 
45
- If a prefix is given and `name` is not a path, `prefix-name` is also searched
46
- (preferring these over non-prefixed modules).
47
- If name starts with a scope (`@scope/name`), the prefix is applied after it:
48
- `@scope/prefix-name`.
58
+ If a `prefix` is given and `name` is not a path, `$prefix-$name` is also
59
+ searched (preferring these over non-prefixed modules).
60
+ If `name` starts with a scope (`@scope/name`), the prefix is applied after it:
61
+ `@scope/$prefix-name`.
49
62
 
50
63
  ##### `options`
51
64
 
@@ -62,28 +75,35 @@ Place or places to search from (`string`, `Array.<string>`, default:
62
75
 
63
76
  Whether to look for `name` in [global places][global] (`boolean`, optional,
64
77
  defaults to whether global is detected).
65
- If this is nully, `load-plugin` will detect if it’s currently running in global
66
- mode: either because it’s in Electron, or because a globally installed package
67
- is running it.
78
+ If this is nullish, `load-plugin` will detect if it’s currently running in
79
+ global mode: either because it’s in Electron, or because a globally installed
80
+ package is running it.
68
81
 
69
82
  Note: Electron runs its own version of Node instead of your system Node.
70
83
  That means global packages cannot be found, unless you’ve [set-up][] a [`prefix`
71
84
  in your `.npmrc`][prefix] or are using [nvm][] to manage your system node.
72
85
 
73
- ###### Returns
86
+ ###### `options.key`
74
87
 
75
- The results of `require`ing the first path that exists.
88
+ Identifier to take from the exports (`string` or `false`, default: `'default'`).
89
+ For example when given `'whatever'`, the value of `export const whatever = 1`
90
+ will be returned, when given `'default'`, the value of `export default …` is
91
+ used, and when `false` the whole module object is returned.
76
92
 
77
- ###### Throws
93
+ ###### Returns
78
94
 
79
- If `require`ing an existing path fails, or if no existing path exists.
95
+ `Promise.<unknown>` — Promise yielding the results of `require`ing the first
96
+ path that exists.
97
+ The promise rejects if `require`ing an existing path fails, or if no existing
98
+ path exists.
80
99
 
81
- ### `loadPlugin.resolve(name[, options])`
100
+ ### `resolvePlugin(name[, options])`
82
101
 
83
102
  Search for `name`.
84
- Accepts the same parameters as [`loadPlugin`][load-plugin] but returns an
85
- absolute path for `name` instead of requiring it, and `null` if it cannot be
86
- found.
103
+ Accepts the same parameters as [`loadPlugin`][load-plugin] (except `key`) but
104
+ returns a promise resolving to an absolute path for `name` instead of importing
105
+ it.
106
+ Throws if `name` cannot be found.
87
107
 
88
108
  ## License
89
109
 
@@ -91,28 +111,34 @@ found.
91
111
 
92
112
  <!-- Definitions -->
93
113
 
94
- [travis-badge]: https://img.shields.io/travis/wooorm/load-plugin.svg
114
+ [build-badge]: https://github.com/wooorm/load-plugin/actions/workflows/main.yml/badge.svg
115
+
116
+ [build]: https://github.com/wooorm/load-plugin/actions
117
+
118
+ [coverage-badge]: https://img.shields.io/codecov/c/github/wooorm/load-plugin.svg
95
119
 
96
- [travis]: https://travis-ci.org/wooorm/load-plugin
120
+ [coverage]: https://codecov.io/github/wooorm/load-plugin
97
121
 
98
- [codecov-badge]: https://img.shields.io/codecov/c/github/wooorm/load-plugin.svg
122
+ [downloads-badge]: https://img.shields.io/npm/dm/load-plugin.svg
99
123
 
100
- [codecov]: https://codecov.io/github/wooorm/load-plugin
124
+ [downloads]: https://www.npmjs.com/package/load-plugin
101
125
 
102
126
  [npm]: https://docs.npmjs.com/cli/install
103
127
 
104
128
  [license]: license
105
129
 
106
- [author]: http://wooorm.com
130
+ [author]: https://wooorm.com
107
131
 
108
132
  [global]: https://docs.npmjs.com/files/folders#node-modules
109
133
 
110
134
  [load-plugin]: #loadpluginname-options
111
135
 
112
- [browser]: browser.js
113
-
114
136
  [prefix]: https://docs.npmjs.com/misc/config#prefix
115
137
 
116
138
  [set-up]: https://github.com/sindresorhus/guides/blob/master/npm-global-without-sudo.md
117
139
 
118
140
  [nvm]: https://github.com/creationix/nvm
141
+
142
+ [algo]: https://nodejs.org/api/esm.html#esm_resolution_algorithm
143
+
144
+ [import-meta-resolve]: https://github.com/wooorm/import-meta-resolve
package/browser.js DELETED
@@ -1,12 +0,0 @@
1
- 'use strict'
2
-
3
- module.exports = loadPlugin
4
- loadPlugin.resolve = resolvePlugin
5
-
6
- function loadPlugin() {
7
- throw new Error('Cannot require plugins in the browser')
8
- }
9
-
10
- function resolvePlugin() {
11
- throw new Error('Cannot resolve plugins in the browser')
12
- }