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