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