@rollup/plugin-node-resolve 8.0.0 → 9.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.
@@ -0,0 +1,532 @@
1
+ import { dirname, resolve, extname, normalize, sep } from 'path';
2
+ import builtinList from 'builtin-modules';
3
+ import deepMerge from 'deepmerge';
4
+ import isModule from 'is-module';
5
+ import fs, { realpathSync } from 'fs';
6
+ import { promisify } from 'util';
7
+ import { createFilter } from '@rollup/pluginutils';
8
+ import resolveModule from 'resolve';
9
+
10
+ const exists = promisify(fs.exists);
11
+ const readFile = promisify(fs.readFile);
12
+ const realpath = promisify(fs.realpath);
13
+ const stat = promisify(fs.stat);
14
+
15
+ const onError = (error) => {
16
+ if (error.code === 'ENOENT') {
17
+ return false;
18
+ }
19
+ throw error;
20
+ };
21
+
22
+ const makeCache = (fn) => {
23
+ const cache = new Map();
24
+ const wrapped = async (param, done) => {
25
+ if (cache.has(param) === false) {
26
+ cache.set(
27
+ param,
28
+ fn(param).catch((err) => {
29
+ cache.delete(param);
30
+ throw err;
31
+ })
32
+ );
33
+ }
34
+
35
+ try {
36
+ const result = cache.get(param);
37
+ const value = await result;
38
+ return done(null, value);
39
+ } catch (error) {
40
+ return done(error);
41
+ }
42
+ };
43
+
44
+ wrapped.clear = () => cache.clear();
45
+
46
+ return wrapped;
47
+ };
48
+
49
+ const isDirCached = makeCache(async (file) => {
50
+ try {
51
+ const stats = await stat(file);
52
+ return stats.isDirectory();
53
+ } catch (error) {
54
+ return onError(error);
55
+ }
56
+ });
57
+
58
+ const isFileCached = makeCache(async (file) => {
59
+ try {
60
+ const stats = await stat(file);
61
+ return stats.isFile();
62
+ } catch (error) {
63
+ return onError(error);
64
+ }
65
+ });
66
+
67
+ const readCachedFile = makeCache(readFile);
68
+
69
+ const resolveId = promisify(resolveModule);
70
+
71
+ // returns the imported package name for bare module imports
72
+ function getPackageName(id) {
73
+ if (id.startsWith('.') || id.startsWith('/')) {
74
+ return null;
75
+ }
76
+
77
+ const split = id.split('/');
78
+
79
+ // @my-scope/my-package/foo.js -> @my-scope/my-package
80
+ // @my-scope/my-package -> @my-scope/my-package
81
+ if (split[0][0] === '@') {
82
+ return `${split[0]}/${split[1]}`;
83
+ }
84
+
85
+ // my-package/foo.js -> my-package
86
+ // my-package -> my-package
87
+ return split[0];
88
+ }
89
+
90
+ function getMainFields(options) {
91
+ let mainFields;
92
+ if (options.mainFields) {
93
+ ({ mainFields } = options);
94
+ } else {
95
+ mainFields = ['module', 'main'];
96
+ }
97
+ if (options.browser && mainFields.indexOf('browser') === -1) {
98
+ return ['browser'].concat(mainFields);
99
+ }
100
+ if (!mainFields.length) {
101
+ throw new Error('Please ensure at least one `mainFields` value is specified');
102
+ }
103
+ return mainFields;
104
+ }
105
+
106
+ function getPackageInfo(options) {
107
+ const { cache, extensions, pkg, mainFields, preserveSymlinks, useBrowserOverrides } = options;
108
+ let { pkgPath } = options;
109
+
110
+ if (cache.has(pkgPath)) {
111
+ return cache.get(pkgPath);
112
+ }
113
+
114
+ // browserify/resolve doesn't realpath paths returned in its packageFilter callback
115
+ if (!preserveSymlinks) {
116
+ pkgPath = realpathSync(pkgPath);
117
+ }
118
+
119
+ const pkgRoot = dirname(pkgPath);
120
+
121
+ const packageInfo = {
122
+ // copy as we are about to munge the `main` field of `pkg`.
123
+ packageJson: Object.assign({}, pkg),
124
+
125
+ // path to package.json file
126
+ packageJsonPath: pkgPath,
127
+
128
+ // directory containing the package.json
129
+ root: pkgRoot,
130
+
131
+ // which main field was used during resolution of this module (main, module, or browser)
132
+ resolvedMainField: 'main',
133
+
134
+ // whether the browser map was used to resolve the entry point to this module
135
+ browserMappedMain: false,
136
+
137
+ // the entry point of the module with respect to the selected main field and any
138
+ // relevant browser mappings.
139
+ resolvedEntryPoint: ''
140
+ };
141
+
142
+ let overriddenMain = false;
143
+ for (let i = 0; i < mainFields.length; i++) {
144
+ const field = mainFields[i];
145
+ if (typeof pkg[field] === 'string') {
146
+ pkg.main = pkg[field];
147
+ packageInfo.resolvedMainField = field;
148
+ overriddenMain = true;
149
+ break;
150
+ }
151
+ }
152
+
153
+ const internalPackageInfo = {
154
+ cachedPkg: pkg,
155
+ hasModuleSideEffects: () => null,
156
+ hasPackageEntry: overriddenMain !== false || mainFields.indexOf('main') !== -1,
157
+ packageBrowserField:
158
+ useBrowserOverrides &&
159
+ typeof pkg.browser === 'object' &&
160
+ Object.keys(pkg.browser).reduce((browser, key) => {
161
+ let resolved = pkg.browser[key];
162
+ if (resolved && resolved[0] === '.') {
163
+ resolved = resolve(pkgRoot, resolved);
164
+ }
165
+ /* eslint-disable no-param-reassign */
166
+ browser[key] = resolved;
167
+ if (key[0] === '.') {
168
+ const absoluteKey = resolve(pkgRoot, key);
169
+ browser[absoluteKey] = resolved;
170
+ if (!extname(key)) {
171
+ extensions.reduce((subBrowser, ext) => {
172
+ subBrowser[absoluteKey + ext] = subBrowser[key];
173
+ return subBrowser;
174
+ }, browser);
175
+ }
176
+ }
177
+ return browser;
178
+ }, {}),
179
+ packageInfo
180
+ };
181
+
182
+ const browserMap = internalPackageInfo.packageBrowserField;
183
+ if (
184
+ useBrowserOverrides &&
185
+ typeof pkg.browser === 'object' &&
186
+ // eslint-disable-next-line no-prototype-builtins
187
+ browserMap.hasOwnProperty(pkg.main)
188
+ ) {
189
+ packageInfo.resolvedEntryPoint = browserMap[pkg.main];
190
+ packageInfo.browserMappedMain = true;
191
+ } else {
192
+ // index.node is technically a valid default entrypoint as well...
193
+ packageInfo.resolvedEntryPoint = resolve(pkgRoot, pkg.main || 'index.js');
194
+ packageInfo.browserMappedMain = false;
195
+ }
196
+
197
+ const packageSideEffects = pkg.sideEffects;
198
+ if (typeof packageSideEffects === 'boolean') {
199
+ internalPackageInfo.hasModuleSideEffects = () => packageSideEffects;
200
+ } else if (Array.isArray(packageSideEffects)) {
201
+ internalPackageInfo.hasModuleSideEffects = createFilter(packageSideEffects, null, {
202
+ resolve: pkgRoot
203
+ });
204
+ }
205
+
206
+ cache.set(pkgPath, internalPackageInfo);
207
+ return internalPackageInfo;
208
+ }
209
+
210
+ function normalizeInput(input) {
211
+ if (Array.isArray(input)) {
212
+ return input;
213
+ } else if (typeof input === 'object') {
214
+ return Object.values(input);
215
+ }
216
+
217
+ // otherwise it's a string
218
+ return [input];
219
+ }
220
+
221
+ // Resolve module specifiers in order. Promise resolves to the first module that resolves
222
+ // successfully, or the error that resulted from the last attempted module resolution.
223
+ function resolveImportSpecifiers(importSpecifierList, resolveOptions) {
224
+ let promise = Promise.resolve();
225
+
226
+ for (let i = 0; i < importSpecifierList.length; i++) {
227
+ promise = promise.then((value) => {
228
+ // if we've already resolved to something, just return it.
229
+ if (value) {
230
+ return value;
231
+ }
232
+
233
+ return resolveId(importSpecifierList[i], resolveOptions).then((result) => {
234
+ if (!resolveOptions.preserveSymlinks) {
235
+ result = realpathSync(result);
236
+ }
237
+ return result;
238
+ });
239
+ });
240
+
241
+ if (i < importSpecifierList.length - 1) {
242
+ // swallow MODULE_NOT_FOUND errors from all but the last resolution
243
+ promise = promise.catch((error) => {
244
+ if (error.code !== 'MODULE_NOT_FOUND') {
245
+ throw error;
246
+ }
247
+ });
248
+ }
249
+ }
250
+
251
+ return promise;
252
+ }
253
+
254
+ /* eslint-disable no-param-reassign, no-shadow, no-undefined */
255
+
256
+ const builtins = new Set(builtinList);
257
+ const ES6_BROWSER_EMPTY = '\0node-resolve:empty.js';
258
+ const nullFn = () => null;
259
+ const deepFreeze = (object) => {
260
+ Object.freeze(object);
261
+
262
+ for (const value of Object.values(object)) {
263
+ if (typeof value === 'object' && !Object.isFrozen(value)) {
264
+ deepFreeze(value);
265
+ }
266
+ }
267
+
268
+ return object;
269
+ };
270
+ const defaults = {
271
+ customResolveOptions: {},
272
+ dedupe: [],
273
+ // It's important that .mjs is listed before .js so that Rollup will interpret npm modules
274
+ // which deploy both ESM .mjs and CommonJS .js files as ESM.
275
+ extensions: ['.mjs', '.js', '.json', '.node'],
276
+ resolveOnly: []
277
+ };
278
+ const DEFAULTS = deepFreeze(deepMerge({}, defaults));
279
+
280
+ function nodeResolve(opts = {}) {
281
+ const options = Object.assign({}, defaults, opts);
282
+ const { customResolveOptions, extensions, jail } = options;
283
+ const warnings = [];
284
+ const packageInfoCache = new Map();
285
+ const idToPackageInfo = new Map();
286
+ const mainFields = getMainFields(options);
287
+ const useBrowserOverrides = mainFields.indexOf('browser') !== -1;
288
+ const isPreferBuiltinsSet = options.preferBuiltins === true || options.preferBuiltins === false;
289
+ const preferBuiltins = isPreferBuiltinsSet ? options.preferBuiltins : true;
290
+ const rootDir = options.rootDir || process.cwd();
291
+ let { dedupe } = options;
292
+ let rollupOptions;
293
+
294
+ if (options.only) {
295
+ warnings.push('node-resolve: The `only` options is deprecated, please use `resolveOnly`');
296
+ options.resolveOnly = options.only;
297
+ }
298
+
299
+ if (typeof dedupe !== 'function') {
300
+ dedupe = (importee) =>
301
+ options.dedupe.includes(importee) || options.dedupe.includes(getPackageName(importee));
302
+ }
303
+
304
+ const resolveOnly = options.resolveOnly.map((pattern) => {
305
+ if (pattern instanceof RegExp) {
306
+ return pattern;
307
+ }
308
+ const normalized = pattern.replace(/[\\^$*+?.()|[\]{}]/g, '\\$&');
309
+ return new RegExp(`^${normalized}$`);
310
+ });
311
+
312
+ const browserMapCache = new Map();
313
+ let preserveSymlinks;
314
+
315
+ return {
316
+ name: 'node-resolve',
317
+
318
+ buildStart(options) {
319
+ rollupOptions = options;
320
+
321
+ for (const warning of warnings) {
322
+ this.warn(warning);
323
+ }
324
+
325
+ ({ preserveSymlinks } = options);
326
+ },
327
+
328
+ generateBundle() {
329
+ readCachedFile.clear();
330
+ isFileCached.clear();
331
+ isDirCached.clear();
332
+ },
333
+
334
+ async resolveId(importee, importer) {
335
+ if (importee === ES6_BROWSER_EMPTY) {
336
+ return importee;
337
+ }
338
+ // ignore IDs with null character, these belong to other plugins
339
+ if (/\0/.test(importee)) return null;
340
+
341
+ // strip hash and query params from import
342
+ const [withoutHash, hash] = importee.split('#');
343
+ const [importPath, params] = withoutHash.split('?');
344
+ const importSuffix = `${params ? `?${params}` : ''}${hash ? `#${hash}` : ''}`;
345
+ importee = importPath;
346
+
347
+ const basedir = !importer || dedupe(importee) ? rootDir : dirname(importer);
348
+
349
+ // https://github.com/defunctzombie/package-browser-field-spec
350
+ const browser = browserMapCache.get(importer);
351
+ if (useBrowserOverrides && browser) {
352
+ const resolvedImportee = resolve(basedir, importee);
353
+ if (browser[importee] === false || browser[resolvedImportee] === false) {
354
+ return ES6_BROWSER_EMPTY;
355
+ }
356
+ const browserImportee =
357
+ browser[importee] ||
358
+ browser[resolvedImportee] ||
359
+ browser[`${resolvedImportee}.js`] ||
360
+ browser[`${resolvedImportee}.json`];
361
+ if (browserImportee) {
362
+ importee = browserImportee;
363
+ }
364
+ }
365
+
366
+ const parts = importee.split(/[/\\]/);
367
+ let id = parts.shift();
368
+ let isRelativeImport = false;
369
+
370
+ if (id[0] === '@' && parts.length > 0) {
371
+ // scoped packages
372
+ id += `/${parts.shift()}`;
373
+ } else if (id[0] === '.') {
374
+ // an import relative to the parent dir of the importer
375
+ id = resolve(basedir, importee);
376
+ isRelativeImport = true;
377
+ }
378
+
379
+ if (
380
+ !isRelativeImport &&
381
+ resolveOnly.length &&
382
+ !resolveOnly.some((pattern) => pattern.test(id))
383
+ ) {
384
+ if (normalizeInput(rollupOptions.input).includes(importee)) {
385
+ return null;
386
+ }
387
+ return false;
388
+ }
389
+
390
+ let hasModuleSideEffects = nullFn;
391
+ let hasPackageEntry = true;
392
+ let packageBrowserField = false;
393
+ let packageInfo;
394
+
395
+ const filter = (pkg, pkgPath) => {
396
+ const info = getPackageInfo({
397
+ cache: packageInfoCache,
398
+ extensions,
399
+ pkg,
400
+ pkgPath,
401
+ mainFields,
402
+ preserveSymlinks,
403
+ useBrowserOverrides
404
+ });
405
+
406
+ ({ packageInfo, hasModuleSideEffects, hasPackageEntry, packageBrowserField } = info);
407
+
408
+ return info.cachedPkg;
409
+ };
410
+
411
+ let resolveOptions = {
412
+ basedir,
413
+ packageFilter: filter,
414
+ readFile: readCachedFile,
415
+ isFile: isFileCached,
416
+ isDirectory: isDirCached,
417
+ extensions
418
+ };
419
+
420
+ if (preserveSymlinks !== undefined) {
421
+ resolveOptions.preserveSymlinks = preserveSymlinks;
422
+ }
423
+
424
+ const importSpecifierList = [];
425
+
426
+ if (importer === undefined && !importee[0].match(/^\.?\.?\//)) {
427
+ // For module graph roots (i.e. when importer is undefined), we
428
+ // need to handle 'path fragments` like `foo/bar` that are commonly
429
+ // found in rollup config files. If importee doesn't look like a
430
+ // relative or absolute path, we make it relative and attempt to
431
+ // resolve it. If we don't find anything, we try resolving it as we
432
+ // got it.
433
+ importSpecifierList.push(`./${importee}`);
434
+ }
435
+
436
+ const importeeIsBuiltin = builtins.has(importee);
437
+
438
+ if (importeeIsBuiltin && (!preferBuiltins || !isPreferBuiltinsSet)) {
439
+ // The `resolve` library will not resolve packages with the same
440
+ // name as a node built-in module. If we're resolving something
441
+ // that's a builtin, and we don't prefer to find built-ins, we
442
+ // first try to look up a local module with that name. If we don't
443
+ // find anything, we resolve the builtin which just returns back
444
+ // the built-in's name.
445
+ importSpecifierList.push(`${importee}/`);
446
+ }
447
+
448
+ // TypeScript files may import '.js' to refer to either '.ts' or '.tsx'
449
+ if (importer && importee.endsWith('.js')) {
450
+ for (const ext of ['.ts', '.tsx']) {
451
+ if (importer.endsWith(ext) && extensions.includes(ext)) {
452
+ importSpecifierList.push(importee.replace(/.js$/, ext));
453
+ }
454
+ }
455
+ }
456
+
457
+ importSpecifierList.push(importee);
458
+ resolveOptions = Object.assign(resolveOptions, customResolveOptions);
459
+
460
+ try {
461
+ let resolved = await resolveImportSpecifiers(importSpecifierList, resolveOptions);
462
+
463
+ if (resolved && packageBrowserField) {
464
+ if (Object.prototype.hasOwnProperty.call(packageBrowserField, resolved)) {
465
+ if (!packageBrowserField[resolved]) {
466
+ browserMapCache.set(resolved, packageBrowserField);
467
+ return ES6_BROWSER_EMPTY;
468
+ }
469
+ resolved = packageBrowserField[resolved];
470
+ }
471
+ browserMapCache.set(resolved, packageBrowserField);
472
+ }
473
+
474
+ if (hasPackageEntry && !preserveSymlinks && resolved) {
475
+ const fileExists = await exists(resolved);
476
+ if (fileExists) {
477
+ resolved = await realpath(resolved);
478
+ }
479
+ }
480
+
481
+ idToPackageInfo.set(resolved, packageInfo);
482
+
483
+ if (hasPackageEntry) {
484
+ if (builtins.has(resolved) && preferBuiltins && isPreferBuiltinsSet) {
485
+ return null;
486
+ } else if (importeeIsBuiltin && preferBuiltins) {
487
+ if (!isPreferBuiltinsSet) {
488
+ this.warn(
489
+ `preferring built-in module '${importee}' over local alternative at '${resolved}', pass 'preferBuiltins: false' to disable this behavior or 'preferBuiltins: true' to disable this warning`
490
+ );
491
+ }
492
+ return null;
493
+ } else if (jail && resolved.indexOf(normalize(jail.trim(sep))) !== 0) {
494
+ return null;
495
+ }
496
+ }
497
+
498
+ if (resolved && options.modulesOnly) {
499
+ const code = await readFile(resolved, 'utf-8');
500
+ if (isModule(code)) {
501
+ return {
502
+ id: `${resolved}${importSuffix}`,
503
+ moduleSideEffects: hasModuleSideEffects(resolved)
504
+ };
505
+ }
506
+ return null;
507
+ }
508
+ const result = {
509
+ id: `${resolved}${importSuffix}`,
510
+ moduleSideEffects: hasModuleSideEffects(resolved)
511
+ };
512
+ return result;
513
+ } catch (error) {
514
+ return null;
515
+ }
516
+ },
517
+
518
+ load(importee) {
519
+ if (importee === ES6_BROWSER_EMPTY) {
520
+ return 'export default {};';
521
+ }
522
+ return null;
523
+ },
524
+
525
+ getPackageInfoForId(id) {
526
+ return idToPackageInfo.get(id);
527
+ }
528
+ };
529
+ }
530
+
531
+ export default nodeResolve;
532
+ export { DEFAULTS, nodeResolve };
@@ -0,0 +1 @@
1
+ {"type":"module"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rollup/plugin-node-resolve",
3
- "version": "8.0.0",
3
+ "version": "9.0.0",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -10,9 +10,10 @@
10
10
  "author": "Rich Harris <richard.a.harris@gmail.com>",
11
11
  "homepage": "https://github.com/rollup/plugins/tree/master/packages/node-resolve/#readme",
12
12
  "bugs": "https://github.com/rollup/plugins/issues",
13
- "main": "dist/index.js",
13
+ "main": "./dist/cjs/index.js",
14
+ "module": "./dist/es/index.js",
14
15
  "engines": {
15
- "node": ">= 8.0.0"
16
+ "node": ">= 10.0.0"
16
17
  },
17
18
  "scripts": {
18
19
  "build": "rollup -c",
@@ -21,7 +22,7 @@
21
22
  "ci:lint:commits": "commitlint --from=${CIRCLE_BRANCH} --to=${CIRCLE_SHA1}",
22
23
  "ci:test": "pnpm run test -- --verbose && pnpm run test:ts",
23
24
  "lint": "pnpm run lint:js && pnpm run lint:docs && pnpm run lint:package",
24
- "lint:docs": "prettier --single-quote --write README.md",
25
+ "lint:docs": "prettier --single-quote --arrow-parens avoid --trailing-comma none --write README.md",
25
26
  "lint:js": "eslint --fix --cache src test types --ext .js,.ts",
26
27
  "lint:package": "prettier --write package.json --plugin=prettier-plugin-package",
27
28
  "prebuild": "del-cli dist",
@@ -48,26 +49,29 @@
48
49
  "rollup": "^1.20.0||^2.0.0"
49
50
  },
50
51
  "dependencies": {
51
- "@rollup/pluginutils": "^3.0.8",
52
- "@types/resolve": "0.0.8",
52
+ "@rollup/pluginutils": "^3.1.0",
53
+ "@types/resolve": "1.17.1",
53
54
  "builtin-modules": "^3.1.0",
54
- "deep-freeze": "^0.0.1",
55
55
  "deepmerge": "^4.2.2",
56
56
  "is-module": "^1.0.0",
57
- "resolve": "^1.14.2"
57
+ "resolve": "^1.17.0"
58
58
  },
59
59
  "devDependencies": {
60
- "@babel/core": "^7.9.0",
61
- "@babel/preset-env": "^7.9.0",
62
- "@rollup/plugin-json": "^4.0.1",
60
+ "@babel/core": "^7.10.5",
61
+ "@babel/plugin-transform-typescript": "^7.10.5",
62
+ "@rollup/plugin-babel": "^5.1.0",
63
+ "@rollup/plugin-commonjs": "^14.0.0",
64
+ "@rollup/plugin-json": "^4.1.0",
63
65
  "es5-ext": "^0.10.53",
64
- "rollup": "^2.0.0",
65
- "rollup-plugin-babel": "^4.3.3",
66
- "rollup-plugin-commonjs": "^10.1.0",
66
+ "rollup": "^2.23.0",
67
67
  "source-map": "^0.7.3",
68
68
  "string-capitalize": "^1.0.1"
69
69
  },
70
+ "types": "types/index.d.ts",
70
71
  "ava": {
72
+ "babel": {
73
+ "compileEnhancements": false
74
+ },
71
75
  "files": [
72
76
  "!**/fixtures/**",
73
77
  "!**/helpers/**",
@@ -75,6 +79,9 @@
75
79
  "!**/types.ts"
76
80
  ]
77
81
  },
78
- "module": "dist/index.es.js",
79
- "types": "types/index.d.ts"
82
+ "exports": {
83
+ "require": "./dist/cjs/index.js",
84
+ "import": "./dist/es/index.js"
85
+ },
86
+ "type": "commonjs"
80
87
  }