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

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-5";
20
20
  var peerDependencies = {
21
- rollup: "^2.60.0"
21
+ rollup: "^2.64.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;
@@ -402,21 +405,15 @@ function getUnknownRequireProxy(id, requireReturnsDefault) {
402
405
  return `import * as ${name} from ${JSON.stringify(id)}; ${exported}`;
403
406
  }
404
407
 
405
- async function getStaticRequireProxy(
406
- id,
407
- requireReturnsDefault,
408
- esModulesWithDefaultExport,
409
- esModulesWithNamedExports,
410
- loadModule
411
- ) {
408
+ async function getStaticRequireProxy(id, requireReturnsDefault, loadModule) {
412
409
  const name = getName(id);
413
410
  const {
414
411
  meta: { commonjs: commonjsMeta }
415
412
  } = await loadModule({ id });
416
- if (commonjsMeta && commonjsMeta.isCommonJS) {
417
- return `export { __moduleExports as default } from ${JSON.stringify(id)};`;
418
- } else if (!commonjsMeta) {
413
+ if (!commonjsMeta) {
419
414
  return getUnknownRequireProxy(id, requireReturnsDefault);
415
+ } else if (commonjsMeta.isCommonJS) {
416
+ return `export { __moduleExports as default } from ${JSON.stringify(id)};`;
420
417
  } else if (!requireReturnsDefault) {
421
418
  return `import { getAugmentedNamespace } from "${HELPERS_ID}"; import * as ${name} from ${JSON.stringify(
422
419
  id
@@ -424,8 +421,8 @@ async function getStaticRequireProxy(
424
421
  } else if (
425
422
  requireReturnsDefault !== true &&
426
423
  (requireReturnsDefault === 'namespace' ||
427
- !esModulesWithDefaultExport.has(id) ||
428
- (requireReturnsDefault === 'auto' && esModulesWithNamedExports.has(id)))
424
+ !commonjsMeta.hasDefaultExport ||
425
+ (requireReturnsDefault === 'auto' && commonjsMeta.hasNamedExports))
429
426
  ) {
430
427
  return `import * as ${name} from ${JSON.stringify(id)}; export default ${name};`;
431
428
  }
@@ -487,10 +484,11 @@ function resolveExtensions(importee, importer, extensions) {
487
484
 
488
485
  function getResolveId(extensions) {
489
486
  return async function resolveId(importee, importer, resolveOptions) {
487
+ // We assume that all requires are pre-resolved
490
488
  if (
491
489
  resolveOptions.custom &&
492
- resolveOptions.custom.commonjs &&
493
- resolveOptions.custom.commonjs.skipResolver
490
+ resolveOptions.custom['node-resolve'] &&
491
+ resolveOptions.custom['node-resolve'].isRequire
494
492
  ) {
495
493
  return null;
496
494
  }
@@ -558,14 +556,73 @@ function getResolveId(extensions) {
558
556
  };
559
557
  }
560
558
 
561
- function getResolveRequireSourcesAndGetMeta(extensions, detectCyclesAndConditional) {
559
+ function getRequireResolver(extensions, detectCyclesAndConditional) {
562
560
  const knownCjsModuleTypes = Object.create(null);
563
561
  const requiredIds = Object.create(null);
564
562
  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));
563
+ const dependencies = Object.create(null);
564
+ const getDependencies = (id) => dependencies[id] || (dependencies[id] = new Set());
565
+
566
+ const isCyclic = (id) => {
567
+ const dependenciesToCheck = new Set(getDependencies(id));
568
+ for (const dependency of dependenciesToCheck) {
569
+ if (dependency === id) {
570
+ return true;
571
+ }
572
+ for (const childDependency of getDependencies(dependency)) {
573
+ dependenciesToCheck.add(childDependency);
574
+ }
575
+ }
576
+ return false;
577
+ };
578
+
579
+ const fullyAnalyzedModules = Object.create(null);
580
+
581
+ const getTypeForFullyAnalyzedModule = (id) => {
582
+ const knownType = knownCjsModuleTypes[id];
583
+ if (knownType !== true || !detectCyclesAndConditional || fullyAnalyzedModules[id]) {
584
+ return knownType;
585
+ }
586
+ fullyAnalyzedModules[id] = true;
587
+ if (isCyclic(id)) {
588
+ return (knownCjsModuleTypes[id] = IS_WRAPPED_COMMONJS);
589
+ }
590
+ return knownType;
591
+ };
592
+
593
+ const setInitialParentType = (id, initialCommonJSType) => {
594
+ // It is possible a transformed module is already fully analyzed when using
595
+ // the cache and one dependency introduces a new cycle. Then transform is
596
+ // run for a fully analzyed module again. Fully analyzed modules may never
597
+ // change their type as importers already trust their type.
598
+ knownCjsModuleTypes[id] = fullyAnalyzedModules[id]
599
+ ? knownCjsModuleTypes[id]
600
+ : initialCommonJSType;
601
+ if (
602
+ detectCyclesAndConditional &&
603
+ knownCjsModuleTypes[id] === true &&
604
+ requiredIds[id] &&
605
+ !unconditionallyRequiredIds[id]
606
+ ) {
607
+ knownCjsModuleTypes[id] = IS_WRAPPED_COMMONJS;
608
+ }
609
+ };
610
+
611
+ const setTypesForRequiredModules = async (parentId, resolved, isConditional, loadModule) => {
612
+ const childId = resolved.id;
613
+ requiredIds[childId] = true;
614
+ if (!(isConditional || knownCjsModuleTypes[parentId] === IS_WRAPPED_COMMONJS)) {
615
+ unconditionallyRequiredIds[childId] = true;
616
+ }
617
+
618
+ getDependencies(parentId).add(childId);
619
+ if (!isCyclic(childId)) {
620
+ // This makes sure the current transform handler waits for all direct dependencies to be
621
+ // loaded and transformed and therefore for all transitive CommonJS dependencies to be
622
+ // loaded as well so that all cycles have been found and knownCjsModuleTypes is reliable.
623
+ await loadModule(resolved);
624
+ }
625
+ };
569
626
 
570
627
  return {
571
628
  getWrappedIds: () =>
@@ -573,19 +630,40 @@ function getResolveRequireSourcesAndGetMeta(extensions, detectCyclesAndCondition
573
630
  (id) => knownCjsModuleTypes[id] === IS_WRAPPED_COMMONJS
574
631
  ),
575
632
  isRequiredId: (id) => requiredIds[id],
576
- resolveRequireSourcesAndGetMeta: (rollupContext) => async (
633
+ async shouldTransformCachedModule({ id: parentId, meta: { commonjs: parentMeta } }) {
634
+ // Ignore modules that did not pass through the original transformer in a previous build
635
+ if (!(parentMeta && parentMeta.requires)) {
636
+ return false;
637
+ }
638
+ setInitialParentType(parentId, parentMeta.initialCommonJSType);
639
+ await Promise.all(
640
+ parentMeta.requires.map(({ resolved, isConditional }) =>
641
+ setTypesForRequiredModules(parentId, resolved, isConditional, this.load)
642
+ )
643
+ );
644
+ if (getTypeForFullyAnalyzedModule(parentId) !== parentMeta.isCommonJS) {
645
+ return true;
646
+ }
647
+ for (const {
648
+ resolved: { id }
649
+ } of parentMeta.requires) {
650
+ if (getTypeForFullyAnalyzedModule(id) !== parentMeta.isRequiredCommonJS[id]) {
651
+ return true;
652
+ }
653
+ }
654
+ return false;
655
+ },
656
+ /* eslint-disable no-param-reassign */
657
+ resolveRequireSourcesAndUpdateMeta: (rollupContext) => async (
577
658
  parentId,
578
659
  isParentCommonJS,
660
+ parentMeta,
579
661
  sources
580
662
  ) => {
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
- }
663
+ parentMeta.initialCommonJSType = isParentCommonJS;
664
+ parentMeta.requires = [];
665
+ parentMeta.isRequiredCommonJS = Object.create(null);
666
+ setInitialParentType(parentId, isParentCommonJS);
589
667
  const requireTargets = await Promise.all(
590
668
  sources.map(async ({ source, isConditional }) => {
591
669
  // Never analyze or proxy internal modules
@@ -594,10 +672,7 @@ function getResolveRequireSourcesAndGetMeta(extensions, detectCyclesAndCondition
594
672
  }
595
673
  const resolved =
596
674
  (await rollupContext.resolve(source, parentId, {
597
- custom: {
598
- 'node-resolve': { isRequire: true },
599
- commonjs: { skipResolver: true }
600
- }
675
+ custom: { 'node-resolve': { isRequire: true } }
601
676
  })) || resolveExtensions(source, parentId, extensions);
602
677
  if (!resolved) {
603
678
  return { id: wrapId(source, EXTERNAL_SUFFIX), allowProxy: false };
@@ -606,96 +681,58 @@ function getResolveRequireSourcesAndGetMeta(extensions, detectCyclesAndCondition
606
681
  if (resolved.external) {
607
682
  return { id: wrapId(childId, EXTERNAL_SUFFIX), allowProxy: false };
608
683
  }
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
- }
684
+ parentMeta.requires.push({ resolved, isConditional });
685
+ await setTypesForRequiredModules(parentId, resolved, isConditional, rollupContext.load);
660
686
  return { id: childId, allowProxy: true };
661
687
  })
662
688
  );
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
- };
689
+ parentMeta.isCommonJS = getTypeForFullyAnalyzedModule(parentId);
690
+ return requireTargets.map(({ id: dependencyId, allowProxy }, index) => {
691
+ // eslint-disable-next-line no-multi-assign
692
+ const isCommonJS = (parentMeta.isRequiredCommonJS[
693
+ dependencyId
694
+ ] = getTypeForFullyAnalyzedModule(dependencyId));
695
+ return {
696
+ source: sources[index].source,
697
+ id: allowProxy
698
+ ? isCommonJS === IS_WRAPPED_COMMONJS
699
+ ? wrapId(dependencyId, WRAPPED_SUFFIX)
700
+ : wrapId(dependencyId, PROXY_SUFFIX)
701
+ : dependencyId,
702
+ isCommonJS
703
+ };
704
+ });
678
705
  }
679
706
  };
680
707
  }
681
708
 
682
- function validateRollupVersion(rollupVersion, peerDependencyVersion) {
683
- const [major, minor] = rollupVersion.split('.').map(Number);
684
- const versionRegexp = /\^(\d+\.\d+)\.\d+/g;
709
+ function validateVersion(actualVersion, peerDependencyVersion, name) {
710
+ const versionRegexp = /\^(\d+\.\d+\.\d+)/g;
685
711
  let minMajor = Infinity;
686
712
  let minMinor = Infinity;
713
+ let minPatch = Infinity;
687
714
  let foundVersion;
688
715
  // eslint-disable-next-line no-cond-assign
689
716
  while ((foundVersion = versionRegexp.exec(peerDependencyVersion))) {
690
- const [foundMajor, foundMinor] = foundVersion[1].split('.').map(Number);
717
+ const [foundMajor, foundMinor, foundPatch] = foundVersion[1].split('.').map(Number);
691
718
  if (foundMajor < minMajor) {
692
719
  minMajor = foundMajor;
693
720
  minMinor = foundMinor;
721
+ minPatch = foundPatch;
694
722
  }
695
723
  }
696
- if (major < minMajor || (major === minMajor && minor < minMinor)) {
724
+ if (!actualVersion) {
725
+ throw new Error(
726
+ `Insufficient ${name} version: "@rollup/plugin-commonjs" requires at least ${name}@${minMajor}.${minMinor}.${minPatch}.`
727
+ );
728
+ }
729
+ const [major, minor, patch] = actualVersion.split('.').map(Number);
730
+ if (
731
+ major < minMajor ||
732
+ (major === minMajor && (minor < minMinor || (minor === minMinor && patch < minPatch)))
733
+ ) {
697
734
  throw new Error(
698
- `Insufficient Rollup version: "@rollup/plugin-commonjs" requires at least rollup@${minMajor}.${minMinor} but found rollup@${rollupVersion}.`
735
+ `Insufficient ${name} version: "@rollup/plugin-commonjs" requires at least ${name}@${minMajor}.${minMinor}.${minPatch} but found ${name}@${actualVersion}.`
699
736
  );
700
737
  }
701
738
  }
@@ -1138,17 +1175,20 @@ function getRequireHandlers() {
1138
1175
  exportsName,
1139
1176
  id,
1140
1177
  exportMode,
1141
- resolveRequireSourcesAndGetMeta,
1178
+ resolveRequireSourcesAndUpdateMeta,
1142
1179
  needsRequireWrapper,
1143
1180
  isEsModule,
1144
- usesRequire,
1145
- getIgnoreTryCatchRequireStatementMode
1181
+ isDynamicRequireModulesEnabled,
1182
+ getIgnoreTryCatchRequireStatementMode,
1183
+ commonjsMeta
1146
1184
  ) {
1147
1185
  const imports = [];
1148
1186
  imports.push(`import * as ${helpersName} from "${HELPERS_ID}";`);
1149
- if (usesRequire) {
1187
+ if (dynamicRequireName) {
1150
1188
  imports.push(
1151
- `import { commonjsRequire as ${dynamicRequireName} } from "${DYNAMIC_MODULES_ID}";`
1189
+ `import { ${
1190
+ isDynamicRequireModulesEnabled ? CREATE_COMMONJS_REQUIRE_EXPORT : COMMONJS_REQUIRE_EXPORT
1191
+ } as ${dynamicRequireName} } from "${DYNAMIC_MODULES_ID}";`
1152
1192
  );
1153
1193
  }
1154
1194
  if (exportMode === 'module') {
@@ -1163,9 +1203,10 @@ function getRequireHandlers() {
1163
1203
  );
1164
1204
  }
1165
1205
  const requiresBySource = collectSources(requireExpressions);
1166
- const { requireTargets, usesRequireWrapper } = await resolveRequireSourcesAndGetMeta(
1206
+ const requireTargets = await resolveRequireSourcesAndUpdateMeta(
1167
1207
  id,
1168
1208
  needsRequireWrapper ? IS_WRAPPED_COMMONJS : !isEsModule,
1209
+ commonjsMeta,
1169
1210
  Object.keys(requiresBySource).map((source) => {
1170
1211
  return {
1171
1212
  source,
@@ -1180,10 +1221,7 @@ function getRequireHandlers() {
1180
1221
  getIgnoreTryCatchRequireStatementMode,
1181
1222
  magicString
1182
1223
  );
1183
- return {
1184
- importBlock: imports.length ? `${imports.join('\n')}\n\n` : '',
1185
- usesRequireWrapper
1186
- };
1224
+ return imports.length ? `${imports.join('\n')}\n\n` : '';
1187
1225
  }
1188
1226
 
1189
1227
  return {
@@ -1286,9 +1324,10 @@ async function transformCommonjs(
1286
1324
  astCache,
1287
1325
  defaultIsModuleExports,
1288
1326
  needsRequireWrapper,
1289
- resolveRequireSourcesAndGetMeta,
1327
+ resolveRequireSourcesAndUpdateMeta,
1290
1328
  isRequired,
1291
- checkDynamicRequire
1329
+ checkDynamicRequire,
1330
+ commonjsMeta
1292
1331
  ) {
1293
1332
  const ast = astCache || tryParse(parse, code, id);
1294
1333
  const magicString = new MagicString__default["default"](code);
@@ -1434,15 +1473,9 @@ async function transformCommonjs(
1434
1473
  isRequire(node.callee.object, scope) &&
1435
1474
  node.callee.property.name === 'resolve'
1436
1475
  ) {
1437
- checkDynamicRequire();
1476
+ checkDynamicRequire(node.start);
1438
1477
  uses.require = true;
1439
1478
  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
1479
  replacedDynamicRequires.push(requireNode);
1447
1480
  return;
1448
1481
  }
@@ -1456,15 +1489,9 @@ async function transformCommonjs(
1456
1489
 
1457
1490
  if (hasDynamicArguments(node)) {
1458
1491
  if (isDynamicRequireModulesEnabled) {
1459
- magicString.appendLeft(
1460
- node.end - 1,
1461
- `, ${JSON.stringify(
1462
- path.dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath
1463
- )}`
1464
- );
1492
+ checkDynamicRequire(node.start);
1465
1493
  }
1466
1494
  if (!ignoreDynamicRequires) {
1467
- checkDynamicRequire();
1468
1495
  replacedDynamicRequires.push(node.callee);
1469
1496
  }
1470
1497
  return;
@@ -1522,7 +1549,6 @@ async function transformCommonjs(
1522
1549
  return;
1523
1550
  }
1524
1551
  if (!ignoreDynamicRequires) {
1525
- checkDynamicRequire();
1526
1552
  if (isShorthandProperty(parent)) {
1527
1553
  magicString.prependRight(node.start, 'require: ');
1528
1554
  }
@@ -1606,9 +1632,10 @@ async function transformCommonjs(
1606
1632
  if (scope.contains(flattened.name)) return;
1607
1633
 
1608
1634
  if (
1609
- flattened.keypath === 'module.exports' ||
1610
- flattened.keypath === 'module' ||
1611
- flattened.keypath === 'exports'
1635
+ !isEsModule &&
1636
+ (flattened.keypath === 'module.exports' ||
1637
+ flattened.keypath === 'module' ||
1638
+ flattened.keypath === 'exports')
1612
1639
  ) {
1613
1640
  magicString.overwrite(node.start, node.end, `'object'`, {
1614
1641
  storeName: false
@@ -1636,7 +1663,13 @@ async function transformCommonjs(
1636
1663
  const requireName = deconflict([scope], globals, `require${capitalize(nameBase)}`);
1637
1664
  const isRequiredName = deconflict([scope], globals, `hasRequired${capitalize(nameBase)}`);
1638
1665
  const helpersName = deconflict([scope], globals, 'commonjsHelpers');
1639
- const dynamicRequireName = deconflict([scope], globals, 'commonjsRequire');
1666
+ const dynamicRequireName =
1667
+ replacedDynamicRequires.length > 0 &&
1668
+ deconflict(
1669
+ [scope],
1670
+ globals,
1671
+ isDynamicRequireModulesEnabled ? CREATE_COMMONJS_REQUIRE_EXPORT : COMMONJS_REQUIRE_EXPORT
1672
+ );
1640
1673
  const deconflictedExportNames = Object.create(null);
1641
1674
  for (const [exportName, { scopes }] of exportsAssignmentsByName) {
1642
1675
  deconflictedExportNames[exportName] = deconflict([...scopes], globals, exportName);
@@ -1648,10 +1681,17 @@ async function transformCommonjs(
1648
1681
  });
1649
1682
  }
1650
1683
  for (const node of replacedDynamicRequires) {
1651
- magicString.overwrite(node.start, node.end, dynamicRequireName, {
1652
- contentOnly: true,
1653
- storeName: true
1654
- });
1684
+ magicString.overwrite(
1685
+ node.start,
1686
+ node.end,
1687
+ isDynamicRequireModulesEnabled
1688
+ ? `${dynamicRequireName}(${JSON.stringify(virtualDynamicRequirePath)})`
1689
+ : dynamicRequireName,
1690
+ {
1691
+ contentOnly: true,
1692
+ storeName: true
1693
+ }
1694
+ );
1655
1695
  }
1656
1696
 
1657
1697
  // We cannot wrap ES/mixed modules
@@ -1671,7 +1711,7 @@ async function transformCommonjs(
1671
1711
  ) &&
1672
1712
  (ignoreGlobal || !uses.global)
1673
1713
  ) {
1674
- return { meta: { commonjs: { isCommonJS: false, isMixedModule: false } } };
1714
+ return { meta: { commonjs: { isCommonJS: false } } };
1675
1715
  }
1676
1716
 
1677
1717
  let leadingComment = '';
@@ -1693,7 +1733,7 @@ async function transformCommonjs(
1693
1733
  ? 'exports'
1694
1734
  : 'module';
1695
1735
 
1696
- const { importBlock, usesRequireWrapper } = await rewriteRequireExpressionsAndGetImportBlock(
1736
+ const importBlock = await rewriteRequireExpressionsAndGetImportBlock(
1697
1737
  magicString,
1698
1738
  topLevelDeclarations,
1699
1739
  reassignedNames,
@@ -1703,12 +1743,14 @@ async function transformCommonjs(
1703
1743
  exportsName,
1704
1744
  id,
1705
1745
  exportMode,
1706
- resolveRequireSourcesAndGetMeta,
1746
+ resolveRequireSourcesAndUpdateMeta,
1707
1747
  needsRequireWrapper,
1708
1748
  isEsModule,
1709
- uses.require,
1710
- getIgnoreTryCatchRequireStatementMode
1749
+ isDynamicRequireModulesEnabled,
1750
+ getIgnoreTryCatchRequireStatementMode,
1751
+ commonjsMeta
1711
1752
  );
1753
+ const usesRequireWrapper = commonjsMeta.isCommonJS === IS_WRAPPED_COMMONJS;
1712
1754
  const exportBlock = isEsModule
1713
1755
  ? ''
1714
1756
  : rewriteExportsAndGetExportsBlock(
@@ -1761,12 +1803,7 @@ function ${requireName} () {
1761
1803
  code: magicString.toString(),
1762
1804
  map: sourceMap ? magicString.generateMap() : null,
1763
1805
  syntheticNamedExports: isEsModule || usesRequireWrapper ? false : '__moduleExports',
1764
- meta: {
1765
- commonjs: {
1766
- isCommonJS: !isEsModule && (usesRequireWrapper ? IS_WRAPPED_COMMONJS : true),
1767
- isMixedModule: isEsModule
1768
- }
1769
- }
1806
+ meta: { commonjs: commonjsMeta }
1770
1807
  };
1771
1808
  }
1772
1809
 
@@ -1797,11 +1834,6 @@ function commonjs(options = {}) {
1797
1834
  const defaultIsModuleExports =
1798
1835
  typeof options.defaultIsModuleExports === 'boolean' ? options.defaultIsModuleExports : 'auto';
1799
1836
 
1800
- const {
1801
- resolveRequireSourcesAndGetMeta,
1802
- getWrappedIds,
1803
- isRequiredId
1804
- } = getResolveRequireSourcesAndGetMeta(extensions, detectCyclesAndConditional);
1805
1837
  const dynamicRequireRoot =
1806
1838
  typeof options.dynamicRequireRoot === 'string'
1807
1839
  ? path.resolve(options.dynamicRequireRoot)
@@ -1812,9 +1844,6 @@ function commonjs(options = {}) {
1812
1844
  );
1813
1845
  const isDynamicRequireModulesEnabled = dynamicRequireModules.size > 0;
1814
1846
 
1815
- const esModulesWithDefaultExport = new Set();
1816
- const esModulesWithNamedExports = new Set();
1817
-
1818
1847
  const ignoreRequire =
1819
1848
  typeof options.ignore === 'function'
1820
1849
  ? options.ignore
@@ -1842,41 +1871,50 @@ function commonjs(options = {}) {
1842
1871
 
1843
1872
  const sourceMap = options.sourceMap !== false;
1844
1873
 
1874
+ // Initialized in buildStart
1875
+ let requireResolver;
1876
+
1845
1877
  function transformAndCheckExports(code, id) {
1846
1878
  const { isEsModule, hasDefaultExport, hasNamedExports, ast } = analyzeTopLevelStatements(
1847
1879
  this.parse,
1848
1880
  code,
1849
1881
  id
1850
1882
  );
1883
+
1884
+ const commonjsMeta = this.getModuleInfo(id).meta.commonjs || {};
1851
1885
  if (hasDefaultExport) {
1852
- esModulesWithDefaultExport.add(id);
1886
+ commonjsMeta.hasDefaultExport = true;
1853
1887
  }
1854
1888
  if (hasNamedExports) {
1855
- esModulesWithNamedExports.add(id);
1889
+ commonjsMeta.hasNamedExports = true;
1856
1890
  }
1857
1891
 
1858
1892
  if (
1859
1893
  !dynamicRequireModules.has(normalizePathSlashes(id)) &&
1860
- (!(hasCjsKeywords(code, ignoreGlobal) || isRequiredId(id)) ||
1894
+ (!(hasCjsKeywords(code, ignoreGlobal) || requireResolver.isRequiredId(id)) ||
1861
1895
  (isEsModule && !options.transformMixedEsModules))
1862
1896
  ) {
1863
- return { meta: { commonjs: { isCommonJS: false } } };
1897
+ commonjsMeta.isCommonJS = false;
1898
+ return { meta: { commonjs: commonjsMeta } };
1864
1899
  }
1865
1900
 
1866
1901
  const needsRequireWrapper =
1867
1902
  !isEsModule &&
1868
1903
  (dynamicRequireModules.has(normalizePathSlashes(id)) || strictRequiresFilter(id));
1869
1904
 
1870
- const checkDynamicRequire = () => {
1905
+ const checkDynamicRequire = (position) => {
1871
1906
  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
- });
1907
+ this.error(
1908
+ {
1909
+ code: 'DYNAMIC_REQUIRE_OUTSIDE_ROOT',
1910
+ id,
1911
+ dynamicRequireRoot,
1912
+ message: `"${id}" contains dynamic require statements but it is not within the current dynamicRequireRoot "${dynamicRequireRoot}". You should set dynamicRequireRoot to "${path.dirname(
1913
+ id
1914
+ )}" or one of its parent directories.`
1915
+ },
1916
+ position
1917
+ );
1880
1918
  }
