Skip to content

Commit 2770478

Browse files
Copilotsapphi-red
andauthored
fix(module-runner): prevent crash when sourceMappingURL pattern appears in string literals (vitejs#20554)
Co-authored-by: copilot-swe-agent[bot] <[email protected]> Co-authored-by: sapphi-red <[email protected]>
1 parent ab33803 commit 2770478

File tree

3 files changed

+34
-1
lines changed

3 files changed

+34
-1
lines changed

packages/vite/src/module-runner/evaluatedModules.ts

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,8 +108,13 @@ export class EvaluatedModules {
108108
if (!mod) return null
109109
if (mod.map) return mod.map
110110
if (!mod.meta || !('code' in mod.meta)) return null
111+
112+
const pattern = `//# ${SOURCEMAPPING_URL}=data:application/json;base64,`
113+
const lastIndex = mod.meta.code.lastIndexOf(pattern)
114+
if (lastIndex === -1) return null
115+
111116
const mapString = MODULE_RUNNER_SOURCEMAPPING_REGEXP.exec(
112-
mod.meta.code,
117+
mod.meta.code.slice(lastIndex),
113118
)?.[1]
114119
if (!mapString) return null
115120
mod.map = new DecodedMap(JSON.parse(decodeBase64(mapString)), mod.file)
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
// This file contains sourceMappingURL pattern in string literals
2+
// which should not crash the module runner
3+
4+
const text = '//# sourceMappingURL=data:application/json;base64,invalidbase64'
5+
6+
export function getMessage() {
7+
return text
8+
}
9+
10+
export function throwError() {
11+
throw new Error('Test error for stacktrace')
12+
}

packages/vite/src/node/ssr/runtime/__tests__/server-source-maps.spec.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,4 +93,20 @@ describe('module runner initialization', async () => {
9393
' at Module.main (<root>/fixtures/has-error-deep.ts:6:3)',
9494
])
9595
})
96+
97+
it('should not crash when sourceMappingURL pattern appears in string literals', async ({
98+
runner,
99+
server,
100+
}) => {
101+
const mod = await runner.import('/fixtures/string-literal-sourcemap.ts')
102+
expect(mod.getMessage()).toBe(
103+
'//# sourceMappingURL=data:application/json;base64,invalidbase64',
104+
)
105+
const error = await getError(() => mod.throwError())
106+
expect(error.message).toBe('Test error for stacktrace')
107+
expect(serializeStackDeep(server, error).slice(0, 2)).toEqual([
108+
'Error: Test error for stacktrace',
109+
' at Module.throwError (<root>/fixtures/string-literal-sourcemap.ts:11:9)',
110+
])
111+
})
96112
})

0 commit comments

Comments
 (0)