@rollup/plugin-commonjs 13.0.1 → 15.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -2,221 +2,97 @@
2
2
 
3
3
  function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
4
4
 
5
- var fs = require('fs');
6
5
  var path = require('path');
7
6
  var pluginutils = require('@rollup/pluginutils');
8
7
  var getCommonDir = _interopDefault(require('commondir'));
9
- var glob = _interopDefault(require('glob'));
8
+ var fs = require('fs');
10
9
  var estreeWalker = require('estree-walker');
11
10
  var MagicString = _interopDefault(require('magic-string'));
12
11
  var resolve = require('resolve');
13
12
  var isReference = _interopDefault(require('is-reference'));
14
-
15
- function _slicedToArray(arr, i) {
16
- return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
17
- }
18
-
19
- function _arrayWithHoles(arr) {
20
- if (Array.isArray(arr)) return arr;
21
- }
22
-
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;
29
-
30
- 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
- }
36
- } 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
- }
45
- }
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
- }
58
-
59
- function _arrayLikeToArray(arr, len) {
60
- if (len == null || len > arr.length) len = arr.length;
61
-
62
- for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
63
-
64
- return arr2;
65
- }
66
-
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
- }
70
-
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
- }
95
-
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
- }
98
-
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
- }
122
- }
123
- };
124
- }
13
+ var glob = _interopDefault(require('glob'));
125
14
 
126
15
  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)
16
+ rollup: "^2.22.0"
139
17
  };
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
- }
149
-
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;
172
- }
173
-
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
- }
180
18
 
181
19
  const PROXY_SUFFIX = '?commonjs-proxy';
182
- const getProxyId = id => `\0${id}${PROXY_SUFFIX}`;
183
- const getIdFromProxyId = proxyId => proxyId.slice(1, -PROXY_SUFFIX.length);
20
+ const getProxyId = (id) => `\0${id}${PROXY_SUFFIX}`;
21
+ const getIdFromProxyId = (proxyId) => proxyId.slice(1, -PROXY_SUFFIX.length);
22
+
184
23
  const EXTERNAL_SUFFIX = '?commonjs-external';
185
- const getExternalProxyId = id => `\0${id}${EXTERNAL_SUFFIX}`;
186
- const getIdFromExternalProxyId = proxyId => proxyId.slice(1, -EXTERNAL_SUFFIX.length);
24
+ const getExternalProxyId = (id) => `\0${id}${EXTERNAL_SUFFIX}`;
25
+ const getIdFromExternalProxyId = (proxyId) => proxyId.slice(1, -EXTERNAL_SUFFIX.length);
26
+
187
27
  const VIRTUAL_PATH_BASE = '/$$rollup_base$$';
188
28
  const getVirtualPathForDynamicRequirePath = (path, commonDir) => {
189
29
  if (path.startsWith(commonDir)) return VIRTUAL_PATH_BASE + path.slice(commonDir.length);
190
30
  return path;
191
31
  };
32
+
192
33
  const DYNAMIC_REGISTER_PREFIX = '\0commonjs-dynamic-register:';
193
34
  const DYNAMIC_JSON_PREFIX = '\0commonjs-dynamic-json:';
194
35
  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.
196
- // Minifiers like uglify will usually transpile it back if compatibility with ES3 is not enabled.
197
36
 
37
+ const HELPERS_ID = '\0commonjsHelpers.js';
38
+
39
+ // `x['default']` is used instead of `x.default` for backward compatibility with ES3 browsers.
40
+ // Minifiers like uglify will usually transpile it back if compatibility with ES3 is not enabled.
41
+ // This will no longer be necessary once Rollup switches to ES6 output, likely
42
+ // in Rollup 3
43
+
44
+ // The "hasOwnProperty" call in "getDefaultExportFromCjs" is technically not
45
+ // needed, but for consumers that use Rollup's old interop pattern, it will fix
46
+ // rollup/rollup-plugin-commonjs#224
47
+ // We should remove it once Rollup core and this plugin are updated to not use
48
+ // this pattern any more
198
49
  const HELPERS = `
199
50
  export var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
200
51
 
52
+ export function getDefaultExportFromCjs (x) {
53
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
54
+ }
55
+
201
56
  export function createCommonjsModule(fn, basedir, module) {
202
57
  return module = {
203
- path: basedir,
204
- exports: {},
205
- require: function (path, base) {
206
- return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
207
- }
58
+ path: basedir,
59
+ exports: {},
60
+ require: function (path, base) {
61
+ return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
62
+ }
208
63
  }, fn(module, module.exports), module.exports;
209
64
  }
210
65
 
211
- export function getCjsExportFromNamespace (n) {
212
- return n && n['default'] || n;
66
+ export function getDefaultExportFromNamespaceIfPresent (n) {
67
+ return n && Object.prototype.hasOwnProperty.call(n, 'default') ? n['default'] : n;
68
+ }
69
+
70
+ export function getDefaultExportFromNamespaceIfNotNamed (n) {
71
+ return n && Object.prototype.hasOwnProperty.call(n, 'default') && Object.keys(n).length === 1 ? n['default'] : n;
72
+ }
73
+
74
+ export function getAugmentedNamespace(n) {
75
+ if (n.__esModule) return n;
76
+ var a = Object.defineProperty({}, '__esModule', {value: true});
77
+ Object.keys(n).forEach(function (k) {
78
+ var d = Object.getOwnPropertyDescriptor(n, k);
79
+ Object.defineProperty(a, k, d.get ? d : {
80
+ enumerable: true,
81
+ get: function () {
82
+ return n[k];
83
+ }
84
+ });
85
+ });
86
+ return a;
213
87
  }
214
88
  `;
89
+
215
90
  const HELPER_NON_DYNAMIC = `
216
91
  export function commonjsRequire () {
217
92
  throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
218
93
  }
219
94
  `;
95
+
220
96
  const HELPERS_DYNAMIC = `
221
97
  export function commonjsRegister (path, loader) {
222
98
  DYNAMIC_REQUIRE_LOADERS[path] = loader;
@@ -356,27 +232,92 @@ export function commonjsRequire (path, originalModuleDir) {
356
232
  commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE;
357
233
  `;
358
234
 
235
+ function getHelpersModule(isDynamicRequireModulesEnabled) {
236
+ return `${HELPERS}${isDynamicRequireModulesEnabled ? HELPERS_DYNAMIC : HELPER_NON_DYNAMIC}`;
237
+ }
238
+
239
+ /* eslint-disable no-undefined */
240
+
241
+ const operators = {
242
+ '==': (x) => equals(x.left, x.right, false),
243
+
244
+ '!=': (x) => not(operators['=='](x)),
245
+
246
+ '===': (x) => equals(x.left, x.right, true),
247
+
248
+ '!==': (x) => not(operators['==='](x)),
249
+
250
+ '!': (x) => isFalsy(x.argument),
251
+
252
+ '&&': (x) => isTruthy(x.left) && isTruthy(x.right),
253
+
254
+ '||': (x) => isTruthy(x.left) || isTruthy(x.right)
255
+ };
256
+
257
+ function flatten(node) {
258
+ const parts = [];
259
+
260
+ while (node.type === 'MemberExpression') {
261
+ if (node.computed) return null;
262
+
263
+ parts.unshift(node.property.name);
264
+ // eslint-disable-next-line no-param-reassign
265
+ node = node.object;
266
+ }
267
+
268
+ if (node.type !== 'Identifier') return null;
269
+
270
+ const { name } = node;
271
+ parts.unshift(name);
272
+
273
+ return { name, keypath: parts.join('.') };
274
+ }
275
+
276
+ function isTruthy(node) {
277
+ if (node.type === 'Literal') return !!node.value;
278
+ if (node.type === 'ParenthesizedExpression') return isTruthy(node.expression);
279
+ if (node.operator in operators) return operators[node.operator](node);
280
+ return undefined;
281
+ }
282
+
283
+ function isFalsy(node) {
284
+ return not(isTruthy(node));
285
+ }
286
+
287
+ function not(value) {
288
+ return value === undefined ? value : !value;
289
+ }
290
+
291
+ function equals(a, b, strict) {
292
+ if (a.type !== b.type) return undefined;
293
+ // eslint-disable-next-line eqeqeq
294
+ if (a.type === 'Literal') return strict ? a.value === b.value : a.value == b.value;
295
+ return undefined;
296
+ }
297
+
359
298
  /* eslint-disable import/prefer-default-export */
