@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.
@@ -7,9 +7,9 @@ import { walk } from 'estree-walker';
7
7
  import MagicString from 'magic-string';
8
8
  import isReference from 'is-reference';
9
9
 
10
- var version = "22.0.0-0";
10
+ var version = "22.0.0-12";
11
11
  var peerDependencies = {
12
- rollup: "^2.60.0"
12
+ rollup: "^2.68.0"
13
13
  };
14
14
 
15
15
  function tryParse(parse, code, id) {
@@ -194,6 +194,9 @@ function getDynamicRequireModules(patterns, dynamicRequireRoot) {
194
194
 
195
195
  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.');`;
196
196
 
197
+ const COMMONJS_REQUIRE_EXPORT = 'commonjsRequire';
198
+ const CREATE_COMMONJS_REQUIRE_EXPORT = 'createCommonjsRequire';
199
+
197
200
  function getDynamicModuleRegistry(
198
201
  isDynamicRequireModulesEnabled,
199
202
  dynamicRequireModules,
@@ -201,7 +204,7 @@ function getDynamicModuleRegistry(
201
204
  ignoreDynamicRequires
202
205
  ) {
203
206
  if (!isDynamicRequireModulesEnabled) {
204
- return `export function commonjsRequire(path) {
207
+ return `export function ${COMMONJS_REQUIRE_EXPORT}(path) {
205
208
  ${FAILED_REQUIRE_ERROR}
206
209
  }`;
207
210
  }
@@ -231,25 +234,25 @@ ${dynamicModuleProps}
231
234
  });
232
235
  }
233
236
 
234
- export function commonjsRequire(path, originalModuleDir) {
235
- var resolvedPath = commonjsResolveImpl(path, originalModuleDir);
236
- if (resolvedPath !== null) {
237
- return getDynamicModules()[resolvedPath]();
237
+ export function ${CREATE_COMMONJS_REQUIRE_EXPORT}(originalModuleDir) {
238
+ function handleRequire(path) {
239
+ var resolvedPath = commonjsResolve(path, originalModuleDir);
240
+ if (resolvedPath !== null) {
241
+ return getDynamicModules()[resolvedPath]();
242
+ }
243
+ ${ignoreDynamicRequires ? 'return require(path);' : FAILED_REQUIRE_ERROR}
238
244
  }
239
- ${ignoreDynamicRequires ? 'return require(path);' : FAILED_REQUIRE_ERROR}
240
- }
241
-
242
- function commonjsResolve (path, originalModuleDir) {
243
- const resolvedPath = commonjsResolveImpl(path, originalModuleDir);
244
- if (resolvedPath !== null) {
245
- return resolvedPath;
245
+ handleRequire.resolve = function (path) {
246
+ var resolvedPath = commonjsResolve(path, originalModuleDir);
247
+ if (resolvedPath !== null) {
248
+ return resolvedPath;
249
+ }
250
+ return require.resolve(path);
246
251
  }
247
- return require.resolve(path);
252
+ return handleRequire;
248
253
  }
249
254
 
250
- commonjsRequire.resolve = commonjsResolve;
251
-
252
- function commonjsResolveImpl (path, originalModuleDir) {
255
+ function commonjsResolve (path, originalModuleDir) {
253
256
  var shouldTryNodeModules = isPossibleNodeModulesPath(path);
254
257
  path = normalize(path);
255
258
  var relPath;
@@ -325,7 +328,8 @@ const WRAPPED_SUFFIX = '?commonjs-wrapped';
325
328
  const EXTERNAL_SUFFIX = '?commonjs-external';
326
329
  const EXPORTS_SUFFIX = '?commonjs-exports';
327
330
  const MODULE_SUFFIX = '?commonjs-module';
328
- const ES_IMPORT_SUFFIX = '?es-import';
331
+ const ENTRY_SUFFIX = '?commonjs-entry';
332
+ const ES_IMPORT_SUFFIX = '?commonjs-es-import';
329
333
 
330
334
  const DYNAMIC_MODULES_ID = '\0commonjs-dynamic-modules';
331
335
  const HELPERS_ID = '\0commonjsHelpers.js';
@@ -393,21 +397,15 @@ function getUnknownRequireProxy(id, requireReturnsDefault) {
393
397
  return `import * as ${name} from ${JSON.stringify(id)}; ${exported}`;
394
398
  }
395
399
 
396
- async function getStaticRequireProxy(
397
- id,
398
- requireReturnsDefault,
399
- esModulesWithDefaultExport,
400
- esModulesWithNamedExports,
401
- loadModule
402
- ) {
400
+ async function getStaticRequireProxy(id, requireReturnsDefault, loadModule) {
403
401
  const name = getName(id);
404
402
  const {
405
403
  meta: { commonjs: commonjsMeta }
406
404
  } = await loadModule({ id });
407
- if (commonjsMeta && commonjsMeta.isCommonJS) {
408
- return `export { __moduleExports as default } from ${JSON.stringify(id)};`;
409
- } else if (!commonjsMeta) {
405
+ if (!commonjsMeta) {
410
406
  return getUnknownRequireProxy(id, requireReturnsDefault);
407
+ } else if (commonjsMeta.isCommonJS) {
408
+ return `export { __moduleExports as default } from ${JSON.stringify(id)};`;
411
409
  } else if (!requireReturnsDefault) {
412
410
  return `import { getAugmentedNamespace } from "${HELPERS_ID}"; import * as ${name} from ${JSON.stringify(
413
411
  id
@@ -415,14 +413,30 @@ async function getStaticRequireProxy(
415
413
  } else if (
416
414
  requireReturnsDefault !== true &&
417
415
  (requireReturnsDefault === 'namespace' ||
418
- !esModulesWithDefaultExport.has(id) ||
419
- (requireReturnsDefault === 'auto' && esModulesWithNamedExports.has(id)))
416
+ !commonjsMeta.hasDefaultExport ||
417
+ (requireReturnsDefault === 'auto' && commonjsMeta.hasNamedExports))
420
418
  ) {
421
419
  return `import * as ${name} from ${JSON.stringify(id)}; export default ${name};`;
422
420
  }
423
421
  return `export { default } from ${JSON.stringify(id)};`;
424
422
  }
425
423
 
424
+ function getEntryProxy(id, defaultIsModuleExports, getModuleInfo) {
425
+ const {
426
+ meta: { commonjs: commonjsMeta },
427
+ hasDefaultExport
428
+ } = getModuleInfo(id);
429
+ if (!commonjsMeta || commonjsMeta.isCommonJS !== IS_WRAPPED_COMMONJS) {
430
+ const stringifiedId = JSON.stringify(id);
431
+ let code = `export * from ${stringifiedId};`;
432
+ if (hasDefaultExport) {
433
+ code += `export { default } from ${stringifiedId};`;
434
+ }
435
+ return code;
436
+ }
437
+ return getEsImportProxy(id, defaultIsModuleExports);
438
+ }
439
+
426
440
  function getEsImportProxy(id, defaultIsModuleExports) {
427
441
  const name = getName(id);
428
442
  const exportsName = `${name}Exports`;
@@ -439,8 +453,7 @@ function getEsImportProxy(id, defaultIsModuleExports) {
439
453
  }
440
454
  return {
441
455
  code,
442
- syntheticNamedExports: '__moduleExports',
443
- meta: { commonjs: { isCommonJS: false } }
456
+ syntheticNamedExports: '__moduleExports'
444
457
  };
445
458
  }
446
459
 
@@ -478,11 +491,17 @@ function resolveExtensions(importee, importer, extensions) {
478
491
 
479
492
  function getResolveId(extensions) {
480
493
  return async function resolveId(importee, importer, resolveOptions) {
494
+ // We assume that all requires are pre-resolved
495
+ const customOptions = resolveOptions.custom;
496
+ if (customOptions && customOptions['node-resolve'] && customOptions['node-resolve'].isRequire) {
497
+ return null;
498
+ }
481
499
  if (isWrappedId(importee, WRAPPED_SUFFIX)) {
482
500
  return unwrapId(importee, WRAPPED_SUFFIX);
483
501
  }
484
502
 
485
503
  if (
504
+ importee.endsWith(ENTRY_SUFFIX) ||
486
505
  isWrappedId(importee, MODULE_SUFFIX) ||
487
506
  isWrappedId(importee, EXPORTS_SUFFIX) ||
488
507
  isWrappedId(importee, PROXY_SUFFIX) ||
@@ -497,9 +516,10 @@ function getResolveId(extensions) {
497
516
  if (importer) {
498
517
  if (
499
518
  importer === DYNAMIC_MODULES_ID ||
500
- // Except for exports, proxies are only importing resolved ids, no need to resolve again
519
+ // Proxies are only importing resolved ids, no need to resolve again
501
520
  isWrappedId(importer, PROXY_SUFFIX) ||
502
- isWrappedId(importer, ES_IMPORT_SUFFIX)
521
+ isWrappedId(importer, ES_IMPORT_SUFFIX) ||
522
+ importer.endsWith(ENTRY_SUFFIX)
503
523
  ) {
504
524
  return importee;
505
525
  }
@@ -519,36 +539,113 @@ function getResolveId(extensions) {
519
539
 
520
540
  // If this is an entry point or ESM import, we need to figure out if the importee is wrapped and
521
541
  // if that is the case, we need to add a proxy.
522
- const customOptions = resolveOptions.custom;
523
-
524
- // If this is a require, we do not need a proxy
525
- if (customOptions && customOptions['node-resolve'] && customOptions['node-resolve'].isRequire) {
526
- return null;
527
- }
528
-
529
542
  const resolved =
530
543
  (await this.resolve(importee, importer, Object.assign({ skipSelf: true }, resolveOptions))) ||
531
544
  resolveExtensions(importee, importer, extensions);
532
- if (!resolved || resolved.external) {
545
+ // Make sure that even if other plugins resolve again, we ignore our own proxies
546
+ if (
547
+ !resolved ||
548
+ resolved.external ||
549
+ resolved.id.endsWith(ENTRY_SUFFIX) ||
550
+ isWrappedId(resolved.id, ES_IMPORT_SUFFIX)
551
+ ) {
533
552
  return resolved;
534
553
  }
554
+ const moduleInfo = await this.load(resolved);
555
+ if (resolveOptions.isEntry) {
556
+ moduleInfo.moduleSideEffects = true;
557
+ // We must not precede entry proxies with a `\0` as that will mess up relative external resolution
558
+ return resolved.id + ENTRY_SUFFIX;
559
+ }
535
560
  const {
536
561
  meta: { commonjs: commonjsMeta }
537
- } = await this.load(resolved);
562
+ } = moduleInfo;
538
563
  if (commonjsMeta && commonjsMeta.isCommonJS === IS_WRAPPED_COMMONJS) {
539
- return wrapId(resolved.id, ES_IMPORT_SUFFIX);
564
+ return { id: wrapId(resolved.id, ES_IMPORT_SUFFIX), meta: { commonjs: { resolved } } };
540
565
  }
541
566
  return resolved;
542
567
  };
543
568
  }
544
569
 
545
- function getResolveRequireSourcesAndGetMeta(extensions, detectCyclesAndConditional) {
570
+ function getRequireResolver(extensions, detectCyclesAndConditional) {
546
571
  const knownCjsModuleTypes = Object.create(null);
547
572
  const requiredIds = Object.create(null);
548
573
  const unconditionallyRequiredIds = Object.create(null);
549
- const dependentModules = Object.create(null);
550
- const getDependentModules = (id) =>
551
- dependentModules[id] || (dependentModules[id] = Object.create(null));
574
+ const dependencies = Object.create(null);
575
+ const getDependencies = (id) => dependencies[id] || (dependencies[id] = new Set());
576
+
577
+ const isCyclic = (id) => {
578
+ const dependenciesToCheck = new Set(getDependencies(id));
579
+ for (const dependency of dependenciesToCheck) {
580
+ if (dependency === id) {
581
+ return true;
582
+ }
583
+ for (const childDependency of getDependencies(dependency)) {
584
+ dependenciesToCheck.add(childDependency);
585
+ }
586
+ }
587
+ return false;
588
+ };
589
+
590
+ // Once a module is listed here, its type (wrapped or not) is fixed and may
591
+ // not change for the rest of the current build, to not break already
592
+ // transformed modules.
593
+ const fullyAnalyzedModules = Object.create(null);
594
+
595
+ const getTypeForFullyAnalyzedModule = (id) => {
596
+ const knownType = knownCjsModuleTypes[id];
597
+ if (knownType !== true || !detectCyclesAndConditional || fullyAnalyzedModules[id]) {
598
+ return knownType;
599
+ }
600
+ if (isCyclic(id)) {
601
+ return (knownCjsModuleTypes[id] = IS_WRAPPED_COMMONJS);
602
+ }
603
+ return knownType;
604
+ };
605
+
606
+ const setInitialParentType = (id, initialCommonJSType) => {
607
+ // Fully analyzed modules may never change type
608
+ if (fullyAnalyzedModules[id]) {
609
+ return;
610
+ }
611
+ knownCjsModuleTypes[id] = initialCommonJSType;
612
+ if (
613
+ detectCyclesAndConditional &&
614
+ knownCjsModuleTypes[id] === true &&
615
+ requiredIds[id] &&
616
+ !unconditionallyRequiredIds[id]
617
+ ) {
618
+ knownCjsModuleTypes[id] = IS_WRAPPED_COMMONJS;
619
+ }
620
+ };
621
+
622
+ const analyzeRequiredModule = async (parentId, resolved, isConditional, loadModule) => {
623
+ const childId = resolved.id;
624
+ requiredIds[childId] = true;
625
+ if (!(isConditional || knownCjsModuleTypes[parentId] === IS_WRAPPED_COMMONJS)) {
626
+ unconditionallyRequiredIds[childId] = true;
627
+ }
628
+
629
+ getDependencies(parentId).add(childId);
630
+ if (!isCyclic(childId)) {
631
+ // This makes sure the current transform handler waits for all direct
632
+ // dependencies to be loaded and transformed and therefore for all
633
+ // transitive CommonJS dependencies to be loaded as well so that all
634
+ // cycles have been found and knownCjsModuleTypes is reliable.
635
+ await loadModule(resolved);
636
+ }
637
+ };
638
+
639
+ const getTypeForImportedModule = async (resolved, loadModule) => {
640
+ if (resolved.id in knownCjsModuleTypes) {
641
+ // This handles cyclic ES dependencies
642
+ return knownCjsModuleTypes[resolved.id];
643
+ }
644
+ const {
645
+ meta: { commonjs }
646
+ } = await loadModule(resolved);
647
+ return (commonjs && commonjs.isCommonJS) || false;
648
+ };
552
649
 
553
650
  return {
554
651
  getWrappedIds: () =>
@@ -556,19 +653,72 @@ function getResolveRequireSourcesAndGetMeta(extensions, detectCyclesAndCondition
556
653
  (id) => knownCjsModuleTypes[id] === IS_WRAPPED_COMMONJS
557
654
  ),
558
655
  isRequiredId: (id) => requiredIds[id],
559
- resolveRequireSourcesAndGetMeta: (rollupContext) => async (
656
+ async shouldTransformCachedModule({
657
+ id: parentId,
658
+ resolvedSources,
659
+ meta: { commonjs: parentMeta }
660
+ }) {
661
+ // We explicitly track ES modules to handle ciruclar imports
662
+ if (!(parentMeta && parentMeta.isCommonJS)) knownCjsModuleTypes[parentId] = false;
663
+ if (isWrappedId(parentId, ES_IMPORT_SUFFIX)) return false;
664
+ const parentRequires = parentMeta && parentMeta.requires;
665
+ if (parentRequires) {
666
+ setInitialParentType(parentId, parentMeta.initialCommonJSType);
667
+ await Promise.all(
668
+ parentRequires.map(({ resolved, isConditional }) =>
669
+ analyzeRequiredModule(parentId, resolved, isConditional, this.load)
670
+ )
671
+ );
672
+ if (getTypeForFullyAnalyzedModule(parentId) !== parentMeta.isCommonJS) {
673
+ return true;
674
+ }
675
+ for (const {
676
+ resolved: { id }
677
+ } of parentRequires) {
678
+ if (getTypeForFullyAnalyzedModule(id) !== parentMeta.isRequiredCommonJS[id]) {
679
+ return true;
680
+ }
681
+ }
682
+ // Now that we decided to go with the cached copy, neither the parent
683
+ // module nor any of its children may change types anymore
684
+ fullyAnalyzedModules[parentId] = true;
685
+ for (const {
686
+ resolved: { id }
687
+ } of parentRequires) {
688
+ fullyAnalyzedModules[id] = true;
689
+ }
690
+ }
691
+ const parentRequireSet = new Set((parentRequires || []).map(({ resolved: { id } }) => id));
692
+ return (
693
+ await Promise.all(
694
+ Object.keys(resolvedSources)
695
+ .map((source) => resolvedSources[source])
696
+ .filter(({ id }) => !parentRequireSet.has(id))
697
+ .map(async (resolved) => {
698
+ if (isWrappedId(resolved.id, ES_IMPORT_SUFFIX)) {
699
+ return (
700
+ (await getTypeForImportedModule(
701
+ (await this.load({ id: resolved.id })).meta.commonjs.resolved,
702
+ this.load
703
+ )) !== IS_WRAPPED_COMMONJS
704
+ );
705
+ }
706
+ return (await getTypeForImportedModule(resolved, this.load)) === IS_WRAPPED_COMMONJS;
707
+ })
708
+ )
709
+ ).some((shouldTransform) => shouldTransform);
710
+ },
711
+ /* eslint-disable no-param-reassign */
712
+ resolveRequireSourcesAndUpdateMeta: (rollupContext) => async (
560
713
  parentId,
561
714
  isParentCommonJS,
715
+ parentMeta,
562
716
  sources
563
717
  ) => {
564
- knownCjsModuleTypes[parentId] = knownCjsModuleTypes[parentId] || isParentCommonJS;
565
- if (
566
- knownCjsModuleTypes[parentId] &&
567
- requiredIds[parentId] &&
568
- !unconditionallyRequiredIds[parentId]
569
- ) {
570
- knownCjsModuleTypes[parentId] = IS_WRAPPED_COMMONJS;
571
- }
718
+ parentMeta.initialCommonJSType = isParentCommonJS;
719
+ parentMeta.requires = [];
720
+ parentMeta.isRequiredCommonJS = Object.create(null);
721
+ setInitialParentType(parentId, isParentCommonJS);
572
722
  const requireTargets = await Promise.all(
573
723
  sources.map(async ({ source, isConditional }) => {
574
724
  // Never analyze or proxy internal modules
@@ -577,9 +727,7 @@ function getResolveRequireSourcesAndGetMeta(extensions, detectCyclesAndCondition
577
727
  }
578
728
  const resolved =
579
729
  (await rollupContext.resolve(source, parentId, {
580
- custom: {
581
- 'node-resolve': { isRequire: true }
582
- }
730
+ custom: { 'node-resolve': { isRequire: true } }
583
731
  })) || resolveExtensions(source, parentId, extensions);
584
732
  if (!resolved) {
585
733
  return { id: wrapId(source, EXTERNAL_SUFFIX), allowProxy: false };
@@ -588,78 +736,60 @@ function getResolveRequireSourcesAndGetMeta(extensions, detectCyclesAndCondition
588
736
  if (resolved.external) {
589
737
  return { id: wrapId(childId, EXTERNAL_SUFFIX), allowProxy: false };
590
738
  }
591
- requiredIds[childId] = true;
592
- if (
593
- !(
594
- detectCyclesAndConditional &&
595
- (isConditional || knownCjsModuleTypes[parentId] === IS_WRAPPED_COMMONJS)
596
- )
597
- ) {
598
- unconditionallyRequiredIds[childId] = true;
599
- }
600
- const parentDependentModules = getDependentModules(parentId);
601
- const childDependentModules = getDependentModules(childId);
602
- childDependentModules[parentId] = true;
603
- for (const dependentId of Object.keys(parentDependentModules)) {
604
- childDependentModules[dependentId] = true;
605
- }
606
- if (parentDependentModules[childId]) {
607
- // If we depend on one of our dependencies, we have a cycle. Then all modules that
608
- // we depend on that also depend on the same module are part of a cycle as well.
609
- if (detectCyclesAndConditional && isParentCommonJS) {
610
- knownCjsModuleTypes[parentId] = IS_WRAPPED_COMMONJS;
611
- knownCjsModuleTypes[childId] = IS_WRAPPED_COMMONJS;
612
- for (const dependentId of Object.keys(parentDependentModules)) {
613
- if (getDependentModules(dependentId)[childId]) {
614
- knownCjsModuleTypes[dependentId] = IS_WRAPPED_COMMONJS;
615
- }
616
- }
617
- }
618
- } else {
619
- // This makes sure the current transform handler waits for all direct dependencies to be
620
- // loaded and transformed and therefore for all transitive CommonJS dependencies to be
621
- // loaded as well so that all cycles have been found and knownCjsModuleTypes is reliable.
622
- await rollupContext.load(resolved);
623
- }
739
+ parentMeta.requires.push({ resolved, isConditional });
740
+ await analyzeRequiredModule(parentId, resolved, isConditional, rollupContext.load);
624
741
  return { id: childId, allowProxy: true };
625
742
  })
626
743
  );
627
- return {
628
- requireTargets: requireTargets.map(({ id: dependencyId, allowProxy }, index) => {
629
- const isCommonJS = knownCjsModuleTypes[dependencyId];
630
- return {
631
- source: sources[index].source,
632
- id: allowProxy
633
- ? isCommonJS === IS_WRAPPED_COMMONJS
634
- ? wrapId(dependencyId, WRAPPED_SUFFIX)
635
- : wrapId(dependencyId, PROXY_SUFFIX)
636
- : dependencyId,
637
- isCommonJS
638
- };
639
- }),
640
- usesRequireWrapper: knownCjsModuleTypes[parentId] === IS_WRAPPED_COMMONJS
641
- };
744
+ parentMeta.isCommonJS = getTypeForFullyAnalyzedModule(parentId);
745
+ fullyAnalyzedModules[parentId] = true;
746
+ return requireTargets.map(({ id: dependencyId, allowProxy }, index) => {
747
+ // eslint-disable-next-line no-multi-assign
748
+ const isCommonJS = (parentMeta.isRequiredCommonJS[
749
+ dependencyId
750
+ ] = getTypeForFullyAnalyzedModule(dependencyId));
751
+ fullyAnalyzedModules[dependencyId] = true;
752
+ return {
753
+ source: sources[index].source,
754
+ id: allowProxy
755
+ ? isCommonJS === IS_WRAPPED_COMMONJS
756
+ ? wrapId(dependencyId, WRAPPED_SUFFIX)
757
+ : wrapId(dependencyId, PROXY_SUFFIX)
758
+ : dependencyId,
759
+ isCommonJS
760
+ };
761
+ });
642
762
  }
643
763
  };
644
764
  }
645
765
 
646
- function validateRollupVersion(rollupVersion, peerDependencyVersion) {
647
- const [major, minor] = rollupVersion.split('.').map(Number);
648
- const versionRegexp = /\^(\d+\.\d+)\.\d+/g;
766
+ function validateVersion(actualVersion, peerDependencyVersion, name) {
767
+ const versionRegexp = /\^(\d+\.\d+\.\d+)/g;
649
768
  let minMajor = Infinity;
650
769
  let minMinor = Infinity;
770
+ let minPatch = Infinity;
651
771
  let foundVersion;
652
772
  // eslint-disable-next-line no-cond-assign
653
773
  while ((foundVersion = versionRegexp.exec(peerDependencyVersion))) {
654
- const [foundMajor, foundMinor] = foundVersion[1].split('.').map(Number);
774
+ const [foundMajor, foundMinor, foundPatch] = foundVersion[1].split('.').map(Number);
655
775
  if (foundMajor < minMajor) {
656
776
  minMajor = foundMajor;
657
777
  minMinor = foundMinor;
778
+ minPatch = foundPatch;
658
779
  }
659
780
  }
660
- if (major < minMajor || (major === minMajor && minor < minMinor)) {
781
+ if (!actualVersion) {
782
+ throw new Error(
783
+ `Insufficient ${name} version: "@rollup/plugin-commonjs" requires at least ${name}@${minMajor}.${minMinor}.${minPatch}.`
784
+ );
785
+ }
786
+ const [major, minor, patch] = actualVersion.split('.').map(Number);
787
+ if (
788
+ major < minMajor ||
789
+ (major === minMajor && (minor < minMinor || (minor === minMinor && patch < minPatch)))
790
+ ) {
661
791
  throw new Error(
662
- `Insufficient Rollup version: "@rollup/plugin-commonjs" requires at least rollup@${minMajor}.${minMinor} but found rollup@${rollupVersion}.`
792
+ `Insufficient ${name} version: "@rollup/plugin-commonjs" requires at least ${name}@${minMajor}.${minMinor}.${minPatch} but found ${name}@${actualVersion}.`
663
793
  );
664
794
  }
665
795
  }
@@ -1102,17 +1232,20 @@ function getRequireHandlers() {
1102
1232
  exportsName,
1103
1233
  id,
1104
1234
  exportMode,
1105
- resolveRequireSourcesAndGetMeta,
1235
+ resolveRequireSourcesAndUpdateMeta,
1106
1236
  needsRequireWrapper,
1107
1237
  isEsModule,
1108
- usesRequire,
1109
- getIgnoreTryCatchRequireStatementMode
1238
+ isDynamicRequireModulesEnabled,
1239
+ getIgnoreTryCatchRequireStatementMode,
1240
+ commonjsMeta
1110
1241
  ) {
1111
1242
  const imports = [];
1112
1243
  imports.push(`import * as ${helpersName} from "${HELPERS_ID}";`);
1113
- if (usesRequire) {
1244
+ if (dynamicRequireName) {
1114
1245
  imports.push(
1115
- `import { commonjsRequire as ${dynamicRequireName} } from "${DYNAMIC_MODULES_ID}";`
1246
+ `import { ${
1247
+ isDynamicRequireModulesEnabled ? CREATE_COMMONJS_REQUIRE_EXPORT : COMMONJS_REQUIRE_EXPORT
1248
+ } as ${dynamicRequireName} } from "${DYNAMIC_MODULES_ID}";`
1116
1249
  );
1117
1250
  }
1118
1251
  if (exportMode === 'module') {
@@ -1127,9 +1260,10 @@ function getRequireHandlers() {
1127
1260
  );
1128
1261
  }
1129
1262
  const requiresBySource = collectSources(requireExpressions);
1130
- const { requireTargets, usesRequireWrapper } = await resolveRequireSourcesAndGetMeta(
1263
+ const requireTargets = await resolveRequireSourcesAndUpdateMeta(
1131
1264
  id,
1132
1265
  needsRequireWrapper ? IS_WRAPPED_COMMONJS : !isEsModule,
1266
+ commonjsMeta,
1133
1267
  Object.keys(requiresBySource).map((source) => {
1134
1268
  return {
1135
1269
  source,
@@ -1144,10 +1278,7 @@ function getRequireHandlers() {
1144
1278
  getIgnoreTryCatchRequireStatementMode,
1145
1279
  magicString
1146
1280
  );
1147
- return {
1148
- importBlock: imports.length ? `${imports.join('\n')}\n\n` : '',
1149
- usesRequireWrapper
1150
- };
1281
+ return imports.length ? `${imports.join('\n')}\n\n` : '';
1151
1282
  }
1152
1283
 
1153
1284
  return {
@@ -1250,9 +1381,10 @@ async function transformCommonjs(
1250
1381
  astCache,
1251
1382
  defaultIsModuleExports,
1252
1383
  needsRequireWrapper,
1253
- resolveRequireSourcesAndGetMeta,
1384
+ resolveRequireSourcesAndUpdateMeta,
1254
1385
  isRequired,
1255
- checkDynamicRequire
1386
+ checkDynamicRequire,
1387
+ commonjsMeta
1256
1388
  ) {
1257
1389
  const ast = astCache || tryParse(parse, code, id);
1258
1390
  const magicString = new MagicString(code);
@@ -1293,6 +1425,7 @@ async function transformCommonjs(
1293
1425
  const topLevelDefineCompiledEsmExpressions = [];
1294
1426
  const replacedGlobal = [];
1295
1427
  const replacedDynamicRequires = [];
1428
+ const importedVariables = new Set();
1296
1429
 
1297
1430
  walk(ast, {
1298
1431
  enter(node, parent) {
@@ -1398,20 +1531,19 @@ async function transformCommonjs(
1398
1531
  isRequire(node.callee.object, scope) &&
1399
1532
  node.callee.property.name === 'resolve'
1400
1533
  ) {
1401
- checkDynamicRequire();
1534
+ checkDynamicRequire(node.start);
1402
1535
  uses.require = true;
1403
1536
  const requireNode = node.callee.object;
1404
- magicString.appendLeft(
1405
- node.end - 1,
1406
- `,${JSON.stringify(
1407
- dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath
1408
- )}`
1409
- );
1410
1537
  replacedDynamicRequires.push(requireNode);
1411
1538
  return;
1412
1539
  }
1413
1540
 
1414
1541
  if (!isRequireExpression(node, scope)) {
1542
+ const keypath = getKeypath(node.callee);
1543
+ if (keypath && importedVariables.has(keypath.name)) {
1544
+ // Heuristic to deoptimize requires after a required function has been called
1545
+ currentConditionalNodeEnd = Infinity;
1546
+ }
1415
1547
  return;
1416
1548
  }
1417
1549
 
@@ -1420,15 +1552,9 @@ async function transformCommonjs(
1420
1552
 
1421
1553
  if (hasDynamicArguments(node)) {
1422
1554
  if (isDynamicRequireModulesEnabled) {
1423
- magicString.appendLeft(
1424
- node.end - 1,
1425
- `, ${JSON.stringify(
1426
- dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath
1427
- )}`
1428
- );
1555
+ checkDynamicRequire(node.start);
1429
1556
  }
1430
1557
  if (!ignoreDynamicRequires) {
1431
- checkDynamicRequire();
1432
1558
  replacedDynamicRequires.push(node.callee);
1433
1559
  }
1434
1560
  return;
@@ -1446,6 +1572,11 @@ async function transformCommonjs(
1446
1572
  currentConditionalNodeEnd !== null,
1447
1573
  parent.type === 'ExpressionStatement' ? parent : node
1448
1574
  );
1575
+ if (parent.type === 'VariableDeclarator' && parent.id.type === 'Identifier') {
1576
+ for (const name of extractAssignedNames(parent.id)) {
1577
+ importedVariables.add(name);
1578
+ }
1579
+ }
1449
1580
  }
1450
1581
  return;
1451
1582
  }
@@ -1486,7 +1617,6 @@ async function transformCommonjs(
1486
1617
  return;
1487
1618
  }
1488
1619
  if (!ignoreDynamicRequires) {
1489
- checkDynamicRequire();
1490
1620
  if (isShorthandProperty(parent)) {
1491
1621
  magicString.prependRight(node.start, 'require: ');
1492
1622
  }
@@ -1570,9 +1700,10 @@ async function transformCommonjs(
1570
1700
  if (scope.contains(flattened.name)) return;
1571
1701
 
1572
1702
  if (
1573
- flattened.keypath === 'module.exports' ||
1574
- flattened.keypath === 'module' ||
1575
- flattened.keypath === 'exports'
1703
+ !isEsModule &&
1704
+ (flattened.keypath === 'module.exports' ||
1705
+ flattened.keypath === 'module' ||
1706
+ flattened.keypath === 'exports')
1576
1707
  ) {
1577
1708
  magicString.overwrite(node.start, node.end, `'object'`, {
1578
1709
  storeName: false
@@ -1600,7 +1731,13 @@ async function transformCommonjs(
1600
1731
  const requireName = deconflict([scope], globals, `require${capitalize(nameBase)}`);
1601
1732
  const isRequiredName = deconflict([scope], globals, `hasRequired${capitalize(nameBase)}`);
1602
1733
  const helpersName = deconflict([scope], globals, 'commonjsHelpers');
1603
- const dynamicRequireName = deconflict([scope], globals, 'commonjsRequire');
1734
+ const dynamicRequireName =
1735
+ replacedDynamicRequires.length > 0 &&
1736
+ deconflict(
1737
+ [scope],
1738
+ globals,
1739
+ isDynamicRequireModulesEnabled ? CREATE_COMMONJS_REQUIRE_EXPORT : COMMONJS_REQUIRE_EXPORT
1740
+ );
1604
1741
  const deconflictedExportNames = Object.create(null);
1605
1742
  for (const [exportName, { scopes }] of exportsAssignmentsByName) {
1606
1743
  deconflictedExportNames[exportName] = deconflict([...scopes], globals, exportName);
@@ -1612,10 +1749,17 @@ async function transformCommonjs(
1612
1749
  });
1613
1750
  }
1614
1751
  for (const node of replacedDynamicRequires) {
1615
- magicString.overwrite(node.start, node.end, dynamicRequireName, {
1616
- contentOnly: true,
1617
- storeName: true
1618
- });
1752
+ magicString.overwrite(
1753
+ node.start,
1754
+ node.end,
1755
+ isDynamicRequireModulesEnabled
1756
+ ? `${dynamicRequireName}(${JSON.stringify(virtualDynamicRequirePath)})`
1757
+ : dynamicRequireName,
1758
+ {
1759
+ contentOnly: true,
1760
+ storeName: true
1761
+ }
1762
+ );
1619
1763
  }
1620
1764
 
1621
1765
  // We cannot wrap ES/mixed modules
@@ -1635,7 +1779,7 @@ async function transformCommonjs(
1635
1779
  ) &&
1636
1780
  (ignoreGlobal || !uses.global)
1637
1781
  ) {
1638
- return { meta: { commonjs: { isCommonJS: false, isMixedModule: false } } };
1782
+ return { meta: { commonjs: { isCommonJS: false } } };
1639
1783
  }
1640
1784
 
1641
1785
  let leadingComment = '';
@@ -1645,7 +1789,9 @@ async function transformCommonjs(
1645
1789
  magicString.remove(0, commentEnd).trim();
1646
1790
  }
1647
1791
 
1648
- const exportMode = shouldWrap
1792
+ const exportMode = isEsModule
1793
+ ? 'none'
1794
+ : shouldWrap
1649
1795
  ? uses.module
1650
1796
  ? 'module'
1651
1797
  : 'exports'
@@ -1657,7 +1803,7 @@ async function transformCommonjs(
1657
1803
  ? 'exports'
1658
1804
  : 'module';
1659
1805
 
1660
- const { importBlock, usesRequireWrapper } = await rewriteRequireExpressionsAndGetImportBlock(
1806
+ const importBlock = await rewriteRequireExpressionsAndGetImportBlock(
1661
1807
  magicString,
1662
1808
  topLevelDeclarations,
1663
1809
  reassignedNames,
@@ -1667,12 +1813,14 @@ async function transformCommonjs(
1667
1813
  exportsName,
1668
1814
  id,
1669
1815
  exportMode,
1670
- resolveRequireSourcesAndGetMeta,
1816
+ resolveRequireSourcesAndUpdateMeta,
1671
1817
  needsRequireWrapper,
1672
1818
  isEsModule,
1673
- uses.require,
1674
- getIgnoreTryCatchRequireStatementMode
1819
+ isDynamicRequireModulesEnabled,
1820
+ getIgnoreTryCatchRequireStatementMode,
1821
+ commonjsMeta
1675
1822
  );
1823
+ const usesRequireWrapper = commonjsMeta.isCommonJS === IS_WRAPPED_COMMONJS;
1676
1824
  const exportBlock = isEsModule
1677
1825
  ? ''
1678
1826
  : rewriteExportsAndGetExportsBlock(
@@ -1725,15 +1873,12 @@ function ${requireName} () {
1725
1873
  code: magicString.toString(),
1726
1874
  map: sourceMap ? magicString.generateMap() : null,
1727
1875
  syntheticNamedExports: isEsModule || usesRequireWrapper ? false : '__moduleExports',
1728
- meta: {
1729
- commonjs: {
1730
- isCommonJS: !isEsModule && (usesRequireWrapper ? IS_WRAPPED_COMMONJS : true),
1731
- isMixedModule: isEsModule
1732
- }
1733
- }
1876
+ meta: { commonjs: commonjsMeta }
1734
1877
  };
1735
1878
  }
1736
1879
 
1880
+ const PLUGIN_NAME = 'commonjs';
1881
+
1737
1882
  function commonjs(options = {}) {
1738
1883
  const {
1739
1884
  ignoreGlobal,
@@ -1761,11 +1906,6 @@ function commonjs(options = {}) {
1761
1906
  const defaultIsModuleExports =
1762
1907
  typeof options.defaultIsModuleExports === 'boolean' ? options.defaultIsModuleExports : 'auto';
1763
1908
 
1764
- const {
1765
- resolveRequireSourcesAndGetMeta,
1766
- getWrappedIds,
1767
- isRequiredId
1768
- } = getResolveRequireSourcesAndGetMeta(extensions, detectCyclesAndConditional);
1769
1909
  const dynamicRequireRoot =
1770
1910
  typeof options.dynamicRequireRoot === 'string'
1771
1911
  ? resolve(options.dynamicRequireRoot)
@@ -1776,9 +1916,6 @@ function commonjs(options = {}) {
1776
1916
  );
1777
1917
  const isDynamicRequireModulesEnabled = dynamicRequireModules.size > 0;
1778
1918
 
1779
- const esModulesWithDefaultExport = new Set();
1780
- const esModulesWithNamedExports = new Set();
1781
-
1782
1919
  const ignoreRequire =
1783
1920
  typeof options.ignore === 'function'
1784
1921
  ? options.ignore
@@ -1806,41 +1943,50 @@ function commonjs(options = {}) {
1806
1943
 
1807
1944
  const sourceMap = options.sourceMap !== false;
1808
1945
 
1946
+ // Initialized in buildStart
1947
+ let requireResolver;
1948
+
1809
1949
  function transformAndCheckExports(code, id) {
1810
1950
  const { isEsModule, hasDefaultExport, hasNamedExports, ast } = analyzeTopLevelStatements(
1811
1951
  this.parse,
1812
1952
  code,
1813
1953
  id
1814
1954
  );
1955
+
1956
+ const commonjsMeta = this.getModuleInfo(id).meta.commonjs || {};
1815
1957
  if (hasDefaultExport) {
1816
- esModulesWithDefaultExport.add(id);
1958
+ commonjsMeta.hasDefaultExport = true;
1817
1959
  }
1818
1960
  if (hasNamedExports) {
1819
- esModulesWithNamedExports.add(id);
1961
+ commonjsMeta.hasNamedExports = true;
1820
1962
  }
1821
1963
 
1822
1964
  if (
1823
1965
  !dynamicRequireModules.has(normalizePathSlashes(id)) &&
1824
- (!(hasCjsKeywords(code, ignoreGlobal) || isRequiredId(id)) ||
1966
+ (!(hasCjsKeywords(code, ignoreGlobal) || requireResolver.isRequiredId(id)) ||
1825
1967
  (isEsModule && !options.transformMixedEsModules))
1826
1968
  ) {
1827
- return { meta: { commonjs: { isCommonJS: false } } };
1969
+ commonjsMeta.isCommonJS = false;
1970
+ return { meta: { commonjs: commonjsMeta } };
1828
1971
  }
1829
1972
 
1830
1973
  const needsRequireWrapper =
1831
1974
  !isEsModule &&
1832
1975
  (dynamicRequireModules.has(normalizePathSlashes(id)) || strictRequiresFilter(id));
1833
1976
 
1834
- const checkDynamicRequire = () => {
1977
+ const checkDynamicRequire = (position) => {
1835
1978
  if (id.indexOf(dynamicRequireRoot) !== 0) {
1836
- this.error({
1837
- code: 'DYNAMIC_REQUIRE_OUTSIDE_ROOT',
1838
- id,
1839
- dynamicRequireRoot,
1840
- message: `"${id}" contains dynamic require statements but it is not within the current dynamicRequireRoot "${dynamicRequireRoot}". You should set dynamicRequireRoot to "${dirname(
1841
- id
1842
- )}" or one of its parent directories.`
1843
- });
1979
+ this.error(
1980
+ {
1981
+ code: 'DYNAMIC_REQUIRE_OUTSIDE_ROOT',
1982
+ id,
1983
+ dynamicRequireRoot,
1984
+ message: `"${id}" contains dynamic require statements but it is not within the current dynamicRequireRoot "${dynamicRequireRoot}". You should set dynamicRequireRoot to "${dirname(
1985
+ id
1986
+ )}" or one of its parent directories.`
1987
+ },
1988
+ position
1989
+ );
1844
1990
  }
1845
1991
  };
1846
1992
 
@@ -1860,14 +2006,15 @@ function commonjs(options = {}) {
1860
2006
  ast,
1861
2007
  defaultIsModuleExports,
1862
2008
  needsRequireWrapper,
1863
- resolveRequireSourcesAndGetMeta(this),
1864
- isRequiredId(id),
1865
- checkDynamicRequire
2009
+ requireResolver.resolveRequireSourcesAndUpdateMeta(this),
2010
+ requireResolver.isRequiredId(id),
2011
+ checkDynamicRequire,
2012
+ commonjsMeta
1866
2013
  );
1867
2014
  }
1868
2015
 
1869
2016
  return {
1870
- name: 'commonjs',
2017
+ name: PLUGIN_NAME,
1871
2018
 
1872
2019
  version,
1873
2020
 
@@ -1875,7 +2022,7 @@ function commonjs(options = {}) {
1875
2022
  // We inject the resolver in the beginning so that "catch-all-resolver" like node-resolver
1876
2023
  // do not prevent our plugin from resolving entry points ot proxies.
1877
2024
  const plugins = Array.isArray(rawOptions.plugins)
1878
- ? rawOptions.plugins
2025
+ ? [...rawOptions.plugins]
1879
2026
  : rawOptions.plugins
1880
2027
  ? [rawOptions.plugins]
1881
2028
  : [];
@@ -1886,18 +2033,23 @@ function commonjs(options = {}) {
1886
2033
  return { ...rawOptions, plugins };
1887
2034
  },
1888
2035
 
1889
- buildStart() {
1890
- validateRollupVersion(this.meta.rollupVersion, peerDependencies.rollup);
2036
+ buildStart({ plugins }) {
2037
+ validateVersion(this.meta.rollupVersion, peerDependencies.rollup, 'rollup');
2038
+ const nodeResolve = plugins.find(({ name }) => name === 'node-resolve');
2039
+ if (nodeResolve) {
2040
+ validateVersion(nodeResolve.version, '^13.0.6', '@rollup/plugin-node-resolve');
2041
+ }
1891
2042
  if (options.namedExports != null) {
1892
2043
  this.warn(
1893
2044
  'The namedExports option from "@rollup/plugin-commonjs" is deprecated. Named exports are now handled automatically.'
1894
2045
  );
1895
2046
  }
2047
+ requireResolver = getRequireResolver(extensions, detectCyclesAndConditional);
1896
2048
  },
1897
2049
 
1898
2050
  buildEnd() {
1899
2051
  if (options.strictRequires === 'debug') {
1900
- const wrappedIds = getWrappedIds();
2052
+ const wrappedIds = requireResolver.getWrappedIds();
1901
2053
  if (wrappedIds.length) {
1902
2054
  this.warn({
1903
2055
  code: 'WRAPPED_IDS',
@@ -1946,6 +2098,15 @@ function commonjs(options = {}) {
1946
2098
  );
1947
2099
  }
1948
2100
 
2101
+ // entry suffix is just appended to not mess up relative external resolution
2102
+ if (id.endsWith(ENTRY_SUFFIX)) {
2103
+ return getEntryProxy(
2104
+ id.slice(0, -ENTRY_SUFFIX.length),
2105
+ defaultIsModuleExports,
2106
+ this.getModuleInfo
2107
+ );
2108
+ }
2109
+
1949
2110
  if (isWrappedId(id, ES_IMPORT_SUFFIX)) {
1950
2111
  return getEsImportProxy(unwrapId(id, ES_IMPORT_SUFFIX), defaultIsModuleExports);
1951
2112
  }
@@ -1961,18 +2122,16 @@ function commonjs(options = {}) {
1961
2122
 
1962
2123
  if (isWrappedId(id, PROXY_SUFFIX)) {
1963
2124
  const actualId = unwrapId(id, PROXY_SUFFIX);
1964
- return getStaticRequireProxy(
1965
- actualId,
1966
- getRequireReturnsDefault(actualId),
1967
- esModulesWithDefaultExport,
1968
- esModulesWithNamedExports,
1969
- this.load
1970
- );
2125
+ return getStaticRequireProxy(actualId, getRequireReturnsDefault(actualId), this.load);
1971
2126
  }
1972
2127
 
1973
2128
  return null;
1974
2129
  },
1975
2130
 
2131
+ shouldTransformCachedModule(...args) {
2132
+ return requireResolver.shouldTransformCachedModule.call(this, ...args);
2133
+ },
2134
+
1976
2135
  transform(code, id) {
1977
2136
  const extName = extname(id);
1978
2137
  if (extName !== '.cjs' && (!filter(id) || !extensions.includes(extName))) {
@@ -1989,4 +2148,4 @@ function commonjs(options = {}) {
1989
2148
  }
1990
2149
 
1991
2150
  export { commonjs as default };
1992
- //# sourceMappingURL=index.es.js.map
2151
+ //# sourceMappingURL=index.js.map