Refactor
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Sindre Sorhus · committed by Sindre Sorhus · parent 7f0137d · Browse files · 33 files·+4769 added−659 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
33 files+4769 added−659 removed
- tests:+4241 added−7 removed
- other:+528 added−652 removed
Provenance
- Commit
a5ed57b- Tree
244cf12- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
Sindre Sorhus <sindresorhus@gmail.com>- Parent
7f0137d
33 files changed+4769 added−659 removed
modified:source/core/constants.ts+6 added-1 removed
52 unmodified lines53 // We still feature-check at runtime before exposing the shortcut.54 bytes: '*/*',55 } as const;56 57+// Only expose `.bytes()` when the environment implements it. Checked on each call, so a polyfill added after Ky is imported still counts.58+export const getSupportedResponseTypes = (): Array<keyof typeof responseTypes> =>59+ (Object.keys(responseTypes) as Array<keyof typeof responseTypes>).filter(type =>60+ type !== 'bytes' || typeof (globalThis.Response?.prototype as unknown as {bytes?: unknown})?.bytes === 'function');61+62 // The maximum value of a 32bit int (see issue #117)63 export const maxSafeTimeout = 2_147_483_647;64 65 // Size in bytes of a typical form boundary (e.g., '------WebKitFormBoundaryaxpyiPgbbPti10Rw'), used to help estimate upload size. Bun's boundary is 54 bytes, so there the estimate runs 14 bytes low for each part and once more for the closing boundary. That is negligible next to a file, but for a body of many small fields `percent` can reach its ceiling before the upload ends. The final event always reports the real total.56 unmodified lines122 123 /**124 Custom request to use for the retry.125 121- This allows you to modify or completely replace the request during a forced retry. The custom request becomes the starting point for the retry - `beforeRetry` hooks can still further modify it if needed.126+ This allows you to modify or completely replace the request during a forced retry. The custom request becomes the starting point for the retry - `beforeRetry` hooks can still further modify it if needed. Anything other than a `Request` or `undefined` makes the request throw a `TypeError`.127 128 **Note:** The custom request's `signal` will be replaced with Ky's managed signal to handle timeouts and user-provided abort signals correctly. If the original request body has been consumed, you must provide a new body or clone the request before consuming.129 130 **Warning:** Custom retry requests are not sanitized. If you reuse headers across origins, remove any credentials you do not want forwarded.174 unmodified linesmodified:source/core/Ky.ts+391 added-532 removed
13 unmodified lines14 SearchParamsOption,15 } from '../types/options.js';16 import {type ResponsePromise} from '../types/ResponsePromise.js';17 import type {StandardSchemaV1} from '../types/standard-schema.js';18-import {limitResponseSize, streamRequest, streamResponse} from '../utils/body.js';18 import {20- cloneShallow,19+ cancelBody,20+ limitResponseSize,21+ streamRequest,22+ streamResponse,23+} from '../utils/body.js';24+import {25 cloneDeep,26+ cloneSearchParameters,27 mergeHeaders,28 mergeHeaderContainers,29 mergeHooks,30 deletedParametersSymbol,31+ type MarkedSearchParameters,32 } from '../utils/merge.js';27-import type {RetryOptions} from '../types/retry.js';33 import {normalizeRequestMethod, normalizeRetryMethod, normalizeRetryOptions} from '../utils/normalize.js';34 import timeout from '../utils/timeout.js';35 import delay from '../utils/delay.js';31-import {type ObjectEntries} from '../utils/types.js';36 import {findUnknownOptions, hasSearchParameters} from '../utils/options.js';37 import isRawNetworkError from '../utils/is-network-error.js';34-import {isError, isObject} from '../utils/is.js';38 import {39+ isError, isNonArrayObject, isNonNegativeNumber, isObject, isRequest, isResponse,40+} from '../utils/is.js';41+import {42 isHTTPError, isNetworkError, isTimeoutError, isResponseSizeError, isForceRetryError,43 } from '../utils/type-guards.js';44 import {45 calculateRetryTimingDelay,1 unmodified line47 } from './retry-timing.js';48 import {49 maxSafeTimeout,50 responseTypes,51+ getSupportedResponseTypes,52 stop,53 isRetryMarker,54 supportsAbortController,55 supportsAbortSignal,3 unmodified lines59 } from './constants.js';60 61 const maxErrorResponseBodySize = 10 * 1024 * 1024;62 const 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';56-const timedOutResponseData = Symbol('timedOutResponseData');57-const timedOutOperation = Symbol('timedOutOperation');63+const timedOut = Symbol('timedOut');64 65+const getCurrentTime = (): number => globalThis.performance?.now() ?? Date.now();66+67+// Settles like `promise`, or resolves with `timedOut` once `milliseconds` pass first. The timer is cleared as soon as `promise` settles.68+// eslint-disable-next-line @typescript-eslint/promise-function-async69+const raceWithTimeout = <T>(promise: Promise<T>, milliseconds: number): Promise<T | typeof timedOut> => Promise.race([70+ promise,71+ new Promise<typeof timedOut>(resolve => {72+ const timeoutId = setTimeout(() => {73+ resolve(timedOut);74+ }, milliseconds);75+ void promise.finally(() => {76+ clearTimeout(timeoutId);77+ }).catch(() => undefined);78+ }),79+]);80+81+// Only a returned request or response has a body to release.82+const cancelReturnedBody = (value: unknown): void => {83+ if (isResponse(value) || isRequest(value)) {84+ cancelBody(value);85+ }86+};87+88+// 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.89+const releaseWhenSettled = (operationPromise: Promise<unknown>): void => {90+ void operationPromise.then(value => {91+ cancelReturnedBody(value);92+ }).catch(() => undefined);93+};94+95 type ErrorDataTimeout = {96 milliseconds: number;97 fromTotalTimeout: boolean;98 };9 unmodified lines108 109 return new TextDecoder();110 };111 112+const isJsonContentType = (contentType: string): boolean => {113+ // Match JSON subtypes like `json`, `problem+json`, and `vnd.api+json`.114+ // 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.115+ const mimeType = (contentType.split(';', 1)[0] ?? '').trim().toLowerCase();116+117+ if (!mimeType.endsWith('json')) {118+ return false;119+ }120+121+ const separator = mimeType.at(-5);122+ if (separator === '/') {123+ return true;124+ }125+126+ if (separator !== '.' && separator !== '+' && separator !== '-') {127+ return false;128+ }129+130+ // The separator is not the slash, so any slash in the type comes before it.131+ return mimeType.includes('/');132+};133+134+// 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`.135+const readResponseText = async (response: Response, milliseconds: number): Promise<string | typeof timedOut | undefined> => {136+ const {body} = response;137+ if (!body) {138+ try {139+ return await response.text();140+ } catch {141+ return undefined;142+ }143+ }144+145+ let reader: ReadableStreamDefaultReader<Uint8Array>;146+ try {147+ reader = body.getReader();148+ } catch {149+ // Another consumer already locked the stream.150+ return undefined;151+ }152+153+ const contentType = response.headers.get('content-type') ?? '';154+ // JSON uses UTF-8 regardless of the charset parameter (RFC 8259).155+ const decoder = isJsonContentType(contentType) ? new TextDecoder() : createTextDecoder(contentType);156+ const chunks: string[] = [];157+ let totalBytes = 0;158+159+ const readAll = (async (): Promise<string | undefined> => {160+ try {161+ for (;;) {162+ // eslint-disable-next-line no-await-in-loop163+ const {done, value} = await reader.read();164+ if (done) {165+ break;166+ }167+168+ totalBytes += value.byteLength;169+ if (totalBytes > maxErrorResponseBodySize) {170+ void reader.cancel().catch(() => undefined);171+ return undefined;172+ }173+174+ chunks.push(decoder.decode(value, {stream: true}));175+ }176+ } catch (error) {177+ if (isResponseSizeError(error)) {178+ throw error;179+ }180+181+ return undefined;182+ }183+184+ chunks.push(decoder.decode());185+ return chunks.join('');186+ })();187+188+ const result = await raceWithTimeout(readAll, milliseconds);189+ if (result === timedOut) {190+ void reader.cancel().catch(() => undefined);191+ }192+193+ return result;194+};195+196 const invalidSchemaMessage = 'The `schema` argument must follow the Standard Schema specification';197 const missingResponseMessage = 'The request resolved without a response, so there is no body to read.'198 + ' This happens when a `beforeRetry` hook returns `ky.stop`. Throw from the hook instead of returning `ky.stop`.';199 2 unmodified lines202 if (value === false) {203 return;204 }205 86- if (typeof value !== 'number' || Number.isNaN(value) || value < 0) {206+ if (!isNonNegativeNumber(value)) {207 throw new TypeError(`The \`${name}\` option must be a non-negative number or \`false\``);208 }209 210 // `Infinity` lands here too, since it is not a usable delay either.15 unmodified lines226 throw new TypeError('The `throwHttpErrors` option must be a boolean or a function');227 }228 };229 110-const cloneRetryOptions = (retry: RetryOptions | number): RetryOptions | number => {111- if (retry === null || typeof retry !== 'object' || Array.isArray(retry)) {112- return retry as RetryOptions | number;113- }230+const leadingC0ControlOrSpacePattern = /^[\0-\u0020]+/g;231+const asciiTabOrNewLinePattern = /[\t\n\r]/g;232+const schemePattern = /^[a-z][\d+.a-z-]*:/i;233+const malformedHttpProtocolPattern = /^https?:(?!\/\/)/i;234 115- const clonedRetry = {...retry};235+const isAbsoluteInput = (input: string): boolean =>236+ schemePattern.test(input);237 117- // Clone nested arrays too so init hooks can mutate retry config without leaking state across requests.118- if (Array.isArray(clonedRetry.methods)) {119- clonedRetry.methods = [...clonedRetry.methods];120- }238+const normalizeInputForProtocolCheck = (input: string): string =>239+ input.replaceAll(leadingC0ControlOrSpacePattern, '').replaceAll(asciiTabOrNewLinePattern, '');240 122- if (Array.isArray(clonedRetry.statusCodes)) {123- clonedRetry.statusCodes = [...clonedRetry.statusCodes];241+// Joins a string input to `prefix`, then resolves it against `baseUrl`. A `URL` or `Request` input is used as-is.242+const resolveInput = (input: Input, prefix: string, baseUrl: Options['baseUrl']): Input => {243+ if (typeof input !== 'string') {244+ return input;245 }246 126- if (Array.isArray(clonedRetry.afterStatusCodes)) {127- clonedRetry.afterStatusCodes = [...clonedRetry.afterStatusCodes];247+ if (prefix) {248+ const normalizedPrefix = prefix.replace(/\/+$/, '');249+ const normalizedInput = input.replace(/^\/+/, '');250+ input = `${normalizedPrefix}/${normalizedInput}`;251 }252 130- return clonedRetry;131-};253+ if (baseUrl) {254+ const normalizedInput = normalizeInputForProtocolCheck(input);255 133-const objectToString = Object.prototype.toString;134-const leadingC0ControlOrSpacePattern = /^[\0-\u0020]+/g;135-const asciiTabOrNewLinePattern = /[\t\n\r]/g;136-const schemePattern = /^[a-z][\d+.a-z-]*:/i;137-const malformedHttpProtocolPattern = /^https?:(?!\/\/)/i;256+ if (malformedHttpProtocolPattern.test(normalizedInput)) {257+ throw new TypeError('`input` url protocol must be followed by `//` when using `baseUrl`');258+ }259 139-const isRequestInstance = (value: unknown): value is Request =>140- value instanceof globalThis.Request || objectToString.call(value) === '[object Request]';260+ if (!isAbsoluteInput(normalizedInput)) {261+ return new URL(input, (new Request(baseUrl)).url);262+ }263+ }264 142-// Accepted custom responses are treated as full Responses throughout Ky.143-// If a custom fetch returns one, it must behave like a Response for cloning,144-// body consumption, `json()` decoration, and any enabled stream features.145-const isResponseInstance = (value: unknown): value is Response =>146- value instanceof globalThis.Response || objectToString.call(value) === '[object Response]';265+ return input;266+};267 148-const isAbsoluteInput = (input: string): boolean =>149- schemePattern.test(input);268+// `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 `+`.269+const deleteSearchParameter = (url: URL, key: string): void => {270+ if (url.searchParams.has(key)) {271+ url.searchParams.delete(key);272+ }273+};274 151-const normalizeInputForProtocolCheck = (input: string): string =>152- input.replaceAll(leadingC0ControlOrSpacePattern, '').replaceAll(asciiTabOrNewLinePattern, '');275+// Adds the `searchParams` option to the search parameters already in `url`.276+const applySearchParameters = (url: URL, searchParameters: SearchParamsOption): void => {277+ const deleted = (searchParameters as MarkedSearchParameters | undefined)?.[deletedParametersSymbol];278 154-const cloneSearchParametersForInitHook = (searchParameters: SearchParamsOption | undefined): SearchParamsOption | undefined => {155- if (Array.isArray(searchParameters)) {156- return searchParameters.map(parameter => [...parameter]) as SearchParamsOption;279+ if (deleted) {280+ // Remove keys from the input URL first so later searchParams entries can intentionally re-add them.281+ for (const key of deleted) {282+ deleteSearchParameter(url, key);283+ }284 }285 159- return cloneShallow(searchParameters) as SearchParamsOption | undefined;286+ if (typeof searchParameters === 'string') {287+ const stringSearchParameters = searchParameters.replace(/^\?/, '');288+ if (stringSearchParameters !== '') {289+ url.search = url.search ? `${url.search}&${stringSearchParameters}` : `?${stringSearchParameters}`;290+ }291+ } else if (isNonArrayObject(searchParameters) && !(searchParameters instanceof URLSearchParams)) {292+ // Filter out undefined values from plain objects. An `undefined` value removes the key from the input URL instead.293+ for (const [key, value] of Object.entries(searchParameters)) {294+ if (value === undefined) {295+ deleteSearchParameter(url, key);296+ } else {297+ url.searchParams.append(key, value as string);298+ }299+ }300+ } else {301+ for (const [key, value] of new URLSearchParams(searchParameters as SearchParamsInit)) {302+ url.searchParams.append(key, value);303+ }304+ }305 };306 307 // 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.308 function cloneInitHookOptions(options: Options): InitOptions {4 unmodified lines313 // `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`.314 context: {...options.context},315 // Deep-clone so init-hook mutations to nested values do not leak across requests, matching the nested `retry` cloning below.316 json: cloneDeep(options.json),172- searchParams: cloneSearchParametersForInitHook(options.searchParams),317+ searchParams: cloneSearchParameters(options.searchParams),318+ // Clone nested arrays too so init hooks can mutate retry config without leaking state across requests.319+ retry: cloneDeep(options.retry),320 };321 175- if (options.retry !== undefined) {176- clonedOptions.retry = cloneRetryOptions(options.retry);177- }178-322 return clonedOptions as InitOptions;323 }324 325 const validateJsonWithSchema = async (jsonValue: unknown, schema: StandardSchemaV1): Promise<unknown> => {183- if (184- (185- typeof schema !== 'object'186- && typeof schema !== 'function'187- )188- || schema === null189- ) {190- throw new TypeError(invalidSchemaMessage);191- }326+ const standardSchema = isObject(schema) || typeof schema === 'function' ? schema['~standard'] : undefined;327 193- const standardSchema = schema['~standard'];194-328 if (196- typeof standardSchema !== 'object'197- || standardSchema === null329+ !isObject(standardSchema)330 || typeof standardSchema.validate !== 'function'331 ) {332 throw new TypeError(invalidSchemaMessage);333 }17 unmodified lines351 }352 353 const ky = new Ky(input, initHookOptions);354 223- const function_ = async (): Promise<Response | void> => {224- // Delay the fetch so that body method shortcuts can set the Accept header225- await Promise.resolve();226- const beforeRequestResponse = await ky.#runBeforeRequestHooks();227- if (beforeRequestResponse !== undefined) {228- ky.#retryLimit = normalizeRetryOptions(ky.#options.retry).limit;229- }230-231- let response = beforeRequestResponse ?? await ky.#retry();232- let responseFromHook = beforeRequestResponse !== undefined233- || ky.#consumeReturnedResponseFromBeforeRetryHook();234-235- for (;;) {236- // `undefined` means a hook stopped the flow.237- if (response === undefined) {238- return response;239- }240-241- try {242- // eslint-disable-next-line no-await-in-loop243- response = await ky.#runAfterResponseHooks(response);244- } catch (error) {245- if (!isForceRetryError(error)) {246- throw error;247- }248-249- // eslint-disable-next-line no-await-in-loop250- const retriedResponse: Response | void = await ky.#retryFromError(error);251- if (retriedResponse === undefined) {252- return retriedResponse;253- }254-255- response = retriedResponse;256- responseFromHook = ky.#consumeReturnedResponseFromBeforeRetryHook();257- continue;258- }259-260- const currentResponse: Response = response;261-262- // 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.263- if (!currentResponse.ok && currentResponse.type !== 'opaque' && ky.#shouldThrowHttpErrors(currentResponse)) {264- // `request` must reflect the request that actually failed, but `options` stays as Ky's265- // normalized options snapshot. Replacement `Request` instances do not preserve the266- // original `BodyInit`, so trying to make `options` mirror arbitrary requests would be lossy.267- const httpError: HTTPError = new HTTPError(currentResponse, ky.#getResponseRequest(currentResponse), ky.#getNormalizedOptions());268- // eslint-disable-next-line no-await-in-loop269- httpError.data = await ky.#getResponseData(currentResponse);270- ky.#throwIfAbortedByUser();271- ky.#throwIfTotalTimeoutExhausted();272-273- if (responseFromHook) {274- throw httpError;275- }276-277- // eslint-disable-next-line no-await-in-loop278- const retriedResponse: Response | void = await ky.#retryFromError(httpError);279- if (retriedResponse === undefined) {280- return retriedResponse;281- }282-283- response = retriedResponse;284- responseFromHook = ky.#consumeReturnedResponseFromBeforeRetryHook();285- continue;286- }287-288- break;289- }290-291- ky.#decorateResponse(response);292-293- // If `onDownloadProgress` is passed, it uses the stream API internally294- if (ky.#options.onDownloadProgress) {295- if (!supportsResponseStreams) {296- throw new Error('Streams are not supported in your environment. `ReadableStream` is missing.');297- }298-299- const progressResponse = streamResponse(response, ky.#options.onDownloadProgress);300- ky.#setResponseRequest(progressResponse, ky.#getResponseRequest(response));301- return ky.#decorateResponse(progressResponse);302- }303-304- return response;305- };306-355 const result = (async () => {356 let response: Response | undefined;357 try {310- response = (await function_()) ?? undefined;358+ response = await ky.#run();359 return response;360 } catch (error: unknown) {361 return await ky.#throwProcessedError(error);362 } finally {363 const originalRequest = ky.#originalRequest;364 365 // Ignore cancellation errors from already-locked or already-consumed streams.366 // A custom fetch or hook can return the request body as its response body; ownership then belongs to the caller.319- if (originalRequest?.body !== response?.body) {320- ky.#cancelBody(originalRequest?.body ?? undefined);321- }367+ cancelBody(originalRequest, response);368 369 // 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.324- if (originalRequest && ky.request !== originalRequest && ky.request.body !== response?.body) {325- ky.#cancelBody(ky.request.body ?? undefined);370+ if (originalRequest && ky.request !== originalRequest) {371+ cancelBody(ky.request, response);372 }373 }374 })() as ResponsePromise;375 330- for (const [type, mimeType] of Object.entries(responseTypes) as ObjectEntries<typeof responseTypes>) {331- // Only expose `.bytes()` when the environment implements it.332- if (333- type === 'bytes'334- && typeof (globalThis.Response?.prototype as unknown as {bytes?: unknown})?.bytes !== 'function'335- ) {336- continue;337- }338-376+ // Only expose `.bytes()` when the environment implements it.377+ for (const type of getSupportedResponseTypes()) {378+ const mimeType = responseTypes[type];379 result[type] = async (schema?: StandardSchemaV1) => {380 // 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.381 if (ky.request !== ky.#originalRequest) {382 // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing16 unmodified lines399 // 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.400 let parsedResult: any;401 try {402 parsedResult = await ky.#raceWithTotalTimeout(async () => {363- const jsonValue = initHookOptions.parseJson364- ? await initHookOptions.parseJson(text, {request, response})365- : (text === '' && schema !== undefined366- ? undefined367- : JSON.parse(text));403+ const jsonValue = text === '' && schema !== undefined && !ky.#options.parseJson404+ ? undefined405+ : await ky.#parseJson(text, request, response);406 407 if (schema === undefined) {408 return jsonValue;409 }410 411 // eslint-disable-next-line no-return-await, @typescript-eslint/return-await -- Awaiting here preserves the caller's async stack when schema validation fails.412 return await validateJsonWithSchema(jsonValue, schema);375- }, ky.#userProvidedAbortSignal);413+ });414 } catch (error: unknown) {415 // 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.416 if (ky.#userProvidedAbortSignal?.aborted) {417 await ky.#throwProcessedError(ky.#userProvidedAbortSignal.reason, request);1 unmodified line419 420 throw error;421 }422 385- if (parsedResult === timedOutOperation) {423+ if (parsedResult === timedOut) {424 await ky.#throwProcessedError(new TimeoutError(request), request);425 }426 427 return parsedResult;2 unmodified lines430 431 return result;432 }433 396- // eslint-disable-next-line unicorn/prevent-abbreviations397- static #normalizeSearchParams(searchParams: SearchParamsOption): SearchParamsOption {398- // Filter out undefined values from plain objects399- if (searchParams && typeof searchParams === 'object' && !Array.isArray(searchParams) && !(searchParams instanceof URLSearchParams)) {400- return Object.fromEntries(Object.entries(searchParams).filter(([, value]) => value !== undefined));401- }402-403- return searchParams;404- }405-434 public request: Request;435 #abortController?: AbortController;436 #retryCount = 0;437 #retryLimit: number;4 unmodified lines442 #requestBodyCanBeCancelled = false;443 readonly #userProvidedAbortSignal: AbortSignal | undefined;444 readonly #beforeRetryHookErrors = new WeakSet<Error>();445 #cachedNormalizedOptions: NormalizedOptions | undefined;418- readonly #startTime: number | undefined;419- #returnedResponseFromBeforeRetryHook = false;446+ // When the `totalTimeout` budget runs out, or `Infinity` without a `totalTimeout`.447+ readonly #deadline: number;448+ // Responses returned by a `beforeRequest` or `beforeRetry` hook. They are used as-is, so a failing status throws instead of being retried.449+ readonly #hookResponses = new WeakSet<Response>();450 readonly #responseRequests = new WeakMap<Response, Request>();451 readonly #decoratedResponses = new WeakSet<Response>();452 453 // eslint-disable-next-line complexity21 unmodified lines475 throw new TypeError(`The \`${key}\` option must not be \`null\`. Use \`undefined\` to clear it.`);476 }477 }478 449- if (options.context !== undefined && (!isObject(options.context) || Array.isArray(options.context))) {479+ if (options.context !== undefined && !isNonArrayObject(options.context)) {480 throw new TypeError('The `context` option must be an object');481 }482 483 this.#options = {24 unmodified lines508 }509 510 this.#requestInput = input instanceof globalThis.Request ? input : undefined;511 482- if (typeof input === 'string') {483- if (this.#options.prefix) {484- const normalizedPrefix = this.#options.prefix.replace(/\/+$/, '');485- const normalizedInput = input.replace(/^\/+/, '');486- input = `${normalizedPrefix}/${normalizedInput}`;487- }512+ input = resolveInput(input, this.#options.prefix, this.#options.baseUrl);513 489- if (this.#options.baseUrl) {490- const normalizedInput = normalizeInputForProtocolCheck(input);491-492- if (malformedHttpProtocolPattern.test(normalizedInput)) {493- throw new TypeError('`input` url protocol must be followed by `//` when using `baseUrl`');494- }495-496- if (!isAbsoluteInput(normalizedInput)) {497- input = new URL(input, (new Request(this.#options.baseUrl)).url);498- }499- }500- }501-514 if (supportsAbortController && supportsAbortSignal) {515 this.#userProvidedAbortSignal = this.#options.signal ?? this.#requestInput?.signal;516 this.#abortController = new globalThis.AbortController();517 this.#options.signal = this.#createManagedSignal();26 unmodified lines544 545 this.request = new globalThis.Request(input, this.#options as RequestInit);546 this.#requestBodyCanBeCancelled = typeof globalThis.ReadableStream === 'function' && this.#options.body instanceof globalThis.ReadableStream;547 548+ const {searchParams} = this.#options;536- if (hasSearchParameters(this.#options.searchParams)) {549+ if (hasSearchParameters(searchParams)) {550 const url = new URL(this.request.url);538- const deleted = (this.#options.searchParams as any)?.[deletedParametersSymbol] as Set<string> | undefined;551+ applySearchParameters(url, searchParams);552 540- if (deleted) {541- // Remove keys from the input URL first so later searchParams entries can intentionally re-add them.542- for (const key of deleted) {543- url.searchParams.delete(key);544- }545- }546-547- if (typeof this.#options.searchParams === 'string') {548- const stringSearchParameters = this.#options.searchParams.replace(/^\?/, '');549- if (stringSearchParameters !== '') {550- url.search = url.search ? `${url.search}&${stringSearchParameters}` : `?${stringSearchParameters}`;551- }552- } else {553- const optionsSearchParameters = new URLSearchParams(Ky.#normalizeSearchParams(this.#options.searchParams) as unknown as SearchParamsInit);554-555- for (const [key, value] of optionsSearchParameters.entries()) {556- url.searchParams.append(key, value);557- }558- }559-560- if (561- this.#options.searchParams562- && typeof this.#options.searchParams === 'object'563- && !Array.isArray(this.#options.searchParams)564- && !(this.#options.searchParams instanceof URLSearchParams)565- ) {566- for (const [key, value] of Object.entries(this.#options.searchParams)) {567- if (value === undefined) {568- url.searchParams.delete(key);569- }570- }571- }572-553 // Recreate request with the updated URL. We already have all options in this.#options, including duplex.554 // Rebuilding is also what drops an inherited `Request` body, so it is skipped when the search parameters leave the URL unchanged.555 if (url.href !== this.request.url) {556 // 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.27 unmodified lines584 }585 586 // `totalTimeout` starts when the request pipeline is created, so it also includes587 // Ky's internal scheduling and user hook time before the first fetch attempt.608- this.#startTime = typeof this.#options.totalTimeout === 'number' ? this.#getCurrentTime() : undefined;588+ this.#deadline = typeof totalTimeout === 'number' ? getCurrentTime() + totalTimeout : Number.POSITIVE_INFINITY;589 }590 591+ async #run(): Promise<Response | undefined> {592+ // Delay the fetch so that body method shortcuts can set the Accept header593+ await Promise.resolve();594+ const beforeRequestResponse = await this.#runBeforeRequestHooks();595+ if (beforeRequestResponse !== undefined) {596+ this.#retryLimit = normalizeRetryOptions(this.#options.retry).limit;597+ }598+599+ let response = beforeRequestResponse ?? await this.#retry();600+601+ for (;;) {602+ // `undefined` means a hook stopped the flow.603+ if (response === undefined) {604+ return undefined;605+ }606+607+ // Read before the `afterResponse` hooks run, since they can replace the response.608+ const responseFromHook = this.#hookResponses.has(response);609+610+ let retryError: Error | undefined;611+ try {612+ // eslint-disable-next-line no-await-in-loop613+ response = await this.#runAfterResponseHooks(response);614+ } catch (error) {615+ if (!isForceRetryError(error)) {616+ throw error;617+ }618+619+ retryError = error;620+ }621+622+ if (retryError === undefined) {623+ const currentResponse: Response = response;624+625+ // 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.626+ if (currentResponse.ok || currentResponse.type === 'opaque' || !this.#shouldThrowHttpErrors(currentResponse)) {627+ break;628+ }629+630+ // `request` must reflect the request that actually failed, but `options` stays as Ky's631+ // normalized options snapshot. Replacement `Request` instances do not preserve the632+ // original `BodyInit`, so trying to make `options` mirror arbitrary requests would be lossy.633+ const httpError: HTTPError = new HTTPError(currentResponse, this.#getResponseRequest(currentResponse), this.#getNormalizedOptions());634+ // eslint-disable-next-line no-await-in-loop635+ httpError.data = await this.#getResponseData(currentResponse);636+ this.#throwIfAbortedByUser();637+ this.#throwIfTotalTimeoutExhausted();638+639+ if (responseFromHook) {640+ throw httpError;641+ }642+643+ retryError = httpError;644+ }645+646+ // eslint-disable-next-line no-await-in-loop647+ response = await this.#retryFromError(retryError);648+ }649+650+ this.#decorateResponse(response);651+652+ // If `onDownloadProgress` is passed, it uses the stream API internally653+ if (this.#options.onDownloadProgress) {654+ if (!supportsResponseStreams) {655+ throw new Error('Streams are not supported in your environment. `ReadableStream` is missing.');656+ }657+658+ const progressResponse = streamResponse(response, this.#options.onDownloadProgress);659+ this.#setResponseRequest(progressResponse, this.#getResponseRequest(response));660+ return this.#decorateResponse(progressResponse);661+ }662+663+ return response;664+ }665+666 #calculateDelay(retry: InternalOptions['retry'], error: unknown): number {667 const retryDelay = retry.delay(this.#retryCount + 1);668 669 // 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.615- if (typeof retryDelay !== 'number' || Number.isNaN(retryDelay) || retryDelay < 0) {670+ if (!isNonNegativeNumber(retryDelay)) {671 // 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.672 throw new TypeError('`retry.delay` must return a non-negative number or `Infinity`', {cause: error});673 }674 16 unmodified lines691 if (this.#retryCount >= Math.min(retry.limit, this.#retryLimit)) {692 throw error;693 }694 640- // Wrap non-Error throws to ensure consistent error handling. `isError` rather than `instanceof`, so a cross-realm error reaches `shouldRetry` as itself, the same way it reaches `beforeError`.641- const errorObject = isError(error) ? error : new NonError(error);695+ // 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`.696+ const errorObject = NonError.wrap(error);697 698 // Handle forced retry from afterResponse hook - skip method check and shouldRetry699 if (isForceRetryError(errorObject)) {700 return errorObject.customDelay ?? this.#calculateDelay(retry, error);6 unmodified lines707 708 let shouldRetryOverride = false;709 const {shouldRetry} = retry;710 if (shouldRetry !== undefined) {656- const result = await this.#raceWithTotalTimeout(async () => shouldRetry({error: errorObject, retryCount: this.#retryCount + 1}), this.#userProvidedAbortSignal);711+ const result = await this.#raceWithTotalTimeout(async () => shouldRetry({error: errorObject, retryCount: this.#retryCount + 1}));712 this.#throwIfAbortedByUser();658- if (result === timedOutOperation) {713+ if (result === timedOut) {714 throw new TimeoutError(this.#sentRequest);715 }716 717 // Only exact booleans override the default retry checks.52 unmodified lines770 771 this.#decoratedResponses.add(response);772 const request = this.#getResponseRequest(response);773 719- response.json = async () => {720- const text = await response.text();721- return this.#options.parseJson!(text, {request, response});722- };774+ response.json = async () => this.#parseJson(await response.text(), request, response);775 776 // `clone()` returns a fresh `Response` that would otherwise fall back to the native `json()`.777 const nativeClone = response.clone.bind(response);778 response.clone = () => this.#decorateResponse(this.#setResponseRequest(nativeClone(), request));36 unmodified lines815 async #getResponseData(response: Response): Promise<unknown> {816 // `request` is the request that actually produced this response, which is not `this.request` once a retry clone has been prepared.817 const request = this.#getResponseRequest(response);818 767- // Even with request timeouts disabled, bound error-body reads so retries and error propagation768- // cannot be stalled indefinitely by never-ending response streams.769- const readTimeout = this.#getErrorDataTimeout(request);770- const text = await this.#readResponseText(response, readTimeout.milliseconds);771- if (text === timedOutResponseData) {772- if (readTimeout.fromTotalTimeout) {819+ // A timed-out read or parse gives up on the data, but an exhausted `totalTimeout` still fails the request.820+ const throwIfTotalTimeoutReached = ({fromTotalTimeout}: ErrorDataTimeout): void => {821+ if (fromTotalTimeout) {822 throw new TimeoutError(request);823 }824 825 this.#throwIfTotalTimeoutExhausted(request);826+ };827+828+ // Even with request timeouts disabled, bound error-body reads so retries and error propagation829+ // cannot be stalled indefinitely by never-ending response streams.830+ const readTimeout = this.#getErrorDataTimeout(request);831+ const text = await readResponseText(response, readTimeout.milliseconds);832+ if (text === timedOut) {833+ throwIfTotalTimeoutReached(readTimeout);834 return undefined;835 }836 837 if (!text) {838 return undefined;839 }840 784- if (!this.#isJsonContentType(response.headers.get('content-type') ?? '')) {841+ if (!isJsonContentType(response.headers.get('content-type') ?? '')) {842 return text;843 }844 845 const parseTimeout = this.#getErrorDataTimeout(request);789- const data = await this.#parseJson(text, response, parseTimeout.milliseconds, request);790- if (data === timedOutResponseData) {791- if (parseTimeout.fromTotalTimeout) {792- throw new TimeoutError(request);793- }794-795- this.#throwIfTotalTimeoutExhausted(request);846+ // Unparsable error data is given up on, like unreadable error data.847+ const data = await raceWithTimeout(Promise.resolve().then(() => this.#parseJson(text, request, response)), parseTimeout.milliseconds).catch(() => undefined);848+ if (data === timedOut) {849+ throwIfTotalTimeoutReached(parseTimeout);850 return undefined;851 }852 853 return data;854 }855 802- #getErrorDataTimeout(request: Request = this.request): ErrorDataTimeout {856+ #getErrorDataTimeout(request: Request): ErrorDataTimeout {857 const errorDataTimeout = this.#options.timeout === false ? 10_000 : this.#options.timeout;858 const remainingTotal = this.#getRemainingTotalTimeout();805- if (remainingTotal === undefined) {806- return {807- milliseconds: errorDataTimeout,808- fromTotalTimeout: false,809- };810- }811-812- if (remainingTotal <= 0) {859+ if (remainingTotal === 0) {860 throw new TimeoutError(request);861 }862 863 return {1 unmodified line865 fromTotalTimeout: remainingTotal <= errorDataTimeout,866 };867 }868 869+ // The smaller of `timeout` and the `totalTimeout` budget left, or `undefined` when neither applies, since `setTimeout()` cannot wait forever.870 #getEffectiveTimeout(): number | undefined {871 const remainingTotal = this.#getRemainingTotalTimeout();824- if (remainingTotal !== undefined) {825- if (remainingTotal <= 0) {826- throw new TimeoutError(this.#sentRequest);872+ if (remainingTotal === 0) {873+ throw new TimeoutError(this.#sentRequest);827- }828-829- return this.#options.timeout === false830- ? remainingTotal831- : Math.min(this.#options.timeout, remainingTotal);874 }875 834- return this.#options.timeout === false ? undefined : this.#options.timeout;876+ const effectiveTimeout = Math.min(this.#options.timeout === false ? Number.POSITIVE_INFINITY : this.#options.timeout, remainingTotal);877+ return effectiveTimeout === Number.POSITIVE_INFINITY ? undefined : effectiveTimeout;878 }879 880 // Unlike error bodies (`#getResponseData`), a successful body read has no fallback value to return -881 // the caller's `.json()`/`.text()`/etc. promise must settle, so a timeout here always rejects.882 async #raceBodyRead(createBodyPromise: () => Promise<unknown>, response: Response): Promise<unknown> {883 const failedRequest = this.#getResponseRequest(response);841- let timeoutMs: number | undefined;884+ let timeoutMilliseconds: number | undefined;885 try {843- timeoutMs = this.#getEffectiveTimeout();886+ timeoutMilliseconds = this.#getEffectiveTimeout();887 } catch (error: unknown) {888 await this.#throwProcessedError(error, failedRequest);889 }890 891 const bodyPromise = createBodyPromise();849- const timeoutPromise = timeoutMs === undefined850- ? undefined851- : new Promise<typeof timedOutResponseData>(resolve => {852- const timeoutId = setTimeout(() => {853- resolve(timedOutResponseData);854- }, timeoutMs);855- void bodyPromise.finally(() => {856- clearTimeout(timeoutId);857- }).catch(() => undefined);858- });892 893 let result: unknown;894 try {862- result = timeoutPromise === undefined895+ result = timeoutMilliseconds === undefined896 ? await bodyPromise864- : await Promise.race([bodyPromise, timeoutPromise]);897+ : await raceWithTimeout(bodyPromise, timeoutMilliseconds);898 } catch (error: unknown) {899 if (this.#userProvidedAbortSignal?.aborted) {900 await this.#throwProcessedError(this.#userProvidedAbortSignal.reason, failedRequest);901 }7 unmodified lines909 910 await this.#throwProcessedError(error, failedRequest);911 }912 880- result = timedOutResponseData;913+ result = timedOut;914 }915 916 // 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.917 if (this.#userProvidedAbortSignal?.aborted) {918 await this.#throwProcessedError(this.#userProvidedAbortSignal.reason, failedRequest);919 }920 888- if (result === timedOutResponseData || this.#getRemainingTotalTimeout() === 0) {921+ if (result === timedOut || this.#getRemainingTotalTimeout() === 0) {922 // The stream is locked by the native body method's own reader by this point, so923 // `response.body.cancel()` would reject as "already locked". Aborting the request's924 // signal is what actually interrupts the underlying network read.925 this.#abortController?.abort();2 unmodified lines928 929 return result;930 }931 899- async #raceWithTotalTimeout<T>(operation: () => Promise<T>, abortSignal?: AbortSignal): Promise<T | typeof timedOutOperation> {932+ async #raceWithTotalTimeout<T>(operation: () => Promise<T>): Promise<T | typeof timedOut> {933+ const abortSignal = this.#userProvidedAbortSignal;934 abortSignal?.throwIfAborted();935 936 const remainingTotal = this.#getRemainingTotalTimeout();903- if (remainingTotal !== undefined && remainingTotal <= 0) {937+ if (remainingTotal === 0) {938 this.#abortController?.abort();905- return timedOutOperation;939+ return timedOut;940 }941 942 let timeoutId: ReturnType<typeof setTimeout> | undefined;943 let abortListener: (() => void) | undefined;8 unmodified lines952 // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors -- AbortSignal reasons can be any value and must be preserved exactly.953 reject(abortSignal.reason);954 };955 956+ // The signal was checked above, and nothing ran since, so it cannot have aborted before the listener is added.957 abortSignal.addEventListener('abort', abortListener, {once: true});923-924- if (abortSignal.aborted) {925- abortListener();926- }958 });959 operationPromise = operation();960 930- if (remainingTotal === undefined) {961+ if (remainingTotal === Number.POSITIVE_INFINITY) {962 return await Promise.race([operationPromise, abortPromise]);963 }964 934- const timeoutPromise = new Promise<typeof timedOutOperation>(resolve => {965+ const timeoutPromise = new Promise<typeof timedOut>(resolve => {966 timeoutId = setTimeout(() => {936- resolve(timedOutOperation);967+ resolve(timedOut);968 }, remainingTotal);969 });970 const result = await Promise.race([operationPromise, timeoutPromise, abortPromise]);940- const remainingAfterOperation = this.#getRemainingTotalTimeout();941- const didTimeOut = result === timedOutOperation || (remainingAfterOperation !== undefined && remainingAfterOperation <= 0);942- if (didTimeOut) {971+ if (result === timedOut || this.#getRemainingTotalTimeout() === 0) {972 this.#abortController?.abort();973 945- if (result === timedOutOperation) {946- this.#releaseWhenSettled(operationPromise);974+ if (result === timedOut) {975+ releaseWhenSettled(operationPromise);976 } else {948- this.#cancelReturnedBody(result);977+ cancelReturnedBody(result);978 }979 951- return timedOutOperation;980+ return timedOut;981 }982 983 return result;984 } catch (error: unknown) {985 if (abortSignal?.aborted) {957- // The abort won the race, so whatever the operation eventually returns is discarded. Release its body, the same way the timeout path below does for a value it never consumed.986+ // 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.987 if (operationPromise) {959- this.#releaseWhenSettled(operationPromise);988+ releaseWhenSettled(operationPromise);989 }990 991 abortSignal.throwIfAborted();992 }993 965- const remainingAfterOperation = this.#getRemainingTotalTimeout();966- if (remainingAfterOperation !== undefined && remainingAfterOperation <= 0) {994+ if (this.#getRemainingTotalTimeout() === 0) {995 this.#abortController?.abort();968- return timedOutOperation;996+ return timedOut;997 }998 999 throw error;1000 } finally {3 unmodified lines1004 }1005 }1006 }1007 980- #isJsonContentType(contentType: string): boolean {981- // Match JSON subtypes like `json`, `problem+json`, and `vnd.api+json`.982- // 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.983- const mimeType = (contentType.split(';', 1)[0] ?? '').trim().toLowerCase();984-985- if (!mimeType.endsWith('json')) {986- return false;987- }988-989- const separator = mimeType.at(-5);990- if (separator === '/') {991- return true;992- }993-994- if (separator !== '.' && separator !== '+' && separator !== '-') {995- return false;996- }997-998- // The separator is not the slash, so any slash in the type comes before it.999- return mimeType.includes('/');1008+ // Uses `parseJson` when it is set, and `JSON.parse()` otherwise.1009+ #parseJson(text: string, request: Request, response: Response): unknown {1010+ const {parseJson} = this.#options;1011+ return parseJson ? parseJson(text, {request, response}) : JSON.parse(text);1012 }1013 1002- async #readResponseText(response: Response, timeoutMs: number): Promise<string | typeof timedOutResponseData | undefined> {1003- const {body} = response;1004- if (!body) {1005- try {1006- return await response.text();1007- } catch {1008- return undefined;1009- }1010- }1011-1012- let reader: ReadableStreamDefaultReader<Uint8Array>;1013- try {1014- reader = body.getReader();1015- } catch {1016- // Another consumer already locked the stream.1017- return undefined;1018- }1019-1020- const contentType = response.headers.get('content-type') ?? '';1021- // JSON uses UTF-8 regardless of the charset parameter (RFC 8259).1022- const decoder = this.#isJsonContentType(contentType) ? new TextDecoder() : createTextDecoder(contentType);1023- const chunks: string[] = [];1024- let totalBytes = 0;1025-1026- const readAll = (async (): Promise<string | undefined> => {1027- try {1028- for (;;) {1029- // eslint-disable-next-line no-await-in-loop1030- const {done, value} = await reader.read();1031- if (done) {1032- break;1033- }1034-1035- totalBytes += value.byteLength;1036- if (totalBytes > maxErrorResponseBodySize) {1037- void reader.cancel().catch(() => undefined);1038- return undefined;1039- }1040-1041- chunks.push(decoder.decode(value, {stream: true}));1042- }1043- } catch (error) {1044- if (isResponseSizeError(error)) {1045- throw error;1046- }1047-1048- return undefined;1049- }1050-1051- chunks.push(decoder.decode());1052- return chunks.join('');1053- })();1054-1055- const timeoutPromise = new Promise<typeof timedOutResponseData>(resolve => {1056- const timeoutId = setTimeout(() => {1057- resolve(timedOutResponseData);1058- }, timeoutMs);1059- void readAll.finally(() => {1060- clearTimeout(timeoutId);1061- }).catch(() => undefined);1062- });1063-1064- const result = await Promise.race([readAll, timeoutPromise]);1065- if (result === timedOutResponseData) {1066- void reader.cancel().catch(() => undefined);1067- }1068-1069- return result;1070- }1071-1072- async #parseJson(text: string, response: Response, timeoutMs: number, request: Request): Promise<unknown> {1073- let timeoutId: ReturnType<typeof setTimeout> | undefined;1074- try {1075- return await Promise.race([1076- Promise.resolve().then(() => this.#options.parseJson1077- ? this.#options.parseJson(text, {request, response})1078- : JSON.parse(text),1079- ),1080- new Promise<typeof timedOutResponseData>(resolve => {1081- timeoutId = setTimeout(() => {1082- resolve(timedOutResponseData);1083- }, timeoutMs);1084- }),1085- ]);1086- } catch {1087- return undefined;1088- } finally {1089- clearTimeout(timeoutId);1090- }1091- }1092-1093- #cancelBody(body: ReadableStream | undefined): void {1094- if (!body) {1095- return;1096- }1097-1098- // Ignore cancellation failures from already-locked or already-consumed streams.1099- void body.cancel().catch(() => undefined);1100- }1101-1102- #cancelResponseBody(response: Response): void {1103- // Ignore cancellation failures from already-locked or already-consumed streams.1104- this.#cancelBody(response.body ?? undefined);1105- }1106-1107- #cancelReturnedBody(value: unknown): void {1108- if (isResponseInstance(value)) {1109- this.#cancelResponseBody(value);1110- } else if (isRequestInstance(value)) {1111- this.#cancelBody(value.body ?? undefined);1112- }1113- }1114-1115- // 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.1116- #releaseWhenSettled(operationPromise: Promise<unknown>): void {1117- void operationPromise.then(value => {1118- this.#cancelReturnedBody(value);1119- }).catch(() => undefined);1120- }1121-1014 #createManagedSignal(): AbortSignal {1015 return this.#userProvidedAbortSignal1016 ? AbortSignal.any([this.#userProvidedAbortSignal, this.#abortController!.signal])1017 : this.#abortController!.signal;4 unmodified lines1022 const {throwHttpErrors} = this.#options;1023 try {1024 return typeof throwHttpErrors === 'function' ? throwHttpErrors(response.status) : throwHttpErrors;1025 } catch (error: unknown) {1134- this.#cancelResponseBody(response);1026+ cancelBody(response);1027 throw error;1028 }1029 }1030 2 unmodified lines1033 return this.#originalRequest ?? this.request;1034 }1035 1036 #throwIfTotalTimeoutExhausted(request: Request = this.#sentRequest): void {1145- const remaining = this.#getRemainingTotalTimeout();1146- if (remaining !== undefined && remaining <= 0) {1037+ if (this.#getRemainingTotalTimeout() === 0) {1038 throw new TimeoutError(request);1039 }1040 }1041 3 unmodified lines1045 const result = await this.#raceWithTotalTimeout(async () => hook({1046 request: this.request,1047 options: this.#getNormalizedOptions(),1048 retryCount: 0,1158- }), this.#userProvidedAbortSignal);1049+ }));1050 1160- if (result === timedOutOperation) {1051+ if (result === timedOut) {1052 throw new TimeoutError(this.#sentRequest);1053 }1054 1164- if (isRequestInstance(result)) {1055+ if (isRequest(result)) {1056 this.#assignRequest(this.#withManagedSignal(result));1166- } else if (isResponseInstance(result)) {1057+ } else if (isResponse(result)) {1058+ this.#hookResponses.add(result);1059 return result;1060 }1061 }1062 16 unmodified lines1079 request: this.request,1080 options: this.#getNormalizedOptions(),1081 response: hookResponse,1082 retryCount: this.#retryCount,1191- }), this.#userProvidedAbortSignal);1083+ }));1084 1193- if (modifiedResponse === timedOutOperation) {1085+ if (modifiedResponse === timedOut) {1086 throw new TimeoutError(this.#sentRequest);1087 }1196- } catch (error) {1197- // Cancel both responses to prevent memory leaks when hook throws1198- if (hookResponse !== response) {1199- this.#cancelResponseBody(hookResponse);1200- }1088 1202- this.#cancelResponseBody(response);1089+ if (isRetryMarker(modifiedResponse)) {1090+ throw new ForceRetryError(modifiedResponse.options);1091+ }1092+ } catch (error) {1093+ // 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).1094+ // Do not await cancellation since hooks can clone the response, leaving extra tee branches that keep cancel promises pending per the Streams spec.1095+ cancelBody(hookResponse);1096+ cancelBody(response);1097 throw error;1098 }1099 1206- if (isRetryMarker(modifiedResponse)) {1207- // Cancel both the cloned response passed to the hook and the current response to prevent resource leaks (especially important in Deno/Bun).1208- // Do not await cancellation since hooks can clone the response, leaving extra tee branches that keep cancel promises pending per the Streams spec.1209- if (hookResponse !== response) {1210- this.#cancelResponseBody(hookResponse);1211- }1212-1213- this.#cancelResponseBody(response);1214- throw new ForceRetryError(modifiedResponse.options);1215- }1216-1217- const nextResponse = isResponseInstance(modifiedResponse)1100+ const nextResponse = isResponse(modifiedResponse)1101 ? this.#setResponseRequest(modifiedResponse, responseRequest)1102 : response;1103 1104 // Cancel any response bodies we won't use to prevent memory leaks.1105 // Uses fire-and-forget since hooks may have cloned the response, creating tee branches that block cancellation.1106 // If the hook wrapped an existing body into a new Response, both Response objects can still point at the same stream.1224- if (hookResponse !== response && hookResponse !== nextResponse && hookResponse.body !== nextResponse.body) {1225- this.#cancelResponseBody(hookResponse);1226- }1107+ cancelBody(hookResponse, nextResponse);1108+ cancelBody(response, nextResponse);1109 1228- if (response !== nextResponse && response.body !== nextResponse.body) {1229- this.#cancelResponseBody(response);1230- }1231-1110 if (nextResponse !== response) {1111 response = this.#limitResponseSize(nextResponse);1112 }1113 }10 unmodified lines1124 }1125 1126 async #retryFromError(error: unknown): Promise<Response | void> {1127 this.#throwIfAbortedByUser();1250- this.#returnedResponseFromBeforeRetryHook = false;1128 1129 const retryDelay = Math.min(await this.#calculateRetryDelay(error), maxSafeTimeout);1130 const delayOptions = {signal: this.#userProvidedAbortSignal};1131 1132 const remainingTimeout = this.#getRemainingTotalTimeout();1256- if (remainingTimeout !== undefined) {1257- if (remainingTimeout <= 0) {1258- throw new TimeoutError(this.#sentRequest);1259- }1133+ if (remainingTimeout === 0) {1134+ throw new TimeoutError(this.#sentRequest);1135+ }1136 1261- // If waiting would consume all remaining budget, time out without starting another request.1262- if (retryDelay >= remainingTimeout) {1263- await delay(remainingTimeout, delayOptions);1264- throw new TimeoutError(this.#sentRequest);1265- }1137+ // If waiting would consume all remaining budget, time out without starting another request.1138+ if (retryDelay >= remainingTimeout) {1139+ await delay(remainingTimeout, delayOptions);1140+ throw new TimeoutError(this.#sentRequest);1141 }1142 1143 // Only use user-provided signal for delay, not our internal abortController1144 await delay(retryDelay, delayOptions);16 unmodified lines1161 this.#assignRequest(this.#withManagedSignal(error.customRequest));1162 }1163 1164 for (const hook of this.#options.hooks.beforeRetry) {1290- let hookResult: Awaited<ReturnType<typeof hook>> | typeof timedOutOperation;1165+ let hookResult: Awaited<ReturnType<typeof hook>> | typeof timedOut;1166 try {1167 // eslint-disable-next-line no-await-in-loop1168 hookResult = await this.#raceWithTotalTimeout(async () => hook({1169 request: this.request,1170 options: this.#getNormalizedOptions(),1296- error: isError(error) ? error : new NonError(error),1171+ error: NonError.wrap(error),1172 retryCount: this.#retryCount + 1,1298- }), this.#userProvidedAbortSignal);1173+ }));1174 } catch (hookError) {1175 // 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.1176 this.#throwIfAbortedByUser();1177 4 unmodified lines1182 1183 throw hookError;1184 }1185 1311- if (hookResult === timedOutOperation) {1186+ if (hookResult === timedOut) {1187 throw new TimeoutError(this.#sentRequest);1188 }1189 1315- if (isRequestInstance(hookResult)) {1190+ if (isRequest(hookResult)) {1191 // Same contract as `ky.retry({request})`: a Request returned from `beforeRetry`1192 // is used as-is rather than being sanitized or otherwise rewritten by Ky.1193 this.#assignRequest(this.#withManagedSignal(hookResult));1194 break;1195 }1196 1322- if (isResponseInstance(hookResult)) {1323- this.#returnedResponseFromBeforeRetryHook = true;1197+ if (isResponse(hookResult)) {1198+ this.#hookResponses.add(hookResult);1199 this.#retryCount++;1200 return hookResult;1201 }1202 8 unmodified lines1211 this.#retryCount++;1212 return this.#retry();1213 }1214 1340- #consumeReturnedResponseFromBeforeRetryHook(): boolean {1341- const value = this.#returnedResponseFromBeforeRetryHook;1342- this.#returnedResponseFromBeforeRetryHook = false;1343- return value;1344- }1345-1215 async #fetch(): Promise<Response> {1216 // A previous attempt can return without consuming its upload. Release that unused branch before replacing the request reference.1348- if (this.#originalRequest && this.#originalRequest.body !== this.request.body) {1349- this.#cancelBody(this.#originalRequest.body ?? undefined);1350- }1217+ cancelBody(this.#originalRequest, this.request);1218 1219 const nonRequestOptions = findUnknownOptions(this.#options);1220 this.#retryLimit = normalizeRetryOptions(this.#options.retry).limit;1221 // Reattach the managed signal because Node.js can garbage-collect the abort controller used by Request.clone().1222 const retryRequest = this.#retryLimit > 0 ? this.#withManagedSignal(this.request.clone()) : undefined;1356- const request = this.#wrapRequestWithUploadProgress(this.request, this.#options.body ?? undefined);1223+ const request = this.#wrapRequestWithUploadProgress(this.request);1224 1225 // Cloning is done here to prepare in advance for retries.1226 // Skip cloning when retries are disabled - cloning a streaming body calls ReadableStream#tee()1227 // which buffers the entire stream in memory, causing excessive memory usage for large uploads.15 unmodified lines1243 fetch,1244 });1245 1246 // `undefined` would otherwise look like `ky.stop`, and any other value fails later with an error that does not name the cause.1380- if (!isResponseInstance(response)) {1247+ if (!isResponse(response)) {1248 throw new TypeError('The `fetch` option must resolve with a `Response`');1249 }1250 1251 if (this.#getRemainingTotalTimeout() === 0) {1252 this.#abortController?.abort();1386- this.#cancelResponseBody(response);1253+ cancelBody(response);1254 throw new TimeoutError(request);1255 }1256 1257 return this.#setResponseRequest(response, request);16 unmodified lines1274 #throwIfAbortedByUser(): void {1275 this.#userProvidedAbortSignal?.throwIfAborted();1276 }1277 1411- #getRemainingTotalTimeout(): number | undefined {1412- if (this.#startTime === undefined) {1413- return undefined;1414- }1415-1416- const elapsed = this.#getCurrentTime() - this.#startTime;1417- return Math.max(0, (this.#options.totalTimeout as number) - elapsed);1278+ // `0` once the `totalTimeout` budget is spent, and `Infinity` without a `totalTimeout`.1279+ #getRemainingTotalTimeout(): number {1280+ return Math.max(0, this.#deadline - getCurrentTime());1281 }1282 1420- #getCurrentTime(): number {1421- return globalThis.performance?.now() ?? Date.now();1422- }1423-1283 #getNormalizedOptions(): NormalizedOptions {1284 if (!this.#cachedNormalizedOptions) {1285 // Exclude Ky-specific options that are not part of `RequestInit`.1286 const {17 unmodified lines1304 }1305 1306 #assignRequest(request: Request, requestBodyCanBeCancelled = false): void {1307 // 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.1449- if (this.#requestBodyCanBeCancelled && this.request.body !== request.body) {1450- this.#cancelBody(this.request.body ?? undefined);1308+ if (this.#requestBodyCanBeCancelled) {1309+ cancelBody(this.request, request);1310 }1311 1312 this.#cachedNormalizedOptions = undefined;1313 this.request = request;27 unmodified lines1341 const request = this.#getResponseRequest(response);1342 return this.#setResponseRequest(limitResponseSize(response, request, this.#options.maxResponseSize), request);1343 }1344 1486- #wrapRequestWithUploadProgress(request: Request, originalBody?: BodyInit): Request {1345+ #wrapRequestWithUploadProgress(request: Request): Request {1346 if (!this.#options.onUploadProgress || !supportsRequestStreams || !request.body) {1347 return request;1348 }1349 1491- return streamRequest(request, this.#options.onUploadProgress, originalBody ?? this.#options.body ?? undefined);1350+ return streamRequest(request, this.#options.onUploadProgress, this.#options.body);1351 }1352 }modified:source/core/retry-timing.ts+2 added-2 removed
166 unmodified linesExpand all167168169170171172171172173166 unmodified linesExpand all if (timestamp === undefined) { return undefined; }
const delay = timestamp - Date.now(); return Number.isFinite(delay) ? Math.max(0, delay) : undefined; // `createTimestamp()` only returns valid dates, so the delay is always finite. return Math.max(0, timestamp - Date.now());};modified:source/errors/ForceRetryError.ts+8 added-5 removed
1 import type {ForceRetryOptions} from '../core/constants.js';2-import {isError} from '../utils/is.js';2+import {isNonNegativeNumber, isRequest} from '../utils/is.js';3 import {KyError} from './KyError.js';4 import {NonError} from './NonError.js';5 6 /**14 unmodified lines21 }22 23 // The custom delay flows straight into `setTimeout`, so a negative or `NaN` value would be clamped to 1ms and silently collapse the backoff, the same failure mode validated away for `retry.delay`.24 const delay = options?.delay;25- if (delay !== undefined && (typeof delay !== 'number' || Number.isNaN(delay) || delay < 0)) {25+ if (delay !== undefined && !isNonNegativeNumber(delay)) {26 throw new TypeError('The `ky.retry()` `delay` option must be a non-negative number or `Infinity`');27 }28 29 if (options?.code !== undefined && typeof options.code !== 'string') {30 throw new TypeError('The `ky.retry()` `code` option must be a string');31 }32 33+ // The request is only read when it is truthy, so `null` would otherwise silently retry with the original request. A `Request` from another realm is accepted, the same way a hook's returned request is.34+ if (options?.request !== undefined && !isRequest(options.request)) {35+ throw new TypeError('The `ky.retry()` `request` option must be a `Request`');36+ }37+38 // Runtime protection: wrap non-Error causes in NonError39 // TypeScript type is Error for guidance, but JS users can pass anything35- const cause = options?.cause === undefined36- ? undefined37- : (isError(options.cause) ? options.cause : new NonError(options.cause));40+ const cause = options?.cause === undefined ? undefined : NonError.wrap(options.cause);41 42 super(43 // `code` is documented as always reaching the message, so only an absent code falls back.44 options?.code === undefined ? 'Forced retry' : `Forced retry: ${options.code}`,8 unmodified linesmodified:source/errors/NonError.ts+9 added
1+import {isError} from '../utils/is.js';2+3 /**4 Wrapper for non-Error values that were thrown.5 6 In JavaScript, any value can be thrown (not just Error instances). This class wraps such values to ensure consistent error handling.7 */8 export class NonError extends Error {9+ /**10+ Returns the value as-is when it is an `Error`, including one from another realm, and otherwise wraps it in a `NonError`.11+ */12+ static wrap(value: unknown): Error {13+ return isError(value) ? value : new NonError(value);14+ }15+16 override name = 'NonError';17 readonly value: unknown;18 19 constructor(value: unknown) {18 unmodified linesmodified:source/types/options.ts+12 added-7 removed
480 unmodified lines481 482 const extended = original.extend({483 headers: {484 rainbow: undefined485+ },486+ hooks: {487+ beforeRequest: [488+ ({request}) => {489+ console.log(request.headers.has('rainbow'));490+ //=> false491+492+ console.log(request.headers.has('unicorn'));493+ //=> true494+ }495+ ]496 }497 });498 488- const response = await extended(url);489-490- console.log(response.headers.has('rainbow'));491- //=> false492-493- console.log(response.headers.has('unicorn'));494- //=> true499+ await extended(url);500 ```501 */502 headers?: KyHeadersInit | undefined;503 52 unmodified linesmodified:source/utils/body.ts+16 added-3 removed
5 unmodified lines6 const responseSizeErrors = new WeakMap<ReadableStream, () => ResponseSizeError | undefined>();7 // The `Response` constructor rejects a body for these statuses, but some browsers (for example, Chromium and WebKit) still expose a body stream on such responses, so they must not be wrapped. A runtime that exposes a non-empty body for one of them, such as WebKit for 205, is therefore left unlimited and without progress events.8 const nullBodyStatuses = new Set([101, 103, 204, 205, 304]);9 10+/**11+Cancels the body of a request or response that is no longer used, unless `keep` still reads the same stream.12+13+Fire-and-forget: cancellation failures from already-locked or already-consumed streams are ignored, and the cancellation is not awaited since a clone leaves extra tee branches that keep the cancel promise pending per the Streams spec.14+*/15+export const cancelBody = (value: Request | Response | undefined, keep?: Request | Response): void => {16+ const body = value?.body;17+ if (body && body !== keep?.body) {18+ void body.cancel().catch(() => undefined);19+ }20+};21+22+const getContentLength = (headers: Headers): number => Math.max(0, Number(headers.get('content-length')) || 0);23+24 // A multipart body sends every line break in a field name or string value as CRLF, and escapes line breaks and quotes in a field name or filename.25 const normalizeLineBreaks = (value: string): string => value.replaceAll(/\r\n|\r|\n/g, '\r\n');26 const escapeFormDataName = (name: string): string => name.replaceAll('\n', '%0A').replaceAll('\r', '%0D').replaceAll('"', '%22');27 178 unmodified lines206 207 // `content-length` counts encoded bytes on the wire, while the progress stream counts the bytes after decompression. Using it for a content-coded response would report a total below what actually arrives, so every event would sit at ~100%. The total is then unknown, which `Progress` already models with `0`. `identity` is a registered no-op coding (RFC 9110 §8.4.2), so it leaves the length valid.208 const contentEncoding = response.headers.get('content-encoding')?.toLowerCase();209 const isContentCoded = Boolean(contentEncoding) && contentEncoding !== 'identity';196- const totalBytes = isContentCoded ? 0 : Math.max(0, Number(response.headers.get('content-length')) || 0);210+ const totalBytes = isContentCoded ? 0 : getContentLength(response.headers);211 const body = withProgress(originalBody, totalBytes, onDownloadProgress);212 213 return copyResponseMetadata(new Response(body, response), response);214 };12 unmodified lines227 return request;228 }229 230 // Use original body for size calculation since request.body is already a stream. A `ReadableStream` measures 0, so fall back to a `content-length` the caller declared. Browsers drop that header from a request, so this only helps outside browsers.217- const totalBytes = getBodySize(originalBody ?? request.body)218- || Math.max(0, Number(request.headers.get('content-length')) || 0);231+ const totalBytes = getBodySize(originalBody ?? request.body) || getContentLength(request.headers);232 233 return new Request(request, {234 // @ts-expect-error - Types are outdated.235 duplex: 'half',7 unmodified linesmodified:source/utils/is.ts+16 added
123456789101112131415161718192021222324// eslint-disable-next-line @typescript-eslint/no-restricted-typesexport const isObject = (value: unknown): value is object => value !== null && typeof value === 'object';
// eslint-disable-next-line @typescript-eslint/no-restricted-typesexport const isNonArrayObject = (value: unknown): value is object => isObject(value) && !Array.isArray(value);
// `NaN` fails the comparison, so it is rejected too.export const isNonNegativeNumber = (value: unknown): value is number => typeof value === 'number' && value >= 0;
const objectToString = Object.prototype.toString;
// An `Error` from another realm (an iframe, a worker, a `vm` context, or a duplicated dependency) fails `instanceof`, so the internal brand is checked as well, the same way the request and response checks do. `instanceof` stays first because it also accepts `DOMException`, which an `AbortSignal` reason is, and that does not carry the `[object Error]` brand.export const isError = (value: unknown): value is Error => value instanceof Error || objectToString.call(value) === '[object Error]';
// A `Request` from another realm, such as one a hook built in an iframe, is accepted through its internal brand.export const isRequest = (value: unknown): value is Request => value instanceof globalThis.Request || objectToString.call(value) === '[object Request]';
// Accepted custom responses are treated as full Responses throughout Ky.// If a custom fetch returns one, it must behave like a Response for cloning,// body consumption, `json()` decoration, and any enabled stream features.export const isResponse = (value: unknown): value is Response => value instanceof globalThis.Response || objectToString.call(value) === '[object Response]';modified:source/utils/merge.ts+40 added-51 removed
1 import type {KyHeadersInit, Options} from '../types/options.js';2 import type {Hooks, NormalizedHooks} from '../types/hooks.js';3 import {supportsAbortSignal} from '../core/constants.js';4-import {isObject} from './is.js';4+import {isNonArrayObject, isObject} from './is.js';5 6 // Registered globally so that a wrapper created by a second copy of Ky, which happens with a duplicated dependency, is still recognised.7 const replaceSymbol: unique symbol = Symbol.for('ky.replaceOption');8 52 unmodified lines61 };62 63 export const validateAndMerge = (...sources: Array<Partial<Options> | undefined>): Partial<Options> => {64 for (const source of sources) {65- if ((!isObject(source) || Array.isArray(source)) && source !== undefined) {65+ if (source !== undefined && !isNonArrayObject(source)) {66 throw new TypeError('The `options` argument must be an object');67 }68 }69 15 unmodified lines85 return result;86 };87 88 const isPlainObject = (value: unknown): value is Record<string, unknown> => {89- if (!isObject(value) || Array.isArray(value)) {89+ if (!isNonArrayObject(value)) {90 return false;91 }92 93 const prototype = Object.getPrototypeOf(value);4 unmodified lines98 const isMergeable = (value: unknown): value is Record<string, unknown> | unknown[] => isPlainObject(value) || Array.isArray(value);99 100 export const cloneShallow = <T>(value: T): T => {101 if (value instanceof URLSearchParams) {102- const copy = new URLSearchParams(value) as URLSearchParams & {[deletedParametersSymbol]?: Set<string>};103- const deleted = (value as URLSearchParams & {[deletedParametersSymbol]?: Set<string>})[deletedParametersSymbol];102+ const copy: MarkedSearchParameters = new URLSearchParams(value);103+ const deleted = (value as MarkedSearchParameters)[deletedParametersSymbol];104 if (deleted) {105 // Preserve internal deletion markers so init-hook cloning does not resurrect params removed during option merging.106 copy[deletedParametersSymbol] = new Set(deleted);107 }12 unmodified lines120 121 return value;122 };123 124+// A tuple array is copied pair by pair, so changing a pair of the copy does not change the caller's `searchParams`.125+export const cloneSearchParameters = <T>(value: T): T =>126+ Array.isArray(value) ? value.map(parameter => cloneShallow(parameter)) as T : cloneShallow(value);127+128 // Recursively clone plain objects and arrays so that `init`-hook mutations to nested `json` or `context` values do not leak into the next request. Non-plain values (functions, class instances, `Date`, `URLSearchParams`, …) are kept by reference, matching how option merging treats them as whole values. The `seen` map keeps shared and cyclic references intact.129 export const cloneDeep = <T>(value: T, seen: WeakMap<Record<string, unknown> | unknown[], unknown> = new WeakMap()): T => {130 if (!isMergeable(value)) {131 return value;33 unmodified lines165 166 return copy as T;167 };168 165-// Header names are case-insensitive, so they are normalized to lowercase (like `Headers` does) so that overrides and `undefined` deletions match regardless of how the name was spelled and `init` hooks can rely on lowercase keys.166-// An `undefined` value is kept as a deletion marker so it can still remove a header inherited from a `Request` input when the request is created.167-const mergeHeaderObjects = (source1: Record<string, unknown>, source2: Record<string, unknown>): Record<string, string | undefined> => {168- const result = new Map<string, string | undefined>();169-170- for (const [key, value] of [...Object.entries(source1), ...Object.entries(source2)]) {171- result.set(key.toLowerCase(), value as string | undefined);172- }173-174- return Object.fromEntries(result);175-};176-169 // Every header source is merged as a plain object so deletion markers survive no matter how the headers were provided. A `Headers` instance cannot hold `undefined`, so its string `'undefined'` counts as a deletion. A plain object is returned as-is, so callers must not mutate the result.170 const toHeaderObject = (source: KyHeadersInit): Record<string, string | undefined> => {171 if (isPlainObject(source)) {172 return source as Record<string, string | undefined>;9 unmodified lines182 183 return result;184 };185 186+// Header names are case-insensitive, so they are normalized to lowercase (like `Headers` does) so that overrides and `undefined` deletions match regardless of how the name was spelled and `init` hooks can rely on lowercase keys.187+// An `undefined` value is kept as a deletion marker so it can still remove a header inherited from a `Request` input when the request is created.194-export const mergeHeaderContainers = (source1: KyHeadersInit, source2: KyHeadersInit): Record<string, string | undefined> =>195- mergeHeaderObjects(toHeaderObject(source1), toHeaderObject(source2));188+export const mergeHeaderContainers = (source1: KyHeadersInit, source2: KyHeadersInit): Record<string, string | undefined> => {189+ const result = new Map<string, string | undefined>();190 191+ for (const [key, value] of [...Object.entries(toHeaderObject(source1)), ...Object.entries(toHeaderObject(source2))]) {192+ result.set(key.toLowerCase(), value);193+ }194+195+ return Object.fromEntries(result);196+};197+198 function newHookValue<K extends keyof Hooks>(original: Hooks, incoming: Hooks, property: K): NormalizedHooks[K] {199 // An absent key must keep the parent's hooks, which is why this check needs `Object.hasOwn`.200 if (Object.hasOwn(incoming, property) && incoming[property] === undefined) {201 return [];14 unmodified lines216 }217 218 export const mergeHooks = (original: Hooks = {}, incoming: Hooks = {}): NormalizedHooks => {219 // `undefined` selects the default through the parameter default. `null` is not accepted, so it reaches this check and is reported like any other bad shape.219- if (!isObject(incoming) || Array.isArray(incoming)) {220+ if (!isNonArrayObject(incoming)) {221 throw new TypeError('The `hooks` option must be an object');222 }223 224 return {6 unmodified lines231 };232 233 export const deletedParametersSymbol = Symbol('deletedParameters');234 234-const resolveArrayMarkers = (value: unknown[], resolveItem: (item: unknown) => unknown): unknown[] | undefined => {235- let resolved: unknown[] | undefined;236- for (const [index, item] of value.entries()) {237- const replacement = resolveItem(item);238- if (replacement !== item) {239- resolved ??= [...value];240- resolved[index] = replacement;241- }242- }235+export type MarkedSearchParameters = URLSearchParams & {[deletedParametersSymbol]?: Set<string>};236 244- return resolved;245-};246-247-const resolveObjectMarkers = (value: Record<string, unknown>, resolveItem: (item: unknown) => unknown): Record<string, unknown> | undefined => {248- let resolved: Record<string, unknown> | undefined;237+// Copies the array or object only when an item actually changes, so an untouched value keeps its identity. A hole in a sparse array is skipped, which is fine since it holds no wrapper.238+const resolveItemMarkers = (value: Record<string, unknown> | unknown[], resolveItem: (item: unknown) => unknown): Record<string, unknown> | unknown[] => {239+ let resolved: Record<string, unknown> | unknown[] | undefined;240 for (const [key, item] of Object.entries(value)) {241 const replacement = resolveItem(item);242 if (replacement !== item) {252- resolved ??= {...value};253- resolved[key] = replacement;243+ resolved ??= Array.isArray(value) ? [...value] : {...value};244+ // An array index is written through its string key, the same way `Object.entries()` gave it.245+ (resolved as Record<string, unknown>)[key] = replacement;246 }247 }248 257- return resolved;249+ return resolved ?? value;250 };251 252 // `json` and `context` are user data, which can be large, so they are not walked on every request.253 const userDataOptions = new Set(['json', 'context']);9 unmodified lines263 }264 265 resolved.set(value, value);266 const resolveItem = (item: unknown) => resolveReplaceMarkers(getReplaceState(item).value, resolved);275- const result = (Array.isArray(value) ? resolveArrayMarkers(value, resolveItem) : resolveObjectMarkers(value, resolveItem)) ?? value;267+ const result = resolveItemMarkers(value, resolveItem);268 resolved.set(value, result);269 270 return result;271 };272 273 const appendSearchParameters = (target: any, source: any): URLSearchParams => {282- const result = new URLSearchParams() as URLSearchParams & {[deletedParametersSymbol]?: Set<string>};274+ const result: MarkedSearchParameters = new URLSearchParams();275 // Deleted keys stay marked even when a later layer re-adds the key, so the key is still removed from the input URL before the re-added value is appended.276 const deleted = new Set<string>();277 278+ // Both are defined, since an `undefined` layer clears the search parameters instead of being merged.279 for (const input of [target, source]) {287- if (input === undefined) {288- continue;289- }290-280 if (input instanceof URLSearchParams) {281 // A merged `URLSearchParams` already applied its own deletions before any re-added entries, so its deletions only apply to what was merged before it.293- const inputDeleted = (input as any)[deletedParametersSymbol] as Set<string> | undefined;282+ const inputDeleted = (input as MarkedSearchParameters)[deletedParametersSymbol];283 if (inputDeleted) {284 for (const key of inputDeleted) {285 result.delete(key);286 deleted.add(key);90 unmodified lines377 // Scoped to the root options level so it never rewrites nested user data that378 // happens to contain a `context` key (e.g. a `json` request body).379 if (isRoot && key === 'context') {380 // `null` is not accepted, so it is reported here rather than treated as absent.392- if (value !== undefined && (!isObject(value) || Array.isArray(value))) {381+ if (value !== undefined && !isNonArrayObject(value)) {382 throw new TypeError('The `context` option must be an object');383 }384 385 // Shallow merge: always create a new object to prevent mutation bugs20 unmodified lines406 // Explicit undefined removes searchParams407 searchParameters = undefined;408 } else if (isReplace || searchParameters === undefined) {409 // First or replacement source: shallow-clone to preserve type (string/object/URLSearchParams/tuples) without sharing the caller's object421- searchParameters = Array.isArray(value) ? value.map(parameter => cloneShallow(parameter)) : cloneShallow(value);410+ searchParameters = cloneSearchParameters(value);411 } else {412 // Subsequent sources: merge and convert to URLSearchParams413 searchParameters = appendSearchParameters(searchParameters, value);414 }415 416 continue;417 }418 419+ // Checked here as well as when the request is built, because a later layer would otherwise replace an invalid value, `null` included, before anything reports it.420+ if (isRoot && key === 'retry' && value !== undefined && typeof value !== 'number' && !isNonArrayObject(value)) {421+ throw new TypeError('`retry` must be a number or an object');422+ }423+424 // `retry` accepts a number as shorthand for `{limit: number}`. Expand it before425 // merging so extending a numeric `retry` with an object keeps the limit instead426 // of dropping it (e.g. `ky.create({retry: 3}).extend({retry: {methods: ['get']}})`),427 // and extending an object `retry` with a number keeps the other options428 // (e.g. `ky.create({retry: {methods: ['post']}}).extend({retry: 3})`).429 // Scoped to the root options level so it never rewrites nested user data that430 // happens to contain a `retry` key (e.g. a `json` request body).437- // Checked here as well as when the request is built, because a later layer would otherwise replace an invalid value, `null` included, before anything reports it.438- if (isRoot && key === 'retry' && value !== undefined && typeof value !== 'number' && (!isObject(value) || Array.isArray(value))) {439- throw new TypeError('`retry` must be a number or an object');440- }441-431 if (isRoot && key === 'retry' && !isReplace) {432 if (isObject(value) && typeof returnValue[key] === 'number') {433 returnValue = {...returnValue, [key]: {limit: returnValue[key]}};434 } else if (typeof value === 'number' && isObject(returnValue[key])) {67 unmodified linesmodified:source/utils/normalize.ts+7 added-20 removed
1 import {requestMethods} from '../core/constants.js';2 import type {RetryOptions} from '../types/retry.js';3 import type {HttpMethod, InternalOptions, RequestHttpMethod} from '../types/options.js';4+import {isNonArrayObject, isNonNegativeNumber} from './is.js';5 6 export const normalizeRequestMethod = (input: string): string =>7 requestMethods.includes(input.toLowerCase() as RequestHttpMethod) ? input.toUpperCase() : input;8 9 unmodified lines18 19 const retryStatusCodes = [408, 413, 429, 500, 502, 503, 504];20 21 const retryAfterStatusCodes = [413, 429, 503];21-const invalidRetryLimitErrorMessage = '`retry.limit` must be a finite, non-negative integer';22 23 type InternalRetryOptions = InternalOptions['retry'];24 25 const defaultRetryOptions: InternalRetryOptions = {7 unmodified lines33 jitter: undefined,34 retryOnTimeout: false,35 };36 37-/**38-Normalizes an omitted retry limit or validates a supplied one.39-*/40-const normalizeRetryLimit = (retryLimit: unknown): number => {41- if (retryLimit === undefined) {42- return defaultRetryOptions.limit;43- }44-45- if (typeof retryLimit !== 'number' || !Number.isInteger(retryLimit) || retryLimit < 0) {46- throw new TypeError(invalidRetryLimitErrorMessage);47- }48-49- return retryLimit;50-};51-37 export const normalizeRetryOptions = (retry: number | RetryOptions = {}): InternalRetryOptions => {38 if (typeof retry === 'number') {39 retry = {limit: retry};40 }41 57- if (retry === null || typeof retry !== 'object' || Array.isArray(retry)) {42+ if (!isNonArrayObject(retry)) {43 throw new TypeError('`retry` must be a number or an object');44 }45 46 const normalizedRetry = {47 ...defaultRetryOptions,48 ...Object.fromEntries(Object.entries(retry).filter(([, value]) => value !== undefined)),49 };65- normalizedRetry.limit = normalizeRetryLimit(normalizedRetry.limit);50+ // Validates the retry limit. An omitted one already got the default above, since `undefined` values are filtered out.51+ if (!Number.isInteger(normalizedRetry.limit) || normalizedRetry.limit < 0) {52+ throw new TypeError('`retry.limit` must be a finite, non-negative integer');53+ }54 55 for (const key of ['methods', 'statusCodes', 'afterStatusCodes'] as const) {56 if (!Array.isArray(normalizedRetry[key])) {57 // eslint-disable-next-line unicorn/prefer-type-error -- Preserve the existing error type.13 unmodified lines71 }72 73 // Both limits are passed to `Math.min()`, so a non-number silently turns every delay into `NaN`, which `setTimeout()` clamps to 1ms. That defeats the whole point of the limits.74 for (const key of ['maxRetryAfter', 'backoffLimit'] as const) {87- const value = normalizedRetry[key];88- if (typeof value !== 'number' || Number.isNaN(value) || value < 0) {75+ if (!isNonNegativeNumber(normalizedRetry[key])) {76 throw new TypeError(`\`retry.${key}\` must be a non-negative number or \`Infinity\``);77 }78 }79 21 unmodified linesmodified:source/utils/options.ts+4 added-8 removed
1 import {kyOptionKeys, requestOptionsRegistry} from '../core/constants.js';2 import type {SearchParamsOption} from '../types/options.js';3-import {deletedParametersSymbol} from './merge.js';3+import {deletedParametersSymbol, type MarkedSearchParameters} from './merge.js';4 5 export const findUnknownOptions = (6 options: Record<string, unknown>,7 ): Record<string, unknown> => {8 const unknownOptions: Record<string, unknown> = {};9 10- for (const key in options) {11- // Skip inherited properties12- if (!Object.hasOwn(options, key)) {13- continue;14- }15-10+ // `Object.keys()` skips inherited properties.11+ for (const key of Object.keys(options)) {12 // Forward every non-standard, non-Ky option to fetch().13 // We intentionally do not check whether the key also exists on `Request`, because some runtimes14 // patch `Request.prototype` with fetch-only extensions. For example, Next.js adds `next`, and the15 // old `key in request` heuristic dropped it unless Ky kept a special-case allowlist.28 unmodified lines44 return search.length > 0;45 }46 47 if (search instanceof URLSearchParams) {52- return search.size > 0 || Boolean((search as any)[deletedParametersSymbol]?.size);48+ return search.size > 0 || Boolean((search as MarkedSearchParameters)[deletedParametersSymbol]?.size);49 }50 51 // Record52 if (typeof search === 'object') {9 unmodified linesmodified:source/utils/timeout.ts+3 added-4 removed
1 import {TimeoutError} from '../errors/TimeoutError.js';2 import type {InternalOptions} from '../types/options.js';3+import {cancelBody} from './body.js';4 5 export type TimeoutOptions = {6 timeout: number;7 fetch: InternalOptions['fetch'];13 unmodified lines21 return await new Promise((resolve, reject) => {22 timeoutId = setTimeout(() => {23 timedOut = true;24 24- if (abortController) {25- abortController.abort();25+ abortController?.abort();26- }26 27 reject(new TimeoutError(request));28 }, options.timeout);29 2 unmodified lines32 const {fetch} = options;33 fetch(request, init).then(response => {34 // A response arriving after the timeout already won is discarded, so its unused body is cancelled. Fire-and-forget: cancellation failures are ignored and never delay the rejection.35 if (timedOut) {37- void response.body?.cancel().catch(() => undefined);36+ cancelBody(response);37 return;38 }39 40 resolve(response);6 unmodified linesmodified:source/utils/type-guards.ts+2 added-1 removed
32 unmodified lines33 }34 ```35 */36 export function isKyError(error: unknown): error is KyError {37- return (error as any)?.isKyError === true || isHTTPError(error) || isNetworkError(error) || isTimeoutError(error) || isForceRetryError(error) || isResponseSizeError(error);37+ // Every Ky error inherits this brand from `KyError`, including one from another realm.38+ return (error as any)?.isKyError === true;39 }40 41 /**42 Type guard to check if an error is an `HTTPError`.113 unmodified linesmodified:source/utils/types.ts-4 removed
1 export type Mutable<T> = {2 -readonly[P in keyof T]: T[P]3 };4-5-export type ObjectEntries<T> = T extends ArrayLike<infer U>6- ? Array<[string, U]>7- : Array<{[K in keyof T]: [K, T[K]]}[keyof T]>;modified:source/index.ts+3 added-7 removed
1 unmodified line2 3 import {Ky} from './core/Ky.js';4 import {5 requestMethods,6- responseTypes,6+ getSupportedResponseTypes,7 stop,8 retry,9 } from './core/constants.js';10 import type {KyInstance} from './types/ky.js';8 unmodified lines19 return Ky.create(input, getOptions());20 } catch (error: unknown) {21 // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors -- A hook can throw any value, and it must be preserved exactly.22 const result = Promise.reject(error) as ResponsePromise;23- for (const type of Object.keys(responseTypes) as Array<keyof typeof responseTypes>) {24- // Matches `Ky.create()`, which only exposes `.bytes()` when the environment implements it.25- if (type === 'bytes' && typeof (globalThis.Response?.prototype as unknown as {bytes?: unknown})?.bytes !== 'function') {23+ // Matches `Ky.create()`, which only exposes `.bytes()` when the environment implements it.24+ for (const type of getSupportedResponseTypes()) {26- continue;27- }28-25 // Returning the same promise marks it as handled, so a body method call does not also report an unhandled rejection.26 result[type] = async () => result as never;27 }28 85 unmodified linesmodified:test/bytes.ts+37 added
41 unmodified lines42 }43 44 await t.throwsAsync(ky(server.url).bytes(), {message: /Bad Request/});45 });46+47+// Support is checked on each call rather than when Ky is imported, so a polyfill added later is picked up, also by the promise that reports a setup error.48+test.serial('.bytes() is offered only while Response.prototype.bytes exists', async t => {49+ const descriptor = Object.getOwnPropertyDescriptor(Response.prototype, 'bytes');50+ t.teardown(() => {51+ Reflect.deleteProperty(Response.prototype, 'bytes');52+ if (descriptor) {53+ Object.defineProperty(Response.prototype, 'bytes', descriptor);54+ }55+ });56+57+ const fetch = async () => new Response('ok');58+59+ Reflect.deleteProperty(Response.prototype, 'bytes');60+61+ const unsupportedPromise = ky('https://example.com', {fetch});62+ const unsupportedSetupErrorPromise = ky('https://example.com', {timeout: -1});63+ t.false('bytes' in unsupportedPromise);64+ t.false('bytes' in unsupportedSetupErrorPromise);65+ await t.throwsAsync(unsupportedSetupErrorPromise);66+ await unsupportedPromise;67+68+ Object.defineProperty(Response.prototype, 'bytes', {69+ configurable: true,70+ writable: true,71+ async value(this: Response) {72+ return new Uint8Array(await this.arrayBuffer());73+ },74+ });75+76+ const supportedPromise = ky('https://example.com', {fetch});77+ const supportedSetupErrorPromise = ky('https://example.com', {timeout: -1});78+ t.true('bytes' in supportedPromise);79+ t.true('bytes' in supportedSetupErrorPromise);80+ await t.throwsAsync(supportedSetupErrorPromise);81+ t.deepEqual([...await supportedPromise.bytes()], [111, 107]);82+});added:test/error-data.ts+240 added
1+import test, {type ExecutionContext} from 'ava';2+import ky, {HTTPError, type Options} from '../source/index.js';3+4+const mebibyte = 1024 * 1024;5+6+const errorResponse = (body: BodyInit | undefined, contentType?: string, status = 400): Response => new Response(body, {7+ status,8+ headers: contentType === undefined ? {} : {'content-type': contentType},9+});10+11+const getHttpError = async (t: ExecutionContext, response: Response, options: Options = {}): Promise<HTTPError> => {12+ const error = await t.throwsAsync(ky('https://example.com', {13+ retry: 0,14+ async fetch() {15+ return response;16+ },17+ ...options,18+ }), {instanceOf: HTTPError});19+20+ return error!;21+};22+23+const getErrorData = async (t: ExecutionContext, body: BodyInit | undefined, contentType?: string): Promise<unknown> => {24+ const error = await getHttpError(t, errorResponse(body, contentType));25+ return error.data;26+};27+28+// Yields `chunkCount` chunks of `chunkSize` bytes followed by an optional tail chunk, and records pulls and cancellation.29+const createChunkedStream = ({chunkCount, chunkSize, tailSize = 0}: {chunkCount: number; chunkSize: number; tailSize?: number}) => {30+ const state = {pulls: 0, cancelled: false};31+ let sentChunks = 0;32+ let sentTail = false;33+ const stream = new ReadableStream<Uint8Array>({34+ pull(controller) {35+ state.pulls++;36+ if (sentChunks < chunkCount) {37+ sentChunks++;38+ controller.enqueue(new Uint8Array(chunkSize).fill(0x61));39+ return;40+ }41+42+ if (tailSize > 0 && !sentTail) {43+ sentTail = true;44+ controller.enqueue(new Uint8Array(tailSize).fill(0x61));45+ return;46+ }47+48+ controller.close();49+ },50+ cancel() {51+ state.cancelled = true;52+ },53+ });54+55+ return {stream, state};56+};57+58+const latin1Cafe = Uint8Array.from([0x63, 0x61, 0x66, 0xE9]);59+60+test('error data is undefined when chunks add up to one byte over the 10 MiB cap', async t => {61+ const {stream} = createChunkedStream({chunkCount: 10, chunkSize: mebibyte, tailSize: 1});62+ t.is(await getErrorData(t, stream, 'text/plain'), undefined);63+});64+65+test('exceeding the error data cap cancels the response stream', async t => {66+ const {stream, state} = createChunkedStream({chunkCount: 1000, chunkSize: mebibyte});67+ t.is(await getErrorData(t, stream, 'text/plain'), undefined);68+ t.true(state.cancelled);69+ t.true(state.pulls < 20);70+});71+72+test('error data is parsed as JSON for the application/x-json subtype', async t => {73+ t.deepEqual(await getErrorData(t, '{"error":"subtype"}', 'application/x-json'), {error: 'subtype'});74+});75+76+test('error data is parsed as JSON when the media type is uppercase', async t => {77+ t.deepEqual(await getErrorData(t, '{"error":"uppercase"}', 'APPLICATION/PROBLEM+JSON'), {error: 'uppercase'});78+});79+80+test('error data is parsed as JSON when whitespace precedes the parameters', async t => {81+ t.deepEqual(await getErrorData(t, '{"error":"spaced"}', 'application/json ; charset=utf-8'), {error: 'spaced'});82+});83+84+test('error data ignores a parameter whose name only ends in charset', async t => {85+ t.is(await getErrorData(t, 'café', 'text/plain; xcharset=utf-16le'), 'café');86+});87+88+test('error data uses a charset that follows other parameters', async t => {89+ t.is(await getErrorData(t, latin1Cafe, 'text/plain; format=flowed; charset=iso-8859-1'), 'café');90+});91+92+test('error data allows whitespace around the charset equals sign', async t => {93+ t.is(await getErrorData(t, latin1Cafe, 'text/plain; charset = iso-8859-1'), 'café');94+});95+96+test('error data charset ends at the comma of a combined content-type header', async t => {97+ const headers = new Headers();98+ headers.append('content-type', 'text/plain; charset=iso-8859-1');99+ headers.append('content-type', 'text/plain');100+ const error = await getHttpError(t, new Response(latin1Cafe, {status: 400, headers}));101+ t.is(error.data, 'café');102+});103+104+test('error data decodes invalid UTF-8 with replacement characters when no charset is given', async t => {105+ t.is(await getErrorData(t, Uint8Array.from([0x61, 0xFF, 0x62]), 'text/plain'), 'a�b');106+});107+108+test('error data is undefined and HTTPError is still thrown when the body stream fails after partial data', async t => {109+ const body = new ReadableStream<Uint8Array>({110+ start(controller) {111+ controller.enqueue(new TextEncoder().encode('partial'));112+ },113+ pull(controller) {114+ controller.error(new Error('connection reset'));115+ },116+ });117+118+ t.is(await getErrorData(t, body, 'text/plain'), undefined);119+});120+121+test('error data is undefined when a response without a body stream fails to read text', async t => {122+ const response = errorResponse('unused', 'text/plain');123+ Object.defineProperty(response, 'body', {value: null});124+ Object.defineProperty(response, 'text', {125+ async value() {126+ throw new TypeError('body unavailable');127+ },128+ });129+130+ const error = await getHttpError(t, response);131+ t.is(error.data, undefined);132+});133+134+test('error.options is a frozen snapshot without Ky-only size and timeout options', async t => {135+ const error = await getHttpError(t, errorResponse('bad', 'text/plain'), {136+ method: 'post',137+ context: {tag: 'value'},138+ timeout: 5000,139+ totalTimeout: 60_000,140+ maxResponseSize: mebibyte,141+ throwHttpErrors: true,142+ });143+144+ t.true(Object.isFrozen(error.options));145+ t.is(error.options.method, 'POST');146+ t.deepEqual(error.options.context, {tag: 'value'});147+ for (const key of ['timeout', 'totalTimeout', 'maxResponseSize', 'throwHttpErrors', 'fetch']) {148+ t.false(Object.hasOwn(error.options, key), key);149+ }150+});151+152+test('the throwHttpErrors predicate is not called for successful responses', async t => {153+ const statuses: number[] = [];154+ const response = await ky('https://example.com', {155+ retry: 0,156+ throwHttpErrors(status) {157+ statuses.push(status);158+ return true;159+ },160+ async fetch() {161+ return new Response('ok', {status: 201});162+ },163+ });164+165+ t.is(await response.text(), 'ok');166+ t.deepEqual(statuses, []);167+});168+169+test('the throwHttpErrors predicate is not called for opaque responses', async t => {170+ let calls = 0;171+ const response = await ky('https://example.com', {172+ retry: 0,173+ throwHttpErrors() {174+ calls++;175+ throw new Error('The predicate must not be called');176+ },177+ async fetch() {178+ const response = new Response(undefined);179+ Object.defineProperty(response, 'type', {value: 'opaque'});180+ Object.defineProperty(response, 'ok', {value: false});181+ Object.defineProperty(response, 'status', {value: 0});182+ return response;183+ },184+ });185+186+ t.is(response.status, 0);187+ t.is(calls, 0);188+});189+190+test('error data is undefined and HTTPError is still thrown when a custom parseJson throws synchronously', async t => {191+ let parseJsonCallCount = 0;192+ const error = await getHttpError(t, errorResponse('{"error":"bad"}', 'application/json'), {193+ parseJson() {194+ parseJsonCallCount++;195+ throw new SyntaxError('Unexpected token');196+ },197+ });198+199+ t.is(error.data, undefined);200+ t.is(parseJsonCallCount, 1);201+});202+203+test('a custom parseJson is not called for an empty JSON error body', async t => {204+ let parseJsonCallCount = 0;205+ const error = await getHttpError(t, errorResponse('', 'application/json'), {206+ parseJson() {207+ parseJsonCallCount++;208+ return {parsed: true};209+ },210+ });211+212+ t.is(error.data, undefined);213+ t.is(parseJsonCallCount, 0);214+});215+216+test('a falsy value from a custom parseJson is kept as the error data', async t => {217+ for (const value of [0, false, '']) {218+ // eslint-disable-next-line no-await-in-loop219+ const error = await getHttpError(t, errorResponse('{"error":"bad"}', 'application/json'), {220+ parseJson: () => value,221+ });222+223+ t.is(error.data, value);224+ }225+});226+227+// `Headers` joins repeated values with a comma. Ky checks the text before the first `;` for a JSON subtype, so without parameters the last media type decides, which agrees with how the Fetch standard extracts a MIME type from a combined header.228+for (const [first, second, expected] of [229+ ['application/json', 'application/json', {error: 'combined'}],230+ ['text/plain', 'application/json', {error: 'combined'}],231+ ['application/json', 'text/plain', '{"error":"combined"}'],232+] as const) {233+ test(`error data for a combined \`${first}, ${second}\` content-type header`, async t => {234+ const headers = new Headers();235+ headers.append('content-type', first);236+ headers.append('content-type', second);237+ const error = await getHttpError(t, new Response('{"error":"combined"}', {status: 400, headers}));238+ t.deepEqual(error.data, expected);239+ });240+}added:test/errors.ts+321 added
1+import {runInNewContext} from 'node:vm';2+import test from 'ava';3+import ky, {4+ ForceRetryError,5+ KyError,6+ NetworkError,7+ ResponseSizeError,8+ SchemaValidationError,9+ TimeoutError,10+ isForceRetryError,11+ isHTTPError,12+ isKyError,13+ isNetworkError,14+ isResponseSizeError,15+ isTimeoutError,16+} from '../source/index.js';17+import {NonError} from '../source/errors/NonError.js';18+import isRawNetworkError from '../source/utils/is-network-error.js';19+import delay from '../source/utils/delay.js';20+21+const url = 'https://example.com/resource';22+23+// Safari reports a network failure as a `TypeError` without a stack.24+const createStacklessTypeError = (message: string): TypeError => {25+ const error = new TypeError(message);26+ error.stack = undefined;27+ return error;28+};29+30+// NonError31+32+test('NonError uses a thrown string as its message', t => {33+ const error = new NonError('Connection reset');34+35+ t.is(error.message, 'Connection reset');36+ t.is(error.value, 'Connection reset');37+ t.is(error.name, 'NonError');38+});39+40+test('NonError uses a default message for a value without a message', t => {41+ const error = new NonError(42);42+43+ t.is(error.message, 'Non-error value was thrown');44+ t.is(error.value, 42);45+});46+47+test('NonError ignores a `message` property that is not a string', t => {48+ const value = {message: 42};49+ const error = new NonError(value);50+51+ t.is(error.message, 'Non-error value was thrown');52+ t.is(error.value, value);53+});54+55+test('NonError falls back to the default message when reading `message` throws', t => {56+ const value = {57+ get message(): string {58+ throw new Error('Getter exploded');59+ },60+ };61+62+ const error = new NonError(value);63+64+ t.is(error.message, 'Non-error value was thrown');65+ t.is(error.value, value);66+});67+68+test('NonError.wrap returns any Error as-is, including one from another realm and a DOMException', t => {69+ const nonError = new NonError('already wrapped');70+71+ for (const error of [72+ new TypeError('local'),73+ runInNewContext('new Error("foreign")') as Error,74+ new DOMException('Aborted', 'AbortError'),75+ nonError,76+ ]) {77+ t.is(NonError.wrap(error), error);78+ }79+});80+81+test('NonError.wrap wraps values that are not errors', t => {82+ const object = {message: 'object message'};83+84+ for (const [value, message] of [85+ ['a string', 'a string'],86+ [object, 'object message'],87+ [undefined, 'Non-error value was thrown'],88+ ] as const) {89+ const wrapped = NonError.wrap(value);90+91+ t.true(wrapped instanceof NonError);92+ t.is((wrapped as NonError).value, value);93+ t.is(wrapped.message, message);94+ }95+});96+97+// ForceRetryError98+99+test('ForceRetryError accepts an infinite delay', t => {100+ t.is(new ForceRetryError({delay: Number.POSITIVE_INFINITY}).customDelay, Number.POSITIVE_INFINITY);101+});102+103+test('ForceRetryError without a cause has no own `cause` property', t => {104+ t.false(Object.hasOwn(new ForceRetryError({code: 'RATE_LIMIT'}), 'cause'));105+ t.false(Object.hasOwn(new ForceRetryError(), 'cause'));106+});107+108+// HTTPError109+110+test('HTTPError message includes a custom request method', async t => {111+ const error = await t.throwsAsync(ky(url, {112+ method: 'PROPFIND',113+ retry: 0,114+ fetch: async () => new Response('', {status: 423, statusText: 'Locked'}),115+ }));116+117+ t.true(isHTTPError(error));118+ t.is(error?.message, `Request failed with status code 423 Locked: PROPFIND ${url}`);119+});120+121+// Other error classes122+123+test('TimeoutError message includes the request method and URL', t => {124+ const request = new Request(url, {method: 'DELETE'});125+ const error = new TimeoutError(request);126+127+ t.is(error.message, `Request timed out: DELETE ${url}`);128+ t.is(error.request, request);129+});130+131+test('ResponseSizeError message includes the limit, method, and URL', t => {132+ const request = new Request(url, {method: 'POST', body: 'x'});133+ const error = new ResponseSizeError(request, 1024);134+135+ t.is(error.message, `Response body exceeded 1024 bytes: POST ${url}`);136+ t.is(error.request, request);137+ t.is(error.maxResponseSize, 1024);138+});139+140+test('KyError is a branded base error with its own name', t => {141+ const error = new KyError('Something in Ky failed');142+143+ t.is(error.name, 'KyError');144+ t.is(error.message, 'Something in Ky failed');145+ t.true(error instanceof Error);146+ t.true(isKyError(error));147+});148+149+// Type guards150+151+test('type guards require the brand to be exactly `true`', t => {152+ for (const brand of [1, 'true', {}]) {153+ const error = Object.assign(new Error('Look-alike'), {name: 'HTTPError', isKyError: brand});154+155+ t.false(isHTTPError(error), `brand: ${JSON.stringify(brand)}`);156+ t.false(isKyError(error), `brand: ${JSON.stringify(brand)}`);157+ }158+});159+160+test('isKyError accepts every Ky error class and any value carrying the exact brand', async t => {161+ const request = new Request(url);162+ const httpError = await t.throwsAsync(ky(url, {163+ retry: 0,164+ fetch: async () => new Response('', {status: 500}),165+ }));166+167+ for (const error of [168+ httpError,169+ new KyError('base'),170+ new NetworkError(request),171+ new TimeoutError(request),172+ new ResponseSizeError(request, 1),173+ new ForceRetryError(),174+ // A copy of Ky in another realm or a duplicated dependency is only recognisable by the brand.175+ runInNewContext('Object.assign(new Error("foreign"), {isKyError: true})') as Error,176+ {isKyError: true},177+ ]) {178+ t.true(isKyError(error), `name: ${String((error as {name?: string}).name)}`);179+ }180+181+ for (const value of [new NonError('thrown'), new SchemaValidationError([{message: 'Invalid'}]), {isKyError: 'true'}]) {182+ t.false(isKyError(value));183+ }184+});185+186+test('type guards return false for values that are not objects', t => {187+ for (const value of [undefined, 0, '', 'HTTPError', true]) {188+ t.false(isKyError(value));189+ t.false(isHTTPError(value));190+ t.false(isNetworkError(value));191+ t.false(isTimeoutError(value));192+ t.false(isForceRetryError(value));193+ t.false(isResponseSizeError(value));194+ }195+});196+197+// Raw network error detection198+199+test('recognizes every exact runtime network error message', t => {200+ for (const message of [201+ 'network error',202+ 'NetworkError when attempting to fetch resource.',203+ 'The Internet connection appears to be offline.',204+ 'Network request failed',205+ 'fetch failed',206+ 'terminated',207+ ' A network error occurred.',208+ 'Network connection lost',209+ 'Failed to fetch',210+ ]) {211+ t.true(isRawNetworkError(new TypeError(message)), `message: ${JSON.stringify(message)}`);212+ }213+});214+215+test('does not recognize look-alike network error messages', t => {216+ for (const message of [217+ 'A network error occurred.',218+ 'Network Error',219+ 'Fetch failed',220+ 'fetch failed.',221+ 'Failed to fetch dynamically imported module: https://example.com/chunk.js',222+ 'Failed to fetch (example.com',223+ 'NetworkError',224+ '',225+ ]) {226+ t.false(isRawNetworkError(new TypeError(message)), `message: ${JSON.stringify(message)}`);227+ }228+});229+230+test('recognizes Chrome `Failed to fetch` with a hostname', t => {231+ t.true(isRawNetworkError(new TypeError('Failed to fetch (api.example.com)')));232+});233+234+test('recognizes a stacked Safari `Load failed` captured by Sentry', t => {235+ t.true(isRawNetworkError(Object.assign(new TypeError('Load failed'), {__sentry_captured__: true})));236+ t.true(isRawNetworkError(Object.assign(new TypeError('Load failed (api.example.com)'), {__sentry_captured__: true})));237+});238+239+test('does not recognize Safari `Load failed` look-alikes without a stack', t => {240+ for (const message of ['Load failed (api.example.com', 'Load failed: script error', 'load failed']) {241+ t.false(isRawNetworkError(createStacklessTypeError(message)), `message: ${JSON.stringify(message)}`);242+ }243+});244+245+test('recognizes Deno network errors only by their prefix', t => {246+ t.true(isRawNetworkError(new TypeError('error sending request for url (https://example.com/): client error (Connect): tcp connect error: Connection refused (os error 61)')));247+ t.false(isRawNetworkError(new TypeError('Upload failed: error sending request for url (https://example.com/)')));248+});249+250+// How Ky turns raw fetch errors into `NetworkError`251+252+test('a network TypeError from another realm becomes a NetworkError with that cause', async t => {253+ const foreignError = runInNewContext('new TypeError("fetch failed")') as TypeError;254+ t.false(foreignError instanceof TypeError);255+256+ const error = await t.throwsAsync(ky(url, {257+ retry: 0,258+ async fetch() {259+ throw foreignError;260+ },261+ }), {instanceOf: NetworkError});262+263+ t.is(error?.cause, foreignError);264+});265+266+test('a NetworkError from a body read reports the request that was sent', async t => {267+ let sent: Request | undefined;268+ const cause = new TypeError('terminated');269+270+ const error = await t.throwsAsync(ky(url, {271+ retry: {limit: 1, delay: () => 0},272+ async fetch(request) {273+ sent = request as Request;274+ return new Response(new ReadableStream({275+ start(controller) {276+ controller.error(cause);277+ },278+ }));279+ },280+ }).text(), {instanceOf: NetworkError});281+282+ t.is(error?.request, sent);283+ t.is(error?.cause, cause);284+});285+286+// `beforeError` processing287+288+test('`beforeError` hooks pass a replacement along and a non-Error result does not undo it', async t => {289+ const replacement = new Error('Replaced');290+ const seen: Error[] = [];291+292+ const error = await t.throwsAsync(ky(url, {293+ retry: 0,294+ fetch: async () => new Response('', {status: 500}),295+ hooks: {296+ beforeError: [297+ () => replacement,298+ ({error}) => {299+ seen.push(error);300+ return 'not an error' as never;301+ },302+ ({error}) => {303+ seen.push(error);304+ },305+ ],306+ },307+ }));308+309+ t.is(error, replacement);310+ t.deepEqual(seen, [replacement, replacement]);311+});312+313+// `delay`314+315+test('delay rejects with the reason of an already aborted signal', async t => {316+ const reason = new Error('Already aborted');317+318+ const error = await t.throwsAsync(delay(0, {signal: AbortSignal.abort(reason)}));319+320+ t.is(error, reason);321+});modified:test/fetch.ts+19 added
219 unmodified lines220 221 t.deepEqual(json, {ok: true, parsedBody: fixture});222 });223 224+// Ky cancels the request body once the request settles, and canceling a stream that a reader still holds rejects, so that rejection must not reach the caller.225+test('a custom fetch that locks a stream request body without reading it still resolves', async t => {226+ const text = await ky.post(fixture, {227+ body: new ReadableStream<Uint8Array>({228+ start(controller) {229+ controller.enqueue(new TextEncoder().encode('payload'));230+ controller.close();231+ },232+ }),233+ retry: 0,234+ async fetch(request) {235+ (request as Request).body!.getReader();236+ return new Response('ok');237+ },238+ }).text();239+240+ t.is(text, 'ok');241+});242+243 test('unknown options are passed to fetch', async t => {244 t.plan(1);245 246 const options = {next: {revalidate: 3600}};733 unmodified linesmodified:test/hooks.ts+585 added
341 unmodified lines342 t.is(text, 'retried');343 t.is(attempts, 3);344 });345 346+test('ky.retry() accepts a Request-like object tagged as Request and sends it', async t => {347+ const sent: unknown[] = [];348+ let retryRequest: unknown;349+350+ const result = await ky('https://example.com', {351+ retry: {limit: 1, delay: () => 0},352+ async fetch(input) {353+ sent.push(input);354+ return new Response(sent.length === 1 ? 'first' : 'second');355+ },356+ hooks: {357+ afterResponse: [({request, retryCount}) => {358+ if (retryCount > 0) {359+ return undefined;360+ }361+362+ retryRequest = createRequestLike(withHeader(request, 'x-retry', 'yes'));363+ return ky.retry({request: retryRequest as Request});364+ }],365+ },366+ }).text();367+368+ t.is(result, 'second');369+ t.is(sent.length, 2);370+ t.is(sent[1], retryRequest);371+ t.is((sent[1] as Request).headers.get('x-retry'), 'yes');372+});373+374 test('beforeRequest hook allows modifications', async t => {375 const server = await createHttpTestServer(t);376 server.post('/', async (request, response) => {377 response.json(request.body);164 unmodified lines542 543 t.is(responseText, 'ok');544 });545 546+test('afterResponse hook can return a Response-like replacement', async t => {547+ let secondHookText: string | undefined;548+549+ const result = await ky('https://example.com', {550+ fetch: async () => new Response('original'),551+ hooks: {552+ afterResponse: [553+ () => createResponseLike(new Response('replacement')),554+ async ({response}) => {555+ secondHookText = await response.text();556+ },557+ ],558+ },559+ }).text();560+561+ t.is(result, 'replacement');562+ t.is(secondHookText, 'replacement');563+});564+565+test('afterResponse hook can return a clone of the response it was given', async t => {566+ const chunks = ['first ', 'second ', 'third'];567+568+ const result = await ky('https://example.com', {569+ async fetch() {570+ let index = 0;571+ // Sends one chunk per pull, so cancelling the wrong branch would cut the body short.572+ return new Response(new ReadableStream<Uint8Array>({573+ pull(controller) {574+ const chunk = chunks[index];575+ index++;576+ if (chunk === undefined) {577+ controller.close();578+ } else {579+ controller.enqueue(new TextEncoder().encode(chunk));580+ }581+ },582+ }));583+ },584+ hooks: {585+ afterResponse: [({response}) => response.clone()],586+ },587+ }).text();588+589+ t.is(result, chunks.join(''));590+});591+592+test('onDownloadProgress reports the body of an afterResponse replacement', async t => {593+ const transferredBytes: number[] = [];594+595+ const result = await ky('https://example.com', {596+ fetch: async () => new Response('original body'),597+ onDownloadProgress(progress) {598+ transferredBytes.push(progress.transferredBytes);599+ },600+ hooks: {601+ afterResponse: [() => new Response('replacement')],602+ },603+ }).text();604+605+ t.is(result, 'replacement');606+ t.is(transferredBytes.at(-1), 'replacement'.length);607+});608+609 test('afterResponse hook can wrap the provided body in a new response', async t => {610 const responseText = await ky('https://example.com', {611 fetch: async () => new Response('ok', {612 headers: {127 unmodified lines740 t.true(originalResponse?.bodyUsed);741 t.true(clonedResponse?.bodyUsed);742 });743 744+test('afterResponse hook forced retry releases the response body and its clone', async t => {745+ let fetchCount = 0;746+ let didCancel = false;747+748+ const result = await ky('https://example.com', {749+ retry: {limit: 1, delay: () => 0},750+ async fetch() {751+ fetchCount++;752+ if (fetchCount > 1) {753+ return new Response('ok');754+ }755+756+ // The source is only cancelled once both the response and the clone given to the hook are cancelled.757+ return new Response(new ReadableStream({758+ cancel() {759+ didCancel = true;760+ },761+ }));762+ },763+ hooks: {764+ afterResponse: [({retryCount}) => retryCount === 0 ? ky.retry() : undefined],765+ },766+ }).text();767+768+ await delay(0);769+ t.is(result, 'ok');770+ t.is(fetchCount, 2);771+ t.true(didCancel);772+});773+774+for (const outcome of ['returns nothing', 'throws', 'forces a retry'] as const) {775+ test(`afterResponse hook that locks its clone and ${outcome} does not break the request`, async t => {776+ const hookError = new Error('hook failed');777+ let fetchCount = 0;778+779+ const request = ky('https://example.com', {780+ retry: {limit: 1, delay: () => 0},781+ async fetch() {782+ fetchCount++;783+ return new Response('ok');784+ },785+ hooks: {786+ afterResponse: [({response, retryCount}) => {787+ response.body?.getReader();788+789+ if (outcome === 'throws') {790+ throw hookError;791+ }792+793+ return outcome === 'forces a retry' && retryCount === 0 ? ky.retry() : undefined;794+ }],795+ },796+ }).text();797+798+ if (outcome === 'throws') {799+ await t.throwsAsync(request, {is: hookError});800+ } else {801+ t.is(await request, 'ok');802+ }803+804+ t.is(fetchCount, outcome === 'forces a retry' ? 2 : 1);805+ });806+}807+808 test('afterResponse hook accepts failed response', async t => {809 const server = await createHttpTestServer(t);810 server.post('/', async (request, response) => {811 response.status(500).send(request.body);423 unmodified lines1235 t.true(result instanceof TimeoutError);1236 t.true(didAbort);1237 });1238 1239+test('totalTimeout during an afterResponse hook releases the fetched body and the response the hook returns later', async t => {1240+ let didHookStart = false;1241+ let didCancelFetchedBody = false;1242+ let didCancelHookBody = false;1243+ const {promise: hookResult, resolve: resolveHook} = Promise.withResolvers<Response>();1244+1245+ await t.throwsAsync(ky('https://example.com', {1246+ totalTimeout: 500,1247+ fetch: async () => new Response(new ReadableStream({1248+ cancel() {1249+ didCancelFetchedBody = true;1250+ },1251+ })),1252+ hooks: {1253+ afterResponse: [async () => {1254+ didHookStart = true;1255+ return hookResult;1256+ }],1257+ },1258+ }).text(), {instanceOf: TimeoutError});1259+1260+ resolveHook(new Response(new ReadableStream({1261+ cancel() {1262+ didCancelHookBody = true;1263+ },1264+ })));1265+ await delay(0);1266+1267+ t.true(didHookStart);1268+ t.true(didCancelFetchedBody);1269+ t.true(didCancelHookBody);1270+});1271+1272 test('beforeRequest hook runs only once and does not run again on retry', async t => {1273 let fetchCallCount = 0;1274 let beforeRequestCallCount = 0;1275 const beforeRequestRetryCounts: number[] = [];798 unmodified lines2074 t.false(fetchCalled);2075 t.is(response, expectedResponse);2076 });2077 2078+test('beforeRequest hook returning a Response skips the remaining beforeRequest hooks', async t => {2079+ let laterHookCalled = false;2080+2081+ const result = await ky('https://example.com', {2082+ fetch: async () => new Response('fetched'),2083+ hooks: {2084+ beforeRequest: [2085+ () => new Response('cached'),2086+ () => {2087+ laterHookCalled = true;2088+ },2089+ ],2090+ },2091+ }).text();2092+2093+ t.is(result, 'cached');2094+ t.false(laterHookCalled);2095+});2096+2097 test('hooks beforeRequest returning Response skips HTTP Request', async t => {2098 const expectedResponse = 'empty hook';2099 2100 const response = await ky200 unmodified lines2301 },2302 });2303 });2304 2305+test('options passed to afterResponse, beforeRetry, and beforeError hooks are frozen, also after a request replacement', async t => {2306+ const frozen: Record<string, boolean[]> = {afterResponse: [], beforeRetry: [], beforeError: []};2307+2308+ await t.throwsAsync(ky('https://example.com', {2309+ retry: {limit: 1, delay: () => 0},2310+ fetch: async () => new Response('error', {status: 500}),2311+ hooks: {2312+ afterResponse: [({options}) => {2313+ frozen.afterResponse!.push(Object.isFrozen(options));2314+ }],2315+ beforeRetry: [({request, options}) => {2316+ frozen.beforeRetry!.push(Object.isFrozen(options));2317+ return withHeader(request, 'x-retry', '1');2318+ }],2319+ beforeError: [({options, error}) => {2320+ frozen.beforeError!.push(Object.isFrozen(options));2321+ return error;2322+ }],2323+ },2324+ }).text(), {instanceOf: HTTPError});2325+2326+ t.deepEqual(frozen, {afterResponse: [true, true], beforeRetry: [true], beforeError: [true]});2327+});2328+2329 test('afterResponse hook receives retryCount in state parameter', async t => {2330 let requestCount = 0;2331 const retryCounts: number[] = [];2332 1432 unmodified lines3765 3766 t.is(requestCount, 3); // Initial request + 2 retries (limit reached)3767 });3768 3769+test('afterResponse hook sees the retry count of each forced retry', async t => {3770+ const retryCounts: number[] = [];3771+ let fetchCount = 0;3772+3773+ const result = await ky('https://example.com', {3774+ retry: {limit: 2, delay: () => 0},3775+ async fetch() {3776+ fetchCount++;3777+ return new Response(`attempt ${fetchCount}`);3778+ },3779+ hooks: {3780+ afterResponse: [({retryCount}) => {3781+ retryCounts.push(retryCount);3782+ return retryCount < 2 ? ky.retry() : undefined;3783+ }],3784+ },3785+ }).text();3786+3787+ t.is(result, 'attempt 3');3788+ t.deepEqual(retryCounts, [0, 1, 2]);3789+});3790+3791+test('beforeRetry returning `ky.stop` after a forced retry resolves without another attempt', async t => {3792+ let fetchCount = 0;3793+ let afterResponseCount = 0;3794+3795+ const response = await ky('https://example.com', {3796+ retry: {limit: 2, delay: () => 0},3797+ async fetch() {3798+ fetchCount++;3799+ return new Response('ok');3800+ },3801+ hooks: {3802+ afterResponse: [() => {3803+ afterResponseCount++;3804+ return ky.retry();3805+ }],3806+ beforeRetry: [() => ky.stop],3807+ },3808+ });3809+3810+ t.is(response, undefined);3811+ t.is(fetchCount, 1);3812+ t.is(afterResponseCount, 1);3813+});3814+3815 test('afterResponse hook forced retry is observable in beforeRetry', async t => {3816 let requestCount = 0;3817 let beforeRetryCallCount = 0;3818 let errorName: string | undefined;1791 unmodified lines5610 // Force retry → 500 (retried via HTTP error path) → 2005611 t.is(fetchCallCount, 2);5612 });5613 5614+for (const hook of ['beforeRequest', 'beforeRetry'] as const) {5615+ test(`afterResponse hook that makes a ${hook} Response fail throws without retrying`, async t => {5616+ let fetchCount = 0;5617+ let afterResponseCount = 0;5618+5619+ const error = await t.throwsAsync<HTTPError>(ky('https://example.com', {5620+ retry: {limit: 3, delay: () => 0},5621+ async fetch() {5622+ fetchCount++;5623+ if (hook === 'beforeRetry') {5624+ throw new TypeError('fetch failed');5625+ }5626+5627+ return new Response('fetched');5628+ },5629+ hooks: {5630+ [hook]: [() => new Response('cached')],5631+ afterResponse: [({response}) => {5632+ afterResponseCount++;5633+ return response.status === 200 ? new Response('bad', {status: 500}) : undefined;5634+ }],5635+ },5636+ }).text(), {instanceOf: HTTPError});5637+5638+ t.is(error?.response.status, 500);5639+ t.is(fetchCount, hook === 'beforeRequest' ? 0 : 1);5640+ t.is(afterResponseCount, 1);5641+ });5642+5643+ test(`a failing Response-like object from ${hook} is not retried`, async t => {5644+ let fetchCount = 0;5645+ let hookCount = 0;5646+5647+ const error = await t.throwsAsync<HTTPError>(ky('https://example.com', {5648+ retry: {limit: 2, delay: () => 0},5649+ async fetch() {5650+ fetchCount++;5651+ throw new TypeError('fetch failed');5652+ },5653+ hooks: {5654+ [hook]: [() => {5655+ hookCount++;5656+ return createResponseLike(new Response('nope', {status: 500}));5657+ }],5658+ },5659+ }).text(), {instanceOf: HTTPError});5660+5661+ t.is(error?.response.status, 500);5662+ t.is(fetchCount, hook === 'beforeRequest' ? 0 : 1);5663+ t.is(hookCount, 1);5664+ });5665+}5666+5667+test('a failing beforeRetry Response reached through a forced retry is not retried again', async t => {5668+ let fetchCount = 0;5669+ let beforeRetryCount = 0;5670+5671+ const error = await t.throwsAsync<HTTPError>(ky('https://example.com', {5672+ retry: {limit: 3, delay: () => 0},5673+ async fetch() {5674+ fetchCount++;5675+ return new Response('ok');5676+ },5677+ hooks: {5678+ afterResponse: [({retryCount}) => retryCount === 0 ? ky.retry() : undefined],5679+ beforeRetry: [() => {5680+ beforeRetryCount++;5681+ return new Response('nope', {status: 500});5682+ }],5683+ },5684+ }).text(), {instanceOf: HTTPError});5685+5686+ t.is(error?.response.status, 500);5687+ t.is(fetchCount, 1);5688+ t.is(beforeRetryCount, 1);5689+});5690+5691+test('a beforeRetry Response does not stop later fetched responses from being retried', async t => {5692+ let fetchCount = 0;5693+ let usedCache = false;5694+ let forcedRetry = false;5695+5696+ const result = await ky('https://example.com', {5697+ retry: {limit: 3, delay: () => 0},5698+ async fetch() {5699+ fetchCount++;5700+ if (fetchCount === 1) {5701+ throw new TypeError('fetch failed');5702+ }5703+5704+ return fetchCount === 2 ? new Response('error', {status: 500}) : new Response('fresh');5705+ },5706+ hooks: {5707+ beforeRetry: [() => {5708+ if (usedCache) {5709+ return undefined;5710+ }5711+5712+ usedCache = true;5713+ return new Response('cached');5714+ }],5715+ afterResponse: [({response}) => {5716+ if (forcedRetry || !response.ok) {5717+ return undefined;5718+ }5719+5720+ forcedRetry = true;5721+ return ky.retry();5722+ }],5723+ },5724+ }).text();5725+5726+ t.is(result, 'fresh');5727+ t.is(fetchCount, 3);5728+});5729+5730+test('a beforeRetry Response counts as a retry for afterResponse and beforeError hooks', async t => {5731+ const afterResponseRetryCounts: number[] = [];5732+ let beforeErrorRetryCount: number | undefined;5733+5734+ await t.throwsAsync(ky('https://example.com', {5735+ retry: {limit: 2, delay: () => 0},5736+ async fetch() {5737+ throw new TypeError('fetch failed');5738+ },5739+ hooks: {5740+ beforeRetry: [() => new Response('nope', {status: 500})],5741+ afterResponse: [({retryCount}) => {5742+ afterResponseRetryCounts.push(retryCount);5743+ }],5744+ beforeError: [({error, retryCount}) => {5745+ beforeErrorRetryCount = retryCount;5746+ return error;5747+ }],5748+ },5749+ }).text(), {instanceOf: HTTPError});5750+5751+ t.deepEqual(afterResponseRetryCounts, [1]);5752+ t.is(beforeErrorRetryCount, 1);5753+});5754+5755+test('HTTPError for a failing beforeRequest Response carries the parsed body as data', async t => {5756+ const error = await t.throwsAsync<HTTPError>(ky('https://example.com', {5757+ fetch: async () => new Response('fetched'),5758+ hooks: {5759+ beforeRequest: [() => Response.json({message: 'from cache'}, {status: 404})],5760+ },5761+ }).text(), {instanceOf: HTTPError});5762+5763+ t.is(error?.response.status, 404);5764+ t.deepEqual(error?.data, {message: 'from cache'});5765+});5766+5767+test('`parseJson` gets the replaced request for a `Response` from `beforeRequest`', async t => {5768+ let parseJsonRequest: Request | undefined;5769+ let hookRequest: Request | undefined;5770+5771+ const data = await ky('https://example.com', {5772+ fetch: async () => new Response('{"fetched":true}'),5773+ parseJson(text, {request}) {5774+ parseJsonRequest = request;5775+ return JSON.parse(text);5776+ },5777+ hooks: {5778+ beforeRequest: [5779+ ({request}) => withHeader(request, 'x-hook', '1'),5780+ ({request}) => {5781+ hookRequest = request;5782+ return new Response('{"cached":true}');5783+ },5784+ ],5785+ },5786+ }).json();5787+5788+ t.deepEqual(data, {cached: true});5789+ t.is(parseJsonRequest?.headers.get('x-hook'), '1');5790+ t.is(parseJsonRequest, hookRequest);5791+});5792+5793 test('second afterResponse hook does not run when first throws, and no retry occurs', async t => {5794 let requestCount = 0;5795 let secondHookCalled = false;5796 const server = await createHttpTestServer(t);447 unmodified lines6244 6245 t.deepEqual(seenLimits, [2, 2]);6246 });6247 6248+test('init hook copy of retry keeps function values by reference', async t => {6249+ let fetchCount = 0;6250+ let shouldRetryCount = 0;6251+ let delayCount = 0;6252+ const seenFunctions: unknown[] = [];6253+6254+ const shouldRetry = () => {6255+ shouldRetryCount++;6256+ return true;6257+ };6258+6259+ const retryDelay = () => {6260+ delayCount++;6261+ return 0;6262+ };6263+6264+ const result = await ky('https://example.com', {6265+ retry: {limit: 1, shouldRetry, delay: retryDelay},6266+ async fetch() {6267+ fetchCount++;6268+ return fetchCount === 1 ? new Response('error', {status: 500}) : new Response('ok');6269+ },6270+ hooks: {6271+ init: [options => {6272+ const retry = options.retry as {shouldRetry: unknown; delay: unknown};6273+ seenFunctions.push(retry.shouldRetry, retry.delay);6274+ }],6275+ },6276+ }).text();6277+6278+ t.is(result, 'ok');6279+ t.is(seenFunctions[0], shouldRetry);6280+ t.is(seenFunctions[1], retryDelay);6281+ t.is(shouldRetryCount, 1);6282+ t.is(delayCount, 1);6283+});6284+6285+test('init hook can change a frozen retry config without changing the source', async t => {6286+ const retry = Object.freeze({6287+ limit: 2,6288+ methods: Object.freeze(['get'] as const),6289+ delay: () => 0,6290+ });6291+ const seenRetries: Array<{limit: number; methods: string[]}> = [];6292+ let fetchCount = 0;6293+6294+ const api = ky.extend({6295+ retry,6296+ async fetch() {6297+ fetchCount++;6298+ return new Response('error', {status: 500});6299+ },6300+ hooks: {6301+ init: [options => {6302+ const retryOptions = options.retry as {limit: number; methods: string[]};6303+ seenRetries.push({limit: retryOptions.limit, methods: [...retryOptions.methods]});6304+ retryOptions.limit = 0;6305+ retryOptions.methods.push('post');6306+ }],6307+ },6308+ });6309+6310+ await t.throwsAsync(api.get('https://example.com'), {instanceOf: HTTPError});6311+ await t.throwsAsync(api.get('https://example.com'), {instanceOf: HTTPError});6312+6313+ t.is(fetchCount, 2);6314+ t.deepEqual(seenRetries, [{limit: 2, methods: ['get']}, {limit: 2, methods: ['get']}]);6315+ t.is(retry.limit, 2);6316+ t.deepEqual(retry.methods, ['get']);6317+ t.true(Object.isFrozen(retry.methods));6318+});6319+6320 test('init hook nested retry mutations do not leak across requests', async t => {6321 const seenMethods: string[][] = [];6322 6323 const api = ky.extend({1180 unmodified lines7504 t.is((error as {request?: unknown}).request, sent, `retry: ${retry}`);7505 }7506 });7507 7508+test('error.request for a beforeRequest Response is the request after hook replacement', async t => {7509+ let hookRequest: Request | undefined;7510+ let beforeErrorRequest: Request | undefined;7511+ let fetchCount = 0;7512+7513+ const error = await t.throwsAsync<HTTPError>(ky('https://example.com', {7514+ retry: 0,7515+ async fetch() {7516+ fetchCount++;7517+ return new Response('fetched');7518+ },7519+ hooks: {7520+ beforeRequest: [7521+ ({request}) => new Request(request, {headers: {'x-hook': '1'}}),7522+ ({request}) => {7523+ hookRequest = request;7524+ return new Response('nope', {status: 500});7525+ },7526+ ],7527+ beforeError: [({request, error}) => {7528+ beforeErrorRequest = request;7529+ return error;7530+ }],7531+ },7532+ }).text(), {instanceOf: HTTPError});7533+7534+ t.is(fetchCount, 0);7535+ t.is(error?.request.headers.get('x-hook'), '1');7536+ t.is(error?.request, hookRequest);7537+ t.is(beforeErrorRequest, hookRequest);7538+});7539+7540+test('error.request for a failing response from afterResponse is the request that was sent', async t => {7541+ const sent: Request[] = [];7542+ let beforeErrorRequest: Request | undefined;7543+7544+ const error = await t.throwsAsync<HTTPError>(ky('https://example.com', {7545+ // A retry limit makes Ky prepare a clone of the request before sending, which must not be reported.7546+ retry: {limit: 1, statusCodes: [503], delay: () => 0},7547+ async fetch(input) {7548+ sent.push(input as Request);7549+ return new Response('ok');7550+ },7551+ hooks: {7552+ afterResponse: [() => new Response('bad', {status: 500})],7553+ beforeError: [({request, error}) => {7554+ beforeErrorRequest = request;7555+ return error;7556+ }],7557+ },7558+ }).text(), {instanceOf: HTTPError});7559+7560+ t.is(sent.length, 1);7561+ t.is(error?.request, sent[0]);7562+ t.is(beforeErrorRequest, sent[0]);7563+});7564+7565 test('a `beforeError` hook receives the request that failed during a body read', async t => {7566 let sent: Request | undefined;7567 const hookRequests: Array<Request | undefined> = [];7568 495 unmodified linesmodified:test/http-error.ts+144 added-1 removed
1-import test from 'ava';1+import {setImmediate} from 'node:timers/promises';2+import test, {type ExecutionContext} from 'ava';3 import {expectTypeOf} from 'expect-type';4 import ky, {HTTPError, isHTTPError, TimeoutError} from '../source/index.js';5 import {type Mutable} from '../source/utils/types.js';6 import {createHttpTestServer} from './helpers/create-http-test-server.js';799 unmodified lines806 807 // The predicate's own error is what the hook sees, unchanged.808 t.deepEqual(seen, [thrown]);809 });810+811+test('an error JSON parse that times out still lets the retry go ahead', async t => {812+ let requestCount = 0;813+ const {promise: neverSettles} = Promise.withResolvers<never>();814+815+ const text = await ky('https://example.com', {816+ timeout: 200,817+ retry: {limit: 1, delay: () => 0},818+ parseJson: async () => neverSettles,819+ async fetch() {820+ requestCount++;821+ return requestCount === 1822+ ? new Response('{"error":"slow parse"}', {status: 500, headers: {'content-type': 'application/json'}})823+ : new Response('ok');824+ },825+ }).text();826+827+ t.is(text, 'ok');828+ t.is(requestCount, 2);829+});830+831+/*832+Tracks the timers created until the test ends. A timer stops being active once it fires or is cleared.833+834+The tests that use this are serial, and AVA runs serial tests before concurrent ones, so every tracked timer comes from the request under test or the test itself.835+*/836+const trackActiveTimers = (t: ExecutionContext) => {837+ const originalSetTimeout = globalThis.setTimeout;838+ const originalClearTimeout = globalThis.clearTimeout;839+ const state = {840+ createdCount: 0,841+ active: new Set<unknown>(),842+ };843+844+ globalThis.setTimeout = ((handler: (...arguments_: unknown[]) => void, milliseconds?: number, ...arguments_: unknown[]) => {845+ state.createdCount++;846+ const timeoutId = originalSetTimeout((...handlerArguments: unknown[]) => {847+ state.active.delete(timeoutId);848+ handler(...handlerArguments);849+ }, milliseconds, ...arguments_);850+ state.active.add(timeoutId);851+ return timeoutId;852+ }) as typeof globalThis.setTimeout;853+854+ globalThis.clearTimeout = ((timeoutId?: Parameters<typeof globalThis.clearTimeout>[0]) => {855+ state.active.delete(timeoutId);856+ originalClearTimeout(timeoutId);857+ }) as typeof globalThis.clearTimeout;858+859+ t.teardown(() => {860+ globalThis.setTimeout = originalSetTimeout;861+ globalThis.clearTimeout = originalClearTimeout;862+ });863+864+ return state;865+};866+867+const assertNoActiveTimers = async (t: ExecutionContext, timers: ReturnType<typeof trackActiveTimers>) => {868+ // Some timers are cleared in a `finally` callback that runs a few microtasks after the request settles.869+ await setImmediate();870+ t.true(timers.createdCount > 0, 'the request should have created timers');871+ t.is(timers.active.size, 0, `${timers.active.size} of ${timers.createdCount} timers are still active`);872+};873+874+const jsonErrorResponse = () => new Response('{"error":"failure"}', {status: 500, headers: {'content-type': 'application/json'}});875+876+test.serial('no timer is left behind after an HTTPError with JSON data', async t => {877+ const timers = trackActiveTimers(t);878+879+ const error = await t.throwsAsync(ky('https://example.com', {880+ retry: 0,881+ fetch: async () => jsonErrorResponse(),882+ }), {instanceOf: HTTPError});883+884+ t.deepEqual(error?.data, {error: 'failure'});885+ await assertNoActiveTimers(t, timers);886+});887+888+test.serial('no timer is left behind after hooks and a body read are raced against totalTimeout', async t => {889+ const timers = trackActiveTimers(t);890+891+ const text = await ky('https://example.com', {892+ totalTimeout: 60_000,893+ fetch: async () => new Response('ok'),894+ hooks: {895+ beforeRequest: [() => undefined],896+ afterResponse: [() => undefined],897+ },898+ }).text();899+900+ t.is(text, 'ok');901+ await assertNoActiveTimers(t, timers);902+});903+904+test.serial('no timer is left behind after shouldRetry and beforeRetry are raced against totalTimeout', async t => {905+ const timers = trackActiveTimers(t);906+ let requestCount = 0;907+908+ const text = await ky('https://example.com', {909+ totalTimeout: 60_000,910+ retry: {911+ limit: 1,912+ delay: () => 0,913+ shouldRetry: () => true,914+ },915+ async fetch() {916+ requestCount++;917+ return requestCount === 1 ? jsonErrorResponse() : new Response('ok');918+ },919+ hooks: {920+ beforeRetry: [() => undefined],921+ },922+ }).text();923+924+ t.is(text, 'ok');925+ t.is(requestCount, 2);926+ await assertNoActiveTimers(t, timers);927+});928+929+test.serial('no timer is left behind after a user abort during the retry delay', async t => {930+ const timers = trackActiveTimers(t);931+ const controller = new AbortController();932+ const reason = new Error('Cancelled during the delay');933+934+ const error = await t.throwsAsync(ky('https://example.com', {935+ signal: controller.signal,936+ retry: {937+ limit: 1,938+ delay() {939+ // `retry.delay` runs just before the wait starts, so this fires once Ky is waiting.940+ setTimeout(() => {941+ controller.abort(reason);942+ }, 0);943+ return 60_000;944+ },945+ },946+ fetch: async () => jsonErrorResponse(),947+ }));948+949+ t.is(error, reason);950+ await assertNoActiveTimers(t, timers);951+});modified:test/main.ts+19 added
993 unmodified lines994 995 t.is(requestCount, 1);996 });997 998+// A timer created with an infinite delay fires after 1ms, so without any timeout Ky must not create one for the fetch or the body read.999+test('`timeout: false` without totalTimeout does not time out a slow fetch or a slow body read', async t => {1000+ const text = await ky('https://example.com', {1001+ timeout: false,1002+ async fetch() {1003+ await delay(50);1004+ return new Response(new ReadableStream({1005+ async pull(controller) {1006+ await delay(50);1007+ controller.enqueue(new TextEncoder().encode('slow'));1008+ controller.close();1009+ },1010+ }, {highWaterMark: 0}));1011+ },1012+ }).text();1013+1014+ t.is(text, 'slow');1015+});1016+1017 test('invalid timeout option', async t => {1018 // #1171019 let requestCount = 0;1020 3346 unmodified linesadded:test/merge.ts+389 added
1+import test from 'ava';2+import ky, {replaceOption, type Hooks} from '../source/index.js';3+import {validateAndMerge} from '../source/utils/merge.js';4+5+const echoUrl = async (request: Request) => new Response(request.url);6+const echoBody = async (request: Request) => new Response(await request.text());7+const echoHeaders = async (request: Request) => new Response(JSON.stringify(Object.fromEntries(request.headers)));8+9+// `cloneDeep`10+11+test('an `init` hook mutating an object inside a `json` array does not leak into the next request', async t => {12+ const bodies: string[] = [];13+ const api = ky.create({14+ json: {items: [{count: 1}]},15+ async fetch(request) {16+ bodies.push(await request.text());17+ return new Response('ok');18+ },19+ hooks: {20+ init: [21+ options => {22+ (options.json as {items: Array<{count: number}>}).items[0]!.count++;23+ },24+ ],25+ },26+ });27+28+ await api.post('https://example.com');29+ await api.post('https://example.com');30+31+ t.deepEqual(bodies, ['{"items":[{"count":2}]}', '{"items":[{"count":2}]}']);32+});33+34+test('an own `__proto__` key in `json` survives the `init` hook copy', async t => {35+ const json: unknown = JSON.parse('{"__proto__":{"a":1},"b":2}');36+37+ const body = await ky.post('https://example.com', {38+ json,39+ fetch: echoBody,40+ hooks: {41+ init: [() => undefined],42+ },43+ }).text();44+45+ t.is(body, '{"__proto__":{"a":1},"b":2}');46+});47+48+test('a nested non-enumerable `json` property is not sent, even when an `init` hook copies the body', async t => {49+ const nested: Record<string, unknown> = {visible: 1};50+ Object.defineProperty(nested, 'hidden', {value: 2, enumerable: false});51+52+ for (const init of [[], [() => undefined]]) {53+ // eslint-disable-next-line no-await-in-loop54+ const body = await ky.post('https://example.com', {55+ json: {nested},56+ fetch: echoBody,57+ hooks: {init},58+ }).text();59+60+ t.is(body, '{"nested":{"visible":1}}');61+ }62+});63+64+test('the `init` hook copy of `json` keeps nested symbol-keyed values', async t => {65+ const symbol = Symbol('meta');66+ let seen: unknown;67+68+ await ky.post('https://example.com', {69+ json: {nested: {[symbol]: 'meta', value: 1}},70+ fetch: async () => new Response('ok'),71+ hooks: {72+ init: [73+ options => {74+ seen = (options.json as {nested: Record<symbol, unknown>}).nested[symbol];75+ },76+ ],77+ },78+ });79+80+ t.is(seen, 'meta');81+});82+83+// Headers84+85+test('the string "undefined" in header pairs is sent as a value instead of removing the header', async t => {86+ const api = ky.create({headers: {'x-a': '1', 'x-b': '1'}, fetch: echoHeaders});87+88+ const headers = await api('https://example.com', {89+ headers: [['x-a', 'undefined']],90+ }).json<Record<string, string>>();91+92+ t.is(headers['x-a'], 'undefined');93+ t.is(headers['x-b'], '1');94+});95+96+test('the string "undefined" in a plain object header is sent as a value instead of removing the header', async t => {97+ const api = ky.create({headers: {'x-a': '1'}, fetch: echoHeaders});98+99+ const headers = await api('https://example.com', {100+ headers: {'x-a': 'undefined'},101+ }).json<Record<string, string>>();102+103+ t.is(headers['x-a'], 'undefined');104+});105+106+test('an `init` hook sees a header removed with `undefined` as a lowercase key with an `undefined` value', async t => {107+ let initHeaders: Record<string, string | undefined> | undefined;108+ const api = ky.create({headers: {'X-Removed': '1', 'X-Kept': '1'}}).extend({headers: {'X-REMOVED': undefined}});109+110+ const headers = await api('https://example.com', {111+ fetch: echoHeaders,112+ hooks: {113+ init: [114+ options => {115+ initHeaders = {...options.headers as Record<string, string | undefined>};116+ },117+ ],118+ },119+ }).json<Record<string, string>>();120+121+ t.true(Object.hasOwn(initHeaders!, 'x-removed'));122+ t.deepEqual(initHeaders, {'x-removed': undefined, 'x-kept': '1'});123+ t.false('x-removed' in headers);124+});125+126+test('repeated header pairs replace an inherited value and keep every repeated value', async t => {127+ const api = ky.create({headers: {'x-a': '0'}, fetch: echoHeaders});128+129+ const headers = await api('https://example.com', {130+ headers: [['x-a', '1'], ['x-a', '2']],131+ }).json<Record<string, string>>();132+133+ t.is(headers['x-a'], '1, 2');134+});135+136+test('a plain object header replaces every value of a repeated header in a `Headers` default', async t => {137+ const api = ky.create({headers: new Headers([['x-a', '1'], ['x-a', '2']]), fetch: echoHeaders});138+139+ const replaced = await api('https://example.com', {headers: {'x-a': '3'}}).json<Record<string, string>>();140+ const kept = await api('https://example.com', {headers: {'x-b': '3'}}).json<Record<string, string>>();141+142+ t.is(replaced['x-a'], '3');143+ t.is(kept['x-a'], '1, 2');144+});145+146+test('merging does not rewrite nested user data with a `headers` key', async t => {147+ const api = ky.create({json: {headers: {'X-Name': 'a'}}, fetch: echoBody}).extend({json: {headers: {'x-other': 'b'}}});148+149+ t.is(await api.post('https://example.com').text(), '{"headers":{"X-Name":"a","x-other":"b"}}');150+});151+152+// Search parameters153+154+test('a merged `URLSearchParams` layer removes the keys it deleted from the layers merged before it', t => {155+ const merged = validateAndMerge({searchParams: {a: '0'}}, {searchParams: {a: undefined, b: '2'}}).searchParams as URLSearchParams;156+ const result = validateAndMerge({searchParams: {a: '1', c: '3'}}, {searchParams: merged}).searchParams as URLSearchParams;157+158+ t.is(result.toString(), 'c=3&b=2');159+});160+161+test('extending a string `searchParams` default with an `undefined` key removes the key from the default and the input URL', async t => {162+ const api = ky.create({searchParams: 'a=1&b=2', fetch: echoUrl}).extend({searchParams: {a: undefined}});163+164+ t.is(await api('https://example.com/?a=0&z=9').text(), 'https://example.com/?z=9&b=2');165+});166+167+test('`searchParams: undefined` clears inherited search parameters', async t => {168+ const api = ky.create({searchParams: {a: '1'}, fetch: echoUrl});169+ const extended = api.extend({searchParams: undefined});170+171+ t.is(await extended('https://example.com/?keep=1').text(), 'https://example.com/?keep=1');172+ t.is(await api('https://example.com', {searchParams: undefined}).text(), 'https://example.com/');173+ t.is(await extended('https://example.com', {searchParams: {b: '2'}}).text(), 'https://example.com/?b=2');174+});175+176+test('`searchParams: null` over inherited search parameters gets an error naming the option', async t => {177+ const api = ky.create({searchParams: {a: '1'}, fetch: echoUrl});178+ const expectation = {instanceOf: TypeError, message: 'The `searchParams` option must not be `null`. Use `undefined` to clear it.'};179+180+ t.throws(() => api.extend({searchParams: null as never}), expectation);181+ await t.throwsAsync(api('https://example.com', {searchParams: null as never}).text(), expectation);182+});183+184+test('merging search parameter pairs over defaults rejects an entry that is not a pair', async t => {185+ const api = ky.create({searchParams: {a: '1'}, fetch: echoUrl});186+187+ // A pair that is not an array, and an array that is not a pair.188+ for (const searchParameters of [['a=1'], [['a', '1', '2']]]) {189+ // eslint-disable-next-line no-await-in-loop190+ await t.throwsAsync(api('https://example.com', {searchParams: searchParameters as never}).text(), {191+ instanceOf: TypeError,192+ message: 'Array search parameters must be provided in [[key, value], ...] format',193+ }, `searchParams: ${JSON.stringify(searchParameters)}`);194+ }195+});196+197+// `replaceOption`198+199+test('resolving a nested `replaceOption` does not change the caller\'s options object', t => {200+ const marker = replaceOption({ttl: 60});201+ const cloudflare = {cacheTtlByStatus: marker};202+ const options: Record<string, unknown> = {cf: cloudflare};203+204+ const merged = validateAndMerge({cf: {cacheTtlByStatus: {old: 1}}}, options) as Record<string, unknown>;205+ const unmerged = validateAndMerge(options) as Record<string, unknown>;206+207+ t.deepEqual(merged.cf, {cacheTtlByStatus: {ttl: 60}});208+ t.deepEqual(unmerged.cf, {cacheTtlByStatus: {ttl: 60}});209+ t.is(cloudflare.cacheTtlByStatus, marker);210+ t.not(unmerged.cf, cloudflare);211+});212+213+test('resolving `replaceOption` inside an array copies only that array and leaves the caller\'s marker in place', t => {214+ const marker = replaceOption(2);215+ const list = [1, marker, 3];216+ const unmarked = [4];217+218+ const merged = validateAndMerge({list, unmarked}) as Record<string, unknown>;219+220+ t.deepEqual(merged.list, [1, 2, 3]);221+ t.not(merged.list, list);222+ t.is(list[1], marker);223+ t.is(merged.unmarked, unmarked);224+});225+226+test('`replaceOption` wrappers nested in `context` are not walked, so large context values are left alone', async t => {227+ const large = new Proxy({}, {228+ ownKeys() {229+ throw new Error('The context value was walked');230+ },231+ });232+233+ t.is(await ky('https://example.com', {234+ context: {large},235+ fetch: async () => new Response('ok'),236+ }).text(), 'ok');237+});238+239+// Hooks240+241+test('`replaceOption(undefined)` on a single hook type clears only that hook type', async t => {242+ const calls: string[] = [];243+ const api = ky.create({244+ fetch: async () => new Response('ok'),245+ hooks: {246+ beforeRequest: [247+ () => {248+ calls.push('beforeRequest');249+ },250+ ],251+ afterResponse: [252+ () => {253+ calls.push('afterResponse');254+ },255+ ],256+ },257+ }).extend({hooks: {beforeRequest: replaceOption(undefined as Hooks['beforeRequest'])}});258+259+ await api('https://example.com');260+261+ t.deepEqual(calls, ['afterResponse']);262+});263+264+test('`beforeRetry` hooks from the instance, an extension and the request run in that order', async t => {265+ const calls: string[] = [];266+ const hook = (name: string) => () => {267+ calls.push(name);268+ };269+270+ let attempts = 0;271+ const api = ky.create({272+ retry: {limit: 1, delay: () => 0},273+ async fetch() {274+ attempts++;275+ return new Response('', {status: attempts === 1 ? 500 : 200});276+ },277+ hooks: {beforeRetry: [hook('instance')]},278+ }).extend({hooks: {beforeRetry: [hook('extension')]}});279+280+ await api('https://example.com', {hooks: {beforeRetry: [hook('request')]}});281+282+ t.deepEqual(calls, ['instance', 'extension', 'request']);283+});284+285+// `context`286+287+test('merging `context` copies only enumerable properties', async t => {288+ const context: Record<string, unknown> = {visible: 1};289+ Object.defineProperty(context, 'hidden', {value: 2, enumerable: false});290+ let seen: Record<string, unknown> | undefined;291+292+ await ky.create({context: {base: 0}})('https://example.com', {293+ context,294+ fetch: async () => new Response('ok'),295+ hooks: {296+ beforeRequest: [297+ ({options}) => {298+ seen = options.context;299+ },300+ ],301+ },302+ });303+304+ t.deepEqual(seen, {base: 0, visible: 1});305+ t.false('hidden' in seen!);306+});307+308+// `create` and `extend`309+310+test('mutating an inherited `URLSearchParams` inside an `extend` callback does not change the parent instance', async t => {311+ const parent = ky.create({searchParams: new URLSearchParams('a=1'), fetch: echoUrl});312+313+ parent.extend(options => {314+ (options.searchParams as URLSearchParams).append('child', '1');315+ return {};316+ });317+318+ t.is(await parent('https://example.com').text(), 'https://example.com/?a=1');319+});320+321+test('the function form of `.extend()` on the root `ky` receives an empty object', t => {322+ let received: unknown;323+ ky.extend(options => {324+ received = options;325+ return {};326+ });327+328+ t.deepEqual(received, {});329+});330+331+test('the function form of `.extend()` is called once when extending, not for every request', async t => {332+ let calls = 0;333+ const api = ky.create({fetch: async () => new Response('ok')}).extend(() => {334+ calls++;335+ return {};336+ });337+338+ t.is(calls, 1);339+ await api('https://example.com');340+ await api('https://example.com');341+ t.is(calls, 1);342+});343+344+test('`.create()` on an instance does not inherit that instance\'s defaults', async t => {345+ const parent = ky.create({headers: {'x-parent': '1'}, searchParams: {parent: '1'}});346+ const created = parent.create({fetch: echoHeaders});347+348+ const headers = await created('https://example.com').json<Record<string, string>>();349+ t.false('x-parent' in headers);350+ t.is(await created('https://example.com', {fetch: echoUrl}).text(), 'https://example.com/');351+});352+353+test('a method shortcut wins over a `method` in the request options and the defaults', async t => {354+ const api = ky.create({method: 'put', fetch: async request => new Response(request.method)});355+356+ t.is(await api.post('https://example.com', {method: 'patch'}).text(), 'POST');357+ t.is(await api.delete('https://example.com').text(), 'DELETE');358+ t.is(await api('https://example.com', {method: 'patch'}).text(), 'PATCH');359+ t.is(await api('https://example.com').text(), 'PUT');360+});361+362+test('the function form of `.extend()` appends hooks after the parent hooks', async t => {363+ const calls: string[] = [];364+ const parent = ky.create({365+ fetch: async () => new Response('ok'),366+ hooks: {367+ beforeRequest: [368+ () => {369+ calls.push('parent');370+ },371+ ],372+ },373+ });374+375+ const child = parent.extend(() => ({376+ hooks: {377+ beforeRequest: [378+ () => {379+ calls.push('child');380+ },381+ ],382+ },383+ }));384+385+ await child('https://example.com');386+ await parent('https://example.com');387+388+ t.deepEqual(calls, ['parent', 'child', 'parent']);389+});modified:test/normalize.ts+29 added-1 removed
1 import test from 'ava';2-import {normalizeRetryOptions} from '../source/utils/normalize.js';2+import {normalizeRetryMethod, normalizeRetryOptions} from '../source/utils/normalize.js';3 4 test('retry shorthand and object options produce independent default arrays', t => {5 const expected = normalizeRetryOptions();6 19 unmodified lines26 message: `retry.${key} must be an array`,27 });28 }29 });30+31+test('retry validation accepts a disabled jitter', t => {32+ t.false(normalizeRetryOptions({jitter: false}).jitter);33+});34+35+test('retry method normalization lowercases standard methods and preserves custom methods', t => {36+ for (const [method, expected] of [37+ ['GET', 'get'],38+ ['OPTIONS', 'options'],39+ ['TRACE', 'trace'],40+ ['Purge', 'Purge'],41+ ]) {42+ t.is(normalizeRetryMethod(method), expected);43+ }44+45+ t.deepEqual(normalizeRetryOptions({methods: ['TRACE', 'Purge'] as never}).methods, ['trace', 'Purge']);46+});47+48+test('retry limit validation accepts negative zero', t => {49+ t.notThrows(() => normalizeRetryOptions(-0));50+ t.notThrows(() => normalizeRetryOptions({limit: -0}));51+});52+53+test('retry validation accepts zero for maxRetryAfter and backoffLimit', t => {54+ const normalized = normalizeRetryOptions({maxRetryAfter: 0, backoffLimit: 0});55+ t.is(normalized.maxRetryAfter, 0);56+ t.is(normalized.backoffLimit, 0);57+});added:test/request-construction.ts+405 added
1+import test from 'ava';2+import ky from '../source/index.js';3+4+// Each test sends the request to a custom `fetch` that records it, so no server is needed.5+const createRecordingFetch = () => {6+ const requests: Request[] = [];7+ const inits: Array<Record<string, unknown>> = [];8+9+ const fetch = async (request: Request, init: Record<string, unknown>) => {10+ requests.push(request);11+ inits.push(init);12+ return new Response('ok');13+ };14+15+ return {fetch: fetch as unknown as typeof globalThis.fetch, requests, inits};16+};17+18+// The URL parser removes a tab or newline anywhere in the input, so `h\rttps:` is still the `https:` scheme and must be rejected like `h\tttps:`.19+test('baseUrl rejects a slashless HTTP URL with a carriage return inside the scheme', async t => {20+ const {fetch, requests} = createRecordingFetch();21+22+ for (const input of ['h\rttps:example.com/collect', 'ht\rtp:example.com/collect']) {23+ // eslint-disable-next-line no-await-in-loop24+ await t.throwsAsync(ky(input, {baseUrl: 'https://trusted.test/api/', fetch, retry: 0}), {25+ instanceOf: TypeError,26+ message: '`input` url protocol must be followed by `//` when using `baseUrl`',27+ }, `input: ${JSON.stringify(input)}`);28+ }29+30+ t.is(requests.length, 0);31+});32+33+// The check only guards `baseUrl` resolution. Without a `baseUrl`, the input goes to the `Request` constructor, which parses a slashless special scheme as an absolute URL.34+test('a slashless HTTP URL is allowed without baseUrl', async t => {35+ const {fetch, requests} = createRecordingFetch();36+37+ await ky('https:example.com/users', {fetch, retry: 0});38+39+ t.is(requests[0]!.url, 'https://example.com/users');40+});41+42+// Only leading C0 control or space characters are stripped, like the URL parser does. A space inside the input stays, so `ht tp:` is not a scheme and the input is a relative path.43+test('baseUrl resolves an input with a space before the colon as a relative path', async t => {44+ const {fetch, requests} = createRecordingFetch();45+46+ await ky('ht tp:example.com/collect', {baseUrl: 'https://trusted.test/api/', fetch, retry: 0});47+48+ t.is(requests[0]!.url, 'https://trusted.test/api/ht%20tp:example.com/collect');49+});50+51+// An absolute input bypasses `baseUrl` completely, so a `baseUrl` that cannot be resolved in Node.js is never used. Each case reaches a different part of the absolute input check.52+for (const [description, input, expectedUrl] of [53+ ['an uppercase scheme', 'HTTPS://example.com/users', 'https://example.com/users'],54+ ['a scheme with a digit, plus, dot and hyphen', 'web+x-app.v2://example.com/users', 'web+x-app.v2://example.com/users'],55+ ['leading whitespace', ' https://example.com/users', 'https://example.com/users'],56+ ['a tab inside the scheme', 'ht\ttps://example.com/users', 'https://example.com/users'],57+] as const) {58+ test(`an absolute input with ${description} bypasses baseUrl`, async t => {59+ const {fetch, requests} = createRecordingFetch();60+61+ await ky(input, {baseUrl: '/api/', fetch, retry: 0});62+63+ t.is(requests[0]!.url, expectedUrl);64+ });65+}66+67+test('prefix is not applied to a URL input', async t => {68+ const {fetch, requests} = createRecordingFetch();69+70+ await ky(new URL('https://example.com/users'), {prefix: 'https://other.test/api/', fetch, retry: 0});71+72+ t.is(requests[0]!.url, 'https://example.com/users');73+});74+75+test('prefix is not applied to a Request input', async t => {76+ const {fetch, requests} = createRecordingFetch();77+78+ await ky(new Request('https://example.com/users'), {prefix: 'https://other.test/api/', fetch, retry: 0});79+80+ t.is(requests[0]!.url, 'https://example.com/users');81+});82+83+// `prefix` is joined to the input before `baseUrl` resolves it, so a slashless scheme in the prefix gets the same check as one in the input.84+test('baseUrl rejects a slashless HTTP URL that comes from prefix', async t => {85+ const {fetch, requests} = createRecordingFetch();86+87+ await t.throwsAsync(ky('users', {88+ prefix: 'https:evil.test',89+ baseUrl: 'https://trusted.test/',90+ fetch,91+ retry: 0,92+ }), {93+ instanceOf: TypeError,94+ message: '`input` url protocol must be followed by `//` when using `baseUrl`',95+ });96+97+ t.is(requests.length, 0);98+});99+100+test('an absolute prefix makes the input absolute, so baseUrl is ignored', async t => {101+ const {fetch, requests} = createRecordingFetch();102+103+ await ky('users', {104+ prefix: 'https://a.test/v1',105+ baseUrl: 'https://b.test/root/',106+ fetch,107+ retry: 0,108+ });109+110+ t.is(requests[0]!.url, 'https://a.test/v1/users');111+});112+113+test('a root-relative prefix resolves against the origin of baseUrl', async t => {114+ const {fetch, requests} = createRecordingFetch();115+116+ await ky('users', {117+ prefix: '/v1/',118+ baseUrl: 'https://example.com/api/',119+ fetch,120+ retry: 0,121+ });122+123+ t.is(requests[0]!.url, 'https://example.com/v1/users');124+});125+126+for (const [description, input, expectedUrl] of [127+ ['a parent path', '../users', 'https://example.com/users'],128+ ['only a query', '?page=2', 'https://example.com/api/items?page=2'],129+ ['only a hash', '#top', 'https://example.com/api/items?page=1#top'],130+] as const) {131+ test(`baseUrl resolves an input with ${description} like the URL parser`, async t => {132+ const {fetch, requests} = createRecordingFetch();133+134+ await ky(input, {baseUrl: 'https://example.com/api/items?page=1', fetch, retry: 0});135+136+ t.is(requests[0]!.url, expectedUrl);137+ });138+}139+140+test('object searchParams add a value to a key that is already in the input URL', async t => {141+ const {fetch, requests} = createRecordingFetch();142+143+ await ky('https://example.com/?tag=a', {searchParams: {tag: 'b'}, fetch, retry: 0});144+145+ t.deepEqual(new URL(requests[0]!.url).searchParams.getAll('tag'), ['a', 'b']);146+});147+148+// `URLSearchParams#delete()` serializes the whole query again even when the key is missing, which would turn `%20` into `+` and `?flag` into `?flag=`, and rebuild the request with the changed URL.149+for (const input of ['https://example.com/?q=a%20b', 'https://example.com/?flag', 'https://example.com/?a=1;b=2']) {150+ test(`object searchParams with only an undefined value for a missing key leave ${input} unchanged`, async t => {151+ const {fetch, requests} = createRecordingFetch();152+153+ await ky(input, {searchParams: {missing: undefined}, fetch, retry: 0});154+155+ t.is(requests[0]!.url, input);156+ });157+}158+159+test('object searchParams with an undefined value for a missing key keep the body of a Request input with a non-canonical query', async t => {160+ const input = new Request('https://example.com/?q=a%20b', {method: 'POST', body: 'payload'});161+162+ await ky(input, {163+ searchParams: {missing: undefined},164+ keepalive: true,165+ retry: 0,166+ async fetch(request) {167+ t.is((request as Request).url, 'https://example.com/?q=a%20b');168+ t.is(await (request as Request).text(), 'payload');169+ return new Response('ok');170+ },171+ });172+});173+174+test('object searchParams with an undefined value still remove that key from the input URL', async t => {175+ const {fetch, requests} = createRecordingFetch();176+177+ await ky('https://example.com/?a=1&b=2', {searchParams: {a: undefined}, fetch, retry: 0});178+179+ t.is(requests[0]!.url, 'https://example.com/?b=2');180+});181+182+test('string searchParams only strip a leading question mark', async t => {183+ const {fetch, requests} = createRecordingFetch();184+185+ await ky('https://example.com/', {searchParams: 'q=why?', fetch, retry: 0});186+187+ t.is(requests[0]!.url, 'https://example.com/?q=why?');188+});189+190+// An `undefined` value removes its key from the input URL, and every other value is appended after the input query in the order of the object.191+test('object searchParams that mix removals and additions keep the order of the input URL and the object', async t => {192+ const {fetch, requests} = createRecordingFetch();193+194+ await ky('https://example.com/?a=1&b=2&c=3', {searchParams: {b: undefined, d: '4', a: '5'}, fetch, retry: 0});195+196+ t.is(requests[0]!.url, 'https://example.com/?a=1&c=3&d=4&a=5');197+});198+199+test('an undefined value in object searchParams removes every value of that key', async t => {200+ const {fetch, requests} = createRecordingFetch();201+202+ await ky('https://example.com/?a=1&b=2&a=3', {searchParams: {a: undefined}, fetch, retry: 0});203+204+ t.is(requests[0]!.url, 'https://example.com/?b=2');205+});206+207+test('object searchParams send falsy and non-string values as strings', async t => {208+ const {fetch, requests} = createRecordingFetch();209+210+ await ky('https://example.com/', {211+ searchParams: {212+ zero: 0,213+ no: false,214+ yes: true,215+ fraction: 1.5,216+ },217+ fetch,218+ retry: 0,219+ });220+221+ t.is(requests[0]!.url, 'https://example.com/?zero=0&no=false&yes=true&fraction=1.5');222+});223+224+test('object searchParams encode reserved characters, so a value cannot add another parameter', async t => {225+ const {fetch, requests} = createRecordingFetch();226+227+ await ky('https://example.com/', {searchParams: {q: 'a b&c=d', 'k y': 'v'}, fetch, retry: 0});228+229+ t.is(requests[0]!.url, 'https://example.com/?q=a+b%26c%3Dd&k+y=v');230+});231+232+test('searchParams pairs and URLSearchParams keep every value of a repeated key after the input query', async t => {233+ const {fetch, requests} = createRecordingFetch();234+235+ await ky('https://example.com/?x=1', {searchParams: [['a', '1'], ['a', '2'], ['b', '3']], fetch, retry: 0});236+ await ky('https://example.com/?a=0', {searchParams: new URLSearchParams([['a', '1'], ['a', '2']]), fetch, retry: 0});237+238+ t.is(requests[0]!.url, 'https://example.com/?x=1&a=1&a=2&b=3');239+ t.is(requests[1]!.url, 'https://example.com/?a=0&a=1&a=2');240+});241+242+test('string searchParams with a leading question mark are joined to the input query with an ampersand', async t => {243+ const {fetch, requests} = createRecordingFetch();244+245+ await ky('https://example.com/?a=1', {searchParams: '?b=2&c', fetch, retry: 0});246+247+ t.is(requests[0]!.url, 'https://example.com/?a=1&b=2&c');248+});249+250+test('string searchParams are appended without encoding the input query or themselves again', async t => {251+ const {fetch, requests} = createRecordingFetch();252+253+ await ky('https://example.com/?q=a%20b', {searchParams: 'r=c+d&s=e%20f', fetch, retry: 0});254+255+ t.is(requests[0]!.url, 'https://example.com/?q=a%20b&r=c+d&s=e%20f');256+});257+258+for (const [input, expectedUrl] of [259+ ['https://example.com/path#hash', 'https://example.com/path?a=1#hash'],260+ ['https://example.com/path?x=1#hash', 'https://example.com/path?x=1&a=1#hash'],261+] as const) {262+ test(`string searchParams go before the hash of ${input}`, async t => {263+ const {fetch, requests} = createRecordingFetch();264+265+ await ky(input, {searchParams: 'a=1', fetch, retry: 0});266+267+ t.is(requests[0]!.url, expectedUrl);268+ });269+}270+271+for (const [description, searchParameters] of [272+ ['an empty string', ''],273+ ['a lone question mark', '?'],274+ ['an empty object', {}],275+ ['an empty URLSearchParams', new URLSearchParams()],276+ ['an empty array', []],277+] as const) {278+ test(`searchParams with ${description} leave a non-canonical input URL unchanged`, async t => {279+ const {fetch, requests} = createRecordingFetch();280+281+ await ky('https://example.com/?q=a%20b', {searchParams: searchParameters, fetch, retry: 0});282+283+ t.is(requests[0]!.url, 'https://example.com/?q=a%20b');284+ });285+}286+287+// `.extend()` stores an `undefined` key as a deletion marker on the merged `URLSearchParams`, which must only touch an input URL that has the key, like an `undefined` value in the request options.288+test('a deletion marker from .extend() only rewrites an input URL that has the key', async t => {289+ const {fetch, requests} = createRecordingFetch();290+ const api = ky.create({searchParams: {a: '1'}}).extend({searchParams: {a: undefined}});291+292+ await api('https://example.com/?q=a%20b', {fetch, retry: 0});293+ await api('https://example.com/?a=0&b=2', {fetch, retry: 0});294+295+ t.is(requests[0]!.url, 'https://example.com/?q=a%20b');296+ t.is(requests[1]!.url, 'https://example.com/?b=2');297+});298+299+// The `Request` input's `content-type` comes from its own body, so it must not describe a replacement `URLSearchParams` body.300+test('a URLSearchParams body replaces the content-type of a Request input', async t => {301+ const {fetch, requests} = createRecordingFetch();302+ const input = new Request('https://example.com/', {method: 'POST', body: 'plain'});303+304+ await ky(input, {body: new URLSearchParams({a: '1'}), fetch, retry: 0});305+306+ t.is(requests[0]!.headers.get('content-type'), 'application/x-www-form-urlencoded;charset=UTF-8');307+});308+309+test('a content-type from the headers option is kept for a FormData body on a Request input', async t => {310+ const {fetch, requests} = createRecordingFetch();311+ const input = new Request('https://example.com/', {method: 'POST', body: 'plain'});312+ const body = new FormData();313+ body.append('field', 'value');314+315+ await ky(input, {316+ body,317+ headers: {'content-type': 'multipart/form-data; boundary=custom'},318+ fetch,319+ retry: 0,320+ });321+322+ t.is(requests[0]!.headers.get('content-type'), 'multipart/form-data; boundary=custom');323+});324+325+// The `Request` constructor only normalizes the methods the Fetch standard lists, so a lowercase `query` on a `Request` input is still lowercase when Ky reads it.326+test('a standard method from a Request input is uppercased', async t => {327+ const {fetch, requests} = createRecordingFetch();328+ const input = new Request('https://example.com/', {method: 'query'});329+ t.is(input.method, 'query');330+331+ await ky(input, {fetch, retry: 0});332+333+ t.is(requests[0]!.method, 'QUERY');334+});335+336+// Option merging rejects an array `context`, but an `init` hook assigns straight onto the options object.337+test('an init hook that sets context to an array gets an error naming the option', async t => {338+ const {fetch, requests} = createRecordingFetch();339+340+ await t.throwsAsync(ky('https://example.com', {341+ fetch,342+ hooks: {343+ init: [options => {344+ options.context = [] as never;345+ }],346+ },347+ }), {348+ instanceOf: TypeError,349+ message: 'The `context` option must be an object',350+ });351+352+ t.is(requests.length, 0);353+});354+355+// Standard request options are already applied to the `Request`, so repeating them in the init object would let `fetch()` apply them a second time.356+test('fetch does not receive standard request options in its init object', async t => {357+ const {fetch, requests, inits} = createRecordingFetch();358+359+ await ky.post('https://example.com', {360+ body: 'body',361+ headers: {'x-custom': 'value'},362+ mode: 'cors',363+ credentials: 'include',364+ cache: 'no-store',365+ redirect: 'manual',366+ referrer: 'about:client',367+ referrerPolicy: 'no-referrer',368+ integrity: 'sha256-47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=',369+ keepalive: false,370+ signal: new AbortController().signal,371+ window: undefined,372+ priority: 'low',373+ fetch,374+ retry: 0,375+ });376+377+ t.is(requests[0]!.integrity, 'sha256-47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=');378+ t.deepEqual(Object.keys(inits[0]!), ['priority']);379+});380+381+test('fetch does not receive Ky options in its init object', async t => {382+ const {fetch, inits} = createRecordingFetch();383+384+ await ky.post('users', {385+ json: {a: 1},386+ parseJson: JSON.parse,387+ stringifyJson: JSON.stringify,388+ searchParams: {page: 1},389+ baseUrl: 'https://example.com/',390+ prefix: 'api',391+ retry: 0,392+ timeout: 1000,393+ totalTimeout: 2000,394+ maxResponseSize: 1000,395+ hooks: {},396+ throwHttpErrors: true,397+ onDownloadProgress: () => undefined,398+ onUploadProgress: () => undefined,399+ context: {token: 'secret'},400+ dispatcher: 'agent',401+ fetch,402+ } as never);403+404+ t.deepEqual(Object.keys(inits[0]!), ['dispatcher']);405+});added:test/resilience.ts+1117 added
1+import {once} from 'node:events';2+import {setTimeout as delay} from 'node:timers/promises';3+import test from 'ava';4+import ky, {5+ HTTPError,6+ NetworkError,7+ TimeoutError,8+ type Options,9+} from '../source/index.js';10+import {createHttpTestServer} from './helpers/create-http-test-server.js';11+12+/*13+Scenarios adapted from the HTTP resilience comparison at https://fetchkit.org/http-resilience/14+15+Every cancellation and deadline test checks the same contract:16+- The caller settles promptly, not when the wait would have ended.17+- Nothing reaches the transport after the cancellation.18+- A hung attempt sees its signal aborted.19+- The next request on the same instance still works.20+*/21+22+const url = 'https://example.com/resource';23+24+type Step =25+ | {status?: number; body?: string; headers?: HeadersInit}26+ | 'hang'27+ | Error;28+29+// A fetch that serves `steps` in order, records what each attempt sent, and fails loudly on an unexpected attempt. Every call counts as an attempt, even one with an aborted signal, so a stray dispatch after a cancellation is visible.30+function scriptedFetch(steps: Step[]) {31+ const transport = {32+ attempts: 0,33+ active: 0,34+ aborted: 0,35+ requests: [] as Request[],36+ bodies: [] as string[],37+ async fetch(input: RequestInfo | URL): Promise<Response> {38+ if (!(input instanceof Request)) {39+ throw new TypeError('Expected Ky to call fetch with a Request');40+ }41+42+ const step = steps[transport.attempts++];43+ transport.requests.push(input);44+45+ // Like native fetch, an aborted signal rejects before anything is sent.46+ input.signal.throwIfAborted();47+48+ transport.active++;49+50+ try {51+ transport.bodies.push(input.body ? await input.text() : '');52+53+ if (step === undefined) {54+ throw new Error(`Unexpected attempt ${transport.attempts}`);55+ }56+57+ if (step === 'hang') {58+ if (!input.signal.aborted) {59+ await once(input.signal, 'abort');60+ }61+62+ transport.aborted++;63+ input.signal.throwIfAborted();64+ }65+66+ if (step instanceof Error) {67+ throw step;68+ }69+70+ const {status = 200, body = '', headers = {}} = step as Exclude<Step, 'hang' | Error>;71+ return new Response(body, {status, headers});72+ } finally {73+ transport.active--;74+ }75+ },76+ };77+78+ return transport;79+}80+81+// Tracks a promise without awaiting it, so a test can check whether it has settled yet.82+function observe<T>(promise: Promise<T>) {83+ const state: {settled: boolean; value?: T; error?: unknown} = {settled: false};84+ void (async () => {85+ try {86+ state.value = await promise;87+ } catch (error) {88+ state.error = error;89+ } finally {90+ state.settled = true;91+ }92+ })();93+94+ return state;95+}96+97+const busy = (body = 'busy'): Step => ({status: 503, body});98+const ready = (body = 'ready'): Step => ({body});99+const networkError = () => new TypeError('fetch failed');100+101+// Options shared by the scripted scenarios: fixed delays, no jitter, and no per-attempt timeout unless a test sets one.102+function client(transport: ReturnType<typeof scriptedFetch>, options: Options = {}) {103+ return ky.create({104+ fetch: transport.fetch,105+ timeout: false,106+ ...options,107+ retry: {108+ limit: 2,109+ delay: () => 20,110+ jitter: false,111+ ...(typeof options.retry === 'object' ? options.retry : {}),112+ },113+ });114+}115+116+// Basic retry contract117+118+test('recovers after two 503 responses with exactly three attempts and no later dispatch', async t => {119+ const transport = scriptedFetch([busy(), busy(), ready()]);120+121+ t.is(await client(transport)(url).text(), 'ready');122+ t.is(transport.attempts, 3);123+124+ await delay(100);125+ t.is(transport.attempts, 3);126+ t.is(transport.active, 0);127+});128+129+test('retry exhaustion rejects with the response of the last attempt', async t => {130+ const transport = scriptedFetch([busy('busy-1'), busy('busy-2'), busy('busy-3')]);131+132+ const error = await t.throwsAsync(client(transport)(url).text(), {instanceOf: HTTPError});133+ t.is(error.response.status, 503);134+ t.is(error.data, 'busy-3');135+ t.is(transport.attempts, 3);136+137+ await delay(100);138+ t.is(transport.attempts, 3);139+});140+141+test('retry: 0 makes exactly one attempt and rejects with its response', async t => {142+ const transport = scriptedFetch([busy('only')]);143+144+ const error = await t.throwsAsync(client(transport, {retry: {limit: 0}})(url).text(), {instanceOf: HTTPError});145+ t.is(error.data, 'only');146+ t.is(transport.attempts, 1);147+148+ await delay(100);149+ t.is(transport.attempts, 1);150+});151+152+test('recovers after two network errors with exactly three attempts', async t => {153+ const transport = scriptedFetch([networkError(), networkError(), ready()]);154+155+ t.is(await client(transport)(url).text(), 'ready');156+ t.is(transport.attempts, 3);157+});158+159+test('recovers across different failure kinds in one retry sequence', async t => {160+ const transport = scriptedFetch([busy(), networkError(), {status: 500}, {status: 429}, ready()]);161+162+ t.is(await client(transport, {retry: {limit: 4}})(url).text(), 'ready');163+ t.is(transport.attempts, 5);164+});165+166+test('exhaustion after a network error rejects with a NetworkError that keeps the last raw error', async t => {167+ const last = networkError();168+ const transport = scriptedFetch([busy(), networkError(), last]);169+170+ const error = await t.throwsAsync(client(transport)(url), {instanceOf: NetworkError});171+ t.is(error.cause, last);172+ t.is(transport.attempts, 3);173+});174+175+test('an exhausted request does not affect the next request on the same instance', async t => {176+ const transport = scriptedFetch([busy(), busy(), busy(), ready('next')]);177+ const api = client(transport);178+179+ await t.throwsAsync(api(url), {instanceOf: HTTPError});180+ t.is(await api(url).text(), 'next');181+ t.is(transport.attempts, 4);182+});183+184+test('every attempt reaches the transport with the same method, URL and headers', async t => {185+ const transport = scriptedFetch([busy(), networkError(), ready()]);186+187+ await client(transport)(url, {headers: {'x-trace': 'abc'}, searchParams: {page: 2}});188+189+ t.is(transport.requests.length, 3);190+ for (const request of transport.requests) {191+ t.is(request.method, 'GET');192+ t.is(request.url, `${url}?page=2`);193+ t.is(request.headers.get('x-trace'), 'abc');194+ }195+});196+197+test('every attempt gets its own Request with an unaborted signal', async t => {198+ const transport = scriptedFetch([busy(), busy(), ready()]);199+200+ await client(transport)(url);201+202+ const [first, second, third] = transport.requests;203+ t.not(first, second);204+ t.not(second, third);205+ for (const request of transport.requests) {206+ t.false(request.signal.aborted);207+ }208+});209+210+// Retry + abort during backoff211+212+test('aborting during the backoff settles promptly with the abort reason and dispatches nothing more', async t => {213+ const transport = scriptedFetch([busy(), ready('healthy'), ready('healthy')]);214+ const api = client(transport, {retry: {delay: () => 1000}});215+ const controller = new AbortController();216+217+ const result = observe(api(url, {signal: controller.signal}).text());218+ await delay(20);219+ controller.abort();220+ await delay(50);221+222+ t.true(result.settled, 'Cancellation must settle during the backoff');223+ t.is(result.error, controller.signal.reason);224+225+ await delay(1100);226+ t.is(transport.attempts, 1, 'No dispatch after cancellation');227+228+ t.is(await api(url).text(), 'healthy');229+ t.is(transport.attempts, 2);230+ t.is(transport.active, 0);231+});232+233+test('aborting during the default exponential backoff settles promptly', async t => {234+ const transport = scriptedFetch([busy()]);235+ const controller = new AbortController();236+237+ // The first default delay is 300ms.238+ const result = observe(ky(url, {239+ fetch: transport.fetch, timeout: false, retry: {limit: 2, jitter: false}, signal: controller.signal,240+ }).text());241+ await delay(20);242+ controller.abort();243+ await delay(50);244+245+ t.true(result.settled);246+ t.is(result.error, controller.signal.reason);247+248+ await delay(400);249+ t.is(transport.attempts, 1);250+});251+252+test('aborting during the second backoff stops after two attempts', async t => {253+ const transport = scriptedFetch([busy(), busy(), ready()]);254+ const controller = new AbortController();255+ const api = client(transport, {retry: {delay: attemptCount => attemptCount === 1 ? 10 : 1000}});256+257+ const result = observe(api(url, {signal: controller.signal}));258+ await delay(100);259+ t.is(transport.attempts, 2);260+ controller.abort();261+ await delay(50);262+263+ t.true(result.settled);264+ t.is(result.error, controller.signal.reason);265+266+ await delay(1000);267+ t.is(transport.attempts, 2);268+});269+270+test('aborting during the backoff after a network error rejects with the abort reason, not a NetworkError', async t => {271+ const transport = scriptedFetch([networkError()]);272+ const controller = new AbortController();273+274+ const result = observe(client(transport, {retry: {delay: () => 1000}})(url, {signal: controller.signal}));275+ await delay(20);276+ controller.abort();277+ await delay(50);278+279+ t.true(result.settled);280+ t.is(result.error, controller.signal.reason);281+ t.is(transport.attempts, 1);282+});283+284+test('aborting during the backoff after a timed out attempt rejects with the abort reason', async t => {285+ const transport = scriptedFetch(['hang']);286+ const controller = new AbortController();287+288+ const result = observe(client(transport, {289+ timeout: 30,290+ retry: {retryOnTimeout: true, delay: () => 1000},291+ })(url, {signal: controller.signal}));292+ await delay(100);293+ t.is(transport.aborted, 1, 'The per-attempt timeout must abort the hung attempt');294+ controller.abort();295+ await delay(50);296+297+ t.true(result.settled);298+ t.is(result.error, controller.signal.reason);299+300+ await delay(1000);301+ t.is(transport.attempts, 1);302+ t.is(transport.active, 0);303+});304+305+test('a non-Error abort reason during the backoff reaches the caller unchanged', async t => {306+ const transport = scriptedFetch([busy()]);307+ const controller = new AbortController();308+309+ const result = observe(client(transport, {retry: {delay: () => 1000}})(url, {signal: controller.signal}));310+ await delay(20);311+ controller.abort('gave up');312+ await delay(50);313+314+ t.true(result.settled);315+ t.is(result.error, 'gave up');316+ t.is(transport.attempts, 1);317+});318+319+test('an AbortSignal.timeout() caller signal ends the backoff with its own TimeoutError', async t => {320+ const transport = scriptedFetch([busy()]);321+ const signal = AbortSignal.timeout(50);322+323+ const result = observe(client(transport, {retry: {delay: () => 1000}})(url, {signal}));324+ await delay(150);325+326+ t.true(result.settled);327+ t.is(result.error, signal.reason);328+ t.false(result.error instanceof TimeoutError, 'A caller deadline is not a Ky timeout');329+ t.is((result.error as DOMException).name, 'TimeoutError');330+ t.is(transport.attempts, 1);331+});332+333+test('a signal from the instance defaults ends the backoff', async t => {334+ const transport = scriptedFetch([busy()]);335+ const controller = new AbortController();336+ const api = client(transport, {retry: {delay: () => 1000}, signal: controller.signal});337+338+ const result = observe(api(url));339+ await delay(20);340+ controller.abort();341+ await delay(50);342+343+ t.true(result.settled);344+ t.is(result.error, controller.signal.reason);345+ t.is(transport.attempts, 1);346+});347+348+test('a signal on a Request input ends the backoff', async t => {349+ const transport = scriptedFetch([busy()]);350+ const controller = new AbortController();351+352+ const result = observe(client(transport, {retry: {delay: () => 1000}})(new Request(url, {signal: controller.signal})));353+ await delay(20);354+ controller.abort();355+ await delay(50);356+357+ t.true(result.settled);358+ t.is(result.error, controller.signal.reason);359+ t.is(transport.attempts, 1);360+});361+362+test('aborting during the backoff does not run beforeRetry hooks', async t => {363+ const transport = scriptedFetch([busy()]);364+ const controller = new AbortController();365+ let beforeRetryCalls = 0;366+367+ const result = observe(client(transport, {368+ retry: {delay: () => 200},369+ hooks: {370+ beforeRetry: [() => {371+ beforeRetryCalls++;372+ }],373+ },374+ })(url, {signal: controller.signal}));375+ await delay(20);376+ controller.abort();377+ await delay(300);378+379+ t.true(result.settled);380+ t.is(beforeRetryCalls, 0);381+ t.is(transport.attempts, 1);382+});383+384+test('aborting during the backoff reaches beforeError hooks as the abort reason', async t => {385+ const transport = scriptedFetch([busy()]);386+ const controller = new AbortController();387+ const seen: unknown[] = [];388+389+ const result = observe(client(transport, {390+ retry: {delay: () => 1000},391+ hooks: {392+ beforeError: [({error}) => {393+ seen.push(error);394+ return error;395+ }],396+ },397+ })(url, {signal: controller.signal}));398+ await delay(20);399+ controller.abort(new Error('cancelled'));400+ await delay(50);401+402+ t.true(result.settled);403+ t.deepEqual(seen, [controller.signal.reason]);404+ t.is(result.error, controller.signal.reason);405+});406+407+test('aborting one request during its backoff does not affect a concurrent request on the same instance', async t => {408+ const transport = scriptedFetch([busy(), busy(), ready('second')]);409+ const api = client(transport, {retry: {delay: () => 150}});410+ const controller = new AbortController();411+412+ const first = observe(api(url, {signal: controller.signal}).text());413+ const second = api(url).text();414+ await delay(20);415+ controller.abort();416+ await delay(50);417+418+ t.true(first.settled);419+ t.is(first.error, controller.signal.reason);420+ t.is(await second, 'second');421+422+ await delay(200);423+ t.is(transport.attempts, 3);424+});425+426+test('aborting many concurrent requests during their backoff leaves nothing running', async t => {427+ const count = 20;428+ const transport = scriptedFetch(Array.from({length: count}, () => busy()));429+ const api = client(transport, {retry: {delay: () => 1000}});430+ const controller = new AbortController();431+432+ const results = Array.from({length: count}, () => observe(api(url, {signal: controller.signal})));433+ await delay(50);434+ t.is(transport.attempts, count);435+ controller.abort();436+ await delay(50);437+438+ for (const result of results) {439+ t.true(result.settled);440+ t.is(result.error, controller.signal.reason);441+ }442+443+ await delay(1000);444+ t.is(transport.attempts, count);445+ t.is(transport.active, 0);446+});447+448+test('an already aborted signal rejects with its reason and is not retried', async t => {449+ const transport = scriptedFetch([ready()]);450+ const controller = new AbortController();451+ controller.abort();452+453+ const error = await t.throwsAsync(client(transport)(url, {signal: controller.signal}));454+ t.is(error, controller.signal.reason);455+456+ // Ky leaves the aborted signal to fetch, which rejects before sending anything.457+ await delay(100);458+ t.is(transport.attempts, 1);459+});460+461+test('aborting during a hung attempt aborts that attempt and does not retry', async t => {462+ const transport = scriptedFetch(['hang', ready()]);463+ const controller = new AbortController();464+465+ const result = observe(client(transport)(url, {signal: controller.signal}));466+ await delay(20);467+ controller.abort();468+ await delay(50);469+470+ t.true(result.settled);471+ t.is(result.error, controller.signal.reason);472+ t.is(transport.aborted, 1);473+ t.is(transport.active, 0);474+475+ await delay(100);476+ t.is(transport.attempts, 1);477+});478+479+test('aborting during a hung retry aborts that attempt and does not retry again', async t => {480+ const transport = scriptedFetch([busy(), 'hang', ready()]);481+ const controller = new AbortController();482+483+ const result = observe(client(transport)(url, {signal: controller.signal}));484+ await delay(80);485+ t.is(transport.attempts, 2);486+ controller.abort();487+ await delay(50);488+489+ t.true(result.settled);490+ t.is(result.error, controller.signal.reason);491+ t.is(transport.aborted, 1);492+ t.is(transport.active, 0);493+494+ await delay(100);495+ t.is(transport.attempts, 2);496+});497+498+// Retry + total timeout499+500+test('totalTimeout expiring during the backoff rejects at the deadline and never dispatches the retry', async t => {501+ const transport = scriptedFetch([busy(), ready('healthy')]);502+ const api = client(transport, {totalTimeout: 300, retry: {limit: 1, delay: () => 1000}});503+504+ const result = observe(api(url));505+ await delay(150);506+ t.false(result.settled, 'The deadline must not fire early');507+ await delay(300);508+509+ t.true(result.settled, 'The deadline must cover the backoff');510+ t.true(result.error instanceof TimeoutError);511+512+ await delay(700);513+ t.is(transport.attempts, 1, 'No dispatch after the deadline');514+515+ t.is(await api(url).text(), 'healthy');516+ t.is(transport.attempts, 2);517+});518+519+test('totalTimeout expiring during a hung retry aborts that attempt', async t => {520+ const transport = scriptedFetch([busy(), 'hang', ready('healthy')]);521+ const api = client(transport, {totalTimeout: 300, retry: {limit: 1, delay: () => 20}});522+523+ const result = observe(api(url));524+ await delay(150);525+ t.false(result.settled);526+ t.is(transport.attempts, 2);527+ await delay(300);528+529+ t.true(result.settled);530+ t.true(result.error instanceof TimeoutError);531+ t.is(transport.aborted, 1, 'The hung attempt must be aborted');532+ t.is(transport.active, 0);533+534+ await delay(100);535+ t.is(transport.attempts, 2);536+537+ t.is(await api(url).text(), 'healthy');538+});539+540+test('totalTimeout aborts a hung first attempt when the per-attempt timeout is disabled', async t => {541+ const transport = scriptedFetch(['hang']);542+543+ const error = await t.throwsAsync(client(transport, {totalTimeout: 300})(url), {instanceOf: TimeoutError});544+ t.is(error.request.url, url);545+ await delay(10);546+ t.is(transport.attempts, 1);547+ t.is(transport.aborted, 1);548+ t.is(transport.active, 0);549+});550+551+test('each request on an instance gets a fresh totalTimeout budget', async t => {552+ const transport = scriptedFetch([busy(), ready('one'), busy(), ready('two')]);553+ const api = client(transport, {totalTimeout: 500, retry: {delay: () => 120}});554+555+ t.is(await api(url).text(), 'one');556+ // A shared budget would be spent by now.557+ await delay(400);558+ t.is(await api(url).text(), 'two');559+ t.is(transport.attempts, 4);560+});561+562+test('totalTimeout aborts every hung attempt under per-attempt timeouts and retryOnTimeout', async t => {563+ const transport = scriptedFetch(['hang', 'hang', 'hang', 'hang']);564+ // The deadline is not a multiple of the 50ms attempt cycle, so it never ties with an attempt starting.565+ const api = client(transport, {timeout: 40, totalTimeout: 175, retry: {limit: 10, retryOnTimeout: true, delay: () => 10}});566+567+ await t.throwsAsync(api(url), {instanceOf: TimeoutError});568+ await delay(10);569+ t.is(transport.active, 0);570+ t.is(transport.aborted, transport.attempts);571+572+ const {attempts} = transport;573+ await delay(100);574+ t.is(transport.attempts, attempts);575+});576+577+test('per-attempt timeouts with retryOnTimeout abort every hung attempt and stop at the retry limit', async t => {578+ const transport = scriptedFetch(['hang', 'hang', 'hang']);579+580+ await t.throwsAsync(client(transport, {timeout: 30, retry: {retryOnTimeout: true}})(url), {instanceOf: TimeoutError});581+ await delay(10);582+ t.is(transport.attempts, 3);583+ t.is(transport.aborted, 3);584+ t.is(transport.active, 0);585+});586+587+// Retry-After + abort588+589+const retryAfterCases = [590+ {591+ title: 'delay seconds',592+ header: () => '1',593+ options: {},594+ minimum: 1000,595+ maximum: 1000,596+ },597+ {598+ title: 'an HTTP date',599+ // HTTP dates have second precision, so the wait lands between one and two seconds.600+ header: () => new Date(Date.now() + 2000).toUTCString(),601+ options: {},602+ minimum: 1000,603+ maximum: 2000,604+ },605+ {606+ title: 'a malformed value',607+ header: () => 'soon',608+ options: {},609+ // Falls back to the configured `delay`.610+ minimum: 150,611+ maximum: 150,612+ },613+ {614+ title: 'a value above maxRetryAfter',615+ header: () => '1000',616+ options: {maxRetryAfter: 300},617+ minimum: 300,618+ maximum: 300,619+ },620+] as const;621+622+for (const {title, header, options, minimum, maximum} of retryAfterCases) {623+ test(`Retry-After with ${title} controls the retry delay`, async t => {624+ const transport = scriptedFetch([{status: 503, headers: {'Retry-After': header()}}, ready()]);625+ const api = client(transport, {626+ retry: {627+ limit: 1, afterStatusCodes: [503], delay: () => 150, ...options,628+ },629+ });630+631+ const result = observe(api(url).text());632+ // Before the expected delay, and after the 150ms fallback for every case that should not use it.633+ await delay(minimum - 50);634+ t.is(transport.attempts, 1, 'The retry must wait for the advertised delay');635+636+ await delay(maximum - minimum + 300);637+ t.true(result.settled);638+ t.is(result.value, 'ready');639+ t.is(transport.attempts, 2);640+ });641+642+ test(`aborting during a Retry-After wait with ${title} settles promptly and dispatches nothing more`, async t => {643+ const transport = scriptedFetch([{status: 503, headers: {'Retry-After': header()}}, ready()]);644+ const api = client(transport, {645+ retry: {646+ limit: 1, afterStatusCodes: [503], delay: () => 150, ...options,647+ },648+ });649+ const controller = new AbortController();650+651+ const result = observe(api(url, {signal: controller.signal}));652+ await delay(20);653+ controller.abort();654+ await delay(50);655+656+ t.true(result.settled, 'Abort must interrupt the header-derived wait');657+ t.is(result.error, controller.signal.reason);658+659+ await delay(maximum + 100);660+ t.is(transport.attempts, 1, 'No dispatch after the wait is cancelled');661+ });662+}663+664+test('Retry-After on a status outside afterStatusCodes uses the configured backoff', async t => {665+ const transport = scriptedFetch([{status: 503, headers: {'Retry-After': '10'}}, ready()]);666+ const api = client(transport, {retry: {limit: 1, afterStatusCodes: [429], delay: () => 50}});667+668+ const result = observe(api(url).text());669+ await delay(300);670+671+ t.true(result.settled);672+ t.is(result.value, 'ready');673+});674+675+// Retry + throwing hooks676+677+// Each hook throws only on its first call, so a follow-up request shows the instance is still usable.678+const hookCases: Array<{title: string; options: (throwOnce: () => void) => Options}> = [679+ {680+ title: 'a synchronous shouldRetry',681+ options: throwOnce => ({682+ retry: {683+ shouldRetry() {684+ throwOnce();685+ return undefined;686+ },687+ },688+ }),689+ },690+ {691+ title: 'an asynchronous shouldRetry',692+ options: throwOnce => ({693+ retry: {694+ async shouldRetry() {695+ await delay(5);696+ throwOnce();697+ return undefined;698+ },699+ },700+ }),701+ },702+ {703+ title: 'a synchronous beforeRetry hook',704+ options: throwOnce => ({705+ hooks: {706+ beforeRetry: [throwOnce],707+ },708+ }),709+ },710+ {711+ title: 'an asynchronous beforeRetry hook',712+ options: throwOnce => ({713+ hooks: {714+ beforeRetry: [async () => {715+ await delay(5);716+ throwOnce();717+ }],718+ },719+ }),720+ },721+ {722+ title: 'retry.delay',723+ options: throwOnce => ({724+ retry: {725+ delay() {726+ throwOnce();727+ return 20;728+ },729+ },730+ }),731+ },732+ {733+ title: 'retry.jitter',734+ options: throwOnce => ({735+ retry: {736+ jitter(delay) {737+ throwOnce();738+ return delay;739+ },740+ },741+ }),742+ },743+];744+745+for (const {title, options} of hookCases) {746+ test(`an error thrown from ${title} reaches the caller unchanged and is not retried`, async t => {747+ const transport = scriptedFetch([busy(), busy(), ready('healthy')]);748+ const sentinel = new Error(`sentinel: ${title}`);749+ let armed = true;750+ const api = client(transport, options(() => {751+ if (armed) {752+ armed = false;753+ throw sentinel;754+ }755+ }));756+757+ const result = observe(api(url));758+ await delay(200);759+760+ t.true(result.settled, 'A throwing hook must settle the caller');761+ t.is(result.error, sentinel);762+ t.is(transport.attempts, 1);763+764+ t.is(await api(url).text(), 'healthy');765+ t.is(transport.attempts, 3);766+ });767+}768+769+test('an error thrown from an afterResponse hook on a retryable response is not retried', async t => {770+ const transport = scriptedFetch([busy(), ready()]);771+ const sentinel = new Error('afterResponse');772+773+ const error = await t.throwsAsync(client(transport, {774+ hooks: {775+ afterResponse: [() => {776+ throw sentinel;777+ }],778+ },779+ })(url));780+ t.is(error, sentinel);781+ t.is(transport.attempts, 1);782+});783+784+test('a beforeRetry hook that throws on the second retry stops after two attempts', async t => {785+ const transport = scriptedFetch([busy(), busy(), ready()]);786+ const sentinel = new Error('second retry');787+788+ const error = await t.throwsAsync(client(transport, {789+ hooks: {790+ beforeRetry: [({retryCount}) => {791+ if (retryCount === 2) {792+ throw sentinel;793+ }794+ }],795+ },796+ })(url));797+ t.is(error, sentinel);798+ t.is(transport.attempts, 2);799+});800+801+test('a shouldRetry that throws after a network error reaches the caller unchanged', async t => {802+ const transport = scriptedFetch([networkError(), ready()]);803+ const sentinel = new Error('shouldRetry');804+805+ const error = await t.throwsAsync(client(transport, {806+ retry: {807+ shouldRetry() {808+ throw sentinel;809+ },810+ },811+ })(url));812+ t.is(error, sentinel);813+ t.is(transport.attempts, 1);814+});815+816+// Retry + body replay817+818+const payload = 'payload: café / 123 🦄';819+const bytes = new TextEncoder().encode(payload);820+821+// `expected` is the exact body on the wire and `contentType` its header, left out when there is none. Both are left out for FormData, whose boundary is random.822+const bodyCases: Array<{title: string; expected?: string; contentType?: string; send: (transport: ReturnType<typeof scriptedFetch>) => Promise<unknown>}> = [823+ {824+ title: 'a string',825+ contentType: 'text/plain;charset=UTF-8',826+ expected: payload,827+ send: async transport => client(transport, {retry: {methods: ['post']}}).post(url, {body: payload}),828+ },829+ {830+ title: 'a Uint8Array',831+ expected: payload,832+ send: async transport => client(transport, {retry: {methods: ['post']}}).post(url, {body: bytes}),833+ },834+ {835+ title: 'an ArrayBuffer',836+ expected: payload,837+ send: async transport => client(transport, {retry: {methods: ['post']}}).post(url, {body: new TextEncoder().encode(payload).buffer}),838+ },839+ {840+ title: 'a Blob',841+ expected: payload,842+ send: async transport => client(transport, {retry: {methods: ['post']}}).post(url, {body: new Blob([payload])}),843+ },844+ {845+ title: 'URLSearchParams',846+ contentType: 'application/x-www-form-urlencoded;charset=UTF-8',847+ expected: new URLSearchParams({payload}).toString(),848+ send: async transport => client(transport, {retry: {methods: ['post']}}).post(url, {body: new URLSearchParams({payload})}),849+ },850+ {851+ title: 'FormData',852+ async send(transport) {853+ const formData = new FormData();854+ formData.append('payload', payload);855+ formData.append('file', new Blob([bytes]), 'file.txt');856+ return client(transport, {retry: {methods: ['post']}}).post(url, {body: formData});857+ },858+ },859+ {860+ title: 'json',861+ contentType: 'application/json',862+ expected: JSON.stringify({payload}),863+ send: async transport => client(transport, {retry: {methods: ['post']}}).post(url, {json: {payload}}),864+ },865+ {866+ title: 'a ReadableStream',867+ expected: payload,868+ send: async transport => client(transport, {retry: {methods: ['post']}}).post(url, {869+ body: new ReadableStream({870+ start(controller) {871+ controller.enqueue(bytes.slice(0, 5));872+ controller.enqueue(bytes.slice(5));873+ controller.close();874+ },875+ }),876+ }),877+ },878+ {879+ title: 'a Request input with a string body',880+ contentType: 'text/plain;charset=UTF-8',881+ expected: payload,882+ send: async transport => client(transport, {retry: {methods: ['post']}})(new Request(url, {method: 'POST', body: payload})),883+ },884+ {885+ title: 'a Request input with a stream body',886+ expected: payload,887+ send: async transport => client(transport, {retry: {methods: ['post']}})(new Request(url, {888+ method: 'POST',889+ body: new ReadableStream({890+ start(controller) {891+ controller.enqueue(bytes);892+ controller.close();893+ },894+ }),895+ duplex: 'half',896+ } as RequestInit)),897+ },898+ {899+ title: 'a PUT under the default retry methods',900+ contentType: 'text/plain;charset=UTF-8',901+ expected: payload,902+ send: async transport => client(transport).put(url, {body: payload}),903+ },904+];905+906+for (const {title, expected, contentType, send} of bodyCases) {907+ test(`a retry resends ${title} body byte for byte`, async t => {908+ const transport = scriptedFetch([busy(), networkError(), ready()]);909+910+ await send(transport);911+912+ t.is(transport.attempts, 3);913+ const contentTypes = transport.requests.map(request => request.headers.get('content-type'));914+ if (expected === undefined) {915+ const boundary = contentTypes[0]?.split('multipart/form-data; boundary=')[1];916+ t.truthy(boundary);917+ t.true(transport.bodies[0]!.includes(`--${boundary}`), 'The body must use the boundary from the header');918+ t.true(transport.bodies[0]!.includes(payload));919+ } else {920+ t.is(transport.bodies[0], expected);921+ t.is(contentTypes[0] ?? undefined, contentType);922+ }923+924+ t.deepEqual(transport.bodies, Array.from({length: 3}, () => transport.bodies[0]));925+ t.deepEqual(contentTypes, Array.from({length: 3}, () => contentTypes[0]));926+ });927+}928+929+test('aborting during the backoff of a POST with a stream body dispatches nothing more', async t => {930+ const transport = scriptedFetch([busy(), ready()]);931+ const controller = new AbortController();932+933+ const result = observe(client(transport, {retry: {methods: ['post'], delay: () => 1000}}).post(url, {934+ signal: controller.signal,935+ body: new ReadableStream({936+ start(streamController) {937+ streamController.enqueue(bytes);938+ streamController.close();939+ },940+ }),941+ }));942+ await delay(20);943+ controller.abort();944+ await delay(50);945+946+ t.true(result.settled);947+ t.is(result.error, controller.signal.reason);948+949+ await delay(1000);950+ t.deepEqual(transport.bodies, [payload]);951+});952+953+// Real HTTP954+955+// Waits for `promise`, failing instead of hanging when it takes longer than two seconds.956+async function withinTwoSeconds<T>(promise: Promise<T>, message: string): Promise<T> {957+ const timeout = delay(2000, undefined, {ref: false}).then(() => {958+ throw new Error(message);959+ });960+961+ return Promise.race([promise, timeout]);962+}963+964+test('retry over real HTTP recovers after two 503 responses', async t => {965+ const server = await createHttpTestServer(t);966+ const arrivals: string[] = [];967+ server.get('/flaky', (request, response) => {968+ arrivals.push(request.url);969+ if (arrivals.length < 3) {970+ response.sendStatus(503);971+ return;972+ }973+974+ response.end('ready');975+ });976+977+ t.is(await ky(`${server.url}/flaky`, {retry: {limit: 2, delay: () => 5}}).text(), 'ready');978+ t.deepEqual(arrivals, ['/flaky', '/flaky', '/flaky']);979+});980+981+test('a timeout over real HTTP closes the hung connection and the next request still works', async t => {982+ const server = await createHttpTestServer(t);983+ const {promise: closed, resolve: markClosed} = Promise.withResolvers<void>();984+ server.get('/slow', (_request, response) => {985+ response.once('close', markClosed);986+ });987+ server.get('/', (_request, response) => {988+ response.end('ready');989+ });990+991+ await t.throwsAsync(ky(`${server.url}/slow`, {timeout: 100, retry: 0}), {instanceOf: TimeoutError});992+ await withinTwoSeconds(closed, 'The hung connection was not closed');993+ t.is(await ky(server.url).text(), 'ready');994+});995+996+test('a totalTimeout over real HTTP closes the hung retry connection', async t => {997+ const server = await createHttpTestServer(t);998+ const {promise: closed, resolve: markClosed} = Promise.withResolvers<void>();999+ let arrivals = 0;1000+ server.get('/', (_request, response) => {1001+ arrivals++;1002+ if (arrivals === 1) {1003+ response.sendStatus(503);1004+ return;1005+ }1006+1007+ response.once('close', markClosed);1008+ });1009+1010+ await t.throwsAsync(ky(server.url, {timeout: false, totalTimeout: 1000, retry: {limit: 1, delay: () => 20}}), {instanceOf: TimeoutError});1011+ await withinTwoSeconds(closed, 'The hung retry connection was not closed');1012+ t.is(arrivals, 2);1013+});1014+1015+test('aborting during the backoff over real HTTP makes exactly one arrival', async t => {1016+ const server = await createHttpTestServer(t);1017+ const {promise: firstArrival, resolve: markFirstArrival} = Promise.withResolvers<void>();1018+ let arrivals = 0;1019+ server.get('/', (_request, response) => {1020+ arrivals++;1021+ response.sendStatus(503);1022+ markFirstArrival();1023+ });1024+ const controller = new AbortController();1025+1026+ const result = observe(ky(server.url, {signal: controller.signal, retry: {limit: 2, delay: () => 1000}}));1027+ await firstArrival;1028+ // Let Ky receive the response and start the backoff.1029+ await delay(100);1030+ controller.abort();1031+ await delay(50);1032+1033+ t.true(result.settled);1034+ t.is(result.error, controller.signal.reason);1035+ await delay(1000);1036+ t.is(arrivals, 1);1037+});1038+1039+test('aborting a hung attempt over real HTTP closes its connection and does not retry', async t => {1040+ const server = await createHttpTestServer(t);1041+ const {promise: arrived, resolve: markArrived} = Promise.withResolvers<void>();1042+ const {promise: closed, resolve: markClosed} = Promise.withResolvers<void>();1043+ let arrivals = 0;1044+ server.get('/', (_request, response) => {1045+ arrivals++;1046+ response.once('close', markClosed);1047+ markArrived();1048+ });1049+ const controller = new AbortController();1050+1051+ const result = observe(ky(server.url, {signal: controller.signal, timeout: false, retry: {limit: 2, delay: () => 5}}));1052+ await arrived;1053+ controller.abort();1054+ await delay(50);1055+1056+ t.true(result.settled);1057+ t.is(result.error, controller.signal.reason);1058+ await withinTwoSeconds(closed, 'The aborted connection was not closed');1059+ await delay(100);1060+ t.is(arrivals, 1);1061+});1062+1063+test('aborting while Ky reads a retryable error body over real HTTP settles promptly and does not retry', async t => {1064+ const server = await createHttpTestServer(t);1065+ const {promise: arrived, resolve: markArrived} = Promise.withResolvers<void>();1066+ let arrivals = 0;1067+ server.get('/', (_request, response) => {1068+ arrivals++;1069+ // The error body never ends, so Ky is still reading it when the caller aborts.1070+ response.writeHead(503, {'content-type': 'text/plain'});1071+ response.write('partial');1072+ markArrived();1073+ });1074+ const controller = new AbortController();1075+1076+ const result = observe(ky(server.url, {signal: controller.signal, timeout: false, retry: {limit: 2, delay: () => 5}}));1077+ await arrived;1078+ await delay(100);1079+ t.false(result.settled);1080+ controller.abort();1081+ await delay(50);1082+1083+ t.true(result.settled);1084+ t.is(result.error, controller.signal.reason);1085+ await delay(100);1086+ t.is(arrivals, 1);1087+});1088+1089+test('a POST body is resent byte for byte over real HTTP', async t => {1090+ const server = await createHttpTestServer(t, {bodyParser: false});1091+ const bodies: string[] = [];1092+ server.post('/', async (request, response) => {1093+ const chunks: Uint8Array[] = [];1094+ for await (const chunk of request) {1095+ chunks.push(chunk as Uint8Array);1096+ }1097+1098+ bodies.push(Buffer.concat(chunks).toString());1099+ if (bodies.length === 1) {1100+ response.sendStatus(503);1101+ return;1102+ }1103+1104+ response.end('ready');1105+ });1106+1107+ t.is(await ky.post(server.url, {1108+ body: new ReadableStream({1109+ start(controller) {1110+ controller.enqueue(bytes);1111+ controller.close();1112+ },1113+ }),1114+ retry: {limit: 1, methods: ['post'], delay: () => 5},1115+ }).text(), 'ready');1116+ t.deepEqual(bodies, [payload, payload]);1117+});added:test/response-handling.ts+309 added
1+import test from 'ava';2+import ky, {3+ ResponseSizeError,4+ SchemaValidationError,5+ type Progress,6+ type StandardSchemaV1,7+} from '../source/index.js';8+9+const url = 'https://example.com/data';10+const encoder = new TextEncoder();11+const invalidSchemaMessage = 'The `schema` argument must follow the Standard Schema specification';12+13+const createChunkedBody = (chunks: string[]) => new ReadableStream<Uint8Array>({14+ start(controller) {15+ for (const chunk of chunks) {16+ controller.enqueue(encoder.encode(chunk));17+ }18+19+ controller.close();20+ },21+});22+23+// A body that was partly read through a reader and then released is used but no longer locked, so only `bodyUsed` tells the wrappers to leave it alone.24+const createReleasedResponse = async (): Promise<Response> => {25+ const response = new Response(createChunkedBody(['first', 'second']));26+ const reader = response.body!.getReader();27+ await reader.read();28+ reader.releaseLock();29+ return response;30+};31+32+// A `content-length` that is not a size must be treated as an unknown total rather than turning `percent` negative or `NaN`.33+for (const contentLength of ['-10', 'not-a-number']) {34+ test(`download progress treats a content-length of ${contentLength} as an unknown total`, async t => {35+ const progressEvents: Progress[] = [];36+ const text = await ky(url, {37+ retry: 0,38+ fetch: async () => new Response(createChunkedBody(['ab', 'cd']), {headers: {'content-length': contentLength}}),39+ onDownloadProgress(progress) {40+ progressEvents.push(progress);41+ },42+ }).text();43+44+ t.is(text, 'abcd');45+ t.deepEqual(progressEvents, [46+ {percent: 0, totalBytes: 0, transferredBytes: 2},47+ {percent: 1, totalBytes: 4, transferredBytes: 4},48+ ]);49+ });50+}51+52+test('upload progress treats a negative declared content-length as an unknown total', async t => {53+ const progressEvents: Progress[] = [];54+ await ky.post(url, {55+ body: createChunkedBody(['ab', 'cd']),56+ headers: {'content-length': '-10'},57+ retry: 0,58+ async fetch(request) {59+ await (request as Request).arrayBuffer();60+ return new Response('ok');61+ },62+ onUploadProgress(progress) {63+ progressEvents.push(progress);64+ },65+ }).text();66+67+ t.deepEqual(progressEvents, [68+ {percent: 0, totalBytes: 0, transferredBytes: 2},69+ {percent: 1, totalBytes: 4, transferredBytes: 4},70+ ]);71+});72+73+// Chromium replaces the size error with a generic TypeError in native body methods, so the wrappers restore it. Node.js passes the stream error through on the first read, so a second read, which natively fails with "Body is unusable", is the only way to make the native method fail with something else here. The tests below use it to check that each wrapper restores the size error.74+test('a body read after the size limit was exceeded reports the size error again', async t => {75+ const response = await ky(url, {76+ retry: 0,77+ maxResponseSize: 1,78+ fetch: async () => new Response('too large'),79+ });80+81+ const firstError = await t.throwsAsync(response.text(), {instanceOf: ResponseSizeError});82+ // The native method now fails with "Body is unusable", which hides why the body is gone.83+ const secondError = await t.throwsAsync(response.arrayBuffer(), {instanceOf: ResponseSizeError});84+ t.is(secondError, firstError);85+});86+87+// The download progress wrapper sits on top of the limited body, so it has to inherit the size error of the body it wraps.88+test('a body read after the size limit was exceeded reports the size error again with download progress', async t => {89+ const response = await ky(url, {90+ retry: 0,91+ maxResponseSize: 1,92+ onDownloadProgress: () => undefined,93+ fetch: async () => new Response('too large'),94+ });95+96+ const firstError = await t.throwsAsync(response.text(), {instanceOf: ResponseSizeError});97+ const secondError = await t.throwsAsync(response.text(), {instanceOf: ResponseSizeError});98+ t.is(secondError, firstError);99+});100+101+test('a clone keeps reporting the size error after its body failed', async t => {102+ const response = await ky(url, {103+ retry: 0,104+ maxResponseSize: 1,105+ fetch: async () => new Response('too large'),106+ });107+108+ const clone = response.clone();109+ const firstError = await t.throwsAsync(clone.text(), {instanceOf: ResponseSizeError});110+ const secondError = await t.throwsAsync(clone.text(), {instanceOf: ResponseSizeError});111+ t.is(secondError, firstError);112+});113+114+// The `afterResponse` hook gets a clone of the limited response, and returning it wraps it in a second limit. That outer limit never sees the bytes past the inner one, so it has to report the inner error.115+test('a response returned by an afterResponse hook reports the size error of the limit it already went through', async t => {116+ const response = await ky(url, {117+ retry: 0,118+ maxResponseSize: 1,119+ fetch: async () => new Response('too large'),120+ hooks: {121+ afterResponse: [({response}) => response],122+ },123+ });124+125+ const firstError = await t.throwsAsync(response.text(), {instanceOf: ResponseSizeError});126+ const secondError = await t.throwsAsync(response.text(), {instanceOf: ResponseSizeError});127+ t.is(secondError, firstError);128+});129+130+for (const [label, options] of [131+ ['with `maxResponseSize`', {maxResponseSize: 1000}],132+ ['with `onDownloadProgress`', {onDownloadProgress: () => undefined}],133+] as Array<[string, Record<string, unknown>]>) {134+ test(`a partly read and released body reports the native error ${label}`, async t => {135+ const response = await ky(url, {136+ ...options,137+ retry: 0,138+ fetch: createReleasedResponse,139+ });140+141+ await t.throwsAsync(response.text(), {142+ name: 'TypeError',143+ message: 'Body is unusable: Body has already been read',144+ });145+ });146+}147+148+for (const [label, takeBody] of [149+ ['locked by a reader', (request: Request) => {150+ request.body!.getReader();151+ }],152+ ['partly read and released', async (request: Request) => {153+ const reader = request.body!.getReader();154+ await reader.read();155+ reader.releaseLock();156+ }],157+] as Array<[string, (request: Request) => void | Promise<void>]>) {158+ test(`upload progress leaves a request body that is ${label} to the native error`, async t => {159+ const run = async (onUploadProgress?: () => void) => t.throwsAsync(ky.post(url, {160+ body: 'payload',161+ retry: 0,162+ onUploadProgress,163+ fetch: async input => new Response(await (input as Request).text()),164+ hooks: {165+ beforeRequest: [async ({request}) => {166+ await takeBody(request);167+ }],168+ },169+ }).text());170+171+ const withoutProgress = await run();172+ const withProgress = await run(() => undefined);173+174+ t.truthy(withoutProgress?.message);175+ t.is(withProgress?.message, withoutProgress?.message);176+ });177+}178+179+for (const [label, standard] of [180+ ['`null`', null],181+ ['a function with a `validate` method', Object.assign(() => undefined, {version: 1, vendor: 'test', validate: (value: unknown) => ({value})})],182+] as Array<[string, unknown]>) {183+ test(`.json(schema) rejects a \`~standard\` property that is ${label}`, async t => {184+ await t.throwsAsync(ky(url, {185+ retry: 0,186+ fetch: async () => Response.json({value: 1}),187+ }).json({'~standard': standard} as unknown as StandardSchemaV1), {188+ instanceOf: TypeError,189+ message: invalidSchemaMessage,190+ });191+ });192+}193+194+// A Standard Schema result signals failure by having `issues` at all, so an empty list is still a failure rather than a success without a `value`.195+test('.json(schema) treats an empty issues list as a validation failure', async t => {196+ const error = await t.throwsAsync(ky(url, {197+ retry: 0,198+ fetch: async () => Response.json({value: 1}),199+ }).json({200+ '~standard': {201+ version: 1,202+ vendor: 'test',203+ validate: () => ({issues: []}),204+ },205+ }), {instanceOf: SchemaValidationError});206+207+ t.deepEqual(error?.issues, []);208+});209+210+test('a clone made after a retry of an earlier attempt response keeps the request of that attempt for parseJson', async t => {211+ const sent: Request[] = [];212+ const parseJsonRequests: Request[] = [];213+ let firstAttemptClone: Response | undefined;214+215+ const data = await ky(url, {216+ retry: {limit: 1, delay: () => 0},217+ async fetch(request) {218+ sent.push(request as Request);219+ return sent.length === 1 ? Response.json({attempt: 1}, {status: 500}) : Response.json({attempt: 2});220+ },221+ parseJson(text, {request}) {222+ parseJsonRequests.push(request);223+ return JSON.parse(text);224+ },225+ hooks: {226+ afterResponse: [({response}) => {227+ firstAttemptClone ??= response.clone();228+ }],229+ },230+ }).json();231+232+ t.deepEqual(data, {attempt: 2});233+ t.is(sent.length, 2);234+ parseJsonRequests.length = 0;235+236+ // Cloned only now, after the second attempt became the request that was sent last.237+ t.deepEqual(await firstAttemptClone!.clone().json(), {attempt: 1});238+ t.deepEqual(parseJsonRequests, [sent[0]]);239+});240+241+// With retries enabled, the hook gets the clone prepared for the next attempt rather than the request that was sent, so releasing that clone once the request settles must spare a response built on its body.242+test('an afterResponse hook can return the body of the request it was given as the response', async t => {243+ const text = await ky.post(url, {244+ body: 'echo-payload',245+ retry: {limit: 2},246+ fetch: async () => new Response('from fetch'),247+ hooks: {248+ afterResponse: [({request}) => new Response(request.body)],249+ },250+ }).text();251+252+ t.is(text, 'echo-payload');253+});254+255+// With retries enabled, `ky.request` is the clone prepared for the next attempt by the time the response arrives, which is not the request that produced it.256+test('response.json() gives parseJson the request that was sent', async t => {257+ let sent: Request | undefined;258+ let parseJsonRequest: Request | undefined;259+260+ const response = await ky(url, {261+ retry: {limit: 2},262+ async fetch(request) {263+ sent = request as Request;264+ return Response.json({value: 1});265+ },266+ parseJson(text, {request}) {267+ parseJsonRequest = request;268+ return JSON.parse(text) as unknown;269+ },270+ });271+272+ t.deepEqual(await response.json(), {value: 1});273+ t.is(parseJsonRequest, sent);274+});275+276+test('the .json() shortcut uses a parseJson set by an init hook', async t => {277+ const parsedTexts: string[] = [];278+279+ const data = await ky(url, {280+ retry: 0,281+ fetch: async () => Response.json({value: 1}),282+ hooks: {283+ init: [options => {284+ options.parseJson = text => {285+ parsedTexts.push(text);286+ return {parsedBy: 'init hook'};287+ };288+ }],289+ },290+ }).json();291+292+ t.deepEqual(data, {parsedBy: 'init hook'});293+ t.deepEqual(parsedTexts, ['{"value":1}']);294+});295+296+test('response.json() with parseJson consumes the body like the native method', async t => {297+ const response = await ky(url, {298+ retry: 0,299+ fetch: async () => Response.json({value: 1}),300+ parseJson: text => JSON.parse(text) as unknown,301+ });302+303+ t.deepEqual(await response.json(), {value: 1});304+ t.true(response.bodyUsed);305+ await t.throwsAsync(response.json(), {306+ name: 'TypeError',307+ message: 'Body is unusable: Body has already been read',308+ });309+});added:test/retry-decisions.ts+424 added
1+import test, {type ExecutionContext} from 'ava';2+import ky, {HTTPError} from '../source/index.js';3+import {NonError} from '../source/errors/NonError.js';4+5+// Ky bounds every HTTP error body read with this timer, even when `timeout` is `false`.6+const errorBodyReadTimeout = 10_000;7+8+/*9+Replaces `setTimeout` until the test ends, so the retry delays Ky schedules are recorded and then run at once.10+11+The tests that use this set `timeout: false`, so the only other timer is the error body read timer, which is not recorded.12+*/13+const captureRetryDelays = (t: ExecutionContext): number[] => {14+ const originalSetTimeout = globalThis.setTimeout;15+ const retryDelays: number[] = [];16+17+ globalThis.setTimeout = ((handler: () => void, milliseconds?: number) => {18+ if (milliseconds === errorBodyReadTimeout) {19+ return originalSetTimeout(handler, milliseconds);20+ }21+22+ retryDelays.push(milliseconds ?? 0);23+ return originalSetTimeout(handler, 0);24+ }) as typeof globalThis.setTimeout;25+26+ t.teardown(() => {27+ globalThis.setTimeout = originalSetTimeout;28+ });29+30+ return retryDelays;31+};32+33+/*34+Creates a `fetch` that responds with the next response from the list and repeats the last one.35+*/36+const createFetch = (...createResponses: Array<() => Response>) => {37+ const state = {38+ requestCount: 0,39+ async fetch() {40+ const createResponse = createResponses[Math.min(state.requestCount, createResponses.length - 1)]!;41+ state.requestCount++;42+ return createResponse();43+ },44+ };45+46+ return state;47+};48+49+const status = (statusCode: number, headers?: HeadersInit) => () => new Response(undefined, {status: statusCode, headers});50+const success = () => new Response('ok');51+52+/*53+Creates an `afterResponse` hook that returns the given forced retry for the first response only.54+*/55+const forceRetryOnce = (createForcedRetry: () => ReturnType<typeof ky.retry>) => {56+ let forcedRetry = false;57+58+ return () => {59+ if (!forcedRetry) {60+ forcedRetry = true;61+ return createForcedRetry();62+ }63+ };64+};65+66+test.serial('a jitter function returning zero gives no delay', async t => {67+ const retryDelays = captureRetryDelays(t);68+ const {fetch} = createFetch(status(500), success);69+70+ await ky('https://example.com', {71+ fetch,72+ timeout: false,73+ retry: {74+ limit: 1,75+ delay: () => 100,76+ jitter: () => 0,77+ },78+ });79+80+ t.deepEqual(retryDelays, [0]);81+});82+83+test.serial('a `retry.delay` of Infinity is accepted and capped by backoffLimit', async t => {84+ const retryDelays = captureRetryDelays(t);85+ const {fetch} = createFetch(status(500), success);86+87+ await ky('https://example.com', {88+ fetch,89+ timeout: false,90+ retry: {91+ limit: 1,92+ delay: () => Number.POSITIVE_INFINITY,93+ backoffLimit: 1000,94+ },95+ });96+97+ t.deepEqual(retryDelays, [1000]);98+});99+100+test.serial('a 429 response without a retry timing header uses the computed delay', async t => {101+ const retryDelays = captureRetryDelays(t);102+ const {fetch} = createFetch(status(429), success);103+104+ await ky('https://example.com', {105+ fetch,106+ timeout: false,107+ retry: {108+ limit: 1,109+ delay: () => 100,110+ },111+ });112+113+ t.deepEqual(retryDelays, [100]);114+});115+116+test.serial('`ky.retry({delay})` bypasses jitter and backoffLimit', async t => {117+ const retryDelays = captureRetryDelays(t);118+ const {fetch} = createFetch(success);119+120+ await ky('https://example.com', {121+ fetch,122+ timeout: false,123+ retry: {124+ limit: 1,125+ backoffLimit: 10,126+ jitter: () => 1,127+ },128+ hooks: {129+ afterResponse: [forceRetryOnce(() => ky.retry({delay: 500}))],130+ },131+ });132+133+ t.deepEqual(retryDelays, [500]);134+});135+136+test.serial('`ky.retry({delay: 0})` retries without the computed delay', async t => {137+ const retryDelays = captureRetryDelays(t);138+ const {fetch} = createFetch(success);139+140+ await ky('https://example.com', {141+ fetch,142+ timeout: false,143+ retry: {144+ limit: 1,145+ delay: () => 5000,146+ },147+ hooks: {148+ afterResponse: [forceRetryOnce(() => ky.retry({delay: 0}))],149+ },150+ });151+152+ t.deepEqual(retryDelays, [0]);153+});154+155+test.serial('`ky.retry()` without a delay applies jitter and backoffLimit to the computed delay', async t => {156+ const retryDelays = captureRetryDelays(t);157+ const {fetch} = createFetch(success);158+159+ await ky('https://example.com', {160+ fetch,161+ timeout: false,162+ retry: {163+ limit: 1,164+ delay: () => 100,165+ jitter: delay => delay / 2,166+ backoffLimit: 30,167+ },168+ hooks: {169+ afterResponse: [forceRetryOnce(() => ky.retry())],170+ },171+ });172+173+ t.deepEqual(retryDelays, [30]);174+});175+176+test('a 413 response is not retried when its status is missing from afterStatusCodes, even with Retry-After', async t => {177+ const state = createFetch(status(413, {'Retry-After': '0'}), success);178+179+ await t.throwsAsync(ky('https://example.com', {180+ fetch: state.fetch,181+ retry: {182+ limit: 1,183+ afterStatusCodes: [429],184+ },185+ }), {instanceOf: HTTPError});186+187+ t.is(state.requestCount, 1);188+});189+190+test('the method of a request replaced in beforeRetry decides whether it is retried again', async t => {191+ const methods: string[] = [];192+193+ await t.throwsAsync(ky('https://example.com', {194+ async fetch(request) {195+ methods.push((request as Request).method);196+ return new Response(undefined, {status: 500});197+ },198+ retry: {199+ limit: 3,200+ delay: () => 0,201+ },202+ hooks: {203+ beforeRetry: [({request}) => new Request(request, {method: 'POST'})],204+ },205+ }), {instanceOf: HTTPError});206+207+ t.deepEqual(methods, ['GET', 'POST']);208+});209+210+test('shouldRetry returning a truthy non-boolean does not force a retry', async t => {211+ const state = createFetch(status(404), success);212+213+ await t.throwsAsync(ky('https://example.com', {214+ fetch: state.fetch,215+ retry: {216+ limit: 1,217+ delay: () => 0,218+ shouldRetry: () => 1 as never,219+ },220+ }), {instanceOf: HTTPError});221+222+ t.is(state.requestCount, 1);223+});224+225+test('shouldRetry returning a falsy non-boolean does not prevent a retry', async t => {226+ const state = createFetch(status(500), success);227+228+ t.is(await ky('https://example.com', {229+ fetch: state.fetch,230+ retry: {231+ limit: 1,232+ delay: () => 0,233+ shouldRetry: () => 0 as never,234+ },235+ }).text(), 'ok');236+237+ t.is(state.requestCount, 2);238+});239+240+test('shouldRetry is not called for a method that is not retried', async t => {241+ const state = createFetch(status(500), success);242+ let shouldRetryCallCount = 0;243+244+ await t.throwsAsync(ky.post('https://example.com', {245+ fetch: state.fetch,246+ retry: {247+ limit: 1,248+ delay: () => 0,249+ shouldRetry() {250+ shouldRetryCallCount++;251+ return true;252+ },253+ },254+ }), {instanceOf: HTTPError});255+256+ t.is(shouldRetryCallCount, 0);257+ t.is(state.requestCount, 1);258+});259+260+test('a non-Error value thrown by fetch reaches shouldRetry as a NonError and is not retried by default', async t => {261+ let requestCount = 0;262+ const shouldRetryErrors: Error[] = [];263+264+ const error = await t.throwsAsync(ky('https://example.com', {265+ async fetch() {266+ requestCount++;267+ // eslint-disable-next-line @typescript-eslint/only-throw-error268+ throw 'temporary failure';269+ },270+ retry: {271+ limit: 1,272+ delay: () => 0,273+ shouldRetry({error}) {274+ shouldRetryErrors.push(error);275+ return undefined;276+ },277+ },278+ }), {any: true});279+280+ t.is(error, 'temporary failure');281+ t.is(requestCount, 1);282+ t.is(shouldRetryErrors.length, 1);283+ t.true(shouldRetryErrors[0] instanceof NonError);284+ t.is((shouldRetryErrors[0] as NonError).value, 'temporary failure');285+});286+287+// `setTimeout()` treats a delay above 2^31 - 1 as 1ms, so an unbounded delay must be capped rather than turning into an immediate retry.288+test.serial('an infinite `retry.delay` without totalTimeout is capped at the largest timer delay and still retries', async t => {289+ const retryDelays = captureRetryDelays(t);290+ const state = createFetch(status(500), success);291+292+ t.is(await ky('https://example.com', {293+ fetch: state.fetch,294+ timeout: false,295+ retry: {296+ limit: 1,297+ delay: () => Number.POSITIVE_INFINITY,298+ backoffLimit: Number.POSITIVE_INFINITY,299+ },300+ }).text(), 'ok');301+302+ t.deepEqual(retryDelays, [2_147_483_647]);303+ t.is(state.requestCount, 2);304+});305+306+test.serial('`ky.retry({delay: Infinity})` is capped at the largest timer delay', async t => {307+ const retryDelays = captureRetryDelays(t);308+ const state = createFetch(success);309+310+ t.is(await ky('https://example.com', {311+ fetch: state.fetch,312+ timeout: false,313+ retry: {314+ limit: 1,315+ backoffLimit: 10,316+ },317+ hooks: {318+ afterResponse: [forceRetryOnce(() => ky.retry({delay: Number.POSITIVE_INFINITY}))],319+ },320+ }).text(), 'ok');321+322+ t.deepEqual(retryDelays, [2_147_483_647]);323+ t.is(state.requestCount, 2);324+});325+326+test.serial('a Retry-After with more digits than a number can hold is capped at the largest timer delay', async t => {327+ const retryDelays = captureRetryDelays(t);328+ const {fetch} = createFetch(status(503, {'Retry-After': '9'.repeat(400)}), success);329+330+ await ky('https://example.com', {331+ fetch,332+ timeout: false,333+ retry: {334+ limit: 1,335+ delay: () => 100,336+ },337+ });338+339+ t.deepEqual(retryDelays, [2_147_483_647]);340+});341+342+test.serial('`maxRetryAfter: 0` retries at once even when the server asks to wait', async t => {343+ const retryDelays = captureRetryDelays(t);344+ const {fetch} = createFetch(status(503, {'Retry-After': '30'}), success);345+346+ await ky('https://example.com', {347+ fetch,348+ timeout: false,349+ retry: {350+ limit: 1,351+ delay: () => 100,352+ maxRetryAfter: 0,353+ },354+ });355+356+ t.deepEqual(retryDelays, [0]);357+});358+359+test.serial('`maxRetryAfter` caps a RateLimit-Reset delay', async t => {360+ const retryDelays = captureRetryDelays(t);361+ const {fetch} = createFetch(status(429, {'RateLimit-Reset': '30'}), success);362+363+ await ky('https://example.com', {364+ fetch,365+ timeout: false,366+ retry: {367+ limit: 1,368+ delay: () => 100,369+ maxRetryAfter: 1000,370+ },371+ });372+373+ t.deepEqual(retryDelays, [1000]);374+});375+376+test.serial('`backoffLimit: 0` retries without a delay', async t => {377+ const retryDelays = captureRetryDelays(t);378+ const {fetch} = createFetch(status(500), status(500), success);379+380+ await ky('https://example.com', {381+ fetch,382+ timeout: false,383+ retry: {384+ limit: 2,385+ backoffLimit: 0,386+ },387+ });388+389+ t.deepEqual(retryDelays, [0, 0]);390+});391+392+test.serial('a jitter function returning Infinity falls back to the computed delay', async t => {393+ const retryDelays = captureRetryDelays(t);394+ const {fetch} = createFetch(status(500), success);395+396+ await ky('https://example.com', {397+ fetch,398+ timeout: false,399+ retry: {400+ limit: 1,401+ delay: () => 100,402+ jitter: () => Number.POSITIVE_INFINITY,403+ },404+ });405+406+ t.deepEqual(retryDelays, [100]);407+});408+409+// A 500 is not in the default `afterStatusCodes`, so its Retry-After is not a server instruction Ky follows.410+test.serial('a Retry-After on a status missing from afterStatusCodes is ignored in favor of the computed delay', async t => {411+ const retryDelays = captureRetryDelays(t);412+ const {fetch} = createFetch(status(500, {'Retry-After': '30'}), success);413+414+ await ky('https://example.com', {415+ fetch,416+ timeout: false,417+ retry: {418+ limit: 1,419+ delay: () => 100,420+ },421+ });422+423+ t.deepEqual(retryDelays, [100]);424+});modified:test/retry-timing.ts+72 added
86 unmodified lines87 88 test('Retry-After numbers are never treated as timestamps', t => {89 t.is(calculateRetryTimingDelay({value: '1700000000', allowTimestamp: false}), 1_700_000_000_000);90 });91+92+for (const [description, headers, expected] of [93+ ['RateLimit-Reset over X-RateLimit-Retry-After', {'RateLimit-Reset': '1', 'X-RateLimit-Retry-After': '2'}, {value: '1', allowTimestamp: true}],94+ ['X-RateLimit-Retry-After over X-RateLimit-Reset', {'X-RateLimit-Retry-After': '2', 'X-RateLimit-Reset': '3'}, {value: '2', allowTimestamp: false}],95+ ['X-RateLimit-Reset over X-Rate-Limit-Reset', {'X-RateLimit-Reset': '3', 'X-Rate-Limit-Reset': '4'}, {value: '3', allowTimestamp: true}],96+] as const) {97+ test(`retry timing header precedence prefers ${description}`, t => {98+ t.deepEqual(getRetryTimingHeader(new Headers(headers)), expected);99+ });100+}101+102+test('an empty X-RateLimit-Retry-After does not fall back to a reset header', t => {103+ t.deepEqual(getRetryTimingHeader(new Headers({'X-RateLimit-Retry-After': '', 'X-RateLimit-Reset': '3'})), {value: '', allowTimestamp: false});104+});105+106+test('HTTP dates with a year below 100 are not mapped to the 1900s', t => {107+ // `Date.UTC()` maps years 0-99 to 1900-1999. Such a date must still be a valid past date, not a malformed one that falls back to the normal retry delay.108+ t.is(calculateRetryTimingDelay({value: 'Fri, 01 Jan 0010 00:00:00 GMT', allowTimestamp: false}), 0);109+ t.is(calculateRetryTimingDelay({value: 'Fri Jan 1 00:00:00 0010', allowTimestamp: false}), 0);110+});111+112+test('RFC 850 date between 50 and 51 years in the future is interpreted as past', t => {113+ // The RFC 850 century window uses the real clock, so build the date from it.114+ const date = new Date();115+ date.setUTCFullYear(date.getUTCFullYear() + 50, date.getUTCMonth() + 6);116+ const weekday = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][date.getUTCDay()];117+ const month = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][date.getUTCMonth()];118+ const [day, year, time] = [119+ String(date.getUTCDate()).padStart(2, '0'),120+ String(date.getUTCFullYear() % 100).padStart(2, '0'),121+ date.toISOString().slice(11, 19),122+ ];123+124+ t.is(calculateRetryTimingDelay({value: `${weekday}, ${day}-${month}-${year} ${time} GMT`, allowTimestamp: false}), 0);125+});126+127+test.serial('asctime date with a two-digit day is parsed', t => {128+ const originalNow = Date.now;129+ t.teardown(() => {130+ Date.now = originalNow;131+ });132+ Date.now = () => Date.parse('2031-01-16T12:00:00Z');133+134+ t.is(calculateRetryTimingDelay({value: 'Thu Jan 16 12:00:02 2031', allowTimestamp: false}), 2000);135+});136+137+test('Retry-After HTTP date in year 9999 gives a finite delay', t => {138+ for (const value of ['Fri, 31 Dec 9999 23:59:59 GMT', 'Fri Dec 31 23:59:59 9999']) {139+ const delay = calculateRetryTimingDelay({value, allowTimestamp: false});140+ t.true(Number.isFinite(delay) && delay! > 0, `value: ${value}`);141+ }142+});143+144+for (const [description, value] of [145+ ['IMF-fixdate', 'Wed, 31 Dec 2031 23:59:60 GMT'],146+ ['asctime', 'Wed Dec 31 23:59:60 2031'],147+] as const) {148+ test.serial(`Retry-After ${description} leap second at the end of a year resolves to the start of the next year`, t => {149+ const originalNow = Date.now;150+ t.teardown(() => {151+ Date.now = originalNow;152+ });153+ Date.now = () => Date.parse('2031-12-31T23:59:59Z');154+155+ t.is(calculateRetryTimingDelay({value, allowTimestamp: false}), 1000);156+ });157+}158+159+// `Number()` of a long digit string overflows to `Infinity` rather than `NaN`, so the delay is unbounded but still a usable number for Ky to cap.160+test('Retry-After with more digits than a number can hold gives an infinite delay', t => {161+ t.is(calculateRetryTimingDelay({value: '9'.repeat(400), allowTimestamp: false}), Number.POSITIVE_INFINITY);162+});modified:test/retry.ts+107 added-5 removed
4836 unmodified lines4837 // Both limits feed `Math.min()`, so a non-number turns the retry delay into `NaN`, which `setTimeout()` clamps to 1ms. A `Retry-After: 1` header would then be retried almost immediately, which is the thundering herd those options exist to prevent.4838 test('rejects non-numeric or negative `maxRetryAfter` and `backoffLimit`', async t => {4839 for (const key of ['maxRetryAfter', 'backoffLimit'] as const) {4840 for (const value of ['1000', Number.NaN, -1, {}, null] as unknown[]) {4841- // `null` is nullish, so it selects the default instead of being rejected.4842- if (value === null) {4843- continue;4844- }4845-4841 const retry: Record<string, unknown> = {[key]: value};4842 4843 // eslint-disable-next-line no-await-in-loop4844 await t.throwsAsync(ky('https://example.com', {retry: retry as never}), {329 unmodified lines5174 });5175 }5176 });5177 5178+// `request` was only read with a truthiness check, so `null` was silently ignored and the retry quietly reused the original request, and a non-`Request` value such as a URL string was sent as-is.5179+test('a `ky.retry({request})` that is not a Request throws', async t => {5180+ for (const request of [null, 'https://example.com/other', {}]) {5181+ t.throws(() => new ForceRetryError({request: request as never}), {5182+ instanceOf: TypeError,5183+ message: 'The `ky.retry()` `request` option must be a `Request`',5184+ }, `request: ${JSON.stringify(request)}`);5185+ }5186+5187+ let attempts = 0;5188+ await t.throwsAsync(ky('https://example.com', {5189+ retry: {limit: 1, delay: () => 0},5190+ async fetch() {5191+ attempts++;5192+ return new Response('ok');5193+ },5194+ hooks: {afterResponse: [({retryCount}) => retryCount === 0 ? ky.retry({request: null as never}) : undefined]},5195+ }).text(), {5196+ instanceOf: TypeError,5197+ message: 'The `ky.retry()` `request` option must be a `Request`',5198+ });5199+ t.is(attempts, 1);5200+5201+ t.notThrows(() => new ForceRetryError({request: undefined}));5202+ t.notThrows(() => new ForceRetryError({request: new Request('https://example.com')}));5203+});5204+5205 // The replace-marker pass only held the values on the current path, so a value shared by two branches was resolved in the first and skipped in the second, which kept its `{value}` envelope. A genuine cycle is still left alone.5206 test('`replaceOption` resolves a shared value in every branch that uses it', t => {5207 const shared = {tags: replaceOption(['a'])};5208 const merged = validateAndMerge({custom: {first: shared, second: shared, list: [shared]}});122 unmodified lines5331 5332 t.is(requestCount, 2);5333 }5334 });5335+5336+test('a numeric string from `retry.delay` is rejected', async t => {5337+ let requestCount = 0;5338+5339+ await t.throwsAsync(ky('https://example.com', {5340+ async fetch() {5341+ requestCount++;5342+ return new Response(undefined, {status: 500});5343+ },5344+ retry: {limit: 1, delay: () => '100' as never},5345+ }).text(), {5346+ instanceOf: TypeError,5347+ message: '`retry.delay` must return a non-negative number or `Infinity`',5348+ });5349+5350+ t.is(requestCount, 1);5351+});5352+5353+test('a user abort while Ky waits out the rest of the totalTimeout budget throws the abort reason', async t => {5354+ const controller = new AbortController();5355+ const reason = new Error('Cancelled while waiting out the budget');5356+ let attempts = 0;5357+5358+ const error = await t.throwsAsync(ky('https://example.com', {5359+ signal: controller.signal,5360+ timeout: false,5361+ totalTimeout: 5000,5362+ retry: {5363+ limit: 3,5364+ // Longer than the budget, so Ky waits out the budget instead of the retry delay.5365+ delay() {5366+ // `retry.delay` runs just before the wait starts, so this fires once Ky is waiting.5367+ setTimeout(() => {5368+ controller.abort(reason);5369+ }, 0);5370+ return 10_000;5371+ },5372+ },5373+ async fetch() {5374+ attempts++;5375+ throw new TypeError('fetch failed');5376+ },5377+ }).text());5378+5379+ t.is(error, reason);5380+ t.is(attempts, 1);5381+});5382+5383+// The clock is frozen, so the remaining budget stays at exactly `totalTimeout` and the comparison with the retry delay is deterministic.5384+test.serial('a retry delay at or above the remaining totalTimeout budget waits out the budget and then times out', async t => {5385+ const originalPerformanceNow = globalThis.performance.now;5386+ globalThis.performance.now = () => 0;5387+ t.teardown(() => {5388+ globalThis.performance.now = originalPerformanceNow;5389+ });5390+5391+ const totalTimeout = 1_500_000;5392+5393+ for (const retryDelay of [totalTimeout, 2_000_000, Number.POSITIVE_INFINITY]) {5394+ let attempts = 0;5395+5396+ // eslint-disable-next-line no-await-in-loop5397+ await withCapturedTimeouts(async scheduledDelays => {5398+ await t.throwsAsync(ky('https://example.com', {5399+ timeout: false,5400+ totalTimeout,5401+ retry: {limit: 1, delay: () => retryDelay},5402+ async fetch() {5403+ attempts++;5404+ throw new TypeError('fetch failed');5405+ },5406+ }).text(), {instanceOf: TimeoutError}, `delay: ${retryDelay}`);5407+5408+ // The first timer bounds the fetch by the budget, and the second is the wait for the rest of the budget.5409+ t.deepEqual(scheduledDelays, [totalTimeout, totalTimeout], `delay: ${retryDelay}`);5410+ });5411+5412+ t.is(attempts, 1, `delay: ${retryDelay}`);5413+ }5414+});modified:test/stream.ts+12 added
1228 unmodified lines1229 t.is(error, callbackError);1230 t.false(isNetworkError(error));1231 });1232 1233+test('a response from a beforeRequest hook still reports download progress', async t => {1234+ const progressEvents: Progress[] = [];1235+ const text = await ky('https://example.com', {1236+ hooks: {beforeRequest: [() => new Response('abc')]},1237+ onDownloadProgress: progress => progressEvents.push(progress),1238+ fetch: async () => new Response('from fetch'),1239+ }).text();1240+1241+ t.is(text, 'abc');1242+ t.deepEqual(progressEvents.at(-1), {percent: 1, transferredBytes: 3, totalBytes: 3});1243+});1244+1245 // `Progress.totalBytes` is documented to be `0` when the total size cannot be determined, and it must agree with the `percent` it is reported with, which is computed from the same estimate.1246 test('download progress reports an unknown total as 0', async t => {1247 const progressEvents: Progress[] = [];1248 const text = await ky('https://example.com', {280 unmodified linesmodified:test/validation.ts+12 added
189 unmodified lines190 }191 }192 });193 194+test('setup errors also reject `.bytes()` with the same error', async t => {195+ if (typeof (Response.prototype as unknown as {bytes?: unknown}).bytes !== 'function') {196+ t.pass();197+ return;198+ }199+200+ const responsePromise = ky('https://example.com', {timeout: -1, fetch: okFetch});201+ const error = await t.throwsAsync(responsePromise);202+203+ t.is(await t.throwsAsync(responsePromise.bytes()), error);204+});205+206 // Option merging only checked `hooks` when it was an object, and replaced an invalid `retry`, so a later layer hid a `null` or another bad shape instead of reporting it.207 test('rejects a bad `hooks` or `retry` while merging, before a later layer can hide it', async t => {208 for (const hooks of [null, 'nope', []] as unknown[]) {209 t.throws(() => ky.create({hooks: hooks as never}), {37 unmodified linesmodified:readme.md+9 added-7 removed
1013 unmodified lines1014 rainbow: undefined1015 },1016 hooks: {1017 beforeRequest: undefined,1018- afterResponse: [ () => console.log('after 2') ],1018+ afterResponse: [1019+ ({request}) => {1020+ console.log('after 2');1021+ console.log(request.headers.has('rainbow'));1022+ console.log(request.headers.has('unicorn'));1023+ }1024+ ],1025 }1026 });1027 1022-const response = await extended(url);1028+await extended(url);1029 //=> after 11030 //=> after 21025-1026-console.log(response.headers.has('rainbow'));1031 //=> false1028-1029-console.log(response.headers.has('unicorn'));1032 //=> true1033 ```1034 1035 You can also refer to parent defaults by providing a function to `.extend()`.142 unmodified lines1178 Type: `Request`1179 1180 Custom request to use for the retry.1181 1180-This allows you to modify or completely replace the request during a forced retry. The custom request becomes the starting point for the retry - `beforeRetry` hooks can still further modify it if needed.1182+This allows you to modify or completely replace the request during a forced retry. The custom request becomes the starting point for the retry - `beforeRetry` hooks can still further modify it if needed. Anything other than a `Request` or `undefined` makes the request throw a `TypeError`.1183 1184 **Note:** The custom request's `signal` will be replaced with Ky's managed signal to handle timeouts and user-provided abort signals correctly. If the original request body has been consumed, you must provide a new body or clone the request before consuming.1185 1186 > [!WARNING]747 unmodified lines