UNPKG

2.13 kBJavaScriptView Raw
1"use strict";Object.defineProperty(exports, "__esModule", {value: true});var _types = require('../parser/tokenizer/types');
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18/**
19 * Determine information about this named import or named export specifier.
20 *
21 * This syntax is the `a` from statements like these:
22 * import {A} from "./foo";
23 * export {A};
24 * export {A} from "./foo";
25 *
26 * As it turns out, we can exactly characterize the syntax meaning by simply
27 * counting the number of tokens, which can be from 1 to 4:
28 * {A}
29 * {type A}
30 * {A as B}
31 * {type A as B}
32 *
33 * In the type case, we never actually need the names in practice, so don't get
34 * them.
35 *
36 * TODO: There's some redundancy with the type detection here and the isType
37 * flag that's already present on tokens in TS mode. This function could
38 * potentially be simplified and/or pushed to the call sites to avoid the object
39 * allocation.
40 */
41 function getImportExportSpecifierInfo(
42 tokens,
43 index = tokens.currentIndex(),
44) {
45 let endIndex = index + 1;
46 if (isSpecifierEnd(tokens, endIndex)) {
47 // import {A}
48 const name = tokens.identifierNameAtIndex(index);
49 return {
50 isType: false,
51 leftName: name,
52 rightName: name,
53 endIndex,
54 };
55 }
56 endIndex++;
57 if (isSpecifierEnd(tokens, endIndex)) {
58 // import {type A}
59 return {
60 isType: true,
61 leftName: null,
62 rightName: null,
63 endIndex,
64 };
65 }
66 endIndex++;
67 if (isSpecifierEnd(tokens, endIndex)) {
68 // import {A as B}
69 return {
70 isType: false,
71 leftName: tokens.identifierNameAtIndex(index),
72 rightName: tokens.identifierNameAtIndex(index + 2),
73 endIndex,
74 };
75 }
76 endIndex++;
77 if (isSpecifierEnd(tokens, endIndex)) {
78 // import {type A as B}
79 return {
80 isType: true,
81 leftName: null,
82 rightName: null,
83 endIndex,
84 };
85 }
86 throw new Error(`Unexpected import/export specifier at ${index}`);
87} exports.default = getImportExportSpecifierInfo;
88
89function isSpecifierEnd(tokens, index) {
90 const token = tokens.tokens[index];
91 return token.type === _types.TokenType.braceR || token.type === _types.TokenType.comma;
92}