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
Provenance
- Commit
16b5936- Tree
2269115- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
Sindre Sorhus <sindresorhus@gmail.com>- Parent
74224d8
8 files changed+52 added−32 removed
modified:source/core/Ky.ts+17 added-18 removed
96 unmodified lines97 throw new RangeError(`The \`${name}\` option cannot be greater than ${maxSafeTimeout}`);98 }99 };100 101+// 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.103+const 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+ }109+110+ 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+};115+116 const 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 lines277 278 const function_ = async (): Promise<Response | void> => {279 validateTimeoutOption(ky.#options.totalTimeout, 'totalTimeout');280 validateTimeoutOption(ky.#options.timeout, 'timeout');266- ky.#validateCallbackOptions();281 282 // Delay the fetch so that body method shortcuts can set the Accept header283 await Promise.resolve();284 const beforeRequestResponse = await ky.#runBeforeRequestHooks();245 unmodified lines530 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;537 538 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 lines673 // 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 }676 661- // 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- }669-670- 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- }677-677 #calculateDelay(retry: InternalOptions['retry']): number {678 const retryDelay = retry.delay(this.#retryCount + 1);679 680 // A `retry.delay` that does not return a usable number would turn every delay into `NaN`, which874 unmodified linesmodified:source/types/options.ts+1 added-1 removed
289 unmodified lines290 @param chunk - Data that was received. When an empty response body stream completes, the callback receives an empty chunk.291 292 `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.293 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.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.295 296 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`.297 298 @example250 unmodified linesmodified:source/utils/body.ts+1 added-2 removed
141 unmodified lines142 // 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 linesmodified:source/utils/merge.ts+1 added-1 removed
206 unmodified lines207 208 export 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 }214 215 return {250 unmodified linesmodified:test/hooks.ts+1 added-1 removed
7260 unmodified lines7261 t.is(ran, 0);7262 });7263 7264 test('`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 linesmodified:test/stream.ts+6 added-1 removed
1526 unmodified lines1527 1528 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 linesmodified:test/validation.ts+24 added-7 removed
73 unmodified lines7475767778797879808182838485868788878889909192939495969798991001011021031041051061071081091109511111211311411511611710210311811912012112212312423 unmodified lines73 unmodified lines );});
// These callbacks are called directly, so a non-function value surfaced as a runtime error naming Ky's own// internals (`this[#options].stringifyJson`, `initHookOptions.parseJson`) instead of the option the user set.test('rejects non-function callback options', async t => {// internals (`this[#options].stringifyJson`, `initHookOptions.parseJson`) instead of the option the user set, and// only once the request had already been built. The constructor calls `stringifyJson` itself, so that one has to be// checked before anything else happens.test('rejects non-function callback options', t => { for (const [key, value] of [ ['parseJson', 'x'], ['stringifyJson', 5], ['fetch', 'x'], ] as Array<[string, unknown]>) { const options: Record<string, unknown> = {[key]: value};
// eslint-disable-next-line no-await-in-loop await t.throwsAsync(ky('https://example.com', options as never).json(), { t.throws(() => { void ky('https://example.com', options as never); }, { name: 'TypeError', message: `The \`${key}\` option must be a function`, }, `${key}: ${JSON.stringify(value)}`); }});
test('rejects a non-function `stringifyJson` before it is called', t => { t.throws(() => { void ky.post('https://example.com', { json: {a: 1}, stringifyJson: 'nope' as never, fetch: okFetch, }); }, { name: 'TypeError', message: 'The `stringifyJson` option must be a function', });});
test('rejects a `throwHttpErrors` value that is neither a boolean nor a function', async t => {test('rejects a `throwHttpErrors` value that is neither a boolean nor a function', t => { for (const value of ['yes', 1, {}] as unknown[]) { const options: Record<string, unknown> = { throwHttpErrors: value, fetch: async () => new Response('server error', {status: 500}), };
// eslint-disable-next-line no-await-in-loop await t.throwsAsync(ky('https://example.com', options as never).json(), { t.throws(() => { void ky('https://example.com', options as never); }, { name: 'TypeError', message: 'The `throwHttpErrors` option must be a boolean or a function', }, `throwHttpErrors: ${JSON.stringify(value)}`); }23 unmodified linesmodified:readme.md+1 added-1 removed
762 unmodified lines763 - `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.764 765 `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.766 767-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.767+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.768 769 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`.770 771 ```js1138 unmodified lines