Fix support with environments that add support for custom `fetch` options (#536)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Kelvin Del Monte · committed by GitHub · parent d372e2e · Browse files · 6 files·+108 added−49 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+108 added−49 removed
- tests:+13 added−0 removed
- other:+95 added−49 removed
Provenance
- Commit
e93bc6d- Tree
ff53940- Author
Kelvin Del Monte <kdelmonten@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
d372e2e
6 files changed+108 added−49 removed
modified:source/core/constants.ts+14 added-1 removed
122345637 unmodified lines4445464748495051525354555657585960import type {Expect, Equal} from '@type-challenges/utils';import {type HttpMethod} from '../types/options.js';import {type HttpMethod, type KyOptionsRegistry} from '../types/options.js';
export const supportsRequestStreams = (() => { let duplexAccessed = false; let hasContentType = false;37 unmodified lines// The maximum value of a 32bit int (see issue #117)export const maxSafeTimeout = 2_147_483_647;
export const stop = Symbol('stop');
export const kyOptionKeys: KyOptionsRegistry = { json: true, parseJson: true, searchParams: true, prefixUrl: true, retry: true, timeout: true, hooks: true, throwHttpErrors: true, onDownloadProgress: true, fetch: true,};modified:source/core/Ky.ts+5 added-2 removed
6 unmodified lines7 import {normalizeRequestMethod, normalizeRetryOptions} from '../utils/normalize.js';8 import timeout, {type TimeoutOptions} from '../utils/timeout.js';9 import delay from '../utils/delay.js';10 import {type ObjectEntries} from '../utils/types.js';11+import {findUnknownOptions} from '../utils/options.js';12 import {13 maxSafeTimeout,14 responseTypes,15 stop,278 unmodified lines294 return result;295 }296 }297 298+ const nonRequestOptions = findUnknownOptions(this.request, this._options);299+300 if (this._options.timeout === false) {298- return this._options.fetch(this.request.clone());301+ return this._options.fetch(this.request.clone(), nonRequestOptions);302 }303 301- return timeout(this.request.clone(), this.abortController, this._options as TimeoutOptions);304+ return timeout(this.request.clone(), nonRequestOptions, this.abortController, this._options as TimeoutOptions);305 }306 307 /* istanbul ignore next */308 protected _stream(response: Response, onDownloadProgress: Options['onDownloadProgress']) {55 unmodified linesmodified:source/types/options.ts+58 added-45 removed
23 unmodified lines24 25 export type KyHeadersInit = HeadersInit | Record<string, string | undefined>;26 27 /**28-Options are the same as `window.fetch`, with some exceptions.28+Custom Ky options29 */30-export interface Options extends Omit<RequestInit, 'headers'> { // eslint-disable-line @typescript-eslint/consistent-type-definitions -- This must stay an interface so that it can be extended outside of Ky for use in `ky.create`.31- /**32- HTTP method used to make the request.30 34- Internally, the standard methods (`GET`, `POST`, `PUT`, `PATCH`, `HEAD` and `DELETE`) are uppercased in order to avoid server errors due to case sensitivity.35- */36- method?: LiteralUnion<HttpMethod, string>;37-31+export type KyOptions = {32 /**39- HTTP headers used to make the request.40-41- You can pass a `Headers` instance or a plain object.42-43- You can remove a header with `.extend()` by passing the header with an `undefined` value.44-45- @example46- ```47- import ky from 'ky';48-49- const url = 'https://sindresorhus.com';50-51- const original = ky.create({52- headers: {53- rainbow: 'rainbow',54- unicorn: 'unicorn'55- }56- });57-58- const extended = original.extend({59- headers: {60- rainbow: undefined61- }62- });63-64- const response = await extended(url).json();65-66- console.log('rainbow' in response);67- //=> false68-69- console.log('unicorn' in response);70- //=> true71- ```72- */73- headers?: KyHeadersInit;74-75- /**33 Shortcut for sending JSON. Use this instead of the `body` option.34 35 Accepts any plain object or value, which will be `JSON.stringify()`'d and sent in the body with the correct header set.36 */140 unmodified lines177 const json = await ky('https://example.com', {fetch}).json();178 ```179 */180 fetch?: (input: RequestInfo, init?: RequestInit) => Promise<Response>;181+};182+183+/**184+Each key from KyOptions is present and set to `true`.185+186+This type is used for identifying and working with the known keys in KyOptions.187+*/188+export type KyOptionsRegistry = {[K in keyof KyOptions]-?: true};189+190+/**191+Options are the same as `window.fetch`, except for the KyOptions192+*/193+export interface Options extends KyOptions, Omit<RequestInit, 'headers'> { // eslint-disable-line @typescript-eslint/consistent-type-definitions -- This must stay an interface so that it can be extended outside of Ky for use in `ky.create`.194+ /**195+ HTTP method used to make the request.196+197+ Internally, the standard methods (`GET`, `POST`, `PUT`, `PATCH`, `HEAD` and `DELETE`) are uppercased in order to avoid server errors due to case sensitivity.198+ */199+ method?: LiteralUnion<HttpMethod, string>;200+201+ /**202+ HTTP headers used to make the request.203+204+ You can pass a `Headers` instance or a plain object.205+206+ You can remove a header with `.extend()` by passing the header with an `undefined` value.207+208+ @example209+ ```210+ import ky from 'ky';211+212+ const url = 'https://sindresorhus.com';213+214+ const original = ky.create({215+ headers: {216+ rainbow: 'rainbow',217+ unicorn: 'unicorn'218+ }219+ });220+221+ const extended = original.extend({222+ headers: {223+ rainbow: undefined224+ }225+ });226+227+ const response = await extended(url).json();228+229+ console.log('rainbow' in response);230+ //=> false231+232+ console.log('unicorn' in response);233+ //=> true234+ ```235+ */236+ headers?: KyHeadersInit;237 }238 239 export type InternalOptions = Required<240 Omit<Options, 'hooks' | 'retry'>,23 unmodified linesadded:source/utils/options.ts+16 added
12345678910111213141516import {kyOptionKeys} from '../core/constants.js';
export const findUnknownOptions = ( request: Request, options: Record<string, unknown>,): Record<string, unknown> => { const unknownOptions: Record<string, unknown> = {};
for (const key in options) { if (!(key in kyOptionKeys) && !(key in request)) { unknownOptions[key] = options[key]; } }
return unknownOptions;};modified:source/utils/timeout.ts+2 added-1 removed
6 unmodified lines7891011121314155 unmodified lines212223242425262728293 unmodified lines6 unmodified lines
// `Promise.race()` workaround (#91)export default async function timeout( request: Request, init: RequestInit, abortController: AbortController | undefined, options: TimeoutOptions,): Promise<Response> { return new Promise((resolve, reject) => {5 unmodified lines reject(new TimeoutError(request)); }, options.timeout);
void options .fetch(request) .fetch(request, init) .then(resolve) .catch(reject) .then(() => { clearTimeout(timeoutId);3 unmodified linesmodified:test/fetch.ts+13 added
62 unmodified lines636465666768697071727374757677787962 unmodified lines const fixture = {x: true}; const json = await ky.post('https://httpbin.org/anything', {json: fixture}).json(); t.deepEqual(json.json, fixture);});
test('unknown options are passed to fetch', async t => { t.plan(1);
const options = {next: {revalidate: 3600}};
const customFetch: typeof fetch = async (request, init) => { t.is(init.next, options.next); return new Response(request.url); };
await ky(fixture, {...options, fetch: customFetch}).text();});