Open History to see the last commit
1import { parse } from '@babel/parser'
2import _generate from '@babel/generator'
3import * as t from '@babel/types'
4import {
5 deadCodeElimination as _deadCodeElimination,
6 findReferencedIdentifiers,
7} from 'babel-dead-code-elimination'
8import type { GeneratorOptions, GeneratorResult } from '@babel/generator'
9import type { ParseResult, ParserOptions } from '@babel/parser'
10import type * as _babel_types from '@babel/types'
11β
12export type ParseAstOptions = ParserOptions & {
13 code: string
14 filename?: string
15}
16β
17export type ParseAstResult = ParseResult<_babel_types.File>
18export function parseAst({
19 code,
20 filename,
21 sourceFilename,
22 plugins,
23 ...opts
24}: ParseAstOptions): ParseAstResult {
25 const inferredFilename = filename ?? sourceFilename
26 return parse(code, {
27 plugins: plugins ?? getDefaultParserPluginsForFilename(inferredFilename),
28 sourceType: 'module',
29 sourceFilename,
30 ...opts,
31 })
32}
33β
34function getDefaultParserPluginsForFilename(
35 filename: string | undefined,
36): NonNullable<ParserOptions['plugins']> {
37 const plugins: NonNullable<ParserOptions['plugins']> = [
38 'typescript',
39 'explicitResourceManagement',
40 'importAttributes',
41 'deprecatedImportAssert',
42 ['decorators', { decoratorsBeforeExport: true }],
43 'decoratorAutoAccessors',
44 ]
45β
46 if (!isPlainTypeScriptFile(filename)) {
47 plugins.unshift('jsx')
48 }
49β
50 return plugins
51}
52β
53function isPlainTypeScriptFile(filename: string | undefined): boolean {
54 if (!filename) {
55 return false
56 }
57β
58 return /\.[cm]?ts(?:$|[?#])/.test(filename)
59}
60β
61let generate = _generate
62β
63if ('default' in generate) {
64 generate = generate.default as typeof generate
65}
66type GenerateFromAstOptions = GeneratorOptions &
67 Required<Pick<GeneratorOptions, 'sourceFileName' | 'filename'>>
68export function generateFromAst(
69 ast: _babel_types.Node,
70 opts?: GenerateFromAstOptions,
71): GeneratorResult {
72 return generate(
73 ast,
74 opts
75 ? { importAttributesKeyword: 'with', sourceMaps: true, ...opts }
76 : undefined,
77 )
78}
79export type { GeneratorResult } from '@babel/generator'
80β
81/**
82 * Strips TypeScript type-only exports and imports from an AST.
83 *
84 * This is necessary because babel-dead-code-elimination doesn't handle
85 * TypeScript type exports/imports. When a type export references an import
86 * that pulls in server-only code, the dead code elimination won't remove
87 * that import because it sees the type as still referencing it.
88 *
89 * This function removes:
90 * - `export type Foo = ...`
91 * - `export interface Foo { ... }`
92 * - `export type { Foo } from './module'`
93 * - `export type * from './module'`
94 * - Type specifiers in mixed exports: `export { value, type Foo }` -> `export { value }`
95 * - `import type { Foo } from './module'`
96 * - Type specifiers in mixed imports: `import { value, type Foo } from './module'` -> `import { value }`
97 *
98 * Note: Non-exported type/interface declarations are preserved as they may be
99 * used as type annotations within the code.
100 *
101 * @param ast - The Babel AST (or ParseResult) to mutate
102 */
103export function stripTypeExports(ast: ParseResult<_babel_types.File>): void {
104 // Filter the program body to remove type-only nodes
105 ast.program.body = ast.program.body.filter((node) => {
106 // Handle export declarations
107 if (t.isExportNamedDeclaration(node)) {
108 // Remove entire export if it's a type-only export
109 // e.g., `export type Foo = string`, `export interface Bar {}`, `export type { X } from './y'`
110 if (node.exportKind === 'type') {
111 return false
112 }
113β
114 // For value exports with mixed specifiers, filter out type-only specifiers
115 // e.g., `export { value, type TypeOnly }` -> `export { value }`
116 if (node.specifiers.length > 0) {
117 node.specifiers = node.specifiers.filter((specifier) => {
118 if (t.isExportSpecifier(specifier)) {
119 return specifier.exportKind !== 'type'
120 }
121 return true
122 })
123β
124 // If all specifiers were removed, remove the entire export declaration
125 // (unless it has a declaration like `export const x = 1`)
126 if (node.specifiers.length === 0 && !node.declaration) {
127 return false
128 }
129 }
130 }
131β
132 // Handle type-only export-all declarations
133 // e.g., `export type * from './module'`
134 if (t.isExportAllDeclaration(node)) {
135 if (node.exportKind === 'type') {
136 return false
137 }
138 }
139β
140 // Handle import declarations
141 if (t.isImportDeclaration(node)) {
142 // Remove entire import if it's a type-only import
143 // e.g., `import type { Foo } from './module'`
144 if (node.importKind === 'type') {
145 return false
146 }
147β
148 // For value imports with mixed specifiers, filter out type-only specifiers
149 // e.g., `import { value, type TypeOnly } from './module'` -> `import { value }`
150 if (node.specifiers.length > 0) {
151 node.specifiers = node.specifiers.filter((specifier) => {
152 if (t.isImportSpecifier(specifier)) {
153 return specifier.importKind !== 'type'
154 }
155 return true
156 })
157β
158 // If all specifiers were removed, remove the entire import declaration
159 if (node.specifiers.length === 0) {
160 return false
161 }
162 }
163 }
164β
165 return true
166 })
167}
168β
169// Re-export findReferencedIdentifiers from babel-dead-code-elimination
170export { findReferencedIdentifiers }
171β
172/**
173 * Performs dead code elimination on the AST, with TypeScript type stripping.
174 *
175 * This is a wrapper around babel-dead-code-elimination that first strips
176 * TypeScript type-only exports and imports. This is necessary because
177 * babel-dead-code-elimination doesn't handle type exports, which can cause
178 * imports to be retained when they're only referenced by type exports.
179 *
180 * @param ast - The Babel AST to mutate
181 * @param candidates - Optional set of identifier paths to consider for removal.
182 * If provided, only these identifiers will be candidates for removal.
183 * This should be the result of `findReferencedIdentifiers(ast)` called
184 * before any AST transformations.
185 */
186export function deadCodeElimination(
187 ast: ParseResult<_babel_types.File>,
188 candidates?: ReturnType<typeof findReferencedIdentifiers>,
189): void {
190 // First strip TypeScript type-only exports and imports
191 stripTypeExports(ast)
192β
193 // Then run the original dead code elimination
194 _deadCodeElimination(ast, candidates)
195}