browser.ts
This file
Path
test/browser.ts
905 lines · 25.7 KiB · TypeScript
Last changed by
Let a `beforeRetry` hook change per-attempt optionsSindre Sorhusbefore adoption242c327
History of this fileTake it
The walk stopped after 200 commits: lines older than 37fc250 point at it.
Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 1–3why, one step back1import test, {type ExecutionContext} from 'ava';2import busboy from 'busboy';3import express from 'express';Gracefully ignore `onUploadProgress` when request streams are unsupported (#845)Sindre Sorhusbefore adoption1e38ff4
lines 4–8why, one step back4import {5 chromium,6 webkit,7 type Page,8} from 'playwright';Require Node.js 22Sindre Sorhusbefore adoptionf1da0fc
lines 9–10why, one step back9import type ky from '../source/index.js';10import type {Progress} from '../source/index.js';Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 11–41why, one step back11import {createHttpTestServer, type ExtendedHttpTestServer, type HttpServerOptions} from './helpers/create-http-test-server.js';12import {parseRawBody} from './helpers/parse-body.js';13import {browserTest, defaultBrowsersTest} from './helpers/with-page.js';1415declare global {16 // eslint-disable-next-line @typescript-eslint/consistent-type-definitions17 interface Window {18 ky: typeof ky;19 }20}2122const DIST_DIR = new URL('../distribution', import.meta.url).toString();23const createEsmTestServer = async (options?: HttpServerOptions) => {24 const server = await createHttpTestServer(options);25 server.use('/distribution', express.static(DIST_DIR.replace(/^file:\/\//, '')));26 server.use((_, response, next) => {27 response.set('Connection', 'close');28 next();29 });30 return server;31};3233const KY_SCRIPT = {34 type: 'module',35 content: `36 import ky from '/distribution/index.js';37 globalThis.ky = ky;38 `,39};40const addKyScriptToPage = async (page: Page) => {41 await page.addScriptTag(KY_SCRIPT);Require Node.js 22Sindre Sorhusbefore adoptionf1da0fc
line 42why, one step back42 await page.waitForFunction(() => typeof globalThis.ky === 'function');Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 43–53why, one step back43};4445let server: ExtendedHttpTestServer;46test.beforeEach(async () => {47 server = await createEsmTestServer();48});4950test.afterEach(async () => {51 await server.close();52});53Add `maxResponseSize` optionSindre Sorhusbefore adoption0d59458
lines 54–88why, one step back54defaultBrowsersTest('maxResponseSize limits response bytes', async (t, page) => {55 server.get('/', (_request, response) => {56 response.end('🦄');57 });5859 await page.goto(server.url);60 await addKyScriptToPage(page);6162 const result = await page.evaluate(async (url: string) => {63 const text = await globalThis.ky(url, {maxResponseSize: 4}).text();64 let errorName: string | undefined;65 let hookErrorName: string | undefined;66 try {67 await globalThis.ky(url, {68 maxResponseSize: 3,69 hooks: {70 afterResponse: [async ({response}) => {71 await response.text();72 }],73 beforeError: [({error}) => {74 hookErrorName = error.name;75 return error;76 }],77 },78 });79 } catch (error) {80 errorName = (error as Error).name;81 }8283 return {text, errorName, hookErrorName};84 }, server.url);8586 t.deepEqual(result, {text: '🦄', errorName: 'ResponseSizeError', hookErrorName: 'ResponseSizeError'});87});88Preserve a user cancellation across retry decisions and report the bytes that arrivedSindre Sorhusbefore adoptionde278ae
lines 89–111why, one step back89defaultBrowsersTest('maxResponseSize passes through a 204 response', async (t, page) => {90 server.get('/', (_request, response) => {91 response.end('meow');92 });9394 server.get('/empty', (_request, response) => {95 response.status(204).header('X-ky-Header', 'ky').end();96 });9798 await page.goto(server.url);99 await addKyScriptToPage(page);100101 // Chromium exposes a body stream on 204 responses even though the `Response` constructor rejects a body for that status.102 const result = await page.evaluate(async (url: string) => {103 const response = await globalThis.ky(`${url}/empty`, {maxResponseSize: 1024});104 return {105 status: response.status,106 header: response.headers.get('X-ky-Header'),107 text: await response.text(),108 };109 }, server.url);110111 t.deepEqual(result, {status: 204, header: 'ky', text: ''});Improve docsSindre Sorhusbefore adoption8778439
lines 112–141why, one step back112});113114// WebKit exposes a body for `205 Reset Content`, which the Fetch spec lists as a null body status. Ky cannot wrap such a response, because the `Response` constructor rejects a body for those statuses, so `maxResponseSize` and `onDownloadProgress` do not apply to it.115browserTest('maxResponseSize does not apply to a 205 response body in WebKit', [webkit], async (t, page) => {116 server.get('/', (_request, response) => {117 response.end('ok');118 });119120 server.get('/reset', (_request, response) => {121 response.writeHead(205, {'content-type': 'text/plain', 'content-length': '4'});122 response.end('abcd');123 });124125 await page.goto(server.url);126 await addKyScriptToPage(page);127128 const result = await page.evaluate(async (url: string) => {129 let progressCalls = 0;130 const response = await globalThis.ky(url, {131 maxResponseSize: 1,132 retry: 0,133 onDownloadProgress() {134 progressCalls++;135 },136 });137138 return {status: response.status, text: await response.text(), progressCalls};139 }, `${server.url}/reset`);140141 t.deepEqual(result, {status: 205, text: 'abcd', progressCalls: 0});Preserve a user cancellation across retry decisions and report the bytes that arrivedSindre Sorhusbefore adoptionde278ae
lines 142–143why, one step back142});143Add `maxResponseSize` optionSindre Sorhusbefore adoption0d59458
lines 144–196why, one step back144defaultBrowsersTest('maxResponseSize preserves errors in native body methods and progress wrappers', async (t, page) => {145 server.get('/', (_request, response) => {146 response.end('ok');147 });148 server.get('/data', (_request, response) => {149 response.set('content-type', 'application/x-www-form-urlencoded').end('a=1');150 });151152 await page.goto(server.url);153 await addKyScriptToPage(page);154155 const errors = await page.evaluate(async (url: string) => {156 const errors: Array<string | undefined> = [];157 for (const method of ['text', 'json', 'arrayBuffer', 'blob', 'formData', 'bytes'] as const) {158 if (typeof Response.prototype[method] !== 'function') {159 continue;160 }161162 // eslint-disable-next-line no-await-in-loop163 const response = await globalThis.ky(`${url}/data`, {164 maxResponseSize: 1,165 hooks: {166 afterResponse: [({response}) => {167 // Exercise both branches of a native clone before wrapping the shared body.168 void response.clone().body?.cancel();169 return new Response(response.body, response);170 }],171 },172 onDownloadProgress() {173 return undefined;174 },175 });176177 for (const body of [response.clone(), response]) {178 let errorName: string | undefined;179 try {180 // eslint-disable-next-line no-await-in-loop181 await body[method]();182 } catch (error) {183 errorName = (error as Error).name;184 }185186 errors.push(errorName);187 }188 }189190 return errors;191 }, server.url);192193 t.true(errors.length >= 10);194 t.true(errors.every(name => name === 'ResponseSizeError'));195});196Add `baseUrl` option, rename `prefixUrl` to `prefix`, and allow leading slashes in input (#606)Seth Holladaybefore adoption1f2ad7f
line 197why, one step back197defaultBrowsersTest('baseUrl option', async (t: ExecutionContext, page: Page) => {Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 198–201why, one step back198 server.get('/', (_request, response) => {199 response.end('zebra');200 });201Add `baseUrl` option, rename `prefixUrl` to `prefix`, and allow leading slashes in input (#606)Seth Holladaybefore adoption1f2ad7f
lines 202–205why, one step back202 server.get('/unicorn', (_request, response) => {203 response.end('charlie');204 });205Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 206–212why, one step back206 server.get('/api/unicorn', (_request, response) => {207 response.end('rainbow');208 });209210 await page.goto(server.url);211 await addKyScriptToPage(page);212Add `baseUrl` option, rename `prefixUrl` to `prefix`, and allow leading slashes in input (#606)Seth Holladaybefore adoption1f2ad7f
lines 213–214why, one step back213 const results = await page.evaluate(async (url: string) => Promise.all([214 globalThis.ky(`${url}/api/unicorn`).text(),TweaksSindre Sorhusbefore adoption3ded2aa
line 215why, one step back215 globalThis.ky(`${url}/api/unicorn`, {baseUrl: undefined}).text(),Add `baseUrl` option, rename `prefixUrl` to `prefix`, and allow leading slashes in input (#606)Seth Holladaybefore adoption1f2ad7f
lines 216–221why, one step back216 globalThis.ky('api/unicorn', {baseUrl: url}).text(),217 globalThis.ky('unicorn', {baseUrl: `${url}/api`}).text(),218 globalThis.ky('/unicorn', {baseUrl: `${url}/api`}).text(),219 globalThis.ky('unicorn', {baseUrl: `${url}/api/`}).text(),220 globalThis.ky('/unicorn', {baseUrl: `${url}/api/`}).text(),221 ]), server.url);Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 222why, one step back222Add `baseUrl` option, rename `prefixUrl` to `prefix`, and allow leading slashes in input (#606)Seth Holladaybefore adoption1f2ad7f
lines 223–237why, one step back223 t.deepEqual(results, ['rainbow', 'rainbow', 'rainbow', 'charlie', 'charlie', 'rainbow', 'charlie']);224});225226defaultBrowsersTest('prefix option', async (t: ExecutionContext, page: Page) => {227 server.get('/', (_request, response) => {228 response.end('zebra');229 });230231 server.get('/api/unicorn', (_request, response) => {232 response.end('rainbow');233 });234235 await page.goto(server.url);236 await addKyScriptToPage(page);237Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 238why, one step back238 const results = await page.evaluate(async (url: string) => Promise.all([Require Node.js 22Sindre Sorhusbefore adoptionf1da0fc
line 239why, one step back239 globalThis.ky(`${url}/api/unicorn`).text(),TweaksSindre Sorhusbefore adoption3ded2aa
line 240why, one step back240 globalThis.ky(`${url}/api/unicorn`, {prefix: undefined}).text(),Add `baseUrl` option, rename `prefixUrl` to `prefix`, and allow leading slashes in input (#606)Seth Holladaybefore adoption1f2ad7f
lines 241–245why, one step back241 globalThis.ky('api/unicorn', {prefix: url}).text(),242 globalThis.ky('unicorn', {prefix: `${url}/api`}).text(),243 globalThis.ky('/unicorn', {prefix: `${url}/api`}).text(),244 globalThis.ky('unicorn', {prefix: `${url}/api/`}).text(),245 globalThis.ky('/unicorn', {prefix: `${url}/api/`}).text(),Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 246–247why, one step back246 ]), server.url);247Add `baseUrl` option, rename `prefixUrl` to `prefix`, and allow leading slashes in input (#606)Seth Holladaybefore adoption1f2ad7f
line 248why, one step back248 t.deepEqual(results, ['rainbow', 'rainbow', 'rainbow', 'rainbow', 'rainbow', 'rainbow', 'rainbow']);Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 249–250why, one step back249});250Add QUERY method support (#873)Sindre Sorhusbefore adoption6edddd9
lines 251–277why, one step back251defaultBrowsersTest('QUERY request', async (t: ExecutionContext, page: Page) => {252 t.plan(2);253254 server.get('/', (_request, response) => {255 response.end();256 });257258 server.all('/test', (request, response) => {259 t.is(request.method, 'QUERY');260 response.json(request.body);261 });262263 await page.goto(server.url);264 await addKyScriptToPage(page);265266 const json = {267 foo: true,268 };269270 const result = await page.evaluate(async ({url, json}) => globalThis.ky.query(`${url}/test`, {json}).json(), {271 url: server.url,272 json,273 });274275 t.deepEqual(result, json);276});277Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 278–293why, one step back278defaultBrowsersTest('aborting a request', async (t: ExecutionContext, page: Page) => {279 server.get('/', (_request, response) => {280 response.end('meow');281 });282283 server.get('/test', (_request, response) => {284 setTimeout(() => {285 response.end('ok');286 }, 500);287 });288289 await page.goto(server.url);290 await addKyScriptToPage(page);291292 const errorName = await page.evaluate(async (url: string) => {293 const controller = new AbortController();Require Node.js 22Sindre Sorhusbefore adoptionf1da0fc
line 294why, one step back294 const request = globalThis.ky(`${url}/test`, {signal: controller.signal}).text();Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 295–319why, one step back295 controller.abort();296 return request.catch(error_ => error_.name);297 }, server.url);298299 t.is(errorName, 'AbortError');300});301302defaultBrowsersTest('should copy origin response info when using `onDownloadProgress`', async (t: ExecutionContext, page: Page) => {303 const json = {hello: 'world'};304 const status = 202;305 const statusText = 'Accepted';306 server.get('/', (_request, response) => {307 response.end('meow');308 });309310 server.get('/test', (_request, response) => {311 setTimeout(() => {312 response.statusMessage = statusText;313 response.status(status).header('X-ky-Header', 'ky').json(json);314 }, 500);315 });316 await page.goto(server.url);317 await addKyScriptToPage(page);318 const data = await page.evaluate(async (url: string) => {319 // eslint-disable-next-line @typescript-eslint/no-empty-functionRequire Node.js 22Sindre Sorhusbefore adoptionf1da0fc
line 320why, one step back320 const request = globalThis.ky.get(`${url}/test`, {onDownloadProgress() {}}).then(async v => ({Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 321–336why, one step back321 headers: v.headers.get('X-ky-Header'),322 status: v.status,323 statusText: v.statusText,324 data: await v.json(),325 }));326 return request;327 }, server.url);328329 t.deepEqual(data, {330 status,331 headers: 'ky',332 statusText,333 data: json,334 });335});336Fix progress callbacks for empty request and response bodies (#881)Sindre Sorhusbefore adoption99644d0
line 337why, one step back337defaultBrowsersTest('should not copy response body with 204 status code when using `onDownloadProgress`', async (t: ExecutionContext, page: Page) => {Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 338–352why, one step back338 const status = 204;339 const statusText = 'No content';340 server.get('/', (_request, response) => {341 response.end('meow');342 });343344 server.get('/test', (_request, response) => {345 setTimeout(() => {346 response.statusMessage = statusText;347 response.status(status).header('X-ky-Header', 'ky').end(null);348 }, 500);349 });350 await page.goto(server.url);351 await addKyScriptToPage(page);352 const data = await page.evaluate(async (url: string) => {Fix progress callbacks for empty request and response bodies (#881)Sindre Sorhusbefore adoption99644d0
line 353why, one step back353 const progress: Progress[] = [];Require Node.js 22Sindre Sorhusbefore adoptionf1da0fc
line 354why, one step back354 const response = await globalThis.ky.get(`${url}/test`, {Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 355–359why, one step back355 onDownloadProgress(progressEvent) {356 progress.push(progressEvent);357 },358 });359 return {Fix progress callbacks for empty request and response bodies (#881)Sindre Sorhusbefore adoption99644d0
lines 360–365why, one step back360 response: {361 headers: response.headers.get('X-ky-Header'),362 status: response.status,363 statusText: response.statusText,364 text: await response.text(),365 },Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 366–373why, one step back366 progress,367 };368 }, server.url);369370 t.deepEqual(data.response, {371 status,372 headers: 'ky',373 statusText,Fix progress callbacks for empty request and response bodies (#881)Sindre Sorhusbefore adoption99644d0
line 374why, one step back374 text: '',Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 375–400why, one step back375 });376 t.deepEqual(data.progress, []);377});378379browserTest('aborting a request with onDownloadProgress', [chromium], async (t: ExecutionContext, page: Page) => {380 server.get('/', (_request, response) => {381 response.end('meow');382 });383384 server.get('/test', (_request, response) => {385 response.writeHead(200, {386 'content-length': '4',387 });388389 response.write('me');390 setTimeout(() => {391 response.end('ow');392 }, 1000);393 });394395 await page.goto(server.url);396 await addKyScriptToPage(page);397398 const error = await page.evaluate(async (url: string) => {399 const controller = new AbortController();400 // eslint-disable-next-line @typescript-eslint/no-empty-functionRequire Node.js 22Sindre Sorhusbefore adoptionf1da0fc
line 401why, one step back401 const request = globalThis.ky(`${url}/test`, {signal: controller.signal, onDownloadProgress() {}}).text();Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 402–404why, one step back402 setTimeout(() => {403 controller.abort();404 }, 500);Fix a user abort in Chromium being reported as `NetworkError` and retriedSindre Sorhusbefore adoption7c1272b
line 405why, one step back405 return request.catch(error_ => error_.name);Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 406why, one step back406 }, server.url);Fix a user abort in Chromium being reported as `NetworkError` and retriedSindre Sorhusbefore adoption7c1272b
lines 407–408why, one step back407 // Chromium reports this abort as `TypeError: Failed to fetch`, which Ky replaces with the abort reason.408 t.is(error, 'AbortError');Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 409–428why, one step back409});410411defaultBrowsersTest(412 'throws TimeoutError even though it does not support AbortController',413 async (t: ExecutionContext, page: Page) => {414 server.get('/', (_request, response) => {415 response.end();416 });417418 server.get('/slow', (_request, response) => {419 setTimeout(() => {420 response.end('ok');421 }, 1000);422 });423424 await page.goto(server.url);425 await page.addScriptTag({content: 'window.AbortController = undefined;\n'});426 await addKyScriptToPage(page);427428 const error = await page.evaluate(async (url: string) => {Require Node.js 22Sindre Sorhusbefore adoptionf1da0fc
line 429why, one step back429 const request = globalThis.ky(`${url}/slow`, {timeout: 500}).text();Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 430–461why, one step back430 return request.catch(error_ => ({431 message: error_.toString(),432 request: {url: error_.request.url},433 }));434 }, server.url);435436 if (typeof error !== 'object') {437 throw new TypeError('Expected to have an object error');438 }439440 t.is(error.message, `TimeoutError: Request timed out: GET ${server.url}/slow`);441 t.is(error.request.url, `${server.url}/slow`);442 },443);444445browserTest('onDownloadProgress works', [chromium, webkit], async (t: ExecutionContext, page: Page) => {446 server.get('/', (_request, response) => {447 response.writeHead(200, {448 'content-length': '4',449 });450451 response.write('me');452 setTimeout(() => {453 response.end('ow');454 }, 1000);455 });456457 await page.goto(server.url);458 await addKyScriptToPage(page);459460 const result = await page.evaluate(async (url: string) => {461 const data: Array<Array<(Progress | string)>> = [];Require Node.js 22Sindre Sorhusbefore adoptionf1da0fc
line 462why, one step back462 const text = await globalThisAdd retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 463–479why, one step back463 .ky(url, {464 onDownloadProgress(progress, chunk) {465 // Decode Utf8466 const stringifiedChunk = String.fromCodePoint(...chunk);467 data.push([progress, stringifiedChunk]);468 },469 })470 .text();471472 return {data, text};473 }, server.url);474475 t.deepEqual(result.data, [476 [{percent: 0.5, transferredBytes: 2, totalBytes: 4}, 'me'],477 [{percent: 1, transferredBytes: 4, totalBytes: 4}, 'ow'],478 ]);479 t.is(result.text, 'meow');Fix progress callbacks for empty request and response bodies (#881)Sindre Sorhusbefore adoption99644d0
lines 480–509why, one step back480});481482defaultBrowsersTest('onDownloadProgress completes for an empty response body', async (t: ExecutionContext, page: Page) => {483 server.get('/', (_request, response) => {484 response.end('meow');485 });486487 server.get('/test', (_request, response) => {488 response.header('content-length', '0').end();489 });490491 await page.goto(server.url);492 await addKyScriptToPage(page);493494 const result = await page.evaluate(async (url: string) => {495 const progressEvents: Array<{progress: Progress; chunkLength: number}> = [];496 const text = await globalThis.ky(`${url}/test`, {497 onDownloadProgress(progress, chunk) {498 progressEvents.push({progress, chunkLength: chunk.byteLength});499 },500 }).text();501502 return {progressEvents, text};503 }, server.url);504505 t.is(result.text, '');506 t.deepEqual(result.progressEvents, [{507 progress: {percent: 1, totalBytes: 0, transferredBytes: 0},508 chunkLength: 0,509 }]);Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 510–521why, one step back510});511512defaultBrowsersTest('throws if onDownloadProgress is not a function', async (t: ExecutionContext, page: Page) => {513 server.get('/', (_request, response) => {514 response.end();515 });516517 await page.goto(server.url);518 await addKyScriptToPage(page);519520 const error = await page.evaluate(async (url: string) => {521 // @ts-expect-errorRequire Node.js 22Sindre Sorhusbefore adoptionf1da0fc
line 522why, one step back522 const request = globalThis.ky(url, {onDownloadProgress: 1}).text();Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 523–538why, one step back523 return request.catch(error_ => error_.toString());524 }, server.url);525 t.is(error, 'TypeError: The `onDownloadProgress` option must be a function');526});527528defaultBrowsersTest('throws if does not support ReadableStream', async (t: ExecutionContext, page: Page) => {529 server.get('/', (_request, response) => {530 response.end();531 });532533 await page.goto(server.url);534 await page.addScriptTag({content: 'window.ReadableStream = undefined;\n'});535 await addKyScriptToPage(page);536537 const error = await page.evaluate(async (url: string) => {538 // eslint-disable-next-line @typescript-eslint/no-empty-functionRequire Node.js 22Sindre Sorhusbefore adoptionf1da0fc
line 539why, one step back539 const request = globalThis.ky(url, {onDownloadProgress() {}}).text();Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 540–542why, one step back540 return request.catch(error_ => error_.toString());541 }, server.url);542 t.is(error, 'Error: Streams are not supported in your environment. `ReadableStream` is missing.');Gracefully ignore `onUploadProgress` when request streams are unsupported (#845)Sindre Sorhusbefore adoption1e38ff4
lines 543–544why, one step back543});544Simulate unsupported request streams in browser testsSindre Sorhusbefore adoption3e2d81a
line 545why, one step back545defaultBrowsersTest('onUploadProgress is silently ignored when request streams are unsupported', async (t: ExecutionContext, page: Page) => {Gracefully ignore `onUploadProgress` when request streams are unsupported (#845)Sindre Sorhusbefore adoption1e38ff4
lines 546–549why, one step back546 server.get('/', (_request, response) => {547 response.end();548 });549Improve `onUploadProgress` test to verify body receipt and callback silenceSindre Sorhusbefore adoption86b1519
lines 550–551why, one step back550 server.post('/', (request, response) => {551 t.is(request.body, 'hello');Gracefully ignore `onUploadProgress` when request streams are unsupported (#845)Sindre Sorhusbefore adoption1e38ff4
lines 552–555why, one step back552 response.end('ok');553 });554555 await page.goto(server.url);Simulate unsupported request streams in browser testsSindre Sorhusbefore adoption3e2d81a
lines 556–557why, one step back556 // Simulate missing stream support instead of relying on a browser version's capabilities.557 await page.addScriptTag({content: 'window.ReadableStream = undefined;\n'});Gracefully ignore `onUploadProgress` when request streams are unsupported (#845)Sindre Sorhusbefore adoption1e38ff4
lines 558–560why, one step back558 await addKyScriptToPage(page);559560 const result = await page.evaluate(async (url: string) => {Improve `onUploadProgress` test to verify body receipt and callback silenceSindre Sorhusbefore adoption86b1519
lines 561–562why, one step back561 let progressCalled = false;562Gracefully ignore `onUploadProgress` when request streams are unsupported (#845)Sindre Sorhusbefore adoption1e38ff4
lines 563–566why, one step back563 const text = await globalThis564 .ky(url, {565 method: 'post',566 body: 'hello',Fix retry abort propagation and uploads without request stream supportSindre Sorhusbefore adoption6520f64
lines 567–581why, one step back567 hooks: {568 beforeRequest: [({request}) => {569 // Accessing the body can turn it into a stream, even when streaming uploads are unsupported.570 Object.defineProperty(request, 'body', {571 configurable: true,572 get() {573 throw new Error('The request body must not be accessed before fetch');574 },575 });576 }],577 },578 async fetch(request, options) {579 Reflect.deleteProperty(request as Request, 'body');580 return globalThis.fetch(request, options);581 },Improve `onUploadProgress` test to verify body receipt and callback silenceSindre Sorhusbefore adoption86b1519
lines 582–584why, one step back582 onUploadProgress() {583 progressCalled = true;584 },Gracefully ignore `onUploadProgress` when request streams are unsupported (#845)Sindre Sorhusbefore adoption1e38ff4
lines 585–587why, one step back585 })586 .text();587Improve `onUploadProgress` test to verify body receipt and callback silenceSindre Sorhusbefore adoption86b1519
line 588why, one step back588 return {text, progressCalled};Gracefully ignore `onUploadProgress` when request streams are unsupported (#845)Sindre Sorhusbefore adoption1e38ff4
lines 589–590why, one step back589 }, server.url);590Improve `onUploadProgress` test to verify body receipt and callback silenceSindre Sorhusbefore adoption86b1519
lines 591–592why, one step back591 t.is(result.text, 'ok');592 t.false(result.progressCalled);Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 593–616why, one step back593});594595defaultBrowsersTest('FormData with searchParams', async (t: ExecutionContext, page: Page) => {596 t.plan(3);597598 server.get('/', (_request, response) => {599 response.end();600 });601602 server.post('/', async (request, response) => {603 const requestBody = await parseRawBody(request);604 const contentType = request.headers['content-type'];605 const boundary = contentType!.split('boundary=')[1];606607 t.truthy(requestBody.includes(boundary!));608 t.regex(requestBody, /bubblegum pie/);609 t.deepEqual(request.query, {foo: '1'});610 response.end();611 });612613 await page.goto(server.url);614 await addKyScriptToPage(page);615616 await page.evaluate(async (url: string) => {Require Node.js 22Sindre Sorhusbefore adoptionf1da0fc
lines 617–619why, one step back617 const formData = new globalThis.FormData();618 formData.append('file', new globalThis.File(['bubblegum pie'], 'my-file'));619 return globalThis.ky(url, {Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 620–686why, one step back620 method: 'post',621 searchParams: 'foo=1',622 body: formData,623 });624 }, server.url);625});626627defaultBrowsersTest('FormData with searchParams ("multipart/form-data" parser)', async (t: ExecutionContext, page: Page) => {628 t.plan(3);629630 server.get('/', (_request, response) => {631 response.end();632 });633634 server.post('/', async (request, response) => {635 const [body, error] = await new Promise(resolve => {636 // @ts-expect-error637 const busboyInstance = busboy({headers: request.headers});638639 busboyInstance.on('error', (error: Error) => {640 resolve([null, error]);641 });642643 // eslint-disable-next-line max-params644 busboyInstance.on('file', async (fieldname, file, filename, encoding, mimetype) => {645 let fileContent = '';646 try {647 for await (const chunk of file) {648 fileContent += chunk; // eslint-disable-line @typescript-eslint/restrict-plus-operands649 }650651 resolve([{fieldname, filename, fileContent}, undefined]);652 } catch (error_: unknown) {653 resolve([null, error_]);654 }655 });656657 busboyInstance.on('finish', () => {658 response.writeHead(303, {Connection: 'close', Location: '/'});659 response.end();660 });661662 setTimeout(() => {663 resolve([null, new Error('Timeout')]);664 }, 3000);665666 request.pipe(busboyInstance);667 });668669 t.falsy(error);670 t.deepEqual(request.query, {foo: '1'});671672 t.deepEqual(body, {673 fieldname: 'file',674 filename: {675 filename: 'my-file',676 encoding: '7bit',677 mimeType: 'text/plain',678 },679 fileContent: 'bubblegum pie',680 });681 });682683 await page.goto(server.url);684 await addKyScriptToPage(page);685686 await page.evaluate(async url => {Require Node.js 22Sindre Sorhusbefore adoptionf1da0fc
line 687why, one step back687 const formData = new globalThis.FormData();Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 688why, one step back688Require Node.js 22Sindre Sorhusbefore adoptionf1da0fc
line 689why, one step back689 formData.append('file', new globalThis.File(['bubblegum pie'], 'my-file', {type: 'text/plain'}));Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 690why, one step back690Require Node.js 22Sindre Sorhusbefore adoptionf1da0fc
line 691why, one step back691 return globalThis.ky(url, {Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 692–717why, one step back692 method: 'post',693 searchParams: 'foo=1',694 body: formData,695 });696 }, server.url);697});698699defaultBrowsersTest(700 'headers are preserved when input is a Request and there are searchParams in the options',701 async (t: ExecutionContext, page: Page) => {702 t.plan(2);703704 server.get('/', (_request, response) => {705 response.end();706 });707708 server.get('/test', (request, response) => {709 t.is(request.headers['content-type'], 'text/css');710 t.deepEqual(request.query, {foo: '1'});711 response.end();712 });713714 await page.goto(server.url);715 await addKyScriptToPage(page);716717 await page.evaluate(async (url: string) => {Require Node.js 22Sindre Sorhusbefore adoptionf1da0fc
line 718why, one step back718 const request = new globalThis.Request(`${url}/test`, {Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 719–721why, one step back719 headers: {'content-type': 'text/css'},720 });721Require Node.js 22Sindre Sorhusbefore adoptionf1da0fc
line 722why, one step back722 return globalThisAdd retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 723–749why, one step back723 .ky(request, {724 searchParams: 'foo=1',725 })726 .text();727 }, server.url);728 },729);730731browserTest('retry with body', [chromium, webkit], async (t: ExecutionContext, page: Page) => {732 t.plan(4);733734 let requestCount = 0;735736 server.get('/', (_request, response) => {737 response.end('zebra');738 });739740 server.put('/test', async (request, response) => {741 requestCount++;742 t.is(request.body, 'foo');743 response.sendStatus(502);744 });745746 await page.goto(server.url);747 await addKyScriptToPage(page);748749 await t.throwsAsync(Require Node.js 22Sindre Sorhusbefore adoptionf1da0fc
line 750why, one step back750 page.evaluate(async (url: string) => globalThis.ky(`${url}/test`, {Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 751–784why, one step back751 body: 'foo',752 method: 'PUT',753 retry: 1,754 }), server.url),755 {message: /HTTPError: Request failed with status code 502 Bad Gateway: PUT/},756 );757758 t.is(requestCount, 2);759});760761defaultBrowsersTest('request is cancelled on timeout', async (t: ExecutionContext, page: Page) => {762 let requestAborted = false;763764 server.get('/', (_request, response) => {765 response.end('meow');766 });767768 server.get('/slow', (request, response) => {769 request.on('aborted', () => {770 requestAborted = true;771 });772773 // Never respond to simulate timeout774 setTimeout(() => {775 if (!response.headersSent) {776 response.end('too late');777 }778 }, 2000);779 });780781 await page.goto(server.url);782 await addKyScriptToPage(page);783784 await t.throwsAsync(Require Node.js 22Sindre Sorhusbefore adoptionf1da0fc
line 785why, one step back785 page.evaluate(async (url: string) => globalThis.ky(`${url}/slow`, {timeout: 100}).text(), server.url),Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 786–793why, one step back786 {message: /Request timed out/},787 );788789 // Wait a bit to ensure the abort signal was received790 await page.waitForTimeout(200);791792 t.true(requestAborted, 'Request should be aborted on timeout');793});Fix `fetch: window.fetch` throwing "Illegal invocation" in browsersSindre Sorhusbefore adoption92ef60e
lines 794–832why, one step back794795defaultBrowsersTest('an unbound window.fetch works as the fetch option', async (t: ExecutionContext, page: Page) => {796 let requestCount = 0;797798 server.get('/', (_request, response) => {799 response.end('zebra');800 });801802 server.get('/unicorn', (_request, response) => {803 response.end('rainbow');804 });805806 server.get('/flaky', (_request, response) => {807 requestCount++;808 if (requestCount === 1) {809 response.sendStatus(500);810 return;811 }812813 response.end('recovered');814 });815816 await page.goto(server.url);817 await addKyScriptToPage(page);818819 // `window.fetch` is intentional here since the bug only reproduces with a native fetch that checks its `this` value.820 /* eslint-disable unicorn/prefer-global-this */821 const results = await page.evaluate(async (url: string) => Promise.all([822 globalThis.ky(`${url}/unicorn`, {fetch: window.fetch}).text(),823 globalThis.ky(`${url}/unicorn`, {fetch: window.fetch, timeout: false}).text(),824 globalThis.ky(`${url}/unicorn`, {fetch: globalThis.fetch}).text(),825 globalThis.ky.create({fetch: window.fetch})(`${url}/unicorn`).text(),826 globalThis.ky(`${url}/flaky`, {fetch: window.fetch, retry: {limit: 1, backoffLimit: 0}}).text(),827 ]), server.url);828 /* eslint-enable unicorn/prefer-global-this */829830 t.deepEqual(results, ['rainbow', 'rainbow', 'rainbow', 'rainbow', 'recovered']);831 t.is(requestCount, 2);832});Let a `beforeRetry` hook change per-attempt optionsSindre Sorhusbefore adoption242c327
lines 833–905why, one step back833834browserTest('beforeRetry upload progress override allows HTTP/1.1 fallback', [chromium], async (t, page) => {835 const uploadServer = await createEsmTestServer({bodyParser: false});836 t.teardown(uploadServer.close);837 uploadServer.get('/', (_request, response) => {838 response.end();839 });840 let receivedRequests = 0;841 uploadServer.put('/upload', async (request, response) => {842 receivedRequests++;843 const body = await parseRawBody(request);844 response.json({body, contentType: request.headers['content-type']});845 });846 await page.goto(uploadServer.url);847 await addKyScriptToPage(page);848849 const results = await page.evaluate(async (url: string) => {850 const formData = new FormData();851 formData.append('field', 'payload');852 const bodies = ['payload', new Blob(['payload']), formData, new URLSearchParams({field: 'payload'})];853 const results = [];854 for (const body of bodies) {855 let retryCount = 0;856 let errorName = '';857 let retryContentType: string | undefined;858 // eslint-disable-next-line no-await-in-loop859 const response = await globalThis.ky.put(`${url}/upload`, {860 body,861 onUploadProgress() {862 // Only enables the streamed upload, which fails over HTTP/1.1 in Chromium.863 },864 retry: {865 limit: 1,866 // A method, because tsx wraps an arrow function assigned to a property with a `__name` helper that does not exist in the page.867 delay() {868 return 0;869 },870 },871 hooks: {872 beforeRetry: [state => {873 retryCount = state.retryCount;874 errorName = state.error.name;875 retryContentType = state.request.headers.get('content-type') ?? undefined;876 return {options: {onUploadProgress: undefined}};877 }],878 },879 }).json<{body: string; contentType?: string}>();880 results.push({881 ...response,882 retryCount,883 errorName,884 retryContentType,885 });886 }887888 return results;889 }, uploadServer.url);890891 t.is(receivedRequests, 4);892 for (const result of results) {893 t.is(result.retryCount, 1);894 t.is(result.errorName, 'NetworkError');895 t.is(result.contentType, result.retryContentType);896 }897898 t.is(results[0]!.body, 'payload');899 t.is(results[1]!.body, 'payload');900 // The multipart boundary in the retried body must match its content type.901 const boundary = results[2]!.contentType!.split('boundary=')[1]!;902 t.true(results[2]!.body.startsWith(`--${boundary}\r\n`));903 t.true(results[2]!.body.includes('name="field"\r\n\r\npayload\r\n'));904 t.is(results[3]!.body, 'field=payload');905});