@rollup/plugin-commonjs 15.0.0 → 17.1.0

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
@@ -1,32 +1,90 @@
1
- import { basename, extname, dirname, sep, resolve, join } from 'path';
1
+ import { basename, extname, dirname, sep, join, resolve } from 'path';
2
2
  import { makeLegalIdentifier, attachScopes, extractAssignedNames, createFilter } from '@rollup/pluginutils';
3
3
  import getCommonDir from 'commondir';
4
4
  import { existsSync, readFileSync, statSync } from 'fs';
5
+ import glob from 'glob';
5
6
  import { walk } from 'estree-walker';
6
7
  import MagicString from 'magic-string';
7
- import { sync } from 'resolve';
8
8
  import isReference from 'is-reference';
9
- import glob from 'glob';
9
+ import { sync } from 'resolve';
10
10
 
11
11
  var peerDependencies = {
12
- rollup: "^2.22.0"
12
+ rollup: "^2.30.0"
13
13
  };
14
14
 
15
- const PROXY_SUFFIX = '?commonjs-proxy';
16
- const getProxyId = (id) => `\0${id}${PROXY_SUFFIX}`;
17
- const getIdFromProxyId = (proxyId) => proxyId.slice(1, -PROXY_SUFFIX.length);
15
+ function tryParse(parse, code, id) {
16
+ try {
17
+ return parse(code, { allowReturnOutsideFunction: true });
18
+ } catch (err) {
19
+ err.message += ` in ${id}`;
20
+ throw err;
21
+ }
22
+ }
18
23
 
19
- const EXTERNAL_SUFFIX = '?commonjs-external';
20
- const getExternalProxyId = (id) => `\0${id}${EXTERNAL_SUFFIX}`;
21
- const getIdFromExternalProxyId = (proxyId) => proxyId.slice(1, -EXTERNAL_SUFFIX.length);
24
+ const firstpassGlobal = /\b(?:require|module|exports|global)\b/;
22
25
 
23
- const VIRTUAL_PATH_BASE = '/$$rollup_base$$';
24
- const getVirtualPathForDynamicRequirePath = (path, commonDir) => {
25
- if (path.startsWith(commonDir)) return VIRTUAL_PATH_BASE + path.slice(commonDir.length);
26
- return path;
27
- };
26
+ const firstpassNoGlobal = /\b(?:require|module|exports)\b/;
27
+
28
+ function hasCjsKeywords(code, ignoreGlobal) {
29
+ const firstpass = ignoreGlobal ? firstpassNoGlobal : firstpassGlobal;
30
+ return firstpass.test(code);
31
+ }
32
+
33
+ /* eslint-disable no-underscore-dangle */
34
+
35
+ function analyzeTopLevelStatements(parse, code, id) {
36
+ const ast = tryParse(parse, code, id);
37
+
38
+ let isEsModule = false;
39
+ let hasDefaultExport = false;
40
+ let hasNamedExports = false;
41
+
42
+ for (const node of ast.body) {
43
+ switch (node.type) {
44
+ case 'ExportDefaultDeclaration':
45
+ isEsModule = true;
46
+ hasDefaultExport = true;
47
+ break;
48
+ case 'ExportNamedDeclaration':
49
+ isEsModule = true;
50
+ if (node.declaration) {
51
+ hasNamedExports = true;
52
+ } else {
53
+ for (const specifier of node.specifiers) {
54
+ if (specifier.exported.name === 'default') {
55
+ hasDefaultExport = true;
56
+ } else {
57
+ hasNamedExports = true;
58
+ }
59
+ }
60
+ }
61
+ break;
62
+ case 'ExportAllDeclaration':
63
+ isEsModule = true;
64
+ if (node.exported && node.exported.name === 'default') {
65
+ hasDefaultExport = true;
66
+ } else {
67
+ hasNamedExports = true;
68
+ }
69
+ break;
70
+ case 'ImportDeclaration':
71
+ isEsModule = true;
72
+ break;
73
+ }
74
+ }
75
+
76
+ return { isEsModule, hasDefaultExport, hasNamedExports, ast };
77
+ }
78
+
79
+ const isWrappedId = (id, suffix) => id.endsWith(suffix);
80
+ const wrapId = (id, suffix) => `\0${id}${suffix}`;
81
+ const unwrapId = (wrappedId, suffix) => wrappedId.slice(1, -suffix.length);
82
+
83
+ const PROXY_SUFFIX = '?commonjs-proxy';
84
+ const REQUIRE_SUFFIX = '?commonjs-require';
85
+ const EXTERNAL_SUFFIX = '?commonjs-external';
28
86
 
29
- const DYNAMIC_REGISTER_PREFIX = '\0commonjs-dynamic-register:';
87
+ const DYNAMIC_REGISTER_SUFFIX = '?commonjs-dynamic-register';
30
88
  const DYNAMIC_JSON_PREFIX = '\0commonjs-dynamic-json:';
31
89
  const DYNAMIC_PACKAGES_ID = '\0commonjs-dynamic-packages';
32
90
 
@@ -37,11 +95,6 @@ const HELPERS_ID = '\0commonjsHelpers.js';
37
95
  // This will no longer be necessary once Rollup switches to ES6 output, likely
38
96
  // in Rollup 3
39
97
 
40
- // The "hasOwnProperty" call in "getDefaultExportFromCjs" is technically not
41
- // needed, but for consumers that use Rollup's old interop pattern, it will fix
42
- // rollup/rollup-plugin-commonjs#224
43
- // We should remove it once Rollup core and this plugin are updated to not use
44
- // this pattern any more
45
98
  const HELPERS = `
46
99
  export var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
47
100
 
@@ -49,16 +102,6 @@ export function getDefaultExportFromCjs (x) {
49
102
  return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
50
103
  }
51
104
 
52
- export function createCommonjsModule(fn, basedir, module) {
53
- return module = {
54
- path: basedir,
55
- exports: {},
56
- require: function (path, base) {
57
- return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
58
- }
59
- }, fn(module, module.exports), module.exports;
60
- }
61
-
62
105
  export function getDefaultExportFromNamespaceIfPresent (n) {
63
106
  return n && Object.prototype.hasOwnProperty.call(n, 'default') ? n['default'] : n;
64
107
  }
@@ -66,15 +109,45 @@ export function getDefaultExportFromNamespaceIfPresent (n) {
66
109
  export function getDefaultExportFromNamespaceIfNotNamed (n) {
67
110
  return n && Object.prototype.hasOwnProperty.call(n, 'default') && Object.keys(n).length === 1 ? n['default'] : n;
68
111
  }
112
+
113
+ export function getAugmentedNamespace(n) {
114
+ if (n.__esModule) return n;
115
+ var a = Object.defineProperty({}, '__esModule', {value: true});
116
+ Object.keys(n).forEach(function (k) {
117
+ var d = Object.getOwnPropertyDescriptor(n, k);
118
+ Object.defineProperty(a, k, d.get ? d : {
119
+ enumerable: true,
120
+ get: function () {
121
+ return n[k];
122
+ }
123
+ });
124
+ });
125
+ return a;
126
+ }
69
127
  `;
70
128
 
71
129
  const HELPER_NON_DYNAMIC = `
72
- export function commonjsRequire () {
73
- throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
130
+ export function createCommonjsModule(fn) {
131
+ var module = { exports: {} }
132
+ return fn(module, module.exports), module.exports;
133
+ }
134
+
135
+ export function commonjsRequire (target) {
136
+ throw new Error('Could not dynamically require "' + target + '". Please configure the dynamicRequireTargets option of @rollup/plugin-commonjs appropriately for this require call to behave properly.');
74
137
  }
75
138
  `;
76
139
 
77
140
  const HELPERS_DYNAMIC = `
141
+ export function createCommonjsModule(fn, basedir, module) {
142
+ return module = {
143
+ path: basedir,
144
+ exports: {},
145
+ require: function (path, base) {
146
+ return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
147
+ }
148
+ }, fn(module, module.exports), module.exports;
149
+ }
150
+
78
151
  export function commonjsRegister (path, loader) {
79
152
  DYNAMIC_REQUIRE_LOADERS[path] = loader;
80
153
  }
@@ -161,10 +234,13 @@ function dirname (path) {
161
234
  return '.';
162
235
  }
163
236
 
164
- export function commonjsRequire (path, originalModuleDir) {
237
+ export function commonjsResolveImpl (path, originalModuleDir, testCache) {
165
238
  const shouldTryNodeModules = isPossibleNodeModulesPath(path);
166
239
  path = normalize(path);
167
240
  let relPath;
241
+ if (path[0] === '/') {
242
+ originalModuleDir = '/';
243
+ }
168
244
  while (true) {
169
245
  if (!shouldTryNodeModules) {
170
246
  relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path;
@@ -173,33 +249,18 @@ export function commonjsRequire (path, originalModuleDir) {
173
249
  } else {
174
250
  relPath = normalize(join('node_modules', path));
175
251
  }
252
+
253
+ if (relPath.endsWith('/..')) {
254
+ break; // Travelled too far up, avoid infinite loop
255
+ }
256
+
176
257
  for (let extensionIndex = 0; extensionIndex < CHECKED_EXTENSIONS.length; extensionIndex++) {
177
258
  const resolvedPath = relPath + CHECKED_EXTENSIONS[extensionIndex];
178
- let cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath];
179
- if (cachedModule) return cachedModule.exports;
180
- const loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath];
181
- if (loader) {
182
- DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = {
183
- id: resolvedPath,
184
- filename: resolvedPath,
185
- path: dirname(resolvedPath),
186
- exports: {},
187
- parent: DEFAULT_PARENT_MODULE,
188
- loaded: false,
189
- children: [],
190
- paths: [],
191
- require: function (path, base) {
192
- return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base);
193
- }
194
- };
195
- try {
196
- loader.call(commonjsGlobal, cachedModule, cachedModule.exports);
197
- } catch (error) {
198
- delete DYNAMIC_REQUIRE_CACHE[resolvedPath];
199
- throw error;
200
- }
201
- cachedModule.loaded = true;
202
- return cachedModule.exports;
259
+ if (DYNAMIC_REQUIRE_CACHE[resolvedPath]) {
260
+ return resolvedPath;
261
+ };
262
+ if (DYNAMIC_REQUIRE_LOADERS[resolvedPath]) {
263
+ return resolvedPath;
203
264
  };
204
265
  }
205
266
  if (!shouldTryNodeModules) break;
@@ -207,77 +268,74 @@ export function commonjsRequire (path, originalModuleDir) {
207
268
  if (nextDir === originalModuleDir) break;
208
269
  originalModuleDir = nextDir;
209
270
  }
271
+ return null;
272
+ }
273
+
274
+ export function commonjsResolve (path, originalModuleDir) {
275
+ const resolvedPath = commonjsResolveImpl(path, originalModuleDir);
276
+ if (resolvedPath !== null) {
277
+ return resolvedPath;
278
+ }
279
+ return require.resolve(path);
280
+ }
281
+
282
+ export function commonjsRequire (path, originalModuleDir) {
283
+ const resolvedPath = commonjsResolveImpl(path, originalModuleDir, true);
284
+ if (resolvedPath !== null) {
285
+ let cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath];
286
+ if (cachedModule) return cachedModule.exports;
287
+ const loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath];
288
+ if (loader) {
289
+ DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = {
290
+ id: resolvedPath,
291
+ filename: resolvedPath,
292
+ path: dirname(resolvedPath),
293
+ exports: {},
294
+ parent: DEFAULT_PARENT_MODULE,
295
+ loaded: false,
296
+ children: [],
297
+ paths: [],
298
+ require: function (path, base) {
299
+ return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base);
300
+ }
301
+ };
302
+ try {
303
+ loader.call(commonjsGlobal, cachedModule, cachedModule.exports);
304
+ } catch (error) {
305
+ delete DYNAMIC_REQUIRE_CACHE[resolvedPath];
306
+ throw error;
307
+ }
308
+ cachedModule.loaded = true;
309
+ return cachedModule.exports;
310
+ };
311
+ }
210
312
  return require(path);
211
313
  }
212
314
 
213
315
  commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE;
316
+ commonjsRequire.resolve = commonjsResolve;
214
317
  `;
215
318
 
216
319
  function getHelpersModule(isDynamicRequireModulesEnabled) {
217
320
  return `${HELPERS}${isDynamicRequireModulesEnabled ? HELPERS_DYNAMIC : HELPER_NON_DYNAMIC}`;
218
321
  }
219
322
 
