Remove dynamic imports (#14369)

This commit is contained in:
fisker Cheung authored and GitHub committed 2023-02-18 11:28:58 +08:00
1 parent be474c7891
commit 4fb03a7f2a
15 files changed
+130 -181

No files matched your search

+5 -10
View File
@@ -1,6 +1,7 @@
import fs from "node:fs/promises";
import path from "node:path";
import chalk from "chalk";
import { createTwoFilesPatch } from "diff";
import * as prettier from "../index.js";
import thirdParty from "../common/third-party.js";
import { createIsIgnoredFunction, errors } from "./prettier-internal.js";
@@ -13,12 +14,7 @@ import { statSafe } from "./utils.js";
const { getStdin } = thirdParty;
let createTwoFilesPatch;
async function diff(a, b) {
if (!createTwoFilesPatch) {
({ createTwoFilesPatch } = await import("diff"));
}
function diff(a, b) {
return createTwoFilesPatch("", "", a, b, "", "", { context: 2 });
}
@@ -137,8 +133,7 @@ async function format(context, input, opt) {
const pppp = await prettier.format(pp, opt);
if (pp !== pppp) {
throw new errors.DebugError(
"prettier(input) !== prettier(prettier(input))\n" +
(await diff(pp, pppp))
"prettier(input) !== prettier(prettier(input))\n" + diff(pp, pppp)
);
} else {
const stringify = (obj) => JSON.stringify(obj, null, 2);
@@ -155,12 +150,12 @@ async function format(context, input, opt) {
const astDiff =
ast.length > MAX_AST_SIZE || past.length > MAX_AST_SIZE
? "AST diff too large to render"
: await diff(ast, past);
: diff(ast, past);
throw new errors.DebugError(
"ast(input) !== ast(prettier(input))\n" +
astDiff +
"\n" +
(await diff(input, pp))
diff(input, pp)
);
}
/* c8 ignore end */
+44 -51
View File
@@ -1,3 +1,9 @@
import postcssParse from "postcss/lib/parse";
import postcssLess from "postcss-less";
import postcssScssParse from "postcss-scss/lib/scss-parse";
import PostcssValuesParser from "postcss-values-parser/lib/parser.js";
import PostcssSelectorParser from "postcss-selector-parser/dist/processor.js";
import postcssMediaQueryParser from "postcss-media-query-parser";
import createError from "../common/parser-create-error.js";
import parseFrontMatter from "../utils/front-matter/parse.js";
import { hasPragma } from "./pragma.js";
@@ -21,7 +27,7 @@ const getHighestAncestor = (node) => {
return node;
};
async function parseValueNode(valueNode, options) {
function parseValueNode(valueNode, options) {
const { nodes } = valueNode;
let parenGroup = {
open: null,
@@ -55,7 +61,7 @@ async function parseValueNode(valueNode, options) {
if (node.type === "func" && node.value === "selector") {
node.group.groups = [
await parseSelector(
parseSelector(
getHighestAncestor(valueNode).text.slice(
node.group.open.sourceIndex + 1,
node.group.close.sourceIndex
@@ -190,13 +196,13 @@ function addMissingType(node) {
return node;
}
async function parseNestedValue(node, options) {
function parseNestedValue(node, options) {
if (node && typeof node === "object") {
for (const key in node) {
if (key !== "parent") {
await parseNestedValue(node[key], options);
parseNestedValue(node[key], options);
if (key === "nodes") {
node.group = flattenGroups(await parseValueNode(node, options));
node.group = flattenGroups(parseValueNode(node, options));
delete node[key];
}
}
@@ -206,16 +212,14 @@ async function parseNestedValue(node, options) {
return node;
}
async function parseValue(value, options) {
function parseValue(value, options) {
// Inline javascript in Less
if (options.parser === "less" && value.startsWith("~`")) {
return { type: "value-unknown", value };
}
const Parser = await import("postcss-values-parser/lib/parser.js").then(
(m) => m.default
);
const valueParser = (source, options) => new Parser(source, options);
const valueParser = (source, options) =>
new PostcssValuesParser(source, options);
let result = null;
@@ -230,12 +234,12 @@ async function parseValue(value, options) {
result.text = value;
const parsedResult = await parseNestedValue(result, options);
const parsedResult = parseNestedValue(result, options);
return addTypePrefix(parsedResult, "value-", /^selector-/);
}
async function parseSelector(selector) {
function parseSelector(selector) {
// If there's a comment inside of a selector, the parser tries to parse
// the content of the comment as selectors which turns it into complete
// garbage. Better to print the whole selector as-is and not try to parse
@@ -247,10 +251,7 @@ async function parseSelector(selector) {
};
}
const SelectorProcessor = await import(
"postcss-selector-parser/dist/processor.js"
).then((m) => m.default);
const selectorParser = (processor) => new SelectorProcessor(processor);
const selectorParser = (processor) => new PostcssSelectorParser(processor);
let result = null;
@@ -274,15 +275,11 @@ async function parseSelector(selector) {
return addTypePrefix(result, "selector-");
}
async function parseMediaQuery(params) {
const mediaParser = await import("postcss-media-query-parser").then(
(m) => m.default.default
);
function parseMediaQuery(params) {
let result = null;
try {
result = mediaParser(params);
result = postcssMediaQueryParser.default(params);
} catch {
// Ignore bad media queries
/* c8 ignore next 4 */
@@ -298,12 +295,12 @@ async function parseMediaQuery(params) {
const DEFAULT_SCSS_DIRECTIVE = /(\s*)(!default).*$/;
const GLOBAL_SCSS_DIRECTIVE = /(\s*)(!global).*$/;
async function parseNestedCSS(node, options) {
function parseNestedCSS(node, options) {
if (node && typeof node === "object") {
delete node.parent;
for (const key in node) {
await parseNestedCSS(node[key], options);
parseNestedCSS(node[key], options);
}
if (!node.type) {
@@ -344,7 +341,7 @@ async function parseNestedCSS(node, options) {
}
let ast;
try {
ast = await parse(fakeContent, { ...options });
ast = parse(fakeContent, { ...options });
} catch {
// noop
}
@@ -424,7 +421,7 @@ async function parseNestedCSS(node, options) {
/* c8 ignore next 6 */
// Ignore LESS mixins
if (node.mixin) {
node.selector = await parseValue(selector, options);
node.selector = parseValue(selector, options);
return node;
}
@@ -434,7 +431,7 @@ async function parseNestedCSS(node, options) {
node.isSCSSNesterProperty = true;
}
node.selector = await parseSelector(selector);
node.selector = parseSelector(selector);
return node;
}
@@ -469,7 +466,7 @@ async function parseNestedCSS(node, options) {
};
}
node.value = await parseValue(value, options);
node.value = parseValue(value, options);
}
if (
@@ -483,7 +480,7 @@ async function parseNestedCSS(node, options) {
// `:extend()` is parsed as value
if (node.extend && !node.selector) {
delete node.value;
node.selector = await parseSelector(value.slice("extend(".length, -1));
node.selector = parseSelector(value.slice("extend(".length, -1));
}
}
@@ -496,7 +493,7 @@ async function parseNestedCSS(node, options) {
node.name +
node.raws.afterName +
node.raws.params;
node.selector = await parseSelector(source);
node.selector = parseSelector(source);
delete node.params;
return node;
}
@@ -511,7 +508,7 @@ async function parseNestedCSS(node, options) {
if (options.parser === "css" && node.name === "custom-selector") {
const customSelector = node.params.match(/:--\S+\s+/)[0].trim();
node.customSelector = customSelector;
node.selector = await parseSelector(
node.selector = parseSelector(
node.params.slice(customSelector.length).trim()
);
delete node.params;
@@ -527,7 +524,7 @@ async function parseNestedCSS(node, options) {
node.variable = true;
const parts = node.name.split(":");
node.name = parts[0];
node.value = await parseValue(parts.slice(1).join(":"), options);
node.value = parseValue(parts.slice(1).join(":"), options);
}
// `@color :blue;`
@@ -538,7 +535,7 @@ async function parseNestedCSS(node, options) {
node.variable = true;
const text = node.params.slice(1);
if (text) {
node.value = await parseValue(text, options);
node.value = parseValue(text, options);
}
node.raws.afterName += ":";
}
@@ -570,7 +567,7 @@ async function parseNestedCSS(node, options) {
}
if (name === "extend" || name === "nest") {
node.selector = await parseSelector(params);
node.selector = parseSelector(params);
delete node.params;
return node;
@@ -578,9 +575,9 @@ async function parseNestedCSS(node, options) {
if (name === "at-root") {
if (/^\(\s*(?:without|with)\s*:.+\)$/s.test(params)) {
node.params = await parseValue(params, options);
node.params = parseValue(params, options);
} else {
node.selector = await parseSelector(params);
node.selector = parseSelector(params);
delete node.params;
}
@@ -590,7 +587,7 @@ async function parseNestedCSS(node, options) {
if (isModuleRuleName(lowercasedName)) {
node.import = true;
delete node.filename;
node.params = await parseValue(params, options);
node.params = parseValue(params, options);
return node;
}
@@ -619,7 +616,7 @@ async function parseNestedCSS(node, options) {
// Move spaces after the `(`, so we can keep the range correct
params = params.replace(/^(?!if)(\S+)(\s+)\(/, "$1($2");
node.value = await parseValue(params, options);
node.value = parseValue(params, options);
delete node.params;
return node;
@@ -634,7 +631,7 @@ async function parseNestedCSS(node, options) {
};
}
node.params = await parseMediaQuery(params);
node.params = parseMediaQuery(params);
return node;
}
@@ -648,7 +645,7 @@ async function parseNestedCSS(node, options) {
return node;
}
async function parseWithParser(parse, text, options) {
function parseWithParser(parse, text, options) {
const parsed = parseFrontMatter(text);
const { frontMatter } = parsed;
text = parsed.content;
@@ -674,7 +671,7 @@ async function parseWithParser(parse, text, options) {
}
options.originalText = text;
result = await parseNestedCSS(addTypePrefix(result, "css-"), options);
result = parseNestedCSS(addTypePrefix(result, "css-"), options);
calculateLoc(result, text);
@@ -689,26 +686,22 @@ async function parseWithParser(parse, text, options) {
return result;
}
async function parseCss(text, options = {}) {
const parse = await import("postcss/lib/parse").then((m) => m.default);
return parseWithParser(parse, text, options);
function parseCss(text, options = {}) {
return parseWithParser(postcssParse.default, text, options);
}
async function parseLess(text, options = {}) {
const less = await import("postcss-less");
function parseLess(text, options = {}) {
return parseWithParser(
// Workaround for https://github.com/shellscape/postcss-less/issues/145
// See comments for `replaceQuotesInInlineComments` in `loc.js`.
(text) => less.parse(replaceQuotesInInlineComments(text)),
(text) => postcssLess.parse(replaceQuotesInInlineComments(text)),
text,
options
);
}
async function parseScss(text, options = {}) {
const { default: parse } = await import("postcss-scss/lib/scss-parse");
return parseWithParser(parse, text, options);
function parseScss(text, options = {}) {
return parseWithParser(postcssScssParse, text, options);
}
const postCssParser = {
+3 -5
View File
@@ -1,3 +1,4 @@
import { parse as parseGraphql } from "graphql/language/parser.mjs";
import createError from "../common/parser-create-error.js";
import { hasPragma } from "./pragma.js";
import { locStart, locEnd } from "./loc.js";
@@ -31,14 +32,11 @@ function createParseError(error) {
return error;
}
async function parse(text /*, options */) {
// Inline `import()` to avoid loading all the JS if we don't use it
const { parse } = await import("graphql/language/parser.mjs");
function parse(text /*, options */) {
/** @type {any} */
let ast;
try {
ast = parse(text, parseOptions);
ast = parseGraphql(text, parseOptions);
} catch (error) {
throw createParseError(error);
}
+8 -11
View File
@@ -1,3 +1,9 @@
/*
The module version `@glimmer/syntax/dist/modules/es2017/lib/parser/tokenizer-event-handlers.js`
can't be be imported since it use `.js` extension, and don't have `type: module` in `package.json`
We'll replace it during build
*/
import { preprocess as parseGlimmer } from "@glimmer/syntax/dist/commonjs/es2017/lib/parser/tokenizer-event-handlers.js";
import { LinesAndColumns } from "lines-and-columns";
import createError from "../common/parser-create-error.js";
import { locStart, locEnd } from "./loc.js";
@@ -47,19 +53,10 @@ function createPlugin(text) {
});
}
async function parse(text /*, options */) {
// Inline `import()` to avoid loading all the JS if we don't use it
/*
The module version `@glimmer/syntax/dist/modules/es2017/lib/parser/tokenizer-event-handlers.js`
can't be be imported since it use `.js` extension, and don't have `type: module` in `package.json`
We'll replace it during build
*/
const { preprocess: glimmer } = await import(
"@glimmer/syntax/dist/commonjs/es2017/lib/parser/tokenizer-event-handlers.js"
);
function parse(text /*, options */) {
let ast;
try {
ast = glimmer(text, {
ast = parseGlimmer(text, {
mode: "codemod",
plugins: { ast: [createPlugin(text)] },
});
+7 -19
View File
@@ -1,3 +1,5 @@
import { ParseSourceSpan } from "angular-html-parser";
// https://css-tricks.com/how-to-create-an-ie-only-stylesheet
const parseFunctions = [
@@ -18,29 +20,23 @@ const parseFunctions = [
},
];
function parseIeConditionalComment(angularHtmlParser, node, parseHtml) {
function parseIeConditionalComment(node, parseHtml) {
if (node.value) {
for (const { regex, parse } of parseFunctions) {
const match = node.value.match(regex);
if (match) {
return parse(angularHtmlParser, node, parseHtml, match);
return parse(node, parseHtml, match);
}
}
}
return null;
}
function parseIeConditionalStartEndComment(
angularHtmlParser,
node,
parseHtml,
match
) {
function parseIeConditionalStartEndComment(node, parseHtml, match) {
const [, openingTagSuffix, condition, data] = match;
const offset = "<!--".length + openingTagSuffix.length;
const contentStartSpan = node.sourceSpan.start.moveBy(offset);
const contentEndSpan = contentStartSpan.moveBy(data.length);
const { ParseSourceSpan } = angularHtmlParser;
const [complete, children] = (() => {
try {
return [true, parseHtml(data, contentStartSpan).children];
@@ -67,12 +63,7 @@ function parseIeConditionalStartEndComment(
};
}
function parseIeConditionalStartComment(
angularHtmlParser,
node,
parseHtml,
match
) {
function parseIeConditionalStartComment(node, parseHtml, match) {
const [, condition] = match;
return {
type: "ieConditionalStartComment",
@@ -81,10 +72,7 @@ function parseIeConditionalStartComment(
};
}
function parseIeConditionalEndComment(
angularHtmlParser,
node /*, parseHtml, match */
) {
function parseIeConditionalEndComment(node /*, parseHtml, match */) {
return {
type: "ieConditionalEndComment",
sourceSpan: node.sourceSpan,
+16 -30
View File
@@ -1,3 +1,13 @@
import {
ParseSourceFile,
ParseLocation,
ParseSourceSpan,
parse as parseHtml,
RecursiveVisitor,
visitAll,
getHtmlTagDefinition,
TagContentType,
} from "angular-html-parser";
import parseFrontMatter from "../utils/front-matter/parse.js";
import inferParserByLanguage from "../utils/infer-parser-by-language.js";
import createError from "../common/parser-create-error.js";
@@ -33,13 +43,11 @@ import { locStart, locEnd } from "./loc.js";
*/
/**
* @param {AngularHtmlParser} angularHtmlParser
* @param {string} input
* @param {ParserOptions} parserOptions
* @param {Options} options
*/
function ngHtmlParser(
angularHtmlParser,
input,
{
canSelfClose,
@@ -51,16 +59,7 @@ function ngHtmlParser(
},
options
) {
const {
parse,
RecursiveVisitor,
visitAll,
ParseSourceSpan,
getHtmlTagDefinition,
TagContentType,
} = angularHtmlParser;
let { rootNodes, errors } = parse(input, {
let { rootNodes, errors } = parseHtml(input, {
canSelfClose,
allowHtmComponentClosingTags,
isTagNameCaseSensitive,
@@ -94,7 +93,7 @@ function ngHtmlParser(
/** @type {ParserTreeResult | undefined} */
let secondParseResult;
const doSecondParse = () =>
parse(input, {
parseHtml(input, {
canSelfClose,
allowHtmComponentClosingTags,
isTagNameCaseSensitive,
@@ -137,7 +136,7 @@ function ngHtmlParser(
normalizeAttributeName = true;
allowHtmComponentClosingTags = true;
isTagNameCaseSensitive = false;
const htmlParseResult = parse(input, {
const htmlParseResult = parseHtml(input, {
canSelfClose,
allowHtmComponentClosingTags,
isTagNameCaseSensitive,
@@ -293,32 +292,23 @@ function ngHtmlParser(
}
/**
* @param {AngularHtmlParser} angularHtmlParser
* @param {string} text
* @param {Options} options
* @param {ParserOptions} parserOptions
* @param {boolean} shouldParseFrontMatter
*/
function _parse(
angularHtmlParser,
text,
options,
parserOptions,
shouldParseFrontMatter = true
) {
function _parse(text, options, parserOptions, shouldParseFrontMatter = true) {
const { frontMatter, content } = shouldParseFrontMatter
? parseFrontMatter(text)
: { frontMatter: null, content: text };
const { ParseSourceFile, ParseLocation, ParseSourceSpan } = angularHtmlParser;
const file = new ParseSourceFile(text, options.filepath);
const start = new ParseLocation(file, 0, 0, 0);
const end = start.moveBy(text.length);
const rawAst = {
type: "root",
sourceSpan: new ParseSourceSpan(start, end),
children: ngHtmlParser(angularHtmlParser, content, parserOptions, options),
children: ngHtmlParser(content, parserOptions, options),
};
if (frontMatter) {
@@ -336,7 +326,6 @@ function _parse(
const fakeContent = text.slice(0, offset).replaceAll(/[^\n\r]/g, " ");
const realContent = subContent;
const subAst = _parse(
angularHtmlParser,
fakeContent + realContent,
options,
parserOptions,
@@ -366,7 +355,6 @@ function _parse(
ast.walk((node) => {
if (node.type === "comment") {
const ieConditionalComment = parseIeConditionalComment(
angularHtmlParser,
node,
parseSubHtml
);
@@ -392,10 +380,8 @@ function createParser({
shouldParseAsRawText,
} = {}) {
return {
async parse(text, options) {
const angularHtmlParser = await import("angular-html-parser");
parse(text, options) {
return _parse(
angularHtmlParser,
text,
{ parser: name, ...options },
{
+25 -17
View File
@@ -1,31 +1,39 @@
import {
parseAction,
parseBinding,
parseInterpolationExpression,
parseTemplateBindings,
} from "angular-estree-parser";
import { locStart, locEnd } from "../loc.js";
/**
* @param {"parseAction" | "parseBinding" | "parseInterpolationExpression" | "parseTemplateBindings"} parseMethod
* @param {parseAction | parseBinding | parseInterpolationExpression | parseTemplateBindings} parseMethod
*/
function createParser(parseMethod) {
const parse = async (text) => {
const { [parseMethod]: parse } = await import("angular-estree-parser");
const node = parse(text);
return {
astFormat: "estree",
parse(text) {
const node = parseMethod(text);
return {
type: "NGRoot",
node:
parseMethod === "parseAction" && node.type !== "NGChainedExpression"
? { ...node, type: "NGChainedExpression", expressions: [node] }
: node,
};
return {
type: "NGRoot",
node:
parseMethod === parseAction && node.type !== "NGChainedExpression"
? { ...node, type: "NGChainedExpression", expressions: [node] }
: node,
};
},
locStart,
locEnd,
};
return { astFormat: "estree", parse, locStart, locEnd };
}
const parser = {
parsers: {
__ng_action: createParser("parseAction"),
__ng_binding: createParser("parseBinding"),
__ng_interpolation: createParser("parseInterpolationExpression"),
__ng_directive: createParser("parseTemplateBindings"),
__ng_action: createParser(parseAction),
__ng_binding: createParser(parseBinding),
__ng_interpolation: createParser(parseInterpolationExpression),
__ng_directive: createParser(parseTemplateBindings),
},
};
+2 -5
View File
@@ -1,3 +1,4 @@
import { parse as babelParse, parseExpression } from "@babel/parser";
import tryCombinations from "../../utils/try-combinations.js";
import getShebang from "../utils/get-shebang.js";
import getNextNonSpaceNonCommentCharacterIndex from "../../utils/get-next-non-space-non-comment-character-index.js";
@@ -102,7 +103,7 @@ function parseWithOptions(parse, text, options) {
}
function createParse({ isExpression = false, optionsCombinations }) {
return async (text, opts = {}) => {
return (text, opts = {}) => {
if (
(opts.parser === "babel" || opts.parser === "__babel_estree") &&
isFlowFile(text, opts)
@@ -142,10 +143,6 @@ function createParse({ isExpression = false, optionsCombinations }) {
);
}
// Inline `import()` to avoid loading all the JS if we don't use it
const { parse: babelParse, parseExpression } = await import(
"@babel/parser"
);
/** @type {Parse} */
const parseFunction = isExpression ? parseExpression : babelParse;
let { result: ast, error } = tryCombinations(
+3 -6
View File
@@ -1,3 +1,4 @@
import flowParser from "flow-parser";
import createError from "../../common/parser-create-error.js";
import createParser from "./utils/create-parser.js";
import replaceHashbang from "./utils/replace-hashbang.js";
@@ -39,12 +40,8 @@ function createParseError(error) {
});
}
async function parse(text, options = {}) {
// Inline `import()` to avoid loading all the JS if we don't use it
const {
default: { parse },
} = await import("flow-parser");
const ast = parse(replaceHashbang(text), parseOptions);
function parse(text, options = {}) {
const ast = flowParser.parse(replaceHashbang(text), parseOptions);
const [error] = ast.errors;
if (error) {
throw createParseError(error);
+5 -6
View File
@@ -1,3 +1,4 @@
import { parse as meriyahParse } from "meriyah";
import createError from "../../common/parser-create-error.js";
import tryCombinations from "../../utils/try-combinations.js";
import createParser from "./utils/create-parser.js";
@@ -40,12 +41,12 @@ const parseOptions = {
uniqueKeyInPattern: false,
};
function parseWithOptions(parse, text, sourceType) {
function parseWithOptions(text, sourceType) {
const comments = [];
const tokens = [];
/** @type {any} */
const ast = parse(text, {
const ast = meriyahParse(text, {
...parseOptions,
module: sourceType === "module",
onComment: comments,
@@ -85,12 +86,10 @@ function createParseError(error) {
});
}
async function parse(text, options = {}) {
const { parse } = await import("meriyah");
function parse(text, options = {}) {
const sourceType = getSourceType(options);
const combinations = (sourceType ? [sourceType] : ["module", "script"]).map(
(sourceType) => () => parseWithOptions(parse, text, sourceType)
(sourceType) => () => parseWithOptions(text, sourceType)
);
const { result: ast, error } = tryCombinations(combinations);
@@ -1,10 +1,8 @@
import ts from "typescript";
import isNonEmptyArray from "../../../utils/is-non-empty-array.js";
import visitNode from "./visit-node.js";
import throwTsSyntaxError from "./throw-ts-syntax-error.js";
/** @type {import("typescript")} */
let ts;
function getTsNodeLocation(nodeOrToken) {
const sourceFile =
// @ts-expect-error -- internal?
@@ -292,15 +290,11 @@ const decoratorOrModifierRegExp = new RegExp(
["@", ...POSSIBLE_MODIFIERS].join("|")
);
async function throwErrorForInvalidNodes(tsParseResult, options) {
function throwErrorForInvalidNodes(tsParseResult, options) {
if (!decoratorOrModifierRegExp.test(options.originalText)) {
return;
}
if (!ts) {
({ default: ts } = await import("typescript"));
}
visitNode(tsParseResult.ast, (esTreeNode) => {
const tsNode = getTsNode(esTreeNode, tsParseResult);
if (!tsNode) {
+3 -5
View File
@@ -1,3 +1,4 @@
import { parseWithNodeMaps } from "@typescript-eslint/typescript-estree/dist/parser.js";
import createError from "../../common/parser-create-error.js";
import tryCombinations from "../../utils/try-combinations.js";
import createParser from "./utils/create-parser.js";
@@ -36,13 +37,10 @@ function createParseError(error) {
});
}
async function parse(text, options = {}) {
function parse(text, options = {}) {
const textToParse = replaceHashbang(text);
const jsx = isProbablyJsx(text);
const { parseWithNodeMaps } = await import(
"@typescript-eslint/typescript-estree/dist/parser.js"
);
const { result, error } = tryCombinations([
// Try passing with our best guess first.
() => parseWithNodeMaps(textToParse, { ...parseOptions, jsx }),
@@ -57,7 +55,7 @@ async function parse(text, options = {}) {
options.originalText = text;
await throwErrorForInvalidNodes(result, options);
throwErrorForInvalidNodes(result, options);
return postprocess(result.ast, options);
}
+2 -2
View File
@@ -1,3 +1,4 @@
import { parseExpression } from "@babel/parser";
import isNonEmptyArray from "../utils/is-non-empty-array.js";
import createError from "../common/parser-create-error.js";
import createParser from "../language-js/parse/utils/create-parser.js";
@@ -7,8 +8,7 @@ import wrapBabelExpression from "../language-js/parse/utils/wrap-babel-expressio
function createJsonParse(options = {}) {
const { allowComments = true } = options;
return async function parse(text, options = {}) {
const { parseExpression } = await import("@babel/parser");
return function parse(text, options = {}) {
let ast;
try {
ast = parseExpression(text, {
+2 -3
View File
@@ -1,10 +1,9 @@
import { parse as parseYaml } from "yaml-unist-parser/lib/parse.js";
import createError from "../common/parser-create-error.js";
import { hasPragma } from "./pragma.js";
import { locStart, locEnd } from "./loc.js";
async function parse(text) {
const { parse: parseYaml } = await import("yaml-unist-parser/lib/parse.js");
function parse(text) {
try {
const root = parseYaml(text);
+3 -3
View File
@@ -1,3 +1,4 @@
import { codeFrameColumns } from "@babel/code-frame";
import { ConfigError } from "../common/errors.js";
function resolveParser({ plugins, parser }) {
@@ -41,17 +42,16 @@ async function parse(originalText, options) {
options
);
} catch (error) {
await handleParseError(error, originalText);
handleParseError(error, originalText);
}
return { text, ast };
}
async function handleParseError(error, text) {
function handleParseError(error, text) {
const { loc } = error;
if (loc) {
const { codeFrameColumns } = await import("@babel/code-frame");
const codeFrame = codeFrameColumns(text, loc, { highlightCode: true });
error.message += "\n" + codeFrame;
error.codeFrame = codeFrame;