Skip to content
Myr

stream.ts

This file

Path

test/stream.ts

1,528 lines · 45.8 KiB · TypeScript

Last changed by

RefactorSindre Sorhusbefore adoptiona5ed57b

History of this file

Take it

1import test, {type ExecutionContext} from 'ava';2import ky, {isNetworkError, type Progress} from '../source/index.js';3import {createLargeBlob} from './helpers/create-large-file.js';4import {createHttpTestServer} from './helpers/create-http-test-server.js';5import {parseRawBody, parseJsonBody} from './helpers/parse-body.js';67test('extending with undefined progress callbacks disables inherited tracking', async t => {8	const server = await createHttpTestServer(t, {bodyParser: false});9	server.post('/', async (request, response) => {10		response.end(await parseRawBody(request));11	});1213	const instance = ky.create({14		onUploadProgress() {15			throw new Error('Inherited onUploadProgress must not run');16		},17		onDownloadProgress() {18			throw new Error('Inherited onDownloadProgress must not run');19		},20	}).extend({onUploadProgress: undefined, onDownloadProgress: undefined});2122	t.is(await instance.post(server.url, {body: 'payload'}).text(), 'payload');23});2425test('empty request body completes upload progress', async t => {26	const server = await createHttpTestServer(t, {bodyParser: false});27	server.post('/', async (request, response) => {28		response.json({body: await parseRawBody(request)});29	});3031	const progressEvents: Array<{progress: Progress; chunk: Uint8Array}> = [];32	const response = await ky33		.post(server.url, {34			body: '',35			onUploadProgress(progress, chunk) {36				progressEvents.push({progress, chunk});37			},38		})39		.json<{body: string}>();4041	t.is(response.body, '');42	t.deepEqual(progressEvents, [{43		progress: {percent: 1, totalBytes: 0, transferredBytes: 0},44		chunk: new Uint8Array(),45	}]);46});4748for (const retryLimit of [0, 1]) {49	test(`upload progress preserves referrer options with retry limit ${retryLimit}`, async t => {50		const referrer = 'https://example.com/source';51		const referrerPolicy = 'no-referrer';52		const requests: Array<{referrer: string; referrerPolicy: string}> = [];53		let completedUploads = 0;5455		const result = await ky.post('https://example.com', {56			body: 'payload',57			referrer,58			referrerPolicy,59			retry: {limit: retryLimit, methods: ['post'], delay: () => 0},60			async fetch(request) {61				requests.push({referrer: request.referrer, referrerPolicy: request.referrerPolicy});62				t.is(await request.text(), 'payload');63				return new Response('ok', {status: requests.length <= retryLimit ? 500 : 200});64			},65			onUploadProgress(progress) {66				if (progress.percent === 1) {67					completedUploads++;68				}69			},70		}).text();7172		t.is(result, 'ok');73		t.is(completedUploads, retryLimit + 1);74		t.deepEqual(requests, Array.from({length: retryLimit + 1}, () => ({referrer, referrerPolicy})));75	});76}7778for (const [name, options] of [79	['keepalive', {keepalive: true}],80	['no-cors', {mode: 'no-cors'}],81] as const) {82	test(`upload progress does not prevent ${name} requests`, async t => {83		const server = await createHttpTestServer(t, {bodyParser: false});84		server.post('/', async (request, response) => {85			response.end(await parseRawBody(request));86		});8788		let progressCalls = 0;89		const result = await ky.post(server.url, {90			...options,91			body: 'payload',92			onUploadProgress() {93				progressCalls++;94			},95		}).text();9697		t.is(result, 'payload');98		t.is(progressCalls, 0);99	});100}101102test('POST JSON with upload progress', async t => {103	const server = await createHttpTestServer(t, {bodyParser: false});104	server.post('/', async (request, response) => {105		response.json(await parseRawBody(request));106	});107108	const json = {test: 'test'};109	const data: Progress[] = [];110	const chunks: string[] = [];111	const responseJson = await ky112		.post(server.url, {113			json,114			onUploadProgress(progress, chunk) {115				data.push(progress);116				chunks.push(new TextDecoder().decode(chunk));117			},118		})119		.json();120121	// Check if we have at least two progress updates122	t.true(data.length > 0, 'Should have at least one progress update');123	t.deepEqual(124		chunks,125		[126			'{"test":"test"}',127		],128		'Should have chunks for all events',129	);130131	// Check the first progress update132	t.true(133		data[0].percent >= 0 && data[0].percent <= 1,134		'First update should have progress between 0 and 100%',135	);136	t.true(137		data[0].transferredBytes >= 0,138		'First update should have non-negative transferred bytes',139	);140141	// Check intermediate updates (if any)142	for (let i = 1; i < data.length - 1; i++) {143		t.true(144			data[i].percent >= data[i - 1].percent,145			`Update ${i} should have higher or equal percent than previous`,146		);147		t.true(148			data[i].transferredBytes >= data[i - 1].transferredBytes,149			`Update ${i} should have more or equal transferred bytes than previous`,150		);151	}152153	// Check the last progress update154	const lastUpdate = data.at(-1);155	t.is(lastUpdate.percent, 1, 'Last update should have 100% progress');156	t.true(157		lastUpdate.totalBytes > 0,158		'Last update should have positive total bytes',159	);160	t.is(161		lastUpdate.transferredBytes,162		lastUpdate.totalBytes,163		'Last update should have transferred all bytes',164	);165});166167test('multiple beforeRequest Request hooks do not duplicate upload progress events', async t => {168	const server = await createHttpTestServer(t, {bodyParser: false});169	server.post('/', async (request, response) => {170		response.json(await parseJsonBody<Record<string, unknown>>(request));171	});172173	let completedUploadProgressEvents = 0;174	const payload = {test: 'test'};175	const responseJson = await ky176		.post(server.url, {177			json: payload,178			hooks: {179				beforeRequest: [180					({request}) => {181						const headers = new Headers(request.headers);182						headers.set('x-hook-1', 'hook-1');183						return new Request(request, {headers});184					},185					({request}) => {186						const headers = new Headers(request.headers);187						headers.set('x-hook-2', 'hook-2');188						return new Request(request, {headers});189					},190				],191			},192			onUploadProgress(progress) {193				if (progress.percent === 1) {194					completedUploadProgressEvents++;195				}196			},197		})198		.json<Record<string, unknown>>();199200	t.deepEqual(responseJson, payload);201	t.is(completedUploadProgressEvents, 1);202});203204test('multiple beforeRequest Request hooks do not duplicate upload progress events across retries', async t => {205	const server = await createHttpTestServer(t, {bodyParser: false});206	let requestCount = 0;207	server.post('/', async (request, response) => {208		requestCount++;209		if (requestCount === 1) {210			response.status(500).json({error: 'retry'});211			return;212		}213214		response.json(await parseJsonBody<Record<string, unknown>>(request));215	});216217	const completedUploadProgressEventsPerAttempt: number[] = [0];218	const payload = {test: 'retry'};219	const responseJson = await ky220		.post(server.url, {221			json: payload,222			retry: {223				limit: 1,224				methods: ['post'],225			},226			hooks: {227				beforeRequest: [228					({request}) => {229						const headers = new Headers(request.headers);230						headers.set('x-hook-1', 'hook-1');231						return new Request(request, {headers});232					},233					({request}) => {234						const headers = new Headers(request.headers);235						headers.set('x-hook-2', 'hook-2');236						return new Request(request, {headers});237					},238				],239				beforeRetry: [240					() => {241						completedUploadProgressEventsPerAttempt.push(0);242					},243				],244			},245			onUploadProgress(progress) {246				if (progress.percent !== 1) {247					return;248				}249250				const currentAttemptIndex = completedUploadProgressEventsPerAttempt.length - 1;251				completedUploadProgressEventsPerAttempt[currentAttemptIndex]++;252			},253		})254		.json<Record<string, unknown>>();255256	t.deepEqual(responseJson, payload);257	t.deepEqual(completedUploadProgressEventsPerAttempt, [1, 1]);258});259260test('beforeRequest Request replacement preserves upload progress sizing', async t => {261	const server = await createHttpTestServer(t, {bodyParser: false});262	server.post('/', async (request, response) => {263		let totalBytes = 0;264		for await (const chunk of request) {265			totalBytes += chunk.length as number;266		}267268		response.json({receivedBytes: totalBytes});269	});270271	const largeBlob = createLargeBlob(10);272	const progressEvents: Progress[] = [];273	const response = await ky274		.post(server.url, {275			body: largeBlob,276			hooks: {277				beforeRequest: [278					({request}) => {279						const headers = new Headers(request.headers);280						headers.set('x-hook', '1');281						return new Request(request, {headers});282					},283				],284			},285			onUploadProgress(progress) {286				progressEvents.push(progress);287			},288		})289		.json<{receivedBytes: number}>();290291	t.true(progressEvents.length >= 2, 'Should produce multiple progress events');292	const nonFinalProgressEvents = progressEvents.filter(progress => progress.percent < 1);293	t.true(nonFinalProgressEvents.length > 0, 'Should include non-final progress events');294	for (const progress of nonFinalProgressEvents) {295		const expectedPercent = progress.transferredBytes / largeBlob.size;296		t.true(progress.percent <= expectedPercent + 0.01, 'Intermediate progress should reflect known body size');297	}298299	const finalProgress = progressEvents.at(-1);300	t.truthy(finalProgress);301	t.is(finalProgress!.percent, 1);302	t.true(finalProgress!.totalBytes > 1024 * 1024);303	t.is(finalProgress!.totalBytes, finalProgress!.transferredBytes);304	t.is(response.receivedBytes, finalProgress!.totalBytes);305});306307test('beforeRequest Request replacement with new body preserves upload progress sizing', async t => {308	const server = await createHttpTestServer(t, {bodyParser: false});309	server.post('/', async (request, response) => {310		let receivedBytes = 0;311		for await (const chunk of request) {312			receivedBytes += chunk.length as number;313		}314315		response.json({receivedBytes});316	});317318	const payload = {initial: true};319	const replacementBody = createLargeBlob(10);320	const progressEvents: Progress[] = [];321	const response = await ky322		.post(server.url, {323			json: payload,324			hooks: {325				beforeRequest: [326					({request}) => new Request(request, {body: replacementBody}),327				],328			},329			onUploadProgress(progress) {330				progressEvents.push(progress);331			},332		})333		.json<{receivedBytes: number}>();334335	t.true(progressEvents.length > 0, 'Should produce progress events');336	const expectedSize = replacementBody.size;337	const finalProgress = progressEvents.at(-1);338	t.truthy(finalProgress);339	t.is(finalProgress!.percent, 1);340	t.is(finalProgress!.totalBytes, expectedSize);341	t.is(finalProgress!.transferredBytes, expectedSize);342	t.is(response.receivedBytes, expectedSize);343});344345test('missing content-length still uses original body size for upload progress', async t => {346	const server = await createHttpTestServer(t, {bodyParser: false});347	server.post('/', async (request, response) => {348		let receivedBytes = 0;349		for await (const chunk of request) {350			receivedBytes += chunk.length as number;351		}352353		response.json({receivedBytes});354	});355356	const body = createLargeBlob(10);357	const progressEvents: Progress[] = [];358	const response = await ky359		.post(server.url, {360			body,361			hooks: {362				beforeRequest: [363					({request}) => {364						request.headers.delete('content-length');365					},366				],367			},368			onUploadProgress(progress) {369				progressEvents.push(progress);370			},371		})372		.json<{receivedBytes: number}>();373374	t.true(progressEvents.length >= 2, 'Should produce multiple progress events');375	const nonFinalProgressEvents = progressEvents.filter(progress => progress.percent < 1);376	t.true(nonFinalProgressEvents.length > 0, 'Should include non-final progress events');377	t.true(nonFinalProgressEvents[0].percent > 0, 'Non-final progress should use known total size');378379	const finalProgress = progressEvents.at(-1);380	t.truthy(finalProgress);381	t.is(finalProgress!.percent, 1);382	t.is(finalProgress!.totalBytes, body.size);383	t.is(finalProgress!.transferredBytes, body.size);384	t.is(response.receivedBytes, body.size);385});386387test('beforeRequest replacement with smaller body completes upload progress correctly', async t => {388	const server = await createHttpTestServer(t, {bodyParser: false});389	server.post('/', async (request, response) => {390		let receivedBytes = 0;391		for await (const chunk of request) {392			receivedBytes += chunk.length as number;393		}394395		response.json({receivedBytes});396	});397398	const originalBody = createLargeBlob(10);399	const replacementBody = 'small-body';400	const replacementBodySize = Buffer.byteLength(replacementBody);401	const progressEvents: Progress[] = [];402	const response = await ky403		.post(server.url, {404			body: originalBody,405			hooks: {406				beforeRequest: [407					({request}) => new Request(request, {body: replacementBody}),408				],409			},410			onUploadProgress(progress) {411				progressEvents.push(progress);412			},413		})414		.json<{receivedBytes: number}>();415416	t.true(progressEvents.length > 0, 'Should produce progress events');417	const nonFinalProgressEvents = progressEvents.filter(progress => progress.percent < 1);418	for (const progress of nonFinalProgressEvents) {419		t.true(progress.percent < 1, 'Intermediate progress should stay below completion');420	}421422	const finalProgress = progressEvents.at(-1);423	t.truthy(finalProgress);424	t.is(finalProgress!.percent, 1);425	t.is(finalProgress!.transferredBytes, replacementBodySize);426	t.is(response.receivedBytes, replacementBodySize);427});428429test('beforeRequest replacement with larger body has monotonic upload progress', async t => {430	const server = await createHttpTestServer(t, {bodyParser: false});431	server.post('/', async (request, response) => {432		let receivedBytes = 0;433		for await (const chunk of request) {434			receivedBytes += chunk.length as number;435		}436437		response.json({receivedBytes});438	});439440	const replacementBody = createLargeBlob(10);441	const progressEvents: Progress[] = [];442	const response = await ky443		.post(server.url, {444			body: 'tiny',445			hooks: {446				beforeRequest: [447					({request}) => new Request(request, {body: replacementBody}),448				],449			},450			onUploadProgress(progress) {451				progressEvents.push(progress);452			},453		})454		.json<{receivedBytes: number}>();455456	t.true(progressEvents.length > 0, 'Should produce progress events');457	for (let index = 1; index < progressEvents.length; index++) {458		t.true(progressEvents[index].transferredBytes >= progressEvents[index - 1].transferredBytes, 'Transferred bytes should be monotonic');459		t.true(progressEvents[index].percent >= progressEvents[index - 1].percent, 'Percent should be monotonic');460	}461462	const finalProgress = progressEvents.at(-1);463	t.truthy(finalProgress);464	t.is(finalProgress!.percent, 1);465	t.is(finalProgress!.transferredBytes, replacementBody.size);466	t.is(response.receivedBytes, replacementBody.size);467});468469test('beforeRequest body replacement followed by header hook keeps progress and headers', async t => {470	const server = await createHttpTestServer(t, {bodyParser: false});471	server.post('/', async (request, response) => {472		let receivedBytes = 0;473		for await (const chunk of request) {474			receivedBytes += chunk.length as number;475		}476477		response.json({478			receivedBytes,479			header: request.headers['x-hook-2'],480		});481	});482483	const replacementBody = 'hook-replacement-body';484	const replacementBodySize = Buffer.byteLength(replacementBody);485	const progressEvents: Progress[] = [];486	const response = await ky487		.post(server.url, {488			body: createLargeBlob(10),489			hooks: {490				beforeRequest: [491					({request}) => new Request(request, {body: replacementBody}),492					({request}) => {493						const headers = new Headers(request.headers);494						headers.set('x-hook-2', 'true');495						return new Request(request, {headers});496					},497				],498			},499			onUploadProgress(progress) {500				progressEvents.push(progress);501			},502		})503		.json<{receivedBytes: number; header: string | undefined}>();504505	const finalProgress = progressEvents.at(-1);506	t.truthy(finalProgress);507	t.is(finalProgress!.percent, 1);508	t.is(finalProgress!.transferredBytes, replacementBodySize);509	t.is(response.receivedBytes, replacementBodySize);510	t.is(response.header, 'true');511});512513test('retry with beforeRequest body changes tracks per-attempt upload progress', async t => {514	const server = await createHttpTestServer(t, {bodyParser: false});515	let requestCount = 0;516	server.post('/', async (_request, response) => {517		requestCount++;518		if (requestCount === 1) {519			response.status(500).json({error: 'retry'});520			return;521		}522523		response.status(200).json({ok: true});524	});525526	const firstAttemptBody = 'first-attempt';527	const secondAttemptBody = 'second-attempt-body';528	const firstAttemptBodySize = Buffer.byteLength(firstAttemptBody);529	const secondAttemptBodySize = Buffer.byteLength(secondAttemptBody);530	const eventsByAttempt: Progress[][] = [];531	let currentAttempt = 0;532533	await ky.post(server.url, {534		body: 'initial',535		retry: {536			limit: 1,537			methods: ['post'],538		},539		hooks: {540			beforeRequest: [541				({request, retryCount}) => {542					currentAttempt = retryCount;543					eventsByAttempt[currentAttempt] = [];544					return new Request(request, {body: firstAttemptBody});545				},546			],547			beforeRetry: [548				({request}) => {549					currentAttempt = 1;550					eventsByAttempt[currentAttempt] = [];551					return new Request(request, {body: secondAttemptBody});552				},553			],554		},555		onUploadProgress(progress) {556			eventsByAttempt[currentAttempt].push(progress);557		},558	}).json();559560	t.is(eventsByAttempt.length, 2);561	const firstAttemptFinalProgress = eventsByAttempt[0].at(-1);562	const secondAttemptFinalProgress = eventsByAttempt[1].at(-1);563	t.truthy(firstAttemptFinalProgress);564	t.truthy(secondAttemptFinalProgress);565	t.is(firstAttemptFinalProgress!.percent, 1);566	t.is(secondAttemptFinalProgress!.percent, 1);567	t.is(firstAttemptFinalProgress!.transferredBytes, firstAttemptBodySize);568	t.is(secondAttemptFinalProgress!.transferredBytes, secondAttemptBodySize);569	t.is(eventsByAttempt[0].filter(progress => progress.percent === 1).length, 1);570	t.is(eventsByAttempt[1].filter(progress => progress.percent === 1).length, 1);571});572573test('ReadableStream upload emits stable non-final progress and completes once', async t => {574	const server = await createHttpTestServer(t, {bodyParser: false});575	server.post('/', async (request, response) => {576		let receivedBytes = 0;577		for await (const chunk of request) {578			receivedBytes += chunk.length as number;579		}580581		response.json({receivedBytes});582	});583584	const streamBody = new ReadableStream<Uint8Array>({585		start(controller) {586			controller.enqueue(new TextEncoder().encode('chunk-1'));587			controller.enqueue(new TextEncoder().encode('chunk-2'));588			controller.close();589		},590	});591592	const progressEvents: Progress[] = [];593	const response = await ky594		.post(server.url, {595			body: streamBody,596			onUploadProgress(progress) {597				progressEvents.push(progress);598			},599		})600		.json<{receivedBytes: number}>();601602	t.true(progressEvents.length > 0, 'Should emit upload progress');603	const nonFinalProgressEvents = progressEvents.filter(progress => progress.percent < 1);604	t.true(nonFinalProgressEvents.length > 0, 'Should emit non-final progress');605	for (const progress of nonFinalProgressEvents) {606		t.true(progress.percent >= 0 && progress.percent < 1, 'Non-final progress should be within [0, 1)');607	}608609	const completedProgressEvents = progressEvents.filter(progress => progress.percent === 1);610	t.is(completedProgressEvents.length, 1, 'Should complete exactly once');611	const finalProgress = completedProgressEvents[0];612	t.is(finalProgress.transferredBytes, response.receivedBytes);613});614615test('empty response body completes download progress', async t => {616	const server = await createHttpTestServer(t);617	server.get('/', (_request, response) => {618		response.header('content-length', '0').end();619	});620621	const progressEvents: Array<{progress: Progress; chunk: Uint8Array}> = [];622	const responseText = await ky(server.url, {623		onDownloadProgress(progress, chunk) {624			progressEvents.push({progress, chunk});625		},626	}).text();627628	t.is(responseText, '');629	t.deepEqual(progressEvents, [{630		progress: {percent: 1, totalBytes: 0, transferredBytes: 0},631		chunk: new Uint8Array(),632	}]);633});634635test('onDownloadProgress preserves response url, redirected, and type', async t => {636	const server = await createHttpTestServer(t);637	server.get('/', (_request, response) => {638		response.end('ok');639	});640	server.get('/redirect', (_request, response) => {641		response.redirect(302, '/');642	});643644	const response = await ky(`${server.url}/redirect`, {645		// eslint-disable-next-line @typescript-eslint/no-empty-function646		onDownloadProgress() {},647	});648649	t.is(await response.text(), 'ok');650	t.is(response.url, `${server.url}/`);651	t.true(response.redirected);652	t.is(response.type, 'basic');653});654655test('onDownloadProgress preserves response metadata through repeated clones', async t => {656	const server = await createHttpTestServer(t);657	server.get('/', (_request, response) => {658		response.end('ok');659	});660	server.get('/redirect', (_request, response) => {661		response.redirect(302, '/');662	});663664	const progressEvents: Progress[] = [];665	const response = await ky(`${server.url}/redirect`, {666		onDownloadProgress(progress) {667			progressEvents.push(progress);668		},669	});670	const clone = response.clone();671	const nestedClone = clone.clone();672673	for (const currentResponse of [response, clone, nestedClone]) {674		t.is(currentResponse.url, `${server.url}/`);675		t.true(currentResponse.redirected);676		t.is(currentResponse.type, 'basic');677	}678679	t.deepEqual(await Promise.all([response.text(), clone.text(), nestedClone.text()]), ['ok', 'ok', 'ok']);680	t.is(progressEvents.filter(progress => progress.percent === 1).length, 1);681	t.throws(() => clone.clone(), {instanceOf: TypeError});682});683684test('onDownloadProgress keeps clone writable and configurable', async t => {685	const server = await createHttpTestServer(t);686	server.get('/', (_request, response) => {687		response.end('ok');688	});689690	const response = await ky(server.url, {691		// eslint-disable-next-line @typescript-eslint/no-empty-function692		onDownloadProgress() {},693	});694	const originalClone = response.clone;695	let cloneCallCount = 0;696697	response.clone = () => {698		cloneCallCount++;699		return originalClone();700	};701702	const clone = response.clone();703704	t.is(cloneCallCount, 1);705	t.is(await clone.text(), 'ok');706	t.true(Object.getOwnPropertyDescriptor(response, 'clone')?.configurable);707});708709test('onDownloadProgress preserves the final url and redirected state without redirects', async t => {710	const server = await createHttpTestServer(t);711	server.get('/', (_request, response) => {712		response.end('ok');713	});714715	const response = await ky(server.url, {716		searchParams: {foo: 'bar'},717		// eslint-disable-next-line @typescript-eslint/no-empty-function718		onDownloadProgress() {},719	});720721	t.is(await response.text(), 'ok');722	t.is(response.url, `${server.url}/?foo=bar`);723	t.false(response.redirected);724});725726test('onDownloadProgress consumes original response body', async t => {727	let originalResponse: Response | undefined;728	let didReportProgress = false;729730	const customFetch: typeof fetch = async request => {731		if (!(request instanceof Request)) {732			throw new TypeError('Expected input to be a Request');733		}734735		const responseBody = new ReadableStream<Uint8Array>({736			start(controller) {737				controller.enqueue(new TextEncoder().encode('ok'));738				controller.close();739			},740		});741742		const response = new Response(responseBody, {743			headers: {744				'content-length': '2',745			},746		});747		originalResponse = response;748749		return response;750	};751752	const responseText = await ky('https://example.com', {753		fetch: customFetch,754		onDownloadProgress() {755			didReportProgress = true;756		},757	}).text();758759	t.is(responseText, 'ok');760	t.true(originalResponse?.bodyUsed);761	t.true(didReportProgress);762});763764test('canceling a download with progress cancels its source without reporting completion', async t => {765	t.timeout(2000);766	const cancellation = Promise.withResolvers<void>();767	let reportedCompletion = false;768	const response = await ky('https://example.com', {769		maxResponseSize: 4,770		fetch: async () => new Response(new ReadableStream<Uint8Array>({771			start(controller) {772				controller.enqueue(new Uint8Array([1, 2]));773			},774			cancel() {775				cancellation.resolve();776			},777		})),778		onDownloadProgress({percent}) {779			reportedCompletion ||= percent === 1;780		},781	});782	const reader = response.body!.getReader();783	const chunk = await reader.read();784	t.deepEqual(chunk, {done: false, value: new Uint8Array([1, 2])});785	await reader.cancel();786	await cancellation.promise;787	t.false(reportedCompletion);788});789790test('forced retry custom request keeps upload progress', async t => {791	const server = await createHttpTestServer(t, {bodyParser: false});792	let requestCount = 0;793794	server.post('/', async (request, response) => {795		requestCount++;796797		if (requestCount === 1) {798			response.status(500).json({error: 'try again'});799			return;800		}801802		const body = await parseJsonBody<Record<string, unknown>>(request);803		response.json(body);804	});805806	const attemptEvents: Progress[][] = [];807	const payload = {payload: 'forced-retry'};808809	const responseJson = await ky810		.post(server.url, {811			json: payload,812			retry: {813				limit: 1,814				methods: ['post'],815			},816			hooks: {817				beforeRequest: [818					() => {819						attemptEvents.push([]);820					},821				],822				beforeRetry: [823					() => {824						attemptEvents.push([]);825					},826				],827				afterResponse: [828					async ({request, response}) => {829						if (response.status === 500) {830							return ky.retry({request: new Request(request)});831						}832					},833				],834			},835			onUploadProgress(progress) {836				const currentAttempt = attemptEvents.at(-1);837				if (!currentAttempt) {838					return;839				}840841				currentAttempt.push(progress);842			},843		})844		.json<Record<string, unknown>>();845846	t.deepEqual(responseJson, payload);847	t.is(attemptEvents.length, 2, 'Should attempt request twice');848849	for (const [index, events] of attemptEvents.entries()) {850		t.true(events.length > 0, `Attempt ${index + 1} should emit upload progress`);851		const last = events.at(-1);852		t.truthy(last);853		t.is(last!.percent, 1, `Attempt ${index + 1} progress should reach completion`);854855		// Verify gradual progress (not just 0% -> 100%)856		// With proper body size calculation, we should see intermediate progress events857		t.true(last!.totalBytes > 0, `Attempt ${index + 1} should have correct totalBytes (got ${last!.totalBytes})`);858		t.true(last!.transferredBytes > 0, `Attempt ${index + 1} should have transferredBytes`);859		t.is(last!.totalBytes, last!.transferredBytes, `Attempt ${index + 1} final totalBytes should equal transferredBytes`);860	}861});862863test('forced retry custom request has correct body size for upload progress', async t => {864	const server = await createHttpTestServer(t, {bodyParser: false});865	let requestCount = 0;866867	server.post('/', async (request, response) => {868		requestCount++;869870		if (requestCount === 1) {871			response.status(500).json({error: 'try again'});872			return;873		}874875		const body = await parseJsonBody<Record<string, unknown>>(request);876		response.json(body);877	});878879	const attemptTotalBytes: number[] = [];880	const payload = {data: 'x'.repeat(1000)}; // 1KB payload881882	await ky883		.post(server.url, {884			json: payload,885			retry: {886				limit: 1,887				methods: ['post'],888			},889			hooks: {890				afterResponse: [891					async ({request, response}) => {892						if (response.status === 500) {893							return ky.retry({request: new Request(request)});894						}895					},896				],897			},898			onUploadProgress(progress) {899				if (progress.percent === 1) {900					attemptTotalBytes.push(progress.totalBytes);901				}902			},903		})904		.json<Record<string, unknown>>();905906	t.is(attemptTotalBytes.length, 2, 'Should track totalBytes for both attempts');907908	// Both attempts should have the same totalBytes (proving body size is correctly preserved)909	t.is(attemptTotalBytes[0], attemptTotalBytes[1], 'Both attempts should have identical totalBytes');910911	// Verify totalBytes is non-zero (correct size calculation)912	t.true(attemptTotalBytes[0] > 1000, `totalBytes should be > 1000 (got ${attemptTotalBytes[0]})`);913});914915test('beforeRetry override updates upload progress after body change', async t => {916	const server = await createHttpTestServer(t, {bodyParser: false});917	let requestCount = 0;918919	server.post('/', async (request, response) => {920		requestCount++;921922		if (requestCount === 1) {923			response.status(500).json({error: 'retry'});924			return;925		}926927		const body = await parseJsonBody<Record<string, unknown>>(request);928		response.json(body);929	});930931	const firstPayload = {attempt: 'initial'};932	const updatedPayload = {attempt: 'retry', data: 'x'.repeat(2048)};933	const updatedPayloadString = JSON.stringify(updatedPayload);934	const attempts: Progress[][] = [];935936	const responseJson = await ky937		.post(server.url, {938			json: firstPayload,939			retry: {940				limit: 1,941				methods: ['post'],942			},943			hooks: {944				beforeRequest: [945					() => {946						attempts.push([]);947					},948				],949				beforeRetry: [950					({request}) => {951						attempts.push([]);952						return new Request(request, {body: updatedPayloadString});953					},954				],955			},956			onUploadProgress(progress) {957				const currentAttempt = attempts.at(-1);958				if (!currentAttempt) {959					return;960				}961962				currentAttempt.push(progress);963			},964		})965		.json<Record<string, unknown>>();966967	t.deepEqual(responseJson, updatedPayload);968	t.is(attempts.length, 2, 'Should perform two attempts');969970	const firstAttempt = attempts[0];971	const secondAttempt = attempts[1];972	t.truthy(firstAttempt);973	t.truthy(secondAttempt);974975	const firstFinal = firstAttempt.at(-1);976	const secondFinal = secondAttempt.at(-1);977	t.truthy(firstFinal);978	t.truthy(secondFinal);979980	t.is(firstFinal!.percent, 1);981	t.true(firstFinal!.totalBytes > 0);982	t.is(firstFinal!.totalBytes, firstFinal!.transferredBytes);983984	const expectedUpdatedTotal = Buffer.byteLength(updatedPayloadString);985	t.is(secondFinal!.percent, 1);986	t.is(secondFinal!.totalBytes, expectedUpdatedTotal, 'Retry should reflect new payload size');987	t.is(secondFinal!.transferredBytes, expectedUpdatedTotal);988});989990test('forced retry with custom request updates upload progress size', async t => {991	const server = await createHttpTestServer(t, {bodyParser: false});992	let requestCount = 0;993994	server.post('/', async (request, response) => {995		requestCount++;996997		if (requestCount === 1) {998			response.status(500).json({error: 'forced-retry'});999			return;1000		}10011002		const body = await parseJsonBody<Record<string, unknown>>(request);1003		response.json(body);1004	});10051006	const firstPayload = {attempt: 'initial'};1007	const updatedPayload = {attempt: 'forced', data: 'y'.repeat(3072)};1008	const updatedPayloadString = JSON.stringify(updatedPayload);1009	const attempts: Progress[][] = [];10101011	const responseJson = await ky1012		.post(server.url, {1013			json: firstPayload,1014			retry: {1015				limit: 1,1016				methods: ['post'],1017			},1018			hooks: {1019				beforeRequest: [1020					() => {1021						attempts.push([]);1022					},1023				],1024				beforeRetry: [1025					() => {1026						attempts.push([]);1027					},1028				],1029				afterResponse: [1030					async ({request, response}) => {1031						if (response.status === 500) {1032							return ky.retry({1033								request: new Request(request, {body: updatedPayloadString}),1034							});1035						}1036					},1037				],1038			},1039			onUploadProgress(progress) {1040				const currentAttempt = attempts.at(-1);1041				if (!currentAttempt) {1042					return;1043				}10441045				currentAttempt.push(progress);1046			},1047		})1048		.json<Record<string, unknown>>();10491050	t.deepEqual(responseJson, updatedPayload);1051	t.is(attempts.length, 2, 'Should perform two attempts');10521053	const firstAttempt = attempts[0];1054	const secondAttempt = attempts[1];1055	t.truthy(firstAttempt);1056	t.truthy(secondAttempt);10571058	const firstFinal = firstAttempt.at(-1);1059	const secondFinal = secondAttempt.at(-1);1060	t.truthy(firstFinal);1061	t.truthy(secondFinal);10621063	t.is(firstFinal!.percent, 1);1064	t.true(firstFinal!.totalBytes > 0);1065	t.is(firstFinal!.totalBytes, firstFinal!.transferredBytes);10661067	const expectedUpdatedTotal = Buffer.byteLength(updatedPayloadString);1068	t.is(secondFinal!.percent, 1);1069	t.is(secondFinal!.totalBytes, expectedUpdatedTotal, 'Forced retry should reflect new payload size');1070	t.is(secondFinal!.transferredBytes, expectedUpdatedTotal);1071});10721073test('POST FormData with 10MB file upload progress', async t => {1074	const server = await createHttpTestServer(t, {bodyParser: false});1075	server.post('/', async (request, response) => {1076		let totalBytes = 0;1077		for await (const chunk of request) {1078			totalBytes += chunk.length as number;1079		}10801081		response.json({receivedBytes: totalBytes});1082	});10831084	const largeBlob = createLargeBlob(10); // 10MB Blob1085	const formData = new FormData();1086	formData.append('file', largeBlob, 'large-file.bin');10871088	const data: Array<{1089		percent: number;1090		transferredBytes: number;1091		totalBytes: number;1092	}> = [];1093	const response = await ky1094		.post(server.url, {1095			body: formData,1096			onUploadProgress(progress) {1097				data.push(progress);1098			},1099		})1100		.json<{receivedBytes: number}>();11011102	// Check if we have at least two progress updates1103	t.true(data.length >= 2, 'Should have at least two progress updates');11041105	// Check the first progress update1106	t.true(1107		data[0].percent >= 0 && data[0].percent < 1,1108		'First update should have progress between 0 and 100%',1109	);1110	t.true(1111		data[0].transferredBytes >= 0,1112		'First update should have non-negative transferred bytes',1113	);11141115	// Check intermediate updates (if any)1116	for (let i = 1; i < data.length - 1; i++) {1117		t.true(1118			data[i].percent >= data[i - 1].percent,1119			`Update ${i} should have higher or equal percent than previous`,1120		);1121		t.true(1122			data[i].transferredBytes >= data[i - 1].transferredBytes,1123			`Update ${i} should have more or equal transferred bytes than previous`,1124		);1125	}11261127	// Check the last progress update1128	const lastUpdate = data.at(-1);1129	t.is(lastUpdate.percent, 1, 'Last update should have 100% progress');1130	t.true(1131		lastUpdate.totalBytes > 0,1132		'Last update should have positive total bytes',1133	);1134	t.is(1135		lastUpdate.transferredBytes,1136		lastUpdate.totalBytes,1137		'Last update should have transferred all bytes',1138	);1139});11401141test('completed download progress uses actual bytes rather than an overestimated content length', async t => {1142	const progressEvents: Progress[] = [];1143	const text = await ky('https://example.com', {1144		fetch: async () => new Response('ok', {headers: {'content-length': '1024'}}),1145		onDownloadProgress(progress) {1146			progressEvents.push(progress);1147		},1148	}).text();11491150	t.is(text, 'ok');1151	t.deepEqual(progressEvents.at(-1), {1152		percent: 1,1153		transferredBytes: 2,1154		totalBytes: 2,1155	});1156});11571158test('completed upload progress uses the actual size of a replaced body', async t => {1159	const progressEvents: Progress[] = [];1160	const originalBody = 'x'.repeat(1024);1161	const replacementBody = 'ok';1162	const text = await ky.post('https://example.com', {1163		body: originalBody,1164		retry: 0,1165		hooks: {1166			beforeRequest: [({request}) => new Request(request, {body: replacementBody})],1167		},1168		async fetch(request) {1169			return new Response(await request.text());1170		},1171		onUploadProgress(progress) {1172			progressEvents.push(progress);1173		},1174	}).text();11751176	t.is(text, replacementBody);1177	t.deepEqual(progressEvents.at(-1), {1178		percent: 1,1179		transferredBytes: 2,1180		totalBytes: 2,1181	});1182});11831184// A server that records how many upload requests reached it.1185const createUploadProgressTestServer = async (t: ExecutionContext) => {1186	let requestCount = 0;1187	const server = await createHttpTestServer(t, {bodyParser: false});1188	server.post('/', async (request, response) => {1189		requestCount++;1190		await parseRawBody(request);1191		response.end('ok');1192	});11931194	return {server, getRequestCount: () => requestCount};1195};11961197// Upload progress runs inside the request body stream, and the runtime reports a failed body stream as a network failure. The readme documents this, so the callback error is only reachable through the `cause` chain.1198test('a throwing upload progress callback fails the request as a network error', async t => {1199	const {server, getRequestCount} = await createUploadProgressTestServer(t);12001201	const callbackError = new Error('upload progress failed');1202	const error = await t.throwsAsync(ky.post(server.url, {1203		body: 'x'.repeat(1024),1204		retry: 0,1205		onUploadProgress() {1206			throw callbackError;1207		},1208	}).text());12091210	t.true(isNetworkError(error));1211	t.is((error?.cause as Error | undefined)?.cause, callbackError);1212	t.is(getRequestCount(), 0);1213});12141215test('a throwing download progress callback propagates its own error', async t => {1216	const server = await createHttpTestServer(t);1217	server.get('/', (_request, response) => {1218		response.end('body');1219	});12201221	const callbackError = new Error('download progress failed');1222	const error = await t.throwsAsync(ky(server.url, {1223		retry: 0,1224		onDownloadProgress() {1225			throw callbackError;1226		},1227	}).text());12281229	t.is(error, callbackError);1230	t.false(isNetworkError(error));1231});12321233test('a response from a beforeRequest hook still reports download progress', async t => {1234	const progressEvents: Progress[] = [];1235	const text = await ky('https://example.com', {1236		hooks: {beforeRequest: [() => new Response('abc')]},1237		onDownloadProgress: progress => progressEvents.push(progress),1238		fetch: async () => new Response('from fetch'),1239	}).text();12401241	t.is(text, 'abc');1242	t.deepEqual(progressEvents.at(-1), {percent: 1, transferredBytes: 3, totalBytes: 3});1243});12441245// `Progress.totalBytes` is documented to be `0` when the total size cannot be determined, and it must agree with the `percent` it is reported with, which is computed from the same estimate.1246test('download progress reports an unknown total as 0', async t => {1247	const progressEvents: Progress[] = [];1248	const text = await ky('https://example.com', {1249		retry: 0,1250		fetch: async () => new Response(new ReadableStream<Uint8Array>({1251			start(controller) {1252				controller.enqueue(new TextEncoder().encode('ab'));1253				controller.enqueue(new TextEncoder().encode('cd'));1254				controller.close();1255			},1256		}), {headers: {'content-type': 'text/plain'}}),1257		onDownloadProgress(progress) {1258			progressEvents.push(progress);1259		},1260	}).text();12611262	t.is(text, 'abcd');1263	t.deepEqual(progressEvents.at(0), {percent: 0, transferredBytes: 2, totalBytes: 0});1264	t.deepEqual(progressEvents.at(-1), {percent: 1, transferredBytes: 4, totalBytes: 4});1265});12661267test('download progress keeps reporting the estimate when it is smaller than the bytes transferred', async t => {1268	const progressEvents: Progress[] = [];1269	await ky('https://example.com', {1270		retry: 0,1271		fetch: async () => new Response(new ReadableStream<Uint8Array>({1272			start(controller) {1273				controller.enqueue(new TextEncoder().encode('ab'));1274				controller.enqueue(new TextEncoder().encode('cd'));1275				controller.close();1276			},1277		}), {headers: {'content-type': 'text/plain', 'content-length': '2'}}),1278		onDownloadProgress(progress) {1279			progressEvents.push(progress);1280		},1281	}).text();12821283	t.deepEqual(progressEvents.at(0), {1284		// The size estimate is exceeded, so `percent` is capped just below 1 instead of reporting completion.1285		percent: 1 - Number.EPSILON,1286		transferredBytes: 2,1287		totalBytes: 2,1288	});1289});12901291// `content-length` is the size of the encoded body on the wire, while the progress stream counts the bytes after decompression. Trusting it made every event report 100% for a compressed response, so a progress bar was useless for exactly the responses that are large enough to need one.1292test('download progress does not trust content-length for a compressed response', async t => {1293	const progressEvents: Progress[] = [];1294	const text = await ky('https://example.com', {1295		async fetch() {1296			const body = new ReadableStream<Uint8Array>({1297				start(controller) {1298					for (let index = 0; index < 8; index++) {1299						controller.enqueue(new Uint8Array(1024));1300					}13011302					controller.close();1303				},1304			});13051306			return new Response(body, {headers: {'content-length': '64', 'content-encoding': 'gzip'}});1307		},1308		onDownloadProgress(progress) {1309			progressEvents.push(progress);1310		},1311	}).text();13121313	t.is(text.length, 8192);1314	t.true(progressEvents.length > 1);1315	// The encoded size is not a usable total, so it is reported as unknown instead of pinning every event to ~100%.1316	for (const event of progressEvents.slice(0, -1)) {1317		t.is(event.percent, 0);1318		t.is(event.totalBytes, 0);1319	}13201321	t.deepEqual(progressEvents.at(-1), {1322		percent: 1,1323		transferredBytes: 8192,1324		totalBytes: 8192,1325	});1326});13271328test('download progress still uses content-length for an uncompressed response', async t => {1329	const progressEvents: Progress[] = [];1330	const text = await ky('https://example.com', {1331		fetch: async () => new Response('x'.repeat(64), {headers: {'content-length': '64'}}),1332		onDownloadProgress(progress) {1333			progressEvents.push(progress);1334		},1335	}).text();13361337	t.is(text.length, 64);1338	t.is(progressEvents.at(-1)?.totalBytes, 64);1339});13401341// A coding list that mentions `identity` alongside a real coding is still content-coded, so the encoded length cannot be used.1342test('download progress reports an unknown total for a multi-coding content-encoding', async t => {1343	const progressEvents: Progress[] = [];1344	const text = await ky('https://example.com', {1345		async fetch() {1346			const body = new ReadableStream<Uint8Array>({1347				start(controller) {1348					for (let index = 0; index < 8; index++) {1349						controller.enqueue(new Uint8Array(1024));1350					}13511352					controller.close();1353				},1354			});1355			return new Response(body, {headers: {'content-length': '64', 'content-encoding': 'identity, gzip'}});1356		},1357		onDownloadProgress(progress) {1358			progressEvents.push(progress);1359		},1360	}).text();13611362	t.is(text.length, 8192);1363	for (const event of progressEvents.slice(0, -1)) {1364		t.is(event.totalBytes, 0);1365	}13661367	t.deepEqual(progressEvents.at(-1), {percent: 1, totalBytes: 8192, transferredBytes: 8192});1368});13691370// `content-encoding: identity` is a registered no-op coding (RFC 9110 §8.4.2), so `content-length` is the decoded length and remains a valid total, as it is for a response with no `content-encoding` at all.1371for (const [label, headers] of [1372	['no content-encoding', {}],1373	['content-encoding: identity', {'content-encoding': 'identity'}],1374	['content-encoding: Identity', {'content-encoding': 'Identity'}],1375	['an empty content-encoding', {'content-encoding': ''}],1376] as Array<[string, Record<string, string>]>) {1377	test(`download progress uses content-length with ${label}`, async t => {1378		const progressEvents: Progress[] = [];1379		const text = await ky('https://example.com', {1380			async fetch() {1381				const body = new ReadableStream<Uint8Array>({1382					start(controller) {1383						for (let index = 0; index < 8; index++) {1384							controller.enqueue(new Uint8Array(1024));1385						}13861387						controller.close();1388					},1389				});1390				return new Response(body, {headers: {'content-length': '8192', ...headers}});1391			},1392			onDownloadProgress(progress) {1393				progressEvents.push(progress);1394			},1395		}).text();13961397		t.is(text.length, 8192);1398		t.is(progressEvents.at(-1)?.totalBytes, 8192);1399		t.is(progressEvents[0]?.totalBytes, 8192);1400		// 1024 of 8192 bytes on the first event, so the percentage has to climb from there.1401		t.is(progressEvents[0]?.percent, 0.125);1402	});1403}14041405// A `ReadableStream` body measures 0, so the upload estimate stayed 0 and the percentage never moved, even when the request itself declared a `content-length`. The download path already falls back to that header.1406test('upload progress uses a declared content-length when the body size is unknown', async t => {1407	const progressEvents: Progress[] = [];1408	let body = '';14091410	await ky.post('https://example.com', {1411		body: new ReadableStream<Uint8Array>({1412			start(controller) {1413				controller.enqueue(new TextEncoder().encode('a'.repeat(1024)));1414				controller.enqueue(new TextEncoder().encode('a'.repeat(1024)));1415				controller.close();1416			},1417		}),1418		headers: {'content-length': '2048'},1419		retry: 0,1420		async fetch(request) {1421			body = await request.clone().text();1422			return new Response('ok');1423		},1424		onUploadProgress(progress) {1425			progressEvents.push(progress);1426		},1427	}).text();14281429	t.is(body.length, 2048);1430	t.deepEqual(progressEvents.at(-1), {percent: 1, totalBytes: 2048, transferredBytes: 2048});1431	t.is(progressEvents[0]?.totalBytes, 2048);1432	t.true(progressEvents[0]!.percent > 0, 'the first event should not sit at 0%');1433});14341435test('upload progress still prefers the body it can measure', async t => {1436	const progressEvents: Progress[] = [];14371438	await ky.post('https://example.com', {1439		body: 'x'.repeat(10),1440		headers: {'content-length': '2048'},1441		retry: 0,1442		async fetch(request) {1443			await request.text();1444			return new Response('ok');1445		},1446		onUploadProgress(progress) {1447			progressEvents.push(progress);1448		},1449	}).text();14501451	t.is(progressEvents.at(-1)?.totalBytes, 10);1452});14531454// The byte accounting holds the last chunk back so the final event can report the real total, which means an intermediate event is attributed to the previous chunk. Chunks of differing sizes are what pins that down, and an estimate below the delivered size is what makes the reported total grow.1455test('progress attributes bytes to the chunk before the one arriving', async t => {1456	const chunkSizes = [10, 30, 20, 40];1457	const chunks: number[] = [];1458	const transferred: number[] = [];1459	const totals: number[] = [];14601461	const text = await ky('https://example.com', {1462		async fetch() {1463			const body = new ReadableStream<Uint8Array>({1464				start(controller) {1465					for (const size of chunkSizes) {1466						controller.enqueue(new Uint8Array(size));1467					}14681469					controller.close();1470				},1471			});1472			// A total below the delivered size, so the reported total has to grow.1473			return new Response(body, {headers: {'content-length': '1'}});1474		},1475		onDownloadProgress({totalBytes, transferredBytes}, chunk) {1476			chunks.push(chunk.byteLength);1477			transferred.push(transferredBytes);1478			totals.push(totalBytes);1479		},1480	}).text();14811482	t.is(text.length, 100);1483	// Each event carries the chunk it was counted for, so the sizes run one behind the arrival order.1484	t.deepEqual(chunks, chunkSizes);1485	t.deepEqual(transferred, [10, 40, 60, 100]);1486	// Each intermediate event reports the running total, which starts below the estimate and grows past it.1487	t.deepEqual(totals, [10, 40, 60, 100]);1488});14891490test('download progress stays silent for a HEAD response', async t => {1491	const server = await createHttpTestServer(t);1492	server.head('/', (_request, response) => {1493		response.setHeader('content-length', '1000');1494		response.end();1495	});14961497	let calls = 0;1498	const result = await ky.head(server.url, {1499		onDownloadProgress() {1500			calls++;1501		},1502	});15031504	t.is(result.status, 200);1505	t.is(result.headers.get('content-length'), '1000');1506	t.is(calls, 0);1507});15081509// The response wrappers already skip a body a hook read, so the native error names the mistake. The upload wrapper did not, and failed with "The ReadableStream is locked" instead.1510test('upload progress leaves a request body that a hook already read to the native error', async t => {1511	const run = async (onUploadProgress?: () => void) => t.throwsAsync(ky.post('https://example.com', {1512		body: 'x',1513		retry: 0,1514		onUploadProgress,1515		fetch: async input => new Response(await (input as Request).text()),1516		hooks: {1517			beforeRequest: [async ({request}) => {1518				await request.text();1519			}],1520		},1521	}).text());15221523	const withoutProgress = await run();1524	const withProgress = await run(() => undefined);15251526	t.truthy(withoutProgress?.message);1527	t.is(withProgress?.message, withoutProgress?.message);1528});