Unify hook signatures around a single state object (#827)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Sindre Sorhus · committed by GitHub · parent dfa3f59 · Browse files · 13 files·+146 added−138 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
13 files+146 added−138 removed
- tests:+75 added−75 removed
- other:+71 added−63 removed
Provenance
- Commit
ecdd45e- Tree
0e91584- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
dfa3f59
13 files changed+146 added−138 removed
modified:source/core/constants.ts+1 added-1 removed
165 unmodified lines166 167 const api = ky.extend({168 hooks: {169 afterResponse: [170- async (request, options, response) => {170+ async ({request, response}) => {171 // Retry based on response body content172 if (response.status === 200) {173 const data = await response.clone().json();174 110 unmodified linesmodified:source/core/Ky.ts+15 added-12 removed
64 unmodified lines65 66 let modifiedResponse;67 try {68 // eslint-disable-next-line no-await-in-loop69- modifiedResponse = await hook(70- ky.request,71- ky.#getNormalizedOptions(),72- clonedResponse,73- {retryCount: ky.#retryCount},74- );69+ modifiedResponse = await hook({70+ request: ky.request,71+ options: ky.#getNormalizedOptions(),72+ response: clonedResponse,73+ retryCount: ky.#retryCount,74+ });75 } catch (error) {76 // Cancel both responses to prevent memory leaks when hook throws77 ky.#cancelResponseBody(clonedResponse);78 ky.#cancelResponseBody(response);35 unmodified lines114 error.data = await ky.#getResponseData(response);115 116 for (const hook of ky.#options.hooks.beforeError) {117 // eslint-disable-next-line no-await-in-loop118- error = await hook(error, {retryCount: ky.#retryCount});118+ error = await hook({119+ error,120+ retryCount: ky.#retryCount,121+ });122 }123 124 throw error;125 }465 unmodified lines591 }592 593 for (const hook of this.#options.hooks.beforeRequest) {594 // eslint-disable-next-line no-await-in-loop592- const result = await hook(593- this.request,594- this.#getNormalizedOptions(),595- {retryCount: this.#retryCount},596- );595+ const result = await hook({596+ request: this.request,597+ options: this.#getNormalizedOptions(),598+ retryCount: this.#retryCount,599+ });600 601 if (result instanceof Response) {602 return result;603 }42 unmodified linesmodified:source/types/hooks.ts+31 added-26 removed
1 unmodified line2 import type {KyRequest, KyResponse, HTTPError} from '../index.js';3 import type {NormalizedOptions} from './options.js';4 5 export type BeforeRequestState = {6+ request: KyRequest;7+ options: NormalizedOptions;8+9 /**10 The number of retries attempted. `0` for the initial request, increments with each retry.11 12 This allows you to distinguish between initial requests and retries, which is useful when you need different behavior for retries (e.g., avoiding overwriting headers set in `beforeRetry`).13 */14 retryCount: number;15 };16 14-export type BeforeRequestHook = (15- request: KyRequest,16- options: NormalizedOptions,17- state: BeforeRequestState18-) => Request | Response | void | Promise<Request | Response | void>;17+export type BeforeRequestHook = (state: BeforeRequestState) => Request | Response | void | Promise<Request | Response | void>;18 19 export type BeforeRetryState = {20 request: KyRequest;21 options: NormalizedOptions;3 unmodified lines25 The number of retries attempted. Always `>= 1` since this hook is only called during retries, not on the initial request.26 */27 retryCount: number;28 };30-export type BeforeRetryHook = (options: BeforeRetryState) => Request | Response | typeof stop | void | Promise<Request | Response | typeof stop | void>;29 30+export type BeforeRetryHook = (state: BeforeRetryState) => Request | Response | typeof stop | void | Promise<Request | Response | typeof stop | void>;31+32 export type AfterResponseState = {33+ request: KyRequest;34+ options: NormalizedOptions;35+ response: KyResponse;36+37 /**38 The number of retries attempted. `0` for the initial request, increments with each retry.39 40 This allows you to distinguish between initial requests and retries, which is useful when you need different behavior for retries (e.g., showing a notification only on the final retry).41 */42 retryCount: number;43 };44 41-export type AfterResponseHook = (42- request: KyRequest,43- options: NormalizedOptions,44- response: KyResponse,45- state: AfterResponseState46-) => Response | RetryMarker | void | Promise<Response | RetryMarker | void>;45+export type AfterResponseHook = (state: AfterResponseState) => Response | RetryMarker | void | Promise<Response | RetryMarker | void>;46 47 export type BeforeErrorState = {48+ error: HTTPError;49+50 /**51 The number of retries attempted. `0` for the initial request, increments with each retry.52 53 This allows you to distinguish between the initial request and retries, which is useful when you need different error handling based on retry attempts (e.g., showing different error messages on the final attempt).54 */55 retryCount: number;56 };57 57-export type BeforeErrorHook = (error: HTTPError, state: BeforeErrorState) => HTTPError | Promise<HTTPError>;58+export type BeforeErrorHook = (state: BeforeErrorState) => HTTPError | Promise<HTTPError>;59 60 export type Hooks = {61 /**61- This hook enables you to modify the request right before it is sent. Ky will make no further changes to the request after this. The hook function receives the normalized request, options, and a state object. You could, for example, modify `request.headers` here.62+ This hook enables you to modify the request right before it is sent. Ky will make no further changes to the request after this. The hook function receives a state object with the normalized request, options, and retry count. You could, for example, modify `request.headers` here.63 63- The `state.retryCount` is `0` for the initial request and increments with each retry. This allows you to distinguish between initial requests and retries, which is useful when you need different behavior for retries (e.g., avoiding overwriting headers set in `beforeRetry`).64+ The `retryCount` is `0` for the initial request and increments with each retry. This allows you to distinguish between initial requests and retries, which is useful when you need different behavior for retries (e.g., avoiding overwriting headers set in `beforeRetry`).65 66 A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) can be returned from this hook to completely avoid making an HTTP request. This can be used to mock a request, check an internal cache, etc. An **important** consideration when returning a `Response` from this hook is that all the following hooks will be skipped, so **ensure you only return a `Response` from the last hook**.67 68 @example2 unmodified lines71 72 const response = await ky('https://example.com', {73 hooks: {74 beforeRequest: [74- (request, options, {retryCount}) => {75+ ({request, retryCount}) => {76 // Only set default auth header on initial request, not on retries77 // (retries may have refreshed token set by beforeRetry)78 if (retryCount === 0) {79 request.headers.set('Authorization', 'token initial-token');8 unmodified lines88 */89 beforeRequest?: BeforeRequestHook[];90 91 /**91- This hook enables you to modify the request right before retry. Ky will make no further changes to the request after this. The hook function receives an object with the normalized request and options, an error instance, and the retry count. You could, for example, modify `request.headers` here.92+ This hook enables you to modify the request right before retry. Ky will make no further changes to the request after this. The hook function receives a state object with the normalized request, options, an error instance, and the retry count. You could, for example, modify `request.headers` here.93 94 The hook can return a [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) to replace the outgoing retry request, or return a [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) to skip the retry and use that response instead. **Note:** Returning a request or response skips remaining `beforeRetry` hooks.95 96 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 will 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 not be an instance of `HTTPError`.69 unmodified lines166 */167 beforeRetry?: BeforeRetryHook[];168 169 /**169- This hook enables you to read and optionally modify the response. The hook function receives normalized request, options, a clone of the response, and a state object. The return value of the hook function will be used by Ky as the response object if it's an instance of [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response).170+ This hook enables you to read and optionally modify the response. The hook function receives a state object with the normalized request, options, a clone of the response, and retry count. The return value of the hook function will be used by Ky as the response object if it's an instance of [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response).171 172+ The `retryCount` is `0` for the initial request and increments with each retry. This allows you to distinguish between initial requests and retries, which is useful when you need different behavior for retries (e.g., showing a notification only on the final retry).173+174 You can also force a retry by returning `ky.retry()` or `ky.retry(options)`. This is useful when you need to retry based on the response body content, even if the response has a successful status code. The retry will respect the retry limit and be observable in `beforeRetry` hooks.175 176 @default []177 3 unmodified lines181 182 const response = await ky('https://example.com', {183 hooks: {184 afterResponse: [182- (_request, _options, response) => {185+ ({response}) => {186 // You could do something with the response, for example, logging.187 log(response);188 189 // Or return a `Response` instance to overwrite the response.190 return new Response('A different response', {status: 200});191 },192 193 // Or retry with a fresh token on a 401 error191- async (request, _options, response, state) => {192- if (response.status === 401 && state.retryCount === 0) {194+ async ({request, response, retryCount}) => {195+ if (response.status === 401 && retryCount === 0) {196 // Only refresh on first 401, not on subsequent retries197 const {token} = await ky.post('https://example.com/auth/refresh').json();198 199 const headers = new Headers(request.headers);6 unmodified lines206 }207 },208 209 // Or force retry based on response body content207- async (request, options, response) => {210+ async ({response}) => {211 if (response.status === 200) {212 const data = await response.clone().json();213 if (data.error?.code === 'RATE_LIMIT') {214 // Force retry with custom delay from API response5 unmodified lines220 }221 },222 223 // Or show a notification only on the last retry for 5xx errors221- (request, options, response, {retryCount}) => {224+ ({options, response, retryCount}) => {225 if (response.status >= 500 && response.status <= 599) {226 if (retryCount === options.retry.limit) {227 showNotification('Request failed after all retries');228 }6 unmodified lines235 */236 afterResponse?: AfterResponseHook[];237 238 /**236- This hook enables you to modify the `HTTPError` right before it is thrown. The hook function receives an `HTTPError` and a state object as arguments and should return an instance of `HTTPError`.239+ This hook enables you to modify the `HTTPError` right before it is thrown. The hook function receives a state object with an `HTTPError` and retry count, and should return an instance of `HTTPError`.240 241+ The `retryCount` is `0` for the initial request and increments with each retry. This allows you to distinguish between the initial request and retries, which is useful when you need different error handling based on retry attempts (e.g., showing different error messages on the final attempt).242+243 @default []244 245 @example246 ```1 unmodified line248 249 await ky('https://example.com', {250 hooks: {251 beforeError: [247- error => {252+ ({error}) => {253 if (254 typeof error.data === 'object'255 && error.data !== null256 && 'message' in error.data5 unmodified lines262 return error;263 },264 265 // Or show different message based on retry count261- (error, {retryCount}) => {266+ ({error, retryCount}) => {267 if (retryCount === error.options.retry.limit) {268 error.message = `${error.message} (failed after ${retryCount} retries)`;269 }270 9 unmodified linesmodified:source/types/ky.ts+1 added-1 removed
145 unmodified linesExpand all14614714814915015015115215315432 unmodified lines145 unmodified linesExpand all
const api = ky.extend({ hooks: { afterResponse: [ async (request, options, response) => { async ({response}) => { // Retry based on response body content if (response.status === 200) { const data = await response.clone().json();
32 unmodified linesmodified:source/types/options.ts+1 added-1 removed
256 unmodified lines257 // Pass data to hooks258 const api = ky.create({259 hooks: {260 beforeRequest: [261- (request, options) => {261+ ({request, options}) => {262 const {token} = options.context;263 if (token) {264 request.headers.set('Authorization', `Bearer ${token}`);265 }121 unmodified linesmodified:test/context.ts+8 added-8 removed
22 unmodified lines23 context,24 retry: {limit: 0},25 hooks: {26 beforeRequest: [27- (_request, options) => {27+ ({options}) => {28 t.deepEqual(options.context, context);29 },30 ],31 afterResponse: [32- async (_input, options, _response) => {32+ async ({options}) => {33 t.deepEqual(options.context, context);34 },35 ],36 beforeError: [37- error => {37+ ({error}) => {38 t.deepEqual(error.options.context, context);39 return error;40 },41 ],28 unmodified lines70 71 await baseApi.get('', {72 hooks: {73 beforeRequest: [74- (_request, options) => {74+ ({options}) => {75 t.deepEqual(options.context, {base: 'value'});76 },77 ],78 },3 unmodified lines82 await extendedApi.get('', {83 context: {request: 'value'},84 hooks: {85 beforeRequest: [86- (_request, options) => {86+ ({options}) => {87 t.deepEqual(options.context, {base: 'value', extended: 'value', request: 'value'});88 },89 ],90 },19 unmodified lines110 context,111 retry: {limit: 2},112 hooks: {113 beforeRequest: [114- (_request, options) => {114+ ({options}) => {115 t.deepEqual(options.context, context);116 callCount++;117 },118 ],10 unmodified lines129 });130 131 await ky.get(server.url, {132 hooks: {133- beforeRequest: [(_request, options) => t.deepEqual(options.context, {})],133+ beforeRequest: [({options}) => t.deepEqual(options.context, {})],134 },135 }).json();136 });137 21 unmodified lines159 160 await extendedApi.get('', {161 hooks: {162 beforeRequest: [163- (_request, options) => {163+ ({options}) => {164 const context = options.context as any;165 t.is(context.auth.apiKey, 'extended');166 t.is(context.auth.userId, undefined);167 t.is(context.settings.timeout, undefined);7 unmodified linesmodified:test/formdata-searchparams.ts+1 added-1 removed
95 unmodified lines96 const result = await ky.post(server.url, {97 body: formData,98 hooks: {99 afterResponse: [100- async (request, options, response) => {100+ async ({request, options, response}) => {101 if (response.status === 401) {102 return ky(request, options);103 }104 },7 unmodified linesmodified:test/hooks.ts+56 added-56 removed
40 unmodified lines41 .post(server.url, {42 json,43 hooks: {44 beforeRequest: [45- async (request, options) => {45+ async ({request, options}) => {46 await delay(100);47 const bodyJson = JSON.parse(options.body as string);48 bodyJson.foo = false;49 return new Request(request, {body: JSON.stringify(bodyJson)});33 unmodified lines83 .post(server.url, {84 json,85 hooks: {86 beforeRequest: [87- (request, options) => {87+ ({request, options}) => {88 const bodyJson = JSON.parse(options.body as string);89 bodyJson.foo = false;90 return new Request(request, {body: JSON.stringify(bodyJson)});91 },20 unmodified lines112 .post(server.url, {113 json,114 hooks: {115 afterResponse: [116- async (_input, _options, response) => {116+ async ({response}) => {117 t.is(response.status, 200);118 t.deepEqual(await response.json(), json);119 },120 ],13 unmodified lines134 135 await ky.get(server.url, {136 hooks: {137 afterResponse: [138- async (_request, _options, response) => {138+ async ({response}) => {139 if (response.body) {140 const originalCancel = response.body.cancel.bind(response.body);141 response.body.cancel = async () => {142 didCancelClonedResponseBody = true;21 unmodified lines164 const responseText = await ky('https://example.com', {165 fetch: customFetch,166 hooks: {167 afterResponse: [168- (_request, _options, response) => {168+ ({response}) => {169 clonedResponse = response;170 return new Response('replacement');171 },172 ],17 unmodified lines190 const responseText = await ky('https://example.com', {191 fetch: customFetch,192 hooks: {193 afterResponse: [194- (_request, _options, response) => response,194+ ({response}) => response,195 ],196 },197 }).text();198 14 unmodified lines213 const responseText = await ky('https://example.com', {214 fetch: customFetch,215 hooks: {216 afterResponse: [217- (_request, _options, response) => {217+ ({response}) => {218 clones.push(response);219 // Return nothing - clone should be cancelled220 },221- (_request, _options, response) => {221+ ({response}) => {222 clones.push(response);223 // Return nothing - clone should be cancelled224 },225- (_request, _options, response) => {225+ ({response}) => {226 clones.push(response);227 // Return nothing - clone should be cancelled228 },229 ],25 unmodified lines255 ky('https://example.com', {256 fetch: customFetch,257 hooks: {258 afterResponse: [259- (_request, _options, response) => {259+ ({response}) => {260 clonedResponse = response;261 throw expectError;262 },263 ],21 unmodified lines285 .post(server.url, {286 json,287 hooks: {288 afterResponse: [289- async (_input, _options, response) => {289+ async ({response}) => {290 t.is(response.status, 500);291 t.deepEqual(await response.json(), json);292 },293 ],22 unmodified lines316 () =>317 new Response(modifiedBody1, {318 status: modifiedStatus1,319 }),320- async (_input, _options, response) => {320+ async ({response}) => {321 t.is(response.status, modifiedStatus1);322 t.is(await response.text(), modifiedBody1);323 324 return new Response(modifiedBody2, {64 unmodified lines389 await ky390 .get(server.url, {391 hooks: {392 afterResponse: [393- (_input, _options, response) => {393+ ({response}) => {394 called = true;395 return response;396 },397 ],25 unmodified lines423 .post(server.url, {424 json,425 hooks: {426 afterResponse: [427- async (request, options, response) => {427+ async ({request, options, response}) => {428 if (response.status === 403) {429 // Retry request with valid token430 return ky(request, {431 ...options,32 unmodified lines464 return {awesome: true};465 },466 hooks: {467 afterResponse: [468- async (_request, _options, response) => {468+ async ({response}) => {469 t.true(response instanceof Response);470 t.deepEqual(await response.json(), {awesome: true});471 },472 ],365 unmodified lines838 await t.throwsAsync(839 ky.post(server.url, {840 hooks: {841 beforeError: [842- (error: HTTPError) => {842+ ({error}) => {843 const {response} = error;844 845 if (response?.body) {846 error.name = 'GitHubError';22 unmodified lines869 await t.throwsAsync(870 ky.post(server.url, {871 hooks: {872 beforeError: [873- async (error: HTTPError) => {873+ async ({error}) => {874 const body = error.data as {reason: string};875 876 error.name = 'GitHubError';877 error.message = `${body.reason} --- (${error.response.status})`.trim();29 unmodified lines907 908 const result = await ky.get(server.url, {909 hooks: {910 beforeRequest: [911- (request, _options, {retryCount}) => {911+ ({request, retryCount}) => {912 retryCounts.push(retryCount);913 // Only set default token on initial request914 if (retryCount === 0) {915 request.headers.set('Authorization', 'token initial-token');24 unmodified lines940 941 await ky.get(server.url, {942 hooks: {943 beforeRequest: [944- (_request, options) => {944+ ({options}) => {945 // Verify hooks field is not present946 t.false('hooks' in options);947 948 // Verify options object is frozen (can't add/modify properties)34 unmodified lines983 limit: 2,984 },985 hooks: {986 afterResponse: [987- (_request, _options, _response, state) => {988- t.is(typeof state.retryCount, 'number');989- retryCounts.push(state.retryCount);987+ ({retryCount}) => {988+ t.is(typeof retryCount, 'number');989+ retryCounts.push(retryCount);990 },991 ],992 },993 });20 unmodified lines1014 limit: 2,1015 },1016 hooks: {1017 beforeError: [1018- (error: HTTPError, state) => {1018+ ({error, retryCount}) => {1019 // Verify retryCount exists in state and is a number1020- t.is(typeof state.retryCount, 'number');1021- t.true(state.retryCount >= 0);1022- errorRetryCount = state.retryCount;1020+ t.is(typeof retryCount, 'number');1021+ t.true(retryCount >= 0);1022+ errorRetryCount = retryCount;1023 return error;1024 },1025 ],1026 },133 unmodified lines1160 limit: 2,1161 },1162 hooks: {1163 afterResponse: [1164- async (_request, _options, response) => {1164+ async ({response}) => {1165 const data = await response.clone().json();1166 if (data.error?.code === 'RATE_LIMIT') {1167 return ky.retry();1168 }24 unmodified lines1193 const result = await ky('https://example.test', {1194 fetch: customFetch,1195 hooks: {1196 afterResponse: [1197- (_request, _options, response) => {1197+ ({response}) => {1198 response.clone();1199 if (response.status === 401) {1200 return ky.retry();1201 }27 unmodified lines1229 limit: 2,1230 },1231 hooks: {1232 afterResponse: [1233- async (_request, _options, response) => {1233+ async ({response}) => {1234 const data = await response.clone().json();1235 if (data.error?.code === 'RATE_LIMIT') {1236 return ky.retry({1237 delay: data.error.retryAfter * 1000,27 unmodified lines1265 limit: 2,1266 },1267 hooks: {1268 afterResponse: [1269- async (_request, _options, response) => {1269+ async ({response}) => {1270 const data = await response.clone().json();1271 if (data.error?.code === 'RATE_LIMIT') {1272 return ky.retry();1273 }31 unmodified lines1305 limit: 2,1306 },1307 hooks: {1308 afterResponse: [1309- async (_request, _options, response) => {1309+ async ({response}) => {1310 const data = await response.clone().json();1311 if (data.error?.code === 'RATE_LIMIT') {1312 return ky.retry({code: 'RATE_LIMIT'});1313 }40 unmodified lines1354 },1355 },1356 hooks: {1357 afterResponse: [1358- async (_request, _options, response) => {1358+ async ({response}) => {1359 const data = await response.clone().json();1360 if (data.error?.code === 'CUSTOM_ERROR') {1361 return ky.retry();1362 }29 unmodified lines1392 limit: 2,1393 },1394 hooks: {1395 afterResponse: [1396- async (_request, _options, response) => {1396+ async ({response}) => {1397 const data = await response.clone().json();1398 if (data.error?.code === 'RATE_LIMIT') {1399 return ky.retry();1400 }27 unmodified lines1428 limit: 2,1429 },1430 hooks: {1431 afterResponse: [1432- async (_request, _options, response) => {1432+ async ({response}) => {1433 firstHookCallCount++;1434 const data = await response.clone().json();1435 if (data.error?.code === 'RATE_LIMIT') {1436 return ky.retry();30 unmodified lines1467 limit: 2,1468 },1469 hooks: {1470 afterResponse: [1471- async (_request, _options, response) => {1471+ async ({response}) => {1472 const data = await response.clone().json();1473 if (data.error?.code === 'RETRY_NOW') {1474 return ky.retry({delay: 0}); // Instant retry, no delay1475 }23 unmodified lines1499 1500 const result = await ky.get(`${server.url}/primary`, {1501 hooks: {1502 afterResponse: [1503- async (request, _options, response) => {1503+ async ({request, response}) => {1504 const data = await response.clone().json();1505 if (data.error?.code === 'FALLBACK_TO_BACKUP') {1506 return ky.retry({1507 request: new Request(`${server.url}/backup`, {30 unmodified lines1538 const result = await ky.get(server.url, {1539 headers: {'X-Auth-Token': 'original-token'},1540 hooks: {1541 afterResponse: [1542- async (request, _options, response) => {1542+ async ({request, response}) => {1543 const data = await response.clone().json();1544 if (data.error?.code === 'TOKEN_REFRESH' && data.error.newToken) {1545 return ky.retry({1546 request: new Request(request, {34 unmodified lines1581 1582 const result = await ky.post(server.url, {1583 hooks: {1584 afterResponse: [1585- async (request, _options, response) => {1585+ async ({request, response}) => {1586 const data = await response.clone().json();1587 if (data.error?.code === 'METHOD_OVERLOAD' && request.method === 'POST') {1588 return ky.retry({1589 request: new Request(request, {30 unmodified lines1620 1621 const result = await ky.get(server.url, {1622 hooks: {1623 afterResponse: [1624- async (request, _options, response) => {1624+ async ({request, response}) => {1625 const data = await response.clone().json();1626 if (data.error?.code === 'RETRY_WITH_CUSTOM_REQUEST') {1627 return ky.retry({1628 request: new Request(request, {50 unmodified lines1679 ky.get(server.url, {1680 retry: {limit: 2},1681 hooks: {1682 afterResponse: [1683- async (request, _options, response) => {1683+ async ({request, response}) => {1684 const data = await response.clone().json();1685 if (data.error?.code === 'ALWAYS_RETRY') {1686 // Always force retry with custom request1687 return ky.retry({26 unmodified lines1714 1715 const result = await ky.get(server.url, {1716 hooks: {1717 afterResponse: [1718- async (request, _options, response) => {1718+ async ({request, response}) => {1719 const data = await response.clone().json();1720 if (data.error?.code === 'CUSTOM_REQUEST_RETRY') {1721 return ky.retry({1722 request: new Request(request),39 unmodified lines1762 1763 const result = await ky.get(`${server.url}/primary`, {1764 hooks: {1765 afterResponse: [1766- async (request, _options, response) => {1766+ async ({request, response}) => {1767 const data = await response.clone().json();1768 if (data.error?.code === 'FALLBACK_WITH_DELAY') {1769 return ky.retry({1770 request: new Request(`${server.url}/backup`, {33 unmodified lines1804 const result = await ky.post(server.url, {1805 json: {original: true},1806 hooks: {1807 afterResponse: [1808- async (request, _options, response) => {1808+ async ({request, response}) => {1809 const data = await response.clone().json();1810 if (data.error?.code === 'RETRY_WITH_MODIFIED_BODY') {1811 return ky.retry({1812 request: new Request(request.url, {33 unmodified lines1846 timeout: 1000, // Timeout configured but shouldn't trigger1847 retry: {limit: 2},1848 hooks: {1849 afterResponse: [1850- async (request, _options, response) => {1850+ async ({request, response}) => {1851 const data = await response.clone().json();1852 if (data.error?.code === 'NEED_FALLBACK') {1853 // Custom request should inherit proper timeout signal1854 return ky.retry({28 unmodified lines1883 1884 const result = await ky.get(server.url, {1885 hooks: {1886 afterResponse: [1887- async (request, _options, response) => {1887+ async ({request, response}) => {1888 const data = await response.clone().json();1889 if (data.error?.code === 'NEED_CUSTOM_REQUEST') {1890 // Create custom request with aborted signal1891 const abortController = new AbortController();38 unmodified lines1930 limit: 2,1931 },1932 hooks: {1933 afterResponse: [1934- async (_request, _options, response) => {1934+ async ({response}) => {1935 const data = await response.clone().json();1936 if (data.error?.code === 'NEEDS_VALIDATION') {1937 return ky.retry({1938 code: 'VALIDATION_ERROR',39 unmodified lines1978 limit: 2,1979 },1980 hooks: {1981 afterResponse: [1982- async (_request, _options, response) => {1982+ async ({response}) => {1983 const data = await response.clone().json();1984 if (data.error?.code === 'NEEDS_VALIDATION') {1985 // JS users (or TS users bypassing types) can pass non-Error values1986 return ky.retry({41 unmodified lines2028 limit: 2,2029 },2030 hooks: {2031 afterResponse: [2032- async (_request, _options, response) => {2032+ async ({response}) => {2033 if (response.status === 401) {2034 return ky.retry();2035 }2036 },31 unmodified lines2068 2069 const api = ky.extend({2070 hooks: {2071 afterResponse: [2072- async (request, _options, response, state) => {2073- if (response.status === 401 && state.retryCount === 0) {2072+ async ({request, response, retryCount}) => {2073+ if (response.status === 401 && retryCount === 0) {2074 const {token} = await ky.post(`${server.url}/auth/refresh`).json<{token: string}>();2075 2076 const headers = new Headers(request.headers);2077 headers.set('Authorization', `Bearer ${token}`);40 unmodified lines2118 2119 const api = ky.extend({2120 hooks: {2121 afterResponse: [2122- async (request, _options, response, state) => {2123- if (response.status === 401 && state.retryCount === 0) {2122+ async ({request, response, retryCount}) => {2123+ if (response.status === 401 && retryCount === 0) {2124 const {token} = await ky.post(`${server.url}/auth/refresh`).json<{token: string}>();2125 2126 const headers = new Headers(request.headers);2127 headers.set('Authorization', `Bearer ${token}`);45 unmodified lines2173 2174 const api = ky.extend({2175 hooks: {2176 afterResponse: [2177- async (request, _options, response, state) => {2178- if (response.status === 401 && state.retryCount === 0) {2177+ async ({request, response, retryCount}) => {2178+ if (response.status === 401 && retryCount === 0) {2179 const {token} = await ky.post(`${server.url}/auth/refresh`).json<{token: string}>();2180 2181 const headers = new Headers(request.headers);2182 headers.set('Authorization', `Bearer ${token}`);46 unmodified lines2229 2230 const api = ky.extend({2231 hooks: {2232 afterResponse: [2233- async (request, _options, response, state) => {2234- if (response.status === 401 && state.retryCount === 0) {2233+ async ({request, response, retryCount}) => {2234+ if (response.status === 401 && retryCount === 0) {2235 const {token} = await ky.post(`${server.url}/auth/refresh`).json<{token: string}>();2236 2237 const headers = new Headers(request.headers);2238 headers.set('Authorization', `Bearer ${token}`);29 unmodified linesmodified:test/http-error.ts+2 added-2 removed
208 unmodified lines209 let hookData: unknown;210 await t.throwsAsync(ky.get(server.url, {211 hooks: {212 beforeError: [213- error => {213+ ({error}) => {214 hookData = error.data;215 return error;216 },217 ],268 unmodified lines486 retry: 0,487 timeout: false,488 hooks: {489 afterResponse: [490- (_request, _options, response) => {490+ ({response}) => {491 void response.text();492 return response;493 },494 ],38 unmodified linesmodified:test/main.ts+2 added-2 removed
536 unmodified lines537 await ky.get(server.url, {538 throwHttpErrors: false,539 hooks: {540 beforeRequest: [541- (_request, options) => {541+ ({options}) => {542 booleanTypeInHook = options.throwHttpErrors;543 },544 ],545 },7 unmodified lines553 await ky.get(server.url, {554 throwHttpErrors: throwFunction,555 hooks: {556 beforeRequest: [557- (_request, options) => {557+ ({options}) => {558 functionTypeInHook = options.throwHttpErrors;559 },560 ],561 },483 unmodified linesmodified:test/methods.ts+3 added-3 removed
11 unmodified lines12 ky(server.url, {13 method: 'get',14 hooks: {15 beforeRequest: [16- (_input, options) => {16+ ({options}) => {17 t.is(options.method, 'GET');18 },19 ],20 },12 unmodified lines33 await t.notThrowsAsync(34 ky(server.url, {35 hooks: {36 beforeRequest: [37- (_input, options) => {37+ ({options}) => {38 t.is(options.method, 'GET');39 },40 ],41 },14 unmodified lines56 ky(server.url, {57 method: 'report',58 hooks: {59 beforeRequest: [60- (_input, options) => {60+ ({options}) => {61 t.is(options.method, 'report');62 },63 ],64 },13 unmodified linesmodified:test/stream.ts+3 added-3 removed
138 unmodified lines139 attemptEvents.push([]);140 },141 ],142 afterResponse: [143- async (request, _normalizedOptions, response) => {143+ async ({request, response}) => {144 if (response.status === 500) {145 return ky.retry({request: new Request(request)});146 }147 },54 unmodified lines202 methods: ['post'],203 },204 hooks: {205 afterResponse: [206- async (request, _normalizedOptions, response) => {206+ async ({request, response}) => {207 if (response.status === 500) {208 return ky.retry({request: new Request(request)});209 }210 },122 unmodified lines333 attempts.push([]);334 },335 ],336 afterResponse: [337- async (request, _normalizedOptions, response) => {337+ async ({request, response}) => {338 if (response.status === 500) {339 return ky.retry({340 request: new Request(request, {body: updatedPayloadString}),341 });105 unmodified linesmodified:readme.md+22 added-22 removed
345 unmodified lines346 347 Type: `Function[]`\348 Default: `[]`349 350-This hook enables you to modify the request right before it is sent. Ky will make no further changes to the request after this. The hook function receives the normalized request, options, and a state object. You could, for example, modify the `request.headers` here.350+This hook enables you to modify the request right before it is sent. Ky will make no further changes to the request after this. The hook function receives a state object with the normalized request, options, and retry count. You could, for example, modify the `request.headers` here.351 352-The `state.retryCount` is `0` for the initial request and increments with each retry. This allows you to distinguish between initial requests and retries, which is useful when you need different behavior for retries (e.g., avoiding overwriting headers set in `beforeRetry`).352+The `retryCount` is `0` for the initial request and increments with each retry. This allows you to distinguish between initial requests and retries, which is useful when you need different behavior for retries (e.g., avoiding overwriting headers set in `beforeRetry`).353 354 The hook can return a [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) to replace the outgoing request, or return a [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) to completely avoid making an HTTP request. This can be used to mock a request, check an internal cache, etc. An **important** consideration when returning a request or response from this hook is that any remaining `beforeRequest` hooks will be skipped, so you may want to only return them from the last hook.355 356 ```js1 unmodified line358 359 const api = ky.extend({360 hooks: {361 beforeRequest: [362- (request, options, {retryCount}) => {362+ ({request, retryCount}) => {363 // Only set default auth header on initial request, not on retries364 // (retries may have refreshed token set by beforeRetry)365 if (retryCount === 0) {366 request.headers.set('Authorization', 'token initial-token');10 unmodified lines377 378 Type: `Function[]`\379 Default: `[]`380 381-This hook enables you to modify the request right before retry. Ky will make no further changes to the request after this. The hook function receives an object with the normalized request and options, an error instance, and the retry count. You could, for example, modify `request.headers` here.381+This hook enables you to modify the request right before retry. Ky will make no further changes to the request after this. The hook function receives a state object with the normalized request, options, an error instance, and the retry count. You could, for example, modify `request.headers` here.382 383 The hook can return a [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) to replace the outgoing retry request, or return a [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) to skip the retry and use that response instead. **Note:** Returning a request or response skips remaining `beforeRetry` hooks.384 385 The `retryCount` is always `>= 1` since this hook is only called during retries, not on the initial request.68 unmodified lines454 455 Type: `Function[]`\456 Default: `[]`457 458-This hook enables you to modify the `HTTPError` right before it is thrown. The hook function receives an `HTTPError` and a state object as arguments and should return an instance of `HTTPError`.458+This hook enables you to modify the `HTTPError` right before it is thrown. The hook function receives a state object with an `HTTPError` and retry count, and should return an instance of `HTTPError`.459 460-The `state.retryCount` is `0` for the initial request and increments with each retry. This allows you to distinguish between the initial request and retries, which is useful when you need different error handling based on retry attempts (e.g., showing different error messages on the final attempt).460+The `retryCount` is `0` for the initial request and increments with each retry. This allows you to distinguish between the initial request and retries, which is useful when you need different error handling based on retry attempts (e.g., showing different error messages on the final attempt).461 462 ```js463 import ky from 'ky';464 465 await ky('https://example.com', {466 hooks: {467 beforeError: [468- error => {468+ ({error}) => {469 if (470 typeof error.data === 'object'471 && error.data !== null472 && 'message' in error.data5 unmodified lines478 return error;479 },480 481 // Or show different message based on retry count482- (error, state) => {483- if (state.retryCount === error.options.retry.limit) {484- error.message = `${error.message} (failed after ${state.retryCount} retries)`;482+ ({error, retryCount}) => {483+ if (retryCount === error.options.retry.limit) {484+ error.message = `${error.message} (failed after ${retryCount} retries)`;485 }486 487 return error;488 }6 unmodified lines495 496 Type: `Function[]`\497 Default: `[]`498 499-This hook enables you to read and optionally modify the response. The hook function receives normalized request, options, a clone of the response, and a state object. The return value of the hook function will be used by Ky as the response object if it's an instance of [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response).499+This hook enables you to read and optionally modify the response. The hook function receives a state object with the normalized request, options, a clone of the response, and retry count. The return value of the hook function will be used by Ky as the response object if it's an instance of [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response).500 501 You can also force a retry by returning [`ky.retry(options)`](#kyretryoptions). This is useful when you need to retry based on the response body content, even if the response has a successful status code. The retry will respect the `retry.limit` option and be observable in `beforeRetry` hooks.502 503-The `state.retryCount` is `0` for the initial request and increments with each retry. This allows you to distinguish between initial requests and retries, which is useful when you need different behavior for retries (e.g., showing a notification only on the final retry).503+The `retryCount` is `0` for the initial request and increments with each retry. This allows you to distinguish between initial requests and retries, which is useful when you need different behavior for retries (e.g., showing a notification only on the final retry).504 505 ```js506 import ky from 'ky';507 508 const response = await ky('https://example.com', {509 hooks: {510 afterResponse: [511- (_request, _options, response) => {511+ ({response}) => {512 // You could do something with the response, for example, logging.513 log(response);514 515 // Or return a `Response` instance to overwrite the response.516 return new Response('A different response', {status: 200});517 },518 519 // Or retry with a fresh token on a 401 error520- async (request, _options, response, state) => {521- if (response.status === 401 && state.retryCount === 0) {520+ async ({request, response, retryCount}) => {521+ if (response.status === 401 && retryCount === 0) {522 // Only refresh on first 401, not on subsequent retries523 const {token} = await ky.post('https://example.com/auth/refresh').json();524 525 const headers = new Headers(request.headers);6 unmodified lines532 }533 },534 535 // Or force retry based on response body content536- async (request, options, response) => {536+ async ({response}) => {537 if (response.status === 200) {538 const data = await response.clone().json();539 if (data.error?.code === 'RATE_LIMIT') {540 // Retry with custom delay from API response5 unmodified lines546 }547 },548 549 // Or show a notification only on the last retry for 5xx errors550- (request, options, response, {retryCount}) => {550+ ({options, response, retryCount}) => {551 if (response.status >= 500 && response.status <= 599) {552 if (retryCount === options.retry.limit) {553 showNotification('Request failed after all retries');554 }157 unmodified lines712 // Pass data to hooks713 const api = ky.create({714 hooks: {715 beforeRequest: [716- (request, options) => {716+ ({request, options}) => {717 const {token} = options.context;718 if (token) {719 request.headers.set('Authorization', `Bearer ${token}`);720 }215 unmodified lines936 937 const api = ky.extend({938 hooks: {939 afterResponse: [940- async (request, options, response) => {940+ async ({request, response}) => {941 // Retry based on response body content942 if (response.status === 200) {943 const data = await response.clone().json();944 89 unmodified lines1034 ```js1035 await ky('https://example.com', {1036 hooks: {1037 beforeError: [1038- error => {1038+ ({error}) => {1039 if (error.data !== undefined) {1040 error.message = `${error.message}: ${JSON.stringify(error.data)}`;1041 }1042 50 unmodified lines1093 const response = await ky.post(url, {1094 body: formData,1095 hooks: {1096 beforeRequest: [1097- request => {1097+ ({request}) => {1098 const newFormData = new FormData();1099 1100 // Modify FormData as needed1101 for (const [key, value] of formData) {178 unmodified lines1280 1281 const api = ky.extend({1282 hooks: {1283 beforeError: [1284- async error => {1284+ async ({error}) => {1285 (error as CustomError).customProperty = 'value';1286 return error;1287 }1288 ]74 unmodified lines