Skip to content

Commit b5a5533

Browse files
authored
perf: read external source maps once per run (#12106)
1 parent f88ab6c commit b5a5533

2 files changed

Lines changed: 110 additions & 20 deletions

File tree

‎packages/vitest/src/node/test-run.ts‎

Lines changed: 34 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -33,9 +33,12 @@ import mime from 'mime/lite'
3333
import { basename, extname, resolve } from 'pathe'
3434

3535
export class TestRun {
36+
private externalSourceMaps = new Map<string, unknown>()
37+
3638
constructor(private vitest: Vitest) {}
3739

3840
async start(specifications: TestSpecification[]): Promise<void> {
41+
this.externalSourceMaps.clear()
3942
const filepaths = specifications.map((spec) => spec.moduleId)
4043
this.vitest.state.collectPaths(filepaths)
4144

@@ -108,7 +111,7 @@ export class TestRun {
108111
? project.browser?.parseStacktrace(entry.stack, { firstOnly: true }) || []
109112
: parseStacktrace(entry.stack, {
110113
firstOnly: true,
111-
getSourceMap: (file) => getExternalSourceMap(project, file),
114+
getSourceMap: (file) => this.getExternalSourceMap(project, file),
112115
})
113116
if (stack) {
114117
entry.location = { file: stack.file, line: stack.line, column: stack.column }
@@ -194,12 +197,20 @@ export class TestRun {
194197
update.forEach(([taskId, result]) => {
195198
const task = this.vitest.state.idMap.get(taskId)
196199
const isBrowser = task && task.file.pool === 'browser'
200+
// the worker sends all errors of the task again in each update
201+
const previous = task?.result
197202

198-
result?.errors?.forEach((error) => {
203+
result?.errors?.forEach((error, i) => {
199204
if (isPrimitive(error)) {
200205
return
201206
}
202207

208+
const parsed = previous?.errors?.[i]
209+
if (error.stack && parsed?.stacks && parsed.stack === error.stack) {
210+
error.stacks = parsed.stacks
211+
return
212+
}
213+
203214
const project = this.vitest.getProjectByName(task!.file.projectName || '')
204215
if (isBrowser) {
205216
error.stacks =
@@ -209,13 +220,33 @@ export class TestRun {
209220
} else {
210221
error.stacks = parseErrorStacktrace(error, {
211222
frameFilter: project.config.onStackTrace,
212-
getSourceMap: (file) => getExternalSourceMap(project, file),
223+
getSourceMap: (file) => this.getExternalSourceMap(project, file),
213224
})
214225
}
215226
})
216227
})
217228
}
218229

230+
private getExternalSourceMap(project: TestProject, file: string): unknown {
231+
// This only handles external modules since
232+
// source map is already applied for inlined modules.
233+
// Module node exists due to Vitest fetch module,
234+
// but transformResult should be empty for external modules.
235+
// TODO: this uses client module graph and thus miss detects
236+
// inlined modules in ssr environment as if external.
237+
const mod = project.vite.moduleGraph.getModuleById(file)
238+
if (mod?.transformResult) {
239+
return undefined
240+
}
241+
if (!this.externalSourceMaps.has(file)) {
242+
const map = existsSync(file)
243+
? extractSourcemapFromFile(readFileSync(file, 'utf-8'), file)?.map
244+
: undefined
245+
this.externalSourceMaps.set(file, map)
246+
}
247+
return this.externalSourceMaps.get(file)
248+
}
249+
219250
private async reportEvent(id: string, event: TaskUpdateEvent, data: TaskEventData | undefined) {
220251
const task = this.vitest.state.idMap.get(id)
221252
const entity = task && this.vitest.state.getReportedEntity(task)
@@ -343,18 +374,3 @@ export class TestRun {
343374
}
344375
}
345376
}
346-
347-
function getExternalSourceMap(project: TestProject, file: string) {
348-
// This only handles external modules since
349-
// source map is already applied for inlined modules.
350-
// Module node exists due to Vitest fetch module,
351-
// but transformResult should be empty for external modules.
352-
// TODO: this uses client module graph and thus miss detects
353-
// inlined modules in ssr environment as if external.
354-
const mod = project.vite.moduleGraph.getModuleById(file)
355-
if (!mod?.transformResult && existsSync(file)) {
356-
const code = readFileSync(file, 'utf-8')
357-
const result = extractSourcemapFromFile(code, file)
358-
return result?.map
359-
}
360-
}

‎test/e2e/test/stacktraces.test.ts‎

Lines changed: 76 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
import { resolve } from 'pathe'
1+
import { relative, resolve } from 'pathe'
22
import { glob } from 'tinyglobby'
33
import { describe, expect, it } from 'vitest'
44
import { rolldownVersion } from 'vitest/node'
5-
import { runInlineTests, runVitest } from '../../test-utils'
5+
import { runInlineTests, runVitest, ts } from '../../test-utils'
66

77
// To prevent the warning coming up in snapshots
88
process.setMaxListeners(20)
@@ -105,6 +105,80 @@ describe('stacktrace in dependency package', () => {
105105
)
106106
expect(removeNodeModules(removeLines(stderr))).toMatchSnapshot()
107107
})
108+
109+
it('uses the changed source map in the next run', async () => {
110+
const { ctx, fs, root, buildTree } = await runInlineTests(
111+
{
112+
'node_modules/dep/package.json': JSON.stringify({
113+
name: 'dep',
114+
type: 'module',
115+
exports: './index.js',
116+
}),
117+
'node_modules/dep/index.js': ts`
118+
export function parse() {
119+
throw new Error('parse failed')
120+
}
121+
export function format() {
122+
throw new Error('format failed')
123+
}
124+
//# sourceMappingURL=index.js.map
125+
`,
126+
'node_modules/dep/index.js.map': JSON.stringify({
127+
version: 3,
128+
sources: ['index.ts'],
129+
names: [],
130+
mappings: ';;AASA;;;AAUA',
131+
}),
132+
'basic.test.js': ts`
133+
import { format, parse } from 'dep'
134+
import { test } from 'vitest'
135+
136+
let tries = 0
137+
test('flaky', { retry: 1 }, () => {
138+
if (tries++ === 0) {
139+
parse()
140+
}
141+
format()
142+
})
143+
`,
144+
},
145+
{ watch: true },
146+
)
147+
const errorLocations = () =>
148+
buildTree((test) =>
149+
test.result().errors?.map((error) => {
150+
const [frame] = error.stacks || []
151+
return `${error.message} at ${relative(root, frame.file)}:${frame.line}:${frame.column}`
152+
}),
153+
)
154+
155+
expect(errorLocations()).toMatchInlineSnapshot(`
156+
{
157+
"basic.test.js": {
158+
"flaky": [
159+
"parse failed at node_modules/dep/index.ts:10:1",
160+
"format failed at node_modules/dep/index.ts:20:1",
161+
],
162+
},
163+
}
164+
`)
165+
166+
fs.editFile('node_modules/dep/index.js.map', (map) => map.replace('index.ts', 'main.ts'))
167+
await ctx!.rerunTestSpecifications(
168+
ctx!.state.getTestModules().map((testModule) => testModule.toTestSpecification()),
169+
)
170+
171+
expect(errorLocations()).toMatchInlineSnapshot(`
172+
{
173+
"basic.test.js": {
174+
"flaky": [
175+
"parse failed at node_modules/dep/main.ts:10:1",
176+
"format failed at node_modules/dep/main.ts:20:1",
177+
],
178+
},
179+
}
180+
`)
181+
})
108182
})
109183

110184
it('stacktrace in vmThreads', async () => {

0 commit comments

Comments
 (0)