@rollup/plugin-node-resolve 8.4.0 → 11.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.
package/dist/es/index.js CHANGED
@@ -1,310 +1,145 @@
1
- import { dirname, resolve, extname, normalize, sep } from 'path';
1
+ import path, { dirname, resolve, extname, normalize, sep } from 'path';
2
2
  import builtinList from 'builtin-modules';
3
- import deepFreeze from 'deep-freeze';
4
3
  import deepMerge from 'deepmerge';
5
4
  import isModule from 'is-module';
6
5
  import fs, { realpathSync } from 'fs';
7
6
  import { promisify } from 'util';
7
+ import resolve$1 from 'resolve';
8
8
  import { createFilter } from '@rollup/pluginutils';
9
- import resolveModule from 'resolve';
10
-
11
- function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
12
- try {
13
- var info = gen[key](arg);
14
- var value = info.value;
15
- } catch (error) {
16
- reject(error);
17
- return;
18
- }
19
-
20
- if (info.done) {
21
- resolve(value);
22
- } else {
23
- Promise.resolve(value).then(_next, _throw);
24
- }
25
- }
26
-
27
- function _asyncToGenerator(fn) {
28
- return function () {
29
- var self = this,
30
- args = arguments;
31
- return new Promise(function (resolve, reject) {
32
- var gen = fn.apply(self, args);
33
-
34
- function _next(value) {
35
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
36
- }
37
-
38
- function _throw(err) {
39
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
40
- }
41
-
42
- _next(undefined);
43
- });
44
- };
45
- }
46
-
47
- function _slicedToArray(arr, i) {
48
- return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
49
- }
50
-
51
- function _arrayWithHoles(arr) {
52
- if (Array.isArray(arr)) return arr;
53
- }
54
-
55
- function _iterableToArrayLimit(arr, i) {
56
- if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return;
57
- var _arr = [];
58
- var _n = true;
59
- var _d = false;
60
- var _e = undefined;
61
-
62
- try {
63
- for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
64
- _arr.push(_s.value);
65
-
66
- if (i && _arr.length === i) break;
67
- }
68
- } catch (err) {
69
- _d = true;
70
- _e = err;
71
- } finally {
72
- try {
73
- if (!_n && _i["return"] != null) _i["return"]();
74
- } finally {
75
- if (_d) throw _e;
76
- }
77
- }
78
-
79
- return _arr;
80
- }
81
-
82
- function _unsupportedIterableToArray(o, minLen) {
83
- if (!o) return;
84
- if (typeof o === "string") return _arrayLikeToArray(o, minLen);
85
- var n = Object.prototype.toString.call(o).slice(8, -1);
86
- if (n === "Object" && o.constructor) n = o.constructor.name;
87
- if (n === "Map" || n === "Set") return Array.from(n);
88
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
89
- }
90
-
91
- function _arrayLikeToArray(arr, len) {
92
- if (len == null || len > arr.length) len = arr.length;
93
-
94
- for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
95
-
96
- return arr2;
97
- }
98
-
99
- function _nonIterableRest() {
100
- throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
101
- }
102
-
103
- function _createForOfIteratorHelper(o) {
104
- if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) {
105
- if (Array.isArray(o) || (o = _unsupportedIterableToArray(o))) {
106
- var i = 0;
107
-
108
- var F = function () {};
109
-
110
- return {
111
- s: F,
112
- n: function () {
113
- if (i >= o.length) return {
114
- done: true
115
- };
116
- return {
117
- done: false,
118
- value: o[i++]
119
- };
120
- },
121
- e: function (e) {
122
- throw e;
123
- },
124
- f: F
125
- };
126
- }
127
-
128
- throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
129
- }
130
-
131
- var it,
132
- normalCompletion = true,
133
- didErr = false,
134
- err;
135
- return {
136
- s: function () {
137
- it = o[Symbol.iterator]();
138
- },
139
- n: function () {
140
- var step = it.next();
141
- normalCompletion = step.done;
142
- return step;
143
- },
144
- e: function (e) {
145
- didErr = true;
146
- err = e;
147
- },
148
- f: function () {
149
- try {
150
- if (!normalCompletion && it.return != null) it.return();
151
- } finally {
152
- if (didErr) throw err;
153
- }
154
- }
155
- };
156
- }
157
9
 
158
10
  const exists = promisify(fs.exists);
159
11
  const readFile = promisify(fs.readFile);
160
12
  const realpath = promisify(fs.realpath);
161
13
  const stat = promisify(fs.stat);
162
14
 
163
- const onError = error => {
15
+ const onError = (error) => {
164
16
  if (error.code === 'ENOENT') {
165
17
  return false;
166
18
  }
167
-
168
19
  throw error;
169
20
  };
170
21
 
171
- const makeCache = fn => {
22
+ const makeCache = (fn) => {
172
23
  const cache = new Map();
173
-
174
- const wrapped = /*#__PURE__*/function () {
175
- var _ref = _asyncToGenerator(function* (param, done) {
176
- if (cache.has(param) === false) {
177
- cache.set(param, fn(param).catch(err => {
24
+ const wrapped = async (param, done) => {
25
+ if (cache.has(param) === false) {
26
+ cache.set(
27
+ param,
28
+ fn(param).catch((err) => {
178
29
  cache.delete(param);
179
30
  throw err;
180
- }));
181
- }
182
-
183
- try {
184
- const result = cache.get(param);
185
- const value = yield result;
186
- return done(null, value);
187
- } catch (error) {
188
- return done(error);
189
- }
190
- });
31
+ })
32
+ );
33
+ }
191
34
 
192
- return function wrapped(_x, _x2) {
193
- return _ref.apply(this, arguments);
194
- };
195
- }();
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
+ };
196
43
 
197
44
  wrapped.clear = () => cache.clear();
198
45
 
199
46
  return wrapped;
200
47
  };
201
48
 
202
- const isDirCached = makeCache( /*#__PURE__*/function () {
203
- var _ref2 = _asyncToGenerator(function* (file) {
204
- try {
205
- const stats = yield stat(file);
206
- return stats.isDirectory();
207
- } catch (error) {
208
- return onError(error);
209
- }
210
- });
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
+ });
211
57
 
212
- return function (_x3) {
213
- return _ref2.apply(this, arguments);
214
- };
215
- }());
216
- const isFileCached = makeCache( /*#__PURE__*/function () {
217
- var _ref3 = _asyncToGenerator(function* (file) {
218
- try {
219
- const stats = yield stat(file);
220
- return stats.isFile();
221
- } catch (error) {
222
- return onError(error);
223
- }
224
- });
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
+ });
225
66
 
