@rollup/plugin-node-resolve 9.0.0 → 11.1.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.
package/dist/es/index.js CHANGED
@@ -1,11 +1,12 @@
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
3
  import deepMerge from 'deepmerge';
4
4
  import isModule from 'is-module';
5
5
  import fs, { realpathSync } from 'fs';
6
6
  import { promisify } from 'util';
7
+ import { pathToFileURL, fileURLToPath } from 'url';
8
+ import resolve$1 from 'resolve';
7
9
  import { createFilter } from '@rollup/pluginutils';
8
- import resolveModule from 'resolve';
9
10
 
10
11
  const exists = promisify(fs.exists);
11
12
  const readFile = promisify(fs.readFile);
@@ -66,8 +67,6 @@ const isFileCached = makeCache(async (file) => {
66
67
 
67
68
  const readCachedFile = makeCache(readFile);
68
69
 
69
- const resolveId = promisify(resolveModule);
70
-
71
70
  // returns the imported package name for bare module imports
72
71
  function getPackageName(id) {
73
72
  if (id.startsWith('.') || id.startsWith('/')) {
@@ -120,7 +119,7 @@ function getPackageInfo(options) {
120
119
 
121
120
  const packageInfo = {
122
121
  // copy as we are about to munge the `main` field of `pkg`.
123
- packageJson: Object.assign({}, pkg),
122
+ packageJson: { ...pkg },
124
123
 
125
124
  // path to package.json file
126
125
  packageJsonPath: pkgPath,
@@ -218,44 +217,553 @@ function normalizeInput(input) {
218
217
  return [input];
219
218
  }
220
219
 
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();
220
+ /* eslint-disable no-await-in-loop */
225
221
 
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;
222
+ const fileExists = promisify(fs.exists);
223
+
224
+ function isModuleDir(current, moduleDirs) {
225
+ return moduleDirs.some((dir) => current.endsWith(dir));
226
+ }
227
+
228
+ async function findPackageJson(base, moduleDirs) {
229
+ const { root } = path.parse(base);
230
+ let current = base;
231
+
232
+ while (current !== root && !isModuleDir(current, moduleDirs)) {
233
+ const pkgJsonPath = path.join(current, 'package.json');
234
+ if (await fileExists(pkgJsonPath)) {
235
+ const pkgJsonString = fs.readFileSync(pkgJsonPath, 'utf-8');
236
+ return { pkgJson: JSON.parse(pkgJsonString), pkgPath: current, pkgJsonPath };
237
+ }
238
+ current = path.resolve(current, '..');
239
+ }
240
+ return null;
241
+ }
242
+
243
+ function isUrl(str) {
244
+ try {
245
+ return !!new URL(str);
246
+ } catch (_) {
247
+ return false;
248
+ }
249
+ }
250
+
251
+ function isConditions(exports) {
252
+ return typeof exports === 'object' && Object.keys(exports).every((k) => !k.startsWith('.'));
253
+ }
254
+
255
+ function isMappings(exports) {
256
+ return typeof exports === 'object' && !isConditions(exports);
257
+ }
258
+
259
+ function isMixedExports(exports) {
260
+ const keys = Object.keys(exports);
261
+ return keys.some((k) => k.startsWith('.')) && keys.some((k) => !k.startsWith('.'));
262
+ }
263
+
264
+ function createBaseErrorMsg(importSpecifier, importer) {
265
+ return `Could not resolve import "${importSpecifier}" in ${importer}`;
266
+ }
267
+
268
+ function createErrorMsg(context, reason, internal) {
269
+ const { importSpecifier, importer, pkgJsonPath } = context;
270
+ const base = createBaseErrorMsg(importSpecifier, importer);
271
+ const field = internal ? 'imports' : 'exports';
272
+ return `${base} using ${field} defined in ${pkgJsonPath}.${reason ? ` ${reason}` : ''}`;
273
+ }
274
+
275
+ class ResolveError extends Error {}
276
+
277
+ class InvalidConfigurationError extends ResolveError {
278
+ constructor(context, reason) {
279
+ super(createErrorMsg(context, `Invalid "exports" field. ${reason}`));
280
+ }
281
+ }
282
+
283
+ class InvalidModuleSpecifierError extends ResolveError {
284
+ constructor(context, internal) {
285
+ super(createErrorMsg(context, internal));
286
+ }
287
+ }
288
+
289
+ class InvalidPackageTargetError extends ResolveError {
290
+ constructor(context, reason) {
291
+ super(createErrorMsg(context, reason));
292
+ }
293
+ }
294
+
295
+ /* eslint-disable no-await-in-loop, no-undefined */
296
+
297
+ function includesInvalidSegments(pathSegments, moduleDirs) {
298
+ return pathSegments
299
+ .split('/')
300
+ .slice(1)
301
+ .some((t) => ['.', '..', ...moduleDirs].includes(t));
302
+ }
303
+
304
+ async function resolvePackageTarget(context, { target, subpath, pattern, internal }) {
305
+ if (typeof target === 'string') {
306
+ if (!pattern && subpath.length > 0 && !target.endsWith('/')) {
307
+ throw new InvalidModuleSpecifierError(context);
308
+ }
309
+
310
+ if (!target.startsWith('./')) {
311
+ if (internal && !['/', '../'].some((p) => target.startsWith(p)) && !isUrl(target)) {
312
+ // this is a bare package import, remap it and resolve it using regular node resolve
313
+ if (pattern) {
314
+ const result = await context.resolveId(
315
+ target.replace(/\*/g, subpath),
316
+ context.pkgURL.href
317
+ );
318
+ return result ? pathToFileURL(result.location) : null;
319
+ }
320
+
321
+ const result = await context.resolveId(`${target}${subpath}`, context.pkgURL.href);
322
+ return result ? pathToFileURL(result.location) : null;
323
+ }
324
+ throw new InvalidPackageTargetError(context, `Invalid mapping: "${target}".`);
325
+ }
326
+
327
+ if (includesInvalidSegments(target, context.moduleDirs)) {
328
+ throw new InvalidPackageTargetError(context, `Invalid mapping: "${target}".`);
329
+ }
330
+
331
+ const resolvedTarget = new URL(target, context.pkgURL);
332
+ if (!resolvedTarget.href.startsWith(context.pkgURL.href)) {
333
+ throw new InvalidPackageTargetError(
334
+ context,
335
+ `Resolved to ${resolvedTarget.href} which is outside package ${context.pkgURL.href}`
336
+ );
337
+ }
338
+
339
+ if (includesInvalidSegments(subpath, context.moduleDirs)) {
340
+ throw new InvalidModuleSpecifierError(context);
341
+ }
342
+
343
+ if (pattern) {
344
+ return resolvedTarget.href.replace(/\*/g, subpath);
345
+ }
346
+ return new URL(subpath, resolvedTarget).href;
347
+ }
348
+
349
+ if (Array.isArray(target)) {
350
+ let lastError;
351
+ for (const item of target) {
352
+ try {
353
+ const resolved = await resolvePackageTarget(context, {
354
+ target: item,
355
+ subpath,
356
+ pattern,
357
+ internal
358
+ });
359
+
360
+ // return if defined or null, but not undefined
361
+ if (resolved !== undefined) {
362
+ return resolved;
363
+ }
364
+ } catch (error) {
365
+ if (!(error instanceof InvalidPackageTargetError)) {
366
+ throw error;
367
+ } else {
368
+ lastError = error;
369
+ }
231
370
  }
371
+ }
232
372
 
233
- return resolveId(importSpecifierList[i], resolveOptions).then((result) => {
234
- if (!resolveOptions.preserveSymlinks) {
235
- result = realpathSync(result);
373
+ if (lastError) {
374
+ throw lastError;
375
+ }
376
+ return null;
377
+ }
378
+
379
+ if (target && typeof target === 'object') {
380
+ for (const [key, value] of Object.entries(target)) {
381
+ if (key === 'default' || context.conditions.includes(key)) {
382
+ const resolved = await resolvePackageTarget(context, {
383
+ target: value,
384
+ subpath,
385
+ pattern,
386
+ internal
387
+ });
388
+
389
+ // return if defined or null, but not undefined
390
+ if (resolved !== undefined) {
391
+ return resolved;
236
392
  }
237
- return result;
393
+ }
394
+ }
395
+ return undefined;
396
+ }
397
+
398
+ if (target === null) {
399
+ return null;
400
+ }
401
+
402
+ throw new InvalidPackageTargetError(context, `Invalid exports field.`);
403
+ }
404
+
405
+ /* eslint-disable no-await-in-loop */
406
+
407
+ async function resolvePackageImportsExports(context, { matchKey, matchObj, internal }) {
408
+ if (!matchKey.endsWith('*') && matchKey in matchObj) {
409
+ const target = matchObj[matchKey];
410
+ const resolved = await resolvePackageTarget(context, { target, subpath: '', internal });
411
+ return resolved;
412
+ }
413
+
414
+ const expansionKeys = Object.keys(matchObj)
415
+ .filter((k) => k.endsWith('/') || k.endsWith('*'))
416
+ .sort((a, b) => b.length - a.length);
417
+
418
+ for (const expansionKey of expansionKeys) {
419
+ const prefix = expansionKey.substring(0, expansionKey.length - 1);
420
+
421
+ if (expansionKey.endsWith('*') && matchKey.startsWith(prefix)) {
422
+ const target = matchObj[expansionKey];
423
+ const subpath = matchKey.substring(expansionKey.length - 1);
424
+ const resolved = await resolvePackageTarget(context, {
425
+ target,
426
+ subpath,
427
+ pattern: true,
428
+ internal
238
429
  });
430
+ return resolved;
431
+ }
432
+
433
+ if (matchKey.startsWith(expansionKey)) {
434
+ const target = matchObj[expansionKey];
435
+ const subpath = matchKey.substring(expansionKey.length);
436
+
437
+ const resolved = await resolvePackageTarget(context, { target, subpath, internal });
438
+ return resolved;
439
+ }
440
+ }
441
+
442
+ throw new InvalidModuleSpecifierError(context, internal);
443
+ }
444
+
445
+ async function resolvePackageExports(context, subpath, exports) {
446
+ if (isMixedExports(exports)) {
447
+ throw new InvalidConfigurationError(
448
+ context,
449
+ 'All keys must either start with ./, or without one.'
450
+ );
451
+ }
452
+
453
+ if (subpath === '.') {
454
+ let mainExport;
455
+ // If exports is a String or Array, or an Object containing no keys starting with ".", then
456
+ if (typeof exports === 'string' || Array.isArray(exports) || isConditions(exports)) {
457
+ mainExport = exports;
458
+ } else if (isMappings(exports)) {
459
+ mainExport = exports['.'];
460
+ }
461
+
462
+ if (mainExport) {
463
+ const resolved = await resolvePackageTarget(context, { target: mainExport, subpath: '' });
464
+ if (resolved) {
465
+ return resolved;
466
+ }
467
+ }
468
+ } else if (isMappings(exports)) {
469
+ const resolvedMatch = await resolvePackageImportsExports(context, {
470
+ matchKey: subpath,
471
+ matchObj: exports
239
472
  });
240
473
 
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') {
474
+ if (resolvedMatch) {
475
+ return resolvedMatch;
476
+ }
477
+ }
478
+
479
+ throw new InvalidModuleSpecifierError(context);
480
+ }
481
+
482
+ async function resolvePackageImports({
483
+ importSpecifier,
484
+ importer,
485
+ moduleDirs,
486
+ conditions,
487
+ resolveId
488
+ }) {
489
+ const result = await findPackageJson(importer, moduleDirs);
490
+ if (!result) {
491
+ throw new Error(createBaseErrorMsg('. Could not find a parent package.json.'));
492
+ }
493
+
494
+ const { pkgPath, pkgJsonPath, pkgJson } = result;
495
+ const pkgURL = pathToFileURL(`${pkgPath}/`);
496
+ const context = {
497
+ importer,
498
+ importSpecifier,
499
+ moduleDirs,
500
+ pkgURL,
501
+ pkgJsonPath,
502
+ conditions,
503
+ resolveId
504
+ };
505
+
506
+ const { imports } = pkgJson;
507
+ if (!imports) {
508
+ throw new InvalidModuleSpecifierError(context, true);
509
+ }
510
+
511
+ if (importSpecifier === '#' || importSpecifier.startsWith('#/')) {
512
+ throw new InvalidModuleSpecifierError(context, 'Invalid import specifier.');
513
+ }
514
+
515
+ return resolvePackageImportsExports(context, {
516
+ matchKey: importSpecifier,
517
+ matchObj: imports,
518
+ internal: true
519
+ });
520
+ }
521
+
522
+ const resolveImportPath = promisify(resolve$1);
523
+ const readFile$1 = promisify(fs.readFile);
524
+
525
+ async function getPackageJson(importer, pkgName, resolveOptions, moduleDirectories) {
526
+ if (importer) {
527
+ const selfPackageJsonResult = await findPackageJson(importer, moduleDirectories);
528
+ if (selfPackageJsonResult && selfPackageJsonResult.pkgJson.name === pkgName) {
529
+ // the referenced package name is the current package
530
+ return selfPackageJsonResult;
531
+ }
532
+ }
533
+
534
+ try {
535
+ const pkgJsonPath = await resolveImportPath(`${pkgName}/package.json`, resolveOptions);
536
+ const pkgJson = JSON.parse(await readFile$1(pkgJsonPath, 'utf-8'));
537
+ return { pkgJsonPath, pkgJson };
538
+ } catch (_) {
539
+ return null;
540
+ }
541
+ }
542
+
543
+ async function resolveId({
544
+ importer,
545
+ importSpecifier,
546
+ exportConditions,
547
+ warn,
548
+ packageInfoCache,
549
+ extensions,
550
+ mainFields,
551
+ preserveSymlinks,
552
+ useBrowserOverrides,
553
+ baseDir,
554
+ moduleDirectories
555
+ }) {
556
+ let hasModuleSideEffects = () => null;
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
+
572
+ ({ packageInfo, hasModuleSideEffects, hasPackageEntry, packageBrowserField } = info);
573
+
574
+ return info.cachedPkg;
575
+ };
576
+
577
+ const resolveOptions = {
578
+ basedir: baseDir,
579
+ readFile: readCachedFile,
580
+ isFile: isFileCached,
581
+ isDirectory: isDirCached,
582
+ extensions,
583
+ includeCoreModules: false,
584
+ moduleDirectory: moduleDirectories,
585
+ preserveSymlinks,
586
+ packageFilter: filter
587
+ };
588
+
589
+ let location;
590
+
591
+ const pkgName = getPackageName(importSpecifier);
592
+ if (importSpecifier.startsWith('#')) {
593
+ // this is a package internal import, resolve using package imports field
594
+ const resolveResult = await resolvePackageImports({
595
+ importSpecifier,
596
+ importer,
597
+ moduleDirs: moduleDirectories,
598
+ conditions: exportConditions,
599
+ resolveId(id, parent) {
600
+ return resolveId({
601
+ importSpecifier: id,
602
+ importer: parent,
603
+ exportConditions,
604
+ warn,
605
+ packageInfoCache,
606
+ extensions,
607
+ mainFields,
608
+ preserveSymlinks,
609
+ useBrowserOverrides,
610
+ baseDir,
611
+ moduleDirectories
612
+ });
613
+ }
614
+ });
615
+ location = fileURLToPath(resolveResult);
616
+ } else if (pkgName) {
617
+ // it's a bare import, find the package.json and resolve using package exports if available
618
+ const result = await getPackageJson(importer, pkgName, resolveOptions, moduleDirectories);
619
+
620
+ if (result && result.pkgJson.exports) {
621
+ const { pkgJson, pkgJsonPath } = result;
622
+ try {
623
+ const subpath =
624
+ pkgName === importSpecifier ? '.' : `.${importSpecifier.substring(pkgName.length)}`;
625
+ const pkgDr = pkgJsonPath.replace('package.json', '');
626
+ const pkgURL = pathToFileURL(pkgDr);
627
+
628
+ const context = {
629
+ importer,
630
+ importSpecifier,
631
+ moduleDirs: moduleDirectories,
632
+ pkgURL,
633
+ pkgJsonPath,
634
+ conditions: exportConditions
635
+ };
636
+ const resolvedPackageExport = await resolvePackageExports(
637
+ context,
638
+ subpath,
639
+ pkgJson.exports
640
+ );
641
+ location = fileURLToPath(resolvedPackageExport);
642
+ } catch (error) {
643
+ if (!(error instanceof ResolveError)) {
245
644
  throw error;
246
645
  }
247
- });
646
+ warn(error);
647
+ return null;
648
+ }
649
+ }
650
+ }
651
+
652
+ if (!location) {
653
+ // package has no imports or exports, use classic node resolve
654
+ try {
655
+ location = await resolveImportPath(importSpecifier, resolveOptions);
656
+ } catch (error) {
657
+ if (error.code !== 'MODULE_NOT_FOUND') {
658
+ throw error;
659
+ }
660
+ return null;
248
661
  }
249
662
  }
250
663
 
251
- return promise;
664
+ if (!preserveSymlinks) {
665
+ if (await exists(location)) {
666
+ location = await realpath(location);
667
+ }
668
+ }
669
+
670
+ return {
671
+ location,
672
+ hasModuleSideEffects,
673
+ hasPackageEntry,
674
+ packageBrowserField,
675
+ packageInfo
676
+ };
677
+ }
678
+
679
+ // Resolve module specifiers in order. Promise resolves to the first module that resolves
680
+ // successfully, or the error that resulted from the last attempted module resolution.
681
+ async function resolveImportSpecifiers({
682
+ importer,
683
+ importSpecifierList,
684
+ exportConditions,
685
+ warn,
686
+ packageInfoCache,
687
+ extensions,
688
+ mainFields,
689
+ preserveSymlinks,
690
+ useBrowserOverrides,
691
+ baseDir,
692
+ moduleDirectories
693
+ }) {
694
+ for (let i = 0; i < importSpecifierList.length; i++) {
695
+ // eslint-disable-next-line no-await-in-loop
696
+ const resolved = await resolveId({
697
+ importer,
698
+ importSpecifier: importSpecifierList[i],
699
+ exportConditions,
700
+ warn,
701
+ packageInfoCache,
702
+ extensions,
703
+ mainFields,
704
+ preserveSymlinks,
705
+ useBrowserOverrides,
706
+ baseDir,
707
+ moduleDirectories
708
+ });
709
+ if (resolved) {
710
+ return resolved;
711
+ }
712
+ }
713
+ return null;
714
+ }
715
+
716
+ function handleDeprecatedOptions(opts) {
717
+ const warnings = [];
718
+
719
+ if (opts.customResolveOptions) {
720
+ const { customResolveOptions } = opts;
721
+ if (customResolveOptions.moduleDirectory) {
722
+ // eslint-disable-next-line no-param-reassign
723
+ opts.moduleDirectories = Array.isArray(customResolveOptions.moduleDirectory)
724
+ ? customResolveOptions.moduleDirectory
725
+ : [customResolveOptions.moduleDirectory];
726
+
727
+ warnings.push(
728
+ 'node-resolve: The `customResolveOptions.moduleDirectory` option has been deprecated. Use `moduleDirectories`, which must be an array.'
729
+ );
730
+ }
731
+
732
+ if (customResolveOptions.preserveSymlinks) {
733
+ throw new Error(
734
+ 'node-resolve: `customResolveOptions.preserveSymlinks` is no longer an option. We now always use the rollup `preserveSymlinks` option.'
735
+ );
736
+ }
737
+
738
+ [
739
+ 'basedir',
740
+ 'package',
741
+ 'extensions',
742
+ 'includeCoreModules',
743
+ 'readFile',
744
+ 'isFile',
745
+ 'isDirectory',
746
+ 'realpath',
747
+ 'packageFilter',
748
+ 'pathFilter',
749
+ 'paths',
750
+ 'packageIterator'
751
+ ].forEach((resolveOption) => {
752
+ if (customResolveOptions[resolveOption]) {
753
+ throw new Error(
754
+ `node-resolve: \`customResolveOptions.${resolveOption}\` is no longer an option. If you need this, please open an issue.`
755
+ );
756
+ }
757
+ });
758
+ }
759
+
760
+ return { warnings };
252
761
  }
253
762
 
254
763
  /* eslint-disable no-param-reassign, no-shadow, no-undefined */
255
764
 
256
765
  const builtins = new Set(builtinList);
257
766
  const ES6_BROWSER_EMPTY = '\0node-resolve:empty.js';
258
- const nullFn = () => null;
259
767
  const deepFreeze = (object) => {
260
768
  Object.freeze(object);
261
769
 
@@ -267,20 +775,27 @@ const deepFreeze = (object) => {
267
775
 
268
776
  return object;
269
777
  };
778
+
779
+ const baseConditions = ['default', 'module'];
780
+ const baseConditionsEsm = [...baseConditions, 'import'];
781
+ const baseConditionsCjs = [...baseConditions, 'require'];
270
782
  const defaults = {
271
- customResolveOptions: {},
272
783
  dedupe: [],
273
784
  // It's important that .mjs is listed before .js so that Rollup will interpret npm modules
274
785
  // which deploy both ESM .mjs and CommonJS .js files as ESM.
275
786
  extensions: ['.mjs', '.js', '.json', '.node'],
276
- resolveOnly: []
787
+ resolveOnly: [],
788
+ moduleDirectories: ['node_modules']
277
789
  };
278
790
  const DEFAULTS = deepFreeze(deepMerge({}, defaults));
279
791
 
280
792
  function nodeResolve(opts = {}) {
281
- const options = Object.assign({}, defaults, opts);
282
- const { customResolveOptions, extensions, jail } = options;
283
- const warnings = [];
793
+ const { warnings } = handleDeprecatedOptions(opts);
794
+
795
+ const options = { ...defaults, ...opts };
796
+ const { extensions, jail, moduleDirectories } = options;
797
+ const conditionsEsm = [...baseConditionsEsm, ...(options.exportConditions || [])];
798
+ const conditionsCjs = [...baseConditionsCjs, ...(options.exportConditions || [])];
284
799
  const packageInfoCache = new Map();
285
800
  const idToPackageInfo = new Map();
286
801
  const mainFields = getMainFields(options);
@@ -291,11 +806,6 @@ function nodeResolve(opts = {}) {
291
806
  let { dedupe } = options;
292
807
  let rollupOptions;
293
808
 
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
809
  if (typeof dedupe !== 'function') {
300
810
  dedupe = (importee) =>
301
811
  options.dedupe.includes(importee) || options.dedupe.includes(getPackageName(importee));
@@ -331,25 +841,28 @@ function nodeResolve(opts = {}) {
331
841
  isDirCached.clear();
332
842
  },
333
843
 
334
- async resolveId(importee, importer) {
844
+ async resolveId(importee, importer, opts) {
335
845
  if (importee === ES6_BROWSER_EMPTY) {
336
846
  return importee;
337
847
  }
338
848
  // ignore IDs with null character, these belong to other plugins
339
849
  if (/\0/.test(importee)) return null;
340
850
 
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}` : ''}`;
851
+ if (/\0/.test(importer)) {
852
+ importer = undefined;
853
+ }
854
+
855
+ // strip query params from import
856
+ const [importPath, params] = importee.split('?');
857
+ const importSuffix = `${params ? `?${params}` : ''}`;
345
858
  importee = importPath;
346
859
 
347
- const basedir = !importer || dedupe(importee) ? rootDir : dirname(importer);
860
+ const baseDir = !importer || dedupe(importee) ? rootDir : dirname(importer);
348
861
 
349
862
  // https://github.com/defunctzombie/package-browser-field-spec
350
863
  const browser = browserMapCache.get(importer);
351
864
  if (useBrowserOverrides && browser) {
352
- const resolvedImportee = resolve(basedir, importee);
865
+ const resolvedImportee = resolve(baseDir, importee);
353
866
  if (browser[importee] === false || browser[resolvedImportee] === false) {
354
867
  return ES6_BROWSER_EMPTY;
355
868
  }
@@ -372,7 +885,7 @@ function nodeResolve(opts = {}) {
372
885
  id += `/${parts.shift()}`;
373
886
  } else if (id[0] === '.') {
374
887
  // an import relative to the parent dir of the importer
375
- id = resolve(basedir, importee);
888
+ id = resolve(baseDir, importee);
376
889
  isRelativeImport = true;
377
890
  }
378
891
 
@@ -387,40 +900,6 @@ function nodeResolve(opts = {}) {
387
900
  return false;
388
901
  }
389
902
 
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
903
  const importSpecifierList = [];
425
904
 
426
905
  if (importer === undefined && !importee[0].match(/^\.?\.?\//)) {
@@ -435,7 +914,7 @@ function nodeResolve(opts = {}) {
435
914
 
436
915
  const importeeIsBuiltin = builtins.has(importee);
437
916
 
438
- if (importeeIsBuiltin && (!preferBuiltins || !isPreferBuiltinsSet)) {
917
+ if (importeeIsBuiltin) {
439
918
  // The `resolve` library will not resolve packages with the same
440
919
  // name as a node built-in module. If we're resolving something
441
920
  // that's a builtin, and we don't prefer to find built-ins, we
@@ -455,64 +934,89 @@ function nodeResolve(opts = {}) {
455
934
  }
456
935
 
457
936
  importSpecifierList.push(importee);
458
- resolveOptions = Object.assign(resolveOptions, customResolveOptions);
459
937
 
460
- try {
461
- let resolved = await resolveImportSpecifiers(importSpecifierList, resolveOptions);
938
+ const warn = (...args) => this.warn(...args);
939
+ const isRequire =
940
+ opts && opts.custom && opts.custom['node-resolve'] && opts.custom['node-resolve'].isRequire;
941
+ const exportConditions = isRequire ? conditionsCjs : conditionsEsm;
942
+
943
+ const resolvedWithoutBuiltins = await resolveImportSpecifiers({
944
+ importer,
945
+ importSpecifierList,
946
+ exportConditions,
947
+ warn,
948
+ packageInfoCache,
949
+ extensions,
950
+ mainFields,
951
+ preserveSymlinks,
952
+ useBrowserOverrides,
953
+ baseDir,
954
+ moduleDirectories
955
+ });
462
956
 
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;
957
+ const resolved =
958
+ importeeIsBuiltin && preferBuiltins
959
+ ? {
960
+ packageInfo: undefined,
961
+ hasModuleSideEffects: () => null,
962
+ hasPackageEntry: true,
963
+ packageBrowserField: false
468
964
  }
469
- resolved = packageBrowserField[resolved];
965
+ : resolvedWithoutBuiltins;
966
+ if (!resolved) {
967
+ return null;
968
+ }
969
+
970
+ const { packageInfo, hasModuleSideEffects, hasPackageEntry, packageBrowserField } = resolved;
971
+ let { location } = resolved;
972
+ if (packageBrowserField) {
973
+ if (Object.prototype.hasOwnProperty.call(packageBrowserField, location)) {
974
+ if (!packageBrowserField[location]) {
975
+ browserMapCache.set(location, packageBrowserField);
976
+ return ES6_BROWSER_EMPTY;
470
977
  }
471
- browserMapCache.set(resolved, packageBrowserField);
978
+ location = packageBrowserField[location];
472
979
  }
980
+ browserMapCache.set(location, packageBrowserField);
981
+ }
473
982
 
474
- if (hasPackageEntry && !preserveSymlinks && resolved) {
475
- const fileExists = await exists(resolved);
476
- if (fileExists) {
477
- resolved = await realpath(resolved);
478
- }
983
+ if (hasPackageEntry && !preserveSymlinks) {
984
+ const fileExists = await exists(location);
985
+ if (fileExists) {
986
+ location = await realpath(location);
479
987
  }
988
+ }
480
989
 
481
- idToPackageInfo.set(resolved, packageInfo);
990
+ idToPackageInfo.set(location, packageInfo);
482
991
 
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;
992
+ if (hasPackageEntry) {
993
+ if (importeeIsBuiltin && preferBuiltins) {
994
+ if (!isPreferBuiltinsSet && resolvedWithoutBuiltins && resolved !== importee) {
995
+ this.warn(
996
+ `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`
997
+ );
495
998
  }
999
+ return false;
1000
+ } else if (jail && location.indexOf(normalize(jail.trim(sep))) !== 0) {
1001
+ return null;
496
1002
  }
1003
+ }
497
1004
 
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;
1005
+ if (options.modulesOnly && (await exists(location))) {
1006
+ const code = await readFile(location, 'utf-8');
1007
+ if (isModule(code)) {
1008
+ return {
1009
+ id: `${location}${importSuffix}`,
1010
+ moduleSideEffects: hasModuleSideEffects(location)
1011
+ };
507
1012
  }
508
- const result = {
509
- id: `${resolved}${importSuffix}`,
510
- moduleSideEffects: hasModuleSideEffects(resolved)
511
- };
512
- return result;
513
- } catch (error) {
514
1013
  return null;
515
1014
  }
1015
+ const result = {
1016
+ id: `${location}${importSuffix}`,
1017
+ moduleSideEffects: hasModuleSideEffects(location)
1018
+ };
1019
+ return result;
516
1020
  },
517
1021
 
518
1022
  load(importee) {