Debian Codegraph @

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

raw
1 import * as helpers from "@babel/helpers";
2 import { NodePath } from "@babel/traverse";
3 import type { HubInterface, Visitor, Scope } from "@babel/traverse";
4 import { codeFrameColumns } from "@babel/code-frame";
5 import traverse from "@babel/traverse";
6 import { cloneNode, interpreterDirective } from "@babel/types";
7 import type * as t from "@babel/types";
8 import { getModuleName } from "@babel/helper-module-transforms";
9 import semver from "semver";
10
11 import type { NormalizedFile } from "../normalize-file";
12
13 const errorVisitor: Visitor<{ loc: NodeLocation["loc"] | null }> = {
14 enter(path, state) {
15 const loc = path.node.loc;
16 if (loc) {
17 state.loc = loc;
18 path.stop();
19 }
20 },
21 };
22
23 export type NodeLocation = {
24 loc?: {
25 end?: {
26 line: number;
27 column: number;
28 };
29 start: {
30 line: number;
31 column: number;
32 };
33 };
34 _loc?: {
35 end?: {
36 line: number;
37 column: number;
38 };
39 start: {
40 line: number;
41 column: number;
42 };
43 };
44 };
45
46 export default class File {
47 _map: Map<unknown, unknown> = new Map();
48 opts: { [key: string]: any };
49 declarations: { [key: string]: t.Identifier } = {};
50 path: NodePath<t.Program>;
51 ast: t.File;
52 scope: Scope;
53 metadata: { [key: string]: any } = {};
54 code: string = "";
55 inputMap: any;
56
57 hub: HubInterface & { file: File } = {
58 // keep it for the usage in babel-core, ex: path.hub.file.opts.filename
59 file: this,
60 getCode: () => this.code,
61 getScope: () => this.scope,
62 addHelper: this.addHelper.bind(this),
63 buildError: this.buildCodeFrameError.bind(this),
64 };
65
66 constructor(options: {}, { code, ast, inputMap }: NormalizedFile) {
67 this.opts = options;
68 this.code = code;
69 this.ast = ast;
70 this.inputMap = inputMap;
71
72 this.path = NodePath.get({
73 hub: this.hub,
74 parentPath: null,
75 parent: this.ast,
76 container: this.ast,
77 key: "program",
78 }).setContext() as NodePath<t.Program>;
79 this.scope = this.path.scope;
80 }
81
82 /**
83 * Provide backward-compatible access to the interpreter directive handling
84 * in Babel 6.x. If you are writing a plugin for Babel 7.x, it would be
85 * best to use 'program.interpreter' directly.
86 */
87 get shebang(): string {
88 const { interpreter } = this.path.node;
89 return interpreter ? interpreter.value : "";
90 }
91 set shebang(value: string) {
92 if (value) {
93 this.path.get("interpreter").replaceWith(interpreterDirective(value));
94 } else {
95 this.path.get("interpreter").remove();
96 }
97 }
98
99 set(key: unknown, val: unknown) {
100 if (key === "helpersNamespace") {
101 throw new Error(
102 "Babel 7.0.0-beta.56 has dropped support for the 'helpersNamespace' utility." +
103 "If you are using @babel/plugin-external-helpers you will need to use a newer " +
104 "version than the one you currently have installed. " +
105 "If you have your own implementation, you'll want to explore using 'helperGenerator' " +
106 "alongside 'file.availableHelper()'.",
107 );
108 }
109
110 this._map.set(key, val);
111 }
112
113 get(key: unknown): any {
114 return this._map.get(key);
115 }
116
117 has(key: unknown): boolean {
118 return this._map.has(key);
119 }
120
121 getModuleName(): string | undefined | null {
122 return getModuleName(this.opts, this.opts);
123 }
124
125 addImport() {
126 throw new Error(
127 "This API has been removed. If you're looking for this " +
128 "functionality in Babel 7, you should import the " +
129 "'@babel/helper-module-imports' module and use the functions exposed " +
130 " from that module, such as 'addNamed' or 'addDefault'.",
131 );
132 }
133
134 /**
135 * Check if a given helper is available in @babel/core's helper list.
136 *
137 * This _also_ allows you to pass a Babel version specifically. If the
138 * helper exists, but was not available for the full given range, it will be
139 * considered unavailable.
140 */
141 availableHelper(name: string, versionRange?: string | null): boolean {
142 let minVersion;
143 try {
144 minVersion = helpers.minVersion(name);
145 } catch (err) {
146 if (err.code !== "BABEL_HELPER_UNKNOWN") throw err;
147
148 return false;
149 }
150
151 if (typeof versionRange !== "string") return true;
152
153 // semver.intersects() has some surprising behavior with comparing ranges
154 // with pre-release versions. We add '^' to ensure that we are always
155 // comparing ranges with ranges, which sidesteps this logic.
156 // For example:
157 //
158 // semver.intersects(`<7.0.1`, "7.0.0-beta.0") // false - surprising
159 // semver.intersects(`<7.0.1`, "^7.0.0-beta.0") // true - expected
160 //
161 // This is because the first falls back to
162 //
163 // semver.satisfies("7.0.0-beta.0", `<7.0.1`) // false - surprising
164 //
165 // and this fails because a prerelease version can only satisfy a range
166 // if it is a prerelease within the same major/minor/patch range.
167 //
168 // Note: If this is found to have issues, please also revisit the logic in
169 // transform-runtime's definitions.js file.
170 if (semver.valid(versionRange)) versionRange = `^${versionRange}`;
171
172 return (
173 !semver.intersects(`<${minVersion}`, versionRange) &&
174 !semver.intersects(`>=8.0.0`, versionRange)
175 );
176 }
177
178 addHelper(name: string): t.Identifier {
179 const declar = this.declarations[name];
180 if (declar) return cloneNode(declar);
181
182 const generator = this.get("helperGenerator");
183 if (generator) {
184 const res = generator(name);
185 if (res) return res;
186 }
187
188 // make sure that the helper exists
189 helpers.ensure(name, File);
190
191 const uid = (this.declarations[name] =
192 this.scope.generateUidIdentifier(name));
193
194 const dependencies: { [key: string]: t.Identifier } = {};
195 for (const dep of helpers.getDependencies(name)) {
196 dependencies[dep] = this.addHelper(dep);
197 }
198
199 const { nodes, globals } = helpers.get(
200 name,
201 dep => dependencies[dep],
202 uid,
203 Object.keys(this.scope.getAllBindings()),
204 );
205
206 globals.forEach(name => {
207 if (this.path.scope.hasBinding(name, true /* noGlobals */)) {
208 this.path.scope.rename(name);
209 }
210 });
211
212 nodes.forEach(node => {
213 // @ts-expect-error Fixme: document _compact node property
214 node._compact = true;
215 });
216
217 this.path.unshiftContainer("body", nodes);
218 // TODO: NodePath#unshiftContainer should automatically register new
219 // bindings.
220 this.path.get("body").forEach(path => {
221 if (nodes.indexOf(path.node) === -1) return;
222 if (path.isVariableDeclaration()) this.scope.registerDeclaration(path);
223 });
224
225 return uid;
226 }
227
228 addTemplateObject() {
229 throw new Error(
230 "This function has been moved into the template literal transform itself.",
231 );
232 }
233
234 buildCodeFrameError(
235 node: NodeLocation | undefined | null,
236 msg: string,
237 _Error: typeof Error = SyntaxError,
238 ): Error {
239 let loc = node && (node.loc || node._loc);
240
241 if (!loc && node) {
242 const state: { loc?: NodeLocation["loc"] | null } = {
243 loc: null,
244 };
245 traverse(node as t.Node, errorVisitor, this.scope, state);
246 loc = state.loc;
247
248 let txt =
249 "This is an error on an internal node. Probably an internal error.";
250 if (loc) txt += " Location has been estimated.";
251
252 msg += ` (${txt})`;
253 }
254
255 if (loc) {
256 const { highlightCode = true } = this.opts;
257
258 msg +=
259 "\n" +
260 codeFrameColumns(
261 this.code,
262 {
263 start: {
264 line: loc.start.line,
265 column: loc.start.column + 1,
266 },
267 end:
268 loc.end && loc.start.line === loc.end.line
269 ? {
270 line: loc.end.line,
271 column: loc.end.column + 1,
272 }
273 : undefined,
274 },
275 { highlightCode },
276 );
277 }
278
279 return new _Error(msg);
280 }
281 }