Ky.ts
This file
Path
source/core/Ky.ts
1,376 lines · 52.2 KiB · TypeScript
Last changed by
Let a `beforeRetry` hook change per-attempt optionsSindre Sorhusbefore adoption242c327
History of this fileTake it
The walk stopped after 200 commits: lines older than 37fc250 point at it.
Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 1why, one step back1import {HTTPError} from '../errors/HTTPError.js';Add `NetworkError` class and tighten retry logic (#842)Sindre Sorhusbefore adoptioneaf0b80
line 2why, one step back2import {NetworkError} from '../errors/NetworkError.js';Add `retryOnTimeout` and `shouldRetry` options (#767)Sindre Sorhusbefore adoptionf0fdbd4
line 3why, one step back3import {NonError} from '../errors/NonError.js';Add `ky.retry()` to force retries from `afterResponse` hooks (#779)Sindre Sorhusbefore adoption68a5228
line 4why, one step back4import {ForceRetryError} from '../errors/ForceRetryError.js';Add Standard Schema validation for `.json()` (#830)Sindre Sorhusbefore adoption94741a9
line 5why, one step back5import {SchemaValidationError} from '../errors/SchemaValidationError.js';Fix timeout to apply to total operation including retries (#825)Sindre Sorhusbefore adoptionaac83fa
line 6why, one step back6import {TimeoutError} from '../errors/TimeoutError.js';Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 7–8why, one step back7import type {8 Input,Support readonly inputs and explicit undefined in TypeScript optionsSindre Sorhusbefore adoption51b3177
line 9why, one step back9 InitOptions,Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 10–13why, one step back10 InternalOptions,11 NormalizedOptions,12 Options,13 SearchParamsInit,Code styleSindre Sorhusbefore adoption333afbe
line 14why, one step back14 SearchParamsOption,Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 15–16why, one step back15} from '../types/options.js';16import {type ResponsePromise} from '../types/ResponsePromise.js';Add Standard Schema validation for `.json()` (#830)Sindre Sorhusbefore adoption94741a9
line 17why, one step back17import type {StandardSchemaV1} from '../types/standard-schema.js';Merge `searchParams` with input URL (#840)AkaHarshitbefore adoption29e78fe
line 18why, one step back18import {RefactorSindre Sorhusbefore adoptiona5ed57b
lines 19–24why, one step back19 cancelBody,20 limitResponseSize,21 streamRequest,22 streamResponse,23} from '../utils/body.js';24import {Fix `init` hook mutations to nested `json` and `context` values leaking across requestsSindre Sorhusbefore adoption88e2432
line 25why, one step back25 cloneDeep,RefactorSindre Sorhusbefore adoptiona5ed57b
line 26why, one step back26 cloneSearchParameters,Merge `searchParams` with input URL (#840)AkaHarshitbefore adoption29e78fe
line 27why, one step back27 mergeHeaders,Normalize mutable init hook optionsSindre Sorhusbefore adoptionff0155d
line 28why, one step back28 mergeHeaderContainers,Merge `searchParams` with input URL (#840)AkaHarshitbefore adoption29e78fe
lines 29–30why, one step back29 mergeHooks,30 deletedParametersSymbol,RefactorSindre Sorhusbefore adoptiona5ed57b
line 31why, one step back31 type MarkedSearchParameters,Merge `searchParams` with input URL (#840)AkaHarshitbefore adoption29e78fe
line 32why, one step back32} from '../utils/merge.js';Respect custom HTTP method case when matching retriesSindre Sorhusbefore adoptione4269f0
line 33why, one step back33import {normalizeRequestMethod, normalizeRetryMethod, normalizeRetryOptions} from '../utils/normalize.js';Various tweaksSindre Sorhusbefore adoption0dd9522
line 34why, one step back34import timeout from '../utils/timeout.js';Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 35–36why, one step back35import delay from '../utils/delay.js';36import {findUnknownOptions, hasSearchParameters} from '../utils/options.js';Add `NetworkError` class and tighten retry logic (#842)Sindre Sorhusbefore adoptioneaf0b80
line 37why, one step back37import isRawNetworkError from '../utils/is-network-error.js';Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 38why, one step back38import {RefactorSindre Sorhusbefore adoptiona5ed57b
lines 39–41why, one step back39 isError, isNonArrayObject, isNonNegativeNumber, isObject, isRequest, isResponse,40} from '../utils/is.js';41import {TweaksSindre Sorhusbefore adoption3ded2aa
line 42why, one step back42 isHTTPError, isNetworkError, isTimeoutError, isResponseSizeError, isForceRetryError,Add `maxResponseSize` optionSindre Sorhusbefore adoption0d59458
lines 43–44why, one step back43} from '../utils/type-guards.js';44import {Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113
lines 45–48why, one step back45 calculateRetryTimingDelay,46 getRetryTimingHeader,47} from './retry-timing.js';48import {Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 49–50why, one step back49 maxSafeTimeout,50 responseTypes,RefactorSindre Sorhusbefore adoptiona5ed57b
line 51why, one step back51 getSupportedResponseTypes,Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 52why, one step back52 stop,Let a `beforeRetry` hook change per-attempt optionsSindre Sorhusbefore adoption242c327
line 53why, one step back53 beforeRetryOptionKeys,TweaksSindre Sorhusbefore adoption3ded2aa
line 54why, one step back54 isRetryMarker,Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 55–61why, one step back55 supportsAbortController,56 supportsAbortSignal,57 supportsFormData,58 supportsResponseStreams,59 supportsRequestStreams,60} from './constants.js';61Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c
line 62why, one step back62const maxErrorResponseBodySize = 10 * 1024 * 1024;Minor tweaksSindre Sorhusbefore adoption4b37c96
line 63why, one step back63const prefixUrlRenamedErrorMessage = 'The `prefixUrl` option has been renamed `prefix` in v2 and enhanced to allow slashes in input. See also the new `baseUrl` option for improved flexibility with standard URL resolution: https://github.com/sindresorhus/ky#baseurl';RefactorSindre Sorhusbefore adoptiona5ed57b
line 64why, one step back64const timedOut = Symbol('timedOut');Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c
line 65why, one step back65RefactorSindre Sorhusbefore adoptiona5ed57b
lines 66–95why, one step back66const getCurrentTime = (): number => globalThis.performance?.now() ?? Date.now();6768// Settles like `promise`, or resolves with `timedOut` once `milliseconds` pass first. The timer is cleared as soon as `promise` settles.69// eslint-disable-next-line @typescript-eslint/promise-function-async70const raceWithTimeout = <T>(promise: Promise<T>, milliseconds: number): Promise<T | typeof timedOut> => Promise.race([71 promise,72 new Promise<typeof timedOut>(resolve => {73 const timeoutId = setTimeout(() => {74 resolve(timedOut);75 }, milliseconds);76 void promise.finally(() => {77 clearTimeout(timeoutId);78 }).catch(() => undefined);79 }),80]);8182// Only a returned request or response has a body to release.83const cancelReturnedBody = (value: unknown): void => {84 if (isResponse(value) || isRequest(value)) {85 cancelBody(value);86 }87};8889// Releases the body of a value whose owner already gave up on it, once the operation settles with something. The promise is abandoned on purpose, so its rejection is swallowed rather than surfacing as an unhandled rejection.90const releaseWhenSettled = (operationPromise: Promise<unknown>): void => {91 void operationPromise.then(value => {92 cancelReturnedBody(value);93 }).catch(() => undefined);94};95Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113
lines 96–100why, one step back96type ErrorDataTimeout = {97 milliseconds: number;98 fromTotalTimeout: boolean;99};100Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c
lines 101–112why, one step back101const createTextDecoder = (contentType: string): TextDecoder => {102 const match = /;\s*charset\s*=\s*(?:"([^"]+)"|([^;,\s]+))/i.exec(contentType);103 const charset = match?.[1] ?? match?.[2];104 if (charset) {105 try {106 return new TextDecoder(charset);107 } catch {}108 }109110 return new TextDecoder();111};112RefactorSindre Sorhusbefore adoptiona5ed57b
lines 113–196why, one step back113const isJsonContentType = (contentType: string): boolean => {114 // Match JSON subtypes like `json`, `problem+json`, and `vnd.api+json`.115 // Written out rather than matched with a pattern like `/\/(?:.*[.+-])?json$/`, which backtracks quadratically on a `Content-Type` full of slashes. The header comes from the server, so this must stay linear.116 const mimeType = (contentType.split(';', 1)[0] ?? '').trim().toLowerCase();117118 if (!mimeType.endsWith('json')) {119 return false;120 }121122 const separator = mimeType.at(-5);123 if (separator === '/') {124 return true;125 }126127 if (separator !== '.' && separator !== '+' && separator !== '-') {128 return false;129 }130131 // The separator is not the slash, so any slash in the type comes before it.132 return mimeType.includes('/');133};134135// Reads an error body as text. Returns `undefined` when the body cannot be read or is larger than `maxErrorResponseBodySize`, and `timedOut` when the read takes longer than `milliseconds`.136const readResponseText = async (response: Response, milliseconds: number): Promise<string | typeof timedOut | undefined> => {137 const {body} = response;138 if (!body) {139 try {140 return await response.text();141 } catch {142 return undefined;143 }144 }145146 let reader: ReadableStreamDefaultReader<Uint8Array>;147 try {148 reader = body.getReader();149 } catch {150 // Another consumer already locked the stream.151 return undefined;152 }153154 const contentType = response.headers.get('content-type') ?? '';155 // JSON uses UTF-8 regardless of the charset parameter (RFC 8259).156 const decoder = isJsonContentType(contentType) ? new TextDecoder() : createTextDecoder(contentType);157 const chunks: string[] = [];158 let totalBytes = 0;159160 const readAll = (async (): Promise<string | undefined> => {161 try {162 for (;;) {163 // eslint-disable-next-line no-await-in-loop164 const {done, value} = await reader.read();165 if (done) {166 break;167 }168169 totalBytes += value.byteLength;170 if (totalBytes > maxErrorResponseBodySize) {171 void reader.cancel().catch(() => undefined);172 return undefined;173 }174175 chunks.push(decoder.decode(value, {stream: true}));176 }177 } catch (error) {178 if (isResponseSizeError(error)) {179 throw error;180 }181182 return undefined;183 }184185 chunks.push(decoder.decode());186 return chunks.join('');187 })();188189 const result = await raceWithTimeout(readAll, milliseconds);190 if (result === timedOut) {191 void reader.cancel().catch(() => undefined);192 }193194 return result;195};196Various tweaksSindre Sorhusbefore adoption0dd9522
line 197why, one step back197const invalidSchemaMessage = 'The `schema` argument must follow the Standard Schema specification';TweaksSindre Sorhusbefore adoption3ded2aa
lines 198–199why, one step back198const missingResponseMessage = 'The request resolved without a response, so there is no body to read.'199 + ' This happens when a `beforeRetry` hook returns `ky.stop`. Throw from the hook instead of returning `ky.stop`.';Various tweaksSindre Sorhusbefore adoption0dd9522
line 200why, one step back200TweaksSindre Sorhusbefore adoption3ded2aa
lines 201–206why, one step back201// Both timeout options are milliseconds or `false`. A `NaN` or negative value used to reach `setTimeout()`, which silently clamps it to ~1ms, or to be ignored entirely when `totalTimeout` was not a number.202const validateTimeoutOption = (value: unknown, name: 'timeout' | 'totalTimeout'): void => {203 if (value === false) {204 return;205 }206RefactorSindre Sorhusbefore adoptiona5ed57b
line 207why, one step back207 if (!isNonNegativeNumber(value)) {TweaksSindre Sorhusbefore adoption3ded2aa
lines 208–216why, one step back208 throw new TypeError(`The \`${name}\` option must be a non-negative number or \`false\``);209 }210211 // `Infinity` lands here too, since it is not a usable delay either.212 if (value > maxSafeTimeout) {213 throw new RangeError(`The \`${name}\` option cannot be greater than ${maxSafeTimeout}`);214 }215};216Let a `beforeRetry` hook change per-attempt optionsSindre Sorhusbefore adoption242c327
lines 217–219why, one step back217// Defaults only replace `undefined`, so a `null` reaches the validation and is reported instead of silently becoming the default.218const withAttemptDefaults = ({throwHttpErrors = true, timeout = 10_000, fetch = globalThis.fetch.bind(globalThis)}: Options) => ({throwHttpErrors, timeout, fetch});219Run `beforeError` for a `beforeRetry` abort and share the body-wrapping checkSindre Sorhusbefore adoption55599c8
line 220why, one step back220// 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.TweaksSindre Sorhusbefore adoption3ded2aa
line 221why, one step back221const validateCallbackOptions = (options: Record<string, unknown>): void => {Run `beforeError` for a `beforeRetry` abort and share the body-wrapping checkSindre Sorhusbefore adoption55599c8
line 222why, one step back222 for (const key of ['parseJson', 'stringifyJson', 'fetch', 'onDownloadProgress', 'onUploadProgress'] as const) {TweaksSindre Sorhusbefore adoption3ded2aa
lines 223–233why, one step back223 if (options[key] !== undefined && typeof options[key] !== 'function') {224 throw new TypeError(`The \`${key}\` option must be a function`);225 }226 }227228 const {throwHttpErrors} = options;229 if (typeof throwHttpErrors !== 'boolean' && typeof throwHttpErrors !== 'function') {230 throw new TypeError('The `throwHttpErrors` option must be a boolean or a function');231 }232};233RefactorSindre Sorhusbefore adoptiona5ed57b
lines 234–237why, one step back234const leadingC0ControlOrSpacePattern = /^[\0-\u0020]+/g;235const asciiTabOrNewLinePattern = /[\t\n\r]/g;236const schemePattern = /^[a-z][\d+.a-z-]*:/i;237const malformedHttpProtocolPattern = /^https?:(?!\/\/)/i;Fix hook state leaks and fetch option forwardingSindre Sorhusbefore adoption2df9b7e
line 238why, one step back238RefactorSindre Sorhusbefore adoptiona5ed57b
lines 239–240why, one step back239const isAbsoluteInput = (input: string): boolean =>240 schemePattern.test(input);Harden retrySindre Sorhusbefore adoptionc426f19
line 241why, one step back241RefactorSindre Sorhusbefore adoptiona5ed57b
lines 242–243why, one step back242const normalizeInputForProtocolCheck = (input: string): string =>243 input.replaceAll(leadingC0ControlOrSpacePattern, '').replaceAll(asciiTabOrNewLinePattern, '');Harden retrySindre Sorhusbefore adoptionc426f19
line 244why, one step back244RefactorSindre Sorhusbefore adoptiona5ed57b
lines 245–248why, one step back245// Joins a string input to `prefix`, then resolves it against `baseUrl`. A `URL` or `Request` input is used as-is.246const resolveInput = (input: Input, prefix: string, baseUrl: Options['baseUrl']): Input => {247 if (typeof input !== 'string') {248 return input;Harden retrySindre Sorhusbefore adoptionc426f19
lines 249–250why, one step back249 }250RefactorSindre Sorhusbefore adoptiona5ed57b
lines 251–254why, one step back251 if (prefix) {252 const normalizedPrefix = prefix.replace(/\/+$/, '');253 const normalizedInput = input.replace(/^\/+/, '');254 input = `${normalizedPrefix}/${normalizedInput}`;Harden retrySindre Sorhusbefore adoptionc426f19
lines 255–256why, one step back255 }256RefactorSindre Sorhusbefore adoptiona5ed57b
lines 257–258why, one step back257 if (baseUrl) {258 const normalizedInput = normalizeInputForProtocolCheck(input);Fix hook state leaks and fetch option forwardingSindre Sorhusbefore adoption2df9b7e
line 259why, one step back259RefactorSindre Sorhusbefore adoptiona5ed57b
lines 260–262why, one step back260 if (malformedHttpProtocolPattern.test(normalizedInput)) {261 throw new TypeError('`input` url protocol must be followed by `//` when using `baseUrl`');262 }Improve compatibility with custom `fetch` implementations (#858)Sindre Sorhusbefore adoption2971991
line 263why, one step back263RefactorSindre Sorhusbefore adoptiona5ed57b
lines 264–267why, one step back264 if (!isAbsoluteInput(normalizedInput)) {265 return new URL(input, (new Request(baseUrl)).url);266 }267 }Improve compatibility with custom `fetch` implementations (#858)Sindre Sorhusbefore adoption2971991
line 268why, one step back268RefactorSindre Sorhusbefore adoptiona5ed57b
lines 269–270why, one step back269 return input;270};Improve compatibility with custom `fetch` implementations (#858)Sindre Sorhusbefore adoption2971991
line 271why, one step back271RefactorSindre Sorhusbefore adoptiona5ed57b
lines 272–277why, one step back272// `URLSearchParams#delete()` serializes the whole query again even when the key is missing, which would rewrite an input URL that has nothing to remove, for example `%20` as `+`.273const deleteSearchParameter = (url: URL, key: string): void => {274 if (url.searchParams.has(key)) {275 url.searchParams.delete(key);276 }277};Reject malformed HTTP URLs with `baseUrl`Sindre Sorhusbefore adoptionbe60db5
line 278why, one step back278RefactorSindre Sorhusbefore adoptiona5ed57b
lines 279–281why, one step back279// Adds the `searchParams` option to the search parameters already in `url`.280const applySearchParameters = (url: URL, searchParameters: SearchParamsOption): void => {281 const deleted = (searchParameters as MarkedSearchParameters | undefined)?.[deletedParametersSymbol];Reject malformed HTTP URLs with `baseUrl`Sindre Sorhusbefore adoptionbe60db5
line 282why, one step back282RefactorSindre Sorhusbefore adoptiona5ed57b
lines 283–287why, one step back283 if (deleted) {284 // Remove keys from the input URL first so later searchParams entries can intentionally re-add them.285 for (const key of deleted) {286 deleteSearchParameter(url, key);287 }Fix tuple `searchParams` mutations leaking across init-hook requests (#861)Atharva Singhbefore adoption346f898
lines 288–289why, one step back288 }289RefactorSindre Sorhusbefore adoptiona5ed57b
lines 290–308why, one step back290 if (typeof searchParameters === 'string') {291 const stringSearchParameters = searchParameters.replace(/^\?/, '');292 if (stringSearchParameters !== '') {293 url.search = url.search ? `${url.search}&${stringSearchParameters}` : `?${stringSearchParameters}`;294 }295 } else if (isNonArrayObject(searchParameters) && !(searchParameters instanceof URLSearchParams)) {296 // Filter out undefined values from plain objects. An `undefined` value removes the key from the input URL instead.297 for (const [key, value] of Object.entries(searchParameters)) {298 if (value === undefined) {299 deleteSearchParameter(url, key);300 } else {301 url.searchParams.append(key, value as string);302 }303 }304 } else {305 for (const [key, value] of new URLSearchParams(searchParameters as SearchParamsInit)) {306 url.searchParams.append(key, value);307 }308 }Fix tuple `searchParams` mutations leaking across init-hook requests (#861)Atharva Singhbefore adoption346f898
lines 309–310why, one step back309};310TweaksSindre Sorhusbefore adoption3ded2aa
line 311why, one step back311// Clone mutable option properties so init hook mutations don't leak across requests. Non-plain values (functions, class instances) are kept by reference, matching how option merging treats them as whole values. A value a hook assigns is used as-is.Support readonly inputs and explicit undefined in TypeScript optionsSindre Sorhusbefore adoption51b3177
line 312why, one step back312function cloneInitHookOptions(options: Options): InitOptions {Restore the retry-only marker condition and cover the remaining casesSindre Sorhusbefore adoption692c435
lines 313–314why, one step back313 const clonedOptions: Options = {314 ...options,TweaksSindre Sorhusbefore adoption3ded2aa
lines 315–316why, one step back315 // `headers` starts as a plain object with lowercase names in `init` hooks, so hooks can add headers in place even when none were provided.316 headers: mergeHeaderContainers({}, options.headers ?? {}),Stop surfacing progress callback errorsSindre Sorhusbefore adoption13c8da5
lines 317–318why, one step back317 // `context` starts as an object in `init` hooks, the same as in every other hook. The copy is shallow like the per-request copy, so nested values stay shared, for example a cache kept in `context`.318 context: {...options.context},TweaksSindre Sorhusbefore adoption3ded2aa
line 319why, one step back319 // Deep-clone so init-hook mutations to nested values do not leak across requests, matching the nested `retry` cloning below.Restore the retry-only marker condition and cover the remaining casesSindre Sorhusbefore adoption692c435
line 320why, one step back320 json: cloneDeep(options.json),RefactorSindre Sorhusbefore adoptiona5ed57b
lines 321–323why, one step back321 searchParams: cloneSearchParameters(options.searchParams),322 // Clone nested arrays too so init hooks can mutate retry config without leaking state across requests.323 retry: cloneDeep(options.retry),Restore the retry-only marker condition and cover the remaining casesSindre Sorhusbefore adoption692c435
line 324why, one step back324 };Normalize mutable init hook optionsSindre Sorhusbefore adoptionff0155d
line 325why, one step back325Support readonly inputs and explicit undefined in TypeScript optionsSindre Sorhusbefore adoption51b3177
line 326why, one step back326 return clonedOptions as InitOptions;Various tweaksSindre Sorhusbefore adoption0dd9522
lines 327–328why, one step back327}328Add Standard Schema validation for `.json()` (#830)Sindre Sorhusbefore adoption94741a9
line 329why, one step back329const validateJsonWithSchema = async (jsonValue: unknown, schema: StandardSchemaV1): Promise<unknown> => {RefactorSindre Sorhusbefore adoptiona5ed57b
line 330why, one step back330 const standardSchema = isObject(schema) || typeof schema === 'function' ? schema['~standard'] : undefined;Add Standard Schema validation for `.json()` (#830)Sindre Sorhusbefore adoption94741a9
lines 331–332why, one step back331332 if (RefactorSindre Sorhusbefore adoptiona5ed57b
line 333why, one step back333 !isObject(standardSchema)Add Standard Schema validation for `.json()` (#830)Sindre Sorhusbefore adoption94741a9
lines 334–335why, one step back334 || typeof standardSchema.validate !== 'function'335 ) {Various tweaksSindre Sorhusbefore adoption0dd9522
line 336why, one step back336 throw new TypeError(invalidSchemaMessage);Add Standard Schema validation for `.json()` (#830)Sindre Sorhusbefore adoption94741a9
lines 337–347why, one step back337 }338339 const validationResult = await standardSchema.validate(jsonValue);340341 if (validationResult.issues) {342 throw new SchemaValidationError(validationResult.issues);343 }344345 return validationResult.value;346};347Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 348–349why, one step back348export class Ky {349 static create(input: Input, options: Options): ResponsePromise {Various tweaksSindre Sorhusbefore adoption0dd9522
lines 350–353why, one step back350 const initHooks = options.hooks?.init ?? [];351 const initHookOptions = initHooks.length > 0 ? cloneInitHookOptions(options) : options;352353 for (const hook of initHooks) {Support readonly inputs and explicit undefined in TypeScript optionsSindre Sorhusbefore adoption51b3177
line 354why, one step back354 hook(initHookOptions as InitOptions);Add `init` hook (#841)Sindre Sorhusbefore adoption87c6740
lines 355–356why, one step back355 }356Various tweaksSindre Sorhusbefore adoption0dd9522
line 357why, one step back357 const ky = new Ky(input, initHookOptions);Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 358why, one step back358Make `beforeError` hook receive all errors (#829)Sindre Sorhusbefore adoption101c74b
line 359why, one step back359 const result = (async () => {Release the bodies a caller cannot reach and stop sharing search parametersSindre Sorhusbefore adoptionec3d17f
line 360why, one step back360 let response: Response | undefined;Make `beforeError` hook receive all errors (#829)Sindre Sorhusbefore adoption101c74b
line 361why, one step back361 try {RefactorSindre Sorhusbefore adoptiona5ed57b
line 362why, one step back362 response = await ky.#run();Release the bodies a caller cannot reach and stop sharing search parametersSindre Sorhusbefore adoptionec3d17f
line 363why, one step back363 return response;Make `beforeError` hook receive all errors (#829)Sindre Sorhusbefore adoption101c74b
line 364why, one step back364 } catch (error: unknown) {Release the bodies a caller cannot reach and stop sharing search parametersSindre Sorhusbefore adoptionec3d17f
line 365why, one step back365 return await ky.#throwProcessedError(error);Make `beforeError` hook receive all errors (#829)Sindre Sorhusbefore adoption101c74b
line 366why, one step back366 } finally {Code styleSindre Sorhusbefore adoption333afbe
line 367why, one step back367 const originalRequest = ky.#originalRequest;Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 368why, one step back368Fix response body cleanup after hooks (#809)Sindre Sorhusbefore adoption2bdbd59
line 369why, one step back369 // Ignore cancellation errors from already-locked or already-consumed streams.Release the bodies a caller cannot reach and stop sharing search parametersSindre Sorhusbefore adoptionec3d17f
line 370why, one step back370 // A custom fetch or hook can return the request body as its response body; ownership then belongs to the caller.RefactorSindre Sorhusbefore adoptiona5ed57b
line 371why, one step back371 cancelBody(originalRequest, response);Release the bodies a caller cannot reach and stop sharing search parametersSindre Sorhusbefore adoptionec3d17f
line 372why, one step back372TweaksSindre Sorhusbefore adoption3ded2aa
line 373why, one step back373 // Only cancel the current request body if it's distinct from the original (i.e. it was cloned for retries). `#originalRequest` is only set once a request is handed to fetch, so a pipeline that never started, for example one where a `beforeRequest` hook threw or returned a `Response`, leaves the caller's own body alone.RefactorSindre Sorhusbefore adoptiona5ed57b
lines 374–375why, one step back374 if (originalRequest && ky.request !== originalRequest) {375 cancelBody(ky.request, response);Skip request cloning when retries are disabled to prevent buffering large streaming bodiesSindre Sorhusbefore adoption6f3d1bd
line 376why, one step back376 }Make `beforeError` hook receive all errors (#829)Sindre Sorhusbefore adoption101c74b
lines 377–378why, one step back377 }378 })() as ResponsePromise;Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 379why, one step back379RefactorSindre Sorhusbefore adoptiona5ed57b
lines 380–382why, one step back380 // Only expose `.bytes()` when the environment implements it.381 for (const type of getSupportedResponseTypes()) {382 const mimeType = responseTypes[type];Add Standard Schema validation for `.json()` (#830)Sindre Sorhusbefore adoption94741a9
line 383why, one step back383 result[type] = async (schema?: StandardSchemaV1) => {TweaksSindre Sorhusbefore adoption3ded2aa
lines 384–388why, one step back384 // Before dispatch, `ky.request` is the request that will be sent. After dispatch, `#fetch()` has replaced it with the clone it prepares for a possible retry, so a late shortcut only affects later attempts. A request that was already sent is never changed, because `error.request` would then report a header that never went over the wire.385 if (ky.request !== ky.#originalRequest) {386 // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing387 ky.request.headers.set('accept', ky.request.headers.get('accept') || mimeType);388 }Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 389–391why, one step back389390 const response = await result;391TweaksSindre Sorhusbefore adoption3ded2aa
lines 392–396why, one step back392 // `ky.stop` from a `beforeRetry` hook resolves the request with no response at all. Reading a body method would otherwise crash deep inside Ky with a TypeError that names Ky internals.393 if (response === undefined) {394 throw new TypeError(missingResponseMessage);395 }396Add Standard Schema validation for `.json()` (#830)Sindre Sorhusbefore adoption94741a9
line 397why, one step back397 if (type !== 'json') {Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113
line 398why, one step back398 return ky.#raceBodyRead(async () => response[type](), response);Add Standard Schema validation for `.json()` (#830)Sindre Sorhusbefore adoption94741a9
line 399why, one step back399 }Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 400why, one step back400Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113
lines 401–402why, one step back401 const text = await ky.#raceBodyRead(async () => response.text(), response) as string;402 const request = ky.#getResponseRequest(response);HardenSindre Sorhusbefore adoption8d8e7a4
lines 403–406why, one step back403 // This implementation is shared by every body method, so its return type has to satisfy all of them. The parsed value is whatever `parseJson` or `JSON.parse` produced, which is `any` at this boundary.404 let parsedResult: any;405 try {406 parsedResult = await ky.#raceWithTotalTimeout(async () => {RefactorSindre Sorhusbefore adoptiona5ed57b
lines 407–409why, one step back407 const jsonValue = text === '' && schema !== undefined && !ky.#options.parseJson408 ? undefined409 : await ky.#parseJson(text, request, response);Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 410why, one step back410HardenSindre Sorhusbefore adoption8d8e7a4
lines 411–416why, one step back411 if (schema === undefined) {412 return jsonValue;413 }414415 // eslint-disable-next-line no-return-await, @typescript-eslint/return-await -- Awaiting here preserves the caller's async stack when schema validation fails.416 return await validateJsonWithSchema(jsonValue, schema);RefactorSindre Sorhusbefore adoptiona5ed57b
line 417why, one step back417 });HardenSindre Sorhusbefore adoption8d8e7a4
lines 418–420why, one step back418 } catch (error: unknown) {419 // A cancellation is part of the request lifecycle, so it reaches `beforeError` like every other abort. Other failures, such as invalid JSON, stay as they are.420 if (ky.#userProvidedAbortSignal?.aborted) {TweaksSindre Sorhusbefore adoption3ded2aa
line 421why, one step back421 await ky.#throwProcessedError(ky.#userProvidedAbortSignal.reason, request);Preserve caller stack for schema validation errors (#883)Sindre Sorhusbefore adoptione68ea7a
lines 422–423why, one step back422 }423HardenSindre Sorhusbefore adoption8d8e7a4
lines 424–425why, one step back424 throw error;425 }Harden retrySindre Sorhusbefore adoptionc426f19
line 426why, one step back426RefactorSindre Sorhusbefore adoptiona5ed57b
line 427why, one step back427 if (parsedResult === timedOut) {TweaksSindre Sorhusbefore adoption3ded2aa
line 428why, one step back428 await ky.#throwProcessedError(new TimeoutError(request), request);Harden retrySindre Sorhusbefore adoptionc426f19
lines 429–431why, one step back429 }430431 return parsedResult;Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 432–438why, one step back432 };433 }434435 return result;436 }437438 public request: Request;Add `retryOnTimeout` and `shouldRetry` options (#767)Sindre Sorhusbefore adoptionf0fdbd4
line 439why, one step back439 #abortController?: AbortController;Code styleSindre Sorhusbefore adoption333afbe
line 440why, one step back440 #retryCount = 0;Harden retrySindre Sorhusbefore adoptionc426f19
line 441why, one step back441 #retryLimit: number;Code styleSindre Sorhusbefore adoption333afbe
line 442why, one step back442 readonly #options: InternalOptions;Preserve Request input abort signalsSindre Sorhusbefore adoption071a9b9
lines 443–444why, one step back443 // Keep the input Request alive because Node.js stops forwarding its signal when the Request is garbage-collected.444 readonly #requestInput: Request | undefined;Code styleSindre Sorhusbefore adoption333afbe
line 445why, one step back445 #originalRequest?: Request;Improve docsSindre Sorhusbefore adoption8778439
line 446why, one step back446 #requestBodyCanBeCancelled = false;Preserve Request input abort signalsSindre Sorhusbefore adoption071a9b9
line 447why, one step back447 readonly #userProvidedAbortSignal: AbortSignal | undefined;Make `beforeError` hook receive all errors (#829)Sindre Sorhusbefore adoption101c74b
line 448why, one step back448 readonly #beforeRetryHookErrors = new WeakSet<Error>();Add `ky.retry()` to force retries from `afterResponse` hooks (#779)Sindre Sorhusbefore adoption68a5228
line 449why, one step back449 #cachedNormalizedOptions: NormalizedOptions | undefined;RefactorSindre Sorhusbefore adoptiona5ed57b
lines 450–453why, one step back450 // When the `totalTimeout` budget runs out, or `Infinity` without a `totalTimeout`.451 readonly #deadline: number;452 // Responses returned by a `beforeRequest` or `beforeRetry` hook. They are used as-is, so a failing status throws instead of being retried.453 readonly #hookResponses = new WeakSet<Response>();Various tweaksSindre Sorhusbefore adoption0dd9522
line 454why, one step back454 readonly #responseRequests = new WeakMap<Response, Request>();Fix `parseJson` being ignored by `response.clone().json()`Sindre Sorhusbefore adoptionc6c5dbf
line 455why, one step back455 readonly #decoratedResponses = new WeakSet<Response>();Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 456–458why, one step back456457 // eslint-disable-next-line complexity458 constructor(input: Input, options: Options = {}) {TweaksSindre Sorhusbefore adoption3ded2aa
lines 459–468why, one step back459 // Checked before the options are built, since building them reads `input.headers`.460 if (typeof input !== 'string' && !(input instanceof URL || input instanceof globalThis.Request)) {461 throw new TypeError('`input` must be a string, URL, or Request');462 }463464 // 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,467 totalTimeout = false,468 } = options;Minor tweaksSindre Sorhusbefore adoption4b37c96
lines 469–471why, one step back469 if (Object.hasOwn(options, 'prefixUrl')) {470 throw new Error(prefixUrlRenamedErrorMessage);471 }Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 472why, one step back472Report the sent request for a hook's response, and finish the cross-realm and `null` checksSindre Sorhusbefore adoption7f0137d
lines 473–474why, one step back473 // 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.474 for (const key of ['headers', 'method', 'prefix', 'baseUrl', 'referrer', 'referrerPolicy'] as const) {TweaksSindre Sorhusbefore adoption3ded2aa
lines 475–479why, one step back475 if (options[key] === null) {476 throw new TypeError(`The \`${key}\` option must not be \`null\`. Use \`undefined\` to clear it.`);477 }478 }479RefactorSindre Sorhusbefore adoptiona5ed57b
line 480why, one step back480 if (options.context !== undefined && !isNonArrayObject(options.context)) {TweaksSindre Sorhusbefore adoption3ded2aa
lines 481–483why, one step back481 throw new TypeError('The `context` option must be an object');482 }483Code styleSindre Sorhusbefore adoption333afbe
line 484why, one step back484 this.#options = {Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 485why, one step back485 ...options,Simplify request state and retry normalizationSindre Sorhusbefore adoptionb28ba90
line 486why, one step back486 headers: mergeHeaders((input as Request).headers, options.headers),Various tweaksSindre Sorhusbefore adoption0dd9522
line 487why, one step back487 hooks: mergeHooks({}, options.hooks),Simplify request state and retry normalizationSindre Sorhusbefore adoptionb28ba90
lines 488–490why, one step back488 method: normalizeRequestMethod(options.method ?? (input as Request).method ?? 'GET'),489 referrer: options.referrer ?? (input as Request).referrer,490 referrerPolicy: options.referrerPolicy ?? (input as Request).referrerPolicy,Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 491why, one step back491 // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescingAdd `baseUrl` option, rename `prefixUrl` to `prefix`, and allow leading slashes in input (#606)Seth Holladaybefore adoption1f2ad7f
line 492why, one step back492 prefix: String(options.prefix || ''),Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 493why, one step back493 retry: normalizeRetryOptions(options.retry),Let a `beforeRetry` hook change per-attempt optionsSindre Sorhusbefore adoption242c327
line 494why, one step back494 ...withAttemptDefaults(options),TweaksSindre Sorhusbefore adoption3ded2aa
line 495why, one step back495 totalTimeout,Add `maxResponseSize` optionSindre Sorhusbefore adoption0d59458
line 496why, one step back496 maxResponseSize,TweaksSindre Sorhusbefore adoption3ded2aa
line 497why, one step back497 context: options.context ?? {},Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 498why, one step back498 };TweaksSindre Sorhusbefore adoption3ded2aa
lines 499–500why, one step back499 // Checked here rather than on the way out, because the constructor already calls `stringifyJson`.500 validateCallbackOptions(this.#options);Let a `beforeRetry` hook change per-attempt optionsSindre Sorhusbefore adoption242c327
line 501why, one step back501 validateTimeoutOption(this.#options.timeout, 'timeout');TweaksSindre Sorhusbefore adoption3ded2aa
line 502why, one step back502 validateTimeoutOption(totalTimeout, 'totalTimeout');Harden retrySindre Sorhusbefore adoptionc426f19
line 503why, one step back503 this.#retryLimit = this.#options.retry.limit;Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 504why, one step back504Add `maxResponseSize` optionSindre Sorhusbefore adoption0d59458
lines 505–508why, one step back505 if (maxResponseSize !== Number.POSITIVE_INFINITY && (!Number.isSafeInteger(maxResponseSize) || maxResponseSize < 0)) {506 throw new TypeError('The `maxResponseSize` option must be a non-negative safe integer or Infinity');507 }508Preserve Request input abort signalsSindre Sorhusbefore adoption071a9b9
lines 509–510why, one step back509 this.#requestInput = input instanceof globalThis.Request ? input : undefined;510RefactorSindre Sorhusbefore adoptiona5ed57b
line 511why, one step back511 input = resolveInput(input, this.#options.prefix, this.#options.baseUrl);Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 512–513why, one step back512513 if (supportsAbortController && supportsAbortSignal) {Preserve Request input abort signalsSindre Sorhusbefore adoption071a9b9
line 514why, one step back514 this.#userProvidedAbortSignal = this.#options.signal ?? this.#requestInput?.signal;Code styleSindre Sorhusbefore adoption333afbe
line 515why, one step back515 this.#abortController = new globalThis.AbortController();Various tweaksSindre Sorhusbefore adoption0dd9522
line 516why, one step back516 this.#options.signal = this.#createManagedSignal();Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 517–520why, one step back517 }518519 if (supportsRequestStreams) {520 // @ts-expect-error - Types are outdated.Code styleSindre Sorhusbefore adoption333afbe
line 521why, one step back521 this.#options.duplex = 'half';Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 522–523why, one step back522 }523Fix `json` option keeping the content-type inherited from a `Request` input bodySindre Sorhusbefore adoption0f2de47
line 524why, one step back524 // A `Request` input's headers are already merged in, so only a content-type from `options.headers` counts as user-provided.Fix headers set to `undefined` in `init` hooks being sent as the string `"undefined"`Sindre Sorhusbefore adoption224034d
line 525why, one step back525 const userProvidedContentType = options.headers !== undefined && mergeHeaders({}, options.headers).has('content-type');Fix `json` option keeping the content-type inherited from a `Request` input bodySindre Sorhusbefore adoption0f2de47
line 526why, one step back526Code styleSindre Sorhusbefore adoption333afbe
lines 527–528why, one step back527 if (this.#options.json !== undefined) {528 this.#options.body = this.#options.stringifyJson?.(this.#options.json) ?? JSON.stringify(this.#options.json);Fix `json` option keeping the content-type inherited from a `Request` input bodySindre Sorhusbefore adoption0f2de47
lines 529–531why, one step back529 if (!userProvidedContentType) {530 this.#options.headers.set('content-type', 'application/json');531 }Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 532–536why, one step back532 }533534 // To provide correct form boundary, Content-Type header should be deleted when creating Request from another Request with FormData/URLSearchParams body535 // Only delete if user didn't explicitly provide a custom content-type536 if (Simplify request state and retry normalizationSindre Sorhusbefore adoptionb28ba90
line 537why, one step back537 input instanceof globalThis.RequestCode styleSindre Sorhusbefore adoption333afbe
line 538why, one step back538 && ((supportsFormData && this.#options.body instanceof globalThis.FormData) || this.#options.body instanceof URLSearchParams)Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 539–540why, one step back539 && !userProvidedContentType540 ) {Code styleSindre Sorhusbefore adoption333afbe
line 541why, one step back541 this.#options.headers.delete('content-type');Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 542–543why, one step back542 }543Simplify request state and retry normalizationSindre Sorhusbefore adoptionb28ba90
line 544why, one step back544 this.request = new globalThis.Request(input, this.#options as RequestInit);Improve docsSindre Sorhusbefore adoption8778439
line 545why, one step back545 this.#requestBodyCanBeCancelled = typeof globalThis.ReadableStream === 'function' && this.#options.body instanceof globalThis.ReadableStream;Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 546why, one step back546RefactorSindre Sorhusbefore adoptiona5ed57b
lines 547–548why, one step back547 const {searchParams} = this.#options;548 if (hasSearchParameters(searchParams)) {Merge `searchParams` with input URL (#840)AkaHarshitbefore adoption29e78fe
line 549why, one step back549 const url = new URL(this.request.url);RefactorSindre Sorhusbefore adoptiona5ed57b
line 550why, one step back550 applySearchParameters(url, searchParams);Merge `searchParams` with input URL (#840)AkaHarshitbefore adoption29e78fe
line 551why, one step back551Remove unnecessary double Request wrapping in searchParams handling (#773)Sindre Sorhusbefore adoption836feb4
line 552why, one step back552 // Recreate request with the updated URL. We already have all options in this.#options, including duplex.Skip a needless request rebuild, report an unknown total as zero, and fix two stale testsSindre Sorhusbefore adoptionfa0eac4
lines 553–582why, one step back553 // Rebuilding is also what drops an inherited `Request` body, so it is skipped when the search parameters leave the URL unchanged.554 if (url.href !== this.request.url) {555 // Request options are read back from the current request so values inherited from a `Request` input (like `credentials`) survive, while explicit options already won when that request was built.556 // A `Request` input's body is only available as a stream, so keeping it requires request stream support.557 const {558 body: inheritedBody,559 cache,560 credentials,561 integrity,562 keepalive,563 mode,564 redirect,565 referrer,566 referrerPolicy,567 } = this.request;568 const canUseInheritedBody = supportsRequestStreams && !keepalive && mode !== 'no-cors';569570 this.request = new globalThis.Request(url, {571 ...this.#options,572 cache,573 credentials,574 integrity,575 keepalive,576 mode,577 redirect,578 referrer,579 referrerPolicy,580 body: this.#options.body ?? (canUseInheritedBody ? inheritedBody : undefined),581 } as RequestInit);582 }Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 583–584why, one step back583 }584Fix flaky testSindre Sorhusbefore adoption4ba8c15
lines 585–586why, one step back585 // `totalTimeout` starts when the request pipeline is created, so it also includes586 // Ky's internal scheduling and user hook time before the first fetch attempt.RefactorSindre Sorhusbefore adoptiona5ed57b
line 587why, one step back587 this.#deadline = typeof totalTimeout === 'number' ? getCurrentTime() + totalTimeout : Number.POSITIVE_INFINITY;Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 588–589why, one step back588 }589RefactorSindre Sorhusbefore adoptiona5ed57b
lines 590–664why, one step back590 async #run(): Promise<Response | undefined> {591 // Delay the fetch so that body method shortcuts can set the Accept header592 await Promise.resolve();593 const beforeRequestResponse = await this.#runBeforeRequestHooks();594 if (beforeRequestResponse !== undefined) {595 this.#retryLimit = normalizeRetryOptions(this.#options.retry).limit;596 }597598 let response = beforeRequestResponse ?? await this.#retry();599600 for (;;) {601 // `undefined` means a hook stopped the flow.602 if (response === undefined) {603 return undefined;604 }605606 // Read before the `afterResponse` hooks run, since they can replace the response.607 const responseFromHook = this.#hookResponses.has(response);608609 let retryError: Error | undefined;610 try {611 // eslint-disable-next-line no-await-in-loop612 response = await this.#runAfterResponseHooks(response);613 } catch (error) {614 if (!isForceRetryError(error)) {615 throw error;616 }617618 retryError = error;619 }620621 if (retryError === undefined) {622 const currentResponse: Response = response;623624 // Opaque responses (`response.type === 'opaque'`) from `no-cors` requests always have `status: 0` and `ok: false`, but this is not a failure - the actual status is hidden by the browser.625 if (currentResponse.ok || currentResponse.type === 'opaque' || !this.#shouldThrowHttpErrors(currentResponse)) {626 break;627 }628629 // `request` must reflect the request that actually failed, but `options` stays as Ky's630 // normalized options snapshot. Replacement `Request` instances do not preserve the631 // original `BodyInit`, so trying to make `options` mirror arbitrary requests would be lossy.632 const httpError: HTTPError = new HTTPError(currentResponse, this.#getResponseRequest(currentResponse), this.#getNormalizedOptions());633 // eslint-disable-next-line no-await-in-loop634 httpError.data = await this.#getResponseData(currentResponse);635 this.#throwIfAbortedByUser();636 this.#throwIfTotalTimeoutExhausted();637638 if (responseFromHook) {639 throw httpError;640 }641642 retryError = httpError;643 }644645 // eslint-disable-next-line no-await-in-loop646 response = await this.#retryFromError(retryError);647 }648649 this.#decorateResponse(response);650651 // If `onDownloadProgress` is passed, it uses the stream API internally652 if (this.#options.onDownloadProgress) {653 if (!supportsResponseStreams) {654 throw new Error('Streams are not supported in your environment. `ReadableStream` is missing.');655 }656657 const progressResponse = streamResponse(response, this.#options.onDownloadProgress);658 this.#setResponseRequest(progressResponse, this.#getResponseRequest(response));659 return this.#decorateResponse(progressResponse);660 }661662 return response;663 }664TweaksSindre Sorhusbefore adoption3ded2aa
line 665why, one step back665 #calculateDelay(retry: InternalOptions['retry'], error: unknown): number {Harden retrySindre Sorhusbefore adoptionc426f19
line 666why, one step back666 const retryDelay = retry.delay(this.#retryCount + 1);Add `retryOnTimeout` and `shouldRetry` options (#767)Sindre Sorhusbefore adoptionf0fdbd4
line 667why, one step back667TweaksSindre Sorhusbefore adoption3ded2aa
line 668why, one step back668 // A `retry.delay` that does not return a usable number would turn every delay into `NaN`, which `setTimeout()` clamps to 1ms, silently disabling the configured backoff. The `jitter` function form already guards its own result, so the input is checked here for every jitter form.RefactorSindre Sorhusbefore adoptiona5ed57b
line 669why, one step back669 if (!isNonNegativeNumber(retryDelay)) {TweaksSindre Sorhusbefore adoption3ded2aa
lines 670–673why, one step back670 // The failure that was being retried is chained as the cause, so `beforeError` can still inspect it instead of losing the response and data to this configuration mistake.671 throw new TypeError('`retry.delay` must return a non-negative number or `Infinity`', {cause: error});672 }673Add `retryOnTimeout` and `shouldRetry` options (#767)Sindre Sorhusbefore adoptionf0fdbd4
line 674why, one step back674 let jitteredDelay = retryDelay;Harden retrySindre Sorhusbefore adoptionc426f19
line 675why, one step back675 if (retry.jitter === true) {Add `retryOnTimeout` and `shouldRetry` options (#767)Sindre Sorhusbefore adoptionf0fdbd4
line 676why, one step back676 jitteredDelay = Math.random() * retryDelay;Harden retrySindre Sorhusbefore adoptionc426f19
lines 677–678why, one step back677 } else if (typeof retry.jitter === 'function') {678 jitteredDelay = retry.jitter(retryDelay);Add `retryOnTimeout` and `shouldRetry` options (#767)Sindre Sorhusbefore adoptionf0fdbd4
lines 679–684why, one step back679680 if (!Number.isFinite(jitteredDelay) || jitteredDelay < 0) {681 jitteredDelay = retryDelay;682 }683 }684Harden retrySindre Sorhusbefore adoptionc426f19
line 685why, one step back685 return Math.min(retry.backoffLimit, jitteredDelay);Add `retryOnTimeout` and `shouldRetry` options (#767)Sindre Sorhusbefore adoptionf0fdbd4
lines 686–688why, one step back686 }687688 async #calculateRetryDelay(error: unknown) {Harden retrySindre Sorhusbefore adoptionc426f19
lines 689–690why, one step back689 const retry = normalizeRetryOptions(this.#options.retry);690 if (this.#retryCount >= Math.min(retry.limit, this.#retryLimit)) {Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 691–693why, one step back691 throw error;692 }693RefactorSindre Sorhusbefore adoptiona5ed57b
lines 694–695why, one step back694 // Wrap non-Error throws to ensure consistent error handling. `NonError.wrap()` checks with `isError` rather than `instanceof`, so a cross-realm error reaches `shouldRetry` as itself, the same way it reaches `beforeError`.695 const errorObject = NonError.wrap(error);Add `retryOnTimeout` and `shouldRetry` options (#767)Sindre Sorhusbefore adoptionf0fdbd4
line 696why, one step back696Add `ky.retry()` to force retries from `afterResponse` hooks (#779)Sindre Sorhusbefore adoption68a5228
line 697why, one step back697 // Handle forced retry from afterResponse hook - skip method check and shouldRetryTweaksSindre Sorhusbefore adoption3ded2aa
lines 698–699why, one step back698 if (isForceRetryError(errorObject)) {699 return errorObject.customDelay ?? this.#calculateDelay(retry, error);Add `ky.retry()` to force retries from `afterResponse` hooks (#779)Sindre Sorhusbefore adoption68a5228
lines 700–702why, one step back700 }701702 // Check if method is retriable for non-forced retriesRespect custom HTTP method case when matching retriesSindre Sorhusbefore adoptione4269f0
line 703why, one step back703 if (!retry.methods.includes(normalizeRetryMethod(this.request.method))) {Add `ky.retry()` to force retries from `afterResponse` hooks (#779)Sindre Sorhusbefore adoption68a5228
lines 704–706why, one step back704 throw error;705 }706Honour a server retry-timing header when `shouldRetry` allows the retrySindre Sorhusbefore adoptiond1c921f
line 707why, one step back707 let shouldRetryOverride = false;Harden retrySindre Sorhusbefore adoptionc426f19
lines 708–709why, one step back708 const {shouldRetry} = retry;709 if (shouldRetry !== undefined) {RefactorSindre Sorhusbefore adoptiona5ed57b
line 710why, one step back710 const result = await this.#raceWithTotalTimeout(async () => shouldRetry({error: errorObject, retryCount: this.#retryCount + 1}));Preserve a user cancellation across retry decisions and report the bytes that arrivedSindre Sorhusbefore adoptionde278ae
line 711why, one step back711 this.#throwIfAbortedByUser();RefactorSindre Sorhusbefore adoptiona5ed57b
line 712why, one step back712 if (result === timedOut) {TweaksSindre Sorhusbefore adoption3ded2aa
line 713why, one step back713 throw new TimeoutError(this.#sentRequest);Harden retrySindre Sorhusbefore adoptionc426f19
line 714why, one step back714 }Add `retryOnTimeout` and `shouldRetry` options (#767)Sindre Sorhusbefore adoptionf0fdbd4
line 715why, one step back715Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113
line 716why, one step back716 // Only exact booleans override the default retry checks.Add `retryOnTimeout` and `shouldRetry` options (#767)Sindre Sorhusbefore adoptionf0fdbd4
lines 717–720why, one step back717 if (result === false) {718 throw error;719 }720Honour a server retry-timing header when `shouldRetry` allows the retrySindre Sorhusbefore adoptiond1c921f
line 721why, one step back721 shouldRetryOverride = result === true;Add `retryOnTimeout` and `shouldRetry` options (#767)Sindre Sorhusbefore adoptionf0fdbd4
lines 722–724why, one step back722 }723724 // Default timeout behaviorAdd `NetworkError` class and tighten retry logic (#842)Sindre Sorhusbefore adoptioneaf0b80
line 725why, one step back725 if (isTimeoutError(error)) {Honour a server retry-timing header when `shouldRetry` allows the retrySindre Sorhusbefore adoptiond1c921f
line 726why, one step back726 if (!shouldRetryOverride && !retry.retryOnTimeout) {Add `NetworkError` class and tighten retry logic (#842)Sindre Sorhusbefore adoptioneaf0b80
lines 727–729why, one step back727 throw error;728 }729TweaksSindre Sorhusbefore adoption3ded2aa
line 730why, one step back730 return this.#calculateDelay(retry, error);Add `retryOnTimeout` and `shouldRetry` options (#767)Sindre Sorhusbefore adoptionf0fdbd4
lines 731–732why, one step back731 }732Stop surfacing progress callback errorsSindre Sorhusbefore adoption13c8da5
line 733why, one step back733 if (isHTTPError(error)) {Honour a server retry-timing header when `shouldRetry` allows the retrySindre Sorhusbefore adoptiond1c921f
line 734why, one step back734 if (!shouldRetryOverride && !retry.statusCodes.includes(error.response.status)) {Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 735–737why, one step back735 throw error;736 }737Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113
line 738why, one step back738 const retryTimingHeader = getRetryTimingHeader(error.response.headers);Harden retrySindre Sorhusbefore adoptionc426f19
line 739why, one step back739 if (retryTimingHeader && retry.afterStatusCodes.includes(error.response.status)) {Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113
lines 740–742why, one step back740 const after = calculateRetryTimingDelay(retryTimingHeader);741 if (after === undefined) {742 // Malformed retry timing headers should not disable retries; they only lose their server-provided timing.TweaksSindre Sorhusbefore adoption3ded2aa
line 743why, one step back743 return this.#calculateDelay(retry, error);Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 744–745why, one step back744 }745Add `retryOnTimeout` and `shouldRetry` options (#767)Sindre Sorhusbefore adoptionf0fdbd4
line 746why, one step back746 // Don't apply jitter when server provides explicit retry timingHarden retrySindre Sorhusbefore adoptionc426f19
line 747why, one step back747 return Math.min(retry.maxRetryAfter, after);Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 748–749why, one step back748 }749Honour a server retry-timing header when `shouldRetry` allows the retrySindre Sorhusbefore adoptiond1c921f
line 750why, one step back750 if (!shouldRetryOverride && error.response.status === 413) {Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 751–752why, one step back751 throw error;752 }Add `NetworkError` class and tighten retry logic (#842)Sindre Sorhusbefore adoptioneaf0b80
line 753why, one step back753TweaksSindre Sorhusbefore adoption3ded2aa
line 754why, one step back754 return this.#calculateDelay(retry, error);Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 755–756why, one step back755 }756Add `NetworkError` class and tighten retry logic (#842)Sindre Sorhusbefore adoptioneaf0b80
line 757why, one step back757 // Only retry known retriable error types. Unknown errors (e.g., programming bugs) are not retried.Honour a server retry-timing header when `shouldRetry` allows the retrySindre Sorhusbefore adoptiond1c921f
line 758why, one step back758 if (!shouldRetryOverride && !isNetworkError(error)) {Add `NetworkError` class and tighten retry logic (#842)Sindre Sorhusbefore adoptioneaf0b80
lines 759–761why, one step back759 throw error;760 }761TweaksSindre Sorhusbefore adoption3ded2aa
line 762why, one step back762 return this.#calculateDelay(retry, error);Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 763–764why, one step back763 }764Code styleSindre Sorhusbefore adoption333afbe
line 765why, one step back765 #decorateResponse(response: Response): Response {Fix `parseJson` being ignored by `response.clone().json()`Sindre Sorhusbefore adoptionc6c5dbf
lines 766–770why, one step back766 if (!this.#options.parseJson || this.#decoratedResponses.has(response)) {767 return response;768 }769770 this.#decoratedResponses.add(response);Various tweaksSindre Sorhusbefore adoption0dd9522
lines 771–772why, one step back771 const request = this.#getResponseRequest(response);772RefactorSindre Sorhusbefore adoptiona5ed57b
line 773why, one step back773 response.json = async () => this.#parseJson(await response.text(), request, response);Fix `parseJson` being ignored by `response.clone().json()`Sindre Sorhusbefore adoptionc6c5dbf
line 774why, one step back774Stop surfacing progress callback errorsSindre Sorhusbefore adoption13c8da5
lines 775–777why, one step back775 // `clone()` returns a fresh `Response` that would otherwise fall back to the native `json()`.776 const nativeClone = response.clone.bind(response);777 response.clone = () => this.#decorateResponse(this.#setResponseRequest(nativeClone(), request));Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 778–779why, one step back778779 return response;Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c
lines 780–781why, one step back780 }781TweaksSindre Sorhusbefore adoption3ded2aa
lines 782–785why, one step back782 // Defaults to the last request that was actually sent, because `this.request` is the clone `#fetch()` prepares for a possible retry and may never be sent at all.783 async #throwProcessedError(error: unknown, request: Request = this.#sentRequest): Promise<never> {784 // Non-Error throws (e.g., thrown strings) pass through unchanged. `isError` reads the internal brand, so an error from another realm still runs the hooks, the same way the Ky type guards accept branded errors.785 if (!isError(error)) {Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113
lines 786–795why, one step back786 throw error;787 }788789 // Errors thrown by beforeRetry hooks must propagate unchanged.790 if (this.#beforeRetryHookErrors.has(error)) {791 throw error;792 }793794 let processedError: Error = error;795 for (const hook of this.#options.hooks.beforeError) {TweaksSindre Sorhusbefore adoption3ded2aa
line 796why, one step back796 // `options` intentionally remains the stable normalized Ky options snapshot for the same reason as `HTTPError` above.Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113
lines 797–798why, one step back797 // eslint-disable-next-line no-await-in-loop798 const hookResult: unknown = await hook({TweaksSindre Sorhusbefore adoption3ded2aa
line 799why, one step back799 request,Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113
lines 800–804why, one step back800 options: this.#getNormalizedOptions(),801 error: processedError,802 retryCount: this.#retryCount,803 });804TweaksSindre Sorhusbefore adoption3ded2aa
lines 805–806why, one step back805 // Only overwrite if the hook returns a valid Error, including one from another realm.806 if (isError(hookResult)) {Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113
lines 807–813why, one step back807 processedError = hookResult;808 }809 }810811 throw processedError;812 }813Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c
line 814why, one step back814 async #getResponseData(response: Response): Promise<unknown> {HardenSindre Sorhusbefore adoption8d8e7a4
lines 815–817why, one step back815 // `request` is the request that actually produced this response, which is not `this.request` once a retry clone has been prepared.816 const request = this.#getResponseRequest(response);817RefactorSindre Sorhusbefore adoptiona5ed57b
lines 818–820why, one step back818 // A timed-out read or parse gives up on the data, but an exhausted `totalTimeout` still fails the request.819 const throwIfTotalTimeoutReached = ({fromTotalTimeout}: ErrorDataTimeout): void => {820 if (fromTotalTimeout) {HardenSindre Sorhusbefore adoption8d8e7a4
line 821why, one step back821 throw new TimeoutError(request);Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113
lines 822–823why, one step back822 }823HardenSindre Sorhusbefore adoption8d8e7a4
line 824why, one step back824 this.#throwIfTotalTimeoutExhausted(request);RefactorSindre Sorhusbefore adoptiona5ed57b
lines 825–832why, one step back825 };826827 // Even with request timeouts disabled, bound error-body reads so retries and error propagation828 // cannot be stalled indefinitely by never-ending response streams.829 const readTimeout = this.#getErrorDataTimeout(request);830 const text = await readResponseText(response, readTimeout.milliseconds);831 if (text === timedOut) {832 throwIfTotalTimeoutReached(readTimeout);Add `totalTimeout` option and make `timeout` be per retry (#848)Sindre Sorhusbefore adoptionc20d7c7
lines 833–835why, one step back833 return undefined;834 }835Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c
lines 836–839why, one step back836 if (!text) {837 return undefined;838 }839RefactorSindre Sorhusbefore adoptiona5ed57b
line 840why, one step back840 if (!isJsonContentType(response.headers.get('content-type') ?? '')) {Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c
lines 841–843why, one step back841 return text;842 }843HardenSindre Sorhusbefore adoption8d8e7a4
line 844why, one step back844 const parseTimeout = this.#getErrorDataTimeout(request);RefactorSindre Sorhusbefore adoptiona5ed57b
lines 845–848why, one step back845 // Unparsable error data is given up on, like unreadable error data.846 const data = await raceWithTimeout(Promise.resolve().then(() => this.#parseJson(text, request, response)), parseTimeout.milliseconds).catch(() => undefined);847 if (data === timedOut) {848 throwIfTotalTimeoutReached(parseTimeout);Add `totalTimeout` option and make `timeout` be per retry (#848)Sindre Sorhusbefore adoptionc20d7c7
lines 849–852why, one step back849 return undefined;850 }851852 return data;Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c
lines 853–854why, one step back853 }854RefactorSindre Sorhusbefore adoptiona5ed57b
line 855why, one step back855 #getErrorDataTimeout(request: Request): ErrorDataTimeout {Add `totalTimeout` option and make `timeout` be per retry (#848)Sindre Sorhusbefore adoptionc20d7c7
lines 856–857why, one step back856 const errorDataTimeout = this.#options.timeout === false ? 10_000 : this.#options.timeout;857 const remainingTotal = this.#getRemainingTotalTimeout();RefactorSindre Sorhusbefore adoptiona5ed57b
line 858why, one step back858 if (remainingTotal === 0) {HardenSindre Sorhusbefore adoption8d8e7a4
line 859why, one step back859 throw new TimeoutError(request);Add `totalTimeout` option and make `timeout` be per retry (#848)Sindre Sorhusbefore adoptionc20d7c7
lines 860–861why, one step back860 }861Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113
lines 862–867why, one step back862 return {863 milliseconds: Math.min(errorDataTimeout, remainingTotal),864 fromTotalTimeout: remainingTotal <= errorDataTimeout,865 };866 }867RefactorSindre Sorhusbefore adoptiona5ed57b
line 868why, one step back868 // The smaller of `timeout` and the `totalTimeout` budget left, or `undefined` when neither applies, since `setTimeout()` cannot wait forever.Simplify request state and retry normalizationSindre Sorhusbefore adoptionb28ba90
line 869why, one step back869 #getEffectiveTimeout(): number | undefined {Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113
line 870why, one step back870 const remainingTotal = this.#getRemainingTotalTimeout();RefactorSindre Sorhusbefore adoptiona5ed57b
lines 871–872why, one step back871 if (remainingTotal === 0) {872 throw new TimeoutError(this.#sentRequest);Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113
lines 873–874why, one step back873 }874RefactorSindre Sorhusbefore adoptiona5ed57b
lines 875–876why, one step back875 const effectiveTimeout = Math.min(this.#options.timeout === false ? Number.POSITIVE_INFINITY : this.#options.timeout, remainingTotal);876 return effectiveTimeout === Number.POSITIVE_INFINITY ? undefined : effectiveTimeout;Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113
lines 877–881why, one step back877 }878879 // Unlike error bodies (`#getResponseData`), a successful body read has no fallback value to return -880 // the caller's `.json()`/`.text()`/etc. promise must settle, so a timeout here always rejects.881 async #raceBodyRead(createBodyPromise: () => Promise<unknown>, response: Response): Promise<unknown> {TweaksSindre Sorhusbefore adoption3ded2aa
line 882why, one step back882 const failedRequest = this.#getResponseRequest(response);RefactorSindre Sorhusbefore adoptiona5ed57b
line 883why, one step back883 let timeoutMilliseconds: number | undefined;Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113
line 884why, one step back884 try {RefactorSindre Sorhusbefore adoptiona5ed57b
line 885why, one step back885 timeoutMilliseconds = this.#getEffectiveTimeout();Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113
line 886why, one step back886 } catch (error: unknown) {TweaksSindre Sorhusbefore adoption3ded2aa
line 887why, one step back887 await this.#throwProcessedError(error, failedRequest);Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113
lines 888–889why, one step back888 }889Fix `beforeError` hooks running again when a body fails after the body read timed outSindre Sorhusbefore adoptione087b0c
lines 890–893why, one step back890 const bodyPromise = createBodyPromise();891892 let result: unknown;893 try {RefactorSindre Sorhusbefore adoptiona5ed57b
line 894why, one step back894 result = timeoutMilliseconds === undefinedFix `beforeError` hooks running again when a body fails after the body read timed outSindre Sorhusbefore adoptione087b0c
line 895why, one step back895 ? await bodyPromiseRefactorSindre Sorhusbefore adoptiona5ed57b
line 896why, one step back896 : await raceWithTimeout(bodyPromise, timeoutMilliseconds);Fix `beforeError` hooks running again when a body fails after the body read timed outSindre Sorhusbefore adoptione087b0c
line 897why, one step back897 } catch (error: unknown) {Release the bodies a caller cannot reach and stop sharing search parametersSindre Sorhusbefore adoptionec3d17f
line 898why, one step back898 if (this.#userProvidedAbortSignal?.aborted) {TweaksSindre Sorhusbefore adoption3ded2aa
line 899why, one step back899 await this.#throwProcessedError(this.#userProvidedAbortSignal.reason, failedRequest);Release the bodies a caller cannot reach and stop sharing search parametersSindre Sorhusbefore adoptionec3d17f
lines 900–901why, one step back900 }901Enforce total timeout after fetch and body processingSindre Sorhusbefore adoption82fa84c
lines 902–905why, one step back902 if (this.#getRemainingTotalTimeout() !== 0) {903 // A connection dropped while streaming the body surfaces as a raw runtime `TypeError`. Wrap it like fetch-phase network errors so it is recognizable and runs `beforeError` hooks.904 // This only happens on the awaited path, so a body that fails after the timeout already won does not run the hooks again.905 if (isRawNetworkError(error)) {TweaksSindre Sorhusbefore adoption3ded2aa
line 906why, one step back906 await this.#throwProcessedError(new NetworkError(failedRequest, {cause: error as Error}), failedRequest);Enforce total timeout after fetch and body processingSindre Sorhusbefore adoption82fa84c
lines 907–908why, one step back907 }908TweaksSindre Sorhusbefore adoption3ded2aa
line 909why, one step back909 await this.#throwProcessedError(error, failedRequest);Fix `beforeError` hooks running again when a body fails after the body read timed outSindre Sorhusbefore adoptione087b0c
lines 910–911why, one step back910 }911RefactorSindre Sorhusbefore adoptiona5ed57b
line 912why, one step back912 result = timedOut;Fix `beforeError` hooks running again when a body fails after the body read timed outSindre Sorhusbefore adoptione087b0c
line 913why, one step back913 }Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113
line 914why, one step back914TweaksSindre Sorhusbefore adoption3ded2aa
lines 915–919why, one step back915 // A cancellation is part of the request lifecycle, so it must not resolve as a successful body read just because the bytes happened to arrive first. `.json()` already gets this check for free through `#raceWithTotalTimeout()`, which is why the shortcuts used to disagree here.916 if (this.#userProvidedAbortSignal?.aborted) {917 await this.#throwProcessedError(this.#userProvidedAbortSignal.reason, failedRequest);918 }919RefactorSindre Sorhusbefore adoptiona5ed57b
line 920why, one step back920 if (result === timedOut || this.#getRemainingTotalTimeout() === 0) {Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113
lines 921–924why, one step back921 // The stream is locked by the native body method's own reader by this point, so922 // `response.body.cancel()` would reject as "already locked". Aborting the request's923 // signal is what actually interrupts the underlying network read.924 this.#abortController?.abort();TweaksSindre Sorhusbefore adoption3ded2aa
line 925why, one step back925 await this.#throwProcessedError(new TimeoutError(failedRequest), failedRequest);Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113
lines 926–930why, one step back926 }927928 return result;929 }930RefactorSindre Sorhusbefore adoptiona5ed57b
lines 931–932why, one step back931 async #raceWithTotalTimeout<T>(operation: () => Promise<T>): Promise<T | typeof timedOut> {932 const abortSignal = this.#userProvidedAbortSignal;Preserve a user cancellation across retry decisions and report the bytes that arrivedSindre Sorhusbefore adoptionde278ae
line 933why, one step back933 abortSignal?.throwIfAborted();Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113
line 934why, one step back934Preserve a user cancellation across retry decisions and report the bytes that arrivedSindre Sorhusbefore adoptionde278ae
line 935why, one step back935 const remainingTotal = this.#getRemainingTotalTimeout();RefactorSindre Sorhusbefore adoptiona5ed57b
line 936why, one step back936 if (remainingTotal === 0) {Harden retrySindre Sorhusbefore adoptionc426f19
line 937why, one step back937 this.#abortController?.abort();RefactorSindre Sorhusbefore adoptiona5ed57b
line 938why, one step back938 return timedOut;Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113
lines 939–940why, one step back939 }940Harden retrySindre Sorhusbefore adoptionc426f19
line 941why, one step back941 let timeoutId: ReturnType<typeof setTimeout> | undefined;Preserve a user cancellation across retry decisions and report the bytes that arrivedSindre Sorhusbefore adoptionde278ae
line 942why, one step back942 let abortListener: (() => void) | undefined;TweaksSindre Sorhusbefore adoption3ded2aa
line 943why, one step back943 let operationPromise: Promise<T> | undefined;Harden retrySindre Sorhusbefore adoptionc426f19
line 944why, one step back944 try {Preserve a user cancellation across retry decisions and report the bytes that arrivedSindre Sorhusbefore adoptionde278ae
lines 945–954why, one step back945 const abortPromise = new Promise<never>((_resolve, reject) => {946 if (!abortSignal) {947 return;948 }949950 abortListener = () => {951 // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors -- AbortSignal reasons can be any value and must be preserved exactly.952 reject(abortSignal.reason);953 };954RefactorSindre Sorhusbefore adoptiona5ed57b
line 955why, one step back955 // The signal was checked above, and nothing ran since, so it cannot have aborted before the listener is added.Preserve a user cancellation across retry decisions and report the bytes that arrivedSindre Sorhusbefore adoptionde278ae
lines 956–957why, one step back956 abortSignal.addEventListener('abort', abortListener, {once: true});957 });TweaksSindre Sorhusbefore adoption3ded2aa
line 958why, one step back958 operationPromise = operation();Preserve a user cancellation across retry decisions and report the bytes that arrivedSindre Sorhusbefore adoptionde278ae
line 959why, one step back959RefactorSindre Sorhusbefore adoptiona5ed57b
line 960why, one step back960 if (remainingTotal === Number.POSITIVE_INFINITY) {Preserve a user cancellation across retry decisions and report the bytes that arrivedSindre Sorhusbefore adoptionde278ae
lines 961–963why, one step back961 return await Promise.race([operationPromise, abortPromise]);962 }963RefactorSindre Sorhusbefore adoptiona5ed57b
line 964why, one step back964 const timeoutPromise = new Promise<typeof timedOut>(resolve => {Harden retrySindre Sorhusbefore adoptionc426f19
line 965why, one step back965 timeoutId = setTimeout(() => {RefactorSindre Sorhusbefore adoptiona5ed57b
line 966why, one step back966 resolve(timedOut);Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113
line 967why, one step back967 }, remainingTotal);Harden retrySindre Sorhusbefore adoptionc426f19
line 968why, one step back968 });Preserve a user cancellation across retry decisions and report the bytes that arrivedSindre Sorhusbefore adoptionde278ae
line 969why, one step back969 const result = await Promise.race([operationPromise, timeoutPromise, abortPromise]);RefactorSindre Sorhusbefore adoptiona5ed57b
line 970why, one step back970 if (result === timedOut || this.#getRemainingTotalTimeout() === 0) {Harden retrySindre Sorhusbefore adoptionc426f19
line 971why, one step back971 this.#abortController?.abort();Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113
line 972why, one step back972RefactorSindre Sorhusbefore adoptiona5ed57b
lines 973–974why, one step back973 if (result === timedOut) {974 releaseWhenSettled(operationPromise);Preserve caller stack for schema validation errors (#883)Sindre Sorhusbefore adoptione68ea7a
line 975why, one step back975 } else {RefactorSindre Sorhusbefore adoptiona5ed57b
line 976why, one step back976 cancelReturnedBody(result);Harden retrySindre Sorhusbefore adoptionc426f19
line 977why, one step back977 }Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113
line 978why, one step back978RefactorSindre Sorhusbefore adoptiona5ed57b
line 979why, one step back979 return timedOut;Harden retrySindre Sorhusbefore adoptionc426f19
lines 980–981why, one step back980 }981Preserve caller stack for schema validation errors (#883)Sindre Sorhusbefore adoptione68ea7a
lines 982–983why, one step back982 return result;983 } catch (error: unknown) {TweaksSindre Sorhusbefore adoption3ded2aa
line 984why, one step back984 if (abortSignal?.aborted) {RefactorSindre Sorhusbefore adoptiona5ed57b
line 985why, one step back985 // The abort won the race, so whatever the operation eventually returns is discarded. Release its body, the same way the timeout path above does for a value it never consumed.TweaksSindre Sorhusbefore adoption3ded2aa
line 986why, one step back986 if (operationPromise) {RefactorSindre Sorhusbefore adoptiona5ed57b
line 987why, one step back987 releaseWhenSettled(operationPromise);TweaksSindre Sorhusbefore adoption3ded2aa
line 988why, one step back988 }Preserve a user cancellation across retry decisions and report the bytes that arrivedSindre Sorhusbefore adoptionde278ae
line 989why, one step back989TweaksSindre Sorhusbefore adoption3ded2aa
lines 990–992why, one step back990 abortSignal.throwIfAborted();991 }992RefactorSindre Sorhusbefore adoptiona5ed57b
line 993why, one step back993 if (this.#getRemainingTotalTimeout() === 0) {Preserve caller stack for schema validation errors (#883)Sindre Sorhusbefore adoptione68ea7a
line 994why, one step back994 this.#abortController?.abort();RefactorSindre Sorhusbefore adoptiona5ed57b
line 995why, one step back995 return timedOut;Harden retrySindre Sorhusbefore adoptionc426f19
lines 996–997why, one step back996 }997Preserve caller stack for schema validation errors (#883)Sindre Sorhusbefore adoptione68ea7a
line 998why, one step back998 throw error;Harden retrySindre Sorhusbefore adoptionc426f19
lines 999–1000why, one step back999 } finally {1000 clearTimeout(timeoutId);Preserve a user cancellation across retry decisions and report the bytes that arrivedSindre Sorhusbefore adoptionde278ae
lines 1001–1003why, one step back1001 if (abortListener) {1002 abortSignal?.removeEventListener('abort', abortListener);1003 }Harden retrySindre Sorhusbefore adoptionc426f19
line 1004why, one step back1004 }Add `totalTimeout` option and make `timeout` be per retry (#848)Sindre Sorhusbefore adoptionc20d7c7
lines 1005–1006why, one step back1005 }1006RefactorSindre Sorhusbefore adoptiona5ed57b
lines 1007–1010why, one step back1007 // Uses `parseJson` when it is set, and `JSON.parse()` otherwise.1008 #parseJson(text: string, request: Request, response: Response): unknown {1009 const {parseJson} = this.#options;1010 return parseJson ? parseJson(text, {request, response}) : JSON.parse(text);Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c
lines 1011–1012why, one step back1011 }1012Various tweaksSindre Sorhusbefore adoption0dd9522
lines 1013–1016why, one step back1013 #createManagedSignal(): AbortSignal {1014 return this.#userProvidedAbortSignal1015 ? AbortSignal.any([this.#userProvidedAbortSignal, this.#abortController!.signal])1016 : this.#abortController!.signal;Release the body when a predicate throws, an abort wins, or a response cannot be decoratedSindre Sorhusbefore adoptiondeb5a33
lines 1017–1018why, one step back1017 }1018TweaksSindre Sorhusbefore adoption3ded2aa
lines 1019–1024why, one step back1019 // A `throwHttpErrors` predicate that throws used to escape from the `if` condition, before the body was read or released, leaving the caller with an error and no handle on the response to release it with.1020 #shouldThrowHttpErrors(response: Response): boolean {1021 const {throwHttpErrors} = this.#options;1022 try {1023 return typeof throwHttpErrors === 'function' ? throwHttpErrors(response.status) : throwHttpErrors;1024 } catch (error: unknown) {RefactorSindre Sorhusbefore adoptiona5ed57b
line 1025why, one step back1025 cancelBody(response);TweaksSindre Sorhusbefore adoption3ded2aa
lines 1026–1035why, one step back1026 throw error;1027 }1028 }10291030 // `#fetch()` replaces `this.request` with the clone it prepares for a possible retry, so anything reporting the request that produced a response or failed has to use the one that was actually sent.1031 get #sentRequest(): Request {1032 return this.#originalRequest ?? this.request;1033 }10341035 #throwIfTotalTimeoutExhausted(request: Request = this.#sentRequest): void {RefactorSindre Sorhusbefore adoptiona5ed57b
line 1036why, one step back1036 if (this.#getRemainingTotalTimeout() === 0) {HardenSindre Sorhusbefore adoption8d8e7a4
line 1037why, one step back1037 throw new TimeoutError(request);Various tweaksSindre Sorhusbefore adoption0dd9522
lines 1038–1040why, one step back1038 }1039 }1040Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00
lines 1041–1043why, one step back1041 async #runBeforeRequestHooks(): Promise<Response | undefined> {1042 for (const hook of this.#options.hooks.beforeRequest) {1043 // eslint-disable-next-line no-await-in-loopHarden retrySindre Sorhusbefore adoptionc426f19
line 1044why, one step back1044 const result = await this.#raceWithTotalTimeout(async () => hook({Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00
lines 1045–1047why, one step back1045 request: this.request,1046 options: this.#getNormalizedOptions(),1047 retryCount: 0,RefactorSindre Sorhusbefore adoptiona5ed57b
line 1048why, one step back1048 }));Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00
line 1049why, one step back1049RefactorSindre Sorhusbefore adoptiona5ed57b
line 1050why, one step back1050 if (result === timedOut) {TweaksSindre Sorhusbefore adoption3ded2aa
line 1051why, one step back1051 throw new TimeoutError(this.#sentRequest);Harden retrySindre Sorhusbefore adoptionc426f19
lines 1052–1053why, one step back1052 }1053RefactorSindre Sorhusbefore adoptiona5ed57b
line 1054why, one step back1054 if (isRequest(result)) {Fix timeouts and user aborts not cancelling a `Request` returned from `beforeRequest` or `beforeRetry` hooksSindre Sorhusbefore adoptione1b088e
line 1055why, one step back1055 this.#assignRequest(this.#withManagedSignal(result));RefactorSindre Sorhusbefore adoptiona5ed57b
lines 1056–1057why, one step back1056 } else if (isResponse(result)) {1057 this.#hookResponses.add(result);Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00
lines 1058–1065why, one step back1058 return result;1059 }1060 }10611062 return undefined;1063 }10641065 async #runAfterResponseHooks(response: Response): Promise<Response> {Various tweaksSindre Sorhusbefore adoption0dd9522
line 1066why, one step back1066 const responseRequest = this.#getResponseRequest(response);Add `maxResponseSize` optionSindre Sorhusbefore adoption0d59458
line 1067why, one step back1067 response = this.#limitResponseSize(response);Various tweaksSindre Sorhusbefore adoption0dd9522
line 1068why, one step back1068Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00
line 1069why, one step back1069 for (const hook of this.#options.hooks.afterResponse) {Improve compatibility with custom `fetch` implementations (#858)Sindre Sorhusbefore adoption2971991
lines 1070–1071why, one step back1070 const hookResponse = this.#setResponseRequest(response.clone(), responseRequest);1071 this.#decorateResponse(hookResponse);Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00
lines 1072–1075why, one step back10721073 let modifiedResponse;1074 try {1075 // eslint-disable-next-line no-await-in-loopHarden retrySindre Sorhusbefore adoptionc426f19
line 1076why, one step back1076 modifiedResponse = await this.#raceWithTotalTimeout(async () => hook({TweaksSindre Sorhusbefore adoption3ded2aa
line 1077why, one step back1077 // Deliberately `this.request`, which `#fetch()` has already replaced with the clone prepared for a retry, so its body is still unread. A hook that forces a retry with `ky.retry({request: new Request(request)})` depends on being able to copy an unconsumed request from here.Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00
lines 1078–1079why, one step back1078 request: this.request,1079 options: this.#getNormalizedOptions(),Improve compatibility with custom `fetch` implementations (#858)Sindre Sorhusbefore adoption2971991
line 1080why, one step back1080 response: hookResponse,Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00
line 1081why, one step back1081 retryCount: this.#retryCount,RefactorSindre Sorhusbefore adoptiona5ed57b
line 1082why, one step back1082 }));Harden retrySindre Sorhusbefore adoptionc426f19
line 1083why, one step back1083RefactorSindre Sorhusbefore adoptiona5ed57b
line 1084why, one step back1084 if (modifiedResponse === timedOut) {TweaksSindre Sorhusbefore adoption3ded2aa
line 1085why, one step back1085 throw new TimeoutError(this.#sentRequest);Harden retrySindre Sorhusbefore adoptionc426f19
line 1086why, one step back1086 }Improve compatibility with custom `fetch` implementations (#858)Sindre Sorhusbefore adoption2971991
line 1087why, one step back1087RefactorSindre Sorhusbefore adoptiona5ed57b
lines 1088–1095why, one step back1088 if (isRetryMarker(modifiedResponse)) {1089 throw new ForceRetryError(modifiedResponse.options);1090 }1091 } catch (error) {1092 // Cancel both the cloned response passed to the hook and the current response to prevent memory leaks when a hook throws, times out, or forces a retry (especially important in Deno/Bun).1093 // Do not await cancellation since hooks can clone the response, leaving extra tee branches that keep cancel promises pending per the Streams spec.1094 cancelBody(hookResponse);1095 cancelBody(response);Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00
lines 1096–1098why, one step back1096 throw error;1097 }1098RefactorSindre Sorhusbefore adoptiona5ed57b
line 1099why, one step back1099 const nextResponse = isResponse(modifiedResponse)Improve compatibility with custom `fetch` implementations (#858)Sindre Sorhusbefore adoption2971991
lines 1100–1101why, one step back1100 ? this.#setResponseRequest(modifiedResponse, responseRequest)1101 : response;Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00
lines 1102–1104why, one step back11021103 // Cancel any response bodies we won't use to prevent memory leaks.1104 // Uses fire-and-forget since hooks may have cloned the response, creating tee branches that block cancellation.Fix hook state leaks and fetch option forwardingSindre Sorhusbefore adoption2df9b7e
line 1105why, one step back1105 // If the hook wrapped an existing body into a new Response, both Response objects can still point at the same stream.RefactorSindre Sorhusbefore adoptiona5ed57b
lines 1106–1107why, one step back1106 cancelBody(hookResponse, nextResponse);1107 cancelBody(response, nextResponse);Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00
line 1108why, one step back1108Add `maxResponseSize` optionSindre Sorhusbefore adoption0d59458
lines 1109–1111why, one step back1109 if (nextResponse !== response) {1110 response = this.#limitResponseSize(nextResponse);1111 }Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00
lines 1112–1116why, one step back1112 }11131114 return response;1115 }1116Simplify request state and retry normalizationSindre Sorhusbefore adoptionb28ba90
line 1117why, one step back1117 async #retry(): Promise<Response | void> {Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 1118why, one step back1118 try {Simplify request state and retry normalizationSindre Sorhusbefore adoptionb28ba90
line 1119why, one step back1119 return await this.#fetch();Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 1120why, one step back1120 } catch (error) {Simplify request state and retry normalizationSindre Sorhusbefore adoptionb28ba90
line 1121why, one step back1121 return this.#retryFromError(error);Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00
lines 1122–1123why, one step back1122 }1123 }Fix timeout to apply to total operation including retries (#825)Sindre Sorhusbefore adoptionaac83fa
line 1124why, one step back1124Simplify request state and retry normalizationSindre Sorhusbefore adoptionb28ba90
line 1125why, one step back1125 async #retryFromError(error: unknown): Promise<Response | void> {Preserve a user cancellation across retry decisions and report the bytes that arrivedSindre Sorhusbefore adoptionde278ae
line 1126why, one step back1126 this.#throwIfAbortedByUser();Fix timeout to apply to total operation including retries (#825)Sindre Sorhusbefore adoptionaac83fa
line 1127why, one step back1127Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00
line 1128why, one step back1128 const retryDelay = Math.min(await this.#calculateRetryDelay(error), maxSafeTimeout);Various tweaksSindre Sorhusbefore adoption0dd9522
line 1129why, one step back1129 const delayOptions = {signal: this.#userProvidedAbortSignal};Fix timeout to apply to total operation including retries (#825)Sindre Sorhusbefore adoptionaac83fa
line 1130why, one step back1130Add `totalTimeout` option and make `timeout` be per retry (#848)Sindre Sorhusbefore adoptionc20d7c7
line 1131why, one step back1131 const remainingTimeout = this.#getRemainingTotalTimeout();RefactorSindre Sorhusbefore adoptiona5ed57b
lines 1132–1134why, one step back1132 if (remainingTimeout === 0) {1133 throw new TimeoutError(this.#sentRequest);1134 }Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 1135why, one step back1135RefactorSindre Sorhusbefore adoptiona5ed57b
lines 1136–1139why, one step back1136 // If waiting would consume all remaining budget, time out without starting another request.1137 if (retryDelay >= remainingTimeout) {1138 await delay(remainingTimeout, delayOptions);1139 throw new TimeoutError(this.#sentRequest);Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00
line 1140why, one step back1140 }Fix timeout to apply to total operation including retries (#825)Sindre Sorhusbefore adoptionaac83fa
line 1141why, one step back1141Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00
lines 1142–1143why, one step back1142 // Only use user-provided signal for delay, not our internal abortController1143 await delay(retryDelay, delayOptions);Add `ky.retry()` to force retries from `afterResponse` hooks (#779)Sindre Sorhusbefore adoption68a5228
line 1144why, one step back1144Various tweaksSindre Sorhusbefore adoption0dd9522
line 1145why, one step back1145 this.#throwIfTotalTimeoutExhausted();Add `ky.retry()` to force retries from `afterResponse` hooks (#779)Sindre Sorhusbefore adoption68a5228
line 1146why, one step back1146Fix hooks receiving an aborted `signal` after retrying a timeoutSindre Sorhusbefore adoption2f0a3fb
lines 1147–1150why, one step back1147 // Reset abortController if it was aborted (happens on timeout retry) so hooks and the retried request get a fresh signal1148 if (this.#abortController?.signal.aborted) {1149 this.#abortController = new globalThis.AbortController();1150 this.#options.signal = this.#createManagedSignal();Improve docsSindre Sorhusbefore adoption8778439
line 1151why, one step back1151 this.#assignRequest(this.#withManagedSignal(this.request), this.#requestBodyCanBeCancelled);Fix hooks receiving an aborted `signal` after retrying a timeoutSindre Sorhusbefore adoption2f0a3fb
lines 1152–1153why, one step back1152 }1153Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00
lines 1154–1155why, one step back1154 // Apply custom request from forced retry before beforeRetry hooks1155 // Ensure the custom request has the correct managed signal for timeouts and user abortsTweaksSindre Sorhusbefore adoption3ded2aa
line 1156why, one step back1156 if (isForceRetryError(error) && error.customRequest) {TweaksSindre Sorhusbefore adoption8f28eac
lines 1157–1159why, one step back1157 // Replacement Requests are authoritative by design. Do not rewrite headers here,1158 // even for cross-origin retries. Callers using `ky.retry({request})` explicitly1159 // opted into the exact Request they constructed.Fix timeouts and user aborts not cancelling a `Request` returned from `beforeRequest` or `beforeRetry` hooksSindre Sorhusbefore adoptione1b088e
line 1160why, one step back1160 this.#assignRequest(this.#withManagedSignal(error.customRequest));Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00
line 1161why, one step back1161 }Make `beforeError` hook receive all errors (#829)Sindre Sorhusbefore adoption101c74b
line 1162why, one step back1162Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00
line 1163why, one step back1163 for (const hook of this.#options.hooks.beforeRetry) {RefactorSindre Sorhusbefore adoptiona5ed57b
line 1164why, one step back1164 let hookResult: Awaited<ReturnType<typeof hook>> | typeof timedOut;Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00
lines 1165–1166why, one step back1165 try {1166 // eslint-disable-next-line no-await-in-loopHarden retrySindre Sorhusbefore adoptionc426f19
line 1167why, one step back1167 hookResult = await this.#raceWithTotalTimeout(async () => hook({Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00
lines 1168–1169why, one step back1168 request: this.request,1169 options: this.#getNormalizedOptions(),RefactorSindre Sorhusbefore adoptiona5ed57b
line 1170why, one step back1170 error: NonError.wrap(error),Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00
line 1171why, one step back1171 retryCount: this.#retryCount + 1,RefactorSindre Sorhusbefore adoptiona5ed57b
line 1172why, one step back1172 }));Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00
line 1173why, one step back1173 } catch (hookError) {Run `beforeError` for a `beforeRetry` abort and share the body-wrapping checkSindre Sorhusbefore adoption55599c8
lines 1174–1177why, one step back1174 // 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.1175 this.#throwIfAbortedByUser();11761177 // Preserve the original request error path (`throw error`) so beforeError hooks can still run. `isError` rather than `instanceof`, so a cross-realm error is recognised the same way `#throwProcessedError` does.TweaksSindre Sorhusbefore adoption3ded2aa
line 1178why, one step back1178 if (isError(hookError) && hookError !== error) {Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00
line 1179why, one step back1179 this.#beforeRetryHookErrors.add(hookError);Allow `beforeRetry` hooks to return a `Request` or `Response` (#774)Sindre Sorhusbefore adoptiona51bb1e
lines 1180–1181why, one step back1180 }1181Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00
lines 1182–1183why, one step back1182 throw hookError;1183 }Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 1184why, one step back1184RefactorSindre Sorhusbefore adoptiona5ed57b
line 1185why, one step back1185 if (hookResult === timedOut) {TweaksSindre Sorhusbefore adoption3ded2aa
line 1186why, one step back1186 throw new TimeoutError(this.#sentRequest);Harden retrySindre Sorhusbefore adoptionc426f19
lines 1187–1188why, one step back1187 }1188RefactorSindre Sorhusbefore adoptiona5ed57b
line 1189why, one step back1189 if (isRequest(hookResult)) {TweaksSindre Sorhusbefore adoption8f28eac
lines 1190–1191why, one step back1190 // Same contract as `ky.retry({request})`: a Request returned from `beforeRetry`1191 // is used as-is rather than being sanitized or otherwise rewritten by Ky.Fix timeouts and user aborts not cancelling a `Request` returned from `beforeRequest` or `beforeRetry` hooksSindre Sorhusbefore adoptione1b088e
line 1192why, one step back1192 this.#assignRequest(this.#withManagedSignal(hookResult));Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00
line 1193why, one step back1193 break;Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 1194–1195why, one step back1194 }1195RefactorSindre Sorhusbefore adoptiona5ed57b
lines 1196–1197why, one step back1196 if (isResponse(hookResult)) {1197 this.#hookResponses.add(hookResult);Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00
lines 1198–1199why, one step back1198 this.#retryCount++;1199 return hookResult;Fix timeout to apply to total operation including retries (#825)Sindre Sorhusbefore adoptionaac83fa
lines 1200–1201why, one step back1200 }1201Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00
lines 1202–1205why, one step back1202 // If `stop` is returned from the hook, the retry process is stopped1203 if (hookResult === stop) {1204 return;1205 }Let a `beforeRetry` hook change per-attempt optionsSindre Sorhusbefore adoption242c327
lines 1206–1209why, one step back12061207 if (isNonArrayObject(hookResult)) {1208 this.#applyBeforeRetryOptions(hookResult.options);1209 }Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 1210why, one step back1210 }Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00
line 1211why, one step back1211Various tweaksSindre Sorhusbefore adoption0dd9522
line 1212why, one step back1212 this.#throwIfTotalTimeoutExhausted();Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00
lines 1213–1214why, one step back12131214 this.#retryCount++;Simplify request state and retry normalizationSindre Sorhusbefore adoptionb28ba90
line 1215why, one step back1215 return this.#retry();Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 1216–1217why, one step back1216 }1217Code styleSindre Sorhusbefore adoption333afbe
line 1218why, one step back1218 async #fetch(): Promise<Response> {Release the bodies a caller cannot reach and stop sharing search parametersSindre Sorhusbefore adoptionec3d17f
line 1219why, one step back1219 // A previous attempt can return without consuming its upload. Release that unused branch before replacing the request reference.RefactorSindre Sorhusbefore adoptiona5ed57b
line 1220why, one step back1220 cancelBody(this.#originalRequest, this.request);Release the bodies a caller cannot reach and stop sharing search parametersSindre Sorhusbefore adoptionec3d17f
line 1221why, one step back1221Fix hook state leaks and fetch option forwardingSindre Sorhusbefore adoption2df9b7e
line 1222why, one step back1222 const nonRequestOptions = findUnknownOptions(this.#options);Harden retrySindre Sorhusbefore adoptionc426f19
line 1223why, one step back1223 this.#retryLimit = normalizeRetryOptions(this.#options.retry).limit;Fix retry abort propagation and uploads without request stream supportSindre Sorhusbefore adoption6520f64
lines 1224–1225why, one step back1224 // Reattach the managed signal because Node.js can garbage-collect the abort controller used by Request.clone().1225 const retryRequest = this.#retryLimit > 0 ? this.#withManagedSignal(this.request.clone()) : undefined;RefactorSindre Sorhusbefore adoptiona5ed57b
line 1226why, one step back1226 const request = this.#wrapRequestWithUploadProgress(this.request);Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 1227why, one step back1227Skip request cloning when retries are disabled to prevent buffering large streaming bodiesSindre Sorhusbefore adoption6f3d1bd
line 1228why, one step back1228 // Cloning is done here to prepare in advance for retries.Fix typosSindre Sorhusbefore adoptionbbc98fc
line 1229why, one step back1229 // Skip cloning when retries are disabled - cloning a streaming body calls ReadableStream#tee()Skip request cloning when retries are disabled to prevent buffering large streaming bodiesSindre Sorhusbefore adoption6f3d1bd
line 1230why, one step back1230 // which buffers the entire stream in memory, causing excessive memory usage for large uploads.Fix `beforeRequest` hooks being skipped when a `Request` is returned (#832)Sindre Sorhusbefore adoptionaec65db
lines 1231–1233why, one step back1231 this.#originalRequest = request;1232 if (retryRequest) {1233 this.request = retryRequest;Improve docsSindre Sorhusbefore adoption8778439
line 1234why, one step back1234 this.#requestBodyCanBeCancelled = true;Skip request cloning when retries are disabled to prevent buffering large streaming bodiesSindre Sorhusbefore adoption6f3d1bd
line 1235why, one step back1235 }Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 1236why, one step back1236Add `NetworkError` class and tighten retry logic (#842)Sindre Sorhusbefore adoptioneaf0b80
line 1237why, one step back1237 try {Simplify request state and retry normalizationSindre Sorhusbefore adoptionb28ba90
line 1238why, one step back1238 const effectiveTimeout = this.#getEffectiveTimeout();Add `totalTimeout` option and make `timeout` be per retry (#848)Sindre Sorhusbefore adoptionc20d7c7
line 1239why, one step back1239Fix `fetch: window.fetch` throwing "Illegal invocation" in browsersSindre Sorhusbefore adoption92ef60e
lines 1240–1241why, one step back1240 // Called unbound so a native `window.fetch` is not invoked with the options object as `this`, which throws "Illegal invocation" in browsers.1241 const {fetch} = this.#options;Various tweaksSindre Sorhusbefore adoption0dd9522
line 1242why, one step back1242 const response = effectiveTimeout === undefinedFix `fetch: window.fetch` throwing "Illegal invocation" in browsersSindre Sorhusbefore adoption92ef60e
line 1243why, one step back1243 ? await fetch(request, nonRequestOptions)Various tweaksSindre Sorhusbefore adoption0dd9522
lines 1244–1245why, one step back1244 : await timeout(request, nonRequestOptions, this.#abortController, {1245 timeout: effectiveTimeout,Fix `fetch: window.fetch` throwing "Illegal invocation" in browsersSindre Sorhusbefore adoption92ef60e
line 1246why, one step back1246 fetch,Various tweaksSindre Sorhusbefore adoption0dd9522
line 1247why, one step back1247 });Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 1248why, one step back1248TweaksSindre Sorhusbefore adoption3ded2aa
line 1249why, one step back1249 // `undefined` would otherwise look like `ky.stop`, and any other value fails later with an error that does not name the cause.RefactorSindre Sorhusbefore adoptiona5ed57b
line 1250why, one step back1250 if (!isResponse(response)) {TweaksSindre Sorhusbefore adoption3ded2aa
lines 1251–1253why, one step back1251 throw new TypeError('The `fetch` option must resolve with a `Response`');1252 }1253Enforce total timeout after fetch and body processingSindre Sorhusbefore adoption82fa84c
lines 1254–1255why, one step back1254 if (this.#getRemainingTotalTimeout() === 0) {1255 this.#abortController?.abort();RefactorSindre Sorhusbefore adoptiona5ed57b
line 1256why, one step back1256 cancelBody(response);Enforce total timeout after fetch and body processingSindre Sorhusbefore adoption82fa84c
lines 1257–1259why, one step back1257 throw new TimeoutError(request);1258 }1259Various tweaksSindre Sorhusbefore adoption0dd9522
line 1260why, one step back1260 return this.#setResponseRequest(response, request);Add `NetworkError` class and tighten retry logic (#842)Sindre Sorhusbefore adoptioneaf0b80
line 1261why, one step back1261 } catch (error) {Enforce total timeout after fetch and body processingSindre Sorhusbefore adoption82fa84c
lines 1262–1267why, one step back1262 this.#throwIfAbortedByUser();1263 if (this.#getRemainingTotalTimeout() === 0) {1264 this.#abortController?.abort();1265 throw new TimeoutError(request);1266 }1267Add `NetworkError` class and tighten retry logic (#842)Sindre Sorhusbefore adoptioneaf0b80
line 1268why, one step back1268 if (isRawNetworkError(error)) {Release the bodies a caller cannot reach and stop sharing search parametersSindre Sorhusbefore adoptionec3d17f
line 1269why, one step back1269 throw new NetworkError(request, {cause: error as Error});Add `NetworkError` class and tighten retry logic (#842)Sindre Sorhusbefore adoptioneaf0b80
lines 1270–1273why, one step back1270 }12711272 throw error;1273 }Fix a user abort in Chromium being reported as `NetworkError` and retriedSindre Sorhusbefore adoption7c1272b
lines 1274–1278why, one step back1274 }12751276 // Chromium reports a user abort during a fetch or body read as `TypeError: Failed to fetch`, which would otherwise be mistaken for a dropped connection. Surface the abort reason instead, like other runtimes do.1277 #throwIfAbortedByUser(): void {1278 this.#userProvidedAbortSignal?.throwIfAborted();Fix timeout to apply to total operation including retries (#825)Sindre Sorhusbefore adoptionaac83fa
lines 1279–1280why, one step back1279 }1280RefactorSindre Sorhusbefore adoptiona5ed57b
lines 1281–1283why, one step back1281 // `0` once the `totalTimeout` budget is spent, and `Infinity` without a `totalTimeout`.1282 #getRemainingTotalTimeout(): number {1283 return Math.max(0, this.#deadline - getCurrentTime());Let a `beforeRetry` hook change per-attempt optionsSindre Sorhusbefore adoption242c327
lines 1284–1304why, one step back1284 }12851286 // 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 }12911292 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 }12971298 const mergedOptions = {...this.#options, ...options};1299 const updatedOptions = {...mergedOptions, ...withAttemptDefaults(mergedOptions)};1300 validateCallbackOptions(updatedOptions);1301 validateTimeoutOption(updatedOptions.timeout, 'timeout');13021303 Object.assign(this.#options, updatedOptions);1304 this.#cachedNormalizedOptions = undefined;Make `beforeError` hook receive all errors (#829)Sindre Sorhusbefore adoption101c74b
lines 1305–1306why, one step back1305 }1306Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 1307–1308why, one step back1307 #getNormalizedOptions(): NormalizedOptions {1308 if (!this.#cachedNormalizedOptions) {Strip Ky-specific properties from normalized options passed to hooks (#826)Sindre Sorhusbefore adoption433febd
lines 1309–1316why, one step back1309 // Exclude Ky-specific options that are not part of `RequestInit`.1310 const {1311 hooks,1312 json,1313 parseJson,1314 stringifyJson,1315 searchParams,1316 timeout,Add `totalTimeout` option and make `timeout` be per retry (#848)Sindre Sorhusbefore adoptionc20d7c7
line 1317why, one step back1317 totalTimeout,Add `maxResponseSize` optionSindre Sorhusbefore adoption0d59458
line 1318why, one step back1318 maxResponseSize,Strip Ky-specific properties from normalized options passed to hooks (#826)Sindre Sorhusbefore adoption433febd
lines 1319–1323why, one step back1319 throwHttpErrors,1320 fetch,1321 ...normalizedOptions1322 } = this.#options;1323Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 1324–1327why, one step back1324 this.#cachedNormalizedOptions = Object.freeze(normalizedOptions) as NormalizedOptions;1325 }13261327 return this.#cachedNormalizedOptions;Add `ky.retry()` to force retries from `afterResponse` hooks (#779)Sindre Sorhusbefore adoption68a5228
lines 1328–1329why, one step back1328 }1329Improve docsSindre Sorhusbefore adoption8778439
lines 1330–1331why, one step back1330 #assignRequest(request: Request, requestBodyCanBeCancelled = false): void {1331 // Runtime-derived bodies such as `FormData` may still be serialized after a hook constructs a replacement Request, so only caller-provided streams and Ky's own prepared retry clones are safe to cancel here.RefactorSindre Sorhusbefore adoptiona5ed57b
lines 1332–1333why, one step back1332 if (this.#requestBodyCanBeCancelled) {1333 cancelBody(this.request, request);Release the bodies a caller cannot reach and stop sharing search parametersSindre Sorhusbefore adoptionec3d17f
lines 1334–1335why, one step back1334 }1335Add `ky.retry()` to force retries from `afterResponse` hooks (#779)Sindre Sorhusbefore adoption68a5228
line 1336why, one step back1336 this.#cachedNormalizedOptions = undefined;Fix `beforeRequest` hooks being skipped when a `Request` is returned (#832)Sindre Sorhusbefore adoptionaec65db
line 1337why, one step back1337 this.request = request;Improve docsSindre Sorhusbefore adoption8778439
line 1338why, one step back1338 this.#requestBodyCanBeCancelled = requestBodyCanBeCancelled;Fix timeouts and user aborts not cancelling a `Request` returned from `beforeRequest` or `beforeRetry` hooksSindre Sorhusbefore adoptione1b088e
lines 1339–1340why, one step back1339 }1340Fix headers set to `undefined` not removing the header from a `Request` inputSindre Sorhusbefore adoptiond5bacef
line 1341why, one step back1341 // A replacement `Request` from a hook or `ky.retry({request})` carries its own signal, so re-attach Ky's managed signal to keep timeouts and user aborts working. Request-like objects are used as-is since the `Request` constructor cannot copy them, so they keep whatever signal they carry, even on a retry after a timeout.Fix timeouts and user aborts not cancelling a `Request` returned from `beforeRequest` or `beforeRetry` hooksSindre Sorhusbefore adoptione1b088e
lines 1342–1346why, one step back1342 #withManagedSignal(request: Request): Request {1343 if (!this.#options.signal || !(request instanceof globalThis.Request)) {1344 return request;1345 }1346Fix retry abort propagation and uploads without request stream supportSindre Sorhusbefore adoption6520f64
lines 1347–1351why, one step back1347 return new globalThis.Request(request, {1348 signal: this.#options.signal,1349 referrer: request.referrer,1350 referrerPolicy: request.referrerPolicy,1351 });Various tweaksSindre Sorhusbefore adoption0dd9522
lines 1352–1353why, one step back1352 }1353Report the sent request for a hook's response, and finish the cross-realm and `null` checksSindre Sorhusbefore adoption7f0137d
line 1354why, one step back1354 // 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.Various tweaksSindre Sorhusbefore adoption0dd9522
line 1355why, one step back1355 #getResponseRequest(response: Response): Request {Report the sent request for a hook's response, and finish the cross-realm and `null` checksSindre Sorhusbefore adoption7f0137d
line 1356why, one step back1356 return this.#responseRequests.get(response) ?? this.#sentRequest;Various tweaksSindre Sorhusbefore adoption0dd9522
lines 1357–1359why, one step back1357 }13581359 #setResponseRequest(response: Response, request: Request): Response {Restore the retry-only marker condition and cover the remaining casesSindre Sorhusbefore adoption692c435
line 1360why, one step back1360 this.#responseRequests.set(response, request);Various tweaksSindre Sorhusbefore adoption0dd9522
line 1361why, one step back1361 return response;Add `maxResponseSize` optionSindre Sorhusbefore adoption0d59458
lines 1362–1366why, one step back1362 }13631364 #limitResponseSize(response: Response): Response {1365 const request = this.#getResponseRequest(response);1366 return this.#setResponseRequest(limitResponseSize(response, request, this.#options.maxResponseSize), request);Add `ky.retry()` to force retries from `afterResponse` hooks (#779)Sindre Sorhusbefore adoption68a5228
lines 1367–1368why, one step back1367 }1368RefactorSindre Sorhusbefore adoptiona5ed57b
line 1369why, one step back1369 #wrapRequestWithUploadProgress(request: Request): Request {Fix retry abort propagation and uploads without request stream supportSindre Sorhusbefore adoption6520f64
line 1370why, one step back1370 if (!this.#options.onUploadProgress || !supportsRequestStreams || !request.body) {Add `ky.retry()` to force retries from `afterResponse` hooks (#779)Sindre Sorhusbefore adoption68a5228
lines 1371–1373why, one step back1371 return request;1372 }1373RefactorSindre Sorhusbefore adoptiona5ed57b
line 1374why, one step back1374 return streamRequest(request, this.#options.onUploadProgress, this.#options.body);Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 1375–1376why, one step back1375 }1376}