@rollup/plugin-commonjs 21.0.0 → 22.0.0-10

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.
@@ -2,13 +2,12 @@
2
2
 
3
3
  var path = require('path');
4
4
  var pluginutils = require('@rollup/pluginutils');
5
- var getCommonDir = require('commondir');
6
5
  var fs = require('fs');
6
+ var getCommonDir = require('commondir');
7
7
  var glob = require('glob');
8
8
  var estreeWalker = require('estree-walker');
9
9
  var MagicString = require('magic-string');
10
10
  var isReference = require('is-reference');
11
- var resolve = require('resolve');
12
11
 
13
12
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
14
13
 
@@ -17,8 +16,9 @@ var glob__default = /*#__PURE__*/_interopDefaultLegacy(glob);
17
16
  var MagicString__default = /*#__PURE__*/_interopDefaultLegacy(MagicString);
18
17
  var isReference__default = /*#__PURE__*/_interopDefaultLegacy(isReference);
19
18
 
19
+ var version = " 22.0.0-10";
20
20
  var peerDependencies = {
21
- rollup: "^2.38.3"
21
+ rollup: "^2.67.0"
22
22
  };
23
23
 
24
24
  function tryParse(parse, code, id) {
@@ -85,271 +85,6 @@ function analyzeTopLevelStatements(parse, code, id) {
85
85
  return { isEsModule, hasDefaultExport, hasNamedExports, ast };
86
86
  }
87
87
 
88
- const isWrappedId = (id, suffix) => id.endsWith(suffix);
89
- const wrapId = (id, suffix) => `\0${id}${suffix}`;
90
- const unwrapId = (wrappedId, suffix) => wrappedId.slice(1, -suffix.length);
91
-
92
- const PROXY_SUFFIX = '?commonjs-proxy';
93
- const REQUIRE_SUFFIX = '?commonjs-require';
94
- const EXTERNAL_SUFFIX = '?commonjs-external';
95
- const EXPORTS_SUFFIX = '?commonjs-exports';
96
- const MODULE_SUFFIX = '?commonjs-module';
97
-
98
- const DYNAMIC_REGISTER_SUFFIX = '?commonjs-dynamic-register';
99
- const DYNAMIC_JSON_PREFIX = '\0commonjs-dynamic-json:';
100
- const DYNAMIC_PACKAGES_ID = '\0commonjs-dynamic-packages';
101
-
102
- const HELPERS_ID = '\0commonjsHelpers.js';
103
-
104
- // `x['default']` is used instead of `x.default` for backward compatibility with ES3 browsers.
105
- // Minifiers like uglify will usually transpile it back if compatibility with ES3 is not enabled.
106
- // This will no longer be necessary once Rollup switches to ES6 output, likely
107
- // in Rollup 3
108
-
109
- const HELPERS = `
110
- export var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
111
-
112
- export function getDefaultExportFromCjs (x) {
113
- return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
114
- }
115
-
116
- export function getDefaultExportFromNamespaceIfPresent (n) {
117
- return n && Object.prototype.hasOwnProperty.call(n, 'default') ? n['default'] : n;
118
- }
119
-
120
- export function getDefaultExportFromNamespaceIfNotNamed (n) {
121
- return n && Object.prototype.hasOwnProperty.call(n, 'default') && Object.keys(n).length === 1 ? n['default'] : n;
122
- }
123
-
124
- export function getAugmentedNamespace(n) {
125
- if (n.__esModule) return n;
126
- var a = Object.defineProperty({}, '__esModule', {value: true});
127
- Object.keys(n).forEach(function (k) {
128
- var d = Object.getOwnPropertyDescriptor(n, k);
129
- Object.defineProperty(a, k, d.get ? d : {
130
- enumerable: true,
131
- get: function () {
132
- return n[k];
133
- }
134
- });
135
- });
136
- return a;
137
- }
138
- `;
139
-
140
- const FAILED_REQUIRE_ERROR = `throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');`;
141
-
142
- const HELPER_NON_DYNAMIC = `
143
- export function commonjsRequire (path) {
144
- ${FAILED_REQUIRE_ERROR}
145
- }
146
- `;
147
-
148
- const getDynamicHelpers = (ignoreDynamicRequires) => `
149
- export function createModule(modulePath) {
150
- return {
151
- path: modulePath,
152
- exports: {},
153
- require: function (path, base) {
154
- return commonjsRequire(path, base == null ? modulePath : base);
155
- }
156
- };
157
- }
158
-
159
- export function commonjsRegister (path, loader) {
160
- DYNAMIC_REQUIRE_LOADERS[path] = loader;
161
- }
162
-
163
- export function commonjsRegisterOrShort (path, to) {
164
- const resolvedPath = commonjsResolveImpl(path, null, true);
165
- if (resolvedPath !== null && DYNAMIC_REQUIRE_CACHE[resolvedPath]) {
166
- DYNAMIC_REQUIRE_CACHE[path] = DYNAMIC_REQUIRE_CACHE[resolvedPath];
167
- } else {
168
- DYNAMIC_REQUIRE_SHORTS[path] = to;
169
- }
170
- }
171
-
172
- const DYNAMIC_REQUIRE_LOADERS = Object.create(null);
173
- const DYNAMIC_REQUIRE_CACHE = Object.create(null);
174
- const DYNAMIC_REQUIRE_SHORTS = Object.create(null);
175
- const DEFAULT_PARENT_MODULE = {
176
- id: '<' + 'rollup>', exports: {}, parent: undefined, filename: null, loaded: false, children: [], paths: []
177
- };
178
- const CHECKED_EXTENSIONS = ['', '.js', '.json'];
179
-
180
- function normalize (path) {
181
- path = path.replace(/\\\\/g, '/');
182
- const parts = path.split('/');
183
- const slashed = parts[0] === '';
184
- for (let i = 1; i < parts.length; i++) {
185
- if (parts[i] === '.' || parts[i] === '') {
186
- parts.splice(i--, 1);
187
- }
188
- }
189
- for (let i = 1; i < parts.length; i++) {
190
- if (parts[i] !== '..') continue;
191
- if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {
192
- parts.splice(--i, 2);
193
- i--;
194
- }
195
- }
196
- path = parts.join('/');
197
- if (slashed && path[0] !== '/')
198
- path = '/' + path;
199
- else if (path.length === 0)
200
- path = '.';
201
- return path;
202
- }
203
-
204
- function join () {
205
- if (arguments.length === 0)
206
- return '.';
207
- let joined;
208
- for (let i = 0; i < arguments.length; ++i) {
209
- let arg = arguments[i];
210
- if (arg.length > 0) {
211
- if (joined === undefined)
212
- joined = arg;
213
- else
214
- joined += '/' + arg;
215
- }
216
- }
217
- if (joined === undefined)
218
- return '.';
219
-
220
- return joined;
221
- }
222
-
223
- function isPossibleNodeModulesPath (modulePath) {
224
- let c0 = modulePath[0];
225
- if (c0 === '/' || c0 === '\\\\') return false;
226
- let c1 = modulePath[1], c2 = modulePath[2];
227
- if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||
228
- (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;
229
- if (c1 === ':' && (c2 === '/' || c2 === '\\\\'))
230
- return false;
231
- return true;
232
- }
233
-
234
- function dirname (path) {
235
- if (path.length === 0)
236
- return '.';
237
-
238
- let i = path.length - 1;
239
- while (i > 0) {
240
- const c = path.charCodeAt(i);
241
- if ((c === 47 || c === 92) && i !== path.length - 1)
242
- break;
243
- i--;
244
- }
245
-
246
- if (i > 0)
247
- return path.substr(0, i);
248
-
249
- if (path.chartCodeAt(0) === 47 || path.chartCodeAt(0) === 92)
250
- return path.charAt(0);
251
-
252
- return '.';
253
- }
254
-
255
- export function commonjsResolveImpl (path, originalModuleDir, testCache) {
256
- const shouldTryNodeModules = isPossibleNodeModulesPath(path);
257
- path = normalize(path);
258
- let relPath;
259
- if (path[0] === '/') {
260
- originalModuleDir = '/';
261
- }
262
- while (true) {
263
- if (!shouldTryNodeModules) {
264
- relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path;
265
- } else if (originalModuleDir) {
266
- relPath = normalize(originalModuleDir + '/node_modules/' + path);
267
- } else {
268
- relPath = normalize(join('node_modules', path));
269
- }
270
-
271
- if (relPath.endsWith('/..')) {
272
- break; // Travelled too far up, avoid infinite loop
273
- }
274
-
275
- for (let extensionIndex = 0; extensionIndex < CHECKED_EXTENSIONS.length; extensionIndex++) {
276
- const resolvedPath = relPath + CHECKED_EXTENSIONS[extensionIndex];
277
- if (DYNAMIC_REQUIRE_CACHE[resolvedPath]) {
278
- return resolvedPath;
279
- }
280
- if (DYNAMIC_REQUIRE_SHORTS[resolvedPath]) {
281
- return resolvedPath;
282
- }
283
- if (DYNAMIC_REQUIRE_LOADERS[resolvedPath]) {
284
- return resolvedPath;
285
- }
286
- }
287
- if (!shouldTryNodeModules) break;
288
- const nextDir = normalize(originalModuleDir + '/..');
289
- if (nextDir === originalModuleDir) break;
290
- originalModuleDir = nextDir;
291
- }
292
- return null;
293
- }
294
-
295
- export function commonjsResolve (path, originalModuleDir) {
296
- const resolvedPath = commonjsResolveImpl(path, originalModuleDir);
297
- if (resolvedPath !== null) {
298
- return resolvedPath;
299
- }
300
- return require.resolve(path);
301
- }
302
-
303
- export function commonjsRequire (path, originalModuleDir) {
304
- let resolvedPath = commonjsResolveImpl(path, originalModuleDir, true);
305
- if (resolvedPath !== null) {
306
- let cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath];
307
- if (cachedModule) return cachedModule.exports;
308
- let shortTo = DYNAMIC_REQUIRE_SHORTS[resolvedPath];
309
- if (shortTo) {
310
- cachedModule = DYNAMIC_REQUIRE_CACHE[shortTo];
311
- if (cachedModule)
312
- return cachedModule.exports;
313
- resolvedPath = commonjsResolveImpl(shortTo, null, true);
314
- }
315
- const loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath];
316
- if (loader) {
317
- DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = {
318
- id: resolvedPath,
319
- filename: resolvedPath,
320
- path: dirname(resolvedPath),
321
- exports: {},
322
- parent: DEFAULT_PARENT_MODULE,
323
- loaded: false,
324
- children: [],
325
- paths: [],
326
- require: function (path, base) {
327
- return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base);
328
- }
329
- };
330
- try {
331
- loader.call(commonjsGlobal, cachedModule, cachedModule.exports);
332
- } catch (error) {
333
- delete DYNAMIC_REQUIRE_CACHE[resolvedPath];
334
- throw error;
335
- }
336
- cachedModule.loaded = true;
337
- return cachedModule.exports;
338
- };
339
- }
340
- ${ignoreDynamicRequires ? 'return require(path);' : FAILED_REQUIRE_ERROR}
341
- }
342
-
343
- commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE;
344
- commonjsRequire.resolve = commonjsResolve;
345
- `;
346
-
347
- function getHelpersModule(isDynamicRequireModulesEnabled, ignoreDynamicRequires) {
348
- return `${HELPERS}${
349
- isDynamicRequireModulesEnabled ? getDynamicHelpers(ignoreDynamicRequires) : HELPER_NON_DYNAMIC
350
- }`;
351
- }
352
-
353
88
  /* eslint-disable import/prefer-default-export */
354
89
 
355
90
  function deconflict(scopes, globals, identifier) {
@@ -382,13 +117,35 @@ function normalizePathSlashes(path) {
382
117
  return path.replace(/\\/g, '/');
383
118
  }
384
119
 
385
- const VIRTUAL_PATH_BASE = '/$$rollup_base$$';
386
- const getVirtualPathForDynamicRequirePath = (path, commonDir) => {
387
- const normalizedPath = normalizePathSlashes(path);
388
- return normalizedPath.startsWith(commonDir)
389
- ? VIRTUAL_PATH_BASE + normalizedPath.slice(commonDir.length)
390
- : normalizedPath;
391
- };
120
+ const getVirtualPathForDynamicRequirePath = (path$1, commonDir) =>
121
+ `/${normalizePathSlashes(path.relative(commonDir, path$1))}`;
122
+
123
+ function capitalize(name) {
124
+ return name[0].toUpperCase() + name.slice(1);
125
+ }
126
+
127
+ function getStrictRequiresFilter({ strictRequires }) {
128
+ switch (strictRequires) {
129
+ case true:
130
+ return { strictRequiresFilter: () => true, detectCyclesAndConditional: false };
131
+ // eslint-disable-next-line no-undefined
132
+ case undefined:
133
+ case 'auto':
134
+ case 'debug':
135
+ case null:
136
+ return { strictRequiresFilter: () => false, detectCyclesAndConditional: true };
137
+ case false:
138
+ return { strictRequiresFilter: () => false, detectCyclesAndConditional: false };
139
+ default:
140
+ if (typeof strictRequires === 'string' || Array.isArray(strictRequires)) {
141
+ return {
142
+ strictRequiresFilter: pluginutils.createFilter(strictRequires),
143
+ detectCyclesAndConditional: false
144
+ };
145
+ }
146
+ throw new Error('Unexpected value for "strictRequires" option.');
147
+ }
148
+ }
392
149
 
393
150
  function getPackageEntryPoint(dirPath) {
394
151
  let entryPoint = 'index.js';
@@ -406,41 +163,6 @@ function getPackageEntryPoint(dirPath) {
406
163
  return entryPoint;
407
164
  }
408
165
 
409
- function getDynamicPackagesModule(dynamicRequireModuleDirPaths, commonDir) {
410
- let code = `const commonjsRegisterOrShort = require('${HELPERS_ID}?commonjsRegisterOrShort');`;
411
- for (const dir of dynamicRequireModuleDirPaths) {
412
- const entryPoint = getPackageEntryPoint(dir);
413
-
414
- code += `\ncommonjsRegisterOrShort(${JSON.stringify(
415
- getVirtualPathForDynamicRequirePath(dir, commonDir)
416
- )}, ${JSON.stringify(getVirtualPathForDynamicRequirePath(path.join(dir, entryPoint), commonDir))});`;
417
- }
418
- return code;
419
- }
420
-
421
- function getDynamicPackagesEntryIntro(
422
- dynamicRequireModuleDirPaths,
423
- dynamicRequireModuleSet
424
- ) {
425
- let dynamicImports = Array.from(
426
- dynamicRequireModuleSet,
427
- (dynamicId) => `require(${JSON.stringify(wrapId(dynamicId, DYNAMIC_REGISTER_SUFFIX))});`
428
- ).join('\n');
429
-
430
- if (dynamicRequireModuleDirPaths.length) {
431
- dynamicImports += `require(${JSON.stringify(
432
- wrapId(DYNAMIC_PACKAGES_ID, DYNAMIC_REGISTER_SUFFIX)
433
- )});`;
434
- }
435
-
436
- return dynamicImports;
437
- }
438
-
439
- function isDynamicModuleImport(id, dynamicRequireModuleSet) {
440
- const normalizedPath = normalizePathSlashes(id);
441
- return dynamicRequireModuleSet.has(normalizedPath) && !normalizedPath.endsWith('.json');
442
- }
443
-
444
166
  function isDirectory(path) {
445
167
  try {
446
168
  if (fs.statSync(path).isDirectory()) return true;
@@ -450,103 +172,249 @@ function isDirectory(path) {
450
172
  return false;
451
173
  }
452
174
 
453
- function getDynamicRequirePaths(patterns) {
454
- const dynamicRequireModuleSet = new Set();
175
+ function getDynamicRequireModules(patterns, dynamicRequireRoot) {
176
+ const dynamicRequireModules = new Map();
177
+ const dirNames = new Set();
455
178
  for (const pattern of !patterns || Array.isArray(patterns) ? patterns || [] : [patterns]) {
456
179
  const isNegated = pattern.startsWith('!');
457
- const modifySet = Set.prototype[isNegated ? 'delete' : 'add'].bind(dynamicRequireModuleSet);
458
- for (const path$1 of glob__default['default'].sync(isNegated ? pattern.substr(1) : pattern)) {
459
- modifySet(normalizePathSlashes(path.resolve(path$1)));
460
- if (isDirectory(path$1)) {
461
- modifySet(normalizePathSlashes(path.resolve(path.join(path$1, getPackageEntryPoint(path$1)))));
180
+ const modifyMap = (targetPath, resolvedPath) =>
181
+ isNegated
182
+ ? dynamicRequireModules.delete(targetPath)
183
+ : dynamicRequireModules.set(targetPath, resolvedPath);
184
+ for (const path$1 of glob__default["default"].sync(isNegated ? pattern.substr(1) : pattern)) {
185
+ const resolvedPath = path.resolve(path$1);
186
+ const requirePath = normalizePathSlashes(resolvedPath);
187
+ if (isDirectory(resolvedPath)) {
188
+ dirNames.add(resolvedPath);
189
+ const modulePath = path.resolve(path.join(resolvedPath, getPackageEntryPoint(path$1)));
190
+ modifyMap(requirePath, modulePath);
191
+ modifyMap(normalizePathSlashes(modulePath), modulePath);
192
+ } else {
193
+ dirNames.add(path.dirname(resolvedPath));
194
+ modifyMap(requirePath, resolvedPath);
462
195
  }
463
196
  }
464
197
  }
465
- const dynamicRequireModuleDirPaths = Array.from(dynamicRequireModuleSet.values()).filter((path) =>
466
- isDirectory(path)
467
- );
468
- return { dynamicRequireModuleSet, dynamicRequireModuleDirPaths };
198
+ return {
199
+ commonDir: dirNames.size ? getCommonDir__default["default"]([...dirNames, dynamicRequireRoot]) : null,
200
+ dynamicRequireModules
201
+ };
469
202
  }
470
203
 
471
- function getCommonJSMetaPromise(commonJSMetaPromises, id) {
472
- let commonJSMetaPromise = commonJSMetaPromises.get(id);
473
- if (commonJSMetaPromise) return commonJSMetaPromise.promise;
204
+ const FAILED_REQUIRE_ERROR = `throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');`;
474
205
 
475
- const promise = new Promise((resolve) => {
476
- commonJSMetaPromise = {
477
- resolve,
478
- promise: null
479
- };
480
- commonJSMetaPromises.set(id, commonJSMetaPromise);
481
- });
482
- commonJSMetaPromise.promise = promise;
206
+ const COMMONJS_REQUIRE_EXPORT = 'commonjsRequire';
207
+ const CREATE_COMMONJS_REQUIRE_EXPORT = 'createCommonjsRequire';
483
208
 
484
- return promise;
209
+ function getDynamicModuleRegistry(
210
+ isDynamicRequireModulesEnabled,
211
+ dynamicRequireModules,
212
+ commonDir,
213
+ ignoreDynamicRequires
214
+ ) {
215
+ if (!isDynamicRequireModulesEnabled) {
216
+ return `export function ${COMMONJS_REQUIRE_EXPORT}(path) {
217
+ ${FAILED_REQUIRE_ERROR}
218
+ }`;
219
+ }
220
+ const dynamicModuleImports = [...dynamicRequireModules.values()]
221
+ .map(
222
+ (id, index) =>
223
+ `import ${
224
+ id.endsWith('.json') ? `json${index}` : `{ __require as require${index} }`
225
+ } from ${JSON.stringify(id)};`
226
+ )
227
+ .join('\n');
228
+ const dynamicModuleProps = [...dynamicRequireModules.keys()]
229
+ .map(
230
+ (id, index) =>
231
+ `\t\t${JSON.stringify(getVirtualPathForDynamicRequirePath(id, commonDir))}: ${
232
+ id.endsWith('.json') ? `function () { return json${index}; }` : `require${index}`
233
+ }`
234
+ )
235
+ .join(',\n');
236
+ return `${dynamicModuleImports}
237
+
238
+ var dynamicModules;
239
+
240
+ function getDynamicModules() {
241
+ return dynamicModules || (dynamicModules = {
242
+ ${dynamicModuleProps}
243
+ });
485
244
  }
486
245
 
487
- function setCommonJSMetaPromise(commonJSMetaPromises, id, commonjsMeta) {
488
- const commonJSMetaPromise = commonJSMetaPromises.get(id);
489
- if (commonJSMetaPromise) {
490
- if (commonJSMetaPromise.resolve) {
491
- commonJSMetaPromise.resolve(commonjsMeta);
492
- commonJSMetaPromise.resolve = null;
493
- }
494
- } else {
495
- commonJSMetaPromises.set(id, { promise: Promise.resolve(commonjsMeta), resolve: null });
496
- }
246
+ export function ${CREATE_COMMONJS_REQUIRE_EXPORT}(originalModuleDir) {
247
+ function handleRequire(path) {
248
+ var resolvedPath = commonjsResolve(path, originalModuleDir);
249
+ if (resolvedPath !== null) {
250
+ return getDynamicModules()[resolvedPath]();
251
+ }
252
+ ${ignoreDynamicRequires ? 'return require(path);' : FAILED_REQUIRE_ERROR}
253
+ }
254
+ handleRequire.resolve = function (path) {
255
+ var resolvedPath = commonjsResolve(path, originalModuleDir);
256
+ if (resolvedPath !== null) {
257
+ return resolvedPath;
258
+ }
259
+ return require.resolve(path);
260
+ }
261
+ return handleRequire;
262
+ }
263
+
264
+ function commonjsResolve (path, originalModuleDir) {
265
+ var shouldTryNodeModules = isPossibleNodeModulesPath(path);
266
+ path = normalize(path);
267
+ var relPath;
268
+ if (path[0] === '/') {
269
+ originalModuleDir = '';
270
+ }
271
+ var modules = getDynamicModules();
272
+ var checkedExtensions = ['', '.js', '.json'];
273
+ while (true) {
274
+ if (!shouldTryNodeModules) {
275
+ relPath = normalize(originalModuleDir + '/' + path);
276
+ } else {
277
+ relPath = normalize(originalModuleDir + '/node_modules/' + path);
278
+ }
279
+
280
+ if (relPath.endsWith('/..')) {
281
+ break; // Travelled too far up, avoid infinite loop
282
+ }
283
+
284
+ for (var extensionIndex = 0; extensionIndex < checkedExtensions.length; extensionIndex++) {
285
+ var resolvedPath = relPath + checkedExtensions[extensionIndex];
286
+ if (modules[resolvedPath]) {
287
+ return resolvedPath;
288
+ }
289
+ }
290
+ if (!shouldTryNodeModules) break;
291
+ var nextDir = normalize(originalModuleDir + '/..');
292
+ if (nextDir === originalModuleDir) break;
293
+ originalModuleDir = nextDir;
294
+ }
295
+ return null;
296
+ }
297
+
298
+ function isPossibleNodeModulesPath (modulePath) {
299
+ var c0 = modulePath[0];
300
+ if (c0 === '/' || c0 === '\\\\') return false;
301
+ var c1 = modulePath[1], c2 = modulePath[2];
302
+ if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||
303
+ (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;
304
+ if (c1 === ':' && (c2 === '/' || c2 === '\\\\')) return false;
305
+ return true;
306
+ }
307
+
308
+ function normalize (path) {
309
+ path = path.replace(/\\\\/g, '/');
310
+ var parts = path.split('/');
311
+ var slashed = parts[0] === '';
312
+ for (var i = 1; i < parts.length; i++) {
313
+ if (parts[i] === '.' || parts[i] === '') {
314
+ parts.splice(i--, 1);
315
+ }
316
+ }
317
+ for (var i = 1; i < parts.length; i++) {
318
+ if (parts[i] !== '..') continue;
319
+ if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {
320
+ parts.splice(--i, 2);
321
+ i--;
322
+ }
323
+ }
324
+ path = parts.join('/');
325
+ if (slashed && path[0] !== '/') path = '/' + path;
326
+ else if (path.length === 0) path = '.';
327
+ return path;
328
+ }`;
329
+ }
330
+
331
+ const isWrappedId = (id, suffix) => id.endsWith(suffix);
332
+ const wrapId = (id, suffix) => `\0${id}${suffix}`;
333
+ const unwrapId = (wrappedId, suffix) => wrappedId.slice(1, -suffix.length);
334
+
335
+ const PROXY_SUFFIX = '?commonjs-proxy';
336
+ const WRAPPED_SUFFIX = '?commonjs-wrapped';
337
+ const EXTERNAL_SUFFIX = '?commonjs-external';
338
+ const EXPORTS_SUFFIX = '?commonjs-exports';
339
+ const MODULE_SUFFIX = '?commonjs-module';
340
+ const ENTRY_SUFFIX = '?commonjs-entry';
341
+ const ES_IMPORT_SUFFIX = '?commonjs-es-import';
342
+
343
+ const DYNAMIC_MODULES_ID = '\0commonjs-dynamic-modules';
344
+ const HELPERS_ID = '\0commonjsHelpers.js';
345
+
346
+ const IS_WRAPPED_COMMONJS = 'withRequireFunction';
347
+
348
+ // `x['default']` is used instead of `x.default` for backward compatibility with ES3 browsers.
349
+ // Minifiers like uglify will usually transpile it back if compatibility with ES3 is not enabled.
350
+ // This could be improved by inspecting Rollup's "generatedCode" option
351
+
352
+ const HELPERS = `
353
+ export var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
354
+
355
+ export function getDefaultExportFromCjs (x) {
356
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
357
+ }
358
+
359
+ export function getDefaultExportFromNamespaceIfPresent (n) {
360
+ return n && Object.prototype.hasOwnProperty.call(n, 'default') ? n['default'] : n;
361
+ }
362
+
363
+ export function getDefaultExportFromNamespaceIfNotNamed (n) {
364
+ return n && Object.prototype.hasOwnProperty.call(n, 'default') && Object.keys(n).length === 1 ? n['default'] : n;
365
+ }
366
+
367
+ export function getAugmentedNamespace(n) {
368
+ var f = n.default;
369
+ if (typeof f == "function") {
370
+ var a = function () {
371
+ return f.apply(this, arguments);
372
+ };
373
+ a.prototype = f.prototype;
374
+ } else a = {};
375
+ Object.defineProperty(a, '__esModule', {value: true});
376
+ Object.keys(n).forEach(function (k) {
377
+ var d = Object.getOwnPropertyDescriptor(n, k);
378
+ Object.defineProperty(a, k, d.get ? d : {
379
+ enumerable: true,
380
+ get: function () {
381
+ return n[k];
382
+ }
383
+ });
384
+ });
385
+ return a;
497
386
  }
387
+ `;
498
388
 
499
- // e.g. id === "commonjsHelpers?commonjsRegister"
500
- function getSpecificHelperProxy(id) {
501
- return `export {${id.split('?')[1]} as default} from "${HELPERS_ID}";`;
389
+ function getHelpersModule() {
390
+ return HELPERS;
502
391
  }
503
392
 
504
393
  function getUnknownRequireProxy(id, requireReturnsDefault) {
505
394
  if (requireReturnsDefault === true || id.endsWith('.json')) {
506
- return `export {default} from ${JSON.stringify(id)};`;
395
+ return `export { default } from ${JSON.stringify(id)};`;
507
396
  }
508
397
  const name = getName(id);
509
398
  const exported =
510
399
  requireReturnsDefault === 'auto'
511
- ? `import {getDefaultExportFromNamespaceIfNotNamed} from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfNotNamed(${name});`
400
+ ? `import { getDefaultExportFromNamespaceIfNotNamed } from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfNotNamed(${name});`
512
401
  : requireReturnsDefault === 'preferred'
513
- ? `import {getDefaultExportFromNamespaceIfPresent} from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfPresent(${name});`
402
+ ? `import { getDefaultExportFromNamespaceIfPresent } from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfPresent(${name});`
514
403
  : !requireReturnsDefault
515
- ? `import {getAugmentedNamespace} from "${HELPERS_ID}"; export default /*@__PURE__*/getAugmentedNamespace(${name});`
404
+ ? `import { getAugmentedNamespace } from "${HELPERS_ID}"; export default /*@__PURE__*/getAugmentedNamespace(${name});`
516
405
  : `export default ${name};`;
517
406
  return `import * as ${name} from ${JSON.stringify(id)}; ${exported}`;
518
407
  }
519
408
 
520
- function getDynamicJsonProxy(id, commonDir) {
521
- const normalizedPath = normalizePathSlashes(id.slice(DYNAMIC_JSON_PREFIX.length));
522
- return `const commonjsRegister = require('${HELPERS_ID}?commonjsRegister');\ncommonjsRegister(${JSON.stringify(
523
- getVirtualPathForDynamicRequirePath(normalizedPath, commonDir)
524
- )}, function (module, exports) {
525
- module.exports = require(${JSON.stringify(normalizedPath)});
526
- });`;
527
- }
528
-
529
- function getDynamicRequireProxy(normalizedPath, commonDir) {
530
- return `const commonjsRegister = require('${HELPERS_ID}?commonjsRegister');\ncommonjsRegister(${JSON.stringify(
531
- getVirtualPathForDynamicRequirePath(normalizedPath, commonDir)
532
- )}, function (module, exports) {
533
- ${fs.readFileSync(normalizedPath, { encoding: 'utf8' })}
534
- });`;
535
- }
536
-
537
- async function getStaticRequireProxy(
538
- id,
539
- requireReturnsDefault,
540
- esModulesWithDefaultExport,
541
- esModulesWithNamedExports,
542
- commonJsMetaPromises
543
- ) {
409
+ async function getStaticRequireProxy(id, requireReturnsDefault, loadModule) {
544
410
  const name = getName(id);
545
- const commonjsMeta = await getCommonJSMetaPromise(commonJsMetaPromises, id);
546
- if (commonjsMeta && commonjsMeta.isCommonJS) {
547
- return `export { __moduleExports as default } from ${JSON.stringify(id)};`;
548
- } else if (commonjsMeta === null) {
411
+ const {
412
+ meta: { commonjs: commonjsMeta }
413
+ } = await loadModule({ id });
414
+ if (!commonjsMeta) {
549
415
  return getUnknownRequireProxy(id, requireReturnsDefault);
416
+ } else if (commonjsMeta.isCommonJS) {
417
+ return `export { __moduleExports as default } from ${JSON.stringify(id)};`;
550
418
  } else if (!requireReturnsDefault) {
551
419
  return `import { getAugmentedNamespace } from "${HELPERS_ID}"; import * as ${name} from ${JSON.stringify(
552
420
  id
@@ -554,14 +422,51 @@ async function getStaticRequireProxy(
554
422
  } else if (
555
423
  requireReturnsDefault !== true &&
556
424
  (requireReturnsDefault === 'namespace' ||
557
- !esModulesWithDefaultExport.has(id) ||
558
- (requireReturnsDefault === 'auto' && esModulesWithNamedExports.has(id)))
425
+ !commonjsMeta.hasDefaultExport ||
426
+ (requireReturnsDefault === 'auto' && commonjsMeta.hasNamedExports))
559
427
  ) {
560
428
  return `import * as ${name} from ${JSON.stringify(id)}; export default ${name};`;
561
429
  }
562
430
  return `export { default } from ${JSON.stringify(id)};`;
563
431
  }
564
432
 
433
+ function getEntryProxy(id, defaultIsModuleExports, getModuleInfo) {
434
+ const {
435
+ meta: { commonjs: commonjsMeta },
436
+ hasDefaultExport
437
+ } = getModuleInfo(id);
438
+ if (!commonjsMeta || commonjsMeta.isCommonJS !== IS_WRAPPED_COMMONJS) {
439
+ const stringifiedId = JSON.stringify(id);
440
+ let code = `export * from ${stringifiedId};`;
441
+ if (hasDefaultExport) {
442
+ code += `export { default } from ${stringifiedId};`;
443
+ }
444
+ return code;
445
+ }
446
+ return getEsImportProxy(id, defaultIsModuleExports);
447
+ }
448
+
449
+ function getEsImportProxy(id, defaultIsModuleExports) {
450
+ const name = getName(id);
451
+ const exportsName = `${name}Exports`;
452
+ const requireModule = `require${capitalize(name)}`;
453
+ let code =
454
+ `import { getDefaultExportFromCjs } from "${HELPERS_ID}";\n` +
455
+ `import { __require as ${requireModule} } from ${JSON.stringify(id)};\n` +
456
+ `var ${exportsName} = ${requireModule}();\n` +
457
+ `export { ${exportsName} as __moduleExports };`;
458
+ if (defaultIsModuleExports) {
459
+ code += `\nexport { ${exportsName} as default };`;
460
+ } else {
461
+ code += `export default /*@__PURE__*/getDefaultExportFromCjs(${exportsName});`;
462
+ }
463
+ return {
464
+ code,
465
+ syntheticNamedExports: '__moduleExports',
466
+ meta: { commonjs: { isCommonJS: false } }
467
+ };
468
+ }
469
+
565
470
  /* eslint-disable no-param-reassign, no-undefined */
566
471
 
567
472
  function getCandidatesForExtension(resolved, extension) {
@@ -575,106 +480,280 @@ function getCandidates(resolved, extensions) {
575
480
  );
576
481
  }
577
482
 
483
+ function resolveExtensions(importee, importer, extensions) {
484
+ // not our problem
485
+ if (importee[0] !== '.' || !importer) return undefined;
486
+
487
+ const resolved = path.resolve(path.dirname(importer), importee);
488
+ const candidates = getCandidates(resolved, extensions);
489
+
490
+ for (let i = 0; i < candidates.length; i += 1) {
491
+ try {
492
+ const stats = fs.statSync(candidates[i]);
493
+ if (stats.isFile()) return { id: candidates[i] };
494
+ } catch (err) {
495
+ /* noop */
496
+ }
497
+ }
498
+
499
+ return undefined;
500
+ }
501
+
578
502
  function getResolveId(extensions) {
579
- function resolveExtensions(importee, importer) {
580
- // not our problem
581
- if (importee[0] !== '.' || !importer) return undefined;
503
+ return async function resolveId(importee, importer, resolveOptions) {
504
+ // We assume that all requires are pre-resolved
505
+ const customOptions = resolveOptions.custom;
506
+ if (customOptions && customOptions['node-resolve'] && customOptions['node-resolve'].isRequire) {
507
+ return null;
508
+ }
509
+ if (isWrappedId(importee, WRAPPED_SUFFIX)) {
510
+ return unwrapId(importee, WRAPPED_SUFFIX);
511
+ }
582
512
 
583
- const resolved = path.resolve(path.dirname(importer), importee);
584
- const candidates = getCandidates(resolved, extensions);
513
+ if (
514
+ importee.endsWith(ENTRY_SUFFIX) ||
515
+ isWrappedId(importee, MODULE_SUFFIX) ||
516
+ isWrappedId(importee, EXPORTS_SUFFIX) ||
517
+ isWrappedId(importee, PROXY_SUFFIX) ||
518
+ isWrappedId(importee, ES_IMPORT_SUFFIX) ||
519
+ isWrappedId(importee, EXTERNAL_SUFFIX) ||
520
+ importee.startsWith(HELPERS_ID) ||
521
+ importee === DYNAMIC_MODULES_ID
522
+ ) {
523
+ return importee;
524
+ }
585
525
 
586
- for (let i = 0; i < candidates.length; i += 1) {
587
- try {
588
- const stats = fs.statSync(candidates[i]);
589
- if (stats.isFile()) return { id: candidates[i] };
590
- } catch (err) {
591
- /* noop */
526
+ if (importer) {
527
+ if (
528
+ importer === DYNAMIC_MODULES_ID ||
529
+ // Proxies are only importing resolved ids, no need to resolve again
530
+ isWrappedId(importer, PROXY_SUFFIX) ||
531
+ isWrappedId(importer, ES_IMPORT_SUFFIX) ||
532
+ importer.endsWith(ENTRY_SUFFIX)
533
+ ) {
534
+ return importee;
535
+ }
536
+ if (isWrappedId(importer, EXTERNAL_SUFFIX)) {
537
+ // We need to return null for unresolved imports so that the proper warning is shown
538
+ if (!(await this.resolve(importee, importer, { skipSelf: true }))) {
539
+ return null;
540
+ }
541
+ // For other external imports, we need to make sure they are handled as external
542
+ return { id: importee, external: true };
592
543
  }
593
544
  }
594
-
595
- return undefined;
596
- }
597
-
598
- return function resolveId(importee, rawImporter) {
599
- if (isWrappedId(importee, MODULE_SUFFIX) || isWrappedId(importee, EXPORTS_SUFFIX)) {
600
- return importee;
545
+
546
+ if (importee.startsWith('\0')) {
547
+ return null;
548
+ }
549
+
550
+ // If this is an entry point or ESM import, we need to figure out if the importee is wrapped and
551
+ // if that is the case, we need to add a proxy.
552
+ const resolved =
553
+ (await this.resolve(importee, importer, Object.assign({ skipSelf: true }, resolveOptions))) ||
554
+ resolveExtensions(importee, importer, extensions);
555
+ // Make sure that even if other plugins resolve again, we ignore our own proxies
556
+ if (
557
+ !resolved ||
558
+ resolved.external ||
559
+ resolved.id.endsWith(ENTRY_SUFFIX) ||
560
+ isWrappedId(resolved.id, ES_IMPORT_SUFFIX)
561
+ ) {
562
+ return resolved;
563
+ }
564
+ const moduleInfo = await this.load(resolved);
565
+ if (resolveOptions.isEntry) {
566
+ moduleInfo.moduleSideEffects = true;
567
+ // We must not precede entry proxies with a `\0` as that will mess up relative external resolution
568
+ return resolved.id + ENTRY_SUFFIX;
569
+ }
570
+ const {
571
+ meta: { commonjs: commonjsMeta }
572
+ } = moduleInfo;
573
+ if (commonjsMeta && commonjsMeta.isCommonJS === IS_WRAPPED_COMMONJS) {
574
+ return wrapId(resolved.id, ES_IMPORT_SUFFIX);
601
575
  }
576
+ return resolved;
577
+ };
578
+ }
602
579
 
603
- const importer =
604
- rawImporter && isWrappedId(rawImporter, DYNAMIC_REGISTER_SUFFIX)
605
- ? unwrapId(rawImporter, DYNAMIC_REGISTER_SUFFIX)
606
- : rawImporter;
580
+ function getRequireResolver(extensions, detectCyclesAndConditional) {
581
+ const knownCjsModuleTypes = Object.create(null);
582
+ const requiredIds = Object.create(null);
583
+ const unconditionallyRequiredIds = Object.create(null);
584
+ const dependencies = Object.create(null);
585
+ const getDependencies = (id) => dependencies[id] || (dependencies[id] = new Set());
607
586
 
608
- // Except for exports, proxies are only importing resolved ids,
609
- // no need to resolve again
610
- if (importer && isWrappedId(importer, PROXY_SUFFIX)) {
611
- return importee;
587
+ const isCyclic = (id) => {
588
+ const dependenciesToCheck = new Set(getDependencies(id));
589
+ for (const dependency of dependenciesToCheck) {
590
+ if (dependency === id) {
591
+ return true;
592
+ }
593
+ for (const childDependency of getDependencies(dependency)) {
594
+ dependenciesToCheck.add(childDependency);
595
+ }
612
596
  }
597
+ return false;
598
+ };
613
599
 
614
- const isProxyModule = isWrappedId(importee, PROXY_SUFFIX);
615
- const isRequiredModule = isWrappedId(importee, REQUIRE_SUFFIX);
616
- let isModuleRegistration = false;
617
-
618
- if (isProxyModule) {
619
- importee = unwrapId(importee, PROXY_SUFFIX);
620
- } else if (isRequiredModule) {
621
- importee = unwrapId(importee, REQUIRE_SUFFIX);
600
+ const fullyAnalyzedModules = Object.create(null);
622
601
 
623
- isModuleRegistration = isWrappedId(importee, DYNAMIC_REGISTER_SUFFIX);
624
- if (isModuleRegistration) {
625
- importee = unwrapId(importee, DYNAMIC_REGISTER_SUFFIX);
626
- }
602
+ const getTypeForFullyAnalyzedModule = (id) => {
603
+ const knownType = knownCjsModuleTypes[id];
604
+ if (knownType !== true || !detectCyclesAndConditional || fullyAnalyzedModules[id]) {
605
+ return knownType;
627
606
  }
607
+ fullyAnalyzedModules[id] = true;
608
+ if (isCyclic(id)) {
609
+ return (knownCjsModuleTypes[id] = IS_WRAPPED_COMMONJS);
610
+ }
611
+ return knownType;
612
+ };
628
613
 
614
+ const setInitialParentType = (id, initialCommonJSType) => {
615
+ // It is possible a transformed module is already fully analyzed when using
616
+ // the cache and one dependency introduces a new cycle. Then transform is
617
+ // run for a fully analzyed module again. Fully analyzed modules may never
618
+ // change their type as importers already trust their type.
619
+ knownCjsModuleTypes[id] = fullyAnalyzedModules[id]
620
+ ? knownCjsModuleTypes[id]
621
+ : initialCommonJSType;
629
622
  if (
630
- importee.startsWith(HELPERS_ID) ||
631
- importee === DYNAMIC_PACKAGES_ID ||
632
- importee.startsWith(DYNAMIC_JSON_PREFIX)
623
+ detectCyclesAndConditional &&
624
+ knownCjsModuleTypes[id] === true &&
625
+ requiredIds[id] &&
626
+ !unconditionallyRequiredIds[id]
633
627
  ) {
634
- return importee;
628
+ knownCjsModuleTypes[id] = IS_WRAPPED_COMMONJS;
635
629
  }
630
+ };
636
631
 
637
- if (importee.startsWith('\0')) {
638
- return null;
632
+ const setTypesForRequiredModules = async (parentId, resolved, isConditional, loadModule) => {
633
+ const childId = resolved.id;
634
+ requiredIds[childId] = true;
635
+ if (!(isConditional || knownCjsModuleTypes[parentId] === IS_WRAPPED_COMMONJS)) {
636
+ unconditionallyRequiredIds[childId] = true;
637
+ }
638
+
639
+ getDependencies(parentId).add(childId);
640
+ if (!isCyclic(childId)) {
641
+ // This makes sure the current transform handler waits for all direct dependencies to be
642
+ // loaded and transformed and therefore for all transitive CommonJS dependencies to be
643
+ // loaded as well so that all cycles have been found and knownCjsModuleTypes is reliable.
644
+ await loadModule(resolved);
639
645
  }
646
+ };
640
647
 
641
- return this.resolve(importee, importer, {
642
- skipSelf: true,
643
- custom: { 'node-resolve': { isRequire: isProxyModule || isRequiredModule } }
644
- }).then((resolved) => {
645
- if (!resolved) {
646
- resolved = resolveExtensions(importee, importer);
648
+ return {
649
+ getWrappedIds: () =>
650
+ Object.keys(knownCjsModuleTypes).filter(
651
+ (id) => knownCjsModuleTypes[id] === IS_WRAPPED_COMMONJS
652
+ ),
653
+ isRequiredId: (id) => requiredIds[id],
654
+ async shouldTransformCachedModule({ id: parentId, meta: { commonjs: parentMeta } }) {
655
+ // Ignore modules that did not pass through the original transformer in a previous build
656
+ if (!(parentMeta && parentMeta.requires)) {
657
+ return false;
647
658
  }
648
- if (resolved && isProxyModule) {
649
- resolved.id = wrapId(resolved.id, resolved.external ? EXTERNAL_SUFFIX : PROXY_SUFFIX);
650
- resolved.external = false;
651
- } else if (resolved && isModuleRegistration) {
652
- resolved.id = wrapId(resolved.id, DYNAMIC_REGISTER_SUFFIX);
653
- } else if (!resolved && (isProxyModule || isRequiredModule)) {
654
- return { id: wrapId(importee, EXTERNAL_SUFFIX), external: false };
659
+ setInitialParentType(parentId, parentMeta.initialCommonJSType);
660
+ await Promise.all(
661
+ parentMeta.requires.map(({ resolved, isConditional }) =>
662
+ setTypesForRequiredModules(parentId, resolved, isConditional, this.load)
663
+ )
664
+ );
665
+ if (getTypeForFullyAnalyzedModule(parentId) !== parentMeta.isCommonJS) {
666
+ return true;
655
667
  }
656
- return resolved;
657
- });
668
+ for (const {
669
+ resolved: { id }
670
+ } of parentMeta.requires) {
671
+ if (getTypeForFullyAnalyzedModule(id) !== parentMeta.isRequiredCommonJS[id]) {
672
+ return true;
673
+ }
674
+ }
675
+ return false;
676
+ },
677
+ /* eslint-disable no-param-reassign */
678
+ resolveRequireSourcesAndUpdateMeta: (rollupContext) => async (
679
+ parentId,
680
+ isParentCommonJS,
681
+ parentMeta,
682
+ sources
683
+ ) => {
684
+ parentMeta.initialCommonJSType = isParentCommonJS;
685
+ parentMeta.requires = [];
686
+ parentMeta.isRequiredCommonJS = Object.create(null);
687
+ setInitialParentType(parentId, isParentCommonJS);
688
+ const requireTargets = await Promise.all(
689
+ sources.map(async ({ source, isConditional }) => {
690
+ // Never analyze or proxy internal modules
691
+ if (source.startsWith('\0')) {
692
+ return { id: source, allowProxy: false };
693
+ }
694
+ const resolved =
695
+ (await rollupContext.resolve(source, parentId, {
696
+ custom: { 'node-resolve': { isRequire: true } }
697
+ })) || resolveExtensions(source, parentId, extensions);
698
+ if (!resolved) {
699
+ return { id: wrapId(source, EXTERNAL_SUFFIX), allowProxy: false };
700
+ }
701
+ const childId = resolved.id;
702
+ if (resolved.external) {
703
+ return { id: wrapId(childId, EXTERNAL_SUFFIX), allowProxy: false };
704
+ }
705
+ parentMeta.requires.push({ resolved, isConditional });
706
+ await setTypesForRequiredModules(parentId, resolved, isConditional, rollupContext.load);
707
+ return { id: childId, allowProxy: true };
708
+ })
709
+ );
710
+ parentMeta.isCommonJS = getTypeForFullyAnalyzedModule(parentId);
711
+ return requireTargets.map(({ id: dependencyId, allowProxy }, index) => {
712
+ // eslint-disable-next-line no-multi-assign
713
+ const isCommonJS = (parentMeta.isRequiredCommonJS[
714
+ dependencyId
715
+ ] = getTypeForFullyAnalyzedModule(dependencyId));
716
+ return {
717
+ source: sources[index].source,
718
+ id: allowProxy
719
+ ? isCommonJS === IS_WRAPPED_COMMONJS
720
+ ? wrapId(dependencyId, WRAPPED_SUFFIX)
721
+ : wrapId(dependencyId, PROXY_SUFFIX)
722
+ : dependencyId,
723
+ isCommonJS
724
+ };
725
+ });
726
+ }
658
727
  };
659
728
  }
660
729
 
661
- function validateRollupVersion(rollupVersion, peerDependencyVersion) {
662
- const [major, minor] = rollupVersion.split('.').map(Number);
663
- const versionRegexp = /\^(\d+\.\d+)\.\d+/g;
730
+ function validateVersion(actualVersion, peerDependencyVersion, name) {
731
+ const versionRegexp = /\^(\d+\.\d+\.\d+)/g;
664
732
  let minMajor = Infinity;
665
733
  let minMinor = Infinity;
734
+ let minPatch = Infinity;
666
735
  let foundVersion;
667
736
  // eslint-disable-next-line no-cond-assign
668
737
  while ((foundVersion = versionRegexp.exec(peerDependencyVersion))) {
669
- const [foundMajor, foundMinor] = foundVersion[1].split('.').map(Number);
738
+ const [foundMajor, foundMinor, foundPatch] = foundVersion[1].split('.').map(Number);
670
739
  if (foundMajor < minMajor) {
671
740
  minMajor = foundMajor;
672
741
  minMinor = foundMinor;
742
+ minPatch = foundPatch;
673
743
  }
674
744
  }
675
- if (major < minMajor || (major === minMajor && minor < minMinor)) {
745
+ if (!actualVersion) {
676
746
  throw new Error(
677
- `Insufficient Rollup version: "@rollup/plugin-commonjs" requires at least rollup@${minMajor}.${minMinor} but found rollup@${rollupVersion}.`
747
+ `Insufficient ${name} version: "@rollup/plugin-commonjs" requires at least ${name}@${minMajor}.${minMinor}.${minPatch}.`
748
+ );
749
+ }
750
+ const [major, minor, patch] = actualVersion.split('.').map(Number);
751
+ if (
752
+ major < minMajor ||
753
+ (major === minMajor && (minor < minMinor || (minor === minMinor && patch < minPatch)))
754
+ ) {
755
+ throw new Error(
756
+ `Insufficient ${name} version: "@rollup/plugin-commonjs" requires at least ${name}@${minMajor}.${minMinor}.${minPatch} but found ${name}@${actualVersion}.`
678
757
  );
679
758
  }
680
759
  }
@@ -814,8 +893,9 @@ function wrapCode(magicString, uses, moduleName, exportsName) {
814
893
  }
815
894
  magicString
816
895
  .trim()
896
+ .indent('\t')
817
897
  .prepend(`(function (${args.join(', ')}) {\n`)
818
- .append(`\n}(${passedArgs.join(', ')}));`);
898
+ .append(`\n} (${passedArgs.join(', ')}));`);
819
899
  }
820
900
 
821
901
  function rewriteExportsAndGetExportsBlock(
@@ -833,12 +913,27 @@ function rewriteExportsAndGetExportsBlock(
833
913
  HELPERS_NAME,
834
914
  exportMode,
835
915
  detectWrappedDefault,
836
- defaultIsModuleExports
916
+ defaultIsModuleExports,
917
+ usesRequireWrapper,
918
+ requireName
837
919
  ) {
838
920
  const exports = [];
839
921
  const exportDeclarations = [];
840
922
 
841
- if (exportMode === 'replace') {
923
+ if (usesRequireWrapper) {
924
+ getExportsWhenUsingRequireWrapper(
925
+ magicString,
926
+ wrapped,
927
+ exportMode,
928
+ exports,
929
+ moduleExportsAssignments,
930
+ exportsAssignmentsByName,
931
+ moduleName,
932
+ exportsName,
933
+ requireName,
934
+ defineCompiledEsmExpressions
935
+ );
936
+ } else if (exportMode === 'replace') {
842
937
  getExportsForReplacedModuleExports(
843
938
  magicString,
844
939
  exports,
@@ -881,6 +976,49 @@ function rewriteExportsAndGetExportsBlock(
881
976
  return `\n\n${exportDeclarations.join('\n')}`;
882
977
  }
883
978
 
979
+ function getExportsWhenUsingRequireWrapper(
980
+ magicString,
981
+ wrapped,
982
+ exportMode,
983
+ exports,
984
+ moduleExportsAssignments,
985
+ exportsAssignmentsByName,
986
+ moduleName,
987
+ exportsName,
988
+ requireName,
989
+ defineCompiledEsmExpressions
990
+ ) {
991
+ if (!wrapped) {
992
+ if (exportMode === 'replace') {
993
+ for (const { left } of moduleExportsAssignments) {
994
+ magicString.overwrite(left.start, left.end, exportsName);
995
+ }
996
+ } else {
997
+ // Collect and rewrite module.exports assignments
998
+ for (const { left } of moduleExportsAssignments) {
999
+ magicString.overwrite(left.start, left.end, `${moduleName}.exports`);
1000
+ }
1001
+ // Collect and rewrite named exports
1002
+ for (const [exportName, { nodes }] of exportsAssignmentsByName) {
1003
+ for (const node of nodes) {
1004
+ magicString.overwrite(node.start, node.left.end, `${exportsName}.${exportName}`);
1005
+ }
1006
+ }
1007
+ // Collect and rewrite exports.__esModule assignments
1008
+ for (const expression of defineCompiledEsmExpressions) {
1009
+ const moduleExportsExpression =
1010
+ expression.type === 'CallExpression' ? expression.arguments[0] : expression.left.object;
1011
+ magicString.overwrite(
1012
+ moduleExportsExpression.start,
1013
+ moduleExportsExpression.end,
1014
+ exportsName
1015
+ );
1016
+ }
1017
+ }
1018
+ }
1019
+ exports.push(`${requireName} as __require`);
1020
+ }
1021
+
884
1022
  function getExportsForReplacedModuleExports(
885
1023
  magicString,
886
1024
  exports,
@@ -968,7 +1106,7 @@ function getExports(
968
1106
  }
969
1107
 
970
1108
  if (!isRestorableCompiledEsm || defaultIsModuleExports === true) {
971
- exportDeclarations.push(`export default ${exportsName};`);
1109
+ exports.push(`${exportsName} as default`);
972
1110
  } else if (moduleExportsAssignments.length === 0 || defaultIsModuleExports === false) {
973
1111
  exports.push(`${deconflictedDefaultExportName || exportsName} as default`);
974
1112
  } else {
@@ -978,7 +1116,7 @@ function getExports(
978
1116
  }
979
1117
  }
980
1118
 
981
- function isRequireStatement(node, scope) {
1119
+ function isRequireExpression(node, scope) {
982
1120
  if (!node) return false;
983
1121
  if (node.type !== 'CallExpression') return false;
984
1122
 
@@ -1005,11 +1143,6 @@ function isModuleRequire({ object, property }, scope) {
1005
1143
  );
1006
1144
  }
1007
1145
 
1008
- function isStaticRequireStatement(node, scope) {
1009
- if (!isRequireStatement(node, scope)) return false;
1010
- return !hasDynamicArguments(node);
1011
- }
1012
-
1013
1146
  function hasDynamicArguments(node) {
1014
1147
  return (
1015
1148
  node.arguments.length > 1 ||
@@ -1024,89 +1157,61 @@ function isNodeRequirePropertyAccess(parent) {
1024
1157
  return parent && parent.property && reservedMethod[parent.property.name];
1025
1158
  }
1026
1159
 
1027
- function isIgnoredRequireStatement(requiredNode, ignoreRequire) {
1028
- return ignoreRequire(requiredNode.arguments[0].value);
1029
- }
1030
-
1031
1160
  function getRequireStringArg(node) {
1032
1161
  return node.arguments[0].type === 'Literal'
1033
1162
  ? node.arguments[0].value
1034
1163
  : node.arguments[0].quasis[0].value.cooked;
1035
1164
  }
1036
1165
 
1037
- function hasDynamicModuleForPath(source, id, dynamicRequireModuleSet) {
1038
- if (!/^(?:\.{0,2}[/\\]|[A-Za-z]:[/\\])/.test(source)) {
1039
- try {
1040
- const resolvedPath = normalizePathSlashes(resolve.sync(source, { basedir: path.dirname(id) }));
1041
- if (dynamicRequireModuleSet.has(resolvedPath)) {
1042
- return true;
1043
- }
1044
- } catch (ex) {
1045
- // Probably a node.js internal module
1046
- return false;
1047
- }
1048
-
1049
- return false;
1050
- }
1051
-
1052
- for (const attemptExt of ['', '.js', '.json']) {
1053
- const resolvedPath = normalizePathSlashes(path.resolve(path.dirname(id), source + attemptExt));
1054
- if (dynamicRequireModuleSet.has(resolvedPath)) {
1055
- return true;
1056
- }
1057
- }
1058
-
1059
- return false;
1060
- }
1061
-
1062
1166
  function getRequireHandlers() {
1063
- const requiredSources = [];
1064
- const requiredBySource = Object.create(null);
1065
- const requiredByNode = new Map();
1066
- const requireExpressionsWithUsedReturnValue = [];
1067
-
1068
- function addRequireStatement(sourceId, node, scope, usesReturnValue) {
1069
- const required = getRequired(sourceId);
1070
- requiredByNode.set(node, { scope, required });
1071
- if (usesReturnValue) {
1072
- required.nodesUsingRequired.push(node);
1073
- requireExpressionsWithUsedReturnValue.push(node);
1074
- }
1075
- }
1076
-
1077
- function getRequired(sourceId) {
1078
- if (!requiredBySource[sourceId]) {
1079
- requiredSources.push(sourceId);
1080
-
1081
- requiredBySource[sourceId] = {
1082
- source: sourceId,
1083
- name: null,
1084
- nodesUsingRequired: []
1085
- };
1086
- }
1087
-
1088
- return requiredBySource[sourceId];
1167
+ const requireExpressions = [];
1168
+
1169
+ function addRequireStatement(
1170
+ sourceId,
1171
+ node,
1172
+ scope,
1173
+ usesReturnValue,
1174
+ isInsideTryBlock,
1175
+ isInsideConditional,
1176
+ toBeRemoved
1177
+ ) {
1178
+ requireExpressions.push({
1179
+ sourceId,
1180
+ node,
1181
+ scope,
1182
+ usesReturnValue,
1183
+ isInsideTryBlock,
1184
+ isInsideConditional,
1185
+ toBeRemoved
1186
+ });
1089
1187
  }
1090
1188
 
1091
- function rewriteRequireExpressionsAndGetImportBlock(
1189
+ async function rewriteRequireExpressionsAndGetImportBlock(
1092
1190
  magicString,
1093
1191
  topLevelDeclarations,
1094
- topLevelRequireDeclarators,
1095
1192
  reassignedNames,
1096
1193
  helpersName,
1097
- dynamicRegisterSources,
1194
+ dynamicRequireName,
1098
1195
  moduleName,
1099
1196
  exportsName,
1100
1197
  id,
1101
- exportMode
1198
+ exportMode,
1199
+ resolveRequireSourcesAndUpdateMeta,
1200
+ needsRequireWrapper,
1201
+ isEsModule,
1202
+ isDynamicRequireModulesEnabled,
1203
+ getIgnoreTryCatchRequireStatementMode,
1204
+ commonjsMeta
1102
1205
  ) {
1103
- setRemainingImportNamesAndRewriteRequires(
1104
- requireExpressionsWithUsedReturnValue,
1105
- requiredByNode,
1106
- magicString
1107
- );
1108
1206
  const imports = [];
1109
1207
  imports.push(`import * as ${helpersName} from "${HELPERS_ID}";`);
1208
+ if (dynamicRequireName) {
1209
+ imports.push(
1210
+ `import { ${
1211
+ isDynamicRequireModulesEnabled ? CREATE_COMMONJS_REQUIRE_EXPORT : COMMONJS_REQUIRE_EXPORT
1212
+ } as ${dynamicRequireName} } from "${DYNAMIC_MODULES_ID}";`
1213
+ );
1214
+ }
1110
1215
  if (exportMode === 'module') {
1111
1216
  imports.push(
1112
1217
  `import { __module as ${moduleName}, exports as ${exportsName} } from ${JSON.stringify(
@@ -1118,58 +1223,113 @@ function getRequireHandlers() {
1118
1223
  `import { __exports as ${exportsName} } from ${JSON.stringify(wrapId(id, EXPORTS_SUFFIX))}`
1119
1224
  );
1120
1225
  }
1121
- for (const source of dynamicRegisterSources) {
1122
- imports.push(`import ${JSON.stringify(wrapId(source, REQUIRE_SUFFIX))};`);
1123
- }
1124
- for (const source of requiredSources) {
1125
- if (!source.startsWith('\0')) {
1126
- imports.push(`import ${JSON.stringify(wrapId(source, REQUIRE_SUFFIX))};`);
1127
- }
1128
- const { name, nodesUsingRequired } = requiredBySource[source];
1129
- imports.push(
1130
- `import ${nodesUsingRequired.length ? `${name} from ` : ''}${JSON.stringify(
1131
- source.startsWith('\0') ? source : wrapId(source, PROXY_SUFFIX)
1132
- )};`
1133
- );
1134
- }
1226
+ const requiresBySource = collectSources(requireExpressions);
1227
+ const requireTargets = await resolveRequireSourcesAndUpdateMeta(
1228
+ id,
1229
+ needsRequireWrapper ? IS_WRAPPED_COMMONJS : !isEsModule,
1230
+ commonjsMeta,
1231
+ Object.keys(requiresBySource).map((source) => {
1232
+ return {
1233
+ source,
1234
+ isConditional: requiresBySource[source].every((require) => require.isInsideConditional)
1235
+ };
1236
+ })
1237
+ );
1238
+ processRequireExpressions(
1239
+ imports,
1240
+ requireTargets,
1241
+ requiresBySource,
1242
+ getIgnoreTryCatchRequireStatementMode,
1243
+ magicString
1244
+ );
1135
1245
  return imports.length ? `${imports.join('\n')}\n\n` : '';
1136
1246
  }
1137
1247
 
1138
1248
  return {
1139
1249
  addRequireStatement,
1140
- requiredSources,
1141
1250
  rewriteRequireExpressionsAndGetImportBlock
1142
1251
  };
1143
1252
  }
1144
1253
 
1145
- function setRemainingImportNamesAndRewriteRequires(
1146
- requireExpressionsWithUsedReturnValue,
1147
- requiredByNode,
1254
+ function collectSources(requireExpressions) {
1255
+ const requiresBySource = Object.create(null);
1256
+ for (const requireExpression of requireExpressions) {
1257
+ const { sourceId } = requireExpression;
1258
+ if (!requiresBySource[sourceId]) {
1259
+ requiresBySource[sourceId] = [];
1260
+ }
1261
+ const requires = requiresBySource[sourceId];
1262
+ requires.push(requireExpression);
1263
+ }
1264
+ return requiresBySource;
1265
+ }
1266
+
1267
+ function processRequireExpressions(
1268
+ imports,
1269
+ requireTargets,
1270
+ requiresBySource,
1271
+ getIgnoreTryCatchRequireStatementMode,
1148
1272
  magicString
1149
1273
  ) {
1150
- let uid = 0;
1151
- for (const requireExpression of requireExpressionsWithUsedReturnValue) {
1152
- const { required } = requiredByNode.get(requireExpression);
1153
- if (!required.name) {
1154
- let potentialName;
1155
- const isUsedName = (node) => requiredByNode.get(node).scope.contains(potentialName);
1156
- do {
1157
- potentialName = `require$$${uid}`;
1158
- uid += 1;
1159
- } while (required.nodesUsingRequired.some(isUsedName));
1160
- required.name = potentialName;
1274
+ const generateRequireName = getGenerateRequireName();
1275
+ for (const { source, id: resolvedId, isCommonJS } of requireTargets) {
1276
+ const requires = requiresBySource[source];
1277
+ const name = generateRequireName(requires);
1278
+ let usesRequired = false;
1279
+ let needsImport = false;
1280
+ for (const { node, usesReturnValue, toBeRemoved, isInsideTryBlock } of requires) {
1281
+ const { canConvertRequire, shouldRemoveRequire } =
1282
+ isInsideTryBlock && isWrappedId(resolvedId, EXTERNAL_SUFFIX)
1283
+ ? getIgnoreTryCatchRequireStatementMode(source)
1284
+ : { canConvertRequire: true, shouldRemoveRequire: false };
1285
+ if (shouldRemoveRequire) {
1286
+ if (usesReturnValue) {
1287
+ magicString.overwrite(node.start, node.end, 'undefined');
1288
+ } else {
1289
+ magicString.remove(toBeRemoved.start, toBeRemoved.end);
1290
+ }
1291
+ } else if (canConvertRequire) {
1292
+ needsImport = true;
1293
+ if (isCommonJS === IS_WRAPPED_COMMONJS) {
1294
+ magicString.overwrite(node.start, node.end, `${name}()`);
1295
+ } else if (usesReturnValue) {
1296
+ usesRequired = true;
1297
+ magicString.overwrite(node.start, node.end, name);
1298
+ } else {
1299
+ magicString.remove(toBeRemoved.start, toBeRemoved.end);
1300
+ }
1301
+ }
1302
+ }
1303
+ if (needsImport) {
1304
+ if (isCommonJS === IS_WRAPPED_COMMONJS) {
1305
+ imports.push(`import { __require as ${name} } from ${JSON.stringify(resolvedId)};`);
1306
+ } else {
1307
+ imports.push(`import ${usesRequired ? `${name} from ` : ''}${JSON.stringify(resolvedId)};`);
1308
+ }
1161
1309
  }
1162
- magicString.overwrite(requireExpression.start, requireExpression.end, required.name);
1163
1310
  }
1164
1311
  }
1165
1312
 
1313
+ function getGenerateRequireName() {
1314
+ let uid = 0;
1315
+ return (requires) => {
1316
+ let name;
1317
+ const hasNameConflict = ({ scope }) => scope.contains(name);
1318
+ do {
1319
+ name = `require$$${uid}`;
1320
+ uid += 1;
1321
+ } while (requires.some(hasNameConflict));
1322
+ return name;
1323
+ };
1324
+ }
1325
+
1166
1326
  /* eslint-disable no-param-reassign, no-shadow, no-underscore-dangle, no-continue */
1167
1327
 
1168
1328
  const exportsPattern = /^(?:module\.)?exports(?:\.([a-zA-Z_$][a-zA-Z_$0-9]*))?$/;
1169
1329
 
1170
1330
  const functionType = /^(?:FunctionDeclaration|FunctionExpression|ArrowFunctionExpression)$/;
1171
1331
 
1172
- function transformCommonjs(
1332
+ async function transformCommonjs(
1173
1333
  parse,
1174
1334
  code,
1175
1335
  id,
@@ -1180,21 +1340,24 @@ function transformCommonjs(
1180
1340
  getIgnoreTryCatchRequireStatementMode,
1181
1341
  sourceMap,
1182
1342
  isDynamicRequireModulesEnabled,
1183
- dynamicRequireModuleSet,
1184
- disableWrap,
1343
+ dynamicRequireModules,
1185
1344
  commonDir,
1186
1345
  astCache,
1187
- defaultIsModuleExports
1346
+ defaultIsModuleExports,
1347
+ needsRequireWrapper,
1348
+ resolveRequireSourcesAndUpdateMeta,
1349
+ isRequired,
1350
+ checkDynamicRequire,
1351
+ commonjsMeta
1188
1352
  ) {
1189
1353
  const ast = astCache || tryParse(parse, code, id);
1190
- const magicString = new MagicString__default['default'](code);
1354
+ const magicString = new MagicString__default["default"](code);
1191
1355
  const uses = {
1192
1356
  module: false,
1193
1357
  exports: false,
1194
1358
  global: false,
1195
1359
  require: false
1196
1360
  };
1197
- let usesDynamicRequire = false;
1198
1361
  const virtualDynamicRequirePath =
1199
1362
  isDynamicRequireModulesEnabled && getVirtualPathForDynamicRequirePath(path.dirname(id), commonDir);
1200
1363
  let scope = pluginutils.attachScopes(ast, 'scope');
@@ -1204,24 +1367,18 @@ function transformCommonjs(
1204
1367
  let shouldWrap = false;
1205
1368
 
1206
1369
  const globals = new Set();
1207
-
1208
- // TODO technically wrong since globals isn't populated yet, but ¯\_(ツ)_/¯
1209
- const HELPERS_NAME = deconflict([scope], globals, 'commonjsHelpers');
1210
- const dynamicRegisterSources = new Set();
1211
- let hasRemovedRequire = false;
1212
-
1213
- const {
1214
- addRequireStatement,
1215
- requiredSources,
1216
- rewriteRequireExpressionsAndGetImportBlock
1217
- } = getRequireHandlers();
1370
+ // A conditionalNode is a node for which execution is not guaranteed. If such a node is a require
1371
+ // or contains nested requires, those should be handled as function calls unless there is an
1372
+ // unconditional require elsewhere.
1373
+ let currentConditionalNodeEnd = null;
1374
+ const conditionalNodes = new Set();
1375
+ const { addRequireStatement, rewriteRequireExpressionsAndGetImportBlock } = getRequireHandlers();
1218
1376
 
1219
1377
  // See which names are assigned to. This is necessary to prevent
1220
1378
  // illegally replacing `var foo = require('foo')` with `import foo from 'foo'`,
1221
1379
  // where `foo` is later reassigned. (This happens in the wild. CommonJS, sigh)
1222
1380
  const reassignedNames = new Set();
1223
1381
  const topLevelDeclarations = [];
1224
- const topLevelRequireDeclarators = new Set();
1225
1382
  const skippedNodes = new Set();
1226
1383
  const moduleAccessScopes = new Set([scope]);
1227
1384
  const exportsAccessScopes = new Set([scope]);
@@ -1230,6 +1387,9 @@ function transformCommonjs(
1230
1387
  const exportsAssignmentsByName = new Map();
1231
1388
  const topLevelAssignments = new Set();
1232
1389
  const topLevelDefineCompiledEsmExpressions = [];
1390
+ const replacedGlobal = [];
1391
+ const replacedDynamicRequires = [];
1392
+ const importedVariables = new Set();
1233
1393
 
1234
1394
  estreeWalker.walk(ast, {
1235
1395
  enter(node, parent) {
@@ -1241,6 +1401,12 @@ function transformCommonjs(
1241
1401
  if (currentTryBlockEnd !== null && node.start > currentTryBlockEnd) {
1242
1402
  currentTryBlockEnd = null;
1243
1403
  }
1404
+ if (currentConditionalNodeEnd !== null && node.start > currentConditionalNodeEnd) {
1405
+ currentConditionalNodeEnd = null;
1406
+ }
1407
+ if (currentConditionalNodeEnd === null && conditionalNodes.has(node)) {
1408
+ currentConditionalNodeEnd = node.end;
1409
+ }
1244
1410
 
1245
1411
  programDepth += 1;
1246
1412
  if (node.scope) ({ scope } = node);
@@ -1252,11 +1418,6 @@ function transformCommonjs(
1252
1418
 
1253
1419
  // eslint-disable-next-line default-case
1254
1420
  switch (node.type) {
1255
- case 'TryStatement':
1256
- if (currentTryBlockEnd === null) {
1257
- currentTryBlockEnd = node.block.end;
1258
- }
1259
- return;
1260
1421
  case 'AssignmentExpression':
1261
1422
  if (node.left.type === 'MemberExpression') {
1262
1423
  const flattened = getKeypath(node.left);
@@ -1327,110 +1488,58 @@ function transformCommonjs(
1327
1488
  return;
1328
1489
  }
1329
1490
 
1491
+ // Transform require.resolve
1330
1492
  if (
1493
+ isDynamicRequireModulesEnabled &&
1331
1494
  node.callee.object &&
1332
- node.callee.object.name === 'require' &&
1333
- node.callee.property.name === 'resolve' &&
1334
- hasDynamicModuleForPath(id, '/', dynamicRequireModuleSet)
1495
+ isRequire(node.callee.object, scope) &&
1496
+ node.callee.property.name === 'resolve'
1335
1497
  ) {
1498
+ checkDynamicRequire(node.start);
1499
+ uses.require = true;
1336
1500
  const requireNode = node.callee.object;
1337
- magicString.appendLeft(
1338
- node.end - 1,
1339
- `,${JSON.stringify(
1340
- path.dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath
1341
- )}`
1342
- );
1343
- magicString.overwrite(
1344
- requireNode.start,
1345
- requireNode.end,
1346
- `${HELPERS_NAME}.commonjsRequire`,
1347
- {
1348
- storeName: true
1349
- }
1350
- );
1501
+ replacedDynamicRequires.push(requireNode);
1351
1502
  return;
1352
1503
  }
1353
1504
 
1354
- if (!isStaticRequireStatement(node, scope)) return;
1355
- if (!isDynamicRequireModulesEnabled) {
1356
- skippedNodes.add(node.callee);
1505
+ if (!isRequireExpression(node, scope)) {
1506
+ const keypath = getKeypath(node.callee);
1507
+ if (keypath && importedVariables.has(keypath.name)) {
1508
+ // Heuristic to deoptimize requires after a required function has been called
1509
+ currentConditionalNodeEnd = Infinity;
1510
+ }
1511
+ return;
1357
1512
  }
1358
- if (!isIgnoredRequireStatement(node, ignoreRequire)) {
1359
- skippedNodes.add(node.callee);
1360
- const usesReturnValue = parent.type !== 'ExpressionStatement';
1361
-
1362
- let canConvertRequire = true;
1363
- let shouldRemoveRequireStatement = false;
1364
1513
 
1365
- if (currentTryBlockEnd !== null) {
1366
- ({
1367
- canConvertRequire,
1368
- shouldRemoveRequireStatement
1369
- } = getIgnoreTryCatchRequireStatementMode(node.arguments[0].value));
1514
+ skippedNodes.add(node.callee);
1515
+ uses.require = true;
1370
1516
 
1371
- if (shouldRemoveRequireStatement) {
1372
- hasRemovedRequire = true;
1373
- }
1517
+ if (hasDynamicArguments(node)) {
1518
+ if (isDynamicRequireModulesEnabled) {
1519
+ checkDynamicRequire(node.start);
1374
1520
  }
1375
-
1376
- let sourceId = getRequireStringArg(node);
1377
- const isDynamicRegister = isWrappedId(sourceId, DYNAMIC_REGISTER_SUFFIX);
1378
- if (isDynamicRegister) {
1379
- sourceId = unwrapId(sourceId, DYNAMIC_REGISTER_SUFFIX);
1380
- if (sourceId.endsWith('.json')) {
1381
- sourceId = DYNAMIC_JSON_PREFIX + sourceId;
1382
- }
1383
- dynamicRegisterSources.add(wrapId(sourceId, DYNAMIC_REGISTER_SUFFIX));
1384
- } else {
1385
- if (
1386
- !sourceId.endsWith('.json') &&
1387
- hasDynamicModuleForPath(sourceId, id, dynamicRequireModuleSet)
1388
- ) {
1389
- if (shouldRemoveRequireStatement) {
1390
- magicString.overwrite(node.start, node.end, `undefined`);
1391
- } else if (canConvertRequire) {
1392
- magicString.overwrite(
1393
- node.start,
1394
- node.end,
1395
- `${HELPERS_NAME}.commonjsRequire(${JSON.stringify(
1396
- getVirtualPathForDynamicRequirePath(sourceId, commonDir)
1397
- )}, ${JSON.stringify(
1398
- path.dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath
1399
- )})`
1400
- );
1401
- usesDynamicRequire = true;
1402
- }
1403
- return;
1404
- }
1405
-
1406
- if (canConvertRequire) {
1407
- addRequireStatement(sourceId, node, scope, usesReturnValue);
1408
- }
1521
+ if (!ignoreDynamicRequires) {
1522
+ replacedDynamicRequires.push(node.callee);
1409
1523
  }
1524
+ return;
1525
+ }
1410
1526
 
1411
- if (usesReturnValue) {
1412
- if (shouldRemoveRequireStatement) {
1413
- magicString.overwrite(node.start, node.end, `undefined`);
1414
- return;
1415
- }
1416
-
1417
- if (
1418
- parent.type === 'VariableDeclarator' &&
1419
- !scope.parent &&
1420
- parent.id.type === 'Identifier'
1421
- ) {
1422
- // This will allow us to reuse this variable name as the imported variable if it is not reassigned
1423
- // and does not conflict with variables in other places where this is imported
1424
- topLevelRequireDeclarators.add(parent);
1425
- }
1426
- } else {
1427
- // This is a bare import, e.g. `require('foo');`
1428
-
1429
- if (!canConvertRequire && !shouldRemoveRequireStatement) {
1430
- return;
1527
+ const requireStringArg = getRequireStringArg(node);
1528
+ if (!ignoreRequire(requireStringArg)) {
1529
+ const usesReturnValue = parent.type !== 'ExpressionStatement';
1530
+ addRequireStatement(
1531
+ requireStringArg,
1532
+ node,
1533
+ scope,
1534
+ usesReturnValue,
1535
+ currentTryBlockEnd !== null,
1536
+ currentConditionalNodeEnd !== null,
1537
+ parent.type === 'ExpressionStatement' ? parent : node
1538
+ );
1539
+ if (parent.type === 'VariableDeclarator' && parent.id.type === 'Identifier') {
1540
+ for (const name of pluginutils.extractAssignedNames(parent.id)) {
1541
+ importedVariables.add(name);
1431
1542
  }
1432
-
1433
- magicString.remove(parent.start, parent.end);
1434
1543
  }
1435
1544
  }
1436
1545
  return;
@@ -1440,45 +1549,43 @@ function transformCommonjs(
1440
1549
  // skip dead branches
1441
1550
  if (isFalsy(node.test)) {
1442
1551
  skippedNodes.add(node.consequent);
1443
- } else if (node.alternate && isTruthy(node.test)) {
1444
- skippedNodes.add(node.alternate);
1552
+ } else if (isTruthy(node.test)) {
1553
+ if (node.alternate) {
1554
+ skippedNodes.add(node.alternate);
1555
+ }
1556
+ } else {
1557
+ conditionalNodes.add(node.consequent);
1558
+ if (node.alternate) {
1559
+ conditionalNodes.add(node.alternate);
1560
+ }
1561
+ }
1562
+ return;
1563
+ case 'ArrowFunctionExpression':
1564
+ case 'FunctionDeclaration':
1565
+ case 'FunctionExpression':
1566
+ // requires in functions should be conditional unless it is an IIFE
1567
+ if (
1568
+ currentConditionalNodeEnd === null &&
1569
+ !(parent.type === 'CallExpression' && parent.callee === node)
1570
+ ) {
1571
+ currentConditionalNodeEnd = node.end;
1445
1572
  }
1446
1573
  return;
1447
1574
  case 'Identifier': {
1448
1575
  const { name } = node;
1449
- if (!(isReference__default['default'](node, parent) && !scope.contains(name))) return;
1576
+ if (!isReference__default["default"](node, parent) || scope.contains(name)) return;
1450
1577
  switch (name) {
1451
1578
  case 'require':
1579
+ uses.require = true;
1452
1580
  if (isNodeRequirePropertyAccess(parent)) {
1453
- if (hasDynamicModuleForPath(id, '/', dynamicRequireModuleSet)) {
1454
- if (parent.property.name === 'cache') {
1455
- magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, {
1456
- storeName: true
1457
- });
1458
- }
1459
- }
1460
-
1461
1581
  return;
1462
1582
  }
1463
-
1464
- if (isDynamicRequireModulesEnabled && isRequireStatement(parent, scope)) {
1465
- magicString.appendLeft(
1466
- parent.end - 1,
1467
- `,${JSON.stringify(
1468
- path.dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath
1469
- )}`
1470
- );
1471
- }
1472
1583
  if (!ignoreDynamicRequires) {
1473
1584
  if (isShorthandProperty(parent)) {
1474
- magicString.appendRight(node.end, `: ${HELPERS_NAME}.commonjsRequire`);
1475
- } else {
1476
- magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, {
1477
- storeName: true
1478
- });
1585
+ magicString.prependRight(node.start, 'require: ');
1479
1586
  }
1587
+ replacedDynamicRequires.push(node);
1480
1588
  }
1481
- usesDynamicRequire = true;
1482
1589
  return;
1483
1590
  case 'module':
1484
1591
  case 'exports':
@@ -1488,9 +1595,7 @@ function transformCommonjs(
1488
1595
  case 'global':
1489
1596
  uses.global = true;
1490
1597
  if (!ignoreGlobal) {
1491
- magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsGlobal`, {
1492
- storeName: true
1493
- });
1598
+ replacedGlobal.push(node);
1494
1599
  }
1495
1600
  return;
1496
1601
  case 'define':
@@ -1503,11 +1608,26 @@ function transformCommonjs(
1503
1608
  return;
1504
1609
  }
1505
1610
  }
1611
+ case 'LogicalExpression':
1612
+ // skip dead branches
1613
+ if (node.operator === '&&') {
1614
+ if (isFalsy(node.left)) {
1615
+ skippedNodes.add(node.right);
1616
+ } else if (!isTruthy(node.left)) {
1617
+ conditionalNodes.add(node.right);
1618
+ }
1619
+ } else if (node.operator === '||') {
1620
+ if (isTruthy(node.left)) {
1621
+ skippedNodes.add(node.right);
1622
+ } else if (!isFalsy(node.left)) {
1623
+ conditionalNodes.add(node.right);
1624
+ }
1625
+ }
1626
+ return;
1506
1627
  case 'MemberExpression':
1507
1628
  if (!isDynamicRequireModulesEnabled && isModuleRequire(node, scope)) {
1508
- magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, {
1509
- storeName: true
1510
- });
1629
+ uses.require = true;
1630
+ replacedDynamicRequires.push(node);
1511
1631
  skippedNodes.add(node.object);
1512
1632
  skippedNodes.add(node.property);
1513
1633
  }
@@ -1523,12 +1643,18 @@ function transformCommonjs(
1523
1643
  if (lexicalDepth === 0) {
1524
1644
  uses.global = true;
1525
1645
  if (!ignoreGlobal) {
1526
- magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsGlobal`, {
1527
- storeName: true
1528
- });
1646
+ replacedGlobal.push(node);
1529
1647
  }
1530
1648
  }
1531
1649
  return;
1650
+ case 'TryStatement':
1651
+ if (currentTryBlockEnd === null) {
1652
+ currentTryBlockEnd = node.block.end;
1653
+ }
1654
+ if (currentConditionalNodeEnd === null) {
1655
+ currentConditionalNodeEnd = node.end;
1656
+ }
1657
+ return;
1532
1658
  case 'UnaryExpression':
1533
1659
  // rewrite `typeof module`, `typeof module.exports` and `typeof exports` (https://github.com/rollup/rollup-plugin-commonjs/issues/151)
1534
1660
  if (node.operator === 'typeof') {
@@ -1538,9 +1664,10 @@ function transformCommonjs(
1538
1664
  if (scope.contains(flattened.name)) return;
1539
1665
 
1540
1666
  if (
1541
- flattened.keypath === 'module.exports' ||
1542
- flattened.keypath === 'module' ||
1543
- flattened.keypath === 'exports'
1667
+ !isEsModule &&
1668
+ (flattened.keypath === 'module.exports' ||
1669
+ flattened.keypath === 'module' ||
1670
+ flattened.keypath === 'exports')
1544
1671
  ) {
1545
1672
  magicString.overwrite(node.start, node.end, `'object'`, {
1546
1673
  storeName: false
@@ -1565,29 +1692,53 @@ function transformCommonjs(
1565
1692
  const nameBase = getName(id);
1566
1693
  const exportsName = deconflict([...exportsAccessScopes], globals, nameBase);
1567
1694
  const moduleName = deconflict([...moduleAccessScopes], globals, `${nameBase}Module`);
1695
+ const requireName = deconflict([scope], globals, `require${capitalize(nameBase)}`);
1696
+ const isRequiredName = deconflict([scope], globals, `hasRequired${capitalize(nameBase)}`);
1697
+ const helpersName = deconflict([scope], globals, 'commonjsHelpers');
1698
+ const dynamicRequireName =
1699
+ replacedDynamicRequires.length > 0 &&
1700
+ deconflict(
1701
+ [scope],
1702
+ globals,
1703
+ isDynamicRequireModulesEnabled ? CREATE_COMMONJS_REQUIRE_EXPORT : COMMONJS_REQUIRE_EXPORT
1704
+ );
1568
1705
  const deconflictedExportNames = Object.create(null);
1569
1706
  for (const [exportName, { scopes }] of exportsAssignmentsByName) {
1570
1707
  deconflictedExportNames[exportName] = deconflict([...scopes], globals, exportName);
1571
1708
  }
1572
1709
 
1710
+ for (const node of replacedGlobal) {
1711
+ magicString.overwrite(node.start, node.end, `${helpersName}.commonjsGlobal`, {
1712
+ storeName: true
1713
+ });
1714
+ }
1715
+ for (const node of replacedDynamicRequires) {
1716
+ magicString.overwrite(
1717
+ node.start,
1718
+ node.end,
1719
+ isDynamicRequireModulesEnabled
1720
+ ? `${dynamicRequireName}(${JSON.stringify(virtualDynamicRequirePath)})`
1721
+ : dynamicRequireName,
1722
+ {
1723
+ contentOnly: true,
1724
+ storeName: true
1725
+ }
1726
+ );
1727
+ }
1728
+
1573
1729
  // We cannot wrap ES/mixed modules
1574
- shouldWrap =
1575
- !isEsModule &&
1576
- !disableWrap &&
1577
- (shouldWrap || (uses.exports && moduleExportsAssignments.length > 0));
1730
+ shouldWrap = !isEsModule && (shouldWrap || (uses.exports && moduleExportsAssignments.length > 0));
1578
1731
  const detectWrappedDefault =
1579
1732
  shouldWrap &&
1580
1733
  (topLevelDefineCompiledEsmExpressions.length > 0 || code.indexOf('__esModule') >= 0);
1581
1734
 
1582
1735
  if (
1583
1736
  !(
1584
- requiredSources.length ||
1585
- dynamicRegisterSources.size ||
1737
+ shouldWrap ||
1738
+ isRequired ||
1586
1739
  uses.module ||
1587
1740
  uses.exports ||
1588
1741
  uses.require ||
1589
- usesDynamicRequire ||
1590
- hasRemovedRequire ||
1591
1742
  topLevelDefineCompiledEsmExpressions.length > 0
1592
1743
  ) &&
1593
1744
  (ignoreGlobal || !uses.global)
@@ -1614,19 +1765,24 @@ function transformCommonjs(
1614
1765
  ? 'exports'
1615
1766
  : 'module';
1616
1767
 
1617
- const importBlock = rewriteRequireExpressionsAndGetImportBlock(
1768
+ const importBlock = await rewriteRequireExpressionsAndGetImportBlock(
1618
1769
  magicString,
1619
1770
  topLevelDeclarations,
1620
- topLevelRequireDeclarators,
1621
1771
  reassignedNames,
1622
- HELPERS_NAME,
1623
- dynamicRegisterSources,
1772
+ helpersName,
1773
+ dynamicRequireName,
1624
1774
  moduleName,
1625
1775
  exportsName,
1626
1776
  id,
1627
- exportMode
1777
+ exportMode,
1778
+ resolveRequireSourcesAndUpdateMeta,
1779
+ needsRequireWrapper,
1780
+ isEsModule,
1781
+ isDynamicRequireModulesEnabled,
1782
+ getIgnoreTryCatchRequireStatementMode,
1783
+ commonjsMeta
1628
1784
  );
1629
-
1785
+ const usesRequireWrapper = commonjsMeta.isCommonJS === IS_WRAPPED_COMMONJS;
1630
1786
  const exportBlock = isEsModule
1631
1787
  ? ''
1632
1788
  : rewriteExportsAndGetExportsBlock(
@@ -1641,16 +1797,35 @@ function transformCommonjs(
1641
1797
  topLevelDefineCompiledEsmExpressions,
1642
1798
  deconflictedExportNames,
1643
1799
  code,
1644
- HELPERS_NAME,
1800
+ helpersName,
1645
1801
  exportMode,
1646
1802
  detectWrappedDefault,
1647
- defaultIsModuleExports
1803
+ defaultIsModuleExports,
1804
+ usesRequireWrapper,
1805
+ requireName
1648
1806
  );
1649
1807
 
1650
1808
  if (shouldWrap) {
1651
1809
  wrapCode(magicString, uses, moduleName, exportsName);
1652
1810
  }
1653
1811
 
1812
+ if (usesRequireWrapper) {
1813
+ magicString.trim().indent('\t');
1814
+ magicString.prepend(
1815
+ `var ${isRequiredName};
1816
+
1817
+ function ${requireName} () {
1818
+ \tif (${isRequiredName}) return ${exportsName};
1819
+ \t${isRequiredName} = 1;
1820
+ `
1821
+ ).append(`
1822
+ \treturn ${exportsName};
1823
+ }`);
1824
+ if (exportMode === 'replace') {
1825
+ magicString.prepend(`var ${exportsName};\n`);
1826
+ }
1827
+ }
1828
+
1654
1829
  magicString
1655
1830
  .trim()
1656
1831
  .prepend(leadingComment + importBlock)
@@ -1659,24 +1834,29 @@ function transformCommonjs(
1659
1834
  return {
1660
1835
  code: magicString.toString(),
1661
1836
  map: sourceMap ? magicString.generateMap() : null,
1662
- syntheticNamedExports: isEsModule ? false : '__moduleExports',
1663
- meta: { commonjs: { isCommonJS: !isEsModule } }
1837
+ syntheticNamedExports: isEsModule || usesRequireWrapper ? false : '__moduleExports',
1838
+ meta: { commonjs: commonjsMeta }
1664
1839
  };
1665
1840
  }
1666
1841
 
1842
+ const PLUGIN_NAME = 'commonjs';
1843
+
1667
1844
  function commonjs(options = {}) {
1668
- const extensions = options.extensions || ['.js'];
1669
- const filter = pluginutils.createFilter(options.include, options.exclude);
1670
1845
  const {
1671
1846
  ignoreGlobal,
1672
1847
  ignoreDynamicRequires,
1673
1848
  requireReturnsDefault: requireReturnsDefaultOption,
1674
1849
  esmExternals
1675
1850
  } = options;
1851
+ const extensions = options.extensions || ['.js'];
1852
+ const filter = pluginutils.createFilter(options.include, options.exclude);
1853
+ const { strictRequiresFilter, detectCyclesAndConditional } = getStrictRequiresFilter(options);
1854
+
1676
1855
  const getRequireReturnsDefault =
1677
1856
  typeof requireReturnsDefaultOption === 'function'
1678
1857
  ? requireReturnsDefaultOption
1679
1858
  : () => requireReturnsDefaultOption;
1859
+
1680
1860
  let esmExternalIds;
1681
1861
  const isEsmExternal =
1682
1862
  typeof esmExternals === 'function'
@@ -1684,20 +1864,19 @@ function commonjs(options = {}) {
1684
1864
  : Array.isArray(esmExternals)
1685
1865
  ? ((esmExternalIds = new Set(esmExternals)), (id) => esmExternalIds.has(id))
1686
1866
  : () => esmExternals;
1867
+
1687
1868
  const defaultIsModuleExports =
1688
1869
  typeof options.defaultIsModuleExports === 'boolean' ? options.defaultIsModuleExports : 'auto';
1689
1870
 
1690
- const { dynamicRequireModuleSet, dynamicRequireModuleDirPaths } = getDynamicRequirePaths(
1691
- options.dynamicRequireTargets
1871
+ const dynamicRequireRoot =
1872
+ typeof options.dynamicRequireRoot === 'string'
1873
+ ? path.resolve(options.dynamicRequireRoot)
1874
+ : process.cwd();
1875
+ const { commonDir, dynamicRequireModules } = getDynamicRequireModules(
1876
+ options.dynamicRequireTargets,
1877
+ dynamicRequireRoot
1692
1878
  );
1693
- const isDynamicRequireModulesEnabled = dynamicRequireModuleSet.size > 0;
1694
- const commonDir = isDynamicRequireModulesEnabled
1695
- ? getCommonDir__default['default'](null, Array.from(dynamicRequireModuleSet).concat(process.cwd()))
1696
- : null;
1697
-
1698
- const esModulesWithDefaultExport = new Set();
1699
- const esModulesWithNamedExports = new Set();
1700
- const commonJsMetaPromises = new Map();
1879
+ const isDynamicRequireModulesEnabled = dynamicRequireModules.size > 0;
1701
1880
 
1702
1881
  const ignoreRequire =
1703
1882
  typeof options.ignore === 'function'
@@ -1718,7 +1897,7 @@ function commonjs(options = {}) {
1718
1897
 
1719
1898
  return {
1720
1899
  canConvertRequire: mode !== 'remove' && mode !== true,
1721
- shouldRemoveRequireStatement: mode === 'remove'
1900
+ shouldRemoveRequire: mode === 'remove'
1722
1901
  };
1723
1902
  };
1724
1903
 
@@ -1726,38 +1905,52 @@ function commonjs(options = {}) {
1726
1905
 
1727
1906
  const sourceMap = options.sourceMap !== false;
1728
1907
 
1729
- function transformAndCheckExports(code, id) {
1730
- if (isDynamicRequireModulesEnabled && this.getModuleInfo(id).isEntry) {
1731
- // eslint-disable-next-line no-param-reassign
1732
- code =
1733
- getDynamicPackagesEntryIntro(dynamicRequireModuleDirPaths, dynamicRequireModuleSet) + code;
1734
- }
1908
+ // Initialized in buildStart
1909
+ let requireResolver;
1735
1910
 
1911
+ function transformAndCheckExports(code, id) {
1736
1912
  const { isEsModule, hasDefaultExport, hasNamedExports, ast } = analyzeTopLevelStatements(
1737
1913
  this.parse,
1738
1914
  code,
1739
1915
  id
1740
1916
  );
1917
+
1918
+ const commonjsMeta = this.getModuleInfo(id).meta.commonjs || {};
1741
1919
  if (hasDefaultExport) {
1742
- esModulesWithDefaultExport.add(id);
1920
+ commonjsMeta.hasDefaultExport = true;
1743
1921
  }
1744
1922
  if (hasNamedExports) {
1745
- esModulesWithNamedExports.add(id);
1923
+ commonjsMeta.hasNamedExports = true;
1746
1924
  }
1747
1925
 
1748
1926
  if (
1749
- !dynamicRequireModuleSet.has(normalizePathSlashes(id)) &&
1750
- (!hasCjsKeywords(code, ignoreGlobal) || (isEsModule && !options.transformMixedEsModules))
1927
+ !dynamicRequireModules.has(normalizePathSlashes(id)) &&
1928
+ (!(hasCjsKeywords(code, ignoreGlobal) || requireResolver.isRequiredId(id)) ||
1929
+ (isEsModule && !options.transformMixedEsModules))
1751
1930
  ) {
1752
- return { meta: { commonjs: { isCommonJS: false } } };
1931
+ commonjsMeta.isCommonJS = false;
1932
+ return { meta: { commonjs: commonjsMeta } };
1753
1933
  }
1754
1934
 
1755
- // avoid wrapping as this is a commonjsRegister call
1756
- const disableWrap = isWrappedId(id, DYNAMIC_REGISTER_SUFFIX);
1757
- if (disableWrap) {
1758
- // eslint-disable-next-line no-param-reassign
1759
- id = unwrapId(id, DYNAMIC_REGISTER_SUFFIX);
1760
- }
1935
+ const needsRequireWrapper =
1936
+ !isEsModule &&
1937
+ (dynamicRequireModules.has(normalizePathSlashes(id)) || strictRequiresFilter(id));
1938
+
1939
+ const checkDynamicRequire = (position) => {
1940
+ if (id.indexOf(dynamicRequireRoot) !== 0) {
1941
+ this.error(
1942
+ {
1943
+ code: 'DYNAMIC_REQUIRE_OUTSIDE_ROOT',
1944
+ id,
1945
+ dynamicRequireRoot,
1946
+ message: `"${id}" contains dynamic require statements but it is not within the current dynamicRequireRoot "${dynamicRequireRoot}". You should set dynamicRequireRoot to "${path.dirname(
1947
+ id
1948
+ )}" or one of its parent directories.`
1949
+ },
1950
+ position
1951
+ );
1952
+ }
1953
+ };
1761
1954
 
1762
1955
  return transformCommonjs(
1763
1956
  this.parse,
@@ -1770,64 +1963,89 @@ function commonjs(options = {}) {
1770
1963
  getIgnoreTryCatchRequireStatementMode,
1771
1964
  sourceMap,
1772
1965
  isDynamicRequireModulesEnabled,
1773
- dynamicRequireModuleSet,
1774
- disableWrap,
1966
+ dynamicRequireModules,
1775
1967
  commonDir,
1776
1968
  ast,
1777
- defaultIsModuleExports
1969
+ defaultIsModuleExports,
1970
+ needsRequireWrapper,
1971
+ requireResolver.resolveRequireSourcesAndUpdateMeta(this),
1972
+ requireResolver.isRequiredId(id),
1973
+ checkDynamicRequire,
1974
+ commonjsMeta
1778
1975
  );
1779
1976
  }
1780
1977
 
1781
1978
  return {
1782
- name: 'commonjs',
1979
+ name: PLUGIN_NAME,
1980
+
1981
+ version,
1982
+
1983
+ options(rawOptions) {
1984
+ // We inject the resolver in the beginning so that "catch-all-resolver" like node-resolver
1985
+ // do not prevent our plugin from resolving entry points ot proxies.
1986
+ const plugins = Array.isArray(rawOptions.plugins)
1987
+ ? [...rawOptions.plugins]
1988
+ : rawOptions.plugins
1989
+ ? [rawOptions.plugins]
1990
+ : [];
1991
+ plugins.unshift({
1992
+ name: 'commonjs--resolver',
1993
+ resolveId
1994
+ });
1995
+ return { ...rawOptions, plugins };
1996
+ },
1783
1997
 
1784
- buildStart() {
1785
- validateRollupVersion(this.meta.rollupVersion, peerDependencies.rollup);
1998
+ buildStart({ plugins }) {
1999
+ validateVersion(this.meta.rollupVersion, peerDependencies.rollup, 'rollup');
2000
+ const nodeResolve = plugins.find(({ name }) => name === 'node-resolve');
2001
+ if (nodeResolve) {
2002
+ validateVersion(nodeResolve.version, '^13.0.6', '@rollup/plugin-node-resolve');
2003
+ }
1786
2004
  if (options.namedExports != null) {
1787
2005
  this.warn(
1788
2006
  'The namedExports option from "@rollup/plugin-commonjs" is deprecated. Named exports are now handled automatically.'
1789
2007
  );
1790
2008
  }
2009
+ requireResolver = getRequireResolver(extensions, detectCyclesAndConditional);
1791
2010
  },
1792
2011
 
1793
- resolveId,
2012
+ buildEnd() {
2013
+ if (options.strictRequires === 'debug') {
2014
+ const wrappedIds = requireResolver.getWrappedIds();
2015
+ if (wrappedIds.length) {
2016
+ this.warn({
2017
+ code: 'WRAPPED_IDS',
2018
+ ids: wrappedIds,
2019
+ message: `The commonjs plugin automatically wrapped the following files:\n[\n${wrappedIds
2020
+ .map((id) => `\t${JSON.stringify(path.relative(process.cwd(), id))}`)
2021
+ .join(',\n')}\n]`
2022
+ });
2023
+ } else {
2024
+ this.warn({
2025
+ code: 'WRAPPED_IDS',
2026
+ ids: wrappedIds,
2027
+ message: 'The commonjs plugin did not wrap any files.'
2028
+ });
2029
+ }
2030
+ }
2031
+ },
1794
2032
 
1795
2033
  load(id) {
1796
2034
  if (id === HELPERS_ID) {
1797
- return getHelpersModule(isDynamicRequireModulesEnabled, ignoreDynamicRequires);
1798
- }
1799
-
1800
- if (id.startsWith(HELPERS_ID)) {
1801
- return getSpecificHelperProxy(id);
2035
+ return getHelpersModule();
1802
2036
  }
1803
2037
 
1804
2038
  if (isWrappedId(id, MODULE_SUFFIX)) {
1805
- const actualId = unwrapId(id, MODULE_SUFFIX);
1806
- let name = getName(actualId);
1807
- let code;
1808
- if (isDynamicRequireModulesEnabled) {
1809
- if (['modulePath', 'commonjsRequire', 'createModule'].includes(name)) {
1810
- name = `${name}_`;
1811
- }
1812
- code =
1813
- `import {commonjsRequire, createModule} from "${HELPERS_ID}";\n` +
1814
- `var ${name} = createModule(${JSON.stringify(
1815
- getVirtualPathForDynamicRequirePath(path.dirname(actualId), commonDir)
1816
- )});\n` +
1817
- `export {${name} as __module}`;
1818
- } else {
1819
- code = `var ${name} = {exports: {}}; export {${name} as __module}`;
1820
- }
2039
+ const name = getName(unwrapId(id, MODULE_SUFFIX));
1821
2040
  return {
1822
- code,
2041
+ code: `var ${name} = {exports: {}}; export {${name} as __module}`,
1823
2042
  syntheticNamedExports: '__module',
1824
2043
  meta: { commonjs: { isCommonJS: false } }
1825
2044
  };
1826
2045
  }
1827
2046
 
1828
2047
  if (isWrappedId(id, EXPORTS_SUFFIX)) {
1829
- const actualId = unwrapId(id, EXPORTS_SUFFIX);
1830
- const name = getName(actualId);
2048
+ const name = getName(unwrapId(id, EXPORTS_SUFFIX));
1831
2049
  return {
1832
2050
  code: `var ${name} = {}; export {${name} as __exports}`,
1833
2051
  meta: { commonjs: { isCommonJS: false } }
@@ -1842,69 +2060,51 @@ function commonjs(options = {}) {
1842
2060
  );
1843
2061
  }
1844
2062
 
1845
- if (id === DYNAMIC_PACKAGES_ID) {
1846
- return getDynamicPackagesModule(dynamicRequireModuleDirPaths, commonDir);
1847
- }
1848
-
1849
- if (id.startsWith(DYNAMIC_JSON_PREFIX)) {
1850
- return getDynamicJsonProxy(id, commonDir);
2063
+ // entry suffix is just appended to not mess up relative external resolution
2064
+ if (id.endsWith(ENTRY_SUFFIX)) {
2065
+ return getEntryProxy(
2066
+ id.slice(0, -ENTRY_SUFFIX.length),
2067
+ defaultIsModuleExports,
2068
+ this.getModuleInfo
2069
+ );
1851
2070
  }
1852
2071
 
1853
- if (isDynamicModuleImport(id, dynamicRequireModuleSet)) {
1854
- return `export default require(${JSON.stringify(normalizePathSlashes(id))});`;
2072
+ if (isWrappedId(id, ES_IMPORT_SUFFIX)) {
2073
+ return getEsImportProxy(unwrapId(id, ES_IMPORT_SUFFIX), defaultIsModuleExports);
1855
2074
  }
1856
2075
 
1857
- if (isWrappedId(id, DYNAMIC_REGISTER_SUFFIX)) {
1858
- return getDynamicRequireProxy(
1859
- normalizePathSlashes(unwrapId(id, DYNAMIC_REGISTER_SUFFIX)),
1860
- commonDir
2076
+ if (id === DYNAMIC_MODULES_ID) {
2077
+ return getDynamicModuleRegistry(
2078
+ isDynamicRequireModulesEnabled,
2079
+ dynamicRequireModules,
2080
+ commonDir,
2081
+ ignoreDynamicRequires
1861
2082
  );
1862
2083
  }
1863
2084
 
1864
2085
  if (isWrappedId(id, PROXY_SUFFIX)) {
1865
2086
  const actualId = unwrapId(id, PROXY_SUFFIX);
1866
- return getStaticRequireProxy(
1867
- actualId,
1868
- getRequireReturnsDefault(actualId),
1869
- esModulesWithDefaultExport,
1870
- esModulesWithNamedExports,
1871
- commonJsMetaPromises
1872
- );
2087
+ return getStaticRequireProxy(actualId, getRequireReturnsDefault(actualId), this.load);
1873
2088
  }
1874
2089
 
1875
2090
  return null;
1876
2091
  },
1877
2092
 
1878
- transform(code, rawId) {
1879
- let id = rawId;
1880
-
1881
- if (isWrappedId(id, DYNAMIC_REGISTER_SUFFIX)) {
1882
- id = unwrapId(id, DYNAMIC_REGISTER_SUFFIX);
1883
- }
2093
+ shouldTransformCachedModule(...args) {
2094
+ return requireResolver.shouldTransformCachedModule.call(this, ...args);
2095
+ },
1884
2096
 
2097
+ transform(code, id) {
1885
2098
  const extName = path.extname(id);
1886
- if (
1887
- extName !== '.cjs' &&
1888
- id !== DYNAMIC_PACKAGES_ID &&
1889
- !id.startsWith(DYNAMIC_JSON_PREFIX) &&
1890
- (!filter(id) || !extensions.includes(extName))
1891
- ) {
2099
+ if (extName !== '.cjs' && (!filter(id) || !extensions.includes(extName))) {
1892
2100
  return null;
1893
2101
  }
1894
2102
 
1895
2103
  try {
1896
- return transformAndCheckExports.call(this, code, rawId);
2104
+ return transformAndCheckExports.call(this, code, id);
1897
2105
  } catch (err) {
1898
2106
  return this.error(err, err.loc);
1899
2107
  }
1900
- },
1901
-
1902
- moduleParsed({ id, meta: { commonjs: commonjsMeta } }) {
1903
- if (commonjsMeta && commonjsMeta.isCommonJS != null) {
1904
- setCommonJSMetaPromise(commonJsMetaPromises, id, commonjsMeta);
1905
- return;
1906
- }
1907
- setCommonJSMetaPromise(commonJsMetaPromises, id, null);
1908
2108
  }
1909
2109
  };
1910
2110
  }