@rollup/plugin-commonjs 22.0.0-1 → 22.0.0-10

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.
@@ -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-1";
19
+ var version = " 22.0.0-10";
20
20
  var peerDependencies = {
21
- rollup: "^2.60.0"
21
+ rollup: "^2.67.0"
22
22
  };
23
23
 
24
24
  function tryParse(parse, code, id) {
@@ -203,6 +203,9 @@ function getDynamicRequireModules(patterns, dynamicRequireRoot) {
203
203
 
204
204
  const FAILED_REQUIRE_ERROR = `throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');`;
205
205
 
206
+ const COMMONJS_REQUIRE_EXPORT = 'commonjsRequire';
207
+ const CREATE_COMMONJS_REQUIRE_EXPORT = 'createCommonjsRequire';
208
+
206
209
  function getDynamicModuleRegistry(
207
210
  isDynamicRequireModulesEnabled,
208
211
  dynamicRequireModules,
@@ -210,7 +213,7 @@ function getDynamicModuleRegistry(
210
213
  ignoreDynamicRequires
211
214
  ) {
212
215
  if (!isDynamicRequireModulesEnabled) {
213
- return `export function commonjsRequire(path) {
216
+ return `export function ${COMMONJS_REQUIRE_EXPORT}(path) {
214
217
  ${FAILED_REQUIRE_ERROR}
215
218
  }`;
216
219
  }
@@ -240,25 +243,25 @@ ${dynamicModuleProps}
240
243
  });
241
244
  }
242
245
 
243
- export function commonjsRequire(path, originalModuleDir) {
244
- var resolvedPath = commonjsResolveImpl(path, originalModuleDir);
245
- if (resolvedPath !== null) {
246
- return getDynamicModules()[resolvedPath]();
246
+ export function ${CREATE_COMMONJS_REQUIRE_EXPORT}(originalModuleDir) {
247
+ function handleRequire(path) {
248
+ var resolvedPath = commonjsResolve(path, originalModuleDir);
249
+ if (resolvedPath !== null) {
250
+ return getDynamicModules()[resolvedPath]();
251
+ }
252
+ ${ignoreDynamicRequires ? 'return require(path);' : FAILED_REQUIRE_ERROR}
247
253
  }
248
- ${ignoreDynamicRequires ? 'return require(path);' : FAILED_REQUIRE_ERROR}
249
- }
250
-
251
- function commonjsResolve (path, originalModuleDir) {
252
- const resolvedPath = commonjsResolveImpl(path, originalModuleDir);
253
- if (resolvedPath !== null) {
254
- return resolvedPath;
254
+ handleRequire.resolve = function (path) {
255
+ var resolvedPath = commonjsResolve(path, originalModuleDir);
256
+ if (resolvedPath !== null) {
257
+ return resolvedPath;
258
+ }
259
+ return require.resolve(path);
255
260
  }
256
- return require.resolve(path);
261
+ return handleRequire;
257
262
  }
258
263
 
259
- commonjsRequire.resolve = commonjsResolve;
260
-
261
- function commonjsResolveImpl (path, originalModuleDir) {
264
+ function commonjsResolve (path, originalModuleDir) {
262
265
  var shouldTryNodeModules = isPossibleNodeModulesPath(path);
263
266
  path = normalize(path);
264
267
  var relPath;
@@ -334,7 +337,8 @@ const WRAPPED_SUFFIX = '?commonjs-wrapped';
334
337
  const EXTERNAL_SUFFIX = '?commonjs-external';
335
338
  const EXPORTS_SUFFIX = '?commonjs-exports';
336
339
  const MODULE_SUFFIX = '?commonjs-module';
337
- const ES_IMPORT_SUFFIX = '?es-import';
340
+ const ENTRY_SUFFIX = '?commonjs-entry';
341
+ const ES_IMPORT_SUFFIX = '?commonjs-es-import';
338
342
 
339
343
  const DYNAMIC_MODULES_ID = '\0commonjs-dynamic-modules';
340
344
  const HELPERS_ID = '\0commonjsHelpers.js';
@@ -402,21 +406,15 @@ function getUnknownRequireProxy(id, requireReturnsDefault) {
402
406
  return `import * as ${name} from ${JSON.stringify(id)}; ${exported}`;
403
407
  }
404
408
 
405
- async function getStaticRequireProxy(
406
- id,
407
- requireReturnsDefault,
408
- esModulesWithDefaultExport,
409
- esModulesWithNamedExports,
410
- loadModule
411
- ) {
409
+ async function getStaticRequireProxy(id, requireReturnsDefault, loadModule) {
412
410
  const name = getName(id);
413
411
  const {
414
412
  meta: { commonjs: commonjsMeta }
415
413
  } = await loadModule({ id });
416
- if (commonjsMeta && commonjsMeta.isCommonJS) {
417
- return `export { __moduleExports as default } from ${JSON.stringify(id)};`;
418
- } else if (!commonjsMeta) {
414
+ if (!commonjsMeta) {
419
415
  return getUnknownRequireProxy(id, requireReturnsDefault);
416
+ } else if (commonjsMeta.isCommonJS) {
417
+ return `export { __moduleExports as default } from ${JSON.stringify(id)};`;
420
418
  } else if (!requireReturnsDefault) {
421
419
  return `import { getAugmentedNamespace } from "${HELPERS_ID}"; import * as ${name} from ${JSON.stringify(
422
420
  id
@@ -424,14 +422,30 @@ async function getStaticRequireProxy(
424
422
  } else if (
425
423
  requireReturnsDefault !== true &&
426
424
  (requireReturnsDefault === 'namespace' ||
427
- !esModulesWithDefaultExport.has(id) ||
428
- (requireReturnsDefault === 'auto' && esModulesWithNamedExports.has(id)))
425
+ !commonjsMeta.hasDefaultExport ||
426
+ (requireReturnsDefault === 'auto' && commonjsMeta.hasNamedExports))
429
427
  ) {
430
428
  return `import * as ${name} from ${JSON.stringify(id)}; export default ${name};`;
431
429
  }
432
430
  return `export { default } from ${JSON.stringify(id)};`;
433
431
  }
434
432
 
433
+ function getEntryProxy(id, defaultIsModuleExports, getModuleInfo) {
434
+ const {
435
+ meta: { commonjs: commonjsMeta },
436
+ hasDefaultExport
437
+ } = getModuleInfo(id);
438
+ if (!commonjsMeta || commonjsMeta.isCommonJS !== IS_WRAPPED_COMMONJS) {
439
+ const stringifiedId = JSON.stringify(id);
440
+ let code = `export * from ${stringifiedId};`;
441
+ if (hasDefaultExport) {
442
+ code += `export { default } from ${stringifiedId};`;
443
+ }
444
+ return code;
445
+ }
446
+ return getEsImportProxy(id, defaultIsModuleExports);
447
+ }
448
+
435
449
  function getEsImportProxy(id, defaultIsModuleExports) {
436
450
  const name = getName(id);
437
451
  const exportsName = `${name}Exports`;
@@ -487,11 +501,9 @@ function resolveExtensions(importee, importer, extensions) {
487
501
 
488
502
  function getResolveId(extensions) {
489
503
  return async function resolveId(importee, importer, resolveOptions) {
490
- if (
491
- resolveOptions.custom &&
492
- resolveOptions.custom.commonjs &&
493
- resolveOptions.custom.commonjs.skipResolver
494
- ) {
504
+ // We assume that all requires are pre-resolved
505
+ const customOptions = resolveOptions.custom;
506
+ if (customOptions && customOptions['node-resolve'] && customOptions['node-resolve'].isRequire) {
495
507
  return null;
496
508
  }
497
509
  if (isWrappedId(importee, WRAPPED_SUFFIX)) {
@@ -499,6 +511,7 @@ function getResolveId(extensions) {
499
511
  }
500
512
 
501
513
  if (
514
+ importee.endsWith(ENTRY_SUFFIX) ||
502
515
  isWrappedId(importee, MODULE_SUFFIX) ||
503
516
  isWrappedId(importee, EXPORTS_SUFFIX) ||
504
517
  isWrappedId(importee, PROXY_SUFFIX) ||
@@ -515,7 +528,8 @@ function getResolveId(extensions) {
515
528
  importer === DYNAMIC_MODULES_ID ||
516
529
  // Proxies are only importing resolved ids, no need to resolve again
517
530
  isWrappedId(importer, PROXY_SUFFIX) ||
518
- isWrappedId(importer, ES_IMPORT_SUFFIX)
531
+ isWrappedId(importer, ES_IMPORT_SUFFIX) ||
532
+ importer.endsWith(ENTRY_SUFFIX)
519
533
  ) {
520
534
  return importee;
521
535
  }
@@ -535,22 +549,27 @@ function getResolveId(extensions) {
535
549
 
536
550
  // If this is an entry point or ESM import, we need to figure out if the importee is wrapped and
537
551
  // if that is the case, we need to add a proxy.
538
- const customOptions = resolveOptions.custom;
539
-
540
- // If this is a require, we do not need a proxy
541
- if (customOptions && customOptions['node-resolve'] && customOptions['node-resolve'].isRequire) {
542
- return null;
543
- }
544
-
545
552
  const resolved =
546
553
  (await this.resolve(importee, importer, Object.assign({ skipSelf: true }, resolveOptions))) ||
547
554
  resolveExtensions(importee, importer, extensions);
548
- if (!resolved || resolved.external) {
555
+ // Make sure that even if other plugins resolve again, we ignore our own proxies
556
+ if (
557
+ !resolved ||
558
+ resolved.external ||
559
+ resolved.id.endsWith(ENTRY_SUFFIX) ||
560
+ isWrappedId(resolved.id, ES_IMPORT_SUFFIX)
561
+ ) {
549
562
  return resolved;
550
563
  }
564
+ const moduleInfo = await this.load(resolved);
565
+ if (resolveOptions.isEntry) {
566
+ moduleInfo.moduleSideEffects = true;
567
+ // We must not precede entry proxies with a `\0` as that will mess up relative external resolution
568
+ return resolved.id + ENTRY_SUFFIX;
569
+ }
551
570
  const {
552
571
  meta: { commonjs: commonjsMeta }
553
- } = await this.load(resolved);
572
+ } = moduleInfo;
554
573
  if (commonjsMeta && commonjsMeta.isCommonJS === IS_WRAPPED_COMMONJS) {
555
574
  return wrapId(resolved.id, ES_IMPORT_SUFFIX);
556
575
  }
@@ -558,14 +577,73 @@ function getResolveId(extensions) {
558
577
  };
559
578
  }
560
579
 
561
- function getResolveRequireSourcesAndGetMeta(extensions, detectCyclesAndConditional) {
580
+ function getRequireResolver(extensions, detectCyclesAndConditional) {
562
581
  const knownCjsModuleTypes = Object.create(null);
563
582
  const requiredIds = Object.create(null);
564
583
  const unconditionallyRequiredIds = Object.create(null);
565
- const parentModules = Object.create(null);
566
- const childModules = Object.create(null);
567
- const getParentModules = (id) => parentModules[id] || (parentModules[id] = Object.create(null));
568
- const getChildModules = (id) => childModules[id] || (childModules[id] = Object.create(null));
584
+ const dependencies = Object.create(null);
585
+ const getDependencies = (id) => dependencies[id] || (dependencies[id] = new Set());
586
+
587
+ const isCyclic = (id) => {
588
+ const dependenciesToCheck = new Set(getDependencies(id));
589
+ for (const dependency of dependenciesToCheck) {
590
+ if (dependency === id) {
591
+ return true;
592
+ }
593
+ for (const childDependency of getDependencies(dependency)) {
594
+ dependenciesToCheck.add(childDependency);
595
+ }
596
+ }
597
+ return false;
598
+ };
599
+
600
+ const fullyAnalyzedModules = Object.create(null);
601
+
602
+ const getTypeForFullyAnalyzedModule = (id) => {
603
+ const knownType = knownCjsModuleTypes[id];
604
+ if (knownType !== true || !detectCyclesAndConditional || fullyAnalyzedModules[id]) {
605
+ return knownType;
606
+ }
607
+ fullyAnalyzedModules[id] = true;
608
+ if (isCyclic(id)) {
609
+ return (knownCjsModuleTypes[id] = IS_WRAPPED_COMMONJS);
610
+ }
611
+ return knownType;
612
+ };
613
+
614
+ const setInitialParentType = (id, initialCommonJSType) => {
615
+ // It is possible a transformed module is already fully analyzed when using
616
+ // the cache and one dependency introduces a new cycle. Then transform is
617
+ // run for a fully analzyed module again. Fully analyzed modules may never
618
+ // change their type as importers already trust their type.
619
+ knownCjsModuleTypes[id] = fullyAnalyzedModules[id]
620
+ ? knownCjsModuleTypes[id]
621
+ : initialCommonJSType;
622
+ if (
623
+ detectCyclesAndConditional &&
624
+ knownCjsModuleTypes[id] === true &&
625
+ requiredIds[id] &&
626
+ !unconditionallyRequiredIds[id]
627
+ ) {
628
+ knownCjsModuleTypes[id] = IS_WRAPPED_COMMONJS;
629
+ }
630
+ };
631
+
632
+ const setTypesForRequiredModules = async (parentId, resolved, isConditional, loadModule) => {
633
+ const childId = resolved.id;
634
+ requiredIds[childId] = true;
635
+ if (!(isConditional || knownCjsModuleTypes[parentId] === IS_WRAPPED_COMMONJS)) {
636
+ unconditionallyRequiredIds[childId] = true;
637
+ }
638
+
639
+ getDependencies(parentId).add(childId);
640
+ if (!isCyclic(childId)) {
641
+ // This makes sure the current transform handler waits for all direct dependencies to be
642
+ // loaded and transformed and therefore for all transitive CommonJS dependencies to be
643
+ // loaded as well so that all cycles have been found and knownCjsModuleTypes is reliable.
644
+ await loadModule(resolved);
645
+ }
646
+ };
569
647
 
570
648
  return {
571
649
  getWrappedIds: () =>
@@ -573,19 +651,40 @@ function getResolveRequireSourcesAndGetMeta(extensions, detectCyclesAndCondition
573
651
  (id) => knownCjsModuleTypes[id] === IS_WRAPPED_COMMONJS
574
652
  ),
575
653
  isRequiredId: (id) => requiredIds[id],
576
- resolveRequireSourcesAndGetMeta: (rollupContext) => async (
654
+ async shouldTransformCachedModule({ id: parentId, meta: { commonjs: parentMeta } }) {
655
+ // Ignore modules that did not pass through the original transformer in a previous build
656
+ if (!(parentMeta && parentMeta.requires)) {
657
+ return false;
658
+ }
659
+ setInitialParentType(parentId, parentMeta.initialCommonJSType);
660
+ await Promise.all(
661
+ parentMeta.requires.map(({ resolved, isConditional }) =>
662
+ setTypesForRequiredModules(parentId, resolved, isConditional, this.load)
663
+ )
664
+ );
665
+ if (getTypeForFullyAnalyzedModule(parentId) !== parentMeta.isCommonJS) {
666
+ return true;
667
+ }
668
+ for (const {
669
+ resolved: { id }
670
+ } of parentMeta.requires) {
671
+ if (getTypeForFullyAnalyzedModule(id) !== parentMeta.isRequiredCommonJS[id]) {
672
+ return true;
673
+ }
674
+ }
675
+ return false;
676
+ },
677
+ /* eslint-disable no-param-reassign */
678
+ resolveRequireSourcesAndUpdateMeta: (rollupContext) => async (
577
679
  parentId,
578
680
  isParentCommonJS,
681
+ parentMeta,
579
682
  sources
580
683
  ) => {
581
- knownCjsModuleTypes[parentId] = knownCjsModuleTypes[parentId] || isParentCommonJS;
582
- if (
583
- knownCjsModuleTypes[parentId] &&
584
- requiredIds[parentId] &&
585
- !unconditionallyRequiredIds[parentId]
586
- ) {
587
- knownCjsModuleTypes[parentId] = IS_WRAPPED_COMMONJS;
588
- }
684
+ parentMeta.initialCommonJSType = isParentCommonJS;
685
+ parentMeta.requires = [];
686
+ parentMeta.isRequiredCommonJS = Object.create(null);
687
+ setInitialParentType(parentId, isParentCommonJS);
589
688
  const requireTargets = await Promise.all(
590
689
  sources.map(async ({ source, isConditional }) => {
591
690
  // Never analyze or proxy internal modules
@@ -594,10 +693,7 @@ function getResolveRequireSourcesAndGetMeta(extensions, detectCyclesAndCondition
594
693
  }
595
694
  const resolved =
596
695
  (await rollupContext.resolve(source, parentId, {
597
- custom: {
598
- 'node-resolve': { isRequire: true },
599
- commonjs: { skipResolver: true }
600
- }
696
+ custom: { 'node-resolve': { isRequire: true } }
601
697
  })) || resolveExtensions(source, parentId, extensions);
602
698
  if (!resolved) {
603
699
  return { id: wrapId(source, EXTERNAL_SUFFIX), allowProxy: false };
@@ -606,96 +702,58 @@ function getResolveRequireSourcesAndGetMeta(extensions, detectCyclesAndCondition
606
702
  if (resolved.external) {
607
703
  return { id: wrapId(childId, EXTERNAL_SUFFIX), allowProxy: false };
608
704
  }
609
- requiredIds[childId] = true;
610
- if (
611
- !(
612
- detectCyclesAndConditional &&
613
- (isConditional || knownCjsModuleTypes[parentId] === IS_WRAPPED_COMMONJS)
614
- )
615
- ) {
616
- unconditionallyRequiredIds[childId] = true;
617
- }
618
- const parentDependentModules = getParentModules(parentId);
619
- const childDependentModules = getParentModules(childId);
620
-
621
- // Copy the parents of the current parent to the child
622
- for (const dependentId of Object.keys(parentDependentModules)) {
623
- childDependentModules[dependentId] = true;
624
- }
625
-
626
- // Add the current parent to the child as well. If the child module already has known
627
- // dependencies because it has already been loaded, add the current parent module to their
628
- // parent modules
629
- childDependentModules[parentId] = true;
630
- const dependenciesToUpdate = new Set(Object.keys(getChildModules(childId)));
631
- for (const dependencyId of dependenciesToUpdate) {
632
- getParentModules(dependencyId)[parentId] = true;
633
- for (const subDependencyId of Object.keys(getChildModules(dependencyId))) {
634
- dependenciesToUpdate.add(subDependencyId);
635
- }
636
- }
637
-
638
- // Add the child as a dependency to the parent
639
- getChildModules(parentId)[childId] = true;
640
-
641
- // If we depend on one of our dependencies, we have a cycle. Then all modules that
642
- // we depend on that also depend on the same module are part of a cycle as well. Trying
643
- // to wait for loading this module would lead to a deadlock.
644
- if (parentDependentModules[childId]) {
645
- if (detectCyclesAndConditional && isParentCommonJS) {
646
- knownCjsModuleTypes[parentId] = IS_WRAPPED_COMMONJS;
647
- knownCjsModuleTypes[childId] = IS_WRAPPED_COMMONJS;
648
- for (const dependentId of Object.keys(parentDependentModules)) {
649
- if (getParentModules(dependentId)[childId]) {
650
- knownCjsModuleTypes[dependentId] = IS_WRAPPED_COMMONJS;
651
- }
652
- }
653
- }
654
- } else {
655
- // This makes sure the current transform handler waits for all direct dependencies to be
656
- // loaded and transformed and therefore for all transitive CommonJS dependencies to be
657
- // loaded as well so that all cycles have been found and knownCjsModuleTypes is reliable.
658
- await rollupContext.load(resolved);
659
- }
705
+ parentMeta.requires.push({ resolved, isConditional });
706
+ await setTypesForRequiredModules(parentId, resolved, isConditional, rollupContext.load);
660
707
  return { id: childId, allowProxy: true };
661
708
  })
662
709
  );
663
- return {
664
- requireTargets: requireTargets.map(({ id: dependencyId, allowProxy }, index) => {
665
- const isCommonJS = knownCjsModuleTypes[dependencyId];
666
- return {
667
- source: sources[index].source,
668
- id: allowProxy
669
- ? isCommonJS === IS_WRAPPED_COMMONJS
670
- ? wrapId(dependencyId, WRAPPED_SUFFIX)
671
- : wrapId(dependencyId, PROXY_SUFFIX)
672
- : dependencyId,
673
- isCommonJS
674
- };
675
- }),
676
- usesRequireWrapper: knownCjsModuleTypes[parentId] === IS_WRAPPED_COMMONJS
677
- };
710
+ parentMeta.isCommonJS = getTypeForFullyAnalyzedModule(parentId);
711
+ return requireTargets.map(({ id: dependencyId, allowProxy }, index) => {
712
+ // eslint-disable-next-line no-multi-assign
713
+ const isCommonJS = (parentMeta.isRequiredCommonJS[
714
+ dependencyId
715
+ ] = getTypeForFullyAnalyzedModule(dependencyId));
716
+ return {
717
+ source: sources[index].source,
718
+ id: allowProxy
719
+ ? isCommonJS === IS_WRAPPED_COMMONJS
720
+ ? wrapId(dependencyId, WRAPPED_SUFFIX)
721
+ : wrapId(dependencyId, PROXY_SUFFIX)
722
+ : dependencyId,
723
+ isCommonJS
724
+ };
725
+ });
678
726
  }
679
727
  };
680
728
  }
681
729
 
682
- function validateRollupVersion(rollupVersion, peerDependencyVersion) {
683
- const [major, minor] = rollupVersion.split('.').map(Number);
684
- const versionRegexp = /\^(\d+\.\d+)\.\d+/g;
730
+ function validateVersion(actualVersion, peerDependencyVersion, name) {
731
+ const versionRegexp = /\^(\d+\.\d+\.\d+)/g;
685
732
  let minMajor = Infinity;
686
733
  let minMinor = Infinity;
734
+ let minPatch = Infinity;
687
735
  let foundVersion;
688
736
  // eslint-disable-next-line no-cond-assign
689
737
  while ((foundVersion = versionRegexp.exec(peerDependencyVersion))) {
690
- const [foundMajor, foundMinor] = foundVersion[1].split('.').map(Number);
738
+ const [foundMajor, foundMinor, foundPatch] = foundVersion[1].split('.').map(Number);
691
739
  if (foundMajor < minMajor) {
692
740
  minMajor = foundMajor;
693
741
  minMinor = foundMinor;
742
+ minPatch = foundPatch;
694
743
  }
695
744
  }
696
- if (major < minMajor || (major === minMajor && minor < minMinor)) {
745
+ if (!actualVersion) {
697
746
  throw new Error(
698
- `Insufficient Rollup version: "@rollup/plugin-commonjs" requires at least rollup@${minMajor}.${minMinor} but found rollup@${rollupVersion}.`
747
+ `Insufficient ${name} version: "@rollup/plugin-commonjs" requires at least ${name}@${minMajor}.${minMinor}.${minPatch}.`
748
+ );
749
+ }
750
+ const [major, minor, patch] = actualVersion.split('.').map(Number);
751
+ if (
752
+ major < minMajor ||
753
+ (major === minMajor && (minor < minMinor || (minor === minMinor && patch < minPatch)))
754
+ ) {
755
+ throw new Error(
756
+ `Insufficient ${name} version: "@rollup/plugin-commonjs" requires at least ${name}@${minMajor}.${minMinor}.${minPatch} but found ${name}@${actualVersion}.`
699
757
  );
700
758
  }
701
759
  }
@@ -1138,17 +1196,20 @@ function getRequireHandlers() {
1138
1196
  exportsName,
1139
1197
  id,
1140
1198
  exportMode,
1141
- resolveRequireSourcesAndGetMeta,
1199
+ resolveRequireSourcesAndUpdateMeta,
1142
1200
  needsRequireWrapper,
1143
1201
  isEsModule,
1144
- usesRequire,
1145
- getIgnoreTryCatchRequireStatementMode
1202
+ isDynamicRequireModulesEnabled,
1203
+ getIgnoreTryCatchRequireStatementMode,
1204
+ commonjsMeta
1146
1205
  ) {
1147
1206
  const imports = [];
1148
1207
  imports.push(`import * as ${helpersName} from "${HELPERS_ID}";`);
1149
- if (usesRequire) {
1208
+ if (dynamicRequireName) {
1150
1209
  imports.push(
1151
- `import { commonjsRequire as ${dynamicRequireName} } from "${DYNAMIC_MODULES_ID}";`
1210
+ `import { ${
1211
+ isDynamicRequireModulesEnabled ? CREATE_COMMONJS_REQUIRE_EXPORT : COMMONJS_REQUIRE_EXPORT
1212
+ } as ${dynamicRequireName} } from "${DYNAMIC_MODULES_ID}";`
1152
1213
  );
1153
1214
  }
1154
1215
  if (exportMode === 'module') {
@@ -1163,9 +1224,10 @@ function getRequireHandlers() {
1163
1224
  );
1164
1225
  }
1165
1226
  const requiresBySource = collectSources(requireExpressions);
1166
- const { requireTargets, usesRequireWrapper } = await resolveRequireSourcesAndGetMeta(
1227
+ const requireTargets = await resolveRequireSourcesAndUpdateMeta(
1167
1228
  id,
1168
1229
  needsRequireWrapper ? IS_WRAPPED_COMMONJS : !isEsModule,
1230
+ commonjsMeta,
1169
1231
  Object.keys(requiresBySource).map((source) => {
1170
1232
  return {
1171
1233
  source,
@@ -1180,10 +1242,7 @@ function getRequireHandlers() {
1180
1242
  getIgnoreTryCatchRequireStatementMode,
1181
1243
  magicString
1182
1244
  );
1183
- return {
1184
- importBlock: imports.length ? `${imports.join('\n')}\n\n` : '',
1185
- usesRequireWrapper
1186
- };
1245
+ return imports.length ? `${imports.join('\n')}\n\n` : '';
1187
1246
  }
1188
1247
 
1189
1248
  return {
@@ -1286,9 +1345,10 @@ async function transformCommonjs(
1286
1345
  astCache,
1287
1346
  defaultIsModuleExports,
1288
1347
  needsRequireWrapper,
1289
- resolveRequireSourcesAndGetMeta,
1348
+ resolveRequireSourcesAndUpdateMeta,
1290
1349
  isRequired,
1291
- checkDynamicRequire
1350
+ checkDynamicRequire,
1351
+ commonjsMeta
1292
1352
  ) {
1293
1353
  const ast = astCache || tryParse(parse, code, id);
1294
1354
  const magicString = new MagicString__default["default"](code);
@@ -1329,6 +1389,7 @@ async function transformCommonjs(
1329
1389
  const topLevelDefineCompiledEsmExpressions = [];
1330
1390
  const replacedGlobal = [];
1331
1391
  const replacedDynamicRequires = [];
1392
+ const importedVariables = new Set();
1332
1393
 
1333
1394
  estreeWalker.walk(ast, {
1334
1395
  enter(node, parent) {
@@ -1434,20 +1495,19 @@ async function transformCommonjs(
1434
1495
  isRequire(node.callee.object, scope) &&
1435
1496
  node.callee.property.name === 'resolve'
1436
1497
  ) {
1437
- checkDynamicRequire();
1498
+ checkDynamicRequire(node.start);
1438
1499
  uses.require = true;
1439
1500
  const requireNode = node.callee.object;
1440
- magicString.appendLeft(
1441
- node.end - 1,
1442
- `,${JSON.stringify(
1443
- path.dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath
1444
- )}`
1445
- );
1446
1501
  replacedDynamicRequires.push(requireNode);
1447
1502
  return;
1448
1503
  }
1449
1504
 
1450
1505
  if (!isRequireExpression(node, scope)) {
1506
+ const keypath = getKeypath(node.callee);
1507
+ if (keypath && importedVariables.has(keypath.name)) {
1508
+ // Heuristic to deoptimize requires after a required function has been called
1509
+ currentConditionalNodeEnd = Infinity;
1510
+ }
1451
1511
  return;
1452
1512
  }
1453
1513
 
@@ -1456,15 +1516,9 @@ async function transformCommonjs(
1456
1516
 
1457
1517
  if (hasDynamicArguments(node)) {
1458
1518
  if (isDynamicRequireModulesEnabled) {
1459
- magicString.appendLeft(
1460
- node.end - 1,
1461
- `, ${JSON.stringify(
1462
- path.dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath
1463
- )}`
1464
- );
1519
+ checkDynamicRequire(node.start);
1465
1520
  }
1466
1521
  if (!ignoreDynamicRequires) {
1467
- checkDynamicRequire();
1468
1522
  replacedDynamicRequires.push(node.callee);
1469
1523
  }
1470
1524
  return;
@@ -1482,6 +1536,11 @@ async function transformCommonjs(
1482
1536
  currentConditionalNodeEnd !== null,
1483
1537
  parent.type === 'ExpressionStatement' ? parent : node
1484
1538
  );
1539
+ if (parent.type === 'VariableDeclarator' && parent.id.type === 'Identifier') {
1540
+ for (const name of pluginutils.extractAssignedNames(parent.id)) {
1541
+ importedVariables.add(name);
1542
+ }
1543
+ }
1485
1544
  }
1486
1545
  return;
1487
1546
  }
@@ -1522,7 +1581,6 @@ async function transformCommonjs(
1522
1581
  return;
1523
1582
  }
1524
1583
  if (!ignoreDynamicRequires) {
1525
- checkDynamicRequire();
1526
1584
  if (isShorthandProperty(parent)) {
1527
1585
  magicString.prependRight(node.start, 'require: ');
1528
1586
  }
@@ -1606,9 +1664,10 @@ async function transformCommonjs(
1606
1664
  if (scope.contains(flattened.name)) return;
1607
1665
 
1608
1666
  if (
1609
- flattened.keypath === 'module.exports' ||
1610
- flattened.keypath === 'module' ||
1611
- flattened.keypath === 'exports'
1667
+ !isEsModule &&
1668
+ (flattened.keypath === 'module.exports' ||
1669
+ flattened.keypath === 'module' ||
1670
+ flattened.keypath === 'exports')
1612
1671
  ) {
1613
1672
  magicString.overwrite(node.start, node.end, `'object'`, {
1614
1673
  storeName: false
@@ -1636,7 +1695,13 @@ async function transformCommonjs(
1636
1695
  const requireName = deconflict([scope], globals, `require${capitalize(nameBase)}`);
1637
1696
  const isRequiredName = deconflict([scope], globals, `hasRequired${capitalize(nameBase)}`);
1638
1697
  const helpersName = deconflict([scope], globals, 'commonjsHelpers');
1639
- const dynamicRequireName = deconflict([scope], globals, 'commonjsRequire');
1698
+ const dynamicRequireName =
1699
+ replacedDynamicRequires.length > 0 &&
1700
+ deconflict(
1701
+ [scope],
1702
+ globals,
1703
+ isDynamicRequireModulesEnabled ? CREATE_COMMONJS_REQUIRE_EXPORT : COMMONJS_REQUIRE_EXPORT
1704
+ );
1640
1705
  const deconflictedExportNames = Object.create(null);
1641
1706
  for (const [exportName, { scopes }] of exportsAssignmentsByName) {
1642
1707
  deconflictedExportNames[exportName] = deconflict([...scopes], globals, exportName);
@@ -1648,10 +1713,17 @@ async function transformCommonjs(
1648
1713
  });
1649
1714
  }
1650
1715
  for (const node of replacedDynamicRequires) {
1651
- magicString.overwrite(node.start, node.end, dynamicRequireName, {
1652
- contentOnly: true,
1653
- storeName: true
1654
- });
1716
+ magicString.overwrite(
1717
+ node.start,
1718
+ node.end,
1719
+ isDynamicRequireModulesEnabled
1720
+ ? `${dynamicRequireName}(${JSON.stringify(virtualDynamicRequirePath)})`
1721
+ : dynamicRequireName,
1722
+ {
1723
+ contentOnly: true,
1724
+ storeName: true
1725
+ }
1726
+ );
1655
1727
  }
1656
1728
 
1657
1729
  // We cannot wrap ES/mixed modules
@@ -1671,7 +1743,7 @@ async function transformCommonjs(
1671
1743
  ) &&
1672
1744
  (ignoreGlobal || !uses.global)
1673
1745
  ) {
1674
- return { meta: { commonjs: { isCommonJS: false, isMixedModule: false } } };
1746
+ return { meta: { commonjs: { isCommonJS: false } } };
1675
1747
  }
1676
1748
 
1677
1749
  let leadingComment = '';
@@ -1693,7 +1765,7 @@ async function transformCommonjs(
1693
1765
  ? 'exports'
1694
1766
  : 'module';
1695
1767
 
1696
- const { importBlock, usesRequireWrapper } = await rewriteRequireExpressionsAndGetImportBlock(
1768
+ const importBlock = await rewriteRequireExpressionsAndGetImportBlock(
1697
1769
  magicString,
1698
1770
  topLevelDeclarations,
1699
1771
  reassignedNames,
@@ -1703,12 +1775,14 @@ async function transformCommonjs(
1703
1775
  exportsName,
1704
1776
  id,
1705
1777
  exportMode,
1706
- resolveRequireSourcesAndGetMeta,
1778
+ resolveRequireSourcesAndUpdateMeta,
1707
1779
  needsRequireWrapper,
1708
1780
  isEsModule,
1709
- uses.require,
1710
- getIgnoreTryCatchRequireStatementMode
1781
+ isDynamicRequireModulesEnabled,
1782
+ getIgnoreTryCatchRequireStatementMode,
1783
+ commonjsMeta
1711
1784
  );
1785
+ const usesRequireWrapper = commonjsMeta.isCommonJS === IS_WRAPPED_COMMONJS;
1712
1786
  const exportBlock = isEsModule
1713
1787
  ? ''
1714
1788
  : rewriteExportsAndGetExportsBlock(
@@ -1761,15 +1835,12 @@ function ${requireName} () {
1761
1835
  code: magicString.toString(),
1762
1836
  map: sourceMap ? magicString.generateMap() : null,
1763
1837
  syntheticNamedExports: isEsModule || usesRequireWrapper ? false : '__moduleExports',
1764
- meta: {
1765
- commonjs: {
1766
- isCommonJS: !isEsModule && (usesRequireWrapper ? IS_WRAPPED_COMMONJS : true),
1767
- isMixedModule: isEsModule
1768
- }
1769
- }
1838
+ meta: { commonjs: commonjsMeta }
1770
1839
  };
1771
1840
  }
1772
1841
 
1842
+ const PLUGIN_NAME = 'commonjs';
1843
+
1773
1844
  function commonjs(options = {}) {
1774
1845
  const {
1775
1846
  ignoreGlobal,
@@ -1797,11 +1868,6 @@ function commonjs(options = {}) {
1797
1868
  const defaultIsModuleExports =
1798
1869
  typeof options.defaultIsModuleExports === 'boolean' ? options.defaultIsModuleExports : 'auto';
1799
1870
 
1800
- const {
1801
- resolveRequireSourcesAndGetMeta,
1802
- getWrappedIds,
1803
- isRequiredId
1804
- } = getResolveRequireSourcesAndGetMeta(extensions, detectCyclesAndConditional);
1805
1871
  const dynamicRequireRoot =
1806
1872
  typeof options.dynamicRequireRoot === 'string'
1807
1873
  ? path.resolve(options.dynamicRequireRoot)
@@ -1812,9 +1878,6 @@ function commonjs(options = {}) {
1812
1878
  );
1813
1879
  const isDynamicRequireModulesEnabled = dynamicRequireModules.size > 0;
1814
1880
 
1815
- const esModulesWithDefaultExport = new Set();
1816
- const esModulesWithNamedExports = new Set();
1817
-
1818
1881
  const ignoreRequire =
1819
1882
  typeof options.ignore === 'function'
1820
1883
  ? options.ignore
@@ -1842,41 +1905,50 @@ function commonjs(options = {}) {
1842
1905
 
1843
1906
  const sourceMap = options.sourceMap !== false;
1844
1907
 
1908
+ // Initialized in buildStart
1909
+ let requireResolver;
1910
+
1845
1911
  function transformAndCheckExports(code, id) {
1846
1912
  const { isEsModule, hasDefaultExport, hasNamedExports, ast } = analyzeTopLevelStatements(
1847
1913
  this.parse,
1848
1914
  code,
1849
1915
  id
1850
1916
  );
1917
+
1918
+ const commonjsMeta = this.getModuleInfo(id).meta.commonjs || {};
1851
1919
  if (hasDefaultExport) {
1852
- esModulesWithDefaultExport.add(id);
1920
+ commonjsMeta.hasDefaultExport = true;
1853
1921
  }
1854
1922
  if (hasNamedExports) {
1855
- esModulesWithNamedExports.add(id);
1923
+ commonjsMeta.hasNamedExports = true;
1856
1924
  }
1857
1925
 
1858
1926
  if (
1859
1927
  !dynamicRequireModules.has(normalizePathSlashes(id)) &&
1860
- (!(hasCjsKeywords(code, ignoreGlobal) || isRequiredId(id)) ||
1928
+ (!(hasCjsKeywords(code, ignoreGlobal) || requireResolver.isRequiredId(id)) ||
1861
1929
  (isEsModule && !options.transformMixedEsModules))
1862
1930
  ) {
1863
- return { meta: { commonjs: { isCommonJS: false } } };
1931
+ commonjsMeta.isCommonJS = false;
1932
+ return { meta: { commonjs: commonjsMeta } };
1864
1933
  }
1865
1934
 
1866
1935
  const needsRequireWrapper =
1867
1936
  !isEsModule &&
1868
1937
  (dynamicRequireModules.has(normalizePathSlashes(id)) || strictRequiresFilter(id));
1869
1938
 
1870
- const checkDynamicRequire = () => {
1939
+ const checkDynamicRequire = (position) => {
1871
1940
  if (id.indexOf(dynamicRequireRoot) !== 0) {
1872
- this.error({
1873
- code: 'DYNAMIC_REQUIRE_OUTSIDE_ROOT',
1874
- id,
1875
- dynamicRequireRoot,
1876
- message: `"${id}" contains dynamic require statements but it is not within the current dynamicRequireRoot "${dynamicRequireRoot}". You should set dynamicRequireRoot to "${path.dirname(
1877
- id
1878
- )}" or one of its parent directories.`
1879
- });
1941
+ this.error(
1942
+ {
1943
+ code: 'DYNAMIC_REQUIRE_OUTSIDE_ROOT',
1944
+ id,
1945
+ dynamicRequireRoot,
1946
+ message: `"${id}" contains dynamic require statements but it is not within the current dynamicRequireRoot "${dynamicRequireRoot}". You should set dynamicRequireRoot to "${path.dirname(
1947
+ id
1948
+ )}" or one of its parent directories.`
1949
+ },
1950
+ position
1951
+ );
1880
1952
  }
1881
1953
  };
1882
1954
 
@@ -1896,14 +1968,15 @@ function commonjs(options = {}) {
1896
1968
  ast,
1897
1969
  defaultIsModuleExports,
1898
1970
  needsRequireWrapper,
1899
- resolveRequireSourcesAndGetMeta(this),
1900
- isRequiredId(id),
1901
- checkDynamicRequire
1971
+ requireResolver.resolveRequireSourcesAndUpdateMeta(this),
1972
+ requireResolver.isRequiredId(id),
1973
+ checkDynamicRequire,
1974
+ commonjsMeta
1902
1975
  );
1903
1976
  }
1904
1977
 
1905
1978
  return {
1906
- name: 'commonjs',
1979
+ name: PLUGIN_NAME,
1907
1980
 
1908
1981
  version,
1909
1982
 
@@ -1911,7 +1984,7 @@ function commonjs(options = {}) {
1911
1984
  // We inject the resolver in the beginning so that "catch-all-resolver" like node-resolver
1912
1985
  // do not prevent our plugin from resolving entry points ot proxies.
1913
1986
  const plugins = Array.isArray(rawOptions.plugins)
1914
- ? rawOptions.plugins
1987
+ ? [...rawOptions.plugins]
1915
1988
  : rawOptions.plugins
1916
1989
  ? [rawOptions.plugins]
1917
1990
  : [];
@@ -1922,18 +1995,23 @@ function commonjs(options = {}) {
1922
1995
  return { ...rawOptions, plugins };
1923
1996
  },
1924
1997
 
1925
- buildStart() {
1926
- validateRollupVersion(this.meta.rollupVersion, peerDependencies.rollup);
1998
+ buildStart({ plugins }) {
1999
+ validateVersion(this.meta.rollupVersion, peerDependencies.rollup, 'rollup');
2000
+ const nodeResolve = plugins.find(({ name }) => name === 'node-resolve');
2001
+ if (nodeResolve) {
2002
+ validateVersion(nodeResolve.version, '^13.0.6', '@rollup/plugin-node-resolve');
2003
+ }
1927
2004
  if (options.namedExports != null) {
1928
2005
  this.warn(
1929
2006
  'The namedExports option from "@rollup/plugin-commonjs" is deprecated. Named exports are now handled automatically.'
1930
2007
  );
1931
2008
  }
2009
+ requireResolver = getRequireResolver(extensions, detectCyclesAndConditional);
1932
2010
  },
1933
2011
 
1934
2012
  buildEnd() {
1935
2013
  if (options.strictRequires === 'debug') {
1936
- const wrappedIds = getWrappedIds();
2014
+ const wrappedIds = requireResolver.getWrappedIds();
1937
2015
  if (wrappedIds.length) {
1938
2016
  this.warn({
1939
2017
  code: 'WRAPPED_IDS',
@@ -1982,6 +2060,15 @@ function commonjs(options = {}) {
1982
2060
  );
1983
2061
  }
1984
2062
 
2063
+ // entry suffix is just appended to not mess up relative external resolution
2064
+ if (id.endsWith(ENTRY_SUFFIX)) {
2065
+ return getEntryProxy(
2066
+ id.slice(0, -ENTRY_SUFFIX.length),
2067
+ defaultIsModuleExports,
2068
+ this.getModuleInfo
2069
+ );
2070
+ }
2071
+
1985
2072
  if (isWrappedId(id, ES_IMPORT_SUFFIX)) {
1986
2073
  return getEsImportProxy(unwrapId(id, ES_IMPORT_SUFFIX), defaultIsModuleExports);
1987
2074
  }
@@ -1997,18 +2084,16 @@ function commonjs(options = {}) {
1997
2084
 
1998
2085
  if (isWrappedId(id, PROXY_SUFFIX)) {
1999
2086
  const actualId = unwrapId(id, PROXY_SUFFIX);
2000
- return getStaticRequireProxy(
2001
- actualId,
2002
- getRequireReturnsDefault(actualId),
2003
- esModulesWithDefaultExport,
2004
- esModulesWithNamedExports,
2005
- this.load
2006
- );
2087
+ return getStaticRequireProxy(actualId, getRequireReturnsDefault(actualId), this.load);
2007
2088
  }
2008
2089
 
2009
2090
  return null;
2010
2091
  },
2011
2092
 
2093
+ shouldTransformCachedModule(...args) {
2094
+ return requireResolver.shouldTransformCachedModule.call(this, ...args);
2095
+ },
2096
+
2012
2097
  transform(code, id) {
2013
2098
  const extName = path.extname(id);
2014
2099
  if (extName !== '.cjs' && (!filter(id) || !extensions.includes(extName))) {