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