Let a `beforeRetry` hook change per-attempt options
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Fixes #885
authored by Sindre Sorhus · committed by Sindre Sorhus · parent d9ddb03 · Browse files · 9 files·+543 added−13 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
9 files+543 added−13 removed
- tests:+391 added−0 removed
- other:+152 added−13 removed
Provenance
- Commit
242c327- Tree
8cdf430- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
Sindre Sorhus <sindresorhus@gmail.com>- Parent
d9ddb03
9 files changed+543 added−13 removed
modified:source/core/constants.ts+3 added
260 unmodified lines261 ```262 */263 export const retry = (options?: ForceRetryOptions) => new RetryMarker(options);264 265+// Ky reads these again for every attempt, so a `beforeRetry` hook can change them without rebuilding the request.266+export const beforeRetryOptionKeys = ['onUploadProgress', 'onDownloadProgress', 'timeout', 'fetch', 'throwHttpErrors'] as const;267+268 export const kyOptionKeys: KyOptionsRegistry = {269 json: true,270 parseJson: true,271 stringifyJson: true,36 unmodified linesmodified:source/core/Ky.ts+31 added-7 removed
48 unmodified lines49 maxSafeTimeout,50 responseTypes,51 getSupportedResponseTypes,52 stop,53+ beforeRetryOptionKeys,54 isRetryMarker,55 supportsAbortController,56 supportsAbortSignal,57 supportsFormData,155 unmodified lines213 throw new RangeError(`The \`${name}\` option cannot be greater than ${maxSafeTimeout}`);214 }215 };216 217+// Defaults only replace `undefined`, so a `null` reaches the validation and is reported instead of silently becoming the default.218+const withAttemptDefaults = ({throwHttpErrors = true, timeout = 10_000, fetch = globalThis.fetch.bind(globalThis)}: Options) => ({throwHttpErrors, timeout, fetch});219+220 // These callbacks are called directly, so a non-function value otherwise surfaces as a runtime error naming Ky's own internals rather than the option the caller set.221 const validateCallbackOptions = (options: Record<string, unknown>): void => {222 for (const key of ['parseJson', 'stringifyJson', 'fetch', 'onDownloadProgress', 'onUploadProgress'] as const) {223 if (options[key] !== undefined && typeof options[key] !== 'function') {239 unmodified lines463 464 // Defaults only replace `undefined`, so a `null` reaches the validation below and is reported instead of silently becoming the default.465 const {466 maxResponseSize = Number.POSITIVE_INFINITY,463- throwHttpErrors = true,464- timeout = 10_000,467 totalTimeout = false,466- fetch = globalThis.fetch.bind(globalThis),468 } = options;469 if (Object.hasOwn(options, 'prefixUrl')) {470 throw new Error(prefixUrlRenamedErrorMessage);471 }18 unmodified lines490 referrerPolicy: options.referrerPolicy ?? (input as Request).referrerPolicy,491 // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing492 prefix: String(options.prefix || ''),493 retry: normalizeRetryOptions(options.retry),493- throwHttpErrors,494- timeout,494+ ...withAttemptDefaults(options),495 totalTimeout,496 maxResponseSize,497- fetch,497 context: options.context ?? {},498 };499 // Checked here rather than on the way out, because the constructor already calls `stringifyJson`.500 validateCallbackOptions(this.#options);502- validateTimeoutOption(timeout, 'timeout');501+ validateTimeoutOption(this.#options.timeout, 'timeout');502 validateTimeoutOption(totalTimeout, 'totalTimeout');503 this.#retryLimit = this.#options.retry.limit;504 505 if (maxResponseSize !== Number.POSITIVE_INFINITY && (!Number.isSafeInteger(maxResponseSize) || maxResponseSize < 0)) {696 unmodified lines1202 // If `stop` is returned from the hook, the retry process is stopped1203 if (hookResult === stop) {1204 return;1205 }1206+1207+ if (isNonArrayObject(hookResult)) {1208+ this.#applyBeforeRetryOptions(hookResult.options);1209+ }1210 }1211 1212 this.#throwIfTotalTimeoutExhausted();1213 68 unmodified lines1282 #getRemainingTotalTimeout(): number {1283 return Math.max(0, this.#deadline - getCurrentTime());1284 }1285 1286+ // Omitted options keep their value, and `undefined` restores Ky's default. The changes apply to the next attempt and every later one.1287+ #applyBeforeRetryOptions(options: unknown): void {1288+ if (!isNonArrayObject(options)) {1289+ throw new TypeError('The `options` returned from a `beforeRetry` hook must be an object');1290+ }1291+1292+ for (const key of Object.keys(options)) {1293+ if (!(beforeRetryOptionKeys as readonly string[]).includes(key)) {1294+ throw new TypeError(`The \`${key}\` option cannot be changed from a \`beforeRetry\` hook`);1295+ }1296+ }1297+1298+ const mergedOptions = {...this.#options, ...options};1299+ const updatedOptions = {...mergedOptions, ...withAttemptDefaults(mergedOptions)};1300+ validateCallbackOptions(updatedOptions);1301+ validateTimeoutOption(updatedOptions.timeout, 'timeout');1302+1303+ Object.assign(this.#options, updatedOptions);1304+ this.#cachedNormalizedOptions = undefined;1305+ }1306+1307 #getNormalizedOptions(): NormalizedOptions {1308 if (!this.#cachedNormalizedOptions) {1309 // Exclude Ky-specific options that are not part of `RequestInit`.1310 const {66 unmodified linesmodified:source/types/hooks.ts+51 added-3 removed
1-import {type stop, type RetryMarker} from '../core/constants.js';1+import {type stop, type RetryMarker, type beforeRetryOptionKeys} from '../core/constants.js';2 import type {KyRequest, KyResponse} from '../index.js';3-import type {InitOptions, NormalizedOptions} from './options.js';3+import type {InitOptions, NormalizedOptions, Options} from './options.js';4 5 /**6 This hook enables you to modify the options before they are used to construct the request. The hook function receives the mutable options object and can modify it in place. You could, for example, modify `searchParams`, `headers`, or `json` here. The `headers` option starts as a plain object with lowercase names, where a header removed with `undefined` keeps an `undefined` value.7 43 unmodified lines51 */52 retryCount: number;53 };54 55-export type BeforeRetryHook = (state: BeforeRetryState) => Request | Response | typeof stop | void | Promise<Request | Response | typeof stop | void>;55+/**56+The value a `beforeRetry` hook can return to change options for this retry and the ones after it.57 58+@example59+```60+import ky, {type BeforeRetryUpdate} from 'ky';61+62+const withoutUploadProgress = (): BeforeRetryUpdate => ({options: {onUploadProgress: undefined}});63+64+await ky.put(uploadUrl, {65+ body: file,66+ onUploadProgress: updateProgress,67+ hooks: {68+ beforeRetry: [withoutUploadProgress],69+ },70+});71+```72+*/73+export type BeforeRetryUpdate = {74+ options: Pick<Options, typeof beforeRetryOptionKeys[number]>;75+};76+77+export type BeforeRetryHook = (state: BeforeRetryState) => Request | Response | BeforeRetryUpdate | typeof stop | void | Promise<Request | Response | BeforeRetryUpdate | typeof stop | void>;78+79 export type BeforeErrorState = {80 request: KyRequest;81 options: Readonly<NormalizedOptions>;82 121 unmodified lines204 If the request received a response, the error will be of type `HTTPError`. The `Response` object will be available at `error.response`, and the pre-parsed response body may be available at `error.data`. Be aware that some types of errors, such as network errors, inherently mean that a response was not received. In that case, the error will be an instance of `NetworkError` instead of `HTTPError`.205 206 You can prevent Ky from retrying the request by throwing an error. Ky will not handle it in any way and the error will be propagated to the request initiator. The rest of the `beforeRetry` hooks will not be called in this case. Alternatively, you can return the [`ky.stop`](#kystop) symbol to do the same thing but without propagating an error (this has some limitations, see `ky.stop` docs for details).207 208+ **Changing options:**209+210+ Return `{options: {...}}` to change `onUploadProgress`, `onDownloadProgress`, `timeout`, `fetch`, or `throwHttpErrors` for this retry and the ones after it. Omitted options keep their value, and `undefined` restores Ky's default, not the value from `ky.create()` or `ky.extend()`. Any other option, or an invalid value, throws an error. The remaining `beforeRetry` hooks still run and see the new progress callbacks in `options`. The `options` a hook receives never include `timeout`, `fetch`, or `throwHttpErrors`.211+212+ For example, turn off upload progress after a network error. Upload progress needs a streamed request body, which Chromium only sends over HTTP/2 or HTTP/3, so the upload fails on an HTTP/1.1 connection. Only retry an upload when it is safe to send it again, since a network error does not tell whether the server got the request.213+214+ @example215+ ```216+ import ky, {isNetworkError} from 'ky';217+218+ await ky.put(uploadUrl, {219+ body: file,220+ onUploadProgress: updateProgress,221+ retry: {limit: 1},222+ hooks: {223+ beforeRetry: [224+ ({error}) => {225+ if (isNetworkError(error)) {226+ return {options: {onUploadProgress: undefined}};227+ }228+ }229+ ]230+ }231+ });232+ ```233+234 **Modifying headers:**235 236 @example237 ```187 unmodified linesmodified:source/types/options.ts+1 added-1 removed
317 unmodified lines318 319 /**320 Upload progress event handler.321 322- Note: Requires [request stream support](https://caniuse.com/wf-fetch-request-streams) and, in Chromium-based browsers, an HTTP/2 or HTTP/3 connection (streaming uploads over HTTP/1.1 fail with a network error, even over plain HTTP). This handler is silently ignored in unsupported environments and for requests with `keepalive: true` or `mode: 'no-cors'`, since they cannot use streaming request bodies.322+ Note: Requires [request stream support](https://caniuse.com/wf-fetch-request-streams) and, in Chromium-based browsers, an HTTP/2 or HTTP/3 connection (streaming uploads over HTTP/1.1 fail with a network error, even over plain HTTP). This handler is silently ignored in unsupported environments and for requests with `keepalive: true` or `mode: 'no-cors'`, since they cannot use streaming request bodies. If an upload fails over HTTP/1.1 in Chromium, you can retry it without upload progress by returning `{options: {onUploadProgress: undefined}}` from a [`beforeRetry`](#hooksbeforeretry) hook.323 324 @param progress - Object containing upload progress information.325 @param chunk - Data that was sent. When an empty request body stream completes, the callback receives an empty chunk.326 229 unmodified linesmodified:source/index.ts+1 added
76 unmodified lines77787980818283848529 unmodified lines76 unmodified lines BeforeRequestHook, BeforeRequestState, BeforeRetryHook, BeforeRetryState, BeforeRetryUpdate, BeforeErrorHook, BeforeErrorState, AfterResponseHook, AfterResponseState,29 unmodified linesmodified:test/browser.ts+73 added
828 unmodified lines829 830 t.deepEqual(results, ['rainbow', 'rainbow', 'rainbow', 'rainbow', 'recovered']);831 t.is(requestCount, 2);832 });833+834+browserTest('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);848+849+ 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+ }887+888+ return results;889+ }, uploadServer.url);890+891+ 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+ }897+898+ 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+});added:test/retry-options.ts+318 added
1+import test from 'ava';2+import ky from '../source/index.js';3+import {createHttpTestServer} from './helpers/create-http-test-server.js';4+5+// Retries right away, so the tests do not wait for a backoff.6+const retryOnce = {limit: 1, delay: () => 0};7+8+// A `fetch` that always answers `503` and counts its calls.9+const createUnavailableFetch = () => {10+ const state = {11+ calls: 0,12+ async fetch() {13+ state.calls++;14+ return new Response('retry', {status: 503});15+ },16+ };17+18+ return state;19+};20+21+test('beforeRetry can turn off upload progress without losing the body', async t => {22+ let attempts = 0;23+ const progressAttempts: number[] = [];24+ const response = await ky.put('https://example.com', {25+ body: 'payload',26+ retry: retryOnce,27+ onUploadProgress() {28+ progressAttempts.push(attempts);29+ },30+ async fetch(request) {31+ attempts++;32+ t.is(await request.text(), 'payload');33+ if (attempts === 1) {34+ throw new TypeError('Failed to fetch');35+ }36+37+ return new Response('ok');38+ },39+ hooks: {40+ beforeRetry: [() => ({options: {onUploadProgress: undefined}})],41+ },42+ });43+44+ t.is(await response.text(), 'ok');45+ t.is(attempts, 2);46+ t.deepEqual(progressAttempts, [1]);47+});48+49+test('beforeRetry can turn on upload progress without losing the body', async t => {50+ let attempts = 0;51+ const progressAttempts: number[] = [];52+ const response = await ky.put('https://example.com', {53+ body: 'payload',54+ retry: retryOnce,55+ async fetch(request) {56+ attempts++;57+ t.is(await request.text(), 'payload');58+ if (attempts === 1) {59+ throw new TypeError('Failed to fetch');60+ }61+62+ return new Response('ok');63+ },64+ hooks: {65+ beforeRetry: [() => ({66+ options: {67+ onUploadProgress() {68+ progressAttempts.push(attempts);69+ },70+ },71+ })],72+ },73+ });74+75+ t.is(await response.text(), 'ok');76+ t.deepEqual(progressAttempts, [2]);77+});78+79+test('beforeRetry options apply to later retries and later hooks', async t => {80+ let attempts = 0;81+ let originalProgressCalls = 0;82+ let replacementProgressCalls = 0;83+ const originalProgress = () => {84+ originalProgressCalls++;85+ };86+87+ const replacementProgress = () => {88+ replacementProgressCalls++;89+ };90+91+ const seenProgress: unknown[] = [];92+ const text = await ky('https://example.com', {93+ onDownloadProgress: originalProgress,94+ retry: {...retryOnce, limit: 2},95+ async fetch() {96+ attempts++;97+ return new Response('ok', {status: attempts < 3 ? 503 : 200});98+ },99+ hooks: {100+ beforeRetry: [101+ ({options, retryCount}) => {102+ seenProgress.push(options.onDownloadProgress);103+ if (retryCount === 1) {104+ return {options: {onDownloadProgress: replacementProgress}};105+ }106+ },107+ ({options}) => {108+ t.is(options.onDownloadProgress, replacementProgress);109+ },110+ ],111+ },112+ }).text();113+114+ t.is(text, 'ok');115+ t.is(attempts, 3);116+ t.deepEqual(seenProgress, [originalProgress, replacementProgress]);117+ t.is(originalProgressCalls, 0);118+ t.true(replacementProgressCalls > 0);119+});120+121+test('beforeRetry can change fetch and throwHttpErrors', async t => {122+ const unavailable = createUnavailableFetch();123+ let replacementFetchCalls = 0;124+ const response = await ky('https://example.com', {125+ retry: retryOnce,126+ fetch: unavailable.fetch,127+ hooks: {128+ beforeRetry: [() => ({129+ options: {130+ async fetch() {131+ replacementFetchCalls++;132+ return new Response('still failing', {status: 500});133+ },134+ throwHttpErrors: false,135+ },136+ })],137+ },138+ });139+140+ t.is(response.status, 500);141+ t.is(unavailable.calls, 1);142+ t.is(replacementFetchCalls, 1);143+});144+145+test('beforeRetry can change throwHttpErrors to a function', async t => {146+ const unavailable = createUnavailableFetch();147+ const statuses: number[] = [];148+ const response = await ky('https://example.com', {149+ retry: retryOnce,150+ fetch: unavailable.fetch,151+ hooks: {152+ beforeRetry: [() => ({153+ options: {154+ throwHttpErrors(status) {155+ statuses.push(status);156+ return false;157+ },158+ },159+ })],160+ },161+ });162+163+ t.is(response.status, 503);164+ t.deepEqual(statuses, [503]);165+});166+167+test('beforeRetry can change the timeout', async t => {168+ let attempts = 0;169+ const response = await ky('https://example.com', {170+ timeout: 10,171+ retry: {...retryOnce, retryOnTimeout: true},172+ async fetch(request) {173+ attempts++;174+ await new Promise(resolve => {175+ setTimeout(resolve, 50);176+ });177+ request.signal.throwIfAborted();178+ return new Response('ok');179+ },180+ hooks: {181+ beforeRetry: [() => ({options: {timeout: 1000}})],182+ },183+ });184+185+ t.is(await response.text(), 'ok');186+ t.is(attempts, 2);187+});188+189+test('beforeRetry options apply to a response returned by a later hook', async t => {190+ const unavailable = createUnavailableFetch();191+ const response = await ky('https://example.com', {192+ retry: retryOnce,193+ fetch: unavailable.fetch,194+ hooks: {195+ beforeRetry: [196+ () => ({options: {throwHttpErrors: false}}),197+ () => new Response('from hook', {status: 500}),198+ ],199+ },200+ });201+202+ t.is(response.status, 500);203+ t.is(await response.text(), 'from hook');204+ t.is(unavailable.calls, 1);205+});206+207+test('beforeRetry `undefined` restores the global fetch', async t => {208+ const server = await createHttpTestServer(t);209+ server.get('/', (_request, response) => {210+ response.end('native');211+ });212+213+ const unavailable = createUnavailableFetch();214+ const result = await ky(server.url, {215+ retry: retryOnce,216+ fetch: unavailable.fetch,217+ hooks: {beforeRetry: [() => ({options: {fetch: undefined}})]},218+ }).text();219+220+ t.is(result, 'native');221+ t.is(unavailable.calls, 1);222+});223+224+test('beforeRetry `undefined` restores Ky\'s default rather than the instance value', async t => {225+ let attempts = 0;226+ const api = ky.create({227+ throwHttpErrors: false,228+ retry: retryOnce,229+ async fetch() {230+ attempts++;231+ if (attempts === 1) {232+ throw new TypeError('Failed to fetch');233+ }234+235+ return new Response('failed', {status: 500});236+ },237+ });238+239+ await t.throwsAsync(api('https://example.com', {240+ hooks: {beforeRetry: [() => ({options: {throwHttpErrors: undefined}})]},241+ }), {name: 'HTTPError'});242+ t.is(attempts, 2);243+});244+245+test('beforeRetry options do not leak into other requests from the same instance', async t => {246+ let progressCalls = 0;247+ const attempts = new Map<string, number>();248+ const api = ky.create({249+ retry: retryOnce,250+ onUploadProgress() {251+ progressCalls++;252+ },253+ async fetch(request) {254+ const count = (attempts.get(request.url) ?? 0) + 1;255+ attempts.set(request.url, count);256+ await request.text();257+ return new Response('ok', {status: count === 1 ? 503 : 200});258+ },259+ });260+261+ await api.put('https://example.com/changed', {262+ body: 'payload',263+ hooks: {beforeRetry: [() => ({options: {onUploadProgress: undefined}})]},264+ });265+ // A small body reports progress once per streamed attempt.266+ t.is(progressCalls, 1);267+268+ await api.put('https://example.com/unchanged', {body: 'payload'});269+ t.is(progressCalls, 3);270+});271+272+test('beforeRetry options do not reset the retry limit', async t => {273+ const unavailable = createUnavailableFetch();274+ await t.throwsAsync(ky('https://example.com', {275+ retry: {...retryOnce, limit: 2},276+ fetch: unavailable.fetch,277+ hooks: {beforeRetry: [() => ({options: {timeout: false}})]},278+ }), {name: 'HTTPError'});279+280+ t.is(unavailable.calls, 3);281+});282+283+const notAnOptionsObject = 'The `options` returned from a `beforeRetry` hook must be an object';284+285+for (const {name, update, message, errorClass = TypeError} of [286+ {name: 'a missing `options`', update: {}, message: notAnOptionsObject},287+ {name: 'array options', update: {options: []}, message: notAnOptionsObject},288+ {name: '`null` options', update: {options: null}, message: notAnOptionsObject},289+ {name: 'the `body` option', update: {options: {body: 'payload'}}, message: 'The `body` option cannot be changed from a `beforeRetry` hook'},290+ {name: 'the `retry` option', update: {options: {retry: 10}}, message: 'The `retry` option cannot be changed from a `beforeRetry` hook'},291+ {292+ name: 'a `__proto__` key',293+ update: {options: JSON.parse('{"__proto__": {"timeout": 1}}') as unknown},294+ message: 'The `__proto__` option cannot be changed from a `beforeRetry` hook',295+ },296+ {name: 'an invalid callback', update: {options: {onUploadProgress: 'invalid'}}, message: 'The `onUploadProgress` option must be a function'},297+ {name: 'a `null` fetch', update: {options: {fetch: null}}, message: 'The `fetch` option must be a function'},298+ {name: 'an invalid throwHttpErrors', update: {options: {throwHttpErrors: 'yes'}}, message: 'The `throwHttpErrors` option must be a boolean or a function'},299+ {name: 'a `null` throwHttpErrors', update: {options: {throwHttpErrors: null}}, message: 'The `throwHttpErrors` option must be a boolean or a function'},300+ {name: 'a `null` timeout', update: {options: {timeout: null}}, message: 'The `timeout` option must be a non-negative number or `false`'},301+ {302+ name: 'an invalid timeout',303+ update: {options: {timeout: 2 ** 31}},304+ message: 'The `timeout` option cannot be greater than 2147483647',305+ errorClass: RangeError,306+ },307+]) {308+ test(`beforeRetry rejects ${name} before retrying`, async t => {309+ const unavailable = createUnavailableFetch();310+ await t.throwsAsync(ky('https://example.com', {311+ retry: retryOnce,312+ fetch: unavailable.fetch,313+ hooks: {beforeRetry: [() => update as never]},314+ }), {instanceOf: errorClass, message});315+316+ t.is(unavailable.calls, 1);317+ });318+}modified:test-d/hooks.ts+39 added-1 removed
12234567814 unmodified lines23242526272829303132333435363738394041424344454647484950515253545556575859606162import {expectTypeOf} from 'expect-type';import type {BeforeErrorHook, Hooks, InitHook} from 'ky';import type { BeforeErrorHook, BeforeRetryHook, BeforeRetryUpdate, Hooks, InitHook,} from 'ky';
const hookList = [() => undefined] as const;const beforeErrorHook: BeforeErrorHook = ({error}) => error;const beforeErrorHooks = [beforeErrorHook] as const;14 unmodified lines }};
expectTypeOf(initHook).toEqualTypeOf<InitHook>();
const retryOptionsHook: BeforeRetryHook = () => ({options: {onUploadProgress: undefined, timeout: false}});const asyncRetryOptionsHook: BeforeRetryHook = async () => ({options: {throwHttpErrors: false}});// `undefined` restores the default for every option, so it must be accepted with `exactOptionalPropertyTypes`.const restoreDefaultsHook: BeforeRetryHook = () => ({ options: { onUploadProgress: undefined, onDownloadProgress: undefined, timeout: undefined, fetch: undefined, throwHttpErrors: undefined, },});expectTypeOf(retryOptionsHook).toEqualTypeOf<BeforeRetryHook>();expectTypeOf(asyncRetryOptionsHook).toEqualTypeOf<BeforeRetryHook>();expectTypeOf(restoreDefaultsHook).toEqualTypeOf<BeforeRetryHook>();
const withoutUploadProgress = (): BeforeRetryUpdate => ({options: {onUploadProgress: undefined}});const separateFunctionHook: BeforeRetryHook = withoutUploadProgress;expectTypeOf(separateFunctionHook).toEqualTypeOf<BeforeRetryHook>();// @ts-expect-error The `body` option cannot be returned from a hook.const invalidUpdate: BeforeRetryUpdate = {options: {body: 'payload'}};expectTypeOf(invalidUpdate).toEqualTypeOf<BeforeRetryUpdate>();
// @ts-expect-error Request properties must be changed through the request.const bodyOptionsHook: BeforeRetryHook = () => ({options: {body: 'payload'}});// @ts-expect-error The `retry` option cannot be returned from a hook.const retryLimitOptionsHook: BeforeRetryHook = () => ({options: {retry: 2}});// @ts-expect-error The `timeout` option must be a number or `false`.const invalidTimeoutOptionsHook: BeforeRetryHook = () => ({options: {timeout: 'soon'}});// @ts-expect-error `null` is not accepted.const nullFetchOptionsHook: BeforeRetryHook = () => ({options: {fetch: null}});expectTypeOf(bodyOptionsHook).toEqualTypeOf<BeforeRetryHook>();expectTypeOf(retryLimitOptionsHook).toEqualTypeOf<BeforeRetryHook>();expectTypeOf(invalidTimeoutOptionsHook).toEqualTypeOf<BeforeRetryHook>();expectTypeOf(nullFetchOptionsHook).toEqualTypeOf<BeforeRetryHook>();modified:readme.md+26 added-1 removed
572 unmodified lines573 If the request received a response, the error will be of type `HTTPError`. The `Response` object will be available at `error.response`, and the pre-parsed response body may be available at `error.data`. Be aware that some types of errors, such as network errors, inherently mean that a response was not received. In that case, the error will be an instance of `NetworkError` instead of `HTTPError`.574 575 You can prevent Ky from retrying the request by throwing an error. Ky will not handle it in any way and the error will be propagated to the request initiator. The rest of the `beforeRetry` hooks will not be called in this case. Alternatively, you can return the [`ky.stop`](#kystop) symbol to do the same thing but without propagating an error (this has some limitations, see `ky.stop` docs for details).576 577+**Changing options:**578+579+Return `{options: {...}}` to change `onUploadProgress`, `onDownloadProgress`, `timeout`, `fetch`, or `throwHttpErrors` for this retry and the ones after it. Omitted options keep their value, and `undefined` restores Ky's default, not the value from `ky.create()` or `ky.extend()`. Any other option, or an invalid value, throws an error. The remaining `beforeRetry` hooks still run and see the new progress callbacks in `options`. The `options` a hook receives never include `timeout`, `fetch`, or `throwHttpErrors`.580+581+For example, turn off upload progress after a network error. Upload progress needs a streamed request body, which Chromium only sends over HTTP/2 or HTTP/3, so the upload fails on an HTTP/1.1 connection. Only retry an upload when it is safe to send it again, since a network error does not tell whether the server got the request.582+583+```js584+import ky, {isNetworkError} from 'ky';585+586+await ky.put(uploadUrl, {587+ body: file,588+ onUploadProgress: updateProgress,589+ retry: {limit: 1},590+ hooks: {591+ beforeRetry: [592+ ({error}) => {593+ if (isNetworkError(error)) {594+ return {options: {onUploadProgress: undefined}};595+ }596+ }597+ ]598+ }599+});600+```601+602 **Modifying headers:**603 604 ```js605 import ky from 'ky';223 unmodified lines829 830 Upload progress event handler.831 832 > [!NOTE]808-> Requires [request stream support](https://caniuse.com/wf-fetch-request-streams) and, in Chromium-based browsers, an HTTP/2 or HTTP/3 connection (streaming uploads over HTTP/1.1 fail with a network error, even over plain HTTP). This handler is silently ignored in unsupported environments and for requests with `keepalive: true` or `mode: 'no-cors'`, since they cannot use streaming request bodies.833+> Requires [request stream support](https://caniuse.com/wf-fetch-request-streams) and, in Chromium-based browsers, an HTTP/2 or HTTP/3 connection (streaming uploads over HTTP/1.1 fail with a network error, even over plain HTTP). This handler is silently ignored in unsupported environments and for requests with `keepalive: true` or `mode: 'no-cors'`, since they cannot use streaming request bodies. If an upload fails over HTTP/1.1 in Chromium, you can retry it without upload progress by returning `{options: {onUploadProgress: undefined}}` from a [`beforeRetry`](#hooksbeforeretry) hook.834 835 The function receives these arguments:836 - `progress` is an object with these properties:837 - `percent` is a number between 0 and 1 representing the progress percentage.1121 unmodified lines