220
- /* eslint-disable no-undefined */
221
-
222
- const operators = {
223
- '==': (x) => equals(x.left, x.right, false),
224
-
225
- '!=': (x) => not(operators['=='](x)),
226
-
227
- '===': (x) => equals(x.left, x.right, true),
228
-
229
- '!==': (x) => not(operators['==='](x)),
230
-
231
- '!': (x) => isFalsy(x.argument),
232
-
233
- '&&': (x) => isTruthy(x.left) && isTruthy(x.right),
234
-
235
- '||': (x) => isTruthy(x.left) || isTruthy(x.right)
236
- };
237
-
238
- function flatten(node) {
239
- const parts = [];
323
+ /* eslint-disable import/prefer-default-export */
240
324
 
241
- while (node.type === 'MemberExpression') {
242
- if (node.computed) return null;
325
+ function deconflict(scope, globals, identifier) {
326
+ let i = 1;
327
+ let deconflicted = makeLegalIdentifier(identifier);
243
328
 
244
- parts.unshift(node.property.name);
245
- // eslint-disable-next-line no-param-reassign
246
- node = node.object;
329
+ while (scope.contains(deconflicted) || globals.has(deconflicted)) {
330
+ deconflicted = makeLegalIdentifier(`${identifier}_${i}`);
331
+ i += 1;
247
332
  }
333
+ // eslint-disable-next-line no-param-reassign
334
+ scope.declarations[deconflicted] = true;
248
335
 
249
- if (node.type !== 'Identifier') return null;
250
-
251
- const { name } = node;
252
- parts.unshift(name);
253
-
254
- return { name, keypath: parts.join('.') };
255
- }
256
-
257
- function isTruthy(node) {
258
- if (node.type === 'Literal') return !!node.value;
259
- if (node.type === 'ParenthesizedExpression') return isTruthy(node.expression);
260
- if (node.operator in operators) return operators[node.operator](node);
261
- return undefined;
262
- }
263
-
264
- function isFalsy(node) {
265
- return not(isTruthy(node));
266
- }
267
-
268
- function not(value) {
269
- return value === undefined ? value : !value;
270
- }
271
-
272
- function equals(a, b, strict) {
273
- if (a.type !== b.type) return undefined;
274
- // eslint-disable-next-line eqeqeq
275
- if (a.type === 'Literal') return strict ? a.value === b.value : a.value == b.value;
276
- return undefined;
336
+ return deconflicted;
277
337
  }
278
338
 
279
- /* eslint-disable import/prefer-default-export */
280
-
281
339
  function getName(id) {
282
340
  const name = makeLegalIdentifier(basename(id, extname(id)));
283
341
  if (name !== 'index') {
@@ -287,918 +345,1219 @@ function getName(id) {
287
345
  return makeLegalIdentifier(segments[segments.length - 1]);
288
346
  }
289
347
 
290
- /* eslint-disable no-param-reassign, no-shadow, no-underscore-dangle, no-continue */
348
+ function normalizePathSlashes(path) {
349
+ return path.replace(/\\/g, '/');
350
+ }
291
351
 
292
- const reserved = 'process location abstract arguments boolean break byte case catch char class const continue debugger default delete do double else enum eval export extends false final finally float for from function goto if implements import in instanceof int interface let long native new null package private protected public return short static super switch synchronized this throw throws transient true try typeof var void volatile while with yield'.split(
293
- ' '
294
- );
295
- const blacklist = { __esModule: true };
296
- reserved.forEach((word) => (blacklist[word] = true));
352
+ const VIRTUAL_PATH_BASE = '/$$rollup_base$$';
353
+ const getVirtualPathForDynamicRequirePath = (path, commonDir) => {
354
+ const normalizedPath = normalizePathSlashes(path);
355
+ return normalizedPath.startsWith(commonDir)
356
+ ? VIRTUAL_PATH_BASE + normalizedPath.slice(commonDir.length)
357
+ : normalizedPath;
358
+ };
297
359
 
298
- const exportsPattern = /^(?:module\.)?exports(?:\.([a-zA-Z_$][a-zA-Z_$0-9]*))?$/;
360
+ function getPackageEntryPoint(dirPath) {
361
+ let entryPoint = 'index.js';
299
362
 
300
- const firstpassGlobal = /\b(?:require|module|exports|global)\b/;
301
- const firstpassNoGlobal = /\b(?:require|module|exports)\b/;
302
- const functionType = /^(?:FunctionDeclaration|FunctionExpression|ArrowFunctionExpression)$/;
363
+ try {
364
+ if (existsSync(join(dirPath, 'package.json'))) {
365
+ entryPoint =
366
+ JSON.parse(readFileSync(join(dirPath, 'package.json'), { encoding: 'utf8' })).main ||
367
+ entryPoint;
368
+ }
369
+ } catch (ignored) {
370
+ // ignored
371
+ }
303
372
 
304
- function deconflict(scope, globals, identifier) {
305
- let i = 1;
306
- let deconflicted = makeLegalIdentifier(identifier);
373
+ return entryPoint;
374
+ }
307
375
 
308
- while (scope.contains(deconflicted) || globals.has(deconflicted) || deconflicted in blacklist) {
309
- deconflicted = `${identifier}_${i}`;
310
- i += 1;
311
- }
312
- scope.declarations[deconflicted] = true;
376
+ function getDynamicPackagesModule(dynamicRequireModuleDirPaths, commonDir) {
377
+ let code = `const commonjsRegister = require('${HELPERS_ID}?commonjsRegister');`;
378
+ for (const dir of dynamicRequireModuleDirPaths) {
379
+ const entryPoint = getPackageEntryPoint(dir);
313
380
 
314
- return deconflicted;
381
+ code += `\ncommonjsRegister(${JSON.stringify(
382
+ getVirtualPathForDynamicRequirePath(dir, commonDir)
383
+ )}, function (module, exports) {
384
+ module.exports = require(${JSON.stringify(normalizePathSlashes(join(dir, entryPoint)))});
385
+ });`;
386
+ }
387
+ return code;
315
388
  }
316
389
 
317
- function tryParse(parse, code, id) {
318
- try {
319
- return parse(code, { allowReturnOutsideFunction: true });
320
- } catch (err) {
321
- err.message += ` in ${id}`;
322
- throw err;
390
+ function getDynamicPackagesEntryIntro(
391
+ dynamicRequireModuleDirPaths,
392
+ dynamicRequireModuleSet
393
+ ) {
394
+ let dynamicImports = Array.from(
395
+ dynamicRequireModuleSet,
396
+ (dynamicId) => `require(${JSON.stringify(wrapModuleRegisterProxy(dynamicId))});`
397
+ ).join('\n');
398
+
399
+ if (dynamicRequireModuleDirPaths.length) {
400
+ dynamicImports += `require(${JSON.stringify(wrapModuleRegisterProxy(DYNAMIC_PACKAGES_ID))});`;
323
401
  }
402
+
403
+ return dynamicImports;
324
404
  }
325
405
 
326
- function normalizePathSlashes(path) {
327
- return path.replace(/\\/g, '/');
406
+ function wrapModuleRegisterProxy(id) {
407
+ return wrapId(id, DYNAMIC_REGISTER_SUFFIX);
328
408
  }
329
409
 
330
- function hasCjsKeywords(code, ignoreGlobal) {
331
- const firstpass = ignoreGlobal ? firstpassNoGlobal : firstpassGlobal;
332
- return firstpass.test(code);
410
+ function unwrapModuleRegisterProxy(id) {
411
+ return unwrapId(id, DYNAMIC_REGISTER_SUFFIX);
333
412
  }
334
413
 
335
- function checkEsModule(parse, code, id) {
336
- const ast = tryParse(parse, code, id);
414
+ function isModuleRegisterProxy(id) {
415
+ return isWrappedId(id, DYNAMIC_REGISTER_SUFFIX);
416
+ }
337
417
 
338
- let isEsModule = false;
339
- let hasDefaultExport = false;
340
- let hasNamedExports = false;
341
- for (const node of ast.body) {
342
- if (node.type === 'ExportDefaultDeclaration') {
343
- isEsModule = true;
344
- hasDefaultExport = true;
345
- } else if (node.type === 'ExportNamedDeclaration') {
346
- isEsModule = true;
347
- if (node.declaration) {
348
- hasNamedExports = true;
349
- } else {
350
- for (const specifier of node.specifiers) {
351
- if (specifier.exported.name === 'default') {
352
- hasDefaultExport = true;
353
- } else {
354
- hasNamedExports = true;
355
- }
356
- }
357
- }
358
- } else if (node.type === 'ExportAllDeclaration') {
359
- isEsModule = true;
360
- if (node.exported && node.exported.name === 'default') {
361
- hasDefaultExport = true;
362
- } else {
363
- hasNamedExports = true;
418
+ function isDynamicModuleImport(id, dynamicRequireModuleSet) {
419
+ const normalizedPath = normalizePathSlashes(id);
420
+ return dynamicRequireModuleSet.has(normalizedPath) && !normalizedPath.endsWith('.json');
421
+ }
422
+
423
+ function isDirectory(path) {
424
+ try {
425
+ if (statSync(path).isDirectory()) return true;
426
+ } catch (ignored) {
427
+ // Nothing to do here
428
+ }
429
+ return false;
430
+ }
431
+
432
+ function getDynamicRequirePaths(patterns) {
433
+ const dynamicRequireModuleSet = new Set();
434
+ for (const pattern of !patterns || Array.isArray(patterns) ? patterns || [] : [patterns]) {
435
+ const isNegated = pattern.startsWith('!');
436
+ const modifySet = Set.prototype[isNegated ? 'delete' : 'add'].bind(dynamicRequireModuleSet);
437
+ for (const path of glob.sync(isNegated ? pattern.substr(1) : pattern)) {
438
+ modifySet(normalizePathSlashes(resolve(path)));
439
+ if (isDirectory(path)) {
440
+ modifySet(normalizePathSlashes(resolve(join(path, getPackageEntryPoint(path)))));
364
441
  }
365
- } else if (node.type === 'ImportDeclaration') {
366
- isEsModule = true;
367
442
  }
368
443
  }
369
-
370
- return { isEsModule, hasDefaultExport, hasNamedExports, ast };
444
+ const dynamicRequireModuleDirPaths = Array.from(dynamicRequireModuleSet.values()).filter((path) =>
445
+ isDirectory(path)
446
+ );
447
+ return { dynamicRequireModuleSet, dynamicRequireModuleDirPaths };
371
448
  }
372
449
 
373
- function getDefinePropertyCallName(node, targetName) {
374
- if (node.type !== 'CallExpression') return;
450
+ const isCjsPromises = new Map();
375
451
 
376
- const {
377
- callee: { object, property }
378
- } = node;
452
+ function getIsCjsPromise(id) {
453
+ let isCjsPromise = isCjsPromises.get(id);
454
+ if (isCjsPromise) return isCjsPromise.promise;
379
455
 
380
- if (!object || object.type !== 'Identifier' || object.name !== 'Object') return;
456
+ const promise = new Promise((resolve) => {
457
+ isCjsPromise = {
458
+ resolve,
459
+ promise: null
460
+ };
461
+ isCjsPromises.set(id, isCjsPromise);
462
+ });
463
+ isCjsPromise.promise = promise;
381
464
 
382
- if (!property || property.type !== 'Identifier' || property.name !== 'defineProperty') return;
465
+ return promise;
466
+ }
383
467
 
384
- if (node.arguments.length !== 3) return;
468
+ function setIsCjsPromise(id, resolution) {
469
+ const isCjsPromise = isCjsPromises.get(id);
470
+ if (isCjsPromise) {
471
+ if (isCjsPromise.resolve) {
472
+ isCjsPromise.resolve(resolution);
473
+ isCjsPromise.resolve = null;
474
+ }
475
+ } else {
476
+ isCjsPromises.set(id, { promise: Promise.resolve(resolution), resolve: null });
477
+ }
478
+ }
385
479
 
386
- const [target, val] = node.arguments;
387
- if (target.type !== 'Identifier' || target.name !== targetName) return;
388
- // eslint-disable-next-line consistent-return
389
- return val.value;
480
+ // e.g. id === "commonjsHelpers?commonjsRegister"
481
+ function getSpecificHelperProxy(id) {
482
+ return `export {${id.split('?')[1]} as default} from '${HELPERS_ID}';`;
390
483
  }
391
484
 
392
- function transformCommonjs(
393
- parse,
394
- code,
395
- id,
396
- isEsModule,
397
- ignoreGlobal,
398
- ignoreRequire,
399
- sourceMap,
400
- isDynamicRequireModulesEnabled,
401
- dynamicRequireModuleSet,
402
- commonDir,
403
- astCache
404
- ) {
405
- const ast = astCache || tryParse(parse, code, id);
406
-
407
- const magicString = new MagicString(code);
408
-
409
- const required = {};
410
- // Because objects have no guaranteed ordering, yet we need it,
411
- // we need to keep track of the order in a array
412
- const sources = [];
485
+ function getUnknownRequireProxy(id, requireReturnsDefault) {
486
+ if (requireReturnsDefault === true || id.endsWith('.json')) {
487
+ return `export {default} from ${JSON.stringify(id)};`;
488
+ }
489
+ const name = getName(id);
490
+ const exported =
491
+ requireReturnsDefault === 'auto'
492
+ ? `import {getDefaultExportFromNamespaceIfNotNamed} from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfNotNamed(${name});`
493
+ : requireReturnsDefault === 'preferred'
494
+ ? `import {getDefaultExportFromNamespaceIfPresent} from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfPresent(${name});`
495
+ : !requireReturnsDefault
496
+ ? `import {getAugmentedNamespace} from "${HELPERS_ID}"; export default /*@__PURE__*/getAugmentedNamespace(${name});`
497
+ : `export default ${name};`;
498
+ return `import * as ${name} from ${JSON.stringify(id)}; ${exported}`;
499
+ }
413
500
 
414
- let uid = 0;
501
+ function getDynamicJsonProxy(id, commonDir) {
502
+ const normalizedPath = normalizePathSlashes(id.slice(DYNAMIC_JSON_PREFIX.length));
503
+ return `const commonjsRegister = require('${HELPERS_ID}?commonjsRegister');\ncommonjsRegister(${JSON.stringify(
504
+ getVirtualPathForDynamicRequirePath(normalizedPath, commonDir)
505
+ )}, function (module, exports) {
506
+ module.exports = require(${JSON.stringify(normalizedPath)});
507
+ });`;
508
+ }
415
509
 
416
- let scope = attachScopes(ast, 'scope');
417
- const uses = { module: false, exports: false, global: false, require: false };
510
+ function getDynamicRequireProxy(normalizedPath, commonDir) {
511
+ return `const commonjsRegister = require('${HELPERS_ID}?commonjsRegister');\ncommonjsRegister(${JSON.stringify(
512
+ getVirtualPathForDynamicRequirePath(normalizedPath, commonDir)
513
+ )}, function (module, exports) {
514
+ ${readFileSync(normalizedPath, { encoding: 'utf8' })}
515
+ });`;
516
+ }
418
517
 
419
- let lexicalDepth = 0;
420
- let programDepth = 0;
518
+ async function getStaticRequireProxy(
519
+ id,
520
+ requireReturnsDefault,
521
+ esModulesWithDefaultExport,
522
+ esModulesWithNamedExports
523
+ ) {
524
+ const name = getName(id);
525
+ const isCjs = await getIsCjsPromise(id);
526
+ if (isCjs) {
527
+ return `import { __moduleExports } from ${JSON.stringify(id)}; export default __moduleExports;`;
528
+ } else if (isCjs === null) {
529
+ return getUnknownRequireProxy(id, requireReturnsDefault);
530
+ } else if (!requireReturnsDefault) {
531
+ return `import {getAugmentedNamespace} from "${HELPERS_ID}"; import * as ${name} from ${JSON.stringify(
532
+ id
533
+ )}; export default /*@__PURE__*/getAugmentedNamespace(${name});`;
534
+ } else if (
535
+ requireReturnsDefault !== true &&
536
+ (requireReturnsDefault === 'namespace' ||
537
+ !esModulesWithDefaultExport.has(id) ||
538
+ (requireReturnsDefault === 'auto' && esModulesWithNamedExports.has(id)))
539
+ ) {
540
+ return `import * as ${name} from ${JSON.stringify(id)}; export default ${name};`;
541
+ }
542
+ return `export {default} from ${JSON.stringify(id)};`;
543
+ }
421
544
 
422
- const globals = new Set();
545
+ /* eslint-disable no-param-reassign, no-undefined */
423
546
 
424
- // TODO technically wrong since globals isn't populated yet, but ¯\_(ツ)_/¯
425
- const HELPERS_NAME = deconflict(scope, globals, 'commonjsHelpers');
547
+ function getCandidatesForExtension(resolved, extension) {
548
+ return [resolved + extension, `${resolved}${sep}index${extension}`];
549
+ }
426
550
 
427
- const namedExports = {};
551
+ function getCandidates(resolved, extensions) {
552
+ return extensions.reduce(
553
+ (paths, extension) => paths.concat(getCandidatesForExtension(resolved, extension)),
554
+ [resolved]
555
+ );
556
+ }
428
557
 
429
- // TODO handle transpiled modules
430
- let shouldWrap = /__esModule/.test(code);
431
- let usesCommonjsHelpers = false;
558
+ function getResolveId(extensions) {
559
+ function resolveExtensions(importee, importer) {
560
+ // not our problem
561
+ if (importee[0] !== '.' || !importer) return undefined;
432
562
 
433
- function isRequireStatement(node) {
434
- if (!node) return false;
435
- if (node.type !== 'CallExpression') return false;
563
+ const resolved = resolve(dirname(importer), importee);
564
+ const candidates = getCandidates(resolved, extensions);
436
565
 
437
- // Weird case of `require()` or `module.require()` without arguments
438
- if (node.arguments.length === 0) return false;
566
+ for (let i = 0; i < candidates.length; i += 1) {
567
+ try {
568
+ const stats = statSync(candidates[i]);
569
+ if (stats.isFile()) return { id: candidates[i] };
570
+ } catch (err) {
571
+ /* noop */
572
+ }
573
+ }
439
574
 
440
- return isRequireIdentifier(node.callee);
575
+ return undefined;
441
576
  }
442
577
 
443
- function isRequireIdentifier(node) {
444
- if (!node) return false;
578
+ return function resolveId(importee, rawImporter) {
579
+ const importer =
580
+ rawImporter && isModuleRegisterProxy(rawImporter)
581
+ ? unwrapModuleRegisterProxy(rawImporter)
582
+ : rawImporter;
445
583
 
446
- if (node.type === 'Identifier' && node.name === 'require' /* `require` */) {
447
- // `require` is hidden by a variable in local scope
448
- if (scope.contains('require')) return false;
584
+ // Proxies are only importing resolved ids, no need to resolve again
585
+ if (importer && isWrappedId(importer, PROXY_SUFFIX)) {
586
+ return importee;
587
+ }
449
588
 
450
- return true;
451
- } else if (node.type === 'MemberExpression' /* `[something].[something]` */) {
452
- // `module.[something]`
453
- if (node.object.type !== 'Identifier' || node.object.name !== 'module') return false;
589
+ const isProxyModule = isWrappedId(importee, PROXY_SUFFIX);
590
+ const isRequiredModule = isWrappedId(importee, REQUIRE_SUFFIX);
591
+ let isModuleRegistration = false;
454
592
 
455
- // `module` is hidden by a variable in local scope
456
- if (scope.contains('module')) return false;
593
+ if (isProxyModule) {
594
+ importee = unwrapId(importee, PROXY_SUFFIX);
595
+ } else if (isRequiredModule) {
596
+ importee = unwrapId(importee, REQUIRE_SUFFIX);
457
597
 
458
- // `module.require(...)`
459
- if (node.property.type !== 'Identifier' || node.property.name !== 'require') return false;
598
+ isModuleRegistration = isModuleRegisterProxy(importee);
599
+ if (isModuleRegistration) {
600
+ importee = unwrapModuleRegisterProxy(importee);
601
+ }
602
+ }
460
603
 
461
- return true;
604
+ if (
605
+ importee.startsWith(HELPERS_ID) ||
606
+ importee === DYNAMIC_PACKAGES_ID ||
607
+ importee.startsWith(DYNAMIC_JSON_PREFIX)
608
+ ) {
609
+ return importee;
462
610
  }
463
611
 
464
- return false;
465
- }
612
+ if (importee.startsWith('\0')) {
613
+ return null;
614
+ }
466
615
 
467
- function hasDynamicArguments(node) {
468
- return (
469
- node.arguments.length > 1 ||
470
- (node.arguments[0].type !== 'Literal' &&
471
- (node.arguments[0].type !== 'TemplateLiteral' || node.arguments[0].expressions.length > 0))
472
- );
473
- }
616
+ return this.resolve(importee, importer, {
617
+ skipSelf: true,
618
+ custom: { 'node-resolve': { isRequire: isProxyModule || isRequiredModule } }
619
+ }).then((resolved) => {
620
+ if (!resolved) {
621
+ resolved = resolveExtensions(importee, importer);
622
+ }
623
+ if (resolved && isProxyModule) {
624
+ resolved.id = wrapId(resolved.id, resolved.external ? EXTERNAL_SUFFIX : PROXY_SUFFIX);
625
+ resolved.external = false;
626
+ } else if (resolved && isModuleRegistration) {
627
+ resolved.id = wrapModuleRegisterProxy(resolved.id);
628
+ } else if (!resolved && (isProxyModule || isRequiredModule)) {
629
+ return { id: wrapId(importee, EXTERNAL_SUFFIX), external: false };
630
+ }
631
+ return resolved;
632
+ });
633
+ };
634
+ }
474
635
 
475
- function isStaticRequireStatement(node) {
476
- if (!isRequireStatement(node)) return false;
477
- return !hasDynamicArguments(node);
636
+ function validateRollupVersion(rollupVersion, peerDependencyVersion) {
637
+ const [major, minor] = rollupVersion.split('.').map(Number);
638
+ const versionRegexp = /\^(\d+\.\d+)\.\d+/g;
639
+ let minMajor = Infinity;
640
+ let minMinor = Infinity;
641
+ let foundVersion;
642
+ // eslint-disable-next-line no-cond-assign
643
+ while ((foundVersion = versionRegexp.exec(peerDependencyVersion))) {
644
+ const [foundMajor, foundMinor] = foundVersion[1].split('.').map(Number);
645
+ if (foundMajor < minMajor) {
646
+ minMajor = foundMajor;
647
+ minMinor = foundMinor;
648
+ }
478
649
  }
479
-
480
- function isNodeRequireStatement(parent) {
481
- const reservedMethod = ['resolve', 'cache', 'main'];
482
- return !!(parent && parent.property && reservedMethod.indexOf(parent.property.name) > -1);
650
+ if (major < minMajor || (major === minMajor && minor < minMinor)) {
651
+ throw new Error(
652
+ `Insufficient Rollup version: "@rollup/plugin-commonjs" requires at least rollup@${minMajor}.${minMinor} but found rollup@${rollupVersion}.`
653
+ );
483
654
  }
655
+ }
484
656
 
485
- function isIgnoredRequireStatement(requiredNode) {
486
- return ignoreRequire(requiredNode.arguments[0].value);
487
- }
657
+ const operators = {
658
+ '==': (x) => equals(x.left, x.right, false),
488
659
 
489
- function getRequireStringArg(node) {
490
- return node.arguments[0].type === 'Literal'
491
- ? node.arguments[0].value
492
- : node.arguments[0].quasis[0].value.cooked;
493
- }
660
+ '!=': (x) => not(operators['=='](x)),
494
661
 
495
- function getRequired(node, name) {
496
- let sourceId = getRequireStringArg(node);
497
- const isDynamicRegister = sourceId.startsWith(DYNAMIC_REGISTER_PREFIX);
498
- if (isDynamicRegister) {
499
- sourceId = sourceId.substr(DYNAMIC_REGISTER_PREFIX.length);
500
- }
662
+ '===': (x) => equals(x.left, x.right, true),
501
663
 
502
- const existing = required[sourceId];
503
- // eslint-disable-next-line no-undefined
504
- if (existing === undefined) {
505
- const isDynamic = hasDynamicModuleForPath(sourceId);
664
+ '!==': (x) => not(operators['==='](x)),
506
665
 
507
- if (!name) {
508
- do {
509
- name = `require$$${uid}`;
510
- uid += 1;
511
- } while (scope.contains(name));
512
- }
666
+ '!': (x) => isFalsy(x.argument),
513
667
 
514
- if (isDynamicRegister && sourceId.endsWith('.json')) {
515
- sourceId = DYNAMIC_JSON_PREFIX + sourceId;
516
- }
668
+ '&&': (x) => isTruthy(x.left) && isTruthy(x.right),
517
669
 
518
- if (isDynamicRegister || !isDynamic || sourceId.endsWith('.json')) {
519
- sources.push([sourceId, !isDynamicRegister]);
520
- }
670
+ '||': (x) => isTruthy(x.left) || isTruthy(x.right)
671
+ };
521
672
 
522
- required[sourceId] = { source: sourceId, name, importsDefault: false, isDynamic };
523
- }
673
+ function not(value) {
674
+ return value === null ? value : !value;
675
+ }
524
676
 
525
- return required[sourceId];
526
- }
677
+ function equals(a, b, strict) {
678
+ if (a.type !== b.type) return null;
679
+ // eslint-disable-next-line eqeqeq
680
+ if (a.type === 'Literal') return strict ? a.value === b.value : a.value == b.value;
681
+ return null;
682
+ }
527
683
 
528
- function hasDynamicModuleForPath(source) {
529
- if (!/[/\\]/.test(source)) {
530
- try {
531
- const resolvedPath = normalizePathSlashes(
532
- sync(source, { basedir: dirname(id) })
533
- );
534
- if (dynamicRequireModuleSet.has(resolvedPath)) {
535
- return true;
536
- }
537
- } catch (ex) {
538
- // Probably a node.js internal module
539
- return false;
540
- }
684
+ function isTruthy(node) {
685
+ if (!node) return false;
686
+ if (node.type === 'Literal') return !!node.value;
687
+ if (node.type === 'ParenthesizedExpression') return isTruthy(node.expression);
688
+ if (node.operator in operators) return operators[node.operator](node);
689
+ return null;
690
+ }
541
691
 
542
- return false;
543
- }
692
+ function isFalsy(node) {
693
+ return not(isTruthy(node));
694
+ }
544
695
 
545
- for (const attemptExt of ['', '.js', '.json']) {
546
- const resolvedPath = normalizePathSlashes(resolve(dirname(id), source + attemptExt));
547
- if (dynamicRequireModuleSet.has(resolvedPath)) {
548
- return true;
549
- }
550
- }
696
+ function getKeypath(node) {
697
+ const parts = [];
551
698
 
552
- return false;
553
- }
699
+ while (node.type === 'MemberExpression') {
700
+ if (node.computed) return null;
554
701
 
555
- function shouldUseSimulatedRequire(required) {
556
- return (
557
- hasDynamicModuleForPath(required.source) &&
558
- // We only do `commonjsRequire` for json if it's the `commonjsRegister` call.
559
- (required.source.startsWith(DYNAMIC_REGISTER_PREFIX) || !required.source.endsWith('.json'))
560
- );
702
+ parts.unshift(node.property.name);
703
+ // eslint-disable-next-line no-param-reassign
704
+ node = node.object;
561
705
  }
562
706
 
563
- // do a first pass, see which names are assigned to. This is necessary to prevent
564
- // illegally replacing `var foo = require('foo')` with `import foo from 'foo'`,
565
- // where `foo` is later reassigned. (This happens in the wild. CommonJS, sigh)
566
- const assignedTo = new Set();
567
- walk(ast, {
568
- enter(node) {
569
- if (node.type !== 'AssignmentExpression') return;
570
- if (node.left.type === 'MemberExpression') return;
571
-
572
- extractAssignedNames(node.left).forEach((name) => {
573
- assignedTo.add(name);
574
- });
575
- }
576
- });
577
-
578
- walk(ast, {
579
- enter(node, parent) {
580
- if (sourceMap) {
581
- magicString.addSourcemapLocation(node.start);
582
- magicString.addSourcemapLocation(node.end);
583
- }
707
+ if (node.type !== 'Identifier') return null;
584
708
 
585
- // skip dead branches
586
- if (parent && (parent.type === 'IfStatement' || parent.type === 'ConditionalExpression')) {
587
- if (node === parent.consequent && isFalsy(parent.test)) {
588
- this.skip();
589
- return;
590
- }
591
- if (node === parent.alternate && isTruthy(parent.test)) {
592
- this.skip();
593
- return;
594
- }
595
- }
709
+ const { name } = node;
710
+ parts.unshift(name);
596
711
 
597
- if (node._skip) {
598
- this.skip();
599
- return;
600
- }
712
+ return { name, keypath: parts.join('.') };
713
+ }
601
714
 
602
- programDepth += 1;
715
+ const KEY_COMPILED_ESM = '__esModule';
603
716
 
604
- if (node.scope) ({ scope } = node);
605
- if (functionType.test(node.type)) lexicalDepth += 1;
717
+ function isDefineCompiledEsm(node) {
718
+ const definedProperty =
719
+ getDefinePropertyCallName(node, 'exports') || getDefinePropertyCallName(node, 'module.exports');
720
+ if (definedProperty && definedProperty.key === KEY_COMPILED_ESM) {
721
+ return isTruthy(definedProperty.value);
722
+ }
723
+ return false;
724
+ }
606
725
 
607
- // if toplevel return, we need to wrap it
608
- if (node.type === 'ReturnStatement' && lexicalDepth === 0) {
609
- shouldWrap = true;
610
- }
726
+ function getDefinePropertyCallName(node, targetName) {
727
+ const targetNames = targetName.split('.');
611
728
 
612
- // rewrite `this` as `commonjsHelpers.commonjsGlobal`
613
- if (node.type === 'ThisExpression' && lexicalDepth === 0) {
614
- uses.global = true;
615
- if (!ignoreGlobal) {
616
- magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsGlobal`, {
617
- storeName: true
618
- });
619
- usesCommonjsHelpers = true;
620
- }
621
- return;
622
- }
729
+ const {
730
+ callee: { object, property }
731
+ } = node;
732
+ if (!object || object.type !== 'Identifier' || object.name !== 'Object') return;
733
+ if (!property || property.type !== 'Identifier' || property.name !== 'defineProperty') return;
734
+ if (node.arguments.length !== 3) return;
623
735
 
624
- // rewrite `typeof module`, `typeof module.exports` and `typeof exports` (https://github.com/rollup/rollup-plugin-commonjs/issues/151)
625
- if (node.type === 'UnaryExpression' && node.operator === 'typeof') {
626
- const flattened = flatten(node.argument);
627
- if (!flattened) return;
736
+ const [target, key, value] = node.arguments;
737
+ if (targetNames.length === 1) {
738
+ if (target.type !== 'Identifier' || target.name !== targetNames[0]) {
739
+ return;
740
+ }
741
+ }
628
742
 
629
- if (scope.contains(flattened.name)) return;
743
+ if (targetNames.length === 2) {
744
+ if (
745
+ target.type !== 'MemberExpression' ||
746
+ target.object.name !== targetNames[0] ||
747
+ target.property.name !== targetNames[1]
748
+ ) {
749
+ return;
750
+ }
751
+ }
630
752
 
631
- if (
632
- flattened.keypath === 'module.exports' ||
633
- flattened.keypath === 'module' ||
634
- flattened.keypath === 'exports'
635
- ) {
636
- magicString.overwrite(node.start, node.end, `'object'`, { storeName: false });
637
- }
638
- }
753
+ if (value.type !== 'ObjectExpression' || !value.properties) return;
639
754
 
640
- // rewrite `require` (if not already handled) `global` and `define`, and handle free references to
641
- // `module` and `exports` as these mean we need to wrap the module in commonjsHelpers.createCommonjsModule
642
- if (node.type === 'Identifier') {
643
- if (isReference(node, parent) && !scope.contains(node.name)) {
644
- if (node.name in uses) {
645
- if (isRequireIdentifier(node)) {
646
- if (isNodeRequireStatement(parent)) {
647
- return;
648
- }
755
+ const valueProperty = value.properties.find((p) => p.key && p.key.name === 'value');
756
+ if (!valueProperty || !valueProperty.value) return;
649
757
 
650
- if (!isDynamicRequireModulesEnabled && isStaticRequireStatement(parent)) {
651
- return;
652
- }
758
+ // eslint-disable-next-line consistent-return
759
+ return { key: key.value, value: valueProperty.value };
760
+ }
653
761
 
654
- if (isDynamicRequireModulesEnabled && isRequireStatement(parent)) {
655
- magicString.appendLeft(
656
- parent.end - 1,
657
- `,${JSON.stringify(
658
- dirname(id) === '.'
659
- ? null /* default behavior */
660
- : getVirtualPathForDynamicRequirePath(
661
- normalizePathSlashes(dirname(id)),
662
- commonDir
663
- )
664
- )}`
665
- );
666
- }
762
+ function isLocallyShadowed(name, scope) {
763
+ while (scope.parent) {
764
+ if (scope.declarations[name]) {
765
+ return true;
766
+ }
767
+ // eslint-disable-next-line no-param-reassign
768
+ scope = scope.parent;
769
+ }
770
+ return false;
771
+ }
667
772
 
668
- magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, {
669
- storeName: true
670
- });
671
- usesCommonjsHelpers = true;
672
- }
773
+ function isShorthandProperty(parent) {
774
+ return parent && parent.type === 'Property' && parent.shorthand;
775
+ }
673
776
 
674
- uses[node.name] = true;
675
- if (node.name === 'global' && !ignoreGlobal) {
676
- magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsGlobal`, {
677
- storeName: true
678
- });
679
- usesCommonjsHelpers = true;
680
- }
777
+ function wrapCode(magicString, uses, moduleName, HELPERS_NAME, virtualDynamicRequirePath) {
778
+ const args = `module${uses.exports ? ', exports' : ''}`;
681
779
 
682
- // if module or exports are used outside the context of an assignment
683
- // expression, we need to wrap the module
684
- if (node.name === 'module' || node.name === 'exports') {
685
- shouldWrap = true;
686
- }
687
- }
780
+ magicString
781
+ .trim()
782
+ .prepend(`var ${moduleName} = ${HELPERS_NAME}.createCommonjsModule(function (${args}) {\n`)
783
+ .append(
784
+ `\n}${virtualDynamicRequirePath ? `, ${JSON.stringify(virtualDynamicRequirePath)}` : ''});`
785
+ );
786
+ }
688
787
 
689
- if (node.name === 'define') {
690
- magicString.overwrite(node.start, node.end, 'undefined', { storeName: true });
691
- }
788
+ function rewriteExportsAndGetExportsBlock(
789
+ magicString,
790
+ moduleName,
791
+ wrapped,
792
+ topLevelModuleExportsAssignments,
793
+ topLevelExportsAssignmentsByName,
794
+ defineCompiledEsmExpressions,
795
+ deconflict,
796
+ isRestorableCompiledEsm,
797
+ code,
798
+ uses,
799
+ HELPERS_NAME
800
+ ) {
801
+ const namedExportDeclarations = [`export { ${moduleName} as __moduleExports };`];
802
+ const moduleExportsPropertyAssignments = [];
803
+ let deconflictedDefaultExportName;
804
+
805
+ if (!wrapped) {
806
+ let hasModuleExportsAssignment = false;
807
+ const namedExportProperties = [];
808
+
809
+ // Collect and rewrite module.exports assignments
810
+ for (const { left } of topLevelModuleExportsAssignments) {
811
+ hasModuleExportsAssignment = true;
812
+ magicString.overwrite(left.start, left.end, `var ${moduleName}`);
813
+ }
692
814
 
693
- globals.add(node.name);
694
- }
815
+ // Collect and rewrite named exports
816
+ for (const [exportName, node] of topLevelExportsAssignmentsByName) {
817
+ const deconflicted = deconflict(exportName);
818
+ magicString.overwrite(node.start, node.left.end, `var ${deconflicted}`);
695
819
 
696
- return;
820
+ if (exportName === 'default') {
821
+ deconflictedDefaultExportName = deconflicted;
822
+ } else {
823
+ namedExportDeclarations.push(
824
+ exportName === deconflicted
825
+ ? `export { ${exportName} };`
826
+ : `export { ${deconflicted} as ${exportName} };`
827
+ );
697
828
  }
698
829
 
699
- // Is this an assignment to exports or module.exports?
700
- if (node.type === 'AssignmentExpression') {
701
- if (node.left.type !== 'MemberExpression') return;
702
-
703
- const flattened = flatten(node.left);
704
- if (!flattened) return;
830
+ if (hasModuleExportsAssignment) {
831
+ moduleExportsPropertyAssignments.push(`${moduleName}.${exportName} = ${deconflicted};`);
832
+ } else {
833
+ namedExportProperties.push(`\t${exportName}: ${deconflicted}`);
834
+ }
835
+ }
705
836
 
706
- if (scope.contains(flattened.name)) return;
837
+ // Regenerate CommonJS namespace
838
+ if (!hasModuleExportsAssignment) {
839
+ const moduleExports = `{\n${namedExportProperties.join(',\n')}\n}`;
840
+ magicString
841
+ .trim()
842
+ .append(
843
+ `\n\nvar ${moduleName} = ${
844
+ isRestorableCompiledEsm
845
+ ? `/*#__PURE__*/Object.defineProperty(${moduleExports}, '__esModule', {value: true})`
846
+ : moduleExports
847
+ };`
848
+ );
849
+ }
850
+ }
707
851
 
708
- const match = exportsPattern.exec(flattened.keypath);
709
- if (!match || flattened.keypath === 'exports') return;
852
+ // Generate default export
853
+ const defaultExport = [];
854
+ if (isRestorableCompiledEsm) {
855
+ defaultExport.push(`export default ${deconflictedDefaultExportName || moduleName};`);
856
+ } else if (
857
+ (wrapped || deconflictedDefaultExportName) &&
858
+ (defineCompiledEsmExpressions.length > 0 || code.indexOf('__esModule') >= 0)
859
+ ) {
860
+ // eslint-disable-next-line no-param-reassign
861
+ uses.commonjsHelpers = true;
862
+ defaultExport.push(
863
+ `export default /*@__PURE__*/${HELPERS_NAME}.getDefaultExportFromCjs(${moduleName});`
864
+ );
865
+ } else {
866
+ defaultExport.push(`export default ${moduleName};`);
867
+ }
710
868
 
711
- uses[flattened.name] = true;
869
+ return `\n\n${defaultExport
870
+ .concat(namedExportDeclarations)
871
+ .concat(moduleExportsPropertyAssignments)
872
+ .join('\n')}`;
873
+ }
712
874
 
713
- // we're dealing with `module.exports = ...` or `[module.]exports.foo = ...` –
714
- // if this isn't top-level, we'll need to wrap the module
715
- if (programDepth > 3) shouldWrap = true;
875
+ function isRequireStatement(node, scope) {
876
+ if (!node) return false;
877
+ if (node.type !== 'CallExpression') return false;
716
878
 
717
- node.left._skip = true;
879
+ // Weird case of `require()` or `module.require()` without arguments
880
+ if (node.arguments.length === 0) return false;
718
881
 
719
- if (flattened.keypath === 'module.exports' && node.right.type === 'ObjectExpression') {
720
- node.right.properties.forEach((prop) => {
721
- if (prop.computed || !('key' in prop) || prop.key.type !== 'Identifier') return;
722
- const { name } = prop.key;
723
- if (name === makeLegalIdentifier(name)) namedExports[name] = true;
724
- });
725
- return;
726
- }
882
+ return isRequire(node.callee, scope);
883
+ }
727
884
 
728
- if (match[1]) namedExports[match[1]] = true;
729
- return;
730
- }
885
+ function isRequire(node, scope) {
886
+ return (
887
+ (node.type === 'Identifier' && node.name === 'require' && !scope.contains('require')) ||
888
+ (node.type === 'MemberExpression' && isModuleRequire(node, scope))
889
+ );
890
+ }
731
891
 
732
- const name = getDefinePropertyCallName(node, 'exports');
733
- if (name && name === makeLegalIdentifier(name)) namedExports[name] = true;
892
+ function isModuleRequire({ object, property }, scope) {
893
+ return (
894
+ object.type === 'Identifier' &&
895
+ object.name === 'module' &&
896
+ property.type === 'Identifier' &&
897
+ property.name === 'require' &&
898
+ !scope.contains('module')
899
+ );
900
+ }
734
901
 
735
- // if this is `var x = require('x')`, we can do `import x from 'x'`
736
- if (
737
- node.type === 'VariableDeclarator' &&
738
- node.id.type === 'Identifier' &&
739
- isStaticRequireStatement(node.init) &&
740
- !isIgnoredRequireStatement(node.init)
741
- ) {
742
- // for now, only do this for top-level requires. maybe fix this in future
743
- if (scope.parent) return;
902
+ function isStaticRequireStatement(node, scope) {
903
+ if (!isRequireStatement(node, scope)) return false;
904
+ return !hasDynamicArguments(node);
905
+ }
744
906
 
745
- // edge case — CJS allows you to assign to imports. ES doesn't
746
- if (assignedTo.has(node.id.name)) return;
907
+ function hasDynamicArguments(node) {
908
+ return (
909
+ node.arguments.length > 1 ||
910
+ (node.arguments[0].type !== 'Literal' &&
911
+ (node.arguments[0].type !== 'TemplateLiteral' || node.arguments[0].expressions.length > 0))
912
+ );
913
+ }
747
914
 
748
- const required = getRequired(node.init, node.id.name);
749
- required.importsDefault = true;
915
+ const reservedMethod = { resolve: true, cache: true, main: true };
750
916
 
751
- if (required.name === node.id.name && !required.isDynamic) {
752
- node._shouldRemove = true;
753
- }
754
- }
917
+ function isNodeRequirePropertyAccess(parent) {
918
+ return parent && parent.property && reservedMethod[parent.property.name];
919
+ }
755
920
 
756
- if (!isStaticRequireStatement(node) || isIgnoredRequireStatement(node)) {
757
- return;
758
- }
921
+ function isIgnoredRequireStatement(requiredNode, ignoreRequire) {
922
+ return ignoreRequire(requiredNode.arguments[0].value);
923
+ }
759
924
 
760
- const required = getRequired(node);
925
+ function getRequireStringArg(node) {
926
+ return node.arguments[0].type === 'Literal'
927
+ ? node.arguments[0].value
928
+ : node.arguments[0].quasis[0].value.cooked;
929
+ }
761
930
 
762
- if (parent.type === 'ExpressionStatement') {
763
- // is a bare import, e.g. `require('foo');`
764
- magicString.remove(parent.start, parent.end);
765
- } else {
766
- required.importsDefault = true;
767
-
768
- if (shouldUseSimulatedRequire(required)) {
769
- magicString.overwrite(
770
- node.start,
771
- node.end,
772
- `${HELPERS_NAME}.commonjsRequire(${JSON.stringify(
773
- getVirtualPathForDynamicRequirePath(normalizePathSlashes(required.source), commonDir)
774
- )}, ${JSON.stringify(
775
- dirname(id) === '.'
776
- ? null /* default behavior */
777
- : getVirtualPathForDynamicRequirePath(normalizePathSlashes(dirname(id)), commonDir)
778
- )})`
779
- );
780
- usesCommonjsHelpers = true;
781
- } else {
782
- magicString.overwrite(node.start, node.end, required.name);
783
- }
931
+ function hasDynamicModuleForPath(source, id, dynamicRequireModuleSet) {
932
+ if (!/^(?:\.{0,2}[/\\]|[A-Za-z]:[/\\])/.test(source)) {
933
+ try {
934
+ const resolvedPath = normalizePathSlashes(sync(source, { basedir: dirname(id) }));
935
+ if (dynamicRequireModuleSet.has(resolvedPath)) {
936
+ return true;
784
937
  }
938
+ } catch (ex) {
939
+ // Probably a node.js internal module
940
+ return false;
941
+ }
785
942
 
786
- node.callee._skip = true;
787
- },
788
-
789
- leave(node) {
790
- programDepth -= 1;
791
- if (node.scope) scope = scope.parent;
792
- if (functionType.test(node.type)) lexicalDepth -= 1;
943
+ return false;
944
+ }
793
945
 
794
- if (node.type === 'VariableDeclaration') {
795
- let keepDeclaration = false;
796
- let c = node.declarations[0].start;
946
+ for (const attemptExt of ['', '.js', '.json']) {
947
+ const resolvedPath = normalizePathSlashes(resolve(dirname(id), source + attemptExt));
948
+ if (dynamicRequireModuleSet.has(resolvedPath)) {
949
+ return true;
950
+ }
951
+ }
797
952
 
798
- for (let i = 0; i < node.declarations.length; i += 1) {
799
- const declarator = node.declarations[i];
953
+ return false;
954
+ }
800
955
 
801
- if (declarator._shouldRemove) {
802
- magicString.remove(c, declarator.end);
803
- } else {
804
- if (!keepDeclaration) {
805
- magicString.remove(c, declarator.start);
806
- keepDeclaration = true;
807
- }
956
+ function getRequireHandlers() {
957
+ const requiredSources = [];
958
+ const requiredBySource = Object.create(null);
959
+ const requiredByNode = new Map();
960
+ const requireExpressionsWithUsedReturnValue = [];
961
+
962
+ function addRequireStatement(sourceId, node, scope, usesReturnValue) {
963
+ const required = getRequired(sourceId);
964
+ requiredByNode.set(node, { scope, required });
965
+ if (usesReturnValue) {
966
+ required.nodesUsingRequired.push(node);
967
+ requireExpressionsWithUsedReturnValue.push(node);
968
+ }
969
+ }
808
970
 
809
- c = declarator.end;
810
- }
811
- }
971
+ function getRequired(sourceId) {
972
+ if (!requiredBySource[sourceId]) {
973
+ requiredSources.push(sourceId);
812
974
 
813
- if (!keepDeclaration) {
814
- magicString.remove(node.start, node.end);
815
- }
816
- }
975
+ requiredBySource[sourceId] = {
976
+ source: sourceId,
977
+ name: null,
978
+ nodesUsingRequired: []
979
+ };
817
980
  }
818
- });
819
981
 
820
- if (
821
- !sources.length &&
822
- !uses.module &&
823
- !uses.exports &&
824
- !uses.require &&
825
- (ignoreGlobal || !uses.global)
826
- ) {
827
- // not a CommonJS module
828
- return null;
982
+ return requiredBySource[sourceId];
829
983
  }
830
984
 
831
- // If `isEsModule` is on, it means it has ES6 import/export statements,
832
- // which just can't be wrapped in a function.
833
- if (isEsModule) shouldWrap = false;
834
-
835
- usesCommonjsHelpers = usesCommonjsHelpers || shouldWrap;
836
-
837
- const importBlock = `${(usesCommonjsHelpers
838
- ? [`import * as ${HELPERS_NAME} from '${HELPERS_ID}';`]
839
- : []
840
- )
841
- .concat(
842
- sources.map(
843
- ([source]) =>
844
- // import the actual module before the proxy, so that we know
845
- // what kind of proxy to build
846
- `import '${source}';`
847
- ),
848
- sources
849
- .filter(([, importProxy]) => importProxy)
850
- .map(([source]) => {
851
- const { name, importsDefault } = required[source];
852
- return `import ${importsDefault ? `${name} from ` : ``}'${
853
- source.startsWith('\0') ? source : getProxyId(source)
985
+ function rewriteRequireExpressionsAndGetImportBlock(
986
+ magicString,
987
+ topLevelDeclarations,
988
+ topLevelRequireDeclarators,
989
+ reassignedNames,
990
+ helpersNameIfUsed,
991
+ dynamicRegisterSources
992
+ ) {
993
+ const removedDeclarators = getDeclaratorsReplacedByImportsAndSetImportNames(
994
+ topLevelRequireDeclarators,
995
+ requiredByNode,
996
+ reassignedNames
997
+ );
998
+ setRemainingImportNamesAndRewriteRequires(
999
+ requireExpressionsWithUsedReturnValue,
1000
+ requiredByNode,
1001
+ magicString
1002
+ );
1003
+ removeDeclaratorsFromDeclarations(topLevelDeclarations, removedDeclarators, magicString);
1004
+ const importBlock = `${(helpersNameIfUsed
1005
+ ? [`import * as ${helpersNameIfUsed} from '${HELPERS_ID}';`]
1006
+ : []
1007
+ )
1008
+ .concat(
1009
+ // dynamic registers first, as the may be required in the other modules
1010
+ [...dynamicRegisterSources].map((source) => `import '${wrapId(source, REQUIRE_SUFFIX)}';`),
1011
+
1012
+ // now the actual modules so that they are analyzed before creating the proxies;
1013
+ // no need to do this for virtual modules as we never proxy them
1014
+ requiredSources
1015
+ .filter((source) => !source.startsWith('\0'))
1016
+ .map((source) => `import '${wrapId(source, REQUIRE_SUFFIX)}';`),
1017
+
1018
+ // now the proxy modules
1019
+ requiredSources.map((source) => {
1020
+ const { name, nodesUsingRequired } = requiredBySource[source];
1021
+ return `import ${nodesUsingRequired.length ? `${name} from ` : ``}'${
1022
+ source.startsWith('\0') ? source : wrapId(source, PROXY_SUFFIX)
854
1023
  }';`;
855
1024
  })
856
- )
857
- .join('\n')}\n\n`;
858
-
859
- const namedExportDeclarations = [];
860
- let wrapperStart = '';
861
- let wrapperEnd = '';
862
-
863
- const moduleName = deconflict(scope, globals, getName(id));
864
- if (!isEsModule) {
865
- const exportModuleExports = {
866
- str: `export { ${moduleName} as __moduleExports };`,
867
- name: '__moduleExports'
868
- };
869
-
870
- namedExportDeclarations.push(exportModuleExports);
1025
+ )
1026
+ .join('\n')}`;
1027
+ return importBlock ? `${importBlock}\n\n` : '';
871
1028
  }
872
1029
 
873
- const defaultExportPropertyAssignments = [];
874
- let hasDefaultExport = false;
875
-
876
- if (shouldWrap) {
877
- const args = `module${uses.exports ? ', exports' : ''}`;
1030
+ return {
1031
+ addRequireStatement,
1032
+ requiredSources,
1033
+ rewriteRequireExpressionsAndGetImportBlock
1034
+ };
1035
+ }
878
1036
 
879
- wrapperStart = `var ${moduleName} = ${HELPERS_NAME}.createCommonjsModule(function (${args}) {\n`;
1037
+ function getDeclaratorsReplacedByImportsAndSetImportNames(
1038
+ topLevelRequireDeclarators,
1039
+ requiredByNode,
1040
+ reassignedNames
1041
+ ) {
1042
+ const removedDeclarators = new Set();
1043
+ for (const declarator of topLevelRequireDeclarators) {
1044
+ const { required } = requiredByNode.get(declarator.init);
1045
+ if (!required.name) {
1046
+ const potentialName = declarator.id.name;
1047
+ if (
1048
+ !reassignedNames.has(potentialName) &&
1049
+ !required.nodesUsingRequired.some((node) =>
1050
+ isLocallyShadowed(potentialName, requiredByNode.get(node).scope)
1051
+ )
1052
+ ) {
1053
+ required.name = potentialName;
1054
+ removedDeclarators.add(declarator);
1055
+ }
1056
+ }
1057
+ }
1058
+ return removedDeclarators;
1059
+ }
880
1060
 
881
- wrapperEnd = `\n}`;
882
- if (isDynamicRequireModulesEnabled) {
883
- wrapperEnd += `, ${JSON.stringify(
884
- getVirtualPathForDynamicRequirePath(normalizePathSlashes(dirname(id)), commonDir)
885
- )}`;
1061
+ function setRemainingImportNamesAndRewriteRequires(
1062
+ requireExpressionsWithUsedReturnValue,
1063
+ requiredByNode,
1064
+ magicString
1065
+ ) {
1066
+ let uid = 0;
1067
+ for (const requireExpression of requireExpressionsWithUsedReturnValue) {
1068
+ const { required } = requiredByNode.get(requireExpression);
1069
+ if (!required.name) {
1070
+ let potentialName;
1071
+ const isUsedName = (node) => requiredByNode.get(node).scope.contains(potentialName);
1072
+ do {
1073
+ potentialName = `require$$${uid}`;
1074
+ uid += 1;
1075
+ } while (required.nodesUsingRequired.some(isUsedName));
1076
+ required.name = potentialName;
886
1077
  }
1078
+ magicString.overwrite(requireExpression.start, requireExpression.end, required.name);
1079
+ }
1080
+ }
887
1081
 
888
- wrapperEnd += `);`;
889
- } else {
890
- const names = [];
1082
+ function removeDeclaratorsFromDeclarations(topLevelDeclarations, removedDeclarators, magicString) {
1083
+ for (const declaration of topLevelDeclarations) {
1084
+ let keepDeclaration = false;
1085
+ let [{ start }] = declaration.declarations;
1086
+ for (const declarator of declaration.declarations) {
1087
+ if (removedDeclarators.has(declarator)) {
1088
+ magicString.remove(start, declarator.end);
1089
+ } else if (!keepDeclaration) {
1090
+ magicString.remove(start, declarator.start);
1091
+ keepDeclaration = true;
1092
+ }
1093
+ start = declarator.end;
1094
+ }
1095
+ if (!keepDeclaration) {
1096
+ magicString.remove(declaration.start, declaration.end);
1097
+ }
1098
+ }
1099
+ }
891
1100
 
892
- for (const node of ast.body) {
893
- if (node.type === 'ExpressionStatement' && node.expression.type === 'AssignmentExpression') {
894
- const { left } = node.expression;
895
- const flattened = flatten(left);
1101
+ /* eslint-disable no-param-reassign, no-shadow, no-underscore-dangle, no-continue */
896
1102
 
897
- if (!flattened) {
898
- continue;
899
- }
1103
+ const exportsPattern = /^(?:module\.)?exports(?:\.([a-zA-Z_$][a-zA-Z_$0-9]*))?$/;
900
1104
 
901
- const match = exportsPattern.exec(flattened.keypath);
902
- if (!match) {
903
- continue;
904
- }
1105
+ const functionType = /^(?:FunctionDeclaration|FunctionExpression|ArrowFunctionExpression)$/;
905
1106
 
906
- if (flattened.keypath === 'module.exports') {
907
- hasDefaultExport = true;
908
- magicString.overwrite(left.start, left.end, `var ${moduleName}`);
909
- } else {
910
- const [, name] = match;
911
- const deconflicted = deconflict(scope, globals, name);
1107
+ function transformCommonjs(
1108
+ parse,
1109
+ code,
1110
+ id,
1111
+ isEsModule,
1112
+ ignoreGlobal,
1113
+ ignoreRequire,
1114
+ getIgnoreTryCatchRequireStatementMode,
1115
+ sourceMap,
1116
+ isDynamicRequireModulesEnabled,
1117
+ dynamicRequireModuleSet,
1118
+ disableWrap,
1119
+ commonDir,
1120
+ astCache
1121
+ ) {
1122
+ const ast = astCache || tryParse(parse, code, id);
1123
+ const magicString = new MagicString(code);
1124
+ const uses = {
1125
+ module: false,
1126
+ exports: false,
1127
+ global: false,
1128
+ require: false,
1129
+ commonjsHelpers: false
1130
+ };
1131
+ const virtualDynamicRequirePath =
1132
+ isDynamicRequireModulesEnabled && getVirtualPathForDynamicRequirePath(dirname(id), commonDir);
1133
+ let scope = attachScopes(ast, 'scope');
1134
+ let lexicalDepth = 0;
1135
+ let programDepth = 0;
1136
+ let currentTryBlockEnd = null;
1137
+ let shouldWrap = false;
1138
+ const defineCompiledEsmExpressions = [];
912
1139
 
913
- names.push({ name, deconflicted });
1140
+ const globals = new Set();
914
1141
 
915
- magicString.overwrite(node.start, left.end, `var ${deconflicted}`);
1142
+ // TODO technically wrong since globals isn't populated yet, but ¯\_(ツ)_/¯
1143
+ const HELPERS_NAME = deconflict(scope, globals, 'commonjsHelpers');
1144
+ const namedExports = {};
1145
+ const dynamicRegisterSources = new Set();
1146
+ let hasRemovedRequire = false;
916
1147
 
917
- const declaration =
918
- name === deconflicted
919
- ? `export { ${name} };`
920
- : `export { ${deconflicted} as ${name} };`;
1148
+ const {
1149
+ addRequireStatement,
1150
+ requiredSources,
1151
+ rewriteRequireExpressionsAndGetImportBlock
1152
+ } = getRequireHandlers();
921
1153
 
922
- if (name !== 'default') {
923
- namedExportDeclarations.push({
924
- str: declaration,
925
- name
926
- });
927
- }
1154
+ // See which names are assigned to. This is necessary to prevent
1155
+ // illegally replacing `var foo = require('foo')` with `import foo from 'foo'`,
1156
+ // where `foo` is later reassigned. (This happens in the wild. CommonJS, sigh)
1157
+ const reassignedNames = new Set();
1158
+ const topLevelDeclarations = [];
1159
+ const topLevelRequireDeclarators = new Set();
1160
+ const skippedNodes = new Set();
1161
+ const topLevelModuleExportsAssignments = [];
1162
+ const topLevelExportsAssignmentsByName = new Map();
928
1163
 
929
- defaultExportPropertyAssignments.push(`${moduleName}.${name} = ${deconflicted};`);
930
- }
1164
+ walk(ast, {
1165
+ enter(node, parent) {
1166
+ if (skippedNodes.has(node)) {
1167
+ this.skip();
1168
+ return;
931
1169
  }
932
- }
933
-
934
- if (!(isEsModule || hasDefaultExport)) {
935
- wrapperEnd = `\n\nvar ${moduleName} = {\n${names
936
- .map(({ name, deconflicted }) => `\t${name}: ${deconflicted}`)
937
- .join(',\n')}\n};`;
938
- }
939
- }
940
-
941
- magicString
942
- .trim()
943
- .prepend(importBlock + wrapperStart)
944
- .trim()
945
- .append(wrapperEnd);
946
-
947
- const defaultExport =
948
- code.indexOf('__esModule') >= 0
949
- ? `export default /*@__PURE__*/${HELPERS_NAME}.getDefaultExportFromCjs(${moduleName});`
950
- : `export default ${moduleName};`;
951
-
952
- const named = namedExportDeclarations
953
- .filter((x) => x.name !== 'default' || !hasDefaultExport)
954
- .map((x) => x.str);
955
-
956
- magicString.append(
957
- `\n\n${(isEsModule ? [] : [defaultExport])
958
- .concat(named)
959
- .concat(hasDefaultExport ? defaultExportPropertyAssignments : [])
960
- .join('\n')}`
961
- );
962
-
963
- code = magicString.toString();
964
- const map = sourceMap ? magicString.generateMap() : null;
965
-
966
- return { code, map, syntheticNamedExports: isEsModule ? false : '__moduleExports' };
967
- }
968
1170
 
969
- function getDynamicPackagesModule(dynamicRequireModuleDirPaths, commonDir) {
970
- let code = `const commonjsRegister = require('${HELPERS_ID}?commonjsRegister');`;
971
- for (const dir of dynamicRequireModuleDirPaths) {
972
- let entryPoint = 'index.js';
1171
+ if (currentTryBlockEnd !== null && node.start > currentTryBlockEnd) {
1172
+ currentTryBlockEnd = null;
1173
+ }
973
1174
 
974
- try {
975
- if (existsSync(join(dir, 'package.json'))) {
976
- entryPoint =
977
- JSON.parse(readFileSync(join(dir, 'package.json'), { encoding: 'utf8' })).main ||
978
- entryPoint;
1175
+ programDepth += 1;
1176
+ if (node.scope) ({ scope } = node);
1177
+ if (functionType.test(node.type)) lexicalDepth += 1;
1178
+ if (sourceMap) {
1179
+ magicString.addSourcemapLocation(node.start);
1180
+ magicString.addSourcemapLocation(node.end);
979
1181
  }
980
- } catch (ignored) {
981
- // ignored
982
- }
983
1182
 
984
- code += `\ncommonjsRegister(${JSON.stringify(
985
- getVirtualPathForDynamicRequirePath(dir, commonDir)
986
- )}, function (module, exports) {
987
- module.exports = require(${JSON.stringify(normalizePathSlashes(join(dir, entryPoint)))});
988
- });`;
989
- }
990
- return code;
991
- }
1183
+ // eslint-disable-next-line default-case
1184
+ switch (node.type) {
1185
+ case 'TryStatement':
1186
+ if (currentTryBlockEnd === null) {
1187
+ currentTryBlockEnd = node.block.end;
1188
+ }
1189
+ return;
1190
+ case 'AssignmentExpression':
1191
+ if (node.left.type === 'MemberExpression') {
1192
+ const flattened = getKeypath(node.left);
1193
+ if (!flattened || scope.contains(flattened.name)) return;
992
1194
 
993
- function getDynamicPackagesEntryIntro(
994
- id,
995
- dynamicRequireModuleDirPaths,
996
- dynamicRequireModuleSet
997
- ) {
998
- try {
999
- const code = readFileSync(id, { encoding: 'utf8' });
1000
- let dynamicImports = Array.from(
1001
- dynamicRequireModuleSet,
1002
- (dynamicId) => `require(${JSON.stringify(DYNAMIC_REGISTER_PREFIX + dynamicId)});`
1003
- ).join('\n');
1195
+ const exportsPatternMatch = exportsPattern.exec(flattened.keypath);
1196
+ if (!exportsPatternMatch || flattened.keypath === 'exports') return;
1004
1197
 
1005
- if (dynamicRequireModuleDirPaths.length) {
1006
- dynamicImports += `require(${JSON.stringify(
1007
- DYNAMIC_REGISTER_PREFIX + DYNAMIC_PACKAGES_ID
1008
- )});`;
1009
- }
1198
+ const [, exportName] = exportsPatternMatch;
1199
+ uses[flattened.name] = true;
1010
1200
 
1011
- return `${dynamicImports}\n${code}`;
1012
- } catch (ex) {
1013
- this.warn(`Failed to read file ${id}, dynamic modules might not work correctly`);
1014
- return null;
1015
- }
1016
- }
1201
+ // we're dealing with `module.exports = ...` or `[module.]exports.foo = ...` –
1202
+ if (programDepth > 3) {
1203
+ shouldWrap = true;
1204
+ } else if (exportName === KEY_COMPILED_ESM) {
1205
+ defineCompiledEsmExpressions.push(parent);
1206
+ } else if (flattened.keypath === 'module.exports') {
1207
+ topLevelModuleExportsAssignments.push(node);
1208
+ } else if (!topLevelExportsAssignmentsByName.has(exportName)) {
1209
+ topLevelExportsAssignmentsByName.set(exportName, node);
1210
+ } else {
1211
+ shouldWrap = true;
1212
+ }
1017
1213
 
1018
- function getDynamicRequirePaths(patterns) {
1019
- const dynamicRequireModuleSet = new Set();
1020
- for (const pattern of !patterns || Array.isArray(patterns) ? patterns || [] : [patterns]) {
1021
- const isNegated = pattern.startsWith('!');
1022
- const modifySet = Set.prototype[isNegated ? 'delete' : 'add'].bind(dynamicRequireModuleSet);
1023
- for (const path of glob.sync(isNegated ? pattern.substr(1) : pattern)) {
1024
- modifySet(normalizePathSlashes(resolve(path)));
1025
- }
1026
- }
1027
- const dynamicRequireModuleDirPaths = Array.from(dynamicRequireModuleSet.values()).filter(
1028
- (path) => {
1029
- try {
1030
- if (statSync(path).isDirectory()) return true;
1031
- } catch (ignored) {
1032
- // Nothing to do here
1033
- }
1034
- return false;
1035
- }
1036
- );
1037
- return { dynamicRequireModuleSet, dynamicRequireModuleDirPaths };
1038
- }
1214
+ skippedNodes.add(node.left);
1039
1215
 
1040
- /* eslint-disable no-undefined */
1041
- const isCjsPromises = new Map();
1216
+ if (flattened.keypath === 'module.exports' && node.right.type === 'ObjectExpression') {
1217
+ node.right.properties.forEach((prop) => {
1218
+ if (prop.computed || !('key' in prop) || prop.key.type !== 'Identifier') return;
1219
+ const { name } = prop.key;
1220
+ if (name === makeLegalIdentifier(name)) namedExports[name] = true;
1221
+ });
1222
+ return;
1223
+ }
1042
1224
 
1043
- function getIsCjsPromise(id) {
1044
- let isCjsPromise = isCjsPromises.get(id);
1045
- if (isCjsPromise) return isCjsPromise.promise;
1225
+ if (exportsPatternMatch[1]) namedExports[exportsPatternMatch[1]] = true;
1226
+ } else {
1227
+ for (const name of extractAssignedNames(node.left)) {
1228
+ reassignedNames.add(name);
1229
+ }
1230
+ }
1231
+ return;
1232
+ case 'CallExpression': {
1233
+ if (isDefineCompiledEsm(node)) {
1234
+ if (programDepth === 3 && parent.type === 'ExpressionStatement') {
1235
+ // skip special handling for [module.]exports until we know we render this
1236
+ skippedNodes.add(node.arguments[0]);
1237
+ defineCompiledEsmExpressions.push(parent);
1238
+ } else {
1239
+ shouldWrap = true;
1240
+ }
1241
+ return;
1242
+ }
1046
1243
 
1047
- const promise = new Promise((resolve) => {
1048
- isCjsPromise = {
1049
- resolve,
1050
- promise: undefined
1051
- };
1052
- isCjsPromises.set(id, isCjsPromise);
1053
- });
1054
- isCjsPromise.promise = promise;
1244
+ if (
1245
+ node.callee.object &&
1246
+ node.callee.object.name === 'require' &&
1247
+ node.callee.property.name === 'resolve' &&
1248
+ hasDynamicModuleForPath(id, '/', dynamicRequireModuleSet)
1249
+ ) {
1250
+ const requireNode = node.callee.object;
1251
+ magicString.appendLeft(
1252
+ node.end - 1,
1253
+ `,${JSON.stringify(
1254
+ dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath
1255
+ )}`
1256
+ );
1257
+ magicString.overwrite(
1258
+ requireNode.start,
1259
+ requireNode.end,
1260
+ `${HELPERS_NAME}.commonjsRequire`,
1261
+ {
1262
+ storeName: true
1263
+ }
1264
+ );
1265
+ uses.commonjsHelpers = true;
1266
+ return;
1267
+ }
1055
1268
 
1056
- return promise;
1057
- }
1269
+ if (!isStaticRequireStatement(node, scope)) return;
1270
+ if (!isDynamicRequireModulesEnabled) {
1271
+ skippedNodes.add(node.callee);
1272
+ }
1273
+ if (!isIgnoredRequireStatement(node, ignoreRequire)) {
1274
+ skippedNodes.add(node.callee);
1275
+ const usesReturnValue = parent.type !== 'ExpressionStatement';
1058
1276
 
1059
- function setIsCjsPromise(id, resolution) {
1060
- const isCjsPromise = isCjsPromises.get(id);
1061
- if (isCjsPromise) {
1062
- if (isCjsPromise.resolve) {
1063
- isCjsPromise.resolve(resolution);
1064
- isCjsPromise.resolve = undefined;
1065
- }
1066
- } else {
1067
- isCjsPromises.set(id, { promise: Promise.resolve(resolution), resolve: undefined });
1068
- }
1069
- }
1277
+ let canConvertRequire = true;
1278
+ let shouldRemoveRequireStatement = false;
1070
1279
 
1071
- // e.g. id === "commonjsHelpers?commonjsRegister"
1072
- function getSpecificHelperProxy(id) {
1073
- return `export {${id.split('?')[1]} as default} from '${HELPERS_ID}';`;
1074
- }
1280
+ if (currentTryBlockEnd !== null) {
1281
+ ({
1282
+ canConvertRequire,
1283
+ shouldRemoveRequireStatement
1284
+ } = getIgnoreTryCatchRequireStatementMode(node.arguments[0].value));
1075
1285
 
1076
- function getUnknownRequireProxy(id, requireReturnsDefault) {
1077
- if (requireReturnsDefault === true || id.endsWith('.json')) {
1078
- return `export {default} from ${JSON.stringify(id)};`;
1079
- }
1080
- const name = getName(id);
1081
- const exported =
1082
- requireReturnsDefault === 'auto'
1083
- ? `import {getDefaultExportFromNamespaceIfNotNamed} from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfNotNamed(${name})`
1084
- : requireReturnsDefault === 'preferred'
1085
- ? `import {getDefaultExportFromNamespaceIfPresent} from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfPresent(${name})`
1086
- : `export default ${name}`;
1087
- return `import * as ${name} from ${JSON.stringify(id)}; ${exported}`;
1088
- }
1286
+ if (shouldRemoveRequireStatement) {
1287
+ hasRemovedRequire = true;
1288
+ }
1289
+ }
1089
1290
 
1090
- function getDynamicJsonProxy(id, commonDir) {
1091
- const normalizedPath = normalizePathSlashes(id.slice(DYNAMIC_JSON_PREFIX.length));
1092
- return `const commonjsRegister = require('${HELPERS_ID}?commonjsRegister');\ncommonjsRegister(${JSON.stringify(
1093
- getVirtualPathForDynamicRequirePath(normalizedPath, commonDir)
1094
- )}, function (module, exports) {
1095
- module.exports = require(${JSON.stringify(normalizedPath)});
1096
- });`;
1097
- }
1291
+ let sourceId = getRequireStringArg(node);
1292
+ const isDynamicRegister = isModuleRegisterProxy(sourceId);
1293
+ if (isDynamicRegister) {
1294
+ sourceId = unwrapModuleRegisterProxy(sourceId);
1295
+ if (sourceId.endsWith('.json')) {
1296
+ sourceId = DYNAMIC_JSON_PREFIX + sourceId;
1297
+ }
1298
+ dynamicRegisterSources.add(wrapModuleRegisterProxy(sourceId));
1299
+ } else {
1300
+ if (
1301
+ !sourceId.endsWith('.json') &&
1302
+ hasDynamicModuleForPath(sourceId, id, dynamicRequireModuleSet)
1303
+ ) {
1304
+ if (shouldRemoveRequireStatement) {
1305
+ magicString.overwrite(node.start, node.end, `undefined`);
1306
+ } else if (canConvertRequire) {
1307
+ magicString.overwrite(
1308
+ node.start,
1309
+ node.end,
1310
+ `${HELPERS_NAME}.commonjsRequire(${JSON.stringify(
1311
+ getVirtualPathForDynamicRequirePath(sourceId, commonDir)
1312
+ )}, ${JSON.stringify(
1313
+ dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath
1314
+ )})`
1315
+ );
1316
+ uses.commonjsHelpers = true;
1317
+ }
1318
+ return;
1319
+ }
1098
1320
 
1099
- function getDynamicRequireProxy(normalizedPath, commonDir) {
1100
- return `const commonjsRegister = require('${HELPERS_ID}?commonjsRegister');\ncommonjsRegister(${JSON.stringify(
1101
- getVirtualPathForDynamicRequirePath(normalizedPath, commonDir)
1102
- )}, function (module, exports) {
1103
- ${readFileSync(normalizedPath, { encoding: 'utf8' })}
1104
- });`;
1105
- }
1321
+ if (canConvertRequire) {
1322
+ addRequireStatement(sourceId, node, scope, usesReturnValue);
1323
+ }
1324
+ }
1106
1325
 
1107
- async function getStaticRequireProxy(
1108
- id,
1109
- requireReturnsDefault,
1110
- esModulesWithDefaultExport,
1111
- esModulesWithNamedExports
1112
- ) {
1113
- const name = getName(id);
1114
- const isCjs = await getIsCjsPromise(id);
1115
- if (isCjs) {
1116
- return `import { __moduleExports } from ${JSON.stringify(id)}; export default __moduleExports;`;
1117
- } else if (isCjs === null) {
1118
- return getUnknownRequireProxy(id, requireReturnsDefault);
1119
- } else if (
1120
- requireReturnsDefault !== true &&
1121
- (!requireReturnsDefault ||
1122
- !esModulesWithDefaultExport.has(id) ||
1123
- (esModulesWithNamedExports.has(id) && requireReturnsDefault === 'auto'))
1124
- ) {
1125
- return `import * as ${name} from ${JSON.stringify(id)}; export default ${name};`;
1126
- }
1127
- return `export {default} from ${JSON.stringify(id)};`;
1128
- }
1326
+ if (usesReturnValue) {
1327
+ if (shouldRemoveRequireStatement) {
1328
+ magicString.overwrite(node.start, node.end, `undefined`);
1329
+ return;
1330
+ }
1129
1331
 
1130
- /* eslint-disable no-param-reassign, no-undefined */
1332
+ if (
1333
+ parent.type === 'VariableDeclarator' &&
1334
+ !scope.parent &&
1335
+ parent.id.type === 'Identifier'
1336
+ ) {
1337
+ // This will allow us to reuse this variable name as the imported variable if it is not reassigned
1338
+ // and does not conflict with variables in other places where this is imported
1339
+ topLevelRequireDeclarators.add(parent);
1340
+ }
1341
+ } else {
1342
+ // This is a bare import, e.g. `require('foo');`
1131
1343
 
1132
- function getCandidatesForExtension(resolved, extension) {
1133
- return [resolved + extension, `${resolved}${sep}index${extension}`];
1134
- }
1344
+ if (!canConvertRequire && !shouldRemoveRequireStatement) {
1345
+ return;
1346
+ }
1135
1347
 
1136
- function getCandidates(resolved, extensions) {
1137
- return extensions.reduce(
1138
- (paths, extension) => paths.concat(getCandidatesForExtension(resolved, extension)),
1139
- [resolved]
1140
- );
1141
- }
1348
+ magicString.remove(parent.start, parent.end);
1349
+ }
1350
+ }
1351
+ return;
1352
+ }
1353
+ case 'ConditionalExpression':
1354
+ case 'IfStatement':
1355
+ // skip dead branches
1356
+ if (isFalsy(node.test)) {
1357
+ skippedNodes.add(node.consequent);
1358
+ } else if (node.alternate && isTruthy(node.test)) {
1359
+ skippedNodes.add(node.alternate);
1360
+ }
1361
+ return;
1362
+ case 'Identifier': {
1363
+ const { name } = node;
1364
+ if (!(isReference(node, parent) && !scope.contains(name))) return;
1365
+ switch (name) {
1366
+ case 'require':
1367
+ if (isNodeRequirePropertyAccess(parent)) {
1368
+ if (hasDynamicModuleForPath(id, '/', dynamicRequireModuleSet)) {
1369
+ if (parent.property.name === 'cache') {
1370
+ magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, {
1371
+ storeName: true
1372
+ });
1373
+ uses.commonjsHelpers = true;
1374
+ }
1375
+ }
1142
1376
 
1143
- function getResolveId(extensions) {
1144
- function resolveExtensions(importee, importer) {
1145
- // not our problem
1146
- if (importee[0] !== '.' || !importer) return undefined;
1377
+ return;
1378
+ }
1147
1379
 
1148
- const resolved = resolve(dirname(importer), importee);
1149
- const candidates = getCandidates(resolved, extensions);
1380
+ if (isDynamicRequireModulesEnabled && isRequireStatement(parent, scope)) {
1381
+ magicString.appendLeft(
1382
+ parent.end - 1,
1383
+ `,${JSON.stringify(
1384
+ dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath
1385
+ )}`
1386
+ );
1387
+ }
1388
+ if (isShorthandProperty(parent)) {
1389
+ magicString.appendRight(node.end, `: ${HELPERS_NAME}.commonjsRequire`);
1390
+ } else {
1391
+ magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, {
1392
+ storeName: true
1393
+ });
1394
+ }
1150
1395
 
1151
- for (let i = 0; i < candidates.length; i += 1) {
1152
- try {
1153
- const stats = statSync(candidates[i]);
1154
- if (stats.isFile()) return { id: candidates[i] };
1155
- } catch (err) {
1156
- /* noop */
1396
+ uses.commonjsHelpers = true;
1397
+ return;
1398
+ case 'module':
1399
+ case 'exports':
1400
+ shouldWrap = true;
1401
+ uses[name] = true;
1402
+ return;
1403
+ case 'global':
1404
+ uses.global = true;
1405
+ if (!ignoreGlobal) {
1406
+ magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsGlobal`, {
1407
+ storeName: true
1408
+ });
1409
+ uses.commonjsHelpers = true;
1410
+ }
1411
+ return;
1412
+ case 'define':
1413
+ magicString.overwrite(node.start, node.end, 'undefined', { storeName: true });
1414
+ return;
1415
+ default:
1416
+ globals.add(name);
1417
+ return;
1418
+ }
1419
+ }
1420
+ case 'MemberExpression':
1421
+ if (!isDynamicRequireModulesEnabled && isModuleRequire(node, scope)) {
1422
+ magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, {
1423
+ storeName: true
1424
+ });
1425
+ uses.commonjsHelpers = true;
1426
+ skippedNodes.add(node.object);
1427
+ skippedNodes.add(node.property);
1428
+ }
1429
+ return;
1430
+ case 'ReturnStatement':
1431
+ // if top-level return, we need to wrap it
1432
+ if (lexicalDepth === 0) {
1433
+ shouldWrap = true;
1434
+ }
1435
+ return;
1436
+ case 'ThisExpression':
1437
+ // rewrite top-level `this` as `commonjsHelpers.commonjsGlobal`
1438
+ if (lexicalDepth === 0) {
1439
+ uses.global = true;
1440
+ if (!ignoreGlobal) {
1441
+ magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsGlobal`, {
1442
+ storeName: true
1443
+ });
1444
+ uses.commonjsHelpers = true;
1445
+ }
1446
+ }
1447
+ return;
1448
+ case 'UnaryExpression':
1449
+ // rewrite `typeof module`, `typeof module.exports` and `typeof exports` (https://github.com/rollup/rollup-plugin-commonjs/issues/151)
1450
+ if (node.operator === 'typeof') {
1451
+ const flattened = getKeypath(node.argument);
1452
+ if (!flattened) return;
1453
+
1454
+ if (scope.contains(flattened.name)) return;
1455
+
1456
+ if (
1457
+ flattened.keypath === 'module.exports' ||
1458
+ flattened.keypath === 'module' ||
1459
+ flattened.keypath === 'exports'
1460
+ ) {
1461
+ magicString.overwrite(node.start, node.end, `'object'`, { storeName: false });
1462
+ }
1463
+ }
1464
+ return;
1465
+ case 'VariableDeclaration':
1466
+ if (!scope.parent) {
1467
+ topLevelDeclarations.push(node);
1468
+ }
1157
1469
  }
1470
+ },
1471
+
1472
+ leave(node) {
1473
+ programDepth -= 1;
1474
+ if (node.scope) scope = scope.parent;
1475
+ if (functionType.test(node.type)) lexicalDepth -= 1;
1158
1476
  }
1477
+ });
1159
1478
 
1160
- return undefined;
1479
+ let isRestorableCompiledEsm = false;
1480
+ if (defineCompiledEsmExpressions.length > 0) {
1481
+ if (!shouldWrap && defineCompiledEsmExpressions.length === 1) {
1482
+ isRestorableCompiledEsm = true;
1483
+ magicString.remove(
1484
+ defineCompiledEsmExpressions[0].start,
1485
+ defineCompiledEsmExpressions[0].end
1486
+ );
1487
+ } else {
1488
+ shouldWrap = true;
1489
+ uses.exports = true;
1490
+ }
1161
1491
  }
1162
1492
 
1163
- function resolveId(importee, importer) {
1164
- const isProxyModule = importee.endsWith(PROXY_SUFFIX);
1165
- if (isProxyModule) {
1166
- importee = getIdFromProxyId(importee);
1167
- }
1168
- if (importee.startsWith('\0')) {
1169
- if (
1170
- importee.startsWith(HELPERS_ID) ||
1171
- importee === DYNAMIC_PACKAGES_ID ||
1172
- importee.startsWith(DYNAMIC_JSON_PREFIX)
1173
- ) {
1174
- return importee;
1175
- }
1176
- if (!isProxyModule) {
1177
- return null;
1178
- }
1179
- }
1493
+ // We cannot wrap ES/mixed modules
1494
+ shouldWrap = shouldWrap && !disableWrap && !isEsModule;
1495
+ uses.commonjsHelpers = uses.commonjsHelpers || shouldWrap;
1180
1496
 
1181
- if (importer && importer.endsWith(PROXY_SUFFIX)) {
1182
- importer = getIdFromProxyId(importer);
1183
- }
1497
+ if (
1498
+ !(
1499
+ requiredSources.length ||
1500
+ dynamicRegisterSources.size ||
1501
+ uses.module ||
1502
+ uses.exports ||
1503
+ uses.require ||
1504
+ uses.commonjsHelpers ||
1505
+ hasRemovedRequire
1506
+ ) &&
1507
+ (ignoreGlobal || !uses.global)
1508
+ ) {
1509
+ return { meta: { commonjs: { isCommonJS: false } } };
1510
+ }
1184
1511
 
1185
- return this.resolve(importee, importer, { skipSelf: true }).then((resolved) => {
1186
- if (!resolved) {
1187
- resolved = resolveExtensions(importee, importer);
1188
- }
1189
- if (isProxyModule) {
1190
- if (!resolved) {
1191
- return { id: getExternalProxyId(importee), external: false };
1192
- }
1193
- resolved.id = (resolved.external ? getExternalProxyId : getProxyId)(resolved.id);
1194
- resolved.external = false;
1195
- return resolved;
1196
- }
1197
- return resolved;
1198
- });
1512
+ const moduleName = deconflict(scope, globals, getName(id));
1513
+
1514
+ let leadingComment = '';
1515
+ if (code.startsWith('/*')) {
1516
+ const commentEnd = code.indexOf('*/', 2) + 2;
1517
+ leadingComment = `${code.slice(0, commentEnd)}\n`;
1518
+ magicString.remove(0, commentEnd).trim();
1199
1519
  }
1200
1520
 
1201
- return resolveId;
1521
+ const exportBlock = isEsModule
1522
+ ? ''
1523
+ : rewriteExportsAndGetExportsBlock(
1524
+ magicString,
1525
+ moduleName,
1526
+ shouldWrap,
1527
+ topLevelModuleExportsAssignments,
1528
+ topLevelExportsAssignmentsByName,
1529
+ defineCompiledEsmExpressions,
1530
+ (name) => deconflict(scope, globals, name),
1531
+ isRestorableCompiledEsm,
1532
+ code,
1533
+ uses,
1534
+ HELPERS_NAME
1535
+ );
1536
+
1537
+ const importBlock = rewriteRequireExpressionsAndGetImportBlock(
1538
+ magicString,
1539
+ topLevelDeclarations,
1540
+ topLevelRequireDeclarators,
1541
+ reassignedNames,
1542
+ uses.commonjsHelpers && HELPERS_NAME,
1543
+ dynamicRegisterSources
1544
+ );
1545
+
1546
+ if (shouldWrap) {
1547
+ wrapCode(magicString, uses, moduleName, HELPERS_NAME, virtualDynamicRequirePath);
1548
+ }
1549
+
1550
+ magicString
1551
+ .trim()
1552
+ .prepend(leadingComment + importBlock)
1553
+ .append(exportBlock);
1554
+
1555
+ return {
1556
+ code: magicString.toString(),
1557
+ map: sourceMap ? magicString.generateMap() : null,
1558
+ syntheticNamedExports: isEsModule ? false : '__moduleExports',
1559
+ meta: { commonjs: { isCommonJS: !isEsModule } }
1560
+ };
1202
1561
  }
1203
1562
 
1204
1563
  function commonjs(options = {}) {
@@ -1239,12 +1598,31 @@ function commonjs(options = {}) {
1239
1598
  ? (id) => options.ignore.includes(id)
1240
1599
  : () => false;
1241
1600
 
1601
+ const getIgnoreTryCatchRequireStatementMode = (id) => {
1602
+ const mode =
1603
+ typeof options.ignoreTryCatch === 'function'
1604
+ ? options.ignoreTryCatch(id)
1605
+ : Array.isArray(options.ignoreTryCatch)
1606
+ ? options.ignoreTryCatch.includes(id)
1607
+ : options.ignoreTryCatch || false;
1608
+
1609
+ return {
1610
+ canConvertRequire: mode !== 'remove' && mode !== true,
1611
+ shouldRemoveRequireStatement: mode === 'remove'
1612
+ };
1613
+ };
1614
+
1242
1615
  const resolveId = getResolveId(extensions);
1243
1616
 
1244
1617
  const sourceMap = options.sourceMap !== false;
1245
1618
 
1246
1619
  function transformAndCheckExports(code, id) {
1247
- const { isEsModule, hasDefaultExport, hasNamedExports, ast } = checkEsModule(
1620
+ if (isDynamicRequireModulesEnabled && this.getModuleInfo(id).isEntry) {
1621
+ code =
1622
+ getDynamicPackagesEntryIntro(dynamicRequireModuleDirPaths, dynamicRequireModuleSet) + code;
1623
+ }
1624
+
1625
+ const { isEsModule, hasDefaultExport, hasNamedExports, ast } = analyzeTopLevelStatements(
1248
1626
  this.parse,
1249
1627
  code,
1250
1628
  id
@@ -1260,46 +1638,44 @@ function commonjs(options = {}) {
1260
1638
  !dynamicRequireModuleSet.has(normalizePathSlashes(id)) &&
1261
1639
  (!hasCjsKeywords(code, ignoreGlobal) || (isEsModule && !options.transformMixedEsModules))
1262
1640
  ) {
1263
- setIsCjsPromise(id, false);
1264
- return null;
1641
+ return { meta: { commonjs: { isCommonJS: false } } };
1265
1642
  }
1266
1643
 
1267
- const transformed = transformCommonjs(
1644
+ let disableWrap = false;
1645
+
1646
+ // avoid wrapping in createCommonjsModule, as this is a commonjsRegister call
1647
+ if (isModuleRegisterProxy(id)) {
1648
+ disableWrap = true;
1649
+ id = unwrapModuleRegisterProxy(id);
1650
+ }
1651
+
1652
+ return transformCommonjs(
1268
1653
  this.parse,
1269
1654
  code,
1270
1655
  id,
1271
1656
  isEsModule,
1272
1657
  ignoreGlobal || isEsModule,
1273
1658
  ignoreRequire,
1659
+ getIgnoreTryCatchRequireStatementMode,
1274
1660
  sourceMap,
1275
1661
  isDynamicRequireModulesEnabled,
1276
1662
  dynamicRequireModuleSet,
1663
+ disableWrap,
1277
1664
  commonDir,
1278
1665
  ast
1279
1666
  );
1280
-
1281
- setIsCjsPromise(id, isEsModule ? false : Boolean(transformed));
1282
- return transformed;
1283
1667
  }
1284
1668
 
1285
1669
  return {
1286
1670
  name: 'commonjs',
1287
1671
 
1288
1672
  buildStart() {
1673
+ validateRollupVersion(this.meta.rollupVersion, peerDependencies.rollup);
1289
1674
  if (options.namedExports != null) {
1290
1675
  this.warn(
1291
1676
  'The namedExports option from "@rollup/plugin-commonjs" is deprecated. Named exports are now handled automatically.'
1292
1677
  );
1293
1678
  }
1294
-
1295
- const [major, minor] = this.meta.rollupVersion.split('.').map(Number);
1296
- const minVersion = peerDependencies.rollup.slice(2);
1297
- const [minMajor, minMinor] = minVersion.split('.').map(Number);
1298
- if (major < minMajor || (major === minMajor && minor < minMinor)) {
1299
- this.error(
1300
- `Insufficient Rollup version: "@rollup/plugin-commonjs" requires at least rollup@${minVersion} but found rollup@${this.meta.rollupVersion}.`
1301
- );
1302
- }
1303
1679
  },
1304
1680
 
1305
1681
  resolveId,
@@ -1313,8 +1689,8 @@ function commonjs(options = {}) {
1313
1689
  return getSpecificHelperProxy(id);
1314
1690
  }
1315
1691
 
1316
- if (id.endsWith(EXTERNAL_SUFFIX)) {
1317
- const actualId = getIdFromExternalProxyId(id);
1692
+ if (isWrappedId(id, EXTERNAL_SUFFIX)) {
1693
+ const actualId = unwrapId(id, EXTERNAL_SUFFIX);
1318
1694
  return getUnknownRequireProxy(
1319
1695
  actualId,
1320
1696
  isEsmExternal(actualId) ? getRequireReturnsDefault(actualId) : true
@@ -1329,13 +1705,19 @@ function commonjs(options = {}) {
1329
1705
  return getDynamicJsonProxy(id, commonDir);
1330
1706
  }
1331
1707
 
1332
- const normalizedPath = normalizePathSlashes(id);
1333
- if (dynamicRequireModuleSet.has(normalizedPath) && !normalizedPath.endsWith('.json')) {
1334
- return getDynamicRequireProxy(normalizedPath, commonDir);
1708
+ if (isDynamicModuleImport(id, dynamicRequireModuleSet)) {
1709
+ return `export default require(${JSON.stringify(normalizePathSlashes(id))});`;
1710
+ }
1711
+
1712
+ if (isModuleRegisterProxy(id)) {
1713
+ return getDynamicRequireProxy(
1714
+ normalizePathSlashes(unwrapModuleRegisterProxy(id)),
1715
+ commonDir
1716
+ );
1335
1717
  }
1336
1718
 
1337
- if (id.endsWith(PROXY_SUFFIX)) {
1338
- const actualId = getIdFromProxyId(id);
1719
+ if (isWrappedId(id, PROXY_SUFFIX)) {
1720
+ const actualId = unwrapId(id, PROXY_SUFFIX);
1339
1721
  return getStaticRequireProxy(
1340
1722
  actualId,
1341
1723
  getRequireReturnsDefault(actualId),
@@ -1344,36 +1726,42 @@ function commonjs(options = {}) {
1344
1726
  );
1345
1727
  }
1346
1728
 
1347
- if (isDynamicRequireModulesEnabled && this.getModuleInfo(id).isEntry) {
1348
- return getDynamicPackagesEntryIntro(
1349
- id,
1350
- dynamicRequireModuleDirPaths,
1351
- dynamicRequireModuleSet
1352
- );
1353
- }
1354
-
1355
1729
  return null;
1356
1730
  },
1357
1731
 
1358
- transform(code, id) {
1732
+ transform(code, rawId) {
1733
+ let id = rawId;
1734
+
1735
+ if (isModuleRegisterProxy(id)) {
1736
+ id = unwrapModuleRegisterProxy(id);
1737
+ }
1738
+
1359
1739
  const extName = extname(id);
1360
- if (extName !== '.cjs' && id !== DYNAMIC_PACKAGES_ID && !id.startsWith(DYNAMIC_JSON_PREFIX)) {
1361
- if (!filter(id) || !extensions.includes(extName)) {
1362
- setIsCjsPromise(id, null);
1363
- return null;
1364
- }
1740
+ if (
1741
+ extName !== '.cjs' &&
1742
+ id !== DYNAMIC_PACKAGES_ID &&
1743
+ !id.startsWith(DYNAMIC_JSON_PREFIX) &&
1744
+ (!filter(id) || !extensions.includes(extName))
1745
+ ) {
1746
+ return null;
1365
1747
  }
1366
1748
 
1367
- let transformed;
1368
1749
  try {
1369
- transformed = transformAndCheckExports.call(this, code, id);
1750
+ return transformAndCheckExports.call(this, code, rawId);
1370
1751
  } catch (err) {
1371
- transformed = null;
1372
- setIsCjsPromise(id, false);
1373
- this.error(err, err.loc);
1752
+ return this.error(err, err.loc);
1374
1753
  }
1754
+ },
1375
1755
 
1376
- return transformed;
1756
+ moduleParsed({ id, meta: { commonjs } }) {
1757
+ if (commonjs) {
1758
+ const isCjs = commonjs.isCommonJS;
1759
+ if (isCjs != null) {
1760
+ setIsCjsPromise(id, isCjs);
1761
+ return;
1762
+ }
1763
+ }
1764
+ setIsCjsPromise(id, null);
1377
1765
  }
1378
1766
  };
1379
1767
  }