Debian Codegraph @

packages/babel-helper-module-transforms/src/index.ts

raw
1 import assert from "assert";
2 import {
3 booleanLiteral,
4 callExpression,
5 cloneNode,
6 directive,
7 directiveLiteral,
8 expressionStatement,
9 identifier,
10 isIdentifier,
11 memberExpression,
12 stringLiteral,
13 valueToNode,
14 variableDeclaration,
15 variableDeclarator,
16 } from "@babel/types";
17 import type * as t from "@babel/types";
18 import template from "@babel/template";
19
20 import { isModule } from "@babel/helper-module-imports";
21
22 import rewriteThis from "./rewrite-this";
23 import rewriteLiveReferences from "./rewrite-live-references";
24 import normalizeModuleAndLoadMetadata, {
25 hasExports,
26 isSideEffectImport,
27 validateImportInteropOption,
28 } from "./normalize-and-load-metadata";
29 import type {
30 ImportInterop,
31 InteropType,
32 Lazy,
33 ModuleMetadata,
34 SourceModuleMetadata,
35 } from "./normalize-and-load-metadata";
36 import type { NodePath } from "@babel/traverse";
37
38 export { buildDynamicImport, getDynamicImportSource } from "./dynamic-import";
39
40 export { default as getModuleName } from "./get-module-name";
41 export type { PluginOptions } from "./get-module-name";
42
43 export { hasExports, isSideEffectImport, isModule, rewriteThis };
44
45 export interface RewriteModuleStatementsAndPrepareHeaderOptions {
46 exportName?: string;
47 strict: boolean;
48 allowTopLevelThis?: boolean;
49 strictMode: boolean;
50 loose?: boolean;
51 importInterop?: ImportInterop;
52 noInterop?: boolean;
53 lazy?: Lazy;
54 esNamespaceOnly?: boolean;
55 filename: string | undefined;
56 constantReexports?: boolean | void;
57 enumerableModuleMeta?: boolean | void;
58 noIncompleteNsImportDetection?: boolean | void;
59 }
60
61 /**
62 * Perform all of the generic ES6 module rewriting needed to handle initial
63 * module processing. This function will rewrite the majority of the given
64 * program to reference the modules described by the returned metadata,
65 * and returns a list of statements for use when initializing the module.
66 */
67 export function rewriteModuleStatementsAndPrepareHeader(
68 path: NodePath<t.Program>,
69 {
70 // TODO(Babel 8): Remove this
71 loose,
72
73 exportName,
74 strict,
75 allowTopLevelThis,
76 strictMode,
77 noInterop,
78 importInterop = noInterop ? "none" : "babel",
79 lazy,
80 esNamespaceOnly,
81 filename,
82
83 constantReexports = loose,
84 enumerableModuleMeta = loose,
85 noIncompleteNsImportDetection,
86 }: RewriteModuleStatementsAndPrepareHeaderOptions,
87 ) {
88 validateImportInteropOption(importInterop);
89 assert(isModule(path), "Cannot process module statements in a script");
90 path.node.sourceType = "script";
91
92 const meta = normalizeModuleAndLoadMetadata(path, exportName, {
93 importInterop,
94 initializeReexports: constantReexports,
95 lazy,
96 esNamespaceOnly,
97 filename,
98 });
99
100 if (!allowTopLevelThis) {
101 rewriteThis(path);
102 }
103
104 rewriteLiveReferences(path, meta);
105
106 if (strictMode !== false) {
107 const hasStrict = path.node.directives.some(directive => {
108 return directive.value.value === "use strict";
109 });
110 if (!hasStrict) {
111 path.unshiftContainer(
112 "directives",
113 directive(directiveLiteral("use strict")),
114 );
115 }
116 }
117
118 const headers = [];
119 if (hasExports(meta) && !strict) {
120 headers.push(buildESModuleHeader(meta, enumerableModuleMeta));
121 }
122
123 const nameList = buildExportNameListDeclaration(path, meta);
124
125 if (nameList) {
126 meta.exportNameListName = nameList.name;
127 headers.push(nameList.statement);
128 }
129
130 // Create all of the statically known named exports.
131 headers.push(
132 ...buildExportInitializationStatements(
133 path,
134 meta,
135 constantReexports,
136 noIncompleteNsImportDetection,
137 ),
138 );
139
140 return { meta, headers };
141 }
142
143 /**
144 * Flag a set of statements as hoisted above all else so that module init
145 * statements all run before user code.
146 */
147 export function ensureStatementsHoisted(statements: t.Statement[]) {
148 // Force all of the header fields to be at the top of the file.
149 statements.forEach(header => {
150 // @ts-expect-error Fixme: handle _blockHoist property
151 header._blockHoist = 3;
152 });
153 }
154
155 /**
156 * Given an expression for a standard import object, like "require('foo')",
157 * wrap it in a call to the interop helpers based on the type.
158 */
159 export function wrapInterop(
160 programPath: NodePath,
161 expr: t.Expression,
162 type: InteropType,
163 ): t.CallExpression {
164 if (type === "none") {
165 return null;
166 }
167
168 if (type === "node-namespace") {
169 return callExpression(programPath.hub.addHelper("interopRequireWildcard"), [
170 expr,
171 booleanLiteral(true),
172 ]);
173 } else if (type === "node-default") {
174 return null;
175 }
176
177 let helper;
178 if (type === "default") {
179 helper = "interopRequireDefault";
180 } else if (type === "namespace") {
181 helper = "interopRequireWildcard";
182 } else {
183 throw new Error(`Unknown interop: ${type}`);
184 }
185
186 return callExpression(programPath.hub.addHelper(helper), [expr]);
187 }
188
189 /**
190 * Create the runtime initialization statements for a given requested source.
191 * These will initialize all of the runtime import/export logic that
192 * can't be handled statically by the statements created by
193 * buildExportInitializationStatements().
194 */
195 export function buildNamespaceInitStatements(
196 metadata: ModuleMetadata,
197 sourceMetadata: SourceModuleMetadata,
198 constantReexports: boolean | void = false,
199 ) {
200 const statements = [];
201
202 let srcNamespace: t.Node = identifier(sourceMetadata.name);
203 if (sourceMetadata.lazy) srcNamespace = callExpression(srcNamespace, []);
204
205 for (const localName of sourceMetadata.importsNamespace) {
206 if (localName === sourceMetadata.name) continue;
207
208 // Create and assign binding to namespace object
209 statements.push(
210 template.statement`var NAME = SOURCE;`({
211 NAME: localName,
212 SOURCE: cloneNode(srcNamespace),
213 }),
214 );
215 }
216 if (constantReexports) {
217 statements.push(...buildReexportsFromMeta(metadata, sourceMetadata, true));
218 }
219 for (const exportName of sourceMetadata.reexportNamespace) {
220 // Assign export to namespace object.
221 statements.push(
222 (sourceMetadata.lazy
223 ? template.statement`
224 Object.defineProperty(EXPORTS, "NAME", {
225 enumerable: true,
226 get: function() {
227 return NAMESPACE;
228 }
229 });
230 `
231 : template.statement`EXPORTS.NAME = NAMESPACE;`)({
232 EXPORTS: metadata.exportName,
233 NAME: exportName,
234 NAMESPACE: cloneNode(srcNamespace),
235 }),
236 );
237 }
238 if (sourceMetadata.reexportAll) {
239 const statement = buildNamespaceReexport(
240 metadata,
241 cloneNode(srcNamespace),
242 constantReexports,
243 );
244 statement.loc = sourceMetadata.reexportAll.loc;
245
246 // Iterate props creating getter for each prop.
247 statements.push(statement);
248 }
249 return statements;
250 }
251
252 const ReexportTemplate = {
253 constant: template.statement`EXPORTS.EXPORT_NAME = NAMESPACE_IMPORT;`,
254 constantComputed: template.statement`EXPORTS["EXPORT_NAME"] = NAMESPACE_IMPORT;`,
255 spec: template.statement`
256 Object.defineProperty(EXPORTS, "EXPORT_NAME", {
257 enumerable: true,
258 get: function() {
259 return NAMESPACE_IMPORT;
260 },
261 });
262 `,
263 };
264
265 function buildReexportsFromMeta(
266 meta: ModuleMetadata,
267 metadata: SourceModuleMetadata,
268 constantReexports: boolean,
269 ) {
270 const namespace = metadata.lazy
271 ? callExpression(identifier(metadata.name), [])
272 : identifier(metadata.name);
273
274 const { stringSpecifiers } = meta;
275 return Array.from(metadata.reexports, ([exportName, importName]) => {
276 let NAMESPACE_IMPORT: t.Expression = cloneNode(namespace);
277 if (importName === "default" && metadata.interop === "node-default") {
278 // Nothing, it's ok as-is
279 } else if (stringSpecifiers.has(importName)) {
280 NAMESPACE_IMPORT = memberExpression(
281 NAMESPACE_IMPORT,
282 stringLiteral(importName),
283 true,
284 );
285 } else {
286 NAMESPACE_IMPORT = memberExpression(
287 NAMESPACE_IMPORT,
288 identifier(importName),
289 );
290 }
291 const astNodes = {
292 EXPORTS: meta.exportName,
293 EXPORT_NAME: exportName,
294 NAMESPACE_IMPORT,
295 };
296 if (constantReexports || isIdentifier(NAMESPACE_IMPORT)) {
297 if (stringSpecifiers.has(exportName)) {
298 return ReexportTemplate.constantComputed(astNodes);
299 } else {
300 return ReexportTemplate.constant(astNodes);
301 }
302 } else {
303 return ReexportTemplate.spec(astNodes);
304 }
305 });
306 }
307
308 /**
309 * Build an "__esModule" header statement setting the property on a given object.
310 */
311 function buildESModuleHeader(
312 metadata: ModuleMetadata,
313 enumerableModuleMeta: boolean | void = false,
314 ) {
315 return (
316 enumerableModuleMeta
317 ? template.statement`
318 EXPORTS.__esModule = true;
319 `
320 : template.statement`
321 Object.defineProperty(EXPORTS, "__esModule", {
322 value: true,
323 });
324 `
325 )({ EXPORTS: metadata.exportName });
326 }
327
328 /**
329 * Create a re-export initialization loop for a specific imported namespace.
330 */
331 function buildNamespaceReexport(
332 metadata: ModuleMetadata,
333 namespace: t.Identifier | t.CallExpression,
334 constantReexports: boolean | void,
335 ) {
336 return (
337 constantReexports
338 ? template.statement`
339 Object.keys(NAMESPACE).forEach(function(key) {
340 if (key === "default" || key === "__esModule") return;
341 VERIFY_NAME_LIST;
342 if (key in EXPORTS && EXPORTS[key] === NAMESPACE[key]) return;
343
344 EXPORTS[key] = NAMESPACE[key];
345 });
346 `
347 : // Also skip already assigned bindings if they are strictly equal
348 // to be somewhat more spec-compliant when a file has multiple
349 // namespace re-exports that would cause a binding to be exported
350 // multiple times. However, multiple bindings of the same name that
351 // export the same primitive value are silently skipped
352 // (the spec requires an "ambigous bindings" early error here).
353 template.statement`
354 Object.keys(NAMESPACE).forEach(function(key) {
355 if (key === "default" || key === "__esModule") return;
356 VERIFY_NAME_LIST;
357 if (key in EXPORTS && EXPORTS[key] === NAMESPACE[key]) return;
358
359 Object.defineProperty(EXPORTS, key, {
360 enumerable: true,
361 get: function() {
362 return NAMESPACE[key];
363 },
364 });
365 });
366 `
367 )({
368 NAMESPACE: namespace,
369 EXPORTS: metadata.exportName,
370 VERIFY_NAME_LIST: metadata.exportNameListName
371 ? template`
372 if (Object.prototype.hasOwnProperty.call(EXPORTS_LIST, key)) return;
373 `({ EXPORTS_LIST: metadata.exportNameListName })
374 : null,
375 });
376 }
377
378 /**
379 * Build a statement declaring a variable that contains all of the exported
380 * variable names in an object so they can easily be referenced from an
381 * export * from statement to check for conflicts.
382 */
383 function buildExportNameListDeclaration(
384 programPath: NodePath,
385 metadata: ModuleMetadata,
386 ) {
387 const exportedVars = Object.create(null);
388 for (const data of metadata.local.values()) {
389 for (const name of data.names) {
390 exportedVars[name] = true;
391 }
392 }
393
394 let hasReexport = false;
395 for (const data of metadata.source.values()) {
396 for (const exportName of data.reexports.keys()) {
397 exportedVars[exportName] = true;
398 }
399 for (const exportName of data.reexportNamespace) {
400 exportedVars[exportName] = true;
401 }
402
403 hasReexport = hasReexport || !!data.reexportAll;
404 }
405
406 if (!hasReexport || Object.keys(exportedVars).length === 0) return null;
407
408 const name = programPath.scope.generateUidIdentifier("exportNames");
409
410 delete exportedVars.default;
411
412 return {
413 name: name.name,
414 statement: variableDeclaration("var", [
415 variableDeclarator(name, valueToNode(exportedVars)),
416 ]),
417 };
418 }
419
420 /**
421 * Create a set of statements that will initialize all of the statically-known
422 * export names with their expected values.
423 */
424 function buildExportInitializationStatements(
425 programPath: NodePath,
426 metadata: ModuleMetadata,
427 constantReexports: boolean | void = false,
428 noIncompleteNsImportDetection: boolean | void = false,
429 ) {
430 const initStatements: Array<[string, t.Statement | null]> = [];
431
432 for (const [localName, data] of metadata.local) {
433 if (data.kind === "import") {
434 // No-open since these are explicitly set with the "reexports" block.
435 } else if (data.kind === "hoisted") {
436 initStatements.push([
437 // data.names is always of length 1 because a hoisted export
438 // name must be id of a function declaration
439 data.names[0],
440 buildInitStatement(metadata, data.names, identifier(localName)),
441 ]);
442 } else if (!noIncompleteNsImportDetection) {
443 for (const exportName of data.names) {
444 initStatements.push([exportName, null]);
445 }
446 }
447 }
448
449 for (const data of metadata.source.values()) {
450 if (!constantReexports) {
451 const reexportsStatements = buildReexportsFromMeta(metadata, data, false);
452 const reexports = [...data.reexports.keys()];
453 for (let i = 0; i < reexportsStatements.length; i++) {
454 initStatements.push([reexports[i], reexportsStatements[i]]);
455 }
456 }
457 if (!noIncompleteNsImportDetection) {
458 for (const exportName of data.reexportNamespace) {
459 initStatements.push([exportName, null]);
460 }
461 }
462 }
463
464 // https://tc39.es/ecma262/#sec-module-namespace-exotic-objects
465 // The [Exports] list is ordered as if an Array of those String values
466 // had been sorted using %Array.prototype.sort% using undefined as comparefn
467 initStatements.sort(([a], [b]) => {
468 if (a < b) return -1;
469 if (b < a) return 1;
470 return 0;
471 });
472
473 const results = [];
474 if (noIncompleteNsImportDetection) {
475 for (const [, initStatement] of initStatements) {
476 results.push(initStatement);
477 }
478 } else {
479 // We generate init statements (`exports.a = exports.b = ... = void 0`)
480 // for every 100 exported names to avoid deeply-nested AST structures.
481 const chunkSize = 100;
482 for (let i = 0; i < initStatements.length; i += chunkSize) {
483 let uninitializedExportNames = [];
484 for (let j = 0; j < chunkSize && i + j < initStatements.length; j++) {
485 const [exportName, initStatement] = initStatements[i + j];
486 if (initStatement !== null) {
487 if (uninitializedExportNames.length > 0) {
488 results.push(
489 buildInitStatement(
490 metadata,
491 uninitializedExportNames,
492 programPath.scope.buildUndefinedNode(),
493 ),
494 );
495 // reset after uninitializedExportNames has been transformed
496 // to init statements
497 uninitializedExportNames = [];
498 }
499 results.push(initStatement);
500 } else {
501 uninitializedExportNames.push(exportName);
502 }
503 }
504 if (uninitializedExportNames.length > 0) {
505 results.push(
506 buildInitStatement(
507 metadata,
508 uninitializedExportNames,
509 programPath.scope.buildUndefinedNode(),
510 ),
511 );
512 }
513 }
514 }
515
516 return results;
517 }
518
519 /**
520 * Given a set of export names, create a set of nested assignments to
521 * initialize them all to a given expression.
522 */
523 const InitTemplate = {
524 computed: template.expression`EXPORTS["NAME"] = VALUE`,
525 default: template.expression`EXPORTS.NAME = VALUE`,
526 };
527
528 function buildInitStatement(
529 metadata: ModuleMetadata,
530 exportNames: string[],
531 initExpr: t.Expression,
532 ) {
533 const { stringSpecifiers, exportName: EXPORTS } = metadata;
534 return expressionStatement(
535 exportNames.reduce((acc, exportName) => {
536 const params = {
537 EXPORTS,
538 NAME: exportName,
539 VALUE: acc,
540 };
541 if (stringSpecifiers.has(exportName)) {
542 return InitTemplate.computed(params);
543 } else {
544 return InitTemplate.default(params);
545 }
546 }, initExpr),
547 );
548 }