@d1g1tal/transportr
Version:
JavaScript wrapper for the Fetch API and more...
1,172 lines (1,163 loc) • 48.6 kB
TypeScript
import { Subscription } from "@d1g1tal/subscribr";
import { MediaType } from "@d1g1tal/media-type";
/**
* A class that holds a status code and a status text, typically from a {@link Response}
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Response/status|Response.status
* @author D1g1talEntr0py <jason.dimeo@gmail.com>
*/
declare class ResponseStatus {
private readonly _code;
private readonly _text;
/**
*
* @param code The status code from the {@link Response}
* @param text The status text from the {@link Response}
*/
constructor(code: number, text: string);
/**
* Returns the status code from the {@link Response}
*
* @returns The status code.
*/
get code(): number;
/**
* Returns the status text from the {@link Response}.
*
* @returns The status text.
*/
get text(): string;
/**
* A String value that is used in the creation of the default string
* description of an object. Called by the built-in method {@link Object.prototype.toString}.
*
* @returns The default string description of this object.
*/
get [Symbol.toStringTag](): string;
/**
* tostring method for the class.
*
* @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString|Object.prototype.toString}
* @returns The status code and status text.
*/
toString(): string;
}
/**
* Defining a constant object with all the HTTP request headers.
*/
declare const HttpRequestHeader: {
/**
* Content-Types that are acceptable for the response. See Content negotiation. Permanent.
*
* @example
* <code>Accept: text/plain</code>
*/
readonly ACCEPT: "accept";
/**
* Character sets that are acceptable. Permanent.
*
* @example
* <code>Accept-Charset: utf-8</code>
*/
readonly ACCEPT_CHARSET: "accept-charset";
/**
* List of acceptable encodings. See HTTP compression. Permanent.
*
* @example
* <code>Accept-Encoding: gzip, deflate</code>
*/
readonly ACCEPT_ENCODING: "accept-encoding";
/**
* List of acceptable human languages for response. See Content negotiation. Permanent.
*
* @example
* <code>Accept-Language: en-US</code>
*/
readonly ACCEPT_LANGUAGE: "accept-language";
/**
* Authentication credentials for HTTP authentication. Permanent.
*
* @example
* <code>Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==</code>
*/
readonly AUTHORIZATION: "authorization";
/**
* Used to specify directives that must be obeyed by all caching mechanisms along the request-response chain.
* Permanent.
*
* @example
* <code>Cache-Control: no-cache</code>
*/
readonly CACHE_CONTROL: "cache-control";
/**
* Control options for the current connection and list of hop-by-hop request fields. Permanent.
*
* @example
* <code>Connection: keep-alive</code>
* <code>Connection: Upgrade</code>
*/
readonly CONNECTION: "connection";
/**
* An HTTP cookie previously sent by the server with Set-Cookie (below). Permanent: standard.
*
* @example
* <code>Cookie: $Version=1, Skin=new,</code>
*/
readonly COOKIE: "cookie";
/**
* The length of the request body in octets (8-bit bytes). Permanent.
*
* @example
* <code>Content-Length: 348</code>
*/
readonly CONTENT_LENGTH: "content-length";
/**
* A Base64-encoded binary MD5 sum of the content of the request body. Obsolete.
*
* @example
* <code>Content-MD5: Q2hlY2sgSW50ZWdyaXR5IQ==</code>
*/
readonly CONTENT_MD5: "content-md5";
/**
* The MIME type of the body of the request (used with POST and PUT requests). Permanent.
* <code>Content-Type: application/x-www-form-urlencoded</code>
*/
readonly CONTENT_TYPE: "content-type";
/**
* The date and time that the message was sent (in "HTTP-date" format as defined by RFC 7231 Date/Time Formats).
* Permanent.
*
* @example
* <code>Date: Tue, 15 Nov 1994 08:12:31 GMT</code>
*/
readonly DATE: "date";
/**
* The domain name of the server (for virtual hosting), and the TCP port number on which the server is listening. The
* port number may be omitted if the port is the standard port for the service requested. Permanent. Mandatory since
* HTTP/1.1.
*
* @example
* <code>Host: en.wikipedia.org:80</code>
* <code>Host: en.wikipedia.org</code>
*/
readonly HOST: "host";
/**
* Only perform the action if the client supplied entity matches the same entity on the server. This is mainly for
* methods like PUT to only update a resource if it has not been modified since the user last updated it. Permanent.
*
* @example
* <code>If-Match: "737060cd8c284d8af7ad3082f209582d"</code>
*/
readonly IF_MATCH: "if-match";
/**
* Allows a 304 Not Modified to be returned if content is unchanged. Permanent.
*
* @example
* <code>If-Modified-Since: Sat, 29 Oct 1994 19:43:31 GMT</code>
*/
readonly IF_MODIFIED_SINCE: "if-modified-since";
/**
* Allows a 304 Not Modified to be returned if content is unchanged, see HTTP ETag. Permanent.
*
* @example
* <code>If-None-Match: "737060cd8c284d8af7ad3082f209582d"</code>
*/
readonly IF_NONE_MATCH: "if-none-match";
/**
* If the entity is unchanged, send me the part(s) that I am missing, otherwise, send me the entire new entity.
* Permanent.
*
* @example
* <code>If-Range: "737060cd8c284d8af7ad3082f209582d"</code>
*/
readonly IF_RANGE: "if-range";
/**
* Only send the response if the entity has not been modified since a specific time. Permanent.
*
* @example
* <code>If-Unmodified-Since: Sat, 29 Oct 1994 19:43:31 GMT</code>
*/
readonly IF_UNMODIFIED_SINCE: "if-unmodified-since";
/**
* Limit the number of times the message can be forwarded through proxies or gateways. Permanent.
*
* @example
* <code>Max-Forwards: 10</code>
*/
readonly MAX_FORWARDS: "max-forwards";
/**
* Initiates a request for cross-origin resource sharing (asks server for an 'Access-Control-Allow-Origin' response
* field). Permanent: standard.
*
* @example
* <code>Origin: http://www.example-social-network.com</code>
*/
readonly ORIGIN: "origin";
/**
* Implementation-specific fields that may have various effects anywhere along the request-response chain. Permanent.
*
* @example
* <code>Pragma: no-cache</code>
*/
readonly PRAGMA: "pragma";
/**
* Authorization credentials for connecting to a proxy. Permanent.
*
* @example
* <code>Proxy-Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==</code>
*/
readonly PROXY_AUTHORIZATION: "proxy-authorization";
/**
* Request only part of an entity. Bytes are numbered from 0. See Byte serving. Permanent.
*
* @example
* <code>Range: bytes=500-999</code>
*/
readonly RANGE: "range";
/**
* This is the address of the previous web page from which a link to the currently requested page was followed. (The
* word "referrer" has been misspelled in the RFC as well as in most implementations to the point that it has become
* standard usage and is considered correct terminology). Permanent.
*
* @example
* <code>Referer: http://en.wikipedia.org/wiki/Main_Page</code>
*/
readonly REFERER: "referer";
/**
* The transfer encodings the user agent is willing to accept: the same values as for the response header field
* Transfer-Encoding can be used, plus the "trailers" value (related to the "chunked" transfer method) to notify the
* server it expects to receive additional fields in the trailer after the last, zero-sized, chunk. Permanent.
*
* @example
* <code>TE: trailers, deflate</code>
*/
readonly TE: "te";
/**
* The user agent string of the user agent. Permanent.
*
* @example
* <code>User-Agent: Mozilla/5.0 (X11, Linux x86_64, rv:12.0) Gecko/20100101 Firefox/21.0</code>
*/
readonly USER_AGENT: "user-agent";
/**
* Ask the server to upgrade to another protocol. Permanent.
*
* @example
* <code>Upgrade: HTTP/2.0, SHTTP/1.3, IRC/6.9, RTA/x11</code>
*/
readonly UPGRADE: "upgrade";
/**
* A general warning about possible problems with the entity body. Permanent.
*
* @example
* <code>Warning: 199 Miscellaneous warning</code>
*/
readonly WARNING: "warning";
/**
* mainly used to identify Ajax requests. Most JavaScript frameworks send this field with value of XMLHttpRequest.
*
* @example
* <code>X-Requested-With: XMLHttpRequest</code>
*/
readonly X_REQUESTED_WITH: "x-requested-with";
/**
* A de facto standard for identifying the originating IP address of a client connecting to a web server through an
* HTTP proxy or load balancer.
*
* @example
* <code>X-Forwarded-For: client1, proxy1, proxy2</code>
* <code>X-Forwarded-For: 129.78.138.66, 129.78.64.103</code>
*/
readonly X_FORWARDED_FOR: "x-forwarded-for";
/**
* A de facto standard for identifying the original host requested by the client in the Host HTTP request header, since
* the host name and/or port of the reverse proxy (load balancer) may differ from the origin server handling the
* request.
*
* @example
* <code>X-Forwarded-Host: en.wikipedia.org:80</code>
* <code>X-Forwarded-Host: en.wikipedia.org</code>
*/
readonly X_FORWARDED_HOST: "x-forwarded-host";
/**
* A de facto standard for identifying the originating protocol of an HTTP request, since a reverse proxy (load
* balancer) may communicate with a web server using HTTP even if the request to the reverse proxy is HTTPS. An
* alternative form of the header (X-ProxyUser-Ip) is used by Google clients talking to Google servers.
*
* @example
* <code>X-Forwarded-Proto: https</code>
*/
readonly X_FORWARDED_PROTO: "x-forwarded-proto";
};
/**
* A collection of some of the available HTTP media types.
* @see {@link https://www.iana.org/assignments/media-types/media-types.xhtml | IANA Media Types}
*/
declare const HttpMediaType: {
/** Advanced Audio Coding (AAC) */
readonly AAC: "audio/aac";
/** AbiWord */
readonly ABW: "application/x-abiword";
/** Archive document (multiple files embedded) */
readonly ARC: "application/x-freearc";
/** AVIF image */
readonly AVIF: "image/avif";
/** Audio Video Interleave (AVI) */
readonly AVI: "video/x-msvideo";
/** Amazon Kindle eBook format */
readonly AZW: "application/vnd.amazon.ebook";
/** Binary Data */
readonly BIN: "application/octet-stream";
/** Windows OS/2 Bitmap Graphics */
readonly BMP: "image/bmp";
/** Bzip Archive */
readonly BZIP: "application/x-bzip";
/** Bzip2 Archive */
readonly BZIP2: "application/x-bzip2";
/** CD audio */
readonly CDA: "application/x-cdf";
/** C Shell Script */
readonly CSH: "application/x-csh";
/** Cascading Style Sheets (CSS) */
readonly CSS: "text/css";
/** Comma-Separated Values */
readonly CSV: "text/csv";
/** Microsoft Office Word Document */
readonly DOC: "application/msword";
/** Microsoft Office Word Document (OpenXML) */
readonly DOCX: "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
/** Microsoft Embedded OpenType */
readonly EOT: "application/vnd.ms-fontobject";
/** Electronic Publication (EPUB) */
readonly EPUB: "application/epub+zip";
/** GZip Compressed Archive */
readonly GZIP: "application/gzip";
/** Graphics Interchange Format */
readonly GIF: "image/gif";
/** HyperText Markup Language (HTML) */
readonly HTML: "text/html";
/** Icon Format */
readonly ICO: "image/vnd.microsoft.icon";
/** iCalendar Format */
readonly ICS: "text/calendar";
/** Java Archive (JAR) */
readonly JAR: "application/java-archive";
/** JPEG Image */
readonly JPEG: "image/jpeg";
/** JavaScript */
readonly JAVA_SCRIPT: "text/javascript";
/** JavaScript Object Notation Format (JSON) */
readonly JSON: "application/json";
/** JavaScript Object Notation LD Format */
readonly JSON_LD: "application/ld+json";
/** JavaScript Object Notation (JSON) Merge Patch */
readonly JSON_MERGE_PATCH: "application/merge-patch+json";
/** Musical Instrument Digital Interface (MIDI) */
readonly MID: "audio/midi";
/** Musical Instrument Digital Interface (MIDI) */
readonly X_MID: "audio/x-midi";
/** MP3 Audio */
readonly MP3: "audio/mpeg";
/** MPEG-4 Audio */
readonly MP4A: "audio/mp4";
/** MPEG-4 Video */
readonly MP4: "video/mp4";
/** MPEG Video */
readonly MPEG: "video/mpeg";
/** Apple Installer Package */
readonly MPKG: "application/vnd.apple.installer+xml";
/** OpenDocument Presentation Document */
readonly ODP: "application/vnd.oasis.opendocument.presentation";
/** OpenDocument Spreadsheet Document */
readonly ODS: "application/vnd.oasis.opendocument.spreadsheet";
/** OpenDocument Text Document */
readonly ODT: "application/vnd.oasis.opendocument.text";
/** Ogg Audio */
readonly OGA: "audio/ogg";
/** Ogg Video */
readonly OGV: "video/ogg";
/** Ogg */
readonly OGX: "application/ogg";
/** Opus audio */
readonly OPUS: "audio/opus";
/** OpenType Font File */
readonly OTF: "font/otf";
/** Portable Network Graphics (PNG) */
readonly PNG: "image/png";
/** Adobe Portable Document Format */
readonly PDF: "application/pdf";
/** Hypertext Preprocessor (Personal Home Page) */
readonly PHP: "application/x-httpd-php";
/** Microsoft PowerPoint */
readonly PPT: "application/vnd.ms-powerpoint";
/** Microsoft Office Presentation (OpenXML) */
readonly PPTX: "application/vnd.openxmlformats-officedocument.presentationml.presentation";
/** RAR Archive */
readonly RAR: "application/vnd.rar";
/** Rich Text Format */
readonly RTF: "application/rtf";
/** Bourne Shell Script */
readonly SH: "application/x-sh";
/** Scalable Vector Graphics (SVG) */
readonly SVG: "image/svg+xml";
/** Tape Archive (TAR) */
readonly TAR: "application/x-tar";
/** Tagged Image File Format (TIFF) */
readonly TIFF: "image/tiff";
/** MPEG transport stream */
readonly TRANSPORT_STREAM: "video/mp2t";
/** TrueType Font */
readonly TTF: "font/ttf";
/** Text, (generally ASCII or ISO 8859-n) */
readonly TEXT: "text/plain";
/** Microsoft Visio */
readonly VSD: "application/vnd.visio";
/** Waveform Audio Format (WAV) */
readonly WAV: "audio/wav";
/** Open Web Media Project - Audio */
readonly WEBA: "audio/webm";
/** Open Web Media Project - Video */
readonly WEBM: "video/webm";
/** WebP Image */
readonly WEBP: "image/webp";
/** Web Open Font Format */
readonly WOFF: "font/woff";
/** Web Open Font Format */
readonly WOFF2: "font/woff2";
/** Form - Encoded */
readonly FORM: "application/x-www-form-urlencoded";
/** Multipart FormData */
readonly MULTIPART_FORM_DATA: "multipart/form-data";
/** XHTML - The Extensible HyperText Markup Language */
readonly XHTML: "application/xhtml+xml";
/** Microsoft Excel Document */
readonly XLS: "application/vnd.ms-excel";
/** Microsoft Office Spreadsheet Document (OpenXML) */
readonly XLSX: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
/** Extensible Markup Language (XML) */
readonly XML: "application/xml";
/** XML User Interface Language (XUL) */
readonly XUL: "application/vnd.mozilla.xul+xml";
/** Zip Archive */
readonly ZIP: "application/zip";
/** 3GPP audio/video container */
readonly '3GP': "video/3gpp";
/** 3GPP2 audio/video container */
readonly '3G2': "video/3gpp2";
/** 7-Zip Archive */
readonly '7Z': "application/x-7z-compressed";
};
type Function<P = any, R = unknown> = (...args: P[]) => R;
type JsonPrimitive = string | number | boolean | null;
type JsonArray<T = any> = T extends any ? Array<JsonValue<T>> : never;
type JsonObject<T = any> = T extends any ? {
[K in keyof T as JsonValue<T[K]> extends never ? never : K]: JsonValue<T[K]>;
} : Record<string, any>;
type JsonValue<T = any> = T extends JsonPrimitive ? T : T extends {
toJSON: () => infer R;
} ? R : T extends Function | undefined ? never : T extends Array<infer U> ? JsonArray<U> : T extends Record<string, any> ? JsonObject<T> : Json;
type Json = JsonPrimitive | JsonObject | JsonArray;
type JsonString<T = unknown> = string & {
source: T;
};
/** The expected response body types returned from a fetch handler. */
type ResponseBody = Json | Document | DocumentFragment | HTMLImageElement | Blob | ArrayBuffer | FormData | string | ReadableStream<Uint8Array> | void | null;
/** Timing information for a request lifecycle. */
type RequestTiming = {
/** Timestamp when the request started (ms since epoch). */
start: number;
/** Timestamp when the response was received (ms since epoch). */
end: number;
/** Total duration in milliseconds. */
duration: number;
};
/** Options for constructing an {@link HttpError}. */
type HttpErrorOptions = {
message?: string;
cause?: Error;
entity?: ResponseBody;
/** The request URL. */
url?: URL;
/** The HTTP method used. */
method?: string;
/** Request timing information. */
timing?: RequestTiming;
};
/**
* An error that represents an HTTP error response.
* @author D1g1talEntr0py <jason.dimeo@gmail.com>
*/
declare class HttpError extends Error {
private readonly _entity;
private readonly responseStatus;
private readonly _url;
private readonly _method;
private readonly _timing;
/**
* Creates an instance of HttpError.
* @param status The status code and status text of the {@link Response}.
* @param httpErrorOptions The http error options.
*/
constructor(status: ResponseStatus, { message, cause, entity, url, method, timing }?: HttpErrorOptions);
/**
* It returns the value of the private variable #entity.
* @returns The entity property of the class.
*/
get entity(): ResponseBody;
/**
* It returns the status code of the {@link Response}.
* @returns The status code of the {@link Response}.
*/
get statusCode(): number;
/**
* It returns the status text of the {@link Response}.
* @returns The status code and status text of the {@link Response}.
*/
get statusText(): string;
/**
* The request URL that caused the error.
* @returns The URL or undefined.
*/
get url(): URL | undefined;
/**
* The HTTP method that was used for the failed request.
* @returns The method string or undefined.
*/
get method(): string | undefined;
/**
* Timing information for the failed request.
* @returns The timing object or undefined.
*/
get timing(): RequestTiming | undefined;
/**
* A String value representing the name of the error.
* @returns The name of the error.
*/
get name(): string;
/**
* A String value that is used in the creation of the default string
* description of an object. Called by the built-in method {@link Object.prototype.toString}.
* @returns The default string description of this object.
*/
get [Symbol.toStringTag](): string;
}
type Prettify<T> = T extends infer U ? {
[K in keyof U]: U[K];
} : never;
type LiteralUnion<T> = T | (string & {});
interface TypedResponse<T> extends Response {
json: () => Promise<T>;
}
type RequestBody = BodyInit | JsonObject;
type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array | BigInt64Array | BigUint64Array;
type RequestMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'HEAD' | 'OPTIONS' | 'CONNECT' | 'TRACE';
type RequestBodyMethod = Extract<RequestMethod, 'POST' | 'PUT' | 'PATCH' | 'DELETE'>;
type RequestNoBodyMethod = Exclude<RequestMethod, RequestBodyMethod>;
type RequestHeaders = Prettify<TypedHeaders & {
[K in Exclude<typeof HttpRequestHeader[keyof typeof HttpRequestHeader], keyof TypedHeaders>]?: string;
} & HeadersInit>;
type SearchParameters = URLSearchParams | string | string[][] | Record<string, string | number | boolean>;
type AuthorizationScheme = 'Basic' | 'Bearer' | 'Digest' | 'HOBA' | 'Mutual' | 'Negotiate' | 'OAuth' | 'SCRAM-SHA-1' | 'SCRAM-SHA-256' | 'vapid';
type ResponseHandler<T extends ResponseBody = ResponseBody> = (response: Response) => Promise<T>;
type RequestLifecycleEvent = 'configured' | 'success' | 'error' | 'aborted' | 'timeout' | 'retry' | 'complete' | 'all-complete';
type RequestEventHandler = (event: Event, data: unknown) => void;
type Entry<K, V> = [K, V];
type Entries<K, V> = Entry<K, V>[];
type ReadOnlyEntries<K, V> = readonly Entry<K, V>[];
type AbortSignalEvent = Event & {
target: AbortSignal;
};
type AbortEvent = CustomEvent<{
cause: 'AbortError';
}>;
type TimeoutEvent = CustomEvent<{
cause: 'TimeoutError';
}>;
type AbortConfiguration = {
signal?: AbortSignal | null;
timeout?: number;
};
type MediaTypeValues = LiteralUnion<typeof HttpMediaType[keyof typeof HttpMediaType]>;
type TypedHeaders = {
[HttpRequestHeader.AUTHORIZATION]?: `${AuthorizationScheme} ${string}` | AuthorizationScheme;
[HttpRequestHeader.ACCEPT]?: MediaTypeValues;
[HttpRequestHeader.CONTENT_TYPE]?: MediaTypeValues;
};
type EventRegistration = Subscription;
type MethodBody = {
method?: RequestBodyMethod;
body?: RequestBody;
} | {
method?: RequestNoBodyMethod;
body?: never;
};
type RequestOptions = Prettify<{
/** A Headers object, an object literal, or an array of two-item arrays to set request's headers. */
headers?: RequestHeaders;
searchParams?: SearchParameters;
timeout?: number;
global?: boolean;
/** Lifecycle hooks for this request. Instance and global hooks run first, then per-request hooks. */
hooks?: HookOptions;
/** Retry configuration. A number sets the retry limit; an object provides fine-grained control. */
retry?: number | RetryOptions;
/** When true, identical in-flight GET/HEAD requests share a single fetch. Defaults to false. */
dedupe?: boolean;
/** XSRF/CSRF protection. When set (or true), reads a cookie and sets a request header. */
xsrf?: boolean | XsrfOptions;
} & Omit<RequestInit, 'headers'> & MethodBody>;
/** Configuration for retry behavior on failed requests. */
type RetryOptions = {
/** Maximum number of retry attempts. Defaults to 0 (no retries). */
limit?: number;
/** HTTP status codes that trigger a retry. Defaults to [408, 413, 429, 500, 502, 503, 504]. */
statusCodes?: number[];
/** HTTP methods allowed to retry. Defaults to ['GET', 'PUT', 'HEAD', 'DELETE', 'OPTIONS']. */
methods?: RequestMethod[];
/** Delay in ms before the first retry, or a function receiving the attempt number (1-based) returning ms. Defaults to 300. */
delay?: number | ((attempt: number) => number);
/** Multiplier applied to delay after each attempt. Defaults to 2. */
backoffFactor?: number;
};
/** Configuration for XSRF/CSRF token handling. */
type XsrfOptions = {
/** The name of the cookie to read the token from. Defaults to 'XSRF-TOKEN'. */
cookieName?: string;
/** The request header name to set the token on. Defaults to 'X-XSRF-TOKEN'. */
headerName?: string;
};
/** Hook called before each request. Can modify the request options. */
type BeforeRequestHook = (options: RequestOptions, url: URL) => RequestOptions | void | Promise<RequestOptions | void>;
/** Hook called after each successful response. Can modify or replace the response. */
type AfterResponseHook = (response: Response, options: RequestOptions) => Response | void | Promise<Response | void>;
/** Hook called before an error is thrown. Can transform the error. */
type BeforeErrorHook = (error: HttpError) => HttpError | void | Promise<HttpError | void>;
/** Configuration for request lifecycle hooks. */
type HookOptions = {
beforeRequest?: BeforeRequestHook[];
afterResponse?: AfterResponseHook[];
beforeError?: BeforeErrorHook[];
};
/** Fully resolved retry configuration with all defaults applied. */
type NormalizedRetryOptions = Required<RetryOptions>;
/** Options for the internal publish helper. */
type PublishOptions = {
name: string;
event?: Event;
data?: unknown;
global?: boolean;
};
declare const endsWithSlashRegEx: RegExp;
/** Default XSRF cookie name */
declare const XSRF_COOKIE_NAME = "XSRF-TOKEN";
/** Default XSRF header name */
declare const XSRF_HEADER_NAME = "X-XSRF-TOKEN";
type MediaTypeKey = 'PNG' | 'TEXT' | 'JSON' | 'HTML' | 'JAVA_SCRIPT' | 'CSS' | 'XML' | 'BIN';
declare const mediaTypes: {
[key in MediaTypeKey]: MediaType;
};
declare const defaultMediaType: string;
/** Constant object for caching policies */
declare const RequestCachingPolicy: {
readonly DEFAULT: "default";
readonly FORCE_CACHE: "force-cache";
readonly NO_CACHE: "no-cache";
readonly NO_STORE: "no-store";
readonly ONLY_IF_CACHED: "only-if-cached";
readonly RELOAD: "reload";
};
/** Constant object for signal events */
declare const SignalEvents: {
readonly ABORT: "abort";
readonly TIMEOUT: "timeout";
};
/** Constant object for signal errors */
declare const SignalErrors: {
readonly ABORT: "AbortError";
readonly TIMEOUT: "TimeoutError";
};
/** Options for adding event listeners */
declare const eventListenerOptions: AddEventListenerOptions;
/**
* Creates a new custom abort event.
* @returns A new AbortEvent instance.
*/
declare const abortEvent: () => AbortEvent;
/**
* Creates a new custom timeout event.
* @returns A new TimeoutEvent instance.
*/
declare const timeoutEvent: () => TimeoutEvent;
/** Array of request body methods */
declare const requestBodyMethods: ReadonlyArray<RequestMethod>;
/** Response status for internal server error */
declare const internalServerError: ResponseStatus;
/** Response status for aborted request */
declare const aborted: ResponseStatus;
/** Response status for timed out request */
declare const timedOut: ResponseStatus;
/** Default HTTP status codes that trigger a retry */
declare const retryStatusCodes: ReadonlyArray<number>;
/** Default HTTP methods allowed to retry (idempotent methods only) */
declare const retryMethods: ReadonlyArray<RequestMethod>;
/** Default delay in ms before the first retry */
declare const retryDelay: number;
/** Default backoff factor applied after each retry attempt */
declare const retryBackoffFactor: number;
/** Constant object for request events */
declare const RequestEvent: {
readonly CONFIGURED: "configured";
readonly SUCCESS: "success";
readonly ERROR: "error";
readonly ABORTED: "aborted";
readonly TIMEOUT: "timeout";
readonly RETRY: "retry";
readonly COMPLETE: "complete";
readonly ALL_COMPLETE: "all-complete";
};
type RequestEvent = (typeof RequestEvent)[keyof typeof RequestEvent];
/**
* A wrapper around the fetch API that makes it easier to make HTTP requests.
* @author D1g1talEntr0py <jason.dimeo@gmail.com>
*/
declare class Transportr {
private readonly _baseUrl;
private readonly _options;
private readonly subscribr;
private readonly hooks;
private static globalSubscribr;
private static globalHooks;
private static signalControllers;
/** Map of in-flight deduplicated requests keyed by URL + method */
private static inflightRequests;
/** Cache for parsed MediaType instances to avoid re-parsing the same content-type strings */
private static mediaTypeCache;
private static contentTypeHandlers;
/**
* Create a new Transportr instance with the provided location or origin and context path.
*
* @param url The URL for {@link fetch} requests.
* @param options The default {@link RequestOptions} for this instance.
*/
constructor(url?: URL | string | RequestOptions, options?: RequestOptions);
/** Credentials Policy */
static readonly CredentialsPolicy: {
readonly INCLUDE: "include";
readonly OMIT: "omit";
readonly SAME_ORIGIN: "same-origin";
};
/** Request Modes */
static readonly RequestModes: {
readonly CORS: "cors";
readonly NAVIGATE: "navigate";
readonly NO_CORS: "no-cors";
readonly SAME_ORIGIN: "same-origin";
};
/** Request Priorities */
static readonly RequestPriorities: {
readonly HIGH: "high";
readonly LOW: "low";
readonly AUTO: "auto";
};
/** Redirect Policies */
static readonly RedirectPolicies: {
readonly ERROR: "error";
readonly FOLLOW: "follow";
readonly MANUAL: "manual";
};
/** Referrer Policies */
static readonly ReferrerPolicy: {
readonly NO_REFERRER: "no-referrer";
readonly NO_REFERRER_WHEN_DOWNGRADE: "no-referrer-when-downgrade";
readonly ORIGIN: "origin";
readonly ORIGIN_WHEN_CROSS_ORIGIN: "origin-when-cross-origin";
readonly SAME_ORIGIN: "same-origin";
readonly STRICT_ORIGIN: "strict-origin";
readonly STRICT_ORIGIN_WHEN_CROSS_ORIGIN: "strict-origin-when-cross-origin";
readonly UNSAFE_URL: "unsafe-url";
};
/** Request Events */
static readonly RequestEvents: typeof RequestEvent;
/** Default Request Options */
private static readonly defaultRequestOptions;
/**
* Returns a {@link EventRegistration} used for subscribing to global events.
*
* @param event The event to subscribe to.
* @param handler The event handler.
* @param context The context to bind the handler to.
* @returns A new {@link EventRegistration} instance.
*/
static register(event: RequestEvent, handler: RequestEventHandler, context?: unknown): EventRegistration;
/**
* Removes a {@link EventRegistration} from the global event handler.
*
* @param eventRegistration The {@link EventRegistration} to remove.
* @returns True if the {@link EventRegistration} was removed, false otherwise.
*/
static unregister(eventRegistration: EventRegistration): boolean;
/**
* Aborts all active requests.
* This is useful for when the user navigates away from the current page.
* This will also clear the {@link Transportr#signalControllers} set.
*/
static abortAll(): void;
/**
* Registers a custom content-type response handler.
* The handler will be matched against response content-type headers using MediaType matching.
* New handlers are prepended so they take priority over built-in handlers.
*
* @param contentType The content-type string to match (e.g. 'application/pdf', 'text', 'csv').
* @param handler The response handler function.
*/
static registerContentTypeHandler(contentType: string, handler: ResponseHandler): void;
/**
* Removes a previously registered content-type response handler.
*
* @param contentType The content-type string to remove.
* @returns True if the handler was found and removed, false otherwise.
*/
static unregisterContentTypeHandler(contentType: string): boolean;
/**
* Registers global lifecycle hooks that run on all requests from all instances.
* Global hooks execute before instance and per-request hooks.
*
* @param hooks The hooks to register globally.
*/
static addHooks(hooks: HookOptions): void;
/**
* Removes all global lifecycle hooks.
*/
static clearHooks(): void;
/**
* Tears down all global state: aborts in-flight requests, clears global event subscriptions,
* hooks, in-flight deduplication map, and media type cache (retaining built-in entries).
*/
static unregisterAll(): void;
/**
* It returns the base {@link URL} for the API.
*
* @returns The baseUrl property.
*/
get baseUrl(): URL;
/**
* Registers an event handler with a {@link Transportr} instance.
*
* @param event The name of the event to listen for.
* @param handler The function to call when the event is triggered.
* @param context The context to bind to the handler.
* @returns An object that can be used to remove the event handler.
*/
register(event: RequestEvent, handler: RequestEventHandler, context?: unknown): EventRegistration;
/**
* Unregisters an event handler from a {@link Transportr} instance.
*
* @param eventRegistration The event registration to remove.
* @returns True if the {@link EventRegistration} was removed, false otherwise.
*/
unregister(eventRegistration: EventRegistration): boolean;
/**
* Registers instance-level lifecycle hooks that run on all requests from this instance.
* Instance hooks execute after global hooks but before per-request hooks.
*
* @param hooks The hooks to register on this instance.
* @returns This instance for method chaining.
*/
addHooks(hooks: HookOptions): this;
/**
* Removes all instance-level lifecycle hooks.
* @returns This instance for method chaining.
*/
clearHooks(): this;
/**
* Tears down this instance: clears all instance subscriptions and hooks.
* The instance should not be used after calling this method.
*/
destroy(): void;
/**
* This function returns a promise that resolves to the result of a request to the specified path with
* the specified options, where the method is GET.
*
* @async
* @param path The path to the resource you want to get.
* @param options The options for the request.
* @returns A promise that resolves to the response of the request.
*/
get<T extends ResponseBody = ResponseBody>(path?: string | RequestOptions, options?: RequestOptions): Promise<T | undefined>;
/**
* This function makes a POST request to the given path with the given body and options.
*
* @async
* @template T The expected response type (defaults to ResponseBody)
* @param path The path to the endpoint you want to call.
* @param options The options for the request.
* @returns A promise that resolves to the response body.
*/
post<T extends ResponseBody = ResponseBody>(path?: string | RequestOptions, options?: RequestOptions): Promise<T | undefined>;
/**
* This function returns a promise that resolves to the result of a request to the specified path with
* the specified options, where the method is PUT.
*
* @async
* @template T The expected response type (defaults to ResponseBody)
* @param path The path to the endpoint you want to call.
* @param options The options for the request.
* @returns The return value of the #request method.
*/
put<T extends ResponseBody = ResponseBody>(path?: string | RequestOptions, options?: RequestOptions): Promise<T | undefined>;
/**
* It takes a path and options, and returns a request with the method set to PATCH.
*
* @async
* @template T The expected response type (defaults to ResponseBody)
* @param path The path to the endpoint you want to hit.
* @param options The options for the request.
* @returns A promise that resolves to the response of the request.
*/
patch<T extends ResponseBody = ResponseBody>(path?: string | RequestOptions, options?: RequestOptions): Promise<T | undefined>;
/**
* It takes a path and options, and returns a request with the method set to DELETE.
*
* @async
* @param path The path to the resource you want to access.
* @param options The options for the request.
* @returns The result of the request.
*/
delete<T extends ResponseBody = ResponseBody>(path?: string | RequestOptions, options?: RequestOptions): Promise<T | undefined>;
/**
* Returns the response headers of a request to the given path.
*
* @async
* @param path The path to the resource you want to access.
* @param options The options for the request.
* @returns A promise that resolves to the response object.
*/
head<T extends ResponseBody = ResponseBody>(path?: string | RequestOptions, options?: RequestOptions): Promise<T | undefined>;
/**
* It returns a promise that resolves to the allowed request methods for the given resource path.
*
* @async
* @param path The path to the resource.
* @param options The options for the request.
* @returns A promise that resolves to an array of allowed request methods for this resource.
*/
options(path?: string | RequestOptions, options?: RequestOptions): Promise<string[] | undefined>;
/**
* It takes a path and options, and makes a request to the server
* @async
* @param path The path to the endpoint you want to hit.
* @param options The options for the request.
* @returns The return value of the function is the return value of the function that is passed to the `then` method of the promise returned by the `fetch` method.
* @throws {HttpError} If an error occurs during the request.
*/
request<T = unknown>(path?: string | RequestOptions, options?: RequestOptions): Promise<TypedResponse<T>>;
/**
* It gets the JSON representation of the resource at the given path.
*
* @async
* @template T The expected JSON response type (defaults to JsonObject)
* @param path The path to the resource.
* @param options The options object to pass to the request.
* @returns A promise that resolves to the response body as a typed JSON value.
*/
getJson(path?: string | RequestOptions, options?: RequestOptions): Promise<Json | undefined>;
/**
* It gets the XML representation of the resource at the given path.
*
* @async
* @param path The path to the resource you want to get.
* @param options The options for the request.
* @returns The result of the function call to #get.
*/
getXml(path?: string | RequestOptions, options?: RequestOptions): Promise<Document | undefined>;
/**
* Get the HTML content of the specified path.
* When a selector is provided, returns only the first matching element from the parsed document.
*
* @async
* @param path The path to the resource.
* @param options The options for the request.
* @param selector An optional CSS selector to extract a specific element from the parsed HTML.
* @returns A promise that resolves to a Document, an Element (if selector matched), or void.
*/
getHtml(path?: string | RequestOptions, options?: RequestOptions, selector?: string): Promise<Document | Element | null | undefined>;
/**
* It returns a promise that resolves to the HTML fragment at the given path.
* When a selector is provided, returns only the first matching element from the parsed fragment.
*
* @async
* @param path The path to the resource.
* @param options The options for the request.
* @param selector An optional CSS selector to extract a specific element from the parsed fragment.
* @returns A promise that resolves to a DocumentFragment, an Element (if selector matched), or void.
*/
getHtmlFragment(path?: string | RequestOptions, options?: RequestOptions, selector?: string): Promise<DocumentFragment | Element | null | undefined>;
/**
* It gets a script from the server, and appends the script to the Document HTMLHeadElement
* @param path The path to the script.
* @param options The options for the request.
* @returns A promise that resolves to void.
*/
getScript(path?: string | RequestOptions, options?: RequestOptions): Promise<void>;
/**
* Gets a stylesheet from the server, and adds it as a Blob URL.
* @param path The path to the stylesheet.
* @param options The options for the request.
* @returns A promise that resolves to void.
*/
getStylesheet(path?: string | RequestOptions, options?: RequestOptions): Promise<void>;
/**
* It returns a blob from the specified path.
* @param path The path to the resource.
* @param options The options for the request.
* @returns A promise that resolves to a Blob or void.
*/
getBlob(path?: string | RequestOptions, options?: RequestOptions): Promise<Blob | undefined>;
/**
* It returns a promise that resolves to an `HTMLImageElement`.
* The object URL created to load the image is automatically revoked to prevent memory leaks.
* Works in both browser and Node.js (via JSDOM) environments.
* @param path The path to the image.
* @param options The options for the request.
* @returns A promise that resolves to an `HTMLImageElement` or `void`.
*/
getImage(path?: string, options?: RequestOptions): Promise<HTMLImageElement | undefined>;
/**
* It gets a buffer from the specified path
* @param path The path to the resource.
* @param options The options for the request.
* @returns A promise that resolves to an ArrayBuffer or void.
*/
getBuffer(path?: string | RequestOptions, options?: RequestOptions): Promise<ArrayBuffer | undefined>;
/**
* It returns a readable stream of the response body from the specified path.
* @param path The path to the resource.
* @param options The options for the request.
* @returns A promise that resolves to a ReadableStream, null, or void.
*/
getStream(path?: string | RequestOptions, options?: RequestOptions): Promise<ReadableStream<Uint8Array> | null | undefined>;
/**
* Handles a GET request.
* @async
* @param path The path to the resource.
* @param userOptions The user options for the request.
* @param options The options for the request.
* @param responseHandler The response handler for the request.
* @returns A promise that resolves to the response body or void.
*/
private _get;
/**
* It processes the request options and returns a new object with the processed options.
* @param path The path to the resource.
* @param processedRequestOptions The user options for the request.
* @returns A new object with the processed options.
*/
private _request;
/**
* Normalizes a retry option into a full RetryOptions object.
* @param retry The retry option from request options.
* @returns Normalized retry configuration.
*/
private static normalizeRetryOptions;
/**
* Waits for the appropriate delay before a retry attempt.
* @param config The retry configuration.
* @param attempt The current attempt number (1-based).
* @returns A promise that resolves after the delay.
*/
private static retryDelay;
/**
* It returns a response handler based on the content type of the response.
* @param path The path to the resource.
* @param userOptions The user options for the request.
* @param options The options for the request.
* @param responseHandler The response handler for the request.
* @returns A response handler function.
*/
private execute;
/**
* Creates a new set of options for a request.
* @param options The user options for the request.
* @param userOptions The default options for the request.
* @returns A new set of options for the request.
*/
private static createOptions;
/**
* Merges user and request headers into the target Headers object.
* @param target The target Headers object.
* @param headerSources Variable number of header sources to merge.
* @returns The merged Headers object.
*/
private static mergeHeaders;
/**
* Merges user and request search parameters into the target URLSearchParams object.
* @param target The target URLSearchParams object.
* @param sources The search parameters to merge.
* @returns The merged URLSearchParams object.
*/
private static mergeSearchParams;
/**
* Processes request options by merging user, instance, and method-specific options.
* This method optimizes performance by using cached instance options and performing
* shallow merges where possible instead of deep object cloning.
* @param userOptions The user-provided options for the request.
* @param options Additional method-specific options.
* @returns Processed request options with signal controller and global flag.
*/
private processRequestOptions;
/**
* Gets the base URL from a URL or string.
* @param url The URL or string to parse.
* @returns The base URL.
*/
private static getBaseUrl;
/**
* Parses a content-type string into a MediaType instance with caching.
* This method caches parsed MediaType instances to avoid re-parsing the same content-type strings,
* which significantly improves performance for repeated requests with the same content types.
* @param contentType The content-type string to parse.
* @returns The parsed MediaType instance, or undefined if parsing fails.
*/
private static getOrParseMediaType;
/**
* Creates a new URL with the given path and search parameters.
* @param url The base URL.
* @param path The path to append to the base URL.
* @param searchParams The search parameters to append to the URL.
* @returns A new URL with the given path and search parameters.
*/
private static createUrl;
/**
* It generates a ResponseStatus object from an error name and a Response object.
* @param errorName The name of the error.
* @param response The Response object.
* @returns A ResponseStatus object.
*/
private static generateResponseStatusFromError;
/**
* Handles an error that occurs during a request.
* @param path The path of the request.
* @param response The Response object.
* @param options Additional error context including cause, entity, url, method, and timing.
* @param requestOptions The original request options that led to the error, used for hooks context.
* @returns An HttpError object.
*/
private handleError;
/**
* Publishes an event to the global and instance event handlers.
* @param eventObject The event object to publish.
*/
private publish;
/**
* It returns a response handler based on the content type of the response.
* @param contentType The content type of the response.
* @returns A response handler function.
*/
private getResponseHandler;
/**
* A string representation of the Transportr instance.
* @returns The string 'Transportr'.
*/
get [Symbol.toStringTag](): string;
}
export { HttpError, HttpErrorOptions, HttpMediaType, HttpRequestHeader, Json, JsonArray, JsonObject, JsonPrimitive, JsonString, JsonValue, RequestCachingPolicy, RequestEvent, RequestTiming, ResponseBody, ResponseStatus, SignalErrors, SignalEvents, Transportr, XSRF_COOKIE_NAME, XSRF_HEADER_NAME, abortEvent, aborted, defaultMediaType, endsWithSlashRegEx, eventListenerOptions, internalServerError, mediaTypes, requestBodyMethods, retryBackoffFactor, retryDelay, retryMethods, retryStatusCodes, timedOut, timeoutEvent };
export type { AbortConfiguration, AbortEvent, AbortSignalEvent, AfterResponseHook, BeforeErrorHook, BeforeRequestHook, Entries, EventRegistration, HookOptions, NormalizedRetryOptions, PublishOptions, ReadOnlyEntries, RequestBody, RequestBodyMethod, RequestEventHandler, RequestHeaders, RequestLifecycleEvent, RequestMethod, RequestOptions, ResponseHandler, RetryOptions, SearchParameters, TimeoutEvent, TypedArray, TypedResponse, XsrfOptions };