commit
This commit is contained in:
parent
70e2f7a8aa
commit
008d2f30d7
675 changed files with 189892 additions and 0 deletions
548
node_modules/ky/index.d.ts
generated
vendored
Normal file
548
node_modules/ky/index.d.ts
generated
vendored
Normal file
|
@ -0,0 +1,548 @@
|
|||
type Primitive = null | undefined | string | number | boolean | symbol | bigint;
|
||||
|
||||
type LiteralUnion<LiteralType extends BaseType, BaseType extends Primitive> =
|
||||
| LiteralType
|
||||
| (BaseType & {_?: never});
|
||||
|
||||
export type Input = Request | URL | string;
|
||||
|
||||
export type BeforeRequestHook = (
|
||||
request: Request,
|
||||
options: NormalizedOptions,
|
||||
) => Request | Response | void | Promise<Request | Response | void>;
|
||||
|
||||
export type BeforeRetryHook = (options: {
|
||||
request: Request;
|
||||
response: Response;
|
||||
options: NormalizedOptions;
|
||||
error: Error;
|
||||
retryCount: number;
|
||||
}) => void | Promise<void>;
|
||||
|
||||
export type AfterResponseHook = (
|
||||
request: Request,
|
||||
options: NormalizedOptions,
|
||||
response: Response,
|
||||
) => Response | void | Promise<Response | void>;
|
||||
|
||||
export interface DownloadProgress {
|
||||
percent: number;
|
||||
transferredBytes: number;
|
||||
|
||||
/**
|
||||
Note: If it's not possible to retrieve the body size, it will be `0`.
|
||||
*/
|
||||
totalBytes: number;
|
||||
}
|
||||
|
||||
export interface Hooks {
|
||||
/**
|
||||
This hook enables you to modify the request right before it is sent. Ky will make no further changes to the request after this. The hook function receives normalized input and options as arguments. You could, for example, modify `options.headers` here.
|
||||
|
||||
A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) can be returned from this hook to completely avoid making a HTTP request. This can be used to mock a request, check an internal cache, etc. An **important** consideration when returning a `Response` from this hook is that all the following hooks will be skipped, so **ensure you only return a `Response` from the last hook**.
|
||||
|
||||
@default []
|
||||
*/
|
||||
beforeRequest?: BeforeRequestHook[];
|
||||
|
||||
/**
|
||||
This hook enables you to modify the request right before retry. Ky will make no further changes to the request after this. The hook function receives an object with the normalized request and options, an error instance, and the retry count. You could, for example, modify `request.headers` here.
|
||||
|
||||
If the request received a response, it will be available at `error.response`. Be aware that some types of errors, such as network errors, inherently mean that a response was not received.
|
||||
|
||||
@example
|
||||
```
|
||||
import ky from 'ky';
|
||||
|
||||
(async () => {
|
||||
await ky('https://example.com', {
|
||||
hooks: {
|
||||
beforeRetry: [
|
||||
async ({request, options, error, retryCount}) => {
|
||||
const token = await ky('https://example.com/refresh-token');
|
||||
options.headers.set('Authorization', `token ${token}`);
|
||||
}
|
||||
]
|
||||
}
|
||||
});
|
||||
})();
|
||||
```
|
||||
|
||||
@default []
|
||||
*/
|
||||
beforeRetry?: BeforeRetryHook[];
|
||||
|
||||
/**
|
||||
This hook enables you to read and optionally modify the response. The hook function receives normalized input, options, and a clone of the response as arguments. The return value of the hook function will be used by Ky as the response object if it's an instance of [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response).
|
||||
|
||||
@default []
|
||||
|
||||
@example
|
||||
```
|
||||
import ky from 'ky';
|
||||
|
||||
(async () => {
|
||||
await ky('https://example.com', {
|
||||
hooks: {
|
||||
afterResponse: [
|
||||
(_input, _options, response) => {
|
||||
// You could do something with the response, for example, logging.
|
||||
log(response);
|
||||
|
||||
// Or return a `Response` instance to overwrite the response.
|
||||
return new Response('A different response', {status: 200});
|
||||
},
|
||||
|
||||
// Or retry with a fresh token on a 403 error
|
||||
async (input, options, response) => {
|
||||
if (response.status === 403) {
|
||||
// Get a fresh token
|
||||
const token = await ky('https://example.com/token').text();
|
||||
|
||||
// Retry with the token
|
||||
options.headers.set('Authorization', `token ${token}`);
|
||||
|
||||
return ky(input, options);
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
});
|
||||
})();
|
||||
```
|
||||
*/
|
||||
afterResponse?: AfterResponseHook[];
|
||||
}
|
||||
|
||||
export interface RetryOptions {
|
||||
/**
|
||||
The number of times to retry failed requests.
|
||||
|
||||
@default 2
|
||||
*/
|
||||
limit?: number;
|
||||
|
||||
/**
|
||||
The HTTP methods allowed to retry.
|
||||
|
||||
@default ['get', 'put', 'head', 'delete', 'options', 'trace']
|
||||
*/
|
||||
methods?: string[];
|
||||
|
||||
/**
|
||||
The HTTP status codes allowed to retry.
|
||||
|
||||
@default [408, 413, 429, 500, 502, 503, 504]
|
||||
*/
|
||||
statusCodes?: number[];
|
||||
|
||||
/**
|
||||
The HTTP status codes allowed to retry with a `Retry-After` header.
|
||||
|
||||
@default [413, 429, 503]
|
||||
*/
|
||||
afterStatusCodes?: number[];
|
||||
|
||||
/**
|
||||
If the `Retry-After` header is greater than `maxRetryAfter`, the request will be canceled.
|
||||
|
||||
@default Infinity
|
||||
*/
|
||||
maxRetryAfter?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
Options are the same as `window.fetch`, with some exceptions.
|
||||
*/
|
||||
export interface Options extends Omit<RequestInit, 'headers'> {
|
||||
/**
|
||||
HTTP method used to make the request.
|
||||
|
||||
Internally, the standard methods (`GET`, `POST`, `PUT`, `PATCH`, `HEAD` and `DELETE`) are uppercased in order to avoid server errors due to case sensitivity.
|
||||
*/
|
||||
method?: LiteralUnion<'get' | 'post' | 'put' | 'delete' | 'patch' | 'head', string>;
|
||||
|
||||
/**
|
||||
HTTP headers used to make the request.
|
||||
|
||||
You can pass a `Headers` instance or a plain object.
|
||||
|
||||
You can remove a header with `.extend()` by passing the header with an `undefined` value.
|
||||
|
||||
@example
|
||||
```
|
||||
import ky from 'ky';
|
||||
|
||||
const url = 'https://sindresorhus.com';
|
||||
|
||||
const original = ky.create({
|
||||
headers: {
|
||||
rainbow: 'rainbow',
|
||||
unicorn: 'unicorn'
|
||||
}
|
||||
});
|
||||
|
||||
const extended = original.extend({
|
||||
headers: {
|
||||
rainbow: undefined
|
||||
}
|
||||
});
|
||||
|
||||
const response = await extended(url).json();
|
||||
|
||||
console.log('rainbow' in response);
|
||||
//=> false
|
||||
|
||||
console.log('unicorn' in response);
|
||||
//=> true
|
||||
```
|
||||
*/
|
||||
headers?: HeadersInit | {[key: string]: undefined};
|
||||
|
||||
/**
|
||||
Shortcut for sending JSON. Use this instead of the `body` option.
|
||||
|
||||
Accepts any plain object or value, which will be `JSON.stringify()`'d and sent in the body with the correct header set.
|
||||
*/
|
||||
json?: unknown;
|
||||
|
||||
/**
|
||||
User-defined JSON-parsing function.
|
||||
|
||||
Use-cases:
|
||||
1. Parse JSON via the [`bourne` package](https://github.com/hapijs/bourne) to protect from prototype pollution.
|
||||
2. Parse JSON with [`reviver` option of `JSON.parse()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse).
|
||||
|
||||
@default JSON.parse()
|
||||
|
||||
@example
|
||||
```
|
||||
import ky from 'ky';
|
||||
import bourne from '@hapijs/bourne';
|
||||
|
||||
(async () => {
|
||||
const parsed = await ky('https://example.com', {
|
||||
parseJson: text => bourne(text)
|
||||
}).json();
|
||||
})();
|
||||
```
|
||||
*/
|
||||
parseJson?: (text: string) => unknown
|
||||
|
||||
/**
|
||||
Search parameters to include in the request URL. Setting this will override all existing search parameters in the input URL.
|
||||
|
||||
Accepts any value supported by [`URLSearchParams()`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/URLSearchParams).
|
||||
*/
|
||||
searchParams?: string | {[key: string]: string | number | boolean} | Array<Array<string | number | boolean>> | URLSearchParams;
|
||||
|
||||
/**
|
||||
A prefix to prepend to the `input` URL when making the request. It can be any valid URL, either relative or absolute. A trailing slash `/` is optional and will be added automatically, if needed, when it is joined with `input`. Only takes effect when `input` is a string. The `input` argument cannot start with a slash `/` when using this option.
|
||||
|
||||
Useful when used with [`ky.extend()`](#kyextenddefaultoptions) to create niche-specific Ky-instances.
|
||||
|
||||
Notes:
|
||||
- After `prefixUrl` and `input` are joined, the result is resolved against the [base URL](https://developer.mozilla.org/en-US/docs/Web/API/Node/baseURI) of the page (if any).
|
||||
- Leading slashes in `input` are disallowed when using this option to enforce consistency and avoid confusion about how the `input` URL is handled, given that `input` will not follow the normal URL resolution rules when `prefixUrl` is being used, which changes the meaning of a leading slash.
|
||||
|
||||
@example
|
||||
```
|
||||
import ky from 'ky';
|
||||
|
||||
// On https://example.com
|
||||
|
||||
(async () => {
|
||||
await ky('unicorn', {prefixUrl: '/api'});
|
||||
//=> 'https://example.com/api/unicorn'
|
||||
|
||||
await ky('unicorn', {prefixUrl: 'https://cats.com'});
|
||||
//=> 'https://cats.com/unicorn'
|
||||
})();
|
||||
```
|
||||
*/
|
||||
prefixUrl?: URL | string;
|
||||
|
||||
/**
|
||||
An object representing `limit`, `methods`, `statusCodes` and `maxRetryAfter` fields for maximum retry count, allowed methods, allowed status codes and maximum [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) time.
|
||||
|
||||
If `retry` is a number, it will be used as `limit` and other defaults will remain in place.
|
||||
|
||||
If `maxRetryAfter` is set to `undefined`, it will use `options.timeout`. If [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) header is greater than `maxRetryAfter`, it will cancel the request.
|
||||
|
||||
Delays between retries is calculated with the function `0.3 * (2 ** (retry - 1)) * 1000`, where `retry` is the attempt number (starts from 1).
|
||||
|
||||
@example
|
||||
```
|
||||
import ky from 'ky';
|
||||
|
||||
(async () => {
|
||||
const parsed = await ky('https://example.com', {
|
||||
retry: {
|
||||
limit: 10,
|
||||
methods: ['get'],
|
||||
statusCodes: [413]
|
||||
}
|
||||
}).json();
|
||||
})();
|
||||
```
|
||||
*/
|
||||
retry?: RetryOptions | number;
|
||||
|
||||
/**
|
||||
Timeout in milliseconds for getting a response. Can not be greater than 2147483647.
|
||||
If set to `false`, there will be no timeout.
|
||||
|
||||
@default 10000
|
||||
*/
|
||||
timeout?: number | false;
|
||||
|
||||
/**
|
||||
Hooks allow modifications during the request lifecycle. Hook functions may be async and are run serially.
|
||||
*/
|
||||
hooks?: Hooks;
|
||||
|
||||
/**
|
||||
Throw an `HTTPError` when, after following redirects, the response has a non-2xx status code. To also throw for redirects instead of following them, set the [`redirect`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters) option to `'manual'`.
|
||||
|
||||
Setting this to `false` may be useful if you are checking for resource availability and are expecting error responses.
|
||||
|
||||
@default true
|
||||
*/
|
||||
throwHttpErrors?: boolean;
|
||||
|
||||
/**
|
||||
Download progress event handler.
|
||||
|
||||
@param chunk - Note: It's empty for the first call.
|
||||
|
||||
@example
|
||||
```
|
||||
import ky from 'ky';
|
||||
|
||||
(async () => {
|
||||
await ky('https://example.com', {
|
||||
onDownloadProgress: (progress, chunk) => {
|
||||
// Example output:
|
||||
// `0% - 0 of 1271 bytes`
|
||||
// `100% - 1271 of 1271 bytes`
|
||||
console.log(`${progress.percent * 100}% - ${progress.transferredBytes} of ${progress.totalBytes} bytes`);
|
||||
}
|
||||
});
|
||||
})();
|
||||
```
|
||||
*/
|
||||
onDownloadProgress?: (progress: DownloadProgress, chunk: Uint8Array) => void;
|
||||
|
||||
/**
|
||||
User-defined `fetch` function.
|
||||
Has to be fully compatible with the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) standard.
|
||||
|
||||
Use-cases:
|
||||
1. Use custom `fetch` implementations like [`isomorphic-unfetch`](https://www.npmjs.com/package/isomorphic-unfetch).
|
||||
2. Use the `fetch` wrapper function provided by some frameworks that use server-side rendering (SSR).
|
||||
|
||||
@default fetch
|
||||
|
||||
@example
|
||||
```
|
||||
import ky from 'ky';
|
||||
import fetch from 'isomorphic-unfetch';
|
||||
|
||||
(async () => {
|
||||
const parsed = await ky('https://example.com', {
|
||||
fetch
|
||||
}).json();
|
||||
})();
|
||||
```
|
||||
*/
|
||||
fetch?: (input: RequestInfo, init?: RequestInit) => Promise<Response>;
|
||||
}
|
||||
|
||||
/**
|
||||
Normalized options passed to the `fetch` call and the `beforeRequest` hooks.
|
||||
*/
|
||||
export interface NormalizedOptions extends RequestInit {
|
||||
// Extended from `RequestInit`, but ensured to be set (not optional).
|
||||
method: RequestInit['method'];
|
||||
credentials: RequestInit['credentials'];
|
||||
|
||||
// Extended from custom `KyOptions`, but ensured to be set (not optional).
|
||||
retry: Options['retry'];
|
||||
prefixUrl: Options['prefixUrl'];
|
||||
onDownloadProgress: Options['onDownloadProgress'];
|
||||
}
|
||||
|
||||
/**
|
||||
Returns a `Response` object with `Body` methods added for convenience. So you can, for example, call `ky.get(input).json()` directly without having to await the `Response` first. When called like that, an appropriate `Accept` header will be set depending on the body method used. Unlike the `Body` methods of `window.Fetch`; these will throw an `HTTPError` if the response status is not in the range of `200...299`. Also, `.json()` will return an empty string if the response status is `204` instead of throwing a parse error due to an empty body.
|
||||
*/
|
||||
export interface ResponsePromise extends Promise<Response> {
|
||||
arrayBuffer: () => Promise<ArrayBuffer>;
|
||||
|
||||
blob: () => Promise<Blob>;
|
||||
|
||||
formData: () => Promise<FormData>;
|
||||
|
||||
// TODO: Use `json<T extends JSONValue>(): Promise<T>;` when it's fixed in TS.
|
||||
// See https://github.com/microsoft/TypeScript/issues/15300 and https://github.com/sindresorhus/ky/pull/80
|
||||
/**
|
||||
Get the response body as JSON.
|
||||
|
||||
@example
|
||||
```
|
||||
import ky from 'ky';
|
||||
|
||||
const parsed = await ky(…).json();
|
||||
```
|
||||
|
||||
@example
|
||||
```
|
||||
import ky from 'ky';
|
||||
|
||||
interface Result {
|
||||
value: number;
|
||||
}
|
||||
|
||||
const result = await ky(…).json<Result>();
|
||||
```
|
||||
*/
|
||||
json: <T>() => Promise<T>;
|
||||
|
||||
text: () => Promise<string>;
|
||||
}
|
||||
|
||||
/**
|
||||
The error has a response property with the `Response` object.
|
||||
*/
|
||||
declare class HTTPError extends Error {
|
||||
constructor(response: Response);
|
||||
response: Response;
|
||||
}
|
||||
|
||||
/**
|
||||
The error thrown when the request times out.
|
||||
*/
|
||||
declare class TimeoutError extends Error {
|
||||
constructor(request: Request);
|
||||
request: Request;
|
||||
}
|
||||
|
||||
declare const ky: {
|
||||
/**
|
||||
Fetch the given `url`.
|
||||
|
||||
@param url - `Request` object, `URL` object, or URL string.
|
||||
@returns A promise with `Body` method added.
|
||||
|
||||
@example
|
||||
```
|
||||
import ky from 'ky';
|
||||
|
||||
(async () => {
|
||||
const parsed = await ky('https://example.com', {json: {foo: true}}).json();
|
||||
|
||||
console.log(parsed);
|
||||
//=> `{data: '🦄'}`
|
||||
})();
|
||||
```
|
||||
*/
|
||||
(url: Input, options?: Options): ResponsePromise;
|
||||
|
||||
/**
|
||||
Fetch the given `url` using the option `{method: 'get'}`.
|
||||
|
||||
@param url - `Request` object, `URL` object, or URL string.
|
||||
@returns A promise with `Body` methods added.
|
||||
*/
|
||||
get: (url: Input, options?: Options) => ResponsePromise;
|
||||
|
||||
/**
|
||||
Fetch the given `url` using the option `{method: 'post'}`.
|
||||
|
||||
@param url - `Request` object, `URL` object, or URL string.
|
||||
@returns A promise with `Body` methods added.
|
||||
*/
|
||||
post: (url: Input, options?: Options) => ResponsePromise;
|
||||
|
||||
/**
|
||||
Fetch the given `url` using the option `{method: 'put'}`.
|
||||
|
||||
@param url - `Request` object, `URL` object, or URL string.
|
||||
@returns A promise with `Body` methods added.
|
||||
*/
|
||||
put: (url: Input, options?: Options) => ResponsePromise;
|
||||
|
||||
/**
|
||||
Fetch the given `url` using the option `{method: 'delete'}`.
|
||||
|
||||
@param url - `Request` object, `URL` object, or URL string.
|
||||
@returns A promise with `Body` methods added.
|
||||
*/
|
||||
delete: (url: Input, options?: Options) => ResponsePromise;
|
||||
|
||||
/**
|
||||
Fetch the given `url` using the option `{method: 'patch'}`.
|
||||
|
||||
@param url - `Request` object, `URL` object, or URL string.
|
||||
@returns A promise with `Body` methods added.
|
||||
*/
|
||||
patch: (url: Input, options?: Options) => ResponsePromise;
|
||||
|
||||
/**
|
||||
Fetch the given `url` using the option `{method: 'head'}`.
|
||||
|
||||
@param url - `Request` object, `URL` object, or URL string.
|
||||
@returns A promise with `Body` methods added.
|
||||
*/
|
||||
head: (url: Input, options?: Options) => ResponsePromise;
|
||||
|
||||
/**
|
||||
Create a new Ky instance with complete new defaults.
|
||||
|
||||
@returns A new Ky instance.
|
||||
*/
|
||||
create: (defaultOptions: Options) => typeof ky;
|
||||
|
||||
/**
|
||||
Create a new Ky instance with some defaults overridden with your own.
|
||||
|
||||
In contrast to `ky.create()`, `ky.extend()` inherits defaults from its parent.
|
||||
|
||||
@returns A new Ky instance.
|
||||
*/
|
||||
extend: (defaultOptions: Options) => typeof ky;
|
||||
|
||||
/**
|
||||
A `Symbol` that can be returned by a `beforeRetry` hook to stop the retry.
|
||||
This will also short circuit the remaining `beforeRetry` hooks.
|
||||
|
||||
@example
|
||||
```
|
||||
import ky from 'ky';
|
||||
|
||||
(async () => {
|
||||
await ky('https://example.com', {
|
||||
hooks: {
|
||||
beforeRetry: [
|
||||
async ({request, options, error, retryCount}) => {
|
||||
const shouldStopRetry = await ky('https://example.com/api');
|
||||
if (shouldStopRetry) {
|
||||
return ky.stop;
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
});
|
||||
})();
|
||||
```
|
||||
*/
|
||||
readonly stop: unique symbol;
|
||||
readonly TimeoutError: typeof TimeoutError;
|
||||
readonly HTTPError: typeof HTTPError;
|
||||
};
|
||||
|
||||
declare namespace ky {
|
||||
export type TimeoutError = InstanceType<typeof TimeoutError>;
|
||||
export type HTTPError = InstanceType<typeof HTTPError>;
|
||||
}
|
||||
|
||||
export default ky;
|
528
node_modules/ky/index.js
generated
vendored
Normal file
528
node_modules/ky/index.js
generated
vendored
Normal file
|
@ -0,0 +1,528 @@
|
|||
/*! MIT License © Sindre Sorhus */
|
||||
|
||||
const globals = {};
|
||||
|
||||
const getGlobal = property => {
|
||||
/* istanbul ignore next */
|
||||
if (typeof self !== 'undefined' && self && property in self) {
|
||||
return self;
|
||||
}
|
||||
|
||||
/* istanbul ignore next */
|
||||
if (typeof window !== 'undefined' && window && property in window) {
|
||||
return window;
|
||||
}
|
||||
|
||||
if (typeof global !== 'undefined' && global && property in global) {
|
||||
return global;
|
||||
}
|
||||
|
||||
/* istanbul ignore next */
|
||||
if (typeof globalThis !== 'undefined' && globalThis) {
|
||||
return globalThis;
|
||||
}
|
||||
};
|
||||
|
||||
const globalProperties = [
|
||||
'Headers',
|
||||
'Request',
|
||||
'Response',
|
||||
'ReadableStream',
|
||||
'fetch',
|
||||
'AbortController',
|
||||
'FormData'
|
||||
];
|
||||
|
||||
for (const property of globalProperties) {
|
||||
Object.defineProperty(globals, property, {
|
||||
get() {
|
||||
const globalObject = getGlobal(property);
|
||||
const value = globalObject && globalObject[property];
|
||||
return typeof value === 'function' ? value.bind(globalObject) : value;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const isObject = value => value !== null && typeof value === 'object';
|
||||
const supportsAbortController = typeof globals.AbortController === 'function';
|
||||
const supportsStreams = typeof globals.ReadableStream === 'function';
|
||||
const supportsFormData = typeof globals.FormData === 'function';
|
||||
|
||||
const mergeHeaders = (source1, source2) => {
|
||||
const result = new globals.Headers(source1 || {});
|
||||
const isHeadersInstance = source2 instanceof globals.Headers;
|
||||
const source = new globals.Headers(source2 || {});
|
||||
|
||||
for (const [key, value] of source) {
|
||||
if ((isHeadersInstance && value === 'undefined') || value === undefined) {
|
||||
result.delete(key);
|
||||
} else {
|
||||
result.set(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
const deepMerge = (...sources) => {
|
||||
let returnValue = {};
|
||||
let headers = {};
|
||||
|
||||
for (const source of sources) {
|
||||
if (Array.isArray(source)) {
|
||||
if (!(Array.isArray(returnValue))) {
|
||||
returnValue = [];
|
||||
}
|
||||
|
||||
returnValue = [...returnValue, ...source];
|
||||
} else if (isObject(source)) {
|
||||
for (let [key, value] of Object.entries(source)) {
|
||||
if (isObject(value) && (key in returnValue)) {
|
||||
value = deepMerge(returnValue[key], value);
|
||||
}
|
||||
|
||||
returnValue = {...returnValue, [key]: value};
|
||||
}
|
||||
|
||||
if (isObject(source.headers)) {
|
||||
headers = mergeHeaders(headers, source.headers);
|
||||
}
|
||||
}
|
||||
|
||||
returnValue.headers = headers;
|
||||
}
|
||||
|
||||
return returnValue;
|
||||
};
|
||||
|
||||
const requestMethods = [
|
||||
'get',
|
||||
'post',
|
||||
'put',
|
||||
'patch',
|
||||
'head',
|
||||
'delete'
|
||||
];
|
||||
|
||||
const responseTypes = {
|
||||
json: 'application/json',
|
||||
text: 'text/*',
|
||||
formData: 'multipart/form-data',
|
||||
arrayBuffer: '*/*',
|
||||
blob: '*/*'
|
||||
};
|
||||
|
||||
const retryMethods = [
|
||||
'get',
|
||||
'put',
|
||||
'head',
|
||||
'delete',
|
||||
'options',
|
||||
'trace'
|
||||
];
|
||||
|
||||
const retryStatusCodes = [
|
||||
408,
|
||||
413,
|
||||
429,
|
||||
500,
|
||||
502,
|
||||
503,
|
||||
504
|
||||
];
|
||||
|
||||
const retryAfterStatusCodes = [
|
||||
413,
|
||||
429,
|
||||
503
|
||||
];
|
||||
|
||||
const stop = Symbol('stop');
|
||||
|
||||
class HTTPError extends Error {
|
||||
constructor(response) {
|
||||
// Set the message to the status text, such as Unauthorized,
|
||||
// with some fallbacks. This message should never be undefined.
|
||||
super(
|
||||
response.statusText ||
|
||||
String(
|
||||
(response.status === 0 || response.status) ?
|
||||
response.status : 'Unknown response error'
|
||||
)
|
||||
);
|
||||
this.name = 'HTTPError';
|
||||
this.response = response;
|
||||
}
|
||||
}
|
||||
|
||||
class TimeoutError extends Error {
|
||||
constructor(request) {
|
||||
super('Request timed out');
|
||||
this.name = 'TimeoutError';
|
||||
this.request = request;
|
||||
}
|
||||
}
|
||||
|
||||
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
|
||||
|
||||
// `Promise.race()` workaround (#91)
|
||||
const timeout = (request, abortController, options) =>
|
||||
new Promise((resolve, reject) => {
|
||||
const timeoutID = setTimeout(() => {
|
||||
if (abortController) {
|
||||
abortController.abort();
|
||||
}
|
||||
|
||||
reject(new TimeoutError(request));
|
||||
}, options.timeout);
|
||||
|
||||
/* eslint-disable promise/prefer-await-to-then */
|
||||
options.fetch(request)
|
||||
.then(resolve)
|
||||
.catch(reject)
|
||||
.then(() => {
|
||||
clearTimeout(timeoutID);
|
||||
});
|
||||
/* eslint-enable promise/prefer-await-to-then */
|
||||
});
|
||||
|
||||
const normalizeRequestMethod = input => requestMethods.includes(input) ? input.toUpperCase() : input;
|
||||
|
||||
const defaultRetryOptions = {
|
||||
limit: 2,
|
||||
methods: retryMethods,
|
||||
statusCodes: retryStatusCodes,
|
||||
afterStatusCodes: retryAfterStatusCodes
|
||||
};
|
||||
|
||||
const normalizeRetryOptions = (retry = {}) => {
|
||||
if (typeof retry === 'number') {
|
||||
return {
|
||||
...defaultRetryOptions,
|
||||
limit: retry
|
||||
};
|
||||
}
|
||||
|
||||
if (retry.methods && !Array.isArray(retry.methods)) {
|
||||
throw new Error('retry.methods must be an array');
|
||||
}
|
||||
|
||||
if (retry.statusCodes && !Array.isArray(retry.statusCodes)) {
|
||||
throw new Error('retry.statusCodes must be an array');
|
||||
}
|
||||
|
||||
return {
|
||||
...defaultRetryOptions,
|
||||
...retry,
|
||||
afterStatusCodes: retryAfterStatusCodes
|
||||
};
|
||||
};
|
||||
|
||||
// The maximum value of a 32bit int (see issue #117)
|
||||
const maxSafeTimeout = 2147483647;
|
||||
|
||||
class Ky {
|
||||
constructor(input, options = {}) {
|
||||
this._retryCount = 0;
|
||||
this._input = input;
|
||||
this._options = {
|
||||
// TODO: credentials can be removed when the spec change is implemented in all browsers. Context: https://www.chromestatus.com/feature/4539473312350208
|
||||
credentials: this._input.credentials || 'same-origin',
|
||||
...options,
|
||||
headers: mergeHeaders(this._input.headers, options.headers),
|
||||
hooks: deepMerge({
|
||||
beforeRequest: [],
|
||||
beforeRetry: [],
|
||||
afterResponse: []
|
||||
}, options.hooks),
|
||||
method: normalizeRequestMethod(options.method || this._input.method),
|
||||
prefixUrl: String(options.prefixUrl || ''),
|
||||
retry: normalizeRetryOptions(options.retry),
|
||||
throwHttpErrors: options.throwHttpErrors !== false,
|
||||
timeout: typeof options.timeout === 'undefined' ? 10000 : options.timeout,
|
||||
fetch: options.fetch || globals.fetch
|
||||
};
|
||||
|
||||
if (typeof this._input !== 'string' && !(this._input instanceof URL || this._input instanceof globals.Request)) {
|
||||
throw new TypeError('`input` must be a string, URL, or Request');
|
||||
}
|
||||
|
||||
if (this._options.prefixUrl && typeof this._input === 'string') {
|
||||
if (this._input.startsWith('/')) {
|
||||
throw new Error('`input` must not begin with a slash when using `prefixUrl`');
|
||||
}
|
||||
|
||||
if (!this._options.prefixUrl.endsWith('/')) {
|
||||
this._options.prefixUrl += '/';
|
||||
}
|
||||
|
||||
this._input = this._options.prefixUrl + this._input;
|
||||
}
|
||||
|
||||
if (supportsAbortController) {
|
||||
this.abortController = new globals.AbortController();
|
||||
if (this._options.signal) {
|
||||
this._options.signal.addEventListener('abort', () => {
|
||||
this.abortController.abort();
|
||||
});
|
||||
}
|
||||
|
||||
this._options.signal = this.abortController.signal;
|
||||
}
|
||||
|
||||
this.request = new globals.Request(this._input, this._options);
|
||||
|
||||
if (this._options.searchParams) {
|
||||
const searchParams = '?' + new URLSearchParams(this._options.searchParams).toString();
|
||||
const url = this.request.url.replace(/(?:\?.*?)?(?=#|$)/, searchParams);
|
||||
|
||||
// To provide correct form boundary, Content-Type header should be deleted each time when new Request instantiated from another one
|
||||
if (((supportsFormData && this._options.body instanceof globals.FormData) || this._options.body instanceof URLSearchParams) && !(this._options.headers && this._options.headers['content-type'])) {
|
||||
this.request.headers.delete('content-type');
|
||||
}
|
||||
|
||||
this.request = new globals.Request(new globals.Request(url, this.request), this._options);
|
||||
}
|
||||
|
||||
if (this._options.json !== undefined) {
|
||||
this._options.body = JSON.stringify(this._options.json);
|
||||
this.request.headers.set('content-type', 'application/json');
|
||||
this.request = new globals.Request(this.request, {body: this._options.body});
|
||||
}
|
||||
|
||||
const fn = async () => {
|
||||
if (this._options.timeout > maxSafeTimeout) {
|
||||
throw new RangeError(`The \`timeout\` option cannot be greater than ${maxSafeTimeout}`);
|
||||
}
|
||||
|
||||
await delay(1);
|
||||
let response = await this._fetch();
|
||||
|
||||
for (const hook of this._options.hooks.afterResponse) {
|
||||
// eslint-disable-next-line no-await-in-loop
|
||||
const modifiedResponse = await hook(
|
||||
this.request,
|
||||
this._options,
|
||||
this._decorateResponse(response.clone())
|
||||
);
|
||||
|
||||
if (modifiedResponse instanceof globals.Response) {
|
||||
response = modifiedResponse;
|
||||
}
|
||||
}
|
||||
|
||||
this._decorateResponse(response);
|
||||
|
||||
if (!response.ok && this._options.throwHttpErrors) {
|
||||
throw new HTTPError(response);
|
||||
}
|
||||
|
||||
// If `onDownloadProgress` is passed, it uses the stream API internally
|
||||
/* istanbul ignore next */
|
||||
if (this._options.onDownloadProgress) {
|
||||
if (typeof this._options.onDownloadProgress !== 'function') {
|
||||
throw new TypeError('The `onDownloadProgress` option must be a function');
|
||||
}
|
||||
|
||||
if (!supportsStreams) {
|
||||
throw new Error('Streams are not supported in your environment. `ReadableStream` is missing.');
|
||||
}
|
||||
|
||||
return this._stream(response.clone(), this._options.onDownloadProgress);
|
||||
}
|
||||
|
||||
return response;
|
||||
};
|
||||
|
||||
const isRetriableMethod = this._options.retry.methods.includes(this.request.method.toLowerCase());
|
||||
const result = isRetriableMethod ? this._retry(fn) : fn();
|
||||
|
||||
for (const [type, mimeType] of Object.entries(responseTypes)) {
|
||||
result[type] = async () => {
|
||||
this.request.headers.set('accept', this.request.headers.get('accept') || mimeType);
|
||||
|
||||
const response = (await result).clone();
|
||||
|
||||
if (type === 'json') {
|
||||
if (response.status === 204) {
|
||||
return '';
|
||||
}
|
||||
|
||||
if (options.parseJson) {
|
||||
return options.parseJson(await response.text());
|
||||
}
|
||||
}
|
||||
|
||||
return response[type]();
|
||||
};
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
_calculateRetryDelay(error) {
|
||||
this._retryCount++;
|
||||
|
||||
if (this._retryCount < this._options.retry.limit && !(error instanceof TimeoutError)) {
|
||||
if (error instanceof HTTPError) {
|
||||
if (!this._options.retry.statusCodes.includes(error.response.status)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const retryAfter = error.response.headers.get('Retry-After');
|
||||
if (retryAfter && this._options.retry.afterStatusCodes.includes(error.response.status)) {
|
||||
let after = Number(retryAfter);
|
||||
if (Number.isNaN(after)) {
|
||||
after = Date.parse(retryAfter) - Date.now();
|
||||
} else {
|
||||
after *= 1000;
|
||||
}
|
||||
|
||||
if (typeof this._options.retry.maxRetryAfter !== 'undefined' && after > this._options.retry.maxRetryAfter) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return after;
|
||||
}
|
||||
|
||||
if (error.response.status === 413) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
const BACKOFF_FACTOR = 0.3;
|
||||
return BACKOFF_FACTOR * (2 ** (this._retryCount - 1)) * 1000;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
_decorateResponse(response) {
|
||||
if (this._options.parseJson) {
|
||||
response.json = async () => {
|
||||
return this._options.parseJson(await response.text());
|
||||
};
|
||||
}
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
async _retry(fn) {
|
||||
try {
|
||||
return await fn();
|
||||
} catch (error) {
|
||||
const ms = Math.min(this._calculateRetryDelay(error), maxSafeTimeout);
|
||||
if (ms !== 0 && this._retryCount > 0) {
|
||||
await delay(ms);
|
||||
|
||||
for (const hook of this._options.hooks.beforeRetry) {
|
||||
// eslint-disable-next-line no-await-in-loop
|
||||
const hookResult = await hook({
|
||||
request: this.request,
|
||||
options: this._options,
|
||||
error,
|
||||
retryCount: this._retryCount
|
||||
});
|
||||
|
||||
// If `stop` is returned from the hook, the retry process is stopped
|
||||
if (hookResult === stop) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
return this._retry(fn);
|
||||
}
|
||||
|
||||
if (this._options.throwHttpErrors) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async _fetch() {
|
||||
for (const hook of this._options.hooks.beforeRequest) {
|
||||
// eslint-disable-next-line no-await-in-loop
|
||||
const result = await hook(this.request, this._options);
|
||||
|
||||
if (result instanceof Request) {
|
||||
this.request = result;
|
||||
break;
|
||||
}
|
||||
|
||||
if (result instanceof Response) {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
if (this._options.timeout === false) {
|
||||
return this._options.fetch(this.request.clone());
|
||||
}
|
||||
|
||||
return timeout(this.request.clone(), this.abortController, this._options);
|
||||
}
|
||||
|
||||
/* istanbul ignore next */
|
||||
_stream(response, onDownloadProgress) {
|
||||
const totalBytes = Number(response.headers.get('content-length')) || 0;
|
||||
let transferredBytes = 0;
|
||||
|
||||
return new globals.Response(
|
||||
new globals.ReadableStream({
|
||||
start(controller) {
|
||||
const reader = response.body.getReader();
|
||||
|
||||
if (onDownloadProgress) {
|
||||
onDownloadProgress({percent: 0, transferredBytes: 0, totalBytes}, new Uint8Array());
|
||||
}
|
||||
|
||||
async function read() {
|
||||
const {done, value} = await reader.read();
|
||||
if (done) {
|
||||
controller.close();
|
||||
return;
|
||||
}
|
||||
|
||||
if (onDownloadProgress) {
|
||||
transferredBytes += value.byteLength;
|
||||
const percent = totalBytes === 0 ? 0 : transferredBytes / totalBytes;
|
||||
onDownloadProgress({percent, transferredBytes, totalBytes}, value);
|
||||
}
|
||||
|
||||
controller.enqueue(value);
|
||||
read();
|
||||
}
|
||||
|
||||
read();
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const validateAndMerge = (...sources) => {
|
||||
for (const source of sources) {
|
||||
if ((!isObject(source) || Array.isArray(source)) && typeof source !== 'undefined') {
|
||||
throw new TypeError('The `options` argument must be an object');
|
||||
}
|
||||
}
|
||||
|
||||
return deepMerge({}, ...sources);
|
||||
};
|
||||
|
||||
const createInstance = defaults => {
|
||||
const ky = (input, options) => new Ky(input, validateAndMerge(defaults, options));
|
||||
|
||||
for (const method of requestMethods) {
|
||||
ky[method] = (input, options) => new Ky(input, validateAndMerge(defaults, options, {method}));
|
||||
}
|
||||
|
||||
ky.HTTPError = HTTPError;
|
||||
ky.TimeoutError = TimeoutError;
|
||||
ky.create = newDefaults => createInstance(validateAndMerge(newDefaults));
|
||||
ky.extend = newDefaults => createInstance(validateAndMerge(defaults, newDefaults));
|
||||
ky.stop = stop;
|
||||
|
||||
return ky;
|
||||
};
|
||||
|
||||
export default createInstance();
|
9
node_modules/ky/license
generated
vendored
Normal file
9
node_modules/ky/license
generated
vendored
Normal file
|
@ -0,0 +1,9 @@
|
|||
MIT License
|
||||
|
||||
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
88
node_modules/ky/package.json
generated
vendored
Normal file
88
node_modules/ky/package.json
generated
vendored
Normal file
|
@ -0,0 +1,88 @@
|
|||
{
|
||||
"name": "ky",
|
||||
"version": "0.25.1",
|
||||
"description": "Tiny and elegant HTTP client based on the browser Fetch API",
|
||||
"license": "MIT",
|
||||
"repository": "sindresorhus/ky",
|
||||
"funding": "https://github.com/sindresorhus/ky?sponsor=1",
|
||||
"author": {
|
||||
"name": "Sindre Sorhus",
|
||||
"email": "sindresorhus@gmail.com",
|
||||
"url": "https://sindresorhus.com"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "rollup index.js --format=umd --name=ky --file=umd.js",
|
||||
"prepare": "npm run build",
|
||||
"test": "xo && npm run build && nyc ava && tsd"
|
||||
},
|
||||
"files": [
|
||||
"index.js",
|
||||
"index.d.ts",
|
||||
"umd.js",
|
||||
"umd.d.ts"
|
||||
],
|
||||
"keywords": [
|
||||
"fetch",
|
||||
"request",
|
||||
"requests",
|
||||
"http",
|
||||
"https",
|
||||
"fetching",
|
||||
"get",
|
||||
"url",
|
||||
"curl",
|
||||
"wget",
|
||||
"net",
|
||||
"network",
|
||||
"ajax",
|
||||
"api",
|
||||
"rest",
|
||||
"xhr",
|
||||
"browser",
|
||||
"got",
|
||||
"axios",
|
||||
"node-fetch"
|
||||
],
|
||||
"devDependencies": {
|
||||
"abort-controller": "^3.0.0",
|
||||
"ava": "^3.2.0",
|
||||
"body": "^5.1.0",
|
||||
"busboy": "^0.3.1",
|
||||
"create-test-server": "2.1.1",
|
||||
"delay": "^4.1.0",
|
||||
"esm": "^3.2.22",
|
||||
"form-data": "^3.0.0",
|
||||
"node-fetch": "^2.5.0",
|
||||
"nyc": "^15.0.0",
|
||||
"puppeteer": "^5.1.0",
|
||||
"rollup": "^2.10.2",
|
||||
"tsd": "^0.13.1",
|
||||
"xo": "^0.25.3"
|
||||
},
|
||||
"sideEffects": false,
|
||||
"xo": {
|
||||
"envs": [
|
||||
"browser"
|
||||
],
|
||||
"globals": [
|
||||
"globalThis"
|
||||
]
|
||||
},
|
||||
"ava": {
|
||||
"require": [
|
||||
"esm",
|
||||
"./test/_require"
|
||||
]
|
||||
},
|
||||
"tsd": {
|
||||
"compilerOptions": {
|
||||
"lib": [
|
||||
"es2018",
|
||||
"dom"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
637
node_modules/ky/readme.md
generated
vendored
Normal file
637
node_modules/ky/readme.md
generated
vendored
Normal file
|
@ -0,0 +1,637 @@
|
|||
<div align="center">
|
||||
<br>
|
||||
<div>
|
||||
<img width="600" height="600" src="media/logo.svg" alt="ky">
|
||||
</div>
|
||||
<p align="center">Huge thanks to <a href="https://lunanode.com"><img src="https://sindresorhus.com/assets/thanks/lunanode-logo.svg" width="170"></a> for sponsoring me!</p>
|
||||
<br>
|
||||
<br>
|
||||
<br>
|
||||
<br>
|
||||
</div>
|
||||
|
||||
> Ky is a tiny and elegant HTTP client based on the browser [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch)
|
||||
|
||||
[](https://codecov.io/gh/sindresorhus/ky) [](https://bundlephobia.com/result?p=ky)
|
||||
|
||||
Ky targets [modern browsers](#browser-support) and [Deno](https://github.com/denoland/deno). For older browsers, you will need to transpile and use a [`fetch` polyfill](https://github.com/github/fetch). For Node.js, check out [Got](https://github.com/sindresorhus/got). For isomorphic needs (like SSR), check out [`ky-universal`](https://github.com/sindresorhus/ky-universal).
|
||||
|
||||
It's just a tiny file with no dependencies.
|
||||
|
||||
## Benefits over plain `fetch`
|
||||
|
||||
- Simpler API
|
||||
- Method shortcuts (`ky.post()`)
|
||||
- Treats non-2xx status codes as errors (after redirects)
|
||||
- Retries failed requests
|
||||
- JSON option
|
||||
- Timeout support
|
||||
- URL prefix option
|
||||
- Instances with custom defaults
|
||||
- Hooks
|
||||
|
||||
## Install
|
||||
|
||||
```
|
||||
$ npm install ky
|
||||
```
|
||||
|
||||
###### Download
|
||||
|
||||
- [Normal](https://cdn.jsdelivr.net/npm/ky/index.js)
|
||||
- [Minified](https://cdn.jsdelivr.net/npm/ky/index.min.js)
|
||||
|
||||
###### CDN
|
||||
|
||||
- [jsdelivr](https://www.jsdelivr.com/package/npm/ky)
|
||||
- [unpkg](https://unpkg.com/ky)
|
||||
|
||||
## Usage
|
||||
|
||||
```js
|
||||
import ky from 'ky';
|
||||
|
||||
(async () => {
|
||||
const parsed = await ky.post('https://example.com', {json: {foo: true}}).json();
|
||||
|
||||
console.log(parsed);
|
||||
//=> `{data: '🦄'}`
|
||||
})();
|
||||
```
|
||||
|
||||
With plain `fetch`, it would be:
|
||||
|
||||
```js
|
||||
(async () => {
|
||||
class HTTPError extends Error {}
|
||||
|
||||
const response = await fetch('https://example.com', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({foo: true}),
|
||||
headers: {
|
||||
'content-type': 'application/json'
|
||||
}
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new HTTPError(`Fetch error: ${response.statusText}`);
|
||||
}
|
||||
|
||||
const parsed = await response.json();
|
||||
|
||||
console.log(parsed);
|
||||
//=> `{data: '🦄'}`
|
||||
})();
|
||||
```
|
||||
|
||||
If you are using [Deno](https://github.com/denoland/deno), import Ky from a URL. For example, using a CDN:
|
||||
|
||||
```js
|
||||
import ky from 'https://unpkg.com/ky/index.js';
|
||||
```
|
||||
|
||||
In environments that do not support `import`, you can load `ky` in [UMD format](https://medium.freecodecamp.org/anatomy-of-js-module-systems-and-building-libraries-fadcd8dbd0e). For example, using `require()`:
|
||||
|
||||
```js
|
||||
const ky = require('ky/umd');
|
||||
```
|
||||
|
||||
With the UMD version, it's also easy to use `ky` [without a bundler](#how-do-i-use-this-without-a-bundler-like-webpack) or module system.
|
||||
|
||||
## API
|
||||
|
||||
### ky(input, options?)
|
||||
|
||||
The `input` and `options` are the same as [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch), with some exceptions:
|
||||
|
||||
- The `credentials` option is `same-origin` by default, which is the default in the spec too, but not all browsers have caught up yet.
|
||||
- Adds some more options. See below.
|
||||
|
||||
Returns a [`Response` object](https://developer.mozilla.org/en-US/docs/Web/API/Response) with [`Body` methods](https://developer.mozilla.org/en-US/docs/Web/API/Body#Methods) added for convenience. So you can, for example, call `ky.get(input).json()` directly without having to await the `Response` first. When called like that, an appropriate `Accept` header will be set depending on the body method used. Unlike the `Body` methods of `window.Fetch`; these will throw an `HTTPError` if the response status is not in the range of `200...299`. Also, `.json()` will return an empty string if the response status is `204` instead of throwing a parse error due to an empty body.
|
||||
|
||||
### ky.get(input, options?)
|
||||
### ky.post(input, options?)
|
||||
### ky.put(input, options?)
|
||||
### ky.patch(input, options?)
|
||||
### ky.head(input, options?)
|
||||
### ky.delete(input, options?)
|
||||
|
||||
Sets `options.method` to the method name and makes a request.
|
||||
|
||||
When using a `Request` instance as `input`, any URL altering options (such as `prefixUrl`) will be ignored.
|
||||
|
||||
#### options
|
||||
|
||||
Type: `object`
|
||||
|
||||
##### method
|
||||
|
||||
Type: `string`\
|
||||
Default: `'get'`
|
||||
|
||||
HTTP method used to make the request.
|
||||
|
||||
Internally, the standard methods (`GET`, `POST`, `PUT`, `PATCH`, `HEAD` and `DELETE`) are uppercased in order to avoid server errors due to case sensitivity.
|
||||
|
||||
##### json
|
||||
|
||||
Type: `object` and any other value accepted by [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify)
|
||||
|
||||
Shortcut for sending JSON. Use this instead of the `body` option. Accepts any plain object or value, which will be `JSON.stringify()`'d and sent in the body with the correct header set.
|
||||
|
||||
##### searchParams
|
||||
|
||||
Type: `string | object<string, string | number | boolean> | Array<Array<string | number | boolean>> | URLSearchParams`\
|
||||
Default: `''`
|
||||
|
||||
Search parameters to include in the request URL. Setting this will override all existing search parameters in the input URL.
|
||||
|
||||
Accepts any value supported by [`URLSearchParams()`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/URLSearchParams).
|
||||
|
||||
##### prefixUrl
|
||||
|
||||
Type: `string | URL`
|
||||
|
||||
A prefix to prepend to the `input` URL when making the request. It can be any valid URL, either relative or absolute. A trailing slash `/` is optional and will be added automatically, if needed, when it is joined with `input`. Only takes effect when `input` is a string. The `input` argument cannot start with a slash `/` when using this option.
|
||||
|
||||
Useful when used with [`ky.extend()`](#kyextenddefaultoptions) to create niche-specific Ky-instances.
|
||||
|
||||
```js
|
||||
import ky from 'ky';
|
||||
|
||||
// On https://example.com
|
||||
|
||||
(async () => {
|
||||
await ky('unicorn', {prefixUrl: '/api'});
|
||||
//=> 'https://example.com/api/unicorn'
|
||||
|
||||
await ky('unicorn', {prefixUrl: 'https://cats.com'});
|
||||
//=> 'https://cats.com/unicorn'
|
||||
})();
|
||||
```
|
||||
|
||||
Notes:
|
||||
- After `prefixUrl` and `input` are joined, the result is resolved against the [base URL](https://developer.mozilla.org/en-US/docs/Web/API/Node/baseURI) of the page (if any).
|
||||
- Leading slashes in `input` are disallowed when using this option to enforce consistency and avoid confusion about how the `input` URL is handled, given that `input` will not follow the normal URL resolution rules when `prefixUrl` is being used, which changes the meaning of a leading slash.
|
||||
|
||||
##### retry
|
||||
|
||||
Type: `object | number`\
|
||||
Default:
|
||||
- `limit`: `2`
|
||||
- `methods`: `get` `put` `head` `delete` `options` `trace`
|
||||
- `statusCodes`: [`408`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/408) [`413`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/413) [`429`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429) [`500`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/500) [`502`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/502) [`503`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/503) [`504`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/504)
|
||||
- `maxRetryAfter`: `undefined`
|
||||
|
||||
An object representing `limit`, `methods`, `statusCodes` and `maxRetryAfter` fields for maximum retry count, allowed methods, allowed status codes and maximum [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) time.
|
||||
|
||||
If `retry` is a number, it will be used as `limit` and other defaults will remain in place.
|
||||
|
||||
If `maxRetryAfter` is set to `undefined`, it will use `options.timeout`. If [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) header is greater than `maxRetryAfter`, it will cancel the request.
|
||||
|
||||
Delays between retries is calculated with the function `0.3 * (2 ** (retry - 1)) * 1000`, where `retry` is the attempt number (starts from 1).
|
||||
|
||||
```js
|
||||
import ky from 'ky';
|
||||
|
||||
(async () => {
|
||||
const parsed = await ky('https://example.com', {
|
||||
retry: {
|
||||
limit: 10,
|
||||
methods: ['get'],
|
||||
statusCodes: [413]
|
||||
}
|
||||
}).json();
|
||||
})();
|
||||
```
|
||||
|
||||
##### timeout
|
||||
|
||||
Type: `number | false`\
|
||||
Default: `10000`
|
||||
|
||||
Timeout in milliseconds for getting a response. Can not be greater than 2147483647.
|
||||
If set to `false`, there will be no timeout.
|
||||
|
||||
##### hooks
|
||||
|
||||
Type: `object<string, Function[]>`\
|
||||
Default: `{beforeRequest: [], beforeRetry: [], afterResponse: []}`
|
||||
|
||||
Hooks allow modifications during the request lifecycle. Hook functions may be async and are run serially.
|
||||
|
||||
###### hooks.beforeRequest
|
||||
|
||||
Type: `Function[]`\
|
||||
Default: `[]`
|
||||
|
||||
This hook enables you to modify the request right before it is sent. Ky will make no further changes to the request after this. The hook function receives `request` and `options` as arguments. You could, for example, modify the `request.headers` here.
|
||||
|
||||
The hook can return a [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) to replace the outgoing request, or return a [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) to completely avoid making an HTTP request. This can be used to mock a request, check an internal cache, etc. An **important** consideration when returning a request or response from this hook is that any remaining `beforeRequest` hooks will be skipped, so you may want to only return them from the last hook.
|
||||
|
||||
```js
|
||||
import ky from 'ky';
|
||||
|
||||
const api = ky.extend({
|
||||
hooks: {
|
||||
beforeRequest: [
|
||||
request => {
|
||||
request.headers.set('X-Requested-With', 'ky');
|
||||
}
|
||||
]
|
||||
}
|
||||
});
|
||||
|
||||
(async () => {
|
||||
const users = await api.get('https://example.com/api/users');
|
||||
// ...
|
||||
})();
|
||||
```
|
||||
|
||||
###### hooks.beforeRetry
|
||||
|
||||
Type: `Function[]`\
|
||||
Default: `[]`
|
||||
|
||||
This hook enables you to modify the request right before retry. Ky will make no further changes to the request after this. The hook function receives an object with the normalized request and options, an error instance, and the retry count. You could, for example, modify `request.headers` here.
|
||||
|
||||
If the request received a response, it will be available at `error.response`. Be aware that some types of errors, such as network errors, inherently mean that a response was not received.
|
||||
|
||||
```js
|
||||
import ky from 'ky';
|
||||
|
||||
(async () => {
|
||||
await ky('https://example.com', {
|
||||
hooks: {
|
||||
beforeRetry: [
|
||||
async ({request, options, error, retryCount}) => {
|
||||
const token = await ky('https://example.com/refresh-token');
|
||||
request.headers.set('Authorization', `token ${token}`);
|
||||
}
|
||||
]
|
||||
}
|
||||
});
|
||||
})();
|
||||
```
|
||||
|
||||
###### hooks.afterResponse
|
||||
|
||||
Type: `Function[]`\
|
||||
Default: `[]`
|
||||
|
||||
This hook enables you to read and optionally modify the response. The hook function receives normalized request, options, and a clone of the response as arguments. The return value of the hook function will be used by Ky as the response object if it's an instance of [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response).
|
||||
|
||||
```js
|
||||
import ky from 'ky';
|
||||
|
||||
(async () => {
|
||||
await ky('https://example.com', {
|
||||
hooks: {
|
||||
afterResponse: [
|
||||
(_request, _options, response) => {
|
||||
// You could do something with the response, for example, logging.
|
||||
log(response);
|
||||
|
||||
// Or return a `Response` instance to overwrite the response.
|
||||
return new Response('A different response', {status: 200});
|
||||
},
|
||||
|
||||
// Or retry with a fresh token on a 403 error
|
||||
async (request, options, response) => {
|
||||
if (response.status === 403) {
|
||||
// Get a fresh token
|
||||
const token = await ky('https://example.com/token').text();
|
||||
|
||||
// Retry with the token
|
||||
request.headers.set('Authorization', `token ${token}`);
|
||||
|
||||
return ky(request);
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
});
|
||||
})();
|
||||
```
|
||||
|
||||
##### throwHttpErrors
|
||||
|
||||
Type: `boolean`\
|
||||
Default: `true`
|
||||
|
||||
Throw an `HTTPError` when, after following redirects, the response has a non-2xx status code. To also throw for redirects instead of following them, set the [`redirect`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters) option to `'manual'`.
|
||||
|
||||
Setting this to `false` may be useful if you are checking for resource availability and are expecting error responses.
|
||||
|
||||
##### onDownloadProgress
|
||||
|
||||
Type: `Function`
|
||||
|
||||
Download progress event handler.
|
||||
|
||||
The function receives a `progress` and `chunk` argument:
|
||||
- The `progress` object contains the following elements: `percent`, `transferredBytes` and `totalBytes`. If it's not possible to retrieve the body size, `totalBytes` will be `0`.
|
||||
- The `chunk` argument is an instance of `Uint8Array`. It's empty for the first call.
|
||||
|
||||
```js
|
||||
import ky from 'ky';
|
||||
|
||||
(async () => {
|
||||
await ky('https://example.com', {
|
||||
onDownloadProgress: (progress, chunk) => {
|
||||
// Example output:
|
||||
// `0% - 0 of 1271 bytes`
|
||||
// `100% - 1271 of 1271 bytes`
|
||||
console.log(`${progress.percent * 100}% - ${progress.transferredBytes} of ${progress.totalBytes} bytes`);
|
||||
}
|
||||
});
|
||||
})();
|
||||
```
|
||||
|
||||
##### parseJson
|
||||
|
||||
Type: `Function`\
|
||||
Default: `JSON.parse()`
|
||||
|
||||
User-defined JSON-parsing function.
|
||||
|
||||
Use-cases:
|
||||
1. Parse JSON via the [`bourne` package](https://github.com/hapijs/bourne) to protect from prototype pollution.
|
||||
2. Parse JSON with [`reviver` option of `JSON.parse()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse).
|
||||
|
||||
```js
|
||||
import ky from 'ky';
|
||||
import bourne from '@hapijs/bourne';
|
||||
|
||||
(async () => {
|
||||
const parsed = await ky('https://example.com', {
|
||||
parseJson: text => bourne(text)
|
||||
}).json();
|
||||
})();
|
||||
```
|
||||
|
||||
##### fetch
|
||||
|
||||
Type: `Function`\
|
||||
Default: `fetch`
|
||||
|
||||
User-defined `fetch` function.
|
||||
Has to be fully compatible with the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) standard.
|
||||
|
||||
Use-cases:
|
||||
1. Use custom `fetch` implementations like [`isomorphic-unfetch`](https://www.npmjs.com/package/isomorphic-unfetch).
|
||||
2. Use the `fetch` wrapper function provided by some frameworks that use server-side rendering (SSR).
|
||||
|
||||
```js
|
||||
import ky from 'ky';
|
||||
import fetch from 'isomorphic-unfetch';
|
||||
|
||||
(async () => {
|
||||
const parsed = await ky('https://example.com', {
|
||||
fetch
|
||||
}).json();
|
||||
})();
|
||||
```
|
||||
|
||||
### ky.extend(defaultOptions)
|
||||
|
||||
Create a new `ky` instance with some defaults overridden with your own.
|
||||
|
||||
In contrast to `ky.create()`, `ky.extend()` inherits defaults from its parent.
|
||||
|
||||
You can pass headers as a `Headers` instance or a plain object.
|
||||
|
||||
You can remove a header with `.extend()` by passing the header with an `undefined` value.
|
||||
Passing `undefined` as a string removes the header only if it comes from a `Headers` instance.
|
||||
|
||||
```js
|
||||
import ky from 'ky';
|
||||
|
||||
const url = 'https://sindresorhus.com';
|
||||
|
||||
const original = ky.create({
|
||||
headers: {
|
||||
rainbow: 'rainbow',
|
||||
unicorn: 'unicorn'
|
||||
}
|
||||
});
|
||||
|
||||
const extended = original.extend({
|
||||
headers: {
|
||||
rainbow: undefined
|
||||
}
|
||||
});
|
||||
|
||||
const response = await extended(url).json();
|
||||
|
||||
console.log('rainbow' in response);
|
||||
//=> false
|
||||
|
||||
console.log('unicorn' in response);
|
||||
//=> true
|
||||
```
|
||||
|
||||
### ky.create(defaultOptions)
|
||||
|
||||
Create a new Ky instance with complete new defaults.
|
||||
|
||||
```js
|
||||
import ky from 'ky';
|
||||
|
||||
// On https://my-site.com
|
||||
|
||||
const api = ky.create({prefixUrl: 'https://example.com/api'});
|
||||
|
||||
(async () => {
|
||||
await api.get('users/123');
|
||||
//=> 'https://example.com/api/users/123'
|
||||
|
||||
await api.get('/status', {prefixUrl: ''});
|
||||
//=> 'https://my-site.com/status'
|
||||
})();
|
||||
```
|
||||
|
||||
#### defaultOptions
|
||||
|
||||
Type: `object`
|
||||
|
||||
### ky.HTTPError
|
||||
|
||||
Exposed for `instanceof` checks. The error has a `response` property with the [`Response` object](https://developer.mozilla.org/en-US/docs/Web/API/Response).
|
||||
|
||||
### ky.TimeoutError
|
||||
|
||||
The error thrown when the request times out.
|
||||
|
||||
### ky.stop
|
||||
|
||||
A `Symbol` that can be returned by a `beforeRetry` hook to stop the retry. This will also short circuit the remaining `beforeRetry` hooks.
|
||||
|
||||
```js
|
||||
import ky from 'ky';
|
||||
|
||||
(async () => {
|
||||
await ky('https://example.com', {
|
||||
hooks: {
|
||||
beforeRetry: [
|
||||
async ({request, options, error, retryCount}) => {
|
||||
const shouldStopRetry = await ky('https://example.com/api');
|
||||
if (shouldStopRetry) {
|
||||
return ky.stop;
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
});
|
||||
})();
|
||||
```
|
||||
|
||||
## Tips
|
||||
|
||||
### Sending form data
|
||||
|
||||
Sending form data in Ky is identical to `fetch`. Just pass a [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData) instance to the `body` option. The `Content-Type` header will be automatically set to `multipart/form-data`.
|
||||
|
||||
```js
|
||||
import ky from 'ky';
|
||||
|
||||
(async () => {
|
||||
// `multipart/form-data`
|
||||
const formData = new FormData();
|
||||
formData.append('food', 'fries');
|
||||
formData.append('drink', 'icetea');
|
||||
|
||||
await ky.post(url, {
|
||||
body: formData
|
||||
});
|
||||
})();
|
||||
```
|
||||
|
||||
If you want to send the data in `application/x-www-form-urlencoded` format, you will need to encode the data with [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams).
|
||||
|
||||
```js
|
||||
import ky from 'ky';
|
||||
|
||||
(async () => {
|
||||
// `application/x-www-form-urlencoded`
|
||||
const searchParams = new URLSearchParams();
|
||||
searchParams.set('food', 'fries');
|
||||
searchParams.set('drink', 'icetea');
|
||||
|
||||
await ky.post(url, {
|
||||
body: searchParams
|
||||
});
|
||||
})();
|
||||
```
|
||||
|
||||
### Cancellation
|
||||
|
||||
Fetch (and hence Ky) has built-in support for request cancellation through the [`AbortController` API](https://developer.mozilla.org/en-US/docs/Web/API/AbortController). [Read more.](https://developers.google.com/web/updates/2017/09/abortable-fetch)
|
||||
|
||||
Example:
|
||||
|
||||
```js
|
||||
import ky from 'ky';
|
||||
|
||||
const controller = new AbortController();
|
||||
const {signal} = controller;
|
||||
|
||||
setTimeout(() => {
|
||||
controller.abort();
|
||||
}, 5000);
|
||||
|
||||
(async () => {
|
||||
try {
|
||||
console.log(await ky(url, {signal}).text());
|
||||
} catch (error) {
|
||||
if (error.name === 'AbortError') {
|
||||
console.log('Fetch aborted');
|
||||
} else {
|
||||
console.error('Fetch error:', error);
|
||||
}
|
||||
}
|
||||
})();
|
||||
```
|
||||
|
||||
## FAQ
|
||||
|
||||
#### How do I use this in Node.js?
|
||||
|
||||
Check out [`ky-universal`](https://github.com/sindresorhus/ky-universal#faq).
|
||||
|
||||
#### How do I use this with a web app (React, Vue.js, etc.) that uses server-side rendering (SSR)?
|
||||
|
||||
Check out [`ky-universal`](https://github.com/sindresorhus/ky-universal#faq).
|
||||
|
||||
#### How do I test a browser library that uses this?
|
||||
|
||||
Either use a test runner that can run in the browser, like Mocha, or use [AVA](https://avajs.dev) with `ky-universal`. [Read more.](https://github.com/sindresorhus/ky-universal#faq)
|
||||
|
||||
#### How do I use this without a bundler like Webpack?
|
||||
|
||||
Upload the [`index.js`](index.js) file in this repo somewhere, for example, to your website server, or use a CDN version. Then import the file.
|
||||
|
||||
```html
|
||||
<script type="module">
|
||||
import ky from 'https://cdn.jsdelivr.net/npm/ky@latest/index.js';
|
||||
|
||||
(async () => {
|
||||
const parsed = await ky('https://jsonplaceholder.typicode.com/todos/1').json();
|
||||
|
||||
console.log(parsed.title);
|
||||
//=> 'delectus aut autem
|
||||
})();
|
||||
</script>
|
||||
```
|
||||
|
||||
Alternatively, you can use the [`umd.js`](umd.js) file with a traditional `<script>` tag (without `type="module"`), in which case `ky` will be a global.
|
||||
|
||||
```html
|
||||
<script src="https://cdn.jsdelivr.net/npm/ky@latest/umd.js"></script>
|
||||
<script>
|
||||
(async () => {
|
||||
const parsed = await ky('https://jsonplaceholder.typicode.com/todos/1').json();
|
||||
|
||||
console.log(parsed.title);
|
||||
//=> 'delectus aut autem
|
||||
})();
|
||||
</script>
|
||||
```
|
||||
|
||||
#### How is it different from [`got`](https://github.com/sindresorhus/got)
|
||||
|
||||
See my answer [here](https://twitter.com/sindresorhus/status/1037406558945042432). Got is maintained by the same people as Ky.
|
||||
|
||||
#### How is it different from [`axios`](https://github.com/axios/axios)?
|
||||
|
||||
See my answer [here](https://twitter.com/sindresorhus/status/1037763588826398720).
|
||||
|
||||
#### How is it different from [`r2`](https://github.com/mikeal/r2)?
|
||||
|
||||
See my answer in [#10](https://github.com/sindresorhus/ky/issues/10).
|
||||
|
||||
#### What does `ky` mean?
|
||||
|
||||
It's just a random short npm package name I managed to get. It does, however, have a meaning in Japanese:
|
||||
|
||||
> A form of text-able slang, KY is an abbreviation for 空気読めない (kuuki yomenai), which literally translates into “cannot read the air.” It's a phrase applied to someone who misses the implied meaning.
|
||||
|
||||
## Browser support
|
||||
|
||||
The latest version of Chrome, Firefox, and Safari.
|
||||
|
||||
## Node.js support
|
||||
|
||||
Polyfill the needed browser global or just use [`ky-universal`](https://github.com/sindresorhus/ky-universal).
|
||||
|
||||
## Related
|
||||
|
||||
- [ky-universal](https://github.com/sindresorhus/ky-universal) - Use Ky in both Node.js and browsers
|
||||
- [got](https://github.com/sindresorhus/got) - Simplified HTTP requests for Node.js
|
||||
- [ky-hooks-change-case](https://github.com/alice-health/ky-hooks-change-case) - Ky hooks to modify cases on requests and responses of objects
|
||||
|
||||
## Maintainers
|
||||
|
||||
- [Sindre Sorhus](https://github.com/sindresorhus)
|
||||
- [Szymon Marczak](https://github.com/szmarczak)
|
||||
- [Seth Holladay](https://github.com/sholladay)
|
1
node_modules/ky/umd.d.ts
generated
vendored
Normal file
1
node_modules/ky/umd.d.ts
generated
vendored
Normal file
|
@ -0,0 +1 @@
|
|||
export {default} from 'ky';
|
538
node_modules/ky/umd.js
generated
vendored
Normal file
538
node_modules/ky/umd.js
generated
vendored
Normal file
|
@ -0,0 +1,538 @@
|
|||
(function (global, factory) {
|
||||
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
|
||||
typeof define === 'function' && define.amd ? define(factory) :
|
||||
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.ky = factory());
|
||||
}(this, (function () { 'use strict';
|
||||
|
||||
/*! MIT License © Sindre Sorhus */
|
||||
|
||||
const globals = {};
|
||||
|
||||
const getGlobal = property => {
|
||||
/* istanbul ignore next */
|
||||
if (typeof self !== 'undefined' && self && property in self) {
|
||||
return self;
|
||||
}
|
||||
|
||||
/* istanbul ignore next */
|
||||
if (typeof window !== 'undefined' && window && property in window) {
|
||||
return window;
|
||||
}
|
||||
|
||||
if (typeof global !== 'undefined' && global && property in global) {
|
||||
return global;
|
||||
}
|
||||
|
||||
/* istanbul ignore next */
|
||||
if (typeof globalThis !== 'undefined' && globalThis) {
|
||||
return globalThis;
|
||||
}
|
||||
};
|
||||
|
||||
const globalProperties = [
|
||||
'Headers',
|
||||
'Request',
|
||||
'Response',
|
||||
'ReadableStream',
|
||||
'fetch',
|
||||
'AbortController',
|
||||
'FormData'
|
||||
];
|
||||
|
||||
for (const property of globalProperties) {
|
||||
Object.defineProperty(globals, property, {
|
||||
get() {
|
||||
const globalObject = getGlobal(property);
|
||||
const value = globalObject && globalObject[property];
|
||||
return typeof value === 'function' ? value.bind(globalObject) : value;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const isObject = value => value !== null && typeof value === 'object';
|
||||
const supportsAbortController = typeof globals.AbortController === 'function';
|
||||
const supportsStreams = typeof globals.ReadableStream === 'function';
|
||||
const supportsFormData = typeof globals.FormData === 'function';
|
||||
|
||||
const mergeHeaders = (source1, source2) => {
|
||||
const result = new globals.Headers(source1 || {});
|
||||
const isHeadersInstance = source2 instanceof globals.Headers;
|
||||
const source = new globals.Headers(source2 || {});
|
||||
|
||||
for (const [key, value] of source) {
|
||||
if ((isHeadersInstance && value === 'undefined') || value === undefined) {
|
||||
result.delete(key);
|
||||
} else {
|
||||
result.set(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
const deepMerge = (...sources) => {
|
||||
let returnValue = {};
|
||||
let headers = {};
|
||||
|
||||
for (const source of sources) {
|
||||
if (Array.isArray(source)) {
|
||||
if (!(Array.isArray(returnValue))) {
|
||||
returnValue = [];
|
||||
}
|
||||
|
||||
returnValue = [...returnValue, ...source];
|
||||
} else if (isObject(source)) {
|
||||
for (let [key, value] of Object.entries(source)) {
|
||||
if (isObject(value) && (key in returnValue)) {
|
||||
value = deepMerge(returnValue[key], value);
|
||||
}
|
||||
|
||||
returnValue = {...returnValue, [key]: value};
|
||||
}
|
||||
|
||||
if (isObject(source.headers)) {
|
||||
headers = mergeHeaders(headers, source.headers);
|
||||
}
|
||||
}
|
||||
|
||||
returnValue.headers = headers;
|
||||
}
|
||||
|
||||
return returnValue;
|
||||
};
|
||||
|
||||
const requestMethods = [
|
||||
'get',
|
||||
'post',
|
||||
'put',
|
||||
'patch',
|
||||
'head',
|
||||
'delete'
|
||||
];
|
||||
|
||||
const responseTypes = {
|
||||
json: 'application/json',
|
||||
text: 'text/*',
|
||||
formData: 'multipart/form-data',
|
||||
arrayBuffer: '*/*',
|
||||
blob: '*/*'
|
||||
};
|
||||
|
||||
const retryMethods = [
|
||||
'get',
|
||||
'put',
|
||||
'head',
|
||||
'delete',
|
||||
'options',
|
||||
'trace'
|
||||
];
|
||||
|
||||
const retryStatusCodes = [
|
||||
408,
|
||||
413,
|
||||
429,
|
||||
500,
|
||||
502,
|
||||
503,
|
||||
504
|
||||
];
|
||||
|
||||
const retryAfterStatusCodes = [
|
||||
413,
|
||||
429,
|
||||
503
|
||||
];
|
||||
|
||||
const stop = Symbol('stop');
|
||||
|
||||
class HTTPError extends Error {
|
||||
constructor(response) {
|
||||
// Set the message to the status text, such as Unauthorized,
|
||||
// with some fallbacks. This message should never be undefined.
|
||||
super(
|
||||
response.statusText ||
|
||||
String(
|
||||
(response.status === 0 || response.status) ?
|
||||
response.status : 'Unknown response error'
|
||||
)
|
||||
);
|
||||
this.name = 'HTTPError';
|
||||
this.response = response;
|
||||
}
|
||||
}
|
||||
|
||||
class TimeoutError extends Error {
|
||||
constructor(request) {
|
||||
super('Request timed out');
|
||||
this.name = 'TimeoutError';
|
||||
this.request = request;
|
||||
}
|
||||
}
|
||||
|
||||
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
|
||||
|
||||
// `Promise.race()` workaround (#91)
|
||||
const timeout = (request, abortController, options) =>
|
||||
new Promise((resolve, reject) => {
|
||||
const timeoutID = setTimeout(() => {
|
||||
if (abortController) {
|
||||
abortController.abort();
|
||||
}
|
||||
|
||||
reject(new TimeoutError(request));
|
||||
}, options.timeout);
|
||||
|
||||
/* eslint-disable promise/prefer-await-to-then */
|
||||
options.fetch(request)
|
||||
.then(resolve)
|
||||
.catch(reject)
|
||||
.then(() => {
|
||||
clearTimeout(timeoutID);
|
||||
});
|
||||
/* eslint-enable promise/prefer-await-to-then */
|
||||
});
|
||||
|
||||
const normalizeRequestMethod = input => requestMethods.includes(input) ? input.toUpperCase() : input;
|
||||
|
||||
const defaultRetryOptions = {
|
||||
limit: 2,
|
||||
methods: retryMethods,
|
||||
statusCodes: retryStatusCodes,
|
||||
afterStatusCodes: retryAfterStatusCodes
|
||||
};
|
||||
|
||||
const normalizeRetryOptions = (retry = {}) => {
|
||||
if (typeof retry === 'number') {
|
||||
return {
|
||||
...defaultRetryOptions,
|
||||
limit: retry
|
||||
};
|
||||
}
|
||||
|
||||
if (retry.methods && !Array.isArray(retry.methods)) {
|
||||
throw new Error('retry.methods must be an array');
|
||||
}
|
||||
|
||||
if (retry.statusCodes && !Array.isArray(retry.statusCodes)) {
|
||||
throw new Error('retry.statusCodes must be an array');
|
||||
}
|
||||
|
||||
return {
|
||||
...defaultRetryOptions,
|
||||
...retry,
|
||||
afterStatusCodes: retryAfterStatusCodes
|
||||
};
|
||||
};
|
||||
|
||||
// The maximum value of a 32bit int (see issue #117)
|
||||
const maxSafeTimeout = 2147483647;
|
||||
|
||||
class Ky {
|
||||
constructor(input, options = {}) {
|
||||
this._retryCount = 0;
|
||||
this._input = input;
|
||||
this._options = {
|
||||
// TODO: credentials can be removed when the spec change is implemented in all browsers. Context: https://www.chromestatus.com/feature/4539473312350208
|
||||
credentials: this._input.credentials || 'same-origin',
|
||||
...options,
|
||||
headers: mergeHeaders(this._input.headers, options.headers),
|
||||
hooks: deepMerge({
|
||||
beforeRequest: [],
|
||||
beforeRetry: [],
|
||||
afterResponse: []
|
||||
}, options.hooks),
|
||||
method: normalizeRequestMethod(options.method || this._input.method),
|
||||
prefixUrl: String(options.prefixUrl || ''),
|
||||
retry: normalizeRetryOptions(options.retry),
|
||||
throwHttpErrors: options.throwHttpErrors !== false,
|
||||
timeout: typeof options.timeout === 'undefined' ? 10000 : options.timeout,
|
||||
fetch: options.fetch || globals.fetch
|
||||
};
|
||||
|
||||
if (typeof this._input !== 'string' && !(this._input instanceof URL || this._input instanceof globals.Request)) {
|
||||
throw new TypeError('`input` must be a string, URL, or Request');
|
||||
}
|
||||
|
||||
if (this._options.prefixUrl && typeof this._input === 'string') {
|
||||
if (this._input.startsWith('/')) {
|
||||
throw new Error('`input` must not begin with a slash when using `prefixUrl`');
|
||||
}
|
||||
|
||||
if (!this._options.prefixUrl.endsWith('/')) {
|
||||
this._options.prefixUrl += '/';
|
||||
}
|
||||
|
||||
this._input = this._options.prefixUrl + this._input;
|
||||
}
|
||||
|
||||
if (supportsAbortController) {
|
||||
this.abortController = new globals.AbortController();
|
||||
if (this._options.signal) {
|
||||
this._options.signal.addEventListener('abort', () => {
|
||||
this.abortController.abort();
|
||||
});
|
||||
}
|
||||
|
||||
this._options.signal = this.abortController.signal;
|
||||
}
|
||||
|
||||
this.request = new globals.Request(this._input, this._options);
|
||||
|
||||
if (this._options.searchParams) {
|
||||
const searchParams = '?' + new URLSearchParams(this._options.searchParams).toString();
|
||||
const url = this.request.url.replace(/(?:\?.*?)?(?=#|$)/, searchParams);
|
||||
|
||||
// To provide correct form boundary, Content-Type header should be deleted each time when new Request instantiated from another one
|
||||
if (((supportsFormData && this._options.body instanceof globals.FormData) || this._options.body instanceof URLSearchParams) && !(this._options.headers && this._options.headers['content-type'])) {
|
||||
this.request.headers.delete('content-type');
|
||||
}
|
||||
|
||||
this.request = new globals.Request(new globals.Request(url, this.request), this._options);
|
||||
}
|
||||
|
||||
if (this._options.json !== undefined) {
|
||||
this._options.body = JSON.stringify(this._options.json);
|
||||
this.request.headers.set('content-type', 'application/json');
|
||||
this.request = new globals.Request(this.request, {body: this._options.body});
|
||||
}
|
||||
|
||||
const fn = async () => {
|
||||
if (this._options.timeout > maxSafeTimeout) {
|
||||
throw new RangeError(`The \`timeout\` option cannot be greater than ${maxSafeTimeout}`);
|
||||
}
|
||||
|
||||
await delay(1);
|
||||
let response = await this._fetch();
|
||||
|
||||
for (const hook of this._options.hooks.afterResponse) {
|
||||
// eslint-disable-next-line no-await-in-loop
|
||||
const modifiedResponse = await hook(
|
||||
this.request,
|
||||
this._options,
|
||||
this._decorateResponse(response.clone())
|
||||
);
|
||||
|
||||
if (modifiedResponse instanceof globals.Response) {
|
||||
response = modifiedResponse;
|
||||
}
|
||||
}
|
||||
|
||||
this._decorateResponse(response);
|
||||
|
||||
if (!response.ok && this._options.throwHttpErrors) {
|
||||
throw new HTTPError(response);
|
||||
}
|
||||
|
||||
// If `onDownloadProgress` is passed, it uses the stream API internally
|
||||
/* istanbul ignore next */
|
||||
if (this._options.onDownloadProgress) {
|
||||
if (typeof this._options.onDownloadProgress !== 'function') {
|
||||
throw new TypeError('The `onDownloadProgress` option must be a function');
|
||||
}
|
||||
|
||||
if (!supportsStreams) {
|
||||
throw new Error('Streams are not supported in your environment. `ReadableStream` is missing.');
|
||||
}
|
||||
|
||||
return this._stream(response.clone(), this._options.onDownloadProgress);
|
||||
}
|
||||
|
||||
return response;
|
||||
};
|
||||
|
||||
const isRetriableMethod = this._options.retry.methods.includes(this.request.method.toLowerCase());
|
||||
const result = isRetriableMethod ? this._retry(fn) : fn();
|
||||
|
||||
for (const [type, mimeType] of Object.entries(responseTypes)) {
|
||||
result[type] = async () => {
|
||||
this.request.headers.set('accept', this.request.headers.get('accept') || mimeType);
|
||||
|
||||
const response = (await result).clone();
|
||||
|
||||
if (type === 'json') {
|
||||
if (response.status === 204) {
|
||||
return '';
|
||||
}
|
||||
|
||||
if (options.parseJson) {
|
||||
return options.parseJson(await response.text());
|
||||
}
|
||||
}
|
||||
|
||||
return response[type]();
|
||||
};
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
_calculateRetryDelay(error) {
|
||||
this._retryCount++;
|
||||
|
||||
if (this._retryCount < this._options.retry.limit && !(error instanceof TimeoutError)) {
|
||||
if (error instanceof HTTPError) {
|
||||
if (!this._options.retry.statusCodes.includes(error.response.status)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const retryAfter = error.response.headers.get('Retry-After');
|
||||
if (retryAfter && this._options.retry.afterStatusCodes.includes(error.response.status)) {
|
||||
let after = Number(retryAfter);
|
||||
if (Number.isNaN(after)) {
|
||||
after = Date.parse(retryAfter) - Date.now();
|
||||
} else {
|
||||
after *= 1000;
|
||||
}
|
||||
|
||||
if (typeof this._options.retry.maxRetryAfter !== 'undefined' && after > this._options.retry.maxRetryAfter) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return after;
|
||||
}
|
||||
|
||||
if (error.response.status === 413) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
const BACKOFF_FACTOR = 0.3;
|
||||
return BACKOFF_FACTOR * (2 ** (this._retryCount - 1)) * 1000;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
_decorateResponse(response) {
|
||||
if (this._options.parseJson) {
|
||||
response.json = async () => {
|
||||
return this._options.parseJson(await response.text());
|
||||
};
|
||||
}
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
async _retry(fn) {
|
||||
try {
|
||||
return await fn();
|
||||
} catch (error) {
|
||||
const ms = Math.min(this._calculateRetryDelay(error), maxSafeTimeout);
|
||||
if (ms !== 0 && this._retryCount > 0) {
|
||||
await delay(ms);
|
||||
|
||||
for (const hook of this._options.hooks.beforeRetry) {
|
||||
// eslint-disable-next-line no-await-in-loop
|
||||
const hookResult = await hook({
|
||||
request: this.request,
|
||||
options: this._options,
|
||||
error,
|
||||
retryCount: this._retryCount
|
||||
});
|
||||
|
||||
// If `stop` is returned from the hook, the retry process is stopped
|
||||
if (hookResult === stop) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
return this._retry(fn);
|
||||
}
|
||||
|
||||
if (this._options.throwHttpErrors) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async _fetch() {
|
||||
for (const hook of this._options.hooks.beforeRequest) {
|
||||
// eslint-disable-next-line no-await-in-loop
|
||||
const result = await hook(this.request, this._options);
|
||||
|
||||
if (result instanceof Request) {
|
||||
this.request = result;
|
||||
break;
|
||||
}
|
||||
|
||||
if (result instanceof Response) {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
if (this._options.timeout === false) {
|
||||
return this._options.fetch(this.request.clone());
|
||||
}
|
||||
|
||||
return timeout(this.request.clone(), this.abortController, this._options);
|
||||
}
|
||||
|
||||
/* istanbul ignore next */
|
||||
_stream(response, onDownloadProgress) {
|
||||
const totalBytes = Number(response.headers.get('content-length')) || 0;
|
||||
let transferredBytes = 0;
|
||||
|
||||
return new globals.Response(
|
||||
new globals.ReadableStream({
|
||||
start(controller) {
|
||||
const reader = response.body.getReader();
|
||||
|
||||
if (onDownloadProgress) {
|
||||
onDownloadProgress({percent: 0, transferredBytes: 0, totalBytes}, new Uint8Array());
|
||||
}
|
||||
|
||||
async function read() {
|
||||
const {done, value} = await reader.read();
|
||||
if (done) {
|
||||
controller.close();
|
||||
return;
|
||||
}
|
||||
|
||||
if (onDownloadProgress) {
|
||||
transferredBytes += value.byteLength;
|
||||
const percent = totalBytes === 0 ? 0 : transferredBytes / totalBytes;
|
||||
onDownloadProgress({percent, transferredBytes, totalBytes}, value);
|
||||
}
|
||||
|
||||
controller.enqueue(value);
|
||||
read();
|
||||
}
|
||||
|
||||
read();
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const validateAndMerge = (...sources) => {
|
||||
for (const source of sources) {
|
||||
if ((!isObject(source) || Array.isArray(source)) && typeof source !== 'undefined') {
|
||||
throw new TypeError('The `options` argument must be an object');
|
||||
}
|
||||
}
|
||||
|
||||
return deepMerge({}, ...sources);
|
||||
};
|
||||
|
||||
const createInstance = defaults => {
|
||||
const ky = (input, options) => new Ky(input, validateAndMerge(defaults, options));
|
||||
|
||||
for (const method of requestMethods) {
|
||||
ky[method] = (input, options) => new Ky(input, validateAndMerge(defaults, options, {method}));
|
||||
}
|
||||
|
||||
ky.HTTPError = HTTPError;
|
||||
ky.TimeoutError = TimeoutError;
|
||||
ky.create = newDefaults => createInstance(validateAndMerge(newDefaults));
|
||||
ky.extend = newDefaults => createInstance(validateAndMerge(defaults, newDefaults));
|
||||
ky.stop = stop;
|
||||
|
||||
return ky;
|
||||
};
|
||||
|
||||
var index = createInstance();
|
||||
|
||||
return index;
|
||||
|
||||
})));
|
Loading…
Add table
Add a link
Reference in a new issue