226
- return function (_x4) {
227
- return _ref3.apply(this, arguments);
228
- };
229
- }());
230
67
  const readCachedFile = makeCache(readFile);
231
68
 
232
- const resolveId = promisify(resolveModule); // returns the imported package name for bare module imports
233
-
69
+ // returns the imported package name for bare module imports
234
70
  function getPackageName(id) {
235
71
  if (id.startsWith('.') || id.startsWith('/')) {
236
72
  return null;
237
73
  }
238
74
 
239
- const split = id.split('/'); // @my-scope/my-package/foo.js -> @my-scope/my-package
240
- // @my-scope/my-package -> @my-scope/my-package
75
+ const split = id.split('/');
241
76
 
77
+ // @my-scope/my-package/foo.js -> @my-scope/my-package
78
+ // @my-scope/my-package -> @my-scope/my-package
242
79
  if (split[0][0] === '@') {
243
80
  return `${split[0]}/${split[1]}`;
244
- } // my-package/foo.js -> my-package
245
- // my-package -> my-package
246
-
81
+ }
247
82
 
83
+ // my-package/foo.js -> my-package
84
+ // my-package -> my-package
248
85
  return split[0];
249
86
  }
87
+
250
88
  function getMainFields(options) {
251
89
  let mainFields;
252
-
253
90
  if (options.mainFields) {
254
- mainFields = options.mainFields;
91
+ ({ mainFields } = options);
255
92
  } else {
256
93
  mainFields = ['module', 'main'];
257
94
  }
258
-
259
95
  if (options.browser && mainFields.indexOf('browser') === -1) {
260
96
  return ['browser'].concat(mainFields);
261
97
  }
262
-
263
98
  if (!mainFields.length) {
264
99
  throw new Error('Please ensure at least one `mainFields` value is specified');
265
100
  }
266
-
267
101
  return mainFields;
268
102
  }
103
+
269
104
  function getPackageInfo(options) {
270
- const cache = options.cache,
271
- extensions = options.extensions,
272
- pkg = options.pkg,
273
- mainFields = options.mainFields,
274
- preserveSymlinks = options.preserveSymlinks,
275
- useBrowserOverrides = options.useBrowserOverrides;
276
- let pkgPath = options.pkgPath;
105
+ const { cache, extensions, pkg, mainFields, preserveSymlinks, useBrowserOverrides } = options;
106
+ let { pkgPath } = options;
277
107
 
278
108
  if (cache.has(pkgPath)) {
279
109
  return cache.get(pkgPath);
280
- } // browserify/resolve doesn't realpath paths returned in its packageFilter callback
281
-
110
+ }
282
111
 
112
+ // browserify/resolve doesn't realpath paths returned in its packageFilter callback
283
113
  if (!preserveSymlinks) {
284
114
  pkgPath = realpathSync(pkgPath);
285
115
  }
286
116
 
287
117
  const pkgRoot = dirname(pkgPath);
118
+
288
119
  const packageInfo = {
289
120
  // copy as we are about to munge the `main` field of `pkg`.
290
- packageJson: Object.assign({}, pkg),
121
+ packageJson: { ...pkg },
122
+
291
123
  // path to package.json file
292
124
  packageJsonPath: pkgPath,
125
+
293
126
  // directory containing the package.json
294
127
  root: pkgRoot,
128
+
295
129
  // which main field was used during resolution of this module (main, module, or browser)
296
130
  resolvedMainField: 'main',
131
+
297
132
  // whether the browser map was used to resolve the entry point to this module
298
133
  browserMappedMain: false,
134
+
299
135
  // the entry point of the module with respect to the selected main field and any
300
136
  // relevant browser mappings.
301
137
  resolvedEntryPoint: ''
302
138
  };
303
- let overriddenMain = false;
304
139
 
