Skip to content

Commit

Permalink
Fix to improve support for unknown causes
Browse files Browse the repository at this point in the history
  • Loading branch information
wooorm committed Aug 16, 2023
1 parent 0db02ab commit c6f23be
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 6 deletions.
24 changes: 18 additions & 6 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -234,17 +234,29 @@ function createByline(state, stats) {
*
* @param {State} state
* Info passed around.
* @param {Error} cause
* @param {unknown} cause
* Cause.
* @returns {Array<string>}
* 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
}
Expand Down Expand Up @@ -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) {
Expand Down
48 changes: 48 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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} */
Expand Down

0 comments on commit c6f23be

Please sign in to comment.