Skip to content
Myr

Accept a cross-realm `beforeError` error and validate a `ky.retry({delay})`

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 0a9cbb1 · Browse files · 7 files+138 added−10 removed
This commit

State

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

Diff stats

7 files+138 added−10 removed

  • tests:+115 added−1 removed
  • other:+23 added−9 removed

7 files+138 added−10 removed

modified:source/core/constants.ts+2 added
75 unmodified lines
7677 If not provided, uses the default retry delay calculation based on `retry.delay` configuration.7879 **Note:** Custom delays bypass jitter and `backoffLimit`. This is intentional, as custom delays often come from server responses (e.g., `Retry-After` headers) and should be respected exactly as specified.8081 Must be a non-negative number, or `undefined`; anything else throws a `TypeError` rather than collapsing to a 1ms retry.82 */83 delay?: number | undefined;8485 /**
204 unmodified lines
modified:source/core/Ky.ts+6 added-4 removed
35 unmodified lines
36import delay from '../utils/delay.js';37import {type ObjectEntries} from '../utils/types.js';38import {findUnknownOptions, hasSearchParameters} from '../utils/options.js';39import isRawNetworkError from '../utils/is-network-error.js';40import {isError} from '../utils/is.js';41import {42 isHTTPError, isNetworkError, isTimeoutError, isResponseSizeError, isForceRetryError,43} from '../utils/type-guards.js';44import {
727 unmodified lines
772773 // Defaults to the last request that was actually sent, because `this.request` is the clone `#fetch()` prepares774 // for a possible retry and may never be sent at all.775 async #throwProcessedError(error: unknown, request: Request = this.#originalRequest ?? this.request): Promise<never> {775 // Non-Error throws (e.g., thrown strings) pass through unchanged776 if (!(error instanceof Error)) {776 // Non-Error throws (e.g., thrown strings) pass through unchanged. `isError` reads the internal brand, so an777 // error from another realm still runs the hooks, the same way the Ky type guards accept branded errors.778 if (!isError(error)) {779 throw error;780 }781782 // Errors thrown by beforeRetry hooks must propagate unchanged.
11 unmodified lines
794 error: processedError,795 retryCount: this.#retryCount,796 });797796 // Only overwrite if the hook returns a valid Error instance.797 if (hookResult instanceof Error) {798 // Only overwrite if the hook returns a valid Error, including one from another realm.799 if (isError(hookResult)) {800 processedError = hookResult;801 }802 }803
713 unmodified lines
modified:source/errors/ForceRetryError.ts+8 added-1 removed
modified:source/utils/is-network-error.ts+1 added-4 removed
modified:source/utils/is.ts+6 added
modified:test/hooks.ts+70 added-1 removed
1import {setTimeout as delay} from 'node:timers/promises';2import test from 'ava';2import {runInNewContext} from 'node:vm';3import test, {type ExecutionContext} from 'ava';4import ky, {5 HTTPError,6 KyError,7 isHTTPError,
7266 unmodified lines
72747275test('`hooks: null` selects the default', async t => {7276 t.is(await ky('https://example.com', {hooks: null as never, fetch: async () => new Response('ok')}).text(), 'ok');7277});72787279// `instanceof Error` fails for an error from another realm, so a cross-realm failure skipped the hooks entirely and7280// a cross-realm replacement from a hook was dropped. The Ky type guards already accept branded errors from another7281// copy of Ky, so the error checks here read the internal brand too.7282test('a cross-realm error thrown by fetch still runs `beforeError` hooks', async t => {7283 const foreignError = runInNewContext('new Error("foreign fetch failure")') as Error;7284 const seen: string[] = [];72857286 await t.throwsAsync(ky('https://example.com', {7287 retry: 0,7288 async fetch() {7289 throw foreignError;7290 },7291 hooks: {7292 beforeError: [({error}) => {7293 seen.push(String(error));7294 }],7295 },7296 }).text(), {message: 'foreign fetch failure'});72977298 t.deepEqual(seen, ['Error: foreign fetch failure']);7299});73007301test('a `beforeError` hook can replace the error with one from another realm', async t => {7302 const foreignError = runInNewContext('new Error("replacement from another realm")') as Error;73037304 const error = await t.throwsAsync(ky('https://example.com', {7305 retry: 0,7306 async fetch() {7307 return new Response('server error', {status: 500});7308 },7309 hooks: {7310 beforeError: [() => foreignError],7311 },7312 }).text());73137314 t.is(error, foreignError);7315});73167317test('a non-Error value from a `beforeError` hook is still ignored', async t => {7318 const error = await t.throwsAsync(ky('https://example.com', {7319 retry: 0,7320 fetch: async () => new Response('server error', {status: 500}),7321 hooks: {7322 beforeError: [() => 'not an error' as never],7323 },7324 }).text());73257326 t.is(error?.name, 'HTTPError');7327});73287329test('a non-Error value thrown by a hook still passes through unchanged', async t => {7330 try {7331 await ky('https://example.com', {7332 retry: 0,7333 fetch: async () => new Response('ok'),7334 hooks: {7335 beforeRequest: [() => {7336 // eslint-disable-next-line @typescript-eslint/only-throw-error7337 throw 'thrown string';7338 }],7339 },7340 }).text();7341 t.fail('should have thrown');7342 } catch (error) {7343 t.is(error, 'thrown string');7344 }7345});
modified:test/retry.ts+45 added
2 unmodified lines
3import test, {type ExecutionContext} from 'ava';4import LeakDetector from 'jest-leak-detector';5import ky, {6 replaceOption,7 ForceRetryError,8 NetworkError,9 TimeoutError,10 isKyError,11 isNetworkError,
5010 unmodified lines
5022 await t.throwsAsync(promise, {name: 'AbortError'});5023 t.is(hookErrors.length, 1);5024 });5025}50265027// A custom delay flows straight into `setTimeout`, so a negative or `NaN` value was clamped to 1ms and the process printed a Node warning, silently collapsing the backoff. `retry.delay` results are validated the same way.5028test('rejects a `ky.retry({delay})` value that cannot be a delay', async t => {5029 for (const delay of [-1, Number.NaN, '1000', {}] as unknown[]) {5030 // eslint-disable-next-line no-await-in-loop5031 await t.throwsAsync(ky('https://example.com', {5032 retry: {limit: 1, delay: () => 0},5033 fetch: async () => new Response('server error', {status: 500}),5034 hooks: {afterResponse: [() => ky.retry({delay: delay as never})]},5035 }).text(), {5036 instanceOf: TypeError,5037 message: 'The `delay` option must be a non-negative number or `Infinity`',5038 }, `delay: ${JSON.stringify(delay)}`);5039 }5040});50415042test('a rejected `ky.retry({delay})` never reaches the retry delay', async t => {5043 let attempts = 0;5044 const error = await t.throwsAsync(ky('https://example.com', {5045 retry: {limit: 1, delay: () => 0},5046 async fetch() {5047 attempts++;5048 return new Response('server error', {status: 500});5049 },5050 hooks: {afterResponse: [() => ky.retry({delay: -1})]},5051 }).text());50525053 t.is(attempts, 1);5054 t.is(error?.name, 'TypeError');5055});50565057// The message used a truthiness check while `code` was assigned without one, so a falsy code was silently dropped from the message the `code` documentation promises.5058test('a falsy `ky.retry({code})` still appears in the ForceRetryError message', t => {5059 for (const code of ['', 0, false] as unknown[]) {5060 const error = new ForceRetryError({code: code as never});50615062 t.is(error.code, code);5063 t.is(error.message, `Forced retry: ${String(code)}`);5064 }50655066 t.is(new ForceRetryError().message, 'Forced retry');5067 t.is(new ForceRetryError({}).message, 'Forced retry');5068 t.is(new ForceRetryError({code: 'RATE_LIMIT'}).message, 'Forced retry: RATE_LIMIT');5069});