299
+
360
300
  function getName(id) {
361
301
  const name = pluginutils.makeLegalIdentifier(path.basename(id, path.extname(id)));
362
-
363
302
  if (name !== 'index') {
364
303
  return name;
365
304
  }
366
-
367
305
  const segments = path.dirname(id).split(path.sep);
368
306
  return pluginutils.makeLegalIdentifier(segments[segments.length - 1]);
369
307
  }
370
308
 
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);
309
+ /* eslint-disable no-param-reassign, no-shadow, no-underscore-dangle, no-continue */
310
+
311
+ 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(
312
+ ' '
313
+ );
314
+ const blacklist = { __esModule: true };
315
+ reserved.forEach((word) => (blacklist[word] = true));
316
+
376
317
  const exportsPattern = /^(?:module\.)?exports(?:\.([a-zA-Z_$][a-zA-Z_$0-9]*))?$/;
318
+
377
319
  const firstpassGlobal = /\b(?:require|module|exports|global)\b/;
378
320
  const firstpassNoGlobal = /\b(?:require|module|exports)\b/;
379
- const importExportDeclaration = /^(?:Import|Export(?:Named|Default))Declaration/;
380
321
  const functionType = /^(?:FunctionDeclaration|FunctionExpression|ArrowFunctionExpression)$/;
381
322
 
382
323
  function deconflict(scope, globals, identifier) {
@@ -387,16 +328,14 @@ function deconflict(scope, globals, identifier) {
387
328
  deconflicted = `${identifier}_${i}`;
388
329
  i += 1;
389
330
  }
390
-
391
331
  scope.declarations[deconflicted] = true;
332
+
392
333
  return deconflicted;
393
334
  }
394
335
 
