From 2a5b908644bda9a3d6dc57186fa020a994011a51 Mon Sep 17 00:00:00 2001 From: legendecas Date: Wed, 22 Nov 2023 01:47:32 +0800 Subject: [PATCH] repl: fix prepareStackTrace frames array order The second parameter of `Error.prepareStackTrace` is an array of reversed call site frames. --- lib/repl.js | 17 ++++++----------- test/parallel/test-repl-pretty-custom-stack.js | 5 +++-- 2 files changed, 9 insertions(+), 13 deletions(-) diff --git a/lib/repl.js b/lib/repl.js index 3029c94b1e1ac0f..8b9cdb31c59b6be 100644 --- a/lib/repl.js +++ b/lib/repl.js @@ -45,7 +45,7 @@ const { ArrayPrototypeAt, ArrayPrototypeFilter, - ArrayPrototypeFindIndex, + ArrayPrototypeFindLastIndex, ArrayPrototypeForEach, ArrayPrototypeIncludes, ArrayPrototypeJoin, @@ -53,12 +53,10 @@ const { ArrayPrototypePop, ArrayPrototypePush, ArrayPrototypePushApply, - ArrayPrototypeReverse, ArrayPrototypeShift, ArrayPrototypeSlice, ArrayPrototypeSome, ArrayPrototypeSort, - ArrayPrototypeSplice, ArrayPrototypeUnshift, Boolean, Error, @@ -153,6 +151,7 @@ const { }, isErrorStackTraceLimitWritable, overrideStackTrace, + getInternalPrepareStackTrace, } = require('internal/errors'); const { sendInspectorCommand } = require('internal/util/inspector'); const { getOptionValue } = require('internal/options'); @@ -679,23 +678,19 @@ function REPLServer(prompt, if (typeof stackFrames === 'object') { // Search from the bottom of the call stack to // find the first frame with a null function name - const idx = ArrayPrototypeFindIndex( - ArrayPrototypeReverse(stackFrames), + const idx = ArrayPrototypeFindLastIndex( + stackFrames, (frame) => frame.getFunctionName() === null, ); // If found, get rid of it and everything below it - frames = ArrayPrototypeSplice(stackFrames, idx + 1); + frames = ArrayPrototypeSlice(stackFrames, 0, idx); } else { frames = stackFrames; } - // FIXME(devsnek): this is inconsistent with the checks - // that the real prepareStackTrace dispatch uses in - // lib/internal/errors.js. if (typeof Error.prepareStackTrace === 'function') { return Error.prepareStackTrace(error, frames); } - ArrayPrototypePush(frames, error); - return ArrayPrototypeJoin(ArrayPrototypeReverse(frames), '\n at '); + return getInternalPrepareStackTrace()(error, frames); }); decorateErrorStack(e); diff --git a/test/parallel/test-repl-pretty-custom-stack.js b/test/parallel/test-repl-pretty-custom-stack.js index a10cd032a688c42..560a7412669ec1e 100644 --- a/test/parallel/test-repl-pretty-custom-stack.js +++ b/test/parallel/test-repl-pretty-custom-stack.js @@ -42,8 +42,9 @@ const origPrepareStackTrace = Error.prepareStackTrace; Error.prepareStackTrace = (err, stack) => { if (err instanceof SyntaxError) return err.toString(); - stack.push(err); - return stack.reverse().join('--->\n'); + // Insert the error at the beginning of the stack + stack.unshift(err); + return stack.join('--->\n'); }; process.on('uncaughtException', (e) => {