Report the sent request for a hook's response, and finish the cross-realm and `null` checks
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 13c8da5 · Browse files · 11 files·+201 added−38 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
11 files+201 added−38 removed
- tests:+149 added−8 removed
- other:+52 added−30 removed
Provenance
- Commit
7f0137d- Tree
1b85d6c- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
Sindre Sorhus <sindresorhus@gmail.com>- Parent
13c8da5
11 files changed+201 added−38 removed
modified:source/core/constants.ts+3 added-3 removed
55 unmodified lines56 57 // The maximum value of a 32bit int (see issue #117)58 export const maxSafeTimeout = 2_147_483_647;59 60-// 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.60+// 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 low for each part and once more for the closing boundary. That is negligible next to a file, but for a body of many small fields `percent` can reach its ceiling before the upload ends. The final event always reports the real total.61 export const usualFormBoundarySize = 40;62 63 /**64 Symbol that can be returned by a `beforeRetry` hook to stop retrying without throwing an error.12 unmodified lines77 If not provided, uses the default retry delay calculation based on `retry.delay` configuration.78 79 **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.80 81- Must be a non-negative number, or `undefined`; anything else throws a `TypeError` rather than collapsing to a 1ms retry.81+ Must be a non-negative number, `Infinity` included, or `undefined`; anything else makes the request throw a `TypeError` rather than collapsing to a 1ms retry.82 */83 delay?: number | undefined;84 85 /**86 Error code for the retry.87 88- This machine-readable identifier will be included in the error message passed to `beforeRetry` hooks, allowing you to distinguish between different types of forced retries.88+ This machine-readable identifier will be included in the error message passed to `beforeRetry` hooks, allowing you to distinguish between different types of forced retries. Anything other than a string makes the request throw a `TypeError`.89 90 @example91 ```92 return ky.retry({code: 'RATE_LIMIT'});207 unmodified linesmodified:source/core/Ky.ts+7 added-6 removed
437 unmodified lines438 if (Object.hasOwn(options, 'prefixUrl')) {439 throw new Error(prefixUrlRenamedErrorMessage);440 }441 442- // An `init` hook assigns straight onto the options object, so these are checked here, after every merge and hook. The defaults below would otherwise quietly turn a `null` into `GET` or no prefix.443- for (const key of ['headers', 'method', 'prefix', 'baseUrl'] as const) {442+ // An `init` hook assigns straight onto the options object, so these are checked here, after every merge and hook. The defaults below would otherwise quietly turn a `null` into `GET`, no prefix, or the referrer of a `Request` input.443+ for (const key of ['headers', 'method', 'prefix', 'baseUrl', 'referrer', 'referrerPolicy'] as const) {444 if (options[key] === null) {445 throw new TypeError(`The \`${key}\` option must not be \`null\`. Use \`undefined\` to clear it.`);446 }447 }188 unmodified lines636 if (this.#retryCount >= Math.min(retry.limit, this.#retryLimit)) {637 throw error;638 }639 640- // Wrap non-Error throws to ensure consistent error handling641- const errorObject = error instanceof Error ? error : new NonError(error);640+ // Wrap non-Error throws to ensure consistent error handling. `isError` rather than `instanceof`, so a cross-realm error reaches `shouldRetry` as itself, the same way it reaches `beforeError`.641+ const errorObject = isError(error) ? error : new NonError(error);642 643 // Handle forced retry from afterResponse hook - skip method check and shouldRetry644 if (isForceRetryError(errorObject)) {645 return errorObject.customDelay ?? this.#calculateDelay(retry, error);646 unmodified lines1292 // eslint-disable-next-line no-await-in-loop1293 hookResult = await this.#raceWithTotalTimeout(async () => hook({1294 request: this.request,1295 options: this.#getNormalizedOptions(),1296- error: error instanceof Error ? error : new NonError(error),1296+ error: isError(error) ? error : new NonError(error),1297 retryCount: this.#retryCount + 1,1298 }), this.#userProvidedAbortSignal);1299 } catch (hookError) {1300 // A cancellation is part of the request lifecycle, so it reaches `beforeError` like every other abort rather than being hidden as a hook error below.166 unmodified lines1467 referrerPolicy: request.referrerPolicy,1468 });1469 }1470 1471+ // A response Ky did not fetch, such as one returned from a `beforeRetry` hook, is reported with the last request that was sent, like every error is.1472 #getResponseRequest(response: Response): Request {1472- return this.#responseRequests.get(response) ?? this.request;1473+ return this.#responseRequests.get(response) ?? this.#sentRequest;1474 }1475 1476 #setResponseRequest(response: Response, request: Request): Response {1477 this.#responseRequests.set(response, request);16 unmodified linesmodified:source/errors/ForceRetryError.ts+13 added-3 removed
1234567 unmodified lines141516171819202122231824252026272829303132333435362737383940418 unmodified linesimport type {ForceRetryOptions} from '../core/constants.js';import {isError} from '../utils/is.js';import {KyError} from './KyError.js';import {NonError} from './NonError.js';
/**7 unmodified lines code: string | undefined; customRequest: Request | undefined;
constructor(options?: ForceRetryOptions) { // `null` is not accepted anywhere in Ky, so it is reported rather than treated like no options. if (options === null) { throw new TypeError('The `ky.retry()` options must be an object'); }
// The custom delay flows straight into `setTimeout`, so a negative or `NaN` value would be clamped to 1ms and silently collapse the backoff, the same failure mode validated away for `retry.delay`. const {delay} = options ?? {}; const delay = options?.delay; if (delay !== undefined && (typeof delay !== 'number' || Number.isNaN(delay) || delay < 0)) { throw new TypeError('The `delay` option must be a non-negative number or `Infinity`'); throw new TypeError('The `ky.retry()` `delay` option must be a non-negative number or `Infinity`'); }
if (options?.code !== undefined && typeof options.code !== 'string') { throw new TypeError('The `ky.retry()` `code` option must be a string'); }
// Runtime protection: wrap non-Error causes in NonError // TypeScript type is Error for guidance, but JS users can pass anything const cause = options?.cause === undefined ? undefined : (options.cause instanceof Error ? options.cause : new NonError(options.cause)); : (isError(options.cause) ? options.cause : new NonError(options.cause));
super( // `code` is documented as always reaching the message, so only an absent code falls back. options?.code === undefined ? 'Forced retry' : `Forced retry: ${options.code}`,8 unmodified linesmodified:source/types/ky.ts+1 added-1 removed
89 unmodified lines90 Create a new Ky instance with some defaults overridden with your own.91 92 In contrast to `ky.create()`, `ky.extend()` inherits defaults from its parent.93 94- You can pass headers as a `Headers` instance or a plain object. Headers are normalized to a plain object with lowercase names when options are merged, so `init` hooks always see a plain object with lowercase keys. A header removed with `undefined` stays in that object with an `undefined` value.94+ You can pass headers as a `Headers` instance or a plain object. Headers are normalized to a plain object with lowercase names when options are merged, so `init` hooks start with a plain object with lowercase keys. A header removed with `undefined` stays in that object with an `undefined` value.95 96 You can remove a header with `.extend()` by passing the header with an `undefined` value. Passing `undefined` as a string removes the header only if it comes from a `Headers` instance.97 98 Similarly, you can remove existing `hooks` entries by extending the hook with an explicit `undefined`.107 unmodified linesmodified:source/types/options.ts+2 added-2 removed
293 unmodified lines294 295 @param progress - Object containing download progress information.296 @param chunk - Data that was received. When an empty response body stream completes, the callback receives an empty chunk.297 298- `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.298+ `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. For a cross-origin response in a browser, `content-encoding` is only visible when the server lists it in `Access-Control-Expose-Headers`. Otherwise Ky cannot tell that the response is compressed, so it uses `content-length` and the percentage stays close to 100% for most of the download.299 300 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.301 302 Do not throw from the callback. A throw fails the response stream, which the runtime reports in its own way: Node.js rejects the body read with your error, while Chromium reports a network failure, so Ky's body methods throw a `NetworkError` there. Pass a `signal` from an `AbortController` to cancel instead.158 unmodified lines461 462 /**463 HTTP headers used to make the request.464 465- You can pass a `Headers` instance or a plain object. Headers are normalized to a plain object with lowercase names when options are merged, so `init` hooks always see a plain object with lowercase keys. A header removed with `undefined` stays in that object with an `undefined` value.465+ You can pass a `Headers` instance or a plain object. Headers are normalized to a plain object with lowercase names when options are merged, so `init` hooks start with a plain object with lowercase keys. A header removed with `undefined` stays in that object with an `undefined` value.466 467 You can remove a header with `.extend()` by passing the header with an `undefined` value. Passing `undefined` as a string removes the header only if it comes from a `Headers` instance.468 469 @example81 unmodified linesmodified:source/utils/body.ts+1 added-1 removed
16 unmodified lines17 return 0;18 }19 20 if (body instanceof FormData) {21- // This is an approximation, as FormData size calculation is not straightforward. The boundary length is a stand-in for the runtime's own, and every other byte is counted so the estimate errs high (except slightly in Bun, see `usualFormBoundarySize`): an estimate below the real size makes `percent` reach its ceiling part way through the upload.21+ // This is an approximation, as FormData size calculation is not straightforward. The boundary length is a stand-in for the runtime's own, and every other byte is counted so the estimate errs high (except in Bun, see `usualFormBoundarySize`): an estimate below the real size makes `percent` reach its ceiling part way through the upload.22 let size = 0;23 24 for (const [key, value] of body) {25 size += usualFormBoundarySize + 4; // `--<boundary>\r\n`204 unmodified linesmodified:source/utils/merge.ts+21 added-10 removed
258 unmodified lines259 260 // `json` and `context` are user data, which can be large, so they are not walked on every request.261 const userDataOptions = new Set(['json', 'context']);262 263-// `replaceOption()` can wrap a value at any depth of a deep-merged option, but a wrapper is only unwrapped where a merge actually runs, so a wrapper on a key with no parent value kept its `{value}` envelope. This resolves the leftovers in one pass, copying only the branches that actually contained a wrapper so every other value keeps its identity. `seen` only holds the values on the current path, so a cyclic option cannot recurse forever while a value shared by two branches is still resolved in both.264-const resolveReplaceMarkers = (value: unknown, seen: Set<Record<string, unknown> | unknown[]>): unknown => {265- if (!isMergeable(value) || seen.has(value)) {263+// `replaceOption()` can wrap a value at any depth of a deep-merged option, but a wrapper is only unwrapped where a merge actually runs, so a wrapper on a key with no parent value kept its `{value}` envelope. This resolves the leftovers in one pass, copying only the branches that actually contained a wrapper so every other value keeps its identity. `resolved` maps each visited value to its result, so a value shared by two branches is walked once and stays shared, and a cyclic option cannot recurse forever: a value still being resolved maps to itself.264+const resolveReplaceMarkers = (value: unknown, resolved: Map<unknown, unknown>): unknown => {265+ if (!isMergeable(value)) {266 return value;267 }268 269- seen.add(value);270- const resolveItem = (item: unknown) => resolveReplaceMarkers(getReplaceState(item).value, seen);271- const resolved = Array.isArray(value) ? resolveArrayMarkers(value, resolveItem) : resolveObjectMarkers(value, resolveItem);272- seen.delete(value);269+ if (resolved.has(value)) {270+ return resolved.get(value);271+ }272 274- return resolved ?? value;273+ resolved.set(value, value);274+ const resolveItem = (item: unknown) => resolveReplaceMarkers(getReplaceState(item).value, resolved);275+ const result = (Array.isArray(value) ? resolveArrayMarkers(value, resolveItem) : resolveObjectMarkers(value, resolveItem)) ?? value;276+ resolved.set(value, result);277+278+ return result;279 };280 281 const appendSearchParameters = (target: any, source: any): URLSearchParams => {282 const result = new URLSearchParams() as URLSearchParams & {[deletedParametersSymbol]?: Set<string>};23 unmodified lines306 if (!Array.isArray(pair) || pair.length !== 2) {307 throw new TypeError('Array search parameters must be provided in [[key, value], ...] format');308 }309 306- result.append(String(pair[0]), String(pair[1]));310+ // Unwrapped for the same reason as in the object branch below.311+ const key = String(pair[0]);312+ const {isReplace, value} = getReplaceState(pair[1]);313+ if (isReplace) {314+ result.delete(key);315+ }316+317+ result.append(key, String(value));318 }319 } else if (isObject(input)) {320 for (const [key, value] of Object.entries(input)) {321 // A `replaceOption()` wrapper is unwrapped here, because this branch stringifies every value, so a wrapper that reached it would land in the URL as `[object Object]`. A wrapped value replaces the inherited values of its key instead of being added to them.177 unmodified lines499 500 if (isRoot) {501 for (const [key, value] of Object.entries(returnValue)) {502 if (!userDataOptions.has(key)) {492- returnValue[key] = resolveReplaceMarkers(value, new Set());503+ returnValue[key] = resolveReplaceMarkers(value, new Map());504 }505 }506 }507 5 unmodified linesmodified:test/hooks.ts+95 added
7379 unmodified lines7380 t.is(error, thrown, label);7381 t.deepEqual(seen, [], `${label}: the hook error must propagate unchanged`);7382 }7383 });7384+7385+// `shouldRetry` and `beforeRetry` used `instanceof Error`, so a cross-realm error reached them as a `NonError`, while `beforeError` got the error itself.7386+test('a cross-realm error reaches `shouldRetry` and `beforeRetry` as itself', async t => {7387+ const foreignError = runInNewContext('new Error("foreign fetch failure")') as Error;7388+ const seen: unknown[] = [];7389+7390+ await t.throwsAsync(ky('https://example.com', {7391+ retry: {7392+ limit: 1,7393+ delay: () => 0,7394+ shouldRetry({error}) {7395+ seen.push(error);7396+ return true;7397+ },7398+ },7399+ async fetch() {7400+ throw foreignError;7401+ },7402+ hooks: {7403+ beforeRetry: [({error}) => {7404+ seen.push(error);7405+ }],7406+ },7407+ }).text(), {message: 'foreign fetch failure'});7408+7409+ t.is(seen.length, 2);7410+ t.true(seen.every(error => error === foreignError));7411+});7412+7413+test('a cross-realm `ky.retry({cause})` is kept as the cause', async t => {7414+ const foreignError = runInNewContext('new Error("foreign cause")') as Error;7415+ let cause: unknown;7416+7417+ await ky('https://example.com', {7418+ retry: {limit: 1, delay: () => 0},7419+ fetch: async () => new Response('ok'),7420+ hooks: {7421+ afterResponse: [({retryCount}) => retryCount === 0 ? ky.retry({cause: foreignError}) : undefined],7422+ beforeRetry: [({error}) => {7423+ cause = error.cause;7424+ }],7425+ },7426+ }).text();7427+7428+ t.is(cause, foreignError);7429+});7430+7431+// A `Response` from a `beforeRetry` hook was not fetched by Ky, so it was reported with the retry clone that was never sent, while `beforeError` got the request that was sent.7432+test('a `Response` from `beforeRetry` is reported with the request that was sent', async t => {7433+ const sent: Request[] = [];7434+ let beforeErrorRequest: Request | undefined;7435+7436+ const error = await t.throwsAsync<HTTPError>(ky('https://example.com', {7437+ retry: {limit: 1, delay: () => 0},7438+ async fetch(input) {7439+ sent.push(input as Request);7440+ return new Response('first', {status: 500});7441+ },7442+ hooks: {7443+ beforeRetry: [() => new Response('from hook', {status: 503})],7444+ beforeError: [({request, error}) => {7445+ beforeErrorRequest = request;7446+ return error;7447+ }],7448+ },7449+ }).text());7450+7451+ t.is(sent.length, 1);7452+ t.is(error?.request, sent[0]);7453+ t.is(beforeErrorRequest, sent[0]);7454+});7455+7456+test('`parseJson` gets the request that was sent for a `Response` from `beforeRetry`', async t => {7457+ const sent: Request[] = [];7458+ let parseJsonRequest: Request | undefined;7459+7460+ const data = await ky('https://example.com', {7461+ retry: {limit: 1, delay: () => 0},7462+ async fetch(input) {7463+ sent.push(input as Request);7464+ return new Response('', {status: 500});7465+ },7466+ parseJson(text, {request}) {7467+ parseJsonRequest = request;7468+ return JSON.parse(text);7469+ },7470+ hooks: {7471+ beforeRetry: [() => new Response('{"a":1}')],7472+ },7473+ }).json();7474+7475+ t.deepEqual(data, {a: 1});7476+ t.is(sent.length, 1);7477+ t.is(parseJsonRequest, sent[0]);7478+});modified:test/retry.ts+44 added-8 removed
5018 unmodified lines5019 5020 t.is(await replaced('https://example.com').text(), 'https://example.com/?sort=name&page=1');5021 });5022 5023+test('`replaceOption` resolves inside a search parameter tuple', async t => {5024+ const fetchFunction = async (request: Request) => new Response(request.url);5025+5026+ const extended = ky.create({fetch: fetchFunction, searchParams: {sort: 'name', page: '5'}})5027+ .extend({searchParams: [['page', replaceOption('1') as never]]});5028+5029+ t.is(await extended('https://example.com').text(), 'https://example.com/?sort=name&page=1');5030+});5031+5032 test('`replaceOption` leaves untouched values identical', t => {5033 const json = {nested: {list: [1, 2]}};5034 const fetchFunction = () => new Response('ok');5035 const merged = validateAndMerge({json, fetch: fetchFunction}) as {json: unknown; fetch: unknown};95 unmodified lines5131 fetch: async () => new Response('server error', {status: 500}),5132 hooks: {afterResponse: [() => ky.retry({delay: delay as never})]},5133 }).text(), {5134 instanceOf: TypeError,5126- message: 'The `delay` option must be a non-negative number or `Infinity`',5135+ message: 'The `ky.retry()` `delay` option must be a non-negative number or `Infinity`',5136 }, `delay: ${JSON.stringify(delay)}`);5137 }5138 });5139 12 unmodified lines5152 t.is(error?.name, 'TypeError');5153 });5154 5155 // The message used a truthiness check while `code` was assigned without one, so a falsy code was silently dropped from the message the `code` documentation promises.5147-test('a falsy `ky.retry({code})` still appears in the ForceRetryError message', t => {5148- for (const code of ['', 0, false] as unknown[]) {5149- const error = new ForceRetryError({code: code as never});5156+test('an empty `ky.retry({code})` still appears in the ForceRetryError message', t => {5157+ const error = new ForceRetryError({code: ''});5158+ t.is(error.code, '');5159+ t.is(error.message, 'Forced retry: ');5160 5151- t.is(error.code, code);5152- t.is(error.message, `Forced retry: ${String(code)}`);5153- }5154-5161 t.is(new ForceRetryError().message, 'Forced retry');5162 t.is(new ForceRetryError({}).message, 'Forced retry');5163 t.is(new ForceRetryError({code: 'RATE_LIMIT'}).message, 'Forced retry: RATE_LIMIT');5164 });5165 5166+test('`ky.retry(null)` throws', t => {5167+ t.throws(() => new ForceRetryError(null as never), {5168+ instanceOf: TypeError,5169+ message: 'The `ky.retry()` options must be an object',5170+ });5171+});5172+5173+// `code` is a string. Anything else, `null` included, used to reach the message as text such as "Forced retry: null".5174+test('a `ky.retry({code})` that is not a string throws', t => {5175+ for (const code of [null, 0, false]) {5176+ t.throws(() => new ForceRetryError({code: code as never}), {5177+ instanceOf: TypeError,5178+ message: 'The `ky.retry()` `code` option must be a string',5179+ });5180+ }5181+});5182+5183 // The replace-marker pass only held the values on the current path, so a value shared by two branches was resolved in the first and skipped in the second, which kept its `{value}` envelope. A genuine cycle is still left alone.5184 test('`replaceOption` resolves a shared value in every branch that uses it', t => {5185 const shared = {tags: replaceOption(['a'])};5186 const merged = validateAndMerge({custom: {first: shared, second: shared, list: [shared]}});5187 5188 t.deepEqual(merged.custom, {first: {tags: ['a']}, second: {tags: ['a']}, list: [{tags: ['a']}]});5189 });5190 5191+// Walking every path through a value that several branches share made the pass exponential in the nesting depth, and gave each branch its own copy.5192+test('`replaceOption` resolves a deeply shared value once and keeps it shared', t => {5193+ let node: Record<string, unknown> = {tags: replaceOption(['a'])};5194+ // Deep enough that a walk per path would visibly slow down, shallow enough that it would still fail on the identity check rather than hang the suite.5195+ for (let depth = 0; depth < 14; depth++) {5196+ node = {left: node, right: node};5197+ }5198+5199+ const merged = validateAndMerge({custom: node}) as {custom: {left: unknown; right: unknown}};5200+5201+ t.is(merged.custom.left, merged.custom.right);5202+});5203+5204 test('`replaceOption` leaves a cyclic option intact', t => {5205 const cyclic: Record<string, unknown> = {a: 1};5206 cyclic.self = cyclic;5207 105 unmodified linesmodified:test/validation.ts+10 added
211 unmodified lines212 message: 'The `hooks` option must be an object',213 });214 });215 216+test('rejects `null` for `referrer` and `referrerPolicy`', async t => {217+ for (const key of ['referrer', 'referrerPolicy']) {218+ // eslint-disable-next-line no-await-in-loop219+ await t.throwsAsync(ky('https://example.com', {[key]: null, fetch: okFetch} as never), {220+ name: 'TypeError',221+ message: `The \`${key}\` option must not be \`null\`. Use \`undefined\` to clear it.`,222+ });223+ }224+});225+226 test('rejects a `retry.retryOnTimeout` that is not a boolean', async t => {227 for (const retryOnTimeout of [null, 'false', 0] as unknown[]) {228 // eslint-disable-next-line no-await-in-loop229 await t.throwsAsync(ky('https://example.com', {retry: {retryOnTimeout: retryOnTimeout as never}, fetch: okFetch}), {5 unmodified linesmodified:readme.md+4 added-4 removed
778 unmodified lines779 - `transferredBytes` is the number of bytes transferred so far.780 - `totalBytes` is the total number of bytes to be transferred. This is an estimate and may be 0 for an empty transfer or when the total size cannot be determined.781 - `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.782 783-`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.783+`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. For a cross-origin response in a browser, `content-encoding` is only visible when the server lists it in `Access-Control-Expose-Headers`. Otherwise Ky cannot tell that the response is compressed, so it uses `content-length` and the percentage stays close to 100% for most of the download.784 785 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.786 787 Do not throw from the callback. A throw fails the response stream, which the runtime reports in its own way: Node.js rejects the body read with your error, while Chromium reports a network failure, so Ky's body methods throw a `NetworkError` there. Pass a `signal` from an `AbortController` to cancel instead.197 unmodified lines985 Create a new `ky` instance with some defaults overridden with your own.986 987 In contrast to `ky.create()`, `ky.extend()` inherits defaults from its parent.988 989-You can pass headers as a `Headers` instance or a plain object. Headers are normalized to a plain object with lowercase names when options are merged, so `init` hooks always see a plain object with lowercase keys. A header removed with `undefined` stays in that object with an `undefined` value.989+You can pass headers as a `Headers` instance or a plain object. Headers are normalized to a plain object with lowercase names when options are merged, so `init` hooks start with a plain object with lowercase keys. A header removed with `undefined` stays in that object with an `undefined` value.990 991 You can remove a header with `.extend()` by passing the header with an `undefined` value.992 Passing `undefined` as a string removes the header only if it comes from a `Headers` instance.993 143 unmodified lines1137 Custom delay in milliseconds before retrying. If not provided, uses the default retry delay calculation based on `retry.delay` configuration.1138 1139 **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.1140 1141-Must be a non-negative number, or `undefined`; anything else throws a `TypeError` rather than collapsing to a 1ms retry.1141+Must be a non-negative number, `Infinity` included, or `undefined`; anything else makes the request throw a `TypeError` rather than collapsing to a 1ms retry.1142 1143 ##### code1144 1145 Type: `string`1146 1147 Error code for the retry.1148 1149-This machine-readable identifier will be included in the error message passed to `beforeRetry` hooks, allowing you to distinguish between different types of forced retries.1149+This machine-readable identifier will be included in the error message passed to `beforeRetry` hooks, allowing you to distinguish between different types of forced retries. Anything other than a string makes the request throw a `TypeError`.1150 1151 ```js1152 return ky.retry({code: 'RATE_LIMIT'});1153 // Resulting error message: 'Forced retry: RATE_LIMIT'778 unmodified lines