UNPKG

2.33 kBJavaScriptView Raw
1import {ContextualKeyword} from "../parser/tokenizer/keywords";
2import {TokenType as tt} from "../parser/tokenizer/types";
3
4
5/**
6 * Special case code to scan for imported names in ESM TypeScript. We need to do this so we can
7 * properly get globals so we can compute shadowed globals.
8 *
9 * This is similar to logic in CJSImportProcessor, but trimmed down to avoid logic with CJS
10 * replacement and flow type imports.
11 */
12export default function getTSImportedNames(tokens) {
13 const importedNames = new Set();
14 for (let i = 0; i < tokens.tokens.length; i++) {
15 if (
16 tokens.matches1AtIndex(i, tt._import) &&
17 !tokens.matches3AtIndex(i, tt._import, tt.name, tt.eq)
18 ) {
19 collectNamesForImport(tokens, i, importedNames);
20 }
21 }
22 return importedNames;
23}
24
25function collectNamesForImport(
26 tokens,
27 index,
28 importedNames,
29) {
30 index++;
31
32 if (tokens.matches1AtIndex(index, tt.parenL)) {
33 // Dynamic import, so nothing to do
34 return;
35 }
36
37 if (tokens.matches1AtIndex(index, tt.name)) {
38 importedNames.add(tokens.identifierNameAtIndex(index));
39 index++;
40 if (tokens.matches1AtIndex(index, tt.comma)) {
41 index++;
42 }
43 }
44
45 if (tokens.matches1AtIndex(index, tt.star)) {
46 // * as
47 index += 2;
48 importedNames.add(tokens.identifierNameAtIndex(index));
49 index++;
50 }
51
52 if (tokens.matches1AtIndex(index, tt.braceL)) {
53 index++;
54 collectNamesForNamedImport(tokens, index, importedNames);
55 }
56}
57
58function collectNamesForNamedImport(
59 tokens,
60 index,
61 importedNames,
62) {
63 while (true) {
64 if (tokens.matches1AtIndex(index, tt.braceR)) {
65 return;
66 }
67
68 // We care about the local name, which might be the first token, or if there's an "as", is the
69 // one after that.
70 let name = tokens.identifierNameAtIndex(index);
71 index++;
72 if (tokens.matchesContextualAtIndex(index, ContextualKeyword._as)) {
73 index++;
74 name = tokens.identifierNameAtIndex(index);
75 index++;
76 }
77 importedNames.add(name);
78 if (tokens.matches2AtIndex(index, tt.comma, tt.braceR)) {
79 return;
80 } else if (tokens.matches1AtIndex(index, tt.braceR)) {
81 return;
82 } else if (tokens.matches1AtIndex(index, tt.comma)) {
83 index++;
84 } else {
85 throw new Error(`Unexpected token: ${JSON.stringify(tokens.tokens[index])}`);
86 }
87 }
88}