Skip to content
Myr

Stop surfacing progress callback errors

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 55599c8 · Browse files · 11 files+47 added−336 removed
This commit

State

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

Diff stats

11 files+47 added−336 removed

  • tests:+20 added−246 removed
  • other:+27 added−90 removed

11 files+47 added−336 removed

modified:source/core/Ky.ts+11 added-44 removed
13 unmodified lines
14 SearchParamsOption,15} from '../types/options.js';16import {type ResponsePromise} from '../types/ResponsePromise.js';17import type {StandardSchemaV1} from '../types/standard-schema.js';18import {limitResponseSize, streamRequest, streamResponse} from '../utils/body.js';19import {19 getProgressCallbackError,20 limitResponseSize,21 streamRequest,22 streamResponse,23} from '../utils/body.js';24import {20 cloneShallow,21 cloneDeep,22 mergeHeaders,23 mergeHeaderContainers,
140 unmodified lines
164 const clonedOptions: Options = {165 ...options,166 // `headers` starts as a plain object with lowercase names in `init` hooks, so hooks can add headers in place even when none were provided.167 headers: mergeHeaderContainers({}, options.headers ?? {}),173 // `context` starts as an object in `init` hooks, the same as in every other hook.174 context: cloneDeep(options.context) ?? {},168 // `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`.169 context: {...options.context},170 // Deep-clone so init-hook mutations to nested values do not leak across requests, matching the nested `retry` cloning below.171 json: cloneDeep(options.json),172 searchParams: cloneSearchParametersForInitHook(options.searchParams),173 };
239 unmodified lines
413 #originalRequest?: Request;414 #requestBodyCanBeCancelled = false;415 readonly #userProvidedAbortSignal: AbortSignal | undefined;416 readonly #beforeRetryHookErrors = new WeakSet<Error>();422 // Values thrown by a user callback that runs while the request is in flight. Retrying would re-send the body and run the callback again, so they are never retriable, whatever `shouldRetry` says. A strong `Set` is safe because a `Ky` instance lives for exactly one request, and the callback can throw a non-`Error` value.423 readonly #inFlightCallbackErrors = new Set<unknown>();417 #cachedNormalizedOptions: NormalizedOptions | undefined;418 readonly #startTime: number | undefined;419 #returnedResponseFromBeforeRetryHook = false;420 readonly #responseRequests = new WeakMap<Response, Request>();
210 unmodified lines
631 return Math.min(retry.backoffLimit, jitteredDelay);632 }633634 async #calculateRetryDelay(error: unknown) {642 if (this.#inFlightCallbackErrors.has(error)) {643 throw error;644 }645635 const retry = normalizeRetryOptions(this.#options.retry);636 if (this.#retryCount >= Math.min(retry.limit, this.#retryLimit)) {637 throw error;638 }
36 unmodified lines
675676 return this.#calculateDelay(retry, error);677 }678690 // The `isHTTPError()` brand only checks `name`, so a cross-realm error may not carry a `response`.691 if (isHTTPError(error) && error.response) {679 if (isHTTPError(error)) {680 if (!shouldRetryOverride && !retry.statusCodes.includes(error.response.status)) {681 throw error;682 }683
31 unmodified lines
715716 this.#decoratedResponses.add(response);717 const request = this.#getResponseRequest(response);718731 try {732 response.json = async () => {733 const text = await response.text();734 return this.#options.parseJson!(text, {request, response});735 };719 response.json = async () => {720 const text = await response.text();721 return this.#options.parseJson!(text, {request, response});722 };723737 // `clone()` returns a fresh `Response` that would otherwise fall back to the native `json()`.738 const nativeClone = response.clone.bind(response);739 response.clone = () => this.#decorateResponse(this.#setResponseRequest(nativeClone(), request));740 } catch (error: unknown) {741 // A frozen response cannot be decorated, so the caller never receives it and nothing else can release its body. Report the real problem and let go of the connection.742 this.#cancelResponseBody(response);743 throw error;744 }724 // `clone()` returns a fresh `Response` that would otherwise fall back to the native `json()`.725 const nativeClone = response.clone.bind(response);726 response.clone = () => this.#decorateResponse(this.#setResponseRequest(nativeClone(), request));727728 return response;729 }730
136 unmodified lines
867 await this.#throwProcessedError(this.#userProvidedAbortSignal.reason, failedRequest);868 }869870 if (this.#getRemainingTotalTimeout() !== 0) {889 // A throwing progress callback errors the response stream, which a browser may report as a raw `TypeError` that would otherwise be mistaken for a dropped connection. Surface the callback error instead.890 const progressCallbackError = getProgressCallbackError(response.body ?? undefined);891 if (progressCallbackError !== undefined) {892 await this.#throwProcessedError(progressCallbackError, failedRequest);893 }894871 // A connection dropped while streaming the body surfaces as a raw runtime `TypeError`. Wrap it like fetch-phase network errors so it is recognizable and runs `beforeError` hooks.872 // This only happens on the awaited path, so a body that fails after the timeout already won does not run the hooks again.873 if (isRawNetworkError(error)) {874 await this.#throwProcessedError(new NetworkError(failedRequest, {cause: error as Error}), failedRequest);
519 unmodified lines
1394 this.#abortController?.abort();1395 throw new TimeoutError(request);1396 }13971422 // The upload progress wrapper errors the request body stream when its callback throws, which the runtime reports as a network failure. Surface the callback error instead.1423 const progressCallbackError = getProgressCallbackError(this.#originalRequest?.body ?? undefined);1424 if (progressCallbackError !== undefined) {1425 this.#inFlightCallbackErrors.add(progressCallbackError);14261427 // eslint-disable-next-line @typescript-eslint/only-throw-error -- The callback can throw any value, and non-Error throws are propagated as-is elsewhere.1428 throw progressCallbackError;1429 }14301398 if (isRawNetworkError(error)) {1399 throw new NetworkError(request, {cause: error as Error});1400 }1401
91 unmodified lines
modified:source/types/hooks.ts+2 added-2 removed
3 unmodified lines
45/**6This hook enables you to modify the options before they are used to construct the request. The hook function receives the mutable options object and can modify it in place. You could, for example, modify `searchParams`, `headers`, or `json` here. The `headers` option starts as a plain object with lowercase names, where a header removed with `undefined` keeps an `undefined` value.78Ky gives the hook its own copies of `headers`, `context`, `json`, `searchParams` and `retry`, so changing them in place only affects the current request. The `context` copy is deep, so when an instance has an `init` hook, nested `context` values are not shared across requests. The `body` option is not copied, so mutating a `FormData` or `URLSearchParams` body in place changes your own object and repeats on every request from the same instance. Assign a new instance instead, as shown in [Modifying FormData in hooks](https://github.com/sindresorhus/ky#modifying-formdata-in-hooks). A value that a hook assigns is used as is, so assign a new object rather than one that you change later.8Ky gives the hook its own copies of `headers`, `context`, `json`, `searchParams` and `retry`, so changing them in place only affects the current request. The `context` copy is shallow, the same as in every other hook, so nested `context` values, such as a cache, stay shared across requests. The `body` option is not copied, so mutating a `FormData` or `URLSearchParams` body in place changes your own object and repeats on every request from the same instance. Assign a new instance instead, as shown in [Modifying FormData in hooks](https://github.com/sindresorhus/ky#modifying-formdata-in-hooks). A value that a hook assigns is used as is, so assign a new object rather than one that you change later.910Unlike other hooks, `init` hooks are synchronous. An error thrown by one rejects the returned promise and is not passed to `beforeError` hooks.1112@example
77 unmodified lines
90export type Hooks = {91 /**92 This hook enables you to modify the options before they are used to construct the request. The hook function receives the mutable options object and can modify it in place. You could, for example, modify `searchParams`, `headers`, or `json` here. The `headers` option starts as a plain object with lowercase names, where a header removed with `undefined` keeps an `undefined` value.9394 Ky gives the hook its own copies of `headers`, `context`, `json`, `searchParams` and `retry`, so changing them in place only affects the current request. The `context` copy is deep, so when an instance has an `init` hook, nested `context` values are not shared across requests. The `body` option is not copied, so mutating a `FormData` or `URLSearchParams` body in place changes your own object and repeats on every request from the same instance. Assign a new instance instead, as shown in [Modifying FormData in hooks](https://github.com/sindresorhus/ky#modifying-formdata-in-hooks). A value that a hook assigns is used as is, so assign a new object rather than one that you change later.94 Ky gives the hook its own copies of `headers`, `context`, `json`, `searchParams` and `retry`, so changing them in place only affects the current request. The `context` copy is shallow, the same as in every other hook, so nested `context` values, such as a cache, stay shared across requests. The `body` option is not copied, so mutating a `FormData` or `URLSearchParams` body in place changes your own object and repeats on every request from the same instance. Assign a new instance instead, as shown in [Modifying FormData in hooks](https://github.com/sindresorhus/ky#modifying-formdata-in-hooks). A value that a hook assigns is used as is, so assign a new object rather than one that you change later.9596 Unlike other hooks, `init` hooks are synchronous. An error thrown by one rejects the returned promise and is not passed to `beforeError` hooks.9798 A common use case is to add a search parameter to every request:
278 unmodified lines
modified:source/types/options.ts+4 added-2 removed
297 unmodified lines
298 `content-length` is only used as the total for a response that is not content-coded, since it counts encoded bytes while the progress stream counts the bytes after decompression. A compressed response therefore reports `totalBytes: 0` until it completes, which means the percentage cannot be calculated while downloading.299300 Responses with no body at all are not streamed, so no progress events are emitted for them. That covers a [null body status](https://fetch.spec.whatwg.org/#null-body-status) such as `204`, and a `HEAD` response in runtimes that give it no body, such as browsers, Node.js and Deno. Bun gives a `HEAD` response an empty body, so it reports one final event with `transferredBytes: 0`. A response whose body an `afterResponse` hook already read, or locked with a reader, is passed through unchanged, so it reports no progress either.301302 When the callback throws, the error is reported by Ky's body method shortcuts. A response read directly with `response.text()` or `response.json()` may instead report the runtime's own stream error, such as Chromium's generic `TypeError`.302 Do not throw from the callback. A throw fails the response stream, which the runtime reports in its own way: Node.js rejects the body read with your error, while Chromium reports a network failure, so Ky's body methods throw a `NetworkError` there. Pass a `signal` from an `AbortController` to cancel instead.303304 @example305 ```306 import ky from 'ky';
16 unmodified lines
323324 @param progress - Object containing upload progress information.325 @param chunk - Data that was sent. When an empty request body stream completes, the callback receives an empty chunk.326327 A `ReadableStream` body cannot be measured, so `totalBytes` falls back to a `content-length` header you set. Browsers do not allow that header on a request, so there the total stays `0`.327 A `ReadableStream` body cannot be measured, so `totalBytes` falls back to a `content-length` header you set. Browsers do not allow that header on a request, so there the total stays `0`. When a hook replaces the request, `totalBytes` is still estimated from the `body` option until the final event, which reports the real total.328329 Do not throw from the callback. A throw fails the upload stream, which the runtime reports as a network failure, so Ky throws a `NetworkError` (in Node.js, with your error in its `cause` chain) and retries it like any other network error, running the callback again. Pass a `signal` from an `AbortController` to cancel instead.330331 @example332 ```333 import ky from 'ky';334
216 unmodified lines
modified:source/utils/body.ts+5 added-39 removed
1import type {Options, Progress} from '../types/options.js';1import type {Options} from '../types/options.js';2import {responseTypes, usualFormBoundarySize} from '../core/constants.js';3import {ResponseSizeError} from '../errors/ResponseSizeError.js';45const encoder = new TextEncoder();6const responseSizeErrors = new WeakMap<ReadableStream, () => ResponseSizeError | undefined>();7// Errors thrown by a progress callback, keyed by the stream the callback reports on.8// A throwing progress callback is a user error, but the runtime reports the resulting stream failure as a network error, so Ky needs the original error to surface it as-is.9const progressCallbackErrors = new WeakMap<ReadableStream, () => unknown>();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.8const nullBodyStatuses = new Set([101, 103, 204, 205, 304]);910// 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.
52 unmodified lines
6364const withProgress = (stream: ReadableStream<Uint8Array>, totalBytes: number, onProgress: Options['onDownloadProgress'] | Options['onUploadProgress']): ReadableStream<Uint8Array> => {65 let previousChunk: Uint8Array | undefined;66 let transferredBytes = 0;70 let progressCallbackError: unknown;71 const report = (progress: Progress, chunk: Uint8Array) => {72 try {73 onProgress?.(progress, chunk);74 } catch (error) {75 // Remember the error so Ky can surface it instead of the network error the runtime reports for the failed stream.76 progressCallbackError = error;77 throw error;78 }79 };6781 // The transformer only runs after construction, so its error accessor can be registered immediately afterwards.82 const progressStream: ReadableStream<Uint8Array> = stream.pipeThrough(new TransformStream<Uint8Array, Uint8Array>({68 return stream.pipeThrough(new TransformStream<Uint8Array, Uint8Array>({69 transform(currentChunk, controller) {70 controller.enqueue(currentChunk);7172 if (previousChunk) {
8 unmodified lines
81 }8283 // An unknown total stays `0`, matching the `percent` computed from the same estimate and the documented progress shape.84 const reportedTotalBytes = totalBytes === 0 ? 0 : Math.max(totalBytes, transferredBytes);99 report({percent, totalBytes: reportedTotalBytes, transferredBytes}, previousChunk);85 onProgress?.({percent, totalBytes: reportedTotalBytes, transferredBytes}, previousChunk);86 }8788 previousChunk = currentChunk;89 },90 flush() {91 const finalChunk = previousChunk ?? new Uint8Array();92 transferredBytes += finalChunk.byteLength;107 report({percent: 1, totalBytes: transferredBytes, transferredBytes}, finalChunk);93 onProgress?.({percent: 1, totalBytes: transferredBytes, transferredBytes}, finalChunk);94 },95 }));110 progressCallbackErrors.set(progressStream, () => progressCallbackError);111112 return progressStream;96};97115/**116The error thrown by a progress callback while reporting on the given stream, if the callback threw.117*/118export const getProgressCallbackError = (stream: ReadableStream | undefined): unknown =>119 stream ? progressCallbackErrors.get(stream)?.() : undefined;12098const copyResponseMetadata = (response: Response, originalResponse: Response, getError = originalResponse.body ? responseSizeErrors.get(originalResponse.body) : undefined): Response => {99 const nativeClone = response.clone.bind(response);123 const getProgressError = response.body124 ? progressCallbackErrors.get(response.body) ?? (originalResponse.body ? progressCallbackErrors.get(originalResponse.body) : undefined)125 : undefined;126 if (response.body && getProgressError) {127 progressCallbackErrors.set(response.body, getProgressError);128 }129100 if (response.body && getError) {101 responseSizeErrors.set(response.body, getError);102103 // Chromium replaces stream errors with a generic TypeError in native body methods.
29 unmodified lines
133 // Keep the shim replaceable like `Response.prototype.clone` for instrumentation and mocks.134 clone: {135 value() {136 const clone = nativeClone();167 // Cloning replaces the original body too, so retain the error accessors on both branches.137 // Cloning replaces the original body too, so retain the error accessor on both branches.138 if (response.body && getError) {139 responseSizeErrors.set(response.body, getError);140 }141172 if (response.body && getProgressError) {173 progressCallbackErrors.set(response.body, getProgressError);174 }175142 return copyResponseMetadata(clone, response);143 },144 writable: true,145 configurable: true,
84 unmodified lines
modified:test/browser.ts-61 removed
109 unmodified lines
110111 t.deepEqual(result, {status: 204, header: 'ky', text: ''});112});113114// A throwing progress callback is a user error. Chromium reports the failed response stream as a generic `TypeError`, so the callback error must survive that instead of becoming a `NetworkError` or a `TypeError`.115browserTest('a throwing download progress callback propagates its own error', [chromium, webkit], async (t, page) => {116 server.get('/', (_request, response) => {117 response.end('body');118 });119120 await page.goto(server.url);121 await addKyScriptToPage(page);122123 const result = await page.evaluate(async (url: string) => {124 try {125 await globalThis.ky(url, {126 retry: 0,127 onDownloadProgress() {128 throw new Error('download progress failed');129 },130 }).text();131 return {errorName: 'none', message: 'none'};132 } catch (error) {133 return {errorName: (error as Error).name, message: (error as Error).message};134 }135 }, server.url);136137 t.deepEqual(result, {errorName: 'Error', message: 'download progress failed'});138});139140browserTest('cloning a response preserves download progress callback errors', [chromium], async (t, page) => {141 server.get('/', (_request, response) => {142 response.end('body');143 });144145 await page.goto(server.url);146 await addKyScriptToPage(page);147148 const result = await page.evaluate(async (url: string) => {149 const callbackError = new Error('download progress failed');150 const pending = globalThis.ky(url, {151 retry: 0,152 onDownloadProgress() {153 throw callbackError;154 },155 });156 const response = await pending;157 const clone = response.clone();158 void clone.body?.cancel().catch(() => undefined);159160 try {161 await pending.text();162 return {sameError: false, errorName: 'none', message: 'none'};163 } catch (error) {164 return {165 sameError: error === callbackError,166 errorName: (error as Error).name,167 message: (error as Error).message,168 };169 }170 }, server.url);171172 t.deepEqual(result, {sameError: true, errorName: 'Error', message: 'download progress failed'});173});174114// WebKit exposes a body for `205 Reset Content`, which the Fetch spec lists as a null body status. Ky cannot wrap such a response, because the `Response` constructor rejects a body for those statuses, so `maxResponseSize` and `onDownloadProgress` do not apply to it.115browserTest('maxResponseSize does not apply to a 205 response body in WebKit', [webkit], async (t, page) => {116 server.get('/', (_request, response) => {117 response.end('ok');
715 unmodified lines
modified:test/context.ts+11 added-11 removed
266 unmodified lines
267 t.is(beforeRequestCalls, 1);268 });269}270271// The `init` hook copy is shallow, so it must still copy symbol keys, and replacing one only affects the current request.271test('init hook mutations to symbol-keyed context stay isolated between requests', async t => {272test('init hook symbol-keyed context assignments stay isolated between requests', async t => {273 const metadataKey = Symbol('metadata');274 const metadata = {attempt: 0};275 const context = {[metadataKey]: metadata};276 let initCalls = 0;
2 unmodified lines
279 context,280 hooks: {281 init: [options => {282 initCalls++;282 const clonedMetadata = Reflect.get(options.context, metadataKey) as typeof metadata;283 t.not(clonedMetadata, metadata);284 t.deepEqual(clonedMetadata, {attempt: 0});285 clonedMetadata.attempt++;283 t.is(Reflect.get(options.context, metadataKey), metadata);284 Reflect.set(options.context, metadataKey, {attempt: 1});285 }],286 beforeRequest: [({options}) => {287 beforeRequestCalls++;288 t.deepEqual(options.context, {[metadataKey]: {attempt: 1}});
8 unmodified lines
297 t.is(initCalls, 2);298 t.is(beforeRequestCalls, 2);299});300302// Context is merged shallowly, so a nested object is shared by every request from the instance, which lets hooks keep state such as a cache in it. An `init` hook gets a deep copy, so this does not hold for an instance with one.301// Context is merged shallowly, so a nested object is shared by every request from the instance, which lets hooks keep state such as a cache in it. An `init` hook gets a shallow copy too, so having one does not change this.302test('a nested context object is shared across requests', async t => {303 const context = {cache: {count: 0}};304 const api = ky.create({305 context,306 hooks: {307 init: [() => undefined],308 beforeRequest: [({options}) => {309 (options.context.cache as typeof context.cache).count++;310 }],311 },
32 unmodified lines
344 t.is(seen[0], seen[1]);345 t.deepEqual(seen[1], {shared: 'set-in-beforeRequest'});346});347348// `init` hooks get a deep copy of the context, which must keep a null prototype.349test('a nested null-prototype context value keeps its prototype in an `init` hook', async t => {348// `init` hooks get a deep copy of `json`, which must keep a null prototype.349test('a nested null-prototype json value keeps its prototype in an `init` hook', async t => {350 const bag = Object.create(null) as Record<string, unknown>;351 bag.count = 1;352353 let seen: Record<string, unknown> | undefined;354 const api = ky.create({355 context: {bag},355 json: {bag},356 hooks: {357 init: [options => {358 seen = options.context!.bag as Record<string, unknown>;358 seen = (options.json as {bag: Record<string, unknown>}).bag;359 }],360 },361 fetch: async () => new Response('ok'),362 });363364 await api('https://example.com').text();364 await api.post('https://example.com').text();365366 t.is(Object.getPrototypeOf(seen!), null);367 // A null-prototype object has no inherited members.368 t.is(seen!.toString, undefined);
35 unmodified lines
modified:test/hooks.ts+4 added-3 removed
6173 unmodified lines
61746175 t.deepEqual(seenRequestIdentifiers, [1, 2]);6176});61776178// `init` hooks get a shallow `context` copy like every other hook, so a nested value such as a cache stays shared, and adding an `init` hook does not change that.6178test('init hook nested context mutations do not leak across requests', async t => {6179test('init hook nested context values are shared across requests', async t => {6180 const seenCounts: number[] = [];61816182 const api = ky.extend({6183 context: {session: {count: 0}},
11 unmodified lines
61956196 await api.get('https://example.com');6197 await api.get('https://example.com');61986198 t.deepEqual(seenCounts, [0, 0]);6199 t.deepEqual(seenCounts, [0, 1]);6200});62016201test('init hook keeps a class-instance context value by reference across the deep clone', async t => {6202test('init hook keeps a class-instance context value by reference', async t => {6203 const store = new Map<string, number>();6204 let sawSameStore = false;62056206 const api = ky.extend({
1177 unmodified lines
modified:test/response-size.ts-28 removed
565 unmodified lines
566 response.headers.set('x-injected', '1');567 }, {instanceOf: TypeError});568});569570// Decoration assigns to the response, so a frozen one throws. The caller then gets the error and never receives the response, which left its body with nobody able to release it.571test('a response that cannot be decorated releases its body', async t => {572 let release: () => void;573 // Awaiting the cancel itself, rather than a sleep, keeps this reliable on a loaded machine.574 const cancelled = new Promise<void>(resolve => {575 release = resolve;576 });577 const body = new ReadableStream<Uint8Array>({578 start(controller) {579 controller.enqueue(new TextEncoder().encode('{"a":1}'));580 },581 cancel() {582 release!();583 },584 });585586 const error = await t.throwsAsync(ky(url, {587 retry: 0,588 parseJson: (text: string) => JSON.parse(text),589 fetch: async () => Object.freeze(new Response(body, {headers: {'content-type': 'application/json'}})),590 }).json(), {591 name: 'TypeError',592 message: /not extensible/,593 });594595 t.is(error?.name, 'TypeError');596 await cancelled;597});
modified:test/stream.ts+5 added-124 removed
1179 unmodified lines
1180 totalBytes: 2,1181 });1182});11831184// The upload progress tests below share a server that records how many requests reached it.1184// A server that records how many upload requests reached it.1185const createUploadProgressTestServer = async (t: ExecutionContext) => {1186 let requestCount = 0;1187 const server = await createHttpTestServer(t, {bodyParser: false});1188 server.post('/', async (request, response) => {
4 unmodified lines
11931194 return {server, getRequestCount: () => requestCount};1195};11961197// A throwing progress callback is a user-space error, so it must surface as that error rather than as a network failure. Upload progress runs inside the request body stream, where the runtime reports any stream error as a `TypeError: fetch failed` that Ky would otherwise classify as a `NetworkError`.1198test('a throwing upload progress callback propagates its own error', async t => {1197// Upload progress runs inside the request body stream, and the runtime reports a failed body stream as a network failure. The readme documents this, so the callback error is only reachable through the `cause` chain.1198test('a throwing upload progress callback fails the request as a network error', async t => {1199 const {server, getRequestCount} = await createUploadProgressTestServer(t);12001201 const callbackError = new Error('upload progress failed');1202 const error = await t.throwsAsync(ky.post(server.url, {
3 unmodified lines
1206 throw callbackError;1207 },1208 }).text());12091210 t.is(error, callbackError);1211 t.is(error.name, 'Error');1212 t.is(error.message, 'upload progress failed');1213 t.false(isNetworkError(error));1210 t.true(isNetworkError(error));1211 t.is((error?.cause as Error | undefined)?.cause, callbackError);1212 t.is(getRequestCount(), 0);1213});12141217test('a throwing upload progress callback is not retried as a network error', async t => {1218 const {server} = await createUploadProgressTestServer(t);1219 let beforeRetryCalls = 0;12201221 // A `NetworkError` would be retried for this method, which would re-send the body of a failed callback.1222 const error = await t.throwsAsync(ky.post(server.url, {1223 body: 'x'.repeat(1024),1224 retry: {limit: 2, delay: () => 0, methods: ['post']},1225 hooks: {1226 beforeRetry: [() => {1227 beforeRetryCalls++;1228 }],1229 },1230 onUploadProgress() {1231 throw new Error('upload progress failed');1232 },1233 }).text());12341235 t.is(error.message, 'upload progress failed');1236 t.is(beforeRetryCalls, 0);1237});12381239test('a throwing upload progress callback is visible to beforeError hooks', async t => {1240 const {server} = await createUploadProgressTestServer(t);12411242 const seen: string[] = [];1243 const error = await t.throwsAsync(ky.post(server.url, {1244 body: 'x'.repeat(1024),1245 retry: 0,1246 hooks: {1247 beforeError: [({error}) => {1248 seen.push(`${error.name}: ${error.message}`);1249 return error;1250 }],1251 },1252 onUploadProgress() {1253 throw new Error('upload progress failed');1254 },1255 }).text());12561257 t.is(error.message, 'upload progress failed');1258 t.deepEqual(seen, ['Error: upload progress failed']);1259});12601215test('a throwing download progress callback propagates its own error', async t => {1216 const server = await createHttpTestServer(t);1217 server.get('/', (_request, response) => {1218 response.end('body');
255 unmodified lines
1474 // Each intermediate event reports the running total, which starts below the estimate and grows past it.1475 t.deepEqual(totals, [10, 40, 60, 100]);1476});14771524// A response with no body at all is not streamed. That covers a null body status, and a `HEAD` response in runtimes that give it no body, such as Node.js.1525test('download progress stays silent for a null body status', async t => {1526 let calls = 0;1527 const result = await ky('https://example.com', {1528 fetch: async () => new Response(null, {status: 204}),1529 onDownloadProgress() {1530 calls++;1531 },1532 });15331534 t.is(result.status, 204);1535 t.is(calls, 0);1536});15371478test('download progress stays silent for a HEAD response', async t => {1479 const server = await createHttpTestServer(t);1480 server.head('/', (_request, response) => {1481 response.setHeader('content-length', '1000');
11 unmodified lines
1493 t.is(result.headers.get('content-length'), '1000');1494 t.is(calls, 0);1495});14961557// A throwing progress callback is a user-space error, but `#fetch()` rethrows it as a plain `Error`, so a `shouldRetry` that returns `true` for everything re-sent the body and ran the callback again.1558test('a throwing upload progress callback is not retried even when `shouldRetry` returns true', async t => {1559 const {server, getRequestCount} = await createUploadProgressTestServer(t);1560 let callbackCalls = 0;1561 let beforeRetryCalls = 0;15621563 await t.throwsAsync(ky.post(server.url, {1564 body: 'x'.repeat(1024),1565 retry: {1566 limit: 3,1567 methods: ['post'],1568 delay: () => 0,1569 shouldRetry: () => true,1570 },1571 hooks: {1572 beforeRetry: [() => {1573 beforeRetryCalls++;1574 }],1575 },1576 onUploadProgress() {1577 callbackCalls++;1578 throw new Error('upload progress failed');1579 },1580 }).text(), {message: 'upload progress failed'});15811582 t.is(getRequestCount(), 0);1583 t.is(callbackCalls, 1);1584 t.is(beforeRetryCalls, 0);1585});15861587// The marker only accepted `Error` values, so a callback that threw a string was still retried even though a callback that threw an `Error` was not. A `Ky` instance lives for one request, so a strong `Set` is safe.1588test('a non-Error throw from an upload progress callback is not retried either', async t => {1589 const {server, getRequestCount} = await createUploadProgressTestServer(t);1590 let callbackCalls = 0;15911592 try {1593 await ky.post(server.url, {1594 body: 'x'.repeat(1024),1595 retry: {1596 limit: 3,1597 methods: ['post'],1598 delay: () => 0,1599 shouldRetry: () => true,1600 },1601 onUploadProgress() {1602 callbackCalls++;1603 // eslint-disable-next-line @typescript-eslint/only-throw-error1604 throw 'upload progress failed';1605 },1606 }).text();1607 t.fail('should have thrown');1608 } catch (error) {1609 t.is(error, 'upload progress failed');1610 }16111612 t.is(getRequestCount(), 0);1613 t.is(callbackCalls, 1);1614});16151497// The response wrappers already skip a body a hook read, so the native error names the mistake. The upload wrapper did not, and failed with "The ReadableStream is locked" instead.1498test('upload progress leaves a request body that a hook already read to the native error', async t => {1499 const run = async (onUploadProgress?: () => void) => t.throwsAsync(ky.post('https://example.com', {1500 body: 'x',
16 unmodified lines
modified:test/type-guards.ts-19 removed
106 unmodified lines
107 t.is(attempts, 2);108 t.is(text, 'retried');109});110111// The brand check accepts any object that claims to be an `HTTPError`, so the retry path must not assume the cross-realm shape also carries a `response`.112test('a branded HTTPError without a response is not retried as an HTTPError', async t => {113 let attempts = 0;114 const branded = Object.assign(new Error('From another Ky constructor'), {115 name: 'HTTPError',116 isKyError: true,117 });118119 const error = await t.throwsAsync(ky('https://example.com', {120 async fetch() {121 attempts++;122 throw branded;123 },124 retry: {limit: 1, delay: () => 0},125 }).text());126127 t.is(attempts, 1);128 t.is(error, branded);129});
modified:readme.md+5 added-3 removed
482 unmodified lines
483Default: `[]`484485This hook enables you to modify the options before they are used to construct the request. The hook function receives the mutable options object and can modify it in place. You could, for example, modify `searchParams`, `headers`, or `json` here. The `headers` option starts as a plain object with lowercase names, where a header removed with `undefined` keeps an `undefined` value.486487Ky gives the hook its own copies of `headers`, `context`, `json`, `searchParams` and `retry`, so changing them in place only affects the current request. The `context` copy is deep, so when an instance has an `init` hook, nested `context` values are not shared across requests. The `body` option is not copied, so mutating a `FormData` or `URLSearchParams` body in place changes your own object and repeats on every request from the same instance. Assign a new instance instead, as shown in [Modifying FormData in hooks](#modifying-formdata-in-hooks). A value that a hook assigns is used as is, so assign a new object rather than one that you change later.487Ky gives the hook its own copies of `headers`, `context`, `json`, `searchParams` and `retry`, so changing them in place only affects the current request. The `context` copy is shallow, the same as in every other hook, so nested `context` values, such as a cache, stay shared across requests. The `body` option is not copied, so mutating a `FormData` or `URLSearchParams` body in place changes your own object and repeats on every request from the same instance. Assign a new instance instead, as shown in [Modifying FormData in hooks](#modifying-formdata-in-hooks). A value that a hook assigns is used as is, so assign a new object rather than one that you change later.488489Unlike other hooks, `init` hooks are synchronous. An error thrown by one rejects the returned promise and is not passed to `beforeError` hooks.490491A common use case is to add a search parameter to every request:
291 unmodified lines
783`content-length` is only used as the total for a response that is not content-coded, since it counts encoded bytes while the progress stream counts the bytes after decompression. A compressed response therefore reports `totalBytes: 0` until it completes, so the percentage cannot be calculated while downloading.784785Responses with no body at all are not streamed, so no progress events are emitted for them. That covers a [null body status](https://fetch.spec.whatwg.org/#null-body-status) such as `204`, and a `HEAD` response in runtimes that give it no body, such as browsers, Node.js and Deno. Bun gives a `HEAD` response an empty body, so it reports one final event with `transferredBytes: 0`. A response whose body an `afterResponse` hook already read, or locked with a reader, is passed through unchanged, so it reports no progress either.786787When the callback throws, the error is reported by Ky's body method shortcuts. A response read directly with `response.text()` or `response.json()` may instead report the runtime's own stream error, such as Chromium's generic `TypeError`.787Do not throw from the callback. A throw fails the response stream, which the runtime reports in its own way: Node.js rejects the body read with your error, while Chromium reports a network failure, so Ky's body methods throw a `NetworkError` there. Pass a `signal` from an `AbortController` to cancel instead.788789```js790import ky from 'ky';791
21 unmodified lines
813 - `transferredBytes` is the number of bytes transferred so far.814 - `totalBytes` is the total number of bytes to be transferred. This is an estimate and may be 0 for an empty transfer or when the total size cannot be determined.815- `chunk` is an instance of `Uint8Array` containing the data that was sent. When an empty request body stream completes, the callback receives an empty chunk.816817A `ReadableStream` body cannot be measured, so `totalBytes` falls back to a `content-length` header you set. Browsers do not allow that header on a request, so there the total stays `0`.817A `ReadableStream` body cannot be measured, so `totalBytes` falls back to a `content-length` header you set. Browsers do not allow that header on a request, so there the total stays `0`. When a hook replaces the request, `totalBytes` is still estimated from the `body` option until the final event, which reports the real total.818819Do not throw from the callback. A throw fails the upload stream, which the runtime reports as a network failure, so Ky throws a `NetworkError` (in Node.js, with your error in its `cause` chain) and retries it like any other network error, running the callback again. Pass a `signal` from an `AbortController` to cancel instead.820821```js822import ky from 'ky';823824const response = await ky.post('https://example.com/upload', {
1107 unmodified lines