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