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
|
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _tokenizer = require('./parser/tokenizer');
var _keywords = require('./parser/tokenizer/keywords');
var _types = require('./parser/tokenizer/types');
var _getImportExportSpecifierInfo = require('./util/getImportExportSpecifierInfo'); var _getImportExportSpecifierInfo2 = _interopRequireDefault(_getImportExportSpecifierInfo);
var _getNonTypeIdentifiers = require('./util/getNonTypeIdentifiers');
/**
* Class responsible for preprocessing and bookkeeping import and export declarations within the
* file.
*
* TypeScript uses a simpler mechanism that does not use functions like interopRequireDefault and
* interopRequireWildcard, so we also allow that mode for compatibility.
*/
class CJSImportProcessor {
__init() {this.nonTypeIdentifiers = new Set()}
__init2() {this.importInfoByPath = new Map()}
__init3() {this.importsToReplace = new Map()}
__init4() {this.identifierReplacements = new Map()}
__init5() {this.exportBindingsByLocalName = new Map()}
constructor(
nameManager,
tokens,
enableLegacyTypeScriptModuleInterop,
options,
isTypeScriptTransformEnabled,
keepUnusedImports,
helperManager,
) {;this.nameManager = nameManager;this.tokens = tokens;this.enableLegacyTypeScriptModuleInterop = enableLegacyTypeScriptModuleInterop;this.options = options;this.isTypeScriptTransformEnabled = isTypeScriptTransformEnabled;this.keepUnusedImports = keepUnusedImports;this.helperManager = helperManager;CJSImportProcessor.prototype.__init.call(this);CJSImportProcessor.prototype.__init2.call(this);CJSImportProcessor.prototype.__init3.call(this);CJSImportProcessor.prototype.__init4.call(this);CJSImportProcessor.prototype.__init5.call(this);}
preprocessTokens() {
for (let i = 0; i < this.tokens.tokens.length; i++) {
if (
this.tokens.matches1AtIndex(i, _types.TokenType._import) &&
!this.tokens.matches3AtIndex(i, _types.TokenType._import, _types.TokenType.name, _types.TokenType.eq)
) {
this.preprocessImportAtIndex(i);
}
if (
this.tokens.matches1AtIndex(i, _types.TokenType._export) &&
!this.tokens.matches2AtIndex(i, _types.TokenType._export, _types.TokenType.eq)
) {
this.preprocessExportAtIndex(i);
}
}
this.generateImportReplacements();
}
/**
* In TypeScript, import statements that only import types should be removed.
* This includes `import {} from 'foo';`, but not `import 'foo';`.
*/
pruneTypeOnlyImports() {
this.nonTypeIdentifiers = _getNonTypeIdentifiers.getNonTypeIdentifiers.call(void 0, this.tokens, this.options);
for (const [path, importInfo] of this.importInfoByPath.entries()) {
if (
importInfo.hasBareImport ||
importInfo.hasStarExport ||
importInfo.exportStarNames.length > 0 ||
importInfo.namedExports.length > 0
) {
continue;
}
const names = [
...importInfo.defaultNames,
...importInfo.wildcardNames,
...importInfo.namedImports.map(({localName}) => localName),
];
if (names.every((name) => this.shouldAutomaticallyElideImportedName(name))) {
this.importsToReplace.set(path, "");
}
}
}
shouldAutomaticallyElideImportedName(name) {
return (
this.isTypeScriptTransformEnabled &&
!this.keepUnusedImports &&
!this.nonTypeIdentifiers.has(name)
);
}
generateImportReplacements() {
for (const [path, importInfo] of this.importInfoByPath.entries()) {
const {
defaultNames,
wildcardNames,
namedImports,
namedExports,
exportStarNames,
hasStarExport,
} = importInfo;
if (
defaultNames.length === 0 &&
wildcardNames.length === 0 &&
namedImports.length === 0 &&
namedExports.length === 0 &&
exportStarNames.length === 0 &&
!hasStarExport
) {
// Import is never used, so don't even assign a name.
this.importsToReplace.set(path, `require('${path}');`);
continue;
}
const primaryImportName = this.getFreeIdentifierForPath(path);
let secondaryImportName;
if (this.enableLegacyTypeScriptModuleInterop) {
secondaryImportName = primaryImportName;
} else {
secondaryImportName =
wildcardNames.length > 0 ? wildcardNames[0] : this.getFreeIdentifierForPath(path);
}
let requireCode = `var ${primaryImportName} = require('${path}');`;
if (wildcardNames.length > 0) {
for (const wildcardName of wildcardNames) {
const moduleExpr = this.enableLegacyTypeScriptModuleInterop
? primaryImportName
: `${this.helperManager.getHelperName("interopRequireWildcard")}(${primaryImportName})`;
requireCode += ` var ${wildcardName} = ${moduleExpr};`;
}
} else if (exportStarNames.length > 0 && secondaryImportName !== primaryImportName) {
requireCode += ` var ${secondaryImportName} = ${this.helperManager.getHelperName(
"interopRequireWildcard",
)}(${primaryImportName});`;
} else if (defaultNames.length > 0 && secondaryImportName !== primaryImportName) {
requireCode += ` var ${secondaryImportName} = ${this.helperManager.getHelperName(
"interopRequireDefault",
)}(${primaryImportName});`;
}
for (const {importedName, localName} of namedExports) {
requireCode += ` ${this.helperManager.getHelperName(
"createNamedExportFrom",
)}(${primaryImportName}, '${localName}', '${importedName}');`;
}
for (const exportStarName of exportStarNames) {
requireCode += ` exports.${exportStarName} = ${secondaryImportName};`;
}
if (hasStarExport) {
requireCode += ` ${this.helperManager.getHelperName(
"createStarExport",
)}(${primaryImportName});`;
}
this.importsToReplace.set(path, requireCode);
for (const defaultName of defaultNames) {
this.identifierReplacements.set(defaultName, `${secondaryImportName}.default`);
}
for (const {importedName, localName} of namedImports) {
this.identifierReplacements.set(localName, `${primaryImportName}.${importedName}`);
}
}
}
getFreeIdentifierForPath(path) {
const components = path.split("/");
const lastComponent = components[components.length - 1];
const baseName = lastComponent.replace(/\W/g, "");
return this.nameManager.claimFreeName(`_${baseName}`);
}
preprocessImportAtIndex(index) {
const defaultNames = [];
const wildcardNames = [];
const namedImports = [];
index++;
if (
(this.tokens.matchesContextualAtIndex(index, _keywords.ContextualKeyword._type) ||
this.tokens.matches1AtIndex(index, _types.TokenType._typeof)) &&
!this.tokens.matches1AtIndex(index + 1, _types.TokenType.comma) &&
!this.tokens.matchesContextualAtIndex(index + 1, _keywords.ContextualKeyword._from)
) {
// import type declaration, so no need to process anything.
return;
}
if (this.tokens.matches1AtIndex(index, _types.TokenType.parenL)) {
// Dynamic import, so nothing to do
return;
}
if (this.tokens.matches1AtIndex(index, _types.TokenType.name)) {
defaultNames.push(this.tokens.identifierNameAtIndex(index));
index++;
if (this.tokens.matches1AtIndex(index, _types.TokenType.comma)) {
index++;
}
}
if (this.tokens.matches1AtIndex(index, _types.TokenType.star)) {
// * as
index += 2;
wildcardNames.push(this.tokens.identifierNameAtIndex(index));
index++;
}
if (this.tokens.matches1AtIndex(index, _types.TokenType.braceL)) {
const result = this.getNamedImports(index + 1);
index = result.newIndex;
for (const namedImport of result.namedImports) {
// Treat {default as X} as a default import to ensure usage of require interop helper
if (namedImport.importedName === "default") {
defaultNames.push(namedImport.localName);
} else {
namedImports.push(namedImport);
}
}
}
if (this.tokens.matchesContextualAtIndex(index, _keywords.ContextualKeyword._from)) {
index++;
}
if (!this.tokens.matches1AtIndex(index, _types.TokenType.string)) {
throw new Error("Expected string token at the end of import statement.");
}
const path = this.tokens.stringValueAtIndex(index);
const importInfo = this.getImportInfo(path);
importInfo.defaultNames.push(...defaultNames);
importInfo.wildcardNames.push(...wildcardNames);
importInfo.namedImports.push(...namedImports);
if (defaultNames.length === 0 && wildcardNames.length === 0 && namedImports.length === 0) {
importInfo.hasBareImport = true;
}
}
preprocessExportAtIndex(index) {
if (
this.tokens.matches2AtIndex(index, _types.TokenType._export, _types.TokenType._var) ||
this.tokens.matches2AtIndex(index, _types.TokenType._export, _types.TokenType._let) ||
this.tokens.matches2AtIndex(index, _types.TokenType._export, _types.TokenType._const)
) {
this.preprocessVarExportAtIndex(index);
} else if (
this.tokens.matches2AtIndex(index, _types.TokenType._export, _types.TokenType._function) ||
this.tokens.matches2AtIndex(index, _types.TokenType._export, _types.TokenType._class)
) {
const exportName = this.tokens.identifierNameAtIndex(index + 2);
this.addExportBinding(exportName, exportName);
} else if (this.tokens.matches3AtIndex(index, _types.TokenType._export, _types.TokenType.name, _types.TokenType._function)) {
const exportName = this.tokens.identifierNameAtIndex(index + 3);
this.addExportBinding(exportName, exportName);
} else if (this.tokens.matches2AtIndex(index, _types.TokenType._export, _types.TokenType.braceL)) {
this.preprocessNamedExportAtIndex(index);
} else if (this.tokens.matches2AtIndex(index, _types.TokenType._export, _types.TokenType.star)) {
this.preprocessExportStarAtIndex(index);
}
}
preprocessVarExportAtIndex(index) {
let depth = 0;
// Handle cases like `export let {x} = y;`, starting at the open-brace in that case.
for (let i = index + 2; ; i++) {
if (
this.tokens.matches1AtIndex(i, _types.TokenType.braceL) ||
this.tokens.matches1AtIndex(i, _types.TokenType.dollarBraceL) ||
this.tokens.matches1AtIndex(i, _types.TokenType.bracketL)
) {
depth++;
} else if (
this.tokens.matches1AtIndex(i, _types.TokenType.braceR) ||
this.tokens.matches1AtIndex(i, _types.TokenType.bracketR)
) {
depth--;
} else if (depth === 0 && !this.tokens.matches1AtIndex(i, _types.TokenType.name)) {
break;
} else if (this.tokens.matches1AtIndex(1, _types.TokenType.eq)) {
const endIndex = this.tokens.currentToken().rhsEndIndex;
if (endIndex == null) {
throw new Error("Expected = token with an end index.");
}
i = endIndex - 1;
} else {
const token = this.tokens.tokens[i];
if (_tokenizer.isDeclaration.call(void 0, token)) {
const exportName = this.tokens.identifierNameAtIndex(i);
this.identifierReplacements.set(exportName, `exports.${exportName}`);
}
}
}
}
/**
* Walk this export statement just in case it's an export...from statement.
* If it is, combine it into the import info for that path. Otherwise, just
* bail out; it'll be handled later.
*/
preprocessNamedExportAtIndex(index) {
// export {
index += 2;
const {newIndex, namedImports} = this.getNamedImports(index);
index = newIndex;
if (this.tokens.matchesContextualAtIndex(index, _keywords.ContextualKeyword._from)) {
index++;
} else {
// Reinterpret "a as b" to be local/exported rather than imported/local.
for (const {importedName: localName, localName: exportedName} of namedImports) {
this.addExportBinding(localName, exportedName);
}
return;
}
if (!this.tokens.matches1AtIndex(index, _types.TokenType.string)) {
throw new Error("Expected string token at the end of import statement.");
}
const path = this.tokens.stringValueAtIndex(index);
const importInfo = this.getImportInfo(path);
importInfo.namedExports.push(...namedImports);
}
preprocessExportStarAtIndex(index) {
let exportedName = null;
if (this.tokens.matches3AtIndex(index, _types.TokenType._export, _types.TokenType.star, _types.TokenType._as)) {
// export * as
index += 3;
exportedName = this.tokens.identifierNameAtIndex(index);
// foo from
index += 2;
} else {
// export * from
index += 3;
}
if (!this.tokens.matches1AtIndex(index, _types.TokenType.string)) {
throw new Error("Expected string token at the end of star export statement.");
}
const path = this.tokens.stringValueAtIndex(index);
const importInfo = this.getImportInfo(path);
if (exportedName !== null) {
importInfo.exportStarNames.push(exportedName);
} else {
importInfo.hasStarExport = true;
}
}
getNamedImports(index) {
const namedImports = [];
while (true) {
if (this.tokens.matches1AtIndex(index, _types.TokenType.braceR)) {
index++;
break;
}
const specifierInfo = _getImportExportSpecifierInfo2.default.call(void 0, this.tokens, index);
index = specifierInfo.endIndex;
if (!specifierInfo.isType) {
namedImports.push({
importedName: specifierInfo.leftName,
localName: specifierInfo.rightName,
});
}
if (this.tokens.matches2AtIndex(index, _types.TokenType.comma, _types.TokenType.braceR)) {
index += 2;
break;
} else if (this.tokens.matches1AtIndex(index, _types.TokenType.braceR)) {
index++;
break;
} else if (this.tokens.matches1AtIndex(index, _types.TokenType.comma)) {
index++;
} else {
throw new Error(`Unexpected token: ${JSON.stringify(this.tokens.tokens[index])}`);
}
}
return {newIndex: index, namedImports};
}
/**
* Get a mutable import info object for this path, creating one if it doesn't
* exist yet.
*/
getImportInfo(path) {
const existingInfo = this.importInfoByPath.get(path);
if (existingInfo) {
return existingInfo;
}
const newInfo = {
defaultNames: [],
wildcardNames: [],
namedImports: [],
namedExports: [],
hasBareImport: false,
exportStarNames: [],
hasStarExport: false,
};
this.importInfoByPath.set(path, newInfo);
return newInfo;
}
addExportBinding(localName, exportedName) {
if (!this.exportBindingsByLocalName.has(localName)) {
this.exportBindingsByLocalName.set(localName, []);
}
this.exportBindingsByLocalName.get(localName).push(exportedName);
}
/**
* Return the code to use for the import for this path, or the empty string if
* the code has already been "claimed" by a previous import.
*/
claimImportCode(importPath) {
const result = this.importsToReplace.get(importPath);
this.importsToReplace.set(importPath, "");
return result || "";
}
getIdentifierReplacement(identifierName) {
return this.identifierReplacements.get(identifierName) || null;
}
/**
* Return a string like `exports.foo = exports.bar`.
*/
resolveExportBinding(assignedName) {
const exportedNames = this.exportBindingsByLocalName.get(assignedName);
if (!exportedNames || exportedNames.length === 0) {
return null;
}
return exportedNames.map((exportedName) => `exports.${exportedName}`).join(" = ");
}
/**
* Return all imported/exported names where we might be interested in whether usages of those
* names are shadowed.
*/
getGlobalNames() {
return new Set([
...this.identifierReplacements.keys(),
...this.exportBindingsByLocalName.keys(),
]);
}
} exports.default = CJSImportProcessor;
|