export async function readBoundedResponseText( response: Response, label: string, maxBytes: number, ): Promise { const contentLength = Number.parseInt(response.headers.get("content-length") ?? "", 10); if (Number.isFinite(contentLength) && contentLength > maxBytes) { throw new Error(`${label} response body exceeded ${maxBytes} bytes.`); } if (!response.body) { return ""; } const reader = response.body.getReader(); const decoder = new TextDecoder(); const chunks: string[] = []; let totalBytes = 0; let canceled = false; try { for (;;) { const { done, value } = await reader.read(); if (done) { const tail = decoder.decode(); if (tail) { chunks.push(tail); } break; } totalBytes += value.byteLength; if (totalBytes > maxBytes) { canceled = true; await reader.cancel().catch(() => undefined); throw new Error(`${label} response body exceeded ${maxBytes} bytes.`); } chunks.push(decoder.decode(value, { stream: true })); } } finally { if (!canceled) { reader.releaseLock(); } } return chunks.join(""); }