load-plugin 3.0.0 → 5.0.0

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 +114 -80
  3. package/package.json +34 -23
  4. package/readme.md +99 -38
  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 | undefined
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 | undefined
32
+ ): Promise<string>
33
+ export type ResolveOptions = {
34
+ prefix?: string | undefined
35
+ cwd?: string | string[] | undefined
36
+ global?: boolean | undefined
37
+ }
38
+ export type LoadOptions = ResolveOptions & {
39
+ key?: string | false
40
+ }
package/index.js CHANGED
@@ -1,46 +1,47 @@
1
- 'use strict'
1
+ /**
2
+ * @typedef ResolveOptions
3
+ * @property {string} [prefix]
4
+ * @property {string|Array<string>} [cwd]
5
+ * @property {boolean} [global]
6
+ *
7
+ * @typedef {ResolveOptions & {key?: string|false}} LoadOptions
8
+ */
2
9
 
3
- var fs = require('fs')
4
- var path = require('path')
5
- var resolve = require('resolve-from').silent
6
- var readNpmConfig = require('libnpmconfig').read
10
+ import fs from 'fs'
11
+ import process from 'process'
12
+ import {pathToFileURL, fileURLToPath} from 'url'
13
+ import path from 'path'
14
+ // @ts-expect-error: untyped
15
+ import NpmConfig from '@npmcli/config'
16
+ import {resolve as esmResolve} from 'import-meta-resolve'
7
17
 
8
- module.exports = loadPlugin
9
- loadPlugin.resolve = resolvePlugin
18
+ const electron = process.versions.electron !== undefined
19
+ const windows = process.platform === 'win32'
10
20
 
11
- var electron = process.versions.electron !== undefined
12
- var windows = process.platform === 'win32'
21
+ const argv = process.argv[1] || /* c8 ignore next */ ''
22
+ const nvm = process.env.NVM_BIN
13
23
 
14
- var argv = process.argv[1] || /* istanbul ignore next */ ''
15
- var nvm = process.env.NVM_BIN
16
- var appData = process.env.APPDATA
24
+ /* c8 ignore next */
25
+ const globalsLibrary = windows ? '' : 'lib'
17
26
 
18
- /* istanbul ignore next */
19
- var globalsLibrary = windows ? '' : 'lib'
27
+ const config = new NpmConfig({definitions: {}})
20
28
 
21
- var builtinNpmConfig
29
+ config.loadGlobalPrefix()
22
30
 
23
- // The prefix config defaults to the location where node is installed.
24
- // On Windows, this is in a place called `%AppData%`, which we have to
25
- // pass to `libnpmconfig` explicitly:
26
- /* istanbul ignore next */
27
- if (windows && appData) {
28
- builtinNpmConfig = {prefix: path.join(appData, 'npm')}
29
- }
30
-
31
- var npmPrefix = readNpmConfig(null, builtinNpmConfig).prefix
31
+ /** @type {string} */
32
+ let npmPrefix = config.globalPrefix
32
33
 
33
34
  // If there is no prefix defined, use the defaults
34
35
  // See: <https://github.com/eush77/npm-prefix/blob/master/index.js>
35
- /* istanbul ignore next */
36
+ /* c8 ignore next 5 */
36
37
  if (!npmPrefix) {
37
38
  npmPrefix = windows
38
39
  ? path.dirname(process.execPath)
39
40
  : path.resolve(process.execPath, '../..')
40
41
  }
41
42
 
42
- var globally = electron || argv.indexOf(npmPrefix) === 0
43
- var globals = path.resolve(npmPrefix, globalsLibrary, 'node_modules')
43
+ const globalsDefault = electron || argv.indexOf(npmPrefix) === 0
44
+ let globalDir = path.resolve(npmPrefix, globalsLibrary, 'node_modules')
44
45
 
45
46
  // If we’re in Electron, we’re running in a modified Node that cannot really
46
47
  // install global node modules.
@@ -50,63 +51,74 @@ var globals = path.resolve(npmPrefix, globalsLibrary, 'node_modules')
50
51
  // versions of Node.
51
52
  // Luckily NVM leaks some environment variables that we can pick up on to try
52
53
  // and detect the actual modules.
