Repository navigation
Expand file tree
/
Copy pathparser-and-printer.js
More file actions
74 lines (62 loc) · 2.03 KB
/
Copy pathparser-and-printer.js
File metadata and controls
74 lines (62 loc) · 2.03 KB
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
import { ConfigError } from "../common/errors.js";
function getParserPluginByParserName(plugins, parserName) {
if (!parserName) {
throw new Error("parserName is required.");
}
/*
Loop from end to allow plugins override builtin plugins,
this is how `resolveParser` works in v2.
This is a temporarily solution, see #13729
*/
const plugin = plugins.findLast(
(plugin) => plugin.parsers && Object.hasOwn(plugin.parsers, parserName),
);
if (plugin) {
return plugin;
}
let message = `Couldn't resolve parser "${parserName}".`;
if (process.env.PRETTIER_TARGET === "universal") {
message += " Plugins must be explicitly added to the standalone bundle.";
}
throw new ConfigError(message);
}
function getPrinterPluginByAstFormat(plugins, astFormat) {
if (!astFormat) {
throw new Error("astFormat is required.");
}
// Loop from end to consistent with parser resolve logic
const plugin = plugins.findLast(
(plugin) => plugin.printers && Object.hasOwn(plugin.printers, astFormat),
);
if (plugin) {
return plugin;
}
let message = `Couldn't find plugin for AST format "${astFormat}".`;
if (process.env.PRETTIER_TARGET === "universal") {
message += " Plugins must be explicitly added to the standalone bundle.";
}
throw new ConfigError(message);
}
function resolveParser({ plugins, parser }) {
const plugin = getParserPluginByParserName(plugins, parser);
return initParser(plugin, parser);
}
function initParser(plugin, parserName) {
const parserOrParserInitFunction = plugin.parsers[parserName];
return typeof parserOrParserInitFunction === "function"
? parserOrParserInitFunction()
: parserOrParserInitFunction;
}
function initPrinter(plugin, astFormat) {
const printerOrPrinterInitFunction = plugin.printers[astFormat];
return typeof printerOrPrinterInitFunction === "function"
? printerOrPrinterInitFunction()
: printerOrPrinterInitFunction;
}
export {
getParserPluginByParserName,
getPrinterPluginByAstFormat,
initParser,
initPrinter,
resolveParser,
};