@rollup/plugin-commonjs 16.0.0 → 17.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +8 -0
- package/README.md +2 -8
- package/dist/index.es.js +1058 -894
- package/dist/index.es.js.map +1 -1
- package/dist/index.js +1058 -894
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.es.js
CHANGED
|
@@ -1,17 +1,81 @@
|
|
|
1
|
-
import { basename, extname, dirname, sep,
|
|
1
|
+
import { basename, extname, dirname, sep, join, resolve } from 'path';
|
|
2
2
|
import { makeLegalIdentifier, attachScopes, extractAssignedNames, createFilter } from '@rollup/pluginutils';
|
|
3
3
|
import getCommonDir from 'commondir';
|
|
4
4
|
import { existsSync, readFileSync, statSync } from 'fs';
|
|
5
|
+
import glob from 'glob';
|
|
5
6
|
import { walk } from 'estree-walker';
|
|
6
7
|
import MagicString from 'magic-string';
|
|
7
|
-
import { sync } from 'resolve';
|
|
8
8
|
import isReference from 'is-reference';
|
|
9
|
-
import
|
|
9
|
+
import { sync } from 'resolve';
|
|
10
10
|
|
|
11
11
|
var peerDependencies = {
|
|
12
12
|
rollup: "^2.30.0"
|
|
13
13
|
};
|
|
14
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
|
+
|
|
15
79
|
const isWrappedId = (id, suffix) => id.endsWith(suffix);
|
|
16
80
|
const wrapId = (id, suffix) => `\0${id}${suffix}`;
|
|
17
81
|
const unwrapId = (wrappedId, suffix) => wrappedId.slice(1, -suffix.length);
|
|
@@ -20,12 +84,6 @@ const PROXY_SUFFIX = '?commonjs-proxy';
|
|
|
20
84
|
const REQUIRE_SUFFIX = '?commonjs-require';
|
|
21
85
|
const EXTERNAL_SUFFIX = '?commonjs-external';
|
|
22
86
|
|
|
23
|
-
const VIRTUAL_PATH_BASE = '/$$rollup_base$$';
|
|
24
|
-
const getVirtualPathForDynamicRequirePath = (path, commonDir) => {
|
|
25
|
-
if (path.startsWith(commonDir)) return VIRTUAL_PATH_BASE + path.slice(commonDir.length);
|
|
26
|
-
return path;
|
|
27
|
-
};
|
|
28
|
-
|
|
29
87
|
const DYNAMIC_REGISTER_PREFIX = '\0commonjs-dynamic-register:';
|
|
30
88
|
const DYNAMIC_JSON_PREFIX = '\0commonjs-dynamic-json:';
|
|
31
89
|
const DYNAMIC_PACKAGES_ID = '\0commonjs-dynamic-packages';
|
|
@@ -37,11 +95,6 @@ const HELPERS_ID = '\0commonjsHelpers.js';
|
|
|
37
95
|
// This will no longer be necessary once Rollup switches to ES6 output, likely
|
|
38
96
|
// in Rollup 3
|
|
39
97
|
|
|
40
|
-
// The "hasOwnProperty" call in "getDefaultExportFromCjs" is technically not
|
|
41
|
-
// needed, but for consumers that use Rollup's old interop pattern, it will fix
|
|
42
|
-
// rollup/rollup-plugin-commonjs#224
|
|
43
|
-
// We should remove it once Rollup core and this plugin are updated to not use
|
|
44
|
-
// this pattern any more
|
|
45
98
|
const HELPERS = `
|
|
46
99
|
export var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
|
|
47
100
|
|
|
@@ -49,16 +102,6 @@ export function getDefaultExportFromCjs (x) {
|
|
|
49
102
|
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
|
|
50
103
|
}
|
|
51
104
|
|
|
52
|
-
export function createCommonjsModule(fn, basedir, module) {
|
|
53
|
-
return module = {
|
|
54
|
-
path: basedir,
|
|
55
|
-
exports: {},
|
|
56
|
-
require: function (path, base) {
|
|
57
|
-
return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
|
|
58
|
-
}
|
|
59
|
-
}, fn(module, module.exports), module.exports;
|
|
60
|
-
}
|
|
61
|
-
|
|
62
105
|
export function getDefaultExportFromNamespaceIfPresent (n) {
|
|
63
106
|
return n && Object.prototype.hasOwnProperty.call(n, 'default') ? n['default'] : n;
|
|
64
107
|
}
|
|
@@ -84,12 +127,27 @@ export function getAugmentedNamespace(n) {
|
|
|
84
127
|
`;
|
|
85
128
|
|
|
86
129
|
const HELPER_NON_DYNAMIC = `
|
|
87
|
-
export function
|
|
88
|
-
|
|
130
|
+
export function createCommonjsModule(fn) {
|
|
131
|
+
var module = { exports: {} }
|
|
132
|
+
return fn(module, module.exports), module.exports;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export function commonjsRequire (target) {
|
|
136
|
+
throw new Error('Could not dynamically require "' + target + '". Please configure the dynamicRequireTargets option of @rollup/plugin-commonjs appropriately for this require call to behave properly.');
|
|
89
137
|
}
|
|
90
138
|
`;
|
|
91
139
|
|
|
92
140
|
const HELPERS_DYNAMIC = `
|
|
141
|
+
export function createCommonjsModule(fn, basedir, module) {
|
|
142
|
+
return module = {
|
|
143
|
+
path: basedir,
|
|
144
|
+
exports: {},
|
|
145
|
+
require: function (path, base) {
|
|
146
|
+
return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
|
|
147
|
+
}
|
|
148
|
+
}, fn(module, module.exports), module.exports;
|
|
149
|
+
}
|
|
150
|
+
|
|
93
151
|
export function commonjsRegister (path, loader) {
|
|
94
152
|
DYNAMIC_REQUIRE_LOADERS[path] = loader;
|
|
95
153
|
}
|
|
@@ -232,67 +290,22 @@ function getHelpersModule(isDynamicRequireModulesEnabled) {
|
|
|
232
290
|
return `${HELPERS}${isDynamicRequireModulesEnabled ? HELPERS_DYNAMIC : HELPER_NON_DYNAMIC}`;
|
|
233
291
|
}
|
|
234
292
|
|
|
235
|
-
/* eslint-disable
|
|
236
|
-
|
|
237
|
-
const operators = {
|
|
238
|
-
'==': (x) => equals(x.left, x.right, false),
|
|
239
|
-
|
|
240
|
-
'!=': (x) => not(operators['=='](x)),
|
|
241
|
-
|
|
242
|
-
'===': (x) => equals(x.left, x.right, true),
|
|
243
|
-
|
|
244
|
-
'!==': (x) => not(operators['==='](x)),
|
|
245
|
-
|
|
246
|
-
'!': (x) => isFalsy(x.argument),
|
|
247
|
-
|
|
248
|
-
'&&': (x) => isTruthy(x.left) && isTruthy(x.right),
|
|
249
|
-
|
|
250
|
-
'||': (x) => isTruthy(x.left) || isTruthy(x.right)
|
|
251
|
-
};
|
|
252
|
-
|
|
253
|
-
function flatten(node) {
|
|
254
|
-
const parts = [];
|
|
293
|
+
/* eslint-disable import/prefer-default-export */
|
|
255
294
|
|
|
256
|
-
|
|
257
|
-
|
|
295
|
+
function deconflict(scope, globals, identifier) {
|
|
296
|
+
let i = 1;
|
|
297
|
+
let deconflicted = makeLegalIdentifier(identifier);
|
|
258
298
|
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
299
|
+
while (scope.contains(deconflicted) || globals.has(deconflicted)) {
|
|
300
|
+
deconflicted = makeLegalIdentifier(`${identifier}_${i}`);
|
|
301
|
+
i += 1;
|
|
262
302
|
}
|
|
303
|
+
// eslint-disable-next-line no-param-reassign
|
|
304
|
+
scope.declarations[deconflicted] = true;
|
|
263
305
|
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
const { name } = node;
|
|
267
|
-
parts.unshift(name);
|
|
268
|
-
|
|
269
|
-
return { name, keypath: parts.join('.') };
|
|
270
|
-
}
|
|
271
|
-
|
|
272
|
-
function isTruthy(node) {
|
|
273
|
-
if (node.type === 'Literal') return !!node.value;
|
|
274
|
-
if (node.type === 'ParenthesizedExpression') return isTruthy(node.expression);
|
|
275
|
-
if (node.operator in operators) return operators[node.operator](node);
|
|
276
|
-
return undefined;
|
|
277
|
-
}
|
|
278
|
-
|
|
279
|
-
function isFalsy(node) {
|
|
280
|
-
return not(isTruthy(node));
|
|
281
|
-
}
|
|
282
|
-
|
|
283
|
-
function not(value) {
|
|
284
|
-
return value === undefined ? value : !value;
|
|
285
|
-
}
|
|
286
|
-
|
|
287
|
-
function equals(a, b, strict) {
|
|
288
|
-
if (a.type !== b.type) return undefined;
|
|
289
|
-
// eslint-disable-next-line eqeqeq
|
|
290
|
-
if (a.type === 'Literal') return strict ? a.value === b.value : a.value == b.value;
|
|
291
|
-
return undefined;
|
|
306
|
+
return deconflicted;
|
|
292
307
|
}
|
|
293
308
|
|
|
294
|
-
/* eslint-disable import/prefer-default-export */
|
|
295
|
-
|
|
296
309
|
function getName(id) {
|
|
297
310
|
const name = makeLegalIdentifier(basename(id, extname(id)));
|
|
298
311
|
if (name !== 'index') {
|
|
@@ -302,780 +315,101 @@ function getName(id) {
|
|
|
302
315
|
return makeLegalIdentifier(segments[segments.length - 1]);
|
|
303
316
|
}
|
|
304
317
|
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
' '
|
|
309
|
-
);
|
|
310
|
-
const blacklist = { __esModule: true };
|
|
311
|
-
reserved.forEach((word) => (blacklist[word] = true));
|
|
318
|
+
function normalizePathSlashes(path) {
|
|
319
|
+
return path.replace(/\\/g, '/');
|
|
320
|
+
}
|
|
312
321
|
|
|
313
|
-
const
|
|
322
|
+
const VIRTUAL_PATH_BASE = '/$$rollup_base$$';
|
|
323
|
+
const getVirtualPathForDynamicRequirePath = (path, commonDir) => {
|
|
324
|
+
const normalizedPath = normalizePathSlashes(path);
|
|
325
|
+
return normalizedPath.startsWith(commonDir)
|
|
326
|
+
? VIRTUAL_PATH_BASE + normalizedPath.slice(commonDir.length)
|
|
327
|
+
: normalizedPath;
|
|
328
|
+
};
|
|
314
329
|
|
|
315
|
-
|
|
316
|
-
const
|
|
317
|
-
const
|
|
330
|
+
function getDynamicPackagesModule(dynamicRequireModuleDirPaths, commonDir) {
|
|
331
|
+
let code = `const commonjsRegister = require('${HELPERS_ID}?commonjsRegister');`;
|
|
332
|
+
for (const dir of dynamicRequireModuleDirPaths) {
|
|
333
|
+
let entryPoint = 'index.js';
|
|
318
334
|
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
335
|
+
try {
|
|
336
|
+
if (existsSync(join(dir, 'package.json'))) {
|
|
337
|
+
entryPoint =
|
|
338
|
+
JSON.parse(readFileSync(join(dir, 'package.json'), { encoding: 'utf8' })).main ||
|
|
339
|
+
entryPoint;
|
|
340
|
+
}
|
|
341
|
+
} catch (ignored) {
|
|
342
|
+
// ignored
|
|
343
|
+
}
|
|
322
344
|
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
345
|
+
code += `\ncommonjsRegister(${JSON.stringify(
|
|
346
|
+
getVirtualPathForDynamicRequirePath(dir, commonDir)
|
|
347
|
+
)}, function (module, exports) {
|
|
348
|
+
module.exports = require(${JSON.stringify(normalizePathSlashes(join(dir, entryPoint)))});
|
|
349
|
+
});`;
|
|
326
350
|
}
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
return deconflicted;
|
|
351
|
+
return code;
|
|
330
352
|
}
|
|
331
353
|
|
|
332
|
-
function
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
354
|
+
function getDynamicPackagesEntryIntro(
|
|
355
|
+
dynamicRequireModuleDirPaths,
|
|
356
|
+
dynamicRequireModuleSet
|
|
357
|
+
) {
|
|
358
|
+
let dynamicImports = Array.from(
|
|
359
|
+
dynamicRequireModuleSet,
|
|
360
|
+
(dynamicId) => `require(${JSON.stringify(DYNAMIC_REGISTER_PREFIX + dynamicId)});`
|
|
361
|
+
).join('\n');
|
|
362
|
+
|
|
363
|
+
if (dynamicRequireModuleDirPaths.length) {
|
|
364
|
+
dynamicImports += `require(${JSON.stringify(DYNAMIC_REGISTER_PREFIX + DYNAMIC_PACKAGES_ID)});`;
|
|
338
365
|
}
|
|
339
|
-
}
|
|
340
366
|
|
|
341
|
-
|
|
342
|
-
return path.replace(/\\/g, '/');
|
|
367
|
+
return dynamicImports;
|
|
343
368
|
}
|
|
344
369
|
|
|
345
|
-
function
|
|
346
|
-
const
|
|
347
|
-
return
|
|
370
|
+
function isModuleRegistrationProxy(id, dynamicRequireModuleSet) {
|
|
371
|
+
const normalizedPath = normalizePathSlashes(id);
|
|
372
|
+
return dynamicRequireModuleSet.has(normalizedPath) && !normalizedPath.endsWith('.json');
|
|
348
373
|
}
|
|
349
374
|
|
|
350
|
-
function
|
|
351
|
-
const
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
if (node.type === 'ExportDefaultDeclaration') {
|
|
358
|
-
isEsModule = true;
|
|
359
|
-
hasDefaultExport = true;
|
|
360
|
-
} else if (node.type === 'ExportNamedDeclaration') {
|
|
361
|
-
isEsModule = true;
|
|
362
|
-
if (node.declaration) {
|
|
363
|
-
hasNamedExports = true;
|
|
364
|
-
} else {
|
|
365
|
-
for (const specifier of node.specifiers) {
|
|
366
|
-
if (specifier.exported.name === 'default') {
|
|
367
|
-
hasDefaultExport = true;
|
|
368
|
-
} else {
|
|
369
|
-
hasNamedExports = true;
|
|
370
|
-
}
|
|
371
|
-
}
|
|
372
|
-
}
|
|
373
|
-
} else if (node.type === 'ExportAllDeclaration') {
|
|
374
|
-
isEsModule = true;
|
|
375
|
-
if (node.exported && node.exported.name === 'default') {
|
|
376
|
-
hasDefaultExport = true;
|
|
377
|
-
} else {
|
|
378
|
-
hasNamedExports = true;
|
|
379
|
-
}
|
|
380
|
-
} else if (node.type === 'ImportDeclaration') {
|
|
381
|
-
isEsModule = true;
|
|
375
|
+
function getDynamicRequirePaths(patterns) {
|
|
376
|
+
const dynamicRequireModuleSet = new Set();
|
|
377
|
+
for (const pattern of !patterns || Array.isArray(patterns) ? patterns || [] : [patterns]) {
|
|
378
|
+
const isNegated = pattern.startsWith('!');
|
|
379
|
+
const modifySet = Set.prototype[isNegated ? 'delete' : 'add'].bind(dynamicRequireModuleSet);
|
|
380
|
+
for (const path of glob.sync(isNegated ? pattern.substr(1) : pattern)) {
|
|
381
|
+
modifySet(normalizePathSlashes(resolve(path)));
|
|
382
382
|
}
|
|
383
383
|
}
|
|
384
|
-
|
|
385
|
-
|
|
384
|
+
const dynamicRequireModuleDirPaths = Array.from(dynamicRequireModuleSet.values()).filter(
|
|
385
|
+
(path) => {
|
|
386
|
+
try {
|
|
387
|
+
if (statSync(path).isDirectory()) return true;
|
|
388
|
+
} catch (ignored) {
|
|
389
|
+
// Nothing to do here
|
|
390
|
+
}
|
|
391
|
+
return false;
|
|
392
|
+
}
|
|
393
|
+
);
|
|
394
|
+
return { dynamicRequireModuleSet, dynamicRequireModuleDirPaths };
|
|
386
395
|
}
|
|
387
396
|
|
|
388
|
-
|
|
389
|
-
if (node.type !== 'CallExpression') return;
|
|
390
|
-
|
|
391
|
-
const {
|
|
392
|
-
callee: { object, property }
|
|
393
|
-
} = node;
|
|
394
|
-
|
|
395
|
-
if (!object || object.type !== 'Identifier' || object.name !== 'Object') return;
|
|
397
|
+
const isCjsPromises = new Map();
|
|
396
398
|
|
|
397
|
-
|
|
399
|
+
function getIsCjsPromise(id) {
|
|
400
|
+
let isCjsPromise = isCjsPromises.get(id);
|
|
401
|
+
if (isCjsPromise) return isCjsPromise.promise;
|
|
398
402
|
|
|
399
|
-
|
|
403
|
+
const promise = new Promise((resolve) => {
|
|
404
|
+
isCjsPromise = {
|
|
405
|
+
resolve,
|
|
406
|
+
promise: null
|
|
407
|
+
};
|
|
408
|
+
isCjsPromises.set(id, isCjsPromise);
|
|
409
|
+
});
|
|
410
|
+
isCjsPromise.promise = promise;
|
|
400
411
|
|
|
401
|
-
|
|
402
|
-
if (target.type !== 'Identifier' || target.name !== targetName) return;
|
|
403
|
-
// eslint-disable-next-line consistent-return
|
|
404
|
-
return val.value;
|
|
405
|
-
}
|
|
406
|
-
|
|
407
|
-
function transformCommonjs(
|
|
408
|
-
parse,
|
|
409
|
-
code,
|
|
410
|
-
id,
|
|
411
|
-
isEsModule,
|
|
412
|
-
ignoreGlobal,
|
|
413
|
-
ignoreRequire,
|
|
414
|
-
sourceMap,
|
|
415
|
-
isDynamicRequireModulesEnabled,
|
|
416
|
-
dynamicRequireModuleSet,
|
|
417
|
-
disableWrap,
|
|
418
|
-
commonDir,
|
|
419
|
-
astCache
|
|
420
|
-
) {
|
|
421
|
-
const ast = astCache || tryParse(parse, code, id);
|
|
422
|
-
|
|
423
|
-
const magicString = new MagicString(code);
|
|
424
|
-
|
|
425
|
-
const required = {};
|
|
426
|
-
// Because objects have no guaranteed ordering, yet we need it,
|
|
427
|
-
// we need to keep track of the order in a array
|
|
428
|
-
const requiredSources = [];
|
|
429
|
-
const dynamicRegisterSources = [];
|
|
430
|
-
|
|
431
|
-
let uid = 0;
|
|
432
|
-
|
|
433
|
-
let scope = attachScopes(ast, 'scope');
|
|
434
|
-
const uses = { module: false, exports: false, global: false, require: false };
|
|
435
|
-
|
|
436
|
-
let lexicalDepth = 0;
|
|
437
|
-
let programDepth = 0;
|
|
438
|
-
|
|
439
|
-
const globals = new Set();
|
|
440
|
-
|
|
441
|
-
// TODO technically wrong since globals isn't populated yet, but ¯\_(ツ)_/¯
|
|
442
|
-
const HELPERS_NAME = deconflict(scope, globals, 'commonjsHelpers');
|
|
443
|
-
|
|
444
|
-
const namedExports = {};
|
|
445
|
-
|
|
446
|
-
// TODO handle transpiled modules
|
|
447
|
-
let shouldWrap = /__esModule/.test(code);
|
|
448
|
-
let usesCommonjsHelpers = false;
|
|
449
|
-
|
|
450
|
-
function isRequireStatement(node) {
|
|
451
|
-
if (!node) return false;
|
|
452
|
-
if (node.type !== 'CallExpression') return false;
|
|
453
|
-
|
|
454
|
-
// Weird case of `require()` or `module.require()` without arguments
|
|
455
|
-
if (node.arguments.length === 0) return false;
|
|
456
|
-
|
|
457
|
-
return isRequireIdentifier(node.callee);
|
|
458
|
-
}
|
|
459
|
-
|
|
460
|
-
function isRequireIdentifier(node) {
|
|
461
|
-
if (!node) return false;
|
|
462
|
-
|
|
463
|
-
if (node.type === 'Identifier' && node.name === 'require' /* `require` */) {
|
|
464
|
-
// `require` is hidden by a variable in local scope
|
|
465
|
-
if (scope.contains('require')) return false;
|
|
466
|
-
|
|
467
|
-
return true;
|
|
468
|
-
} else if (node.type === 'MemberExpression' /* `[something].[something]` */) {
|
|
469
|
-
// `module.[something]`
|
|
470
|
-
if (node.object.type !== 'Identifier' || node.object.name !== 'module') return false;
|
|
471
|
-
|
|
472
|
-
// `module` is hidden by a variable in local scope
|
|
473
|
-
if (scope.contains('module')) return false;
|
|
474
|
-
|
|
475
|
-
// `module.require(...)`
|
|
476
|
-
if (node.property.type !== 'Identifier' || node.property.name !== 'require') return false;
|
|
477
|
-
|
|
478
|
-
return true;
|
|
479
|
-
}
|
|
480
|
-
|
|
481
|
-
return false;
|
|
482
|
-
}
|
|
483
|
-
|
|
484
|
-
function hasDynamicArguments(node) {
|
|
485
|
-
return (
|
|
486
|
-
node.arguments.length > 1 ||
|
|
487
|
-
(node.arguments[0].type !== 'Literal' &&
|
|
488
|
-
(node.arguments[0].type !== 'TemplateLiteral' || node.arguments[0].expressions.length > 0))
|
|
489
|
-
);
|
|
490
|
-
}
|
|
491
|
-
|
|
492
|
-
function isStaticRequireStatement(node) {
|
|
493
|
-
if (!isRequireStatement(node)) return false;
|
|
494
|
-
return !hasDynamicArguments(node);
|
|
495
|
-
}
|
|
496
|
-
|
|
497
|
-
function isNodeRequireStatement(parent) {
|
|
498
|
-
const reservedMethod = ['resolve', 'cache', 'main'];
|
|
499
|
-
return !!(parent && parent.property && reservedMethod.indexOf(parent.property.name) > -1);
|
|
500
|
-
}
|
|
501
|
-
|
|
502
|
-
function isIgnoredRequireStatement(requiredNode) {
|
|
503
|
-
return ignoreRequire(requiredNode.arguments[0].value);
|
|
504
|
-
}
|
|
505
|
-
|
|
506
|
-
function getRequireStringArg(node) {
|
|
507
|
-
return node.arguments[0].type === 'Literal'
|
|
508
|
-
? node.arguments[0].value
|
|
509
|
-
: node.arguments[0].quasis[0].value.cooked;
|
|
510
|
-
}
|
|
511
|
-
|
|
512
|
-
function getRequired(node, name) {
|
|
513
|
-
let sourceId = getRequireStringArg(node);
|
|
514
|
-
const isDynamicRegister = sourceId.startsWith(DYNAMIC_REGISTER_PREFIX);
|
|
515
|
-
if (isDynamicRegister) {
|
|
516
|
-
sourceId = sourceId.substr(DYNAMIC_REGISTER_PREFIX.length);
|
|
517
|
-
}
|
|
518
|
-
|
|
519
|
-
const existing = required[sourceId];
|
|
520
|
-
if (!existing) {
|
|
521
|
-
const isDynamic = hasDynamicModuleForPath(sourceId);
|
|
522
|
-
|
|
523
|
-
if (!name) {
|
|
524
|
-
do {
|
|
525
|
-
name = `require$$${uid}`;
|
|
526
|
-
uid += 1;
|
|
527
|
-
} while (scope.contains(name));
|
|
528
|
-
}
|
|
529
|
-
|
|
530
|
-
if (isDynamicRegister) {
|
|
531
|
-
if (sourceId.endsWith('.json')) {
|
|
532
|
-
sourceId = DYNAMIC_JSON_PREFIX + sourceId;
|
|
533
|
-
}
|
|
534
|
-
dynamicRegisterSources.push(sourceId);
|
|
535
|
-
}
|
|
536
|
-
|
|
537
|
-
if (!isDynamic || sourceId.endsWith('.json')) {
|
|
538
|
-
requiredSources.push(sourceId);
|
|
539
|
-
}
|
|
540
|
-
|
|
541
|
-
required[sourceId] = { source: sourceId, name, importsDefault: false, isDynamic };
|
|
542
|
-
}
|
|
543
|
-
|
|
544
|
-
return required[sourceId];
|
|
545
|
-
}
|
|
546
|
-
|
|
547
|
-
function hasDynamicModuleForPath(source) {
|
|
548
|
-
if (!/^(?:\.{0,2}[/\\]|[A-Za-z]:[/\\])/.test(source)) {
|
|
549
|
-
try {
|
|
550
|
-
const resolvedPath = normalizePathSlashes(
|
|
551
|
-
sync(source, { basedir: dirname(id) })
|
|
552
|
-
);
|
|
553
|
-
if (dynamicRequireModuleSet.has(resolvedPath)) {
|
|
554
|
-
return true;
|
|
555
|
-
}
|
|
556
|
-
} catch (ex) {
|
|
557
|
-
// Probably a node.js internal module
|
|
558
|
-
return false;
|
|
559
|
-
}
|
|
560
|
-
|
|
561
|
-
return false;
|
|
562
|
-
}
|
|
563
|
-
|
|
564
|
-
for (const attemptExt of ['', '.js', '.json']) {
|
|
565
|
-
const resolvedPath = normalizePathSlashes(resolve(dirname(id), source + attemptExt));
|
|
566
|
-
if (dynamicRequireModuleSet.has(resolvedPath)) {
|
|
567
|
-
return true;
|
|
568
|
-
}
|
|
569
|
-
}
|
|
570
|
-
|
|
571
|
-
return false;
|
|
572
|
-
}
|
|
573
|
-
|
|
574
|
-
function shouldUseSimulatedRequire(required) {
|
|
575
|
-
return (
|
|
576
|
-
hasDynamicModuleForPath(required.source) &&
|
|
577
|
-
// We only do `commonjsRequire` for json if it's the `commonjsRegister` call.
|
|
578
|
-
(required.source.startsWith(DYNAMIC_REGISTER_PREFIX) || !required.source.endsWith('.json'))
|
|
579
|
-
);
|
|
580
|
-
}
|
|
581
|
-
|
|
582
|
-
// do a first pass, see which names are assigned to. This is necessary to prevent
|
|
583
|
-
// illegally replacing `var foo = require('foo')` with `import foo from 'foo'`,
|
|
584
|
-
// where `foo` is later reassigned. (This happens in the wild. CommonJS, sigh)
|
|
585
|
-
const assignedTo = new Set();
|
|
586
|
-
walk(ast, {
|
|
587
|
-
enter(node) {
|
|
588
|
-
if (node.type !== 'AssignmentExpression') return;
|
|
589
|
-
if (node.left.type === 'MemberExpression') return;
|
|
590
|
-
|
|
591
|
-
extractAssignedNames(node.left).forEach((name) => {
|
|
592
|
-
assignedTo.add(name);
|
|
593
|
-
});
|
|
594
|
-
}
|
|
595
|
-
});
|
|
596
|
-
|
|
597
|
-
walk(ast, {
|
|
598
|
-
enter(node, parent) {
|
|
599
|
-
if (sourceMap) {
|
|
600
|
-
magicString.addSourcemapLocation(node.start);
|
|
601
|
-
magicString.addSourcemapLocation(node.end);
|
|
602
|
-
}
|
|
603
|
-
|
|
604
|
-
// skip dead branches
|
|
605
|
-
if (parent && (parent.type === 'IfStatement' || parent.type === 'ConditionalExpression')) {
|
|
606
|
-
if (node === parent.consequent && isFalsy(parent.test)) {
|
|
607
|
-
this.skip();
|
|
608
|
-
return;
|
|
609
|
-
}
|
|
610
|
-
if (node === parent.alternate && isTruthy(parent.test)) {
|
|
611
|
-
this.skip();
|
|
612
|
-
return;
|
|
613
|
-
}
|
|
614
|
-
}
|
|
615
|
-
|
|
616
|
-
if (node._skip) {
|
|
617
|
-
this.skip();
|
|
618
|
-
return;
|
|
619
|
-
}
|
|
620
|
-
|
|
621
|
-
programDepth += 1;
|
|
622
|
-
|
|
623
|
-
if (node.scope) ({ scope } = node);
|
|
624
|
-
if (functionType.test(node.type)) lexicalDepth += 1;
|
|
625
|
-
|
|
626
|
-
// if toplevel return, we need to wrap it
|
|
627
|
-
if (node.type === 'ReturnStatement' && lexicalDepth === 0) {
|
|
628
|
-
shouldWrap = true;
|
|
629
|
-
}
|
|
630
|
-
|
|
631
|
-
// rewrite `this` as `commonjsHelpers.commonjsGlobal`
|
|
632
|
-
if (node.type === 'ThisExpression' && lexicalDepth === 0) {
|
|
633
|
-
uses.global = true;
|
|
634
|
-
if (!ignoreGlobal) {
|
|
635
|
-
magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsGlobal`, {
|
|
636
|
-
storeName: true
|
|
637
|
-
});
|
|
638
|
-
usesCommonjsHelpers = true;
|
|
639
|
-
}
|
|
640
|
-
return;
|
|
641
|
-
}
|
|
642
|
-
|
|
643
|
-
// rewrite `typeof module`, `typeof module.exports` and `typeof exports` (https://github.com/rollup/rollup-plugin-commonjs/issues/151)
|
|
644
|
-
if (node.type === 'UnaryExpression' && node.operator === 'typeof') {
|
|
645
|
-
const flattened = flatten(node.argument);
|
|
646
|
-
if (!flattened) return;
|
|
647
|
-
|
|
648
|
-
if (scope.contains(flattened.name)) return;
|
|
649
|
-
|
|
650
|
-
if (
|
|
651
|
-
flattened.keypath === 'module.exports' ||
|
|
652
|
-
flattened.keypath === 'module' ||
|
|
653
|
-
flattened.keypath === 'exports'
|
|
654
|
-
) {
|
|
655
|
-
magicString.overwrite(node.start, node.end, `'object'`, { storeName: false });
|
|
656
|
-
}
|
|
657
|
-
}
|
|
658
|
-
|
|
659
|
-
// rewrite `require` (if not already handled) `global` and `define`, and handle free references to
|
|
660
|
-
// `module` and `exports` as these mean we need to wrap the module in commonjsHelpers.createCommonjsModule
|
|
661
|
-
if (node.type === 'Identifier') {
|
|
662
|
-
if (isReference(node, parent) && !scope.contains(node.name)) {
|
|
663
|
-
if (node.name in uses) {
|
|
664
|
-
if (isRequireIdentifier(node)) {
|
|
665
|
-
if (isNodeRequireStatement(parent)) {
|
|
666
|
-
return;
|
|
667
|
-
}
|
|
668
|
-
|
|
669
|
-
if (!isDynamicRequireModulesEnabled && isStaticRequireStatement(parent)) {
|
|
670
|
-
return;
|
|
671
|
-
}
|
|
672
|
-
|
|
673
|
-
if (isDynamicRequireModulesEnabled && isRequireStatement(parent)) {
|
|
674
|
-
magicString.appendLeft(
|
|
675
|
-
parent.end - 1,
|
|
676
|
-
`,${JSON.stringify(
|
|
677
|
-
dirname(id) === '.'
|
|
678
|
-
? null /* default behavior */
|
|
679
|
-
: getVirtualPathForDynamicRequirePath(
|
|
680
|
-
normalizePathSlashes(dirname(id)),
|
|
681
|
-
commonDir
|
|
682
|
-
)
|
|
683
|
-
)}`
|
|
684
|
-
);
|
|
685
|
-
}
|
|
686
|
-
|
|
687
|
-
magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, {
|
|
688
|
-
storeName: true
|
|
689
|
-
});
|
|
690
|
-
usesCommonjsHelpers = true;
|
|
691
|
-
}
|
|
692
|
-
|
|
693
|
-
uses[node.name] = true;
|
|
694
|
-
if (node.name === 'global' && !ignoreGlobal) {
|
|
695
|
-
magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsGlobal`, {
|
|
696
|
-
storeName: true
|
|
697
|
-
});
|
|
698
|
-
usesCommonjsHelpers = true;
|
|
699
|
-
}
|
|
700
|
-
|
|
701
|
-
// if module or exports are used outside the context of an assignment
|
|
702
|
-
// expression, we need to wrap the module
|
|
703
|
-
if (node.name === 'module' || node.name === 'exports') {
|
|
704
|
-
shouldWrap = true;
|
|
705
|
-
}
|
|
706
|
-
}
|
|
707
|
-
|
|
708
|
-
if (node.name === 'define') {
|
|
709
|
-
magicString.overwrite(node.start, node.end, 'undefined', { storeName: true });
|
|
710
|
-
}
|
|
711
|
-
|
|
712
|
-
globals.add(node.name);
|
|
713
|
-
}
|
|
714
|
-
|
|
715
|
-
return;
|
|
716
|
-
}
|
|
717
|
-
|
|
718
|
-
// Is this an assignment to exports or module.exports?
|
|
719
|
-
if (node.type === 'AssignmentExpression') {
|
|
720
|
-
if (node.left.type !== 'MemberExpression') return;
|
|
721
|
-
|
|
722
|
-
const flattened = flatten(node.left);
|
|
723
|
-
if (!flattened) return;
|
|
724
|
-
|
|
725
|
-
if (scope.contains(flattened.name)) return;
|
|
726
|
-
|
|
727
|
-
const match = exportsPattern.exec(flattened.keypath);
|
|
728
|
-
if (!match || flattened.keypath === 'exports') return;
|
|
729
|
-
|
|
730
|
-
uses[flattened.name] = true;
|
|
731
|
-
|
|
732
|
-
// we're dealing with `module.exports = ...` or `[module.]exports.foo = ...` –
|
|
733
|
-
// if this isn't top-level, we'll need to wrap the module
|
|
734
|
-
if (programDepth > 3) shouldWrap = true;
|
|
735
|
-
|
|
736
|
-
node.left._skip = true;
|
|
737
|
-
|
|
738
|
-
if (flattened.keypath === 'module.exports' && node.right.type === 'ObjectExpression') {
|
|
739
|
-
node.right.properties.forEach((prop) => {
|
|
740
|
-
if (prop.computed || !('key' in prop) || prop.key.type !== 'Identifier') return;
|
|
741
|
-
const { name } = prop.key;
|
|
742
|
-
if (name === makeLegalIdentifier(name)) namedExports[name] = true;
|
|
743
|
-
});
|
|
744
|
-
return;
|
|
745
|
-
}
|
|
746
|
-
|
|
747
|
-
if (match[1]) namedExports[match[1]] = true;
|
|
748
|
-
return;
|
|
749
|
-
}
|
|
750
|
-
|
|
751
|
-
const name = getDefinePropertyCallName(node, 'exports');
|
|
752
|
-
if (name && name === makeLegalIdentifier(name)) namedExports[name] = true;
|
|
753
|
-
|
|
754
|
-
// if this is `var x = require('x')`, we can do `import x from 'x'`
|
|
755
|
-
if (
|
|
756
|
-
node.type === 'VariableDeclarator' &&
|
|
757
|
-
node.id.type === 'Identifier' &&
|
|
758
|
-
isStaticRequireStatement(node.init) &&
|
|
759
|
-
!isIgnoredRequireStatement(node.init)
|
|
760
|
-
) {
|
|
761
|
-
// for now, only do this for top-level requires. maybe fix this in future
|
|
762
|
-
if (scope.parent) return;
|
|
763
|
-
|
|
764
|
-
// edge case — CJS allows you to assign to imports. ES doesn't
|
|
765
|
-
if (assignedTo.has(node.id.name)) return;
|
|
766
|
-
|
|
767
|
-
const required = getRequired(node.init, node.id.name);
|
|
768
|
-
required.importsDefault = true;
|
|
769
|
-
|
|
770
|
-
if (required.name === node.id.name && !required.isDynamic) {
|
|
771
|
-
node._shouldRemove = true;
|
|
772
|
-
}
|
|
773
|
-
}
|
|
774
|
-
|
|
775
|
-
if (!isStaticRequireStatement(node) || isIgnoredRequireStatement(node)) {
|
|
776
|
-
return;
|
|
777
|
-
}
|
|
778
|
-
|
|
779
|
-
const required = getRequired(node);
|
|
780
|
-
|
|
781
|
-
if (parent.type === 'ExpressionStatement') {
|
|
782
|
-
// is a bare import, e.g. `require('foo');`
|
|
783
|
-
magicString.remove(parent.start, parent.end);
|
|
784
|
-
} else {
|
|
785
|
-
required.importsDefault = true;
|
|
786
|
-
|
|
787
|
-
if (shouldUseSimulatedRequire(required)) {
|
|
788
|
-
magicString.overwrite(
|
|
789
|
-
node.start,
|
|
790
|
-
node.end,
|
|
791
|
-
`${HELPERS_NAME}.commonjsRequire(${JSON.stringify(
|
|
792
|
-
getVirtualPathForDynamicRequirePath(normalizePathSlashes(required.source), commonDir)
|
|
793
|
-
)}, ${JSON.stringify(
|
|
794
|
-
dirname(id) === '.'
|
|
795
|
-
? null /* default behavior */
|
|
796
|
-
: getVirtualPathForDynamicRequirePath(normalizePathSlashes(dirname(id)), commonDir)
|
|
797
|
-
)})`
|
|
798
|
-
);
|
|
799
|
-
usesCommonjsHelpers = true;
|
|
800
|
-
} else {
|
|
801
|
-
magicString.overwrite(node.start, node.end, required.name);
|
|
802
|
-
}
|
|
803
|
-
}
|
|
804
|
-
|
|
805
|
-
node.callee._skip = true;
|
|
806
|
-
},
|
|
807
|
-
|
|
808
|
-
leave(node) {
|
|
809
|
-
programDepth -= 1;
|
|
810
|
-
if (node.scope) scope = scope.parent;
|
|
811
|
-
if (functionType.test(node.type)) lexicalDepth -= 1;
|
|
812
|
-
|
|
813
|
-
if (node.type === 'VariableDeclaration') {
|
|
814
|
-
let keepDeclaration = false;
|
|
815
|
-
let c = node.declarations[0].start;
|
|
816
|
-
|
|
817
|
-
for (let i = 0; i < node.declarations.length; i += 1) {
|
|
818
|
-
const declarator = node.declarations[i];
|
|
819
|
-
|
|
820
|
-
if (declarator._shouldRemove) {
|
|
821
|
-
magicString.remove(c, declarator.end);
|
|
822
|
-
} else {
|
|
823
|
-
if (!keepDeclaration) {
|
|
824
|
-
magicString.remove(c, declarator.start);
|
|
825
|
-
keepDeclaration = true;
|
|
826
|
-
}
|
|
827
|
-
|
|
828
|
-
c = declarator.end;
|
|
829
|
-
}
|
|
830
|
-
}
|
|
831
|
-
|
|
832
|
-
if (!keepDeclaration) {
|
|
833
|
-
magicString.remove(node.start, node.end);
|
|
834
|
-
}
|
|
835
|
-
}
|
|
836
|
-
}
|
|
837
|
-
});
|
|
838
|
-
|
|
839
|
-
// If `isEsModule` is on, it means it has ES6 import/export statements,
|
|
840
|
-
// which just can't be wrapped in a function.
|
|
841
|
-
shouldWrap = shouldWrap && !disableWrap && !isEsModule;
|
|
842
|
-
|
|
843
|
-
usesCommonjsHelpers = usesCommonjsHelpers || shouldWrap;
|
|
844
|
-
|
|
845
|
-
if (
|
|
846
|
-
!requiredSources.length &&
|
|
847
|
-
!dynamicRegisterSources.length &&
|
|
848
|
-
!uses.module &&
|
|
849
|
-
!uses.exports &&
|
|
850
|
-
!uses.require &&
|
|
851
|
-
!usesCommonjsHelpers &&
|
|
852
|
-
(ignoreGlobal || !uses.global)
|
|
853
|
-
) {
|
|
854
|
-
return { meta: { commonjs: { isCommonJS: false } } };
|
|
855
|
-
}
|
|
856
|
-
|
|
857
|
-
const importBlock = `${(usesCommonjsHelpers
|
|
858
|
-
? [`import * as ${HELPERS_NAME} from '${HELPERS_ID}';`]
|
|
859
|
-
: []
|
|
860
|
-
)
|
|
861
|
-
.concat(
|
|
862
|
-
// dynamic registers first, as the may be required in the other modules
|
|
863
|
-
dynamicRegisterSources.map((source) => `import '${source}';`),
|
|
864
|
-
|
|
865
|
-
// now the actual modules so that they are analyzed before creating the proxies;
|
|
866
|
-
// no need to do this for virtual modules as we never proxy them
|
|
867
|
-
requiredSources
|
|
868
|
-
.filter((source) => !source.startsWith('\0'))
|
|
869
|
-
.map((source) => `import '${wrapId(source, REQUIRE_SUFFIX)}';`),
|
|
870
|
-
|
|
871
|
-
// now the proxy modules
|
|
872
|
-
requiredSources.map((source) => {
|
|
873
|
-
const { name, importsDefault } = required[source];
|
|
874
|
-
return `import ${importsDefault ? `${name} from ` : ``}'${
|
|
875
|
-
source.startsWith('\0') ? source : wrapId(source, PROXY_SUFFIX)
|
|
876
|
-
}';`;
|
|
877
|
-
})
|
|
878
|
-
)
|
|
879
|
-
.join('\n')}\n\n`;
|
|
880
|
-
|
|
881
|
-
const namedExportDeclarations = [];
|
|
882
|
-
let wrapperStart = '';
|
|
883
|
-
let wrapperEnd = '';
|
|
884
|
-
|
|
885
|
-
const moduleName = deconflict(scope, globals, getName(id));
|
|
886
|
-
if (!isEsModule) {
|
|
887
|
-
const exportModuleExports = {
|
|
888
|
-
str: `export { ${moduleName} as __moduleExports };`,
|
|
889
|
-
name: '__moduleExports'
|
|
890
|
-
};
|
|
891
|
-
|
|
892
|
-
namedExportDeclarations.push(exportModuleExports);
|
|
893
|
-
}
|
|
894
|
-
|
|
895
|
-
const defaultExportPropertyAssignments = [];
|
|
896
|
-
let hasDefaultExport = false;
|
|
897
|
-
|
|
898
|
-
if (shouldWrap) {
|
|
899
|
-
const args = `module${uses.exports ? ', exports' : ''}`;
|
|
900
|
-
|
|
901
|
-
wrapperStart = `var ${moduleName} = ${HELPERS_NAME}.createCommonjsModule(function (${args}) {\n`;
|
|
902
|
-
|
|
903
|
-
wrapperEnd = `\n}`;
|
|
904
|
-
if (isDynamicRequireModulesEnabled) {
|
|
905
|
-
wrapperEnd += `, ${JSON.stringify(
|
|
906
|
-
getVirtualPathForDynamicRequirePath(normalizePathSlashes(dirname(id)), commonDir)
|
|
907
|
-
)}`;
|
|
908
|
-
}
|
|
909
|
-
|
|
910
|
-
wrapperEnd += `);`;
|
|
911
|
-
} else {
|
|
912
|
-
const names = [];
|
|
913
|
-
|
|
914
|
-
for (const node of ast.body) {
|
|
915
|
-
if (node.type === 'ExpressionStatement' && node.expression.type === 'AssignmentExpression') {
|
|
916
|
-
const { left } = node.expression;
|
|
917
|
-
const flattened = flatten(left);
|
|
918
|
-
|
|
919
|
-
if (!flattened) {
|
|
920
|
-
continue;
|
|
921
|
-
}
|
|
922
|
-
|
|
923
|
-
const match = exportsPattern.exec(flattened.keypath);
|
|
924
|
-
if (!match) {
|
|
925
|
-
continue;
|
|
926
|
-
}
|
|
927
|
-
|
|
928
|
-
if (flattened.keypath === 'module.exports') {
|
|
929
|
-
hasDefaultExport = true;
|
|
930
|
-
magicString.overwrite(left.start, left.end, `var ${moduleName}`);
|
|
931
|
-
} else {
|
|
932
|
-
const [, name] = match;
|
|
933
|
-
const deconflicted = deconflict(scope, globals, name);
|
|
934
|
-
|
|
935
|
-
names.push({ name, deconflicted });
|
|
936
|
-
|
|
937
|
-
magicString.overwrite(node.start, left.end, `var ${deconflicted}`);
|
|
938
|
-
|
|
939
|
-
const declaration =
|
|
940
|
-
name === deconflicted
|
|
941
|
-
? `export { ${name} };`
|
|
942
|
-
: `export { ${deconflicted} as ${name} };`;
|
|
943
|
-
|
|
944
|
-
if (name !== 'default') {
|
|
945
|
-
namedExportDeclarations.push({
|
|
946
|
-
str: declaration,
|
|
947
|
-
name
|
|
948
|
-
});
|
|
949
|
-
}
|
|
950
|
-
|
|
951
|
-
defaultExportPropertyAssignments.push(`${moduleName}.${name} = ${deconflicted};`);
|
|
952
|
-
}
|
|
953
|
-
}
|
|
954
|
-
}
|
|
955
|
-
|
|
956
|
-
if (!(isEsModule || hasDefaultExport)) {
|
|
957
|
-
wrapperEnd = `\n\nvar ${moduleName} = {\n${names
|
|
958
|
-
.map(({ name, deconflicted }) => `\t${name}: ${deconflicted}`)
|
|
959
|
-
.join(',\n')}\n};`;
|
|
960
|
-
}
|
|
961
|
-
}
|
|
962
|
-
|
|
963
|
-
magicString
|
|
964
|
-
.trim()
|
|
965
|
-
.prepend(importBlock + wrapperStart)
|
|
966
|
-
.trim()
|
|
967
|
-
.append(wrapperEnd);
|
|
968
|
-
|
|
969
|
-
const defaultExport =
|
|
970
|
-
code.indexOf('__esModule') >= 0
|
|
971
|
-
? `export default /*@__PURE__*/${HELPERS_NAME}.getDefaultExportFromCjs(${moduleName});`
|
|
972
|
-
: `export default ${moduleName};`;
|
|
973
|
-
|
|
974
|
-
const named = namedExportDeclarations
|
|
975
|
-
.filter((x) => x.name !== 'default' || !hasDefaultExport)
|
|
976
|
-
.map((x) => x.str);
|
|
977
|
-
|
|
978
|
-
magicString.append(
|
|
979
|
-
`\n\n${(isEsModule ? [] : [defaultExport])
|
|
980
|
-
.concat(named)
|
|
981
|
-
.concat(hasDefaultExport ? defaultExportPropertyAssignments : [])
|
|
982
|
-
.join('\n')}`
|
|
983
|
-
);
|
|
984
|
-
|
|
985
|
-
code = magicString.toString();
|
|
986
|
-
const map = sourceMap ? magicString.generateMap() : null;
|
|
987
|
-
|
|
988
|
-
return {
|
|
989
|
-
code,
|
|
990
|
-
map,
|
|
991
|
-
syntheticNamedExports: isEsModule ? false : '__moduleExports',
|
|
992
|
-
meta: { commonjs: { isCommonJS: !isEsModule } }
|
|
993
|
-
};
|
|
994
|
-
}
|
|
995
|
-
|
|
996
|
-
function getDynamicPackagesModule(dynamicRequireModuleDirPaths, commonDir) {
|
|
997
|
-
let code = `const commonjsRegister = require('${HELPERS_ID}?commonjsRegister');`;
|
|
998
|
-
for (const dir of dynamicRequireModuleDirPaths) {
|
|
999
|
-
let entryPoint = 'index.js';
|
|
1000
|
-
|
|
1001
|
-
try {
|
|
1002
|
-
if (existsSync(join(dir, 'package.json'))) {
|
|
1003
|
-
entryPoint =
|
|
1004
|
-
JSON.parse(readFileSync(join(dir, 'package.json'), { encoding: 'utf8' })).main ||
|
|
1005
|
-
entryPoint;
|
|
1006
|
-
}
|
|
1007
|
-
} catch (ignored) {
|
|
1008
|
-
// ignored
|
|
1009
|
-
}
|
|
1010
|
-
|
|
1011
|
-
code += `\ncommonjsRegister(${JSON.stringify(
|
|
1012
|
-
getVirtualPathForDynamicRequirePath(dir, commonDir)
|
|
1013
|
-
)}, function (module, exports) {
|
|
1014
|
-
module.exports = require(${JSON.stringify(normalizePathSlashes(join(dir, entryPoint)))});
|
|
1015
|
-
});`;
|
|
1016
|
-
}
|
|
1017
|
-
return code;
|
|
1018
|
-
}
|
|
1019
|
-
|
|
1020
|
-
function getDynamicPackagesEntryIntro(
|
|
1021
|
-
dynamicRequireModuleDirPaths,
|
|
1022
|
-
dynamicRequireModuleSet
|
|
1023
|
-
) {
|
|
1024
|
-
let dynamicImports = Array.from(
|
|
1025
|
-
dynamicRequireModuleSet,
|
|
1026
|
-
(dynamicId) => `require(${JSON.stringify(DYNAMIC_REGISTER_PREFIX + dynamicId)});`
|
|
1027
|
-
).join('\n');
|
|
1028
|
-
|
|
1029
|
-
if (dynamicRequireModuleDirPaths.length) {
|
|
1030
|
-
dynamicImports += `require(${JSON.stringify(DYNAMIC_REGISTER_PREFIX + DYNAMIC_PACKAGES_ID)});`;
|
|
1031
|
-
}
|
|
1032
|
-
|
|
1033
|
-
return dynamicImports;
|
|
1034
|
-
}
|
|
1035
|
-
|
|
1036
|
-
function isModuleRegistrationProxy(id, dynamicRequireModuleSet) {
|
|
1037
|
-
const normalizedPath = normalizePathSlashes(id);
|
|
1038
|
-
return dynamicRequireModuleSet.has(normalizedPath) && !normalizedPath.endsWith('.json');
|
|
1039
|
-
}
|
|
1040
|
-
|
|
1041
|
-
function getDynamicRequirePaths(patterns) {
|
|
1042
|
-
const dynamicRequireModuleSet = new Set();
|
|
1043
|
-
for (const pattern of !patterns || Array.isArray(patterns) ? patterns || [] : [patterns]) {
|
|
1044
|
-
const isNegated = pattern.startsWith('!');
|
|
1045
|
-
const modifySet = Set.prototype[isNegated ? 'delete' : 'add'].bind(dynamicRequireModuleSet);
|
|
1046
|
-
for (const path of glob.sync(isNegated ? pattern.substr(1) : pattern)) {
|
|
1047
|
-
modifySet(normalizePathSlashes(resolve(path)));
|
|
1048
|
-
}
|
|
1049
|
-
}
|
|
1050
|
-
const dynamicRequireModuleDirPaths = Array.from(dynamicRequireModuleSet.values()).filter(
|
|
1051
|
-
(path) => {
|
|
1052
|
-
try {
|
|
1053
|
-
if (statSync(path).isDirectory()) return true;
|
|
1054
|
-
} catch (ignored) {
|
|
1055
|
-
// Nothing to do here
|
|
1056
|
-
}
|
|
1057
|
-
return false;
|
|
1058
|
-
}
|
|
1059
|
-
);
|
|
1060
|
-
return { dynamicRequireModuleSet, dynamicRequireModuleDirPaths };
|
|
1061
|
-
}
|
|
1062
|
-
|
|
1063
|
-
const isCjsPromises = new Map();
|
|
1064
|
-
|
|
1065
|
-
function getIsCjsPromise(id) {
|
|
1066
|
-
let isCjsPromise = isCjsPromises.get(id);
|
|
1067
|
-
if (isCjsPromise) return isCjsPromise.promise;
|
|
1068
|
-
|
|
1069
|
-
const promise = new Promise((resolve) => {
|
|
1070
|
-
isCjsPromise = {
|
|
1071
|
-
resolve,
|
|
1072
|
-
promise: null
|
|
1073
|
-
};
|
|
1074
|
-
isCjsPromises.set(id, isCjsPromise);
|
|
1075
|
-
});
|
|
1076
|
-
isCjsPromise.promise = promise;
|
|
1077
|
-
|
|
1078
|
-
return promise;
|
|
412
|
+
return promise;
|
|
1079
413
|
}
|
|
1080
414
|
|
|
1081
415
|
function setIsCjsPromise(id, resolution) {
|
|
@@ -1155,78 +489,916 @@ async function getStaticRequireProxy(
|
|
|
1155
489
|
return `export {default} from ${JSON.stringify(id)};`;
|
|
1156
490
|
}
|
|
1157
491
|
|
|
1158
|
-
/* eslint-disable no-param-reassign, no-undefined */
|
|
492
|
+
/* eslint-disable no-param-reassign, no-undefined */
|
|
493
|
+
|
|
494
|
+
function getCandidatesForExtension(resolved, extension) {
|
|
495
|
+
return [resolved + extension, `${resolved}${sep}index${extension}`];
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
function getCandidates(resolved, extensions) {
|
|
499
|
+
return extensions.reduce(
|
|
500
|
+
(paths, extension) => paths.concat(getCandidatesForExtension(resolved, extension)),
|
|
501
|
+
[resolved]
|
|
502
|
+
);
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
function getResolveId(extensions) {
|
|
506
|
+
function resolveExtensions(importee, importer) {
|
|
507
|
+
// not our problem
|
|
508
|
+
if (importee[0] !== '.' || !importer) return undefined;
|
|
509
|
+
|
|
510
|
+
const resolved = resolve(dirname(importer), importee);
|
|
511
|
+
const candidates = getCandidates(resolved, extensions);
|
|
512
|
+
|
|
513
|
+
for (let i = 0; i < candidates.length; i += 1) {
|
|
514
|
+
try {
|
|
515
|
+
const stats = statSync(candidates[i]);
|
|
516
|
+
if (stats.isFile()) return { id: candidates[i] };
|
|
517
|
+
} catch (err) {
|
|
518
|
+
/* noop */
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
return undefined;
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
return function resolveId(importee, importer) {
|
|
526
|
+
// Proxies are only importing resolved ids, no need to resolve again
|
|
527
|
+
if (importer && isWrappedId(importer, PROXY_SUFFIX)) {
|
|
528
|
+
return importee;
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
const isProxyModule = isWrappedId(importee, PROXY_SUFFIX);
|
|
532
|
+
const isRequiredModule = isWrappedId(importee, REQUIRE_SUFFIX);
|
|
533
|
+
if (isProxyModule) {
|
|
534
|
+
importee = unwrapId(importee, PROXY_SUFFIX);
|
|
535
|
+
} else if (isRequiredModule) {
|
|
536
|
+
importee = unwrapId(importee, REQUIRE_SUFFIX);
|
|
537
|
+
}
|
|
538
|
+
if (importee.startsWith('\0')) {
|
|
539
|
+
if (
|
|
540
|
+
importee.startsWith(HELPERS_ID) ||
|
|
541
|
+
importee === DYNAMIC_PACKAGES_ID ||
|
|
542
|
+
importee.startsWith(DYNAMIC_JSON_PREFIX)
|
|
543
|
+
) {
|
|
544
|
+
return importee;
|
|
545
|
+
}
|
|
546
|
+
return null;
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
return this.resolve(importee, importer, {
|
|
550
|
+
skipSelf: true,
|
|
551
|
+
custom: { 'node-resolve': { isRequire: isProxyModule || isRequiredModule } }
|
|
552
|
+
}).then((resolved) => {
|
|
553
|
+
if (!resolved) {
|
|
554
|
+
resolved = resolveExtensions(importee, importer);
|
|
555
|
+
}
|
|
556
|
+
if (resolved && isProxyModule) {
|
|
557
|
+
resolved.id = wrapId(resolved.id, resolved.external ? EXTERNAL_SUFFIX : PROXY_SUFFIX);
|
|
558
|
+
resolved.external = false;
|
|
559
|
+
} else if (!resolved && (isProxyModule || isRequiredModule)) {
|
|
560
|
+
return { id: wrapId(importee, EXTERNAL_SUFFIX), external: false };
|
|
561
|
+
}
|
|
562
|
+
return resolved;
|
|
563
|
+
});
|
|
564
|
+
};
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
function validateRollupVersion(rollupVersion, peerDependencyVersion) {
|
|
568
|
+
const [major, minor] = rollupVersion.split('.').map(Number);
|
|
569
|
+
const versionRegexp = /\^(\d+\.\d+)\.\d+/g;
|
|
570
|
+
let minMajor = Infinity;
|
|
571
|
+
let minMinor = Infinity;
|
|
572
|
+
let foundVersion;
|
|
573
|
+
// eslint-disable-next-line no-cond-assign
|
|
574
|
+
while ((foundVersion = versionRegexp.exec(peerDependencyVersion))) {
|
|
575
|
+
const [foundMajor, foundMinor] = foundVersion[1].split('.').map(Number);
|
|
576
|
+
if (foundMajor < minMajor) {
|
|
577
|
+
minMajor = foundMajor;
|
|
578
|
+
minMinor = foundMinor;
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
if (major < minMajor || (major === minMajor && minor < minMinor)) {
|
|
582
|
+
throw new Error(
|
|
583
|
+
`Insufficient Rollup version: "@rollup/plugin-commonjs" requires at least rollup@${minMajor}.${minMinor} but found rollup@${rollupVersion}.`
|
|
584
|
+
);
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
const operators = {
|
|
589
|
+
'==': (x) => equals(x.left, x.right, false),
|
|
590
|
+
|
|
591
|
+
'!=': (x) => not(operators['=='](x)),
|
|
592
|
+
|
|
593
|
+
'===': (x) => equals(x.left, x.right, true),
|
|
594
|
+
|
|
595
|
+
'!==': (x) => not(operators['==='](x)),
|
|
596
|
+
|
|
597
|
+
'!': (x) => isFalsy(x.argument),
|
|
598
|
+
|
|
599
|
+
'&&': (x) => isTruthy(x.left) && isTruthy(x.right),
|
|
600
|
+
|
|
601
|
+
'||': (x) => isTruthy(x.left) || isTruthy(x.right)
|
|
602
|
+
};
|
|
603
|
+
|
|
604
|
+
function not(value) {
|
|
605
|
+
return value === null ? value : !value;
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
function equals(a, b, strict) {
|
|
609
|
+
if (a.type !== b.type) return null;
|
|
610
|
+
// eslint-disable-next-line eqeqeq
|
|
611
|
+
if (a.type === 'Literal') return strict ? a.value === b.value : a.value == b.value;
|
|
612
|
+
return null;
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
function isTruthy(node) {
|
|
616
|
+
if (!node) return false;
|
|
617
|
+
if (node.type === 'Literal') return !!node.value;
|
|
618
|
+
if (node.type === 'ParenthesizedExpression') return isTruthy(node.expression);
|
|
619
|
+
if (node.operator in operators) return operators[node.operator](node);
|
|
620
|
+
return null;
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
function isFalsy(node) {
|
|
624
|
+
return not(isTruthy(node));
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
function getKeypath(node) {
|
|
628
|
+
const parts = [];
|
|
629
|
+
|
|
630
|
+
while (node.type === 'MemberExpression') {
|
|
631
|
+
if (node.computed) return null;
|
|
632
|
+
|
|
633
|
+
parts.unshift(node.property.name);
|
|
634
|
+
// eslint-disable-next-line no-param-reassign
|
|
635
|
+
node = node.object;
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
if (node.type !== 'Identifier') return null;
|
|
639
|
+
|
|
640
|
+
const { name } = node;
|
|
641
|
+
parts.unshift(name);
|
|
642
|
+
|
|
643
|
+
return { name, keypath: parts.join('.') };
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
const KEY_COMPILED_ESM = '__esModule';
|
|
647
|
+
|
|
648
|
+
function isDefineCompiledEsm(node) {
|
|
649
|
+
const definedProperty =
|
|
650
|
+
getDefinePropertyCallName(node, 'exports') || getDefinePropertyCallName(node, 'module.exports');
|
|
651
|
+
if (definedProperty && definedProperty.key === KEY_COMPILED_ESM) {
|
|
652
|
+
return isTruthy(definedProperty.value);
|
|
653
|
+
}
|
|
654
|
+
return false;
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
function getDefinePropertyCallName(node, targetName) {
|
|
658
|
+
const targetNames = targetName.split('.');
|
|
659
|
+
|
|
660
|
+
const {
|
|
661
|
+
callee: { object, property }
|
|
662
|
+
} = node;
|
|
663
|
+
if (!object || object.type !== 'Identifier' || object.name !== 'Object') return;
|
|
664
|
+
if (!property || property.type !== 'Identifier' || property.name !== 'defineProperty') return;
|
|
665
|
+
if (node.arguments.length !== 3) return;
|
|
666
|
+
|
|
667
|
+
const [target, key, value] = node.arguments;
|
|
668
|
+
if (targetNames.length === 1) {
|
|
669
|
+
if (target.type !== 'Identifier' || target.name !== targetNames[0]) {
|
|
670
|
+
return;
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
if (targetNames.length === 2) {
|
|
675
|
+
if (
|
|
676
|
+
target.type !== 'MemberExpression' ||
|
|
677
|
+
target.object.name !== targetNames[0] ||
|
|
678
|
+
target.property.name !== targetNames[1]
|
|
679
|
+
) {
|
|
680
|
+
return;
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
if (value.type !== 'ObjectExpression' || !value.properties) return;
|
|
685
|
+
|
|
686
|
+
const valueProperty = value.properties.find((p) => p.key && p.key.name === 'value');
|
|
687
|
+
if (!valueProperty || !valueProperty.value) return;
|
|
688
|
+
|
|
689
|
+
// eslint-disable-next-line consistent-return
|
|
690
|
+
return { key: key.value, value: valueProperty.value };
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
function isLocallyShadowed(name, scope) {
|
|
694
|
+
while (scope.parent) {
|
|
695
|
+
if (scope.declarations[name]) {
|
|
696
|
+
return true;
|
|
697
|
+
}
|
|
698
|
+
// eslint-disable-next-line no-param-reassign
|
|
699
|
+
scope = scope.parent;
|
|
700
|
+
}
|
|
701
|
+
return false;
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
function wrapCode(magicString, uses, moduleName, HELPERS_NAME, virtualDynamicRequirePath) {
|
|
705
|
+
const args = `module${uses.exports ? ', exports' : ''}`;
|
|
706
|
+
|
|
707
|
+
magicString
|
|
708
|
+
.trim()
|
|
709
|
+
.prepend(`var ${moduleName} = ${HELPERS_NAME}.createCommonjsModule(function (${args}) {\n`)
|
|
710
|
+
.append(
|
|
711
|
+
`\n}${virtualDynamicRequirePath ? `, ${JSON.stringify(virtualDynamicRequirePath)}` : ''});`
|
|
712
|
+
);
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
function rewriteExportsAndGetExportsBlock(
|
|
716
|
+
magicString,
|
|
717
|
+
moduleName,
|
|
718
|
+
wrapped,
|
|
719
|
+
topLevelModuleExportsAssignments,
|
|
720
|
+
topLevelExportsAssignmentsByName,
|
|
721
|
+
defineCompiledEsmExpressions,
|
|
722
|
+
deconflict,
|
|
723
|
+
isRestorableCompiledEsm,
|
|
724
|
+
code,
|
|
725
|
+
uses,
|
|
726
|
+
HELPERS_NAME
|
|
727
|
+
) {
|
|
728
|
+
const namedExportDeclarations = [`export { ${moduleName} as __moduleExports };`];
|
|
729
|
+
const moduleExportsPropertyAssignments = [];
|
|
730
|
+
let deconflictedDefaultExportName;
|
|
731
|
+
|
|
732
|
+
if (!wrapped) {
|
|
733
|
+
let hasModuleExportsAssignment = false;
|
|
734
|
+
const namedExportProperties = [];
|
|
735
|
+
|
|
736
|
+
// Collect and rewrite module.exports assignments
|
|
737
|
+
for (const { left } of topLevelModuleExportsAssignments) {
|
|
738
|
+
hasModuleExportsAssignment = true;
|
|
739
|
+
magicString.overwrite(left.start, left.end, `var ${moduleName}`);
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
// Collect and rewrite named exports
|
|
743
|
+
for (const [exportName, node] of topLevelExportsAssignmentsByName) {
|
|
744
|
+
const deconflicted = deconflict(exportName);
|
|
745
|
+
magicString.overwrite(node.start, node.left.end, `var ${deconflicted}`);
|
|
746
|
+
|
|
747
|
+
if (exportName === 'default') {
|
|
748
|
+
deconflictedDefaultExportName = deconflicted;
|
|
749
|
+
} else {
|
|
750
|
+
namedExportDeclarations.push(
|
|
751
|
+
exportName === deconflicted
|
|
752
|
+
? `export { ${exportName} };`
|
|
753
|
+
: `export { ${deconflicted} as ${exportName} };`
|
|
754
|
+
);
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
if (hasModuleExportsAssignment) {
|
|
758
|
+
moduleExportsPropertyAssignments.push(`${moduleName}.${exportName} = ${deconflicted};`);
|
|
759
|
+
} else {
|
|
760
|
+
namedExportProperties.push(`\t${exportName}: ${deconflicted}`);
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
// Regenerate CommonJS namespace
|
|
765
|
+
if (!hasModuleExportsAssignment) {
|
|
766
|
+
const moduleExports = `{\n${namedExportProperties.join(',\n')}\n}`;
|
|
767
|
+
magicString
|
|
768
|
+
.trim()
|
|
769
|
+
.append(
|
|
770
|
+
`\n\nvar ${moduleName} = ${
|
|
771
|
+
isRestorableCompiledEsm
|
|
772
|
+
? `/*#__PURE__*/Object.defineProperty(${moduleExports}, '__esModule', {value: true})`
|
|
773
|
+
: moduleExports
|
|
774
|
+
};`
|
|
775
|
+
);
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
// Generate default export
|
|
780
|
+
const defaultExport = [];
|
|
781
|
+
if (isRestorableCompiledEsm) {
|
|
782
|
+
defaultExport.push(`export default ${deconflictedDefaultExportName || moduleName};`);
|
|
783
|
+
} else if (
|
|
784
|
+
(wrapped || deconflictedDefaultExportName) &&
|
|
785
|
+
(defineCompiledEsmExpressions.length > 0 || code.indexOf('__esModule') >= 0)
|
|
786
|
+
) {
|
|
787
|
+
// eslint-disable-next-line no-param-reassign
|
|
788
|
+
uses.commonjsHelpers = true;
|
|
789
|
+
defaultExport.push(
|
|
790
|
+
`export default /*@__PURE__*/${HELPERS_NAME}.getDefaultExportFromCjs(${moduleName});`
|
|
791
|
+
);
|
|
792
|
+
} else {
|
|
793
|
+
defaultExport.push(`export default ${moduleName};`);
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
return `\n\n${defaultExport
|
|
797
|
+
.concat(namedExportDeclarations)
|
|
798
|
+
.concat(moduleExportsPropertyAssignments)
|
|
799
|
+
.join('\n')}`;
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
function isRequireStatement(node, scope) {
|
|
803
|
+
if (!node) return false;
|
|
804
|
+
if (node.type !== 'CallExpression') return false;
|
|
1159
805
|
|
|
1160
|
-
|
|
1161
|
-
|
|
806
|
+
// Weird case of `require()` or `module.require()` without arguments
|
|
807
|
+
if (node.arguments.length === 0) return false;
|
|
808
|
+
|
|
809
|
+
return isRequire(node.callee, scope);
|
|
1162
810
|
}
|
|
1163
811
|
|
|
1164
|
-
function
|
|
1165
|
-
return
|
|
1166
|
-
(
|
|
1167
|
-
|
|
812
|
+
function isRequire(node, scope) {
|
|
813
|
+
return (
|
|
814
|
+
(node.type === 'Identifier' && node.name === 'require' && !scope.contains('require')) ||
|
|
815
|
+
(node.type === 'MemberExpression' && isModuleRequire(node, scope))
|
|
1168
816
|
);
|
|
1169
817
|
}
|
|
1170
818
|
|
|
1171
|
-
function
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
819
|
+
function isModuleRequire({ object, property }, scope) {
|
|
820
|
+
return (
|
|
821
|
+
object.type === 'Identifier' &&
|
|
822
|
+
object.name === 'module' &&
|
|
823
|
+
property.type === 'Identifier' &&
|
|
824
|
+
property.name === 'require' &&
|
|
825
|
+
!scope.contains('module')
|
|
826
|
+
);
|
|
827
|
+
}
|
|
1175
828
|
|
|
1176
|
-
|
|
1177
|
-
|
|
829
|
+
function isStaticRequireStatement(node, scope) {
|
|
830
|
+
if (!isRequireStatement(node, scope)) return false;
|
|
831
|
+
return !hasDynamicArguments(node);
|
|
832
|
+
}
|
|
1178
833
|
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
834
|
+
function hasDynamicArguments(node) {
|
|
835
|
+
return (
|
|
836
|
+
node.arguments.length > 1 ||
|
|
837
|
+
(node.arguments[0].type !== 'Literal' &&
|
|
838
|
+
(node.arguments[0].type !== 'TemplateLiteral' || node.arguments[0].expressions.length > 0))
|
|
839
|
+
);
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
const reservedMethod = { resolve: true, cache: true, main: true };
|
|
843
|
+
|
|
844
|
+
function isNodeRequirePropertyAccess(parent) {
|
|
845
|
+
return parent && parent.property && reservedMethod[parent.property.name];
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
function isIgnoredRequireStatement(requiredNode, ignoreRequire) {
|
|
849
|
+
return ignoreRequire(requiredNode.arguments[0].value);
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
function getRequireStringArg(node) {
|
|
853
|
+
return node.arguments[0].type === 'Literal'
|
|
854
|
+
? node.arguments[0].value
|
|
855
|
+
: node.arguments[0].quasis[0].value.cooked;
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
function hasDynamicModuleForPath(source, id, dynamicRequireModuleSet) {
|
|
859
|
+
if (!/^(?:\.{0,2}[/\\]|[A-Za-z]:[/\\])/.test(source)) {
|
|
860
|
+
try {
|
|
861
|
+
const resolvedPath = normalizePathSlashes(sync(source, { basedir: dirname(id) }));
|
|
862
|
+
if (dynamicRequireModuleSet.has(resolvedPath)) {
|
|
863
|
+
return true;
|
|
1185
864
|
}
|
|
865
|
+
} catch (ex) {
|
|
866
|
+
// Probably a node.js internal module
|
|
867
|
+
return false;
|
|
1186
868
|
}
|
|
1187
869
|
|
|
1188
|
-
return
|
|
870
|
+
return false;
|
|
1189
871
|
}
|
|
1190
872
|
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
if (
|
|
1194
|
-
return
|
|
873
|
+
for (const attemptExt of ['', '.js', '.json']) {
|
|
874
|
+
const resolvedPath = normalizePathSlashes(resolve(dirname(id), source + attemptExt));
|
|
875
|
+
if (dynamicRequireModuleSet.has(resolvedPath)) {
|
|
876
|
+
return true;
|
|
1195
877
|
}
|
|
878
|
+
}
|
|
1196
879
|
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
880
|
+
return false;
|
|
881
|
+
}
|
|
882
|
+
|
|
883
|
+
function getRequireHandlers() {
|
|
884
|
+
const requiredSources = [];
|
|
885
|
+
const requiredBySource = Object.create(null);
|
|
886
|
+
const requiredByNode = new Map();
|
|
887
|
+
const requireExpressionsWithUsedReturnValue = [];
|
|
888
|
+
|
|
889
|
+
function addRequireStatement(sourceId, node, scope, usesReturnValue) {
|
|
890
|
+
const required = getRequired(sourceId);
|
|
891
|
+
requiredByNode.set(node, { scope, required });
|
|
892
|
+
if (usesReturnValue) {
|
|
893
|
+
required.nodesUsingRequired.push(node);
|
|
894
|
+
requireExpressionsWithUsedReturnValue.push(node);
|
|
1203
895
|
}
|
|
1204
|
-
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
function getRequired(sourceId) {
|
|
899
|
+
if (!requiredBySource[sourceId]) {
|
|
900
|
+
requiredSources.push(sourceId);
|
|
901
|
+
|
|
902
|
+
requiredBySource[sourceId] = {
|
|
903
|
+
source: sourceId,
|
|
904
|
+
name: null,
|
|
905
|
+
nodesUsingRequired: []
|
|
906
|
+
};
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
return requiredBySource[sourceId];
|
|
910
|
+
}
|
|
911
|
+
|
|
912
|
+
function rewriteRequireExpressionsAndGetImportBlock(
|
|
913
|
+
magicString,
|
|
914
|
+
topLevelDeclarations,
|
|
915
|
+
topLevelRequireDeclarators,
|
|
916
|
+
reassignedNames,
|
|
917
|
+
helpersNameIfUsed,
|
|
918
|
+
dynamicRegisterSources
|
|
919
|
+
) {
|
|
920
|
+
const removedDeclarators = getDeclaratorsReplacedByImportsAndSetImportNames(
|
|
921
|
+
topLevelRequireDeclarators,
|
|
922
|
+
requiredByNode,
|
|
923
|
+
reassignedNames
|
|
924
|
+
);
|
|
925
|
+
setRemainingImportNamesAndRewriteRequires(
|
|
926
|
+
requireExpressionsWithUsedReturnValue,
|
|
927
|
+
requiredByNode,
|
|
928
|
+
magicString
|
|
929
|
+
);
|
|
930
|
+
removeDeclaratorsFromDeclarations(topLevelDeclarations, removedDeclarators, magicString);
|
|
931
|
+
const importBlock = `${(helpersNameIfUsed
|
|
932
|
+
? [`import * as ${helpersNameIfUsed} from '${HELPERS_ID}';`]
|
|
933
|
+
: []
|
|
934
|
+
)
|
|
935
|
+
.concat(
|
|
936
|
+
// dynamic registers first, as the may be required in the other modules
|
|
937
|
+
[...dynamicRegisterSources].map((source) => `import '${wrapId(source, REQUIRE_SUFFIX)}';`),
|
|
938
|
+
|
|
939
|
+
// now the actual modules so that they are analyzed before creating the proxies;
|
|
940
|
+
// no need to do this for virtual modules as we never proxy them
|
|
941
|
+
requiredSources
|
|
942
|
+
.filter((source) => !source.startsWith('\0'))
|
|
943
|
+
.map((source) => `import '${wrapId(source, REQUIRE_SUFFIX)}';`),
|
|
944
|
+
|
|
945
|
+
// now the proxy modules
|
|
946
|
+
requiredSources.map((source) => {
|
|
947
|
+
const { name, nodesUsingRequired } = requiredBySource[source];
|
|
948
|
+
return `import ${nodesUsingRequired.length ? `${name} from ` : ``}'${
|
|
949
|
+
source.startsWith('\0') ? source : wrapId(source, PROXY_SUFFIX)
|
|
950
|
+
}';`;
|
|
951
|
+
})
|
|
952
|
+
)
|
|
953
|
+
.join('\n')}`;
|
|
954
|
+
return importBlock ? `${importBlock}\n\n` : '';
|
|
955
|
+
}
|
|
956
|
+
|
|
957
|
+
return {
|
|
958
|
+
addRequireStatement,
|
|
959
|
+
requiredSources,
|
|
960
|
+
rewriteRequireExpressionsAndGetImportBlock
|
|
961
|
+
};
|
|
962
|
+
}
|
|
963
|
+
|
|
964
|
+
function getDeclaratorsReplacedByImportsAndSetImportNames(
|
|
965
|
+
topLevelRequireDeclarators,
|
|
966
|
+
requiredByNode,
|
|
967
|
+
reassignedNames
|
|
968
|
+
) {
|
|
969
|
+
const removedDeclarators = new Set();
|
|
970
|
+
for (const declarator of topLevelRequireDeclarators) {
|
|
971
|
+
const { required } = requiredByNode.get(declarator.init);
|
|
972
|
+
if (!required.name) {
|
|
973
|
+
const potentialName = declarator.id.name;
|
|
1205
974
|
if (
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
975
|
+
!reassignedNames.has(potentialName) &&
|
|
976
|
+
!required.nodesUsingRequired.some((node) =>
|
|
977
|
+
isLocallyShadowed(potentialName, requiredByNode.get(node).scope)
|
|
978
|
+
)
|
|
1209
979
|
) {
|
|
1210
|
-
|
|
980
|
+
required.name = potentialName;
|
|
981
|
+
removedDeclarators.add(declarator);
|
|
1211
982
|
}
|
|
1212
|
-
return null;
|
|
1213
983
|
}
|
|
984
|
+
}
|
|
985
|
+
return removedDeclarators;
|
|
986
|
+
}
|
|
987
|
+
|
|
988
|
+
function setRemainingImportNamesAndRewriteRequires(
|
|
989
|
+
requireExpressionsWithUsedReturnValue,
|
|
990
|
+
requiredByNode,
|
|
991
|
+
magicString
|
|
992
|
+
) {
|
|
993
|
+
let uid = 0;
|
|
994
|
+
for (const requireExpression of requireExpressionsWithUsedReturnValue) {
|
|
995
|
+
const { required } = requiredByNode.get(requireExpression);
|
|
996
|
+
if (!required.name) {
|
|
997
|
+
let potentialName;
|
|
998
|
+
const isUsedName = (node) => requiredByNode.get(node).scope.contains(potentialName);
|
|
999
|
+
do {
|
|
1000
|
+
potentialName = `require$$${uid}`;
|
|
1001
|
+
uid += 1;
|
|
1002
|
+
} while (required.nodesUsingRequired.some(isUsedName));
|
|
1003
|
+
required.name = potentialName;
|
|
1004
|
+
}
|
|
1005
|
+
magicString.overwrite(requireExpression.start, requireExpression.end, required.name);
|
|
1006
|
+
}
|
|
1007
|
+
}
|
|
1214
1008
|
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
}
|
|
1219
|
-
|
|
1220
|
-
|
|
1009
|
+
function removeDeclaratorsFromDeclarations(topLevelDeclarations, removedDeclarators, magicString) {
|
|
1010
|
+
for (const declaration of topLevelDeclarations) {
|
|
1011
|
+
let keepDeclaration = false;
|
|
1012
|
+
let [{ start }] = declaration.declarations;
|
|
1013
|
+
for (const declarator of declaration.declarations) {
|
|
1014
|
+
if (removedDeclarators.has(declarator)) {
|
|
1015
|
+
magicString.remove(start, declarator.end);
|
|
1016
|
+
} else if (!keepDeclaration) {
|
|
1017
|
+
magicString.remove(start, declarator.start);
|
|
1018
|
+
keepDeclaration = true;
|
|
1221
1019
|
}
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1020
|
+
start = declarator.end;
|
|
1021
|
+
}
|
|
1022
|
+
if (!keepDeclaration) {
|
|
1023
|
+
magicString.remove(declaration.start, declaration.end);
|
|
1024
|
+
}
|
|
1025
|
+
}
|
|
1026
|
+
}
|
|
1027
|
+
|
|
1028
|
+
/* eslint-disable no-param-reassign, no-shadow, no-underscore-dangle, no-continue */
|
|
1029
|
+
|
|
1030
|
+
const exportsPattern = /^(?:module\.)?exports(?:\.([a-zA-Z_$][a-zA-Z_$0-9]*))?$/;
|
|
1031
|
+
|
|
1032
|
+
const functionType = /^(?:FunctionDeclaration|FunctionExpression|ArrowFunctionExpression)$/;
|
|
1033
|
+
|
|
1034
|
+
function transformCommonjs(
|
|
1035
|
+
parse,
|
|
1036
|
+
code,
|
|
1037
|
+
id,
|
|
1038
|
+
isEsModule,
|
|
1039
|
+
ignoreGlobal,
|
|
1040
|
+
ignoreRequire,
|
|
1041
|
+
sourceMap,
|
|
1042
|
+
isDynamicRequireModulesEnabled,
|
|
1043
|
+
dynamicRequireModuleSet,
|
|
1044
|
+
disableWrap,
|
|
1045
|
+
commonDir,
|
|
1046
|
+
astCache
|
|
1047
|
+
) {
|
|
1048
|
+
const ast = astCache || tryParse(parse, code, id);
|
|
1049
|
+
const magicString = new MagicString(code);
|
|
1050
|
+
const uses = {
|
|
1051
|
+
module: false,
|
|
1052
|
+
exports: false,
|
|
1053
|
+
global: false,
|
|
1054
|
+
require: false,
|
|
1055
|
+
commonjsHelpers: false
|
|
1056
|
+
};
|
|
1057
|
+
const virtualDynamicRequirePath =
|
|
1058
|
+
isDynamicRequireModulesEnabled && getVirtualPathForDynamicRequirePath(dirname(id), commonDir);
|
|
1059
|
+
let scope = attachScopes(ast, 'scope');
|
|
1060
|
+
let lexicalDepth = 0;
|
|
1061
|
+
let programDepth = 0;
|
|
1062
|
+
let shouldWrap = false;
|
|
1063
|
+
const defineCompiledEsmExpressions = [];
|
|
1064
|
+
|
|
1065
|
+
const globals = new Set();
|
|
1066
|
+
|
|
1067
|
+
// TODO technically wrong since globals isn't populated yet, but ¯\_(ツ)_/¯
|
|
1068
|
+
const HELPERS_NAME = deconflict(scope, globals, 'commonjsHelpers');
|
|
1069
|
+
const namedExports = {};
|
|
1070
|
+
const dynamicRegisterSources = new Set();
|
|
1071
|
+
|
|
1072
|
+
const {
|
|
1073
|
+
addRequireStatement,
|
|
1074
|
+
requiredSources,
|
|
1075
|
+
rewriteRequireExpressionsAndGetImportBlock
|
|
1076
|
+
} = getRequireHandlers();
|
|
1077
|
+
|
|
1078
|
+
// See which names are assigned to. This is necessary to prevent
|
|
1079
|
+
// illegally replacing `var foo = require('foo')` with `import foo from 'foo'`,
|
|
1080
|
+
// where `foo` is later reassigned. (This happens in the wild. CommonJS, sigh)
|
|
1081
|
+
const reassignedNames = new Set();
|
|
1082
|
+
const topLevelDeclarations = [];
|
|
1083
|
+
const topLevelRequireDeclarators = new Set();
|
|
1084
|
+
const skippedNodes = new Set();
|
|
1085
|
+
const topLevelModuleExportsAssignments = [];
|
|
1086
|
+
const topLevelExportsAssignmentsByName = new Map();
|
|
1087
|
+
|
|
1088
|
+
walk(ast, {
|
|
1089
|
+
enter(node, parent) {
|
|
1090
|
+
if (skippedNodes.has(node)) {
|
|
1091
|
+
this.skip();
|
|
1092
|
+
return;
|
|
1227
1093
|
}
|
|
1228
|
-
|
|
1229
|
-
|
|
1094
|
+
|
|
1095
|
+
programDepth += 1;
|
|
1096
|
+
if (node.scope) ({ scope } = node);
|
|
1097
|
+
if (functionType.test(node.type)) lexicalDepth += 1;
|
|
1098
|
+
if (sourceMap) {
|
|
1099
|
+
magicString.addSourcemapLocation(node.start);
|
|
1100
|
+
magicString.addSourcemapLocation(node.end);
|
|
1101
|
+
}
|
|
1102
|
+
|
|
1103
|
+
// eslint-disable-next-line default-case
|
|
1104
|
+
switch (node.type) {
|
|
1105
|
+
case 'AssignmentExpression':
|
|
1106
|
+
if (node.left.type === 'MemberExpression') {
|
|
1107
|
+
const flattened = getKeypath(node.left);
|
|
1108
|
+
if (!flattened || scope.contains(flattened.name)) return;
|
|
1109
|
+
|
|
1110
|
+
const exportsPatternMatch = exportsPattern.exec(flattened.keypath);
|
|
1111
|
+
if (!exportsPatternMatch || flattened.keypath === 'exports') return;
|
|
1112
|
+
|
|
1113
|
+
const [, exportName] = exportsPatternMatch;
|
|
1114
|
+
uses[flattened.name] = true;
|
|
1115
|
+
|
|
1116
|
+
// we're dealing with `module.exports = ...` or `[module.]exports.foo = ...` –
|
|
1117
|
+
if (programDepth > 3) {
|
|
1118
|
+
shouldWrap = true;
|
|
1119
|
+
} else if (exportName === KEY_COMPILED_ESM) {
|
|
1120
|
+
defineCompiledEsmExpressions.push(parent);
|
|
1121
|
+
} else if (flattened.keypath === 'module.exports') {
|
|
1122
|
+
topLevelModuleExportsAssignments.push(node);
|
|
1123
|
+
} else if (!topLevelExportsAssignmentsByName.has(exportName)) {
|
|
1124
|
+
topLevelExportsAssignmentsByName.set(exportName, node);
|
|
1125
|
+
} else {
|
|
1126
|
+
shouldWrap = true;
|
|
1127
|
+
}
|
|
1128
|
+
|
|
1129
|
+
skippedNodes.add(node.left);
|
|
1130
|
+
|
|
1131
|
+
if (flattened.keypath === 'module.exports' && node.right.type === 'ObjectExpression') {
|
|
1132
|
+
node.right.properties.forEach((prop) => {
|
|
1133
|
+
if (prop.computed || !('key' in prop) || prop.key.type !== 'Identifier') return;
|
|
1134
|
+
const { name } = prop.key;
|
|
1135
|
+
if (name === makeLegalIdentifier(name)) namedExports[name] = true;
|
|
1136
|
+
});
|
|
1137
|
+
return;
|
|
1138
|
+
}
|
|
1139
|
+
|
|
1140
|
+
if (exportsPatternMatch[1]) namedExports[exportsPatternMatch[1]] = true;
|
|
1141
|
+
} else {
|
|
1142
|
+
for (const name of extractAssignedNames(node.left)) {
|
|
1143
|
+
reassignedNames.add(name);
|
|
1144
|
+
}
|
|
1145
|
+
}
|
|
1146
|
+
return;
|
|
1147
|
+
case 'CallExpression': {
|
|
1148
|
+
if (isDefineCompiledEsm(node)) {
|
|
1149
|
+
if (programDepth === 3 && parent.type === 'ExpressionStatement') {
|
|
1150
|
+
// skip special handling for [module.]exports until we know we render this
|
|
1151
|
+
skippedNodes.add(node.arguments[0]);
|
|
1152
|
+
defineCompiledEsmExpressions.push(parent);
|
|
1153
|
+
} else {
|
|
1154
|
+
shouldWrap = true;
|
|
1155
|
+
}
|
|
1156
|
+
return;
|
|
1157
|
+
}
|
|
1158
|
+
if (!isStaticRequireStatement(node, scope)) return;
|
|
1159
|
+
if (!isDynamicRequireModulesEnabled) {
|
|
1160
|
+
skippedNodes.add(node.callee);
|
|
1161
|
+
}
|
|
1162
|
+
if (!isIgnoredRequireStatement(node, ignoreRequire)) {
|
|
1163
|
+
skippedNodes.add(node.callee);
|
|
1164
|
+
const usesReturnValue = parent.type !== 'ExpressionStatement';
|
|
1165
|
+
|
|
1166
|
+
let sourceId = getRequireStringArg(node);
|
|
1167
|
+
const isDynamicRegister = sourceId.startsWith(DYNAMIC_REGISTER_PREFIX);
|
|
1168
|
+
if (isDynamicRegister) {
|
|
1169
|
+
sourceId = sourceId.substr(DYNAMIC_REGISTER_PREFIX.length);
|
|
1170
|
+
if (sourceId.endsWith('.json')) {
|
|
1171
|
+
sourceId = DYNAMIC_JSON_PREFIX + sourceId;
|
|
1172
|
+
}
|
|
1173
|
+
dynamicRegisterSources.add(sourceId);
|
|
1174
|
+
} else {
|
|
1175
|
+
if (
|
|
1176
|
+
!sourceId.endsWith('.json') &&
|
|
1177
|
+
hasDynamicModuleForPath(sourceId, id, dynamicRequireModuleSet)
|
|
1178
|
+
) {
|
|
1179
|
+
magicString.overwrite(
|
|
1180
|
+
node.start,
|
|
1181
|
+
node.end,
|
|
1182
|
+
`${HELPERS_NAME}.commonjsRequire(${JSON.stringify(
|
|
1183
|
+
getVirtualPathForDynamicRequirePath(sourceId, commonDir)
|
|
1184
|
+
)}, ${JSON.stringify(
|
|
1185
|
+
dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath
|
|
1186
|
+
)})`
|
|
1187
|
+
);
|
|
1188
|
+
uses.commonjsHelpers = true;
|
|
1189
|
+
return;
|
|
1190
|
+
}
|
|
1191
|
+
addRequireStatement(sourceId, node, scope, usesReturnValue);
|
|
1192
|
+
}
|
|
1193
|
+
|
|
1194
|
+
if (usesReturnValue) {
|
|
1195
|
+
if (
|
|
1196
|
+
parent.type === 'VariableDeclarator' &&
|
|
1197
|
+
!scope.parent &&
|
|
1198
|
+
parent.id.type === 'Identifier'
|
|
1199
|
+
) {
|
|
1200
|
+
// This will allow us to reuse this variable name as the imported variable if it is not reassigned
|
|
1201
|
+
// and does not conflict with variables in other places where this is imported
|
|
1202
|
+
topLevelRequireDeclarators.add(parent);
|
|
1203
|
+
}
|
|
1204
|
+
} else {
|
|
1205
|
+
// This is a bare import, e.g. `require('foo');`
|
|
1206
|
+
magicString.remove(parent.start, parent.end);
|
|
1207
|
+
}
|
|
1208
|
+
}
|
|
1209
|
+
return;
|
|
1210
|
+
}
|
|
1211
|
+
case 'ConditionalExpression':
|
|
1212
|
+
case 'IfStatement':
|
|
1213
|
+
// skip dead branches
|
|
1214
|
+
if (isFalsy(node.test)) {
|
|
1215
|
+
skippedNodes.add(node.consequent);
|
|
1216
|
+
} else if (node.alternate && isTruthy(node.test)) {
|
|
1217
|
+
skippedNodes.add(node.alternate);
|
|
1218
|
+
}
|
|
1219
|
+
return;
|
|
1220
|
+
case 'Identifier': {
|
|
1221
|
+
const { name } = node;
|
|
1222
|
+
if (!(isReference(node, parent) && !scope.contains(name))) return;
|
|
1223
|
+
switch (name) {
|
|
1224
|
+
case 'require':
|
|
1225
|
+
if (isNodeRequirePropertyAccess(parent)) return;
|
|
1226
|
+
|
|
1227
|
+
if (isDynamicRequireModulesEnabled && isRequireStatement(parent, scope)) {
|
|
1228
|
+
magicString.appendLeft(
|
|
1229
|
+
parent.end - 1,
|
|
1230
|
+
`,${JSON.stringify(
|
|
1231
|
+
dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath
|
|
1232
|
+
)}`
|
|
1233
|
+
);
|
|
1234
|
+
}
|
|
1235
|
+
|
|
1236
|
+
magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, {
|
|
1237
|
+
storeName: true
|
|
1238
|
+
});
|
|
1239
|
+
uses.commonjsHelpers = true;
|
|
1240
|
+
return;
|
|
1241
|
+
case 'module':
|
|
1242
|
+
case 'exports':
|
|
1243
|
+
shouldWrap = true;
|
|
1244
|
+
uses[name] = true;
|
|
1245
|
+
return;
|
|
1246
|
+
case 'global':
|
|
1247
|
+
uses.global = true;
|
|
1248
|
+
if (!ignoreGlobal) {
|
|
1249
|
+
magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsGlobal`, {
|
|
1250
|
+
storeName: true
|
|
1251
|
+
});
|
|
1252
|
+
uses.commonjsHelpers = true;
|
|
1253
|
+
}
|
|
1254
|
+
return;
|
|
1255
|
+
case 'define':
|
|
1256
|
+
magicString.overwrite(node.start, node.end, 'undefined', { storeName: true });
|
|
1257
|
+
return;
|
|
1258
|
+
default:
|
|
1259
|
+
globals.add(name);
|
|
1260
|
+
return;
|
|
1261
|
+
}
|
|
1262
|
+
}
|
|
1263
|
+
case 'MemberExpression':
|
|
1264
|
+
if (!isDynamicRequireModulesEnabled && isModuleRequire(node, scope)) {
|
|
1265
|
+
magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, {
|
|
1266
|
+
storeName: true
|
|
1267
|
+
});
|
|
1268
|
+
uses.commonjsHelpers = true;
|
|
1269
|
+
skippedNodes.add(node.object);
|
|
1270
|
+
skippedNodes.add(node.property);
|
|
1271
|
+
}
|
|
1272
|
+
return;
|
|
1273
|
+
case 'ReturnStatement':
|
|
1274
|
+
// if top-level return, we need to wrap it
|
|
1275
|
+
if (lexicalDepth === 0) {
|
|
1276
|
+
shouldWrap = true;
|
|
1277
|
+
}
|
|
1278
|
+
return;
|
|
1279
|
+
case 'ThisExpression':
|
|
1280
|
+
// rewrite top-level `this` as `commonjsHelpers.commonjsGlobal`
|
|
1281
|
+
if (lexicalDepth === 0) {
|
|
1282
|
+
uses.global = true;
|
|
1283
|
+
if (!ignoreGlobal) {
|
|
1284
|
+
magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsGlobal`, {
|
|
1285
|
+
storeName: true
|
|
1286
|
+
});
|
|
1287
|
+
uses.commonjsHelpers = true;
|
|
1288
|
+
}
|
|
1289
|
+
}
|
|
1290
|
+
return;
|
|
1291
|
+
case 'UnaryExpression':
|
|
1292
|
+
// rewrite `typeof module`, `typeof module.exports` and `typeof exports` (https://github.com/rollup/rollup-plugin-commonjs/issues/151)
|
|
1293
|
+
if (node.operator === 'typeof') {
|
|
1294
|
+
const flattened = getKeypath(node.argument);
|
|
1295
|
+
if (!flattened) return;
|
|
1296
|
+
|
|
1297
|
+
if (scope.contains(flattened.name)) return;
|
|
1298
|
+
|
|
1299
|
+
if (
|
|
1300
|
+
flattened.keypath === 'module.exports' ||
|
|
1301
|
+
flattened.keypath === 'module' ||
|
|
1302
|
+
flattened.keypath === 'exports'
|
|
1303
|
+
) {
|
|
1304
|
+
magicString.overwrite(node.start, node.end, `'object'`, { storeName: false });
|
|
1305
|
+
}
|
|
1306
|
+
}
|
|
1307
|
+
return;
|
|
1308
|
+
case 'VariableDeclaration':
|
|
1309
|
+
if (!scope.parent) {
|
|
1310
|
+
topLevelDeclarations.push(node);
|
|
1311
|
+
}
|
|
1312
|
+
}
|
|
1313
|
+
},
|
|
1314
|
+
|
|
1315
|
+
leave(node) {
|
|
1316
|
+
programDepth -= 1;
|
|
1317
|
+
if (node.scope) scope = scope.parent;
|
|
1318
|
+
if (functionType.test(node.type)) lexicalDepth -= 1;
|
|
1319
|
+
}
|
|
1320
|
+
});
|
|
1321
|
+
|
|
1322
|
+
let isRestorableCompiledEsm = false;
|
|
1323
|
+
if (defineCompiledEsmExpressions.length > 0) {
|
|
1324
|
+
if (!shouldWrap && defineCompiledEsmExpressions.length === 1) {
|
|
1325
|
+
isRestorableCompiledEsm = true;
|
|
1326
|
+
magicString.remove(
|
|
1327
|
+
defineCompiledEsmExpressions[0].start,
|
|
1328
|
+
defineCompiledEsmExpressions[0].end
|
|
1329
|
+
);
|
|
1330
|
+
} else {
|
|
1331
|
+
shouldWrap = true;
|
|
1332
|
+
uses.exports = true;
|
|
1333
|
+
}
|
|
1334
|
+
}
|
|
1335
|
+
|
|
1336
|
+
// We cannot wrap ES/mixed modules
|
|
1337
|
+
shouldWrap = shouldWrap && !disableWrap && !isEsModule;
|
|
1338
|
+
uses.commonjsHelpers = uses.commonjsHelpers || shouldWrap;
|
|
1339
|
+
|
|
1340
|
+
if (
|
|
1341
|
+
!(
|
|
1342
|
+
requiredSources.length ||
|
|
1343
|
+
dynamicRegisterSources.size ||
|
|
1344
|
+
uses.module ||
|
|
1345
|
+
uses.exports ||
|
|
1346
|
+
uses.require ||
|
|
1347
|
+
uses.commonjsHelpers
|
|
1348
|
+
) &&
|
|
1349
|
+
(ignoreGlobal || !uses.global)
|
|
1350
|
+
) {
|
|
1351
|
+
return { meta: { commonjs: { isCommonJS: false } } };
|
|
1352
|
+
}
|
|
1353
|
+
|
|
1354
|
+
const moduleName = deconflict(scope, globals, getName(id));
|
|
1355
|
+
|
|
1356
|
+
let leadingComment = '';
|
|
1357
|
+
if (code.startsWith('/*')) {
|
|
1358
|
+
const commentEnd = code.indexOf('*/', 2) + 2;
|
|
1359
|
+
leadingComment = `${code.slice(0, commentEnd)}\n`;
|
|
1360
|
+
magicString.remove(0, commentEnd).trim();
|
|
1361
|
+
}
|
|
1362
|
+
|
|
1363
|
+
const exportBlock = isEsModule
|
|
1364
|
+
? ''
|
|
1365
|
+
: rewriteExportsAndGetExportsBlock(
|
|
1366
|
+
magicString,
|
|
1367
|
+
moduleName,
|
|
1368
|
+
shouldWrap,
|
|
1369
|
+
topLevelModuleExportsAssignments,
|
|
1370
|
+
topLevelExportsAssignmentsByName,
|
|
1371
|
+
defineCompiledEsmExpressions,
|
|
1372
|
+
(name) => deconflict(scope, globals, name),
|
|
1373
|
+
isRestorableCompiledEsm,
|
|
1374
|
+
code,
|
|
1375
|
+
uses,
|
|
1376
|
+
HELPERS_NAME
|
|
1377
|
+
);
|
|
1378
|
+
|
|
1379
|
+
const importBlock = rewriteRequireExpressionsAndGetImportBlock(
|
|
1380
|
+
magicString,
|
|
1381
|
+
topLevelDeclarations,
|
|
1382
|
+
topLevelRequireDeclarators,
|
|
1383
|
+
reassignedNames,
|
|
1384
|
+
uses.commonjsHelpers && HELPERS_NAME,
|
|
1385
|
+
dynamicRegisterSources
|
|
1386
|
+
);
|
|
1387
|
+
|
|
1388
|
+
if (shouldWrap) {
|
|
1389
|
+
wrapCode(magicString, uses, moduleName, HELPERS_NAME, virtualDynamicRequirePath);
|
|
1390
|
+
}
|
|
1391
|
+
|
|
1392
|
+
magicString
|
|
1393
|
+
.trim()
|
|
1394
|
+
.prepend(leadingComment + importBlock)
|
|
1395
|
+
.append(exportBlock);
|
|
1396
|
+
|
|
1397
|
+
return {
|
|
1398
|
+
code: magicString.toString(),
|
|
1399
|
+
map: sourceMap ? magicString.generateMap() : null,
|
|
1400
|
+
syntheticNamedExports: isEsModule ? false : '__moduleExports',
|
|
1401
|
+
meta: { commonjs: { isCommonJS: !isEsModule } }
|
|
1230
1402
|
};
|
|
1231
1403
|
}
|
|
1232
1404
|
|
|
@@ -1278,7 +1450,7 @@ function commonjs(options = {}) {
|
|
|
1278
1450
|
getDynamicPackagesEntryIntro(dynamicRequireModuleDirPaths, dynamicRequireModuleSet) + code;
|
|
1279
1451
|
}
|
|
1280
1452
|
|
|
1281
|
-
const { isEsModule, hasDefaultExport, hasNamedExports, ast } =
|
|
1453
|
+
const { isEsModule, hasDefaultExport, hasNamedExports, ast } = analyzeTopLevelStatements(
|
|
1282
1454
|
this.parse,
|
|
1283
1455
|
code,
|
|
1284
1456
|
id
|
|
@@ -1320,20 +1492,12 @@ function commonjs(options = {}) {
|
|
|
1320
1492
|
name: 'commonjs',
|
|
1321
1493
|
|
|
1322
1494
|
buildStart() {
|
|
1495
|
+
validateRollupVersion(this.meta.rollupVersion, peerDependencies.rollup);
|
|
1323
1496
|
if (options.namedExports != null) {
|
|
1324
1497
|
this.warn(
|
|
1325
1498
|
'The namedExports option from "@rollup/plugin-commonjs" is deprecated. Named exports are now handled automatically.'
|
|
1326
1499
|
);
|
|
1327
1500
|
}
|
|
1328
|
-
|
|
1329
|
-
const [major, minor] = this.meta.rollupVersion.split('.').map(Number);
|
|
1330
|
-
const minVersion = peerDependencies.rollup.slice(2);
|
|
1331
|
-
const [minMajor, minMinor] = minVersion.split('.').map(Number);
|
|
1332
|
-
if (major < minMajor || (major === minMajor && minor < minMinor)) {
|
|
1333
|
-
this.error(
|
|
1334
|
-
`Insufficient Rollup version: "@rollup/plugin-commonjs" requires at least rollup@${minVersion} but found rollup@${this.meta.rollupVersion}.`
|
|
1335
|
-
);
|
|
1336
|
-
}
|
|
1337
1501
|
},
|
|
1338
1502
|
|
|
1339
1503
|
resolveId,
|