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
Provenance
- Commit
bd0e26f- Tree
2591037- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
Sindre Sorhus <sindresorhus@gmail.com>- Parent
0a9cbb1
7 files changed+138 added−10 removed
modified:source/core/constants.ts+2 added
75 unmodified lines76 77 If not provided, uses the default retry delay calculation based on `retry.delay` configuration.78 79 **Note:** Custom delays bypass jitter and `backoffLimit`. This is intentional, as custom delays often come from server responses (e.g., `Retry-After` headers) and should be respected exactly as specified.80+81+ Must be a non-negative number, or `undefined`; anything else throws a `TypeError` rather than collapsing to a 1ms retry.82 */83 delay?: number | undefined;84 85 /**204 unmodified linesmodified:source/core/Ky.ts+6 added-4 removed
35 unmodified lines36 import delay from '../utils/delay.js';37 import {type ObjectEntries} from '../utils/types.js';38 import {findUnknownOptions, hasSearchParameters} from '../utils/options.js';39 import isRawNetworkError from '../utils/is-network-error.js';40+import {isError} from '../utils/is.js';41 import {42 isHTTPError, isNetworkError, isTimeoutError, isResponseSizeError, isForceRetryError,43 } from '../utils/type-guards.js';44 import {727 unmodified lines772 773 // 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 }781 782 // Errors thrown by beforeRetry hooks must propagate unchanged.11 unmodified lines794 error: processedError,795 retryCount: this.#retryCount,796 });797 796- // 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 linesmodified:source/errors/ForceRetryError.ts+8 added-1 removed
12 unmodified lines1314151617181920212223242526272829243031323334354 unmodified lines12 unmodified lines code: string | undefined; customRequest: Request | undefined;
constructor(options?: ForceRetryOptions) { // The custom delay flows straight into `setTimeout`, so a negative or `NaN` value would be clamped to 1ms and silently collapse the backoff, the same failure mode validated away for `retry.delay`. const {delay} = options ?? {}; if (delay !== undefined && (typeof delay !== 'number' || Number.isNaN(delay) || delay < 0)) { throw new TypeError('The `delay` option must be a non-negative number or `Infinity`'); }
// Runtime protection: wrap non-Error causes in NonError // TypeScript type is Error for guidance, but JS users can pass anything const cause = options?.cause === undefined ? undefined : (options.cause instanceof Error ? options.cause : new NonError(options.cause));
super( options?.code ? `Forced retry: ${options.code}` : 'Forced retry', // `code` is documented as always reaching the message, so only an absent code falls back. options?.code === undefined ? 'Forced retry' : `Forced retry: ${options.code}`, cause ? {cause} : undefined, );
this.customDelay = options?.delay;4 unmodified linesmodified:source/utils/is-network-error.ts+1 added-4 removed
1233456456739 unmodified lines// Inlined from https://github.com/sindresorhus/is-network-error v1.3.2import {isError} from './is.js';
const objectToString = Object.prototype.toString;
const isError = (value: unknown): value is Error => objectToString.call(value) === '[object Error]';
const errorMessages = new Set([ 'network error', // Chrome 'NetworkError when attempting to fetch resource.', // Firefox 'The Internet connection appears to be offline.', // Safari 1639 unmodified linesmodified:source/utils/is.ts+6 added
12345678// eslint-disable-next-line @typescript-eslint/no-restricted-typesexport const isObject = (value: unknown): value is object => value !== null && typeof value === 'object';
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]';modified:test/hooks.ts+70 added-1 removed
1 import {setTimeout as delay} from 'node:timers/promises';2-import test from 'ava';2+import {runInNewContext} from 'node:vm';3+import test, {type ExecutionContext} from 'ava';4 import ky, {5 HTTPError,6 KyError,7 isHTTPError,7266 unmodified lines7274 7275 test('`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 });7278+7279+// `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.7282+test('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[] = [];7285+7286+ 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'});7297+7298+ t.deepEqual(seen, ['Error: foreign fetch failure']);7299+});7300+7301+test('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;7303+7304+ 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());7313+7314+ t.is(error, foreignError);7315+});7316+7317+test('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());7325+7326+ t.is(error?.name, 'HTTPError');7327+});7328+7329+test('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 lines3 import test, {type ExecutionContext} from 'ava';4 import LeakDetector from 'jest-leak-detector';5 import ky, {6 replaceOption,7+ ForceRetryError,8 NetworkError,9 TimeoutError,10 isKyError,11 isNetworkError,5010 unmodified lines5022 await t.throwsAsync(promise, {name: 'AbortError'});5023 t.is(hookErrors.length, 1);5024 });5025 }5026+5027+// 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.5028+test('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+});5041+5042+test('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());5052+5053+ t.is(attempts, 1);5054+ t.is(error?.name, 'TypeError');5055+});5056+5057+// 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.5058+test('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});5061+5062+ t.is(error.code, code);5063+ t.is(error.message, `Forced retry: ${String(code)}`);5064+ }5065+5066+ 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+});