Skip to content

Commit 11fe1e4

Browse files
authored
fix(bundled-dev): map forwarded error stacks through the bundle source maps (#23741)
1 parent c2c9ef4 commit 11fe1e4

2 files changed

Lines changed: 101 additions & 13 deletions

File tree

‎packages/vite/src/node/plugins/forwardConsole.ts‎

Lines changed: 92 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
11
import fs from 'node:fs'
22
import path from 'node:path'
33
import { parseErrorStacktrace } from '@vitest/utils/source-map'
4+
import convertSourceMap from 'convert-source-map'
45
import c from 'picocolors'
56
import type { ForwardConsolePayload } from '#types/customEvent'
67
import type { DevEnvironment, Plugin } from '..'
78
import { normalizePath } from '..'
9+
import { cleanUrl } from '../../shared/utils'
10+
import type { MemoryFiles } from '../server/bundledDev'
811
import { extractSourcemapFromFile } from '../server/sourcemap'
912
import { generateCodeFrame } from '../utils'
1013

@@ -19,12 +22,18 @@ export function forwardConsolePlugin(pluginOpts: {
1922
configureServer(server) {
2023
for (const name of pluginOpts.environments) {
2124
const environment = server.environments[name]
25+
const bundledDevOutDir = getBundledDevOutDir(environment)
2226
environment.hot.on('vite:forward-console', (payload) => {
2327
if (
2428
payload.type === 'error' ||
2529
payload.type === 'unhandled-rejection'
2630
) {
27-
const output = formatError(payload, environment, sourceMapCache)
31+
const output = formatError(
32+
payload,
33+
environment,
34+
sourceMapCache,
35+
bundledDevOutDir,
36+
)
2837
environment.config.logger.error(output, {
2938
timestamp: true,
3039
})
@@ -58,10 +67,22 @@ function formatError(
5867
>,
5968
environment: DevEnvironment,
6069
sourceMapCache: Map<string, any>,
70+
bundledDevOutDir: string,
6171
) {
6272
const error = payload.data
73+
const memoryFiles = environment.bundledDev?.memoryFiles
6374
const stacks = parseErrorStacktrace(error, {
6475
getUrlId(id) {
76+
if (memoryFiles) {
77+
return (
78+
getBundledDevChunkPath(
79+
environment,
80+
memoryFiles,
81+
bundledDevOutDir,
82+
id,
83+
) ?? id
84+
)
85+
}
6586
const moduleGraph = environment.moduleGraph
6687
const mod = moduleGraph.getModuleById(id)
6788
if (mod) {
@@ -83,6 +104,9 @@ function formatError(
83104
return id
84105
},
85106
getSourceMap(id) {
107+
if (memoryFiles) {
108+
return getBundledDevSourceMap(memoryFiles, bundledDevOutDir, id)
109+
}
86110
if (sourceMapCache.has(id)) {
87111
return sourceMapCache.get(id)
88112
}
@@ -114,6 +138,14 @@ function formatError(
114138
})
115139

116140
const nearest = stacks.find((stack) => {
141+
if (memoryFiles) {
142+
return (
143+
!environment.config.dev.sourcemapIgnoreList(
144+
stack.file,
145+
`${stack.file}.map`,
146+
) && fs.existsSync(stack.file)
147+
)
148+
}
117149
const modules = environment.moduleGraph.getModulesByFile(stack.file)
118150
return (
119151
[...(modules || [])].some((m) => m.transformResult) &&
@@ -142,3 +174,62 @@ function formatError(
142174
}
143175
return output
144176
}
177+
178+
// Under bundled dev, the client module graph is empty and the browser runs
179+
// bundle chunks served from `memoryFiles`. Their source maps list the sources
180+
// relative to the output dir, so chunk URLs are turned into paths inside it.
181+
function getBundledDevOutDir(environment: DevEnvironment): string {
182+
return normalizePath(
183+
path.resolve(environment.config.root, environment.config.build.outDir),
184+
)
185+
}
186+
187+
function getBundledDevChunkPath(
188+
environment: DevEnvironment,
189+
memoryFiles: MemoryFiles,
190+
outDir: string,
191+
url: string,
192+
): string | undefined {
193+
const { decodedBase } = environment.config
194+
url = cleanUrl(url)
195+
if (!url.startsWith(decodedBase)) return
196+
const fileName = url.slice(decodedBase.length)
197+
if (memoryFiles.has(fileName)) {
198+
return `${outDir}/${fileName}`
199+
}
200+
}
201+
202+
function getBundledDevSourceMap(
203+
memoryFiles: MemoryFiles,
204+
outDir: string,
205+
chunkPath: string,
206+
) {
207+
if (!chunkPath.startsWith(`${outDir}/`)) return null
208+
const chunkFileName = chunkPath.slice(outDir.length + 1)
209+
const readFile = (fileName: string) => {
210+
const source = memoryFiles.get(fileName)?.source
211+
return typeof source === 'string'
212+
? source
213+
: source && Buffer.from(source).toString('utf-8')
214+
}
215+
const code = readFile(chunkFileName)
216+
if (code === undefined) return null
217+
try {
218+
const converter =
219+
convertSourceMap.fromSource(code) ||
220+
convertSourceMap.fromMapFileSource(code, (mapFileName: string) => {
221+
const mapFilePath = path.posix.join(
222+
path.posix.dirname(chunkFileName),
223+
mapFileName,
224+
)
225+
const map = readFile(mapFilePath)
226+
if (map === undefined) {
227+
throw new Error(`${mapFilePath} is not in memoryFiles`)
228+
}
229+
return map
230+
})
231+
return converter?.toObject() ?? null
232+
} catch {
233+
return null
234+
}
235+
}

‎playground/forward-console/__test__/forward-console.spec.ts‎

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { stripVTControlCharacters } from 'node:util'
22
import { expect, test } from 'vitest'
3-
import { isBundledDev, isServe, page, serverLogs } from '~utils'
3+
import { isServe, page, serverLogs } from '~utils'
44

55
function normalizeLogs(logs: string[]) {
66
return (
@@ -17,7 +17,7 @@ function normalizeLogs(logs: string[]) {
1717
)
1818
}
1919

20-
test.runIf(isServe && !isBundledDev)('unhandled error', async () => {
20+
test.runIf(isServe)('unhandled error', async () => {
2121
await page.click('#test-error')
2222
await expect.poll(() => normalizeLogs(serverLogs)).toContain(`\
2323
[Unhandled error] Error: this is test error
@@ -32,7 +32,7 @@ test.runIf(isServe && !isBundledDev)('unhandled error', async () => {
3232
`)
3333
})
3434

35-
test.runIf(isServe && !isBundledDev)('unhandled rejection', async () => {
35+
test.runIf(isServe)('unhandled rejection', async () => {
3636
const logIndex = serverLogs.length
3737
await page.click('#test-unhandledrejection')
3838
await expect.poll(() => normalizeLogs(serverLogs.slice(logIndex)))
@@ -59,13 +59,11 @@ test.runIf(isServe)('console.error', async () => {
5959
)
6060
})
6161

62-
test.runIf(isServe && !isBundledDev)(
63-
'dependency stack uses source map path',
64-
async () => {
65-
const logIndex = serverLogs.length
66-
await page.click('#test-dep-error')
67-
await expect.poll(() => normalizeLogs(serverLogs.slice(logIndex)))
68-
.toContain(`\
62+
test.runIf(isServe)('dependency stack uses source map path', async () => {
63+
const logIndex = serverLogs.length
64+
await page.click('#test-dep-error')
65+
await expect.poll(() => normalizeLogs(serverLogs.slice(logIndex)))
66+
.toContain(`\
6967
[Unhandled error] Error: this is test dependency error
7068
> throwDepError ../../node_modules/.pnpm/<normalized>/node_modules/@vitejs/test-forward-console-throw-dep/index.js:2:8
7169
> testDepError src/main.ts:38:2
@@ -77,5 +75,4 @@ test.runIf(isServe && !isBundledDev)(
7775
40 |
7876
> HTMLButtonElement.<anonymous> src/main.ts:22:2
7977
`)
80-
},
81-
)
78+
})

0 commit comments

Comments
 (0)