395
336
  function tryParse(parse, code, id) {
396
337
  try {
397
- return parse(code, {
398
- allowReturnOutsideFunction: true
399
- });
338
+ return parse(code, { allowReturnOutsideFunction: true });
400
339
  } catch (err) {
401
340
  err.message += ` in ${id}`;
402
341
  throw err;
@@ -406,157 +345,160 @@ function tryParse(parse, code, id) {
406
345
  function normalizePathSlashes(path) {
407
346
  return path.replace(/\\/g, '/');
408
347
  }
348
+
409
349
  function hasCjsKeywords(code, ignoreGlobal) {
410
350
  const firstpass = ignoreGlobal ? firstpassNoGlobal : firstpassGlobal;
411
351
  return firstpass.test(code);
412
352
  }
353
+
413
354
  function checkEsModule(parse, code, id) {
414
355
  const ast = tryParse(parse, code, id);
415
- let isEsModule = false;
416
-
417
- var _iterator = _createForOfIteratorHelper(ast.body),
418
- _step;
419
356
 
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
-
429
- if (node.type === 'ExportNamedDeclaration') {
430
- isEsModule = true;
431
-
432
- var _iterator2 = _createForOfIteratorHelper(node.specifiers),
433
- _step2;
434
-
435
- try {
436
- for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
437
- const specifier = _step2.value;
438
-
439
- if (specifier.exported.name === 'default') {
440
- return {
441
- isEsModule: true,
442
- hasDefaultExport: true,
443
- ast
444
- };
445
- }
357
+ let isEsModule = false;
358
+ let hasDefaultExport = false;
359
+ let hasNamedExports = false;
360
+ for (const node of ast.body) {
361
+ if (node.type === 'ExportDefaultDeclaration') {
362
+ isEsModule = true;
363
+ hasDefaultExport = true;
364
+ } else if (node.type === 'ExportNamedDeclaration') {
365
+ isEsModule = true;
366
+ if (node.declaration) {
367
+ hasNamedExports = true;
368
+ } else {
369
+ for (const specifier of node.specifiers) {
370
+ if (specifier.exported.name === 'default') {
371
+ hasDefaultExport = true;
372
+ } else {
373
+ hasNamedExports = true;
446
374
  }
447
- } catch (err) {
448
- _iterator2.e(err);
449
- } finally {
450
- _iterator2.f();
451
375
  }
452
- } else if (importExportDeclaration.test(node.type)) isEsModule = true;
376
+ }
377
+ } else if (node.type === 'ExportAllDeclaration') {
378
+ isEsModule = true;
379
+ if (node.exported && node.exported.name === 'default') {
380
+ hasDefaultExport = true;
381
+ } else {
382
+ hasNamedExports = true;
383
+ }
384
+ } else if (node.type === 'ImportDeclaration') {
385
+ isEsModule = true;
453
386
  }
454
- } catch (err) {
455
- _iterator.e(err);
456
- } finally {
457
- _iterator.f();
458
387
  }
459
388
 
460
- return {
461
- isEsModule,
462
- hasDefaultExport: false,
463
- ast
464
- };
389
+ return { isEsModule, hasDefaultExport, hasNamedExports, ast };
465
390
  }
466
391
 
467
392
  function getDefinePropertyCallName(node, targetName) {
468
393
  if (node.type !== 'CallExpression') return;
469
- const _node$callee = node.callee,
470
- object = _node$callee.object,
471
- property = _node$callee.property;
394
+
395
+ const {
396
+ callee: { object, property }
397
+ } = node;
398
+
472
399
  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
400
 
476
- const _node$arguments = _slicedToArray(node.arguments, 2),
477
- target = _node$arguments[0],
478
- val = _node$arguments[1];
401
+ if (!property || property.type !== 'Identifier' || property.name !== 'defineProperty') return;
479
402
 
480
- if (target.type !== 'Identifier' || target.name !== targetName) return; // eslint-disable-next-line consistent-return
403
+ if (node.arguments.length !== 3) return;
481
404
 
405
+ const [target, val] = node.arguments;
406
+ if (target.type !== 'Identifier' || target.name !== targetName) return;
407
+ // eslint-disable-next-line consistent-return
482
408
  return val.value;
483
409
  }
484
410
 
485
- function transformCommonjs(parse, code, id, isEntry, hasImporters, isEsModule, ignoreGlobal, ignoreRequire, sourceMap, isDynamicRequireModulesEnabled, dynamicRequireModuleSet, commonDir, astCache) {
411
+ function transformCommonjs(
412
+ parse,
413
+ code,
414
+ id,
415
+ isEsModule,
416
+ ignoreGlobal,
417
+ ignoreRequire,
418
+ sourceMap,
419
+ isDynamicRequireModulesEnabled,
420
+ dynamicRequireModuleSet,
421
+ commonDir,
422
+ astCache
423
+ ) {
486
424
  const ast = astCache || tryParse(parse, code, id);
425
+
487
426
  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
427
 
428
+ const required = {};
429
+ // Because objects have no guaranteed ordering, yet we need it,
430
+ // we need to keep track of the order in a array
491
431
  const sources = [];
432
+
492
433
  let uid = 0;
434
+
493
435
  let scope = pluginutils.attachScopes(ast, 'scope');
494
- const uses = {
495
- module: false,
496
- exports: false,
497
- global: false,
498
- require: false
499
- };
436
+ const uses = { module: false, exports: false, global: false, require: false };
437
+
500
438
  let lexicalDepth = 0;
501
439
  let programDepth = 0;
502
- const globals = new Set(); // TODO technically wrong since globals isn't populated yet, but ¯\_(ツ)_/¯
503
440
 
441
+ const globals = new Set();
442
+
443
+ // TODO technically wrong since globals isn't populated yet, but ¯\_(ツ)_/¯
504
444
  const HELPERS_NAME = deconflict(scope, globals, 'commonjsHelpers');
505
- const namedExports = {}; // TODO handle transpiled modules
506
445
 
446
+ const namedExports = {};
447
+
448
+ // TODO handle transpiled modules
507
449
  let shouldWrap = /__esModule/.test(code);
508
450
  let usesCommonjsHelpers = false;
509
451
 
510
452
  function isRequireStatement(node) {
511
453
  if (!node) return false;
512
- if (node.type !== 'CallExpression') return false; // Weird case of `require()` or `module.require()` without arguments
454
+ if (node.type !== 'CallExpression') return false;
513
455
 
456
+ // Weird case of `require()` or `module.require()` without arguments
514
457
  if (node.arguments.length === 0) return false;
458
+
515
459
  return isRequireIdentifier(node.callee);
516
460
  }
517
461
 
518
462
  function isRequireIdentifier(node) {
519
463
  if (!node) return false;
520
464
 
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
465
+ if (node.type === 'Identifier' && node.name === 'require' /* `require` */) {
466
+ // `require` is hidden by a variable in local scope
467
+ if (scope.contains('require')) return false;
532
468
 
533
- if (scope.contains('module')) return false; // `module.require(...)`
469
+ return true;
470
+ } else if (node.type === 'MemberExpression' /* `[something].[something]` */) {
471
+ // `module.[something]`
472
+ if (node.object.type !== 'Identifier' || node.object.name !== 'module') return false;
534
473
 
535
- if (node.property.type !== 'Identifier' || node.property.name !== 'require') return false;
536
- return true;
537
- }
474
+ // `module` is hidden by a variable in local scope
475
+ if (scope.contains('module')) return false;
476
+
477
+ // `module.require(...)`
478
+ if (node.property.type !== 'Identifier' || node.property.name !== 'require') return false;
479
+
480
+ return true;
481
+ }
538
482
 
539
483
  return false;
540
484
  }
541
485
 
542
486
  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);
487
+ return (
488
+ node.arguments.length > 1 ||
489
+ (node.arguments[0].type !== 'Literal' &&
490
+ (node.arguments[0].type !== 'TemplateLiteral' || node.arguments[0].expressions.length > 0))
491
+ );
544
492
  }
545
493
 
546
494
  function isStaticRequireStatement(node) {
547
495
  if (!isRequireStatement(node)) return false;
548
- if (hasDynamicArguments(node)) return false;
549
- return true;
496
+ return !hasDynamicArguments(node);
550
497
  }
551
498
 
552
499
  function isNodeRequireStatement(parent) {
553
500
  const reservedMethod = ['resolve', 'cache', 'main'];
554
-
555
- if (parent && parent.property && reservedMethod.indexOf(parent.property.name) > -1) {
556
- return true;
557
- }
558
-
559
- return false;
501
+ return !!(parent && parent.property && reservedMethod.indexOf(parent.property.name) > -1);
560
502
  }
561
503
 
562
504
  function isIgnoredRequireStatement(requiredNode) {
@@ -564,19 +506,20 @@ function transformCommonjs(parse, code, id, isEntry, hasImporters, isEsModule, i
564
506
  }
565
507
 
566
508
  function getRequireStringArg(node) {
567
- return node.arguments[0].type === 'Literal' ? node.arguments[0].value : node.arguments[0].quasis[0].value.cooked;
509
+ return node.arguments[0].type === 'Literal'
510
+ ? node.arguments[0].value
511
+ : node.arguments[0].quasis[0].value.cooked;
568
512
  }
569
513
 
570
514
  function getRequired(node, name) {
571
515
  let sourceId = getRequireStringArg(node);
572
516
  const isDynamicRegister = sourceId.startsWith(DYNAMIC_REGISTER_PREFIX);
573
-
574
517
  if (isDynamicRegister) {
575
518
  sourceId = sourceId.substr(DYNAMIC_REGISTER_PREFIX.length);
576
519
  }
577
520
 
578
- const existing = required[sourceId]; // eslint-disable-next-line no-undefined
579
-
521
+ const existing = required[sourceId];
522
+ // eslint-disable-next-line no-undefined
580
523
  if (existing === undefined) {
581
524
  const isDynamic = hasDynamicModuleForPath(sourceId);
582
525
 
@@ -595,12 +538,7 @@ function transformCommonjs(parse, code, id, isEntry, hasImporters, isEsModule, i
595
538
  sources.push([sourceId, !isDynamicRegister]);
596
539
  }
597
540
 
598
- required[sourceId] = {
599
- source: sourceId,
600
- name,
601
- importsDefault: false,
602
- isDynamic
603
- };
541
+ required[sourceId] = { source: sourceId, name, importsDefault: false, isDynamic };
604
542
  }
605
543
 
606
544
  return required[sourceId];
@@ -609,10 +547,9 @@ function transformCommonjs(parse, code, id, isEntry, hasImporters, isEsModule, i
609
547
  function hasDynamicModuleForPath(source) {
610
548
  if (!/[/\\]/.test(source)) {
611
549
  try {
612
- const resolvedPath = normalizePathSlashes(resolve.sync(source, {
613
- basedir: path.dirname(id)
614
- }));
615
-
550
+ const resolvedPath = normalizePathSlashes(
551
+ resolve.sync(source, { basedir: path.dirname(id) })
552
+ );
616
553
  if (dynamicRequireModuleSet.has(resolvedPath)) {
617
554
  return true;
618
555
  }
@@ -624,10 +561,8 @@ function transformCommonjs(parse, code, id, isEntry, hasImporters, isEsModule, i
624
561
  return false;
625
562
  }
626
563
 
627
- for (var _i = 0, _arr = ['', '.js', '.json']; _i < _arr.length; _i++) {
628
- const attemptExt = _arr[_i];
564
+ for (const attemptExt of ['', '.js', '.json']) {
629
565
  const resolvedPath = normalizePathSlashes(path.resolve(path.dirname(id), source + attemptExt));
630
-
631
566
  if (dynamicRequireModuleSet.has(resolvedPath)) {
632
567
  return true;
633
568
  }
@@ -637,38 +572,41 @@ function transformCommonjs(parse, code, id, isEntry, hasImporters, isEsModule, i
637
572
  }
638
573
 
639
574
  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
575
+ return (
576
+ hasDynamicModuleForPath(required.source) &&
577
+ // We only do `commonjsRequire` for json if it's the `commonjsRegister` call.
578
+ (required.source.startsWith(DYNAMIC_REGISTER_PREFIX) || !required.source.endsWith('.json'))
579
+ );
580
+ }
581
+
582
+ // do a first pass, see which names are assigned to. This is necessary to prevent
643
583
  // illegally replacing `var foo = require('foo')` with `import foo from 'foo'`,
644
584
  // where `foo` is later reassigned. (This happens in the wild. CommonJS, sigh)
645
-
646
-
647
585
  const assignedTo = new Set();
648
586
  estreeWalker.walk(ast, {
649
587
  enter(node) {
650
588
  if (node.type !== 'AssignmentExpression') return;
651
589
  if (node.left.type === 'MemberExpression') return;
652
- pluginutils.extractAssignedNames(node.left).forEach(name => {
590
+
591
+ pluginutils.extractAssignedNames(node.left).forEach((name) => {
653
592
  assignedTo.add(name);
654
593
  });
655
594
  }
656
-
657
595
  });
596
+
658
597
  estreeWalker.walk(ast, {
659
598
  enter(node, parent) {
660
599
  if (sourceMap) {
661
600
  magicString.addSourcemapLocation(node.start);
662
601
  magicString.addSourcemapLocation(node.end);
663
- } // skip dead branches
664
-
602
+ }
665
603
 
604
+ // skip dead branches
666
605
  if (parent && (parent.type === 'IfStatement' || parent.type === 'ConditionalExpression')) {
667
606
  if (node === parent.consequent && isFalsy(parent.test)) {
668
607
  this.skip();
669
608
  return;
670
609
  }
671
-
672
610
  if (node === parent.alternate && isTruthy(parent.test)) {
673
611
  this.skip();
674
612
  return;
@@ -682,45 +620,44 @@ function transformCommonjs(parse, code, id, isEntry, hasImporters, isEsModule, i
682
620
 
683
621
  programDepth += 1;
684
622
 
685
- if (node.scope) {
686
- scope = node.scope;
687
- }
688
-
689
- if (functionType.test(node.type)) lexicalDepth += 1; // if toplevel return, we need to wrap it
623
+ if (node.scope) ({ scope } = node);
624
+ if (functionType.test(node.type)) lexicalDepth += 1;
690
625
 
626
+ // if toplevel return, we need to wrap it
691
627
  if (node.type === 'ReturnStatement' && lexicalDepth === 0) {
692
628
  shouldWrap = true;
693
- } // rewrite `this` as `commonjsHelpers.commonjsGlobal`
694
-
629
+ }
695
630
 
631
+ // rewrite `this` as `commonjsHelpers.commonjsGlobal`
696
632
  if (node.type === 'ThisExpression' && lexicalDepth === 0) {
697
633
  uses.global = true;
698
-
699
634
  if (!ignoreGlobal) {
700
635
  magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsGlobal`, {
701
636
  storeName: true
702
637
  });
703
638
  usesCommonjsHelpers = true;
704
639
  }
705
-
706
640
  return;
707
- } // rewrite `typeof module`, `typeof module.exports` and `typeof exports` (https://github.com/rollup/rollup-plugin-commonjs/issues/151)
708
-
641
+ }
709
642
 
643
+ // rewrite `typeof module`, `typeof module.exports` and `typeof exports` (https://github.com/rollup/rollup-plugin-commonjs/issues/151)
710
644
  if (node.type === 'UnaryExpression' && node.operator === 'typeof') {
711
645
  const flattened = flatten(node.argument);
712
646
  if (!flattened) return;
647
+
713
648
  if (scope.contains(flattened.name)) return;
714
649
 
715
- if (flattened.keypath === 'module.exports' || flattened.keypath === 'module' || flattened.keypath === 'exports') {
716
- magicString.overwrite(node.start, node.end, `'object'`, {
717
- storeName: false
718
- });
650
+ if (
651
+ flattened.keypath === 'module.exports' ||
652
+ flattened.keypath === 'module' ||
653
+ flattened.keypath === 'exports'
654
+ ) {
655
+ magicString.overwrite(node.start, node.end, `'object'`, { storeName: false });
719
656
  }
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
722
-
657
+ }
723
658
 
659
+ // rewrite `require` (if not already handled) `global` and `define`, and handle free references to
660
+ // `module` and `exports` as these mean we need to wrap the module in commonjsHelpers.createCommonjsModule
724
661
  if (node.type === 'Identifier') {
725
662
  if (isReference(node, parent) && !scope.contains(node.name)) {
726
663
  if (node.name in uses) {
@@ -734,9 +671,17 @@ function transformCommonjs(parse, code, id, isEntry, hasImporters, isEsModule, i
734
671
  }
735
672
 
736
673
  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))}`);
674
+ magicString.appendLeft(
675
+ parent.end - 1,
676
+ `,${JSON.stringify(
677
+ path.dirname(id) === '.'
678
+ ? null /* default behavior */
679
+ : getVirtualPathForDynamicRequirePath(
680
+ normalizePathSlashes(path.dirname(id)),
681
+ commonDir
682
+ )
683
+ )}`
684
+ );
740
685
  }
741
686
 
742
687
  magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, {
@@ -746,51 +691,54 @@ function transformCommonjs(parse, code, id, isEntry, hasImporters, isEsModule, i
746
691
  }
747
692
 
748
693
  uses[node.name] = true;
749
-
750
694
  if (node.name === 'global' && !ignoreGlobal) {
751
695
  magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsGlobal`, {
752
696
  storeName: true
753
697
  });
754
698
  usesCommonjsHelpers = true;
755
- } // if module or exports are used outside the context of an assignment
756
- // expression, we need to wrap the module
757
-
699
+ }
758
700
 
701
+ // if module or exports are used outside the context of an assignment
702
+ // expression, we need to wrap the module
759
703
  if (node.name === 'module' || node.name === 'exports') {
760
704
  shouldWrap = true;
761
705
  }
762
706
  }
763
707
 
764
708
  if (node.name === 'define') {
765
- magicString.overwrite(node.start, node.end, 'undefined', {
766
- storeName: true
767
- });
709
+ magicString.overwrite(node.start, node.end, 'undefined', { storeName: true });
768
710
  }
769
711
 
770
712
  globals.add(node.name);
771
713
  }
772
714
 
773
715
  return;
774
- } // Is this an assignment to exports or module.exports?
775
-
716
+ }
776
717
 
718
+ // Is this an assignment to exports or module.exports?
777
719
  if (node.type === 'AssignmentExpression') {
778
720
  if (node.left.type !== 'MemberExpression') return;
721
+
779
722
  const flattened = flatten(node.left);
780
723
  if (!flattened) return;
724
+
781
725
  if (scope.contains(flattened.name)) return;
726
+
782
727
  const match = exportsPattern.exec(flattened.keypath);
783
728
  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
729
 
730
+ uses[flattened.name] = true;
731
+
732
+ // we're dealing with `module.exports = ...` or `[module.]exports.foo = ...` –
733
+ // if this isn't top-level, we'll need to wrap the module
787
734
  if (programDepth > 3) shouldWrap = true;
735
+
788
736
  node.left._skip = true;
789
737
 
790
738
  if (flattened.keypath === 'module.exports' && node.right.type === 'ObjectExpression') {
791
- node.right.properties.forEach(prop => {
739
+ node.right.properties.forEach((prop) => {
792
740
  if (prop.computed || !('key' in prop) || prop.key.type !== 'Identifier') return;
793
- const name = prop.key.name;
741
+ const { name } = prop.key;
794
742
  if (name === pluginutils.makeLegalIdentifier(name)) namedExports[name] = true;
795
743
  });
796
744
  return;
@@ -801,13 +749,21 @@ function transformCommonjs(parse, code, id, isEntry, hasImporters, isEsModule, i
801
749
  }
802
750
 
803
751
  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'`
805
-
806
- if (node.type === 'VariableDeclarator' && node.id.type === 'Identifier' && isStaticRequireStatement(node.init) && !isIgnoredRequireStatement(node.init)) {
752
+ if (name && name === pluginutils.makeLegalIdentifier(name)) namedExports[name] = true;
753
+
754
+ // if this is `var x = require('x')`, we can do `import x from 'x'`
755
+ if (
756
+ node.type === 'VariableDeclarator' &&
757
+ node.id.type === 'Identifier' &&
758
+ isStaticRequireStatement(node.init) &&
759
+ !isIgnoredRequireStatement(node.init)
760
+ ) {
807
761
  // 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
762
+ if (scope.parent) return;
809
763
 
764
+ // edge case — CJS allows you to assign to imports. ES doesn't
810
765
  if (assignedTo.has(node.id.name)) return;
766
+
811
767
  const required = getRequired(node.init, node.id.name);
812
768
  required.importsDefault = true;
813
769
 
@@ -829,9 +785,17 @@ function transformCommonjs(parse, code, id, isEntry, hasImporters, isEsModule, i
829
785
  required.importsDefault = true;
830
786
 
831
787
  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))})`);
788
+ magicString.overwrite(
789
+ node.start,
790
+ node.end,
791
+ `${HELPERS_NAME}.commonjsRequire(${JSON.stringify(
792
+ getVirtualPathForDynamicRequirePath(normalizePathSlashes(required.source), commonDir)
793
+ )}, ${JSON.stringify(
794
+ path.dirname(id) === '.'
795
+ ? null /* default behavior */
796
+ : getVirtualPathForDynamicRequirePath(normalizePathSlashes(path.dirname(id)), commonDir)
797
+ )})`
798
+ );
835
799
  usesCommonjsHelpers = true;
836
800
  } else {
837
801
  magicString.overwrite(node.start, node.end, required.name);
@@ -870,36 +834,58 @@ function transformCommonjs(parse, code, id, isEntry, hasImporters, isEsModule, i
870
834
  }
871
835
  }
872
836
  }
873
-
874
837
  });
875
838
 
876
- if (!sources.length && !uses.module && !uses.exports && !uses.require && (ignoreGlobal || !uses.global)) {
839
+ if (
840
+ !sources.length &&
841
+ !uses.module &&
842
+ !uses.exports &&
843
+ !uses.require &&
844
+ (ignoreGlobal || !uses.global)
845
+ ) {
877
846
  // not a CommonJS module
878
847
  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
-
848
+ }
882
849
 
850
+ // If `isEsModule` is on, it means it has ES6 import/export statements,
851
+ // which just can't be wrapped in a function.
883
852
  if (isEsModule) shouldWrap = false;
853
+
884
854
  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`;
855
+
856
+ const importBlock = `${(usesCommonjsHelpers
857
+ ? [`import * as ${HELPERS_NAME} from '${HELPERS_ID}';`]
858
+ : []
859
+ )
860
+ .concat(
861
+ sources.map(
862
+ ([source]) =>
863
+ // import the actual module before the proxy, so that we know
864
+ // what kind of proxy to build
865
+ `import '${source}';`
866
+ ),
867
+ sources
868
+ .filter(([, importProxy]) => importProxy)
869
+ .map(([source]) => {
870
+ const { name, importsDefault } = required[source];
871
+ return `import ${importsDefault ? `${name} from ` : ``}'${
872
+ source.startsWith('\0') ? source : getProxyId(source)
873
+ }';`;
874
+ })
875
+ )
876
+ .join('\n')}\n\n`;
877
+
893
878
  const namedExportDeclarations = [];
894
879
  let wrapperStart = '';
895
880
  let wrapperEnd = '';
896
- const moduleName = deconflict(scope, globals, getName(id));
897
881
 
898
- if ((!isEntry || hasImporters) && !isEsModule) {
882
+ const moduleName = deconflict(scope, globals, getName(id));
883
+ if (!isEsModule) {
899
884
  const exportModuleExports = {
900
885
  str: `export { ${moduleName} as __moduleExports };`,
901
886
  name: '__moduleExports'
902
887
  };
888
+
903
889
  namedExportDeclarations.push(exportModuleExports);
904
890
  }
905
891
 
@@ -908,149 +894,176 @@ function transformCommonjs(parse, code, id, isEntry, hasImporters, isEsModule, i
908
894
 
909
895
  if (shouldWrap) {
910
896
  const args = `module${uses.exports ? ', exports' : ''}`;
897
+
911
898
  wrapperStart = `var ${moduleName} = ${HELPERS_NAME}.createCommonjsModule(function (${args}) {\n`;
912
- wrapperEnd = `\n}`;
913
899
 
900
+ wrapperEnd = `\n}`;
914
901
  if (isDynamicRequireModulesEnabled) {
915
- wrapperEnd += `, ${JSON.stringify(getVirtualPathForDynamicRequirePath(normalizePathSlashes(path.dirname(id)), commonDir))}`;
902
+ wrapperEnd += `, ${JSON.stringify(
903
+ getVirtualPathForDynamicRequirePath(normalizePathSlashes(path.dirname(id)), commonDir)
904
+ )}`;
916
905
  }
917
906
 
918
907
  wrapperEnd += `);`;
919
908
  } else {
920
909
  const names = [];
921
910
 
922
- var _iterator3 = _createForOfIteratorHelper(ast.body),
923
- _step3;
911
+ for (const node of ast.body) {
912
+ if (node.type === 'ExpressionStatement' && node.expression.type === 'AssignmentExpression') {
913
+ const { left } = node.expression;
914
+ const flattened = flatten(left);
924
915
 
925
- try {
926
- for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
927
- const node = _step3.value;
916
+ if (!flattened) {
917
+ continue;
918
+ }
928
919
 
929
- if (node.type === 'ExpressionStatement' && node.expression.type === 'AssignmentExpression') {
930
- const left = node.expression.left;
931
- const flattened = flatten(left);
920
+ const match = exportsPattern.exec(flattened.keypath);
921
+ if (!match) {
922
+ continue;
923
+ }
932
924
 
933
- if (!flattened) {
934
- continue;
935
- }
925
+ if (flattened.keypath === 'module.exports') {
926
+ hasDefaultExport = true;
927
+ magicString.overwrite(left.start, left.end, `var ${moduleName}`);
928
+ } else {
929
+ const [, name] = match;
930
+ const deconflicted = deconflict(scope, globals, name);
936
931
 
937
- const match = exportsPattern.exec(flattened.keypath);
932
+ names.push({ name, deconflicted });
938
933
 
939
- if (!match) {
940
- continue;
941
- }
934
+ magicString.overwrite(node.start, left.end, `var ${deconflicted}`);
942
935
 
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];
936
+ const declaration =
937
+ name === deconflicted
938
+ ? `export { ${name} };`
939
+ : `export { ${deconflicted} as ${name} };`;
949
940
 
950
- const deconflicted = deconflict(scope, globals, name);
951
- names.push({
952
- name,
953
- deconflicted
941
+ if (name !== 'default') {
942
+ namedExportDeclarations.push({
943
+ str: declaration,
944
+ name
954
945
  });
955
- magicString.overwrite(node.start, left.end, `var ${deconflicted}`);
956
- const declaration = name === deconflicted ? `export { ${name} };` : `export { ${deconflicted} as ${name} };`;
957
-
958
- if (name !== 'default') {
959
- namedExportDeclarations.push({
960
- str: declaration,
961
- name
962
- });
963
- }
964
-
965
- defaultExportPropertyAssignments.push(`${moduleName}.${name} = ${deconflicted};`);
966
946
  }
947
+
948
+ defaultExportPropertyAssignments.push(`${moduleName}.${name} = ${deconflicted};`);
967
949
  }
968
950
  }
969
- } catch (err) {
970
- _iterator3.e(err);
971
- } finally {
972
- _iterator3.f();
973
951
  }
974
952
 
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};`;
953
+ if (!(isEsModule || hasDefaultExport)) {
954
+ wrapperEnd = `\n\nvar ${moduleName} = {\n${names
955
+ .map(({ name, deconflicted }) => `\t${name}: ${deconflicted}`)
956
+ .join(',\n')}\n};`;
980
957
  }
981
958
  }
982
959
 
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;
960
+ magicString
961
+ .trim()
962
+ .prepend(importBlock + wrapperStart)
963
+ .trim()
964
+ .append(wrapperEnd);
988
965
 
989
- if (injectExportBlock) {
990
- magicString.append(exportBlock);
991
- }
966
+ const defaultExport =
967
+ code.indexOf('__esModule') >= 0
968
+ ? `export default /*@__PURE__*/${HELPERS_NAME}.getDefaultExportFromCjs(${moduleName});`
969
+ : `export default ${moduleName};`;
970
+
971
+ const named = namedExportDeclarations
972
+ .filter((x) => x.name !== 'default' || !hasDefaultExport)
973
+ .map((x) => x.str);
974
+
975
+ magicString.append(
976
+ `\n\n${(isEsModule ? [] : [defaultExport])
977
+ .concat(named)
978
+ .concat(hasDefaultExport ? defaultExportPropertyAssignments : [])
979
+ .join('\n')}`
980
+ );
992
981
 
993
982
  code = magicString.toString();
994
983
  const map = sourceMap ? magicString.generateMap() : null;
995
- return {
996
- code,
997
- map,
998
- syntheticNamedExports: injectExportBlock
999
- };
984
+
985
+ return { code, map, syntheticNamedExports: isEsModule ? false : '__moduleExports' };
1000
986
  }
1001
987
 
1002
- function getDynamicRequirePaths(patterns) {
1003
- const dynamicRequireModuleSet = new Set();
988
+ function getDynamicPackagesModule(dynamicRequireModuleDirPaths, commonDir) {
989
+ let code = `const commonjsRegister = require('${HELPERS_ID}?commonjsRegister');`;
990
+ for (const dir of dynamicRequireModuleDirPaths) {
991
+ let entryPoint = 'index.js';
1004
992
 
1005
- var _iterator = _createForOfIteratorHelper(!patterns || Array.isArray(patterns) ? patterns || [] : [patterns]),
1006
- _step;
993
+ try {
994
+ if (fs.existsSync(path.join(dir, 'package.json'))) {
995
+ entryPoint =
996
+ JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), { encoding: 'utf8' })).main ||
997
+ entryPoint;
998
+ }
999
+ } catch (ignored) {
1000
+ // ignored
1001
+ }
1002
+
1003
+ code += `\ncommonjsRegister(${JSON.stringify(
1004
+ getVirtualPathForDynamicRequirePath(dir, commonDir)
1005
+ )}, function (module, exports) {
1006
+ module.exports = require(${JSON.stringify(normalizePathSlashes(path.join(dir, entryPoint)))});
1007
+ });`;
1008
+ }
1009
+ return code;
1010
+ }
1007
1011
 
1012
+ function getDynamicPackagesEntryIntro(
1013
+ id,
1014
+ dynamicRequireModuleDirPaths,
1015
+ dynamicRequireModuleSet
1016
+ ) {
1008
1017
  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);
1018
+ const code = fs.readFileSync(id, { encoding: 'utf8' });
1019
+ let dynamicImports = Array.from(
1020
+ dynamicRequireModuleSet,
1021
+ (dynamicId) => `require(${JSON.stringify(DYNAMIC_REGISTER_PREFIX + dynamicId)});`
1022
+ ).join('\n');
1023
+
1024
+ if (dynamicRequireModuleDirPaths.length) {
1025
+ dynamicImports += `require(${JSON.stringify(
1026
+ DYNAMIC_REGISTER_PREFIX + DYNAMIC_PACKAGES_ID
1027
+ )});`;
1028
+ }
1013
1029
 
1014
- var _iterator2 = _createForOfIteratorHelper(glob.sync(isNegated ? pattern.substr(1) : pattern)),
1015
- _step2;
1030
+ return `${dynamicImports}\n${code}`;
1031
+ } catch (ex) {
1032
+ this.warn(`Failed to read file ${id}, dynamic modules might not work correctly`);
1033
+ return null;
1034
+ }
1035
+ }
1016
1036
 
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();
1026
- }
1037
+ function getDynamicRequirePaths(patterns) {
1038
+ const dynamicRequireModuleSet = new Set();
1039
+ for (const pattern of !patterns || Array.isArray(patterns) ? patterns || [] : [patterns]) {
1040
+ const isNegated = pattern.startsWith('!');
1041
+ const modifySet = Set.prototype[isNegated ? 'delete' : 'add'].bind(dynamicRequireModuleSet);
1042
+ for (const path$1 of glob.sync(isNegated ? pattern.substr(1) : pattern)) {
1043
+ modifySet(normalizePathSlashes(path.resolve(path$1)));
1027
1044
  }
1028
- } catch (err) {
1029
- _iterator.e(err);
1030
- } finally {
1031
- _iterator.f();
1032
1045
  }
1033
-
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
1046
+ const dynamicRequireModuleDirPaths = Array.from(dynamicRequireModuleSet.values()).filter(
1047
+ (path) => {
1048
+ try {
1049
+ if (fs.statSync(path).isDirectory()) return true;
1050
+ } catch (ignored) {
1051
+ // Nothing to do here
1052
+ }
1053
+ return false;
1038
1054
  }
1039
-
1040
- return false;
1041
- });
1042
- return {
1043
- dynamicRequireModuleSet,
1044
- dynamicRequireModuleDirPaths
1045
- };
1055
+ );
1056
+ return { dynamicRequireModuleSet, dynamicRequireModuleDirPaths };
1046
1057
  }
1047
1058
 
1048
1059
  /* eslint-disable no-undefined */
1049
1060
  const isCjsPromises = new Map();
1061
+
1050
1062
  function getIsCjsPromise(id) {
1051
1063
  let isCjsPromise = isCjsPromises.get(id);
1052
1064
  if (isCjsPromise) return isCjsPromise.promise;
1053
- const promise = new Promise(resolve => {
1065
+
1066
+ const promise = new Promise((resolve) => {
1054
1067
  isCjsPromise = {
1055
1068
  resolve,
1056
1069
  promise: undefined
@@ -1058,22 +1071,85 @@ function getIsCjsPromise(id) {
1058
1071
  isCjsPromises.set(id, isCjsPromise);
1059
1072
  });
1060
1073
  isCjsPromise.promise = promise;
1074
+
1061
1075
  return promise;
1062
1076
  }
1077
+
1063
1078
  function setIsCjsPromise(id, resolution) {
1064
1079
  const isCjsPromise = isCjsPromises.get(id);
1065
-
1066
1080
  if (isCjsPromise) {
1067
1081
  if (isCjsPromise.resolve) {
1068
1082
  isCjsPromise.resolve(resolution);
1069
1083
  isCjsPromise.resolve = undefined;
1070
1084
  }
1071
1085
  } else {
1072
- isCjsPromises.set(id, {
1073
- promise: Promise.resolve(resolution),
1074
- resolve: undefined
1075
- });
1086
+ isCjsPromises.set(id, { promise: Promise.resolve(resolution), resolve: undefined });
1087
+ }
1088
+ }
1089
+
1090
+ // e.g. id === "commonjsHelpers?commonjsRegister"
1091
+ function getSpecificHelperProxy(id) {
1092
+ return `export {${id.split('?')[1]} as default} from '${HELPERS_ID}';`;
1093
+ }
1094
+
1095
+ function getUnknownRequireProxy(id, requireReturnsDefault) {
1096
+ if (requireReturnsDefault === true || id.endsWith('.json')) {
1097
+ return `export {default} from ${JSON.stringify(id)};`;
1098
+ }
1099
+ const name = getName(id);
1100
+ const exported =
1101
+ requireReturnsDefault === 'auto'
1102
+ ? `import {getDefaultExportFromNamespaceIfNotNamed} from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfNotNamed(${name});`
1103
+ : requireReturnsDefault === 'preferred'
1104
+ ? `import {getDefaultExportFromNamespaceIfPresent} from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfPresent(${name});`
1105
+ : !requireReturnsDefault
1106
+ ? `import {getAugmentedNamespace} from "${HELPERS_ID}"; export default /*@__PURE__*/getAugmentedNamespace(${name});`
1107
+ : `export default ${name};`;
1108
+ return `import * as ${name} from ${JSON.stringify(id)}; ${exported}`;
1109
+ }
1110
+
1111
+ function getDynamicJsonProxy(id, commonDir) {
1112
+ const normalizedPath = normalizePathSlashes(id.slice(DYNAMIC_JSON_PREFIX.length));
1113
+ return `const commonjsRegister = require('${HELPERS_ID}?commonjsRegister');\ncommonjsRegister(${JSON.stringify(
1114
+ getVirtualPathForDynamicRequirePath(normalizedPath, commonDir)
1115
+ )}, function (module, exports) {
1116
+ module.exports = require(${JSON.stringify(normalizedPath)});
1117
+ });`;
1118
+ }
1119
+
1120
+ function getDynamicRequireProxy(normalizedPath, commonDir) {
1121
+ return `const commonjsRegister = require('${HELPERS_ID}?commonjsRegister');\ncommonjsRegister(${JSON.stringify(
1122
+ getVirtualPathForDynamicRequirePath(normalizedPath, commonDir)
1123
+ )}, function (module, exports) {
1124
+ ${fs.readFileSync(normalizedPath, { encoding: 'utf8' })}
1125
+ });`;
1126
+ }
1127
+
1128
+ async function getStaticRequireProxy(
1129
+ id,
1130
+ requireReturnsDefault,
1131
+ esModulesWithDefaultExport,
1132
+ esModulesWithNamedExports
1133
+ ) {
1134
+ const name = getName(id);
1135
+ const isCjs = await getIsCjsPromise(id);
1136
+ if (isCjs) {
1137
+ return `import { __moduleExports } from ${JSON.stringify(id)}; export default __moduleExports;`;
1138
+ } else if (isCjs === null) {
1139
+ return getUnknownRequireProxy(id, requireReturnsDefault);
1140
+ } else if (!requireReturnsDefault) {
1141
+ return `import {getAugmentedNamespace} from "${HELPERS_ID}"; import * as ${name} from ${JSON.stringify(
1142
+ id
1143
+ )}; export default /*@__PURE__*/getAugmentedNamespace(${name});`;
1144
+ } else if (
1145
+ requireReturnsDefault !== true &&
1146
+ (requireReturnsDefault === 'namespace' ||
1147
+ !esModulesWithDefaultExport.has(id) ||
1148
+ (requireReturnsDefault === 'auto' && esModulesWithNamedExports.has(id)))
1149
+ ) {
1150
+ return `import * as ${name} from ${JSON.stringify(id)}; export default ${name};`;
1076
1151
  }
1152
+ return `export {default} from ${JSON.stringify(id)};`;
1077
1153
  }
1078
1154
 
1079
1155
  /* eslint-disable no-param-reassign, no-undefined */
@@ -1083,22 +1159,24 @@ function getCandidatesForExtension(resolved, extension) {
1083
1159
  }
1084
1160
 
1085
1161
  function getCandidates(resolved, extensions) {
1086
- return extensions.reduce((paths, extension) => paths.concat(getCandidatesForExtension(resolved, extension)), [resolved]);
1162
+ return extensions.reduce(
1163
+ (paths, extension) => paths.concat(getCandidatesForExtension(resolved, extension)),
1164
+ [resolved]
1165
+ );
1087
1166
  }
1088
1167
 
1089
1168
  function getResolveId(extensions) {
1090
1169
  function resolveExtensions(importee, importer) {
1091
1170
  // not our problem
1092
1171
  if (importee[0] !== '.' || !importer) return undefined;
1172
+
1093
1173
  const resolved = path.resolve(path.dirname(importer), importee);
1094
1174
  const candidates = getCandidates(resolved, extensions);
1095
1175
 
1096
1176
  for (let i = 0; i < candidates.length; i += 1) {
1097
1177
  try {
1098
1178
  const stats = fs.statSync(candidates[i]);
1099
- if (stats.isFile()) return {
1100
- id: candidates[i]
1101
- };
1179
+ if (stats.isFile()) return { id: candidates[i] };
1102
1180
  } catch (err) {
1103
1181
  /* noop */
1104
1182
  }
@@ -1109,45 +1187,38 @@ function getResolveId(extensions) {
1109
1187
 
1110
1188
  function resolveId(importee, importer) {
1111
1189
  const isProxyModule = importee.endsWith(PROXY_SUFFIX);
1112
-
1113
1190
  if (isProxyModule) {
1114
1191
  importee = getIdFromProxyId(importee);
1115
- } else if (importee.startsWith('\0')) {
1116
- if (importee === HELPERS_ID || importee === DYNAMIC_PACKAGES_ID || importee.startsWith(DYNAMIC_JSON_PREFIX)) {
1192
+ }
1193
+ if (importee.startsWith('\0')) {
1194
+ if (
1195
+ importee.startsWith(HELPERS_ID) ||
1196
+ importee === DYNAMIC_PACKAGES_ID ||
1197
+ importee.startsWith(DYNAMIC_JSON_PREFIX)
1198
+ ) {
1117
1199
  return importee;
1118
1200
  }
1119
-
1120
- return null;
1121
- }
1122
-
1123
- if (importee.startsWith(DYNAMIC_JSON_PREFIX)) {
1124
- return importee;
1201
+ if (!isProxyModule) {
1202
+ return null;
1203
+ }
1125
1204
  }
1126
1205
 
1127
1206
  if (importer && importer.endsWith(PROXY_SUFFIX)) {
1128
1207
  importer = getIdFromProxyId(importer);
1129
1208
  }
1130
1209
 
1131
- return this.resolve(importee, importer, {
1132
- skipSelf: true
1133
- }).then(resolved => {
1210
+ return this.resolve(importee, importer, { skipSelf: true }).then((resolved) => {
1134
1211
  if (!resolved) {
1135
1212
  resolved = resolveExtensions(importee, importer);
1136
1213
  }
1137
-
1138
1214
  if (isProxyModule) {
1139
1215
  if (!resolved) {
1140
- return {
1141
- id: getExternalProxyId(importee),
1142
- external: false
1143
- };
1216
+ return { id: getExternalProxyId(importee), external: false };
1144
1217
  }
1145
-
1146
1218
  resolved.id = (resolved.external ? getExternalProxyId : getProxyId)(resolved.id);
1147
1219
  resolved.external = false;
1148
1220
  return resolved;
1149
1221
  }
1150
-
1151
1222
  return resolved;
1152
1223
  });
1153
1224
  }
@@ -1158,51 +1229,81 @@ function getResolveId(extensions) {
1158
1229
  function commonjs(options = {}) {
1159
1230
  const extensions = options.extensions || ['.js'];
1160
1231
  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
-
1232
+ const {
1233
+ ignoreGlobal,
1234
+ requireReturnsDefault: requireReturnsDefaultOption,
1235
+ esmExternals
1236
+ } = options;
1237
+ const getRequireReturnsDefault =
1238
+ typeof requireReturnsDefaultOption === 'function'
1239
+ ? requireReturnsDefaultOption
1240
+ : () => requireReturnsDefaultOption;
1241
+ let esmExternalIds;
1242
+ const isEsmExternal =
1243
+ typeof esmExternals === 'function'
1244
+ ? esmExternals
1245
+ : Array.isArray(esmExternals)
1246
+ ? ((esmExternalIds = new Set(esmExternals)), (id) => esmExternalIds.has(id))
1247
+ : () => esmExternals;
1248
+
1249
+ const { dynamicRequireModuleSet, dynamicRequireModuleDirPaths } = getDynamicRequirePaths(
1250
+ options.dynamicRequireTargets
1251
+ );
1167
1252
  const isDynamicRequireModulesEnabled = dynamicRequireModuleSet.size > 0;
1168
- const commonDir = isDynamicRequireModulesEnabled ? getCommonDir(null, Array.from(dynamicRequireModuleSet).concat(process.cwd())) : null;
1169
- const esModulesWithoutDefaultExport = new Set();
1170
- 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;
1253
+ const commonDir = isDynamicRequireModulesEnabled
1254
+ ? getCommonDir(null, Array.from(dynamicRequireModuleSet).concat(process.cwd()))
1255
+ : null;
1174
1256
 
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;
1257
+ const esModulesWithDefaultExport = new Set();
1258
+ const esModulesWithNamedExports = new Set();
1180
1259
 
1181
- const isDynamicRequireModule = dynamicRequireModuleSet.has(normalizePathSlashes(id));
1260
+ const ignoreRequire =
1261
+ typeof options.ignore === 'function'
1262
+ ? options.ignore
1263
+ : Array.isArray(options.ignore)
1264
+ ? (id) => options.ignore.includes(id)
1265
+ : () => false;
1182
1266
 
1183
- if (isEsModule && (!isDynamicRequireModule || !options.transformMixedEsModules)) {
1184
- (hasDefaultExport ? esModulesWithDefaultExport : esModulesWithoutDefaultExport).add(id);
1267
+ const resolveId = getResolveId(extensions);
1185
1268
 
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
- }
1269
+ const sourceMap = options.sourceMap !== false;
1196
1270
 
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));
1271
+ function transformAndCheckExports(code, id) {
1272
+ const { isEsModule, hasDefaultExport, hasNamedExports, ast } = checkEsModule(
1273
+ this.parse,
1274
+ code,
1275
+ id
1276
+ );
1277
+ if (hasDefaultExport) {
1278
+ esModulesWithDefaultExport.add(id);
1279
+ }
1280
+ if (hasNamedExports) {
1281
+ esModulesWithNamedExports.add(id);
1282
+ }
1200
1283
 
1201
- if (!transformed) {
1202
- if (!isEsModule || isDynamicRequireModule) esModulesWithoutDefaultExport.add(id);
1284
+ if (
1285
+ !dynamicRequireModuleSet.has(normalizePathSlashes(id)) &&
1286
+ (!hasCjsKeywords(code, ignoreGlobal) || (isEsModule && !options.transformMixedEsModules))
1287
+ ) {
1288
+ setIsCjsPromise(id, false);
1203
1289
  return null;
1204
1290
  }
1205
1291
 
1292
+ const transformed = transformCommonjs(
1293
+ this.parse,
1294
+ code,
1295
+ id,
1296
+ isEsModule,
1297
+ ignoreGlobal || isEsModule,
1298
+ ignoreRequire,
1299
+ sourceMap,
1300
+ isDynamicRequireModulesEnabled,
1301
+ dynamicRequireModuleSet,
1302
+ commonDir,
1303
+ ast
1304
+ );
1305
+
1306
+ setIsCjsPromise(id, isEsModule ? false : Boolean(transformed));
1206
1307
  return transformed;
1207
1308
  }
1208
1309
 
@@ -1211,23 +1312,18 @@ function commonjs(options = {}) {
1211
1312
 
1212
1313
  buildStart() {
1213
1314
  if (options.namedExports != null) {
1214
- this.warn('The namedExports option from "@rollup/plugin-commonjs" is deprecated. Named exports are now handled automatically.');
1315
+ this.warn(
1316
+ 'The namedExports option from "@rollup/plugin-commonjs" is deprecated. Named exports are now handled automatically.'
1317
+ );
1215
1318
  }
1216
1319
 
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
-
1320
+ const [major, minor] = this.meta.rollupVersion.split('.').map(Number);
1222
1321
  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}.`);
1322
+ const [minMajor, minMinor] = minVersion.split('.').map(Number);
1323
+ if (major < minMajor || (major === minMajor && minor < minMinor)) {
1324
+ this.error(
1325
+ `Insufficient Rollup version: "@rollup/plugin-commonjs" requires at least rollup@${minVersion} but found rollup@${this.meta.rollupVersion}.`
1326
+ );
1231
1327
  }
1232
1328
  },
1233
1329
 
@@ -1235,125 +1331,68 @@ function commonjs(options = {}) {
1235
1331
 
1236
1332
  load(id) {
1237
1333
  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
1334
+ return getHelpersModule(isDynamicRequireModulesEnabled);
1335
+ }
1243
1336
 
1337
+ if (id.startsWith(HELPERS_ID)) {
1338
+ return getSpecificHelperProxy(id);
1339
+ }
1244
1340
 
1245
1341
  if (id.endsWith(EXTERNAL_SUFFIX)) {
1246
1342
  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};`;
1343
+ return getUnknownRequireProxy(
1344
+ actualId,
1345
+ isEsmExternal(actualId) ? getRequireReturnsDefault(actualId) : true
1346
+ );
1251
1347
  }
1252
1348
 
1253
1349
  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;
1350
+ return getDynamicPackagesModule(dynamicRequireModuleDirPaths, commonDir);
1284
1351
  }
1285
1352
 
1286
- let actualId = id;
1287
- const isDynamicJson = actualId.startsWith(DYNAMIC_JSON_PREFIX);
1288
-
1289
- if (isDynamicJson) {
1290
- actualId = actualId.slice(DYNAMIC_JSON_PREFIX.length);
1291
- }
1292
-
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
- });`;
1353
+ if (id.startsWith(DYNAMIC_JSON_PREFIX)) {
1354
+ return getDynamicJsonProxy(id, commonDir);
1299
1355
  }
1300
1356
 
1357
+ const normalizedPath = normalizePathSlashes(id);
1301
1358
  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
- });`;
1359
+ return getDynamicRequireProxy(normalizedPath, commonDir);
1309
1360
  }
1310
1361
 
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
- });
1362
+ if (id.endsWith(PROXY_SUFFIX)) {
1363
+ const actualId = getIdFromProxyId(id);
1364
+ return getStaticRequireProxy(
1365
+ actualId,
1366
+ getRequireReturnsDefault(actualId),
1367
+ esModulesWithDefaultExport,
1368
+ esModulesWithNamedExports
1369
+ );
1320
1370
  }
1321
1371
 
1322
1372
  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;
1373
+ return getDynamicPackagesEntryIntro(
1374
+ id,
1375
+ dynamicRequireModuleDirPaths,
1376
+ dynamicRequireModuleSet
1377
+ );
1342
1378
  }
1343
1379
 
1344
1380
  return null;
1345
1381
  },
1346
1382
 
1347
1383
  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
- }
1384
+ const extName = path.extname(id);
1385
+ if (
1386
+ extName !== '.cjs' &&
1387
+ id !== DYNAMIC_PACKAGES_ID &&
1388
+ !id.startsWith(DYNAMIC_JSON_PREFIX) &&
1389
+ (!filter(id) || !extensions.includes(extName))
1390
+ ) {
1391
+ setIsCjsPromise(id, null);
1392
+ return null;
1353
1393
  }
1354
1394
 
1355
1395
  let transformed;
1356
-
1357
1396
  try {
1358
1397
  transformed = transformAndCheckExports.call(this, code, id);
1359
1398
  } catch (err) {
@@ -1364,7 +1403,6 @@ function commonjs(options = {}) {
1364
1403
 
1365
1404
  return transformed;
1366
1405
  }
1367
-
1368
1406
  };
1369
1407
  }
1370
1408