Skip to content

Commit f8b8003

Browse files
committed
fix: improve error handling for code parsing in createFakeJsPlugin
1 parent 4b2867f commit f8b8003

File tree

1 file changed

+26
-11
lines changed

1 file changed

+26
-11
lines changed

src/fake-js.ts

Lines changed: 26 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { generate } from '@babel/generator'
22
import { isIdentifierName } from '@babel/helper-validator-identifier'
3-
import { parse } from '@babel/parser'
3+
import { parse, type ParseResult } from '@babel/parser'
44
import * as t from '@babel/types'
55
import {
66
isDeclarationType,
@@ -142,12 +142,21 @@ export function createFakeJsPlugin({
142142
code: string,
143143
id: string,
144144
): TransformResult {
145-
const file = parse(code, {
146-
plugins: [['typescript', { dts: true }], 'decoratorAutoAccessors'],
147-
sourceType: 'module',
148-
errorRecovery: true,
149-
createParenthesizedExpressions: true,
150-
})
145+
let file: ParseResult
146+
try {
147+
file = parse(code, {
148+
plugins: [['typescript', { dts: true }], 'decoratorAutoAccessors'],
149+
sourceType: 'module',
150+
errorRecovery: true,
151+
createParenthesizedExpressions: true,
152+
})
153+
} catch (error) {
154+
throw new Error(
155+
`Failed to parse ${id}. This may be caused by a syntax error in the declaration file or a bug in the plugin. Please report this issue to https://github.com/sxzz/rolldown-plugin-dts\n${error}`,
156+
{ cause: error },
157+
)
158+
}
159+
151160
const { program, comments } = file
152161
const typeOnlyIds: string[] = []
153162
const identifierMap: Record<string, number> = Object.create(null)
@@ -369,11 +378,17 @@ export function createFakeJsPlugin({
369378
if (ids) typeOnlyIds.push(...ids)
370379
}
371380

372-
const file = parse(code, {
373-
sourceType: 'module',
374-
})
375-
const { program } = file
381+
let file: ParseResult
382+
try {
383+
file = parse(code, { sourceType: 'module' })
384+
} catch (error) {
385+
throw new Error(
386+
`Failed to parse generated code for chunk ${chunk.fileName}. This may be caused by a bug in the plugin. Please report this issue to https://github.com/sxzz/rolldown-plugin-dts\n${error}`,
387+
{ cause: error },
388+
)
389+
}
376390

391+
const { program } = file
377392
program.body = patchTsNamespace(program.body)
378393
program.body = patchReExport(program.body)
379394

0 commit comments

Comments
 (0)