diff --git a/lib/api/api-request.js b/lib/api/api-request.js index 285c76de241..2537b264ee3 100644 --- a/lib/api/api-request.js +++ b/lib/api/api-request.js @@ -1,6 +1,6 @@ 'use strict' -const Readable = require('./readable') +const { Readable } = require('./readable') const { InvalidArgumentError, RequestAbortedError diff --git a/lib/api/readable.js b/lib/api/readable.js index f2eca3f822e..f4d935c5bf6 100644 --- a/lib/api/readable.js +++ b/lib/api/readable.js @@ -16,7 +16,7 @@ const kContentType = Symbol('kContentType') const noop = () => {} -module.exports = class BodyReadable extends Readable { +class BodyReadable extends Readable { constructor ({ resume, abort, @@ -348,3 +348,5 @@ function consumeFinish (consume, err) { consume.length = 0 consume.body = null } + +module.exports = { Readable: BodyReadable, chunksDecode } diff --git a/lib/api/util.js b/lib/api/util.js index 60f001b2254..24f69d12bd3 100644 --- a/lib/api/util.js +++ b/lib/api/util.js @@ -2,18 +2,20 @@ const assert = require('node:assert') const { ResponseStatusCodeError } = require('../core/errors') -const { toUSVString } = require('../core/util') + +const { chunksDecode } = require('./readable') +const CHUNK_LIMIT = 128 * 1024 async function getResolveErrorBodyCallback ({ callback, body, contentType, statusCode, statusMessage, headers }) { assert(body) let chunks = [] - let limit = 0 + let length = 0 for await (const chunk of body) { chunks.push(chunk) - limit += chunk.length - if (limit > 128 * 1024) { + length += chunk.length + if (length > CHUNK_LIMIT) { chunks = null break } @@ -26,13 +28,13 @@ async function getResolveErrorBodyCallback ({ callback, body, contentType, statu try { if (contentType.startsWith('application/json')) { - const payload = JSON.parse(toUSVString(Buffer.concat(chunks))) + const payload = JSON.parse(chunksDecode(chunks, length)) process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers, payload)) return } if (contentType.startsWith('text/')) { - const payload = toUSVString(Buffer.concat(chunks)) + const payload = chunksDecode(chunks, length) process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers, payload)) return } diff --git a/test/readable.js b/test/readable.js index 72327482aa2..dd0631daf8b 100644 --- a/test/readable.js +++ b/test/readable.js @@ -2,7 +2,7 @@ const { tspl } = require('@matteo.collina/tspl') const { test, describe } = require('node:test') -const Readable = require('../lib/api/readable') +const { Readable } = require('../lib/api/readable') describe('Readable', () => { test('avoid body reordering', async function (t) {