Repository navigation
Expand file tree
/
Copy pathnormalize-format-options.js
More file actions
99 lines (84 loc) · 2.7 KB
/
Copy pathnormalize-format-options.js
File metadata and controls
99 lines (84 loc) · 2.7 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
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
import { UndefinedParserError } from "../common/errors.js";
import { getSupportInfo } from "../main/support.js";
import inferParser from "../utils/infer-parser.js";
import normalizeOptions from "./normalize-options.js";
import {
getParserPluginByParserName,
getPrinterPluginByAstFormat,
initParser,
initPrinter,
} from "./parser-and-printer.js";
const formatOptionsHiddenDefaults = {
astFormat: "estree",
printer: {},
originalText: undefined,
locStart: null,
locEnd: null,
};
// Copy options and fill in default values.
async function normalizeFormatOptions(options, opts = {}) {
const rawOptions = { ...options };
if (!rawOptions.parser) {
if (!rawOptions.filepath) {
throw new UndefinedParserError(
"No parser and no file path given, couldn't infer a parser.",
);
} else {
rawOptions.parser = inferParser(rawOptions, {
physicalFile: rawOptions.filepath,
});
if (!rawOptions.parser) {
throw new UndefinedParserError(
`No parser could be inferred for file "${rawOptions.filepath}".`,
);
}
}
}
const supportOptions = getSupportInfo({
plugins: options.plugins,
showDeprecated: true,
}).options;
const defaults = {
...formatOptionsHiddenDefaults,
...Object.fromEntries(
supportOptions
.filter((optionInfo) => optionInfo.default !== undefined)
.map((option) => [option.name, option.default]),
),
};
const parserPlugin = getParserPluginByParserName(
rawOptions.plugins,
rawOptions.parser,
);
const parser = await initParser(parserPlugin, rawOptions.parser);
rawOptions.astFormat = parser.astFormat;
rawOptions.locEnd = parser.locEnd;
rawOptions.locStart = parser.locStart;
const printerPlugin = parserPlugin.printers?.[parser.astFormat]
? parserPlugin
: getPrinterPluginByAstFormat(rawOptions.plugins, parser.astFormat);
const printer = await initPrinter(printerPlugin, parser.astFormat);
rawOptions.printer = printer;
const pluginDefaults = printerPlugin.defaultOptions
? Object.fromEntries(
Object.entries(printerPlugin.defaultOptions).filter(
([, value]) => value !== undefined,
),
)
: {};
const mixedDefaults = { ...defaults, ...pluginDefaults };
for (const [k, value] of Object.entries(mixedDefaults)) {
if (rawOptions[k] === null || rawOptions[k] === undefined) {
rawOptions[k] = value;
}
}
if (rawOptions.parser === "json") {
rawOptions.trailingComma = "none";
}
return normalizeOptions(rawOptions, supportOptions, {
passThrough: Object.keys(formatOptionsHiddenDefaults),
...opts,
});
}
export default normalizeFormatOptions;
export { formatOptionsHiddenDefaults };