Debian Codegraph @

packages/babel-helper-module-transforms/src/normalize-and-load-metadata.ts

raw
1 import { basename, extname } from "path";
2 import type * as t from "@babel/types";
3
4 import { isIdentifierName } from "@babel/helper-validator-identifier";
5 import splitExportDeclaration from "@babel/helper-split-export-declaration";
6 import type { NodePath } from "@babel/traverse";
7
8 export interface ModuleMetadata {
9 exportName: string;
10 // The name of the variable that will reference an object containing export names.
11 exportNameListName: null | string;
12 hasExports: boolean;
13 // Lookup from local binding to export information.
14 local: Map<string, LocalExportMetadata>;
15 // Lookup of source file to source file metadata.
16 source: Map<string, SourceModuleMetadata>;
17 // List of names that should only be printed as string literals.
18 // i.e. `import { "any unicode" as foo } from "some-module"`
19 // `stringSpecifiers` is Set(1) ["any unicode"]
20 // In most cases `stringSpecifiers` is an empty Set
21 stringSpecifiers: Set<string>;
22 }
23
24 export type InteropType =
25 | "default" // Babel interop for default-only imports
26 | "namespace" // Babel interop for namespace or default+named imports
27 | "node-default" // Node.js interop for default-only imports
28 | "node-namespace" // Node.js interop for namespace or default+named imports
29 | "none"; // No interop, or named-only imports
30
31 export type ImportInterop =
32 | "none"
33 | "babel"
34 | "node"
35 | ((source: string, filename?: string) => "none" | "babel" | "node");
36
37 export type Lazy = boolean | string[] | ((source: string) => boolean);
38
39 export interface SourceModuleMetadata {
40 // A unique variable name to use for this namespace object. Centralized for simplicity.
41 name: string;
42 loc: t.SourceLocation | undefined | null;
43 interop: InteropType;
44 // Local binding to reference from this source namespace. Key: Local name, value: Import name
45 imports: Map<string, string>;
46 // Local names that reference namespace object.
47 importsNamespace: Set<string>;
48 // Reexports to create for namespace. Key: Export name, value: Import name
49 reexports: Map<string, string>;
50 // List of names to re-export namespace as.
51 reexportNamespace: Set<string>;
52 // Tracks if the source should be re-exported.
53 reexportAll: null | {
54 loc: t.SourceLocation | undefined | null;
55 };
56 lazy?: Lazy;
57 }
58
59 export interface LocalExportMetadata {
60 names: Array<string>; // names of exports,
61 kind: "import" | "hoisted" | "block" | "var";
62 }
63
64 /**
65 * Check if the module has any exports that need handling.
66 */
67 export function hasExports(metadata: ModuleMetadata) {
68 return metadata.hasExports;
69 }
70
71 /**
72 * Check if a given source is an anonymous import, e.g. "import 'foo';"
73 */
74 export function isSideEffectImport(source: SourceModuleMetadata) {
75 return (
76 source.imports.size === 0 &&
77 source.importsNamespace.size === 0 &&
78 source.reexports.size === 0 &&
79 source.reexportNamespace.size === 0 &&
80 !source.reexportAll
81 );
82 }
83
84 export function validateImportInteropOption(
85 importInterop: any,
86 ): importInterop is ImportInterop {
87 if (
88 typeof importInterop !== "function" &&
89 importInterop !== "none" &&
90 importInterop !== "babel" &&
91 importInterop !== "node"
92 ) {
93 throw new Error(
94 `.importInterop must be one of "none", "babel", "node", or a function returning one of those values (received ${importInterop}).`,
95 );
96 }
97 return importInterop;
98 }
99
100 function resolveImportInterop(
101 importInterop: ImportInterop,
102 source: string,
103 filename: string | undefined,
104 ) {
105 if (typeof importInterop === "function") {
106 return validateImportInteropOption(importInterop(source, filename));
107 }
108 return importInterop;
109 }
110
111 /**
112 * Remove all imports and exports from the file, and return all metadata
113 * needed to reconstruct the module's behavior.
114 */
115 export default function normalizeModuleAndLoadMetadata(
116 programPath: NodePath<t.Program>,
117 exportName: string,
118 {
119 importInterop,
120 initializeReexports = false,
121 lazy = false,
122 esNamespaceOnly = false,
123 filename,
124 }: {
125 importInterop: ImportInterop;
126 initializeReexports: boolean | void;
127 lazy: Lazy;
128 esNamespaceOnly: boolean;
129 filename: string;
130 },
131 ): ModuleMetadata {
132 if (!exportName) {
133 exportName = programPath.scope.generateUidIdentifier("exports").name;
134 }
135 const stringSpecifiers = new Set<string>();
136
137 nameAnonymousExports(programPath);
138
139 const { local, source, hasExports } = getModuleMetadata(
140 programPath,
141 { initializeReexports, lazy },
142 stringSpecifiers,
143 );
144
145 removeImportExportDeclarations(programPath);
146
147 // Reuse the imported namespace name if there is one.
148 for (const [, metadata] of source) {
149 if (metadata.importsNamespace.size > 0) {
150 // This is kind of gross. If we stop using `loose: true` we should
151 // just make this destructuring assignment.
152 metadata.name = metadata.importsNamespace.values().next().value;
153 }
154
155 const resolvedInterop = resolveImportInterop(
156 importInterop,
157 metadata.source,
158 filename,
159 );
160
161 if (resolvedInterop === "none") {
162 metadata.interop = "none";
163 } else if (resolvedInterop === "node" && metadata.interop === "namespace") {
164 metadata.interop = "node-namespace";
165 } else if (resolvedInterop === "node" && metadata.interop === "default") {
166 metadata.interop = "node-default";
167 } else if (esNamespaceOnly && metadata.interop === "namespace") {
168 // Both the default and namespace interops pass through __esModule
169 // objects, but the namespace interop is used to enable Babel's
170 // destructuring-like interop behavior for normal CommonJS.
171 // Since some tooling has started to remove that behavior, we expose
172 // it as the `esNamespace` option.
173 metadata.interop = "default";
174 }
175 }
176
177 return {
178 exportName,
179 exportNameListName: null,
180 hasExports,
181 local,
182 source,
183 stringSpecifiers,
184 };
185 }
186
187 function getExportSpecifierName(
188 path: NodePath,
189 stringSpecifiers: Set<string>,
190 ): string {
191 if (path.isIdentifier()) {
192 return path.node.name;
193 } else if (path.isStringLiteral()) {
194 const stringValue = path.node.value;
195 // add specifier value to `stringSpecifiers` only when it can not be converted to an identifier name
196 // i.e In `import { "foo" as bar }`
197 // we do not consider `"foo"` to be a `stringSpecifier` because we can treat it as
198 // `import { foo as bar }`
199 // This helps minimize the size of `stringSpecifiers` and reduce overhead of checking valid identifier names
200 // when building transpiled code from metadata
201 if (!isIdentifierName(stringValue)) {
202 stringSpecifiers.add(stringValue);
203 }
204 return stringValue;
205 } else {
206 throw new Error(
207 `Expected export specifier to be either Identifier or StringLiteral, got ${path.node.type}`,
208 );
209 }
210 }
211
212 function assertExportSpecifier(
213 path: NodePath,
214 ): asserts path is NodePath<t.ExportSpecifier> {
215 if (path.isExportSpecifier()) {
216 return;
217 } else if (path.isExportNamespaceSpecifier()) {
218 throw path.buildCodeFrameError(
219 "Export namespace should be first transformed by `@babel/plugin-proposal-export-namespace-from`.",
220 );
221 } else {
222 throw path.buildCodeFrameError("Unexpected export specifier type");
223 }
224 }
225
226 /**
227 * Get metadata about the imports and exports present in this module.
228 */
229 function getModuleMetadata(
230 programPath: NodePath<t.Program>,
231 {
232 lazy,
233 initializeReexports,
234 }: {
235 // todo(flow-ts) changed from boolean, to match expected usage inside the function
236 lazy: boolean | string[] | ((source: string) => boolean);
237 initializeReexports: boolean | void;
238 },
239 stringSpecifiers: Set<string>,
240 ) {
241 const localData = getLocalExportMetadata(
242 programPath,
243 initializeReexports,
244 stringSpecifiers,
245 );
246
247 const sourceData = new Map();
248 const getData = (sourceNode: t.StringLiteral) => {
249 const source = sourceNode.value;
250
251 let data = sourceData.get(source);
252 if (!data) {
253 data = {
254 name: programPath.scope.generateUidIdentifier(
255 basename(source, extname(source)),
256 ).name,
257
258 interop: "none",
259
260 loc: null,
261
262 // Data about the requested sources and names.
263 imports: new Map(),
264 importsNamespace: new Set(),
265
266 // Metadata about data that is passed directly from source to export.
267 reexports: new Map(),
268 reexportNamespace: new Set(),
269 reexportAll: null,
270
271 lazy: false,
272
273 source,
274 };
275 sourceData.set(source, data);
276 }
277 return data;
278 };
279 let hasExports = false;
280 programPath.get("body").forEach(child => {
281 if (child.isImportDeclaration()) {
282 const data = getData(child.node.source);
283 if (!data.loc) data.loc = child.node.loc;
284
285 child.get("specifiers").forEach(spec => {
286 if (spec.isImportDefaultSpecifier()) {
287 const localName = spec.get("local").node.name;
288
289 data.imports.set(localName, "default");
290
291 const reexport = localData.get(localName);
292 if (reexport) {
293 localData.delete(localName);
294
295 reexport.names.forEach(name => {
296 data.reexports.set(name, "default");
297 });
298 }
299 } else if (spec.isImportNamespaceSpecifier()) {
300 const localName = spec.get("local").node.name;
301
302 data.importsNamespace.add(localName);
303 const reexport = localData.get(localName);
304 if (reexport) {
305 localData.delete(localName);
306
307 reexport.names.forEach(name => {
308 data.reexportNamespace.add(name);
309 });
310 }
311 } else if (spec.isImportSpecifier()) {
312 const importName = getExportSpecifierName(
313 spec.get("imported"),
314 stringSpecifiers,
315 );
316 const localName = spec.get("local").node.name;
317
318 data.imports.set(localName, importName);
319
320 const reexport = localData.get(localName);
321 if (reexport) {
322 localData.delete(localName);
323
324 reexport.names.forEach(name => {
325 data.reexports.set(name, importName);
326 });
327 }
328 }
329 });
330 } else if (child.isExportAllDeclaration()) {
331 hasExports = true;
332 const data = getData(child.node.source);
333 if (!data.loc) data.loc = child.node.loc;
334
335 data.reexportAll = {
336 loc: child.node.loc,
337 };
338 } else if (child.isExportNamedDeclaration() && child.node.source) {
339 hasExports = true;
340 const data = getData(child.node.source);
341 if (!data.loc) data.loc = child.node.loc;
342
343 child.get("specifiers").forEach(spec => {
344 assertExportSpecifier(spec);
345 const importName = getExportSpecifierName(
346 spec.get("local"),
347 stringSpecifiers,
348 );
349 const exportName = getExportSpecifierName(
350 spec.get("exported"),
351 stringSpecifiers,
352 );
353
354 data.reexports.set(exportName, importName);
355
356 if (exportName === "__esModule") {
357 throw spec
358 .get("exported")
359 .buildCodeFrameError('Illegal export "__esModule".');
360 }
361 });
362 } else if (
363 child.isExportNamedDeclaration() ||
364 child.isExportDefaultDeclaration()
365 ) {
366 hasExports = true;
367 }
368 });
369
370 for (const metadata of sourceData.values()) {
371 let needsDefault = false;
372 let needsNamed = false;
373
374 if (metadata.importsNamespace.size > 0) {
375 needsDefault = true;
376 needsNamed = true;
377 }
378
379 if (metadata.reexportAll) {
380 needsNamed = true;
381 }
382
383 for (const importName of metadata.imports.values()) {
384 if (importName === "default") needsDefault = true;
385 else needsNamed = true;
386 }
387 for (const importName of metadata.reexports.values()) {
388 if (importName === "default") needsDefault = true;
389 else needsNamed = true;
390 }
391
392 if (needsDefault && needsNamed) {
393 // TODO(logan): Using the namespace interop here is unfortunate. Revisit.
394 metadata.interop = "namespace";
395 } else if (needsDefault) {
396 metadata.interop = "default";
397 }
398 }
399
400 for (const [source, metadata] of sourceData) {
401 if (
402 lazy !== false &&
403 !(isSideEffectImport(metadata) || metadata.reexportAll)
404 ) {
405 if (lazy === true) {
406 // 'true' means that local relative files are eagerly loaded and
407 // dependency modules are loaded lazily.
408 metadata.lazy = !/\./.test(source);
409 } else if (Array.isArray(lazy)) {
410 metadata.lazy = lazy.indexOf(source) !== -1;
411 } else if (typeof lazy === "function") {
412 metadata.lazy = lazy(source);
413 } else {
414 throw new Error(`.lazy must be a boolean, string array, or function`);
415 }
416 }
417 }
418
419 return {
420 hasExports,
421 local: localData,
422 source: sourceData,
423 };
424 }
425
426 type ModuleBindingKind = "import" | "hoisted" | "block" | "var";
427 /**
428 * Get metadata about local variables that are exported.
429 */
430 function getLocalExportMetadata(
431 programPath: NodePath<t.Program>,
432 initializeReexports: boolean | void,
433 stringSpecifiers: Set<string>,
434 ): Map<string, LocalExportMetadata> {
435 const bindingKindLookup = new Map();
436
437 programPath.get("body").forEach((child: NodePath) => {
438 let kind: ModuleBindingKind;
439 if (child.isImportDeclaration()) {
440 kind = "import";
441 } else {
442 if (child.isExportDefaultDeclaration()) {
443 child = child.get("declaration");
444 }
445 if (child.isExportNamedDeclaration()) {
446 if (child.node.declaration) {
447 child = child.get("declaration");
448 } else if (
449 initializeReexports &&
450 child.node.source &&
451 child.get("source").isStringLiteral()
452 ) {
453 child.get("specifiers").forEach(spec => {
454 assertExportSpecifier(spec);
455 bindingKindLookup.set(spec.get("local").node.name, "block");
456 });
457 return;
458 }
459 }
460
461 if (child.isFunctionDeclaration()) {
462 kind = "hoisted";
463 } else if (child.isClassDeclaration()) {
464 kind = "block";
465 } else if (child.isVariableDeclaration({ kind: "var" })) {
466 kind = "var";
467 } else if (child.isVariableDeclaration()) {
468 kind = "block";
469 } else {
470 return;
471 }
472 }
473
474 Object.keys(child.getOuterBindingIdentifiers()).forEach(name => {
475 bindingKindLookup.set(name, kind);
476 });
477 });
478
479 const localMetadata = new Map();
480 const getLocalMetadata = (idPath: NodePath<t.Identifier>) => {
481 const localName = idPath.node.name;
482 let metadata = localMetadata.get(localName);
483
484 if (!metadata) {
485 const kind = bindingKindLookup.get(localName);
486
487 if (kind === undefined) {
488 throw idPath.buildCodeFrameError(
489 `Exporting local "${localName}", which is not declared.`,
490 );
491 }
492
493 metadata = {
494 names: [],
495 kind,
496 };
497 localMetadata.set(localName, metadata);
498 }
499 return metadata;
500 };
501
502 programPath.get("body").forEach(child => {
503 if (
504 child.isExportNamedDeclaration() &&
505 (initializeReexports || !child.node.source)
506 ) {
507 if (child.node.declaration) {
508 const declaration = child.get("declaration");
509 const ids = declaration.getOuterBindingIdentifierPaths();
510 Object.keys(ids).forEach(name => {
511 if (name === "__esModule") {
512 throw declaration.buildCodeFrameError(
513 'Illegal export "__esModule".',
514 );
515 }
516 getLocalMetadata(ids[name]).names.push(name);
517 });
518 } else {
519 child.get("specifiers").forEach(spec => {
520 const local = spec.get("local");
521 const exported = spec.get("exported");
522 const localMetadata = getLocalMetadata(local);
523 const exportName = getExportSpecifierName(exported, stringSpecifiers);
524
525 if (exportName === "__esModule") {
526 throw exported.buildCodeFrameError('Illegal export "__esModule".');
527 }
528 localMetadata.names.push(exportName);
529 });
530 }
531 } else if (child.isExportDefaultDeclaration()) {
532 const declaration = child.get("declaration");
533 if (
534 declaration.isFunctionDeclaration() ||
535 declaration.isClassDeclaration()
536 ) {
537 // @ts-expect-error todo(flow->ts): improve babel-types
538 getLocalMetadata(declaration.get("id")).names.push("default");
539 } else {
540 // These should have been removed by the nameAnonymousExports() call.
541 throw declaration.buildCodeFrameError(
542 "Unexpected default expression export.",
543 );
544 }
545 }
546 });
547 return localMetadata;
548 }
549
550 /**
551 * Ensure that all exported values have local binding names.
552 */
553 function nameAnonymousExports(programPath: NodePath<t.Program>) {
554 // Name anonymous exported locals.
555 programPath.get("body").forEach(child => {
556 if (!child.isExportDefaultDeclaration()) return;
557 splitExportDeclaration(child);
558 });
559 }
560
561 function removeImportExportDeclarations(programPath: NodePath<t.Program>) {
562 programPath.get("body").forEach(child => {
563 if (child.isImportDeclaration()) {
564 child.remove();
565 } else if (child.isExportNamedDeclaration()) {
566 if (child.node.declaration) {
567 // @ts-expect-error todo(flow->ts): avoid mutations
568 child.node.declaration._blockHoist = child.node._blockHoist;
569 child.replaceWith(child.node.declaration);
570 } else {
571 child.remove();
572 }
573 } else if (child.isExportDefaultDeclaration()) {
574 // export default foo;
575 const declaration = child.get("declaration");
576 if (
577 declaration.isFunctionDeclaration() ||
578 declaration.isClassDeclaration()
579 ) {
580 // @ts-expect-error todo(flow->ts): avoid mutations
581 declaration._blockHoist = child.node._blockHoist;
582 child.replaceWith(
583 declaration as NodePath<t.FunctionDeclaration | t.ClassDeclaration>,
584 );
585 } else {
586 // These should have been removed by the nameAnonymousExports() call.
587 throw declaration.buildCodeFrameError(
588 "Unexpected default expression export.",
589 );
590 }
591 } else if (child.isExportAllDeclaration()) {
592 child.remove();
593 }
594 });
595 }