(
response: {
headers?: { get(name: string): string | null }
body?: ReadableStream<Uint8Array> | null
arrayBuffer?: () => Promise<ArrayBuffer>
text?: () => Promise<string>
},
options: ReadResponseWithLimitOptions
)
| 227 | } |
| 228 | |
| 229 | export async function readResponseToBufferWithLimit( |
| 230 | response: { |
| 231 | headers?: { get(name: string): string | null } |
| 232 | body?: ReadableStream<Uint8Array> | null |
| 233 | arrayBuffer?: () => Promise<ArrayBuffer> |
| 234 | text?: () => Promise<string> |
| 235 | }, |
| 236 | options: ReadResponseWithLimitOptions |
| 237 | ): Promise<Buffer> { |
| 238 | const contentLength = getContentLength(response.headers ?? options.headers) |
| 239 | try { |
| 240 | if (contentLength !== null) { |
| 241 | assertKnownSizeWithinLimit(contentLength, options.maxBytes, options.label) |
| 242 | } |
| 243 | } catch (error) { |
| 244 | if (isPayloadSizeLimitError(error)) { |
| 245 | await response.body?.cancel(error).catch(() => {}) |
| 246 | } |
| 247 | throw error |
| 248 | } |
| 249 | if ( |
| 250 | !options.allowNoBodyFallback && |
| 251 | !response.body && |
| 252 | contentLength === null && |
| 253 | (response.arrayBuffer || response.text) |
| 254 | ) { |
| 255 | throw new PayloadSizeLimitError({ |
| 256 | label: options.label, |
| 257 | maxBytes: options.maxBytes, |
| 258 | }) |
| 259 | } |
| 260 | if (!response.body && options.preferTextFallback && response.text) { |
| 261 | const text = await response.text() |
| 262 | const buffer = Buffer.from(text) |
| 263 | assertKnownSizeWithinLimit(buffer.byteLength, options.maxBytes, options.label) |
| 264 | return buffer |
| 265 | } |
| 266 | if (!response.body && response.arrayBuffer) { |
| 267 | const buffer = Buffer.from(await response.arrayBuffer()) |
| 268 | assertKnownSizeWithinLimit(buffer.byteLength, options.maxBytes, options.label) |
| 269 | if (buffer.byteLength > 0 || !response.text) { |
| 270 | return buffer |
| 271 | } |
| 272 | const text = await response.text() |
| 273 | const textBuffer = Buffer.from(text) |
| 274 | assertKnownSizeWithinLimit(textBuffer.byteLength, options.maxBytes, options.label) |
| 275 | return textBuffer |
| 276 | } |
| 277 | if (!response.body && response.text) { |
| 278 | const text = await response.text() |
| 279 | const buffer = Buffer.from(text) |
| 280 | assertKnownSizeWithinLimit(buffer.byteLength, options.maxBytes, options.label) |
| 281 | return buffer |
| 282 | } |
| 283 | return readStreamToBufferWithLimit(response.body, options) |
| 284 | } |
| 285 | |
| 286 | export async function readResponseTextWithLimit( |
no test coverage detected