@rollup/plugin-commonjs 13.0.2 → 16.0.0

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