UNPKG

60.3 kBJavaScriptView Raw
1'use strict';
2
3var path = require('path');
4var pluginutils = require('@rollup/pluginutils');
5var getCommonDir = require('commondir');
6var fs = require('fs');
7var glob = require('glob');
8var estreeWalker = require('estree-walker');
9var MagicString = require('magic-string');
10var isReference = require('is-reference');
11var resolve = require('resolve');
12
13function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
14
15var getCommonDir__default = /*#__PURE__*/_interopDefaultLegacy(getCommonDir);
16var glob__default = /*#__PURE__*/_interopDefaultLegacy(glob);
17var MagicString__default = /*#__PURE__*/_interopDefaultLegacy(MagicString);
18var isReference__default = /*#__PURE__*/_interopDefaultLegacy(isReference);
19
20var peerDependencies = {
21 rollup: "^2.38.3"
22};
23
24function tryParse(parse, code, id) {
25 try {
26 return parse(code, { allowReturnOutsideFunction: true });
27 } catch (err) {
28 err.message += ` in ${id}`;
29 throw err;
30 }
31}
32
33const firstpassGlobal = /\b(?:require|module|exports|global)\b/;
34
35const firstpassNoGlobal = /\b(?:require|module|exports)\b/;
36
37function hasCjsKeywords(code, ignoreGlobal) {
38 const firstpass = ignoreGlobal ? firstpassNoGlobal : firstpassGlobal;
39 return firstpass.test(code);
40}
41
42/* eslint-disable no-underscore-dangle */
43
44function analyzeTopLevelStatements(parse, code, id) {
45 const ast = tryParse(parse, code, id);
46
47 let isEsModule = false;
48 let hasDefaultExport = false;
49 let hasNamedExports = false;
50
51 for (const node of ast.body) {
52 switch (node.type) {
53 case 'ExportDefaultDeclaration':
54 isEsModule = true;
55 hasDefaultExport = true;
56 break;
57 case 'ExportNamedDeclaration':
58 isEsModule = true;
59 if (node.declaration) {
60 hasNamedExports = true;
61 } else {
62 for (const specifier of node.specifiers) {
63 if (specifier.exported.name === 'default') {
64 hasDefaultExport = true;
65 } else {
66 hasNamedExports = true;
67 }
68 }
69 }
70 break;
71 case 'ExportAllDeclaration':
72 isEsModule = true;
73 if (node.exported && node.exported.name === 'default') {
74 hasDefaultExport = true;
75 } else {
76 hasNamedExports = true;
77 }
78 break;
79 case 'ImportDeclaration':
80 isEsModule = true;
81 break;
82 }
83 }
84
85 return { isEsModule, hasDefaultExport, hasNamedExports, ast };
86}
87
88const isWrappedId = (id, suffix) => id.endsWith(suffix);
89const wrapId = (id, suffix) => `\0${id}${suffix}`;
90const unwrapId = (wrappedId, suffix) => wrappedId.slice(1, -suffix.length);
91
92const PROXY_SUFFIX = '?commonjs-proxy';
93const REQUIRE_SUFFIX = '?commonjs-require';
94const EXTERNAL_SUFFIX = '?commonjs-external';
95const EXPORTS_SUFFIX = '?commonjs-exports';
96const MODULE_SUFFIX = '?commonjs-module';
97
98const DYNAMIC_REGISTER_SUFFIX = '?commonjs-dynamic-register';
99const DYNAMIC_JSON_PREFIX = '\0commonjs-dynamic-json:';
100const DYNAMIC_PACKAGES_ID = '\0commonjs-dynamic-packages';
101
102const 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
109const HELPERS = `
110export var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
111
112export function getDefaultExportFromCjs (x) {
113 return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
114}
115
116export function getDefaultExportFromNamespaceIfPresent (n) {
117 return n && Object.prototype.hasOwnProperty.call(n, 'default') ? n['default'] : n;
118}
119
120export function getDefaultExportFromNamespaceIfNotNamed (n) {
121 return n && Object.prototype.hasOwnProperty.call(n, 'default') && Object.keys(n).length === 1 ? n['default'] : n;
122}
123
124export 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
140const 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
142const HELPER_NON_DYNAMIC = `
143export function commonjsRequire (path) {
144 ${FAILED_REQUIRE_ERROR}
145}
146`;
147
148const getDynamicHelpers = (ignoreDynamicRequires) => `
149export 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
159export function commonjsRegister (path, loader) {
160 DYNAMIC_REQUIRE_LOADERS[path] = loader;
161}
162
163export function commonjsRegisterOrShort (path, to) {
164 var 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
172var DYNAMIC_REQUIRE_LOADERS = Object.create(null);
173var DYNAMIC_REQUIRE_CACHE = Object.create(null);
174var DYNAMIC_REQUIRE_SHORTS = Object.create(null);
175var DEFAULT_PARENT_MODULE = {
176 id: '<' + 'rollup>', exports: {}, parent: undefined, filename: null, loaded: false, children: [], paths: []
177};
178var CHECKED_EXTENSIONS = ['', '.js', '.json'];
179
180function normalize (path) {
181 path = path.replace(/\\\\/g, '/');
182 var parts = path.split('/');
183 var slashed = parts[0] === '';
184 for (var i = 1; i < parts.length; i++) {
185 if (parts[i] === '.' || parts[i] === '') {
186 parts.splice(i--, 1);
187 }
188 }
189 for (var 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
204function join () {
205 if (arguments.length === 0)
206 return '.';
207 var joined;
208 for (var i = 0; i < arguments.length; ++i) {
209 var 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
223function isPossibleNodeModulesPath (modulePath) {
224 var c0 = modulePath[0];
225 if (c0 === '/' || c0 === '\\\\') return false;
226 var 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
234function dirname (path) {
235 if (path.length === 0)
236 return '.';
237
238 var i = path.length - 1;
239 while (i > 0) {
240 var 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
255export function commonjsResolveImpl (path, originalModuleDir, testCache) {
256 var shouldTryNodeModules = isPossibleNodeModulesPath(path);
257 path = normalize(path);
258 var 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 (var extensionIndex = 0; extensionIndex < CHECKED_EXTENSIONS.length; extensionIndex++) {
276 var 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 var nextDir = normalize(originalModuleDir + '/..');
289 if (nextDir === originalModuleDir) break;
290 originalModuleDir = nextDir;
291 }
292 return null;
293}
294
295export function commonjsResolve (path, originalModuleDir) {
296 var resolvedPath = commonjsResolveImpl(path, originalModuleDir);
297 if (resolvedPath !== null) {
298 return resolvedPath;
299 }
300 return require.resolve(path);
301}
302
303export function commonjsRequire (path, originalModuleDir) {
304 var resolvedPath = commonjsResolveImpl(path, originalModuleDir, true);
305 if (resolvedPath !== null) {
306 var cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath];
307 if (cachedModule) return cachedModule.exports;
308 var 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 var 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
343commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE;
344commonjsRequire.resolve = commonjsResolve;
345`;
346
347function getHelpersModule(isDynamicRequireModulesEnabled, ignoreDynamicRequires) {
348 return `${HELPERS}${
349 isDynamicRequireModulesEnabled ? getDynamicHelpers(ignoreDynamicRequires) : HELPER_NON_DYNAMIC
350 }`;
351}
352
353/* eslint-disable import/prefer-default-export */
354
355function deconflict(scopes, globals, identifier) {
356 let i = 1;
357 let deconflicted = pluginutils.makeLegalIdentifier(identifier);
358 const hasConflicts = () =>
359 scopes.some((scope) => scope.contains(deconflicted)) || globals.has(deconflicted);
360
361 while (hasConflicts()) {
362 deconflicted = pluginutils.makeLegalIdentifier(`${identifier}_${i}`);
363 i += 1;
364 }
365
366 for (const scope of scopes) {
367 scope.declarations[deconflicted] = true;
368 }
369
370 return deconflicted;
371}
372
373function getName(id) {
374 const name = pluginutils.makeLegalIdentifier(path.basename(id, path.extname(id)));
375 if (name !== 'index') {
376 return name;
377 }
378 return pluginutils.makeLegalIdentifier(path.basename(path.dirname(id)));
379}
380
381function normalizePathSlashes(path) {
382 return path.replace(/\\/g, '/');
383}
384
385const VIRTUAL_PATH_BASE = '/$$rollup_base$$';
386const getVirtualPathForDynamicRequirePath = (path, commonDir) => {
387 const normalizedPath = normalizePathSlashes(path);
388 return normalizedPath.startsWith(commonDir)
389 ? VIRTUAL_PATH_BASE + normalizedPath.slice(commonDir.length)
390 : normalizedPath;
391};
392
393function getPackageEntryPoint(dirPath) {
394 let entryPoint = 'index.js';
395
396 try {
397 if (fs.existsSync(path.join(dirPath, 'package.json'))) {
398 entryPoint =
399 JSON.parse(fs.readFileSync(path.join(dirPath, 'package.json'), { encoding: 'utf8' })).main ||
400 entryPoint;
401 }
402 } catch (ignored) {
403 // ignored
404 }
405
406 return entryPoint;
407}
408
409function 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
421function 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
439function isDynamicModuleImport(id, dynamicRequireModuleSet) {
440 const normalizedPath = normalizePathSlashes(id);
441 return dynamicRequireModuleSet.has(normalizedPath) && !normalizedPath.endsWith('.json');
442}
443
444function isDirectory(path) {
445 try {
446 if (fs.statSync(path).isDirectory()) return true;
447 } catch (ignored) {
448 // Nothing to do here
449 }
450 return false;
451}
452
453function getDynamicRequirePaths(patterns) {
454 const dynamicRequireModuleSet = new Set();
455 for (const pattern of !patterns || Array.isArray(patterns) ? patterns || [] : [patterns]) {
456 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)))));
462 }
463 }
464 }
465 const dynamicRequireModuleDirPaths = Array.from(dynamicRequireModuleSet.values()).filter((path) =>
466 isDirectory(path)
467 );
468 return { dynamicRequireModuleSet, dynamicRequireModuleDirPaths };
469}
470
471function getCommonJSMetaPromise(commonJSMetaPromises, id) {
472 let commonJSMetaPromise = commonJSMetaPromises.get(id);
473 if (commonJSMetaPromise) return commonJSMetaPromise.promise;
474
475 const promise = new Promise((resolve) => {
476 commonJSMetaPromise = {
477 resolve,
478 promise: null
479 };
480 commonJSMetaPromises.set(id, commonJSMetaPromise);
481 });
482 commonJSMetaPromise.promise = promise;
483
484 return promise;
485}
486
487function 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 }
497}
498
499// e.g. id === "commonjsHelpers?commonjsRegister"
500function getSpecificHelperProxy(id) {
501 return `export {${id.split('?')[1]} as default} from "${HELPERS_ID}";`;
502}
503
504function getUnknownRequireProxy(id, requireReturnsDefault) {
505 if (requireReturnsDefault === true || id.endsWith('.json')) {
506 return `export {default} from ${JSON.stringify(id)};`;
507 }
508 const name = getName(id);
509 const exported =
510 requireReturnsDefault === 'auto'
511 ? `import {getDefaultExportFromNamespaceIfNotNamed} from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfNotNamed(${name});`
512 : requireReturnsDefault === 'preferred'
513 ? `import {getDefaultExportFromNamespaceIfPresent} from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfPresent(${name});`
514 : !requireReturnsDefault
515 ? `import {getAugmentedNamespace} from "${HELPERS_ID}"; export default /*@__PURE__*/getAugmentedNamespace(${name});`
516 : `export default ${name};`;
517 return `import * as ${name} from ${JSON.stringify(id)}; ${exported}`;
518}
519
520function 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
529function 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
537async function getStaticRequireProxy(
538 id,
539 requireReturnsDefault,
540 esModulesWithDefaultExport,
541 esModulesWithNamedExports,
542 commonJsMetaPromises
543) {
544 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) {
549 return getUnknownRequireProxy(id, requireReturnsDefault);
550 } else if (!requireReturnsDefault) {
551 return `import { getAugmentedNamespace } from "${HELPERS_ID}"; import * as ${name} from ${JSON.stringify(
552 id
553 )}; export default /*@__PURE__*/getAugmentedNamespace(${name});`;
554 } else if (
555 requireReturnsDefault !== true &&
556 (requireReturnsDefault === 'namespace' ||
557 !esModulesWithDefaultExport.has(id) ||
558 (requireReturnsDefault === 'auto' && esModulesWithNamedExports.has(id)))
559 ) {
560 return `import * as ${name} from ${JSON.stringify(id)}; export default ${name};`;
561 }
562 return `export { default } from ${JSON.stringify(id)};`;
563}
564
565/* eslint-disable no-param-reassign, no-undefined */
566
567function getCandidatesForExtension(resolved, extension) {
568 return [resolved + extension, `${resolved}${path.sep}index${extension}`];
569}
570
571function getCandidates(resolved, extensions) {
572 return extensions.reduce(
573 (paths, extension) => paths.concat(getCandidatesForExtension(resolved, extension)),
574 [resolved]
575 );
576}
577
578function getResolveId(extensions) {
579 function resolveExtensions(importee, importer) {
580 // not our problem
581 if (importee[0] !== '.' || !importer) return undefined;
582
583 const resolved = path.resolve(path.dirname(importer), importee);
584 const candidates = getCandidates(resolved, extensions);
585
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 */
592 }
593 }
594
595 return undefined;
596 }
597
598 return function resolveId(importee, rawImporter, resolveOptions) {
599 if (isWrappedId(importee, MODULE_SUFFIX) || isWrappedId(importee, EXPORTS_SUFFIX)) {
600 return importee;
601 }
602
603 const importer =
604 rawImporter && isWrappedId(rawImporter, DYNAMIC_REGISTER_SUFFIX)
605 ? unwrapId(rawImporter, DYNAMIC_REGISTER_SUFFIX)
606 : rawImporter;
607
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;
612 }
613
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);
622
623 isModuleRegistration = isWrappedId(importee, DYNAMIC_REGISTER_SUFFIX);
624 if (isModuleRegistration) {
625 importee = unwrapId(importee, DYNAMIC_REGISTER_SUFFIX);
626 }
627 }
628
629 if (
630 importee.startsWith(HELPERS_ID) ||
631 importee === DYNAMIC_PACKAGES_ID ||
632 importee.startsWith(DYNAMIC_JSON_PREFIX)
633 ) {
634 return importee;
635 }
636
637 if (importee.startsWith('\0')) {
638 return null;
639 }
640
641 return this.resolve(
642 importee,
643 importer,
644 Object.assign({}, resolveOptions, {
645 skipSelf: true,
646 custom: Object.assign({}, resolveOptions.custom, {
647 'node-resolve': { isRequire: isProxyModule || isRequiredModule }
648 })
649 })
650 ).then((resolved) => {
651 if (!resolved) {
652 resolved = resolveExtensions(importee, importer);
653 }
654 if (resolved && isProxyModule) {
655 resolved.id = wrapId(resolved.id, resolved.external ? EXTERNAL_SUFFIX : PROXY_SUFFIX);
656 resolved.external = false;
657 } else if (resolved && isModuleRegistration) {
658 resolved.id = wrapId(resolved.id, DYNAMIC_REGISTER_SUFFIX);
659 } else if (!resolved && (isProxyModule || isRequiredModule)) {
660 return { id: wrapId(importee, EXTERNAL_SUFFIX), external: false };
661 }
662 return resolved;
663 });
664 };
665}
666
667function validateRollupVersion(rollupVersion, peerDependencyVersion) {
668 const [major, minor] = rollupVersion.split('.').map(Number);
669 const versionRegexp = /\^(\d+\.\d+)\.\d+/g;
670 let minMajor = Infinity;
671 let minMinor = Infinity;
672 let foundVersion;
673 // eslint-disable-next-line no-cond-assign
674 while ((foundVersion = versionRegexp.exec(peerDependencyVersion))) {
675 const [foundMajor, foundMinor] = foundVersion[1].split('.').map(Number);
676 if (foundMajor < minMajor) {
677 minMajor = foundMajor;
678 minMinor = foundMinor;
679 }
680 }
681 if (major < minMajor || (major === minMajor && minor < minMinor)) {
682 throw new Error(
683 `Insufficient Rollup version: "@rollup/plugin-commonjs" requires at least rollup@${minMajor}.${minMinor} but found rollup@${rollupVersion}.`
684 );
685 }
686}
687
688const operators = {
689 '==': (x) => equals(x.left, x.right, false),
690
691 '!=': (x) => not(operators['=='](x)),
692
693 '===': (x) => equals(x.left, x.right, true),
694
695 '!==': (x) => not(operators['==='](x)),
696
697 '!': (x) => isFalsy(x.argument),
698
699 '&&': (x) => isTruthy(x.left) && isTruthy(x.right),
700
701 '||': (x) => isTruthy(x.left) || isTruthy(x.right)
702};
703
704function not(value) {
705 return value === null ? value : !value;
706}
707
708function equals(a, b, strict) {
709 if (a.type !== b.type) return null;
710 // eslint-disable-next-line eqeqeq
711 if (a.type === 'Literal') return strict ? a.value === b.value : a.value == b.value;
712 return null;
713}
714
715function isTruthy(node) {
716 if (!node) return false;
717 if (node.type === 'Literal') return !!node.value;
718 if (node.type === 'ParenthesizedExpression') return isTruthy(node.expression);
719 if (node.operator in operators) return operators[node.operator](node);
720 return null;
721}
722
723function isFalsy(node) {
724 return not(isTruthy(node));
725}
726
727function getKeypath(node) {
728 const parts = [];
729
730 while (node.type === 'MemberExpression') {
731 if (node.computed) return null;
732
733 parts.unshift(node.property.name);
734 // eslint-disable-next-line no-param-reassign
735 node = node.object;
736 }
737
738 if (node.type !== 'Identifier') return null;
739
740 const { name } = node;
741 parts.unshift(name);
742
743 return { name, keypath: parts.join('.') };
744}
745
746const KEY_COMPILED_ESM = '__esModule';
747
748function isDefineCompiledEsm(node) {
749 const definedProperty =
750 getDefinePropertyCallName(node, 'exports') || getDefinePropertyCallName(node, 'module.exports');
751 if (definedProperty && definedProperty.key === KEY_COMPILED_ESM) {
752 return isTruthy(definedProperty.value);
753 }
754 return false;
755}
756
757function getDefinePropertyCallName(node, targetName) {
758 const {
759 callee: { object, property }
760 } = node;
761 if (!object || object.type !== 'Identifier' || object.name !== 'Object') return;
762 if (!property || property.type !== 'Identifier' || property.name !== 'defineProperty') return;
763 if (node.arguments.length !== 3) return;
764
765 const targetNames = targetName.split('.');
766 const [target, key, value] = node.arguments;
767 if (targetNames.length === 1) {
768 if (target.type !== 'Identifier' || target.name !== targetNames[0]) {
769 return;
770 }
771 }
772
773 if (targetNames.length === 2) {
774 if (
775 target.type !== 'MemberExpression' ||
776 target.object.name !== targetNames[0] ||
777 target.property.name !== targetNames[1]
778 ) {
779 return;
780 }
781 }
782
783 if (value.type !== 'ObjectExpression' || !value.properties) return;
784
785 const valueProperty = value.properties.find((p) => p.key && p.key.name === 'value');
786 if (!valueProperty || !valueProperty.value) return;
787
788 // eslint-disable-next-line consistent-return
789 return { key: key.value, value: valueProperty.value };
790}
791
792function isShorthandProperty(parent) {
793 return parent && parent.type === 'Property' && parent.shorthand;
794}
795
796function hasDefineEsmProperty(node) {
797 return node.properties.some((property) => {
798 if (
799 property.type === 'Property' &&
800 property.key.type === 'Identifier' &&
801 property.key.name === '__esModule' &&
802 isTruthy(property.value)
803 ) {
804 return true;
805 }
806 return false;
807 });
808}
809
810function wrapCode(magicString, uses, moduleName, exportsName) {
811 const args = [];
812 const passedArgs = [];
813 if (uses.module) {
814 args.push('module');
815 passedArgs.push(moduleName);
816 }
817 if (uses.exports) {
818 args.push('exports');
819 passedArgs.push(exportsName);
820 }
821 magicString
822 .trim()
823 .prepend(`(function (${args.join(', ')}) {\n`)
824 .append(`\n}(${passedArgs.join(', ')}));`);
825}
826
827function rewriteExportsAndGetExportsBlock(
828 magicString,
829 moduleName,
830 exportsName,
831 wrapped,
832 moduleExportsAssignments,
833 firstTopLevelModuleExportsAssignment,
834 exportsAssignmentsByName,
835 topLevelAssignments,
836 defineCompiledEsmExpressions,
837 deconflictedExportNames,
838 code,
839 HELPERS_NAME,
840 exportMode,
841 detectWrappedDefault,
842 defaultIsModuleExports
843) {
844 const exports = [];
845 const exportDeclarations = [];
846
847 if (exportMode === 'replace') {
848 getExportsForReplacedModuleExports(
849 magicString,
850 exports,
851 exportDeclarations,
852 moduleExportsAssignments,
853 firstTopLevelModuleExportsAssignment,
854 exportsName
855 );
856 } else {
857 exports.push(`${exportsName} as __moduleExports`);
858 if (wrapped) {
859 getExportsWhenWrapping(
860 exportDeclarations,
861 exportsName,
862 detectWrappedDefault,
863 HELPERS_NAME,
864 defaultIsModuleExports
865 );
866 } else {
867 getExports(
868 magicString,
869 exports,
870 exportDeclarations,
871 moduleExportsAssignments,
872 exportsAssignmentsByName,
873 deconflictedExportNames,
874 topLevelAssignments,
875 moduleName,
876 exportsName,
877 defineCompiledEsmExpressions,
878 HELPERS_NAME,
879 defaultIsModuleExports
880 );
881 }
882 }
883 if (exports.length) {
884 exportDeclarations.push(`export { ${exports.join(', ')} };`);
885 }
886
887 return `\n\n${exportDeclarations.join('\n')}`;
888}
889
890function getExportsForReplacedModuleExports(
891 magicString,
892 exports,
893 exportDeclarations,
894 moduleExportsAssignments,
895 firstTopLevelModuleExportsAssignment,
896 exportsName
897) {
898 for (const { left } of moduleExportsAssignments) {
899 magicString.overwrite(left.start, left.end, exportsName);
900 }
901 magicString.prependRight(firstTopLevelModuleExportsAssignment.left.start, 'var ');
902 exports.push(`${exportsName} as __moduleExports`);
903 exportDeclarations.push(`export default ${exportsName};`);
904}
905
906function getExportsWhenWrapping(
907 exportDeclarations,
908 exportsName,
909 detectWrappedDefault,
910 HELPERS_NAME,
911 defaultIsModuleExports
912) {
913 exportDeclarations.push(
914 `export default ${
915 detectWrappedDefault && defaultIsModuleExports === 'auto'
916 ? `/*@__PURE__*/${HELPERS_NAME}.getDefaultExportFromCjs(${exportsName})`
917 : defaultIsModuleExports === false
918 ? `${exportsName}.default`
919 : exportsName
920 };`
921 );
922}
923
924function getExports(
925 magicString,
926 exports,
927 exportDeclarations,
928 moduleExportsAssignments,
929 exportsAssignmentsByName,
930 deconflictedExportNames,
931 topLevelAssignments,
932 moduleName,
933 exportsName,
934 defineCompiledEsmExpressions,
935 HELPERS_NAME,
936 defaultIsModuleExports
937) {
938 let deconflictedDefaultExportName;
939 // Collect and rewrite module.exports assignments
940 for (const { left } of moduleExportsAssignments) {
941 magicString.overwrite(left.start, left.end, `${moduleName}.exports`);
942 }
943
944 // Collect and rewrite named exports
945 for (const [exportName, { nodes }] of exportsAssignmentsByName) {
946 const deconflicted = deconflictedExportNames[exportName];
947 let needsDeclaration = true;
948 for (const node of nodes) {
949 let replacement = `${deconflicted} = ${exportsName}.${exportName}`;
950 if (needsDeclaration && topLevelAssignments.has(node)) {
951 replacement = `var ${replacement}`;
952 needsDeclaration = false;
953 }
954 magicString.overwrite(node.start, node.left.end, replacement);
955 }
956 if (needsDeclaration) {
957 magicString.prepend(`var ${deconflicted};\n`);
958 }
959
960 if (exportName === 'default') {
961 deconflictedDefaultExportName = deconflicted;
962 } else {
963 exports.push(exportName === deconflicted ? exportName : `${deconflicted} as ${exportName}`);
964 }
965 }
966
967 // Collect and rewrite exports.__esModule assignments
968 let isRestorableCompiledEsm = false;
969 for (const expression of defineCompiledEsmExpressions) {
970 isRestorableCompiledEsm = true;
971 const moduleExportsExpression =
972 expression.type === 'CallExpression' ? expression.arguments[0] : expression.left.object;
973 magicString.overwrite(moduleExportsExpression.start, moduleExportsExpression.end, exportsName);
974 }
975
976 if (!isRestorableCompiledEsm || defaultIsModuleExports === true) {
977 exportDeclarations.push(`export default ${exportsName};`);
978 } else if (moduleExportsAssignments.length === 0 || defaultIsModuleExports === false) {
979 exports.push(`${deconflictedDefaultExportName || exportsName} as default`);
980 } else {
981 exportDeclarations.push(
982 `export default /*@__PURE__*/${HELPERS_NAME}.getDefaultExportFromCjs(${exportsName});`
983 );
984 }
985}
986
987function isRequireStatement(node, scope) {
988 if (!node) return false;
989 if (node.type !== 'CallExpression') return false;
990
991 // Weird case of `require()` or `module.require()` without arguments
992 if (node.arguments.length === 0) return false;
993
994 return isRequire(node.callee, scope);
995}
996
997function isRequire(node, scope) {
998 return (
999 (node.type === 'Identifier' && node.name === 'require' && !scope.contains('require')) ||
1000 (node.type === 'MemberExpression' && isModuleRequire(node, scope))
1001 );
1002}
1003
1004function isModuleRequire({ object, property }, scope) {
1005 return (
1006 object.type === 'Identifier' &&
1007 object.name === 'module' &&
1008 property.type === 'Identifier' &&
1009 property.name === 'require' &&
1010 !scope.contains('module')
1011 );
1012}
1013
1014function isStaticRequireStatement(node, scope) {
1015 if (!isRequireStatement(node, scope)) return false;
1016 return !hasDynamicArguments(node);
1017}
1018
1019function hasDynamicArguments(node) {
1020 return (
1021 node.arguments.length > 1 ||
1022 (node.arguments[0].type !== 'Literal' &&
1023 (node.arguments[0].type !== 'TemplateLiteral' || node.arguments[0].expressions.length > 0))
1024 );
1025}
1026
1027const reservedMethod = { resolve: true, cache: true, main: true };
1028
1029function isNodeRequirePropertyAccess(parent) {
1030 return parent && parent.property && reservedMethod[parent.property.name];
1031}
1032
1033function isIgnoredRequireStatement(requiredNode, ignoreRequire) {
1034 return ignoreRequire(requiredNode.arguments[0].value);
1035}
1036
1037function getRequireStringArg(node) {
1038 return node.arguments[0].type === 'Literal'
1039 ? node.arguments[0].value
1040 : node.arguments[0].quasis[0].value.cooked;
1041}
1042
1043function hasDynamicModuleForPath(source, id, dynamicRequireModuleSet) {
1044 if (!/^(?:\.{0,2}[/\\]|[A-Za-z]:[/\\])/.test(source)) {
1045 try {
1046 const resolvedPath = normalizePathSlashes(resolve.sync(source, { basedir: path.dirname(id) }));
1047 if (dynamicRequireModuleSet.has(resolvedPath)) {
1048 return true;
1049 }
1050 } catch (ex) {
1051 // Probably a node.js internal module
1052 return false;
1053 }
1054
1055 return false;
1056 }
1057
1058 for (const attemptExt of ['', '.js', '.json']) {
1059 const resolvedPath = normalizePathSlashes(path.resolve(path.dirname(id), source + attemptExt));
1060 if (dynamicRequireModuleSet.has(resolvedPath)) {
1061 return true;
1062 }
1063 }
1064
1065 return false;
1066}
1067
1068function getRequireHandlers() {
1069 const requiredSources = [];
1070 const requiredBySource = Object.create(null);
1071 const requiredByNode = new Map();
1072 const requireExpressionsWithUsedReturnValue = [];
1073
1074 function addRequireStatement(sourceId, node, scope, usesReturnValue) {
1075 const required = getRequired(sourceId);
1076 requiredByNode.set(node, { scope, required });
1077 if (usesReturnValue) {
1078 required.nodesUsingRequired.push(node);
1079 requireExpressionsWithUsedReturnValue.push(node);
1080 }
1081 }
1082
1083 function getRequired(sourceId) {
1084 if (!requiredBySource[sourceId]) {
1085 requiredSources.push(sourceId);
1086
1087 requiredBySource[sourceId] = {
1088 source: sourceId,
1089 name: null,
1090 nodesUsingRequired: []
1091 };
1092 }
1093
1094 return requiredBySource[sourceId];
1095 }
1096
1097 function rewriteRequireExpressionsAndGetImportBlock(
1098 magicString,
1099 topLevelDeclarations,
1100 topLevelRequireDeclarators,
1101 reassignedNames,
1102 helpersName,
1103 dynamicRegisterSources,
1104 moduleName,
1105 exportsName,
1106 id,
1107 exportMode
1108 ) {
1109 setRemainingImportNamesAndRewriteRequires(
1110 requireExpressionsWithUsedReturnValue,
1111 requiredByNode,
1112 magicString
1113 );
1114 const imports = [];
1115 imports.push(`import * as ${helpersName} from "${HELPERS_ID}";`);
1116 if (exportMode === 'module') {
1117 imports.push(
1118 `import { __module as ${moduleName}, exports as ${exportsName} } from ${JSON.stringify(
1119 wrapId(id, MODULE_SUFFIX)
1120 )}`
1121 );
1122 } else if (exportMode === 'exports') {
1123 imports.push(
1124 `import { __exports as ${exportsName} } from ${JSON.stringify(wrapId(id, EXPORTS_SUFFIX))}`
1125 );
1126 }
1127 for (const source of dynamicRegisterSources) {
1128 imports.push(`import ${JSON.stringify(wrapId(source, REQUIRE_SUFFIX))};`);
1129 }
1130 for (const source of requiredSources) {
1131 if (!source.startsWith('\0')) {
1132 imports.push(`import ${JSON.stringify(wrapId(source, REQUIRE_SUFFIX))};`);
1133 }
1134 const { name, nodesUsingRequired } = requiredBySource[source];
1135 imports.push(
1136 `import ${nodesUsingRequired.length ? `${name} from ` : ''}${JSON.stringify(
1137 source.startsWith('\0') ? source : wrapId(source, PROXY_SUFFIX)
1138 )};`
1139 );
1140 }
1141 return imports.length ? `${imports.join('\n')}\n\n` : '';
1142 }
1143
1144 return {
1145 addRequireStatement,
1146 requiredSources,
1147 rewriteRequireExpressionsAndGetImportBlock
1148 };
1149}
1150
1151function setRemainingImportNamesAndRewriteRequires(
1152 requireExpressionsWithUsedReturnValue,
1153 requiredByNode,
1154 magicString
1155) {
1156 let uid = 0;
1157 for (const requireExpression of requireExpressionsWithUsedReturnValue) {
1158 const { required } = requiredByNode.get(requireExpression);
1159 if (!required.name) {
1160 let potentialName;
1161 const isUsedName = (node) => requiredByNode.get(node).scope.contains(potentialName);
1162 do {
1163 potentialName = `require$$${uid}`;
1164 uid += 1;
1165 } while (required.nodesUsingRequired.some(isUsedName));
1166 required.name = potentialName;
1167 }
1168 magicString.overwrite(requireExpression.start, requireExpression.end, required.name);
1169 }
1170}
1171
1172/* eslint-disable no-param-reassign, no-shadow, no-underscore-dangle, no-continue */
1173
1174const exportsPattern = /^(?:module\.)?exports(?:\.([a-zA-Z_$][a-zA-Z_$0-9]*))?$/;
1175
1176const functionType = /^(?:FunctionDeclaration|FunctionExpression|ArrowFunctionExpression)$/;
1177
1178function transformCommonjs(
1179 parse,
1180 code,
1181 id,
1182 isEsModule,
1183 ignoreGlobal,
1184 ignoreRequire,
1185 ignoreDynamicRequires,
1186 getIgnoreTryCatchRequireStatementMode,
1187 sourceMap,
1188 isDynamicRequireModulesEnabled,
1189 dynamicRequireModuleSet,
1190 disableWrap,
1191 commonDir,
1192 astCache,
1193 defaultIsModuleExports
1194) {
1195 const ast = astCache || tryParse(parse, code, id);
1196 const magicString = new MagicString__default["default"](code);
1197 const uses = {
1198 module: false,
1199 exports: false,
1200 global: false,
1201 require: false
1202 };
1203 let usesDynamicRequire = false;
1204 const virtualDynamicRequirePath =
1205 isDynamicRequireModulesEnabled && getVirtualPathForDynamicRequirePath(path.dirname(id), commonDir);
1206 let scope = pluginutils.attachScopes(ast, 'scope');
1207 let lexicalDepth = 0;
1208 let programDepth = 0;
1209 let currentTryBlockEnd = null;
1210 let shouldWrap = false;
1211
1212 const globals = new Set();
1213
1214 // TODO technically wrong since globals isn't populated yet, but ¯\_(ツ)_/¯
1215 const HELPERS_NAME = deconflict([scope], globals, 'commonjsHelpers');
1216 const dynamicRegisterSources = new Set();
1217 let hasRemovedRequire = false;
1218
1219 const {
1220 addRequireStatement,
1221 requiredSources,
1222 rewriteRequireExpressionsAndGetImportBlock
1223 } = getRequireHandlers();
1224
1225 // See which names are assigned to. This is necessary to prevent
1226 // illegally replacing `var foo = require('foo')` with `import foo from 'foo'`,
1227 // where `foo` is later reassigned. (This happens in the wild. CommonJS, sigh)
1228 const reassignedNames = new Set();
1229 const topLevelDeclarations = [];
1230 const topLevelRequireDeclarators = new Set();
1231 const skippedNodes = new Set();
1232 const moduleAccessScopes = new Set([scope]);
1233 const exportsAccessScopes = new Set([scope]);
1234 const moduleExportsAssignments = [];
1235 let firstTopLevelModuleExportsAssignment = null;
1236 const exportsAssignmentsByName = new Map();
1237 const topLevelAssignments = new Set();
1238 const topLevelDefineCompiledEsmExpressions = [];
1239
1240 estreeWalker.walk(ast, {
1241 enter(node, parent) {
1242 if (skippedNodes.has(node)) {
1243 this.skip();
1244 return;
1245 }
1246
1247 if (currentTryBlockEnd !== null && node.start > currentTryBlockEnd) {
1248 currentTryBlockEnd = null;
1249 }
1250
1251 programDepth += 1;
1252 if (node.scope) ({ scope } = node);
1253 if (functionType.test(node.type)) lexicalDepth += 1;
1254 if (sourceMap) {
1255 magicString.addSourcemapLocation(node.start);
1256 magicString.addSourcemapLocation(node.end);
1257 }
1258
1259 // eslint-disable-next-line default-case
1260 switch (node.type) {
1261 case 'TryStatement':
1262 if (currentTryBlockEnd === null) {
1263 currentTryBlockEnd = node.block.end;
1264 }
1265 return;
1266 case 'AssignmentExpression':
1267 if (node.left.type === 'MemberExpression') {
1268 const flattened = getKeypath(node.left);
1269 if (!flattened || scope.contains(flattened.name)) return;
1270
1271 const exportsPatternMatch = exportsPattern.exec(flattened.keypath);
1272 if (!exportsPatternMatch || flattened.keypath === 'exports') return;
1273
1274 const [, exportName] = exportsPatternMatch;
1275 uses[flattened.name] = true;
1276
1277 // we're dealing with `module.exports = ...` or `[module.]exports.foo = ...` –
1278 if (flattened.keypath === 'module.exports') {
1279 moduleExportsAssignments.push(node);
1280 if (programDepth > 3) {
1281 moduleAccessScopes.add(scope);
1282 } else if (!firstTopLevelModuleExportsAssignment) {
1283 firstTopLevelModuleExportsAssignment = node;
1284 }
1285
1286 if (defaultIsModuleExports === false) {
1287 shouldWrap = true;
1288 } else if (defaultIsModuleExports === 'auto') {
1289 if (node.right.type === 'ObjectExpression') {
1290 if (hasDefineEsmProperty(node.right)) {
1291 shouldWrap = true;
1292 }
1293 } else if (defaultIsModuleExports === false) {
1294 shouldWrap = true;
1295 }
1296 }
1297 } else if (exportName === KEY_COMPILED_ESM) {
1298 if (programDepth > 3) {
1299 shouldWrap = true;
1300 } else {
1301 topLevelDefineCompiledEsmExpressions.push(node);
1302 }
1303 } else {
1304 const exportsAssignments = exportsAssignmentsByName.get(exportName) || {
1305 nodes: [],
1306 scopes: new Set()
1307 };
1308 exportsAssignments.nodes.push(node);
1309 exportsAssignments.scopes.add(scope);
1310 exportsAccessScopes.add(scope);
1311 exportsAssignmentsByName.set(exportName, exportsAssignments);
1312 if (programDepth <= 3) {
1313 topLevelAssignments.add(node);
1314 }
1315 }
1316
1317 skippedNodes.add(node.left);
1318 } else {
1319 for (const name of pluginutils.extractAssignedNames(node.left)) {
1320 reassignedNames.add(name);
1321 }
1322 }
1323 return;
1324 case 'CallExpression': {
1325 if (isDefineCompiledEsm(node)) {
1326 if (programDepth === 3 && parent.type === 'ExpressionStatement') {
1327 // skip special handling for [module.]exports until we know we render this
1328 skippedNodes.add(node.arguments[0]);
1329 topLevelDefineCompiledEsmExpressions.push(node);
1330 } else {
1331 shouldWrap = true;
1332 }
1333 return;
1334 }
1335
1336 if (
1337 node.callee.object &&
1338 node.callee.object.name === 'require' &&
1339 node.callee.property.name === 'resolve' &&
1340 hasDynamicModuleForPath(id, '/', dynamicRequireModuleSet)
1341 ) {
1342 const requireNode = node.callee.object;
1343 magicString.appendLeft(
1344 node.end - 1,
1345 `,${JSON.stringify(
1346 path.dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath
1347 )}`
1348 );
1349 magicString.overwrite(
1350 requireNode.start,
1351 requireNode.end,
1352 `${HELPERS_NAME}.commonjsRequire`,
1353 {
1354 storeName: true
1355 }
1356 );
1357 return;
1358 }
1359
1360 if (!isStaticRequireStatement(node, scope)) return;
1361 if (!isDynamicRequireModulesEnabled) {
1362 skippedNodes.add(node.callee);
1363 }
1364 if (!isIgnoredRequireStatement(node, ignoreRequire)) {
1365 skippedNodes.add(node.callee);
1366 const usesReturnValue = parent.type !== 'ExpressionStatement';
1367
1368 let canConvertRequire = true;
1369 let shouldRemoveRequireStatement = false;
1370
1371 if (currentTryBlockEnd !== null) {
1372 ({
1373 canConvertRequire,
1374 shouldRemoveRequireStatement
1375 } = getIgnoreTryCatchRequireStatementMode(node.arguments[0].value));
1376
1377 if (shouldRemoveRequireStatement) {
1378 hasRemovedRequire = true;
1379 }
1380 }
1381
1382 let sourceId = getRequireStringArg(node);
1383 const isDynamicRegister = isWrappedId(sourceId, DYNAMIC_REGISTER_SUFFIX);
1384 if (isDynamicRegister) {
1385 sourceId = unwrapId(sourceId, DYNAMIC_REGISTER_SUFFIX);
1386 if (sourceId.endsWith('.json')) {
1387 sourceId = DYNAMIC_JSON_PREFIX + sourceId;
1388 }
1389 dynamicRegisterSources.add(wrapId(sourceId, DYNAMIC_REGISTER_SUFFIX));
1390 } else {
1391 if (
1392 !sourceId.endsWith('.json') &&
1393 hasDynamicModuleForPath(sourceId, id, dynamicRequireModuleSet)
1394 ) {
1395 if (shouldRemoveRequireStatement) {
1396 magicString.overwrite(node.start, node.end, `undefined`);
1397 } else if (canConvertRequire) {
1398 magicString.overwrite(
1399 node.start,
1400 node.end,
1401 `${HELPERS_NAME}.commonjsRequire(${JSON.stringify(
1402 getVirtualPathForDynamicRequirePath(sourceId, commonDir)
1403 )}, ${JSON.stringify(
1404 path.dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath
1405 )})`
1406 );
1407 usesDynamicRequire = true;
1408 }
1409 return;
1410 }
1411
1412 if (canConvertRequire) {
1413 addRequireStatement(sourceId, node, scope, usesReturnValue);
1414 }
1415 }
1416
1417 if (usesReturnValue) {
1418 if (shouldRemoveRequireStatement) {
1419 magicString.overwrite(node.start, node.end, `undefined`);
1420 return;
1421 }
1422
1423 if (
1424 parent.type === 'VariableDeclarator' &&
1425 !scope.parent &&
1426 parent.id.type === 'Identifier'
1427 ) {
1428 // This will allow us to reuse this variable name as the imported variable if it is not reassigned
1429 // and does not conflict with variables in other places where this is imported
1430 topLevelRequireDeclarators.add(parent);
1431 }
1432 } else {
1433 // This is a bare import, e.g. `require('foo');`
1434
1435 if (!canConvertRequire && !shouldRemoveRequireStatement) {
1436 return;
1437 }
1438
1439 magicString.remove(parent.start, parent.end);
1440 }
1441 }
1442 return;
1443 }
1444 case 'ConditionalExpression':
1445 case 'IfStatement':
1446 // skip dead branches
1447 if (isFalsy(node.test)) {
1448 skippedNodes.add(node.consequent);
1449 } else if (node.alternate && isTruthy(node.test)) {
1450 skippedNodes.add(node.alternate);
1451 }
1452 return;
1453 case 'Identifier': {
1454 const { name } = node;
1455 if (!(isReference__default["default"](node, parent) && !scope.contains(name))) return;
1456 switch (name) {
1457 case 'require':
1458 if (isNodeRequirePropertyAccess(parent)) {
1459 if (hasDynamicModuleForPath(id, '/', dynamicRequireModuleSet)) {
1460 if (parent.property.name === 'cache') {
1461 magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, {
1462 storeName: true
1463 });
1464 }
1465 }
1466
1467 return;
1468 }
1469
1470 if (isDynamicRequireModulesEnabled && isRequireStatement(parent, scope)) {
1471 magicString.appendLeft(
1472 parent.end - 1,
1473 `,${JSON.stringify(
1474 path.dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath
1475 )}`
1476 );
1477 }
1478 if (!ignoreDynamicRequires) {
1479 if (isShorthandProperty(parent)) {
1480 magicString.appendRight(node.end, `: ${HELPERS_NAME}.commonjsRequire`);
1481 } else {
1482 magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, {
1483 storeName: true
1484 });
1485 }
1486 }
1487 usesDynamicRequire = true;
1488 return;
1489 case 'module':
1490 case 'exports':
1491 shouldWrap = true;
1492 uses[name] = true;
1493 return;
1494 case 'global':
1495 uses.global = true;
1496 if (!ignoreGlobal) {
1497 magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsGlobal`, {
1498 storeName: true
1499 });
1500 }
1501 return;
1502 case 'define':
1503 magicString.overwrite(node.start, node.end, 'undefined', {
1504 storeName: true
1505 });
1506 return;
1507 default:
1508 globals.add(name);
1509 return;
1510 }
1511 }
1512 case 'MemberExpression':
1513 if (!isDynamicRequireModulesEnabled && isModuleRequire(node, scope)) {
1514 magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, {
1515 storeName: true
1516 });
1517 skippedNodes.add(node.object);
1518 skippedNodes.add(node.property);
1519 }
1520 return;
1521 case 'ReturnStatement':
1522 // if top-level return, we need to wrap it
1523 if (lexicalDepth === 0) {
1524 shouldWrap = true;
1525 }
1526 return;
1527 case 'ThisExpression':
1528 // rewrite top-level `this` as `commonjsHelpers.commonjsGlobal`
1529 if (lexicalDepth === 0) {
1530 uses.global = true;
1531 if (!ignoreGlobal) {
1532 magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsGlobal`, {
1533 storeName: true
1534 });
1535 }
1536 }
1537 return;
1538 case 'UnaryExpression':
1539 // rewrite `typeof module`, `typeof module.exports` and `typeof exports` (https://github.com/rollup/rollup-plugin-commonjs/issues/151)
1540 if (node.operator === 'typeof') {
1541 const flattened = getKeypath(node.argument);
1542 if (!flattened) return;
1543
1544 if (scope.contains(flattened.name)) return;
1545
1546 if (
1547 flattened.keypath === 'module.exports' ||
1548 flattened.keypath === 'module' ||
1549 flattened.keypath === 'exports'
1550 ) {
1551 magicString.overwrite(node.start, node.end, `'object'`, {
1552 storeName: false
1553 });
1554 }
1555 }
1556 return;
1557 case 'VariableDeclaration':
1558 if (!scope.parent) {
1559 topLevelDeclarations.push(node);
1560 }
1561 }
1562 },
1563
1564 leave(node) {
1565 programDepth -= 1;
1566 if (node.scope) scope = scope.parent;
1567 if (functionType.test(node.type)) lexicalDepth -= 1;
1568 }
1569 });
1570
1571 const nameBase = getName(id);
1572 const exportsName = deconflict([...exportsAccessScopes], globals, nameBase);
1573 const moduleName = deconflict([...moduleAccessScopes], globals, `${nameBase}Module`);
1574 const deconflictedExportNames = Object.create(null);
1575 for (const [exportName, { scopes }] of exportsAssignmentsByName) {
1576 deconflictedExportNames[exportName] = deconflict([...scopes], globals, exportName);
1577 }
1578
1579 // We cannot wrap ES/mixed modules
1580 shouldWrap =
1581 !isEsModule &&
1582 !disableWrap &&
1583 (shouldWrap || (uses.exports && moduleExportsAssignments.length > 0));
1584 const detectWrappedDefault =
1585 shouldWrap &&
1586 (topLevelDefineCompiledEsmExpressions.length > 0 || code.indexOf('__esModule') >= 0);
1587
1588 if (
1589 !(
1590 requiredSources.length ||
1591 dynamicRegisterSources.size ||
1592 uses.module ||
1593 uses.exports ||
1594 uses.require ||
1595 usesDynamicRequire ||
1596 hasRemovedRequire ||
1597 topLevelDefineCompiledEsmExpressions.length > 0
1598 ) &&
1599 (ignoreGlobal || !uses.global)
1600 ) {
1601 return { meta: { commonjs: { isCommonJS: false } } };
1602 }
1603
1604 let leadingComment = '';
1605 if (code.startsWith('/*')) {
1606 const commentEnd = code.indexOf('*/', 2) + 2;
1607 leadingComment = `${code.slice(0, commentEnd)}\n`;
1608 magicString.remove(0, commentEnd).trim();
1609 }
1610
1611 const exportMode = shouldWrap
1612 ? uses.module
1613 ? 'module'
1614 : 'exports'
1615 : firstTopLevelModuleExportsAssignment
1616 ? exportsAssignmentsByName.size === 0 && topLevelDefineCompiledEsmExpressions.length === 0
1617 ? 'replace'
1618 : 'module'
1619 : moduleExportsAssignments.length === 0
1620 ? 'exports'
1621 : 'module';
1622
1623 const importBlock = rewriteRequireExpressionsAndGetImportBlock(
1624 magicString,
1625 topLevelDeclarations,
1626 topLevelRequireDeclarators,
1627 reassignedNames,
1628 HELPERS_NAME,
1629 dynamicRegisterSources,
1630 moduleName,
1631 exportsName,
1632 id,
1633 exportMode
1634 );
1635
1636 const exportBlock = isEsModule
1637 ? ''
1638 : rewriteExportsAndGetExportsBlock(
1639 magicString,
1640 moduleName,
1641 exportsName,
1642 shouldWrap,
1643 moduleExportsAssignments,
1644 firstTopLevelModuleExportsAssignment,
1645 exportsAssignmentsByName,
1646 topLevelAssignments,
1647 topLevelDefineCompiledEsmExpressions,
1648 deconflictedExportNames,
1649 code,
1650 HELPERS_NAME,
1651 exportMode,
1652 detectWrappedDefault,
1653 defaultIsModuleExports
1654 );
1655
1656 if (shouldWrap) {
1657 wrapCode(magicString, uses, moduleName, exportsName);
1658 }
1659
1660 magicString
1661 .trim()
1662 .prepend(leadingComment + importBlock)
1663 .append(exportBlock);
1664
1665 return {
1666 code: magicString.toString(),
1667 map: sourceMap ? magicString.generateMap() : null,
1668 syntheticNamedExports: isEsModule ? false : '__moduleExports',
1669 meta: { commonjs: { isCommonJS: !isEsModule } }
1670 };
1671}
1672
1673function commonjs(options = {}) {
1674 const extensions = options.extensions || ['.js'];
1675 const filter = pluginutils.createFilter(options.include, options.exclude);
1676 const {
1677 ignoreGlobal,
1678 ignoreDynamicRequires,
1679 requireReturnsDefault: requireReturnsDefaultOption,
1680 esmExternals
1681 } = options;
1682 const getRequireReturnsDefault =
1683 typeof requireReturnsDefaultOption === 'function'
1684 ? requireReturnsDefaultOption
1685 : () => requireReturnsDefaultOption;
1686 let esmExternalIds;
1687 const isEsmExternal =
1688 typeof esmExternals === 'function'
1689 ? esmExternals
1690 : Array.isArray(esmExternals)
1691 ? ((esmExternalIds = new Set(esmExternals)), (id) => esmExternalIds.has(id))
1692 : () => esmExternals;
1693 const defaultIsModuleExports =
1694 typeof options.defaultIsModuleExports === 'boolean' ? options.defaultIsModuleExports : 'auto';
1695
1696 const { dynamicRequireModuleSet, dynamicRequireModuleDirPaths } = getDynamicRequirePaths(
1697 options.dynamicRequireTargets
1698 );
1699 const isDynamicRequireModulesEnabled = dynamicRequireModuleSet.size > 0;
1700 const commonDir = isDynamicRequireModulesEnabled
1701 ? getCommonDir__default["default"](null, Array.from(dynamicRequireModuleSet).concat(process.cwd()))
1702 : null;
1703
1704 const esModulesWithDefaultExport = new Set();
1705 const esModulesWithNamedExports = new Set();
1706 const commonJsMetaPromises = new Map();
1707
1708 const ignoreRequire =
1709 typeof options.ignore === 'function'
1710 ? options.ignore
1711 : Array.isArray(options.ignore)
1712 ? (id) => options.ignore.includes(id)
1713 : () => false;
1714
1715 const getIgnoreTryCatchRequireStatementMode = (id) => {
1716 const mode =
1717 typeof options.ignoreTryCatch === 'function'
1718 ? options.ignoreTryCatch(id)
1719 : Array.isArray(options.ignoreTryCatch)
1720 ? options.ignoreTryCatch.includes(id)
1721 : typeof options.ignoreTryCatch !== 'undefined'
1722 ? options.ignoreTryCatch
1723 : true;
1724
1725 return {
1726 canConvertRequire: mode !== 'remove' && mode !== true,
1727 shouldRemoveRequireStatement: mode === 'remove'
1728 };
1729 };
1730
1731 const resolveId = getResolveId(extensions);
1732
1733 const sourceMap = options.sourceMap !== false;
1734
1735 function transformAndCheckExports(code, id) {
1736 if (isDynamicRequireModulesEnabled && this.getModuleInfo(id).isEntry) {
1737 // eslint-disable-next-line no-param-reassign
1738 code =
1739 getDynamicPackagesEntryIntro(dynamicRequireModuleDirPaths, dynamicRequireModuleSet) + code;
1740 }
1741
1742 const { isEsModule, hasDefaultExport, hasNamedExports, ast } = analyzeTopLevelStatements(
1743 this.parse,
1744 code,
1745 id
1746 );
1747 if (hasDefaultExport) {
1748 esModulesWithDefaultExport.add(id);
1749 }
1750 if (hasNamedExports) {
1751 esModulesWithNamedExports.add(id);
1752 }
1753
1754 if (
1755 !dynamicRequireModuleSet.has(normalizePathSlashes(id)) &&
1756 (!hasCjsKeywords(code, ignoreGlobal) || (isEsModule && !options.transformMixedEsModules))
1757 ) {
1758 return { meta: { commonjs: { isCommonJS: false } } };
1759 }
1760
1761 // avoid wrapping as this is a commonjsRegister call
1762 const disableWrap = isWrappedId(id, DYNAMIC_REGISTER_SUFFIX);
1763 if (disableWrap) {
1764 // eslint-disable-next-line no-param-reassign
1765 id = unwrapId(id, DYNAMIC_REGISTER_SUFFIX);
1766 }
1767
1768 return transformCommonjs(
1769 this.parse,
1770 code,
1771 id,
1772 isEsModule,
1773 ignoreGlobal || isEsModule,
1774 ignoreRequire,
1775 ignoreDynamicRequires && !isDynamicRequireModulesEnabled,
1776 getIgnoreTryCatchRequireStatementMode,
1777 sourceMap,
1778 isDynamicRequireModulesEnabled,
1779 dynamicRequireModuleSet,
1780 disableWrap,
1781 commonDir,
1782 ast,
1783 defaultIsModuleExports
1784 );
1785 }
1786
1787 return {
1788 name: 'commonjs',
1789
1790 buildStart() {
1791 validateRollupVersion(this.meta.rollupVersion, peerDependencies.rollup);
1792 if (options.namedExports != null) {
1793 this.warn(
1794 'The namedExports option from "@rollup/plugin-commonjs" is deprecated. Named exports are now handled automatically.'
1795 );
1796 }
1797 },
1798
1799 resolveId,
1800
1801 load(id) {
1802 if (id === HELPERS_ID) {
1803 return getHelpersModule(isDynamicRequireModulesEnabled, ignoreDynamicRequires);
1804 }
1805
1806 if (id.startsWith(HELPERS_ID)) {
1807 return getSpecificHelperProxy(id);
1808 }
1809
1810 if (isWrappedId(id, MODULE_SUFFIX)) {
1811 const actualId = unwrapId(id, MODULE_SUFFIX);
1812 let name = getName(actualId);
1813 let code;
1814 if (isDynamicRequireModulesEnabled) {
1815 if (['modulePath', 'commonjsRequire', 'createModule'].includes(name)) {
1816 name = `${name}_`;
1817 }
1818 code =
1819 `import {commonjsRequire, createModule} from "${HELPERS_ID}";\n` +
1820 `var ${name} = createModule(${JSON.stringify(
1821 getVirtualPathForDynamicRequirePath(path.dirname(actualId), commonDir)
1822 )});\n` +
1823 `export {${name} as __module}`;
1824 } else {
1825 code = `var ${name} = {exports: {}}; export {${name} as __module}`;
1826 }
1827 return {
1828 code,
1829 syntheticNamedExports: '__module',
1830 meta: { commonjs: { isCommonJS: false } }
1831 };
1832 }
1833
1834 if (isWrappedId(id, EXPORTS_SUFFIX)) {
1835 const actualId = unwrapId(id, EXPORTS_SUFFIX);
1836 const name = getName(actualId);
1837 return {
1838 code: `var ${name} = {}; export {${name} as __exports}`,
1839 meta: { commonjs: { isCommonJS: false } }
1840 };
1841 }
1842
1843 if (isWrappedId(id, EXTERNAL_SUFFIX)) {
1844 const actualId = unwrapId(id, EXTERNAL_SUFFIX);
1845 return getUnknownRequireProxy(
1846 actualId,
1847 isEsmExternal(actualId) ? getRequireReturnsDefault(actualId) : true
1848 );
1849 }
1850
1851 if (id === DYNAMIC_PACKAGES_ID) {
1852 return getDynamicPackagesModule(dynamicRequireModuleDirPaths, commonDir);
1853 }
1854
1855 if (id.startsWith(DYNAMIC_JSON_PREFIX)) {
1856 return getDynamicJsonProxy(id, commonDir);
1857 }
1858
1859 if (isDynamicModuleImport(id, dynamicRequireModuleSet)) {
1860 return `export default require(${JSON.stringify(normalizePathSlashes(id))});`;
1861 }
1862
1863 if (isWrappedId(id, DYNAMIC_REGISTER_SUFFIX)) {
1864 return getDynamicRequireProxy(
1865 normalizePathSlashes(unwrapId(id, DYNAMIC_REGISTER_SUFFIX)),
1866 commonDir
1867 );
1868 }
1869
1870 if (isWrappedId(id, PROXY_SUFFIX)) {
1871 const actualId = unwrapId(id, PROXY_SUFFIX);
1872 return getStaticRequireProxy(
1873 actualId,
1874 getRequireReturnsDefault(actualId),
1875 esModulesWithDefaultExport,
1876 esModulesWithNamedExports,
1877 commonJsMetaPromises
1878 );
1879 }
1880
1881 return null;
1882 },
1883
1884 transform(code, rawId) {
1885 let id = rawId;
1886
1887 if (isWrappedId(id, DYNAMIC_REGISTER_SUFFIX)) {
1888 id = unwrapId(id, DYNAMIC_REGISTER_SUFFIX);
1889 }
1890
1891 const extName = path.extname(id);
1892 if (
1893 extName !== '.cjs' &&
1894 id !== DYNAMIC_PACKAGES_ID &&
1895 !id.startsWith(DYNAMIC_JSON_PREFIX) &&
1896 (!filter(id) || !extensions.includes(extName))
1897 ) {
1898 return null;
1899 }
1900
1901 try {
1902 return transformAndCheckExports.call(this, code, rawId);
1903 } catch (err) {
1904 return this.error(err, err.loc);
1905 }
1906 },
1907
1908 moduleParsed({ id, meta: { commonjs: commonjsMeta } }) {
1909 if (commonjsMeta && commonjsMeta.isCommonJS != null) {
1910 setCommonJSMetaPromise(commonJsMetaPromises, id, commonjsMeta);
1911 return;
1912 }
1913 setCommonJSMetaPromise(commonJsMetaPromises, id, null);
1914 }
1915 };
1916}
1917
1918module.exports = commonjs;
1919//# sourceMappingURL=index.js.map