53
- /* istanbul ignore next */
54
- if (electron && nvm && !fs.existsSync(globals)) {
55
- globals = path.resolve(nvm, '..', globalsLibrary, 'node_modules')
54
+ /* c8 ignore next 3 */
55
+ if (electron && nvm && !fs.existsSync(globalDir)) {
56
+ globalDir = path.resolve(nvm, '..', globalsLibrary, 'node_modules')
56
57
  }
57
58
 
58
- // Load the plugin found using `resolvePlugin`.
59
- function loadPlugin(name, options) {
60
- return require(resolvePlugin(name, options) || name)
59
+ /**
60
+ * Load the plugin found using `resolvePlugin`.
61
+ *
62
+ * @param {string} name The name to import.
63
+ * @param {LoadOptions} [options]
64
+ * @returns {Promise<unknown>}
65
+ */
66
+ export async function loadPlugin(name, options = {}) {
67
+ const {key = 'default', ...rest} = options
68
+ const fp = await resolvePlugin(name, rest)
69
+ /** @type {Record<string, unknown>} */
70
+ // Bug with coverage on Node@12.
71
+ /* c8 ignore next 3 */
72
+ const mod = await import(pathToFileURL(fp).href)
73
+ return key === false ? mod : mod[key]
61
74
  }
62
75
 
63
- // Find a plugin.
64
- //
65
- // See also:
66
- // <https://docs.npmjs.com/files/folders#node-modules>
67
- // <https://github.com/sindresorhus/resolve-from>
68
- //
69
- // Uses the standard node module loading strategy to find $name in each given
70
- // `cwd` (and optionally the global `node_modules` directory).
71
- //
72
- // If a prefix is given and $name is not a path, `$prefix-$name` is also
73
- // searched (preferring these over non-prefixed modules).
74
- function resolvePlugin(name, options) {
75
- var settings = options || {}
76
- var prefix = settings.prefix
77
- var cwd = settings.cwd
78
- var global = settings.global
79
- var filePath
80
- var sources
81
- var length
82
- var index
83
- var plugin
84
- var slash
85
- var scope = ''
86
-
87
- if (global === null || global === undefined) {
88
- global = globally
89
- }
90
-
91
- if (cwd && typeof cwd === 'object') {
92
- sources = cwd.concat()
93
- } else {
94
- sources = [cwd || process.cwd()]
95
- }
76
+ /**
77
+ * Find a plugin.
78
+ *
79
+ * See also:
80
+ * * https://docs.npmjs.com/files/folders#node-modules
81
+ * * https://github.com/sindresorhus/resolve-from
82
+ *
83
+ * Uses the standard node module loading strategy to find `$name` in each given
84
+ * `cwd` (and optionally the global `node_modules` directory).
85
+ *
86
+ * If a prefix is given and `$name` is not a path, `$prefix-$name` is also
87
+ * searched (preferring these over non-prefixed modules).
88
+ *
89
+ * @param {string} name
90
+ * @param {ResolveOptions} [options]
91
+ * @returns {Promise<string>}
92
+ */
93
+ export async function resolvePlugin(name, options = {}) {
94
+ const prefix = options.prefix
95
+ ? options.prefix +
96
+ (options.prefix.charAt(options.prefix.length - 1) === '-' ? '' : '-')
97
+ : undefined
98
+ const cwd = options.cwd
99
+ const globals =
100
+ options.global === undefined || options.global === null
101
+ ? globalsDefault
102
+ : options.global
103
+ const sources = Array.isArray(cwd) ? cwd.concat() : [cwd || process.cwd()]
104
+ /** @type {string|undefined} */
105
+ let plugin
106
+ /** @type {Error|undefined} */
107
+ let lastError
96
108
 
97
109
  // Non-path.
98
110
  if (name.charAt(0) !== '.') {
99
- if (global) {
100
- sources.push(globals)
111
+ if (globals) {
112
+ sources.push(globalDir)
101
113
  }
102
114
 
115
+ let scope = ''
116
+
103
117
  // Unprefix module.
104
118
  if (prefix) {
105
- prefix = prefix.charAt(prefix.length - 1) === '-' ? prefix : prefix + '-'
106
-
107
119
  // Scope?
108
120
  if (name.charAt(0) === '@') {
109
- slash = name.indexOf('/')
121
+ const slash = name.indexOf('/')
110
122
 
111
123
  // Let’s keep the algorithm simple.
112
124
  // No need to care if this is a “valid” scope (I think?).
@@ -125,17 +137,39 @@ function resolvePlugin(name, options) {
125
137
  }
126
138
  }
127
139
 
128
- length = sources.length
129
- index = -1
140
+ let index = -1
141
+ /** @type {string|undefined} */
142
+ let fp
130
143
 
131
- while (++index < length) {
132
- cwd = sources[index]
133
- filePath = (plugin && resolve(cwd, plugin)) || resolve(cwd, name)
144
+ while (++index < sources.length) {
145
+ fp = plugin ? await attempt(sources[index], plugin) : undefined
146
+ if (fp) return fp
134
147
 
135
- if (filePath) {
136
- return filePath
137
- }
148
+ fp = await attempt(sources[index], name)
149
+ if (fp) return fp
138
150
  }
139
151
 
140
- return null
152
+ // There’s always an error.
153
+ // Bug with coverage on Node@12.
154
+ /* c8 ignore next 8 */
155
+ throw lastError
156
+
157
+ /**
158
+ * @param {string} base
159
+ * @param {string} name
160
+ * @returns {Promise<string|undefined>}
161
+ */
162
+ async function attempt(base, name) {
163
+ try {
164
+ // `import-meta-resolve` resolves from files, whereas `load-plugin` works
165
+ // on folders, which is why we add a `/` at the end.
166
+ return fileURLToPath(
167
+ await esmResolve(name, pathToFileURL(base).href + '/')
168
+ )
169
+ // Bug with coverage on Node@12.
170
+ /* c8 ignore next 1 */
171
+ } catch (error) {
172
+ lastError = /** @type {Error} */ (error)
173
+ }
174
+ }
141
175
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "load-plugin",
3
- "version": "3.0.0",
3
+ "version": "5.0.0",
4
4
  "description": "Load a submodule, plugin, or file",
5
5
  "license": "MIT",
6
6
  "keywords": [
@@ -19,30 +19,38 @@
19
19
  "contributors": [
20
20
  "Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)"
21
21
  ],
22
+ "sideEffects": false,
23
+ "type": "module",
22
24
  "main": "index.js",
23
- "browser": "browser.js",
25
+ "types": "index.d.ts",
24
26
  "files": [
25
- "browser",
27
+ "index.d.ts",
26
28
  "index.js"
27
29
  ],
28
30
  "dependencies": {
29
- "libnpmconfig": "^1.0.0",
30
- "resolve-from": "^5.0.0"
31
+ "@npmcli/config": "^4.0.0",
32
+ "import-meta-resolve": "^2.0.0"
31
33
  },
32
34
  "devDependencies": {
33
- "nyc": "^15.0.0",
34
- "prettier": "^1.0.0",
35
- "remark-cli": "^7.0.0",
36
- "remark-lint": "^6.0.0",
37
- "remark-preset-wooorm": "^6.0.0",
38
- "tape": "^4.0.0",
39
- "xo": "^0.25.0"
35
+ "@types/tape": "^4.0.0",
36
+ "c8": "^7.0.0",
37
+ "prettier": "^2.0.0",
38
+ "remark-cli": "^10.0.0",
39
+ "remark-lint": "^9.0.0",
40
+ "remark-preset-wooorm": "^9.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.49.0"
40
46
  },
41
47
  "scripts": {
42
- "format": "remark . -qfo && prettier --write \"**/*.js\" && xo --fix",
43
- "test-api": "node test",
44
- "test-coverage": "nyc --reporter lcov tape test/index.js",
45
- "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"
46
54
  },
47
55
  "prettier": {
48
56
  "tabWidth": 2,
@@ -54,17 +62,20 @@
54
62
  },
55
63
  "xo": {
56
64
  "prettier": true,
57
- "esnext": false
58
- },
59
- "nyc": {
60
- "check-coverage": true,
61
- "lines": 100,
62
- "functions": 100,
63
- "branches": 100
65
+ "rules": {
66
+ "unicorn/prefer-node-protocol": "off",
67
+ "no-await-in-loop": "off"
68
+ }
64
69
  },
65
70
  "remarkConfig": {
66
71
  "plugins": [
67
72
  "preset-wooorm"
68
73
  ]
74
+ },
75
+ "typeCoverage": {
76
+ "atLeast": 100,
77
+ "detail": true,
78
+ "strict": true,
79
+ "ignoreCatch": true
69
80
  }
70
81
  }
package/readme.md CHANGED
@@ -4,90 +4,143 @@
4
4
  [![Coverage][coverage-badge]][coverage]
5
5
  [![Downloads][downloads-badge]][downloads]
6
6
 
7
- Load a submodule, plugin, or file.
8
- Like Node’s `require` and `require.resolve`, but from one or more places, and
9
- optionally global too.
7
+ Load submodules, plugins, or files.
8
+
9
+ ## Contents
10
+
11
+ * [What is this?](#what-is-this)
12
+ * [When to use this?](#when-to-use-this)
13
+ * [Install](#install)
14
+ * [Use](#use)
15
+ * [API](#api)
16
+ * [`loadPlugin(name[, options])`](#loadpluginname-options)
17
+ * [`resolvePlugin(name[, options])`](#resolvepluginname-options)
18
+ * [Types](#types)
19
+ * [Compatibility](#compatibility)
20
+ * [Contribute](#contribute)
21
+ * [License](#license)
22
+
23
+ ## What is this?
24
+
25
+ This package is useful when you want to load plugins.
26
+ It resolves things like Node.js does, but supports a prefix (e.g., when given a
27
+ prefix `remark` and the user provided value `gfm`, it can find `remark-gfm`),
28
+ can load from several places, and optionally global too.
29
+
30
+ ## When to use this?
31
+
32
+ This package is particularly useful when you want users to configure something
33
+ with plugins.
34
+ One example is `remark-cli` which can load remark plugins from configuration
35
+ files.
10
36
 
11
37
  ## Install
12
38
 
13
- [npm][]:
39
+ This package is [ESM only][esm].
40
+ In Node.js (version 14.14+, 16.0+, or 18.0+), install with [npm][]:
14
41
 
15
42
  ```sh
16
43
  npm install load-plugin
17
44
  ```
18
45
 
19
- When bundled for the browser, a small [file][browser] is included to warn that,
20
- when any of the below functions are invoked, the action is unsupported.
21
-
22
46
  ## Use
23
47
 
24
48
  Say we’re in this project (with dependencies installed):
25
49
 
26
- ```javascript
27
- var load = require('load-plugin')
50
+ ```js
51
+ import {loadPlugin, resolvePlugin} from 'load-plugin'
28
52
 
29
- load.resolve('lint', {prefix: 'remark'})
53
+ console.log(await resolvePlugin('lint', {prefix: 'remark'}))
30
54
  // => '/Users/tilde/projects/oss/load-plugin/node_modules/remark-lint/index.js'
31
55
 
32
- load.resolve('@babel/function-name', {prefix: 'helper'})
33
- // => '/Users/tilde/projects/oss/load-plugin/node_modules/@babel/helper-function-name/index.js'
56
+ console.log(await resolvePlugin('validator-identifier', {prefix: '@babel/helper'}))
57
+ // => '/Users/tilde/Projects/oss/load-plugin/node_modules/@babel/helper-validator-identifier/lib/index.js'
34
58
 
35
- load.resolve('./index.js', {prefix: 'remark'})
59
+ console.log(await resolvePlugin('./index.js', {prefix: 'remark'}))
36
60
  // => '/Users/tilde/projects/oss/load-plugin/index.js'
37
61
 
38
- load.require('lint', {prefix: 'remark'})
39
- // => [Function: lint]
62
+ console.log(await loadPlugin('lint', {prefix: 'remark'}))
63
+ // => [Function: remarkLint]
40
64
  ```
41
65
 
42
66
  ## API
43
67
 
68
+ This package exports the identifiers `loadPlugin` and `resolvePlugin`.
69
+ There is no default export.
70
+
44
71
  ### `loadPlugin(name[, options])`
45
72
 
46
- Uses the standard node module loading strategy to require `name` in each given
47
- `cwd` (and optionally the global `node_modules` directory).
73
+ Uses Node’s [resolution algorithm][algo] (through
74
+ [`import-meta-resolve`][import-meta-resolve]) to load CJS and ESM packages and
75
+ files to import `name` in each given `cwd` (and optionally the global
76
+ `node_modules` directory).
48
77
 
49
- If a prefix is given and `name` is not a path, `prefix-name` is also searched
50
- (preferring these over non-prefixed modules).
51
- If name starts with a scope (`@scope/name`), the prefix is applied after it:
52
- `@scope/prefix-name`.
78
+ If a `prefix` is given and `name` is not a path, `$prefix-$name` is also
79
+ searched (preferring these over non-prefixed modules).
80
+ If `name` starts with a scope (`@scope/name`), the prefix is applied after it:
81
+ `@scope/$prefix-name`.
53
82
 
54
83
  ##### `options`
55
84
 
85
+ Configuration (optional).
86
+
56
87
  ###### `options.prefix`
57
88
 
58
89
  Prefix to search for (`string`, optional).
59
90
 
60
91
  ###### `options.cwd`
61
92
 
62
- Place or places to search from (`string`, `Array.<string>`, default:
93
+ Place or places to search from (`string`, `Array<string>`, default:
63
94
  `process.cwd()`).
64
95
 
65
96
  ###### `options.global`
66
97
 
67
98
  Whether to look for `name` in [global places][global] (`boolean`, optional,
68
99
  defaults to whether global is detected).
69
- If this is nully, `load-plugin` will detect if it’s currently running in global
70
- mode: either because it’s in Electron, or because a globally installed package
71
- is running it.
100
+ If this is nullish, `load-plugin` will detect if it’s currently running in
101
+ global mode: either because it’s in Electron, or because a globally installed
102
+ package is running it.
72
103
 
73
104
  Note: Electron runs its own version of Node instead of your system Node.
74
105
  That means global packages cannot be found, unless you’ve [set-up][] a [`prefix`
75
106
  in your `.npmrc`][prefix] or are using [nvm][] to manage your system node.
76
107
 
77
- ###### Returns
108
+ ###### `options.key`
78
109
 
79
- The results of `require`ing the first path that exists.
110
+ Identifier to take from the exports (`string` or `false`, default: `'default'`).
111
+ For example when given `'whatever'`, the value of `export const whatever = 1`
112
+ will be returned, when given `'default'`, the value of `export default …` is
113
+ used, and when `false` the whole module object is returned.
80
114
 
81
- ###### Throws
115
+ ###### Returns
82
116
 
83
- If `require`ing an existing path fails, or if no existing path exists.
117
+ Promise yielding the results of importing the first path that exists
118
+ (`Promise<unknown>`).
119
+ The promise rejects if importing an existing path fails, or if no existing
120
+ path exists.
84
121
 
85
- ### `loadPlugin.resolve(name[, options])`
122
+ ### `resolvePlugin(name[, options])`
86
123
 
87
124
  Search for `name`.
88
- Accepts the same parameters as [`loadPlugin`][load-plugin] but returns an
89
- absolute path for `name` instead of requiring it, and `null` if it cannot be
90
- found.
125
+ Accepts the same parameters as [`loadPlugin`][load-plugin] (except `key`) but
126
+ returns a promise resolving to an absolute URL (`string`) for `name` instead of
127
+ importing it.
128
+ Throws if `name` cannot be found.
129
+
130
+ ## Types
131
+
132
+ This package is fully typed with [TypeScript][].
133
+ It exports the additional types `ResolveOptions` and `LoadOptions`.
134
+
135
+ ## Compatibility
136
+
137
+ This package is at least compatible with all maintained versions of Node.js.
138
+ As of now, that is Node.js 14.14+, 16.0+, and 18.0+.
139
+
140
+ ## Contribute
141
+
142
+ Yes please!
143
+ See [How to Contribute to Open Source][contribute].
91
144
 
92
145
  ## License
93
146
 
@@ -95,9 +148,9 @@ found.
95
148
 
96
149
  <!-- Definitions -->
97
150
 
98
- [build-badge]: https://img.shields.io/travis/wooorm/load-plugin.svg
151
+ [build-badge]: https://github.com/wooorm/load-plugin/actions/workflows/main.yml/badge.svg
99
152
 
100
- [build]: https://travis-ci.org/wooorm/load-plugin
153
+ [build]: https://github.com/wooorm/load-plugin/actions
101
154
 
102
155
  [coverage-badge]: https://img.shields.io/codecov/c/github/wooorm/load-plugin.svg
103
156
 
@@ -113,14 +166,22 @@ found.
113
166
 
114
167
  [author]: https://wooorm.com
115
168
 
116
- [global]: https://docs.npmjs.com/files/folders#node-modules
169
+ [esm]: https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c
117
170
 
118
- [load-plugin]: #loadpluginname-options
171
+ [typescript]: https://www.typescriptlang.org
119
172
 
120
- [browser]: browser.js
173
+ [contribute]: https://opensource.guide/how-to-contribute/
174
+
175
+ [global]: https://docs.npmjs.com/files/folders#node-modules
121
176
 
122
177
  [prefix]: https://docs.npmjs.com/misc/config#prefix
123
178
 
124
179
  [set-up]: https://github.com/sindresorhus/guides/blob/master/npm-global-without-sudo.md
125
180
 
126
181
  [nvm]: https://github.com/creationix/nvm
182
+
183
+ [algo]: https://nodejs.org/api/esm.html#esm_resolution_algorithm
184
+
185
+ [import-meta-resolve]: https://github.com/wooorm/import-meta-resolve
186
+
187
+ [load-plugin]: #loadpluginname-options
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
- }