create-request 0.0.1-beta.23 → 0.0.1-beta.24

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,21 +1,27 @@
1
- import { type HttpMethod, type RedirectMode, type RequestMode, type RequestPriority, CredentialsPolicy } from "./enums.js";
2
- import type { RequestOptions, RetryCallback, CookiesRecord, CookieOptions } from "./types.js";
3
- import { type ResponsePromise } from "./ResponseWrapper.js";
4
- import type { CacheOptions } from "./types/cache.js";
5
- import { CacheManager } from "./utils/CacheManager.js";
1
+ import { type HttpMethod, RedirectMode, RequestMode, RequestPriority, ReferrerPolicy, CredentialsPolicy } from "./enums.js";
2
+ import type { RequestOptions, RetryCallback, CookiesRecord, CookieOptions, RequestInterceptor, ResponseInterceptor, ErrorInterceptor } from "./types.js";
3
+ import { ResponseWrapper } from "./ResponseWrapper.js";
6
4
  /**
7
5
  * Base class with common functionality for all request types
8
6
  * Provides the core request building and execution capabilities.
9
7
  */
10
8
  export declare abstract class BaseRequest {
11
9
  protected abstract method: HttpMethod;
10
+ protected url: string;
12
11
  protected requestOptions: RequestOptions;
13
12
  protected abortController?: AbortController;
14
13
  protected queryParams: URLSearchParams;
15
14
  protected autoApplyCsrfProtection: boolean;
16
- protected cacheManager?: CacheManager;
17
- protected cacheEnabled: boolean;
18
- constructor();
15
+ private requestInterceptors;
16
+ private responseInterceptors;
17
+ private errorInterceptors;
18
+ constructor(url: string);
19
+ /**
20
+ * Creates a fluent API for setting enum-based options
21
+ * Combines direct setter with convenience methods
22
+ */
23
+ private createFluentSetter;
24
+ private validateUrl;
19
25
  /**
20
26
  * Add multiple HTTP headers to the request
21
27
  *
@@ -78,11 +84,17 @@ export declare abstract class BaseRequest {
78
84
  */
79
85
  onRetry(callback: RetryCallback): this;
80
86
  /**
81
- * Sets the credentials policy for the request
82
- * @param credentialsPolicy - Can be 'omit', 'same-origin', or 'include'
83
- * @returns The instance for chaining
87
+ * Sets credentials policy - supports both direct call and fluent API
88
+ * @example
89
+ * request.withCredentials("include")
90
+ * request.withCredentials(CredentialsPolicy.INCLUDE)
91
+ * request.withCredentials.INCLUDE()
84
92
  */
85
- withCredentials(credentialsPolicy?: CredentialsPolicy): this;
93
+ get withCredentials(): ((credentialsPolicy: CredentialsPolicy | string) => BaseRequest) & {
94
+ INCLUDE: () => BaseRequest;
95
+ OMIT: () => BaseRequest;
96
+ SAME_ORIGIN: () => BaseRequest;
97
+ };
86
98
  /**
87
99
  * Allows providing an external AbortController to cancel the request
88
100
  * @param controller - The AbortController to use for this request
@@ -96,17 +108,34 @@ export declare abstract class BaseRequest {
96
108
  */
97
109
  withReferrer(referrer: string): this;
98
110
  /**
99
- * Sets the referrer policy for the request
100
- * @param policy - The referrer policy to use
101
- * @returns The instance for chaining
111
+ * Sets referrer policy - supports both direct call and fluent API
112
+ * @example
113
+ * request.withReferrerPolicy("no-referrer")
114
+ * request.withReferrerPolicy(ReferrerPolicy.NO_REFERRER)
115
+ * request.withReferrerPolicy.NO_REFERRER()
102
116
  */
103
- withReferrerPolicy(policy: ReferrerPolicy): this;
117
+ get withReferrerPolicy(): ((policy: ReferrerPolicy | string) => BaseRequest) & {
118
+ ORIGIN: () => BaseRequest;
119
+ UNSAFE_URL: () => BaseRequest;
120
+ SAME_ORIGIN: () => BaseRequest;
121
+ NO_REFERRER: () => BaseRequest;
122
+ STRICT_ORIGIN: () => BaseRequest;
123
+ ORIGIN_WHEN_CROSS_ORIGIN: () => BaseRequest;
124
+ NO_REFERRER_WHEN_DOWNGRADE: () => BaseRequest;
125
+ STRICT_ORIGIN_WHEN_CROSS_ORIGIN: () => BaseRequest;
126
+ };
104
127
  /**
105
- * Sets the redirect policy for the request
106
- * @param redirect - Can be 'follow', 'error', or 'manual'
107
- * @returns The instance for chaining
128
+ * Sets redirect mode - supports both direct call and fluent API
129
+ * @example
130
+ * request.withRedirect("follow")
131
+ * request.withRedirect(RedirectMode.FOLLOW)
132
+ * request.withRedirect.FOLLOW()
108
133
  */
109
- withRedirect(redirect: RedirectMode): this;
134
+ get withRedirect(): ((redirect: RedirectMode | string) => BaseRequest) & {
135
+ FOLLOW: () => BaseRequest;
136
+ ERROR: () => BaseRequest;
137
+ MANUAL: () => BaseRequest;
138
+ };
110
139
  /**
111
140
  * Sets the keepalive flag for the request
112
141
  * @param keepalive - Whether to allow the request to outlive the page
@@ -114,11 +143,17 @@ export declare abstract class BaseRequest {
114
143
  */
115
144
  withKeepAlive(keepalive: boolean): this;
116
145
  /**
117
- * Sets the priority of the request
118
- * @param priority - Can be 'high', 'low', or 'auto'
119
- * @returns The instance for chaining
146
+ * Sets request priority - supports both direct call and fluent API
147
+ * @example
148
+ * request.withPriority("high")
149
+ * request.withPriority(RequestPriority.HIGH)
150
+ * request.withPriority.HIGH()
120
151
  */
121
- withPriority(priority: RequestPriority): this;
152
+ get withPriority(): ((priority: RequestPriority | string) => BaseRequest) & {
153
+ HIGH: () => BaseRequest;
154
+ LOW: () => BaseRequest;
155
+ AUTO: () => BaseRequest;
156
+ };
122
157
  /**
123
158
  * Adds query parameters to the request URL
124
159
  * @param params - An object containing the query parameters
@@ -133,11 +168,18 @@ export declare abstract class BaseRequest {
133
168
  */
134
169
  withQueryParam(key: string, value: string | string[] | number | boolean | null | undefined): this;
135
170
  /**
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
171
+ * Sets request mode - supports both direct call and fluent API
172
+ * @example
173
+ * request.withMode("cors")
174
+ * request.withMode(RequestMode.CORS)
175
+ * request.withMode.CORS()
139
176
  */
140
- withMode(mode: RequestMode): this;
177
+ get withMode(): ((mode: RequestMode | string) => BaseRequest) & {
178
+ CORS: () => BaseRequest;
179
+ NO_CORS: () => BaseRequest;
180
+ SAME_ORIGIN: () => BaseRequest;
181
+ NAVIGATE: () => BaseRequest;
182
+ };
141
183
  /**
142
184
  * Shorthand for setting the Content-Type header
143
185
  * @param contentType - The content type
@@ -168,9 +210,13 @@ export declare abstract class BaseRequest {
168
210
  * @returns The instance for chaining
169
211
  */
170
212
  withBearerToken(token: string): this;
213
+ /**
214
+ * Safely get headers as a Record<string, string>
215
+ * @returns The headers object
216
+ */
217
+ private getHeadersRecord;
171
218
  /**
172
219
  * Helper function to check for header presence in a case-insensitive way
173
- * @param headers Headers object
174
220
  * @param headerName Header name to check
175
221
  * @returns Boolean indicating if the header exists (case-insensitive)
176
222
  */
@@ -207,32 +253,113 @@ export declare abstract class BaseRequest {
207
253
  */
208
254
  withAntiCsrfHeaders(): this;
209
255
  /**
210
- * Configure request caching behavior
211
- * When enabled, responses will be cached and reused for subsequent identical requests.
256
+ * Add a request interceptor for this specific request
257
+ * Request interceptors can modify the request configuration or return an early response
212
258
  *
213
- * @param options - Cache configuration options
214
- * @returns The request instance for chaining
259
+ * @param interceptor - The request interceptor function
260
+ * @returns The instance for chaining
215
261
  *
216
262
  * @example
217
- * request.withCache({
218
- * ttl: 60000, // Cache for 1 minute
219
- * maxEntries: 100,
220
- * storage: localStorage
263
+ * request.withRequestInterceptor((config) => {
264
+ * config.headers['X-Custom'] = 'value';
265
+ * return config;
221
266
  * });
222
267
  */
223
- withCache(options?: CacheOptions): this;
268
+ withRequestInterceptor(interceptor: RequestInterceptor): this;
269
+ /**
270
+ * Add a response interceptor for this specific request
271
+ * Response interceptors can transform the response
272
+ *
273
+ * @param interceptor - The response interceptor function
274
+ * @returns The instance for chaining
275
+ *
276
+ * @example
277
+ * request.withResponseInterceptor((response) => {
278
+ * console.log('Status:', response.status);
279
+ * return response;
280
+ * });
281
+ */
282
+ withResponseInterceptor(interceptor: ResponseInterceptor): this;
283
+ /**
284
+ * Add an error interceptor for this specific request
285
+ * Error interceptors can handle or transform errors
286
+ *
287
+ * @param interceptor - The error interceptor function
288
+ * @returns The instance for chaining
289
+ *
290
+ * @example
291
+ * request.withErrorInterceptor((error) => {
292
+ * console.error('Request failed:', error);
293
+ * throw error;
294
+ * });
295
+ */
296
+ withErrorInterceptor(interceptor: ErrorInterceptor): this;
297
+ /**
298
+ * Execute the request and return the ResponseWrapper
299
+ * This is the base method for getting the full response.
300
+ *
301
+ * @returns A promise that resolves to the ResponseWrapper
302
+ *
303
+ * @example
304
+ * const response = await request.getResponse();
305
+ * console.log(response.status);
306
+ */
307
+ getResponse(): Promise<ResponseWrapper>;
308
+ /**
309
+ * Execute the request and parse the response as JSON
310
+ *
311
+ * @returns A promise that resolves to the parsed JSON data
312
+ *
313
+ * @example
314
+ * const users = await request.getJson<User[]>();
315
+ */
316
+ getJson<T = unknown>(): Promise<T>;
317
+ /**
318
+ * Execute the request and get the response as text
319
+ *
320
+ * @returns A promise that resolves to the response text
321
+ *
322
+ * @example
323
+ * const text = await request.getText();
324
+ */
325
+ getText(): Promise<string>;
224
326
  /**
225
- * Send the request to the specified URL
226
- * This is the final method in the chain that executes the request.
327
+ * Execute the request and get the response as a Blob
227
328
  *
228
- * @param url - The URL to send the request to
229
- * @returns A promise with additional methods for processing the response
329
+ * @returns A promise that resolves to the response Blob
230
330
  *
231
331
  * @example
232
- * const response = await request.sendTo('/api/users');
233
- * const data = await response.getJson();
332
+ * const blob = await request.getBlob();
333
+ */
334
+ getBlob(): Promise<Blob>;
335
+ /**
336
+ * Execute the request and get the response body as a ReadableStream
337
+ *
338
+ * @returns A promise that resolves to the response body stream
339
+ *
340
+ * @example
341
+ * const stream = await request.getBody();
342
+ */
343
+ getBody(): Promise<ReadableStream<Uint8Array> | null>;
344
+ /**
345
+ * Execute the request and extract specific data using a selector function
346
+ * If no selector is provided, returns the full JSON response.
347
+ *
348
+ * @param selector - Optional function to extract and transform data
349
+ * @returns A promise that resolves to the selected data
350
+ *
351
+ * @example
352
+ * // Get full response
353
+ * const data = await request.getData();
354
+ *
355
+ * // Extract specific data
356
+ * const users = await request.getData(data => data.results.users);
234
357
  */
235
- sendTo(url: string): ResponsePromise;
358
+ getData<T = unknown, R = T>(selector?: (data: T) => R): Promise<T | R>;
359
+ /**
360
+ * Apply CSRF protection headers based on configuration
361
+ */
362
+ private applyCsrfProtection;
236
363
  /**
237
364
  * Formats the URL with any query parameters
238
365
  * @param url The base URL
@@ -247,12 +374,41 @@ export declare abstract class BaseRequest {
247
374
  * @throws RequestError if the request fails after all retries
248
375
  */
249
376
  private executeWithRetries;
250
- private executeRequest;
251
377
  /**
252
- * Executes a request using cache when possible
253
- * @param url The formatted URL to send the request to
254
- * @param fetchOptions The fetch options to use
255
- * @param cacheKey The cache key for this request
378
+ * Run request interceptors in order: global interceptors first, then per-request
379
+ * @param configParam - The request configuration
380
+ * @returns Modified config or a Response to short-circuit
381
+ */
382
+ private runRequestInterceptors;
383
+ /**
384
+ * Run response interceptors in reverse order: per-request interceptors first, then global in reverse
385
+ * @param response - The response wrapper
386
+ * @returns Modified response wrapper
387
+ */
388
+ private runResponseInterceptors;
389
+ /**
390
+ * Run error interceptors in reverse order: per-request interceptors first, then global in reverse
391
+ * @param error - The error that occurred
392
+ * @returns Modified error or a ResponseWrapper to recover
256
393
  */
257
- private executeWithCache;
394
+ private runErrorInterceptors;
395
+ /**
396
+ * Helper to create an abort signal with timeout support
397
+ * Handles various AbortSignal API levels gracefully
398
+ */
399
+ private createAbortSignal;
400
+ /**
401
+ * Manually combine two abort signals for older environments
402
+ * Returns the first signal and listens to the second
403
+ */
404
+ private combineSignalsManually;
405
+ /**
406
+ * Convert fetchOptions to RequestConfig with proper typing
407
+ */
408
+ private createRequestConfig;
409
+ /**
410
+ * Apply interceptor results back to fetchOptions
411
+ */
412
+ private applyRequestConfig;
413
+ private executeRequest;
258
414
  }
@@ -1,20 +1,43 @@
1
1
  import { BaseRequest } from "./BaseRequest.js";
2
2
  import type { Body } from "./types.js";
3
+ import type { ResponseWrapper } from "./ResponseWrapper.js";
3
4
  /**
4
5
  * Base class for requests that can have a body (POST, PUT, PATCH)
5
6
  */
6
7
  export declare abstract class BodyRequest extends BaseRequest {
7
8
  protected body?: Body;
8
9
  private bodyType?;
10
+ constructor(url: string);
9
11
  /**
10
12
  * Sets the body of the request
11
13
  * @param body - The request body
12
14
  */
13
15
  withBody(body: Body): this;
16
+ /**
17
+ * Sets a GraphQL query or mutation as the request body
18
+ * Automatically formats the body as JSON and sets Content-Type to application/json
19
+ *
20
+ * @param query - The GraphQL query or mutation string
21
+ * @param variables - Optional variables object to pass with the query
22
+ * @returns The request instance for chaining
23
+ *
24
+ * @example
25
+ * const request = new PostRequest('/graphql')
26
+ * .withGraphQL('query { user(id: $id) { name email } }', { id: '123' });
27
+ *
28
+ * @example
29
+ * const request = new PostRequest('/graphql')
30
+ * .withGraphQL('mutation { createUser(name: $name) { id } }', { name: 'John' });
31
+ */
32
+ withGraphQL(query: string, variables?: Record<string, unknown>): this;
33
+ /**
34
+ * Check if Content-Type header is already set (case-insensitive)
35
+ */
36
+ private hasContentType;
14
37
  private setContentTypeIfNeeded;
15
38
  /**
16
- * Send the request to the specified URL
39
+ * Execute the request and return the ResponseWrapper
17
40
  * Overrides the base implementation to add body handling
18
41
  */
19
- sendTo(url: string): ReturnType<BaseRequest["sendTo"]>;
42
+ getResponse(): Promise<ResponseWrapper>;
20
43
  }
@@ -3,11 +3,13 @@ export declare class RequestError extends Error {
3
3
  readonly response?: Response;
4
4
  readonly url: string;
5
5
  readonly method: string;
6
- readonly timeoutError?: boolean;
6
+ readonly isTimeout?: boolean;
7
+ readonly isAborted?: boolean;
7
8
  constructor(message: string, url: string, method: string, options?: {
8
9
  status?: number;
9
10
  response?: Response;
10
- timeoutError?: boolean;
11
+ isTimeout?: boolean;
12
+ isAborted?: boolean;
11
13
  });
12
14
  /**
13
15
  * Static methods for creating specific types of RequestError
@@ -15,4 +17,5 @@ export declare class RequestError extends Error {
15
17
  static timeout(url: string, method: string, timeoutMs: number): RequestError;
16
18
  static fromResponse(response: Response, url: string, method: string): RequestError;
17
19
  static networkError(url: string, method: string, originalError: Error): RequestError;
20
+ static abortError(url: string, method: string): RequestError;
18
21
  }
@@ -4,12 +4,13 @@
4
4
  */
5
5
  export declare class ResponseWrapper {
6
6
  private readonly response;
7
+ readonly url?: string;
8
+ readonly method?: string;
7
9
  private textCache;
8
10
  private jsonCache;
9
11
  private blobCache;
10
- private arrayBufferCache;
11
12
  private bodyUsed;
12
- constructor(response: Response);
13
+ constructor(response: Response, url?: string, method?: string);
13
14
  get status(): number;
14
15
  get statusText(): string;
15
16
  get headers(): Headers;
@@ -52,18 +53,6 @@ export declare class ResponseWrapper {
52
53
  * const url = URL.createObjectURL(blob);
53
54
  */
54
55
  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
56
  /**
68
57
  * Get the raw response body as a ReadableStream
69
58
  * This method consumes the body and should only be called once.
@@ -79,15 +68,19 @@ export declare class ResponseWrapper {
79
68
  * }
80
69
  */
81
70
  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>;
71
+ /**
72
+ * Extract specific data using a selector function
73
+ * If no selector is provided, returns the full JSON response.
74
+ *
75
+ * @param selector - Optional function to extract and transform data
76
+ * @returns A promise that resolves to the selected data
77
+ *
78
+ * @example
79
+ * // Get full response
80
+ * const data = await response.getData();
81
+ *
82
+ * // Extract specific data
83
+ * const users = await response.getData(data => data.results.users);
84
+ */
92
85
  getData<T = unknown, R = T>(selector?: (data: T) => R): Promise<T | R>;
93
86
  }
@@ -43,17 +43,6 @@ export declare enum RedirectMode {
43
43
  FOLLOW = "follow",
44
44
  MANUAL = "manual"
45
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
46
  /**
58
47
  * Enum for cookie SameSite policies
59
48
  */