Debian Codegraph @

packages/babel-core/src/parse.ts

raw
1 import gensync, { type Handler } from "gensync";
2
3 import loadConfig from "./config";
4 import type { InputOptions } from "./config";
5 import parser from "./parser";
6 import type { ParseResult } from "./parser";
7 import normalizeOptions from "./transformation/normalize-opts";
8 import type { ValidatedOptions } from "./config/validation/options";
9
10 import { beginHiddenCallStack } from "./errors/rewrite-stack-trace";
11
12 type FileParseCallback = {
13 (err: Error, ast: null): void;
14 (err: null, ast: ParseResult | null): void;
15 };
16
17 type Parse = {
18 (code: string, callback: FileParseCallback): void;
19 (
20 code: string,
21 opts: InputOptions | undefined | null,
22 callback: FileParseCallback,
23 ): void;
24 (code: string, opts?: InputOptions | null): ParseResult | null;
25 };
26
27 const parseRunner = gensync(function* parse(
28 code: string,
29 opts: InputOptions | undefined | null,
30 ): Handler<ParseResult | null> {
31 const config = yield* loadConfig(opts);
32
33 if (config === null) {
34 return null;
35 }
36
37 return yield* parser(config.passes, normalizeOptions(config), code);
38 });
39
40 export const parse: Parse = function parse(
41 code,
42 opts?,
43 callback?: FileParseCallback,
44 ) {
45 if (typeof opts === "function") {
46 callback = opts;
47 opts = undefined as ValidatedOptions;
48 }
49
50 if (callback === undefined) {
51 if (process.env.BABEL_8_BREAKING) {
52 throw new Error(
53 "Starting from Babel 8.0.0, the 'parse' function expects a callback. If you need to call it synchronously, please use 'parseSync'.",
54 );
55 } else {
56 // console.warn(
57 // "Starting from Babel 8.0.0, the 'parse' function will expect a callback. If you need to call it synchronously, please use 'parseSync'.",
58 // );
59 return beginHiddenCallStack(parseRunner.sync)(code, opts);
60 }
61 }
62
63 beginHiddenCallStack(parseRunner.errback)(code, opts, callback);
64 };
65
66 export function parseSync(...args: Parameters<typeof parseRunner.sync>) {
67 return beginHiddenCallStack(parseRunner.sync)(...args);
68 }
69 export function parseAsync(...args: Parameters<typeof parseRunner.async>) {
70 return beginHiddenCallStack(parseRunner.async)(...args);
71 }