@rollup/plugin-commonjs 18.0.0 → 19.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.es.js CHANGED
@@ -9,7 +9,7 @@ import isReference from 'is-reference';
9
9
  import { sync } from 'resolve';
10
10
 
11
11
  var peerDependencies = {
12
- rollup: "^2.30.0"
12
+ rollup: "^2.38.3"
13
13
  };
14
14
 
15
15
  function tryParse(parse, code, id) {
@@ -83,6 +83,8 @@ const unwrapId = (wrappedId, suffix) => wrappedId.slice(1, -suffix.length);
83
83
  const PROXY_SUFFIX = '?commonjs-proxy';
84
84
  const REQUIRE_SUFFIX = '?commonjs-require';
85
85
  const EXTERNAL_SUFFIX = '?commonjs-external';
86
+ const EXPORTS_SUFFIX = '?commonjs-exports';
87
+ const MODULE_SUFFIX = '?commonjs-module';
86
88
 
87
89
  const DYNAMIC_REGISTER_SUFFIX = '?commonjs-dynamic-register';
88
90
  const DYNAMIC_JSON_PREFIX = '\0commonjs-dynamic-json:';
@@ -129,33 +131,38 @@ export function getAugmentedNamespace(n) {
129
131
  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.');`;
130
132
 
131
133
  const HELPER_NON_DYNAMIC = `
132
- export function createCommonjsModule(fn) {
133
- var module = { exports: {} }
134
- return fn(module, module.exports), module.exports;
135
- }
136
-
137
134
  export function commonjsRequire (path) {
138
135
  ${FAILED_REQUIRE_ERROR}
139
136
  }
140
137
  `;
141
138
 
142
139
  const getDynamicHelpers = (ignoreDynamicRequires) => `
143
- export function createCommonjsModule(fn, basedir, module) {
144
- return module = {
145
- path: basedir,
140
+ export function createModule(modulePath) {
141
+ return {
142
+ path: modulePath,
146
143
  exports: {},
147
144
  require: function (path, base) {
148
- return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
145
+ return commonjsRequire(path, base == null ? modulePath : base);
149
146
  }
150
- }, fn(module, module.exports), module.exports;
147
+ };
151
148
  }
152
149
 
153
150
  export function commonjsRegister (path, loader) {
154
151
  DYNAMIC_REQUIRE_LOADERS[path] = loader;
155
152
  }
156
153
 
154
+ export function commonjsRegisterOrShort (path, to) {
155
+ const resolvedPath = commonjsResolveImpl(path, null, true);
156
+ if (resolvedPath !== null && DYNAMIC_REQUIRE_CACHE[resolvedPath]) {
157
+ DYNAMIC_REQUIRE_CACHE[path] = DYNAMIC_REQUIRE_CACHE[resolvedPath];
158
+ } else {
159
+ DYNAMIC_REQUIRE_SHORTS[path] = to;
160
+ }
161
+ }
162
+
157
163
  const DYNAMIC_REQUIRE_LOADERS = Object.create(null);
158
164
  const DYNAMIC_REQUIRE_CACHE = Object.create(null);
165
+ const DYNAMIC_REQUIRE_SHORTS = Object.create(null);
159
166
  const DEFAULT_PARENT_MODULE = {
160
167
  id: '<' + 'rollup>', exports: {}, parent: undefined, filename: null, loaded: false, children: [], paths: []
161
168
  };
@@ -260,10 +267,13 @@ export function commonjsResolveImpl (path, originalModuleDir, testCache) {
260
267
  const resolvedPath = relPath + CHECKED_EXTENSIONS[extensionIndex];
261
268
  if (DYNAMIC_REQUIRE_CACHE[resolvedPath]) {
262
269
  return resolvedPath;
263
- };
270
+ }
271
+ if (DYNAMIC_REQUIRE_SHORTS[resolvedPath]) {
272
+ return resolvedPath;
273
+ }
264
274
  if (DYNAMIC_REQUIRE_LOADERS[resolvedPath]) {
265
275
  return resolvedPath;
266
- };
276
+ }
267
277
  }
268
278
  if (!shouldTryNodeModules) break;
269
279
  const nextDir = normalize(originalModuleDir + '/..');
@@ -282,10 +292,17 @@ export function commonjsResolve (path, originalModuleDir) {
282
292
  }
283
293
 
284
294
  export function commonjsRequire (path, originalModuleDir) {
285
- const resolvedPath = commonjsResolveImpl(path, originalModuleDir, true);
295
+ let resolvedPath = commonjsResolveImpl(path, originalModuleDir, true);
286
296
  if (resolvedPath !== null) {
287
297
  let cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath];
288
298
  if (cachedModule) return cachedModule.exports;
299
+ let shortTo = DYNAMIC_REQUIRE_SHORTS[resolvedPath];
300
+ if (shortTo) {
301
+ cachedModule = DYNAMIC_REQUIRE_CACHE[shortTo];
302
+ if (cachedModule)
303
+ return cachedModule.exports;
304
+ resolvedPath = commonjsResolveImpl(shortTo, null, true);
305
+ }
289
306
  const loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath];
290
307
  if (loader) {
291
308
  DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = {
@@ -326,16 +343,20 @@ function getHelpersModule(isDynamicRequireModulesEnabled, ignoreDynamicRequires)
326
343
 
327
344
  /* eslint-disable import/prefer-default-export */
328
345
 
329
- function deconflict(scope, globals, identifier) {
346
+ function deconflict(scopes, globals, identifier) {
330
347
  let i = 1;
331
348
  let deconflicted = makeLegalIdentifier(identifier);
349
+ const hasConflicts = () =>
350
+ scopes.some((scope) => scope.contains(deconflicted)) || globals.has(deconflicted);
332
351
 
333
- while (scope.contains(deconflicted) || globals.has(deconflicted)) {
352
+ while (hasConflicts()) {
334
353
  deconflicted = makeLegalIdentifier(`${identifier}_${i}`);
335
354
  i += 1;
336
355
  }
337
- // eslint-disable-next-line no-param-reassign
338
- scope.declarations[deconflicted] = true;
356
+
357
+ for (const scope of scopes) {
358
+ scope.declarations[deconflicted] = true;
359
+ }
339
360
 
340
361
  return deconflicted;
341
362
  }
@@ -378,15 +399,13 @@ function getPackageEntryPoint(dirPath) {
378
399
  }
379
400
 
380
401
  function getDynamicPackagesModule(dynamicRequireModuleDirPaths, commonDir) {
381
- let code = `const commonjsRegister = require('${HELPERS_ID}?commonjsRegister');`;
402
+ let code = `const commonjsRegisterOrShort = require('${HELPERS_ID}?commonjsRegisterOrShort');`;
382
403
  for (const dir of dynamicRequireModuleDirPaths) {
383
404
  const entryPoint = getPackageEntryPoint(dir);
384
405
 
385
- code += `\ncommonjsRegister(${JSON.stringify(
406
+ code += `\ncommonjsRegisterOrShort(${JSON.stringify(
386
407
  getVirtualPathForDynamicRequirePath(dir, commonDir)
387
- )}, function (module, exports) {
388
- module.exports = require(${JSON.stringify(normalizePathSlashes(join(dir, entryPoint)))});
389
- });`;
408
+ )}, ${JSON.stringify(getVirtualPathForDynamicRequirePath(join(dir, entryPoint), commonDir))});`;
390
409
  }
391
410
  return code;
392
411
  }
@@ -397,28 +416,18 @@ function getDynamicPackagesEntryIntro(
397
416
  ) {
398
417
  let dynamicImports = Array.from(
399
418
  dynamicRequireModuleSet,
400
- (dynamicId) => `require(${JSON.stringify(wrapModuleRegisterProxy(dynamicId))});`
419
+ (dynamicId) => `require(${JSON.stringify(wrapId(dynamicId, DYNAMIC_REGISTER_SUFFIX))});`
401
420
  ).join('\n');
402
421
 
403
422
  if (dynamicRequireModuleDirPaths.length) {
404
- dynamicImports += `require(${JSON.stringify(wrapModuleRegisterProxy(DYNAMIC_PACKAGES_ID))});`;
423
+ dynamicImports += `require(${JSON.stringify(
424
+ wrapId(DYNAMIC_PACKAGES_ID, DYNAMIC_REGISTER_SUFFIX)
425
+ )});`;
405
426
  }
406
427
 
407
428
  return dynamicImports;
408
429
  }
409
430
 
410
- function wrapModuleRegisterProxy(id) {
411
- return wrapId(id, DYNAMIC_REGISTER_SUFFIX);
412
- }
413
-
414
- function unwrapModuleRegisterProxy(id) {
415
- return unwrapId(id, DYNAMIC_REGISTER_SUFFIX);
416
- }
417
-
418
- function isModuleRegisterProxy(id) {
419
- return isWrappedId(id, DYNAMIC_REGISTER_SUFFIX);
420
- }
421
-
422
431
  function isDynamicModuleImport(id, dynamicRequireModuleSet) {
423
432
  const normalizedPath = normalizePathSlashes(id);
424
433
  return dynamicRequireModuleSet.has(normalizedPath) && !normalizedPath.endsWith('.json');
@@ -451,39 +460,37 @@ function getDynamicRequirePaths(patterns) {
451
460
  return { dynamicRequireModuleSet, dynamicRequireModuleDirPaths };
452
461
  }
453
462
 
454
- const isCjsPromises = new Map();
455
-
456
- function getIsCjsPromise(id) {
457
- let isCjsPromise = isCjsPromises.get(id);
458
- if (isCjsPromise) return isCjsPromise.promise;
463
+ function getCommonJSMetaPromise(commonJSMetaPromises, id) {
464
+ let commonJSMetaPromise = commonJSMetaPromises.get(id);
465
+ if (commonJSMetaPromise) return commonJSMetaPromise.promise;
459
466
 
460
467
  const promise = new Promise((resolve) => {
461
- isCjsPromise = {
468
+ commonJSMetaPromise = {
462
469
  resolve,
463
470
  promise: null
464
471
  };
465
- isCjsPromises.set(id, isCjsPromise);
472
+ commonJSMetaPromises.set(id, commonJSMetaPromise);
466
473
  });
467
- isCjsPromise.promise = promise;
474
+ commonJSMetaPromise.promise = promise;
468
475
 
469
476
  return promise;
470
477
  }
471
478
 
472
- function setIsCjsPromise(id, resolution) {
473
- const isCjsPromise = isCjsPromises.get(id);
474
- if (isCjsPromise) {
475
- if (isCjsPromise.resolve) {
476
- isCjsPromise.resolve(resolution);
477
- isCjsPromise.resolve = null;
479
+ function setCommonJSMetaPromise(commonJSMetaPromises, id, commonjsMeta) {
480
+ const commonJSMetaPromise = commonJSMetaPromises.get(id);
481
+ if (commonJSMetaPromise) {
482
+ if (commonJSMetaPromise.resolve) {
483
+ commonJSMetaPromise.resolve(commonjsMeta);
484
+ commonJSMetaPromise.resolve = null;
478
485
  }
479
486
  } else {
480
- isCjsPromises.set(id, { promise: Promise.resolve(resolution), resolve: null });
487
+ commonJSMetaPromises.set(id, { promise: Promise.resolve(commonjsMeta), resolve: null });
481
488
  }
482
489
  }
483
490
 
484
491
  // e.g. id === "commonjsHelpers?commonjsRegister"
485
492
  function getSpecificHelperProxy(id) {
486
- return `export {${id.split('?')[1]} as default} from '${HELPERS_ID}';`;
493
+ return `export {${id.split('?')[1]} as default} from "${HELPERS_ID}";`;
487
494
  }
488
495
 
489
496
  function getUnknownRequireProxy(id, requireReturnsDefault) {
@@ -523,16 +530,17 @@ async function getStaticRequireProxy(
523
530
  id,
524
531
  requireReturnsDefault,
525
532
  esModulesWithDefaultExport,
526
- esModulesWithNamedExports
533
+ esModulesWithNamedExports,
534
+ commonJsMetaPromises
527
535
  ) {
528
536
  const name = getName(id);
529
- const isCjs = await getIsCjsPromise(id);
530
- if (isCjs) {
531
- return `import { __moduleExports } from ${JSON.stringify(id)}; export default __moduleExports;`;
532
- } else if (isCjs === null) {
537
+ const commonjsMeta = await getCommonJSMetaPromise(commonJsMetaPromises, id);
538
+ if (commonjsMeta && commonjsMeta.isCommonJS) {
539
+ return `export { __moduleExports as default } from ${JSON.stringify(id)};`;
540
+ } else if (commonjsMeta === null) {
533
541
  return getUnknownRequireProxy(id, requireReturnsDefault);
534
542
  } else if (!requireReturnsDefault) {
535
- return `import {getAugmentedNamespace} from "${HELPERS_ID}"; import * as ${name} from ${JSON.stringify(
543
+ return `import { getAugmentedNamespace } from "${HELPERS_ID}"; import * as ${name} from ${JSON.stringify(
536
544
  id
537
545
  )}; export default /*@__PURE__*/getAugmentedNamespace(${name});`;
538
546
  } else if (
@@ -543,7 +551,7 @@ async function getStaticRequireProxy(
543
551
  ) {
544
552
  return `import * as ${name} from ${JSON.stringify(id)}; export default ${name};`;
545
553
  }
546
- return `export {default} from ${JSON.stringify(id)};`;
554
+ return `export { default } from ${JSON.stringify(id)};`;
547
555
  }
548
556
 
549
557
  /* eslint-disable no-param-reassign, no-undefined */
@@ -580,12 +588,17 @@ function getResolveId(extensions) {
580
588
  }
581
589
 
582
590
  return function resolveId(importee, rawImporter) {
591
+ if (isWrappedId(importee, MODULE_SUFFIX) || isWrappedId(importee, EXPORTS_SUFFIX)) {
592
+ return importee;
593
+ }
594
+
583
595
  const importer =
584
- rawImporter && isModuleRegisterProxy(rawImporter)
585
- ? unwrapModuleRegisterProxy(rawImporter)
596
+ rawImporter && isWrappedId(rawImporter, DYNAMIC_REGISTER_SUFFIX)
597
+ ? unwrapId(rawImporter, DYNAMIC_REGISTER_SUFFIX)
586
598
  : rawImporter;
587
599
 
588
- // Proxies are only importing resolved ids, no need to resolve again
600
+ // Except for exports, proxies are only importing resolved ids,
601
+ // no need to resolve again
589
602
  if (importer && isWrappedId(importer, PROXY_SUFFIX)) {
590
603
  return importee;
591
604
  }
@@ -599,9 +612,9 @@ function getResolveId(extensions) {
599
612
  } else if (isRequiredModule) {
600
613
  importee = unwrapId(importee, REQUIRE_SUFFIX);
601
614
 
602
- isModuleRegistration = isModuleRegisterProxy(importee);
615
+ isModuleRegistration = isWrappedId(importee, DYNAMIC_REGISTER_SUFFIX);
603
616
  if (isModuleRegistration) {
604
- importee = unwrapModuleRegisterProxy(importee);
617
+ importee = unwrapId(importee, DYNAMIC_REGISTER_SUFFIX);
605
618
  }
606
619
  }
607
620
 
@@ -628,7 +641,7 @@ function getResolveId(extensions) {
628
641
  resolved.id = wrapId(resolved.id, resolved.external ? EXTERNAL_SUFFIX : PROXY_SUFFIX);
629
642
  resolved.external = false;
630
643
  } else if (resolved && isModuleRegistration) {
631
- resolved.id = wrapModuleRegisterProxy(resolved.id);
644
+ resolved.id = wrapId(resolved.id, DYNAMIC_REGISTER_SUFFIX);
632
645
  } else if (!resolved && (isProxyModule || isRequiredModule)) {
633
646
  return { id: wrapId(importee, EXTERNAL_SUFFIX), external: false };
634
647
  }
@@ -728,8 +741,6 @@ function isDefineCompiledEsm(node) {
728
741
  }
729
742
 
730
743
  function getDefinePropertyCallName(node, targetName) {
731
- const targetNames = targetName.split('.');
732
-
733
744
  const {
734
745
  callee: { object, property }
735
746
  } = node;
@@ -737,6 +748,7 @@ function getDefinePropertyCallName(node, targetName) {
737
748
  if (!property || property.type !== 'Identifier' || property.name !== 'defineProperty') return;
738
749
  if (node.arguments.length !== 3) return;
739
750
 
751
+ const targetNames = targetName.split('.');
740
752
  const [target, key, value] = node.arguments;
741
753
  if (targetNames.length === 1) {
742
754
  if (target.type !== 'Identifier' || target.name !== targetNames[0]) {
@@ -763,117 +775,199 @@ function getDefinePropertyCallName(node, targetName) {
763
775
  return { key: key.value, value: valueProperty.value };
764
776
  }
765
777
 
766
- function isLocallyShadowed(name, scope) {
767
- while (scope.parent) {
768
- if (scope.declarations[name]) {
769
- return true;
770
- }
771
- // eslint-disable-next-line no-param-reassign
772
- scope = scope.parent;
773
- }
774
- return false;
775
- }
776
-
777
778
  function isShorthandProperty(parent) {
778
779
  return parent && parent.type === 'Property' && parent.shorthand;
779
780
  }
780
781
 
781
- function wrapCode(magicString, uses, moduleName, HELPERS_NAME, virtualDynamicRequirePath) {
782
- const args = `module${uses.exports ? ', exports' : ''}`;
782
+ function hasDefineEsmProperty(node) {
783
+ return node.properties.some((property) => {
784
+ if (
785
+ property.type === 'Property' &&
786
+ property.key.type === 'Identifier' &&
787
+ property.key.name === '__esModule' &&
788
+ isTruthy(property.value)
789
+ ) {
790
+ return true;
791
+ }
792
+ return false;
793
+ });
794
+ }
783
795
 
796
+ function wrapCode(magicString, uses, moduleName, exportsName) {
797
+ const args = [];
798
+ const passedArgs = [];
799
+ if (uses.module) {
800
+ args.push('module');
801
+ passedArgs.push(moduleName);
802
+ }
803
+ if (uses.exports) {
804
+ args.push('exports');
805
+ passedArgs.push(exportsName);
806
+ }
784
807
  magicString
785
808
  .trim()
786
- .prepend(`var ${moduleName} = ${HELPERS_NAME}.createCommonjsModule(function (${args}) {\n`)
787
- .append(
788
- `\n}${virtualDynamicRequirePath ? `, ${JSON.stringify(virtualDynamicRequirePath)}` : ''});`
789
- );
809
+ .prepend(`(function (${args.join(', ')}) {\n`)
810
+ .append(`\n}(${passedArgs.join(', ')}));`);
790
811
  }
791
812
 
792
813
  function rewriteExportsAndGetExportsBlock(
793
814
  magicString,
794
815
  moduleName,
816
+ exportsName,
795
817
  wrapped,
796
- topLevelModuleExportsAssignments,
797
- topLevelExportsAssignmentsByName,
818
+ moduleExportsAssignments,
819
+ firstTopLevelModuleExportsAssignment,
820
+ exportsAssignmentsByName,
821
+ topLevelAssignments,
798
822
  defineCompiledEsmExpressions,
799
- deconflict,
800
- isRestorableCompiledEsm,
823
+ deconflictedExportNames,
801
824
  code,
802
- uses,
803
- HELPERS_NAME
825
+ HELPERS_NAME,
826
+ exportMode,
827
+ detectWrappedDefault,
828
+ defaultIsModuleExports
804
829
  ) {
805
- const namedExportDeclarations = [`export { ${moduleName} as __moduleExports };`];
806
- const moduleExportsPropertyAssignments = [];
807
- let deconflictedDefaultExportName;
830
+ const exports = [];
831
+ const exportDeclarations = [];
832
+
833
+ if (exportMode === 'replace') {
834
+ getExportsForReplacedModuleExports(
835
+ magicString,
836
+ exports,
837
+ exportDeclarations,
838
+ moduleExportsAssignments,
839
+ firstTopLevelModuleExportsAssignment,
840
+ exportsName
841
+ );
842
+ } else {
843
+ exports.push(`${exportsName} as __moduleExports`);
844
+ if (wrapped) {
845
+ getExportsWhenWrapping(
846
+ exportDeclarations,
847
+ exportsName,
848
+ detectWrappedDefault,
849
+ HELPERS_NAME,
850
+ defaultIsModuleExports
851
+ );
852
+ } else {
853
+ getExports(
854
+ magicString,
855
+ exports,
856
+ exportDeclarations,
857
+ moduleExportsAssignments,
858
+ exportsAssignmentsByName,
859
+ deconflictedExportNames,
860
+ topLevelAssignments,
861
+ moduleName,
862
+ exportsName,
863
+ defineCompiledEsmExpressions,
864
+ HELPERS_NAME,
865
+ defaultIsModuleExports
866
+ );
867
+ }
868
+ }
869
+ if (exports.length) {
870
+ exportDeclarations.push(`export { ${exports.join(', ')} };`);
871
+ }
808
872
 
809
- if (!wrapped) {
810
- let hasModuleExportsAssignment = false;
811
- const namedExportProperties = [];
873
+ return `\n\n${exportDeclarations.join('\n')}`;
874
+ }
812
875
 
813
- // Collect and rewrite module.exports assignments
814
- for (const { left } of topLevelModuleExportsAssignments) {
815
- hasModuleExportsAssignment = true;
816
- magicString.overwrite(left.start, left.end, `var ${moduleName}`);
817
- }
876
+ function getExportsForReplacedModuleExports(
877
+ magicString,
878
+ exports,
879
+ exportDeclarations,
880
+ moduleExportsAssignments,
881
+ firstTopLevelModuleExportsAssignment,
882
+ exportsName
883
+ ) {
884
+ for (const { left } of moduleExportsAssignments) {
885
+ magicString.overwrite(left.start, left.end, exportsName);
886
+ }
887
+ magicString.prependRight(firstTopLevelModuleExportsAssignment.left.start, 'var ');
888
+ exports.push(`${exportsName} as __moduleExports`);
889
+ exportDeclarations.push(`export default ${exportsName};`);
890
+ }
818
891
 
819
- // Collect and rewrite named exports
820
- for (const [exportName, node] of topLevelExportsAssignmentsByName) {
821
- const deconflicted = deconflict(exportName);
822
- magicString.overwrite(node.start, node.left.end, `var ${deconflicted}`);
823
-
824
- if (exportName === 'default') {
825
- deconflictedDefaultExportName = deconflicted;
826
- } else {
827
- namedExportDeclarations.push(
828
- exportName === deconflicted
829
- ? `export { ${exportName} };`
830
- : `export { ${deconflicted} as ${exportName} };`
831
- );
832
- }
892
+ function getExportsWhenWrapping(
893
+ exportDeclarations,
894
+ exportsName,
895
+ detectWrappedDefault,
896
+ HELPERS_NAME,
897
+ defaultIsModuleExports
898
+ ) {
899
+ exportDeclarations.push(
900
+ `export default ${
901
+ detectWrappedDefault && defaultIsModuleExports === 'auto'
902
+ ? `/*@__PURE__*/${HELPERS_NAME}.getDefaultExportFromCjs(${exportsName})`
903
+ : defaultIsModuleExports === false
904
+ ? `${exportsName}.default`
905
+ : exportsName
906
+ };`
907
+ );
908
+ }
909
+
910
+ function getExports(
911
+ magicString,
912
+ exports,
913
+ exportDeclarations,
914
+ moduleExportsAssignments,
915
+ exportsAssignmentsByName,
916
+ deconflictedExportNames,
917
+ topLevelAssignments,
918
+ moduleName,
919
+ exportsName,
920
+ defineCompiledEsmExpressions,
921
+ HELPERS_NAME,
922
+ defaultIsModuleExports
923
+ ) {
924
+ let deconflictedDefaultExportName;
925
+ // Collect and rewrite module.exports assignments
926
+ for (const { left } of moduleExportsAssignments) {
927
+ magicString.overwrite(left.start, left.end, `${moduleName}.exports`);
928
+ }
833
929
 
834
- if (hasModuleExportsAssignment) {
835
- moduleExportsPropertyAssignments.push(`${moduleName}.${exportName} = ${deconflicted};`);
836
- } else {
837
- namedExportProperties.push(`\t${exportName}: ${deconflicted}`);
930
+ // Collect and rewrite named exports
931
+ for (const [exportName, { nodes }] of exportsAssignmentsByName) {
932
+ const deconflicted = deconflictedExportNames[exportName];
933
+ let needsDeclaration = true;
934
+ for (const node of nodes) {
935
+ let replacement = `${deconflicted} = ${exportsName}.${exportName}`;
936
+ if (needsDeclaration && topLevelAssignments.has(node)) {
937
+ replacement = `var ${replacement}`;
938
+ needsDeclaration = false;
838
939
  }
940
+ magicString.overwrite(node.start, node.left.end, replacement);
941
+ }
942
+ if (needsDeclaration) {
943
+ magicString.prepend(`var ${deconflicted};\n`);
839
944
  }
840
945
 
841
- // Regenerate CommonJS namespace
842
- if (!hasModuleExportsAssignment) {
843
- const moduleExports = `{\n${namedExportProperties.join(',\n')}\n}`;
844
- magicString
845
- .trim()
846
- .append(
847
- `\n\nvar ${moduleName} = ${
848
- isRestorableCompiledEsm
849
- ? `/*#__PURE__*/Object.defineProperty(${moduleExports}, '__esModule', {value: true})`
850
- : moduleExports
851
- };`
852
- );
946
+ if (exportName === 'default') {
947
+ deconflictedDefaultExportName = deconflicted;
948
+ } else {
949
+ exports.push(exportName === deconflicted ? exportName : `${deconflicted} as ${exportName}`);
853
950
  }
854
951
  }
855
952
 
856
- // Generate default export
857
- const defaultExport = [];
858
- if (isRestorableCompiledEsm) {
859
- defaultExport.push(`export default ${deconflictedDefaultExportName || moduleName};`);
860
- } else if (
861
- (wrapped || deconflictedDefaultExportName) &&
862
- (defineCompiledEsmExpressions.length > 0 || code.indexOf('__esModule') >= 0)
863
- ) {
864
- // eslint-disable-next-line no-param-reassign
865
- uses.commonjsHelpers = true;
866
- defaultExport.push(
867
- `export default /*@__PURE__*/${HELPERS_NAME}.getDefaultExportFromCjs(${moduleName});`
868
- );
869
- } else {
870
- defaultExport.push(`export default ${moduleName};`);
953
+ // Collect and rewrite exports.__esModule assignments
954
+ let isRestorableCompiledEsm = false;
955
+ for (const expression of defineCompiledEsmExpressions) {
956
+ isRestorableCompiledEsm = true;
957
+ const moduleExportsExpression =
958
+ expression.type === 'CallExpression' ? expression.arguments[0] : expression.left.object;
959
+ magicString.overwrite(moduleExportsExpression.start, moduleExportsExpression.end, exportsName);
871
960
  }
872
961
 
873
- return `\n\n${defaultExport
874
- .concat(namedExportDeclarations)
875
- .concat(moduleExportsPropertyAssignments)
876
- .join('\n')}`;
962
+ if (!isRestorableCompiledEsm || defaultIsModuleExports === true) {
963
+ exportDeclarations.push(`export default ${exportsName};`);
964
+ } else if (moduleExportsAssignments.length === 0 || defaultIsModuleExports === false) {
965
+ exports.push(`${deconflictedDefaultExportName || exportsName} as default`);
966
+ } else {
967
+ exportDeclarations.push(
968
+ `export default /*@__PURE__*/${HELPERS_NAME}.getDefaultExportFromCjs(${exportsName});`
969
+ );
970
+ }
877
971
  }
878
972
 
879
973
  function isRequireStatement(node, scope) {
@@ -991,44 +1085,46 @@ function getRequireHandlers() {
991
1085
  topLevelDeclarations,
992
1086
  topLevelRequireDeclarators,
993
1087
  reassignedNames,
994
- helpersNameIfUsed,
995
- dynamicRegisterSources
1088
+ helpersName,
1089
+ dynamicRegisterSources,
1090
+ moduleName,
1091
+ exportsName,
1092
+ id,
1093
+ exportMode
996
1094
  ) {
997
- const removedDeclarators = getDeclaratorsReplacedByImportsAndSetImportNames(
998
- topLevelRequireDeclarators,
999
- requiredByNode,
1000
- reassignedNames
1001
- );
1002
1095
  setRemainingImportNamesAndRewriteRequires(
1003
1096
  requireExpressionsWithUsedReturnValue,
1004
1097
  requiredByNode,
1005
1098
  magicString
1006
1099
  );
1007
- removeDeclaratorsFromDeclarations(topLevelDeclarations, removedDeclarators, magicString);
1008
- const importBlock = `${(helpersNameIfUsed
1009
- ? [`import * as ${helpersNameIfUsed} from '${HELPERS_ID}';`]
1010
- : []
1011
- )
1012
- .concat(
1013
- // dynamic registers first, as the may be required in the other modules
1014
- [...dynamicRegisterSources].map((source) => `import '${wrapId(source, REQUIRE_SUFFIX)}';`),
1015
-
1016
- // now the actual modules so that they are analyzed before creating the proxies;
1017
- // no need to do this for virtual modules as we never proxy them
1018
- requiredSources
1019
- .filter((source) => !source.startsWith('\0'))
1020
- .map((source) => `import '${wrapId(source, REQUIRE_SUFFIX)}';`),
1021
-
1022
- // now the proxy modules
1023
- requiredSources.map((source) => {
1024
- const { name, nodesUsingRequired } = requiredBySource[source];
1025
- return `import ${nodesUsingRequired.length ? `${name} from ` : ``}'${
1026
- source.startsWith('\0') ? source : wrapId(source, PROXY_SUFFIX)
1027
- }';`;
1028
- })
1029
- )
1030
- .join('\n')}`;
1031
- return importBlock ? `${importBlock}\n\n` : '';
1100
+ const imports = [];
1101
+ imports.push(`import * as ${helpersName} from "${HELPERS_ID}";`);
1102
+ if (exportMode === 'module') {
1103
+ imports.push(
1104
+ `import { __module as ${moduleName}, exports as ${exportsName} } from ${JSON.stringify(
1105
+ wrapId(id, MODULE_SUFFIX)
1106
+ )}`
1107
+ );
1108
+ } else if (exportMode === 'exports') {
1109
+ imports.push(
1110
+ `import { __exports as ${exportsName} } from ${JSON.stringify(wrapId(id, EXPORTS_SUFFIX))}`
1111
+ );
1112
+ }
1113
+ for (const source of dynamicRegisterSources) {
1114
+ imports.push(`import ${JSON.stringify(wrapId(source, REQUIRE_SUFFIX))};`);
1115
+ }
1116
+ for (const source of requiredSources) {
1117
+ if (!source.startsWith('\0')) {
1118
+ imports.push(`import ${JSON.stringify(wrapId(source, REQUIRE_SUFFIX))};`);
1119
+ }
1120
+ const { name, nodesUsingRequired } = requiredBySource[source];
1121
+ imports.push(
1122
+ `import ${nodesUsingRequired.length ? `${name} from ` : ''}${JSON.stringify(
1123
+ source.startsWith('\0') ? source : wrapId(source, PROXY_SUFFIX)
1124
+ )};`
1125
+ );
1126
+ }
1127
+ return imports.length ? `${imports.join('\n')}\n\n` : '';
1032
1128
  }
1033
1129
 
1034
1130
  return {
@@ -1038,30 +1134,6 @@ function getRequireHandlers() {
1038
1134
  };
1039
1135
  }
1040
1136
 
1041
- function getDeclaratorsReplacedByImportsAndSetImportNames(
1042
- topLevelRequireDeclarators,
1043
- requiredByNode,
1044
- reassignedNames
1045
- ) {
1046
- const removedDeclarators = new Set();
1047
- for (const declarator of topLevelRequireDeclarators) {
1048
- const { required } = requiredByNode.get(declarator.init);
1049
- if (!required.name) {
1050
- const potentialName = declarator.id.name;
1051
- if (
1052
- !reassignedNames.has(potentialName) &&
1053
- !required.nodesUsingRequired.some((node) =>
1054
- isLocallyShadowed(potentialName, requiredByNode.get(node).scope)
1055
- )
1056
- ) {
1057
- required.name = potentialName;
1058
- removedDeclarators.add(declarator);
1059
- }
1060
- }
1061
- }
1062
- return removedDeclarators;
1063
- }
1064
-
1065
1137
  function setRemainingImportNamesAndRewriteRequires(
1066
1138
  requireExpressionsWithUsedReturnValue,
1067
1139
  requiredByNode,
@@ -1083,25 +1155,6 @@ function setRemainingImportNamesAndRewriteRequires(
1083
1155
  }
1084
1156
  }
1085
1157
 
1086
- function removeDeclaratorsFromDeclarations(topLevelDeclarations, removedDeclarators, magicString) {
1087
- for (const declaration of topLevelDeclarations) {
1088
- let keepDeclaration = false;
1089
- let [{ start }] = declaration.declarations;
1090
- for (const declarator of declaration.declarations) {
1091
- if (removedDeclarators.has(declarator)) {
1092
- magicString.remove(start, declarator.end);
1093
- } else if (!keepDeclaration) {
1094
- magicString.remove(start, declarator.start);
1095
- keepDeclaration = true;
1096
- }
1097
- start = declarator.end;
1098
- }
1099
- if (!keepDeclaration) {
1100
- magicString.remove(declaration.start, declaration.end);
1101
- }
1102
- }
1103
- }
1104
-
1105
1158
  /* eslint-disable no-param-reassign, no-shadow, no-underscore-dangle, no-continue */
1106
1159
 
1107
1160
  const exportsPattern = /^(?:module\.)?exports(?:\.([a-zA-Z_$][a-zA-Z_$0-9]*))?$/;
@@ -1122,7 +1175,8 @@ function transformCommonjs(
1122
1175
  dynamicRequireModuleSet,
1123
1176
  disableWrap,
1124
1177
  commonDir,
1125
- astCache
1178
+ astCache,
1179
+ defaultIsModuleExports
1126
1180
  ) {
1127
1181
  const ast = astCache || tryParse(parse, code, id);
1128
1182
  const magicString = new MagicString(code);
@@ -1130,9 +1184,9 @@ function transformCommonjs(
1130
1184
  module: false,
1131
1185
  exports: false,
1132
1186
  global: false,
1133
- require: false,
1134
- commonjsHelpers: false
1187
+ require: false
1135
1188
  };
1189
+ let usesDynamicRequire = false;
1136
1190
  const virtualDynamicRequirePath =
1137
1191
  isDynamicRequireModulesEnabled && getVirtualPathForDynamicRequirePath(dirname(id), commonDir);
1138
1192
  let scope = attachScopes(ast, 'scope');
@@ -1140,13 +1194,11 @@ function transformCommonjs(
1140
1194
  let programDepth = 0;
1141
1195
  let currentTryBlockEnd = null;
1142
1196
  let shouldWrap = false;
1143
- const defineCompiledEsmExpressions = [];
1144
1197
 
1145
1198
  const globals = new Set();
1146
1199
 
1147
1200
  // TODO technically wrong since globals isn't populated yet, but ¯\_(ツ)_/¯
1148
- const HELPERS_NAME = deconflict(scope, globals, 'commonjsHelpers');
1149
- const namedExports = {};
1201
+ const HELPERS_NAME = deconflict([scope], globals, 'commonjsHelpers');
1150
1202
  const dynamicRegisterSources = new Set();
1151
1203
  let hasRemovedRequire = false;
1152
1204
 
@@ -1163,8 +1215,13 @@ function transformCommonjs(
1163
1215
  const topLevelDeclarations = [];
1164
1216
  const topLevelRequireDeclarators = new Set();
1165
1217
  const skippedNodes = new Set();
1166
- const topLevelModuleExportsAssignments = [];
1167
- const topLevelExportsAssignmentsByName = new Map();
1218
+ const moduleAccessScopes = new Set([scope]);
1219
+ const exportsAccessScopes = new Set([scope]);
1220
+ const moduleExportsAssignments = [];
1221
+ let firstTopLevelModuleExportsAssignment = null;
1222
+ const exportsAssignmentsByName = new Map();
1223
+ const topLevelAssignments = new Set();
1224
+ const topLevelDefineCompiledEsmExpressions = [];
1168
1225
 
1169
1226
  walk(ast, {
1170
1227
  enter(node, parent) {
@@ -1204,30 +1261,46 @@ function transformCommonjs(
1204
1261
  uses[flattened.name] = true;
1205
1262
 
1206
1263
  // we're dealing with `module.exports = ...` or `[module.]exports.foo = ...` –
1207
- if (programDepth > 3) {
1208
- shouldWrap = true;
1264
+ if (flattened.keypath === 'module.exports') {
1265
+ moduleExportsAssignments.push(node);
1266
+ if (programDepth > 3) {
1267
+ moduleAccessScopes.add(scope);
1268
+ } else if (!firstTopLevelModuleExportsAssignment) {
1269
+ firstTopLevelModuleExportsAssignment = node;
1270
+ }
1271
+
1272
+ if (defaultIsModuleExports === false) {
1273
+ shouldWrap = true;
1274
+ } else if (defaultIsModuleExports === 'auto') {
1275
+ if (node.right.type === 'ObjectExpression') {
1276
+ if (hasDefineEsmProperty(node.right)) {
1277
+ shouldWrap = true;
1278
+ }
1279
+ } else if (defaultIsModuleExports === false) {
1280
+ shouldWrap = true;
1281
+ }
1282
+ }
1209
1283
  } else if (exportName === KEY_COMPILED_ESM) {
1210
- defineCompiledEsmExpressions.push(parent);
1211
- } else if (flattened.keypath === 'module.exports') {
1212
- topLevelModuleExportsAssignments.push(node);
1213
- } else if (!topLevelExportsAssignmentsByName.has(exportName)) {
1214
- topLevelExportsAssignmentsByName.set(exportName, node);
1284
+ if (programDepth > 3) {
1285
+ shouldWrap = true;
1286
+ } else {
1287
+ topLevelDefineCompiledEsmExpressions.push(node);
1288
+ }
1215
1289
  } else {
1216
- shouldWrap = true;
1290
+ const exportsAssignments = exportsAssignmentsByName.get(exportName) || {
1291
+ nodes: [],
1292
+ scopes: new Set()
1293
+ };
1294
+ exportsAssignments.nodes.push(node);
1295
+ exportsAssignments.scopes.add(scope);
1296
+ exportsAccessScopes.add(scope);
1297
+ exportsAssignmentsByName.set(exportName, exportsAssignments);
1298
+ if (programDepth <= 3) {
1299
+ topLevelAssignments.add(node);
1300
+ }
1217
1301
  }
1218
1302
 
1219
1303
  skippedNodes.add(node.left);
1220
-
1221
- if (flattened.keypath === 'module.exports' && node.right.type === 'ObjectExpression') {
1222
- node.right.properties.forEach((prop) => {
1223
- if (prop.computed || !('key' in prop) || prop.key.type !== 'Identifier') return;
1224
- const { name } = prop.key;
1225
- if (name === makeLegalIdentifier(name)) namedExports[name] = true;
1226
- });
1227
- return;
1228
- }
1229
-
1230
- if (exportsPatternMatch[1]) namedExports[exportsPatternMatch[1]] = true;
1231
1304
  } else {
1232
1305
  for (const name of extractAssignedNames(node.left)) {
1233
1306
  reassignedNames.add(name);
@@ -1239,7 +1312,7 @@ function transformCommonjs(
1239
1312
  if (programDepth === 3 && parent.type === 'ExpressionStatement') {
1240
1313
  // skip special handling for [module.]exports until we know we render this
1241
1314
  skippedNodes.add(node.arguments[0]);
1242
- defineCompiledEsmExpressions.push(parent);
1315
+ topLevelDefineCompiledEsmExpressions.push(node);
1243
1316
  } else {
1244
1317
  shouldWrap = true;
1245
1318
  }
@@ -1267,7 +1340,6 @@ function transformCommonjs(
1267
1340
  storeName: true
1268
1341
  }
1269
1342
  );
1270
- uses.commonjsHelpers = true;
1271
1343
  return;
1272
1344
  }
1273
1345
 
@@ -1294,13 +1366,13 @@ function transformCommonjs(
1294
1366
  }
1295
1367
 
1296
1368
  let sourceId = getRequireStringArg(node);
1297
- const isDynamicRegister = isModuleRegisterProxy(sourceId);
1369
+ const isDynamicRegister = isWrappedId(sourceId, DYNAMIC_REGISTER_SUFFIX);
1298
1370
  if (isDynamicRegister) {
1299
- sourceId = unwrapModuleRegisterProxy(sourceId);
1371
+ sourceId = unwrapId(sourceId, DYNAMIC_REGISTER_SUFFIX);
1300
1372
  if (sourceId.endsWith('.json')) {
1301
1373
  sourceId = DYNAMIC_JSON_PREFIX + sourceId;
1302
1374
  }
1303
- dynamicRegisterSources.add(wrapModuleRegisterProxy(sourceId));
1375
+ dynamicRegisterSources.add(wrapId(sourceId, DYNAMIC_REGISTER_SUFFIX));
1304
1376
  } else {
1305
1377
  if (
1306
1378
  !sourceId.endsWith('.json') &&
@@ -1318,7 +1390,7 @@ function transformCommonjs(
1318
1390
  dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath
1319
1391
  )})`
1320
1392
  );
1321
- uses.commonjsHelpers = true;
1393
+ usesDynamicRequire = true;
1322
1394
  }
1323
1395
  return;
1324
1396
  }
@@ -1375,7 +1447,6 @@ function transformCommonjs(
1375
1447
  magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, {
1376
1448
  storeName: true
1377
1449
  });
1378
- uses.commonjsHelpers = true;
1379
1450
  }
1380
1451
  }
1381
1452
 
@@ -1399,8 +1470,7 @@ function transformCommonjs(
1399
1470
  });
1400
1471
  }
1401
1472
  }
1402
-
1403
- uses.commonjsHelpers = true;
1473
+ usesDynamicRequire = true;
1404
1474
  return;
1405
1475
  case 'module':
1406
1476
  case 'exports':
@@ -1413,11 +1483,12 @@ function transformCommonjs(
1413
1483
  magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsGlobal`, {
1414
1484
  storeName: true
1415
1485
  });
1416
- uses.commonjsHelpers = true;
1417
1486
  }
1418
1487
  return;
1419
1488
  case 'define':
1420
- magicString.overwrite(node.start, node.end, 'undefined', { storeName: true });
1489
+ magicString.overwrite(node.start, node.end, 'undefined', {
1490
+ storeName: true
1491
+ });
1421
1492
  return;
1422
1493
  default:
1423
1494
  globals.add(name);
@@ -1429,7 +1500,6 @@ function transformCommonjs(
1429
1500
  magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, {
1430
1501
  storeName: true
1431
1502
  });
1432
- uses.commonjsHelpers = true;
1433
1503
  skippedNodes.add(node.object);
1434
1504
  skippedNodes.add(node.property);
1435
1505
  }
@@ -1448,7 +1518,6 @@ function transformCommonjs(
1448
1518
  magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsGlobal`, {
1449
1519
  storeName: true
1450
1520
  });
1451
- uses.commonjsHelpers = true;
1452
1521
  }
1453
1522
  }
1454
1523
  return;
@@ -1465,7 +1534,9 @@ function transformCommonjs(
1465
1534
  flattened.keypath === 'module' ||
1466
1535
  flattened.keypath === 'exports'
1467
1536
  ) {
1468
- magicString.overwrite(node.start, node.end, `'object'`, { storeName: false });
1537
+ magicString.overwrite(node.start, node.end, `'object'`, {
1538
+ storeName: false
1539
+ });
1469
1540
  }
1470
1541
  }
