create-request 1.6.1 → 2.0.0

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.
@@ -1,329 +0,0 @@
1
- import { HttpMethod, RequestPriority, CredentialsPolicy, RequestMode, RedirectMode, SameSitePolicy, CacheMode, type ReferrerPolicy } from "./enums";
2
- import type { RequestError } from "./RequestError.js";
3
- import type { ResponseWrapper } from "./ResponseWrapper.js";
4
- /**
5
- * Request body type that extends the standard BodyInit with support for JSON-serializable values.
6
- * This allows you to pass plain objects and arrays directly, which will be automatically stringified.
7
- *
8
- * @example
9
- * ```typescript
10
- * // All of these are valid Body types:
11
- * const body1: Body = { name: 'John', age: 30 }; // Object (auto-stringified)
12
- * const body2: Body = [1, 2, 3]; // Array (auto-stringified)
13
- * const body3: Body = 'plain text'; // String
14
- * const body4: Body = new FormData(); // FormData
15
- * const body5: Body = new Blob(['content']); // Blob
16
- * ```
17
- */
18
- export type Body = BodyInit | Record<string, unknown> | unknown[];
19
- /**
20
- * Callback function invoked before each retry attempt.
21
- * Can be used for logging, implementing custom backoff strategies, or other side effects.
22
- *
23
- * @param options - Retry callback options
24
- * @param options.attempt - The current retry attempt number (1-based, so first retry is 1)
25
- * @param options.error - The RequestError that triggered this retry
26
- * @returns `void` or a `Promise<void>` if the callback is async
27
- *
28
- * @example
29
- * ```typescript
30
- * const onRetry: RetryCallback = ({ attempt, error }) => {
31
- * console.log(`Retry attempt ${attempt} after error: ${error.message}`);
32
- * };
33
- * ```
34
- */
35
- export type RetryCallback = (options: {
36
- attempt: number;
37
- error: RequestError;
38
- }) => void | Promise<void>;
39
- /**
40
- * Function that calculates the delay (in milliseconds) before the next retry attempt.
41
- * Allows for dynamic delay strategies like exponential backoff or error-based delays.
42
- *
43
- * @param options - Delay calculation options
44
- * @param options.attempt - The current retry attempt number (1-based, so first retry is 1)
45
- * @param options.error - The RequestError that triggered this retry
46
- * @returns The delay in milliseconds (must be non-negative)
47
- *
48
- * @example
49
- * ```typescript
50
- * // Exponential backoff
51
- * const delayFn: RetryDelayFunction = ({ attempt }) => {
52
- * return Math.min(1000 * Math.pow(2, attempt - 1), 10000);
53
- * };
54
- * ```
55
- *
56
- * @example
57
- * ```typescript
58
- * // Error-based delay (longer delay for rate limits)
59
- * const delayFn: RetryDelayFunction = ({ attempt, error }) => {
60
- * if (error.status === 429) return 5000; // Rate limited, wait 5 seconds
61
- * return attempt * 1000; // Otherwise, linear backoff
62
- * };
63
- * ```
64
- */
65
- export type RetryDelayFunction = (options: {
66
- attempt: number;
67
- error: RequestError;
68
- }) => number;
69
- /**
70
- * Configuration object for retry behavior.
71
- * Provides fine-grained control over how failed requests are retried.
72
- *
73
- * @example
74
- * ```typescript
75
- * // Fixed delay
76
- * const config: RetryConfig = {
77
- * attempts: 3,
78
- * delay: 1000 // Wait 1 second between retries
79
- * };
80
- * ```
81
- *
82
- * @example
83
- * ```typescript
84
- * // Exponential backoff
85
- * const config: RetryConfig = {
86
- * attempts: 3,
87
- * delay: ({ attempt }) => Math.min(1000 * Math.pow(2, attempt - 1), 10000)
88
- * };
89
- * ```
90
- */
91
- export interface RetryConfig {
92
- /**
93
- * Number of retry attempts before giving up.
94
- * For example, `attempts: 3` means the request will be tried up to 4 times total (1 initial + 3 retries).
95
- */
96
- attempts: number;
97
- /**
98
- * Delay between retries in milliseconds, or a function that calculates the delay.
99
- * - If a number: fixed delay in milliseconds (must be non-negative)
100
- * - If a function: calculates delay synchronously based on attempt number and error
101
- * - If not provided: no delay between retries (immediate retry)
102
- */
103
- delay?: number | RetryDelayFunction;
104
- }
105
- /**
106
- * Configuration object passed to request interceptors.
107
- * Contains all the information needed to make the request and can be modified by interceptors.
108
- *
109
- * @example
110
- * ```typescript
111
- * const interceptor: RequestInterceptor = (config) => {
112
- * // Modify headers
113
- * config.headers['X-Custom'] = 'value';
114
- * // Change URL
115
- * config.url = 'https://other-api.com' + config.url;
116
- * return config;
117
- * };
118
- * ```
119
- */
120
- export interface RequestConfig {
121
- url: string;
122
- method: string;
123
- headers: Record<string, string>;
124
- body?: Body;
125
- signal?: AbortSignal;
126
- credentials?: RequestCredentials;
127
- mode?: RequestMode;
128
- redirect?: RedirectMode;
129
- referrer?: string;
130
- referrerPolicy?: ReferrerPolicy;
131
- keepalive?: boolean;
132
- priority?: RequestPriority;
133
- integrity?: string;
134
- cache?: RequestCache;
135
- }
136
- /**
137
- * Request interceptor function that can modify the request configuration or return an early response.
138
- * Interceptors run before the request is sent. If an interceptor returns a Response object,
139
- * the request is short-circuited and that response is used instead of making the actual request.
140
- *
141
- * @param config - The request configuration that can be modified
142
- * @returns Either:
143
- * - A modified `RequestConfig` object (request proceeds with modifications)
144
- * - A `Response` object (request is short-circuited, this response is used)
145
- * - A Promise resolving to either of the above
146
- *
147
- * @example
148
- * ```typescript
149
- * const interceptor: RequestInterceptor = (config) => {
150
- * // Add custom header
151
- * config.headers['X-Request-ID'] = generateId();
152
- * return config;
153
- * };
154
- * ```
155
- *
156
- * @example
157
- * ```typescript
158
- * // Short-circuit request (e.g., for caching)
159
- * const cacheInterceptor: RequestInterceptor = (config) => {
160
- * const cached = getFromCache(config.url);
161
- * if (cached) {
162
- * return new Response(JSON.stringify(cached));
163
- * }
164
- * return config;
165
- * };
166
- * ```
167
- */
168
- export type RequestInterceptor = (config: RequestConfig) => RequestConfig | Response | Promise<RequestConfig | Response>;
169
- /**
170
- * Response interceptor function that can transform the response.
171
- * Interceptors run after a successful request, allowing you to modify or log responses.
172
- *
173
- * @param response - The ResponseWrapper that can be modified or replaced
174
- * @returns Either:
175
- * - A modified `ResponseWrapper` object
176
- * - A Promise resolving to a `ResponseWrapper`
177
- *
178
- * @example
179
- * ```typescript
180
- * const interceptor: ResponseInterceptor = (response) => {
181
- * console.log(`Response status: ${response.status}`);
182
- * return response;
183
- * };
184
- * ```
185
- *
186
- * @example
187
- * ```typescript
188
- * // Transform response data
189
- * const interceptor: ResponseInterceptor = async (response) => {
190
- * const data = await response.getJson();
191
- * // Modify data...
192
- * // Note: You'd need to create a new ResponseWrapper with modified data
193
- * return response;
194
- * };
195
- * ```
196
- */
197
- export type ResponseInterceptor = (response: ResponseWrapper) => ResponseWrapper | Promise<ResponseWrapper>;
198
- /**
199
- * Error interceptor function that can handle or transform errors.
200
- * Interceptors run when a request fails, allowing you to handle errors, transform them,
201
- * or recover by returning a ResponseWrapper.
202
- *
203
- * @param error - The RequestError that occurred
204
- * @returns Either:
205
- * - A modified `RequestError` (error is re-thrown with modifications)
206
- * - A `ResponseWrapper` (error is recovered, request succeeds with this response)
207
- * - A Promise resolving to either of the above
208
- *
209
- * @example
210
- * ```typescript
211
- * // Log errors
212
- * const interceptor: ErrorInterceptor = (error) => {
213
- * console.error('Request failed:', error);
214
- * return error; // Re-throw the error
215
- * };
216
- * ```
217
- *
218
- * @example
219
- * ```typescript
220
- * // Recover from specific errors
221
- * const interceptor: ErrorInterceptor = (error) => {
222
- * if (error.status === 404) {
223
- * // Return a default response instead of throwing
224
- * return new ResponseWrapper(
225
- * new Response(JSON.stringify({ data: [] }), { status: 200 })
226
- * );
227
- * }
228
- * return error; // Re-throw other errors
229
- * };
230
- * ```
231
- */
232
- export type ErrorInterceptor = (error: RequestError) => RequestError | ResponseWrapper | Promise<RequestError | ResponseWrapper>;
233
- /**
234
- * Options for setting cookie properties.
235
- * Note: When used in request cookies (via `withCookies()`), these options are primarily
236
- * for documentation purposes, as the Cookie header only sends name-value pairs.
237
- * These options are more relevant when parsing Set-Cookie headers from responses.
238
- *
239
- * @example
240
- * ```typescript
241
- * const cookieOptions: CookieOptions = {
242
- * value: 'abc123',
243
- * secure: true,
244
- * httpOnly: true,
245
- * sameSite: SameSitePolicy.STRICT,
246
- * expires: new Date('2024-12-31'),
247
- * path: '/',
248
- * domain: '.example.com',
249
- * maxAge: 3600 // 1 hour in seconds
250
- * };
251
- * ```
252
- */
253
- export interface CookieOptions {
254
- /** The cookie value */
255
- value: string;
256
- /** Whether the cookie should only be sent over HTTPS */
257
- secure?: boolean;
258
- /** Whether the cookie should not be accessible via JavaScript (HttpOnly flag) */
259
- httpOnly?: boolean;
260
- /** SameSite policy for the cookie */
261
- sameSite?: SameSitePolicy;
262
- /** Expiration date for the cookie */
263
- expires?: Date;
264
- /** Path where the cookie is valid */
265
- path?: string;
266
- /** Domain where the cookie is valid */
267
- domain?: string;
268
- /** Maximum age of the cookie in seconds */
269
- maxAge?: number;
270
- }
271
- /**
272
- * Record type for cookies.
273
- * Keys are cookie names, values are either simple strings or CookieOptions objects.
274
- *
275
- * @example
276
- * ```typescript
277
- * const cookies: CookiesRecord = {
278
- * sessionId: 'abc123',
279
- * token: { value: 'xyz789', secure: true }
280
- * };
281
- * ```
282
- */
283
- export type CookiesRecord = Record<string, string | CookieOptions>;
284
- export { HttpMethod, RequestMode, RedirectMode, SameSitePolicy, RequestPriority, CredentialsPolicy, CacheMode };
285
- /**
286
- * Options for GraphQL requests.
287
- *
288
- * @example
289
- * ```typescript
290
- * const options: GraphQLOptions = {
291
- * throwOnError: true // Throw RequestError if GraphQL response contains errors
292
- * };
293
- * ```
294
- */
295
- export interface GraphQLOptions {
296
- /**
297
- * If `true`, throws a RequestError when the GraphQL response contains errors.
298
- * If `false` or undefined, errors are returned in the response data and must be checked manually.
299
- */
300
- throwOnError?: boolean;
301
- }
302
- /**
303
- * A fetch-compatible function used to execute the actual HTTP request.
304
- * Must match the signature of the standard `fetch` API and should honor `init.signal`
305
- * for timeout and abort support.
306
- *
307
- * @example
308
- * ```typescript
309
- * // A logging wrapper around the global fetch
310
- * const loggingFetch: FetchFunction = (input, init) => {
311
- * console.log(`${init?.method ?? 'GET'} ${input}`);
312
- * return fetch(input, init);
313
- * };
314
- * ```
315
- */
316
- export type FetchFunction = (input: string | URL | globalThis.Request, init?: RequestInit) => Promise<Response>;
317
- export interface RequestOptions extends Omit<RequestInit, "signal" | "body" | "method" | "credentials" | "mode" | "redirect" | "priority" | "cache"> {
318
- timeout?: number;
319
- retries?: number | RetryConfig;
320
- onRetry?: RetryCallback;
321
- body?: Body;
322
- credentials?: RequestCredentials;
323
- mode?: RequestMode;
324
- redirect?: RequestRedirect;
325
- priority?: RequestPriority;
326
- keepalive?: boolean;
327
- integrity?: string;
328
- cache?: RequestCache;
329
- }
@@ -1,221 +0,0 @@
1
- import type { RequestInterceptor, ResponseInterceptor, ErrorInterceptor } from "../types.js";
2
- /**
3
- * Global configuration for create-request
4
- */
5
- export declare class Config {
6
- private static _instance;
7
- private _csrfHeader;
8
- private _xsrfCookie;
9
- private _xsrfHeader;
10
- private _csrfToken;
11
- private _autoXsrf;
12
- private _antiCsrf;
13
- private _reqI;
14
- private _resI;
15
- private _errI;
16
- private _nextId;
17
- private constructor();
18
- /**
19
- * Get the singleton instance of the Config class
20
- *
21
- * @returns The global configuration instance
22
- *
23
- * @example
24
- * const config = Config.getInstance();
25
- * config.setCsrfToken('token123');
26
- */
27
- static getInstance(): Config;
28
- /**
29
- * Set a global CSRF token to be used for all requests
30
- *
31
- * @param token - The CSRF token value
32
- * @returns The config instance for chaining
33
- *
34
- * @example
35
- * Config.getInstance().setCsrfToken('myToken123');
36
- */
37
- setCsrfToken(token: string): Config;
38
- /**
39
- * Get the global CSRF token that will be automatically applied to requests
40
- *
41
- * @returns The current CSRF token or null if not set
42
- */
43
- getCsrfToken(): string | null;
44
- /**
45
- * Set the CSRF header name used when sending the token
46
- *
47
- * @param name - The header name to use
48
- * @returns The config instance for chaining
49
- *
50
- * @example
51
- * Config.getInstance().setCsrfHeaderName('X-My-CSRF-Token');
52
- */
53
- setCsrfHeaderName(name: string): Config;
54
- /**
55
- * Get the configured CSRF header name
56
- *
57
- * @returns The current CSRF header name
58
- */
59
- getCsrfHeaderName(): string;
60
- /**
61
- * Set the XSRF cookie name to look for when extracting tokens from cookies
62
- *
63
- * @param name - The cookie name to look for
64
- * @returns The config instance for chaining
65
- *
66
- * @example
67
- * Config.getInstance().setXsrfCookieName('MY-XSRF-COOKIE');
68
- */
69
- setXsrfCookieName(name: string): Config;
70
- /**
71
- * Get the configured XSRF cookie name
72
- *
73
- * @returns The current XSRF cookie name
74
- */
75
- getXsrfCookieName(): string;
76
- /**
77
- * Set the XSRF header name for sending tokens extracted from cookies
78
- *
79
- * @param name - The header name to use
80
- * @returns The config instance for chaining
81
- */
82
- setXsrfHeaderName(name: string): Config;
83
- /**
84
- * Get the configured XSRF header name
85
- *
86
- * @returns The current XSRF header name
87
- */
88
- getXsrfHeaderName(): string;
89
- /**
90
- * Enable or disable automatic extraction of XSRF tokens from cookies
91
- * When enabled, the library will look for XSRF tokens in cookies and
92
- * automatically add them to request headers.
93
- *
94
- * @param enable - Whether to enable this feature
95
- * @returns The config instance for chaining
96
- *
97
- * @example
98
- * Config.getInstance().setEnableAutoXsrf(false); // Disable XSRF extraction
99
- */
100
- setEnableAutoXsrf(enable: boolean): Config;
101
- /**
102
- * Check if automatic XSRF token extraction is enabled
103
- *
104
- * @returns True if automatic XSRF is enabled
105
- */
106
- isAutoXsrfEnabled(): boolean;
107
- /**
108
- * Enable or disable automatic addition of anti-CSRF headers
109
- * When enabled, X-Requested-With: XMLHttpRequest will be added to all requests.
110
- *
111
- * @param enable - Whether to enable this feature
112
- * @returns The config instance for chaining
113
- */
114
- setEnableAntiCsrf(enable: boolean): Config;
115
- /**
116
- * Check if anti-CSRF protection is enabled
117
- *
118
- * @returns True if anti-CSRF protection is enabled
119
- */
120
- isAntiCsrfEnabled(): boolean;
121
- /**
122
- * Add a global request interceptor
123
- * Request interceptors can modify the request configuration or return an early response
124
- *
125
- * @param interceptor - The request interceptor function
126
- * @returns The interceptor ID for later removal
127
- *
128
- * @example
129
- * const id = Config.getInstance().addRequestInterceptor((config) => {
130
- * config.headers['X-Custom'] = 'value';
131
- * return config;
132
- * });
133
- */
134
- addRequestInterceptor(interceptor: RequestInterceptor): number;
135
- /**
136
- * Add a global response interceptor
137
- * Response interceptors can transform the response
138
- *
139
- * @param interceptor - The response interceptor function
140
- * @returns The interceptor ID for later removal
141
- *
142
- * @example
143
- * const id = Config.getInstance().addResponseInterceptor((response) => {
144
- * console.log('Response received:', response.status);
145
- * return response;
146
- * });
147
- */
148
- addResponseInterceptor(interceptor: ResponseInterceptor): number;
149
- /**
150
- * Add a global error interceptor
151
- * Error interceptors can handle or transform errors
152
- *
153
- * @param interceptor - The error interceptor function
154
- * @returns The interceptor ID for later removal
155
- *
156
- * @example
157
- * const id = Config.getInstance().addErrorInterceptor((error) => {
158
- * console.error('Request failed:', error);
159
- * throw error;
160
- * });
161
- */
162
- addErrorInterceptor(interceptor: ErrorInterceptor): number;
163
- /**
164
- * Remove a request interceptor by its ID
165
- *
166
- * @param id - The interceptor ID returned from addRequestInterceptor
167
- *
168
- * @example
169
- * Config.getInstance().removeRequestInterceptor(id);
170
- */
171
- removeRequestInterceptor(id: number): void;
172
- /**
173
- * Remove a response interceptor by its ID
174
- *
175
- * @param id - The interceptor ID returned from addResponseInterceptor
176
- *
177
- * @example
178
- * Config.getInstance().removeResponseInterceptor(id);
179
- */
180
- removeResponseInterceptor(id: number): void;
181
- /**
182
- * Remove an error interceptor by its ID
183
- *
184
- * @param id - The interceptor ID returned from addErrorInterceptor
185
- *
186
- * @example
187
- * Config.getInstance().removeErrorInterceptor(id);
188
- */
189
- removeErrorInterceptor(id: number): void;
190
- /**
191
- * Clear all interceptors (request, response, and error)
192
- *
193
- * @example
194
- * Config.getInstance().clearInterceptors();
195
- */
196
- clearInterceptors(): void;
197
- /**
198
- * Get all global request interceptors (in registration order)
199
- * @internal
200
- */
201
- getRequestInterceptors(): RequestInterceptor[];
202
- /**
203
- * Get all global response interceptors (in registration order)
204
- * @internal
205
- */
206
- getResponseInterceptors(): ResponseInterceptor[];
207
- /**
208
- * Get all global error interceptors (in registration order)
209
- * @internal
210
- */
211
- getErrorInterceptors(): ErrorInterceptor[];
212
- /**
213
- * Reset all configuration options to their default values
214
- *
215
- * @returns The config instance for chaining
216
- *
217
- * @example
218
- * Config.getInstance().reset();
219
- */
220
- reset(): Config;
221
- }
@@ -1,9 +0,0 @@
1
- import type { CookiesRecord } from "../types.js";
2
- export declare class CookieUtils {
3
- /**
4
- * Formats cookies for a request
5
- * @param cookies Object containing cookie name-value pairs or cookie options
6
- * @returns Formatted cookie string for the Cookie header
7
- */
8
- static formatRequestCookies(cookies: CookiesRecord): string;
9
- }
@@ -1,24 +0,0 @@
1
- /**
2
- * Utility class for CSRF token management
3
- */
4
- export declare class CsrfUtils {
5
- /**
6
- * Extracts CSRF token from a meta tag in the document head
7
- * @param metaName The name attribute of the meta tag (default: "csrf-token")
8
- * @returns The CSRF token or null if not found
9
- */
10
- static getTokenFromMeta(metaName?: string): string | null;
11
- /**
12
- * Extracts CSRF token from a cookie
13
- * @param cookieName The name of the cookie containing the CSRF token
14
- * @returns The CSRF token or null if not found
15
- */
16
- static getTokenFromCookie(cookieName?: string): string | null;
17
- /**
18
- * Validates if the provided string is a potential CSRF token
19
- * Checks if the token meets security requirements
20
- * @param token The token to validate
21
- * @returns Whether the token is valid
22
- */
23
- static isValidToken(token: string | null | undefined): boolean;
24
- }