create-request 0.0.1-beta.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,257 @@
1
+ import { type HttpMethod, type RedirectMode, type RequestMode, type RequestPriority, CredentialsPolicy } from "./enums";
2
+ import { type ResponsePromise } from "./ResponseWrapper";
3
+ import type { RequestOptions, RetryCallback, CookiesRecord, CookieOptions } from "./types";
4
+ import type { CacheOptions } from "./types/cache";
5
+ import { CacheManager } from "./utils/CacheManager";
6
+ /**
7
+ * Base class with common functionality for all request types
8
+ * Provides the core request building and execution capabilities.
9
+ */
10
+ export declare abstract class BaseRequest {
11
+ protected abstract method: HttpMethod;
12
+ protected requestOptions: RequestOptions;
13
+ protected abortController?: AbortController;
14
+ protected queryParams: URLSearchParams;
15
+ protected autoApplyCsrfProtection: boolean;
16
+ protected cacheManager?: CacheManager;
17
+ protected cacheEnabled: boolean;
18
+ constructor();
19
+ /**
20
+ * Add multiple HTTP headers to the request
21
+ *
22
+ * @param headers - Key-value pairs of header names and values
23
+ * @returns The request instance for chaining
24
+ *
25
+ * @example
26
+ * request.withHeaders({
27
+ * 'Accept': 'application/json',
28
+ * 'X-Custom-Header': 'value'
29
+ * });
30
+ */
31
+ withHeaders(headers: Record<string, string>): this;
32
+ /**
33
+ * Add a single HTTP header to the request
34
+ *
35
+ * @param key - The header name
36
+ * @param value - The header value
37
+ * @returns The request instance for chaining
38
+ *
39
+ * @example
40
+ * request.withHeader('Accept', 'application/json');
41
+ */
42
+ withHeader(key: string, value: string): this;
43
+ /**
44
+ * Set a timeout for the request
45
+ * If the request takes longer than the specified timeout, it will be aborted.
46
+ *
47
+ * @param timeout - The timeout in milliseconds
48
+ * @returns The request instance for chaining
49
+ * @throws Error if timeout is not a positive number
50
+ *
51
+ * @example
52
+ * request.withTimeout(5000); // 5 seconds timeout
53
+ */
54
+ withTimeout(timeout: number): this;
55
+ /**
56
+ * Configure automatic retry behavior for failed requests
57
+ *
58
+ * @param retries - Number of retry attempts before failing
59
+ * @returns The request instance for chaining
60
+ * @throws Error if retries is not a non-negative integer
61
+ *
62
+ * @example
63
+ * request.withRetries(3); // Retry up to 3 times
64
+ */
65
+ withRetries(retries: number): this;
66
+ /**
67
+ * Set a callback to be invoked before each retry attempt
68
+ * Useful for implementing backoff strategies or logging retry attempts.
69
+ *
70
+ * @param callback - Function to call before retrying
71
+ * @returns The request instance for chaining
72
+ *
73
+ * @example
74
+ * request.onRetry(({ attempt, error }) => {
75
+ * console.log(`Retry attempt ${attempt} after error: ${error.message}`);
76
+ * return new Promise(resolve => setTimeout(resolve, attempt * 1000));
77
+ * });
78
+ */
79
+ onRetry(callback: RetryCallback): this;
80
+ /**
81
+ * Sets the credentials policy for the request
82
+ * @param credentialsPolicy - Can be 'omit', 'same-origin', or 'include'
83
+ * @returns The instance for chaining
84
+ */
85
+ withCredentials(credentialsPolicy?: CredentialsPolicy): this;
86
+ /**
87
+ * Allows providing an external AbortController to cancel the request
88
+ * @param controller - The AbortController to use for this request
89
+ * @returns The instance for chaining
90
+ */
91
+ withAbortController(controller: AbortController): this;
92
+ /**
93
+ * Sets the referrer for the request
94
+ * @param referrer - The referrer URL or policy
95
+ * @returns The instance for chaining
96
+ */
97
+ withReferrer(referrer: string): this;
98
+ /**
99
+ * Sets the referrer policy for the request
100
+ * @param policy - The referrer policy to use
101
+ * @returns The instance for chaining
102
+ */
103
+ withReferrerPolicy(policy: ReferrerPolicy): this;
104
+ /**
105
+ * Sets the redirect policy for the request
106
+ * @param redirect - Can be 'follow', 'error', or 'manual'
107
+ * @returns The instance for chaining
108
+ */
109
+ withRedirect(redirect: RedirectMode): this;
110
+ /**
111
+ * Sets the keepalive flag for the request
112
+ * @param keepalive - Whether to allow the request to outlive the page
113
+ * @returns The instance for chaining
114
+ */
115
+ withKeepAlive(keepalive: boolean): this;
116
+ /**
117
+ * Sets the priority of the request
118
+ * @param priority - Can be 'high', 'low', or 'auto'
119
+ * @returns The instance for chaining
120
+ */
121
+ withPriority(priority: RequestPriority): this;
122
+ /**
123
+ * Adds query parameters to the request URL
124
+ * @param params - An object containing the query parameters
125
+ * @returns The instance for chaining
126
+ */
127
+ withQueryParams(params: Record<string, string | string[] | number | boolean | null | undefined>): this;
128
+ /**
129
+ * Adds a single query parameter
130
+ * @param key - The parameter name
131
+ * @param value - The parameter value, can be a single value or array of values
132
+ * @returns The instance for chaining
133
+ */
134
+ withQueryParam(key: string, value: string | string[] | number | boolean | null | undefined): this;
135
+ /**
136
+ * Sets the mode of the request
137
+ * @param mode - The mode for the request (cors, no-cors, same-origin, navigate)
138
+ * @returns The instance for chaining
139
+ */
140
+ withMode(mode: RequestMode): this;
141
+ /**
142
+ * Shorthand for setting the Content-Type header
143
+ * @param contentType - The content type
144
+ * @returns The instance for chaining
145
+ */
146
+ withContentType(contentType: string): this;
147
+ /**
148
+ * Shorthand for setting the Authorization header
149
+ * @param authValue - The authorization value
150
+ * @returns The instance for chaining
151
+ */
152
+ withAuthorization(authValue: string): this;
153
+ /**
154
+ * Shorthand for setting up Basic authentication
155
+ * @param username - The username
156
+ * @param password - The password
157
+ * @returns The instance for chaining
158
+ */
159
+ withBasicAuth(username: string, password: string): this;
160
+ /**
161
+ * Cross-environment base64 encoding
162
+ * Works in both browser and Node.js environments
163
+ */
164
+ private encodeBase64;
165
+ /**
166
+ * Sets the bearer token for authentication
167
+ * @param token - The bearer token
168
+ * @returns The instance for chaining
169
+ */
170
+ withBearerToken(token: string): this;
171
+ /**
172
+ * Helper function to check for header presence in a case-insensitive way
173
+ * @param headers Headers object
174
+ * @param headerName Header name to check
175
+ * @returns Boolean indicating if the header exists (case-insensitive)
176
+ */
177
+ private hasHeader;
178
+ /**
179
+ * Sets cookies for the request
180
+ * @param cookies Object containing cookie name-value pairs or cookie options
181
+ * @returns The instance for chaining
182
+ */
183
+ withCookies(cookies: CookiesRecord): this;
184
+ /**
185
+ * Set a single cookie
186
+ * @param name Cookie name
187
+ * @param value Cookie value or options object
188
+ * @returns The instance for chaining
189
+ */
190
+ withCookie(name: string, value: string | CookieOptions): this;
191
+ /**
192
+ * Sets a CSRF token in the request headers
193
+ * @param token The CSRF token
194
+ * @param headerName The name of the header to use (default: X-CSRF-Token)
195
+ * @returns The instance for chaining
196
+ */
197
+ withCsrfToken(token: string, headerName?: string): this;
198
+ /**
199
+ * Disables automatic anti-CSRF protection.
200
+ * By default, X-Requested-With: XMLHttpRequest header is sent with all requests.
201
+ * @returns The instance for chaining
202
+ */
203
+ withoutCsrfProtection(): this;
204
+ /**
205
+ * Sets common security headers to help prevent CSRF attacks
206
+ * @returns The instance for chaining
207
+ */
208
+ withAntiCsrfHeaders(): this;
209
+ /**
210
+ * Configure request caching behavior
211
+ * When enabled, responses will be cached and reused for subsequent identical requests.
212
+ *
213
+ * @param options - Cache configuration options
214
+ * @returns The request instance for chaining
215
+ *
216
+ * @example
217
+ * request.withCache({
218
+ * ttl: 60000, // Cache for 1 minute
219
+ * maxEntries: 100,
220
+ * storage: localStorage
221
+ * });
222
+ */
223
+ withCache(options?: CacheOptions): this;
224
+ /**
225
+ * Send the request to the specified URL
226
+ * This is the final method in the chain that executes the request.
227
+ *
228
+ * @param url - The URL to send the request to
229
+ * @returns A promise with additional methods for processing the response
230
+ *
231
+ * @example
232
+ * const response = await request.sendTo('/api/users');
233
+ * const data = await response.getJson();
234
+ */
235
+ sendTo(url: string): ResponsePromise;
236
+ /**
237
+ * Formats the URL with any query parameters
238
+ * @param url The base URL
239
+ * @returns The URL with query parameters appended
240
+ */
241
+ private formatUrlWithQueryParams;
242
+ /**
243
+ * Executes a request with configured retry logic
244
+ * @param url The formatted URL to send the request to
245
+ * @param fetchOptions The fetch options to use
246
+ * @returns A wrapped response object
247
+ */
248
+ private executeWithRetries;
249
+ private executeRequest;
250
+ /**
251
+ * Executes a request using cache when possible
252
+ * @param url The formatted URL to send the request to
253
+ * @param fetchOptions The fetch options to use
254
+ * @param cacheKey The cache key for this request
255
+ */
256
+ private executeWithCache;
257
+ }
@@ -0,0 +1,20 @@
1
+ import { BaseRequest } from "./BaseRequest";
2
+ import type { Body } from "./types";
3
+ /**
4
+ * Base class for requests that can have a body (POST, PUT, PATCH)
5
+ */
6
+ export declare abstract class BodyRequest extends BaseRequest {
7
+ protected body?: Body;
8
+ private bodyType?;
9
+ /**
10
+ * Sets the body of the request
11
+ * @param body - The request body
12
+ */
13
+ withBody(body: Body): this;
14
+ private setContentTypeIfNeeded;
15
+ /**
16
+ * Send the request to the specified URL
17
+ * Overrides the base implementation to add body handling
18
+ */
19
+ sendTo(url: string): ReturnType<BaseRequest["sendTo"]>;
20
+ }
@@ -0,0 +1,18 @@
1
+ export declare class RequestError extends Error {
2
+ readonly status?: number;
3
+ readonly response?: Response;
4
+ readonly url: string;
5
+ readonly method: string;
6
+ readonly timeoutError?: boolean;
7
+ constructor(message: string, url: string, method: string, options?: {
8
+ status?: number;
9
+ response?: Response;
10
+ timeoutError?: boolean;
11
+ });
12
+ /**
13
+ * Static methods for creating specific types of RequestError
14
+ */
15
+ static timeout(url: string, method: string, timeoutMs: number): RequestError;
16
+ static fromResponse(response: Response, url: string, method: string): RequestError;
17
+ static networkError(url: string, method: string, originalError: Error): RequestError;
18
+ }
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Wrapper for HTTP responses with methods to transform the response data
3
+ * Provides caching and conversion between different response formats.
4
+ */
5
+ export declare class ResponseWrapper {
6
+ private readonly response;
7
+ private textCache;
8
+ private jsonCache;
9
+ private blobCache;
10
+ private arrayBufferCache;
11
+ private bodyUsed;
12
+ constructor(response: Response);
13
+ get status(): number;
14
+ get statusText(): string;
15
+ get headers(): Headers;
16
+ get ok(): boolean;
17
+ get raw(): Response;
18
+ /**
19
+ * Parse the response body as JSON
20
+ * Caches the result for subsequent calls.
21
+ *
22
+ * @returns The parsed JSON data
23
+ * @throws Error if the response has already been consumed in a different format
24
+ *
25
+ * @example
26
+ * const data = await response.getJson();
27
+ * console.log(data.items);
28
+ */
29
+ getJson<T = unknown>(): Promise<T>;
30
+ /**
31
+ * Get the response body as text
32
+ * Caches the result for subsequent calls. Attempts to convert from JSON or Blob
33
+ * if the body has already been consumed in those formats.
34
+ *
35
+ * @returns The response text
36
+ * @throws Error if the response has already been consumed in an incompatible format
37
+ *
38
+ * @example
39
+ * const text = await response.getText();
40
+ */
41
+ getText(): Promise<string>;
42
+ /**
43
+ * Get the response body as a Blob
44
+ * Caches the result for subsequent calls. Attempts to convert from text
45
+ * if the body has already been consumed as text.
46
+ *
47
+ * @returns The response as a Blob
48
+ * @throws Error if the response has already been consumed in an incompatible format
49
+ *
50
+ * @example
51
+ * const blob = await response.getBlob();
52
+ * const url = URL.createObjectURL(blob);
53
+ */
54
+ getBlob(): Promise<Blob>;
55
+ /**
56
+ * Get the response body as an ArrayBuffer
57
+ * Caches the result for subsequent calls. Attempts to convert from text or Blob
58
+ * if the body has already been consumed in those formats.
59
+ *
60
+ * @returns The response as an ArrayBuffer
61
+ * @throws Error if the response has already been consumed in an incompatible format
62
+ *
63
+ * @example
64
+ * const buffer = await response.getArrayBuffer();
65
+ */
66
+ getArrayBuffer(): Promise<ArrayBuffer>;
67
+ /**
68
+ * Get the raw response body as a ReadableStream
69
+ * This method consumes the body and should only be called once.
70
+ *
71
+ * @returns The response body as a ReadableStream or null
72
+ * @throws Error if the response body has already been consumed
73
+ *
74
+ * @example
75
+ * const stream = response.getBody();
76
+ * if (stream) {
77
+ * const reader = stream.getReader();
78
+ * // Process the stream
79
+ * }
80
+ */
81
+ getBody(): ReadableStream<Uint8Array> | null;
82
+ }
83
+ /**
84
+ * Type for Promise with response data transformation methods
85
+ */
86
+ export interface ResponsePromise<T = ResponseWrapper> extends Promise<T> {
87
+ getJson<R = unknown>(): Promise<R>;
88
+ getText(): Promise<string>;
89
+ getBlob(): Promise<Blob>;
90
+ getArrayBuffer(): Promise<ArrayBuffer>;
91
+ getBody(): Promise<ReadableStream<Uint8Array> | null>;
92
+ getData<T = unknown, R = T>(selector?: (data: T) => R): Promise<T | R>;
93
+ }
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Enum for HTTP methods
3
+ */
4
+ export declare enum HttpMethod {
5
+ GET = "GET",
6
+ PUT = "PUT",
7
+ POST = "POST",
8
+ HEAD = "HEAD",
9
+ PATCH = "PATCH",
10
+ DELETE = "DELETE",
11
+ OPTIONS = "OPTIONS"
12
+ }
13
+ /**
14
+ * Enum for request priorities
15
+ */
16
+ export declare enum RequestPriority {
17
+ LOW = "low",
18
+ HIGH = "high",
19
+ AUTO = "auto"
20
+ }
21
+ /**
22
+ * Enum for credentials policies
23
+ */
24
+ export declare enum CredentialsPolicy {
25
+ OMIT = "omit",
26
+ INCLUDE = "include",
27
+ SAME_ORIGIN = "same-origin"
28
+ }
29
+ /**
30
+ * Enum for request modes
31
+ */
32
+ export declare enum RequestMode {
33
+ CORS = "cors",
34
+ NO_CORS = "no-cors",
35
+ SAME_ORIGIN = "same-origin",
36
+ NAVIGATE = "navigate"
37
+ }
38
+ /**
39
+ * Enum for redirect modes
40
+ */
41
+ export declare enum RedirectMode {
42
+ ERROR = "error",
43
+ FOLLOW = "follow",
44
+ MANUAL = "manual"
45
+ }
46
+ /**
47
+ * Enum for cache modes
48
+ */
49
+ export declare enum CacheMode {
50
+ DEFAULT = "default",
51
+ RELOAD = "reload",
52
+ NO_STORE = "no-store",
53
+ NO_CACHE = "no-cache",
54
+ FORCE_CACHE = "force-cache",
55
+ ONLY_IF_CACHED = "only-if-cached"
56
+ }
57
+ /**
58
+ * Enum for cookie SameSite policies
59
+ */
60
+ export declare enum SameSitePolicy {
61
+ LAX = "Lax",
62
+ NONE = "None",
63
+ STRICT = "Strict"
64
+ }
65
+ /**
66
+ * Enum for body types
67
+ */
68
+ export declare enum BodyType {
69
+ JSON = "json",
70
+ STRING = "string",
71
+ BINARY = "binary"
72
+ }
73
+ /**
74
+ * Referrer policies for fetch requests
75
+ */
76
+ export declare enum ReferrerPolicy {
77
+ ORIGIN = "origin",
78
+ UNSAFE_URL = "unsafe-url",
79
+ SAME_ORIGIN = "same-origin",
80
+ NO_REFERRER = "no-referrer",
81
+ STRICT_ORIGIN = "strict-origin",
82
+ ORIGIN_WHEN_CROSS_ORIGIN = "origin-when-cross-origin",
83
+ NO_REFERRER_WHEN_DOWNGRADE = "no-referrer-when-downgrade",
84
+ STRICT_ORIGIN_WHEN_CROSS_ORIGIN = "strict-origin-when-cross-origin"
85
+ }
@@ -0,0 +1,37 @@
1
+ import { get, put, head, post, patch, del, options } from "./requestFactories";
2
+ import { Config } from "./utils/Config";
3
+ export { HttpMethod, RequestPriority, CredentialsPolicy, RequestMode, RedirectMode, CacheMode, SameSitePolicy, ReferrerPolicy } from "./enums";
4
+ export type { RetryCallback, RequestOptions, CookieOptions, CookiesRecord } from "./types";
5
+ export { RequestError } from "./RequestError";
6
+ export { ResponseWrapper } from "./ResponseWrapper";
7
+ export { CookieUtils } from "./utils/CookieUtils";
8
+ export { GetRequest, PostRequest, PutRequest, DeleteRequest, PatchRequest, HeadRequest, OptionsRequest } from "./requestMethods";
9
+ export { createMemoryStorage, createLocalStorageStorage, createSessionStorageStorage } from "./utils/CacheStorage";
10
+ export { CacheManager } from "./utils/CacheManager";
11
+ export type { CacheOptions } from "./types/cache";
12
+ export type { StorageProvider } from "./utils/StorageProvider";
13
+ /**
14
+ * Main API object for creating HTTP requests
15
+ * Provides factory methods for all HTTP methods and access to global configuration.
16
+ *
17
+ * @example
18
+ * // Making a GET request
19
+ * const users = await create.get()
20
+ * .withQueryParams({ limit: 10 })
21
+ * .sendTo('/api/users')
22
+ * .getJson();
23
+ *
24
+ * // Configure global settings
25
+ * create.config.setCsrfToken('token123');
26
+ */
27
+ declare const create: {
28
+ readonly get: typeof get;
29
+ readonly post: typeof post;
30
+ readonly put: typeof put;
31
+ readonly del: typeof del;
32
+ readonly patch: typeof patch;
33
+ readonly head: typeof head;
34
+ readonly options: typeof options;
35
+ readonly config: Config;
36
+ };
37
+ export default create;