From 733f15fe5bd2d67e1fadaee82e7913b70d45dc5e Mon Sep 17 00:00:00 2001 From: Dmitriy Mozgovoy Date: Mon, 20 May 2024 16:15:15 +0300 Subject: [PATCH] fix(fetch): fixed ReferenceError issue when TextEncoder is not available in the environment; (#6410) --- lib/adapters/fetch.js | 12 +++++++++--- lib/helpers/trackStream.js | 11 +++++------ 2 files changed, 14 insertions(+), 9 deletions(-) diff --git a/lib/adapters/fetch.js b/lib/adapters/fetch.js index 6d3ceb065d..3abd8cf2e2 100644 --- a/lib/adapters/fetch.js +++ b/lib/adapters/fetch.js @@ -20,6 +20,12 @@ const fetchProgressDecorator = (total, fn) => { const isFetchSupported = typeof fetch !== 'undefined'; const isReadableStreamSupported = isFetchSupported && typeof ReadableStream !== 'undefined'; +// used only inside the fetch adapter +const encodeText = isFetchSupported && (typeof TextEncoder !== 'undefined' ? + ((encoder) => (str) => encoder.encode(str))(new TextEncoder()) : + async (str) => new Uint8Array(await new Response(str).arrayBuffer()) +); + const supportsRequestStream = isReadableStreamSupported && (() => { let duplexAccessed = false; @@ -80,7 +86,7 @@ const getBodyLength = async (body) => { } if(utils.isString(body)) { - return (await new TextEncoder().encode(body)).byteLength; + return (await encodeText(body)).byteLength; } } @@ -144,7 +150,7 @@ export default isFetchSupported && (async (config) => { data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, fetchProgressDecorator( requestContentLength, progressEventReducer(onUploadProgress) - )); + ), null, encodeText); } } @@ -179,7 +185,7 @@ export default isFetchSupported && (async (config) => { trackStream(response.body, DEFAULT_CHUNK_SIZE, onDownloadProgress && fetchProgressDecorator( responseContentLength, progressEventReducer(onDownloadProgress, true) - ), isStreamResponse && onFinish), + ), isStreamResponse && onFinish, encodeText), options ); } diff --git a/lib/helpers/trackStream.js b/lib/helpers/trackStream.js index 395d962e40..6241d06f45 100644 --- a/lib/helpers/trackStream.js +++ b/lib/helpers/trackStream.js @@ -1,4 +1,5 @@ + export const streamChunk = function* (chunk, chunkSize) { let len = chunk.byteLength; @@ -17,16 +18,14 @@ export const streamChunk = function* (chunk, chunkSize) { } } -const encoder = new TextEncoder(); - -export const readBytes = async function* (iterable, chunkSize) { +export const readBytes = async function* (iterable, chunkSize, encode) { for await (const chunk of iterable) { - yield* streamChunk(ArrayBuffer.isView(chunk) ? chunk : (await encoder.encode(String(chunk))), chunkSize); + yield* streamChunk(ArrayBuffer.isView(chunk) ? chunk : (await encode(String(chunk))), chunkSize); } } -export const trackStream = (stream, chunkSize, onProgress, onFinish) => { - const iterator = readBytes(stream, chunkSize); +export const trackStream = (stream, chunkSize, onProgress, onFinish, encode) => { + const iterator = readBytes(stream, chunkSize, encode); let bytes = 0;