Debian Codegraph @

packages/babel-core/src/transformation/normalize-file.ts

raw ◀ ▶
1 Debian patch touch this file
1 import fs from "fs";
2 import path from "path";
3 import buildDebug from "debug";
4 import type { Handler } from "gensync";
5 import { file, traverseFast } from "@babel/types";
6 import type * as t from "@babel/types";
7 import type { PluginPasses } from "../config";
8 import convertSourceMap from "convert-source-map";
9 import type { SourceMapConverter as Converter } from "convert-source-map";
10 import File from "./file/file";
11 import parser from "../parser";
12 import cloneDeep from "./util/clone-deep";
13
14 const debug = buildDebug("babel:transform:file");
•15 const LARGE_INPUT_SOURCEMAP_THRESHOLD = 3000000;
16
17 // These regexps are copied from the convert-source-map package,
18 // but without // or /* at the beginning of the comment.
19
20 // eslint-disable-next-line max-len
21 const INLINE_SOURCEMAP_REGEX =
22 /^[@#]\s+sourceMappingURL=data:(?:application|text)\/json;(?:charset[:=]\S+?;)?base64,(?:.*)$/;
23 const EXTERNAL_SOURCEMAP_REGEX =
24 /^[@#][ \t]+sourceMappingURL=([^\s'"`]+)[ \t]*$/;
25
26 export type NormalizedFile = {
27 code: string;
28 ast: t.File;
29 inputMap: Converter | null;
30 };
31
32 export default function* normalizeFile(
33 pluginPasses: PluginPasses,
34 options: { [key: string]: any },
35 code: string,
36 ast?: t.File | t.Program | null,
37 ): Handler<File> {
38 code = `${code || ""}`;
39
40 if (ast) {
41 if (ast.type === "Program") {
42 ast = file(ast, [], []);
43 } else if (ast.type !== "File") {
44 throw new Error("AST root must be a Program or File node");
45 }
46
47 if (options.cloneInputAst) {
48 ast = cloneDeep(ast);
49 }
50 } else {
51 // @ts-expect-error todo: use babel-types ast typings in Babel parser
52 ast = yield* parser(pluginPasses, options, code);
53 }
54
55 let inputMap = null;
56 if (options.inputSourceMap !== false) {
57 // If an explicit object is passed in, it overrides the processing of
58 // source maps that may be in the file itself.
59 if (typeof options.inputSourceMap === "object") {
60 inputMap = convertSourceMap.fromObject(options.inputSourceMap);
61 }
62
63 if (!inputMap) {
64 const lastComment = extractComments(INLINE_SOURCEMAP_REGEX, ast);
65 if (lastComment) {
66 try {
67 inputMap = convertSourceMap.fromComment(lastComment);
68 } catch (err) {
69 debug("discarding unknown inline input sourcemap", err);
70 }
71 }
72 }
73
74 if (!inputMap) {
75 const lastComment = extractComments(EXTERNAL_SOURCEMAP_REGEX, ast);
76 if (typeof options.filename === "string" && lastComment) {
77 try {
78 // when `lastComment` is non-null, EXTERNAL_SOURCEMAP_REGEX must have matches
79 const match: [string, string] = EXTERNAL_SOURCEMAP_REGEX.exec(
80 lastComment,
81 ) as any;
82 const inputMapContent = fs.readFileSync(
83 path.resolve(path.dirname(options.filename), match[1]),
84 );
85 if (inputMapContent.length > LARGE_INPUT_SOURCEMAP_THRESHOLD) {
86 debug("skip merging input map > 1 MB");
87 } else {
88 inputMap = convertSourceMap.fromJSON(
89 // todo:
90 inputMapContent as unknown as string,
91 );
92 }
93 } catch (err) {
94 debug("discarding unknown file input sourcemap", err);
95 }
96 } else if (lastComment) {
97 debug("discarding un-loadable file input sourcemap");
98 }
99 }
100 }
101
102 return new File(options, {
103 code,
104 ast: ast as t.File,
105 inputMap,
106 });
107 }
108
109 function extractCommentsFromList(
110 regex: RegExp,
111 comments: t.Comment[],
112 lastComment: string | null,
113 ): [t.Comment[], string | null] {
114 if (comments) {
115 comments = comments.filter(({ value }) => {
116 if (regex.test(value)) {
117 lastComment = value;
118 return false;
119 }
120 return true;
121 });
122 }
123 return [comments, lastComment];
124 }
125
126 function extractComments(regex: RegExp, ast: t.Node) {
127 let lastComment: string = null;
128 traverseFast(ast, node => {
129 [node.leadingComments, lastComment] = extractCommentsFromList(
130 regex,
131 node.leadingComments,
132 lastComment,
133 );
134 [node.innerComments, lastComment] = extractCommentsFromList(
135 regex,
136 node.innerComments,
137 lastComment,
138 );
139 [node.trailingComments, lastComment] = extractCommentsFromList(
140 regex,
141 node.trailingComments,
142 lastComment,
143 );
144 });
145 return lastComment;
146 }