Skip to content
Myr

Explain both causes of a missing response and document the new validation

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Sindre Sorhus · committed by Sindre Sorhus · parent 33462fc · Browse files · 10 files+69 added−39 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

10 files+69 added−39 removed

  • tests:+15 added−1 removed
  • other:+54 added−38 removed

10 files+69 added−39 removed

modified:source/core/constants.ts+3 added-1 removed
55 unmodified lines
5657// The maximum value of a 32bit int (see issue #117)58export const maxSafeTimeout = 2_147_483_647;5960// Size in bytes of a typical form boundary (e.g., '------WebKitFormBoundaryaxpyiPgbbPti10Rw'), used to help estimate upload size60// Size in bytes of a typical form boundary (e.g., '------WebKitFormBoundaryaxpyiPgbbPti10Rw'), used to help estimate upload size. Bun's boundary is 54 bytes, so there the estimate runs 14 bytes per part low, which is negligible next to any real upload, and the final event always reports the real total.61export const usualFormBoundarySize = 40;6263/**64Symbol that can be returned by a `beforeRetry` hook to stop retrying without throwing an error.
109 unmodified lines
174Force a retry from an `afterResponse` hook.175176This allows you to retry a request based on the response content, even if the response has a successful status code. The retry will respect the `retry.limit` option and skip the `shouldRetry` check. The forced retry is observable in `beforeRetry` hooks, where the error will be a `ForceRetryError`.177178A marker returned by a second copy of Ky, which happens with a duplicated dependency, is still recognised, the same way the Ky error guards accept branded errors.179180@param options - Optional configuration for the retry.181182@example183```
116 unmodified lines
modified:source/core/Ky.ts+3 added-1 removed
78 unmodified lines
79 return new TextDecoder();80};8182const invalidSchemaMessage = 'The `schema` argument must follow the Standard Schema specification';83const missingResponseMessage = 'The request resolved without a response. Returning `ky.stop` from a `beforeRetry` hook is not compatible with body method shortcuts. Throw from the hook instead.';83const missingResponseMessage = 'The request resolved without a response, so there is no body to read.'84 + ' Returning `ky.stop` from a `beforeRetry` hook, or a custom `fetch` that resolves with nothing, both do that.'85 + ' Throw from the hook instead of returning `ky.stop`.';8687// Both timeout options are milliseconds or `false`. A non-finite or negative value used to reach `setTimeout()`,88// which silently clamps it to ~1ms, or to be ignored entirely when `totalTimeout` was not a number.89const validateTimeoutOption = (value: unknown, name: 'timeout' | 'totalTimeout'): void => {
1498 unmodified lines
modified:source/types/ky.ts+6 added-5 removed
121 unmodified lines
122123 /**124 A `Symbol` that can be returned by a `beforeRetry` hook to stop the retry. This will also short circuit the remaining `beforeRetry` hooks.125126 Note: Returning this symbol makes Ky abort and return with an `undefined` response. Be sure to check for a response before accessing any properties on it or use [optional chaining](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining). It is also incompatible with body methods, such as `.json()` or `.text()`, because there is no response to parse. In general, we recommend throwing an error instead of returning this symbol, as that will cause Ky to abort and then throw, which avoids these limitations.126 Note: Returning this symbol makes Ky abort and return with an `undefined` response. Be sure to check for a response before accessing any properties on it or use [optional chaining](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining). It is also incompatible with body methods, such as `.json()` or `.text()`, because there is no response to parse. Calling one throws a `TypeError` explaining this. In general, we recommend throwing an error instead of returning this symbol, as that will cause Ky to abort and then throw, which avoids these limitations.127128 A valid use-case for `ky.stop` is to prevent retries when making requests for side effects, where the returned data is not important. For example, logging client activity to the server.129130 @example131 ```132 import ky from 'ky';133134 // Note that response will be `undefined` in case `ky.stop` is returned.134 // Note that `response` will be `undefined` in case `ky.stop` is returned.135 const response = await ky.post('https://example.com', {136 hooks: {137 beforeRetry: [138 async ({error}) => {138 async ({request, options, error, retryCount}) => {139 const shouldStopRetry = await ky('https://example.com/api');140 if (shouldStopRetry) {141 return ky.stop;142 }
1 unmodified line
144 ]145 }146 });147148 // Using `.text()` or other body methods is not supported.149 // const text = await ky('https://example.com', options).text();148 // Using `.text()` or other body methods is not supported, because there is no response to parse.149 ```150 */151 readonly stop: typeof stop;152
1 unmodified line
154 Force a retry from an `afterResponse` hook.155156 This allows you to retry a request based on the response content, even if the response has a successful status code. The retry will respect the `retry.limit` option and skip the `shouldRetry` check. The forced retry is observable in `beforeRetry` hooks, where the error will be a `ForceRetryError`.157158 A marker returned by a second copy of Ky, which happens with a duplicated dependency, is still recognised, the same way the Ky error guards accept branded errors.159160 @example161 ```162 import ky, {isForceRetryError} from 'ky';163
40 unmodified lines
modified:source/types/options.ts+1 added-19 removed
291 unmodified lines
292 @param chunk - Data that was received. When an empty response body stream completes, the callback receives an empty chunk.293294 `content-length` is only used as the total for a response that is not content-coded, since it counts encoded bytes while the progress stream counts the bytes after decompression. A compressed response therefore reports `totalBytes: 0` until it completes, which means the percentage cannot be calculated while downloading.295296 Responses with no body at all are not streamed, so no progress events are emitted for them. That covers a [null body status](https://fetch.spec.whatwg.org/#null-body-status) such as `204`, and a `HEAD` request, which has no body even on an ordinary status. A response whose body an `afterResponse` hook already read, or locked with a reader, is passed through unchanged, so it reports no progress either.296 Responses with no body at all are not streamed, so no progress events are emitted for them. That covers a [null body status](https://fetch.spec.whatwg.org/#null-body-status) such as `204`, and a `HEAD` response in runtimes that give it no body, such as browsers, Node.js and Deno. Bun gives a `HEAD` response an empty body, so it reports one final event with `transferredBytes: 0`. A response whose body an `afterResponse` hook already read, or locked with a reader, is passed through unchanged, so it reports no progress either.297298 When the callback throws, the error is reported by Ky's body method shortcuts. A response read directly with `response.text()` or `response.json()` may instead report the runtime's own stream error, such as Chromium's generic `TypeError`.299300 @example
149 unmodified lines
450export interface Options extends KyOptions, RequestOptions { // eslint-disable-line @typescript-eslint/consistent-type-definitions -- This must stay an interface so that it can be extended outside of Ky for use in `ky.create`.451 /**452 HTTP method used to make the request.453454 Ky forwards every option it does not recognize straight to `fetch()`, so fetch-only extensions are supported even455 when the ambient `RequestInit` type does not declare them. The two documented below are declared here for that456 reason; any other extension is accepted at runtime and needs a type assertion.457 */458459 /**460 An undici `Agent` or `Dispatcher`, forwarded to `fetch()` as-is.461 */462 dispatcher?: unknown;463464 /**465 A framework-specific fetch extension, such as Next.js's `next`, forwarded to `fetch()` as-is.466 */467 next?: unknown;468469 /**470 HTTP method used to make the request.471454 Internally, the standard methods (`GET`, `POST`, `PUT`, `PATCH`, `HEAD`, `DELETE`, and `QUERY`) are uppercased in order to avoid server errors due to case sensitivity.455 */456 method?: LiteralUnion<HttpMethod, string> | undefined;457
93 unmodified lines
modified:source/types/ResponsePromise.ts+1 added-1 removed
modified:source/utils/merge.ts+2 added-2 removed
414 unmodified lines
415 value = {limit: value};416 }417 }418419 if (isRoot && key === 'retry' && isPlainObject(value) && (isReplace || !isMergeable(returnValue[key]))) {420 // Resolve nested replacement markers even when there is no parent retry configuration to merge.419 if (isRoot && isPlainObject(value) && (isReplace || !isMergeable(returnValue[key]))) {420 // Resolve nested replacement markers even when there is no parent configuration to merge.421 value = deepMergeInternal<unknown>(false, {}, value);422 } else if (!isReplace && isMergeable(returnValue[key]) && isMergeable(value) && Array.isArray(returnValue[key]) === Array.isArray(value)) {423 value = deepMergeInternal<unknown>(false, returnValue[key], value);424 }
56 unmodified lines
modified:test/hooks.ts+6 added-1 removed
12 unmodified lines
13} from '../source/index.js';14import {type Options, type NormalizedOptions} from '../source/types/options.js';15import {createHttpTestServer} from './helpers/create-http-test-server.js';1617// Kept in sync with `missingResponseMessage` in source/core/Ky.ts.18const noResponseMessage = 'The request resolved without a response, so there is no body to read.'19 + ' Returning `ky.stop` from a `beforeRetry` hook, or a custom `fetch` that resolves with nothing, both do that.'20 + ' Throw from the hook instead of returning `ky.stop`.';2122const withHeader = (request: Request, name: string, value: string) => {23 const headers = new Headers(request.headers);24 headers.set(name, value);25 return new Request(request, {headers});
6891 unmodified lines
6917 beforeRetry: [() => ky.stop],6918 },6919 })[type](), {6920 name: 'TypeError',6916 message: 'The request resolved without a response. Returning `ky.stop` from a `beforeRetry` hook is not compatible with body method shortcuts. Throw from the hook instead.',6921 message: noResponseMessage,6922 });6923 });6924}6925
586 unmodified lines
modified:test/main.ts+9 added
2580 unmodified lines
2581 t.deepEqual(result, {foo: 'bar', baz: 'baz'});2582 t.false('context' in result);2583});25842585test('json merging resolves nested replacement markers without a parent property', async t => {2586 const api = ky.create({2587 fetch: async request => new Response(await request.text()),2588 });2589 const extended = api.extend({json: {items: replaceOption(['new'])}});25902591 t.deepEqual(await extended.post('https://example.com').json(), {items: ['new']});2592});25932594for (const [original, replacement] of [2595 [['old'], {value: 'new'}],2596 [{value: 'old'}, ['new']],2597] as const) {
1718 unmodified lines
modified:test-d/fetch-extensions.ts+16 added-4 removed
1import {expectTypeOf} from 'expect-type';2import type {Options} from 'ky';33// Ky forwards options it does not recognize to `fetch()`, so a fetch-only extension must be accepted even though4// the ambient `RequestInit` type does not declare it.5const withDispatcher: Options = {dispatcher: {fake: true}};4type NextFetchRequestConfig = {5 revalidate?: number | false;6 tags?: string[];7};89// Frameworks and runtimes declare their fetch-only extensions on the global `RequestInit`, the way Next.js declares `next` and `@types/node` declares `dispatcher`. Ky must pick up that type rather than redeclare the option, which conflicts with the ambient declaration.10declare global {11 // eslint-disable-next-line @typescript-eslint/consistent-type-definitions -- Global augmentation requires an interface.12 interface RequestInit {13 next?: NextFetchRequestConfig;14 }15}1617const withNext: Options = {next: {revalidate: 0}};188void withDispatcher;19expectTypeOf<Options['next']>().toEqualTypeOf<NextFetchRequestConfig | undefined>();2021void withNext;
modified:readme.md+22 added-5 removed
400 unmodified lines
401402Type: `number | false`\403Default: `10000`404405Per-attempt timeout in milliseconds for getting a response, applied independently to each retry. Ky shortcut methods also use this value as a separate timeout for reading the response body. Cannot be greater than 2147483647. See also [`totalTimeout`](#totaltimeout).405Per-attempt timeout in milliseconds for getting a response, applied independently to each retry. Ky shortcut methods also use this value as a separate timeout for reading the response body. Must be a non-negative number no greater than 2147483647, or `false`; anything else throws a `TypeError`. See also [`totalTimeout`](#totaltimeout).406407If set to `false`, there will be no per-attempt timeout.408409If the signal you passed in is aborted while a body method is reading, or just after the read finished, the body method rejects with the abort reason rather than resolving with the bytes that already arrived.410411##### totalTimeout412413Type: `number | false`\414Default: `false`415414Overall timeout in milliseconds for the entire operation, including retries and delays. Throws a `TimeoutError` if exceeded. Cannot be greater than 2147483647.416Overall timeout in milliseconds for the entire operation, including retries and delays. Throws a `TimeoutError` if exceeded. Must be a non-negative number no greater than 2147483647, or `false`; anything else throws a `TypeError`.417418`beforeError` hooks run after an error is produced and are not bounded by `totalTimeout`.419420If set to `false` or not specified, there is no overall timeout.
32 unmodified lines
453 maxResponseSize: 20 * 1024 * 1024,454}).json();455```456457##### dispatcher458459An [undici](https://github.com/nodejs/undici) `Agent` or `Dispatcher`, forwarded to `fetch()` as-is. Ky does not use it, it just passes it through.460461##### next462463A framework-specific fetch extension, such as [Next.js's `next`](https://nextjs.org/docs/app/api-reference/functions/next#options), forwarded to `fetch()` as-is.464465Ky forwards every option it does not recognize to `fetch()`. The type of such an option comes from the global `RequestInit` type, which `@types/node` extends with `dispatcher` and Next.js extends with `next`. An extension that your environment does not declare needs a type assertion.466467##### hooks468469Type: `object<string, Function[]>`\470Default: `{init: [], beforeRequest: [], beforeRetry: [], beforeError: [], afterResponse: []}`471472Hooks allow modifications during the request lifecycle. Hook functions may be async and are run serially, unless otherwise noted.473474Each hook must be an array of functions. A single function, a string, or any other value throws a `TypeError` rather than being silently dropped, and a nullish value means absent, so it clears the hooks it would have replaced.475476###### hooks.init477478Type: `Function[]`\479Default: `[]`
297 unmodified lines
777- `chunk` is an instance of `Uint8Array` containing the data that was received. When an empty response body stream completes, the callback receives an empty chunk.778779`content-length` is only used as the total for a response that is not content-coded, since it counts encoded bytes while the progress stream counts the bytes after decompression. A compressed response therefore reports `totalBytes: 0` until it completes, so the percentage cannot be calculated while downloading.780767Responses with no body at all are not streamed, so no progress events are emitted for them. That covers a [null body status](https://fetch.spec.whatwg.org/#null-body-status) such as `204`, and a `HEAD` request, which has no body even on an ordinary status. A response whose body an `afterResponse` hook already read, or locked with a reader, is passed through unchanged, so it reports no progress either.781Responses with no body at all are not streamed, so no progress events are emitted for them. That covers a [null body status](https://fetch.spec.whatwg.org/#null-body-status) such as `204`, and a `HEAD` response in runtimes that give it no body, such as browsers, Node.js and Deno. Bun gives a `HEAD` response an empty body, so it reports one final event with `transferredBytes: 0`. A response whose body an `afterResponse` hook already read, or locked with a reader, is passed through unchanged, so it reports no progress either.782783When the callback throws, the error is reported by Ky's body method shortcuts. A response read directly with `response.text()` or `response.json()` may instead report the runtime's own stream error, such as Chromium's generic `TypeError`.784785```js
324 unmodified lines
1110 ]1111 }1112});11131100// Using `.text()` or other body methods is not supported.1101const text = await ky('https://example.com', options).text();1114// Using `.text()` or other body methods is not supported, because there is no response to parse.1115```11161117### ky.retry(options?)11181119Force a retry from an `afterResponse` hook.11201121This allows you to retry a request based on the response content, even if the response has a successful status code. The retry will respect the `retry.limit` option and skip the `shouldRetry` check. The forced retry is observable in `beforeRetry` hooks, where the error will be a `ForceRetryError`.11221123A marker returned by a second copy of Ky, which happens with a duplicated dependency, is still recognised, the same way the Ky error guards accept branded errors.11241125#### options11261127Type: `object`1128
4 unmodified lines
1133Custom delay in milliseconds before retrying. If not provided, uses the default retry delay calculation based on `retry.delay` configuration.11341135**Note:** Custom delays bypass jitter and `backoffLimit`. This is intentional, as custom delays often come from server responses (e.g., `Retry-After` headers) and should be respected exactly as specified.11361137Must be a non-negative number, or `undefined`; anything else throws a `TypeError` rather than collapsing to a 1ms retry.11381139##### code11401141Type: `string`1142
785 unmodified lines