UNPKG

2.61 kBJavaScriptView Raw
1"use strict";Object.defineProperty(exports, "__esModule", {value: true});var _keywords = require('../parser/tokenizer/keywords');
2var _types = require('../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 */
12 function getTSImportedNames(tokens) {
13 const importedNames = new Set();
14 for (let i = 0; i < tokens.tokens.length; i++) {
15 if (
16 tokens.matches1AtIndex(i, _types.TokenType._import) &&
17 !tokens.matches3AtIndex(i, _types.TokenType._import, _types.TokenType.name, _types.TokenType.eq)
18 ) {
19 collectNamesForImport(tokens, i, importedNames);
20 }
21 }
22 return importedNames;
23} exports.default = getTSImportedNames;
24
25function collectNamesForImport(
26 tokens,
27 index,
28 importedNames,
29) {
30 index++;
31
32 if (tokens.matches1AtIndex(index, _types.TokenType.parenL)) {
33 // Dynamic import, so nothing to do
34 return;
35 }
36
37 if (tokens.matches1AtIndex(index, _types.TokenType.name)) {
38 importedNames.add(tokens.identifierNameAtIndex(index));
39 index++;
40 if (tokens.matches1AtIndex(index, _types.TokenType.comma)) {
41 index++;
42 }
43 }
44
45 if (tokens.matches1AtIndex(index, _types.TokenType.star)) {
46 // * as
47 index += 2;
48 importedNames.add(tokens.identifierNameAtIndex(index));
49 index++;
50 }
51
52 if (tokens.matches1AtIndex(index, _types.TokenType.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, _types.TokenType.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, _keywords.ContextualKeyword._as)) {
73 index++;
74 name = tokens.identifierNameAtIndex(index);
75 index++;
76 }
77 importedNames.add(name);
78 if (tokens.matches2AtIndex(index, _types.TokenType.comma, _types.TokenType.braceR)) {
79 return;
80 } else if (tokens.matches1AtIndex(index, _types.TokenType.braceR)) {
81 return;
82 } else if (tokens.matches1AtIndex(index, _types.TokenType.comma)) {
83 index++;
84 } else {
85 throw new Error(`Unexpected token: ${JSON.stringify(tokens.tokens[index])}`);
86 }
87 }
88}