Skip to content
Open
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
8 changes: 8 additions & 0 deletions docs/guide/api-environment-instances.md
Original file line number Diff line number Diff line change
Expand Up @@ -293,5 +293,13 @@ export interface ViteFetchResult {
* Invalidate module on the client side.
*/
invalidate: boolean
/**
* Source map of `code` as a JSON string. Set when the runner asked for
* `separateSourceMap` and the environment's `dev.sourcemapForDebugger` is
* disabled, in which case `code` has no inline source map.
*/
sourceMap?: string
}
```

By default the source map is inlined at the end of `code` as a `sourceMappingURL` comment. Debuggers, Node's own source map support and `NODE_V8_COVERAGE` read it from there. When the environment's `dev.sourcemapForDebugger` option is disabled, module runners that don't use the `'node'` interceptor get the map in `sourceMap` instead, so the evaluated code has no source map comment and is cheaper to compile. Stack traces are still mapped by the `'prepareStackTrace'` interceptor, which `createServerModuleRunner` uses by default in that case.
10 changes: 8 additions & 2 deletions packages/vite/src/module-runner/evaluatedModules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,8 +116,9 @@ export class EvaluatedModules {
}

/**
* Extracts the inlined source map from the module code and returns the decoded
* source map. If the source map is not inlined, it will return null.
* Returns the decoded source map of the module, either the one the server
* sent separately or the one inlined in the module code. If there is none,
* it will return null.
* @param id Resolved module ID
*/
getModuleSourceMapById(id: string): DecodedMap | null {
Expand All @@ -126,6 +127,11 @@ export class EvaluatedModules {
if (mod.map) return mod.map
if (!mod.meta || !('code' in mod.meta)) return null

if (mod.meta.sourceMap) {
mod.map = new DecodedMap(JSON.parse(mod.meta.sourceMap), mod.file)
return mod.map
}

const mapString = extractInlineSourceMap(mod.meta.code)
if (!mapString) return null
mod.map = new DecodedMap(JSON.parse(decodeBase64(mapString)), mod.file)
Expand Down
2 changes: 2 additions & 0 deletions packages/vite/src/module-runner/runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -378,6 +378,8 @@ export class ModuleRunner {
{
cached: isCached,
startOffset: this.evaluator.startOffset,
// Node's own source map support reads the inline comment
separateSourceMap: this.options.sourcemapInterceptor !== 'node',
},
])
) as ResolvedResult
Expand Down
13 changes: 13 additions & 0 deletions packages/vite/src/node/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,18 @@ export interface DevEnvironmentOptions {
* This option can also be used instead of the removed config.experimental.skipSsrTransform.
*/
moduleRunnerTransform?: boolean

/**
* Keep the source map as an inline `sourceMappingURL` comment in the code
* that module runners evaluate. Debuggers, Node's own source map support
* (`sourcemapInterceptor: 'node'`) and `NODE_V8_COVERAGE` read it from there.
* When disabled, the server sends the map separately so the evaluated code
* is cheaper to compile, and `createServerModuleRunner` maps stack traces
* with the `'prepareStackTrace'` interceptor by default. Runners using the
* `'node'` interceptor still get the inline comment.
* @default true
*/
sourcemapForDebugger?: boolean
}

function defaultCreateClientDevEnvironment(
Expand Down Expand Up @@ -990,6 +1002,7 @@ export function resolveDevEnvironmentOptions(
: defaultCreateDevEnvironment,
recoverable: consumer === 'client',
moduleRunnerTransform: consumer === 'server',
sourcemapForDebugger: true,
},
dev ?? {},
)
Expand Down
86 changes: 71 additions & 15 deletions packages/vite/src/node/ssr/fetchModule.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import path from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'
import type { SourceMap } from 'rolldown'
import type { FetchResult } from 'vite/module-runner'
import type { TransformResult } from '..'
import {
Expand All @@ -23,6 +24,7 @@ import { ssrTransform } from './ssrTransform'
export interface FetchModuleOptions {
cached?: boolean
inlineSourceMap?: boolean
separateSourceMap?: boolean
startOffset?: number
}

Expand Down Expand Up @@ -119,20 +121,32 @@ export async function fetchModule(
)
}

if (options.inlineSourceMap !== false) {
// with `sourcemapForDebugger` on, the map stays inlined: the server writes it
// into the shared transform result once instead of every runner encoding it
const separate =
options.inlineSourceMap !== false &&
!!options.separateSourceMap &&
!environment.config.dev.sourcemapForDebugger

if (options.inlineSourceMap !== false && !separate) {
result = inlineSourceMap(mod.id!, result, options.startOffset)
}

// remove shebang
if (result.code[0] === '#')
result.code = result.code.replace(/^#!.*/, (s) => ' '.repeat(s.length))

const separated = separate
? separateSourceMap(mod.id!, result, options.startOffset)
: undefined

return {
code: result.code,
code: separated?.code ?? result.code,
file: mod.file,
id: mod.id!,
url: mod.url,
invalidate: !cached,
...(separated && { sourceMap: separated.sourceMap }),
}
}

Expand Down Expand Up @@ -281,37 +295,79 @@ const OTHER_SOURCE_MAP_REGEXP = new RegExp(
'gm',
)

const INLINED_MAP_PREFIX = `${MODULE_RUNNER_SOURCEMAPPING_SOURCE}\n//# ${SOURCEMAPPING_URL}=`

