Skip to content

Commit 1df1fd1

Browse files
authored
perf: skip computing sourceRoot in injectSourcesContent (#15207)
1 parent 4380b82 commit 1df1fd1

File tree

1 file changed

+40
-24
lines changed

1 file changed

+40
-24
lines changed

packages/vite/src/node/server/sourcemap.ts

+40-24
Original file line numberDiff line numberDiff line change
@@ -19,40 +19,56 @@ interface SourceMapLike {
1919
sourceRoot?: string
2020
}
2121

22-
export async function injectSourcesContent(
23-
map: SourceMapLike,
24-
file: string,
25-
logger: Logger,
26-
): Promise<void> {
22+
async function computeSourceRoute(map: SourceMapLike, file: string) {
2723
let sourceRoot: string | undefined
2824
try {
2925
// The source root is undefined for virtual modules and permission errors.
3026
sourceRoot = await fsp.realpath(
3127
path.resolve(path.dirname(file), map.sourceRoot || ''),
3228
)
3329
} catch {}
30+
return sourceRoot
31+
}
32+
33+
export async function injectSourcesContent(
34+
map: SourceMapLike,
35+
file: string,
36+
logger: Logger,
37+
): Promise<void> {
38+
let sourceRootPromise: Promise<string | undefined>
3439

3540
const missingSources: string[] = []
3641
const sourcesContent = map.sourcesContent || []
37-
await Promise.all(
38-
map.sources.map(async (sourcePath, index) => {
39-
let content = null
40-
if (sourcePath && !virtualSourceRE.test(sourcePath)) {
41-
sourcePath = decodeURI(sourcePath)
42-
if (sourceRoot) {
43-
sourcePath = path.resolve(sourceRoot, sourcePath)
44-
}
45-
// inject content from source file when sourcesContent is null
46-
content =
47-
sourcesContent[index] ??
48-
(await fsp.readFile(sourcePath, 'utf-8').catch(() => {
49-
missingSources.push(sourcePath)
50-
return null
51-
}))
52-
}
53-
sourcesContent[index] = content
54-
}),
55-
)
42+
const sourcesContentPromises: Promise<void>[] = []
43+
for (let index = 0; index < map.sources.length; index++) {
44+
const sourcePath = map.sources[index]
45+
if (
46+
!sourcesContent[index] &&
47+
sourcePath &&
48+
!virtualSourceRE.test(sourcePath)
49+
) {
50+
sourcesContentPromises.push(
51+
(async () => {
52+
// inject content from source file when sourcesContent is null
53+
sourceRootPromise ??= computeSourceRoute(map, file)
54+
const sourceRoot = await sourceRootPromise
55+
let resolvedSourcePath = decodeURI(sourcePath)
56+
if (sourceRoot) {
57+
resolvedSourcePath = path.resolve(sourceRoot, resolvedSourcePath)
58+
}
59+
60+
sourcesContent[index] = await fsp
61+
.readFile(resolvedSourcePath, 'utf-8')
62+
.catch(() => {
63+
missingSources.push(resolvedSourcePath)
64+
return null
65+
})
66+
})(),
67+
)
68+
}
69+
}
70+
71+
await Promise.all(sourcesContentPromises)
5672

5773
map.sourcesContent = sourcesContent
5874

0 commit comments

Comments
 (0)