Skip to content
Myr

Check the callbacks before the constructor uses them and reject an array `hooks`

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 74224d8 · Browse files · 8 files+52 added−32 removed
This commit

State

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

Diff stats

8 files+52 added−32 removed

  • tests:+31 added−9 removed
  • other:+21 added−23 removed

8 files+52 added−32 removed

modified:source/core/Ky.ts+17 added-18 removed
96 unmodified lines
97 throw new RangeError(`The \`${name}\` option cannot be greater than ${maxSafeTimeout}`);98 }99};100101// These callbacks are called directly, so a non-function value otherwise surfaces as a runtime error naming Ky's102// own internals rather than the option the caller set.103const validateCallbackOptions = (options: Record<string, unknown>): void => {104 for (const key of ['parseJson', 'stringifyJson', 'fetch'] as const) {105 if (options[key] !== undefined && typeof options[key] !== 'function') {106 throw new TypeError(`The \`${key}\` option must be a function`);107 }108 }109110 const {throwHttpErrors} = options;111 if (typeof throwHttpErrors !== 'boolean' && typeof throwHttpErrors !== 'function') {112 throw new TypeError('The `throwHttpErrors` option must be a boolean or a function');113 }114};115116const cloneRetryOptions = (retry: RetryOptions | number): RetryOptions | number => {117 if (retry === null || typeof retry !== 'object' || Array.isArray(retry)) {118 return retry as RetryOptions | number;119 }
157 unmodified lines
277278 const function_ = async (): Promise<Response | void> => {279 validateTimeoutOption(ky.#options.totalTimeout, 'totalTimeout');280 validateTimeoutOption(ky.#options.timeout, 'timeout');266 ky.#validateCallbackOptions();281282 // Delay the fetch so that body method shortcuts can set the Accept header283 await Promise.resolve();284 const beforeRequestResponse = await ky.#runBeforeRequestHooks();
245 unmodified lines
530 fetch: options.fetch ?? globalThis.fetch.bind(globalThis),531 // Deep-cloned so a hook mutating a nested plain object or array cannot write back to the instance defaults or the caller's object. Non-plain values such as class instances are kept by reference, matching how `json` and the shallow `context` merge treat them.532 context: cloneDeep(options.context) ?? {},533 };534 // Checked here rather than on the way out, because the constructor already calls `stringifyJson`.535 validateCallbackOptions(this.#options);536 this.#retryLimit = this.#options.retry.limit;537538 if (maxResponseSize !== Number.POSITIVE_INFINITY && (!Number.isSafeInteger(maxResponseSize) || maxResponseSize < 0)) {539 throw new TypeError('The `maxResponseSize` option must be a non-negative safe integer or Infinity');
133 unmodified lines
673 // Ky's internal scheduling and user hook time before the first fetch attempt.674 this.#startTime = typeof this.#options.totalTimeout === 'number' ? this.#getCurrentTime() : undefined;675 }676661 // These callbacks are called directly, so a non-function value otherwise surfaces as a runtime error naming Ky's662 // own internals rather than the option the caller set.663 #validateCallbackOptions(): void {664 for (const key of ['parseJson', 'stringifyJson', 'fetch'] as const) {665 if (this.#options[key] !== undefined && typeof this.#options[key] !== 'function') {666 throw new TypeError(`The \`${key}\` option must be a function`);667 }668 }669670 if (671 typeof this.#options.throwHttpErrors !== 'boolean'672 && typeof this.#options.throwHttpErrors !== 'function'673 ) {674 throw new TypeError('The `throwHttpErrors` option must be a boolean or a function');675 }676 }677677 #calculateDelay(retry: InternalOptions['retry']): number {678 const retryDelay = retry.delay(this.#retryCount + 1);679680 // A `retry.delay` that does not return a usable number would turn every delay into `NaN`, which
874 unmodified lines
modified:source/types/options.ts+1 added-1 removed
289 unmodified lines
290 @param chunk - Data that was received. When an empty response body stream completes, the callback receives an empty chunk.291292 `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.293294 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` request, which has no body even on an ordinary status.294 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` request, which has no body even on an ordinary status. A response whose body an `afterResponse` hook already read, or locked with a reader, is passed through unchanged, so it reports no progress either.295296 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`.297298 @example
250 unmodified lines
modified:source/utils/body.ts+1 added-2 removed
141 unmodified lines
142 // The `Response` constructor cannot set these, so copy them over from the original response.143 url: {value: originalResponse.url},144 redirected: {value: originalResponse.redirected},145 type: {value: originalResponse.type},146 // The constructor also rebuilds the header list under the mutable "response" guard, so a network response147 // that arrived immutable would silently become mutable. Reuse the original's headers to keep the guard.146 // The constructor also rebuilds the header list under the mutable "response" guard, so a network response that arrived immutable would silently become mutable. Reusing the original's headers keeps the guard; a clone shares that same object, which the spec would have copied, but copying it would drop the guard again.147 headers: {value: originalResponse.headers},148 // Native `clone()` creates a new `Response`, which would drop them again.149 // Keep the shim replaceable like `Response.prototype.clone` for instrumentation and mocks.150 clone: {
84 unmodified lines
modified:source/utils/merge.ts+1 added-1 removed
206 unmodified lines
207208export const mergeHooks = (original: Hooks = {}, incoming: Hooks = {}): NormalizedHooks => {209 // `null` selects the default, the same way option merging treats a nullish value as absent.210 const incomingHooks = incoming ?? {};211 if (!isObject(incomingHooks)) {211 if (!isObject(incomingHooks) || Array.isArray(incomingHooks)) {212 throw new TypeError('The `hooks` option must be an object');213 }214215 return {
250 unmodified lines
modified:test/hooks.ts+1 added-1 removed
7260 unmodified lines
7261 t.is(ran, 0);7262});72637264test('`hooks` that is not an object reports a clear error', t => {7265 for (const hooks of ['none', 42, true] as unknown[]) {7265 for (const hooks of ['none', 42, true, []] as unknown[]) {7266 t.throws(() => {7267 void ky('https://example.com', {hooks: hooks as never});7268 }, {7269 instanceOf: TypeError,
122 unmodified lines
modified:test/stream.ts+6 added-1 removed
1526 unmodified lines
15271528 try {1529 await ky.post(server.url, {1530 body: 'x'.repeat(1024),1531 retry: {limit: 3, methods: ['post'], delay: () => 0, shouldRetry: () => true},1531 retry: {1532 limit: 3,1533 methods: ['post'],1534 delay: () => 0,1535 shouldRetry: () => true,1536 },1537 onUploadProgress() {1538 callbackCalls++;1539 // eslint-disable-next-line @typescript-eslint/only-throw-error1540 throw 'upload progress failed';
10 unmodified lines
modified:test/validation.ts+24 added-7 removed
modified:readme.md+1 added-1 removed
762 unmodified lines
763- `chunk` is an instance of `Uint8Array` containing the data that was received. When an empty response body stream completes, the callback receives an empty chunk.764765`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.766767Responses 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` request, which has no body even on an ordinary status.767Responses 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` request, which has no body even on an ordinary status. A response whose body an `afterResponse` hook already read, or locked with a reader, is passed through unchanged, so it reports no progress either.768769When 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`.770771```js
1138 unmodified lines