140
+ let overriddenMain = false;
305
141
  for (let i = 0; i < mainFields.length; i++) {
306
142
  const field = mainFields[i];
307
-
308
143
  if (typeof pkg[field] === 'string') {
309
144
  pkg.main = pkg[field];
310
145
  packageInfo.resolvedMainField = field;
@@ -317,37 +152,38 @@ function getPackageInfo(options) {
317
152
  cachedPkg: pkg,
318
153
  hasModuleSideEffects: () => null,
319
154
  hasPackageEntry: overriddenMain !== false || mainFields.indexOf('main') !== -1,
320
- packageBrowserField: useBrowserOverrides && typeof pkg.browser === 'object' && Object.keys(pkg.browser).reduce((browser, key) => {
321
- let resolved = pkg.browser[key];
322
-
323
- if (resolved && resolved[0] === '.') {
324
- resolved = resolve(pkgRoot, resolved);
325
- }
326
- /* eslint-disable no-param-reassign */
327
-
328
-
329
- browser[key] = resolved;
330
-
331
- if (key[0] === '.') {
332
- const absoluteKey = resolve(pkgRoot, key);
333
- browser[absoluteKey] = resolved;
334
-
335
- if (!extname(key)) {
336
- extensions.reduce((subBrowser, ext) => {
337
- subBrowser[absoluteKey + ext] = subBrowser[key];
338
- return subBrowser;
339
- }, browser);
155
+ packageBrowserField:
156
+ useBrowserOverrides &&
157
+ typeof pkg.browser === 'object' &&
158
+ Object.keys(pkg.browser).reduce((browser, key) => {
159
+ let resolved = pkg.browser[key];
160
+ if (resolved && resolved[0] === '.') {
161
+ resolved = resolve(pkgRoot, resolved);
340
162
  }
341
- }
342
-
343
- return browser;
344
- }, {}),
163
+ /* eslint-disable no-param-reassign */
164
+ browser[key] = resolved;
165
+ if (key[0] === '.') {
166
+ const absoluteKey = resolve(pkgRoot, key);
167
+ browser[absoluteKey] = resolved;
168
+ if (!extname(key)) {
169
+ extensions.reduce((subBrowser, ext) => {
170
+ subBrowser[absoluteKey + ext] = subBrowser[key];
171
+ return subBrowser;
172
+ }, browser);
173
+ }
174
+ }
175
+ return browser;
176
+ }, {}),
345
177
  packageInfo
346
178
  };
347
- const browserMap = internalPackageInfo.packageBrowserField;
348
179
 
349
- if (useBrowserOverrides && typeof pkg.browser === 'object' && // eslint-disable-next-line no-prototype-builtins
350
- browserMap.hasOwnProperty(pkg.main)) {
180
+ const browserMap = internalPackageInfo.packageBrowserField;
181
+ if (
182
+ useBrowserOverrides &&
183
+ typeof pkg.browser === 'object' &&
184
+ // eslint-disable-next-line no-prototype-builtins
185
+ browserMap.hasOwnProperty(pkg.main)
186
+ ) {
351
187
  packageInfo.resolvedEntryPoint = browserMap[pkg.main];
352
188
  packageInfo.browserMappedMain = true;
353
189
  } else {
@@ -357,7 +193,6 @@ function getPackageInfo(options) {
357
193
  }
358
194
 
359
195
  const packageSideEffects = pkg.sideEffects;
360
-
361
196
  if (typeof packageSideEffects === 'boolean') {
362
197
  internalPackageInfo.hasModuleSideEffects = () => packageSideEffects;
363
198
  } else if (Array.isArray(packageSideEffects)) {
@@ -369,70 +204,403 @@ function getPackageInfo(options) {
369
204
  cache.set(pkgPath, internalPackageInfo);
370
205
  return internalPackageInfo;
371
206
  }
207
+
372
208
  function normalizeInput(input) {
373
209
  if (Array.isArray(input)) {
374
210
  return input;
375
211
  } else if (typeof input === 'object') {
376
212
  return Object.values(input);
377
- } // otherwise it's a string
378
-
213
+ }
379
214
 
215
+ // otherwise it's a string
380
216
  return [input];
381
- } // Resolve module specifiers in order. Promise resolves to the first module that resolves
382
- // successfully, or the error that resulted from the last attempted module resolution.
217
+ }
383
218
 
384
- function resolveImportSpecifiers(importSpecifierList, resolveOptions) {
385
- let promise = Promise.resolve();
219
+ const resolveImportPath = promisify(resolve$1);
220
+ const readFile$1 = promisify(fs.readFile);
386
221
 
387
- for (let i = 0; i < importSpecifierList.length; i++) {
388
- promise = promise.then(value => {
389
- // if we've already resolved to something, just return it.
390
- if (value) {
391
- return value;
222
+ const pathNotFoundError = (importPath, importer, subPath, pkgPath) =>
223
+ new Error(
224
+ `Could not resolve import "${importPath}" in "${importer}".` +
225
+ ` Package subpath "${subPath}" is not defined by "exports" in ${pkgPath}`
226
+ );
227
+
228
+ function findExportKeyMatch(exportMap, subPath) {
229
+ if (subPath in exportMap) {
230
+ return subPath;
231
+ }
232
+
233
+ const matchKeys = Object.keys(exportMap)
234
+ .filter((key) => key.endsWith('/') || key.endsWith('*'))
235
+ .sort((a, b) => b.length - a.length);
236
+
237
+ for (const key of matchKeys) {
238
+ if (key.endsWith('*')) {
239
+ // star match: "./foo/*": "./foo/*.js"
240
+ const keyWithoutStar = key.substring(0, key.length - 1);
241
+ if (subPath.startsWith(keyWithoutStar)) {
242
+ return key;
392
243
  }
244
+ }
393
245
 
394
- return resolveId(importSpecifierList[i], resolveOptions).then(result => {
395
- if (!resolveOptions.preserveSymlinks) {
396
- result = realpathSync(result);
397
- }
246
+ if (key.endsWith('/') && subPath.startsWith(key)) {
247
+ // directory match (deprecated by node): "./foo/": "./foo/.js"
248
+ return key;
249
+ }
250
+
251
+ if (key === subPath) {
252
+ // literal match
253
+ return key;
254
+ }
255
+ }
256
+ return null;
257
+ }
258
+
259
+ function mapSubPath({ importPath, importer, pkgJsonPath, subPath, key, value }) {
260
+ if (typeof value === 'string') {
261
+ if (typeof key === 'string' && key.endsWith('*')) {
262
+ // star match: "./foo/*": "./foo/*.js"
263
+ const keyWithoutStar = key.substring(0, key.length - 1);
264
+ const subPathAfterKey = subPath.substring(keyWithoutStar.length);
265
+ return value.replace(/\*/g, subPathAfterKey);
266
+ }
267
+
268
+ if (value.endsWith('/')) {
269
+ // directory match (deprecated by node): "./foo/": "./foo/.js"
270
+ return `${value}${subPath.substring(key.length)}`;
271
+ }
272
+
273
+ // mapping is a string, for example { "./foo": "./dist/foo.js" }
274
+ return value;
275
+ }
276
+
277
+ if (Array.isArray(value)) {
278
+ // mapping is an array with fallbacks, for example { "./foo": ["foo:bar", "./dist/foo.js"] }
279
+ return value.find((v) => v.startsWith('./'));
280
+ }
281
+
282
+ throw pathNotFoundError(importPath, importer, subPath, pkgJsonPath);
283
+ }
398
284
 
399
- return result;
285
+ function findEntrypoint({
286
+ importPath,
287
+ importer,
288
+ pkgJsonPath,
289
+ subPath,
290
+ exportMap,
291
+ conditions,
292
+ key
293
+ }) {
294
+ if (typeof exportMap !== 'object') {
295
+ return mapSubPath({ importPath, importer, pkgJsonPath, subPath, key, value: exportMap });
296
+ }
297
+
298
+ // iterate conditions recursively, find the first that matches all conditions
299
+ for (const [condition, subExportMap] of Object.entries(exportMap)) {
300
+ if (conditions.includes(condition)) {
301
+ const mappedSubPath = findEntrypoint({
302
+ importPath,
303
+ importer,
304
+ pkgJsonPath,
305
+ subPath,
306
+ exportMap: subExportMap,
307
+ conditions,
308
+ key
400
309
  });
310
+ if (mappedSubPath) {
311
+ return mappedSubPath;
312
+ }
313
+ }
314
+ }
315
+ throw pathNotFoundError(importer, subPath, pkgJsonPath);
316
+ }
317
+
318
+ function findEntrypointTopLevel({
319
+ importPath,
320
+ importer,
321
+ pkgJsonPath,
322
+ subPath,
323
+ exportMap,
324
+ conditions
325
+ }) {
326
+ if (typeof exportMap !== 'object') {
327
+ // the export map shorthand, for example { exports: "./index.js" }
328
+ if (subPath !== '.') {
329
+ // shorthand only supports a main entrypoint
330
+ throw pathNotFoundError(importPath, importer, subPath, pkgJsonPath);
331
+ }
332
+ return mapSubPath({ importPath, importer, pkgJsonPath, subPath, key: null, value: exportMap });
333
+ }
334
+
335
+ // export map is an object, the top level can be either conditions or sub path mappings
336
+ const keys = Object.keys(exportMap);
337
+ const isConditions = keys.every((k) => !k.startsWith('.'));
338
+ const isMappings = keys.every((k) => k.startsWith('.'));
339
+
340
+ if (!isConditions && !isMappings) {
341
+ throw new Error(
342
+ `Invalid package config ${pkgJsonPath}, "exports" cannot contain some keys starting with '.'` +
343
+ ' and some not. The exports object must either be an object of package subpath keys or an object of main entry' +
344
+ ' condition name keys only.'
345
+ );
346
+ }
347
+
348
+ let key = null;
349
+ let exportMapForSubPath;
350
+
351
+ if (isConditions) {
352
+ // top level is conditions, for example { "import": ..., "require": ..., "module": ... }
353
+ if (subPath !== '.') {
354
+ // package with top level conditions means it only supports a main entrypoint
355
+ throw pathNotFoundError(importPath, importer, subPath, pkgJsonPath);
356
+ }
357
+ exportMapForSubPath = exportMap;
358
+ } else {
359
+ // top level is sub path mappings, for example { ".": ..., "./foo": ..., "./bar": ... }
360
+ key = findExportKeyMatch(exportMap, subPath);
361
+ if (!key) {
362
+ throw pathNotFoundError(importPath, importer, subPath, pkgJsonPath);
363
+ }
364
+ exportMapForSubPath = exportMap[key];
365
+ }
366
+
367
+ return findEntrypoint({
368
+ importPath,
369
+ importer,
370
+ pkgJsonPath,
371
+ subPath,
372
+ exportMap: exportMapForSubPath,
373
+ conditions,
374
+ key
375
+ });
376
+ }
377
+
378
+ async function resolveId({
379
+ importer,
380
+ importPath,
381
+ exportConditions,
382
+ warn,
383
+ packageInfoCache,
384
+ extensions,
385
+ mainFields,
386
+ preserveSymlinks,
387
+ useBrowserOverrides,
388
+ baseDir,
389
+ moduleDirectories
390
+ }) {
391
+ let hasModuleSideEffects = () => null;
392
+ let hasPackageEntry = true;
393
+ let packageBrowserField = false;
394
+ let packageInfo;
395
+
396
+ const filter = (pkg, pkgPath) => {
397
+ const info = getPackageInfo({
398
+ cache: packageInfoCache,
399
+ extensions,
400
+ pkg,
401
+ pkgPath,
402
+ mainFields,
403
+ preserveSymlinks,
404
+ useBrowserOverrides
401
405
  });
402
406
 
403
- if (i < importSpecifierList.length - 1) {
404
- // swallow MODULE_NOT_FOUND errors from all but the last resolution
405
- promise = promise.catch(error => {
406
- if (error.code !== 'MODULE_NOT_FOUND') {
407
- throw error;
408
- }
409
- });
407
+ ({ packageInfo, hasModuleSideEffects, hasPackageEntry, packageBrowserField } = info);
408
+
409
+ return info.cachedPkg;
410
+ };
411
+
412
+ const resolveOptions = {
413
+ basedir: baseDir,
414
+ readFile: readCachedFile,
415
+ isFile: isFileCached,
416
+ isDirectory: isDirCached,
417
+ extensions,
418
+ includeCoreModules: false,
419
+ moduleDirectory: moduleDirectories,
420
+ preserveSymlinks,
421
+ packageFilter: filter
422
+ };
423
+
424
+ let location;
425
+
426
+ const pkgName = getPackageName(importPath);
427
+ if (pkgName) {
428
+ let pkgJsonPath;
429
+ let pkgJson;
430
+ try {
431
+ pkgJsonPath = await resolveImportPath(`${pkgName}/package.json`, resolveOptions);
432
+ pkgJson = JSON.parse(await readFile$1(pkgJsonPath, 'utf-8'));
433
+ } catch (_) {
434
+ // if there is no package.json we defer to regular resolve behavior
435
+ }
436
+
437
+ if (pkgJsonPath && pkgJson && pkgJson.exports) {
438
+ try {
439
+ const packageSubPath =
440
+ pkgName === importPath ? '.' : `.${importPath.substring(pkgName.length)}`;
441
+ const mappedSubPath = findEntrypointTopLevel({
442
+ importer,
443
+ importPath,
444
+ pkgJsonPath,
445
+ subPath: packageSubPath,
446
+ exportMap: pkgJson.exports,
447
+ conditions: exportConditions
448
+ });
449
+ const pkgDir = path.dirname(pkgJsonPath);
450
+ location = path.join(pkgDir, mappedSubPath);
451
+ } catch (error) {
452
+ warn(error);
453
+ return null;
454
+ }
455
+ }
456
+ }
457
+
458
+ if (!location) {
459
+ try {
460
+ location = await resolveImportPath(importPath, resolveOptions);
461
+ } catch (error) {
462
+ if (error.code !== 'MODULE_NOT_FOUND') {
463
+ throw error;
464
+ }
465
+ return null;
410
466
  }
411
467
  }
412
468
 
413
- return promise;
469
+ if (!preserveSymlinks) {
470
+ if (await exists(location)) {
471
+ location = await realpath(location);
472
+ }
473
+ }
474
+
475
+ return {
476
+ location,
477
+ hasModuleSideEffects,
478
+ hasPackageEntry,
479
+ packageBrowserField,
480
+ packageInfo
481
+ };
414
482
  }
415
483
 
484
+ // Resolve module specifiers in order. Promise resolves to the first module that resolves
485
+ // successfully, or the error that resulted from the last attempted module resolution.
486
+ async function resolveImportSpecifiers({
487
+ importer,
488
+ importSpecifierList,
489
+ exportConditions,
490
+ warn,
491
+ packageInfoCache,
492
+ extensions,
493
+ mainFields,
494
+ preserveSymlinks,
495
+ useBrowserOverrides,
496
+ baseDir,
497
+ moduleDirectories
498
+ }) {
499
+ for (let i = 0; i < importSpecifierList.length; i++) {
500
+ // eslint-disable-next-line no-await-in-loop
501
+ const resolved = await resolveId({
502
+ importer,
503
+ importPath: importSpecifierList[i],
504
+ exportConditions,
505
+ warn,
506
+ packageInfoCache,
507
+ extensions,
508
+ mainFields,
509
+ preserveSymlinks,
510
+ useBrowserOverrides,
511
+ baseDir,
512
+ moduleDirectories
513
+ });
514
+ if (resolved) {
515
+ return resolved;
516
+ }
517
+ }
518
+ return null;
519
+ }
520
+
521
+ function handleDeprecatedOptions(opts) {
522
+ const warnings = [];
523
+
524
+ if (opts.customResolveOptions) {
525
+ const { customResolveOptions } = opts;
526
+ if (customResolveOptions.moduleDirectory) {
527
+ // eslint-disable-next-line no-param-reassign
528
+ opts.moduleDirectories = Array.isArray(customResolveOptions.moduleDirectory)
529
+ ? customResolveOptions.moduleDirectory
530
+ : [customResolveOptions.moduleDirectory];
531
+
532
+ warnings.push(
533
+ 'node-resolve: The `customResolveOptions.moduleDirectory` option has been deprecated. Use `moduleDirectories`, which must be an array.'
534
+ );
535
+ }
536
+
537
+ if (customResolveOptions.preserveSymlinks) {
538
+ throw new Error(
539
+ 'node-resolve: `customResolveOptions.preserveSymlinks` is no longer an option. We now always use the rollup `preserveSymlinks` option.'
540
+ );
541
+ }
542
+
543
+ [
544
+ 'basedir',
545
+ 'package',
546
+ 'extensions',
547
+ 'includeCoreModules',
548
+ 'readFile',
549
+ 'isFile',
550
+ 'isDirectory',
551
+ 'realpath',
552
+ 'packageFilter',
553
+ 'pathFilter',
554
+ 'paths',
555
+ 'packageIterator'
556
+ ].forEach((resolveOption) => {
557
+ if (customResolveOptions[resolveOption]) {
558
+ throw new Error(
559
+ `node-resolve: \`customResolveOptions.${resolveOption}\` is no longer an option. If you need this, please open an issue.`
560
+ );
561
+ }
562
+ });
563
+ }
564
+
565
+ return { warnings };
566
+ }
567
+
568
+ /* eslint-disable no-param-reassign, no-shadow, no-undefined */
569
+
416
570
  const builtins = new Set(builtinList);
417
571
  const ES6_BROWSER_EMPTY = '\0node-resolve:empty.js';
572
+ const deepFreeze = (object) => {
573
+ Object.freeze(object);
418
574
 
419
- const nullFn = () => null;
575
+ for (const value of Object.values(object)) {
576
+ if (typeof value === 'object' && !Object.isFrozen(value)) {
577
+ deepFreeze(value);
578
+ }
579
+ }
420
580
 
581
+ return object;
582
+ };
583
+
584
+ const baseConditions = ['default', 'module'];
585
+ const baseConditionsEsm = [...baseConditions, 'import'];
586
+ const baseConditionsCjs = [...baseConditions, 'require'];
421
587
  const defaults = {
422
- customResolveOptions: {},
423
588
  dedupe: [],
424
589
  // It's important that .mjs is listed before .js so that Rollup will interpret npm modules
425
590
  // which deploy both ESM .mjs and CommonJS .js files as ESM.
426
591
  extensions: ['.mjs', '.js', '.json', '.node'],
427
- resolveOnly: []
592
+ resolveOnly: [],
593
+ moduleDirectories: ['node_modules']
428
594
  };
429
595
  const DEFAULTS = deepFreeze(deepMerge({}, defaults));
596
+
430
597
  function nodeResolve(opts = {}) {
431
- const options = Object.assign({}, defaults, opts);
432
- const customResolveOptions = options.customResolveOptions,
433
- extensions = options.extensions,
434
- jail = options.jail;
435
- const warnings = [];
598
+ const { warnings } = handleDeprecatedOptions(opts);
599
+
600
+ const options = { ...defaults, ...opts };
601
+ const { extensions, jail, moduleDirectories } = options;
602
+ const conditionsEsm = [...baseConditionsEsm, ...(options.exportConditions || [])];
603
+ const conditionsCjs = [...baseConditionsCjs, ...(options.exportConditions || [])];
436
604
  const packageInfoCache = new Map();
437
605
  const idToPackageInfo = new Map();
438
606
  const mainFields = getMainFields(options);
@@ -440,49 +608,36 @@ function nodeResolve(opts = {}) {
440
608
  const isPreferBuiltinsSet = options.preferBuiltins === true || options.preferBuiltins === false;
441
609
  const preferBuiltins = isPreferBuiltinsSet ? options.preferBuiltins : true;
442
610
  const rootDir = options.rootDir || process.cwd();
443
- let dedupe = options.dedupe;
611
+ let { dedupe } = options;
444
612
  let rollupOptions;
445
613
 
446
- if (options.only) {
447
- warnings.push('node-resolve: The `only` options is deprecated, please use `resolveOnly`');
448
- options.resolveOnly = options.only;
449
- }
450
-
451
614
  if (typeof dedupe !== 'function') {
452
- dedupe = importee => options.dedupe.includes(importee) || options.dedupe.includes(getPackageName(importee));
615
+ dedupe = (importee) =>
616
+ options.dedupe.includes(importee) || options.dedupe.includes(getPackageName(importee));
453
617
  }
454
618
 
455
- const resolveOnly = options.resolveOnly.map(pattern => {
619
+ const resolveOnly = options.resolveOnly.map((pattern) => {
456
620
  if (pattern instanceof RegExp) {
457
621
  return pattern;
458
622
  }
459
-
460
623
  const normalized = pattern.replace(/[\\^$*+?.()|[\]{}]/g, '\\$&');
461
624
  return new RegExp(`^${normalized}$`);
462
625
  });
626
+
463
627
  const browserMapCache = new Map();
464
628
  let preserveSymlinks;
629
+
465
630
  return {
466
631
  name: 'node-resolve',
467
632
 
468
633
  buildStart(options) {
469
634
  rollupOptions = options;
470
635
 
471
- var _iterator = _createForOfIteratorHelper(warnings),
472
- _step;
473
-
474
- try {
475
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
476
- const warning = _step.value;
477
- this.warn(warning);
478
- }
479
- } catch (err) {
480
- _iterator.e(err);
481
- } finally {
482
- _iterator.f();
636
+ for (const warning of warnings) {
637
+ this.warn(warning);
483
638
  }
484
639
 
485
- preserveSymlinks = options.preserveSymlinks;
640
+ ({ preserveSymlinks } = options);
486
641
  },
487
642
 
488
643
  generateBundle() {
@@ -491,217 +646,194 @@ function nodeResolve(opts = {}) {
491
646
  isDirCached.clear();
492
647
  },
493
648
 
494
- resolveId(importee, importer) {
495
- var _this = this;
496
-
497
- return _asyncToGenerator(function* () {
498
- if (importee === ES6_BROWSER_EMPTY) {
499
- return importee;
500
- } // ignore IDs with null character, these belong to other plugins
501
-
502
-
503
- if (/\0/.test(importee)) return null; // strip hash and query params from import
504
-
505
- const _importee$split = importee.split('#'),
506
- _importee$split2 = _slicedToArray(_importee$split, 2),
507
- withoutHash = _importee$split2[0],
508
- hash = _importee$split2[1];
509
-
510
- const _withoutHash$split = withoutHash.split('?'),
511
- _withoutHash$split2 = _slicedToArray(_withoutHash$split, 2),
512
- importPath = _withoutHash$split2[0],
513
- params = _withoutHash$split2[1];
514
-
515
- const importSuffix = `${params ? `?${params}` : ''}${hash ? `#${hash}` : ''}`;
516
- importee = importPath;
517
- const basedir = !importer || dedupe(importee) ? rootDir : dirname(importer); // https://github.com/defunctzombie/package-browser-field-spec
518
-
519
- const browser = browserMapCache.get(importer);
520
-
521
- if (useBrowserOverrides && browser) {
522
- const resolvedImportee = resolve(basedir, importee);
523
-
524
- if (browser[importee] === false || browser[resolvedImportee] === false) {
525
- return ES6_BROWSER_EMPTY;
526
- }
527
-
528
- const browserImportee = browser[importee] || browser[resolvedImportee] || browser[`${resolvedImportee}.js`] || browser[`${resolvedImportee}.json`];
649
+ async resolveId(importee, importer, opts) {
650
+ if (importee === ES6_BROWSER_EMPTY) {
651
+ return importee;
652
+ }
653
+ // ignore IDs with null character, these belong to other plugins
654
+ if (/\0/.test(importee)) return null;
529
655
 
530
- if (browserImportee) {
531
- importee = browserImportee;
532
- }
533
- }
656
+ if (/\0/.test(importer)) {
657
+ importer = undefined;
658
+ }
534
659
 
535
- const parts = importee.split(/[/\\]/);
536
- let id = parts.shift();
537
- let isRelativeImport = false;
538
-
539
- if (id[0] === '@' && parts.length > 0) {
540
- // scoped packages
541
- id += `/${parts.shift()}`;
542
- } else if (id[0] === '.') {
543
- // an import relative to the parent dir of the importer
544
- id = resolve(basedir, importee);
545
- isRelativeImport = true;
546
- }
660
+ // strip query params from import
661
+ const [importPath, params] = importee.split('?');
662
+ const importSuffix = `${params ? `?${params}` : ''}`;
663
+ importee = importPath;
547
664
 
548
- if (!isRelativeImport && resolveOnly.length && !resolveOnly.some(pattern => pattern.test(id))) {
549
- if (normalizeInput(rollupOptions.input).includes(importee)) {
550
- return null;
551
- }
665
+ const baseDir = !importer || dedupe(importee) ? rootDir : dirname(importer);
552
666
 
553
- return false;
667
+ // https://github.com/defunctzombie/package-browser-field-spec
668
+ const browser = browserMapCache.get(importer);
669
+ if (useBrowserOverrides && browser) {
670
+ const resolvedImportee = resolve(baseDir, importee);
671
+ if (browser[importee] === false || browser[resolvedImportee] === false) {
672
+ return ES6_BROWSER_EMPTY;
554
673
  }
555
-
556
- let hasModuleSideEffects = nullFn;
557
- let hasPackageEntry = true;
558
- let packageBrowserField = false;
559
- let packageInfo;
560
-
561
- const filter = (pkg, pkgPath) => {
562
- const info = getPackageInfo({
563
- cache: packageInfoCache,
564
- extensions,
565
- pkg,
566
- pkgPath,
567
- mainFields,
568
- preserveSymlinks,
569
- useBrowserOverrides
570
- });
571
- packageInfo = info.packageInfo;
572
- hasModuleSideEffects = info.hasModuleSideEffects;
573
- hasPackageEntry = info.hasPackageEntry;
574
- packageBrowserField = info.packageBrowserField;
575
- return info.cachedPkg;
576
- };
577
-
578
- let resolveOptions = {
579
- basedir,
580
- packageFilter: filter,
581
- readFile: readCachedFile,
582
- isFile: isFileCached,
583
- isDirectory: isDirCached,
584
- extensions
585
- };
586
-
587
- if (preserveSymlinks !== undefined) {
588
- resolveOptions.preserveSymlinks = preserveSymlinks;
674
+ const browserImportee =
675
+ browser[importee] ||
676
+ browser[resolvedImportee] ||
677
+ browser[`${resolvedImportee}.js`] ||
678
+ browser[`${resolvedImportee}.json`];
679
+ if (browserImportee) {
680
+ importee = browserImportee;
589
681
  }
682
+ }
590
683
 
591
- const importSpecifierList = [];
684
+ const parts = importee.split(/[/\\]/);
685
+ let id = parts.shift();
686
+ let isRelativeImport = false;
687
+
688
+ if (id[0] === '@' && parts.length > 0) {
689
+ // scoped packages
690
+ id += `/${parts.shift()}`;
691
+ } else if (id[0] === '.') {
692
+ // an import relative to the parent dir of the importer
693
+ id = resolve(baseDir, importee);
694
+ isRelativeImport = true;
695
+ }
592
696
 
593
- if (importer === undefined && !importee[0].match(/^\.?\.?\//)) {
594
- // For module graph roots (i.e. when importer is undefined), we
595
- // need to handle 'path fragments` like `foo/bar` that are commonly
596
- // found in rollup config files. If importee doesn't look like a
597
- // relative or absolute path, we make it relative and attempt to
598
- // resolve it. If we don't find anything, we try resolving it as we
599
- // got it.
600
- importSpecifierList.push(`./${importee}`);
697
+ if (
698
+ !isRelativeImport &&
699
+ resolveOnly.length &&
700
+ !resolveOnly.some((pattern) => pattern.test(id))
701
+ ) {
702
+ if (normalizeInput(rollupOptions.input).includes(importee)) {
703
+ return null;
601
704
  }
705
+ return false;
706
+ }
602
707
 
603
- const importeeIsBuiltin = builtins.has(importee);
708
+ const importSpecifierList = [];
604
709
 
605
- if (importeeIsBuiltin && (!preferBuiltins || !isPreferBuiltinsSet)) {
606
- // The `resolve` library will not resolve packages with the same
607
- // name as a node built-in module. If we're resolving something
608
- // that's a builtin, and we don't prefer to find built-ins, we
609
- // first try to look up a local module with that name. If we don't
610
- // find anything, we resolve the builtin which just returns back
611
- // the built-in's name.
612
- importSpecifierList.push(`${importee}/`);
613
- } // TypeScript files may import '.js' to refer to either '.ts' or '.tsx'
710
+ if (importer === undefined && !importee[0].match(/^\.?\.?\//)) {
711
+ // For module graph roots (i.e. when importer is undefined), we
712
+ // need to handle 'path fragments` like `foo/bar` that are commonly
713
+ // found in rollup config files. If importee doesn't look like a
714
+ // relative or absolute path, we make it relative and attempt to
715
+ // resolve it. If we don't find anything, we try resolving it as we
716
+ // got it.
717
+ importSpecifierList.push(`./${importee}`);
718
+ }
614
719
 
720
+ const importeeIsBuiltin = builtins.has(importee);
615
721
 
616
- if (importer && importee.endsWith('.js')) {
617
- for (var _i = 0, _arr = ['.ts', '.tsx']; _i < _arr.length; _i++) {
618
- const ext = _arr[_i];
722
+ if (importeeIsBuiltin) {
723
+ // The `resolve` library will not resolve packages with the same
724
+ // name as a node built-in module. If we're resolving something
725
+ // that's a builtin, and we don't prefer to find built-ins, we
726
+ // first try to look up a local module with that name. If we don't
727
+ // find anything, we resolve the builtin which just returns back
728
+ // the built-in's name.
729
+ importSpecifierList.push(`${importee}/`);
730
+ }
619
731
 
620
- if (importer.endsWith(ext) && extensions.includes(ext)) {
621
- importSpecifierList.push(importee.replace(/.js$/, ext));
622
- }
732
+ // TypeScript files may import '.js' to refer to either '.ts' or '.tsx'
733
+ if (importer && importee.endsWith('.js')) {
734
+ for (const ext of ['.ts', '.tsx']) {
735
+ if (importer.endsWith(ext) && extensions.includes(ext)) {
736
+ importSpecifierList.push(importee.replace(/.js$/, ext));
623
737
  }
624
738
  }
739
+ }
625
740
 
626
- importSpecifierList.push(importee);
627
- resolveOptions = Object.assign(resolveOptions, customResolveOptions);
628
-
629
- try {
630
- let resolved = yield resolveImportSpecifiers(importSpecifierList, resolveOptions);
631
-
632
- if (resolved && packageBrowserField) {
633
- if (Object.prototype.hasOwnProperty.call(packageBrowserField, resolved)) {
634
- if (!packageBrowserField[resolved]) {
635
- browserMapCache.set(resolved, packageBrowserField);
636
- return ES6_BROWSER_EMPTY;
637
- }
638
-
639
- resolved = packageBrowserField[resolved];
640
- }
641
-
642
- browserMapCache.set(resolved, packageBrowserField);
643
- }
644
-
645
- if (hasPackageEntry && !preserveSymlinks && resolved) {
646
- const fileExists = yield exists(resolved);
741
+ importSpecifierList.push(importee);
742
+
743
+ const warn = (...args) => this.warn(...args);
744
+ const isRequire =
745
+ opts && opts.custom && opts.custom['node-resolve'] && opts.custom['node-resolve'].isRequire;
746
+ const exportConditions = isRequire ? conditionsCjs : conditionsEsm;
747
+
748
+ const resolvedWithoutBuiltins = await resolveImportSpecifiers({
749
+ importer,
750
+ importSpecifierList,
751
+ exportConditions,
752
+ warn,
753
+ packageInfoCache,
754
+ extensions,
755
+ mainFields,
756
+ preserveSymlinks,
757
+ useBrowserOverrides,
758
+ baseDir,
759
+ moduleDirectories
760
+ });
647
761
 
648
- if (fileExists) {
649
- resolved = yield realpath(resolved);
762
+ const resolved =
763
+ importeeIsBuiltin && preferBuiltins
764
+ ? {
765
+ packageInfo: undefined,
766
+ hasModuleSideEffects: () => null,
767
+ hasPackageEntry: true,
768
+ packageBrowserField: false
650
769
  }
651
- }
652
-
653
- idToPackageInfo.set(resolved, packageInfo);
654
-
655
- if (hasPackageEntry) {
656
- if (builtins.has(resolved) && preferBuiltins && isPreferBuiltinsSet) {
657
- return null;
658
- } else if (importeeIsBuiltin && preferBuiltins) {
659
- if (!isPreferBuiltinsSet) {
660
- _this.warn(`preferring built-in module '${importee}' over local alternative at '${resolved}', pass 'preferBuiltins: false' to disable this behavior or 'preferBuiltins: true' to disable this warning`);
661
- }
770
+ : resolvedWithoutBuiltins;
771
+ if (!resolved) {
772
+ return null;
773
+ }
662
774
 
663
- return null;
664
- } else if (jail && resolved.indexOf(normalize(jail.trim(sep))) !== 0) {
665
- return null;
666
- }
775
+ const { packageInfo, hasModuleSideEffects, hasPackageEntry, packageBrowserField } = resolved;
776
+ let { location } = resolved;
777
+ if (packageBrowserField) {
778
+ if (Object.prototype.hasOwnProperty.call(packageBrowserField, location)) {
779
+ if (!packageBrowserField[location]) {
780
+ browserMapCache.set(location, packageBrowserField);
781
+ return ES6_BROWSER_EMPTY;
667
782
  }
783
+ location = packageBrowserField[location];
784
+ }
785
+ browserMapCache.set(location, packageBrowserField);
786
+ }
668
787
 
669
- if (resolved && options.modulesOnly) {
670
- const code = yield readFile(resolved, 'utf-8');
788
+ if (hasPackageEntry && !preserveSymlinks) {
789
+ const fileExists = await exists(location);
790
+ if (fileExists) {
791
+ location = await realpath(location);
792
+ }
793
+ }
671
794
 
672
- if (isModule(code)) {
673
- return {
674
- id: `${resolved}${importSuffix}`,
675
- moduleSideEffects: hasModuleSideEffects(resolved)
676
- };
677
- }
795
+ idToPackageInfo.set(location, packageInfo);
678
796
 
679
- return null;
797
+ if (hasPackageEntry) {
798
+ if (importeeIsBuiltin && preferBuiltins) {
799
+ if (!isPreferBuiltinsSet && resolvedWithoutBuiltins && resolved !== importee) {
800
+ this.warn(
801
+ `preferring built-in module '${importee}' over local alternative at '${resolvedWithoutBuiltins.location}', pass 'preferBuiltins: false' to disable this behavior or 'preferBuiltins: true' to disable this warning`
802
+ );
680
803
  }
804
+ return false;
805
+ } else if (jail && location.indexOf(normalize(jail.trim(sep))) !== 0) {
806
+ return null;
807
+ }
808
+ }
681
809
 
682
- const result = {
683
- id: `${resolved}${importSuffix}`,
684
- moduleSideEffects: hasModuleSideEffects(resolved)
810
+ if (options.modulesOnly && (await exists(location))) {
811
+ const code = await readFile(location, 'utf-8');
812
+ if (isModule(code)) {
813
+ return {
814
+ id: `${location}${importSuffix}`,
815
+ moduleSideEffects: hasModuleSideEffects(location)
685
816
  };
686
- return result;
687
- } catch (error) {
688
- return null;
689
817
  }
690
- })();
818
+ return null;
819
+ }
820
+ const result = {
821
+ id: `${location}${importSuffix}`,
822
+ moduleSideEffects: hasModuleSideEffects(location)
823
+ };
824
+ return result;
691
825
  },
692
826
 
693
827
  load(importee) {
694
828
  if (importee === ES6_BROWSER_EMPTY) {
695
829
  return 'export default {};';
696
830
  }
697
-
698
831
  return null;
699
832
  },
700
833
 
701
834
  getPackageInfoForId(id) {
702
835
  return idToPackageInfo.get(id);
703
836
  }
704
-
705
837
  };
706
838
  }
707
839