Skip to content
Myr

response-size.ts

This file

Path

test/response-size.ts

569 lines · 17.9 KiB · TypeScript

Last changed by

Stop surfacing progress callback errorsSindre Sorhusbefore adoption13c8da5

History of this file

Take it

Add `maxResponseSize` optionSindre Sorhusbefore adoption0d59458

lines 1–21why, one step back
1import {gzipSync} from 'node:zlib';
2import test from 'ava';3import ky, {4 HTTPError, KyError, ResponseSizeError, isKyError, isResponseSizeError,5} from '../source/index.js';6import {createHttpTestServer} from './helpers/create-http-test-server.js';78const url = 'https://example.com/data';910for (const maxResponseSize of [0, 4, Number.POSITIVE_INFINITY]) {11 test(`allows bodies at the limit of ${maxResponseSize} bytes`, async t => {12 const body = maxResponseSize === 0 ? '' : '🦄';13 const text = await ky(url, {14 maxResponseSize,15 fetch: async () => new Response(body),16 }).text();17 t.is(text, body);18 });19}2021for (const maxResponseSize of [-1, 1.5, Number.NaN, Number.NEGATIVE_INFINITY, Number.MAX_SAFE_INTEGER + 1, '4', null]) {

TweaksSindre Sorhusbefore adoption3ded2aa

lines 22–29why, one step back
22 test(`rejects invalid maxResponseSize: ${String(maxResponseSize)}`, async t => {
23 await t.throwsAsync(ky(url, {24 maxResponseSize: maxResponseSize as number,25 async fetch() {26 t.fail('Should validate before fetching');27 return new Response();28 },29 }), {instanceOf: TypeError});

Add `maxResponseSize` optionSindre Sorhusbefore adoption0d59458

lines 30–450why, one step back
30 });
31}3233test('counts bytes rather than characters and ignores Content-Length', async t => {34 const error = await t.throwsAsync(ky(url, {35 maxResponseSize: 3,36 fetch: async () => new Response('🦄', {headers: {'content-length': '1'}}),37 }).text(), {instanceOf: ResponseSizeError});38 t.is(error?.maxResponseSize, 3);39 t.is(error?.request.url, url);40 t.true(error instanceof KyError);41 t.true(isKyError(error));42 t.true(isResponseSizeError(error));43 t.true(isResponseSizeError({name: 'ResponseSizeError', isKyError: true}));44 t.true(isKyError({name: 'ResponseSizeError', isKyError: true}));45 t.false(isResponseSizeError(new Error('Unrelated error')));46});4748test('does not reject a body within the limit based on Content-Length', async t => {49 const text = await ky(url, {50 maxResponseSize: 4,51 fetch: async () => new Response('okay', {headers: {'content-length': '1000'}}),52 }).text();53 t.is(text, 'okay');54});5556test('does not reject an empty HEAD body based on Content-Length', async t => {57 const response = await ky.head(url, {58 maxResponseSize: 0,59 fetch: async () => new Response(null, {headers: {'content-length': '1000'}}),60 });61 t.is(await response.text(), '');62});6364test('cancels the source when cumulative streamed bytes exceed the limit', async t => {65 let canceledWith: unknown;66 let chunkCount = 0;67 const response = await ky(url, {68 maxResponseSize: 4,69 fetch: async () => new Response(new ReadableStream<Uint8Array>({70 pull(controller) {71 chunkCount++;72 controller.enqueue(new Uint8Array([1, 2]));73 },74 cancel(reason) {75 canceledWith = reason;76 },77 })),78 });79 const reader = response.body!.getReader();80 const first = await reader.read();81 const second = await reader.read();82 t.deepEqual(first.value, new Uint8Array([1, 2]));83 t.deepEqual(second.value, new Uint8Array([1, 2]));84 const error = await t.throwsAsync(reader.read(), {instanceOf: ResponseSizeError});85 await new Promise(resolve => {86 setImmediate(resolve);87 });88 t.is(canceledWith, error);89 t.true(chunkCount <= 4);90});9192for (const method of ['json', 'text', 'arrayBuffer', 'blob', 'formData', 'bytes'] as const) {93 test(`limits the ${method} shortcut and runs beforeError once`, async t => {94 if (method === 'bytes' && typeof Response.prototype.bytes !== 'function') {95 t.pass();96 return;97 }9899 let errorCount = 0;100 let fetchCount = 0;101 const error = await t.throwsAsync(ky(url, {102 maxResponseSize: 1,103 retry: {shouldRetry: () => true},104 async fetch() {105 fetchCount++;106 return new Response('a=1', {headers: {'content-type': 'application/x-www-form-urlencoded'}});107 },108 hooks: {109 beforeError: [({error}) => {110 errorCount++;111 return error;112 }],113 },114 })[method](), {instanceOf: ResponseSizeError});115 t.true(isResponseSizeError(error));116 t.is(errorCount, 1);117 t.is(fetchCount, 1);118 });119}120121test('body reads after the response is returned do not run beforeError', async t => {122 let errorCount = 0;123 const response = await ky(url, {124 maxResponseSize: 1,125 fetch: async () => new Response('oversized'),126 hooks: {127 beforeError: [({error}) => {128 errorCount++;129 return error;130 }],131 },132 });133134 await t.throwsAsync(response.text(), {instanceOf: ResponseSizeError});135 t.is(errorCount, 0);136});137138test('limits afterResponse hook reads before cloning can buffer an oversized body', async t => {139 let errorCount = 0;140 await t.throwsAsync(ky(url, {141 maxResponseSize: 1,142 fetch: async () => new Response('oversized'),143 hooks: {144 afterResponse: [async ({response}) => {145 await response.clone().text();146 }],147 beforeError: [({error}) => {148 errorCount++;149 return error;150 }],151 },152 }), {instanceOf: ResponseSizeError});153 t.is(errorCount, 1);154});155156for (const hook of ['beforeRequest', 'beforeRetry', 'afterResponse'] as const) {157 test(`limits responses returned by ${hook}`, async t => {158 await t.throwsAsync(ky(url, {159 maxResponseSize: 1,160 retry: {delay: () => 0},161 fetch: async () => new Response('', {status: hook === 'beforeRetry' ? 503 : 200}),162 hooks: {163 [hook]: [() => new Response('oversized')],164 },165 }).text(), {instanceOf: ResponseSizeError});166 });167}168169test('limits replacement bodies before subsequent afterResponse hooks', async t => {170 await t.throwsAsync(ky(url, {171 maxResponseSize: 1,172 fetch: async () => new Response('a'),173 hooks: {174 afterResponse: [175 () => new Response('oversized'),176 async ({response}) => {177 await response.text();178 },179 ],180 },181 }), {instanceOf: ResponseSizeError});182});183184test('HTTP error body size failures are not swallowed or retried', async t => {185 let fetchCount = 0;186 let errorCount = 0;187 await t.throwsAsync(ky(url, {188 maxResponseSize: 1,189 retry: {shouldRetry: () => true, delay: () => 0},190 async fetch() {191 fetchCount++;192 return new Response('oversized', {status: 503});193 },194 hooks: {195 beforeError: [({error}) => {196 t.true(error instanceof ResponseSizeError);197 errorCount++;198 return error;199 }],200 },201 }), {instanceOf: ResponseSizeError});202 t.is(fetchCount, 1);203 t.is(errorCount, 1);204});205206test('HTTP error bodies within the limit retain their data', async t => {207 const error = await t.throwsAsync(ky(url, {208 maxResponseSize: 3,209 fetch: async () => new Response('bad', {status: 400}),210 }), {instanceOf: HTTPError});211 t.is(error?.data, 'bad');212});213214test('a response wrapper retains metadata, clones, and custom JSON parsing', async t => {215 const server = await createHttpTestServer(t);216 server.get('/redirect', (_request, response) => {217 response.redirect('/data');218 });219 server.get('/data', (_request, response) => {220 response.json({value: 1});221 });222 const response = await ky(`${server.url}/redirect`, {223 maxResponseSize: 100,224 parseJson: text => ({...JSON.parse(text), parsed: true}),225 });226 const clone = response.clone();227 t.is(response.url, `${server.url}/data`);228 t.true(response.redirected);229 t.is(clone.url, response.url);230 t.is(clone.type, response.type);231 t.true(clone.redirected);232 t.deepEqual(await clone.json(), {value: 1, parsed: true});233 t.deepEqual(await response.json(), {value: 1, parsed: true});234});235236test('limits decompressed response bytes', async t => {237 const server = await createHttpTestServer(t);238 const body = 'a'.repeat(1000);239 const compressed = gzipSync(body);240 t.true(compressed.byteLength < 100);241 server.get('/', (_request, response) => {242 response.set('content-encoding', 'gzip').send(compressed);243 });244 await t.throwsAsync(ky(server.url, {maxResponseSize: 100}).text(), {instanceOf: ResponseSizeError});245});246247test('combines with download progress', async t => {248 const sizes: number[] = [];249 const api = ky.create({250 maxResponseSize: 4,251 fetch: async () => new Response('test'),252 onDownloadProgress({transferredBytes}) {253 sizes.push(transferredBytes);254 },255 });256 t.is(await api(url).text(), 'test');257 t.is(sizes.at(-1), 4);258 await t.throwsAsync(api(url, {maxResponseSize: 3}).text(), {instanceOf: ResponseSizeError});259});260261test('does not report completed download progress when the size limit is exceeded', async t => {262 const maxResponseSize = 4;263 let reportedBytes = 0;264 await t.throwsAsync(ky(url, {265 maxResponseSize,266 fetch: async () => new Response(new ReadableStream<Uint8Array>({267 start(controller) {268 controller.enqueue(new Uint8Array([1, 2]));269 controller.enqueue(new Uint8Array([3, 4]));270 controller.enqueue(new Uint8Array([5, 6]));271 controller.close();272 },273 })),274 onDownloadProgress({percent, transferredBytes}, chunk) {275 reportedBytes += chunk.byteLength;276 t.is(transferredBytes, reportedBytes);277 t.true(transferredBytes <= maxResponseSize);278 t.true(percent < 1);279 },280 }).arrayBuffer(), {instanceOf: ResponseSizeError});281 t.true(reportedBytes > 0);282});283284test('defaults to unlimited and allows overriding an inherited limit', async t => {285 const api = ky.create({fetch: async () => new Response('test')});286 t.is(await api(url).text(), 'test');287 const limited = api.extend({maxResponseSize: 1});288 await t.throwsAsync(limited(url).text(), {instanceOf: ResponseSizeError});289 t.is(await limited(url, {maxResponseSize: Number.POSITIVE_INFINITY}).text(), 'test');290});291292test('a zero limit rejects a nonempty body', async t => {293 await t.throwsAsync(ky(url, {294 maxResponseSize: 0,295 fetch: async () => new Response(new Uint8Array([0])),296 }).arrayBuffer(), {instanceOf: ResponseSizeError});297});298299test('counts chunk view lengths and accepts multiple chunks exactly at the limit', async t => {300 const buffer = new Uint8Array(1024).fill(255);301 buffer.set([1, 2, 3, 4], 100);302 const body = await ky(url, {303 maxResponseSize: 4,304 fetch: async () => new Response(new ReadableStream<Uint8Array>({305 start(controller) {306 controller.enqueue(buffer.subarray(100, 102));307 controller.enqueue(new Uint8Array());308 controller.enqueue(buffer.subarray(102, 104));309 controller.close();310 },311 })),312 }).arrayBuffer();313 t.deepEqual(new Uint8Array(body), new Uint8Array([1, 2, 3, 4]));314});315316for (const forced of [false, true]) {317 test(`resets the byte count for ${forced ? 'forced' : 'HTTP'} retries`, async t => {318 let fetchCount = 0;319 const text = await ky(url, {320 maxResponseSize: 4,321 retry: {limit: 1, delay: () => 0},322 async fetch() {323 fetchCount++;324 return new Response(fetchCount === 1 ? 'fail' : 'done', {325 status: !forced && fetchCount === 1 ? 503 : 200,326 });327 },328 hooks: {329 afterResponse: [async ({response, retryCount}) => {330 if (forced && retryCount === 0) {331 t.is(await response.text(), 'fail');332 return ky.retry();333 }334 }],335 },336 }).text();337 t.is(text, 'done');338 t.is(fetchCount, 2);339 });340}341342test('concurrent requests on one instance have independent byte counts and errors', async t => {343 const api = ky.create({344 maxResponseSize: 4,345 fetch: async request => new Response(new URL((request as Request).url).pathname === '/large' ? 'large' : 'okay'),346 });347 const results = await Promise.allSettled([348 api('https://example.com/large').text(),349 api('https://example.com/small').text(),350 ]);351 const [large, small] = results;352 t.is(large.status, 'rejected');353 if (large.status === 'rejected') {354 t.true(large.reason instanceof ResponseSizeError);355 t.is((large.reason as ResponseSizeError).request.url, 'https://example.com/large');356 }357358 t.deepEqual(small, {status: 'fulfilled', value: 'okay'});359 t.is(await api('https://example.com/small').text(), 'okay');360});361362test('rejects an oversized JSON body before calling a custom parser', async t => {363 let parseCount = 0;364 await t.throwsAsync(ky(url, {365 maxResponseSize: 4,366 fetch: async () => Response.json({value: 1}),367 parseJson(text) {368 parseCount++;369 return JSON.parse(text);370 },371 }).json(), {instanceOf: ResponseSizeError});372 t.is(parseCount, 0);373});374375test('preserves custom parser errors for bodies within the limit', async t => {376 const parseError = new Error('Custom parser failed');377 const response = await ky(url, {378 maxResponseSize: 4,379 fetch: async () => new Response('null'),380 parseJson() {381 throw parseError;382 },383 });384 await t.throwsAsync(response.clone().json(), {is: parseError});385 await t.throwsAsync(response.json(), {is: parseError});386});387388test('preserves source stream errors instead of reporting a size failure', async t => {389 const streamError = new Error('Source stream failed');390 await t.throwsAsync(ky(url, {391 maxResponseSize: 4,392 fetch: async () => new Response(new ReadableStream<Uint8Array>({393 pull(controller) {394 controller.error(streamError);395 },396 })),397 }).text(), {is: streamError});398});399400test('allows beforeError to replace the size error without running twice', async t => {401 const replacementError = new Error('Response rejected by application');402 let errorCount = 0;403 await t.throwsAsync(ky(url, {404 maxResponseSize: 1,405 fetch: async () => new Response('large'),406 hooks: {407 beforeError: [({error}) => {408 t.true(error instanceof ResponseSizeError);409 errorCount++;410 return replacementError;411 }],412 },413 }).text(), {is: replacementError});414 t.is(errorCount, 1);415});416417test('size errors refer to the replacement request from beforeRequest', async t => {418 const replacement = new Request('https://example.com/replacement', {method: 'POST'});419 const error = await t.throwsAsync(ky(url, {420 maxResponseSize: 1,421 fetch: async () => new Response('large'),422 hooks: {423 beforeRequest: [() => replacement],424 },425 }).text(), {instanceOf: ResponseSizeError});426 t.is(error?.request.url, replacement.url);427 t.is(error?.request.method, 'POST');428});429430test('returns a streaming response before completion and forwards caller cancellation', async t => {431 t.timeout(2000);432 const cancellation = Promise.withResolvers<unknown>();433 const response = await ky(url, {434 maxResponseSize: 4,435 fetch: async () => new Response(new ReadableStream<Uint8Array>({436 start(controller) {437 controller.enqueue(new Uint8Array([1, 2]));438 // Leave the stream open to verify Ky does not wait for the whole body.439 },440 cancel(reason) {441 cancellation.resolve(reason);442 },443 })),444 });445 const reader = response.body!.getReader();446 const chunk = await reader.read();447 t.deepEqual(chunk, {done: false, value: new Uint8Array([1, 2])});448 await reader.cancel('No more data needed');449 t.is(await cancellation.promise, 'No more data needed');450});

Detect request stream support in Bun and Deno, and cover the pipeline with testsSindre Sorhusbefore adoption83c711c

lines 451–478why, one step back
451
452// Chromium and WebKit expose an empty body stream on responses whose status forbids a body, even though the `Response` constructor rejects such a body.453for (const status of [101, 103, 204, 205, 304]) {454 test(`passes through a browser-style empty body stream with status ${status}`, async t => {455 let progressCallCount = 0;456 const response = await ky(url, {457 maxResponseSize: 1,458 throwHttpErrors: false,459 onDownloadProgress() {460 progressCallCount++;461 },462 async fetch() {463 const emptyResponse = new Response(new ReadableStream({464 start(controller) {465 controller.close();466 },467 }), {headers: {'x-ky-header': 'ky'}});468 Object.defineProperty(emptyResponse, 'status', {value: status});469 return emptyResponse;470 },471 });472473 t.is(response.status, status);474 t.is(response.headers.get('x-ky-header'), 'ky');475 t.is(await response.text(), '');476 t.is(progressCallCount, 0);477 });478}

Skip wrapping a body a hook read, and read a past reset epoch as a timestampSindre Sorhusbefore adoption23ca564

lines 479–483why, one step back
479
480// Wrapping a body that a hook already read fails with \"The ReadableStream is locked\", which names neither the real mistake nor the option that caused it. The native \"Body is unusable\" error is far clearer, so the wrappers skip an already consumed body instead of crashing inside `pipeThrough()`.481for (const [label, options] of [482 ['without the limit', {}],483 ['with `maxResponseSize`', {maxResponseSize: 1000}],

Honour a late abort, count a no-op `content-encoding`, and keep wrapped headers immutableSindre Sorhusbefore adoption3f0e330

lines 484–490why, one step back
484 [
485 'with `onDownloadProgress`',486 {487 // Only the option's presence matters here.488 onDownloadProgress: () => undefined,489 },490 ],

Skip wrapping a body a hook read, and read a past reset epoch as a timestampSindre Sorhusbefore adoption23ca564

lines 491–509why, one step back
491] as Array<[string, Record<string, unknown>]>) {
492 test(`an afterResponse hook that returns a consumed response reports the native error ${label}`, async t => {493 const response = await ky(url, {494 ...options,495 fetch: async () => new Response('x'.repeat(50)),496 hooks: {497 afterResponse: [async ({response}) => {498 await response.text();499 return response;500 }],501 },502 });503504 await t.throwsAsync(response.text(), {505 name: 'TypeError',506 message: 'Body is unusable: Body has already been read',507 });508 });509}

Honour a late abort, count a no-op `content-encoding`, and keep wrapped headers immutableSindre Sorhusbefore adoption3f0e330

lines 510–568why, one step back
510
511// A reader taken with `getReader()` but never read leaves `bodyUsed` false, so the guard missed it and `pipeThrough()` failed with an error that names neither the mistake nor the option.512for (const [label, options] of [513 ['with `maxResponseSize`', {maxResponseSize: 1000}],514 [515 'with `onDownloadProgress`',516 {517 // Only the option's presence matters here.518 onDownloadProgress: () => undefined,519 },520 ],521] as Array<[string, Record<string, unknown>]>) {522 test(`a body that is only locked reports the native error ${label}`, async t => {523 const response = await ky(url, {524 ...options,525 async fetch() {526 const result = new Response('x'.repeat(50));527 result.body!.getReader();528 return result;529 },530 });531532 await t.throwsAsync(response.text(), {533 name: 'TypeError',534 message: 'Body is unusable: Body has already been read',535 });536 });537}538539// `new Response(body, response)` rebuilds the header list under the mutable "response" guard, so a network response that arrived immutable became mutable as soon as one of these options was set.540for (const [label, options] of [541 ['with `maxResponseSize`', {maxResponseSize: 1000}],542 ['with `onDownloadProgress`', {onDownloadProgress: () => undefined}],543] as Array<[string, Record<string, unknown>]>) {544 test(`response headers stay immutable ${label}`, async t => {545 const server = await createHttpTestServer(t);546 server.get('/', (_request, response) => {547 response.set('content-type', 'text/plain').end('payload');548 });549550 const response = await ky(server.url, options);551 t.true(response.headers.get('content-type')!.startsWith('text/plain'));552 t.throws(() => {553 response.headers.set('x-injected', '1');554 }, {instanceOf: TypeError});555 });556}557558test('response headers stay immutable without the wrapping options', async t => {559 const server = await createHttpTestServer(t);560 server.get('/', (_request, response) => {561 response.end('payload');562 });563564 const response = await ky(server.url);565 t.throws(() => {566 response.headers.set('x-injected', '1');567 }, {instanceOf: TypeError});568});

Release the body when a predicate throws, an abort wins, or a response cannot be decoratedSindre Sorhusbefore adoptiondeb5a33

line 569why, one step back
569