Skip to content

Commit

Permalink
fetch: implement isomorphic decoding (#1743)
Browse files Browse the repository at this point in the history
  • Loading branch information
KhafraDev committed Oct 28, 2022
1 parent 9251008 commit d23f5dd
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
6 changes: 3 additions & 3 deletions lib/fetch/dataURL.js
@@ -1,6 +1,6 @@
const assert = require('assert')
const { atob } = require('buffer')
const { isValidHTTPToken } = require('./util')
const { isValidHTTPToken, isomorphicDecode } = require('./util')

const encoder = new TextEncoder()

Expand Down Expand Up @@ -54,15 +54,15 @@ function dataURLProcessor (dataURL) {
const encodedBody = input.slice(mimeTypeLength + 1)

// 10. Let body be the percent-decoding of encodedBody.
/** @type {Uint8Array|string} */
let body = stringPercentDecode(encodedBody)

// 11. If mimeType ends with U+003B (;), followed by
// zero or more U+0020 SPACE, followed by an ASCII
// case-insensitive match for "base64", then:
if (/;(\u0020){0,}base64$/i.test(mimeType)) {
// 1. Let stringBody be the isomorphic decode of body.
const stringBody = decodeURIComponent(new TextDecoder('utf-8').decode(body))
const stringBody = isomorphicDecode(body)

// 2. Set body to the forgiving-base64 decode of
// stringBody.
body = forgivingBase64(stringBody)
Expand Down
20 changes: 19 additions & 1 deletion lib/fetch/util.js
Expand Up @@ -856,6 +856,23 @@ function isReadableStreamLike (stream) {
)
}

/**
* @see https://infra.spec.whatwg.org/#isomorphic-decode
* @param {number[]|Uint8Array} input
*/
function isomorphicDecode (input) {
// 1. To isomorphic decode a byte sequence input, return a string whose code point
// length is equal to input’s length and whose code points have the same values
// as the values of input’s bytes, in the same order.
let output = ''

for (let i = 0; i < input.length; i++) {
output += String.fromCharCode(input[i])
}

return output
}

/**
* @param {ReadableStreamController<Uint8Array>} controller
*/
Expand Down Expand Up @@ -929,5 +946,6 @@ module.exports = {
bytesMatch,
isReadableStreamLike,
readableStreamClose,
isomorphicEncode
isomorphicEncode,
isomorphicDecode
}

0 comments on commit d23f5dd

Please sign in to comment.