Skip to content

Commit

Permalink
feat(webidl): better error message for ByteString converter
Browse files Browse the repository at this point in the history
Fixes #1590
  • Loading branch information
KhafraDev committed Aug 3, 2022
1 parent 2f4b3b6 commit ef6ecce
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 6 deletions.
15 changes: 9 additions & 6 deletions lib/fetch/webidl.js
Expand Up @@ -388,10 +388,6 @@ webidl.converters.DOMString = function (V, opts = {}) {
return String(V)
}

// Check for 0 or more characters outside of the latin1 range.
// eslint-disable-next-line no-control-regex
const isLatin1 = /^[\u0000-\u00ff]{0,}$/

// https://webidl.spec.whatwg.org/#es-ByteString
webidl.converters.ByteString = function (V) {
// 1. Let x be ? ToString(V).
Expand All @@ -400,8 +396,15 @@ webidl.converters.ByteString = function (V) {

// 2. If the value of any element of x is greater than
// 255, then throw a TypeError.
if (!isLatin1.test(x)) {
throw new TypeError('Argument is not a ByteString')
for (let index = 0; index < x.length; index++) {
const charCode = x.charCodeAt(index)

if (charCode > 255) {
throw new TypeError(
'Cannot convert argument to a ByteString because the character at' +
`index ${index} has a value of ${charCode} which is greater than 255.`
)
}
}

// 3. Return an IDL ByteString value whose length is the
Expand Down
9 changes: 9 additions & 0 deletions test/webidl/converters.js
Expand Up @@ -189,5 +189,14 @@ test('ByteString', (t) => {
webidl.converters.ByteString('')
})

// https://github.com/nodejs/undici/issues/1590
t.throws(() => {
const char = String.fromCharCode(256)
webidl.converters.ByteString(`invalid${char}char`)
}, {
message: 'Cannot convert argument to a ByteString because the character at' +
'index 7 has a value of 256 which is greater than 255.'
})

t.end()
})

0 comments on commit ef6ecce

Please sign in to comment.