From c6f23be4ba5a94e88c492ca5cf3c9698c20058bf Mon Sep 17 00:00:00 2001 From: Titus Wormer Date: Wed, 16 Aug 2023 19:02:16 +0200 Subject: [PATCH] Fix to improve support for unknown causes --- lib/index.js | 24 ++++++++++++++++++------ test.js | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+), 6 deletions(-) diff --git a/lib/index.js b/lib/index.js index 095f27b..6c4c2c5 100644 --- a/lib/index.js +++ b/lib/index.js @@ -234,17 +234,29 @@ function createByline(state, stats) { * * @param {State} state * Info passed around. - * @param {Error} cause + * @param {unknown} cause * Cause. * @returns {Array} * Lines. */ function createCauseLines(state, cause) { const lines = [' ' + state.bold + '[cause]' + state.normalIntensity + ':'] - /* c8 ignore next -- stacks can be missing for weird reasons or in weird places. */ - const stackLines = (cause.stack || cause.message).split(eol) - stackLines[0] = ' ' + stackLines[0] - lines.push(...stackLines) + /** @type {string | undefined} */ + let stackValue + + if (cause !== null && typeof cause === 'object') { + stackValue = + ('stack' in cause ? String(cause.stack) : undefined) || + ('message' in cause ? String(cause.message) : undefined) + } + + if (typeof stackValue === 'string') { + const stackLines = stackValue.split(eol) + stackLines[0] = ' ' + stackLines[0] + lines.push(...stackLines) + } else { + lines.push(' ' + cause) + } return lines } @@ -346,7 +358,7 @@ function createMessageLine(state, message) { ] if (message.cause) { - rest.push(...createCauseLines(state, /** @type {Error} */ (message.cause))) + rest.push(...createCauseLines(state, message.cause)) } if (state.verbose && message.url) { diff --git a/test.js b/test.js index af4d289..25550e6 100644 --- a/test.js +++ b/test.js @@ -413,6 +413,54 @@ test('reporter', async function () { 'should support a `message.cause`' ) + file = new VFile() + let message = file.message('Something failed terribly') + message.cause = 'Boom!' + + assert.equal( + strip(reporter(file)), + [ + ' warning Something failed terribly', + ' [cause]:', + ' Boom!', + '', + '⚠ 1 warning' + ].join('\n'), + 'should support a `message.cause` set to a primitive' + ) + + file = new VFile() + message = file.message('Something failed terribly') + message.cause = {message: 'Boom!'} + + assert.equal( + strip(reporter(file)), + [ + ' warning Something failed terribly', + ' [cause]:', + ' Boom!', + '', + '⚠ 1 warning' + ].join('\n'), + 'should support a `message.cause` set to a n object w/o stack' + ) + + file = new VFile() + message = file.message('Something failed terribly') + message.cause = {} + + assert.equal( + strip(reporter(file)), + [ + ' warning Something failed terribly', + ' [cause]:', + ' [object Object]', + '', + '⚠ 1 warning' + ].join('\n'), + 'should support a `message.cause` set to a n object w/o stack or message' + ) + /** @type {Text} */ const text = {type: 'text', value: 'a'} /** @type {MdxJsxTextElementHast} */