create-request 0.0.1-beta.2 → 0.0.1-beta.20

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,635 +1 @@
1
- (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
3
- typeof define === 'function' && define.amd ? define(['exports'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.createRequest = {}));
5
- })(this, (function (exports) { 'use strict';
6
-
7
- /**
8
- * Enum for HTTP methods
9
- */
10
- exports.HttpMethod = void 0;
11
- (function (HttpMethod) {
12
- HttpMethod["GET"] = "GET";
13
- HttpMethod["POST"] = "POST";
14
- HttpMethod["PUT"] = "PUT";
15
- HttpMethod["DELETE"] = "DELETE";
16
- HttpMethod["PATCH"] = "PATCH";
17
- HttpMethod["HEAD"] = "HEAD";
18
- HttpMethod["OPTIONS"] = "OPTIONS";
19
- })(exports.HttpMethod || (exports.HttpMethod = {}));
20
- /**
21
- * Enum for request priorities
22
- */
23
- exports.RequestPriority = void 0;
24
- (function (RequestPriority) {
25
- RequestPriority["HIGH"] = "high";
26
- RequestPriority["LOW"] = "low";
27
- RequestPriority["AUTO"] = "auto";
28
- })(exports.RequestPriority || (exports.RequestPriority = {}));
29
- /**
30
- * Enum for credentials policies
31
- */
32
- exports.CredentialsPolicy = void 0;
33
- (function (CredentialsPolicy) {
34
- CredentialsPolicy["INCLUDE"] = "include";
35
- CredentialsPolicy["SAME_ORIGIN"] = "same-origin";
36
- CredentialsPolicy["OMIT"] = "omit";
37
- })(exports.CredentialsPolicy || (exports.CredentialsPolicy = {}));
38
- /**
39
- * Enum for request modes
40
- */
41
- exports.RequestMode = void 0;
42
- (function (RequestMode) {
43
- RequestMode["CORS"] = "cors";
44
- RequestMode["NO_CORS"] = "no-cors";
45
- RequestMode["SAME_ORIGIN"] = "same-origin";
46
- RequestMode["NAVIGATE"] = "navigate";
47
- })(exports.RequestMode || (exports.RequestMode = {}));
48
- /**
49
- * Enum for redirect modes
50
- */
51
- exports.RedirectMode = void 0;
52
- (function (RedirectMode) {
53
- RedirectMode["FOLLOW"] = "follow";
54
- RedirectMode["ERROR"] = "error";
55
- RedirectMode["MANUAL"] = "manual";
56
- })(exports.RedirectMode || (exports.RedirectMode = {}));
57
- /**
58
- * Enum for cache modes
59
- */
60
- exports.CacheMode = void 0;
61
- (function (CacheMode) {
62
- CacheMode["DEFAULT"] = "default";
63
- CacheMode["NO_STORE"] = "no-store";
64
- CacheMode["RELOAD"] = "reload";
65
- CacheMode["NO_CACHE"] = "no-cache";
66
- CacheMode["FORCE_CACHE"] = "force-cache";
67
- CacheMode["ONLY_IF_CACHED"] = "only-if-cached";
68
- })(exports.CacheMode || (exports.CacheMode = {}));
69
-
70
- class RequestError extends Error {
71
- constructor(message, url, method, options = {}) {
72
- super(message);
73
- this.name = "RequestError";
74
- this.url = url;
75
- this.method = method;
76
- this.status = options.status;
77
- this.response = options.response;
78
- this.timeoutError = options.timeoutError;
79
- // For better stack traces in modern environments
80
- if (Error.captureStackTrace) {
81
- Error.captureStackTrace(this, RequestError);
82
- }
83
- // Maintains proper prototype chain for instanceof checks
84
- Object.setPrototypeOf(this, RequestError.prototype);
85
- }
86
- /**
87
- * Static methods for creating specific types of RequestError
88
- */
89
- static timeout(url, method, timeoutMs) {
90
- return new RequestError(`Request timed out after ${timeoutMs}ms`, url, method, {
91
- timeoutError: true,
92
- });
93
- }
94
- static fromResponse(response, url, method) {
95
- return new RequestError(`Request failed with status ${response.status}`, url, method, {
96
- status: response.status,
97
- response,
98
- });
99
- }
100
- static networkError(url, method, originalError) {
101
- const error = new RequestError(`Network error: ${originalError.message}`, url, method);
102
- error.stack = originalError.stack;
103
- return error;
104
- }
105
- }
106
-
107
- /**
108
- * Wrapper for HTTP responses with methods to transform the response data
109
- */
110
- class ResponseWrapper {
111
- constructor(response) {
112
- this.response = response;
113
- this.ok = response.status >= 200 && response.status < 300; // Standard Fetch API behavior
114
- }
115
- /**
116
- * Get the raw Response object
117
- */
118
- get raw() {
119
- return this.response;
120
- }
121
- /**
122
- * Get the HTTP status code
123
- */
124
- get status() {
125
- return this.response.status;
126
- }
127
- /**
128
- * Get the HTTP status text
129
- */
130
- get statusText() {
131
- return this.response.statusText;
132
- }
133
- /**
134
- * Get response headers
135
- */
136
- get headers() {
137
- return this.response.headers;
138
- }
139
- /**
140
- * Parse response as JSON
141
- */
142
- async json() {
143
- return this.response.json();
144
- }
145
- /**
146
- * Get response as text
147
- */
148
- async text() {
149
- return this.response.text();
150
- }
151
- /**
152
- * Get response as Blob
153
- */
154
- async blob() {
155
- return this.response.blob();
156
- }
157
- /**
158
- * Get response as ArrayBuffer
159
- */
160
- async arrayBuffer() {
161
- return this.response.arrayBuffer();
162
- }
163
- /**
164
- * Get response as ReadableStream
165
- */
166
- body() {
167
- return this.response.body;
168
- }
169
- }
170
-
171
- // Base class with common functionality for all request types
172
- class BaseRequest {
173
- constructor() {
174
- this.requestOptions = {};
175
- this.queryParams = new URLSearchParams();
176
- }
177
- withHeaders(headers) {
178
- this.requestOptions.headers = {
179
- ...(this.requestOptions.headers || {}),
180
- ...headers,
181
- };
182
- return this;
183
- }
184
- withTimeout(timeout) {
185
- this.requestOptions.timeout = timeout;
186
- return this;
187
- }
188
- withRetries(retries) {
189
- this.requestOptions.retries = retries;
190
- return this;
191
- }
192
- onRetry(callback) {
193
- this.requestOptions.onRetry = callback;
194
- return this;
195
- }
196
- /**
197
- * Sets the credentials policy for the request
198
- * @param credentialsPolicy - Can be 'omit', 'same-origin', or 'include'
199
- * @returns The instance for chaining
200
- */
201
- withCredentials(credentialsPolicy = exports.CredentialsPolicy.SAME_ORIGIN) {
202
- this.requestOptions.credentials = credentialsPolicy;
203
- return this;
204
- }
205
- /**
206
- * Allows providing an external AbortController to cancel the request
207
- * @param controller - The AbortController to use for this request
208
- * @returns The instance for chaining
209
- */
210
- withAbortController(controller) {
211
- this.abortController = controller;
212
- return this;
213
- }
214
- /**
215
- * Sets the referrer for the request
216
- * @param referrer - The referrer URL or policy
217
- * @returns The instance for chaining
218
- */
219
- withReferrer(referrer) {
220
- this.requestOptions.referrer = referrer;
221
- return this;
222
- }
223
- /**
224
- * Sets the redirect policy for the request
225
- * @param redirect - Can be 'follow', 'error', or 'manual'
226
- * @returns The instance for chaining
227
- */
228
- withRedirect(redirect) {
229
- this.requestOptions.redirect = redirect;
230
- return this;
231
- }
232
- /**
233
- * Sets the keepalive flag for the request
234
- * @param keepalive - Whether to allow the request to outlive the page
235
- * @returns The instance for chaining
236
- */
237
- withKeepAlive(keepalive) {
238
- this.requestOptions.keepalive = keepalive;
239
- return this;
240
- }
241
- /**
242
- * Sets the priority of the request
243
- * @param priority - Can be 'high', 'low', or 'auto'
244
- * @returns The instance for chaining
245
- */
246
- withPriority(priority) {
247
- this.requestOptions.priority = priority;
248
- return this;
249
- }
250
- /**
251
- * Adds query parameters to the request URL
252
- * @param params - An object containing the query parameters
253
- * @returns The instance for chaining
254
- */
255
- withQueryParams(params) {
256
- Object.entries(params).forEach(([key, value]) => {
257
- if (value === null || value === undefined) {
258
- return;
259
- }
260
- if (Array.isArray(value)) {
261
- // Handle array values - add multiple entries with the same key
262
- value.forEach(v => this.queryParams.append(key, String(v)));
263
- }
264
- else {
265
- this.queryParams.append(key, String(value));
266
- }
267
- });
268
- return this;
269
- }
270
- /**
271
- * Adds a single query parameter
272
- * @param key - The parameter name
273
- * @param value - The parameter value
274
- * @returns The instance for chaining
275
- */
276
- withQueryParam(key, value) {
277
- if (value !== null && value !== undefined) {
278
- this.queryParams.append(key, String(value));
279
- }
280
- return this;
281
- }
282
- /**
283
- * Sets the mode of the request
284
- * @param mode - The mode for the request (cors, no-cors, same-origin, navigate)
285
- * @returns The instance for chaining
286
- */
287
- withMode(mode) {
288
- this.requestOptions.mode = mode;
289
- return this;
290
- }
291
- /**
292
- * Shorthand for setting the Content-Type header
293
- * @param contentType - The content type
294
- * @returns The instance for chaining
295
- */
296
- withContentType(contentType) {
297
- return this.withHeaders({
298
- "Content-Type": contentType,
299
- });
300
- }
301
- /**
302
- * Shorthand for setting the Authorization header
303
- * @param authValue - The authorization value
304
- * @returns The instance for chaining
305
- */
306
- withAuthorization(authValue) {
307
- return this.withHeaders({
308
- Authorization: authValue,
309
- });
310
- }
311
- /**
312
- * Shorthand for setting up Basic authentication
313
- * @param username - The username
314
- * @param password - The password
315
- * @returns The instance for chaining
316
- */
317
- withBasicAuth(username, password) {
318
- const credentials = btoa(`${username}:${password}`);
319
- return this.withAuthorization(`Basic ${credentials}`);
320
- }
321
- /**
322
- * Sets the bearer token for authentication
323
- * @param token - The bearer token
324
- * @returns The instance for chaining
325
- */
326
- withBearerToken(token) {
327
- return this.withAuthorization(`Bearer ${token}`);
328
- }
329
- /**
330
- * Sets cookies for the request
331
- * @param cookies - An object containing cookie name-value pairs
332
- * @returns The instance for chaining
333
- */
334
- withCookies(cookies) {
335
- const cookieEntries = Object.entries(cookies);
336
- if (cookieEntries.length === 0) {
337
- return this;
338
- }
339
- // Format cookies as name=value pairs
340
- const cookieString = cookieEntries
341
- .map(([name, value]) => `${encodeURIComponent(name)}=${encodeURIComponent(value)}`)
342
- .join("; ");
343
- // Get current headers or initialize empty object
344
- const currentHeaders = this.requestOptions.headers || {};
345
- // If there's already a Cookie header, append to it; otherwise create a new one
346
- const existingCookies = currentHeaders["Cookie"] || "";
347
- const newCookieValue = existingCookies ? `${existingCookies}; ${cookieString}` : cookieString;
348
- // Set the Cookie header
349
- return this.withHeaders({
350
- Cookie: newCookieValue,
351
- });
352
- }
353
- /**
354
- * Send the request to the specified URL
355
- * @param url The URL to send the request to
356
- */
357
- sendTo(url) {
358
- // Format the URL with query parameters
359
- url = this.formatUrlWithQueryParams(url);
360
- // Cast the request options to RequestInit to ensure compatibility
361
- const fetchOptions = {
362
- ...this.requestOptions,
363
- method: this.method,
364
- };
365
- // Create the base promise
366
- const basePromise = !this.requestOptions.retries
367
- ? this.executeRequest(url, fetchOptions)
368
- : this.executeWithRetries(url, fetchOptions);
369
- // Enhance the promise with response methods
370
- const responsePromise = basePromise.then(response => response);
371
- // Attach convenience methods to the promise
372
- responsePromise.json = async () => {
373
- const response = await basePromise;
374
- return response.json();
375
- };
376
- responsePromise.text = async () => {
377
- const response = await basePromise;
378
- return response.text();
379
- };
380
- responsePromise.blob = async () => {
381
- const response = await basePromise;
382
- return response.blob();
383
- };
384
- responsePromise.arrayBuffer = async () => {
385
- const response = await basePromise;
386
- return response.arrayBuffer();
387
- };
388
- responsePromise.body = async () => {
389
- const response = await basePromise;
390
- return response.body();
391
- };
392
- return responsePromise;
393
- }
394
- /**
395
- * Formats the URL with any query parameters
396
- * @param url The base URL
397
- * @returns The URL with query parameters appended
398
- */
399
- formatUrlWithQueryParams(url) {
400
- if (!this.queryParams.toString()) {
401
- return url;
402
- }
403
- const urlObj = new URL(url);
404
- // Merge our query params with any that might be in the URL already
405
- this.queryParams.forEach((value, key) => {
406
- urlObj.searchParams.append(key, value);
407
- });
408
- return urlObj.toString();
409
- }
410
- /**
411
- * Executes a request with configured retry logic
412
- * @param url The formatted URL to send the request to
413
- * @param fetchOptions The fetch options to use
414
- * @returns A wrapped response object
415
- */
416
- async executeWithRetries(url, fetchOptions) {
417
- let retryCount = 0;
418
- const maxRetries = this.requestOptions.retries || 0;
419
- // eslint-disable-next-line no-constant-condition
420
- while (true) {
421
- try {
422
- return await this.executeRequest(url, fetchOptions);
423
- }
424
- catch (error) {
425
- const requestError = error instanceof RequestError
426
- ? error
427
- : RequestError.networkError(url, fetchOptions.method, error);
428
- if (retryCount >= maxRetries || requestError.timeoutError) {
429
- throw requestError;
430
- }
431
- retryCount++;
432
- if (this.requestOptions.onRetry) {
433
- await this.requestOptions.onRetry({ retryCount, error: requestError });
434
- }
435
- }
436
- }
437
- }
438
- async executeRequest(url, fetchOptions) {
439
- // Create a request controller for timeout if needed, or use the provided one
440
- const controller = this.abortController || new AbortController();
441
- const { signal } = controller;
442
- // Use the controller signal for the fetch request, but don't overwrite an existing signal
443
- // that might have been set in requestOptions if it exists
444
- fetchOptions.signal = fetchOptions.signal || signal;
445
- let timeoutId;
446
- // If we have a timeout and we're using our own controller (not provided externally)
447
- if (this.requestOptions.timeout && !this.abortController) {
448
- timeoutId = setTimeout(() => {
449
- controller.abort();
450
- }, this.requestOptions.timeout);
451
- }
452
- try {
453
- let response;
454
- try {
455
- response = await fetch(url, fetchOptions);
456
- }
457
- catch (error) {
458
- // Check if this is an abort error from our timeout
459
- if (error instanceof DOMException && error.name === "AbortError" && timeoutId) {
460
- throw RequestError.timeout(url, fetchOptions.method, this.requestOptions.timeout);
461
- }
462
- // Otherwise it's a network error
463
- throw RequestError.networkError(url, fetchOptions.method, error);
464
- }
465
- if (!response.ok) {
466
- throw RequestError.fromResponse(response, url, fetchOptions.method);
467
- }
468
- // Return a wrapped response instead of parsing it
469
- return new ResponseWrapper(response);
470
- }
471
- finally {
472
- if (timeoutId) {
473
- clearTimeout(timeoutId);
474
- }
475
- }
476
- }
477
- }
478
-
479
- // An extension of BaseRequest for methods that support request bodies
480
- class BodyRequest extends BaseRequest {
481
- /**
482
- * Sets the request body with appropriate content type handling
483
- */
484
- withBody(body) {
485
- if (body === undefined || body === null) {
486
- this.requestOptions.body = null;
487
- return this;
488
- }
489
- // Handle special body types that don't need transformation
490
- if (body instanceof Blob ||
491
- body instanceof FormData ||
492
- body instanceof URLSearchParams ||
493
- body instanceof ArrayBuffer ||
494
- body instanceof ReadableStream) {
495
- this.requestOptions.body = body;
496
- // For FormData, make sure to NOT explicitly set Content-Type
497
- // The browser will set it automatically with the correct boundary
498
- // If we set it manually, it would be missing the boundary parameter
499
- return this;
500
- }
501
- // Handle strings
502
- if (typeof body === "string") {
503
- this.requestOptions.body = body;
504
- return this;
505
- }
506
- // For objects and other types, stringify and set JSON content-type
507
- try {
508
- this.requestOptions.body = JSON.stringify(body);
509
- this.requestOptions.headers = {
510
- "Content-Type": "application/json",
511
- ...(this.requestOptions.headers || {}),
512
- };
513
- }
514
- catch (error) {
515
- const errorMessage = error instanceof Error ? error.message : String(error);
516
- throw new Error(`Failed to stringify request body: ${errorMessage}`);
517
- }
518
- return this;
519
- }
520
- }
521
-
522
- // Methods without body
523
- class GetRequest extends BaseRequest {
524
- constructor() {
525
- super(...arguments);
526
- this.method = exports.HttpMethod.GET;
527
- }
528
- }
529
- class HeadRequest extends BaseRequest {
530
- constructor() {
531
- super(...arguments);
532
- this.method = exports.HttpMethod.HEAD;
533
- }
534
- }
535
- class OptionsRequest extends BaseRequest {
536
- constructor() {
537
- super(...arguments);
538
- this.method = exports.HttpMethod.OPTIONS;
539
- }
540
- }
541
- class DeleteRequest extends BaseRequest {
542
- constructor() {
543
- super(...arguments);
544
- this.method = exports.HttpMethod.DELETE;
545
- }
546
- }
547
- // Methods with body
548
- class PostRequest extends BodyRequest {
549
- constructor() {
550
- super(...arguments);
551
- this.method = exports.HttpMethod.POST;
552
- }
553
- }
554
- class PutRequest extends BodyRequest {
555
- constructor() {
556
- super(...arguments);
557
- this.method = exports.HttpMethod.PUT;
558
- }
559
- }
560
- class PatchRequest extends BodyRequest {
561
- constructor() {
562
- super(...arguments);
563
- this.method = exports.HttpMethod.PATCH;
564
- }
565
- }
566
-
567
- /**
568
- * Create a GET request
569
- */
570
- function get() {
571
- return new GetRequest();
572
- }
573
- /**
574
- * Create a POST request
575
- */
576
- function post() {
577
- return new PostRequest();
578
- }
579
- /**
580
- * Create a PUT request
581
- */
582
- function put() {
583
- return new PutRequest();
584
- }
585
- /**
586
- * Create a DELETE request
587
- * Note: We use 'del' to avoid JS keyword conflict
588
- */
589
- function del() {
590
- return new DeleteRequest();
591
- }
592
- /**
593
- * Create a PATCH request
594
- */
595
- function patch() {
596
- return new PatchRequest();
597
- }
598
- /**
599
- * Create a HEAD request
600
- */
601
- function head() {
602
- return new HeadRequest();
603
- }
604
- /**
605
- * Create an OPTIONS request
606
- */
607
- function options() {
608
- return new OptionsRequest();
609
- }
610
-
611
- // Create the main API object
612
- const create = {
613
- get,
614
- post,
615
- put,
616
- del,
617
- patch,
618
- head,
619
- options,
620
- };
621
-
622
- exports.DeleteRequest = DeleteRequest;
623
- exports.GetRequest = GetRequest;
624
- exports.HeadRequest = HeadRequest;
625
- exports.OptionsRequest = OptionsRequest;
626
- exports.PatchRequest = PatchRequest;
627
- exports.PostRequest = PostRequest;
628
- exports.PutRequest = PutRequest;
629
- exports.RequestError = RequestError;
630
- exports.ResponseWrapper = ResponseWrapper;
631
- exports["default"] = create;
632
-
633
- Object.defineProperty(exports, '__esModule', { value: true });
634
-
635
- }));
1
+ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).createRequest={})}(this,(function(t){"use strict";var e,s,r,i,n,o,h,a,c;t.HttpMethod=void 0,(e=t.HttpMethod||(t.HttpMethod={})).GET="GET",e.PUT="PUT",e.POST="POST",e.HEAD="HEAD",e.PATCH="PATCH",e.DELETE="DELETE",e.OPTIONS="OPTIONS",t.RequestPriority=void 0,(s=t.RequestPriority||(t.RequestPriority={})).LOW="low",s.HIGH="high",s.AUTO="auto",t.CredentialsPolicy=void 0,(r=t.CredentialsPolicy||(t.CredentialsPolicy={})).OMIT="omit",r.INCLUDE="include",r.SAME_ORIGIN="same-origin",t.RequestMode=void 0,(i=t.RequestMode||(t.RequestMode={})).CORS="cors",i.NO_CORS="no-cors",i.SAME_ORIGIN="same-origin",i.NAVIGATE="navigate",t.RedirectMode=void 0,(n=t.RedirectMode||(t.RedirectMode={})).ERROR="error",n.FOLLOW="follow",n.MANUAL="manual",t.CacheMode=void 0,(o=t.CacheMode||(t.CacheMode={})).DEFAULT="default",o.RELOAD="reload",o.NO_STORE="no-store",o.NO_CACHE="no-cache",o.FORCE_CACHE="force-cache",o.ONLY_IF_CACHED="only-if-cached",t.SameSitePolicy=void 0,(h=t.SameSitePolicy||(t.SameSitePolicy={})).LAX="Lax",h.NONE="None",h.STRICT="Strict",function(t){t.JSON="json",t.STRING="string",t.BINARY="binary"}(a||(a={})),t.ReferrerPolicy=void 0,(c=t.ReferrerPolicy||(t.ReferrerPolicy={})).ORIGIN="origin",c.UNSAFE_URL="unsafe-url",c.SAME_ORIGIN="same-origin",c.NO_REFERRER="no-referrer",c.STRICT_ORIGIN="strict-origin",c.ORIGIN_WHEN_CROSS_ORIGIN="origin-when-cross-origin",c.NO_REFERRER_WHEN_DOWNGRADE="no-referrer-when-downgrade",c.STRICT_ORIGIN_WHEN_CROSS_ORIGIN="strict-origin-when-cross-origin";class u{constructor(t){this.bodyUsed=!1,this.response=t}get status(){return this.response.status}get statusText(){return this.response.statusText}get headers(){return this.response.headers}get ok(){return this.response.ok}get raw(){return this.response}async getJson(){if(void 0!==this.jsonCache)return this.jsonCache;if(this.bodyUsed){if(void 0!==this.textCache)try{return this.jsonCache=JSON.parse(this.textCache),this.jsonCache}catch(t){throw Error("Cannot parse cached text as JSON")}throw Error("Response body has already been consumed in a different format")}return this.bodyUsed=!0,this.jsonCache=await this.response.json(),this.jsonCache}async getText(){if(void 0!==this.textCache)return this.textCache;if(this.bodyUsed){if(void 0!==this.jsonCache)return this.textCache=JSON.stringify(this.jsonCache),this.textCache;if(void 0!==this.blobCache)return this.textCache=await this.blobCache.text(),this.textCache;throw Error("Response body has already been consumed in a format that cannot be converted to text")}return this.bodyUsed=!0,this.textCache=await this.response.text(),this.textCache}async getBlob(){if(void 0!==this.blobCache)return this.blobCache;if(this.bodyUsed){if(void 0!==this.textCache)return this.blobCache=new Blob([this.textCache],{type:"text/plain"}),this.blobCache;throw Error("Response body has already been consumed in a format that cannot be converted to Blob")}return this.bodyUsed=!0,this.blobCache=await this.response.blob(),this.blobCache}async getArrayBuffer(){if(void 0!==this.arrayBufferCache)return this.arrayBufferCache;if(this.bodyUsed){if(void 0!==this.textCache){const t=(new TextEncoder).encode(this.textCache);return this.arrayBufferCache=t.buffer,this.arrayBufferCache}if(void 0!==this.blobCache)return this.arrayBufferCache=await this.blobCache.arrayBuffer(),this.arrayBufferCache;throw Error("Response body has already been consumed in a format that cannot be converted to ArrayBuffer")}return this.bodyUsed=!0,this.arrayBufferCache=await this.response.arrayBuffer(),this.arrayBufferCache}getBody(){if(this.bodyUsed)throw Error("Response body has already been consumed");return this.bodyUsed=!0,this.response.body}}function f(){const t=new Map;return{get:e=>t.get(e)||null,set(e,s){t.set(e,s)},has:e=>t.has(e),delete(e){t.delete(e)},clear(){t.clear()}}}function l(){return{get:t=>"undefined"==typeof localStorage?null:localStorage.getItem(t),set(t,e){if("undefined"!=typeof localStorage)try{localStorage.setItem(t,e)}catch(s){console.warn("Cache storage quota exceeded, clearing cache"),this.clear();try{localStorage.setItem(t,e)}catch(t){console.error("Failed to set cache item even after clearing cache")}}},has:t=>"undefined"!=typeof localStorage&&null!==localStorage.getItem(t),delete(t){"undefined"!=typeof localStorage&&localStorage.removeItem(t)},clear(){"undefined"!=typeof localStorage&&localStorage.clear()}}}function d(){return{get:t=>"undefined"==typeof sessionStorage?null:sessionStorage.getItem(t),set(t,e){if("undefined"!=typeof sessionStorage)try{sessionStorage.setItem(t,e)}catch(s){console.warn("Cache storage quota exceeded, clearing cache"),this.clear();try{sessionStorage.setItem(t,e)}catch(t){console.error("Failed to set cache item even after clearing cache")}}},has:t=>"undefined"!=typeof sessionStorage&&null!==sessionStorage.getItem(t),delete(t){"undefined"!=typeof sessionStorage&&sessionStorage.removeItem(t)},clear(){"undefined"!=typeof sessionStorage&&sessionStorage.clear()}}}class y{constructor(t={}){this.entryCount=0,this.totalSize=0,this.options=t,this.storage=function(t){const{storage:e}=t||{};return e?"function"==typeof e.get&&"function"==typeof e.set?e:e===localStorage?l():e===sessionStorage?d():e instanceof Map?{get:t=>e.get(t)||null,set(t,s,r){e.set(t,s)},has:t=>e.has(t),delete(t){e.delete(t)},clear(){e.clear()}}:(console.warn("Unsupported storage type, falling back to memory storage"),f()):f()}(t)}generateKey(t,e,s,r){if(this.options.keyGenerator){const i=this.options.keyGenerator(t,e,s,r);return this.options.keyPrefix?`${this.options.keyPrefix}:${i}`:i}let i=`${e}:${t}`;if(this.options.varyByHeaders&&s){const t={};this.options.varyByHeaders.forEach((e=>{const r=e.toLowerCase();Object.keys(s).forEach((e=>{e.toLowerCase()===r&&(t[r]=s[e])}))})),Object.keys(t).length>0&&(i+=":"+JSON.stringify(t))}if("GET"!==e&&null!=r)try{"string"==typeof r||"number"==typeof r||"boolean"==typeof r?i+=":"+r:"object"==typeof r&&(i+=":"+JSON.stringify(r))}catch(t){console.warn("Failed to stringify request body for cache key")}return this.options.keyPrefix?`${this.options.keyPrefix}:${i}`:i}async get(t){const e=await Promise.resolve(this.storage.get(t));if(!e)return null;try{const s=JSON.parse(e);return s.expiry&&s.expiry<Date.now()?(await Promise.resolve(this.storage.delete(t)),null):s}catch(e){return await Promise.resolve(this.storage.delete(t)),null}}async set(t,e,s){const r=Date.now(),i=this.options.ttl,n=JSON.stringify({value:e,timestamp:r,expiry:i?r+i:null,headers:s});if(this.options.maxSize){const t=function(t){var e;if("number"==typeof t)return t;const s=t.match(/^(\d+(?:\.\d+)?)\s*(KB|MB|GB)?$/i);if(!s)return 0;const r=parseFloat(s[1]);switch(null===(e=s[2])||void 0===e?void 0:e.toUpperCase()){case"KB":return 1024*r;case"MB":return 1048576*r;case"GB":return 1073741824*r;default:return r}}(this.options.maxSize),e=(new TextEncoder).encode(n).length;if(e>t)return void console.warn(`Cache entry size (${e} bytes) exceeds maximum cache size (${t} bytes)`);this.totalSize+e>t&&(await Promise.resolve(this.storage.clear()),this.totalSize=0,this.entryCount=0),this.totalSize+=e}this.options.maxEntries&&(this.entryCount++,this.entryCount>this.options.maxEntries&&(await Promise.resolve(this.storage.clear()),this.entryCount=1)),await Promise.resolve(this.storage.set(t,n,i))}async has(t){return Promise.resolve(this.storage.has(t))}async delete(t){return Promise.resolve(this.storage.delete(t))}async clear(){return this.entryCount=0,this.totalSize=0,Promise.resolve(this.storage.clear())}}class w{static formatRequestCookies(t){const e=[];return Object.entries(t).forEach((([t,s])=>{let r;r="string"==typeof s?s:s.value,e.push(`${encodeURIComponent(t)}=${encodeURIComponent(r)}`)})),e.join("; ")}}class g extends Error{constructor(t,e,s,r={}){super(t),this.name="RequestError",this.url=e,this.method=s,this.status=r.status,this.response=r.response,this.timeoutError=r.timeoutError,Error.captureStackTrace&&Error.captureStackTrace(this,g),Object.setPrototypeOf(this,g.prototype)}static timeout(t,e,s){return new g(`Request timed out after ${s}ms`,t,e,{timeoutError:!0})}static fromResponse(t,e,s){return new g("Request failed with status "+t.status,e,s,{status:t.status,response:t})}static networkError(t,e,s){const r=new g("Network error: "+s.message,t,e);return r.stack=s.stack,r}}class p{static getTokenFromMeta(t="csrf-token"){if("undefined"==typeof document)return null;const e=document.querySelector(`meta[name="${t}"]`);return(null==e?void 0:e.getAttribute("content"))||null}static getTokenFromCookie(t="csrf-token"){if("undefined"==typeof document)return null;const e=document.cookie.split(";");for(const s of e){const[e,r]=s.trim().split("=");if(e===t)return decodeURIComponent(r)}return null}static isValidToken(t){return!("string"!=typeof t||8>t.length||t.length>10&&(!/^[A-Za-z0-9\-_=+/.]+$/.test(t)||2>[/[A-Z]/.test(t),/[a-z]/.test(t),/[0-9]/.test(t),/[-_=+/.]/.test(t)].filter(Boolean).length))}}class m{constructor(){this.csrfHeaderName="X-CSRF-Token",this.xsrfCookieName="XSRF-TOKEN",this.xsrfHeaderName="X-XSRF-TOKEN",this.csrfToken=null,this.enableAutoXsrf=!0,this.enableAntiCsrf=!0}static getInstance(){return m.instance||(m.instance=new m),m.instance}setCsrfToken(t){return this.csrfToken=t,this}getCsrfToken(){return this.csrfToken}setCsrfHeaderName(t){return this.csrfHeaderName=t,this}getCsrfHeaderName(){return this.csrfHeaderName}setXsrfCookieName(t){return this.xsrfCookieName=t,this}getXsrfCookieName(){return this.xsrfCookieName}setXsrfHeaderName(t){return this.xsrfHeaderName=t,this}getXsrfHeaderName(){return this.xsrfHeaderName}setEnableAutoXsrf(t){return this.enableAutoXsrf=t,this}isAutoXsrfEnabled(){return this.enableAutoXsrf}setEnableAntiCsrf(t){return this.enableAntiCsrf=t,this}isAntiCsrfEnabled(){return this.enableAntiCsrf}reset(){return this.csrfToken=null,this.csrfHeaderName="X-CSRF-Token",this.enableAntiCsrf=!0,this.xsrfCookieName="XSRF-TOKEN",this.xsrfHeaderName="X-XSRF-TOKEN",this.enableAutoXsrf=!0,this}}class b{constructor(){this.requestOptions={headers:{}},this.queryParams=new URLSearchParams,this.autoApplyCsrfProtection=!0,this.cacheEnabled=!1}withHeaders(t){return this.requestOptions.headers={...this.requestOptions.headers,...t},this}withHeader(t,e){return this.withHeaders({[t]:e})}withTimeout(t){if(!Number.isFinite(t)||0>=t)throw Error("Timeout must be a positive number");return this.requestOptions.timeout=t,this}withRetries(t){if(!Number.isInteger(t)||0>t)throw Error("Retry count must be a non-negative integer");return this.requestOptions.retries=t,this}onRetry(t){return this.requestOptions.onRetry=t,this}withCredentials(e=t.CredentialsPolicy.SAME_ORIGIN){return this.requestOptions.credentials=e,this}withAbortController(t){return this.abortController=t,this}withReferrer(t){return this.requestOptions.referrer=t,this}withReferrerPolicy(t){return this.requestOptions.referrerPolicy=t,this}withRedirect(t){return this.requestOptions.redirect=t,this}withKeepAlive(t){return this.requestOptions.keepalive=t,this}withPriority(t){return this.requestOptions.priority=t,this}withQueryParams(t){return Object.entries(t).forEach((([t,e])=>{null!=e&&(Array.isArray(e)?e.forEach((e=>this.queryParams.append(t,e+""))):this.queryParams.append(t,e+""))})),this}withQueryParam(t,e){return null==e||(Array.isArray(e)?e.forEach((e=>this.queryParams.append(t,e+""))):this.queryParams.append(t,e+"")),this}withMode(t){return this.requestOptions.mode=t,this}withContentType(t){return this.withHeaders({"Content-Type":t})}withAuthorization(t){return this.withHeaders({Authorization:t})}withBasicAuth(t,e){const s=this.encodeBase64(`${t}:${e}`);return this.withAuthorization("Basic "+s)}encodeBase64(t){if("undefined"!=typeof TextEncoder&&"function"==typeof btoa){const e=(new TextEncoder).encode(t);return btoa(String.fromCharCode.call(null,...new Uint8Array(e)))}if("function"==typeof btoa)return btoa(t);if("undefined"!=typeof Buffer)return Buffer.from(t).toString("base64");throw Error("Base64 encoding is not supported in this environment")}withBearerToken(t){return this.withAuthorization("Bearer "+t)}hasHeader(t,e){return Object.keys(t).some((t=>t.toLowerCase()===e.toLowerCase()))}withCookies(t){if(0===Object.entries(t).length)return this;const e=this.requestOptions.headers||{},s=[],r=[];Object.keys(e).forEach((t=>{"cookie"===t.toLowerCase()&&(e[t]&&s.push(e[t]),r.push(t))}));const i=w.formatRequestCookies(t),n=r.length>0?r[0]:"Cookie",o=[...s,i].filter(Boolean).join("; "),h={...e};return r.forEach((t=>{delete h[t]})),this.requestOptions.headers={...h,[n]:o},this}withCookie(t,e){return this.withCookies({[t]:e})}withCsrfToken(t,e="X-CSRF-Token"){return this.withHeaders({[e]:t})}withoutCsrfProtection(){return this.autoApplyCsrfProtection=!1,this}withAntiCsrfHeaders(){return this.withHeaders({"X-Requested-With":"XMLHttpRequest"})}withCache(t={}){return this.cacheEnabled=!0,this.cacheManager=new y(t),this}sendTo(t){if(t=this.formatUrlWithQueryParams(t),this.autoApplyCsrfProtection){const t=m.getInstance();t.isAntiCsrfEnabled()&&this.withHeaders({"X-Requested-With":"XMLHttpRequest"});const e=t.getCsrfToken();if(e){const s=this.requestOptions.headers,r=t.getCsrfHeaderName();this.hasHeader(s,"X-CSRF-Token")||this.hasHeader(s,r)||this.withHeaders({[r]:e})}if(t.isAutoXsrfEnabled()&&"undefined"!=typeof document){const e=p.getTokenFromCookie(t.getXsrfCookieName());if(e&&p.isValidToken(e)){const s=this.requestOptions.headers,r=t.getXsrfHeaderName();this.hasHeader(s,"X-XSRF-TOKEN")||this.hasHeader(s,r)||this.withHeaders({[r]:e})}}}const e={...this.requestOptions,method:this.method};let s;if(this.cacheEnabled&&this.cacheManager){const r=this.cacheManager.generateKey(t,this.method,this.requestOptions.headers,this.requestOptions.body);s=this.executeWithCache(t,e,r)}else s=this.requestOptions.retries?this.executeWithRetries(t,e):this.executeRequest(t,e);const r=s;return r.getJson=async()=>s.then((t=>t.getJson())),r.getText=async()=>s.then((t=>t.getText())),r.getBlob=async()=>s.then((t=>t.getBlob())),r.getArrayBuffer=async()=>s.then((t=>t.getArrayBuffer())),r.getBody=async()=>s.then((t=>t.getBody())),r.getData=async t=>{try{const e=await s.then((t=>t.getJson()));return t?t(e):e}catch(t){const e=Error(`Data selector failed: ${t instanceof Error?t.message:t+""}. Original data: ${JSON.stringify(await s.then((t=>t.getJson())),null,2)}`);throw t instanceof Error&&t.stack&&(e.stack=t.stack),e}},r}formatUrlWithQueryParams(t){if(!(""+this.queryParams))return t;try{const e=new URL(t);return this.queryParams.forEach(((t,s)=>{e.searchParams.append(s,t)})),""+e}catch(e){const s=t.includes("?");return`${t}${s?"&":"?"}${""+this.queryParams}`}}async executeWithRetries(t,e){const s=this.requestOptions.retries||0;for(let r=0;s>=r;r++)try{return await this.executeRequest(t,e)}catch(i){const n=i instanceof g?i:g.networkError(t,e.method,i);if(r>=s)throw n;this.requestOptions.onRetry&&await this.requestOptions.onRetry({attempt:r+1,error:n})}throw new g("Max retries reached",t,e.method)}async executeRequest(t,e){const s=this.abortController||new AbortController,{signal:r}=s;let i;e.signal=e.signal||r;let n=!1;this.requestOptions.timeout&&(this.abortController?"function"==typeof AbortSignal.timeout?AbortSignal.timeout(this.requestOptions.timeout).addEventListener("abort",(()=>{s.signal.aborted||(n=!0,s.abort())})):i=setTimeout((()=>{s.signal.aborted||(n=!0,s.abort())}),this.requestOptions.timeout):i=setTimeout((()=>{n=!0,s.abort()}),this.requestOptions.timeout));try{let s;try{s=await fetch(t,e)}catch(s){if(s instanceof DOMException&&"AbortError"===s.name&&n)throw g.timeout(t,e.method,this.requestOptions.timeout);throw g.networkError(t,e.method,s)}if(!s.ok)throw g.fromResponse(s,t,e.method);return new u(s)}finally{i&&clearTimeout(i)}}async executeWithCache(t,e,s){if(this.cacheManager){const t=await this.cacheManager.get(s);if(t){const e=new Response(JSON.stringify(t.value),{status:200,headers:new Headers(t.headers||{})});return new u(e)}}const r=await(this.requestOptions.retries?this.executeWithRetries(t,e):this.executeRequest(t,e));if(r.ok&&this.cacheManager)try{const t=await r.getJson(),e={};r.headers.forEach(((t,s)=>{e[s]=t})),await this.cacheManager.set(s,t,e)}catch(t){console.warn("Failed to cache response:",t)}return r}}class S extends b{withBody(t){if(this.body=t,"string"==typeof t)this.bodyType=a.STRING,this.setContentTypeIfNeeded("text/plain");else if(null===t||"object"!=typeof t||t instanceof FormData||t instanceof Blob||t instanceof ArrayBuffer||t instanceof URLSearchParams||t instanceof ReadableStream)this.bodyType=a.BINARY;else{this.bodyType=a.JSON,this.setContentTypeIfNeeded("application/json");try{JSON.stringify(t)}catch(t){throw Error("Failed to stringify request body: "+t)}}return this}setContentTypeIfNeeded(t){Object.keys(this.requestOptions.headers).some((t=>"content-type"===t.toLowerCase()))||this.withContentType(t)}sendTo(t){return void 0!==this.body&&(this.requestOptions.body&&delete this.requestOptions.body,this.requestOptions.body=this.bodyType===a.JSON?JSON.stringify(this.body):this.body),super.sendTo(t)}}class T extends b{constructor(){super(...arguments),this.method=t.HttpMethod.GET}}class E extends b{constructor(){super(...arguments),this.method=t.HttpMethod.HEAD}}class R extends b{constructor(){super(...arguments),this.method=t.HttpMethod.OPTIONS}}class v extends b{constructor(){super(...arguments),this.method=t.HttpMethod.DELETE}}class C extends S{constructor(){super(...arguments),this.method=t.HttpMethod.POST}}class x extends S{constructor(){super(...arguments),this.method=t.HttpMethod.PUT}}class O extends S{constructor(){super(...arguments),this.method=t.HttpMethod.PATCH}}const N={get:function(){return new T},post:function(){return new C},put:function(){return new x},del:function(){return new v},patch:function(){return new O},head:function(){return new E},options:function(){return new R},config:m.getInstance()};t.CacheManager=y,t.CookieUtils=w,t.DeleteRequest=v,t.GetRequest=T,t.HeadRequest=E,t.OptionsRequest=R,t.PatchRequest=O,t.PostRequest=C,t.PutRequest=x,t.RequestError=g,t.ResponseWrapper=u,t.createLocalStorageStorage=l,t.createMemoryStorage=f,t.createSessionStorageStorage=d,t.default=N,Object.defineProperty(t,"t",{value:!0})}));//# sourceMappingURL=index.js.map