Skip to content
Myr

Rename some internal types and upgrade dev dependencies

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 ff1563a · Browse files · 23 files+426 added−424 removed
This commit

State

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

Diff stats

23 files+426 added−424 removed

  • tests:+295 added−297 removed
  • other:+131 added−127 removed

23 files+426 added−424 removed

modified:source/core/constants.ts+4 added-4 removed
modified:source/core/Ky.ts+89 added-91 removed
8 unmodified lines
9import {ObjectEntries} from '../utils/types.js';10import {maxSafeTimeout, responseTypes, stop, supportsAbortController, supportsFormData, supportsStreams} from './constants.js';1112export class Ky {13 // eslint-disable-next-line @typescript-eslint/promise-function-async14 static create(input: Input, options: Options): ResponsePromise {15 const ky = new Ky(input, options);1617 const fn = async (): Promise<Response> => {18 if (ky._options.timeout > maxSafeTimeout) {19 throw new RangeError(`The \`timeout\` option cannot be greater than ${maxSafeTimeout}`);20 }2122 // Delay the fetch so that body method shortcuts can set the Accept header23 await Promise.resolve();24 let response = await ky._fetch();2526 for (const hook of ky._options.hooks.afterResponse) {27 // eslint-disable-next-line no-await-in-loop28 const modifiedResponse = await hook(29 ky.request,30 ky._options as NormalizedOptions,31 ky._decorateResponse(response.clone()),32 );3334 if (modifiedResponse instanceof globalThis.Response) {35 response = modifiedResponse;36 }37 }3839 ky._decorateResponse(response);4041 if (!response.ok && ky._options.throwHttpErrors) {42 throw new HTTPError(response, ky.request, (ky._options as unknown) as NormalizedOptions);43 }4445 // If `onDownloadProgress` is passed, it uses the stream API internally46 /* istanbul ignore next */47 if (ky._options.onDownloadProgress) {48 if (typeof ky._options.onDownloadProgress !== 'function') {49 throw new TypeError('The `onDownloadProgress` option must be a function');50 }5152 if (!supportsStreams) {53 throw new Error('Streams are not supported in your environment. `ReadableStream` is missing.');54 }5556 return ky._stream(response.clone(), ky._options.onDownloadProgress);57 }5859 return response;60 };6162 const isRetriableMethod = ky._options.retry.methods.includes(ky.request.method.toLowerCase());63 const result = (isRetriableMethod ? ky._retry(fn) : fn()) as ResponsePromise;6465 for (const [type, mimeType] of Object.entries(responseTypes) as ObjectEntries<typeof responseTypes>) {66 result[type] = async () => {67 // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing68 ky.request.headers.set('accept', ky.request.headers.get('accept') || mimeType);6970 const response = (await result).clone();7172 if (type === 'json') {73 if (response.status === 204) {74 return '';75 }7677 if (options.parseJson) {78 return options.parseJson(await response.text());79 }80 }8182 return response[type]();83 };84 }8586 return result;87 }8889 public request: Request;90 protected abortController?: AbortController;91 protected _retryCount = 0;92 protected _input: Input;
10 unmodified lines
103 hooks: deepMerge<Required<Hooks>>(104 {105 beforeRequest: [],106 beforeRetry: [],31 afterResponse: []107 afterResponse: [],108 },33 options.hooks109 options.hooks,110 ),111 method: normalizeRequestMethod(options.method ?? (this._input as Request).method),112 // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing113 prefixUrl: String(options.prefixUrl || ''),114 retry: normalizeRetryOptions(options.retry),115 throwHttpErrors: options.throwHttpErrors !== false,40 timeout: typeof options.timeout === 'undefined' ? 10000 : options.timeout,41 fetch: options.fetch ?? globalThis.fetch.bind(globalThis)116 timeout: typeof options.timeout === 'undefined' ? 10_000 : options.timeout,117 fetch: options.fetch ?? globalThis.fetch.bind(globalThis),118 };119120 if (typeof this._input !== 'string' && !(this._input instanceof URL || this._input instanceof globalThis.Request)) {121 throw new TypeError('`input` must be a string, URL, or Request');
25 unmodified lines
147 this.request = new globalThis.Request(this._input as RequestInfo, this._options as RequestInit);148149 if (this._options.searchParams) {150 // eslint-disable-next-line unicorn/prevent-abbreviations75 const textSearchParams = typeof this._options.searchParams === 'string' ?76 this._options.searchParams.replace(/^\?/, '') :77 new URLSearchParams(this._options.searchParams as unknown as SearchParamsInit).toString();151 const textSearchParams = typeof this._options.searchParams === 'string'152 ? this._options.searchParams.replace(/^\?/, '')153 : new URLSearchParams(this._options.searchParams as unknown as SearchParamsInit).toString();154 // eslint-disable-next-line unicorn/prevent-abbreviations155 const searchParams = '?' + textSearchParams;156 const url = this.request.url.replace(/(?:\?.*?)?(?=#|$)/, searchParams);157158 // To provide correct form boundary, Content-Type header should be deleted each time when new Request instantiated from another one159 if (84 ((supportsFormData && this._options.body instanceof globalThis.FormData) ||85 this._options.body instanceof URLSearchParams) && !(this._options.headers && (this._options.headers as Record<string, string>)['content-type'])160 ((supportsFormData && this._options.body instanceof globalThis.FormData)161 || this._options.body instanceof URLSearchParams) && !(this._options.headers && (this._options.headers as Record<string, string>)['content-type'])162 ) {163 this.request.headers.delete('content-type');164 }165
6 unmodified lines
172 this.request = new globalThis.Request(this.request, {body: this._options.body});173 }174 }175100 // eslint-disable-next-line @typescript-eslint/promise-function-async101 static create(input: Input, options: Options): ResponsePromise {102 const ky = new Ky(input, options);103104 const fn = async (): Promise<Response> => {105 if (ky._options.timeout > maxSafeTimeout) {106 throw new RangeError(`The \`timeout\` option cannot be greater than ${maxSafeTimeout}`);107 }108109 // Delay the fetch so that body method shortcuts can set the Accept header110 await Promise.resolve();111 let response = await ky._fetch();112113 for (const hook of ky._options.hooks.afterResponse) {114 // eslint-disable-next-line no-await-in-loop115 const modifiedResponse = await hook(116 ky.request,117 ky._options as NormalizedOptions,118 ky._decorateResponse(response.clone())119 );120121 if (modifiedResponse instanceof globalThis.Response) {122 response = modifiedResponse;123 }124 }125126 ky._decorateResponse(response);127128 if (!response.ok && ky._options.throwHttpErrors) {129 throw new HTTPError(response, ky.request, (ky._options as unknown) as NormalizedOptions);130 }131132 // If `onDownloadProgress` is passed, it uses the stream API internally133 /* istanbul ignore next */134 if (ky._options.onDownloadProgress) {135 if (typeof ky._options.onDownloadProgress !== 'function') {136 throw new TypeError('The `onDownloadProgress` option must be a function');137 }138139 if (!supportsStreams) {140 throw new Error('Streams are not supported in your environment. `ReadableStream` is missing.');141 }142143 return ky._stream(response.clone(), ky._options.onDownloadProgress);144 }145146 return response;147 };148149 const isRetriableMethod = ky._options.retry.methods.includes(ky.request.method.toLowerCase());150 const result = (isRetriableMethod ? ky._retry(fn) : fn()) as ResponsePromise;151152 for (const [type, mimeType] of Object.entries(responseTypes) as ObjectEntries<typeof responseTypes>) {153 result[type] = async () => {154 // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing155 ky.request.headers.set('accept', ky.request.headers.get('accept') || mimeType);156157 const response = (await result).clone();158159 if (type === 'json') {160 if (response.status === 204) {161 return '';162 }163164 if (options.parseJson) {165 return options.parseJson(await response.text());166 }167 }168169 return response[type]();170 };171 }172173 return result;174 }175176 protected _calculateRetryDelay(error: unknown) {177 this._retryCount++;178179 if (this._retryCount < this._options.retry.limit && !(error instanceof TimeoutError)) {
31 unmodified lines
211 }212213 protected _decorateResponse(response: Response): Response {214 if (this._options.parseJson) {215 response.json = async () => {216 return this._options.parseJson!(await response.text());217 };215 response.json = async () => this._options.parseJson!(await response.text());216 }217218 return response;219 }
12 unmodified lines
232 const hookResult = await hook({233 request: this.request,234 options: (this._options as unknown) as NormalizedOptions,235 error: error as Error,238 retryCount: this._retryCount236 retryCount: this._retryCount,237 });238239 // If `stop` is returned from the hook, the retry process is stopped240 if (hookResult === stop) {
61 unmodified lines
302 await read();303 }304305 await read();308 }309 })306 },307 }),308 );309 }310}
modified:source/errors/HTTPError.ts+1 added
modified:source/types/ky.ts+3 added-3 removed
modified:source/types/options.ts+2 added-2 removed
6 unmodified lines
78// eslint-disable-next-line unicorn/prevent-abbreviations9export type SearchParamsOption = SearchParamsInit | Record<string, string | number | boolean> | Array<Array<string | number | boolean>>;1011export type HTTPMethod = 'get' | 'post' | 'put' | 'patch' | 'head' | 'delete';11export type HttpMethod = 'get' | 'post' | 'put' | 'patch' | 'head' | 'delete';1213export type Input = string | URL | Request;1415export interface DownloadProgress {
16 unmodified lines
32 HTTP method used to make the request.3334 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>;36 method?: LiteralUnion<HttpMethod, string>;3738 /**39 HTTP headers used to make the request.40
208 unmodified lines
modified:source/types/response.ts+1 added-1 removed
29 unmodified lines
3031 const result = await ky(…).json<Result>();32 ```33 */34 json: <T>() => Promise<T>;34 json: <T = unknown>() => Promise<T>;3536 text: () => Promise<string>;37}
modified:source/utils/merge.ts+1 added
25 unmodified lines
2627 return result;28};2930// TODO: Make this strongly-typed (no `any`).31export const deepMerge = <T>(...sources: Array<Partial<T> | undefined>): T => {32 let returnValue: any = {};33 let headers = {};34
25 unmodified lines
modified:source/utils/normalize.ts+5 added-5 removed
1import {requestMethods} from '../core/constants.js';2import type {HTTPMethod} from '../types/options.js';2import type {HttpMethod} from '../types/options.js';3import type {RetryOptions} from '../types/retry.js';45export const normalizeRequestMethod = (input: string): string =>6 requestMethods.includes(input as HTTPMethod) ? input.toUpperCase() : input;6 requestMethods.includes(input as HttpMethod) ? input.toUpperCase() : input;78const retryMethods = ['get', 'put', 'head', 'delete', 'options', 'trace'];910const retryStatusCodes = [408, 413, 429, 500, 502, 503, 504];
4 unmodified lines
15 limit: 2,16 methods: retryMethods,17 statusCodes: retryStatusCodes,18 afterStatusCodes: retryAfterStatusCodes,19 maxRetryAfter: Number.POSITIVE_INFINITY19 maxRetryAfter: Number.POSITIVE_INFINITY,20};2122export const normalizeRetryOptions = (retry: number | RetryOptions = {}): Required<RetryOptions> => {23 if (typeof retry === 'number') {24 return {25 ...defaultRetryOptions,26 limit: retry26 limit: retry,27 };28 }2930 if (retry.methods && !Array.isArray(retry.methods)) {
6 unmodified lines
3738 return {39 ...defaultRetryOptions,40 ...retry,41 afterStatusCodes: retryAfterStatusCodes41 afterStatusCodes: retryAfterStatusCodes,42 };43};
modified:source/utils/time.ts+3 added-3 removed
7 unmodified lines
8// `Promise.race()` workaround (#91)9export const timeout = async (10 request: Request,11 abortController: AbortController | undefined,12 options: TimeoutOptions12 options: TimeoutOptions,13): Promise<Response> =>14 new Promise((resolve, reject) => {15 const timeoutID = setTimeout(() => {15 const timeoutId = setTimeout(() => {16 if (abortController) {17 abortController.abort();18 }19
5 unmodified lines
25 .fetch(request)26 .then(resolve)27 .catch(reject)28 .then(() => {29 clearTimeout(timeoutID);29 clearTimeout(timeoutId);30 });31 /* eslint-enable promise/prefer-await-to-then */32 });33
3 unmodified lines
modified:source/index.ts+6 added-6 removed
1/*! MIT License © Sindre Sorhus */23import {Ky} from './core/Ky.js';4import {requestMethods, stop} from './core/constants.js';5import type {ky as KyInterface} from './types/ky.js';5import type {KyInstance} from './types/ky.js';6import type {Input, Options} from './types/options.js';7import {validateAndMerge} from './utils/merge.js';8import {Mutable} from './utils/types.js';910const createInstance = (defaults?: Partial<Options>): KyInterface => {10const createInstance = (defaults?: Partial<Options>): KyInstance => {11 // eslint-disable-next-line @typescript-eslint/promise-function-async12 const ky: Partial<Mutable<KyInterface>> = (input: Input, options?: Options) => Ky.create(input, validateAndMerge(defaults, options));12 const ky: Partial<Mutable<KyInstance>> = (input: Input, options?: Options) => Ky.create(input, validateAndMerge(defaults, options));1314 for (const method of requestMethods) {15 // eslint-disable-next-line @typescript-eslint/promise-function-async16 ky[method] = (input: Input, options?: Options) => Ky.create(input, validateAndMerge(defaults, options, {method}));
2 unmodified lines
19 ky.create = (newDefaults?: Partial<Options>) => createInstance(validateAndMerge(newDefaults));20 ky.extend = (newDefaults?: Partial<Options>) => createInstance(validateAndMerge(defaults, newDefaults));21 ky.stop = stop;2223 return ky as KyInterface;23 return ky as KyInstance;24};2526const ky = createInstance();27
3 unmodified lines
31 Options,32 NormalizedOptions,33 RetryOptions,34 SearchParamsOption,35 DownloadProgress35 DownloadProgress,36} from './types/options.js';3738export {39 Hooks,40 BeforeRequestHook,41 BeforeRetryHook,42 AfterResponseHook42 AfterResponseHook,43} from './types/hooks.js';4445export {ResponsePromise} from './types/response.js';46export {HTTPError} from './errors/HTTPError.js';
1 unmodified line
modified:test/helpers/create-http-test-server.ts+10 added-10 removed
1import http from 'http';2import net from 'net';1import http from 'node:http';2import net from 'node:net';3import express from 'express';4import pify from 'pify';5import bodyParser from 'body-parser';6
19 unmodified lines
26 server.use(27 bodyParser.json({28 limit: '1mb',29 type: 'application/json',30 ...options.bodyParser31 })30 ...options.bodyParser,31 }),32 );33 server.use(34 bodyParser.text({35 limit: '1mb',36 type: 'text/plain',37 ...options.bodyParser38 })37 ...options.bodyParser,38 }),39 );40 server.use(41 bodyParser.urlencoded({42 limit: '1mb',43 type: 'application/x-www-form-urlencoded',44 extended: true,45 ...options.bodyParser46 })45 ...options.bodyParser,46 }),47 );48 server.use(49 bodyParser.raw({50 limit: '1mb',51 type: 'application/octet-stream',52 ...options.bodyParser53 })52 ...options.bodyParser,53 }),54 );55 }5657 await pify(server.http.listen.bind(server.http))();
9 unmodified lines
modified:test/helpers/with-page.ts+2 added-1 removed
1import process from 'node:process';2// eslint-disable-next-line ava/use-test3import type {ExecutionContext, UntitledMacro} from 'ava';4import {chromium, Page} from 'playwright-chromium';5
2 unmodified lines
8const PWDEBUG = Boolean(process.env['PWDEBUG']);910export const withPage: UntitledMacro<any[]> = async (t: ExecutionContext, run: Run): Promise<void> => {11 const browser = await chromium.launch({11 devtools: PWDEBUG12 devtools: PWDEBUG,13 });14 const page = await browser.newPage();15 try {16 await run(t, page);
4 unmodified lines
modified:test/_require.ts+8 added-5 removed
1/* eslint-disable @typescript-eslint/prefer-ts-expect-error */2import fetch, {Headers, Request, Response} from 'node-fetch';3import AbortController from 'abort-controller';4import FormData from 'form-data';56// We use `@ts-ignore` as there are some inconsistency error when using `@ts-expect-error`.78globalThis.AbortController = AbortController;6// @ts-expect-error9// @ts-ignore10globalThis.fetch = fetch;8// @ts-expect-error11// @ts-ignore12globalThis.Headers = Headers;10// @ts-expect-error13// @ts-ignore14globalThis.Request = Request;12// @ts-expect-error15// @ts-ignore16globalThis.Response = Response;14// @ts-expect-error17// @ts-ignore18globalThis.FormData = FormData;
modified:test/browser.ts+35 added-43 removed
1import test, {ExecutionContext} from 'ava';2import Busboy from 'busboy';3import express from 'express';4import {Page} from 'playwright-chromium';5import type {ky as kyInterface} from '../source/types/ky.js';5import ky from '../source/index.js';6import {createHttpTestServer, HttpServerOptions} from './helpers/create-http-test-server.js';7import {parseRawBody} from './helpers/parse-body.js';8import {withPage} from './helpers/with-page.js';910declare global {11 interface Window {12 ky: kyInterface;12 ky: typeof ky;13 }14}1516const DIST_DIR = new URL('../distribution', import.meta.url).toString();
7 unmodified lines
24 type: 'module',25 content: `26 import ky from '/distribution/index.js';27 globalThis.ky = ky;28 `28 `,29};30const addKyScriptToPage = async (page: Page) => {31 await page.addScriptTag(KY_SCRIPT);32 await page.waitForFunction(() => typeof window.ky === 'function');
10 unmodified lines
43 await page.goto(server.url);44 await addKyScriptToPage(page);4546 await t.throwsAsync(47 page.evaluate(async () => {48 return window.ky('/foo', {prefixUrl: '/'});49 }),50 {message: /`input` must not begin with a slash when using `prefixUrl`/}47 page.evaluate(async () => window.ky('/foo', {prefixUrl: '/'})),48 {message: /`input` must not begin with a slash when using `prefixUrl`/},49 );5053 const results = await page.evaluate(async url => {54 return Promise.all([55 window.ky(`${url}/api/unicorn`).text(),56 // @ts-expect-error unsupported {prefixUrl: null} type57 window.ky(`${url}/api/unicorn`, {prefixUrl: null}).text(),58 window.ky('api/unicorn', {prefixUrl: url}).text(),59 window.ky('api/unicorn', {prefixUrl: `${url}/`}).text()60 ]);61 }, server.url);51 const results = await page.evaluate(async url => Promise.all([52 window.ky(`${url}/api/unicorn`).text(),53 // @ts-expect-error unsupported {prefixUrl: null} type54 window.ky(`${url}/api/unicorn`, {prefixUrl: null}).text(),55 window.ky('api/unicorn', {prefixUrl: url}).text(),56 window.ky('api/unicorn', {prefixUrl: `${url}/`}).text(),57 ]), server.url);5859 t.deepEqual(results, ['rainbow', 'rainbow', 'rainbow', 'rainbow']);6061 await server.close();
34 unmodified lines
96 });9798 server.get('/test', (_request, response) => {99 response.writeHead(200, {104 'content-length': '4'100 'content-length': '4',101 });102103 response.write('me');104 setTimeout(() => {
40 unmodified lines
145 await addKyScriptToPage(page);146147 const error = await page.evaluate(async url => {148 const request = window.ky(`${url}/slow`, {timeout: 500}).text();153 return request.catch(error_ => {154 return {155 message: error_.toString(),156 request: {url: error_.request.url}157 };158 });149 return request.catch(error_ => ({150 message: error_.toString(),151 request: {url: error_.request.url},152 }));153 }, server.url);154155 if (typeof error !== 'object') {156 throw new TypeError('Expected to have an object error');
2 unmodified lines
159 t.is(error.message, 'TimeoutError: Request timed out');160 t.is(error.request.url, `${server.url}/slow`);161162 await server.close();169 }163 },164);165166test('onDownloadProgress works', withPage, async (t: ExecutionContext, page: Page) => {167 const server = await createEsmTestServer();168169 server.get('/', (_request, response) => {170 response.writeHead(200, {177 'content-length': '4'171 'content-length': '4',172 });173174 response.write('me');175 setTimeout(() => {
5 unmodified lines
181 await addKyScriptToPage(page);182183 const result = await page.evaluate(async url => {184 // `new TextDecoder('utf-8').decode` hangs up?191 const decodeUTF8 = (array: Uint8Array) => String.fromCharCode(...array);185 const decodeUtf8 = (array: Uint8Array) => String.fromCharCode(...array);186187 const data: any[] = [];188 const text = await window189 .ky(url, {190 onDownloadProgress: (progress, chunk) => {197 const stringifiedChunk = decodeUTF8(chunk);191 const stringifiedChunk = decodeUtf8(chunk);192 data.push([progress, stringifiedChunk]);199 }193 },194 })195 .text();196197 return {data, text};
1 unmodified line
199200 t.deepEqual(result.data, [201 [{percent: 0, transferredBytes: 0, totalBytes: 4}, ''],202 [{percent: 0.5, transferredBytes: 2, totalBytes: 4}, 'me'],209 [{percent: 1, transferredBytes: 4, totalBytes: 4}, 'ow']203 [{percent: 1, transferredBytes: 4, totalBytes: 4}, 'ow'],204 ]);205 t.is(result.text, 'meow');206207 await server.close();
65 unmodified lines
273 formData.append('file', new window.File(['bubblegum pie'], 'my-file'));274 return window.ky(url, {275 method: 'post',276 searchParams: 'foo=1',283 body: formData277 body: formData,278 });279 }, server.url);280281 await server.close();
40 unmodified lines
322 fieldname: 'file',323 filename: 'my-file',324 encoding: '7bit',325 mimetype: 'text/plain',332 fileContent: 'bubblegum pie'326 fileContent: 'bubblegum pie',327 });328 });329330 await page.goto(server.url);
3 unmodified lines
334 formData.append('file', new window.File(['bubblegum pie'], 'my-file', {type: 'text/plain'}));335 return window.ky(url, {336 method: 'post',337 searchParams: 'foo=1',344 body: formData338 body: formData,339 });340 }, server.url);341 await server.close();342});
18 unmodified lines
361 await addKyScriptToPage(page);362363 await page.evaluate(async url => {364 const request = new window.Request(url + '/test', {371 headers: {'content-type': 'text/css'}365 headers: {'content-type': 'text/css'},366 });367368 return window369 .ky(request, {376 searchParams: 'foo=1'370 searchParams: 'foo=1',371 })372 .text();373 }, server.url);374375 await server.close();382 }376 },377);378379test('retry with body', withPage, async (t: ExecutionContext, page: Page) => {380 t.plan(4);
13 unmodified lines
394 await page.goto(server.url);395 await addKyScriptToPage(page);396397 await t.throwsAsync(404 page.evaluate(async url => {405 return window.ky(url + '/test', {406 body: 'foo',407 method: 'PUT',408 retry: 2409 });410 }, server.url),411 {message: /HTTPError: Request failed with status code 502 Bad Gateway/}398 page.evaluate(async url => window.ky(url + '/test', {399 body: 'foo',400 method: 'PUT',401 retry: 2,402 }), server.url),403 {message: /HTTPError: Request failed with status code 502 Bad Gateway/},404 );405406 t.is(requestCount, 2);407
2 unmodified lines
modified:test/fetch.ts+8 added-8 removed
34 unmodified lines
35 t.is(await ky('/unicorn', {fetch: customFetch}).text(), '/unicorn');36 t.is(37 await ky('/unicorn', {38 fetch: customFetch,39 searchParams: {foo: 'bar'}39 searchParams: {foo: 'bar'},40 }).text(),41 '/unicorn?foo=bar'41 '/unicorn?foo=bar',42 );43 t.is(44 await ky('/unicorn#hash', {45 fetch: customFetch,46 searchParams: 'foo'46 searchParams: 'foo',47 }).text(),48 '/unicorn?foo#hash'48 '/unicorn?foo#hash',49 );50 t.is(51 await ky('/unicorn?old', {52 fetch: customFetch,53 searchParams: 'new'53 searchParams: 'new',54 }).text(),55 '/unicorn?new'55 '/unicorn?new',56 );57 t.is(58 await ky('/unicorn?old#hash', {59 fetch: customFetch,60 searchParams: 'new'60 searchParams: 'new',61 }).text(),62 '/unicorn?new#hash'62 '/unicorn?new#hash',63 );64 t.is(await ky('unicorn', {fetch: customFetch, prefixUrl: '/api/'}).text(), '/api/unicorn');65});
modified:test/headers.ts+39 added-38 removed
1import {Buffer} from 'node:buffer';2import type {IncomingHttpHeaders} from 'node:http';3import test from 'ava';4import type {RequestHandler} from 'express';5import FormData from 'form-data';4import type {IncomingHttpHeaders} from 'http';6import ky from '../source/index.js';7import {createHttpTestServer} from './helpers/create-http-test-server.js';89const echoHeaders: RequestHandler = (request, response) => {
50 unmodified lines
6061 const headers = await ky62 .get(server.url, {63 headers: {63 'accept-encoding': 'gzip'64 }64 'accept-encoding': 'gzip',65 },66 })67 .json<IncomingHttpHeaders>();68 t.is(headers['accept-encoding'], 'gzip');69});
4 unmodified lines
7475 const headers = await ky76 .get(server.url, {77 headers: {77 'X-Request-Id': 'value'78 }78 'X-Request-Id': 'value',79 },80 })81 .json<IncomingHttpHeaders>();8283 t.is(headers.accept, 'application/json');
11 unmodified lines
9596 headers = await ky97 .get(server.url, {98 headers: {98 accept: ''99 }99 accept: '',100 },101 })102 .json<IncomingHttpHeaders>();103104 t.is(headers.accept, 'application/json');
12 unmodified lines
117 server.get('/', echoHeaders);118119 const headers = await ky(server.url, {120 headers: {120 'ACCEPT-ENCODING': 'identity'121 }121 'ACCEPT-ENCODING': 'identity',122 },123 }).json<IncomingHttpHeaders>();124 t.is(headers['accept-encoding'], 'identity');125});126
3 unmodified lines
130131 const headers = await ky132 .post(server.url, {133 headers: {133 'content-length': '0'134 'content-length': '0',135 },135 body: 'sup'136 body: 'sup',137 })138 .json<IncomingHttpHeaders>();139140 t.is(headers['content-length'], '3');
16 unmodified lines
157 form.append('a', 'b');158 const headers = await ky159 .post(server.url, {160 headers: {160 'content-type': 'custom'161 'content-type': 'custom',162 },163 // @ts-expect-error FormData type mismatch163 body: form164 body: form,165 })166 .json<IncomingHttpHeaders>();167168 t.is(headers['content-type'], 'custom');
7 unmodified lines
176 form.append('a', 'b');177 const headers = await ky178 .post(server.url, {179 // @ts-expect-error FormData type mismatch179 body: form180 body: form,181 })182 .json<IncomingHttpHeaders>();183184 t.is(headers['content-type'], `multipart/form-data;boundary=${form.getBoundary()}`);
8 unmodified lines
193 const headers = await ky194 .post(server.url, {195 searchParams: 'foo=1',196 headers: {196 'content-type': 'custom'197 'content-type': 'custom',198 },199 // @ts-expect-error FormData type mismatch199 body: form200 body: form,201 })202 .json<IncomingHttpHeaders>();203204 t.is(headers['content-type'], 'custom');
8 unmodified lines
213 const headers = await ky214 .post(server.url, {215 searchParams: 'foo=1',216 // @ts-expect-error FormData type mismatch216 body: form217 body: form,218 })219 .json<IncomingHttpHeaders>();220221 t.is(headers['content-type'], `multipart/form-data;boundary=${form.getBoundary()}`);
17 unmodified lines
239240 const buffer = Buffer.from('unicorn');241 const headers = await ky242 .post(server.url, {242 body: buffer243 body: buffer,244 })245 .json<IncomingHttpHeaders>();246247 t.is(Number(headers['content-length']), buffer.length);
7 unmodified lines
255 const headers = await ky256 .get(server.url, {257 headers: {258 'user-agent': undefined,258 unicorn: 'unicorn'259 }259 unicorn: 'unicorn',260 },261 })262 .json<IncomingHttpHeaders>();263264 t.is(headers['user-agent'], 'undefined');
7 unmodified lines
272 const headers = await ky273 .get(server.url, {274 headers: {275 blah: undefined,275 rainbow: 'unicorn'276 }276 rainbow: 'unicorn',277 },278 })279 .json<IncomingHttpHeaders>();280281 t.false('blah' in headers);
34 unmodified lines
316317 const original = ky.create({318 headers: {319 rainbow: 'rainbow',319 unicorn: 'unicorn'320 }320 unicorn: 'unicorn',321 },322 });323324 const extended = original.extend({325 headers: {325 rainbow: undefined326 }326 rainbow: undefined,327 },328 });329330 const response = await extended(server.url).json<IncomingHttpHeaders>();331
9 unmodified lines
341342 const original = ky.create({343 headers: new Headers({344 rainbow: 'rainbow',344 unicorn: 'unicorn'345 })345 unicorn: 'unicorn',346 }),347 });348349 const extended = original.extend({350 // @ts-expect-error Headers does not support undefined values351 headers: new Headers({351 rainbow: undefined352 })352 rainbow: undefined,353 }),354 });355356 const response = await extended(server.url).json<IncomingHttpHeaders>();357
9 unmodified lines
367368 const original = ky.create({369 headers: new Headers({370 rainbow: 'rainbow',370 unicorn: 'unicorn'371 })371 unicorn: 'unicorn',372 }),373 });374375 const extended = original.extend({376 headers: {376 rainbow: undefined377 }377 rainbow: undefined,378 },379 });380381 const response = await extended(server.url).json<IncomingHttpHeaders>();382
9 unmodified lines
392393 const original = ky.create({394 headers: {395 rainbow: 'rainbow',395 unicorn: 'unicorn'396 }396 unicorn: 'unicorn',397 },398 });399400 const extended = original.extend({401 // @ts-expect-error Headers does not support undefined values402 headers: new Headers({402 rainbow: undefined403 })403 rainbow: undefined,404 }),405 });406407 const response = await extended(server.url).json<IncomingHttpHeaders>();408
5 unmodified lines
modified:test/hooks.ts+76 added-76 removed
9 unmodified lines
10 response.json(request.body);11 });1213 const json = {14 foo: true14 foo: true,15 };1617 const responseJson = await ky18 .post(server.url, {
4 unmodified lines
23 await delay(100);24 const bodyJson = JSON.parse(options.body as string);25 bodyJson.foo = false;26 return new Request(request, {body: JSON.stringify(bodyJson)});27 }28 ]29 }27 },28 ],29 },30 })31 .json<typeof json>();3233 t.false(responseJson.foo);
22 unmodified lines
56 response.json(request.body);57 });5859 const json = {60 foo: true60 foo: true,61 };6263 const responseJson = await ky64 .post(server.url, {
3 unmodified lines
68 (request, options) => {69 const bodyJson = JSON.parse(options.body as string);70 bodyJson.foo = false;71 return new Request(request, {body: JSON.stringify(bodyJson)});72 }73 ]74 }72 },73 ],74 },75 })76 .json<typeof json>();7778 t.false(responseJson.foo);
7 unmodified lines
86 response.json(request.body);87 });8889 const json = {90 foo: true90 foo: true,91 };9293 await t.notThrowsAsync(94 ky
3 unmodified lines
98 afterResponse: [99 async (_input, _options, response) => {100 t.is(response.status, 200);101 t.deepEqual(await response.json(), json);102 }103 ]104 }102 },103 ],104 },105 })106 .json()106 .json(),107 );108109 await server.close();110});
4 unmodified lines
115 response.status(500).send(request.body);116 });117118 const json = {119 foo: true119 foo: true,120 };121122 await t.throwsAsync(123 ky
3 unmodified lines
127 afterResponse: [128 async (_input, _options, response) => {129 t.is(response.status, 500);130 t.deepEqual(await response.json(), json);131 }132 ]133 }131 },132 ],133 },134 })135 .json()135 .json(),136 );137138 await server.close();139});
15 unmodified lines
155 hooks: {156 afterResponse: [157 () =>158 new Response(modifiedBody1, {159 status: modifiedStatus1159 status: modifiedStatus1,160 }),161 async (_input, _options, response) => {162 t.is(response.status, modifiedStatus1);163 t.is(await response.text(), modifiedBody1);164165 return new Response(modifiedBody2, {166 status: modifiedStatus2166 status: modifiedStatus2,167 });168 }169 ]170 }168 },169 ],170 },171 })172 .text();173174 t.is(responseBody, modifiedBody2);
17 unmodified lines
192 hooks: {193 afterResponse: [194 () => {195 throw expectError;196 }197 ]198 }196 },197 ],198 },199 })200 .text(),201 {202 is: expectError203 }202 is: expectError,203 },204 );205206 // Async hook function207 await t.throwsAsync(
2 unmodified lines
210 hooks: {211 afterResponse: [212 async () => {213 throw expectError;214 }215 ]216 }214 },215 ],216 },217 })218 .text(),219 {220 is: expectError221 }220 is: expectError,221 },222 );223224 await server.close();225});
11 unmodified lines
237 afterResponse: [238 (_input, _options, response) => {239 called = true;240 return response;241 }242 ]243 }241 },242 ],243 },244 })245 .json();246247 t.true(called);
13 unmodified lines
261 });262263 const json = {264 foo: true,265 token: 'invalid:token'265 token: 'invalid:token',266 };267268 t.deepEqual(269 await ky
7 unmodified lines
277 return ky(request, {278 ...options,279 json: {280 ...(options as Options).json as Record<string, unknown>,281 token: 'valid:token'282 }281 token: 'valid:token',282 },283 });284 }285286 return undefined;287 }288 ]289 }287 },288 ],289 },290 })291 .json(),292 {293 foo: true,294 token: 'valid:token'295 }294 token: 'valid:token',295 },296 );297298 await server.close();299});
16 unmodified lines
316 afterResponse: [317 async (_request, _options, response) => {318 t.true(response instanceof Response);319 t.deepEqual(await response.json(), {awesome: true});320 }321 ]322 }320 },321 ],322 },323 })324 .json();325326 t.deepEqual(json, {awesome: true});
14 unmodified lines
341 hooks: {342 beforeRetry: [343 ({options}) => {344 (options.headers as Headers | undefined)?.set('unicorn', fixture);345 }346 ]347 }345 },346 ],347 },348 })349 .text(),350 fixture350 fixture,351 );352353 await server.close();354});
19 unmodified lines
374 hooks: {375 beforeRetry: [376 ({request}) => {377 request.headers.set('unicorn', fixture);378 }379 ]380 }378 },379 ],380 },381 })382 .text(),383 fixture383 fixture,384 );385386 await server.close();387});
17 unmodified lines
405 beforeRetry: [406 ({error, retryCount}) => {407 t.true(error instanceof HTTPError);408 t.true(retryCount >= 1);409 }410 ]411 }409 },410 ],411 },412 });413414 await server.close();415});
27 unmodified lines
443 // @ts-expect-error444 t.is(error.response, undefined);445 t.is(retryCount, 1);446 t.is(requestCount, 1);447 }448 ]449 }447 },448 ],449 },450 })451 .text();452453 t.is(text, 'unicorn');
32 unmodified lines
486 t.true((error as HTTPError).response instanceof Response);487 t.deepEqual(await (error as HTTPError).response.json(), {awesome: true});488 t.is(retryCount, 1);489 t.is(requestCount, 1);490 }491 ]492 }490 },491 ],492 },493 })494 .json();495496 t.deepEqual(json, {awesome: true});
23 unmodified lines
520 t.truthy(error);521 t.is(retryCount, 1);522523 return ky.stop;524 }525 ]526 }524 },525 ],526 },527 });528529 t.is(requestCount, 1);530
22 unmodified lines
553 hooks: {554 beforeRetry: [555 () => {556 throw error;557 }558 ]559 }557 },558 ],559 },560 }),561 {message: errorString}561 {message: errorString},562 );563});564565test('catches beforeRetry promise rejections', async t => {
15 unmodified lines
581582 await t.throwsAsync(583 ky.get(server.url, {584 hooks: {585 beforeRetry: [async () => Promise.reject(error)]586 }585 beforeRetry: [async () => Promise.reject(error)],586 },587 }),588 {message: errorString}588 {message: errorString},589 );590});591592test('hooks beforeRequest returning Response skips HTTP Request', async t => {
1 unmodified line
594595 const response = await ky596 .get('server.url', {597 hooks: {598 beforeRequest: [() => new Response(expectedResponse, {status: 200, statusText: 'OK'})]599 }598 beforeRequest: [() => new Response(expectedResponse, {status: 200, statusText: 'OK'})],599 },600 })601 .text();602603 t.is(response, expectedResponse);
1 unmodified line
modified:test/http-error.ts+3 added-3 removed
17 unmodified lines
18 const error = new HTTPError(19 // This simulates the case where a browser Response object does20 // not define statusText, such as IE, Safari, etc.21 // See https://developer.mozilla.org/en-US/docs/Web/API/Response/statusText#Browser_compatibility22 createFakeResponse({statusText: undefined, status})22 createFakeResponse({statusText: undefined, status}),23 );2425 t.is(error.message, 'Request failed with status code 500');26});
2 unmodified lines
29 // @ts-expect-error missing Request30 const error = new HTTPError(31 // This simulates a catastrophic case where some unexpected32 // response object was sent to HTTPError.33 createFakeResponse({statusText: undefined, status: undefined})33 createFakeResponse({statusText: undefined, status: undefined}),34 );3536 t.is(error.message, 'Request failed with an unknown error');37});
1 unmodified line
39test('HTTPError handles a response.status of 0', t => {40 // @ts-expect-error missing Request41 const error = new HTTPError(42 // Apparently, it's possible to get a response status of 0.43 createFakeResponse({statusText: undefined, status: 0})43 createFakeResponse({statusText: undefined, status: 0}),44 );4546 t.is(error.message, 'Request failed with status code 0');47});
modified:test/main.ts+53 added-52 removed
1import {Buffer} from 'node:buffer';2import test from 'ava';3import delay from 'delay';4import ky, {TimeoutError} from '../source/index.js';5import {createHttpTestServer} from './helpers/create-http-test-server.js';
90 unmodified lines
96 response.json(request.body);97 });9899 const json = {99 foo: true100 foo: true,101 };102103 const responseJson = await ky.post(server.url, {json}).json();104
7 unmodified lines
112 () => {113 void ky.get('https://example.com', {body: 'foobar'});114 },115 {115 message: 'Request with GET/HEAD method cannot have body'116 }116 message: 'Request with GET/HEAD method cannot have body',117 },118 );119120 t.throws(121 () => {122 void ky.head('https://example.com', {body: 'foobar'});123 },124 {124 message: 'Request with GET/HEAD method cannot have body'125 }125 message: 'Request with GET/HEAD method cannot have body',126 },127 );128});129130test('cannot use `json` option with GET or HEAD method', t => {
1 unmodified line
132 () => {133 void ky.get('https://example.com', {json: {}});134 },135 {135 message: 'Request with GET/HEAD method cannot have body'136 }136 message: 'Request with GET/HEAD method cannot have body',137 },138 );139140 t.throws(141 () => {142 void ky.head('https://example.com', {json: {}});143 },144 {144 message: 'Request with GET/HEAD method cannot have body'145 }145 message: 'Request with GET/HEAD method cannot have body',146 },147 );148});149150test('`json` option overrides the `body` option', async t => {
5 unmodified lines
156 response.json(request.body);157 });158159 const json = {159 foo: 'bar'160 foo: 'bar',161 };162163 const responseJson = await ky164 .post(server.url, {165 body: 'hello',165 json166 json,167 })168 .json();169170 t.deepEqual(responseJson, json);
9 unmodified lines
180181 t.is(182 await ky(server.url, {183 headers: {183 unicorn: fixture184 }184 unicorn: fixture,185 },186 }).text(),186 fixture187 fixture,188 );189190 await server.close();191});
8 unmodified lines
200 response.json(request.body);201 });202203 const json = {203 foo: true204 foo: true,205 };206207 const responseJson = await ky208 .post(server.url, {209 headers: new Headers({unicorn: 'rainbow'}),209 json210 json,211 })212 .json();213214 t.deepEqual(responseJson, json);
10 unmodified lines
225 response.json({});226 });227228 const responseJson = await ky(server.url, {228 headers: {accept: 'foo/bar'}229 headers: {accept: 'foo/bar'},230 }).json();231232 t.deepEqual(responseJson, {});233
9 unmodified lines
243 response.status(200).end();244 });245246 await t.throwsAsync(ky(server.url).json(), {246 message: /Unexpected end of JSON input/247 message: /Unexpected end of JSON input/,248 });249250 await server.close();251});
25 unmodified lines
277 response.end(fixture);278 });279280 await t.throwsAsync(ky(server.url, {timeout: 1000}).text(), {280 instanceOf: TimeoutError281 instanceOf: TimeoutError,282 });283284 t.is(requestCount, 1);285
27 unmodified lines
313 await delay(1000);314 response.end(fixture);315 });316316 await t.throwsAsync(ky(server.url, {timeout: 21474836470}).text(), {317 await t.throwsAsync(ky(server.url, {timeout: 21_474_836_470}).text(), {318 instanceOf: RangeError,318 message: 'The `timeout` option cannot be greater than 2147483647'319 message: 'The `timeout` option cannot be greater than 2147483647',320 });321322 t.is(requestCount, 0);323
27 unmodified lines
351352 const arrayParameters = [353 ['cats', 'meow'],354 ['dogs', 'true'],354 ['opossums', 'false']355 ['opossums', 'false'],356 ];357 const objectParameters = {358 cats: 'meow',359 dogs: 'true',359 opossums: 'false'360 opossums: 'false',361 };362 const searchParameters = new URLSearchParams(arrayParameters);363 const stringParameters = '?cats=meow&dogs=true&opossums=false';364 const customStringParameters = '?cats&dogs[0]=true&dogs[1]=false';
40 unmodified lines
405 });406407 await t.throwsAsync(408 ky(server.url, {throwHttpErrors: false, timeout: 500}).text(),408 {instanceOf: TimeoutError}409 {instanceOf: TimeoutError},410 );411412 t.is(requestCount, 1);413
8 unmodified lines
422 });423424 const extended = ky.create({425 headers: {425 rainbow: 'rainbow'426 }426 rainbow: 'rainbow',427 },428 });429430 t.is(431 await extended(server.url, {432 headers: {432 unicorn: 'unicorn'433 }433 unicorn: 'unicorn',434 },435 }).text(),435 'unicorn - rainbow'436 'unicorn - rainbow',437 );438439 t.true((await extended.head(server.url)).ok);440
11 unmodified lines
452 ky.create(value);453 },454 {455 instanceOf: TypeError,455 message: 'The `options` argument must be an object'456 }456 message: 'The `options` argument must be an object',457 },458 );459 }460});461
10 unmodified lines
472 hooks: {473 beforeRequest: [474 () => {475 isOriginBeforeRequestTrigged = true;475 }476 ]477 }476 },477 ],478 },479 });480481 await extended(server.url, {482 hooks: {483 beforeRequest: [484 () => {485 isExtendBeforeRequestTrigged = true;485 }486 ]487 }486 },487 ],488 },489 });490491 t.is(isOriginBeforeRequestTrigged, true);492 t.is(isExtendBeforeRequestTrigged, true);
28 unmodified lines
521 hooks: {522 beforeRequest: [523 () => {524 isOriginBeforeRequestTrigged = true;524 }525 ]526 }525 },526 ],527 },528 })529 .extend({530 hooks: {531 beforeRequest: [532 () => {533 isExtendBeforeRequestTrigged = true;533 }534 ]535 }534 },535 ],536 },537 });538539 await extended(server.url);540
36 unmodified lines
577 // @ts-expect-error578 void ky.get(0);579 },580 {580 message: '`input` must be a string, URL, or Request'581 }581 message: '`input` must be a string, URL, or Request',582 },583 );584});585586test('options override Request instance method', async t => {
16 unmodified lines
603 const expectedBody = JSON.stringify({test: false});604605 const inputRequest = new Request(server.url, {606 method: 'POST',606 body: requestBody607 body: requestBody,608 });609610 server.post('/', (request, response) => {611 const body: Buffer[] = [];
40 unmodified lines
652653 const response = await ky.get(server.url, {654 parseJson: text => ({655 ...JSON.parse(text),655 extra: 'extraValue'656 })656 extra: 'extraValue',657 }),658 });659 const responseJson = await response.json();660661 t.deepEqual(responseJson, {662 ...json,662 extra: 'extraValue'663 extra: 'extraValue',664 });665666 await server.close();667});
9 unmodified lines
677 const responseJson = await ky678 .get(server.url, {679 parseJson: text => ({680 ...JSON.parse(text),680 extra: 'extraValue'681 })681 extra: 'extraValue',682 }),683 })684 .json();685686 t.deepEqual(responseJson, {687 ...json,687 extra: 'extraValue'688 extra: 'extraValue',689 });690691 await server.close();692});
modified:test/methods.ts+8 added-8 removed
13 unmodified lines
14 hooks: {15 beforeRequest: [16 (_input, options) => {17 t.is(options.method, 'GET');18 }19 ]20 }21 })18 },19 ],20 },21 }),22 );2324 await server.close();25});
10 unmodified lines
36 hooks: {37 beforeRequest: [38 (_input, options) => {39 t.is(options.method, 'report');40 }41 ]42 }43 })40 },41 ],42 },43 }),44 );4546 await server.close();47});
12 unmodified lines
modified:test/prefix-url.ts+3 added-3 removed
12 unmodified lines
1314 t.is(15 // @ts-expect-error {prefixUrl: boolean} isn't officially supported16 await ky(`${server.url}/api/unicorn`, {prefixUrl: false}).text(),17 'rainbow'17 'rainbow',18 );19 t.is(await ky(`${server.url}/api/unicorn`, {prefixUrl: ''}).text(), 'rainbow');20 t.is(await ky(new URL(`${server.url}/api/unicorn`), {prefixUrl: ''}).text(), 'rainbow');21 t.is(await ky('api/unicorn', {prefixUrl: server.url}).text(), 'rainbow');
9 unmodified lines
31 () => {32 void ky('/unicorn', {prefixUrl: `${server.url}/api`});33 },34 {35 message: '`input` must not begin with a slash when using `prefixUrl`'36 }35 message: '`input` must not begin with a slash when using `prefixUrl`',36 },37 );3839 await server.close();40});
modified:test/retry.ts+50 added-50 removed
15 unmodified lines
1617 if (requestCount === defaultRetryCount) {18 response.end(fixture);19 } else {20 response.status(99999).end();20 response.status(99_999).end();21 }22 });2324 t.is(await ky(server.url).text(), fixture);
53 unmodified lines
78 }79 });8081 await t.throwsAsync(ky.post(server.url).text(), {82 message: /Internal Server Error/82 message: /Internal Server Error/,83 });8485 await server.close();86});
8 unmodified lines
95 if (requestCount === defaultRetryCount) {96 response.end((Date.now() - lastTried413access).toString());97 } else {98 response.writeHead(413, {99 'Retry-After': retryAfterOn41399 'Retry-After': retryAfterOn413,100 });101 response.end('');102 }103 });
15 unmodified lines
119 } else {120 // @NOTE we need to round up to the next second due to http-date resolution121 const date = new Date(Date.now() + ((retryAfterOn413 + 1) * 1000)).toUTCString();122 response.writeHead(413, {123 'Retry-After': date123 'Retry-After': date,124 });125 response.end('');126 }127 });
33 unmodified lines
161162 await t.throwsAsync(163 ky(server.url, {164 retry: {165 limit: 3166 }165 limit: 3,166 },167 }).text(),168 {169 message: /Request Timeout/170 }169 message: /Request Timeout/,170 },171 );172 t.is(requestCount, 3);173174 await server.close();
17 unmodified lines
192 ky(server.url, {193 method: 'post',194 retry: {195 limit: 3,196 methods: ['get']197 }196 methods: ['get'],197 },198 }).text(),199 {200 message: /Request Timeout/201 }200 message: /Request Timeout/,201 },202 );203 t.is(requestCount, 1);204205 requestCount = 0;206 await t.throwsAsync(207 ky(server.url, {208 retry: {209 limit: 3,210 methods: ['get']211 }210 methods: ['get'],211 },212 }).text(),213 {214 message: /Request Timeout/215 }214 message: /Request Timeout/,215 },216 );217 t.is(requestCount, 3);218219 await server.close();
6 unmodified lines
226 server.get('/', async (_request, response) => {227 requestCount++;228229 response.writeHead(413, {230 'Retry-After': 1230 'Retry-After': 1,231 });232233 response.end('');234 });
1 unmodified line
236 await t.throwsAsync(237 ky(server.url, {238 retry: {239 limit: 5,240 maxRetryAfter: 100241 }240 maxRetryAfter: 100,241 },242 }).text(),243 {244 message: /Payload Too Large/245 }244 message: /Payload Too Large/,245 },246 );247 t.is(requestCount, 1);248249 requestCount = 0;250 await t.throwsAsync(251 ky(server.url, {252 retry: {253 limit: 5,254 maxRetryAfter: 2000255 }254 maxRetryAfter: 2000,255 },256 }).text(),257 {258 message: /Payload Too Large/259 }258 message: /Payload Too Large/,259 },260 );261 t.is(requestCount, 5);262263 await server.close();
8 unmodified lines
272 response.sendStatus(408);273 });274275 await t.throwsAsync(ky(server.url, {retry: 5}).text(), {276 message: /Request Timeout/276 message: /Request Timeout/,277 });278 t.is(requestCount, 5);279280 await server.close();
13 unmodified lines
294 ky(server.url, {295 retry: {296 limit: 10,297 statusCodes: [],298 methods: []299 }298 methods: [],299 },300 }).text(),301 {302 message: /Payload Too Large/303 }302 message: /Payload Too Large/,303 },304 );305306 t.is(requestCount, 1);307
12 unmodified lines
320 await t.throwsAsync(321 ky(server.url, {322 retry: {323 limit: 10,324 methods: []325 }324 methods: [],325 },326 }).text(),327 {328 message: /Payload Too Large/329 }328 message: /Payload Too Large/,329 },330 );331332 t.is(requestCount, 1);333
12 unmodified lines
346 await t.throwsAsync(347 ky(server.url, {348 retry: {349 limit: 4,350 methods: ['get']351 }350 methods: ['get'],351 },352 }).text(),353 {354 message: /Request Timeout/355 }354 message: /Request Timeout/,355 },356 );357358 t.is(requestCount, 4);359
12 unmodified lines
372 await t.throwsAsync(373 ky(server.url, {374 retry: {375 limit: 4,376 statusCodes: [408]377 }376 statusCodes: [408],377 },378 }).text(),379 {380 message: /Request Timeout/381 }380 message: /Request Timeout/,381 },382 );383384 t.is(requestCount, 4);385
11 unmodified lines
397398 await t.throwsAsync(399 ky(server.url, {400 retry: {401 limit: 0402 }401 limit: 0,402 },403 }).text(),404 {405 message: /Request Timeout/406 }405 message: /Request Timeout/,406 },407 );408409 t.is(requestCount, 1);410
6 unmodified lines
417 t.throws(() => {418 void ky(server.url, {419 retry: {420 // @ts-expect-error421 methods: 'get'422 }421 methods: 'get',422 },423 });424 });425426 await server.close();
5 unmodified lines
432 t.throws(() => {433 void ky(server.url, {434 retry: {435 // @ts-expect-error436 statusCodes: 403437 }436 statusCodes: 403,437 },438 });439 });440441 await server.close();
1 unmodified line
modified:package.json+16 added-12 removed
48 unmodified lines
49 "axios",50 "node-fetch"51 ],52 "devDependencies": {53 "@sindresorhus/tsconfig": "^1.0.2",53 "@sindresorhus/tsconfig": "^2.0.0",54 "@type-challenges/utils": "^0.1.1",55 "@types/body-parser": "^1.19.0",56 "@types/busboy": "^0.2.3",57 "@types/express": "^4.17.12",55 "@types/body-parser": "^1.19.1",56 "@types/busboy": "^0.2.4",57 "@types/express": "^4.17.13",58 "@types/node-fetch": "^2.5.10",59 "@types/pify": "^5.0.0",59 "@types/pify": "^5.0.1",60 "abort-controller": "^3.0.0",61 "ava": "^4.0.0-alpha.2",62 "body-parser": "^1.19.0",63 "busboy": "^0.3.1",64 "del-cli": "^3.0.1",64 "del-cli": "^4.0.1",65 "delay": "^5.0.0",66 "express": "^4.17.1",67 "form-data": "^4.0.0",68 "node-fetch": "^2.6.1",69 "pify": "^5.0.0",70 "playwright-chromium": "^1.11.1",70 "playwright-chromium": "^1.15.2",71 "raw-body": "^2.4.1",72 "ts-node": "^10.0.0",73 "typescript": "^4.4.3",74 "xo": "^0.39.0"72 "ts-node": "^10.3.0",73 "typescript": "^4.4.4",74 "xo": "^0.45.0"75 },76 "sideEffects": false,77 "xo": {78 "envs": [
3 unmodified lines
82 "globalThis"83 ],84 "rules": {85 "unicorn/filename-case": "off",86 "@typescript-eslint/no-non-null-assertion": "off",87 "@typescript-eslint/no-unsafe-argument": "off"86 "@typescript-eslint/ban-ts-comment": "off",87 "@typescript-eslint/no-unsafe-argument": "off",88 "@typescript-eslint/no-unsafe-assignment": "off",89 "@typescript-eslint/no-unsafe-return": "off",90 "@typescript-eslint/no-unsafe-call": "off",91 "@typescript-eslint/naming-convention": "off"92 }93 },94 "ava": {95 "require": [
23 unmodified lines