1881
1919
  };
1882
1920
 
@@ -1896,9 +1934,10 @@ function commonjs(options = {}) {
1896
1934
  ast,
1897
1935
  defaultIsModuleExports,
1898
1936
  needsRequireWrapper,
1899
- resolveRequireSourcesAndGetMeta(this),
1900
- isRequiredId(id),
1901
- checkDynamicRequire
1937
+ requireResolver.resolveRequireSourcesAndUpdateMeta(this),
1938
+ requireResolver.isRequiredId(id),
1939
+ checkDynamicRequire,
1940
+ commonjsMeta
1902
1941
  );
1903
1942
  }
1904
1943
 
@@ -1922,18 +1961,23 @@ function commonjs(options = {}) {
1922
1961
  return { ...rawOptions, plugins };
1923
1962
  },
1924
1963
 
1925
- buildStart() {
1926
- validateRollupVersion(this.meta.rollupVersion, peerDependencies.rollup);
1964
+ buildStart({ plugins }) {
1965
+ validateVersion(this.meta.rollupVersion, peerDependencies.rollup, 'rollup');
1966
+ const nodeResolve = plugins.find(({ name }) => name === 'node-resolve');
1967
+ if (nodeResolve) {
1968
+ validateVersion(nodeResolve.version, '^13.0.6', '@rollup/plugin-node-resolve');
1969
+ }
1927
1970
  if (options.namedExports != null) {
1928
1971
  this.warn(
1929
1972
  'The namedExports option from "@rollup/plugin-commonjs" is deprecated. Named exports are now handled automatically.'
1930
1973
  );
1931
1974
  }
1975
+ requireResolver = getRequireResolver(extensions, detectCyclesAndConditional);
1932
1976
  },
1933
1977
 
1934
1978
  buildEnd() {
1935
1979
  if (options.strictRequires === 'debug') {
1936
- const wrappedIds = getWrappedIds();
1980
+ const wrappedIds = requireResolver.getWrappedIds();
1937
1981
  if (wrappedIds.length) {
1938
1982
  this.warn({
1939
1983
  code: 'WRAPPED_IDS',
@@ -1997,18 +2041,16 @@ function commonjs(options = {}) {
1997
2041
 
1998
2042
  if (isWrappedId(id, PROXY_SUFFIX)) {
1999
2043
  const actualId = unwrapId(id, PROXY_SUFFIX);
2000
- return getStaticRequireProxy(
2001
- actualId,
2002
- getRequireReturnsDefault(actualId),
2003
- esModulesWithDefaultExport,
2004
- esModulesWithNamedExports,
2005
- this.load
2006
- );
2044
+ return getStaticRequireProxy(actualId, getRequireReturnsDefault(actualId), this.load);
2007
2045
  }
2008
2046
 
2009
2047
  return null;
2010
2048
  },
2011
2049
 
2050
+ shouldTransformCachedModule(...args) {
2051
+ return requireResolver.shouldTransformCachedModule.call(this, ...args);
2052
+ },
2053
+
2012
2054
  transform(code, id) {
2013
2055
  const extName = path.extname(id);
2014
2056
  if (extName !== '.cjs' && (!filter(id) || !extensions.includes(extName))) {