Skip to content

Commit

Permalink
perf: skip computing sourceRoot in injectSourcesContent (#15207)
Browse files Browse the repository at this point in the history
  • Loading branch information
patak-dev authored Dec 2, 2023
1 parent 4380b82 commit 1df1fd1
Showing 1 changed file with 40 additions and 24 deletions.
64 changes: 40 additions & 24 deletions packages/vite/src/node/server/sourcemap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,40 +19,56 @@ interface SourceMapLike {
sourceRoot?: string
}

export async function injectSourcesContent(
map: SourceMapLike,
file: string,
logger: Logger,
): Promise<void> {
async function computeSourceRoute(map: SourceMapLike, file: string) {
let sourceRoot: string | undefined
try {
// The source root is undefined for virtual modules and permission errors.
sourceRoot = await fsp.realpath(
path.resolve(path.dirname(file), map.sourceRoot || ''),
)
} catch {}
return sourceRoot
}

export async function injectSourcesContent(
map: SourceMapLike,
file: string,
logger: Logger,
): Promise<void> {
let sourceRootPromise: Promise<string | undefined>

const missingSources: string[] = []
const sourcesContent = map.sourcesContent || []
await Promise.all(
map.sources.map(async (sourcePath, index) => {
let content = null
if (sourcePath && !virtualSourceRE.test(sourcePath)) {
sourcePath = decodeURI(sourcePath)
if (sourceRoot) {
sourcePath = path.resolve(sourceRoot, sourcePath)
}
// inject content from source file when sourcesContent is null
content =
sourcesContent[index] ??
(await fsp.readFile(sourcePath, 'utf-8').catch(() => {
missingSources.push(sourcePath)
return null
}))
}
sourcesContent[index] = content
}),
)
const sourcesContentPromises: Promise<void>[] = []
for (let index = 0; index < map.sources.length; index++) {
const sourcePath = map.sources[index]
if (
!sourcesContent[index] &&
sourcePath &&
!virtualSourceRE.test(sourcePath)
) {
sourcesContentPromises.push(
(async () => {
// inject content from source file when sourcesContent is null
sourceRootPromise ??= computeSourceRoute(map, file)
const sourceRoot = await sourceRootPromise
let resolvedSourcePath = decodeURI(sourcePath)
if (sourceRoot) {
resolvedSourcePath = path.resolve(sourceRoot, resolvedSourcePath)
}

sourcesContent[index] = await fsp
.readFile(resolvedSourcePath, 'utf-8')
.catch(() => {
missingSources.push(resolvedSourcePath)
return null
})
})(),
)
}
}

await Promise.all(sourcesContentPromises)

map.sourcesContent = sourcesContent

Expand Down

0 comments on commit 1df1fd1

Please sign in to comment.