function inlineSourceMap(
id: string,
result: TransformResult,
startOffset: number | undefined,
) {
const map = result.map
let code = result.code

if (
!map ||
!('version' in map) ||
code.includes(MODULE_RUNNER_SOURCEMAPPING_SOURCE)
result.code.includes(MODULE_RUNNER_SOURCEMAPPING_SOURCE)
)
return result

// to reduce the payload size, we only inline vite node source map, because it's also the only one we use
result.code = `${withSourceURL(id, result.code)}${INLINED_MAP_PREFIX}${genSourceMapUrl(offsetSourceMap(map, startOffset))}\n`

return result
}

interface SeparatedSourceMap {
startOffset: number | undefined
code: string
sourceMap: string
}

// Runners share a transform result until the module is invalidated, so the map
// is separated once per result. Unlike `inlineSourceMap`, this can't cache by
// writing to `result`, because runners that want the map inlined read it too.
const separatedSourceMaps = new WeakMap<TransformResult, SeparatedSourceMap>()

function separateSourceMap(
id: string,
result: TransformResult,
startOffset: number | undefined,
): SeparatedSourceMap | undefined {
const map = result.map
if (!map || !('version' in map)) return

const cached = separatedSourceMaps.get(result)
if (cached && cached.startOffset === startOffset) return cached

// if a runner with inline maps fetched this transform result first, the code
// already ends with the sourceURL and the trailer `inlineSourceMap` wrote
const code = result.code
const trailer = code.lastIndexOf(INLINED_MAP_PREFIX)
const isInlined =
trailer !== -1 &&
code.indexOf('\n', trailer + INLINED_MAP_PREFIX.length) === code.length - 1

const separated = {
startOffset,
code: isInlined ? code.slice(0, trailer) : withSourceURL(id, code),
sourceMap: JSON.stringify(offsetSourceMap(map, startOffset)),
}
separatedSourceMaps.set(result, separated)
return separated
}

function withSourceURL(id: string, code: string) {
// to reduce the payload size, we only keep vite node source map, because it's also the only one we use
OTHER_SOURCE_MAP_REGEXP.lastIndex = 0
if (OTHER_SOURCE_MAP_REGEXP.test(code))
code = code.replace(OTHER_SOURCE_MAP_REGEXP, '')

const sourceMap = startOffset
? {
...map,
mappings: ';'.repeat(startOffset) + map.mappings,
}
: map
result.code = `${code.trimEnd()}\n//# sourceURL=${encodeSourceURL(
id,
)}\n${MODULE_RUNNER_SOURCEMAPPING_SOURCE}\n//# ${SOURCEMAPPING_URL}=${genSourceMapUrl(sourceMap)}\n`
return `${code.trimEnd()}\n//# sourceURL=${encodeSourceURL(id)}\n`
}

return result
function offsetSourceMap(map: SourceMap, startOffset: number | undefined) {
return startOffset
? { ...map, mappings: ';'.repeat(startOffset) + map.mappings }
: map
}

function isBundledChunkUrl(environment: DevEnvironment, url: string) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
// This file contains the marker Vite puts before its inline source map
// in a string literal, which should not be mistaken for an inline map

const text = '//# sourceMappingSource=vite-generated'

export function getMessage() {
return text
}
Loading
Loading