1471
1542
  return;
@@ -1483,23 +1554,22 @@ function transformCommonjs(
1483
1554
  }
1484
1555
  });
1485
1556
 
1486
- let isRestorableCompiledEsm = false;
1487
- if (defineCompiledEsmExpressions.length > 0) {
1488
- if (!shouldWrap && defineCompiledEsmExpressions.length === 1) {
1489
- isRestorableCompiledEsm = true;
1490
- magicString.remove(
1491
- defineCompiledEsmExpressions[0].start,
1492
- defineCompiledEsmExpressions[0].end
1493
- );
1494
- } else {
1495
- shouldWrap = true;
1496
- uses.exports = true;
1497
- }
1557
+ const nameBase = getName(id);
1558
+ const exportsName = deconflict([...exportsAccessScopes], globals, nameBase);
1559
+ const moduleName = deconflict([...moduleAccessScopes], globals, `${nameBase}Module`);
1560
+ const deconflictedExportNames = Object.create(null);
1561
+ for (const [exportName, { scopes }] of exportsAssignmentsByName) {
1562
+ deconflictedExportNames[exportName] = deconflict([...scopes], globals, exportName);
1498
1563
  }
1499
1564
 
1500
1565
  // We cannot wrap ES/mixed modules
1501
- shouldWrap = shouldWrap && !disableWrap && !isEsModule;
1502
- uses.commonjsHelpers = uses.commonjsHelpers || shouldWrap;
1566
+ shouldWrap =
1567
+ !isEsModule &&
1568
+ !disableWrap &&
1569
+ (shouldWrap || (uses.exports && moduleExportsAssignments.length > 0));
1570
+ const detectWrappedDefault =
1571
+ shouldWrap &&
1572
+ (topLevelDefineCompiledEsmExpressions.length > 0 || code.indexOf('__esModule') >= 0);
1503
1573
 
1504
1574
  if (
1505
1575
  !(
@@ -1508,17 +1578,15 @@ function transformCommonjs(
1508
1578
  uses.module ||
1509
1579
  uses.exports ||
1510
1580
  uses.require ||
1511
- uses.commonjsHelpers ||
1581
+ usesDynamicRequire ||
1512
1582
  hasRemovedRequire ||
1513
- isRestorableCompiledEsm
1583
+ topLevelDefineCompiledEsmExpressions.length > 0
1514
1584
  ) &&
1515
1585
  (ignoreGlobal || !uses.global)
1516
1586
  ) {
1517
1587
  return { meta: { commonjs: { isCommonJS: false } } };
1518
1588
  }
1519
1589
 
1520
- const moduleName = deconflict(scope, globals, getName(id));
1521
-
1522
1590
  let leadingComment = '';
1523
1591
  if (code.startsWith('/*')) {
1524
1592
  const commentEnd = code.indexOf('*/', 2) + 2;
@@ -1526,33 +1594,53 @@ function transformCommonjs(
1526
1594
  magicString.remove(0, commentEnd).trim();
1527
1595
  }
1528
1596
 
1597
+ const exportMode = shouldWrap
1598
+ ? uses.module
1599
+ ? 'module'
1600
+ : 'exports'
1601
+ : firstTopLevelModuleExportsAssignment
1602
+ ? exportsAssignmentsByName.size === 0 && topLevelDefineCompiledEsmExpressions.length === 0
1603
+ ? 'replace'
1604
+ : 'module'
1605
+ : moduleExportsAssignments.length === 0
1606
+ ? 'exports'
1607
+ : 'module';
1608
+
1609
+ const importBlock = rewriteRequireExpressionsAndGetImportBlock(
1610
+ magicString,
1611
+ topLevelDeclarations,
1612
+ topLevelRequireDeclarators,
1613
+ reassignedNames,
1614
+ HELPERS_NAME,
1615
+ dynamicRegisterSources,
1616
+ moduleName,
1617
+ exportsName,
1618
+ id,
1619
+ exportMode
1620
+ );
1621
+
1529
1622
  const exportBlock = isEsModule
1530
1623
  ? ''
1531
1624
  : rewriteExportsAndGetExportsBlock(
1532
1625
  magicString,
1533
1626
  moduleName,
1627
+ exportsName,
1534
1628
  shouldWrap,
1535
- topLevelModuleExportsAssignments,
1536
- topLevelExportsAssignmentsByName,
1537
- defineCompiledEsmExpressions,
1538
- (name) => deconflict(scope, globals, name),
1539
- isRestorableCompiledEsm,
1629
+ moduleExportsAssignments,
1630
+ firstTopLevelModuleExportsAssignment,
1631
+ exportsAssignmentsByName,
1632
+ topLevelAssignments,
1633
+ topLevelDefineCompiledEsmExpressions,
1634
+ deconflictedExportNames,
1540
1635
  code,
1541
- uses,
1542
- HELPERS_NAME
1636
+ HELPERS_NAME,
1637
+ exportMode,
1638
+ detectWrappedDefault,
1639
+ defaultIsModuleExports
1543
1640
  );
1544
1641
 
1545
- const importBlock = rewriteRequireExpressionsAndGetImportBlock(
1546
- magicString,
1547
- topLevelDeclarations,
1548
- topLevelRequireDeclarators,
1549
- reassignedNames,
1550
- uses.commonjsHelpers && HELPERS_NAME,
1551
- dynamicRegisterSources
1552
- );
1553
-
1554
1642
  if (shouldWrap) {
1555
- wrapCode(magicString, uses, moduleName, HELPERS_NAME, virtualDynamicRequirePath);
1643
+ wrapCode(magicString, uses, moduleName, exportsName);
1556
1644
  }
1557
1645
 
1558
1646
  magicString
@@ -1588,6 +1676,8 @@ function commonjs(options = {}) {
1588
1676
  : Array.isArray(esmExternals)
1589
1677
  ? ((esmExternalIds = new Set(esmExternals)), (id) => esmExternalIds.has(id))
1590
1678
  : () => esmExternals;
1679
+ const defaultIsModuleExports =
1680
+ typeof options.defaultIsModuleExports === 'boolean' ? options.defaultIsModuleExports : 'auto';
1591
1681
 
1592
1682
  const { dynamicRequireModuleSet, dynamicRequireModuleDirPaths } = getDynamicRequirePaths(
1593
1683
  options.dynamicRequireTargets
@@ -1599,6 +1689,7 @@ function commonjs(options = {}) {
1599
1689
 
1600
1690
  const esModulesWithDefaultExport = new Set();
1601
1691
  const esModulesWithNamedExports = new Set();
1692
+ const commonJsMetaPromises = new Map();
1602
1693
 
1603
1694
  const ignoreRequire =
1604
1695
  typeof options.ignore === 'function'
@@ -1651,13 +1742,11 @@ function commonjs(options = {}) {
1651
1742
  return { meta: { commonjs: { isCommonJS: false } } };
1652
1743
  }
1653
1744
 
1654
- let disableWrap = false;
1655
-
1656
- // avoid wrapping in createCommonjsModule, as this is a commonjsRegister call
1657
- if (isModuleRegisterProxy(id)) {
1658
- disableWrap = true;
1745
+ // avoid wrapping as this is a commonjsRegister call
1746
+ const disableWrap = isWrappedId(id, DYNAMIC_REGISTER_SUFFIX);
1747
+ if (disableWrap) {
1659
1748
  // eslint-disable-next-line no-param-reassign
1660
- id = unwrapModuleRegisterProxy(id);
1749
+ id = unwrapId(id, DYNAMIC_REGISTER_SUFFIX);
1661
1750
  }
1662
1751
 
1663
1752
  return transformCommonjs(
@@ -1674,7 +1763,8 @@ function commonjs(options = {}) {
1674
1763
  dynamicRequireModuleSet,
1675
1764
  disableWrap,
1676
1765
  commonDir,
1677
- ast
1766
+ ast,
1767
+ defaultIsModuleExports
1678
1768
  );
1679
1769
  }
1680
1770
 
@@ -1701,6 +1791,39 @@ function commonjs(options = {}) {
1701
1791
  return getSpecificHelperProxy(id);
1702
1792
  }
1703
1793
 
1794
+ if (isWrappedId(id, MODULE_SUFFIX)) {
1795
+ const actualId = unwrapId(id, MODULE_SUFFIX);
1796
+ let name = getName(actualId);
1797
+ let code;
1798
+ if (isDynamicRequireModulesEnabled) {
1799
+ if (['modulePath', 'commonjsRequire', 'createModule'].includes(name)) {
1800
+ name = `${name}_`;
1801
+ }
1802
+ code =
1803
+ `import {commonjsRequire, createModule} from "${HELPERS_ID}";\n` +
1804
+ `var ${name} = createModule(${JSON.stringify(
1805
+ getVirtualPathForDynamicRequirePath(dirname(actualId), commonDir)
1806
+ )});\n` +
1807
+ `export {${name} as __module}`;
1808
+ } else {
1809
+ code = `var ${name} = {exports: {}}; export {${name} as __module}`;
1810
+ }
1811
+ return {
1812
+ code,
1813
+ syntheticNamedExports: '__module',
1814
+ meta: { commonjs: { isCommonJS: false } }
1815
+ };
1816
+ }
1817
+
1818
+ if (isWrappedId(id, EXPORTS_SUFFIX)) {
1819
+ const actualId = unwrapId(id, EXPORTS_SUFFIX);
1820
+ const name = getName(actualId);
1821
+ return {
1822
+ code: `var ${name} = {}; export {${name} as __exports}`,
1823
+ meta: { commonjs: { isCommonJS: false } }
1824
+ };
1825
+ }
1826
+
1704
1827
  if (isWrappedId(id, EXTERNAL_SUFFIX)) {
1705
1828
  const actualId = unwrapId(id, EXTERNAL_SUFFIX);
1706
1829
  return getUnknownRequireProxy(
@@ -1721,9 +1844,9 @@ function commonjs(options = {}) {
1721
1844
  return `export default require(${JSON.stringify(normalizePathSlashes(id))});`;
1722
1845
  }
1723
1846
 
1724
- if (isModuleRegisterProxy(id)) {
1847
+ if (isWrappedId(id, DYNAMIC_REGISTER_SUFFIX)) {
1725
1848
  return getDynamicRequireProxy(
1726
- normalizePathSlashes(unwrapModuleRegisterProxy(id)),
1849
+ normalizePathSlashes(unwrapId(id, DYNAMIC_REGISTER_SUFFIX)),
1727
1850
  commonDir
1728
1851
  );
1729
1852
  }
@@ -1734,7 +1857,8 @@ function commonjs(options = {}) {
1734
1857
  actualId,
1735
1858
  getRequireReturnsDefault(actualId),
1736
1859
  esModulesWithDefaultExport,
1737
- esModulesWithNamedExports
1860
+ esModulesWithNamedExports,
1861
+ commonJsMetaPromises
1738
1862
  );
1739
1863
  }
1740
1864
 
@@ -1744,8 +1868,8 @@ function commonjs(options = {}) {
1744
1868
  transform(code, rawId) {
1745
1869
  let id = rawId;
1746
1870
 
1747
- if (isModuleRegisterProxy(id)) {
1748
- id = unwrapModuleRegisterProxy(id);
1871
+ if (isWrappedId(id, DYNAMIC_REGISTER_SUFFIX)) {
1872
+ id = unwrapId(id, DYNAMIC_REGISTER_SUFFIX);
1749
1873
  }
1750
1874
 
1751
1875
  const extName = extname(id);
@@ -1765,16 +1889,12 @@ function commonjs(options = {}) {
1765
1889
  }
1766
1890
  },
1767
1891
 
1768
- // eslint-disable-next-line no-shadow
1769
- moduleParsed({ id, meta: { commonjs } }) {
1770
- if (commonjs) {
1771
- const isCjs = commonjs.isCommonJS;
1772
- if (isCjs != null) {
1773
- setIsCjsPromise(id, isCjs);
1774
- return;
1775
- }
1892
+ moduleParsed({ id, meta: { commonjs: commonjsMeta } }) {
1893
+ if (commonjsMeta && commonjsMeta.isCommonJS != null) {
1894
+ setCommonJSMetaPromise(commonJsMetaPromises, id, commonjsMeta);
1895
+ return;
1776
1896
  }
1777
- setIsCjsPromise(id, null);
1897
+ setCommonJSMetaPromise(commonJsMetaPromises, id, null);
1778
1898
  }
1779
1899
  };
1780
1900
  }