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
Provenance
- Commit
13c8da5- Tree
03bea0b- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
Sindre Sorhus <sindresorhus@gmail.com>- Parent
55599c8
11 files changed+47 added−336 removed
modified:source/core/Ky.ts+11 added-44 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';19 import {19- getProgressCallbackError,20- limitResponseSize,21- streamRequest,22- streamResponse,23-} from '../utils/body.js';24-import {20 cloneShallow,21 cloneDeep,22 mergeHeaders,23 mergeHeaderContainers,140 unmodified lines164 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 lines413 #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 lines631 return Math.min(retry.backoffLimit, jitteredDelay);632 }633 634 async #calculateRetryDelay(error: unknown) {642- if (this.#inFlightCallbackErrors.has(error)) {643- throw error;644- }645-635 const retry = normalizeRetryOptions(this.#options.retry);636 if (this.#retryCount >= Math.min(retry.limit, this.#retryLimit)) {637 throw error;638 }36 unmodified lines675 676 return this.#calculateDelay(retry, error);677 }678 690- // 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 lines715 716 this.#decoratedResponses.add(response);717 const request = this.#getResponseRequest(response);718 731- 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+ };723 737- // `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));727 728 return response;729 }730 136 unmodified lines867 await this.#throwProcessedError(this.#userProvidedAbortSignal.reason, failedRequest);868 }869 870 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- }894-871 // 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 lines1394 this.#abortController?.abort();1395 throw new TimeoutError(request);1396 }1397 1422- // 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);1426-1427- // 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- }1430-1398 if (isRawNetworkError(error)) {1399 throw new NetworkError(request, {cause: error as Error});1400 }1401 91 unmodified linesmodified:source/types/hooks.ts+2 added-2 removed
3 unmodified lines4 5 /**6 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.7 8-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.8+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.9 10 Unlike other hooks, `init` hooks are synchronous. An error thrown by one rejects the returned promise and is not passed to `beforeError` hooks.11 12 @example77 unmodified lines90 export 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.93 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 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.95 96 Unlike other hooks, `init` hooks are synchronous. An error thrown by one rejects the returned promise and is not passed to `beforeError` hooks.97 98 A common use case is to add a search parameter to every request:278 unmodified linesmodified:source/types/options.ts+4 added-2 removed
297 unmodified lines298 `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.299 300 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.301 302- 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.303 304 @example305 ```306 import ky from 'ky';16 unmodified lines323 324 @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.326 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`.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.328 329+ 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.330+331 @example332 ```333 import ky from 'ky';334 216 unmodified linesmodified:source/utils/body.ts+5 added-39 removed
1-import type {Options, Progress} from '../types/options.js';1+import type {Options} from '../types/options.js';2 import {responseTypes, usualFormBoundarySize} from '../core/constants.js';3 import {ResponseSizeError} from '../errors/ResponseSizeError.js';4 5 const encoder = new TextEncoder();6 const 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.9-const 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.8 const nullBodyStatuses = new Set([101, 103, 204, 205, 304]);9 10 // 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 lines63 64 const 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- };67 81- // 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);71 72 if (previousChunk) {8 unmodified lines81 }82 83 // 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 }87 88 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);111-112- return progressStream;96 };97 115-/**116-The error thrown by a progress callback while reporting on the given stream, if the callback threw.117-*/118-export const getProgressCallbackError = (stream: ReadableStream | undefined): unknown =>119- stream ? progressCallbackErrors.get(stream)?.() : undefined;120-98 const 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- }129-100 if (response.body && getError) {101 responseSizeErrors.set(response.body, getError);102 103 // Chromium replaces stream errors with a generic TypeError in native body methods.29 unmodified lines133 // 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 }141 172- if (response.body && getProgressError) {173- progressCallbackErrors.set(response.body, getProgressError);174- }175-142 return copyResponseMetadata(clone, response);143 },144 writable: true,145 configurable: true,84 unmodified linesmodified:test/browser.ts-61 removed
109 unmodified lines110 111 t.deepEqual(result, {status: 204, header: 'ky', text: ''});112 });113 114-// 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`.115-browserTest('a throwing download progress callback propagates its own error', [chromium, webkit], async (t, page) => {116- server.get('/', (_request, response) => {117- response.end('body');118- });119-120- await page.goto(server.url);121- await addKyScriptToPage(page);122-123- 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);136-137- t.deepEqual(result, {errorName: 'Error', message: 'download progress failed'});138-});139-140-browserTest('cloning a response preserves download progress callback errors', [chromium], async (t, page) => {141- server.get('/', (_request, response) => {142- response.end('body');143- });144-145- await page.goto(server.url);146- await addKyScriptToPage(page);147-148- 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);159-160- 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);171-172- t.deepEqual(result, {sameError: true, errorName: 'Error', message: 'download progress failed'});173-});174-114 // 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.115 browserTest('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 linesmodified:test/context.ts+11 added-11 removed
266 unmodified lines267 t.is(beforeRequestCalls, 1);268 });269 }270 271+// The `init` hook copy is shallow, so it must still copy symbol keys, and replacing one only affects the current request.271-test('init hook mutations to symbol-keyed context stay isolated between requests', async t => {272+test('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 lines279 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 lines297 t.is(initCalls, 2);298 t.is(beforeRequestCalls, 2);299 });300 302-// 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.302 test('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 lines344 t.is(seen[0], seen[1]);345 t.deepEqual(seen[1], {shared: 'set-in-beforeRequest'});346 });347 348-// `init` hooks get a deep copy of the context, which must keep a null prototype.349-test('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.349+test('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;352 353 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 });363 364- await api('https://example.com').text();364+ await api.post('https://example.com').text();365 366 t.is(Object.getPrototypeOf(seen!), null);367 // A null-prototype object has no inherited members.368 t.is(seen!.toString, undefined);35 unmodified linesmodified:test/hooks.ts+4 added-3 removed
6173 unmodified lines6174 6175 t.deepEqual(seenRequestIdentifiers, [1, 2]);6176 });6177 6178+// `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.6178-test('init hook nested context mutations do not leak across requests', async t => {6179+test('init hook nested context values are shared across requests', async t => {6180 const seenCounts: number[] = [];6181 6182 const api = ky.extend({6183 context: {session: {count: 0}},11 unmodified lines6195 6196 await api.get('https://example.com');6197 await api.get('https://example.com');6198 6198- t.deepEqual(seenCounts, [0, 0]);6199+ t.deepEqual(seenCounts, [0, 1]);6200 });6201 6201-test('init hook keeps a class-instance context value by reference across the deep clone', async t => {6202+test('init hook keeps a class-instance context value by reference', async t => {6203 const store = new Map<string, number>();6204 let sawSameStore = false;6205 6206 const api = ky.extend({1177 unmodified linesmodified:test/response-size.ts-28 removed
565 unmodified lines566 response.headers.set('x-injected', '1');567 }, {instanceOf: TypeError});568 });569 570-// 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.571-test('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- });585-586- 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- });594-595- t.is(error?.name, 'TypeError');596- await cancelled;597-});modified:test/stream.ts+5 added-124 removed
1179 unmodified lines1180 totalBytes: 2,1181 });1182 });1183 1184-// 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.1185 const createUploadProgressTestServer = async (t: ExecutionContext) => {1186 let requestCount = 0;1187 const server = await createHttpTestServer(t, {bodyParser: false});1188 server.post('/', async (request, response) => {4 unmodified lines1193 1194 return {server, getRequestCount: () => requestCount};1195 };1196 1197-// 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`.1198-test('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.1198+test('a throwing upload progress callback fails the request as a network error', async t => {1199 const {server, getRequestCount} = await createUploadProgressTestServer(t);1200 1201 const callbackError = new Error('upload progress failed');1202 const error = await t.throwsAsync(ky.post(server.url, {3 unmodified lines1206 throw callbackError;1207 },1208 }).text());1209 1210- 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 });1214 1217-test('a throwing upload progress callback is not retried as a network error', async t => {1218- const {server} = await createUploadProgressTestServer(t);1219- let beforeRetryCalls = 0;1220-1221- // 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());1234-1235- t.is(error.message, 'upload progress failed');1236- t.is(beforeRetryCalls, 0);1237-});1238-1239-test('a throwing upload progress callback is visible to beforeError hooks', async t => {1240- const {server} = await createUploadProgressTestServer(t);1241-1242- 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());1256-1257- t.is(error.message, 'upload progress failed');1258- t.deepEqual(seen, ['Error: upload progress failed']);1259-});1260-1215 test('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 lines1474 // 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 });1477 1524-// 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.1525-test('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- });1533-1534- t.is(result.status, 204);1535- t.is(calls, 0);1536-});1537-1478 test('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 lines1493 t.is(result.headers.get('content-length'), '1000');1494 t.is(calls, 0);1495 });1496 1557-// 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.1558-test('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;1562-1563- 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'});1581-1582- t.is(getRequestCount(), 0);1583- t.is(callbackCalls, 1);1584- t.is(beforeRetryCalls, 0);1585-});1586-1587-// 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.1588-test('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;1591-1592- 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- }1611-1612- t.is(getRequestCount(), 0);1613- t.is(callbackCalls, 1);1614-});1615-1497 // 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.1498 test('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 linesmodified:test/type-guards.ts-19 removed
106 unmodified lines107 t.is(attempts, 2);108 t.is(text, 'retried');109 });110 111-// 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`.112-test('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- });118-119- 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());126-127- t.is(attempts, 1);128- t.is(error, branded);129-});modified:readme.md+5 added-3 removed
482 unmodified lines483 Default: `[]`484 485 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.486 487-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](#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.487+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](#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.488 489 Unlike other hooks, `init` hooks are synchronous. An error thrown by one rejects the returned promise and is not passed to `beforeError` hooks.490 491 A common use case is to add a search parameter to every request:291 unmodified lines783 `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.784 785 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.786 787-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`.787+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.788 789 ```js790 import ky from 'ky';791 21 unmodified lines813 - `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.816 817-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`.817+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.818 819+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.820+821 ```js822 import ky from 'ky';823 824 const response = await ky.post('https://example.com/upload', {1107 unmodified lines