Debian Codegraph @

packages/babel-helpers/src/index.ts

raw symbols SCIP
1 import type { File } from "@babel/core";
2 import type { NodePath, Visitor } from "@babel/traverse";
3 import traverse from "@babel/traverse";
4 import {
5 assignmentExpression,
6 cloneNode,
7 expressionStatement,
8 file,
9 identifier,
10 } from "@babel/types";
11 import type * as t from "@babel/types";
12 import helpers from "./helpers";
13
14 function makePath(path: NodePath) {
15 const parts = [];
16
17 for (; path.parentPath; path = path.parentPath) {
18 parts.push(path.key);
19 if (path.inList) parts.push(path.listKey);
20 }
21
22 return parts.reverse().join(".");
23 }
24
25 let FileClass: typeof File | undefined = undefined;
26
27 interface HelperMetadata {
28 globals: string[];
29 localBindingNames: string[];
30 dependencies: Map<t.Identifier, string>;
31 exportBindingAssignments: string[];
32 exportPath: string;
33 exportName: string;
34 importBindingsReferences: string[];
35 importPaths: string[];
36 }
37
38 /**
39 * Given a file AST for a given helper, get a bunch of metadata about it so that Babel can quickly render
40 * the helper is whatever context it is needed in.
41 */
42 function getHelperMetadata(file: File): HelperMetadata {
43 const globals = new Set<string>();
44 const localBindingNames = new Set<string>();
45 // Maps imported identifier -> helper name
46 const dependencies = new Map<t.Identifier, string>();
47
48 let exportName: string | undefined;
49 let exportPath: string | undefined;
50 const exportBindingAssignments: string[] = [];
51 const importPaths: string[] = [];
52 const importBindingsReferences: string[] = [];
53
54 const dependencyVisitor: Visitor = {
55 ImportDeclaration(child) {
56 const name = child.node.source.value;
57 if (!helpers[name]) {
58 throw child.buildCodeFrameError(`Unknown helper ${name}`);
59 }
60 if (
61 child.get("specifiers").length !== 1 ||
62 // @ts-expect-error isImportDefaultSpecifier does not work with NodePath union
63 !child.get("specifiers.0").isImportDefaultSpecifier()
64 ) {
65 throw child.buildCodeFrameError(
66 "Helpers can only import a default value",
67 );
68 }
69 const bindingIdentifier = child.node.specifiers[0].local;
70 dependencies.set(bindingIdentifier, name);
71 importPaths.push(makePath(child));
72 },
73 ExportDefaultDeclaration(child) {
74 const decl = child.get("declaration");
75
76 if (!decl.isFunctionDeclaration() || !decl.node.id) {
77 throw decl.buildCodeFrameError(
78 "Helpers can only export named function declarations",
79 );
80 }
81
82 exportName = decl.node.id.name;
83 exportPath = makePath(child);
84 },
85 ExportAllDeclaration(child) {
86 throw child.buildCodeFrameError("Helpers can only export default");
87 },
88 ExportNamedDeclaration(child) {
89 throw child.buildCodeFrameError("Helpers can only export default");
90 },
91 Statement(child) {
92 if (child.isImportDeclaration() || child.isExportDeclaration()) return;
93
94 child.skip();
95 },
96 };
97
98 const referenceVisitor: Visitor = {
99 Program(path) {
100 const bindings = path.scope.getAllBindings();
101
102 Object.keys(bindings).forEach(name => {
103 if (name === exportName) return;
104 if (dependencies.has(bindings[name].identifier)) return;
105
106 localBindingNames.add(name);
107 });
108 },
109 ReferencedIdentifier(child) {
110 const name = child.node.name;
111 const binding = child.scope.getBinding(name);
112 if (!binding) {
113 globals.add(name);
114 } else if (dependencies.has(binding.identifier)) {
115 importBindingsReferences.push(makePath(child));
116 }
117 },
118 AssignmentExpression(child) {
119 const left = child.get("left");
120
121 if (!(exportName in left.getBindingIdentifiers())) return;
122
123 if (!left.isIdentifier()) {
124 throw left.buildCodeFrameError(
125 "Only simple assignments to exports are allowed in helpers",
126 );
127 }
128
129 const binding = child.scope.getBinding(exportName);
130
131 if (binding?.scope.path.isProgram()) {
132 exportBindingAssignments.push(makePath(child));
133 }
134 },
135 };
136
137 traverse(file.ast, dependencyVisitor, file.scope);
138 traverse(file.ast, referenceVisitor, file.scope);
139
140 if (!exportPath) throw new Error("Helpers must have a default export.");
141
142 // Process these in reverse so that mutating the references does not invalidate any later paths in
143 // the list.
144 exportBindingAssignments.reverse();
145
146 return {
147 globals: Array.from(globals),
148 localBindingNames: Array.from(localBindingNames),
149 dependencies,
150 exportBindingAssignments,
151 exportPath,
152 exportName,
153 importBindingsReferences,
154 importPaths,
155 };
156 }
157
158 type GetDependency = (name: string) => t.Expression;
159
160 /**
161 * Given a helper AST and information about how it will be used, update the AST to match the usage.
162 */
163 function permuteHelperAST(
164 file: File,
165 metadata: HelperMetadata,
166 id?: t.Identifier | t.MemberExpression,
167 localBindings?: string[],
168 getDependency?: GetDependency,
169 ) {
170 if (localBindings && !id) {
171 throw new Error("Unexpected local bindings for module-based helpers.");
172 }
173
174 if (!id) return;
175
176 const {
177 localBindingNames,
178 dependencies,
179 exportBindingAssignments,
180 exportPath,
181 exportName,
182 importBindingsReferences,
183 importPaths,
184 } = metadata;
185
186 const dependenciesRefs: Record<string, t.Expression> = {};
187 dependencies.forEach((name, id) => {
188 dependenciesRefs[id.name] =
189 (typeof getDependency === "function" && getDependency(name)) || id;
190 });
191
192 const toRename: Record<string, string> = {};
193 const bindings = new Set(localBindings || []);
194 localBindingNames.forEach(name => {
195 let newName = name;
196 while (bindings.has(newName)) newName = "_" + newName;
197
198 if (newName !== name) toRename[name] = newName;
199 });
200
201 if (id.type === "Identifier" && exportName !== id.name) {
202 toRename[exportName] = id.name;
203 }
204
205 const { path } = file;
206
207 // We need to compute these in advance because removing nodes would
208 // invalidate the paths.
209 const exp: NodePath<t.ExportDefaultDeclaration> = path.get(exportPath);
210 const imps: NodePath<t.ImportDeclaration>[] = importPaths.map(p =>
211 path.get(p),
212 );
213 const impsBindingRefs: NodePath<t.Identifier>[] =
214 importBindingsReferences.map(p => path.get(p));
215
216 // We assert that this is a FunctionDeclaration in dependencyVisitor.
217 const decl = exp.get("declaration") as NodePath<t.FunctionDeclaration>;
218
219 if (id.type === "Identifier") {
220 exp.replaceWith(decl);
221 } else if (id.type === "MemberExpression") {
222 exportBindingAssignments.forEach(assignPath => {
223 const assign: NodePath<t.Expression> = path.get(assignPath);
224 assign.replaceWith(assignmentExpression("=", id, assign.node));
225 });
226 exp.replaceWith(decl);
227 path.pushContainer(
228 "body",
229 expressionStatement(
230 assignmentExpression("=", id, identifier(exportName)),
231 ),
232 );
233 } else {
234 throw new Error("Unexpected helper format.");
235 }
236
237 Object.keys(toRename).forEach(name => {
238 path.scope.rename(name, toRename[name]);
239 });
240
241 for (const path of imps) path.remove();
242 for (const path of impsBindingRefs) {
243 const node = cloneNode(dependenciesRefs[path.node.name]);
244 path.replaceWith(node);
245 }
246 }
247
248 interface HelperData {
249 build: (
250 getDependency: GetDependency,
251 id: t.Identifier | t.MemberExpression,
252 localBindings: string[],
253 ) => {
254 nodes: t.Program["body"];
255 globals: string[];
256 };
257 minVersion: string;
258 getDependencies: () => string[];
259 }
260
261 const helperData: Record<string, HelperData> = Object.create(null);
262 function loadHelper(name: string) {
263 if (!helperData[name]) {
264 const helper = helpers[name];
265 if (!helper) {
266 throw Object.assign(new ReferenceError(`Unknown helper ${name}`), {
267 code: "BABEL_HELPER_UNKNOWN",
268 helper: name,
269 });
270 }
271
272 const fn = (): File => {
273 if (!process.env.BABEL_8_BREAKING) {
274 if (!FileClass) {
275 const fakeFile = { ast: file(helper.ast()), path: null } as File;
276 traverse(fakeFile.ast, {
277 Program: path => (fakeFile.path = path).stop(),
278 });
279 return fakeFile;
280 }
281 }
282 return new FileClass(
283 { filename: `babel-helper://${name}` },
284 {
285 ast: file(helper.ast()),
286 code: "[internal Babel helper code]",
287 inputMap: null,
288 },
289 );
290 };
291
292 // We compute the helper metadata lazily, so that we skip that
293 // work if we only need the `.minVersion` (for example because
294 // of a call to `.availableHelper` when `@babel/rutime`).
295 let metadata: HelperMetadata | null = null;
296
297 helperData[name] = {
298 minVersion: helper.minVersion,
299 build(getDependency, id, localBindings) {
300 const file = fn();
301 metadata ||= getHelperMetadata(file);
302 permuteHelperAST(file, metadata, id, localBindings, getDependency);
303
304 return {
305 nodes: file.ast.program.body,
306 globals: metadata.globals,
307 };
308 },
309 getDependencies() {
310 metadata ||= getHelperMetadata(fn());
311 return Array.from(metadata.dependencies.values());
312 },
313 };
314 }
315
316 return helperData[name];
317 }
318
319 export function get(
320 name: string,
321 getDependency?: GetDependency,
322 id?: t.Identifier | t.MemberExpression,
323 localBindings?: string[],
324 ) {
325 return loadHelper(name).build(getDependency, id, localBindings);
326 }
327
328 export function minVersion(name: string) {
329 return loadHelper(name).minVersion;
330 }
331
332 export function getDependencies(name: string): ReadonlyArray<string> {
333 return loadHelper(name).getDependencies();
334 }
335
336 export function ensure(name: string, newFileClass: typeof File) {
337 // We inject the File class here rather than importing it to avoid
338 // circular dependencies between @babel/core and @babel/helpers.
339 FileClass ||= newFileClass;
340
341 loadHelper(name);
342 }
343
344 export const list = Object.keys(helpers).map(name => name.replace(/^_/, ""));
345
346 export default get;