-
-
Notifications
You must be signed in to change notification settings - Fork 5.6k
/
index.ts
275 lines (234 loc) 路 6.39 KB
/
index.ts
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
/// <reference path="../../../lib/third-party-libs.d.ts" />
import type { Token as JSToken, JSXToken } from "js-tokens";
import jsTokens from "js-tokens";
import {
isStrictReservedWord,
isKeyword,
} from "@babel/helper-validator-identifier";
import Chalk from "chalk";
type ChalkClass = ReturnType<typeof getChalk>;
/**
* Names that are always allowed as identifiers, but also appear as keywords
* within certain syntactic productions.
*
* https://tc39.es/ecma262/#sec-keywords-and-reserved-words
*
* `target` has been omitted since it is very likely going to be a false
* positive.
*/
const sometimesKeywords = new Set(["as", "async", "from", "get", "of", "set"]);
type InternalTokenType =
| "keyword"
| "capitalized"
| "jsxIdentifier"
| "punctuator"
| "number"
| "string"
| "regex"
| "comment"
| "invalid";
type Token = {
type: InternalTokenType | "uncolored";
value: string;
};
/**
* Chalk styles for token types.
*/
function getDefs(chalk: ChalkClass): Record<InternalTokenType, ChalkClass> {
return {
keyword: chalk.cyan,
capitalized: chalk.yellow,
jsxIdentifier: chalk.yellow,
punctuator: chalk.yellow,
number: chalk.magenta,
string: chalk.green,
regex: chalk.magenta,
comment: chalk.grey,
invalid: chalk.white.bgRed.bold,
};
}
/**
* RegExp to test for newlines in terminal.
*/
const NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
/**
* RegExp to test for the three types of brackets.
*/
const BRACKET = /^[()[\]{}]$/;
let tokenize: (
text: string,
) => Generator<{ type: InternalTokenType | "uncolored"; value: string }>;
if (process.env.BABEL_8_BREAKING) {
/**
* Get the type of token, specifying punctuator type.
*/
const getTokenType = function (
token: JSToken | JSXToken,
): InternalTokenType | "uncolored" {
if (token.type === "IdentifierName") {
if (
isKeyword(token.value) ||
isStrictReservedWord(token.value, true) ||
sometimesKeywords.has(token.value)
) {
return "keyword";
}
if (token.value[0] !== token.value[0].toLowerCase()) {
return "capitalized";
}
}
if (token.type === "Punctuator" && BRACKET.test(token.value)) {
return "uncolored";
}
if (token.type === "Invalid" && token.value === "@") {
return "punctuator";
}
switch (token.type) {
case "NumericLiteral":
return "number";
case "StringLiteral":
case "JSXString":
case "NoSubstitutionTemplate":
return "string";
case "RegularExpressionLiteral":
return "regex";
case "Punctuator":
case "JSXPunctuator":
return "punctuator";
case "MultiLineComment":
case "SingleLineComment":
return "comment";
case "Invalid":
case "JSXInvalid":
return "invalid";
case "JSXIdentifier":
return "jsxIdentifier";
default:
return "uncolored";
}
};
/**
* Turn a string of JS into an array of objects.
*/
tokenize = function* (text: string): Generator<Token> {
for (const token of jsTokens(text, { jsx: true })) {
switch (token.type) {
case "TemplateHead":
yield { type: "string", value: token.value.slice(0, -2) };
yield { type: "punctuator", value: "${" };
break;
case "TemplateMiddle":
yield { type: "punctuator", value: "}" };
yield { type: "string", value: token.value.slice(1, -2) };
yield { type: "punctuator", value: "${" };
break;
case "TemplateTail":
yield { type: "punctuator", value: "}" };
yield { type: "string", value: token.value.slice(1) };
break;
default:
yield {
type: getTokenType(token),
value: token.value,
};
}
}
};
} else {
/**
* RegExp to test for what seems to be a JSX tag name.
*/
const JSX_TAG = /^[a-z][\w-]*$/i;
// The token here is defined in js-tokens@4. However we don't bother
// typing it since the whole block will be removed in Babel 8
const getTokenType = function (token: any, offset: number, text: string) {
if (token.type === "name") {
if (
isKeyword(token.value) ||
isStrictReservedWord(token.value, true) ||
sometimesKeywords.has(token.value)
) {
return "keyword";
}
if (
JSX_TAG.test(token.value) &&
(text[offset - 1] === "<" || text.slice(offset - 2, offset) == "</")
) {
return "jsxIdentifier";
}
if (token.value[0] !== token.value[0].toLowerCase()) {
return "capitalized";
}
}
if (token.type === "punctuator" && BRACKET.test(token.value)) {
return "bracket";
}
if (
token.type === "invalid" &&
(token.value === "@" || token.value === "#")
) {
return "punctuator";
}
return token.type;
};
tokenize = function* (text: string) {
let match;
while ((match = (jsTokens as any).default.exec(text))) {
const token = (jsTokens as any).matchToToken(match);
yield {
type: getTokenType(token, match.index, text),
value: token.value,
};
}
};
}
/**
* Highlight `text` using the token definitions in `defs`.
*/
function highlightTokens(defs: Record<string, ChalkClass>, text: string) {
let highlighted = "";
for (const { type, value } of tokenize(text)) {
const colorize = defs[type];
if (colorize) {
highlighted += value
.split(NEWLINE)
.map(str => colorize(str))
.join("\n");
} else {
highlighted += value;
}
}
return highlighted;
}
/**
* Highlight `text` using the token definitions in `defs`.
*/
type Options = {
forceColor?: boolean;
};
/**
* Whether the code should be highlighted given the passed options.
*/
export function shouldHighlight(options: Options): boolean {
return !!Chalk.supportsColor || options.forceColor;
}
/**
* The Chalk instance that should be used given the passed options.
*/
export function getChalk(options: Options) {
return options.forceColor
? new Chalk.constructor({ enabled: true, level: 1 })
: Chalk;
}
/**
* Highlight `code`.
*/
export default function highlight(code: string, options: Options = {}): string {
if (code !== "" && shouldHighlight(options)) {
const chalk = getChalk(options);
const defs = getDefs(chalk);
return highlightTokens(defs, code);
} else {
return code;
}
}