Skip to content

Commit

Permalink
lib: decorate async stack trace in source maps
Browse files Browse the repository at this point in the history
Decorate stack frame with 'async' and 'new' keywords based on the type
of the call site info.

PR-URL: #53860
Reviewed-By: James M Snell <[email protected]>
Reviewed-By: Michaël Zasso <[email protected]>
Reviewed-By: Benjamin Gruenbaum <[email protected]>
  • Loading branch information
legendecas authored and marco-ippolito committed Aug 19, 2024
1 parent 137a2e5 commit 51ba566
Show file tree
Hide file tree
Showing 11 changed files with 166 additions and 45 deletions.
111 changes: 68 additions & 43 deletions lib/internal/source_map/prepare_stack_trace.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ const {
const { fileURLToPath } = require('internal/url');
const { setGetSourceMapErrorSource } = internalBinding('errors');

const kStackLineAt = '\n at ';

// Create a prettified stacktrace, inserting context from source maps
// if possible.
function prepareStackTraceWithSourceMaps(error, trace) {
Expand All @@ -40,75 +42,98 @@ function prepareStackTraceWithSourceMaps(error, trace) {

let lastSourceMap;
let lastFileName;
const preparedTrace = ArrayPrototypeJoin(ArrayPrototypeMap(trace, (t, i) => {
const str = '\n at ';
const preparedTrace = ArrayPrototypeJoin(ArrayPrototypeMap(trace, (callSite, i) => {
try {
// A stack trace will often have several call sites in a row within the
// same file, cache the source map and file content accordingly:
let fileName = t.getFileName();
let fileName = callSite.getFileName();
if (fileName === undefined) {
fileName = t.getEvalOrigin();
fileName = callSite.getEvalOrigin();
}
const sm = fileName === lastFileName ?
lastSourceMap :
findSourceMap(fileName);
lastSourceMap = sm;
lastFileName = fileName;
if (sm) {
// Source Map V3 lines/columns start at 0/0 whereas stack traces
// start at 1/1:
const {
originalLine,
originalColumn,
originalSource,
} = sm.findEntry(t.getLineNumber() - 1, t.getColumnNumber() - 1);
if (originalSource && originalLine !== undefined &&
originalColumn !== undefined) {
const name = getOriginalSymbolName(sm, trace, i);
// Construct call site name based on: v8.dev/docs/stack-trace-api:
const fnName = t.getFunctionName() ?? t.getMethodName();
const typeName = t.getTypeName();
const namePrefix = typeName !== null && typeName !== 'global' ? `${typeName}.` : '';
const originalName = `${namePrefix}${fnName || '<anonymous>'}`;
// The original call site may have a different symbol name
// associated with it, use it:
const prefix = (name && name !== originalName) ?
`${name}` :
`${originalName}`;
const hasName = !!(name || originalName);
const originalSourceNoScheme =
StringPrototypeStartsWith(originalSource, 'file://') ?
fileURLToPath(originalSource) : originalSource;
// Replace the transpiled call site with the original:
return `${str}${prefix}${hasName ? ' (' : ''}` +
`${originalSourceNoScheme}:${originalLine + 1}:` +
`${originalColumn + 1}${hasName ? ')' : ''}`;
}
return `${kStackLineAt}${serializeJSStackFrame(sm, callSite, trace[i + 1])}`;
}
} catch (err) {
debug(err);
}
return `${str}${t}`;
return `${kStackLineAt}${callSite}`;
}), '');
return `${errorString}${preparedTrace}`;
}

/**
* Serialize a single call site in the stack trace.
* Refer to SerializeJSStackFrame in deps/v8/src/objects/call-site-info.cc for
* more details about the default ToString(CallSite).
* The CallSite API is documented at https://v8.dev/docs/stack-trace-api.
* @param {import('internal/source_map/source_map').SourceMap} sm
* @param {CallSite} callSite - the CallSite object to be serialized
* @param {CallSite} callerCallSite - caller site info
* @returns {string} - the serialized call site
*/
function serializeJSStackFrame(sm, callSite, callerCallSite) {
// Source Map V3 lines/columns start at 0/0 whereas stack traces
// start at 1/1:
const {
originalLine,
originalColumn,
originalSource,
} = sm.findEntry(callSite.getLineNumber() - 1, callSite.getColumnNumber() - 1);
if (originalSource === undefined || originalLine === undefined ||
originalColumn === undefined) {
return `${callSite}`;
}
const name = getOriginalSymbolName(sm, callSite, callerCallSite);
const originalSourceNoScheme =
StringPrototypeStartsWith(originalSource, 'file://') ?
fileURLToPath(originalSource) : originalSource;
// Construct call site name based on: v8.dev/docs/stack-trace-api:
const fnName = callSite.getFunctionName() ?? callSite.getMethodName();

let prefix = '';
if (callSite.isAsync()) {
// Promise aggregation operation frame has no locations. This must be an
// async stack frame.
prefix = 'async ';
} else if (callSite.isConstructor()) {
prefix = 'new ';
}

const typeName = callSite.getTypeName();
const namePrefix = typeName !== null && typeName !== 'global' ? `${typeName}.` : '';
const originalName = `${namePrefix}${fnName || '<anonymous>'}`;
// The original call site may have a different symbol name
// associated with it, use it:
const mappedName = (name && name !== originalName) ?
`${name}` :
`${originalName}`;
const hasName = !!(name || originalName);
// Replace the transpiled call site with the original:
return `${prefix}${mappedName}${hasName ? ' (' : ''}` +
`${originalSourceNoScheme}:${originalLine + 1}:` +
`${originalColumn + 1}${hasName ? ')' : ''}`;
}

// Transpilers may have removed the original symbol name used in the stack
// trace, if possible restore it from the names field of the source map:
function getOriginalSymbolName(sourceMap, trace, curIndex) {
function getOriginalSymbolName(sourceMap, callSite, callerCallSite) {
// First check for a symbol name associated with the enclosing function:
const enclosingEntry = sourceMap.findEntry(
trace[curIndex].getEnclosingLineNumber() - 1,
trace[curIndex].getEnclosingColumnNumber() - 1,
callSite.getEnclosingLineNumber() - 1,
callSite.getEnclosingColumnNumber() - 1,
);
if (enclosingEntry.name) return enclosingEntry.name;
// Fallback to using the symbol name attached to the next stack frame:
const currentFileName = trace[curIndex].getFileName();
const nextCallSite = trace[curIndex + 1];
if (nextCallSite && currentFileName === nextCallSite.getFileName()) {
// Fallback to using the symbol name attached to the caller site:
const currentFileName = callSite.getFileName();
if (callerCallSite && currentFileName === callerCallSite.getFileName()) {
const { name } = sourceMap.findEntry(
nextCallSite.getLineNumber() - 1,
nextCallSite.getColumnNumber() - 1,
callerCallSite.getLineNumber() - 1,
callerCallSite.getColumnNumber() - 1,
);
return name;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// Flags: --enable-source-maps
import '../../../common/index.mjs';
async function Throw() {
await 0;
throw new Error('message');
}
(async function main() {
await Promise.all([0, 1, 2, Throw()]);
})();
// To recreate:
//
// npx --package typescript tsc --module nodenext --target esnext --outDir test/fixtures/source-map/output --sourceMap test/fixtures/source-map/output/source_map_throw_async_stack_trace.mts
//# sourceMappingURL=source_map_throw_async_stack_trace.mjs.map

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// Flags: --enable-source-maps

import '../../../common/index.mjs';

interface Foo {
/** line
*
* blocks */
}

async function Throw() {
await 0;
throw new Error('message')
}

(async function main() {
await Promise.all([0, 1, 2, Throw()]);
})()

// To recreate:
//
// npx --package typescript tsc --module nodenext --target esnext --outDir test/fixtures/source-map/output --sourceMap test/fixtures/source-map/output/source_map_throw_async_stack_trace.mts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
*output*source_map_throw_async_stack_trace.mts:13
throw new Error('message')
^


Error: message
at Throw (*output*source_map_throw_async_stack_trace.mts:13:9)
at async Promise.all (index 3)
at async main (*output*source_map_throw_async_stack_trace.mts:17:3)

Node.js *
12 changes: 12 additions & 0 deletions test/fixtures/source-map/output/source_map_throw_construct.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// Flags: --enable-source-maps
import '../../../common/index.mjs';
class Foo {
constructor() {
throw new Error('message');
}
}
new Foo();
// To recreate:
//
// npx --package typescript tsc --module nodenext --target esnext --outDir test/fixtures/source-map/output --sourceMap test/fixtures/source-map/output/source_map_throw_construct.mts
//# sourceMappingURL=source_map_throw_construct.mjs.map

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

21 changes: 21 additions & 0 deletions test/fixtures/source-map/output/source_map_throw_construct.mts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// Flags: --enable-source-maps

import '../../../common/index.mjs';

interface Block {
/** line
*
* blocks */
}

class Foo {
constructor() {
throw new Error('message');
}
}

new Foo();

// To recreate:
//
// npx --package typescript tsc --module nodenext --target esnext --outDir test/fixtures/source-map/output --sourceMap test/fixtures/source-map/output/source_map_throw_construct.mts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
*output*source_map_throw_construct.mts:13
throw new Error('message');
^


Error: message
at new Foo (*output*source_map_throw_construct.mts:13:11)
at <anonymous> (*output*source_map_throw_construct.mts:17:1)
*
*
*

Node.js *
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,6 @@
Error: goodbye
at Hello (*uglify-throw-original.js:5:9)
at Immediate.<anonymous> (*uglify-throw-original.js:9:3)
at process.processImmediate (node:internal*timers:483:21)
*

Node.js *
4 changes: 3 additions & 1 deletion test/parallel/test-node-output-sourcemaps.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ describe('sourcemaps output', { concurrency: true }, () => {
.replaceAll(/\/(\w)/g, '*$1')
.replaceAll('*test*', '*')
.replaceAll('*fixtures*source-map*', '*')
.replaceAll(/(\W+).*node:internal\*modules.*/g, '$1*');
.replaceAll(/(\W+).*node:.*/g, '$1*');
if (common.isWindows) {
const currentDeviceLetter = path.parse(process.cwd()).root.substring(0, 1).toLowerCase();
const regex = new RegExp(`${currentDeviceLetter}:/?`, 'gi');
Expand All @@ -34,7 +34,9 @@ describe('sourcemaps output', { concurrency: true }, () => {
{ name: 'source-map/output/source_map_prepare_stack_trace.js' },
{ name: 'source-map/output/source_map_reference_error_tabs.js' },
{ name: 'source-map/output/source_map_sourcemapping_url_string.js' },
{ name: 'source-map/output/source_map_throw_async_stack_trace.mjs' },
{ name: 'source-map/output/source_map_throw_catch.js' },
{ name: 'source-map/output/source_map_throw_construct.mjs' },
{ name: 'source-map/output/source_map_throw_first_tick.js' },
{ name: 'source-map/output/source_map_throw_icu.js' },
{ name: 'source-map/output/source_map_throw_set_immediate.js' },
Expand Down

0 comments on commit 51ba566

Please sign in to comment.