Skip to content
Myr

Code style

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 5d0a85d · Browse files · 3 files+136 added−134 removed
This commit

State

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

Diff stats

3 files+136 added−134 removed

  • other:+136 added−134 removed

3 files+136 added−134 removed

modified:source/core/Ky.ts+80 added-78 removed
3 unmodified lines
4 InternalOptions,5 NormalizedOptions,6 Options,7 SearchParamsInit,8 SearchParamsOption,9} from '../types/options.js';10import {type ResponsePromise} from '../types/ResponsePromise.js';11import {streamRequest, streamResponse} from '../utils/body.js';12import {mergeHeaders, mergeHooks} from '../utils/merge.js';
18 unmodified lines
31 static create(input: Input, options: Options): ResponsePromise {32 const ky = new Ky(input, options);3334 const function_ = async (): Promise<Response> => {34 if (typeof ky._options.timeout === 'number' && ky._options.timeout > maxSafeTimeout) {35 if (typeof ky.#options.timeout === 'number' && ky.#options.timeout > maxSafeTimeout) {36 throw new RangeError(`The \`timeout\` option cannot be greater than ${maxSafeTimeout}`);37 }3839 // Delay the fetch so that body method shortcuts can set the Accept header40 await Promise.resolve();41 // Before using ky.request, _fetch clones it and saves the clone for future retries to use.42 // If retry is not needed, close the cloned request's ReadableStream for memory safety.42 let response = await ky._fetch();43 let response = await ky.#fetch();4444 for (const hook of ky._options.hooks.afterResponse) {45 for (const hook of ky.#options.hooks.afterResponse) {46 // eslint-disable-next-line no-await-in-loop47 const modifiedResponse = await hook(48 ky.request,49 ky.#getNormalizedOptions(),49 ky._decorateResponse(response.clone()),50 {retryCount: ky._retryCount},50 ky.#decorateResponse(response.clone()),51 {retryCount: ky.#retryCount},52 );5354 if (modifiedResponse instanceof globalThis.Response) {55 response = modifiedResponse;56 }57 }5858 ky._decorateResponse(response);59 ky.#decorateResponse(response);6060 if (!response.ok && ky._options.throwHttpErrors) {61 if (!response.ok && ky.#options.throwHttpErrors) {62 let error = new HTTPError(response, ky.request, ky.#getNormalizedOptions());6363 for (const hook of ky._options.hooks.beforeError) {64 for (const hook of ky.#options.hooks.beforeError) {65 // eslint-disable-next-line no-await-in-loop65 error = await hook(error, {retryCount: ky._retryCount});66 error = await hook(error, {retryCount: ky.#retryCount});67 }6869 throw error;70 }7172 // If `onDownloadProgress` is passed, it uses the stream API internally72 if (ky._options.onDownloadProgress) {73 if (typeof ky._options.onDownloadProgress !== 'function') {73 if (ky.#options.onDownloadProgress) {74 if (typeof ky.#options.onDownloadProgress !== 'function') {75 throw new TypeError('The `onDownloadProgress` option must be a function');76 }7778 if (!supportsResponseStreams) {79 throw new Error('Streams are not supported in your environment. `ReadableStream` is missing.');80 }8181 return streamResponse(response.clone(), ky._options.onDownloadProgress);82 return streamResponse(response.clone(), ky.#options.onDownloadProgress);83 }8485 return response;86 };8787 const isRetriableMethod = ky._options.retry.methods.includes(ky.request.method.toLowerCase());88 const result = (isRetriableMethod ? ky._retry(function_) : function_())88 const isRetriableMethod = ky.#options.retry.methods.includes(ky.request.method.toLowerCase());89 const result = (isRetriableMethod ? ky.#retry(function_) : function_())90 .finally(async () => {90 const originalRequest = ky._originalRequest;91 const originalRequest = ky.#originalRequest;92 const cleanupPromises = [];9394 if (originalRequest && !originalRequest.bodyUsed) {95 cleanupPromises.push(originalRequest.body?.cancel());
45 unmodified lines
141 return result;142 }143144 // eslint-disable-next-line unicorn/prevent-abbreviations144 static #normalizeSearchParams(searchParams: any): any {145 static #normalizeSearchParams(searchParams: SearchParamsOption): SearchParamsOption {146 // Filter out undefined values from plain objects147 if (searchParams && typeof searchParams === 'object' && !Array.isArray(searchParams) && !(searchParams instanceof URLSearchParams)) {148 return Object.fromEntries(149 Object.entries(searchParams).filter(([, value]) => value !== undefined),
3 unmodified lines
153 return searchParams;154 }155156 public request: Request;156 protected abortController?: AbortController;157 protected _retryCount = 0;158 protected _input: Input;159 protected _options: InternalOptions;160 protected _originalRequest?: Request;157 readonly #abortController?: AbortController;158 #retryCount = 0;159 // eslint-disable-next-line @typescript-eslint/prefer-readonly -- False positive: #input is reassigned on line 202160 #input: Input;161 readonly #options: InternalOptions;162 #originalRequest?: Request;163 #cachedNormalizedOptions?: NormalizedOptions;164165 // eslint-disable-next-line complexity166 constructor(input: Input, options: Options = {}) {165 this._input = input;167 this.#input = input;168167 this._options = {169 this.#options = {170 ...options,169 headers: mergeHeaders((this._input as Request).headers, options.headers),171 headers: mergeHeaders((this.#input as Request).headers, options.headers),172 hooks: mergeHooks(173 {174 beforeRequest: [],175 beforeRetry: [],
1 unmodified line
177 afterResponse: [],178 },179 options.hooks,180 ),179 method: normalizeRequestMethod(options.method ?? (this._input as Request).method ?? 'GET'),181 method: normalizeRequestMethod(options.method ?? (this.#input as Request).method ?? 'GET'),182 // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing183 prefixUrl: String(options.prefixUrl || ''),184 retry: normalizeRetryOptions(options.retry),185 throwHttpErrors: options.throwHttpErrors !== false,186 timeout: options.timeout ?? 10_000,187 fetch: options.fetch ?? globalThis.fetch.bind(globalThis),188 };189188 if (typeof this._input !== 'string' && !(this._input instanceof URL || this._input instanceof globalThis.Request)) {190 if (typeof this.#input !== 'string' && !(this.#input instanceof URL || this.#input instanceof globalThis.Request)) {191 throw new TypeError('`input` must be a string, URL, or Request');192 }193192 if (this._options.prefixUrl && typeof this._input === 'string') {193 if (this._input.startsWith('/')) {194 if (this.#options.prefixUrl && typeof this.#input === 'string') {195 if (this.#input.startsWith('/')) {196 throw new Error('`input` must not begin with a slash when using `prefixUrl`');197 }198197 if (!this._options.prefixUrl.endsWith('/')) {198 this._options.prefixUrl += '/';199 if (!this.#options.prefixUrl.endsWith('/')) {200 this.#options.prefixUrl += '/';201 }202201 this._input = this._options.prefixUrl + this._input;203 this.#input = this.#options.prefixUrl + this.#input;204 }205206 if (supportsAbortController && supportsAbortSignal) {205 const originalSignal = this._options.signal ?? (this._input as Request).signal;206 this.abortController = new globalThis.AbortController();207 this._options.signal = originalSignal ? AbortSignal.any([originalSignal, this.abortController.signal]) : this.abortController.signal;207 const originalSignal = this.#options.signal ?? (this.#input as Request).signal;208 this.#abortController = new globalThis.AbortController();209 this.#options.signal = originalSignal ? AbortSignal.any([originalSignal, this.#abortController.signal]) : this.#abortController.signal;210 }211212 if (supportsRequestStreams) {213 // @ts-expect-error - Types are outdated.212 this._options.duplex = 'half';214 this.#options.duplex = 'half';215 }216215 if (this._options.json !== undefined) {216 this._options.body = this._options.stringifyJson?.(this._options.json) ?? JSON.stringify(this._options.json);217 this._options.headers.set('content-type', this._options.headers.get('content-type') ?? 'application/json');217 if (this.#options.json !== undefined) {218 this.#options.body = this.#options.stringifyJson?.(this.#options.json) ?? JSON.stringify(this.#options.json);219 this.#options.headers.set('content-type', this.#options.headers.get('content-type') ?? 'application/json');220 }221222 // To provide correct form boundary, Content-Type header should be deleted when creating Request from another Request with FormData/URLSearchParams body223 // Only delete if user didn't explicitly provide a custom content-type224 const userProvidedContentType = options.headers && new globalThis.Headers(options.headers as HeadersInit).has('content-type');225 if (224 this._input instanceof globalThis.Request225 && ((supportsFormData && this._options.body instanceof globalThis.FormData) || this._options.body instanceof URLSearchParams)226 this.#input instanceof globalThis.Request227 && ((supportsFormData && this.#options.body instanceof globalThis.FormData) || this.#options.body instanceof URLSearchParams)228 && !userProvidedContentType229 ) {228 this._options.headers.delete('content-type');230 this.#options.headers.delete('content-type');231 }232231 this.request = new globalThis.Request(this._input, this._options);233 this.request = new globalThis.Request(this.#input, this.#options);234233 if (hasSearchParameters(this._options.searchParams)) {235 if (hasSearchParameters(this.#options.searchParams)) {236 // eslint-disable-next-line unicorn/prevent-abbreviations235 const textSearchParams = typeof this._options.searchParams === 'string'236 ? this._options.searchParams.replace(/^\?/, '')237 : new URLSearchParams(Ky.#normalizeSearchParams(this._options.searchParams) as unknown as SearchParamsInit).toString();237 const textSearchParams = typeof this.#options.searchParams === 'string'238 ? this.#options.searchParams.replace(/^\?/, '')239 : new URLSearchParams(Ky.#normalizeSearchParams(this.#options.searchParams) as unknown as SearchParamsInit).toString();240 // eslint-disable-next-line unicorn/prevent-abbreviations241 const searchParams = '?' + textSearchParams;242 const url = this.request.url.replace(/(?:\?.*?)?(?=#|$)/, searchParams);243244 // The spread of `this.request` is required as otherwise it misses the `duplex` option for some reason and throws.243 this.request = new globalThis.Request(new globalThis.Request(url, {...this.request}), this._options as RequestInit);245 this.request = new globalThis.Request(new globalThis.Request(url, {...this.request}), this.#options as RequestInit);246 }247248 // If `onUploadProgress` is passed, it uses the stream API internally247 if (this._options.onUploadProgress) {248 if (typeof this._options.onUploadProgress !== 'function') {249 if (this.#options.onUploadProgress) {250 if (typeof this.#options.onUploadProgress !== 'function') {251 throw new TypeError('The `onUploadProgress` option must be a function');252 }253254 if (!supportsRequestStreams) {
2 unmodified lines
257258 const originalBody = this.request.body;259 if (originalBody) {260 // Pass original body to calculate size correctly (before it becomes a stream)259 this.request = streamRequest(this.request, this._options.onUploadProgress, this._options.body);261 this.request = streamRequest(this.request, this.#options.onUploadProgress, this.#options.body);262 }263 }264 }265264 protected _calculateRetryDelay(error: unknown) {265 this._retryCount++;266 #calculateRetryDelay(error: unknown) {267 this.#retryCount++;268267 if (this._retryCount > this._options.retry.limit || isTimeoutError(error)) {269 if (this.#retryCount > this.#options.retry.limit || isTimeoutError(error)) {270 throw error;271 }272273 if (isHTTPError(error)) {272 if (!this._options.retry.statusCodes.includes(error.response.status)) {274 if (!this.#options.retry.statusCodes.includes(error.response.status)) {275 throw error;276 }277278 const retryAfter = error.response.headers.get('Retry-After')279 ?? error.response.headers.get('RateLimit-Reset')280 ?? error.response.headers.get('X-RateLimit-Reset') // GitHub281 ?? error.response.headers.get('X-Rate-Limit-Reset'); // Twitter280 if (retryAfter && this._options.retry.afterStatusCodes.includes(error.response.status)) {282 if (retryAfter && this.#options.retry.afterStatusCodes.includes(error.response.status)) {283 let after = Number(retryAfter) * 1000;284 if (Number.isNaN(after)) {285 after = Date.parse(retryAfter) - Date.now();286 } else if (after >= Date.parse('2024-01-01')) {287 // A large number is treated as a timestamp (fixed threshold protects against clock skew)288 after -= Date.now();289 }290289 const max = this._options.retry.maxRetryAfter ?? after;291 const max = this.#options.retry.maxRetryAfter ?? after;292 return after < max ? after : max;293 }294295 if (error.response.status === 413) {296 throw error;297 }298 }299298 const retryDelay = this._options.retry.delay(this._retryCount);299 return Math.min(this._options.retry.backoffLimit, retryDelay);300 const retryDelay = this.#options.retry.delay(this.#retryCount);301 return Math.min(this.#options.retry.backoffLimit, retryDelay);302 }303302 protected _decorateResponse(response: Response): Response {303 if (this._options.parseJson) {304 response.json = async () => this._options.parseJson!(await response.text());304 #decorateResponse(response: Response): Response {305 if (this.#options.parseJson) {306 response.json = async () => this.#options.parseJson!(await response.text());307 }308309 return response;310 }311310 protected async _retry<T extends (...arguments_: any) => Promise<any>>(function_: T): Promise<ReturnType<T> | void> {312 async #retry<T extends (...arguments_: any) => Promise<any>>(function_: T): Promise<ReturnType<T> | void> {313 try {314 return await function_();315 } catch (error) {314 const ms = Math.min(this._calculateRetryDelay(error), maxSafeTimeout);315 if (this._retryCount < 1) {316 const ms = Math.min(this.#calculateRetryDelay(error), maxSafeTimeout);317 if (this.#retryCount < 1) {318 throw error;319 }320319 await delay(ms, {signal: this._options.signal});321 await delay(ms, {signal: this.#options.signal});322321 for (const hook of this._options.hooks.beforeRetry) {323 for (const hook of this.#options.hooks.beforeRetry) {324 // eslint-disable-next-line no-await-in-loop325 const hookResult = await hook({326 request: this.request,327 options: this.#getNormalizedOptions(),328 error: error as Error,327 retryCount: this._retryCount,329 retryCount: this.#retryCount,330 });331332 // If `stop` is returned from the hook, the retry process is stopped333 if (hookResult === stop) {334 return;335 }336 }337336 return this._retry(function_);338 return this.#retry(function_);339 }340 }341340 protected async _fetch(): Promise<Response> {341 for (const hook of this._options.hooks.beforeRequest) {342 async #fetch(): Promise<Response> {343 for (const hook of this.#options.hooks.beforeRequest) {344 // eslint-disable-next-line no-await-in-loop345 const result = await hook(346 this.request,347 this.#getNormalizedOptions(),346 {retryCount: this._retryCount},348 {retryCount: this.#retryCount},349 );350351 if (result instanceof Request) {352 this.request = result;
4 unmodified lines
357 return result;358 }359 }360359 const nonRequestOptions = findUnknownOptions(this.request, this._options);361 const nonRequestOptions = findUnknownOptions(this.request, this.#options);362363 // Cloning is done here to prepare in advance for retries362 this._originalRequest = this.request;363 this.request = this._originalRequest.clone();364 this.#originalRequest = this.request;365 this.request = this.#originalRequest.clone();366365 if (this._options.timeout === false) {366 return this._options.fetch(this._originalRequest, nonRequestOptions);367 if (this.#options.timeout === false) {368 return this.#options.fetch(this.#originalRequest, nonRequestOptions);369 }370369 return timeout(this._originalRequest, nonRequestOptions, this.abortController, this._options as TimeoutOptions);371 return timeout(this.#originalRequest, nonRequestOptions, this.#abortController, this.#options as TimeoutOptions);372 }373374 #getNormalizedOptions(): NormalizedOptions {375 if (!this.#cachedNormalizedOptions) {374 const {hooks, ...normalizedOptions} = this._options;376 const {hooks, ...normalizedOptions} = this.#options;377 this.#cachedNormalizedOptions = Object.freeze(normalizedOptions) as NormalizedOptions;378 }379380 return this.#cachedNormalizedOptions;
2 unmodified lines
modified:source/utils/body.ts+1 added-1 removed
modified:source/utils/type-guards.ts+55 added-55 removed
1import {HTTPError} from '../errors/HTTPError.js';2import {TimeoutError} from '../errors/TimeoutError.js';34/**5 * Type guard to check if an error is a Ky error (HTTPError or TimeoutError).6 *7 * @param error - The error to check8 * @returns `true` if the error is a Ky error, `false` otherwise9 *10 * @example11 * ```12 * import ky, {isKyError} from 'ky';13 * try {14 * const response = await ky.get('/api/data');15 * } catch (error) {16 * if (isKyError(error)) {17 * // Handle Ky-specific errors18 * console.log('Ky error occurred:', error.message);19 * } else {20 * // Handle other errors21 * console.log('Unknown error:', error);22 * }23 * }24 * ```25 */5Type guard to check if an error is a Ky error (HTTPError or TimeoutError).67@param error - The error to check8@returns `true` if the error is a Ky error, `false` otherwise910@example11```12import ky, {isKyError} from 'ky';13try {14 const response = await ky.get('/api/data');15} catch (error) {16 if (isKyError(error)) {17 // Handle Ky-specific errors18 console.log('Ky error occurred:', error.message);19 } else {20 // Handle other errors21 console.log('Unknown error:', error);22 }23}24```25*/26export function isKyError(error: unknown): error is HTTPError | TimeoutError {27 return isHTTPError(error) || isTimeoutError(error);28}2930/**31 * Type guard to check if an error is an HTTPError.32 *33 * @param error - The error to check34 * @returns `true` if the error is an HTTPError, `false` otherwise35 *36 * @example37 * ```38 * import ky, {isHTTPError} from 'ky';39 * try {40 * const response = await ky.get('/api/data');41 * } catch (error) {42 * if (isHTTPError(error)) {43 * console.log('HTTP error status:', error.response.status);44 * }45 * }46 * ```47 */31Type guard to check if an error is an HTTPError.3233@param error - The error to check34@returns `true` if the error is an HTTPError, `false` otherwise3536@example37```38import ky, {isHTTPError} from 'ky';39try {40 const response = await ky.get('/api/data');41} catch (error) {42 if (isHTTPError(error)) {43 console.log('HTTP error status:', error.response.status);44 }45}46```47*/48export function isHTTPError<T = unknown>(error: unknown): error is HTTPError<T> {49 return error instanceof HTTPError || ((error as any)?.name === HTTPError.name);50}5152/**53 * Type guard to check if an error is a TimeoutError.54 *55 * @param error - The error to check56 * @returns `true` if the error is a TimeoutError, `false` otherwise57 *58 * @example59 * ```60 * import ky, {isTimeoutError} from 'ky';61 * try {62 * const response = await ky.get('/api/data', { timeout: 1000 });63 * } catch (error) {64 * if (isTimeoutError(error)) {65 * console.log('Request timed out:', error.request.url);66 * }67 * }68 * ```69 */53Type guard to check if an error is a TimeoutError.5455@param error - The error to check56@returns `true` if the error is a TimeoutError, `false` otherwise5758@example59```60import ky, {isTimeoutError} from 'ky';61try {62 const response = await ky.get('/api/data', { timeout: 1000 });63} catch (error) {64 if (isTimeoutError(error)) {65 console.log('Request timed out:', error.request.url);66 }67}68```69*/70export function isTimeoutError(error: unknown): error is TimeoutError {71 return error instanceof TimeoutError || ((error as any)?.name === TimeoutError.name);72}