/
transform-commonjs.js
500 lines (453 loc) · 16.5 KB
/
transform-commonjs.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
/* eslint-disable no-param-reassign, no-shadow, no-underscore-dangle, no-continue */
import { dirname } from 'path';
import { attachScopes, extractAssignedNames, makeLegalIdentifier } from '@rollup/pluginutils';
import { walk } from 'estree-walker';
import MagicString from 'magic-string';
import {
getKeypath,
isDefineCompiledEsm,
isFalsy,
isReference,
isShorthandProperty,
isTruthy,
KEY_COMPILED_ESM
} from './ast-utils';
import { rewriteExportsAndGetExportsBlock, wrapCode } from './generate-exports';
import {
getRequireHandlers,
getRequireStringArg,
hasDynamicModuleForPath,
isIgnoredRequireStatement,
isModuleRequire,
isNodeRequirePropertyAccess,
isRequireStatement,
isStaticRequireStatement
} from './generate-imports';
import { DYNAMIC_JSON_PREFIX } from './helpers';
import { tryParse } from './parse';
import { deconflict, getName, getVirtualPathForDynamicRequirePath } from './utils';
import {
isModuleRegisterProxy,
unwrapModuleRegisterProxy,
wrapModuleRegisterProxy
} from './dynamic-packages-manager';
const exportsPattern = /^(?:module\.)?exports(?:\.([a-zA-Z_$][a-zA-Z_$0-9]*))?$/;
const functionType = /^(?:FunctionDeclaration|FunctionExpression|ArrowFunctionExpression)$/;
export default function transformCommonjs(
parse,
code,
id,
isEsModule,
ignoreGlobal,
ignoreRequire,
ignoreDynamicRequires,
getIgnoreTryCatchRequireStatementMode,
sourceMap,
isDynamicRequireModulesEnabled,
dynamicRequireModuleSet,
disableWrap,
commonDir,
astCache
) {
const ast = astCache || tryParse(parse, code, id);
const magicString = new MagicString(code);
const uses = {
module: false,
exports: false,
global: false,
require: false,
commonjsHelpers: false
};
const virtualDynamicRequirePath =
isDynamicRequireModulesEnabled && getVirtualPathForDynamicRequirePath(dirname(id), commonDir);
let scope = attachScopes(ast, 'scope');
let lexicalDepth = 0;
let programDepth = 0;
let currentTryBlockEnd = null;
let shouldWrap = false;
const defineCompiledEsmExpressions = [];
const globals = new Set();
// TODO technically wrong since globals isn't populated yet, but ¯\_(ツ)_/¯
const HELPERS_NAME = deconflict(scope, globals, 'commonjsHelpers');
const namedExports = {};
const dynamicRegisterSources = new Set();
let hasRemovedRequire = false;
const {
addRequireStatement,
requiredSources,
rewriteRequireExpressionsAndGetImportBlock
} = getRequireHandlers();
// See which names are assigned to. This is necessary to prevent
// illegally replacing `var foo = require('foo')` with `import foo from 'foo'`,
// where `foo` is later reassigned. (This happens in the wild. CommonJS, sigh)
const reassignedNames = new Set();
const topLevelDeclarations = [];
const topLevelRequireDeclarators = new Set();
const skippedNodes = new Set();
const topLevelModuleExportsAssignments = [];
const topLevelExportsAssignmentsByName = new Map();
walk(ast, {
enter(node, parent) {
if (skippedNodes.has(node)) {
this.skip();
return;
}
if (currentTryBlockEnd !== null && node.start > currentTryBlockEnd) {
currentTryBlockEnd = null;
}
programDepth += 1;
if (node.scope) ({ scope } = node);
if (functionType.test(node.type)) lexicalDepth += 1;
if (sourceMap) {
magicString.addSourcemapLocation(node.start);
magicString.addSourcemapLocation(node.end);
}
// eslint-disable-next-line default-case
switch (node.type) {
case 'TryStatement':
if (currentTryBlockEnd === null) {
currentTryBlockEnd = node.block.end;
}
return;
case 'AssignmentExpression':
if (node.left.type === 'MemberExpression') {
const flattened = getKeypath(node.left);
if (!flattened || scope.contains(flattened.name)) return;
const exportsPatternMatch = exportsPattern.exec(flattened.keypath);
if (!exportsPatternMatch || flattened.keypath === 'exports') return;
const [, exportName] = exportsPatternMatch;
uses[flattened.name] = true;
// we're dealing with `module.exports = ...` or `[module.]exports.foo = ...` –
if (programDepth > 3) {
shouldWrap = true;
} else if (exportName === KEY_COMPILED_ESM) {
defineCompiledEsmExpressions.push(parent);
} else if (flattened.keypath === 'module.exports') {
topLevelModuleExportsAssignments.push(node);
} else if (!topLevelExportsAssignmentsByName.has(exportName)) {
topLevelExportsAssignmentsByName.set(exportName, node);
} else {
shouldWrap = true;
}
skippedNodes.add(node.left);
if (flattened.keypath === 'module.exports' && node.right.type === 'ObjectExpression') {
node.right.properties.forEach((prop) => {
if (prop.computed || !('key' in prop) || prop.key.type !== 'Identifier') return;
const { name } = prop.key;
if (name === makeLegalIdentifier(name)) namedExports[name] = true;
});
return;
}
if (exportsPatternMatch[1]) namedExports[exportsPatternMatch[1]] = true;
} else {
for (const name of extractAssignedNames(node.left)) {
reassignedNames.add(name);
}
}
return;
case 'CallExpression': {
if (isDefineCompiledEsm(node)) {
if (programDepth === 3 && parent.type === 'ExpressionStatement') {
// skip special handling for [module.]exports until we know we render this
skippedNodes.add(node.arguments[0]);
defineCompiledEsmExpressions.push(parent);
} else {
shouldWrap = true;
}
return;
}
if (
node.callee.object &&
node.callee.object.name === 'require' &&
node.callee.property.name === 'resolve' &&
hasDynamicModuleForPath(id, '/', dynamicRequireModuleSet)
) {
const requireNode = node.callee.object;
magicString.appendLeft(
node.end - 1,
`,${JSON.stringify(
dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath
)}`
);
magicString.overwrite(
requireNode.start,
requireNode.end,
`${HELPERS_NAME}.commonjsRequire`,
{
storeName: true
}
);
uses.commonjsHelpers = true;
return;
}
if (!isStaticRequireStatement(node, scope)) return;
if (!isDynamicRequireModulesEnabled) {
skippedNodes.add(node.callee);
}
if (!isIgnoredRequireStatement(node, ignoreRequire)) {
skippedNodes.add(node.callee);
const usesReturnValue = parent.type !== 'ExpressionStatement';
let canConvertRequire = true;
let shouldRemoveRequireStatement = false;
if (currentTryBlockEnd !== null) {
({
canConvertRequire,
shouldRemoveRequireStatement
} = getIgnoreTryCatchRequireStatementMode(node.arguments[0].value));
if (shouldRemoveRequireStatement) {
hasRemovedRequire = true;
}
}
let sourceId = getRequireStringArg(node);
const isDynamicRegister = isModuleRegisterProxy(sourceId);
if (isDynamicRegister) {
sourceId = unwrapModuleRegisterProxy(sourceId);
if (sourceId.endsWith('.json')) {
sourceId = DYNAMIC_JSON_PREFIX + sourceId;
}
dynamicRegisterSources.add(wrapModuleRegisterProxy(sourceId));
} else {
if (
!sourceId.endsWith('.json') &&
hasDynamicModuleForPath(sourceId, id, dynamicRequireModuleSet)
) {
if (shouldRemoveRequireStatement) {
magicString.overwrite(node.start, node.end, `undefined`);
} else if (canConvertRequire) {
magicString.overwrite(
node.start,
node.end,
`${HELPERS_NAME}.commonjsRequire(${JSON.stringify(
getVirtualPathForDynamicRequirePath(sourceId, commonDir)
)}, ${JSON.stringify(
dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath
)})`
);
uses.commonjsHelpers = true;
}
return;
}
if (canConvertRequire) {
addRequireStatement(sourceId, node, scope, usesReturnValue);
}
}
if (usesReturnValue) {
if (shouldRemoveRequireStatement) {
magicString.overwrite(node.start, node.end, `undefined`);
return;
}
if (
parent.type === 'VariableDeclarator' &&
!scope.parent &&
parent.id.type === 'Identifier'
) {
// This will allow us to reuse this variable name as the imported variable if it is not reassigned
// and does not conflict with variables in other places where this is imported
topLevelRequireDeclarators.add(parent);
}
} else {
// This is a bare import, e.g. `require('foo');`
if (!canConvertRequire && !shouldRemoveRequireStatement) {
return;
}
magicString.remove(parent.start, parent.end);
}
}
return;
}
case 'ConditionalExpression':
case 'IfStatement':
// skip dead branches
if (isFalsy(node.test)) {
skippedNodes.add(node.consequent);
} else if (node.alternate && isTruthy(node.test)) {
skippedNodes.add(node.alternate);
}
return;
case 'Identifier': {
const { name } = node;
if (!(isReference(node, parent) && !scope.contains(name))) return;
switch (name) {
case 'require':
if (isNodeRequirePropertyAccess(parent)) {
if (hasDynamicModuleForPath(id, '/', dynamicRequireModuleSet)) {
if (parent.property.name === 'cache') {
magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, {
storeName: true
});
uses.commonjsHelpers = true;
}
}
return;
}
if (isDynamicRequireModulesEnabled && isRequireStatement(parent, scope)) {
magicString.appendLeft(
parent.end - 1,
`,${JSON.stringify(
dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath
)}`
);
}
if (!ignoreDynamicRequires) {
if (isShorthandProperty(parent)) {
magicString.appendRight(node.end, `: ${HELPERS_NAME}.commonjsRequire`);
} else {
magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, {
storeName: true
});
}
}
uses.commonjsHelpers = true;
return;
case 'module':
case 'exports':
shouldWrap = true;
uses[name] = true;
return;
case 'global':
uses.global = true;
if (!ignoreGlobal) {
magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsGlobal`, {
storeName: true
});
uses.commonjsHelpers = true;
}
return;
case 'define':
magicString.overwrite(node.start, node.end, 'undefined', { storeName: true });
return;
default:
globals.add(name);
return;
}
}
case 'MemberExpression':
if (!isDynamicRequireModulesEnabled && isModuleRequire(node, scope)) {
magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, {
storeName: true
});
uses.commonjsHelpers = true;
skippedNodes.add(node.object);
skippedNodes.add(node.property);
}
return;
case 'ReturnStatement':
// if top-level return, we need to wrap it
if (lexicalDepth === 0) {
shouldWrap = true;
}
return;
case 'ThisExpression':
// rewrite top-level `this` as `commonjsHelpers.commonjsGlobal`
if (lexicalDepth === 0) {
uses.global = true;
if (!ignoreGlobal) {
magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsGlobal`, {
storeName: true
});
uses.commonjsHelpers = true;
}
}
return;
case 'UnaryExpression':
// rewrite `typeof module`, `typeof module.exports` and `typeof exports` (https://github.com/rollup/rollup-plugin-commonjs/issues/151)
if (node.operator === 'typeof') {
const flattened = getKeypath(node.argument);
if (!flattened) return;
if (scope.contains(flattened.name)) return;
if (
flattened.keypath === 'module.exports' ||
flattened.keypath === 'module' ||
flattened.keypath === 'exports'
) {
magicString.overwrite(node.start, node.end, `'object'`, { storeName: false });
}
}
return;
case 'VariableDeclaration':
if (!scope.parent) {
topLevelDeclarations.push(node);
}
}
},
leave(node) {
programDepth -= 1;
if (node.scope) scope = scope.parent;
if (functionType.test(node.type)) lexicalDepth -= 1;
}
});
let isRestorableCompiledEsm = false;
if (defineCompiledEsmExpressions.length > 0) {
if (!shouldWrap && defineCompiledEsmExpressions.length === 1) {
isRestorableCompiledEsm = true;
magicString.remove(
defineCompiledEsmExpressions[0].start,
defineCompiledEsmExpressions[0].end
);
} else {
shouldWrap = true;
uses.exports = true;
}
}
// We cannot wrap ES/mixed modules
shouldWrap = shouldWrap && !disableWrap && !isEsModule;
uses.commonjsHelpers = uses.commonjsHelpers || shouldWrap;
if (
!(
requiredSources.length ||
dynamicRegisterSources.size ||
uses.module ||
uses.exports ||
uses.require ||
uses.commonjsHelpers ||
hasRemovedRequire ||
isRestorableCompiledEsm
) &&
(ignoreGlobal || !uses.global)
) {
return { meta: { commonjs: { isCommonJS: false } } };
}
const moduleName = deconflict(scope, globals, getName(id));
let leadingComment = '';
if (code.startsWith('/*')) {
const commentEnd = code.indexOf('*/', 2) + 2;
leadingComment = `${code.slice(0, commentEnd)}\n`;
magicString.remove(0, commentEnd).trim();
}
const exportBlock = isEsModule
? ''
: rewriteExportsAndGetExportsBlock(
magicString,
moduleName,
shouldWrap,
topLevelModuleExportsAssignments,
topLevelExportsAssignmentsByName,
defineCompiledEsmExpressions,
(name) => deconflict(scope, globals, name),
isRestorableCompiledEsm,
code,
uses,
HELPERS_NAME
);
const importBlock = rewriteRequireExpressionsAndGetImportBlock(
magicString,
topLevelDeclarations,
topLevelRequireDeclarators,
reassignedNames,
uses.commonjsHelpers && HELPERS_NAME,
dynamicRegisterSources
);
if (shouldWrap) {
wrapCode(magicString, uses, moduleName, HELPERS_NAME, virtualDynamicRequirePath);
}
magicString
.trim()
.prepend(leadingComment + importBlock)
.append(exportBlock);
return {
code: magicString.toString(),
map: sourceMap ? magicString.generateMap() : null,
syntheticNamedExports: isEsModule ? false : '__moduleExports',
meta: { commonjs: { isCommonJS: !isEsModule } }
};
}