neue Homepage auf react basis

This commit is contained in:
2026-08-07 21:39:30 +02:00
parent 164bdd19ad
commit ee89442c04
52191 changed files with 1230242 additions and 58 deletions
+4
View File
@@ -0,0 +1,4 @@
import type { Options } from '../types/options.js';
export declare const getBodySize: (body?: BodyInit | null) => number;
export declare const streamResponse: (response: Response, onDownloadProgress: Options["onDownloadProgress"]) => Response;
export declare const streamRequest: (request: Request, onUploadProgress: Options["onUploadProgress"], originalBody?: BodyInit | null) => Request;
+89
View File
@@ -0,0 +1,89 @@
import { usualFormBoundarySize } from '../core/constants.js';
const encoder = new TextEncoder();
// eslint-disable-next-line @typescript-eslint/no-restricted-types
export const getBodySize = (body) => {
if (!body) {
return 0;
}
if (body instanceof FormData) {
// This is an approximation, as FormData size calculation is not straightforward
let size = 0;
for (const [key, value] of body) {
size += usualFormBoundarySize;
size += encoder.encode(`Content-Disposition: form-data; name="${key}"`).byteLength;
size += typeof value === 'string'
? encoder.encode(value).byteLength
: value.size;
}
return size;
}
if (body instanceof Blob) {
return body.size;
}
if (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) {
return body.byteLength;
}
if (typeof body === 'string') {
return encoder.encode(body).byteLength;
}
if (body instanceof URLSearchParams) {
return encoder.encode(body.toString()).byteLength;
}
return 0;
};
const withProgress = (stream, totalBytes, onProgress) => {
let previousChunk;
let transferredBytes = 0;
return stream.pipeThrough(new TransformStream({
transform(currentChunk, controller) {
controller.enqueue(currentChunk);
if (previousChunk) {
transferredBytes += previousChunk.byteLength;
let percent = totalBytes === 0 ? 0 : transferredBytes / totalBytes;
// Avoid reporting 100% progress before the stream is actually finished (in case totalBytes is inaccurate)
if (percent >= 1) {
// Epsilon is used here to get as close as possible to 100% without reaching it.
// If we were to use 0.99 here, percent could potentially go backwards.
percent = 1 - Number.EPSILON;
}
onProgress?.({ percent, totalBytes: Math.max(totalBytes, transferredBytes), transferredBytes }, previousChunk);
}
previousChunk = currentChunk;
},
flush() {
if (previousChunk) {
transferredBytes += previousChunk.byteLength;
onProgress?.({ percent: 1, totalBytes: Math.max(totalBytes, transferredBytes), transferredBytes }, previousChunk);
}
},
}));
};
export const streamResponse = (response, onDownloadProgress) => {
if (!response.body) {
return response;
}
const responseInit = {
status: response.status,
statusText: response.statusText,
headers: response.headers,
};
if (response.status === 204) {
return new Response(null, responseInit);
}
const totalBytes = Math.max(0, Number(response.headers.get('content-length')) || 0);
return new Response(withProgress(response.body, totalBytes, onDownloadProgress), responseInit);
};
// eslint-disable-next-line @typescript-eslint/no-restricted-types
export const streamRequest = (request, onUploadProgress, originalBody) => {
if (!request.body) {
return request;
}
// Use original body for size calculation since request.body is already a stream
const totalBytes = getBodySize(originalBody ?? request.body);
return new Request(request, {
// @ts-expect-error - Types are outdated.
duplex: 'half',
body: withProgress(request.body, totalBytes, onUploadProgress),
});
};
//# sourceMappingURL=body.js.map
File diff suppressed because one or more lines are too long
+5
View File
@@ -0,0 +1,5 @@
import { type InternalOptions } from '../types/options.js';
export type DelayOptions = {
signal?: InternalOptions['signal'];
};
export default function delay(ms: number, { signal }: DelayOptions): Promise<void>;
+18
View File
@@ -0,0 +1,18 @@
// https://github.com/sindresorhus/delay/tree/ab98ae8dfcb38e1593286c94d934e70d14a4e111
export default async function delay(ms, { signal }) {
return new Promise((resolve, reject) => {
if (signal) {
signal.throwIfAborted();
signal.addEventListener('abort', abortHandler, { once: true });
}
function abortHandler() {
clearTimeout(timeoutId);
reject(signal.reason);
}
const timeoutId = setTimeout(() => {
signal?.removeEventListener('abort', abortHandler);
resolve();
}, ms);
});
}
//# sourceMappingURL=delay.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"delay.js","sourceRoot":"","sources":["../../source/utils/delay.ts"],"names":[],"mappings":"AAAA,sFAAsF;AAQtF,MAAM,CAAC,OAAO,CAAC,KAAK,UAAU,KAAK,CAClC,EAAU,EACV,EAAC,MAAM,EAAe;IAEtB,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACtC,IAAI,MAAM,EAAE,CAAC;YACZ,MAAM,CAAC,cAAc,EAAE,CAAC;YACxB,MAAM,CAAC,gBAAgB,CAAC,OAAO,EAAE,YAAY,EAAE,EAAC,IAAI,EAAE,IAAI,EAAC,CAAC,CAAC;QAC9D,CAAC;QAED,SAAS,YAAY;YACpB,YAAY,CAAC,SAAS,CAAC,CAAC;YACxB,MAAM,CAAC,MAAO,CAAC,MAAe,CAAC,CAAC;QACjC,CAAC;QAED,MAAM,SAAS,GAAG,UAAU,CAAC,GAAG,EAAE;YACjC,MAAM,EAAE,mBAAmB,CAAC,OAAO,EAAE,YAAY,CAAC,CAAC;YACnD,OAAO,EAAE,CAAC;QACX,CAAC,EAAE,EAAE,CAAC,CAAC;IACR,CAAC,CAAC,CAAC;AACJ,CAAC","sourcesContent":["// https://github.com/sindresorhus/delay/tree/ab98ae8dfcb38e1593286c94d934e70d14a4e111\n\nimport {type InternalOptions} from '../types/options.js';\n\nexport type DelayOptions = {\n\tsignal?: InternalOptions['signal'];\n};\n\nexport default async function delay(\n\tms: number,\n\t{signal}: DelayOptions,\n): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tif (signal) {\n\t\t\tsignal.throwIfAborted();\n\t\t\tsignal.addEventListener('abort', abortHandler, {once: true});\n\t\t}\n\n\t\tfunction abortHandler() {\n\t\t\tclearTimeout(timeoutId);\n\t\t\treject(signal!.reason as Error);\n\t\t}\n\n\t\tconst timeoutId = setTimeout(() => {\n\t\t\tsignal?.removeEventListener('abort', abortHandler);\n\t\t\tresolve();\n\t\t}, ms);\n\t});\n}\n"]}
+1
View File
@@ -0,0 +1 @@
export default function isRawNetworkError(error: unknown): error is TypeError;
+40
View File
@@ -0,0 +1,40 @@
// Inlined from https://github.com/sindresorhus/is-network-error v1.3.1
const objectToString = Object.prototype.toString;
const isError = (value) => objectToString.call(value) === '[object Error]';
const errorMessages = new Set([
'network error', // Chrome
'NetworkError when attempting to fetch resource.', // Firefox
'The Internet connection appears to be offline.', // Safari 16
'Network request failed', // `cross-fetch`
'fetch failed', // Undici (Node.js)
'terminated', // Undici (Node.js)
' A network error occurred.', // Bun (WebKit) - leading space is intentional
'Network connection lost', // Cloudflare Workers (fetch)
]);
export default function isRawNetworkError(error) {
const isValid = error
&& isError(error)
&& error.name === 'TypeError'
&& typeof error.message === 'string';
if (!isValid) {
return false;
}
const { message, stack } = error;
// Safari 17+ has generic message but no stack for network errors
if (message === 'Load failed') {
return stack === undefined
// Sentry adds its own stack trace to the fetch error, so also check for that
|| '__sentry_captured__' in error;
}
// Deno network errors start with specific text
if (message.startsWith('error sending request for url')) {
return true;
}
// Chrome: exact "Failed to fetch" or with hostname: "Failed to fetch (example.com)"
if (message === 'Failed to fetch' || (message.startsWith('Failed to fetch (') && message.endsWith(')'))) {
return true;
}
// Standard network error messages
return errorMessages.has(message);
}
//# sourceMappingURL=is-network-error.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"is-network-error.js","sourceRoot":"","sources":["../../source/utils/is-network-error.ts"],"names":[],"mappings":"AAAA,uEAAuE;AAEvE,MAAM,cAAc,GAAG,MAAM,CAAC,SAAS,CAAC,QAAQ,CAAC;AAEjD,MAAM,OAAO,GAAG,CAAC,KAAc,EAAkB,EAAE,CAAC,cAAc,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,gBAAgB,CAAC;AAEpG,MAAM,aAAa,GAAG,IAAI,GAAG,CAAC;IAC7B,eAAe,EAAE,SAAS;IAC1B,iDAAiD,EAAE,UAAU;IAC7D,gDAAgD,EAAE,YAAY;IAC9D,wBAAwB,EAAE,gBAAgB;IAC1C,cAAc,EAAE,mBAAmB;IACnC,YAAY,EAAE,mBAAmB;IACjC,4BAA4B,EAAE,8CAA8C;IAC5E,yBAAyB,EAAE,6BAA6B;CACxD,CAAC,CAAC;AAEH,MAAM,CAAC,OAAO,UAAU,iBAAiB,CAAC,KAAc;IACvD,MAAM,OAAO,GAAG,KAAK;WACjB,OAAO,CAAC,KAAK,CAAC;WACd,KAAK,CAAC,IAAI,KAAK,WAAW;WAC1B,OAAO,KAAK,CAAC,OAAO,KAAK,QAAQ,CAAC;IAEtC,IAAI,CAAC,OAAO,EAAE,CAAC;QACd,OAAO,KAAK,CAAC;IACd,CAAC;IAED,MAAM,EAAC,OAAO,EAAE,KAAK,EAAC,GAAG,KAAK,CAAC;IAE/B,iEAAiE;IACjE,IAAI,OAAO,KAAK,aAAa,EAAE,CAAC;QAC/B,OAAO,KAAK,KAAK,SAAS;YACzB,6EAA6E;eAC1E,qBAAqB,IAAI,KAAK,CAAC;IACpC,CAAC;IAED,+CAA+C;IAC/C,IAAI,OAAO,CAAC,UAAU,CAAC,+BAA+B,CAAC,EAAE,CAAC;QACzD,OAAO,IAAI,CAAC;IACb,CAAC;IAED,oFAAoF;IACpF,IAAI,OAAO,KAAK,iBAAiB,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,mBAAmB,CAAC,IAAI,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC;QACzG,OAAO,IAAI,CAAC;IACb,CAAC;IAED,kCAAkC;IAClC,OAAO,aAAa,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;AACnC,CAAC","sourcesContent":["// Inlined from https://github.com/sindresorhus/is-network-error v1.3.1\n\nconst objectToString = Object.prototype.toString;\n\nconst isError = (value: unknown): value is Error => objectToString.call(value) === '[object Error]';\n\nconst errorMessages = new Set([\n\t'network error', // Chrome\n\t'NetworkError when attempting to fetch resource.', // Firefox\n\t'The Internet connection appears to be offline.', // Safari 16\n\t'Network request failed', // `cross-fetch`\n\t'fetch failed', // Undici (Node.js)\n\t'terminated', // Undici (Node.js)\n\t' A network error occurred.', // Bun (WebKit) - leading space is intentional\n\t'Network connection lost', // Cloudflare Workers (fetch)\n]);\n\nexport default function isRawNetworkError(error: unknown): error is TypeError {\n\tconst isValid = error\n\t\t&& isError(error)\n\t\t&& error.name === 'TypeError'\n\t\t&& typeof error.message === 'string';\n\n\tif (!isValid) {\n\t\treturn false;\n\t}\n\n\tconst {message, stack} = error;\n\n\t// Safari 17+ has generic message but no stack for network errors\n\tif (message === 'Load failed') {\n\t\treturn stack === undefined\n\t\t\t// Sentry adds its own stack trace to the fetch error, so also check for that\n\t\t\t|| '__sentry_captured__' in error;\n\t}\n\n\t// Deno network errors start with specific text\n\tif (message.startsWith('error sending request for url')) {\n\t\treturn true;\n\t}\n\n\t// Chrome: exact \"Failed to fetch\" or with hostname: \"Failed to fetch (example.com)\"\n\tif (message === 'Failed to fetch' || (message.startsWith('Failed to fetch (') && message.endsWith(')'))) {\n\t\treturn true;\n\t}\n\n\t// Standard network error messages\n\treturn errorMessages.has(message);\n}\n"]}
+1
View File
@@ -0,0 +1 @@
export declare const isObject: (value: unknown) => value is object;
+3
View File
@@ -0,0 +1,3 @@
// eslint-disable-next-line @typescript-eslint/no-restricted-types
export const isObject = (value) => value !== null && typeof value === 'object';
//# sourceMappingURL=is.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"is.js","sourceRoot":"","sources":["../../source/utils/is.ts"],"names":[],"mappings":"AAAA,kEAAkE;AAClE,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAC,KAAc,EAAmB,EAAE,CAAC,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,CAAC","sourcesContent":["// eslint-disable-next-line @typescript-eslint/no-restricted-types\nexport const isObject = (value: unknown): value is object => value !== null && typeof value === 'object';\n"]}
+29
View File
@@ -0,0 +1,29 @@
import type { KyHeadersInit, Options } from '../types/options.js';
import type { Hooks } from '../types/hooks.js';
/**
Wraps a value so that `ky.extend()` will replace the parent value instead of merging with it. Works with hooks, headers, search parameters, context, and any other deep-merged option.
By default, `.extend()` deep-merges options with the parent instance: hooks get appended, headers get merged, and search parameters get accumulated. Use `replaceOption` when you want to fully replace a merged property instead.
@example
```
import ky, {replaceOption} from 'ky';
const base = ky.create({
hooks: {beforeRequest: [addAuth, addTracking]},
});
// Replaces instead of appending
const extended = base.extend({
hooks: replaceOption({beforeRequest: [onlyThis]}),
});
// hooks.beforeRequest is now [onlyThis], not [addAuth, addTracking, onlyThis]
```
*/
export declare const replaceOption: <T>(value: T) => T;
export declare const validateAndMerge: (...sources: Array<Partial<Options> | undefined>) => Partial<Options>;
export declare const mergeHeaders: (source1?: KyHeadersInit, source2?: KyHeadersInit) => Headers;
export declare const cloneShallow: <T>(value: T) => T;
export declare const mergeHooks: (original?: Hooks, incoming?: Hooks) => Required<Hooks>;
export declare const deletedParametersSymbol: unique symbol;
export declare const deepMerge: <T>(...sources: Array<Partial<T> | undefined>) => T;
+259
View File
@@ -0,0 +1,259 @@
import { supportsAbortSignal } from '../core/constants.js';
import { isObject } from './is.js';
const replaceSymbol = Symbol('replaceOption');
const getReplaceState = (value) => isObject(value) && value[replaceSymbol] === true
? {
isReplace: true,
value: value.value,
}
: {
isReplace: false,
value,
};
/**
Wraps a value so that `ky.extend()` will replace the parent value instead of merging with it. Works with hooks, headers, search parameters, context, and any other deep-merged option.
By default, `.extend()` deep-merges options with the parent instance: hooks get appended, headers get merged, and search parameters get accumulated. Use `replaceOption` when you want to fully replace a merged property instead.
@example
```
import ky, {replaceOption} from 'ky';
const base = ky.create({
hooks: {beforeRequest: [addAuth, addTracking]},
});
// Replaces instead of appending
const extended = base.extend({
hooks: replaceOption({beforeRequest: [onlyThis]}),
});
// hooks.beforeRequest is now [onlyThis], not [addAuth, addTracking, onlyThis]
```
*/
export const replaceOption = (value) => {
const markedValue = { [replaceSymbol]: true, value };
return markedValue;
};
export const validateAndMerge = (...sources) => {
for (const source of sources) {
if ((!isObject(source) || Array.isArray(source)) && source !== undefined) {
throw new TypeError('The `options` argument must be an object');
}
}
return deepMerge({}, ...sources);
};
export const mergeHeaders = (source1 = {}, source2 = {}) => {
const result = new globalThis.Headers(source1);
const isHeadersInstance = source2 instanceof globalThis.Headers;
const source = new globalThis.Headers(source2);
for (const [key, value] of source.entries()) {
if ((isHeadersInstance && value === 'undefined') || value === undefined) {
result.delete(key);
}
else {
result.set(key, value);
}
}
return result;
};
const isPlainObject = (value) => {
if (!isObject(value) || Array.isArray(value)) {
return false;
}
const prototype = Object.getPrototypeOf(value);
return prototype === Object.prototype || prototype === null;
};
export const cloneShallow = (value) => {
if (value instanceof URLSearchParams) {
const copy = new URLSearchParams(value);
const deleted = value[deletedParametersSymbol];
if (deleted) {
// Preserve internal deletion markers so init-hook cloning does not resurrect params removed during option merging.
copy[deletedParametersSymbol] = new Set(deleted);
}
return copy;
}
if (value instanceof globalThis.Headers) {
return new globalThis.Headers(value);
}
if (Array.isArray(value)) {
return [...value];
}
if (isPlainObject(value)) {
const copy = { ...value };
return copy;
}
return value;
};
const normalizeHeaderObject = (headers) => Object.fromEntries(Object.entries(headers).filter((entry) => entry[1] !== undefined));
const mergeHeaderContainers = (source1, source2) => {
if (isPlainObject(source1) && isPlainObject(source2)) {
return normalizeHeaderObject({ ...source1, ...source2 });
}
return mergeHeaders(source1, source2);
};
function newHookValue(original, incoming, property) {
return (Object.hasOwn(incoming, property) && incoming[property] === undefined)
? []
: deepMerge(original[property] ?? [], incoming[property] ?? []);
}
export const mergeHooks = (original = {}, incoming = {}) => ({
init: newHookValue(original, incoming, 'init'),
beforeRequest: newHookValue(original, incoming, 'beforeRequest'),
beforeRetry: newHookValue(original, incoming, 'beforeRetry'),
beforeError: newHookValue(original, incoming, 'beforeError'),
afterResponse: newHookValue(original, incoming, 'afterResponse'),
});
export const deletedParametersSymbol = Symbol('deletedParameters');
const appendSearchParameters = (target, source) => {
const result = new URLSearchParams();
const deleted = new Set();
for (const input of [target, source]) {
if (input === undefined) {
continue;
}
if (input instanceof URLSearchParams) {
for (const [key, value] of input.entries()) {
result.append(key, value);
deleted.delete(key);
}
const inputDeleted = input[deletedParametersSymbol];
if (inputDeleted) {
for (const key of inputDeleted) {
result.delete(key);
deleted.add(key);
}
}
}
else if (Array.isArray(input)) {
for (const pair of input) {
if (!Array.isArray(pair) || pair.length !== 2) {
throw new TypeError('Array search parameters must be provided in [[key, value], ...] format');
}
result.append(String(pair[0]), String(pair[1]));
deleted.delete(String(pair[0]));
}
}
else if (isObject(input)) {
for (const [key, value] of Object.entries(input)) {
if (value === undefined) {
result.delete(key);
deleted.add(key);
}
else {
result.append(key, String(value));
deleted.delete(key);
}
}
}
else {
// String
const parameters = new URLSearchParams(input);
for (const [key, value] of parameters.entries()) {
result.append(key, value);
deleted.delete(key);
}
}
}
if (deleted.size > 0) {
result[deletedParametersSymbol] = deleted;
}
return result;
};
// TODO: Make this strongly-typed (no `any`).
export const deepMerge = (...sources) => {
let returnValue = {};
let headers = {};
let hooks = {};
let searchParameters;
const signals = [];
for (const source of sources) {
if (Array.isArray(source)) {
if (!Array.isArray(returnValue)) {
returnValue = [];
}
returnValue = [...returnValue, ...source];
}
else if (isObject(source)) {
for (let [key, value] of Object.entries(source)) {
// Special handling for AbortSignal instances
if (key === 'signal' && value instanceof globalThis.AbortSignal) {
signals.push(value);
continue;
}
const replaceState = getReplaceState(value);
const { isReplace } = replaceState;
value = replaceState.value;
// Special handling for context - shallow merge only
if (key === 'context') {
if (value !== undefined && value !== null && (!isObject(value) || Array.isArray(value))) {
throw new TypeError('The `context` option must be an object');
}
// Shallow merge: always create a new object to prevent mutation bugs
returnValue = {
...returnValue,
context: (value === undefined || value === null)
? {}
: (isReplace
? { ...value }
: { ...returnValue.context, ...value }),
};
continue;
}
// Special handling for searchParams
if (key === 'searchParams') {
if (value === undefined || value === null) {
// Explicit undefined or null removes searchParams
searchParameters = undefined;
}
else if (isReplace) {
searchParameters = value;
}
else {
// First source: keep as-is to preserve type (string/object/URLSearchParams)
// Subsequent sources: merge and convert to URLSearchParams
searchParameters = searchParameters === undefined ? value : appendSearchParameters(searchParameters, value);
}
continue;
}
if (isObject(value) && !isReplace && key in returnValue) {
value = deepMerge(returnValue[key], value);
}
returnValue = { ...returnValue, [key]: value };
}
if (isObject(source.hooks)) {
const { value: hookValue, isReplace } = getReplaceState(source.hooks);
hooks = isReplace
? mergeHooks({}, hookValue)
: mergeHooks(hooks, hookValue);
returnValue.hooks = hooks;
}
if (isObject(source.headers)) {
const { value: headerValue, isReplace } = getReplaceState(source.headers);
headers = isReplace
? cloneShallow(headerValue)
: mergeHeaderContainers(headers, headerValue);
returnValue.headers = headers;
}
}
}
if (searchParameters !== undefined) {
returnValue.searchParams = searchParameters;
}
if (signals.length > 0) {
if (signals.length === 1) {
returnValue.signal = signals[0];
}
else if (supportsAbortSignal) {
returnValue.signal = AbortSignal.any(signals);
}
else {
// When AbortSignal.any is not available, use the last signal
// This maintains the previous behavior before signal merging was added
// This can be remove when the `supportsAbortSignal` check is removed.`
returnValue.signal = signals.at(-1);
}
}
return returnValue;
};
//# sourceMappingURL=merge.js.map
File diff suppressed because one or more lines are too long
+5
View File
@@ -0,0 +1,5 @@
import type { RetryOptions } from '../types/retry.js';
export declare const normalizeRequestMethod: (input: string) => string;
type InternalRetryOptions = Required<Omit<RetryOptions, 'shouldRetry'>> & Pick<RetryOptions, 'shouldRetry'>;
export declare const normalizeRetryOptions: (retry?: number | RetryOptions) => InternalRetryOptions;
export {};
+39
View File
@@ -0,0 +1,39 @@
import { requestMethods } from '../core/constants.js';
export const normalizeRequestMethod = (input) => requestMethods.includes(input) ? input.toUpperCase() : input;
const retryMethods = ['get', 'put', 'head', 'delete', 'options', 'trace'];
const retryStatusCodes = [408, 413, 429, 500, 502, 503, 504];
const retryAfterStatusCodes = [413, 429, 503];
const defaultRetryOptions = {
limit: 2,
methods: retryMethods,
statusCodes: retryStatusCodes,
afterStatusCodes: retryAfterStatusCodes,
maxRetryAfter: Number.POSITIVE_INFINITY,
backoffLimit: Number.POSITIVE_INFINITY,
delay: attemptCount => 0.3 * (2 ** (attemptCount - 1)) * 1000,
jitter: undefined,
retryOnTimeout: false,
};
export const normalizeRetryOptions = (retry = {}) => {
if (typeof retry === 'number') {
return {
...defaultRetryOptions,
limit: retry,
};
}
if (retry.methods && !Array.isArray(retry.methods)) {
throw new Error('retry.methods must be an array');
}
if (retry.statusCodes && !Array.isArray(retry.statusCodes)) {
throw new Error('retry.statusCodes must be an array');
}
const normalizedRetry = Object.fromEntries(Object.entries({
...retry,
methods: retry.methods?.map(method => method.toLowerCase()),
}).filter(([, value]) => value !== undefined));
return {
...defaultRetryOptions,
...normalizedRetry,
};
};
//# sourceMappingURL=normalize.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"normalize.js","sourceRoot":"","sources":["../../source/utils/normalize.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,cAAc,EAAC,MAAM,sBAAsB,CAAC;AAIpD,MAAM,CAAC,MAAM,sBAAsB,GAAG,CAAC,KAAa,EAAU,EAAE,CAC/D,cAAc,CAAC,QAAQ,CAAC,KAA0B,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC;AAEnF,MAAM,YAAY,GAAiB,CAAC,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,SAAS,EAAE,OAAO,CAAC,CAAC;AAExF,MAAM,gBAAgB,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC;AAE7D,MAAM,qBAAqB,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC;AAI9C,MAAM,mBAAmB,GAAyB;IACjD,KAAK,EAAE,CAAC;IACR,OAAO,EAAE,YAAY;IACrB,WAAW,EAAE,gBAAgB;IAC7B,gBAAgB,EAAE,qBAAqB;IACvC,aAAa,EAAE,MAAM,CAAC,iBAAiB;IACvC,YAAY,EAAE,MAAM,CAAC,iBAAiB;IACtC,KAAK,EAAE,YAAY,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,CAAC,IAAI,CAAC,YAAY,GAAG,CAAC,CAAC,CAAC,GAAG,IAAI;IAC7D,MAAM,EAAE,SAAS;IACjB,cAAc,EAAE,KAAK;CACrB,CAAC;AAEF,MAAM,CAAC,MAAM,qBAAqB,GAAG,CAAC,QAA+B,EAAE,EAAwB,EAAE;IAChG,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QAC/B,OAAO;YACN,GAAG,mBAAmB;YACtB,KAAK,EAAE,KAAK;SACZ,CAAC;IACH,CAAC;IAED,IAAI,KAAK,CAAC,OAAO,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,CAAC;QACpD,MAAM,IAAI,KAAK,CAAC,gCAAgC,CAAC,CAAC;IACnD,CAAC;IAED,IAAI,KAAK,CAAC,WAAW,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,WAAW,CAAC,EAAE,CAAC;QAC5D,MAAM,IAAI,KAAK,CAAC,oCAAoC,CAAC,CAAC;IACvD,CAAC;IAED,MAAM,eAAe,GAAG,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,OAAO,CAAC;QACzD,GAAG,KAAK;QACR,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC,MAAM,CAAC,WAAW,EAAE,CAAC;KAC3D,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,KAAK,KAAK,SAAS,CAAC,CAAiB,CAAC;IAE/D,OAAO;QACN,GAAG,mBAAmB;QACtB,GAAG,eAAe;KAClB,CAAC;AACH,CAAC,CAAC","sourcesContent":["import {requestMethods} from '../core/constants.js';\nimport type {RetryOptions} from '../types/retry.js';\nimport type {HttpMethod, RequestHttpMethod} from '../types/options.js';\n\nexport const normalizeRequestMethod = (input: string): string =>\n\trequestMethods.includes(input as RequestHttpMethod) ? input.toUpperCase() : input;\n\nconst retryMethods: HttpMethod[] = ['get', 'put', 'head', 'delete', 'options', 'trace'];\n\nconst retryStatusCodes = [408, 413, 429, 500, 502, 503, 504];\n\nconst retryAfterStatusCodes = [413, 429, 503];\n\ntype InternalRetryOptions = Required<Omit<RetryOptions, 'shouldRetry'>> & Pick<RetryOptions, 'shouldRetry'>;\n\nconst defaultRetryOptions: InternalRetryOptions = {\n\tlimit: 2,\n\tmethods: retryMethods,\n\tstatusCodes: retryStatusCodes,\n\tafterStatusCodes: retryAfterStatusCodes,\n\tmaxRetryAfter: Number.POSITIVE_INFINITY,\n\tbackoffLimit: Number.POSITIVE_INFINITY,\n\tdelay: attemptCount => 0.3 * (2 ** (attemptCount - 1)) * 1000,\n\tjitter: undefined,\n\tretryOnTimeout: false,\n};\n\nexport const normalizeRetryOptions = (retry: number | RetryOptions = {}): InternalRetryOptions => {\n\tif (typeof retry === 'number') {\n\t\treturn {\n\t\t\t...defaultRetryOptions,\n\t\t\tlimit: retry,\n\t\t};\n\t}\n\n\tif (retry.methods && !Array.isArray(retry.methods)) {\n\t\tthrow new Error('retry.methods must be an array');\n\t}\n\n\tif (retry.statusCodes && !Array.isArray(retry.statusCodes)) {\n\t\tthrow new Error('retry.statusCodes must be an array');\n\t}\n\n\tconst normalizedRetry = Object.fromEntries(Object.entries({\n\t\t...retry,\n\t\tmethods: retry.methods?.map(method => method.toLowerCase()),\n\t}).filter(([, value]) => value !== undefined)) as RetryOptions;\n\n\treturn {\n\t\t...defaultRetryOptions,\n\t\t...normalizedRetry,\n\t};\n};\n"]}
+3
View File
@@ -0,0 +1,3 @@
import type { SearchParamsOption } from '../types/options.js';
export declare const findUnknownOptions: (options: Record<string, unknown>) => Record<string, unknown>;
export declare const hasSearchParameters: (search: SearchParamsOption) => boolean;
+41
View File
@@ -0,0 +1,41 @@
import { kyOptionKeys, requestOptionsRegistry } from '../core/constants.js';
import { deletedParametersSymbol } from './merge.js';
export const findUnknownOptions = (options) => {
const unknownOptions = {};
for (const key in options) {
// Skip inherited properties
if (!Object.hasOwn(options, key)) {
continue;
}
// Forward every non-standard, non-Ky option to fetch().
// We intentionally do not check whether the key also exists on `Request`, because some runtimes
// patch `Request.prototype` with fetch-only extensions. For example, Next.js adds `next`, and the
// old `key in request` heuristic dropped it unless Ky kept a special-case allowlist.
// Passing all non-standard keys makes that allowlist unnecessary and preserves future fetch extensions too.
if (!(key in requestOptionsRegistry) && !(key in kyOptionKeys)) {
unknownOptions[key] = options[key];
}
}
return unknownOptions;
};
export const hasSearchParameters = (search) => {
if (search === undefined) {
return false;
}
// The `typeof array` still gives "object", so we need different checking for array.
if (Array.isArray(search)) {
return search.length > 0;
}
if (search instanceof URLSearchParams) {
return search.size > 0 || Boolean(search[deletedParametersSymbol]?.size);
}
// Record
if (typeof search === 'object') {
return Object.keys(search).length > 0;
}
if (typeof search === 'string') {
return search.trim().length > 0;
}
return Boolean(search);
};
//# sourceMappingURL=options.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"options.js","sourceRoot":"","sources":["../../source/utils/options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,YAAY,EAAE,sBAAsB,EAAC,MAAM,sBAAsB,CAAC;AAE1E,OAAO,EAAC,uBAAuB,EAAC,MAAM,YAAY,CAAC;AAEnD,MAAM,CAAC,MAAM,kBAAkB,GAAG,CACjC,OAAgC,EACN,EAAE;IAC5B,MAAM,cAAc,GAA4B,EAAE,CAAC;IAEnD,KAAK,MAAM,GAAG,IAAI,OAAO,EAAE,CAAC;QAC3B,4BAA4B;QAC5B,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,OAAO,EAAE,GAAG,CAAC,EAAE,CAAC;YAClC,SAAS;QACV,CAAC;QAED,wDAAwD;QACxD,gGAAgG;QAChG,kGAAkG;QAClG,qFAAqF;QACrF,4GAA4G;QAC5G,IAAI,CAAC,CAAC,GAAG,IAAI,sBAAsB,CAAC,IAAI,CAAC,CAAC,GAAG,IAAI,YAAY,CAAC,EAAE,CAAC;YAChE,cAAc,CAAC,GAAG,CAAC,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC;QACpC,CAAC;IACF,CAAC;IAED,OAAO,cAAc,CAAC;AACvB,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,mBAAmB,GAAG,CAAC,MAA0B,EAAW,EAAE;IAC1E,IAAI,MAAM,KAAK,SAAS,EAAE,CAAC;QAC1B,OAAO,KAAK,CAAC;IACd,CAAC;IAED,oFAAoF;IACpF,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC;QAC3B,OAAO,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC;IAC1B,CAAC;IAED,IAAI,MAAM,YAAY,eAAe,EAAE,CAAC;QACvC,OAAO,MAAM,CAAC,IAAI,GAAG,CAAC,IAAI,OAAO,CAAE,MAAc,CAAC,uBAAuB,CAAC,EAAE,IAAI,CAAC,CAAC;IACnF,CAAC;IAED,SAAS;IACT,IAAI,OAAO,MAAM,KAAK,QAAQ,EAAE,CAAC;QAChC,OAAO,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC;IACvC,CAAC;IAED,IAAI,OAAO,MAAM,KAAK,QAAQ,EAAE,CAAC;QAChC,OAAO,MAAM,CAAC,IAAI,EAAE,CAAC,MAAM,GAAG,CAAC,CAAC;IACjC,CAAC;IAED,OAAO,OAAO,CAAC,MAAM,CAAC,CAAC;AACxB,CAAC,CAAC","sourcesContent":["import {kyOptionKeys, requestOptionsRegistry} from '../core/constants.js';\nimport type {SearchParamsOption} from '../types/options.js';\nimport {deletedParametersSymbol} from './merge.js';\n\nexport const findUnknownOptions = (\n\toptions: Record<string, unknown>,\n): Record<string, unknown> => {\n\tconst unknownOptions: Record<string, unknown> = {};\n\n\tfor (const key in options) {\n\t\t// Skip inherited properties\n\t\tif (!Object.hasOwn(options, key)) {\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Forward every non-standard, non-Ky option to fetch().\n\t\t// We intentionally do not check whether the key also exists on `Request`, because some runtimes\n\t\t// patch `Request.prototype` with fetch-only extensions. For example, Next.js adds `next`, and the\n\t\t// old `key in request` heuristic dropped it unless Ky kept a special-case allowlist.\n\t\t// Passing all non-standard keys makes that allowlist unnecessary and preserves future fetch extensions too.\n\t\tif (!(key in requestOptionsRegistry) && !(key in kyOptionKeys)) {\n\t\t\tunknownOptions[key] = options[key];\n\t\t}\n\t}\n\n\treturn unknownOptions;\n};\n\nexport const hasSearchParameters = (search: SearchParamsOption): boolean => {\n\tif (search === undefined) {\n\t\treturn false;\n\t}\n\n\t// The `typeof array` still gives \"object\", so we need different checking for array.\n\tif (Array.isArray(search)) {\n\t\treturn search.length > 0;\n\t}\n\n\tif (search instanceof URLSearchParams) {\n\t\treturn search.size > 0 || Boolean((search as any)[deletedParametersSymbol]?.size);\n\t}\n\n\t// Record\n\tif (typeof search === 'object') {\n\t\treturn Object.keys(search).length > 0;\n\t}\n\n\tif (typeof search === 'string') {\n\t\treturn search.trim().length > 0;\n\t}\n\n\treturn Boolean(search);\n};\n"]}
+5
View File
@@ -0,0 +1,5 @@
export type TimeoutOptions = {
timeout: number;
fetch: typeof fetch;
};
export default function timeout(request: Request, init: RequestInit, abortController: AbortController | undefined, options: TimeoutOptions): Promise<Response>;
+20
View File
@@ -0,0 +1,20 @@
import { TimeoutError } from '../errors/TimeoutError.js';
// `Promise.race()` workaround (#91)
export default async function timeout(request, init, abortController, options) {
return new Promise((resolve, reject) => {
const timeoutId = setTimeout(() => {
if (abortController) {
abortController.abort();
}
reject(new TimeoutError(request));
}, options.timeout);
void options
.fetch(request, init)
.then(resolve)
.catch(reject)
.then(() => {
clearTimeout(timeoutId);
});
});
}
//# sourceMappingURL=timeout.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"timeout.js","sourceRoot":"","sources":["../../source/utils/timeout.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,YAAY,EAAC,MAAM,2BAA2B,CAAC;AAOvD,oCAAoC;AACpC,MAAM,CAAC,OAAO,CAAC,KAAK,UAAU,OAAO,CACpC,OAAgB,EAChB,IAAiB,EACjB,eAA4C,EAC5C,OAAuB;IAEvB,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACtC,MAAM,SAAS,GAAG,UAAU,CAAC,GAAG,EAAE;YACjC,IAAI,eAAe,EAAE,CAAC;gBACrB,eAAe,CAAC,KAAK,EAAE,CAAC;YACzB,CAAC;YAED,MAAM,CAAC,IAAI,YAAY,CAAC,OAAO,CAAC,CAAC,CAAC;QACnC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,CAAC;QAEpB,KAAK,OAAO;aACV,KAAK,CAAC,OAAO,EAAE,IAAI,CAAC;aACpB,IAAI,CAAC,OAAO,CAAC;aACb,KAAK,CAAC,MAAM,CAAC;aACb,IAAI,CAAC,GAAG,EAAE;YACV,YAAY,CAAC,SAAS,CAAC,CAAC;QACzB,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import {TimeoutError} from '../errors/TimeoutError.js';\n\nexport type TimeoutOptions = {\n\ttimeout: number;\n\tfetch: typeof fetch;\n};\n\n// `Promise.race()` workaround (#91)\nexport default async function timeout(\n\trequest: Request,\n\tinit: RequestInit,\n\tabortController: AbortController | undefined,\n\toptions: TimeoutOptions,\n): Promise<Response> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst timeoutId = setTimeout(() => {\n\t\t\tif (abortController) {\n\t\t\t\tabortController.abort();\n\t\t\t}\n\n\t\t\treject(new TimeoutError(request));\n\t\t}, options.timeout);\n\n\t\tvoid options\n\t\t\t.fetch(request, init)\n\t\t\t.then(resolve)\n\t\t\t.catch(reject)\n\t\t\t.then(() => {\n\t\t\t\tclearTimeout(timeoutId);\n\t\t\t});\n\t});\n}\n"]}
+111
View File
@@ -0,0 +1,111 @@
import type { KyError } from '../errors/KyError.js';
import { HTTPError } from '../errors/HTTPError.js';
import { NetworkError } from '../errors/NetworkError.js';
import { TimeoutError } from '../errors/TimeoutError.js';
import { ForceRetryError } from '../errors/ForceRetryError.js';
/**
Type guard to check if an error is a `KyError`.
Note: `SchemaValidationError` is intentionally not considered a Ky error. `KyError` covers failures in Ky's HTTP lifecycle (bad status, timeout, retry), while schema validation errors originate from the user-provided schema, not from Ky itself.
@param error - The error to check
@returns `true` if the error is a Ky error, `false` otherwise
@example
```
import ky, {isKyError} from 'ky';
try {
const response = await ky.get('/api/data');
} catch (error) {
if (isKyError(error)) {
// Handle Ky-specific errors
console.log('Ky error occurred:', error.message);
} else {
// Handle other errors
console.log('Unknown error:', error);
}
}
```
*/
export declare function isKyError(error: unknown): error is KyError;
/**
Type guard to check if an error is an `HTTPError`.
@param error - The error to check
@returns `true` if the error is an `HTTPError`, `false` otherwise
@example
```
import ky, {isHTTPError} from 'ky';
try {
const response = await ky.get('/api/data');
} catch (error) {
if (isHTTPError(error)) {
console.log('HTTP error status:', error.response.status);
}
}
```
*/
export declare function isHTTPError<T = unknown>(error: unknown): error is HTTPError<T>;
/**
Type guard to check if an error is a `NetworkError`.
@param error - The error to check
@returns `true` if the error is a `NetworkError`, `false` otherwise
@example
```
import ky, {isNetworkError} from 'ky';
try {
const response = await ky.get('/api/data');
} catch (error) {
if (isNetworkError(error)) {
console.log('Network error:', error.request.url);
}
}
```
*/
export declare function isNetworkError(error: unknown): error is NetworkError;
/**
Type guard to check if an error is a `TimeoutError`.
@param error - The error to check
@returns `true` if the error is a `TimeoutError`, `false` otherwise
@example
```
import ky, {isTimeoutError} from 'ky';
try {
const response = await ky.get('/api/data', { timeout: 1000 });
} catch (error) {
if (isTimeoutError(error)) {
console.log('Request timed out:', error.request.url);
}
}
```
*/
export declare function isTimeoutError(error: unknown): error is TimeoutError;
/**
Type guard to check if an error is a `ForceRetryError`.
@param error - The error to check
@returns `true` if the error is a `ForceRetryError`, `false` otherwise
@example
```
import ky, {isForceRetryError} from 'ky';
const api = ky.extend({
hooks: {
beforeRetry: [
({error, retryCount}) => {
if (isForceRetryError(error)) {
console.log(`Forced retry #${retryCount}: ${error.code}`);
}
}
]
}
});
```
*/
export declare function isForceRetryError(error: unknown): error is ForceRetryError;
+123
View File
@@ -0,0 +1,123 @@
import { HTTPError } from '../errors/HTTPError.js';
import { NetworkError } from '../errors/NetworkError.js';
import { TimeoutError } from '../errors/TimeoutError.js';
import { ForceRetryError } from '../errors/ForceRetryError.js';
// Handles cross-realm cases (e.g., iframes, different JS contexts) where `instanceof` fails.
const isErrorType = (error, cls) => error instanceof cls || error?.name === cls.name;
/**
Type guard to check if an error is a `KyError`.
Note: `SchemaValidationError` is intentionally not considered a Ky error. `KyError` covers failures in Ky's HTTP lifecycle (bad status, timeout, retry), while schema validation errors originate from the user-provided schema, not from Ky itself.
@param error - The error to check
@returns `true` if the error is a Ky error, `false` otherwise
@example
```
import ky, {isKyError} from 'ky';
try {
const response = await ky.get('/api/data');
} catch (error) {
if (isKyError(error)) {
// Handle Ky-specific errors
console.log('Ky error occurred:', error.message);
} else {
// Handle other errors
console.log('Unknown error:', error);
}
}
```
*/
export function isKyError(error) {
return error?.isKyError === true || isHTTPError(error) || isNetworkError(error) || isTimeoutError(error) || isForceRetryError(error);
}
/**
Type guard to check if an error is an `HTTPError`.
@param error - The error to check
@returns `true` if the error is an `HTTPError`, `false` otherwise
@example
```
import ky, {isHTTPError} from 'ky';
try {
const response = await ky.get('/api/data');
} catch (error) {
if (isHTTPError(error)) {
console.log('HTTP error status:', error.response.status);
}
}
```
*/
export function isHTTPError(error) {
return isErrorType(error, HTTPError);
}
/**
Type guard to check if an error is a `NetworkError`.
@param error - The error to check
@returns `true` if the error is a `NetworkError`, `false` otherwise
@example
```
import ky, {isNetworkError} from 'ky';
try {
const response = await ky.get('/api/data');
} catch (error) {
if (isNetworkError(error)) {
console.log('Network error:', error.request.url);
}
}
```
*/
export function isNetworkError(error) {
return isErrorType(error, NetworkError);
}
/**
Type guard to check if an error is a `TimeoutError`.
@param error - The error to check
@returns `true` if the error is a `TimeoutError`, `false` otherwise
@example
```
import ky, {isTimeoutError} from 'ky';
try {
const response = await ky.get('/api/data', { timeout: 1000 });
} catch (error) {
if (isTimeoutError(error)) {
console.log('Request timed out:', error.request.url);
}
}
```
*/
export function isTimeoutError(error) {
return isErrorType(error, TimeoutError);
}
/**
Type guard to check if an error is a `ForceRetryError`.
@param error - The error to check
@returns `true` if the error is a `ForceRetryError`, `false` otherwise
@example
```
import ky, {isForceRetryError} from 'ky';
const api = ky.extend({
hooks: {
beforeRetry: [
({error, retryCount}) => {
if (isForceRetryError(error)) {
console.log(`Forced retry #${retryCount}: ${error.code}`);
}
}
]
}
});
```
*/
export function isForceRetryError(error) {
return isErrorType(error, ForceRetryError);
}
//# sourceMappingURL=type-guards.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"type-guards.js","sourceRoot":"","sources":["../../source/utils/type-guards.ts"],"names":[],"mappings":"AACA,OAAO,EAAC,SAAS,EAAC,MAAM,wBAAwB,CAAC;AACjD,OAAO,EAAC,YAAY,EAAC,MAAM,2BAA2B,CAAC;AACvD,OAAO,EAAC,YAAY,EAAC,MAAM,2BAA2B,CAAC;AACvD,OAAO,EAAC,eAAe,EAAC,MAAM,8BAA8B,CAAC;AAE7D,6FAA6F;AAC7F,MAAM,WAAW,GAAG,CAAC,KAAc,EAAE,GAAmB,EAAW,EAAE,CACpE,KAAK,YAAa,GAAW,IAAK,KAAa,EAAE,IAAI,KAAK,GAAG,CAAC,IAAI,CAAC;AAEpE;;;;;;;;;;;;;;;;;;;;;;;EAuBE;AACF,MAAM,UAAU,SAAS,CAAC,KAAc;IACvC,OAAQ,KAAa,EAAE,SAAS,KAAK,IAAI,IAAI,WAAW,CAAC,KAAK,CAAC,IAAI,cAAc,CAAC,KAAK,CAAC,IAAI,cAAc,CAAC,KAAK,CAAC,IAAI,iBAAiB,CAAC,KAAK,CAAC,CAAC;AAC/I,CAAC;AAED;;;;;;;;;;;;;;;;;EAiBE;AACF,MAAM,UAAU,WAAW,CAAc,KAAc;IACtD,OAAO,WAAW,CAAC,KAAK,EAAE,SAAS,CAAC,CAAC;AACtC,CAAC;AAED;;;;;;;;;;;;;;;;;EAiBE;AACF,MAAM,UAAU,cAAc,CAAC,KAAc;IAC5C,OAAO,WAAW,CAAC,KAAK,EAAE,YAAY,CAAC,CAAC;AACzC,CAAC;AAED;;;;;;;;;;;;;;;;;EAiBE;AACF,MAAM,UAAU,cAAc,CAAC,KAAc;IAC5C,OAAO,WAAW,CAAC,KAAK,EAAE,YAAY,CAAC,CAAC;AACzC,CAAC;AAED;;;;;;;;;;;;;;;;;;;;;;EAsBE;AACF,MAAM,UAAU,iBAAiB,CAAC,KAAc;IAC/C,OAAO,WAAW,CAAC,KAAK,EAAE,eAAe,CAAC,CAAC;AAC5C,CAAC","sourcesContent":["import type {KyError} from '../errors/KyError.js';\nimport {HTTPError} from '../errors/HTTPError.js';\nimport {NetworkError} from '../errors/NetworkError.js';\nimport {TimeoutError} from '../errors/TimeoutError.js';\nimport {ForceRetryError} from '../errors/ForceRetryError.js';\n\n// Handles cross-realm cases (e.g., iframes, different JS contexts) where `instanceof` fails.\nconst isErrorType = (error: unknown, cls: {name: string}): boolean =>\n\terror instanceof (cls as any) || (error as any)?.name === cls.name;\n\n/**\nType guard to check if an error is a `KyError`.\n\nNote: `SchemaValidationError` is intentionally not considered a Ky error. `KyError` covers failures in Ky's HTTP lifecycle (bad status, timeout, retry), while schema validation errors originate from the user-provided schema, not from Ky itself.\n\n@param error - The error to check\n@returns `true` if the error is a Ky error, `false` otherwise\n\n@example\n```\nimport ky, {isKyError} from 'ky';\ntry {\n\tconst response = await ky.get('/api/data');\n} catch (error) {\n\tif (isKyError(error)) {\n\t\t// Handle Ky-specific errors\n\t\tconsole.log('Ky error occurred:', error.message);\n\t} else {\n\t\t// Handle other errors\n\t\tconsole.log('Unknown error:', error);\n\t}\n}\n```\n*/\nexport function isKyError(error: unknown): error is KyError {\n\treturn (error as any)?.isKyError === true || isHTTPError(error) || isNetworkError(error) || isTimeoutError(error) || isForceRetryError(error);\n}\n\n/**\nType guard to check if an error is an `HTTPError`.\n\n@param error - The error to check\n@returns `true` if the error is an `HTTPError`, `false` otherwise\n\n@example\n```\nimport ky, {isHTTPError} from 'ky';\ntry {\n\tconst response = await ky.get('/api/data');\n} catch (error) {\n\tif (isHTTPError(error)) {\n\t\tconsole.log('HTTP error status:', error.response.status);\n\t}\n}\n```\n*/\nexport function isHTTPError<T = unknown>(error: unknown): error is HTTPError<T> {\n\treturn isErrorType(error, HTTPError);\n}\n\n/**\nType guard to check if an error is a `NetworkError`.\n\n@param error - The error to check\n@returns `true` if the error is a `NetworkError`, `false` otherwise\n\n@example\n```\nimport ky, {isNetworkError} from 'ky';\ntry {\n\tconst response = await ky.get('/api/data');\n} catch (error) {\n\tif (isNetworkError(error)) {\n\t\tconsole.log('Network error:', error.request.url);\n\t}\n}\n```\n*/\nexport function isNetworkError(error: unknown): error is NetworkError {\n\treturn isErrorType(error, NetworkError);\n}\n\n/**\nType guard to check if an error is a `TimeoutError`.\n\n@param error - The error to check\n@returns `true` if the error is a `TimeoutError`, `false` otherwise\n\n@example\n```\nimport ky, {isTimeoutError} from 'ky';\ntry {\n\tconst response = await ky.get('/api/data', { timeout: 1000 });\n} catch (error) {\n\tif (isTimeoutError(error)) {\n\t\tconsole.log('Request timed out:', error.request.url);\n\t}\n}\n```\n*/\nexport function isTimeoutError(error: unknown): error is TimeoutError {\n\treturn isErrorType(error, TimeoutError);\n}\n\n/**\nType guard to check if an error is a `ForceRetryError`.\n\n@param error - The error to check\n@returns `true` if the error is a `ForceRetryError`, `false` otherwise\n\n@example\n```\nimport ky, {isForceRetryError} from 'ky';\n\nconst api = ky.extend({\n\thooks: {\n\t\tbeforeRetry: [\n\t\t\t({error, retryCount}) => {\n\t\t\t\tif (isForceRetryError(error)) {\n\t\t\t\t\tconsole.log(`Forced retry #${retryCount}: ${error.code}`);\n\t\t\t\t}\n\t\t\t}\n\t\t]\n\t}\n});\n```\n*/\nexport function isForceRetryError(error: unknown): error is ForceRetryError {\n\treturn isErrorType(error, ForceRetryError);\n}\n"]}
+6
View File
@@ -0,0 +1,6 @@
export type Mutable<T> = {
-readonly [P in keyof T]: T[P];
};
export type ObjectEntries<T> = T extends ArrayLike<infer U> ? Array<[string, U]> : Array<{
[K in keyof T]: [K, T[K]];
}[keyof T]>;
+2
View File
@@ -0,0 +1,2 @@
export {};
//# sourceMappingURL=types.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../source/utils/types.ts"],"names":[],"mappings":"","sourcesContent":["export type Mutable<T> = {\n\t-readonly[P in keyof T]: T[P]\n};\n\nexport type ObjectEntries<T> = T extends ArrayLike<infer U>\n\t? Array<[string, U]>\n\t: Array<{[K in keyof T]: [K, T[K]]}[keyof T]>;\n"]}