forked from prettier/prettier
/
typescript.js
76 lines (65 loc) · 2.05 KB
/
typescript.js
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
"use strict";
const createError = require("../../common/parser-create-error.js");
const tryCombinations = require("../../utils/try-combinations.js");
const createParser = require("./utils/create-parser.js");
const replaceHashbang = require("./utils/replace-hashbang.js");
const postprocess = require("./postprocess/index.js");
/** @type {import("@typescript-eslint/typescript-estree").TSESTreeOptions} */
const parseOptions = {
// `jest@<=26.4.2` rely on `loc`
// https://github.com/facebook/jest/issues/10444
loc: true,
range: true,
comment: true,
jsx: true,
tokens: true,
loggerFn: false,
project: [],
};
function createParseError(error) {
const { message, lineNumber, column } = error;
/* istanbul ignore next */
if (typeof lineNumber !== "number") {
return error;
}
return createError(message, {
start: { line: lineNumber, column: column + 1 },
});
}
function parse(text, parsers, options = {}) {
const textToParse = replaceHashbang(text);
const jsx = isProbablyJsx(text);
const { parseWithNodeMaps } = require("@typescript-eslint/typescript-estree");
const { result, error: firstError } = tryCombinations(
// Try passing with our best guess first.
() => parseWithNodeMaps(textToParse, { ...parseOptions, jsx }),
// But if we get it wrong, try the opposite.
() => parseWithNodeMaps(textToParse, { ...parseOptions, jsx: !jsx })
);
if (!result) {
// Suppose our guess is correct, throw the first error
throw createParseError(firstError);
}
options.originalText = text;
options.tsParseResult = result;
return postprocess(result.ast, options);
}
/**
* Use a naive regular expression to detect JSX
*/
function isProbablyJsx(text) {
return new RegExp(
[
"(?:^[^\"'`]*</)", // Contains "</" when probably not in a string
"|",
"(?:^[^/]{2}.*/>)", // Contains "/>" on line not starting with "//"
].join(""),
"m"
).test(text);
}
// Export as a plugin so we can reuse the same bundle for UMD loading
module.exports = {
parsers: {
typescript: createParser(parse),
},
};