@rollup/plugin-commonjs 22.0.0-7 → 22.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.
package/dist/cjs/index.js CHANGED
@@ -16,9 +16,9 @@ var glob__default = /*#__PURE__*/_interopDefaultLegacy(glob);
16
16
  var MagicString__default = /*#__PURE__*/_interopDefaultLegacy(MagicString);
17
17
  var isReference__default = /*#__PURE__*/_interopDefaultLegacy(isReference);
18
18
 
19
- var version = "22.0.0-7";
19
+ var version = "22.0.0";
20
20
  var peerDependencies = {
21
- rollup: "^2.66.1"
21
+ rollup: "^2.68.0"
22
22
  };
23
23
 
24
24
  function tryParse(parse, code, id) {
@@ -430,11 +430,11 @@ async function getStaticRequireProxy(id, requireReturnsDefault, loadModule) {
430
430
  return `export { default } from ${JSON.stringify(id)};`;
431
431
  }
432
432
 
433
- async function getEntryProxy(id, defaultIsModuleExports, loadModule) {
433
+ function getEntryProxy(id, defaultIsModuleExports, getModuleInfo) {
434
434
  const {
435
435
  meta: { commonjs: commonjsMeta },
436
436
  hasDefaultExport
437
- } = await loadModule({ id, moduleSideEffects: true });
437
+ } = getModuleInfo(id);
438
438
  if (!commonjsMeta || commonjsMeta.isCommonJS !== IS_WRAPPED_COMMONJS) {
439
439
  const stringifiedId = JSON.stringify(id);
440
440
  let code = `export * from ${stringifiedId};`;
@@ -462,8 +462,7 @@ function getEsImportProxy(id, defaultIsModuleExports) {
462
462
  }
463
463
  return {
464
464
  code,
465
- syntheticNamedExports: '__moduleExports',
466
- meta: { commonjs: { isCommonJS: false } }
465
+ syntheticNamedExports: '__moduleExports'
467
466
  };
468
467
  }
469
468
 
@@ -500,86 +499,119 @@ function resolveExtensions(importee, importer, extensions) {
500
499
  }
501
500
 
502
501
  function getResolveId(extensions) {
503
- return async function resolveId(importee, importer, resolveOptions) {
504
- // We assume that all requires are pre-resolved
505
- if (
506
- resolveOptions.custom &&
507
- resolveOptions.custom['node-resolve'] &&
508
- resolveOptions.custom['node-resolve'].isRequire
509
- ) {
510
- return null;
511
- }
512
- if (isWrappedId(importee, WRAPPED_SUFFIX)) {
513
- return unwrapId(importee, WRAPPED_SUFFIX);
514
- }
502
+ const currentlyResolving = new Map();
515
503
 
516
- if (
517
- importee.endsWith(ENTRY_SUFFIX) ||
518
- isWrappedId(importee, MODULE_SUFFIX) ||
519
- isWrappedId(importee, EXPORTS_SUFFIX) ||
520
- isWrappedId(importee, PROXY_SUFFIX) ||
521
- isWrappedId(importee, ES_IMPORT_SUFFIX) ||
522
- isWrappedId(importee, EXTERNAL_SUFFIX) ||
523
- importee.startsWith(HELPERS_ID) ||
524
- importee === DYNAMIC_MODULES_ID
525
- ) {
526
- return importee;
527
- }
504
+ return {
505
+ /**
506
+ * This is a Maps of importers to Sets of require sources being resolved at
507
+ * the moment by resolveRequireSourcesAndUpdateMeta
508
+ */
509
+ currentlyResolving,
510
+ async resolveId(importee, importer, resolveOptions) {
511
+ const customOptions = resolveOptions.custom;
512
+ // All logic below is specific to ES imports.
513
+ // Also, if we do not skip this logic for requires that are resolved while
514
+ // transforming a commonjs file, it can easily lead to deadlocks.
515
+ if (
516
+ customOptions &&
517
+ customOptions['node-resolve'] &&
518
+ customOptions['node-resolve'].isRequire
519
+ ) {
520
+ return null;
521
+ }
522
+ const currentlyResolvingForParent = currentlyResolving.get(importer);
523
+ if (currentlyResolvingForParent && currentlyResolvingForParent.has(importee)) {
524
+ this.warn({
525
+ code: 'THIS_RESOLVE_WITHOUT_OPTIONS',
526
+ message:
527
+ 'It appears a plugin has implemented a "resolveId" hook that uses "this.resolve" without forwarding the third "options" parameter of "resolveId". This is problematic as it can lead to wrong module resolutions especially for the node-resolve plugin and in certain cases cause early exit errors for the commonjs plugin.\nIn rare cases, this warning can appear if the same file is both imported and required from the same mixed ES/CommonJS module, in which case it can be ignored.',
528
+ url: 'https://rollupjs.org/guide/en/#resolveid'
529
+ });
530
+ return null;
531
+ }
532
+
533
+ if (isWrappedId(importee, WRAPPED_SUFFIX)) {
534
+ return unwrapId(importee, WRAPPED_SUFFIX);
535
+ }
528
536
 
529
- if (importer) {
530
537
  if (
531
- importer === DYNAMIC_MODULES_ID ||
532
- // Proxies are only importing resolved ids, no need to resolve again
533
- isWrappedId(importer, PROXY_SUFFIX) ||
534
- isWrappedId(importer, ES_IMPORT_SUFFIX) ||
535
- importer.endsWith(ENTRY_SUFFIX)
538
+ importee.endsWith(ENTRY_SUFFIX) ||
539
+ isWrappedId(importee, MODULE_SUFFIX) ||
540
+ isWrappedId(importee, EXPORTS_SUFFIX) ||
541
+ isWrappedId(importee, PROXY_SUFFIX) ||
542
+ isWrappedId(importee, ES_IMPORT_SUFFIX) ||
543
+ isWrappedId(importee, EXTERNAL_SUFFIX) ||
544
+ importee.startsWith(HELPERS_ID) ||
545
+ importee === DYNAMIC_MODULES_ID
536
546
  ) {
537
547
  return importee;
538
548
  }
539
- if (isWrappedId(importer, EXTERNAL_SUFFIX)) {
540
- // We need to return null for unresolved imports so that the proper warning is shown
541
- if (!(await this.resolve(importee, importer, { skipSelf: true }))) {
542
- return null;
549
+
550
+ if (importer) {
551
+ if (
552
+ importer === DYNAMIC_MODULES_ID ||
553
+ // Proxies are only importing resolved ids, no need to resolve again
554
+ isWrappedId(importer, PROXY_SUFFIX) ||
555
+ isWrappedId(importer, ES_IMPORT_SUFFIX) ||
556
+ importer.endsWith(ENTRY_SUFFIX)
557
+ ) {
558
+ return importee;
559
+ }
560
+ if (isWrappedId(importer, EXTERNAL_SUFFIX)) {
561
+ // We need to return null for unresolved imports so that the proper warning is shown
562
+ if (
563
+ !(await this.resolve(
564
+ importee,
565
+ importer,
566
+ Object.assign({ skipSelf: true }, resolveOptions)
567
+ ))
568
+ ) {
569
+ return null;
570
+ }
571
+ // For other external imports, we need to make sure they are handled as external
572
+ return { id: importee, external: true };
543
573
  }
544
- // For other external imports, we need to make sure they are handled as external
545
- return { id: importee, external: true };
546
574
  }
547
- }
548
575
 
549
- if (importee.startsWith('\0')) {
550
- return null;
551
- }
552
-
553
- // If this is an entry point or ESM import, we need to figure out if the importee is wrapped and
554
- // if that is the case, we need to add a proxy.
555
- const customOptions = resolveOptions.custom;
556
-
557
- // If this is a require, we do not need a proxy
558
- if (customOptions && customOptions['node-resolve'] && customOptions['node-resolve'].isRequire) {
559
- return null;
560
- }
576
+ if (importee.startsWith('\0')) {
577
+ return null;
578
+ }
561
579
 
562
- const resolved =
563
- (await this.resolve(importee, importer, Object.assign({ skipSelf: true }, resolveOptions))) ||
564
- resolveExtensions(importee, importer, extensions);
565
- if (!resolved || resolved.external) {
580
+ // If this is an entry point or ESM import, we need to figure out if the importee is wrapped and
581
+ // if that is the case, we need to add a proxy.
582
+ const resolved =
583
+ (await this.resolve(
584
+ importee,
585
+ importer,
586
+ Object.assign({ skipSelf: true }, resolveOptions)
587
+ )) || resolveExtensions(importee, importer, extensions);
588
+ // Make sure that even if other plugins resolve again, we ignore our own proxies
589
+ if (
590
+ !resolved ||
591
+ resolved.external ||
592
+ resolved.id.endsWith(ENTRY_SUFFIX) ||
593
+ isWrappedId(resolved.id, ES_IMPORT_SUFFIX)
594
+ ) {
595
+ return resolved;
596
+ }
597
+ const moduleInfo = await this.load(resolved);
598
+ if (resolveOptions.isEntry) {
599
+ moduleInfo.moduleSideEffects = true;
600
+ // We must not precede entry proxies with a `\0` as that will mess up relative external resolution
601
+ return resolved.id + ENTRY_SUFFIX;
602
+ }
603
+ const {
604
+ meta: { commonjs: commonjsMeta }
605
+ } = moduleInfo;
606
+ if (commonjsMeta && commonjsMeta.isCommonJS === IS_WRAPPED_COMMONJS) {
607
+ return { id: wrapId(resolved.id, ES_IMPORT_SUFFIX), meta: { commonjs: { resolved } } };
608
+ }
566
609
  return resolved;
567
610
  }
568
- if (resolveOptions.isEntry) {
569
- // We must not precede entry proxies with a `\0` as that will mess up relative external resolution
570
- return resolved.id + ENTRY_SUFFIX;
571
- }
572
- const {
573
- meta: { commonjs: commonjsMeta }
574
- } = await this.load(resolved);
575
- if (commonjsMeta && commonjsMeta.isCommonJS === IS_WRAPPED_COMMONJS) {
576
- return wrapId(resolved.id, ES_IMPORT_SUFFIX);
577
- }
578
- return resolved;
579
611
  };
580
612
  }
581
613
 
582
- function getRequireResolver(extensions, detectCyclesAndConditional) {
614
+ function getRequireResolver(extensions, detectCyclesAndConditional, currentlyResolving) {
583
615
  const knownCjsModuleTypes = Object.create(null);
584
616
  const requiredIds = Object.create(null);
585
617
  const unconditionallyRequiredIds = Object.create(null);
@@ -599,6 +631,9 @@ function getRequireResolver(extensions, detectCyclesAndConditional) {
599
631
  return false;
600
632
  };
601
633
 
634
+ // Once a module is listed here, its type (wrapped or not) is fixed and may
635
+ // not change for the rest of the current build, to not break already
636
+ // transformed modules.
602
637
  const fullyAnalyzedModules = Object.create(null);
603
638
 
604
639
  const getTypeForFullyAnalyzedModule = (id) => {
@@ -606,7 +641,6 @@ function getRequireResolver(extensions, detectCyclesAndConditional) {
606
641
  if (knownType !== true || !detectCyclesAndConditional || fullyAnalyzedModules[id]) {
607
642
  return knownType;
608
643
  }
609
- fullyAnalyzedModules[id] = true;
610
644
  if (isCyclic(id)) {
611
645
  return (knownCjsModuleTypes[id] = IS_WRAPPED_COMMONJS);
612
646
  }
@@ -614,13 +648,11 @@ function getRequireResolver(extensions, detectCyclesAndConditional) {
614
648
  };
615
649
 
616
650
  const setInitialParentType = (id, initialCommonJSType) => {
617
- // It is possible a transformed module is already fully analyzed when using
618
- // the cache and one dependency introduces a new cycle. Then transform is
619
- // run for a fully analzyed module again. Fully analyzed modules may never
620
- // change their type as importers already trust their type.
621
- knownCjsModuleTypes[id] = fullyAnalyzedModules[id]
622
- ? knownCjsModuleTypes[id]
623
- : initialCommonJSType;
651
+ // Fully analyzed modules may never change type
652
+ if (fullyAnalyzedModules[id]) {
653
+ return;
654
+ }
655
+ knownCjsModuleTypes[id] = initialCommonJSType;
624
656
  if (
625
657
  detectCyclesAndConditional &&
626
658
  knownCjsModuleTypes[id] === true &&
@@ -631,7 +663,7 @@ function getRequireResolver(extensions, detectCyclesAndConditional) {
631
663
  }
632
664
  };
633
665
 
634
- const setTypesForRequiredModules = async (parentId, resolved, isConditional, loadModule) => {
666
+ const analyzeRequiredModule = async (parentId, resolved, isConditional, loadModule) => {
635
667
  const childId = resolved.id;
636
668
  requiredIds[childId] = true;
637
669
  if (!(isConditional || knownCjsModuleTypes[parentId] === IS_WRAPPED_COMMONJS)) {
@@ -640,41 +672,85 @@ function getRequireResolver(extensions, detectCyclesAndConditional) {
640
672
 
641
673
  getDependencies(parentId).add(childId);
642
674
  if (!isCyclic(childId)) {
643
- // This makes sure the current transform handler waits for all direct dependencies to be
644
- // loaded and transformed and therefore for all transitive CommonJS dependencies to be
645
- // loaded as well so that all cycles have been found and knownCjsModuleTypes is reliable.
675
+ // This makes sure the current transform handler waits for all direct
676
+ // dependencies to be loaded and transformed and therefore for all
677
+ // transitive CommonJS dependencies to be loaded as well so that all
678
+ // cycles have been found and knownCjsModuleTypes is reliable.
646
679
  await loadModule(resolved);
647
680
  }
648
681
  };
649
682
 
683
+ const getTypeForImportedModule = async (resolved, loadModule) => {
684
+ if (resolved.id in knownCjsModuleTypes) {
685
+ // This handles cyclic ES dependencies
686
+ return knownCjsModuleTypes[resolved.id];
687
+ }
688
+ const {
689
+ meta: { commonjs }
690
+ } = await loadModule(resolved);
691
+ return (commonjs && commonjs.isCommonJS) || false;
692
+ };
693
+
650
694
  return {
651
695
  getWrappedIds: () =>
652
696
  Object.keys(knownCjsModuleTypes).filter(
653
697
  (id) => knownCjsModuleTypes[id] === IS_WRAPPED_COMMONJS
654
698
  ),
655
699
  isRequiredId: (id) => requiredIds[id],
656
- async shouldTransformCachedModule({ id: parentId, meta: { commonjs: parentMeta } }) {
657
- // Ignore modules that did not pass through the original transformer in a previous build
658
- if (!(parentMeta && parentMeta.requires)) {
659
- return false;
660
- }
661
- setInitialParentType(parentId, parentMeta.initialCommonJSType);
662
- await Promise.all(
663
- parentMeta.requires.map(({ resolved, isConditional }) =>
664
- setTypesForRequiredModules(parentId, resolved, isConditional, this.load)
665
- )
666
- );
667
- if (getTypeForFullyAnalyzedModule(parentId) !== parentMeta.isCommonJS) {
668
- return true;
669
- }
670
- for (const {
671
- resolved: { id }
672
- } of parentMeta.requires) {
673
- if (getTypeForFullyAnalyzedModule(id) !== parentMeta.isRequiredCommonJS[id]) {
700
+ async shouldTransformCachedModule({
701
+ id: parentId,
702
+ resolvedSources,
703
+ meta: { commonjs: parentMeta }
704
+ }) {
705
+ // We explicitly track ES modules to handle circular imports
706
+ if (!(parentMeta && parentMeta.isCommonJS)) knownCjsModuleTypes[parentId] = false;
707
+ if (isWrappedId(parentId, ES_IMPORT_SUFFIX)) return false;
708
+ const parentRequires = parentMeta && parentMeta.requires;
709
+ if (parentRequires) {
710
+ setInitialParentType(parentId, parentMeta.initialCommonJSType);
711
+ await Promise.all(
712
+ parentRequires.map(({ resolved, isConditional }) =>
713
+ analyzeRequiredModule(parentId, resolved, isConditional, this.load)
714
+ )
715
+ );
716
+ if (getTypeForFullyAnalyzedModule(parentId) !== parentMeta.isCommonJS) {
674
717
  return true;
675
718
  }
719
+ for (const {
720
+ resolved: { id }
721
+ } of parentRequires) {
722
+ if (getTypeForFullyAnalyzedModule(id) !== parentMeta.isRequiredCommonJS[id]) {
723
+ return true;
724
+ }
725
+ }
726
+ // Now that we decided to go with the cached copy, neither the parent
727
+ // module nor any of its children may change types anymore
728
+ fullyAnalyzedModules[parentId] = true;
729
+ for (const {
730
+ resolved: { id }
731
+ } of parentRequires) {
732
+ fullyAnalyzedModules[id] = true;
733
+ }
676
734
  }
677
- return false;
735
+ const parentRequireSet = new Set((parentRequires || []).map(({ resolved: { id } }) => id));
736
+ return (
737
+ await Promise.all(
738
+ Object.keys(resolvedSources)
739
+ .map((source) => resolvedSources[source])
740
+ .filter(({ id, external }) => !(external || parentRequireSet.has(id)))
741
+ .map(async (resolved) => {
742
+ if (isWrappedId(resolved.id, ES_IMPORT_SUFFIX)) {
743
+ return (
744
+ (await getTypeForImportedModule(
745
+ (await this.load({ id: resolved.id })).meta.commonjs.resolved,
746
+ this.load
747
+ )) !== IS_WRAPPED_COMMONJS
748
+ );
749
+ }
750
+ return (await getTypeForImportedModule(resolved, this.load)) === IS_WRAPPED_COMMONJS;
751
+ })
752
+ )
753
+ ).some((shouldTransform) => shouldTransform);
678
754
  },
679
755
  /* eslint-disable no-param-reassign */
680
756
  resolveRequireSourcesAndUpdateMeta: (rollupContext) => async (
@@ -687,16 +763,20 @@ function getRequireResolver(extensions, detectCyclesAndConditional) {
687
763
  parentMeta.requires = [];
688
764
  parentMeta.isRequiredCommonJS = Object.create(null);
689
765
  setInitialParentType(parentId, isParentCommonJS);
766
+ const currentlyResolvingForParent = currentlyResolving.get(parentId) || new Set();
767
+ currentlyResolving.set(parentId, currentlyResolvingForParent);
690
768
  const requireTargets = await Promise.all(
691
769
  sources.map(async ({ source, isConditional }) => {
692
770
  // Never analyze or proxy internal modules
693
771
  if (source.startsWith('\0')) {
694
772
  return { id: source, allowProxy: false };
695
773
  }
774
+ currentlyResolvingForParent.add(source);
696
775
  const resolved =
697
776
  (await rollupContext.resolve(source, parentId, {
698
777
  custom: { 'node-resolve': { isRequire: true } }
699
778
  })) || resolveExtensions(source, parentId, extensions);
779
+ currentlyResolvingForParent.delete(source);
700
780
  if (!resolved) {
701
781
  return { id: wrapId(source, EXTERNAL_SUFFIX), allowProxy: false };
702
782
  }
@@ -705,16 +785,18 @@ function getRequireResolver(extensions, detectCyclesAndConditional) {
705
785
  return { id: wrapId(childId, EXTERNAL_SUFFIX), allowProxy: false };
706
786
  }
707
787
  parentMeta.requires.push({ resolved, isConditional });
708
- await setTypesForRequiredModules(parentId, resolved, isConditional, rollupContext.load);
788
+ await analyzeRequiredModule(parentId, resolved, isConditional, rollupContext.load);
709
789
  return { id: childId, allowProxy: true };
710
790
  })
711
791
  );
712
792
  parentMeta.isCommonJS = getTypeForFullyAnalyzedModule(parentId);
793
+ fullyAnalyzedModules[parentId] = true;
713
794
  return requireTargets.map(({ id: dependencyId, allowProxy }, index) => {
714
795
  // eslint-disable-next-line no-multi-assign
715
796
  const isCommonJS = (parentMeta.isRequiredCommonJS[
716
797
  dependencyId
717
798
  ] = getTypeForFullyAnalyzedModule(dependencyId));
799
+ fullyAnalyzedModules[dependencyId] = true;
718
800
  return {
719
801
  source: sources[index].source,
720
802
  id: allowProxy
@@ -725,6 +807,10 @@ function getRequireResolver(extensions, detectCyclesAndConditional) {
725
807
  isCommonJS
726
808
  };
727
809
  });
810
+ },
811
+ isCurrentlyResolving(source, parentId) {
812
+ const currentlyResolvingForParent = currentlyResolving.get(parentId);
813
+ return currentlyResolvingForParent && currentlyResolvingForParent.has(source);
728
814
  }
729
815
  };
730
816
  }
@@ -1168,7 +1254,7 @@ function getRequireStringArg(node) {
1168
1254
  function getRequireHandlers() {
1169
1255
  const requireExpressions = [];
1170
1256
 
1171
- function addRequireStatement(
1257
+ function addRequireExpression(
1172
1258
  sourceId,
1173
1259
  node,
1174
1260
  scope,
@@ -1248,7 +1334,7 @@ function getRequireHandlers() {
1248
1334
  }
1249
1335
 
1250
1336
  return {
1251
- addRequireStatement,
1337
+ addRequireExpression,
1252
1338
  rewriteRequireExpressionsAndGetImportBlock
1253
1339
  };
1254
1340
  }
@@ -1367,6 +1453,7 @@ async function transformCommonjs(
1367
1453
  let programDepth = 0;
1368
1454
  let currentTryBlockEnd = null;
1369
1455
  let shouldWrap = false;
1456
+ let reexports = false;
1370
1457
 
1371
1458
  const globals = new Set();
1372
1459
  // A conditionalNode is a node for which execution is not guaranteed. If such a node is a require
@@ -1374,7 +1461,7 @@ async function transformCommonjs(
1374
1461
  // unconditional require elsewhere.
1375
1462
  let currentConditionalNodeEnd = null;
1376
1463
  const conditionalNodes = new Set();
1377
- const { addRequireStatement, rewriteRequireExpressionsAndGetImportBlock } = getRequireHandlers();
1464
+ const { addRequireExpression, rewriteRequireExpressionsAndGetImportBlock } = getRequireHandlers();
1378
1465
 
1379
1466
  // See which names are assigned to. This is necessary to prevent
1380
1467
  // illegally replacing `var foo = require('foo')` with `import foo from 'foo'`,
@@ -1391,6 +1478,7 @@ async function transformCommonjs(
1391
1478
  const topLevelDefineCompiledEsmExpressions = [];
1392
1479
  const replacedGlobal = [];
1393
1480
  const replacedDynamicRequires = [];
1481
+ const importedVariables = new Set();
1394
1482
 
1395
1483
  estreeWalker.walk(ast, {
1396
1484
  enter(node, parent) {
@@ -1446,8 +1534,9 @@ async function transformCommonjs(
1446
1534
  if (hasDefineEsmProperty(node.right)) {
1447
1535
  shouldWrap = true;
1448
1536
  }
1449
- } else if (defaultIsModuleExports === false) {
1537
+ } else if (isRequireExpression(node.right, scope)) {
1450
1538
  shouldWrap = true;
1539
+ reexports = true;
1451
1540
  }
1452
1541
  }
1453
1542
  } else if (exportName === KEY_COMPILED_ESM) {
@@ -1504,6 +1593,11 @@ async function transformCommonjs(
1504
1593
  }
1505
1594
 
1506
1595
  if (!isRequireExpression(node, scope)) {
1596
+ const keypath = getKeypath(node.callee);
1597
+ if (keypath && importedVariables.has(keypath.name)) {
1598
+ // Heuristic to deoptimize requires after a required function has been called
1599
+ currentConditionalNodeEnd = Infinity;
1600
+ }
1507
1601
  return;
1508
1602
  }
1509
1603
 
@@ -1523,15 +1617,28 @@ async function transformCommonjs(
1523
1617
  const requireStringArg = getRequireStringArg(node);
1524
1618
  if (!ignoreRequire(requireStringArg)) {
1525
1619
  const usesReturnValue = parent.type !== 'ExpressionStatement';
1526
- addRequireStatement(
1620
+ const toBeRemoved =
1621
+ parent.type === 'ExpressionStatement' &&
1622
+ (!currentConditionalNodeEnd ||
1623
+ // We should completely remove requires directly in a try-catch
1624
+ // so that Rollup can remove up the try-catch
1625
+ (currentTryBlockEnd !== null && currentTryBlockEnd < currentConditionalNodeEnd))
1626
+ ? parent
1627
+ : node;
1628
+ addRequireExpression(
1527
1629
  requireStringArg,
1528
1630
  node,
1529
1631
  scope,
1530
1632
  usesReturnValue,
1531
1633
  currentTryBlockEnd !== null,
1532
1634
  currentConditionalNodeEnd !== null,
1533
- parent.type === 'ExpressionStatement' ? parent : node
1635
+ toBeRemoved
1534
1636
  );
1637
+ if (parent.type === 'VariableDeclarator' && parent.id.type === 'Identifier') {
1638
+ for (const name of pluginutils.extractAssignedNames(parent.id)) {
1639
+ importedVariables.add(name);
1640
+ }
1641
+ }
1535
1642
  }
1536
1643
  return;
1537
1644
  }
@@ -1721,12 +1828,15 @@ async function transformCommonjs(
1721
1828
  shouldWrap = !isEsModule && (shouldWrap || (uses.exports && moduleExportsAssignments.length > 0));
1722
1829
  const detectWrappedDefault =
1723
1830
  shouldWrap &&
1724
- (topLevelDefineCompiledEsmExpressions.length > 0 || code.indexOf('__esModule') >= 0);
1831
+ (reexports ||
1832
+ topLevelDefineCompiledEsmExpressions.length > 0 ||
1833
+ code.indexOf('__esModule') >= 0);
1725
1834
 
1726
1835
  if (
1727
1836
  !(
1728
1837
  shouldWrap ||
1729
1838
  isRequired ||
1839
+ needsRequireWrapper ||
1730
1840
  uses.module ||
1731
1841
  uses.exports ||
1732
1842
  uses.require ||
@@ -1744,7 +1854,9 @@ async function transformCommonjs(
1744
1854
  magicString.remove(0, commentEnd).trim();
1745
1855
  }
1746
1856
 
1747
- const exportMode = shouldWrap
1857
+ const exportMode = isEsModule
1858
+ ? 'none'
1859
+ : shouldWrap
1748
1860
  ? uses.module
1749
1861
  ? 'module'
1750
1862
  : 'exports'
@@ -1830,11 +1942,14 @@ function ${requireName} () {
1830
1942
  };
1831
1943
  }
1832
1944
 
1945
+ const PLUGIN_NAME = 'commonjs';
1946
+
1833
1947
  function commonjs(options = {}) {
1834
1948
  const {
1835
1949
  ignoreGlobal,
1836
1950
  ignoreDynamicRequires,
1837
1951
  requireReturnsDefault: requireReturnsDefaultOption,
1952
+ defaultIsModuleExports: defaultIsModuleExportsOption,
1838
1953
  esmExternals
1839
1954
  } = options;
1840
1955
  const extensions = options.extensions || ['.js'];
@@ -1854,8 +1969,11 @@ function commonjs(options = {}) {
1854
1969
  ? ((esmExternalIds = new Set(esmExternals)), (id) => esmExternalIds.has(id))
1855
1970
  : () => esmExternals;
1856
1971
 
1857
- const defaultIsModuleExports =
1858
- typeof options.defaultIsModuleExports === 'boolean' ? options.defaultIsModuleExports : 'auto';
1972
+ const getDefaultIsModuleExports =
1973
+ typeof defaultIsModuleExportsOption === 'function'
1974
+ ? defaultIsModuleExportsOption
1975
+ : () =>
1976
+ typeof defaultIsModuleExportsOption === 'boolean' ? defaultIsModuleExportsOption : 'auto';
1859
1977
 
1860
1978
  const dynamicRequireRoot =
1861
1979
  typeof options.dynamicRequireRoot === 'string'
@@ -1890,7 +2008,7 @@ function commonjs(options = {}) {
1890
2008
  };
1891
2009
  };
1892
2010
 
1893
- const resolveId = getResolveId(extensions);
2011
+ const { currentlyResolving, resolveId } = getResolveId(extensions);
1894
2012
 
1895
2013
  const sourceMap = options.sourceMap !== false;
1896
2014
 
@@ -1955,7 +2073,7 @@ function commonjs(options = {}) {
1955
2073
  dynamicRequireModules,
1956
2074
  commonDir,
1957
2075
  ast,
1958
- defaultIsModuleExports,
2076
+ getDefaultIsModuleExports(id),
1959
2077
  needsRequireWrapper,
1960
2078
  requireResolver.resolveRequireSourcesAndUpdateMeta(this),
1961
2079
  requireResolver.isRequiredId(id),
@@ -1965,7 +2083,7 @@ function commonjs(options = {}) {
1965
2083
  }
1966
2084
 
1967
2085
  return {
1968
- name: 'commonjs',
2086
+ name: PLUGIN_NAME,
1969
2087
 
1970
2088
  version,
1971
2089
 
@@ -1973,7 +2091,7 @@ function commonjs(options = {}) {
1973
2091
  // We inject the resolver in the beginning so that "catch-all-resolver" like node-resolver
1974
2092
  // do not prevent our plugin from resolving entry points ot proxies.
1975
2093
  const plugins = Array.isArray(rawOptions.plugins)
1976
- ? rawOptions.plugins
2094
+ ? [...rawOptions.plugins]
1977
2095
  : rawOptions.plugins
1978
2096
  ? [rawOptions.plugins]
1979
2097
  : [];
@@ -1995,7 +2113,11 @@ function commonjs(options = {}) {
1995
2113
  'The namedExports option from "@rollup/plugin-commonjs" is deprecated. Named exports are now handled automatically.'
1996
2114
  );
1997
2115
  }
1998
- requireResolver = getRequireResolver(extensions, detectCyclesAndConditional);
2116
+ requireResolver = getRequireResolver(
2117
+ extensions,
2118
+ detectCyclesAndConditional,
2119
+ currentlyResolving
2120
+ );
1999
2121
  },
2000
2122
 
2001
2123
  buildEnd() {
@@ -2051,11 +2173,13 @@ function commonjs(options = {}) {
2051
2173
 
2052
2174
  // entry suffix is just appended to not mess up relative external resolution
2053
2175
  if (id.endsWith(ENTRY_SUFFIX)) {
2054
- return getEntryProxy(id.slice(0, -ENTRY_SUFFIX.length), defaultIsModuleExports, this.load);
2176
+ const acutalId = id.slice(0, -ENTRY_SUFFIX.length);
2177
+ return getEntryProxy(acutalId, getDefaultIsModuleExports(acutalId), this.getModuleInfo);
2055
2178
  }
2056
2179
 
2057
2180
  if (isWrappedId(id, ES_IMPORT_SUFFIX)) {
2058
- return getEsImportProxy(unwrapId(id, ES_IMPORT_SUFFIX), defaultIsModuleExports);
2181
+ const actualId = unwrapId(id, ES_IMPORT_SUFFIX);
2182
+ return getEsImportProxy(actualId, getDefaultIsModuleExports(actualId));
2059
2183
  }
2060
2184
 
2061
2185
  if (id === DYNAMIC_MODULES_ID) {