Unverified Commit 94db8c6e authored by Will Binns-Smith's avatar Will Binns-Smith Committed by GitHub

Turbopack server HMR: inline source maps for `eval`ed modules (#90561)

Previously, we lost stack frame information when server hmr code was applied through `eval`. 

This adds and calls \`maybeInlineSourcemap()\` to the Turbopack Node.js HMR runtime that appends \`//# sourceURL\` and \`//# sourceMappingURL\` (base64-encoded) to each `eval`ed module entry. 
    
Test Plan: CI for #90389
parent 89f3649a
// hmr-trigger: 0
export default function Page() {
throw new Error('hmr-sourcemap-test-error')
}
...@@ -127,4 +127,31 @@ describe('server-hmr', () => { ...@@ -127,4 +127,31 @@ describe('server-hmr', () => {
} }
) )
}) })
describe('source maps', () => {
itTurbopackDev(
"stack frames from eval'd HMR modules point to original source locations",
async () => {
await next.fetch('/sourcemaps').catch(() => {})
await next.patchFile('app/sourcemaps/page.tsx', (content) =>
content.replace('hmr-trigger: 0', 'hmr-trigger: 1')
)
const outputLengthBeforeFetch = next.cliOutput.length
await next.fetch('/sourcemaps').catch(() => {})
await retry(async () => {
expect(next.cliOutput.slice(outputLengthBeforeFetch)).toContain(
'hmr-sourcemap-test-error'
)
})
const outputAfterHmr = next.cliOutput.slice(outputLengthBeforeFetch)
// Without proper sourcemaps, the stack frame doesn't include the accurate file number
expect(outputAfterHmr).toMatch(/page\.tsx:4:9/)
}
)
})
}) })
...@@ -13,6 +13,25 @@ type NodeJsHmrPayload = { ...@@ -13,6 +13,25 @@ type NodeJsHmrPayload = {
instruction: EcmascriptMergedUpdate instruction: EcmascriptMergedUpdate
} }
/**
* Appends the module code with //# sourceURL and //# sourceMappingURL so
* that Node.js can resolve stack frames from `eval`ed server HMR modules back to
* their original source files. Mirrors the browser's _eval in dev-backend-dom.ts.
*/
function inlineSourcemaps(entry: EcmascriptModuleEntry): string {
const [chunkPath, moduleId] = entry.url.split('?', 2)
const absolutePath = path.resolve(RUNTIME_ROOT, chunkPath)
const fileHref = url.pathToFileURL(absolutePath).href
const sourceURL = moduleId ? `${fileHref}?${moduleId}` : fileHref
let code = entry.code + '\n\n//# sourceURL=' + sourceURL
if (entry.map) {
code +=
'\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,' +
Buffer.from(entry.map).toString('base64')
}
return code
}
let serverHmrUpdateHandler: ((msg: NodeJsHmrPayload) => void) | null = null let serverHmrUpdateHandler: ((msg: NodeJsHmrPayload) => void) | null = null
function initializeServerHmr( function initializeServerHmr(
...@@ -75,10 +94,9 @@ function handleNodejsUpdate( ...@@ -75,10 +94,9 @@ function handleNodejsUpdate(
try { try {
const { entries = {}, chunks = {} } = instruction const { entries = {}, chunks = {} } = instruction
// Node.js eval function (no source maps)
const evalModuleEntry = (entry: EcmascriptModuleEntry) => { const evalModuleEntry = (entry: EcmascriptModuleEntry) => {
// eslint-disable-next-line no-eval // eslint-disable-next-line no-eval
return (0, eval)(entry.code) return (0, eval)(entry.map ? inlineSourcemaps(entry) : entry.code)
} }
const { added, modified } = computeChangedModules( const { added, modified } = computeChangedModules(
......
...@@ -1466,7 +1466,22 @@ module.exports = (sourcePath)=>({ ...@@ -1466,7 +1466,22 @@ module.exports = (sourcePath)=>({
}); });
/// <reference path="../../shared/runtime/dev-protocol.d.ts" /> /// <reference path="../../shared/runtime/dev-protocol.d.ts" />
/// <reference path="../../shared/runtime/hmr-runtime.ts" /> /// <reference path="../../shared/runtime/hmr-runtime.ts" />
/* eslint-disable @typescript-eslint/no-unused-vars */ let serverHmrUpdateHandler = null; /* eslint-disable @typescript-eslint/no-unused-vars */ /**
* Appends the module code with //# sourceURL and //# sourceMappingURL so
* that Node.js can resolve stack frames from `eval`ed server HMR modules back to
* their original source files. Mirrors the browser's _eval in dev-backend-dom.ts.
*/ function inlineSourcemaps(entry) {
const [chunkPath, moduleId] = entry.url.split('?', 2);
const absolutePath = path.resolve(RUNTIME_ROOT, chunkPath);
const fileHref = url.pathToFileURL(absolutePath).href;
const sourceURL = moduleId ? `${fileHref}?${moduleId}` : fileHref;
let code = entry.code + '\n\n//# sourceURL=' + sourceURL;
if (entry.map) {
code += '\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,' + Buffer.from(entry.map).toString('base64');
}
return code;
}
let serverHmrUpdateHandler = null;
function initializeServerHmr(moduleFactories, devModuleCache) { function initializeServerHmr(moduleFactories, devModuleCache) {
if (serverHmrUpdateHandler != null) { if (serverHmrUpdateHandler != null) {
throw new Error('[Server HMR] Server HMR client is already initialized'); throw new Error('[Server HMR] Server HMR client is already initialized');
...@@ -1508,10 +1523,9 @@ function initializeServerHmr(moduleFactories, devModuleCache) { ...@@ -1508,10 +1523,9 @@ function initializeServerHmr(moduleFactories, devModuleCache) {
} }
try { try {
const { entries = {}, chunks = {} } = instruction; const { entries = {}, chunks = {} } = instruction;
// Node.js eval function (no source maps)
const evalModuleEntry = (entry)=>{ const evalModuleEntry = (entry)=>{
// eslint-disable-next-line no-eval // eslint-disable-next-line no-eval
return (0, eval)(entry.code); return (0, eval)(entry.map ? inlineSourcemaps(entry) : entry.code);
}; };
const { added, modified } = computeChangedModules(entries, chunks, undefined // no chunkModulesMap for Node.js const { added, modified } = computeChangedModules(entries, chunks, undefined // no chunkModulesMap for Node.js
); );
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment