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
Provenance
- Commit
2049aff- Tree
51a0dd5- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
Sindre Sorhus <sindresorhus@gmail.com>- Parent
ff1563a
23 files changed+426 added−424 removed
modified:source/core/constants.ts+4 added-4 removed
12234567891011121213141516171819202021222324242526import type {Expect, Equal} from '@type-challenges/utils';import {HTTPMethod} from '../types/options.js';import {HttpMethod} from '../types/options.js';
export const supportsAbortController = typeof globalThis.AbortController === 'function';export const supportsStreams = typeof globalThis.ReadableStream === 'function';export const supportsFormData = typeof globalThis.FormData === 'function';
export const requestMethods = ['get', 'post', 'put', 'patch', 'head', 'delete'] as const;
const validate = <T extends Array<true>>() => undefined as unknown as T;validate<[ Expect<Equal<typeof requestMethods[number], HTTPMethod>> Expect<Equal<typeof requestMethods[number], HttpMethod>>,]>();
export const responseTypes = { json: 'application/json', text: 'text/*', formData: 'multipart/form-data', arrayBuffer: '*/*', blob: '*/*' blob: '*/*',} as const;
// The maximum value of a 32bit int (see issue #117)export const maxSafeTimeout = 2147483647;export const maxSafeTimeout = 2_147_483_647;
export const stop = Symbol('stop');modified:source/core/Ky.ts+89 added-91 removed
8 unmodified lines9 import {ObjectEntries} from '../utils/types.js';10 import {maxSafeTimeout, responseTypes, stop, supportsAbortController, supportsFormData, supportsStreams} from './constants.js';11 12 export 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);16+17+ const fn = async (): Promise<Response> => {18+ if (ky._options.timeout > maxSafeTimeout) {19+ throw new RangeError(`The \`timeout\` option cannot be greater than ${maxSafeTimeout}`);20+ }21+22+ // Delay the fetch so that body method shortcuts can set the Accept header23+ await Promise.resolve();24+ let response = await ky._fetch();25+26+ 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+ );33+34+ if (modifiedResponse instanceof globalThis.Response) {35+ response = modifiedResponse;36+ }37+ }38+39+ ky._decorateResponse(response);40+41+ if (!response.ok && ky._options.throwHttpErrors) {42+ throw new HTTPError(response, ky.request, (ky._options as unknown) as NormalizedOptions);43+ }44+45+ // 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+ }51+52+ if (!supportsStreams) {53+ throw new Error('Streams are not supported in your environment. `ReadableStream` is missing.');54+ }55+56+ return ky._stream(response.clone(), ky._options.onDownloadProgress);57+ }58+59+ return response;60+ };61+62+ const isRetriableMethod = ky._options.retry.methods.includes(ky.request.method.toLowerCase());63+ const result = (isRetriableMethod ? ky._retry(fn) : fn()) as ResponsePromise;64+65+ 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);69+70+ const response = (await result).clone();71+72+ if (type === 'json') {73+ if (response.status === 204) {74+ return '';75+ }76+77+ if (options.parseJson) {78+ return options.parseJson(await response.text());79+ }80+ }81+82+ return response[type]();83+ };84+ }85+86+ return result;87+ }88+89 public request: Request;90 protected abortController?: AbortController;91 protected _retryCount = 0;92 protected _input: Input;10 unmodified lines103 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 };119 120 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 lines147 this.request = new globalThis.Request(this._input as RequestInfo, this._options as RequestInit);148 149 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);157 158 // 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 lines172 this.request = new globalThis.Request(this.request, {body: this._options.body});173 }174 }175 100- // eslint-disable-next-line @typescript-eslint/promise-function-async101- static create(input: Input, options: Options): ResponsePromise {102- const ky = new Ky(input, options);103-104- const fn = async (): Promise<Response> => {105- if (ky._options.timeout > maxSafeTimeout) {106- throw new RangeError(`The \`timeout\` option cannot be greater than ${maxSafeTimeout}`);107- }108-109- // Delay the fetch so that body method shortcuts can set the Accept header110- await Promise.resolve();111- let response = await ky._fetch();112-113- 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- );120-121- if (modifiedResponse instanceof globalThis.Response) {122- response = modifiedResponse;123- }124- }125-126- ky._decorateResponse(response);127-128- if (!response.ok && ky._options.throwHttpErrors) {129- throw new HTTPError(response, ky.request, (ky._options as unknown) as NormalizedOptions);130- }131-132- // 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- }138-139- if (!supportsStreams) {140- throw new Error('Streams are not supported in your environment. `ReadableStream` is missing.');141- }142-143- return ky._stream(response.clone(), ky._options.onDownloadProgress);144- }145-146- return response;147- };148-149- const isRetriableMethod = ky._options.retry.methods.includes(ky.request.method.toLowerCase());150- const result = (isRetriableMethod ? ky._retry(fn) : fn()) as ResponsePromise;151-152- 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);156-157- const response = (await result).clone();158-159- if (type === 'json') {160- if (response.status === 204) {161- return '';162- }163-164- if (options.parseJson) {165- return options.parseJson(await response.text());166- }167- }168-169- return response[type]();170- };171- }172-173- return result;174- }175-176 protected _calculateRetryDelay(error: unknown) {177 this._retryCount++;178 179 if (this._retryCount < this._options.retry.limit && !(error instanceof TimeoutError)) {31 unmodified lines211 }212 213 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 }217 218 return response;219 }12 unmodified lines232 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 });238 239 // If `stop` is returned from the hook, the retry process is stopped240 if (hookResult === stop) {61 unmodified lines302 await read();303 }304 305 await read();308- }309- })306+ },307+ }),308 );309 }310 }modified:source/errors/HTTPError.ts+1 added
123456715 unmodified linesimport type {NormalizedOptions} from '../types/options.js';
// eslint-lint-disable-next-line @typescript-eslint/naming-conventionexport class HTTPError extends Error { public response: Response; public request: Request; public options: NormalizedOptions;15 unmodified linesmodified:source/types/ky.ts+3 added-3 removed
123455678963 unmodified lines737475767777787980818283848586868788899030 unmodified linesimport {stop} from '../core/constants.js';import type {Input, Options} from './options.js';import type {ResponsePromise} from './response.js';
export interface ky {export interface KyInstance { /** Fetch the given `url`.
@param url - `Request` object, `URL` object, or URL string.63 unmodified lines Create a new Ky instance with complete new defaults.
@returns A new Ky instance. */ create: (defaultOptions: Options) => ky; create: (defaultOptions: Options) => KyInstance;
/** 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) => ky; extend: (defaultOptions: Options) => KyInstance;
/** A `Symbol` that can be returned by a `beforeRetry` hook to stop the retry. This will also short circuit the remaining `beforeRetry` hooks.
30 unmodified linesmodified:source/types/options.ts+2 added-2 removed
6 unmodified lines7 8 // eslint-disable-next-line unicorn/prevent-abbreviations9 export type SearchParamsOption = SearchParamsInit | Record<string, string | number | boolean> | Array<Array<string | number | boolean>>;10 11-export type HTTPMethod = 'get' | 'post' | 'put' | 'patch' | 'head' | 'delete';11+export type HttpMethod = 'get' | 'post' | 'put' | 'patch' | 'head' | 'delete';12 13 export type Input = string | URL | Request;14 15 export interface DownloadProgress {16 unmodified lines32 HTTP method used to make the request.33 34 Internally, the standard methods (`GET`, `POST`, `PUT`, `PATCH`, `HEAD` and `DELETE`) are uppercased in order to avoid server errors due to case sensitivity.35 */36- method?: LiteralUnion<HTTPMethod, string>;36+ method?: LiteralUnion<HttpMethod, string>;37 38 /**39 HTTP headers used to make the request.40 208 unmodified linesmodified:source/types/response.ts+1 added-1 removed
29 unmodified lines30 31 const result = await ky(…).json<Result>();32 ```33 */34- json: <T>() => Promise<T>;34+ json: <T = unknown>() => Promise<T>;35 36 text: () => Promise<string>;37 }modified:source/utils/merge.ts+1 added
25 unmodified lines26 27 return result;28 };29 30+// TODO: Make this strongly-typed (no `any`).31 export const deepMerge = <T>(...sources: Array<Partial<T> | undefined>): T => {32 let returnValue: any = {};33 let headers = {};34 25 unmodified linesmodified:source/utils/normalize.ts+5 added-5 removed
1 import {requestMethods} from '../core/constants.js';2-import type {HTTPMethod} from '../types/options.js';2+import type {HttpMethod} from '../types/options.js';3 import type {RetryOptions} from '../types/retry.js';4 5 export const normalizeRequestMethod = (input: string): string =>6- requestMethods.includes(input as HTTPMethod) ? input.toUpperCase() : input;6+ requestMethods.includes(input as HttpMethod) ? input.toUpperCase() : input;7 8 const retryMethods = ['get', 'put', 'head', 'delete', 'options', 'trace'];9 10 const retryStatusCodes = [408, 413, 429, 500, 502, 503, 504];4 unmodified lines15 limit: 2,16 methods: retryMethods,17 statusCodes: retryStatusCodes,18 afterStatusCodes: retryAfterStatusCodes,19- maxRetryAfter: Number.POSITIVE_INFINITY19+ maxRetryAfter: Number.POSITIVE_INFINITY,20 };21 22 export const normalizeRetryOptions = (retry: number | RetryOptions = {}): Required<RetryOptions> => {23 if (typeof retry === 'number') {24 return {25 ...defaultRetryOptions,26- limit: retry26+ limit: retry,27 };28 }29 30 if (retry.methods && !Array.isArray(retry.methods)) {6 unmodified lines37 38 return {39 ...defaultRetryOptions,40 ...retry,41- afterStatusCodes: retryAfterStatusCodes41+ afterStatusCodes: retryAfterStatusCodes,42 };43 };modified:source/utils/time.ts+3 added-3 removed
7 unmodified lines8 // `Promise.race()` workaround (#91)9 export 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 lines25 .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 linesmodified:source/index.ts+6 added-6 removed
1 /*! MIT License © Sindre Sorhus */2 3 import {Ky} from './core/Ky.js';4 import {requestMethods, stop} from './core/constants.js';5-import type {ky as KyInterface} from './types/ky.js';5+import type {KyInstance} from './types/ky.js';6 import type {Input, Options} from './types/options.js';7 import {validateAndMerge} from './utils/merge.js';8 import {Mutable} from './utils/types.js';9 10-const createInstance = (defaults?: Partial<Options>): KyInterface => {10+const 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));13 14 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 lines19 ky.create = (newDefaults?: Partial<Options>) => createInstance(validateAndMerge(newDefaults));20 ky.extend = (newDefaults?: Partial<Options>) => createInstance(validateAndMerge(defaults, newDefaults));21 ky.stop = stop;22 23- return ky as KyInterface;23+ return ky as KyInstance;24 };25 26 const ky = createInstance();27 3 unmodified lines31 Options,32 NormalizedOptions,33 RetryOptions,34 SearchParamsOption,35- DownloadProgress35+ DownloadProgress,36 } from './types/options.js';37 38 export {39 Hooks,40 BeforeRequestHook,41 BeforeRetryHook,42- AfterResponseHook42+ AfterResponseHook,43 } from './types/hooks.js';44 45 export {ResponsePromise} from './types/response.js';46 export {HTTPError} from './errors/HTTPError.js';1 unmodified linemodified:test/helpers/create-http-test-server.ts+10 added-10 removed
1-import http from 'http';2-import net from 'net';1+import http from 'node:http';2+import net from 'node:net';3 import express from 'express';4 import pify from 'pify';5 import bodyParser from 'body-parser';6 19 unmodified lines26 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 }56 57 await pify(server.http.listen.bind(server.http))();9 unmodified linesmodified:test/helpers/with-page.ts+2 added-1 removed
1+import process from 'node:process';2 // eslint-disable-next-line ava/use-test3 import type {ExecutionContext, UntitledMacro} from 'ava';4 import {chromium, Page} from 'playwright-chromium';5 2 unmodified lines8 const PWDEBUG = Boolean(process.env['PWDEBUG']);9 10 export 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 linesmodified:test/_require.ts+8 added-5 removed
1+/* eslint-disable @typescript-eslint/prefer-ts-expect-error */2 import fetch, {Headers, Request, Response} from 'node-fetch';3 import AbortController from 'abort-controller';4 import FormData from 'form-data';5 6+// We use `@ts-ignore` as there are some inconsistency error when using `@ts-expect-error`.7+8 globalThis.AbortController = AbortController;6-// @ts-expect-error9+// @ts-ignore10 globalThis.fetch = fetch;8-// @ts-expect-error11+// @ts-ignore12 globalThis.Headers = Headers;10-// @ts-expect-error13+// @ts-ignore14 globalThis.Request = Request;12-// @ts-expect-error15+// @ts-ignore16 globalThis.Response = Response;14-// @ts-expect-error17+// @ts-ignore18 globalThis.FormData = FormData;modified:test/browser.ts+35 added-43 removed
1 import test, {ExecutionContext} from 'ava';2 import Busboy from 'busboy';3 import express from 'express';4 import {Page} from 'playwright-chromium';5-import type {ky as kyInterface} from '../source/types/ky.js';5+import ky from '../source/index.js';6 import {createHttpTestServer, HttpServerOptions} from './helpers/create-http-test-server.js';7 import {parseRawBody} from './helpers/parse-body.js';8 import {withPage} from './helpers/with-page.js';9 10 declare global {11 interface Window {12- ky: kyInterface;12+ ky: typeof ky;13 }14 }15 16 const DIST_DIR = new URL('../distribution', import.meta.url).toString();7 unmodified lines24 type: 'module',25 content: `26 import ky from '/distribution/index.js';27 globalThis.ky = ky;28- `28+ `,29 };30 const addKyScriptToPage = async (page: Page) => {31 await page.addScriptTag(KY_SCRIPT);32 await page.waitForFunction(() => typeof window.ky === 'function');10 unmodified lines43 await page.goto(server.url);44 await addKyScriptToPage(page);45 46 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 );50 53- 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);58 59 t.deepEqual(results, ['rainbow', 'rainbow', 'rainbow', 'rainbow']);60 61 await server.close();34 unmodified lines96 });97 98 server.get('/test', (_request, response) => {99 response.writeHead(200, {104- 'content-length': '4'100+ 'content-length': '4',101 });102 103 response.write('me');104 setTimeout(() => {40 unmodified lines145 await addKyScriptToPage(page);146 147 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);154 155 if (typeof error !== 'object') {156 throw new TypeError('Expected to have an object error');2 unmodified lines159 t.is(error.message, 'TimeoutError: Request timed out');160 t.is(error.request.url, `${server.url}/slow`);161 162 await server.close();169- }163+ },164 );165 166 test('onDownloadProgress works', withPage, async (t: ExecutionContext, page: Page) => {167 const server = await createEsmTestServer();168 169 server.get('/', (_request, response) => {170 response.writeHead(200, {177- 'content-length': '4'171+ 'content-length': '4',172 });173 174 response.write('me');175 setTimeout(() => {5 unmodified lines181 await addKyScriptToPage(page);182 183 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);186 187 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();196 197 return {data, text};1 unmodified line199 200 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');206 207 await server.close();65 unmodified lines273 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);280 281 await server.close();40 unmodified lines322 fieldname: 'file',323 filename: 'my-file',324 encoding: '7bit',325 mimetype: 'text/plain',332- fileContent: 'bubblegum pie'326+ fileContent: 'bubblegum pie',327 });328 });329 330 await page.goto(server.url);3 unmodified lines334 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 lines361 await addKyScriptToPage(page);362 363 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 });367 368 return window369 .ky(request, {376- searchParams: 'foo=1'370+ searchParams: 'foo=1',371 })372 .text();373 }, server.url);374 375 await server.close();382- }376+ },377 );378 379 test('retry with body', withPage, async (t: ExecutionContext, page: Page) => {380 t.plan(4);13 unmodified lines394 await page.goto(server.url);395 await addKyScriptToPage(page);396 397 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 );405 406 t.is(requestCount, 2);407 2 unmodified linesmodified:test/fetch.ts+8 added-8 removed
34 unmodified lines35 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
1+import {Buffer} from 'node:buffer';2+import type {IncomingHttpHeaders} from 'node:http';3 import test from 'ava';4 import type {RequestHandler} from 'express';5 import FormData from 'form-data';4-import type {IncomingHttpHeaders} from 'http';6 import ky from '../source/index.js';7 import {createHttpTestServer} from './helpers/create-http-test-server.js';8 9 const echoHeaders: RequestHandler = (request, response) => {50 unmodified lines60 61 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 lines74 75 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>();82 83 t.is(headers.accept, 'application/json');11 unmodified lines95 96 headers = await ky97 .get(server.url, {98 headers: {98- accept: ''99- }99+ accept: '',100+ },101 })102 .json<IncomingHttpHeaders>();103 104 t.is(headers.accept, 'application/json');12 unmodified lines117 server.get('/', echoHeaders);118 119 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 lines130 131 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>();139 140 t.is(headers['content-length'], '3');16 unmodified lines157 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>();167 168 t.is(headers['content-type'], 'custom');7 unmodified lines176 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>();183 184 t.is(headers['content-type'], `multipart/form-data;boundary=${form.getBoundary()}`);8 unmodified lines193 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>();203 204 t.is(headers['content-type'], 'custom');8 unmodified lines213 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>();220 221 t.is(headers['content-type'], `multipart/form-data;boundary=${form.getBoundary()}`);17 unmodified lines239 240 const buffer = Buffer.from('unicorn');241 const headers = await ky242 .post(server.url, {242- body: buffer243+ body: buffer,244 })245 .json<IncomingHttpHeaders>();246 247 t.is(Number(headers['content-length']), buffer.length);7 unmodified lines255 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>();263 264 t.is(headers['user-agent'], 'undefined');7 unmodified lines272 const headers = await ky273 .get(server.url, {274 headers: {275 blah: undefined,275- rainbow: 'unicorn'276- }276+ rainbow: 'unicorn',277+ },278 })279 .json<IncomingHttpHeaders>();280 281 t.false('blah' in headers);34 unmodified lines316 317 const original = ky.create({318 headers: {319 rainbow: 'rainbow',319- unicorn: 'unicorn'320- }320+ unicorn: 'unicorn',321+ },322 });323 324 const extended = original.extend({325 headers: {325- rainbow: undefined326- }326+ rainbow: undefined,327+ },328 });329 330 const response = await extended(server.url).json<IncomingHttpHeaders>();331 9 unmodified lines341 342 const original = ky.create({343 headers: new Headers({344 rainbow: 'rainbow',344- unicorn: 'unicorn'345- })345+ unicorn: 'unicorn',346+ }),347 });348 349 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 });355 356 const response = await extended(server.url).json<IncomingHttpHeaders>();357 9 unmodified lines367 368 const original = ky.create({369 headers: new Headers({370 rainbow: 'rainbow',370- unicorn: 'unicorn'371- })371+ unicorn: 'unicorn',372+ }),373 });374 375 const extended = original.extend({376 headers: {376- rainbow: undefined377- }377+ rainbow: undefined,378+ },379 });380 381 const response = await extended(server.url).json<IncomingHttpHeaders>();382 9 unmodified lines392 393 const original = ky.create({394 headers: {395 rainbow: 'rainbow',395- unicorn: 'unicorn'396- }396+ unicorn: 'unicorn',397+ },398 });399 400 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 });406 407 const response = await extended(server.url).json<IncomingHttpHeaders>();408 5 unmodified linesmodified:test/hooks.ts+76 added-76 removed
9 unmodified lines10 response.json(request.body);11 });12 13 const json = {14- foo: true14+ foo: true,15 };16 17 const responseJson = await ky18 .post(server.url, {4 unmodified lines23 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>();32 33 t.false(responseJson.foo);22 unmodified lines56 response.json(request.body);57 });58 59 const json = {60- foo: true60+ foo: true,61 };62 63 const responseJson = await ky64 .post(server.url, {3 unmodified lines68 (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>();77 78 t.false(responseJson.foo);7 unmodified lines86 response.json(request.body);87 });88 89 const json = {90- foo: true90+ foo: true,91 };92 93 await t.notThrowsAsync(94 ky3 unmodified lines98 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 );108 109 await server.close();110 });4 unmodified lines115 response.status(500).send(request.body);116 });117 118 const json = {119- foo: true119+ foo: true,120 };121 122 await t.throwsAsync(123 ky3 unmodified lines127 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 );137 138 await server.close();139 });15 unmodified lines155 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);164 165 return new Response(modifiedBody2, {166- status: modifiedStatus2166+ status: modifiedStatus2,167 });168- }169- ]170- }168+ },169+ ],170+ },171 })172 .text();173 174 t.is(responseBody, modifiedBody2);17 unmodified lines192 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 );205 206 // Async hook function207 await t.throwsAsync(2 unmodified lines210 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 );223 224 await server.close();225 });11 unmodified lines237 afterResponse: [238 (_input, _options, response) => {239 called = true;240 return response;241- }242- ]243- }241+ },242+ ],243+ },244 })245 .json();246 247 t.true(called);13 unmodified lines261 });262 263 const json = {264 foo: true,265- token: 'invalid:token'265+ token: 'invalid:token',266 };267 268 t.deepEqual(269 await ky7 unmodified lines277 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 }285 286 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 );297 298 await server.close();299 });16 unmodified lines316 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();325 326 t.deepEqual(json, {awesome: true});14 unmodified lines341 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 );352 353 await server.close();354 });19 unmodified lines374 hooks: {375 beforeRetry: [376 ({request}) => {377 request.headers.set('unicorn', fixture);378- }379- ]380- }378+ },379+ ],380+ },381 })382 .text(),383- fixture383+ fixture,384 );385 386 await server.close();387 });17 unmodified lines405 beforeRetry: [406 ({error, retryCount}) => {407 t.true(error instanceof HTTPError);408 t.true(retryCount >= 1);409- }410- ]411- }409+ },410+ ],411+ },412 });413 414 await server.close();415 });27 unmodified lines443 // @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();452 453 t.is(text, 'unicorn');32 unmodified lines486 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();495 496 t.deepEqual(json, {awesome: true});23 unmodified lines520 t.truthy(error);521 t.is(retryCount, 1);522 523 return ky.stop;524- }525- ]526- }524+ },525+ ],526+ },527 });528 529 t.is(requestCount, 1);530 22 unmodified lines553 hooks: {554 beforeRetry: [555 () => {556 throw error;557- }558- ]559- }557+ },558+ ],559+ },560 }),561- {message: errorString}561+ {message: errorString},562 );563 });564 565 test('catches beforeRetry promise rejections', async t => {15 unmodified lines581 582 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 });591 592 test('hooks beforeRequest returning Response skips HTTP Request', async t => {1 unmodified line594 595 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();602 603 t.is(response, expectedResponse);1 unmodified linemodified:test/http-error.ts+3 added-3 removed
17 unmodified lines18 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 );24 25 t.is(error.message, 'Request failed with status code 500');26 });2 unmodified lines29 // @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 );35 36 t.is(error.message, 'Request failed with an unknown error');37 });1 unmodified line39 test('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 );45 46 t.is(error.message, 'Request failed with status code 0');47 });modified:test/main.ts+53 added-52 removed
1+import {Buffer} from 'node:buffer';2 import test from 'ava';3 import delay from 'delay';4 import ky, {TimeoutError} from '../source/index.js';5 import {createHttpTestServer} from './helpers/create-http-test-server.js';90 unmodified lines96 response.json(request.body);97 });98 99 const json = {99- foo: true100+ foo: true,101 };102 103 const responseJson = await ky.post(server.url, {json}).json();104 7 unmodified lines112 () => {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 );119 120 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 });129 130 test('cannot use `json` option with GET or HEAD method', t => {1 unmodified line132 () => {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 );139 140 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 });149 150 test('`json` option overrides the `body` option', async t => {5 unmodified lines156 response.json(request.body);157 });158 159 const json = {159- foo: 'bar'160+ foo: 'bar',161 };162 163 const responseJson = await ky164 .post(server.url, {165 body: 'hello',165- json166+ json,167 })168 .json();169 170 t.deepEqual(responseJson, json);9 unmodified lines180 181 t.is(182 await ky(server.url, {183 headers: {183- unicorn: fixture184- }184+ unicorn: fixture,185+ },186 }).text(),186- fixture187+ fixture,188 );189 190 await server.close();191 });8 unmodified lines200 response.json(request.body);201 });202 203 const json = {203- foo: true204+ foo: true,205 };206 207 const responseJson = await ky208 .post(server.url, {209 headers: new Headers({unicorn: 'rainbow'}),209- json210+ json,211 })212 .json();213 214 t.deepEqual(responseJson, json);10 unmodified lines225 response.json({});226 });227 228 const responseJson = await ky(server.url, {228- headers: {accept: 'foo/bar'}229+ headers: {accept: 'foo/bar'},230 }).json();231 232 t.deepEqual(responseJson, {});233 9 unmodified lines243 response.status(200).end();244 });245 246 await t.throwsAsync(ky(server.url).json(), {246- message: /Unexpected end of JSON input/247+ message: /Unexpected end of JSON input/,248 });249 250 await server.close();251 });25 unmodified lines277 response.end(fixture);278 });279 280 await t.throwsAsync(ky(server.url, {timeout: 1000}).text(), {280- instanceOf: TimeoutError281+ instanceOf: TimeoutError,282 });283 284 t.is(requestCount, 1);285 27 unmodified lines313 await delay(1000);314 response.end(fixture);315 });316 316- 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 });321 322 t.is(requestCount, 0);323 27 unmodified lines351 352 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 lines405 });406 407 await t.throwsAsync(408 ky(server.url, {throwHttpErrors: false, timeout: 500}).text(),408- {instanceOf: TimeoutError}409+ {instanceOf: TimeoutError},410 );411 412 t.is(requestCount, 1);413 8 unmodified lines422 });423 424 const extended = ky.create({425 headers: {425- rainbow: 'rainbow'426- }426+ rainbow: 'rainbow',427+ },428 });429 430 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 );438 439 t.true((await extended.head(server.url)).ok);440 11 unmodified lines452 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 lines472 hooks: {473 beforeRequest: [474 () => {475 isOriginBeforeRequestTrigged = true;475- }476- ]477- }476+ },477+ ],478+ },479 });480 481 await extended(server.url, {482 hooks: {483 beforeRequest: [484 () => {485 isExtendBeforeRequestTrigged = true;485- }486- ]487- }486+ },487+ ],488+ },489 });490 491 t.is(isOriginBeforeRequestTrigged, true);492 t.is(isExtendBeforeRequestTrigged, true);28 unmodified lines521 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 });538 539 await extended(server.url);540 36 unmodified lines577 // @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 });585 586 test('options override Request instance method', async t => {16 unmodified lines603 const expectedBody = JSON.stringify({test: false});604 605 const inputRequest = new Request(server.url, {606 method: 'POST',606- body: requestBody607+ body: requestBody,608 });609 610 server.post('/', (request, response) => {611 const body: Buffer[] = [];40 unmodified lines652 653 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();660 661 t.deepEqual(responseJson, {662 ...json,662- extra: 'extraValue'663+ extra: 'extraValue',664 });665 666 await server.close();667 });9 unmodified lines677 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();685 686 t.deepEqual(responseJson, {687 ...json,687- extra: 'extraValue'688+ extra: 'extraValue',689 });690 691 await server.close();692 });modified:test/methods.ts+8 added-8 removed
13 unmodified lines14 hooks: {15 beforeRequest: [16 (_input, options) => {17 t.is(options.method, 'GET');18- }19- ]20- }21- })18+ },19+ ],20+ },21+ }),22 );23 24 await server.close();25 });10 unmodified lines36 hooks: {37 beforeRequest: [38 (_input, options) => {39 t.is(options.method, 'report');40- }41- ]42- }43- })40+ },41+ ],42+ },43+ }),44 );45 46 await server.close();47 });12 unmodified linesmodified:test/prefix-url.ts+3 added-3 removed
12 unmodified lines13 14 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 lines31 () => {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 );38 39 await server.close();40 });modified:test/retry.ts+50 added-50 removed
15 unmodified lines16 17 if (requestCount === defaultRetryCount) {18 response.end(fixture);19 } else {20- response.status(99999).end();20+ response.status(99_999).end();21 }22 });23 24 t.is(await ky(server.url).text(), fixture);53 unmodified lines78 }79 });80 81 await t.throwsAsync(ky.post(server.url).text(), {82- message: /Internal Server Error/82+ message: /Internal Server Error/,83 });84 85 await server.close();86 });8 unmodified lines95 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 lines119 } 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 lines161 162 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);173 174 await server.close();17 unmodified lines192 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);204 205 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);218 219 await server.close();6 unmodified lines226 server.get('/', async (_request, response) => {227 requestCount++;228 229 response.writeHead(413, {230- 'Retry-After': 1230+ 'Retry-After': 1,231 });232 233 response.end('');234 });1 unmodified line236 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);248 249 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);262 263 await server.close();8 unmodified lines272 response.sendStatus(408);273 });274 275 await t.throwsAsync(ky(server.url, {retry: 5}).text(), {276- message: /Request Timeout/276+ message: /Request Timeout/,277 });278 t.is(requestCount, 5);279 280 await server.close();13 unmodified lines294 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 );305 306 t.is(requestCount, 1);307 12 unmodified lines320 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 );331 332 t.is(requestCount, 1);333 12 unmodified lines346 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 );357 358 t.is(requestCount, 4);359 12 unmodified lines372 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 );383 384 t.is(requestCount, 4);385 11 unmodified lines397 398 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 );408 409 t.is(requestCount, 1);410 6 unmodified lines417 t.throws(() => {418 void ky(server.url, {419 retry: {420 // @ts-expect-error421- methods: 'get'422- }421+ methods: 'get',422+ },423 });424 });425 426 await server.close();5 unmodified lines432 t.throws(() => {433 void ky(server.url, {434 retry: {435 // @ts-expect-error436- statusCodes: 403437- }436+ statusCodes: 403,437+ },438 });439 });440 441 await server.close();1 unmodified linemodified:package.json+16 added-12 removed
48 unmodified lines49 "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 lines82 "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