Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
93 changes: 92 additions & 1 deletion packages/vite/src/node/plugins/forwardConsole.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import fs from 'node:fs'
import path from 'node:path'
import { parseErrorStacktrace } from '@vitest/utils/source-map'
import convertSourceMap from 'convert-source-map'
import c from 'picocolors'
import type { ForwardConsolePayload } from '#types/customEvent'
import type { DevEnvironment, Plugin } from '..'
import { normalizePath } from '..'
import { cleanUrl } from '../../shared/utils'
import type { MemoryFiles } from '../server/bundledDev'
import { extractSourcemapFromFile } from '../server/sourcemap'
import { generateCodeFrame } from '../utils'

Expand All @@ -19,12 +22,18 @@ export function forwardConsolePlugin(pluginOpts: {
configureServer(server) {
for (const name of pluginOpts.environments) {
const environment = server.environments[name]
const bundledDevOutDir = getBundledDevOutDir(environment)
environment.hot.on('vite:forward-console', (payload) => {
if (
payload.type === 'error' ||
payload.type === 'unhandled-rejection'
) {
const output = formatError(payload, environment, sourceMapCache)
const output = formatError(
payload,
environment,
sourceMapCache,
bundledDevOutDir,
)
environment.config.logger.error(output, {
timestamp: true,
})
Expand Down Expand Up @@ -58,10 +67,22 @@ function formatError(
>,
environment: DevEnvironment,
sourceMapCache: Map<string, any>,
bundledDevOutDir: string,
) {
const error = payload.data
const memoryFiles = environment.bundledDev?.memoryFiles
const stacks = parseErrorStacktrace(error, {
getUrlId(id) {
if (memoryFiles) {
return (
getBundledDevChunkPath(
environment,
memoryFiles,
bundledDevOutDir,
id,
) ?? id
)
}
const moduleGraph = environment.moduleGraph
const mod = moduleGraph.getModuleById(id)
if (mod) {
Expand All @@ -83,6 +104,9 @@ function formatError(
return id
},
getSourceMap(id) {
if (memoryFiles) {
return getBundledDevSourceMap(memoryFiles, bundledDevOutDir, id)
}
if (sourceMapCache.has(id)) {
return sourceMapCache.get(id)
}
Expand Down Expand Up @@ -114,6 +138,14 @@ function formatError(
})

const nearest = stacks.find((stack) => {
if (memoryFiles) {
return (
!environment.config.dev.sourcemapIgnoreList(
stack.file,
`${stack.file}.map`,
) && fs.existsSync(stack.file)
)
}
Comment on lines +141 to +148

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Where did this !isInNodeModules(stack.file) come from?

@h-a-n-a h-a-n-a Oct 14, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wrote this because I was trying to guess why we use module.transformResult as a hint to filter the modules in the stack. I thought it's a way to distinguish user code from vendor code. Then I did a deeper research just now and found out this might be a bug but happens to be working:

In plain dev, frames in node_modules never pass that check either, but only as a side effect:

  • a pre-bundled dep is mapped back to its original file, and the graph only has the .vite/deps copy so module.transformResult is not there, thus that stack is ignored.
  • a dep excluded from pre-bundling keeps the ?v= query in the frame path, so the lookup misses so that stack is ignored again.

But the result seems to be expected, based on my assumption by checking the behavior for plain dev, as we don't want user to work on vendor errors that are beyond our control so instead we use user code as the code frame.

Maybe we can use isInNodeModules here or use dev.sourcemapIgnoreList as its default is isInNodeModules as well.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see. I guess dev.sourcemapIgnoreList makes sense here.

@hi-ogawa Just in case, this is meant to find out the first user (authored) code, right?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just in case, this is meant to find out the first user (authored) code, right?

Yes, that's the idea. To be honest, I'm not sure in practice whether showing user code stack is always better than showing the actual error source in dependency (or Vitest's node testing case it's external module), but Vitest error printing behavior was like this for a long time, so the same idea is ported to forward console.

const modules = environment.moduleGraph.getModulesByFile(stack.file)
return (
[...(modules || [])].some((m) => m.transformResult) &&
Expand Down Expand Up @@ -142,3 +174,62 @@ function formatError(
}
return output
}

// Under bundled dev, the client module graph is empty and the browser runs
// bundle chunks served from `memoryFiles`. Their source maps list the sources
// relative to the output dir, so chunk URLs are turned into paths inside it.
function getBundledDevOutDir(environment: DevEnvironment): string {
return normalizePath(
path.resolve(environment.config.root, environment.config.build.outDir),
)
}

function getBundledDevChunkPath(
environment: DevEnvironment,
memoryFiles: MemoryFiles,
outDir: string,
url: string,
): string | undefined {
const { decodedBase } = environment.config
url = cleanUrl(url)
if (!url.startsWith(decodedBase)) return
const fileName = url.slice(decodedBase.length)
if (memoryFiles.has(fileName)) {
return `${outDir}/${fileName}`
}
}

function getBundledDevSourceMap(
memoryFiles: MemoryFiles,
outDir: string,
chunkPath: string,
) {
if (!chunkPath.startsWith(`${outDir}/`)) return null
const chunkFileName = chunkPath.slice(outDir.length + 1)
const readFile = (fileName: string) => {
const source = memoryFiles.get(fileName)?.source
return typeof source === 'string'
? source
: source && Buffer.from(source).toString('utf-8')
}
const code = readFile(chunkFileName)
if (code === undefined) return null
try {
const converter =
convertSourceMap.fromSource(code) ||
convertSourceMap.fromMapFileSource(code, (mapFileName: string) => {
const mapFilePath = path.posix.join(
path.posix.dirname(chunkFileName),
mapFileName,
)
const map = readFile(mapFilePath)
if (map === undefined) {
throw new Error(`${mapFilePath} is not in memoryFiles`)
}
return map
})
return converter?.toObject() ?? null
} catch {
return null
}
}
21 changes: 9 additions & 12 deletions playground/forward-console/__test__/forward-console.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { stripVTControlCharacters } from 'node:util'
import { expect, test } from 'vitest'
import { isBundledDev, isServe, page, serverLogs } from '~utils'
import { isServe, page, serverLogs } from '~utils'

function normalizeLogs(logs: string[]) {
return (
Expand All @@ -17,7 +17,7 @@ function normalizeLogs(logs: string[]) {
)
}

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

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

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