@rollup/plugin-commonjs 22.0.0-0 → 22.0.0-12

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-0";
19
+ var version = "22.0.0-12";
20
20
  var peerDependencies = {
21
- rollup: "^2.60.0"
21
+ rollup: "^2.68.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`;
@@ -448,8 +462,7 @@ function getEsImportProxy(id, defaultIsModuleExports) {
448
462
  }
449
463
  return {
450
464
  code,
451
- syntheticNamedExports: '__moduleExports',
452
- meta: { commonjs: { isCommonJS: false } }
465
+ syntheticNamedExports: '__moduleExports'
453
466
  };
454
467
  }
455
468
 
@@ -487,11 +500,17 @@ function resolveExtensions(importee, importer, extensions) {
487
500
 
488
501
  function getResolveId(extensions) {
489
502
  return async function resolveId(importee, importer, resolveOptions) {
503
+ // We assume that all requires are pre-resolved
504
+ const customOptions = resolveOptions.custom;
505
+ if (customOptions && customOptions['node-resolve'] && customOptions['node-resolve'].isRequire) {
506
+ return null;
507
+ }
490
508
  if (isWrappedId(importee, WRAPPED_SUFFIX)) {
491
509
  return unwrapId(importee, WRAPPED_SUFFIX);
492
510
  }
493
511
 
494
512
  if (
513
+ importee.endsWith(ENTRY_SUFFIX) ||
495
514
  isWrappedId(importee, MODULE_SUFFIX) ||
496
515
  isWrappedId(importee, EXPORTS_SUFFIX) ||
497
516
  isWrappedId(importee, PROXY_SUFFIX) ||
@@ -506,9 +525,10 @@ function getResolveId(extensions) {
506
525
  if (importer) {
507
526
  if (
508
527
  importer === DYNAMIC_MODULES_ID ||
509
- // Except for exports, proxies are only importing resolved ids, no need to resolve again
528
+ // Proxies are only importing resolved ids, no need to resolve again
510
529
  isWrappedId(importer, PROXY_SUFFIX) ||
511
- isWrappedId(importer, ES_IMPORT_SUFFIX)
530
+ isWrappedId(importer, ES_IMPORT_SUFFIX) ||
531
+ importer.endsWith(ENTRY_SUFFIX)
512
532
  ) {
513
533
  return importee;
514
534
  }
@@ -528,36 +548,113 @@ function getResolveId(extensions) {
528
548
 
529
549
  // If this is an entry point or ESM import, we need to figure out if the importee is wrapped and
530
550
  // if that is the case, we need to add a proxy.
531
- const customOptions = resolveOptions.custom;
532
-
533
- // If this is a require, we do not need a proxy
534
- if (customOptions && customOptions['node-resolve'] && customOptions['node-resolve'].isRequire) {
535
- return null;
536
- }
537
-
538
551
  const resolved =
539
552
  (await this.resolve(importee, importer, Object.assign({ skipSelf: true }, resolveOptions))) ||
540
553
  resolveExtensions(importee, importer, extensions);
541
- if (!resolved || resolved.external) {
554
+ // Make sure that even if other plugins resolve again, we ignore our own proxies
555
+ if (
556
+ !resolved ||
557
+ resolved.external ||
558
+ resolved.id.endsWith(ENTRY_SUFFIX) ||
559
+ isWrappedId(resolved.id, ES_IMPORT_SUFFIX)
560
+ ) {
542
561
  return resolved;
543
562
  }
563
+ const moduleInfo = await this.load(resolved);
564
+ if (resolveOptions.isEntry) {
565
+ moduleInfo.moduleSideEffects = true;
566
+ // We must not precede entry proxies with a `\0` as that will mess up relative external resolution
567
+ return resolved.id + ENTRY_SUFFIX;
568
+ }
544
569
  const {
545
570
  meta: { commonjs: commonjsMeta }
546
- } = await this.load(resolved);
571
+ } = moduleInfo;
547
572
  if (commonjsMeta && commonjsMeta.isCommonJS === IS_WRAPPED_COMMONJS) {
548
- return wrapId(resolved.id, ES_IMPORT_SUFFIX);
573
+ return { id: wrapId(resolved.id, ES_IMPORT_SUFFIX), meta: { commonjs: { resolved } } };
549
574
  }
550
575
  return resolved;
551
576
  };
552
577
  }
553
578
 
554
- function getResolveRequireSourcesAndGetMeta(extensions, detectCyclesAndConditional) {
579
+ function getRequireResolver(extensions, detectCyclesAndConditional) {
555
580
  const knownCjsModuleTypes = Object.create(null);
556
581
  const requiredIds = Object.create(null);
557
582
  const unconditionallyRequiredIds = Object.create(null);
558
- const dependentModules = Object.create(null);
559
- const getDependentModules = (id) =>
560
- dependentModules[id] || (dependentModules[id] = Object.create(null));
583
+ const dependencies = Object.create(null);
584
+ const getDependencies = (id) => dependencies[id] || (dependencies[id] = new Set());
585
+
586
+ const isCyclic = (id) => {
587
+ const dependenciesToCheck = new Set(getDependencies(id));
588
+ for (const dependency of dependenciesToCheck) {
589
+ if (dependency === id) {
590
+ return true;
591
+ }
592
+ for (const childDependency of getDependencies(dependency)) {
593
+ dependenciesToCheck.add(childDependency);
594
+ }
595
+ }
596
+ return false;
597
+ };
598
+
599
+ // Once a module is listed here, its type (wrapped or not) is fixed and may
600
+ // not change for the rest of the current build, to not break already
601
+ // transformed modules.
602
+ const fullyAnalyzedModules = Object.create(null);
603
+
604
+ const getTypeForFullyAnalyzedModule = (id) => {
605
+ const knownType = knownCjsModuleTypes[id];
606
+ if (knownType !== true || !detectCyclesAndConditional || fullyAnalyzedModules[id]) {
607
+ return knownType;
608
+ }
609
+ if (isCyclic(id)) {
610
+ return (knownCjsModuleTypes[id] = IS_WRAPPED_COMMONJS);
611
+ }
612
+ return knownType;
613
+ };
614
+
615
+ const setInitialParentType = (id, initialCommonJSType) => {
616
+ // Fully analyzed modules may never change type
617
+ if (fullyAnalyzedModules[id]) {
618
+ return;
619
+ }
620
+ knownCjsModuleTypes[id] = initialCommonJSType;
621
+ if (
622
+ detectCyclesAndConditional &&
623
+ knownCjsModuleTypes[id] === true &&
624
+ requiredIds[id] &&
625
+ !unconditionallyRequiredIds[id]
626
+ ) {
627
+ knownCjsModuleTypes[id] = IS_WRAPPED_COMMONJS;
628
+ }
629
+ };
630
+
631
+ const analyzeRequiredModule = async (parentId, resolved, isConditional, loadModule) => {
632
+ const childId = resolved.id;
633
+ requiredIds[childId] = true;
634
+ if (!(isConditional || knownCjsModuleTypes[parentId] === IS_WRAPPED_COMMONJS)) {
635
+ unconditionallyRequiredIds[childId] = true;
636
+ }
637
+
638
+ getDependencies(parentId).add(childId);
639
+ if (!isCyclic(childId)) {
640
+ // This makes sure the current transform handler waits for all direct
641
+ // dependencies to be loaded and transformed and therefore for all
642
+ // transitive CommonJS dependencies to be loaded as well so that all
643
+ // cycles have been found and knownCjsModuleTypes is reliable.
644
+ await loadModule(resolved);
645
+ }
646
+ };
647
+
648
+ const getTypeForImportedModule = async (resolved, loadModule) => {
649
+ if (resolved.id in knownCjsModuleTypes) {
650
+ // This handles cyclic ES dependencies
651
+ return knownCjsModuleTypes[resolved.id];
652
+ }
653
+ const {
654
+ meta: { commonjs }
655
+ } = await loadModule(resolved);
656
+ return (commonjs && commonjs.isCommonJS) || false;
657
+ };
561
658
 
562
659
  return {
563
660
  getWrappedIds: () =>
@@ -565,19 +662,72 @@ function getResolveRequireSourcesAndGetMeta(extensions, detectCyclesAndCondition
565
662
  (id) => knownCjsModuleTypes[id] === IS_WRAPPED_COMMONJS
566
663
  ),
567
664
  isRequiredId: (id) => requiredIds[id],
568
- resolveRequireSourcesAndGetMeta: (rollupContext) => async (
665
+ async shouldTransformCachedModule({
666
+ id: parentId,
667
+ resolvedSources,
668
+ meta: { commonjs: parentMeta }
669
+ }) {
670
+ // We explicitly track ES modules to handle ciruclar imports
671
+ if (!(parentMeta && parentMeta.isCommonJS)) knownCjsModuleTypes[parentId] = false;
672
+ if (isWrappedId(parentId, ES_IMPORT_SUFFIX)) return false;
673
+ const parentRequires = parentMeta && parentMeta.requires;
674
+ if (parentRequires) {
675
+ setInitialParentType(parentId, parentMeta.initialCommonJSType);
676
+ await Promise.all(
677
+ parentRequires.map(({ resolved, isConditional }) =>
678
+ analyzeRequiredModule(parentId, resolved, isConditional, this.load)
679
+ )
680
+ );
681
+ if (getTypeForFullyAnalyzedModule(parentId) !== parentMeta.isCommonJS) {
682
+ return true;
683
+ }
684
+ for (const {
685
+ resolved: { id }
686
+ } of parentRequires) {
687
+ if (getTypeForFullyAnalyzedModule(id) !== parentMeta.isRequiredCommonJS[id]) {
688
+ return true;
689
+ }
690
+ }
691
+ // Now that we decided to go with the cached copy, neither the parent
692
+ // module nor any of its children may change types anymore
693
+ fullyAnalyzedModules[parentId] = true;
694
+ for (const {
695
+ resolved: { id }
696
+ } of parentRequires) {
697
+ fullyAnalyzedModules[id] = true;
698
+ }
699
+ }
700
+ const parentRequireSet = new Set((parentRequires || []).map(({ resolved: { id } }) => id));
701
+ return (
702
+ await Promise.all(
703
+ Object.keys(resolvedSources)
704
+ .map((source) => resolvedSources[source])
705
+ .filter(({ id }) => !parentRequireSet.has(id))
706
+ .map(async (resolved) => {
707
+ if (isWrappedId(resolved.id, ES_IMPORT_SUFFIX)) {
708
+ return (
709
+ (await getTypeForImportedModule(
710
+ (await this.load({ id: resolved.id })).meta.commonjs.resolved,
711
+ this.load
712
+ )) !== IS_WRAPPED_COMMONJS
713
+ );
714
+ }
715
+ return (await getTypeForImportedModule(resolved, this.load)) === IS_WRAPPED_COMMONJS;
716
+ })
717
+ )
718
+ ).some((shouldTransform) => shouldTransform);
719
+ },
720
+ /* eslint-disable no-param-reassign */
721
+ resolveRequireSourcesAndUpdateMeta: (rollupContext) => async (
569
722
  parentId,
570
723
  isParentCommonJS,
724
+ parentMeta,
571
725
  sources
572
726
  ) => {
573
- knownCjsModuleTypes[parentId] = knownCjsModuleTypes[parentId] || isParentCommonJS;
574
- if (
575
- knownCjsModuleTypes[parentId] &&
576
- requiredIds[parentId] &&
577
- !unconditionallyRequiredIds[parentId]
578
- ) {
579
- knownCjsModuleTypes[parentId] = IS_WRAPPED_COMMONJS;
580
- }
727
+ parentMeta.initialCommonJSType = isParentCommonJS;
728
+ parentMeta.requires = [];
729
+ parentMeta.isRequiredCommonJS = Object.create(null);
730
+ setInitialParentType(parentId, isParentCommonJS);
581
731
  const requireTargets = await Promise.all(
582
732
  sources.map(async ({ source, isConditional }) => {
583
733
  // Never analyze or proxy internal modules
@@ -586,9 +736,7 @@ function getResolveRequireSourcesAndGetMeta(extensions, detectCyclesAndCondition
586
736
  }
587
737
  const resolved =
588
738
  (await rollupContext.resolve(source, parentId, {
589
- custom: {
590
- 'node-resolve': { isRequire: true }
591
- }
739
+ custom: { 'node-resolve': { isRequire: true } }
592
740
  })) || resolveExtensions(source, parentId, extensions);
593
741
  if (!resolved) {
594
742
  return { id: wrapId(source, EXTERNAL_SUFFIX), allowProxy: false };
@@ -597,78 +745,60 @@ function getResolveRequireSourcesAndGetMeta(extensions, detectCyclesAndCondition
597
745
  if (resolved.external) {
598
746
  return { id: wrapId(childId, EXTERNAL_SUFFIX), allowProxy: false };
599
747
  }
600
- requiredIds[childId] = true;
601
- if (
602
- !(
603
- detectCyclesAndConditional &&
604
- (isConditional || knownCjsModuleTypes[parentId] === IS_WRAPPED_COMMONJS)
605
- )
606
- ) {
607
- unconditionallyRequiredIds[childId] = true;
608
- }
609
- const parentDependentModules = getDependentModules(parentId);
610
- const childDependentModules = getDependentModules(childId);
611
- childDependentModules[parentId] = true;
612
- for (const dependentId of Object.keys(parentDependentModules)) {
613
- childDependentModules[dependentId] = true;
614
- }
615
- if (parentDependentModules[childId]) {
616
- // If we depend on one of our dependencies, we have a cycle. Then all modules that
617
- // we depend on that also depend on the same module are part of a cycle as well.
618
- if (detectCyclesAndConditional && isParentCommonJS) {
619
- knownCjsModuleTypes[parentId] = IS_WRAPPED_COMMONJS;
620
- knownCjsModuleTypes[childId] = IS_WRAPPED_COMMONJS;
621
- for (const dependentId of Object.keys(parentDependentModules)) {
622
- if (getDependentModules(dependentId)[childId]) {
623
- knownCjsModuleTypes[dependentId] = IS_WRAPPED_COMMONJS;
624
- }
625
- }
626
- }
627
- } else {
628
- // This makes sure the current transform handler waits for all direct dependencies to be
629
- // loaded and transformed and therefore for all transitive CommonJS dependencies to be
630
- // loaded as well so that all cycles have been found and knownCjsModuleTypes is reliable.
631
- await rollupContext.load(resolved);
632
- }
748
+ parentMeta.requires.push({ resolved, isConditional });
749
+ await analyzeRequiredModule(parentId, resolved, isConditional, rollupContext.load);
633
750
  return { id: childId, allowProxy: true };
634
751
  })
635
752
  );
636
- return {
637
- requireTargets: requireTargets.map(({ id: dependencyId, allowProxy }, index) => {
638
- const isCommonJS = knownCjsModuleTypes[dependencyId];
639
- return {
640
- source: sources[index].source,
641
- id: allowProxy
642
- ? isCommonJS === IS_WRAPPED_COMMONJS
643
- ? wrapId(dependencyId, WRAPPED_SUFFIX)
644
- : wrapId(dependencyId, PROXY_SUFFIX)
645
- : dependencyId,
646
- isCommonJS
647
- };
648
- }),
649
- usesRequireWrapper: knownCjsModuleTypes[parentId] === IS_WRAPPED_COMMONJS
650
- };
753
+ parentMeta.isCommonJS = getTypeForFullyAnalyzedModule(parentId);
754
+ fullyAnalyzedModules[parentId] = true;
755
+ return requireTargets.map(({ id: dependencyId, allowProxy }, index) => {
756
+ // eslint-disable-next-line no-multi-assign
757
+ const isCommonJS = (parentMeta.isRequiredCommonJS[
758
+ dependencyId
759
+ ] = getTypeForFullyAnalyzedModule(dependencyId));
760
+ fullyAnalyzedModules[dependencyId] = true;
761
+ return {
762
+ source: sources[index].source,
763
+ id: allowProxy
764
+ ? isCommonJS === IS_WRAPPED_COMMONJS
765
+ ? wrapId(dependencyId, WRAPPED_SUFFIX)
766
+ : wrapId(dependencyId, PROXY_SUFFIX)
767
+ : dependencyId,
768
+ isCommonJS
769
+ };
770
+ });
651
771
  }
652
772
  };
653
773
  }
654
774
 
655
- function validateRollupVersion(rollupVersion, peerDependencyVersion) {
656
- const [major, minor] = rollupVersion.split('.').map(Number);
657
- const versionRegexp = /\^(\d+\.\d+)\.\d+/g;
775
+ function validateVersion(actualVersion, peerDependencyVersion, name) {
776
+ const versionRegexp = /\^(\d+\.\d+\.\d+)/g;
658
777
  let minMajor = Infinity;
659
778
  let minMinor = Infinity;
779
+ let minPatch = Infinity;
660
780
  let foundVersion;
661
781
  // eslint-disable-next-line no-cond-assign
662
782
  while ((foundVersion = versionRegexp.exec(peerDependencyVersion))) {
663
- const [foundMajor, foundMinor] = foundVersion[1].split('.').map(Number);
783
+ const [foundMajor, foundMinor, foundPatch] = foundVersion[1].split('.').map(Number);
664
784
  if (foundMajor < minMajor) {
665
785
  minMajor = foundMajor;
666
786
  minMinor = foundMinor;
787
+ minPatch = foundPatch;
667
788
  }
668
789
  }
669
- if (major < minMajor || (major === minMajor && minor < minMinor)) {
790
+ if (!actualVersion) {
791
+ throw new Error(
792
+ `Insufficient ${name} version: "@rollup/plugin-commonjs" requires at least ${name}@${minMajor}.${minMinor}.${minPatch}.`
793
+ );
794
+ }
795
+ const [major, minor, patch] = actualVersion.split('.').map(Number);
796
+ if (
797
+ major < minMajor ||
798
+ (major === minMajor && (minor < minMinor || (minor === minMinor && patch < minPatch)))
799
+ ) {
670
800
  throw new Error(
671
- `Insufficient Rollup version: "@rollup/plugin-commonjs" requires at least rollup@${minMajor}.${minMinor} but found rollup@${rollupVersion}.`
801
+ `Insufficient ${name} version: "@rollup/plugin-commonjs" requires at least ${name}@${minMajor}.${minMinor}.${minPatch} but found ${name}@${actualVersion}.`
672
802
  );
673
803
  }
674
804
  }
@@ -1111,17 +1241,20 @@ function getRequireHandlers() {
1111
1241
  exportsName,
1112
1242
  id,
1113
1243
  exportMode,
1114
- resolveRequireSourcesAndGetMeta,
1244
+ resolveRequireSourcesAndUpdateMeta,
1115
1245
  needsRequireWrapper,
1116
1246
  isEsModule,
1117
- usesRequire,
1118
- getIgnoreTryCatchRequireStatementMode
1247
+ isDynamicRequireModulesEnabled,
1248
+ getIgnoreTryCatchRequireStatementMode,
1249
+ commonjsMeta
1119
1250
  ) {
1120
1251
  const imports = [];
1121
1252
  imports.push(`import * as ${helpersName} from "${HELPERS_ID}";`);
1122
- if (usesRequire) {
1253
+ if (dynamicRequireName) {
1123
1254
  imports.push(
1124
- `import { commonjsRequire as ${dynamicRequireName} } from "${DYNAMIC_MODULES_ID}";`
1255
+ `import { ${
1256
+ isDynamicRequireModulesEnabled ? CREATE_COMMONJS_REQUIRE_EXPORT : COMMONJS_REQUIRE_EXPORT
1257
+ } as ${dynamicRequireName} } from "${DYNAMIC_MODULES_ID}";`
1125
1258
  );
1126
1259
  }
1127
1260
  if (exportMode === 'module') {
@@ -1136,9 +1269,10 @@ function getRequireHandlers() {
1136
1269
  );
1137
1270
  }
1138
1271
  const requiresBySource = collectSources(requireExpressions);
1139
- const { requireTargets, usesRequireWrapper } = await resolveRequireSourcesAndGetMeta(
1272
+ const requireTargets = await resolveRequireSourcesAndUpdateMeta(
1140
1273
  id,
1141
1274
  needsRequireWrapper ? IS_WRAPPED_COMMONJS : !isEsModule,
1275
+ commonjsMeta,
1142
1276
  Object.keys(requiresBySource).map((source) => {
1143
1277
  return {
1144
1278
  source,
@@ -1153,10 +1287,7 @@ function getRequireHandlers() {
1153
1287
  getIgnoreTryCatchRequireStatementMode,
1154
1288
  magicString
1155
1289
  );
1156
- return {
1157
- importBlock: imports.length ? `${imports.join('\n')}\n\n` : '',
1158
- usesRequireWrapper
1159
- };
1290
+ return imports.length ? `${imports.join('\n')}\n\n` : '';
1160
1291
  }
1161
1292
 
1162
1293
  return {
@@ -1259,9 +1390,10 @@ async function transformCommonjs(
1259
1390
  astCache,
1260
1391
  defaultIsModuleExports,
1261
1392
  needsRequireWrapper,
1262
- resolveRequireSourcesAndGetMeta,
1393
+ resolveRequireSourcesAndUpdateMeta,
1263
1394
  isRequired,
1264
- checkDynamicRequire
1395
+ checkDynamicRequire,
1396
+ commonjsMeta
1265
1397
  ) {
1266
1398
  const ast = astCache || tryParse(parse, code, id);
1267
1399
  const magicString = new MagicString__default["default"](code);
@@ -1302,6 +1434,7 @@ async function transformCommonjs(
1302
1434
  const topLevelDefineCompiledEsmExpressions = [];
1303
1435
  const replacedGlobal = [];
1304
1436
  const replacedDynamicRequires = [];
1437
+ const importedVariables = new Set();
1305
1438
 
1306
1439
  estreeWalker.walk(ast, {
1307
1440
  enter(node, parent) {
@@ -1407,20 +1540,19 @@ async function transformCommonjs(
1407
1540
  isRequire(node.callee.object, scope) &&
1408
1541
  node.callee.property.name === 'resolve'
1409
1542
  ) {
1410
- checkDynamicRequire();
1543
+ checkDynamicRequire(node.start);
1411
1544
  uses.require = true;
1412
1545
  const requireNode = node.callee.object;
1413
- magicString.appendLeft(
1414
- node.end - 1,
1415
- `,${JSON.stringify(
1416
- path.dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath
1417
- )}`
1418
- );
1419
1546
  replacedDynamicRequires.push(requireNode);
1420
1547
  return;
1421
1548
  }
1422
1549
 
1423
1550
  if (!isRequireExpression(node, scope)) {
1551
+ const keypath = getKeypath(node.callee);
1552
+ if (keypath && importedVariables.has(keypath.name)) {
1553
+ // Heuristic to deoptimize requires after a required function has been called
1554
+ currentConditionalNodeEnd = Infinity;
1555
+ }
1424
1556
  return;
1425
1557
  }
1426
1558
 
@@ -1429,15 +1561,9 @@ async function transformCommonjs(
1429
1561
 
1430
1562
  if (hasDynamicArguments(node)) {
1431
1563
  if (isDynamicRequireModulesEnabled) {
1432
- magicString.appendLeft(
1433
- node.end - 1,
1434
- `, ${JSON.stringify(
1435
- path.dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath
1436
- )}`
1437
- );
1564
+ checkDynamicRequire(node.start);
1438
1565
  }
1439
1566
  if (!ignoreDynamicRequires) {
1440
- checkDynamicRequire();
1441
1567
  replacedDynamicRequires.push(node.callee);
1442
1568
  }
1443
1569
  return;
@@ -1455,6 +1581,11 @@ async function transformCommonjs(
1455
1581
  currentConditionalNodeEnd !== null,
1456
1582
  parent.type === 'ExpressionStatement' ? parent : node
1457
1583
  );
1584
+ if (parent.type === 'VariableDeclarator' && parent.id.type === 'Identifier') {
1585
+ for (const name of pluginutils.extractAssignedNames(parent.id)) {
1586
+ importedVariables.add(name);
1587
+ }
1588
+ }
1458
1589
  }
1459
1590
  return;
1460
1591
  }
@@ -1495,7 +1626,6 @@ async function transformCommonjs(
1495
1626
  return;
1496
1627
  }
1497
1628
  if (!ignoreDynamicRequires) {
1498
- checkDynamicRequire();
1499
1629
  if (isShorthandProperty(parent)) {
1500
1630
  magicString.prependRight(node.start, 'require: ');
1501
1631
  }
@@ -1579,9 +1709,10 @@ async function transformCommonjs(
1579
1709
  if (scope.contains(flattened.name)) return;
1580
1710
 
1581
1711
  if (
1582
- flattened.keypath === 'module.exports' ||
1583
- flattened.keypath === 'module' ||
1584
- flattened.keypath === 'exports'
1712
+ !isEsModule &&
1713
+ (flattened.keypath === 'module.exports' ||
1714
+ flattened.keypath === 'module' ||
1715
+ flattened.keypath === 'exports')
1585
1716
  ) {
1586
1717
  magicString.overwrite(node.start, node.end, `'object'`, {
1587
1718
  storeName: false
@@ -1609,7 +1740,13 @@ async function transformCommonjs(
1609
1740
  const requireName = deconflict([scope], globals, `require${capitalize(nameBase)}`);
1610
1741
  const isRequiredName = deconflict([scope], globals, `hasRequired${capitalize(nameBase)}`);
1611
1742
  const helpersName = deconflict([scope], globals, 'commonjsHelpers');
1612
- const dynamicRequireName = deconflict([scope], globals, 'commonjsRequire');
1743
+ const dynamicRequireName =
1744
+ replacedDynamicRequires.length > 0 &&
1745
+ deconflict(
1746
+ [scope],
1747
+ globals,
1748
+ isDynamicRequireModulesEnabled ? CREATE_COMMONJS_REQUIRE_EXPORT : COMMONJS_REQUIRE_EXPORT
1749
+ );
1613
1750
  const deconflictedExportNames = Object.create(null);
1614
1751
  for (const [exportName, { scopes }] of exportsAssignmentsByName) {
1615
1752
  deconflictedExportNames[exportName] = deconflict([...scopes], globals, exportName);
@@ -1621,10 +1758,17 @@ async function transformCommonjs(
1621
1758
  });
1622
1759
  }
1623
1760
  for (const node of replacedDynamicRequires) {
1624
- magicString.overwrite(node.start, node.end, dynamicRequireName, {
1625
- contentOnly: true,
1626
- storeName: true
1627
- });
1761
+ magicString.overwrite(
1762
+ node.start,
1763
+ node.end,
1764
+ isDynamicRequireModulesEnabled
1765
+ ? `${dynamicRequireName}(${JSON.stringify(virtualDynamicRequirePath)})`
1766
+ : dynamicRequireName,
1767
+ {
1768
+ contentOnly: true,
1769
+ storeName: true
1770
+ }
1771
+ );
1628
1772
  }
1629
1773
 
1630
1774
  // We cannot wrap ES/mixed modules
@@ -1644,7 +1788,7 @@ async function transformCommonjs(
1644
1788
  ) &&
1645
1789
  (ignoreGlobal || !uses.global)
1646
1790
  ) {
1647
- return { meta: { commonjs: { isCommonJS: false, isMixedModule: false } } };
1791
+ return { meta: { commonjs: { isCommonJS: false } } };
1648
1792
  }
1649
1793
 
1650
1794
  let leadingComment = '';
@@ -1654,7 +1798,9 @@ async function transformCommonjs(
1654
1798
  magicString.remove(0, commentEnd).trim();
1655
1799
  }
1656
1800
 
1657
- const exportMode = shouldWrap
1801
+ const exportMode = isEsModule
1802
+ ? 'none'
1803
+ : shouldWrap
1658
1804
  ? uses.module
1659
1805
  ? 'module'
1660
1806
  : 'exports'
@@ -1666,7 +1812,7 @@ async function transformCommonjs(
1666
1812
  ? 'exports'
1667
1813
  : 'module';
1668
1814
 
1669
- const { importBlock, usesRequireWrapper } = await rewriteRequireExpressionsAndGetImportBlock(
1815
+ const importBlock = await rewriteRequireExpressionsAndGetImportBlock(
1670
1816
  magicString,
1671
1817
  topLevelDeclarations,
1672
1818
  reassignedNames,
@@ -1676,12 +1822,14 @@ async function transformCommonjs(
1676
1822
  exportsName,
1677
1823
  id,
1678
1824
  exportMode,
1679
- resolveRequireSourcesAndGetMeta,
1825
+ resolveRequireSourcesAndUpdateMeta,
1680
1826
  needsRequireWrapper,
1681
1827
  isEsModule,
1682
- uses.require,
1683
- getIgnoreTryCatchRequireStatementMode
1828
+ isDynamicRequireModulesEnabled,
1829
+ getIgnoreTryCatchRequireStatementMode,
1830
+ commonjsMeta
1684
1831
  );
1832
+ const usesRequireWrapper = commonjsMeta.isCommonJS === IS_WRAPPED_COMMONJS;
1685
1833
  const exportBlock = isEsModule
1686
1834
  ? ''
1687
1835
  : rewriteExportsAndGetExportsBlock(
@@ -1734,15 +1882,12 @@ function ${requireName} () {
1734
1882
  code: magicString.toString(),
1735
1883
  map: sourceMap ? magicString.generateMap() : null,
1736
1884
  syntheticNamedExports: isEsModule || usesRequireWrapper ? false : '__moduleExports',
1737
- meta: {
1738
- commonjs: {
1739
- isCommonJS: !isEsModule && (usesRequireWrapper ? IS_WRAPPED_COMMONJS : true),
1740
- isMixedModule: isEsModule
1741
- }
1742
- }
1885
+ meta: { commonjs: commonjsMeta }
1743
1886
  };
1744
1887
  }
1745
1888
 
1889
+ const PLUGIN_NAME = 'commonjs';
1890
+
1746
1891
  function commonjs(options = {}) {
1747
1892
  const {
1748
1893
  ignoreGlobal,
@@ -1770,11 +1915,6 @@ function commonjs(options = {}) {
1770
1915
  const defaultIsModuleExports =
1771
1916
  typeof options.defaultIsModuleExports === 'boolean' ? options.defaultIsModuleExports : 'auto';
1772
1917
 
1773
- const {
1774
- resolveRequireSourcesAndGetMeta,
1775
- getWrappedIds,
1776
- isRequiredId
1777
- } = getResolveRequireSourcesAndGetMeta(extensions, detectCyclesAndConditional);
1778
1918
  const dynamicRequireRoot =
1779
1919
  typeof options.dynamicRequireRoot === 'string'
1780
1920
  ? path.resolve(options.dynamicRequireRoot)
@@ -1785,9 +1925,6 @@ function commonjs(options = {}) {
1785
1925
  );
1786
1926
  const isDynamicRequireModulesEnabled = dynamicRequireModules.size > 0;
1787
1927
 
1788
- const esModulesWithDefaultExport = new Set();
1789
- const esModulesWithNamedExports = new Set();
1790
-
1791
1928
  const ignoreRequire =
1792
1929
  typeof options.ignore === 'function'
1793
1930
  ? options.ignore
@@ -1815,41 +1952,50 @@ function commonjs(options = {}) {
1815
1952
 
1816
1953
  const sourceMap = options.sourceMap !== false;
1817
1954
 
1955
+ // Initialized in buildStart
1956
+ let requireResolver;
1957
+
1818
1958
  function transformAndCheckExports(code, id) {
1819
1959
  const { isEsModule, hasDefaultExport, hasNamedExports, ast } = analyzeTopLevelStatements(
1820
1960
  this.parse,
1821
1961
  code,
1822
1962
  id
1823
1963
  );
1964
+
1965
+ const commonjsMeta = this.getModuleInfo(id).meta.commonjs || {};
1824
1966
  if (hasDefaultExport) {
1825
- esModulesWithDefaultExport.add(id);
1967
+ commonjsMeta.hasDefaultExport = true;
1826
1968
  }
1827
1969
  if (hasNamedExports) {
1828
- esModulesWithNamedExports.add(id);
1970
+ commonjsMeta.hasNamedExports = true;
1829
1971
  }
1830
1972
 
1831
1973
  if (
1832
1974
  !dynamicRequireModules.has(normalizePathSlashes(id)) &&
1833
- (!(hasCjsKeywords(code, ignoreGlobal) || isRequiredId(id)) ||
1975
+ (!(hasCjsKeywords(code, ignoreGlobal) || requireResolver.isRequiredId(id)) ||
1834
1976
  (isEsModule && !options.transformMixedEsModules))
1835
1977
  ) {
1836
- return { meta: { commonjs: { isCommonJS: false } } };
1978
+ commonjsMeta.isCommonJS = false;
1979
+ return { meta: { commonjs: commonjsMeta } };
1837
1980
  }
1838
1981
 
1839
1982
  const needsRequireWrapper =
1840
1983
  !isEsModule &&
1841
1984
  (dynamicRequireModules.has(normalizePathSlashes(id)) || strictRequiresFilter(id));
1842
1985
 
1843
- const checkDynamicRequire = () => {
1986
+ const checkDynamicRequire = (position) => {
1844
1987
  if (id.indexOf(dynamicRequireRoot) !== 0) {
1845
- this.error({
1846
- code: 'DYNAMIC_REQUIRE_OUTSIDE_ROOT',
1847
- id,
1848
- dynamicRequireRoot,
1849
- message: `"${id}" contains dynamic require statements but it is not within the current dynamicRequireRoot "${dynamicRequireRoot}". You should set dynamicRequireRoot to "${path.dirname(
1850
- id
1851
- )}" or one of its parent directories.`
1852
- });
1988
+ this.error(
1989
+ {
1990
+ code: 'DYNAMIC_REQUIRE_OUTSIDE_ROOT',
1991
+ id,
1992
+ dynamicRequireRoot,
1993
+ message: `"${id}" contains dynamic require statements but it is not within the current dynamicRequireRoot "${dynamicRequireRoot}". You should set dynamicRequireRoot to "${path.dirname(
1994
+ id
1995
+ )}" or one of its parent directories.`
1996
+ },
1997
+ position
1998
+ );
1853
1999
  }
1854
2000
  };
1855
2001
 
@@ -1869,14 +2015,15 @@ function commonjs(options = {}) {
1869
2015
  ast,
1870
2016
  defaultIsModuleExports,
1871
2017
  needsRequireWrapper,
1872
- resolveRequireSourcesAndGetMeta(this),
1873
- isRequiredId(id),
1874
- checkDynamicRequire
2018
+ requireResolver.resolveRequireSourcesAndUpdateMeta(this),
2019
+ requireResolver.isRequiredId(id),
2020
+ checkDynamicRequire,
2021
+ commonjsMeta
1875
2022
  );
1876
2023
  }
1877
2024
 
1878
2025
  return {
1879
- name: 'commonjs',
2026
+ name: PLUGIN_NAME,
1880
2027
 
1881
2028
  version,
1882
2029
 
@@ -1884,7 +2031,7 @@ function commonjs(options = {}) {
1884
2031
  // We inject the resolver in the beginning so that "catch-all-resolver" like node-resolver
1885
2032
  // do not prevent our plugin from resolving entry points ot proxies.
1886
2033
  const plugins = Array.isArray(rawOptions.plugins)
1887
- ? rawOptions.plugins
2034
+ ? [...rawOptions.plugins]
1888
2035
  : rawOptions.plugins
1889
2036
  ? [rawOptions.plugins]
1890
2037
  : [];
@@ -1895,18 +2042,23 @@ function commonjs(options = {}) {
1895
2042
  return { ...rawOptions, plugins };
1896
2043
  },
1897
2044
 
1898
- buildStart() {
1899
- validateRollupVersion(this.meta.rollupVersion, peerDependencies.rollup);
2045
+ buildStart({ plugins }) {
2046
+ validateVersion(this.meta.rollupVersion, peerDependencies.rollup, 'rollup');
2047
+ const nodeResolve = plugins.find(({ name }) => name === 'node-resolve');
2048
+ if (nodeResolve) {
2049
+ validateVersion(nodeResolve.version, '^13.0.6', '@rollup/plugin-node-resolve');
2050
+ }
1900
2051
  if (options.namedExports != null) {
1901
2052
  this.warn(
1902
2053
  'The namedExports option from "@rollup/plugin-commonjs" is deprecated. Named exports are now handled automatically.'
1903
2054
  );
1904
2055
  }
2056
+ requireResolver = getRequireResolver(extensions, detectCyclesAndConditional);
1905
2057
  },
1906
2058
 
1907
2059
  buildEnd() {
1908
2060
  if (options.strictRequires === 'debug') {
1909
- const wrappedIds = getWrappedIds();
2061
+ const wrappedIds = requireResolver.getWrappedIds();
1910
2062
  if (wrappedIds.length) {
1911
2063
  this.warn({
1912
2064
  code: 'WRAPPED_IDS',
@@ -1955,6 +2107,15 @@ function commonjs(options = {}) {
1955
2107
  );
1956
2108
  }
1957
2109
 
2110
+ // entry suffix is just appended to not mess up relative external resolution
2111
+ if (id.endsWith(ENTRY_SUFFIX)) {
2112
+ return getEntryProxy(
2113
+ id.slice(0, -ENTRY_SUFFIX.length),
2114
+ defaultIsModuleExports,
2115
+ this.getModuleInfo
2116
+ );
2117
+ }
2118
+
1958
2119
  if (isWrappedId(id, ES_IMPORT_SUFFIX)) {
1959
2120
  return getEsImportProxy(unwrapId(id, ES_IMPORT_SUFFIX), defaultIsModuleExports);
1960
2121
  }
@@ -1970,18 +2131,16 @@ function commonjs(options = {}) {
1970
2131
 
1971
2132
  if (isWrappedId(id, PROXY_SUFFIX)) {
1972
2133
  const actualId = unwrapId(id, PROXY_SUFFIX);
1973
- return getStaticRequireProxy(
1974
- actualId,
1975
- getRequireReturnsDefault(actualId),
1976
- esModulesWithDefaultExport,
1977
- esModulesWithNamedExports,
1978
- this.load
1979
- );
2134
+ return getStaticRequireProxy(actualId, getRequireReturnsDefault(actualId), this.load);
1980
2135
  }
1981
2136
 
1982
2137
  return null;
1983
2138
  },
1984
2139
 
2140
+ shouldTransformCachedModule(...args) {
2141
+ return requireResolver.shouldTransformCachedModule.call(this, ...args);
2142
+ },
2143
+
1985
2144
  transform(code, id) {
1986
2145
  const extName = path.extname(id);
1987
2146
  if (extName !== '.cjs' && (!filter(id) || !extensions.includes(extName))) {