@indra211/exios 0.0.0-stage → 1.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.
package/dist/index.js ADDED
@@ -0,0 +1,1442 @@
1
+ // src/errors/ExiosError.ts
2
+ var ExiosError = class _ExiosError extends Error {
3
+ static ERR_BAD_REQUEST = "ERR_BAD_REQUEST";
4
+ static ERR_BAD_RESPONSE = "ERR_BAD_RESPONSE";
5
+ static ERR_NETWORK = "ERR_NETWORK";
6
+ static ECONNABORTED = "ECONNABORTED";
7
+ static ETIMEDOUT = "ETIMEDOUT";
8
+ static ERR_CANCELED = "ERR_CANCELED";
9
+ static ERR_BAD_OPTION_VALUE = "ERR_BAD_OPTION_VALUE";
10
+ static ERR_CIRCUIT_OPEN = "ERR_CIRCUIT_OPEN";
11
+ code;
12
+ config;
13
+ request;
14
+ response;
15
+ status;
16
+ isExiosError = true;
17
+ meta = { attempts: 0 };
18
+ constructor(message, code, config, request, response) {
19
+ super(message);
20
+ Object.setPrototypeOf(this, new.target.prototype);
21
+ this.name = "ExiosError";
22
+ this.code = code;
23
+ this.config = config;
24
+ this.request = request;
25
+ this.response = response;
26
+ this.status = response?.status;
27
+ }
28
+ toJSON() {
29
+ return {
30
+ message: this.message,
31
+ name: this.name,
32
+ code: this.code,
33
+ status: this.status,
34
+ config: this.config,
35
+ meta: this.meta,
36
+ stack: this.stack
37
+ };
38
+ }
39
+ static from(err, code, config, request, response) {
40
+ const message = err instanceof Error ? err.message : String(err);
41
+ const e = new _ExiosError(message, code, config, request, response);
42
+ e.cause = err;
43
+ return e;
44
+ }
45
+ };
46
+ var CanceledError = class extends ExiosError {
47
+ constructor(message = "canceled", config, request) {
48
+ super(message, ExiosError.ERR_CANCELED, config, request);
49
+ Object.setPrototypeOf(this, new.target.prototype);
50
+ this.name = "CanceledError";
51
+ }
52
+ };
53
+ var CircuitOpenError = class extends ExiosError {
54
+ origin;
55
+ retryAt;
56
+ constructor(origin, retryAt, config) {
57
+ super(`Circuit open for ${origin}`, ExiosError.ERR_CIRCUIT_OPEN, config);
58
+ Object.setPrototypeOf(this, new.target.prototype);
59
+ this.name = "CircuitOpenError";
60
+ this.origin = origin;
61
+ this.retryAt = retryAt;
62
+ }
63
+ };
64
+ function isExiosError(v) {
65
+ return v instanceof ExiosError || typeof v === "object" && v !== null && v.isExiosError === true;
66
+ }
67
+ function isCancel(v) {
68
+ return v instanceof CanceledError || isExiosError(v) && v.code === ExiosError.ERR_CANCELED;
69
+ }
70
+
71
+ // src/core/buildURL.ts
72
+ var ABSOLUTE_URL = /^([a-z][a-z\d+\-.]*:)?\/\//i;
73
+ function encode(s) {
74
+ return encodeURIComponent(s).replace(/%3A/gi, ":").replace(/%24/g, "$").replace(/%2C/gi, ",").replace(/%20/g, "+").replace(/%5B/gi, "[").replace(/%5D/gi, "]");
75
+ }
76
+ function isPlainObject(v) {
77
+ if (v === null || typeof v !== "object") return false;
78
+ const proto = Object.getPrototypeOf(v);
79
+ return proto === Object.prototype || proto === null;
80
+ }
81
+ function serializeParams(params, opts = {}) {
82
+ if (params === void 0 || params === null) return "";
83
+ if (params instanceof URLSearchParams) return params.toString();
84
+ const enc = opts.encode ?? encode;
85
+ const indexes = opts.indexes === void 0 ? false : opts.indexes;
86
+ const parts = [];
87
+ const add = (key, value) => {
88
+ if (value === void 0 || value === null) return;
89
+ if (value instanceof Date) {
90
+ parts.push(`${enc(key)}=${enc(value.toISOString())}`);
91
+ } else if (Array.isArray(value)) {
92
+ value.forEach(
93
+ (item, i) => add(indexes === null ? key : `${key}[${indexes ? i : ""}]`, item)
94
+ );
95
+ } else if (isPlainObject(value)) {
96
+ for (const k of Object.keys(value)) add(`${key}[${k}]`, value[k]);
97
+ } else {
98
+ parts.push(`${enc(key)}=${enc(String(value))}`);
99
+ }
100
+ };
101
+ for (const k of Object.keys(params)) add(k, params[k]);
102
+ return parts.join("&");
103
+ }
104
+ function buildURL(url, params, serializer) {
105
+ const hash = url.indexOf("#");
106
+ if (hash !== -1) url = url.slice(0, hash);
107
+ if (params === void 0 || params === null) return url;
108
+ let serialized;
109
+ if (typeof serializer === "function") serialized = serializer(params);
110
+ else if (serializer?.serialize) serialized = serializer.serialize(params);
111
+ else serialized = serializeParams(params, serializer ?? {});
112
+ if (!serialized) return url;
113
+ if (url.endsWith("?") || url.endsWith("&")) return url + serialized;
114
+ return url + (url.includes("?") ? "&" : "?") + serialized;
115
+ }
116
+ function buildFullPath(baseURL, url, allowAbsoluteUrls = true) {
117
+ const u = url ?? "";
118
+ if (!baseURL) return u;
119
+ if (allowAbsoluteUrls && ABSOLUTE_URL.test(u)) return u;
120
+ if (!u) return baseURL;
121
+ return `${baseURL.replace(/\/+$/, "")}/${u.replace(/^\/+/, "")}`;
122
+ }
123
+
124
+ // src/core/toFormData.ts
125
+ function toFormData(obj, fd = new FormData()) {
126
+ const append = (key, value) => {
127
+ if (value === void 0 || value === null) return;
128
+ if (value instanceof Blob) {
129
+ fd.append(key, value);
130
+ } else if (value instanceof Date) {
131
+ fd.append(key, value.toISOString());
132
+ } else if (Array.isArray(value)) {
133
+ for (const item of value) append(`${key}[]`, item);
134
+ } else if (typeof value === "object") {
135
+ for (const [k, v] of Object.entries(value)) append(`${key}[${k}]`, v);
136
+ } else {
137
+ fd.append(key, String(value));
138
+ }
139
+ };
140
+ for (const [k, v] of Object.entries(obj)) append(k, v);
141
+ return fd;
142
+ }
143
+
144
+ // src/core/transforms.ts
145
+ function isPlainObject2(v) {
146
+ if (v === null || typeof v !== "object") return false;
147
+ const proto = Object.getPrototypeOf(v);
148
+ return proto === Object.prototype || proto === null;
149
+ }
150
+ function isPassThrough(data) {
151
+ return typeof FormData !== "undefined" && data instanceof FormData || typeof Blob !== "undefined" && data instanceof Blob || data instanceof ArrayBuffer || ArrayBuffer.isView(data) || typeof ReadableStream !== "undefined" && data instanceof ReadableStream || data instanceof URLSearchParams;
152
+ }
153
+ function defaultTransformRequest(data, headers) {
154
+ if (data === void 0 || data === null) return void 0;
155
+ if (isPassThrough(data)) {
156
+ if (data instanceof URLSearchParams) {
157
+ if (!headers["content-type"])
158
+ headers["content-type"] = "application/x-www-form-urlencoded;charset=utf-8";
159
+ } else if (typeof FormData !== "undefined" && data instanceof FormData) {
160
+ delete headers["content-type"];
161
+ }
162
+ return data;
163
+ }
164
+ if (typeof data === "string") return data;
165
+ if (typeof data !== "object") return data;
166
+ const ct = (headers["content-type"] ?? "").toLowerCase();
167
+ if (isPlainObject2(data) || Array.isArray(data)) {
168
+ if (ct.includes("multipart/form-data")) {
169
+ delete headers["content-type"];
170
+ return toFormData(data);
171
+ }
172
+ if (ct.includes("application/x-www-form-urlencoded"))
173
+ return serializeParams(data);
174
+ }
175
+ if (!ct) headers["content-type"] = "application/json";
176
+ return JSON.stringify(data);
177
+ }
178
+ function defaultTransformResponse(data, headers, _status) {
179
+ const rt = this.responseType;
180
+ if ((rt === void 0 || rt === "json") && typeof data === "string") {
181
+ if (data === "") return "";
182
+ try {
183
+ return JSON.parse(data);
184
+ } catch (e) {
185
+ const isJson = (headers["content-type"] ?? "").toLowerCase().includes("json");
186
+ if (this.transitional?.silentJSONParsing === false && isJson) {
187
+ throw new ExiosError(
188
+ e.message,
189
+ ExiosError.ERR_BAD_RESPONSE,
190
+ this
191
+ );
192
+ }
193
+ return data;
194
+ }
195
+ }
196
+ return data;
197
+ }
198
+ function runTransforms(fns, config, data, headers, status) {
199
+ if (!fns) return data;
200
+ for (const fn of Array.isArray(fns) ? fns : [fns])
201
+ data = fn.call(config, data, headers, status);
202
+ return data;
203
+ }
204
+
205
+ // src/core/defaults.ts
206
+ var DEFAULT_RETRY = Object.freeze({
207
+ retries: 3,
208
+ methods: Object.freeze([
209
+ "get",
210
+ "head",
211
+ "options",
212
+ "put",
213
+ "delete"
214
+ ]),
215
+ statusCodes: Object.freeze([408, 429, 500, 502, 503, 504]),
216
+ retryOnNetworkError: true,
217
+ baseDelayMs: 300,
218
+ maxDelayMs: 3e4,
219
+ factor: 2,
220
+ jitter: "full",
221
+ respectRetryAfter: true
222
+ });
223
+ var DEFAULT_BREAKER = Object.freeze({
224
+ failureThreshold: 5,
225
+ minRequests: 10,
226
+ failureRateThreshold: 0.5,
227
+ resetTimeoutMs: 3e4,
228
+ halfOpenMaxRequests: 1,
229
+ successThreshold: 1
230
+ });
231
+ function createHeaderBuckets(common = {}) {
232
+ return {
233
+ common,
234
+ get: {},
235
+ post: {},
236
+ put: {},
237
+ patch: {},
238
+ delete: {},
239
+ head: {},
240
+ options: {}
241
+ };
242
+ }
243
+ function createDefaults() {
244
+ return {
245
+ timeout: 0,
246
+ responseType: "json",
247
+ headers: createHeaderBuckets({
248
+ Accept: "application/json, text/plain, */*"
249
+ }),
250
+ transformRequest: [defaultTransformRequest],
251
+ transformResponse: [defaultTransformResponse],
252
+ validateStatus: (s) => s >= 200 && s < 300,
253
+ maxContentLength: -1,
254
+ maxBodyLength: -1,
255
+ transitional: { silentJSONParsing: true, clarifyTimeoutError: false },
256
+ retry: {
257
+ ...DEFAULT_RETRY,
258
+ methods: [...DEFAULT_RETRY.methods],
259
+ statusCodes: [...DEFAULT_RETRY.statusCodes]
260
+ },
261
+ breaker: { ...DEFAULT_BREAKER }
262
+ };
263
+ }
264
+
265
+ // src/resilience/breaker.ts
266
+ var FAILURE_CODES = /* @__PURE__ */ new Set([
267
+ ExiosError.ERR_NETWORK,
268
+ ExiosError.ECONNABORTED,
269
+ ExiosError.ETIMEDOUT
270
+ ]);
271
+ function defaultIsFailure(o) {
272
+ const code = o.error?.code;
273
+ if (code === ExiosError.ERR_CANCELED) return false;
274
+ if (code !== void 0 && FAILURE_CODES.has(code)) return true;
275
+ const status = o.response?.status ?? o.error?.response?.status;
276
+ if (status === void 0) return false;
277
+ return status >= 500 || status === 408 || status === 429;
278
+ }
279
+ var CircuitBreaker = class {
280
+ constructor(key, cfg, now = Date.now) {
281
+ this.key = key;
282
+ this.cfg = cfg;
283
+ this.now = now;
284
+ }
285
+ key;
286
+ cfg;
287
+ now;
288
+ _state = "closed";
289
+ epoch = 0;
290
+ openedAt = 0;
291
+ consecutive = 0;
292
+ samples = [];
293
+ probes = /* @__PURE__ */ new Set();
294
+ windowFailures = 0;
295
+ probeSuccesses = 0;
296
+ /** Stored state; open -> half-open happens lazily on `acquire` (no timers). */
297
+ get state() {
298
+ return this._state;
299
+ }
300
+ retryAt() {
301
+ return this.openedAt + this.cfg.resetTimeoutMs;
302
+ }
303
+ acquire(config) {
304
+ if (this._state === "open") {
305
+ if (this.now() < this.retryAt())
306
+ throw new CircuitOpenError(this.key, this.retryAt(), config);
307
+ this.transition("half-open");
308
+ }
309
+ if (this._state === "half-open") {
310
+ const cutoff = this.now() - this.cfg.resetTimeoutMs;
311
+ for (const p of this.probes) {
312
+ if (p.at <= cutoff) {
313
+ this.transition("open");
314
+ throw new CircuitOpenError(this.key, this.retryAt(), config);
315
+ }
316
+ }
317
+ if (this.probes.size >= this.cfg.halfOpenMaxRequests) {
318
+ throw new CircuitOpenError(this.key, this.now(), config);
319
+ }
320
+ const probe = {
321
+ probe: true,
322
+ done: false,
323
+ epoch: this.epoch,
324
+ at: this.now()
325
+ };
326
+ this.probes.add(probe);
327
+ return probe;
328
+ }
329
+ return { probe: false, done: false, epoch: this.epoch, at: this.now() };
330
+ }
331
+ /** Called before each retry: a non-probe ticket may not continue unless closed. */
332
+ check(ticket) {
333
+ if (this._state === "closed" || ticket.probe && ticket.epoch === this.epoch)
334
+ return;
335
+ throw new CircuitOpenError(
336
+ this.key,
337
+ this._state === "open" ? this.retryAt() : this.now()
338
+ );
339
+ }
340
+ record(ticket, failed) {
341
+ if (ticket.done) return;
342
+ ticket.done = true;
343
+ if (ticket.epoch !== this.epoch) return;
344
+ if (ticket.probe) {
345
+ this.probes.delete(ticket);
346
+ if (this._state !== "half-open") return;
347
+ if (failed) return this.transition("open");
348
+ if (++this.probeSuccesses >= this.cfg.successThreshold)
349
+ this.transition("closed");
350
+ return;
351
+ }
352
+ if (this._state !== "closed") return;
353
+ if (this.cfg.windowMs !== void 0) {
354
+ const t = this.now();
355
+ this.samples.push({ t, failed });
356
+ if (failed) this.windowFailures++;
357
+ let i = 0;
358
+ while (i < this.samples.length && t - this.samples[i].t > this.cfg.windowMs) {
359
+ if (this.samples[i].failed) this.windowFailures--;
360
+ i++;
361
+ }
362
+ if (i > 0) this.samples.splice(0, i);
363
+ if (this.samples.length >= this.cfg.minRequests && this.windowFailures / this.samples.length >= this.cfg.failureRateThreshold) {
364
+ this.transition("open");
365
+ }
366
+ return;
367
+ }
368
+ this.consecutive = failed ? this.consecutive + 1 : 0;
369
+ if (this.consecutive >= this.cfg.failureThreshold) this.transition("open");
370
+ }
371
+ /** No outcome (cancel): frees a probe slot, never changes state. */
372
+ release(ticket) {
373
+ if (ticket.done) return;
374
+ ticket.done = true;
375
+ if (ticket.probe && ticket.epoch === this.epoch) this.probes.delete(ticket);
376
+ }
377
+ transition(to) {
378
+ const from = this._state;
379
+ this._state = to;
380
+ this.epoch++;
381
+ this.probes = /* @__PURE__ */ new Set();
382
+ this.windowFailures = 0;
383
+ this.probeSuccesses = 0;
384
+ this.consecutive = 0;
385
+ this.samples = [];
386
+ if (to === "open") this.openedAt = this.now();
387
+ try {
388
+ this.cfg.onStateChange?.(this.key, from, to);
389
+ } catch {
390
+ }
391
+ }
392
+ };
393
+ var BreakerRegistry = class {
394
+ constructor(getConfig, now = Date.now) {
395
+ this.getConfig = getConfig;
396
+ this.now = now;
397
+ }
398
+ getConfig;
399
+ now;
400
+ breakers = /* @__PURE__ */ new Map();
401
+ get(key) {
402
+ const cfg = this.getConfig();
403
+ if (cfg === false) return null;
404
+ let b = this.breakers.get(key);
405
+ if (!b) {
406
+ b = new CircuitBreaker(key, cfg, this.now);
407
+ this.breakers.set(key, b);
408
+ }
409
+ return b;
410
+ }
411
+ state(key) {
412
+ return this.breakers.get(key)?.state ?? "closed";
413
+ }
414
+ reset(key) {
415
+ if (key === void 0) this.breakers.clear();
416
+ else this.breakers.delete(key);
417
+ }
418
+ };
419
+
420
+ // src/core/headers.ts
421
+ var HEADER_BUCKETS = [
422
+ "common",
423
+ "get",
424
+ "post",
425
+ "put",
426
+ "patch",
427
+ "delete",
428
+ "head",
429
+ "options"
430
+ ];
431
+ function normalizeHeaders(h) {
432
+ const out = {};
433
+ if (!h) return out;
434
+ if (typeof Headers !== "undefined" && h instanceof Headers) {
435
+ h.forEach((v, k) => {
436
+ out[k.toLowerCase()] = v;
437
+ });
438
+ return out;
439
+ }
440
+ for (const [k, v] of Object.entries(h)) {
441
+ if (v === null || v === void 0 || v === false) continue;
442
+ out[k.toLowerCase()] = String(v);
443
+ }
444
+ return out;
445
+ }
446
+ function flattenHeaders(h, method) {
447
+ if (!h) return {};
448
+ if (typeof Headers !== "undefined" && h instanceof Headers)
449
+ return normalizeHeaders(h);
450
+ const src = h;
451
+ const isBucket2 = (k) => HEADER_BUCKETS.includes(k.toLowerCase());
452
+ const bucket = (name) => {
453
+ const key = Object.keys(src).find((k) => k.toLowerCase() === name);
454
+ const v = key === void 0 ? void 0 : src[key];
455
+ return v && typeof v === "object" ? v : void 0;
456
+ };
457
+ const top = {};
458
+ for (const [k, v] of Object.entries(src)) {
459
+ if (isBucket2(k)) continue;
460
+ Object.assign(top, normalizeHeaders({ [k]: v }));
461
+ }
462
+ return {
463
+ ...normalizeHeaders(bucket("common")),
464
+ ...normalizeHeaders(bucket(method)),
465
+ ...top
466
+ };
467
+ }
468
+ function finalizeHeaders(h, method) {
469
+ if (!h || typeof h !== "object") return {};
470
+ if (typeof Headers !== "undefined" && h instanceof Headers)
471
+ return normalizeHeaders(h);
472
+ const src = h;
473
+ const isBucket2 = (k) => HEADER_BUCKETS.includes(k.toLowerCase());
474
+ const out = {};
475
+ for (const name of ["common", method]) {
476
+ for (const [k, v] of Object.entries(src)) {
477
+ if (k.toLowerCase() === name && v && typeof v === "object")
478
+ Object.assign(out, normalizeHeaders(v));
479
+ }
480
+ }
481
+ for (const [k, v] of Object.entries(src)) {
482
+ if (isBucket2(k)) continue;
483
+ const lk = k.toLowerCase();
484
+ if (v === null || v === void 0 || v === false) delete out[lk];
485
+ else out[lk] = String(v);
486
+ }
487
+ return out;
488
+ }
489
+ function headersToObject(h) {
490
+ const out = {};
491
+ h.forEach((v, k) => {
492
+ if (k.toLowerCase() !== "set-cookie") out[k.toLowerCase()] = v;
493
+ });
494
+ if (h.has("set-cookie")) {
495
+ const cookies = h.getSetCookie?.();
496
+ out["set-cookie"] = cookies ?? h.get("set-cookie");
497
+ }
498
+ return out;
499
+ }
500
+
501
+ // src/fetch/linkStream.ts
502
+ var isStream = (v) => typeof ReadableStream !== "undefined" && v instanceof ReadableStream;
503
+ function cancelBody(data) {
504
+ if (isStream(data) && !data.locked) data.cancel().catch(() => {
505
+ });
506
+ }
507
+ function linkStream(body, signal, abortError) {
508
+ if (!signal) return body;
509
+ const reader = body.getReader();
510
+ let detach = () => {
511
+ };
512
+ const safe = (fn) => {
513
+ try {
514
+ fn();
515
+ } catch {
516
+ }
517
+ };
518
+ return new ReadableStream({
519
+ start(controller) {
520
+ const onAbort = () => {
521
+ detach();
522
+ safe(() => controller.error(abortError()));
523
+ reader.cancel(signal.reason).catch(() => {
524
+ });
525
+ };
526
+ if (signal.aborted) return onAbort();
527
+ signal.addEventListener("abort", onAbort, { once: true });
528
+ detach = () => {
529
+ detach = () => {
530
+ };
531
+ signal.removeEventListener("abort", onAbort);
532
+ };
533
+ },
534
+ async pull(controller) {
535
+ try {
536
+ const { done, value } = await reader.read();
537
+ if (done) {
538
+ detach();
539
+ safe(() => controller.close());
540
+ } else safe(() => controller.enqueue(value));
541
+ } catch (err) {
542
+ detach();
543
+ safe(() => controller.error(signal.aborted ? abortError() : err));
544
+ }
545
+ },
546
+ cancel(reason) {
547
+ detach();
548
+ return reader.cancel(reason);
549
+ }
550
+ });
551
+ }
552
+
553
+ // src/fetch/readBody.ts
554
+ function convert(res, type, bytes) {
555
+ switch (type) {
556
+ case "blob":
557
+ return new Blob([bytes], { type: res.headers.get("content-type") ?? "" });
558
+ case "arraybuffer":
559
+ return bytes.buffer;
560
+ case "formData":
561
+ return new Response(bytes, { headers: res.headers }).formData();
562
+ default:
563
+ return new TextDecoder().decode(bytes);
564
+ }
565
+ }
566
+ async function readBody(res, config, onProgress = config.onDownloadProgress) {
567
+ const type = config.responseType;
568
+ if (type === "stream") return res.body;
569
+ const max = config.maxContentLength ?? -1;
570
+ if (!onProgress && !(max > -1) || !res.body) {
571
+ switch (type) {
572
+ case "blob":
573
+ return res.blob();
574
+ case "arraybuffer":
575
+ return res.arrayBuffer();
576
+ case "formData":
577
+ return res.formData();
578
+ default:
579
+ return res.text();
580
+ }
581
+ }
582
+ const lengthHeader = Number(res.headers.get("content-length"));
583
+ const total = lengthHeader > 0 ? lengthHeader : void 0;
584
+ const tooLarge = () => new ExiosError(
585
+ `maxContentLength size of ${max} exceeded`,
586
+ ExiosError.ERR_BAD_RESPONSE,
587
+ config
588
+ );
589
+ if (max > -1 && total !== void 0 && total > max) {
590
+ await res.body.cancel().catch(() => {
591
+ });
592
+ throw tooLarge();
593
+ }
594
+ const reader = res.body.getReader();
595
+ const chunks = [];
596
+ let loaded = 0;
597
+ const start = Date.now();
598
+ for (; ; ) {
599
+ const { done, value } = await reader.read();
600
+ if (done) break;
601
+ loaded += value.byteLength;
602
+ if (max > -1 && loaded > max) {
603
+ await reader.cancel().catch(() => {
604
+ });
605
+ throw tooLarge();
606
+ }
607
+ chunks.push(value);
608
+ if (onProgress) {
609
+ const elapsed = (Date.now() - start) / 1e3;
610
+ const rate = elapsed > 0 ? loaded / elapsed : void 0;
611
+ const ev = {
612
+ loaded,
613
+ total,
614
+ progress: total ? loaded / total : void 0,
615
+ bytes: value.byteLength,
616
+ rate,
617
+ estimated: rate && total ? (total - loaded) / rate : void 0,
618
+ download: true
619
+ };
620
+ onProgress(ev);
621
+ }
622
+ }
623
+ const bytes = new Uint8Array(loaded);
624
+ let offset = 0;
625
+ for (const c of chunks) {
626
+ bytes.set(c, offset);
627
+ offset += c.byteLength;
628
+ }
629
+ return convert(res, type, bytes);
630
+ }
631
+
632
+ // src/fetch/signals.ts
633
+ function combineSignals(...signals) {
634
+ const controller = new AbortController();
635
+ const active = signals.filter((s) => !!s);
636
+ const listeners = [];
637
+ const cleanup = () => {
638
+ for (const off of listeners.splice(0)) off();
639
+ };
640
+ for (const s of active) {
641
+ if (s.aborted) {
642
+ controller.abort(s.reason);
643
+ cleanup();
644
+ return { signal: controller.signal, cleanup };
645
+ }
646
+ }
647
+ for (const s of active) {
648
+ const onAbort = () => {
649
+ controller.abort(s.reason);
650
+ cleanup();
651
+ };
652
+ s.addEventListener("abort", onAbort, { once: true });
653
+ listeners.push(() => s.removeEventListener("abort", onAbort));
654
+ }
655
+ return { signal: controller.signal, cleanup };
656
+ }
657
+ function attemptSignal(user, timeoutMs) {
658
+ const timer = new AbortController();
659
+ let fired = false;
660
+ let handle;
661
+ if (timeoutMs > 0) {
662
+ handle = setTimeout(() => {
663
+ fired = true;
664
+ timer.abort(new Error("timeout"));
665
+ }, timeoutMs);
666
+ }
667
+ const combined = combineSignals(user, timer.signal);
668
+ return {
669
+ signal: combined.signal,
670
+ timedOut: () => fired,
671
+ cleanup() {
672
+ if (handle !== void 0) clearTimeout(handle);
673
+ handle = void 0;
674
+ combined.cleanup();
675
+ }
676
+ };
677
+ }
678
+
679
+ // src/fetch/performAttempt.ts
680
+ function bodyLength(body) {
681
+ if (typeof body === "string")
682
+ return new TextEncoder().encode(body).byteLength;
683
+ if (typeof Blob !== "undefined" && body instanceof Blob) return body.size;
684
+ if (body instanceof ArrayBuffer) return body.byteLength;
685
+ if (ArrayBuffer.isView(body)) return body.byteLength;
686
+ return void 0;
687
+ }
688
+ function basicAuth(auth) {
689
+ const bytes = new TextEncoder().encode(`${auth.username}:${auth.password}`);
690
+ let bin = "";
691
+ for (const b of bytes) bin += String.fromCharCode(b);
692
+ return `Basic ${btoa(bin)}`;
693
+ }
694
+ async function performAttempt(config) {
695
+ const url = buildURL(
696
+ buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls),
697
+ config.params,
698
+ config.paramsSerializer
699
+ );
700
+ const headers = { ...config.headers };
701
+ if (config.auth) headers.authorization = basicAuth(config.auth);
702
+ const hasBody = config.method !== "get" && config.method !== "head";
703
+ const body = hasBody ? runTransforms(config.transformRequest, config, config.data, headers) : void 0;
704
+ const maxBody = config.maxBodyLength ?? -1;
705
+ if (maxBody > -1) {
706
+ const len = bodyLength(body);
707
+ if (len !== void 0 && len > maxBody) {
708
+ throw new ExiosError(
709
+ `Request body larger than maxBodyLength limit`,
710
+ ExiosError.ERR_BAD_REQUEST,
711
+ config
712
+ );
713
+ }
714
+ }
715
+ const sig = attemptSignal(config.signal, config.timeout ?? 0);
716
+ try {
717
+ const init = {
718
+ ...config.fetchOptions,
719
+ method: config.method.toUpperCase(),
720
+ headers,
721
+ body,
722
+ credentials: config.withCredentials ? "include" : config.fetchOptions?.credentials ?? "same-origin",
723
+ signal: sig.signal
724
+ };
725
+ if (config.redirect) init.redirect = config.redirect;
726
+ if (typeof ReadableStream !== "undefined" && body instanceof ReadableStream)
727
+ init.duplex = "half";
728
+ let request;
729
+ try {
730
+ request = new Request(url, init);
731
+ } catch (err) {
732
+ const e = new ExiosError(
733
+ err instanceof Error ? err.message : String(err),
734
+ ExiosError.ERR_BAD_REQUEST,
735
+ config
736
+ );
737
+ e.cause = err;
738
+ throw e;
739
+ }
740
+ if (config.signal?.aborted)
741
+ throw new CanceledError("canceled", config, request);
742
+ let userError;
743
+ const progress = config.onDownloadProgress ? (ev) => {
744
+ try {
745
+ config.onDownloadProgress(ev);
746
+ } catch (err) {
747
+ userError = { err };
748
+ throw err;
749
+ }
750
+ } : void 0;
751
+ let res;
752
+ let data;
753
+ try {
754
+ res = await (config.fetch ?? globalThis.fetch)(request);
755
+ data = await readBody(res, config, progress);
756
+ } catch (err) {
757
+ if (userError && userError.err === err) throw err;
758
+ if (isExios(err)) {
759
+ err.request ??= request;
760
+ throw err;
761
+ }
762
+ if (config.signal?.aborted)
763
+ throw new CanceledError("canceled", config, request);
764
+ if (sig.timedOut()) {
765
+ const code = config.transitional?.clarifyTimeoutError ? ExiosError.ETIMEDOUT : ExiosError.ECONNABORTED;
766
+ throw new ExiosError(
767
+ config.timeoutErrorMessage ?? `timeout of ${config.timeout}ms exceeded`,
768
+ code,
769
+ config,
770
+ request
771
+ );
772
+ }
773
+ const netErr = new ExiosError(
774
+ "Network Error",
775
+ ExiosError.ERR_NETWORK,
776
+ config,
777
+ request
778
+ );
779
+ netErr.cause = err;
780
+ throw netErr;
781
+ }
782
+ if (config.responseType === "stream" && typeof ReadableStream !== "undefined" && data instanceof ReadableStream) {
783
+ data = linkStream(
784
+ data,
785
+ config.signal,
786
+ () => new CanceledError("canceled", config, request)
787
+ );
788
+ }
789
+ const resHeaders = headersToObject(res.headers);
790
+ const response = {
791
+ data,
792
+ status: res.status,
793
+ statusText: res.statusText,
794
+ headers: resHeaders,
795
+ config,
796
+ request,
797
+ meta: { attempts: 0 }
798
+ };
799
+ try {
800
+ response.data = runTransforms(
801
+ config.transformResponse,
802
+ config,
803
+ data,
804
+ resHeaders,
805
+ res.status
806
+ );
807
+ } catch (err) {
808
+ cancelBody(data);
809
+ if (isExios(err)) {
810
+ err.request ??= request;
811
+ err.response ??= response;
812
+ err.status ??= response.status;
813
+ }
814
+ throw err;
815
+ }
816
+ return response;
817
+ } finally {
818
+ sig.cleanup();
819
+ }
820
+ }
821
+ function isExios(e) {
822
+ return e instanceof ExiosError;
823
+ }
824
+
825
+ // src/resilience/backoff.ts
826
+ function computeDelay(attempt, cfg, random = Math.random) {
827
+ const capped = Math.min(
828
+ cfg.maxDelayMs,
829
+ cfg.baseDelayMs * cfg.factor ** (attempt - 1)
830
+ );
831
+ return cfg.jitter === "full" ? Math.floor(random() * capped) : capped;
832
+ }
833
+ function parseRetryAfter(value, now = Date.now()) {
834
+ if (value === void 0) return void 0;
835
+ const v = value.trim();
836
+ if (/^\d+$/.test(v)) return Number(v) * 1e3;
837
+ if (!/^[A-Za-z]{3,9},? /.test(v)) return void 0;
838
+ const date = Date.parse(v);
839
+ if (Number.isNaN(date)) return void 0;
840
+ return Math.max(0, date - now);
841
+ }
842
+
843
+ // src/resilience/retry.ts
844
+ var NEVER_RETRY = /* @__PURE__ */ new Set([
845
+ "ERR_CANCELED",
846
+ "ERR_CIRCUIT_OPEN",
847
+ "ERR_BAD_OPTION_VALUE"
848
+ ]);
849
+ var RETRYABLE_ERRORS = /* @__PURE__ */ new Set(["ERR_NETWORK", "ECONNABORTED", "ETIMEDOUT"]);
850
+ function defaultShouldRetry(o, cfg, config) {
851
+ if (!cfg.methods.includes(config.method)) return false;
852
+ if (o.response) return cfg.statusCodes.includes(o.response.status);
853
+ if (o.error)
854
+ return cfg.retryOnNetworkError && RETRYABLE_ERRORS.has(o.error.code ?? "");
855
+ return false;
856
+ }
857
+ function defaultSleep(ms, signal) {
858
+ return new Promise((resolve, reject) => {
859
+ if (signal?.aborted) return reject(new CanceledError());
860
+ const onAbort = () => {
861
+ clearTimeout(timer);
862
+ reject(new CanceledError());
863
+ };
864
+ const timer = setTimeout(() => {
865
+ signal?.removeEventListener("abort", onAbort);
866
+ resolve();
867
+ }, ms);
868
+ signal?.addEventListener("abort", onAbort, { once: true });
869
+ });
870
+ }
871
+ async function runWithRetry(attempt, cfg, config, hooks) {
872
+ const sleep = hooks.sleep ?? defaultSleep;
873
+ const now = hooks.now ?? Date.now;
874
+ const start = now();
875
+ const isStream2 = typeof ReadableStream !== "undefined" && config.data instanceof ReadableStream;
876
+ let attempts = 0;
877
+ for (; ; ) {
878
+ attempts++;
879
+ let outcome;
880
+ try {
881
+ outcome = { response: await attempt() };
882
+ } catch (e) {
883
+ if (!isExiosError(e)) throw e;
884
+ outcome = { error: e };
885
+ }
886
+ if (cfg === false || attempts > cfg.retries || isStream2)
887
+ return { outcome, attempts };
888
+ if (outcome.response && outcome.response.status >= 200 && outcome.response.status < 300)
889
+ return { outcome, attempts };
890
+ if (NEVER_RETRY.has(outcome.error?.code ?? ""))
891
+ return { outcome, attempts };
892
+ let decide;
893
+ try {
894
+ decide = cfg.shouldRetry ? await cfg.shouldRetry({ ...outcome, attempt: attempts, config }) : defaultShouldRetry(outcome, cfg, config);
895
+ } catch (e) {
896
+ cancelBody(outcome.response?.data);
897
+ throw e;
898
+ }
899
+ if (!decide) return { outcome, attempts };
900
+ let delay;
901
+ if (cfg.respectRetryAfter) {
902
+ const raw = outcome.response?.headers["retry-after"];
903
+ const parsed = parseRetryAfter(Array.isArray(raw) ? raw[0] : raw, now());
904
+ if (parsed !== void 0)
905
+ delay = Math.min(Math.max(parsed, 0), cfg.maxDelayMs);
906
+ }
907
+ delay ??= computeDelay(attempts, cfg, hooks.random);
908
+ if (cfg.maxElapsedMs !== void 0 && now() - start + delay > cfg.maxElapsedMs) {
909
+ return { outcome, attempts };
910
+ }
911
+ cancelBody(outcome.response?.data);
912
+ if (hooks.signal?.aborted) throw new CanceledError();
913
+ cfg.onRetry?.({ ...outcome, attempt: attempts, delayMs: delay });
914
+ await sleep(delay, hooks.signal);
915
+ hooks.beforeRetry?.();
916
+ }
917
+ }
918
+
919
+ // src/core/dispatchRequest.ts
920
+ function defaultBreakerKey(config) {
921
+ const full = buildFullPath(
922
+ config.baseURL,
923
+ config.url,
924
+ config.allowAbsoluteUrls
925
+ );
926
+ try {
927
+ return new URL(
928
+ full,
929
+ globalThis.location?.href
930
+ ).origin;
931
+ } catch {
932
+ return full;
933
+ }
934
+ }
935
+ async function dispatchRequest(config, registry) {
936
+ if (config.signal?.aborted) throw new CanceledError("canceled", config);
937
+ const bcfg = config.breaker;
938
+ const breaker = bcfg === false ? null : registry.get(bcfg.key ? bcfg.key(config) : defaultBreakerKey(config));
939
+ const ticket = breaker?.acquire(config);
940
+ let attempts = 0;
941
+ try {
942
+ let result;
943
+ try {
944
+ result = await runWithRetry(
945
+ () => {
946
+ attempts++;
947
+ return performAttempt(config);
948
+ },
949
+ ticket?.probe ? false : config.retry,
950
+ // half-open probes get exactly one attempt
951
+ config,
952
+ {
953
+ signal: config.signal,
954
+ beforeRetry: breaker && ticket ? () => breaker.check(ticket) : void 0
955
+ }
956
+ );
957
+ } catch (e) {
958
+ if (isExiosError(e)) {
959
+ e.config ??= config;
960
+ e.meta.attempts = attempts;
961
+ }
962
+ throw e;
963
+ }
964
+ const { outcome } = result;
965
+ attempts = result.attempts;
966
+ if (outcome.error) outcome.error.meta.attempts = attempts;
967
+ if (outcome.error?.code === ExiosError.ERR_CANCELED) throw outcome.error;
968
+ if (breaker && ticket && bcfg)
969
+ breaker.record(ticket, (bcfg.isFailure ?? defaultIsFailure)(outcome));
970
+ if (outcome.error) throw outcome.error;
971
+ const response = outcome.response;
972
+ response.meta.attempts = attempts;
973
+ const { status } = response;
974
+ if (config.validateStatus && !config.validateStatus(status)) {
975
+ const err = new ExiosError(
976
+ "Request failed with status code " + status,
977
+ status >= 500 ? ExiosError.ERR_BAD_RESPONSE : ExiosError.ERR_BAD_REQUEST,
978
+ config,
979
+ response.request,
980
+ response
981
+ );
982
+ err.meta.attempts = attempts;
983
+ throw err;
984
+ }
985
+ return response;
986
+ } finally {
987
+ if (breaker && ticket) breaker.release(ticket);
988
+ }
989
+ }
990
+
991
+ // src/core/InterceptorManager.ts
992
+ var InterceptorManager = class {
993
+ handlers = [];
994
+ use(onFulfilled, onRejected, opts) {
995
+ this.handlers.push({
996
+ fulfilled: onFulfilled,
997
+ rejected: onRejected,
998
+ synchronous: opts?.synchronous ?? false,
999
+ runWhen: opts?.runWhen ?? null
1000
+ });
1001
+ return this.handlers.length - 1;
1002
+ }
1003
+ eject(id) {
1004
+ if (this.handlers[id]) this.handlers[id] = null;
1005
+ }
1006
+ clear() {
1007
+ this.handlers = [];
1008
+ }
1009
+ forEach(fn) {
1010
+ for (const h of this.handlers) if (h) fn(h);
1011
+ }
1012
+ };
1013
+
1014
+ // src/core/resilienceConfig.ts
1015
+ function defined(o) {
1016
+ const out = {};
1017
+ if (!o) return out;
1018
+ for (const [k, v] of Object.entries(o))
1019
+ if (v !== void 0) out[k] = v;
1020
+ return out;
1021
+ }
1022
+ function bad(name, value, rule) {
1023
+ throw new ExiosError(
1024
+ `ERR_BAD_OPTION_VALUE: ${name} must be ${rule} (got ${String(value)})`,
1025
+ ExiosError.ERR_BAD_OPTION_VALUE
1026
+ );
1027
+ }
1028
+ var isNum = (v) => typeof v === "number" && !Number.isNaN(v);
1029
+ function check(name, v, ok, rule) {
1030
+ if (!isNum(v) || !ok(v)) bad(name, v, rule);
1031
+ }
1032
+ var nonNegFinite = (n) => n >= 0 && Number.isFinite(n);
1033
+ function resolveRetry(v) {
1034
+ if (v === false) return false;
1035
+ if (v !== void 0 && (typeof v !== "object" || v === null))
1036
+ bad("retry", v, "false or an object");
1037
+ const r = { ...DEFAULT_RETRY, ...defined(v) };
1038
+ if (!Array.isArray(r.methods)) bad("retry.methods", r.methods, "an array");
1039
+ if (!Array.isArray(r.statusCodes))
1040
+ bad("retry.statusCodes", r.statusCodes, "an array");
1041
+ r.methods = [...r.methods];
1042
+ r.statusCodes = [...r.statusCodes];
1043
+ check(
1044
+ "retry.retries",
1045
+ r.retries,
1046
+ nonNegFinite,
1047
+ "a non-negative finite number"
1048
+ );
1049
+ check(
1050
+ "retry.baseDelayMs",
1051
+ r.baseDelayMs,
1052
+ nonNegFinite,
1053
+ "a non-negative finite number"
1054
+ );
1055
+ check(
1056
+ "retry.maxDelayMs",
1057
+ r.maxDelayMs,
1058
+ nonNegFinite,
1059
+ "a non-negative finite number"
1060
+ );
1061
+ if (r.maxElapsedMs !== void 0) {
1062
+ check(
1063
+ "retry.maxElapsedMs",
1064
+ r.maxElapsedMs,
1065
+ nonNegFinite,
1066
+ "a non-negative finite number"
1067
+ );
1068
+ }
1069
+ check(
1070
+ "retry.factor",
1071
+ r.factor,
1072
+ (n) => n >= 1 && Number.isFinite(n),
1073
+ "a finite number >= 1"
1074
+ );
1075
+ return r;
1076
+ }
1077
+ function resolveBreaker(v) {
1078
+ if (v === false) return false;
1079
+ if (v !== void 0 && (typeof v !== "object" || v === null))
1080
+ bad("breaker", v, "false or an object");
1081
+ const b = { ...DEFAULT_BREAKER, ...defined(v) };
1082
+ const positive = (n) => n > 0;
1083
+ check(
1084
+ "breaker.failureThreshold",
1085
+ b.failureThreshold,
1086
+ positive,
1087
+ "a number > 0"
1088
+ );
1089
+ check("breaker.resetTimeoutMs", b.resetTimeoutMs, positive, "a number > 0");
1090
+ check("breaker.minRequests", b.minRequests, positive, "a number > 0");
1091
+ check(
1092
+ "breaker.failureRateThreshold",
1093
+ b.failureRateThreshold,
1094
+ (n) => n > 0 && n <= 1,
1095
+ "in (0, 1]"
1096
+ );
1097
+ check(
1098
+ "breaker.halfOpenMaxRequests",
1099
+ b.halfOpenMaxRequests,
1100
+ (n) => n >= 1,
1101
+ "a number >= 1"
1102
+ );
1103
+ check(
1104
+ "breaker.successThreshold",
1105
+ b.successThreshold,
1106
+ (n) => n >= 1,
1107
+ "a number >= 1"
1108
+ );
1109
+ if (b.windowMs !== void 0)
1110
+ check("breaker.windowMs", b.windowMs, positive, "a number > 0");
1111
+ return b;
1112
+ }
1113
+
1114
+ // src/core/mergeConfig.ts
1115
+ var isPlainObject3 = (v) => {
1116
+ if (typeof v !== "object" || v === null) return false;
1117
+ const p = Object.getPrototypeOf(v);
1118
+ return p === Object.prototype || p === null;
1119
+ };
1120
+ var isBucket = (k) => HEADER_BUCKETS.includes(k.toLowerCase());
1121
+ var SHALLOW_MERGE = /* @__PURE__ */ new Set(["auth", "transitional", "fetchOptions"]);
1122
+ function setCI(target, k, v) {
1123
+ const lk = k.toLowerCase();
1124
+ for (const existing of Object.keys(target)) {
1125
+ if (existing.toLowerCase() === lk) delete target[existing];
1126
+ }
1127
+ target[k] = v;
1128
+ }
1129
+ function toPlainHeaders(h) {
1130
+ if (!h) return {};
1131
+ if (typeof Headers !== "undefined" && h instanceof Headers)
1132
+ return normalizeHeaders(h);
1133
+ return h;
1134
+ }
1135
+ function mergeFlat(a, b) {
1136
+ const out = { ...a };
1137
+ for (const [k, v] of Object.entries(b)) setCI(out, k, v);
1138
+ return out;
1139
+ }
1140
+ function mergeHeaders(a, b) {
1141
+ const pa = toPlainHeaders(a);
1142
+ const pb = toPlainHeaders(b);
1143
+ const out = {};
1144
+ for (const [k, v] of Object.entries(pa))
1145
+ setCI(out, k, isBucket(k) && isPlainObject3(v) ? { ...v } : v);
1146
+ for (const [k, v] of Object.entries(pb)) {
1147
+ const existingKey = Object.keys(out).find(
1148
+ (e) => e.toLowerCase() === k.toLowerCase()
1149
+ );
1150
+ const existing = existingKey === void 0 ? void 0 : out[existingKey];
1151
+ if (isBucket(k) && isPlainObject3(v) && isPlainObject3(existing))
1152
+ setCI(out, k, mergeFlat(existing, v));
1153
+ else setCI(out, k, isBucket(k) && isPlainObject3(v) ? { ...v } : v);
1154
+ }
1155
+ return out;
1156
+ }
1157
+ function mergeRetry(a, b) {
1158
+ if (b === false) return false;
1159
+ if (b === void 0) return a;
1160
+ return { ...a || DEFAULT_RETRY, ...defined(b) };
1161
+ }
1162
+ function mergeBreaker(a, b) {
1163
+ if (b === false) return false;
1164
+ if (b === void 0) return a;
1165
+ return { ...a || DEFAULT_BREAKER, ...defined(b) };
1166
+ }
1167
+ function mergeConfig(a, b = {}) {
1168
+ const out = {};
1169
+ const A = a;
1170
+ const B = b;
1171
+ for (const k of /* @__PURE__ */ new Set([...Object.keys(A), ...Object.keys(B)])) {
1172
+ if (k === "url" || k === "method" || k === "data" || k === "headers" || k === "retry" || k === "breaker")
1173
+ continue;
1174
+ if (SHALLOW_MERGE.has(k) && isPlainObject3(A[k]) && isPlainObject3(B[k]))
1175
+ out[k] = { ...A[k], ...B[k] };
1176
+ else out[k] = B[k] !== void 0 ? B[k] : A[k];
1177
+ }
1178
+ out.url = B.url;
1179
+ out.method = B.method;
1180
+ out.data = B.data;
1181
+ out.headers = mergeHeaders(A.headers, B.headers);
1182
+ const retry = mergeRetry(a.retry, b.retry);
1183
+ const breaker = mergeBreaker(a.breaker, b.breaker);
1184
+ if (retry !== void 0) out.retry = retry;
1185
+ if (breaker !== void 0) out.breaker = breaker;
1186
+ return out;
1187
+ }
1188
+ function resolveConfig(merged) {
1189
+ const method = (merged.method ?? "get").toLowerCase();
1190
+ const { retry, breaker, headers: _h, ...rest } = merged;
1191
+ return {
1192
+ ...rest,
1193
+ method,
1194
+ headers: normalizeHeaders(flattenHeaders(merged.headers, method)),
1195
+ retry: resolveRetry(retry),
1196
+ breaker: resolveBreaker(breaker)
1197
+ };
1198
+ }
1199
+ function finalizeConfig(config) {
1200
+ const method = (config.method ?? "get").toLowerCase();
1201
+ return {
1202
+ ...config,
1203
+ method,
1204
+ headers: finalizeHeaders(config.headers, method),
1205
+ retry: resolveRetry(config.retry),
1206
+ breaker: resolveBreaker(config.breaker)
1207
+ };
1208
+ }
1209
+ function assertRequestBreaker(b) {
1210
+ if (b === void 0 || b === false) return;
1211
+ if (typeof b !== "object" || b === null) {
1212
+ throw new ExiosError(
1213
+ "Per-request breaker must be false or an object",
1214
+ ExiosError.ERR_BAD_OPTION_VALUE
1215
+ );
1216
+ }
1217
+ const bad2 = Object.keys(b).filter((k) => k !== "key" && k !== "isFailure");
1218
+ if (bad2.length) {
1219
+ throw new ExiosError(
1220
+ `ERR_BAD_OPTION_VALUE: per-request breaker only accepts "key" and "isFailure" (got ${bad2.join(", ")})`,
1221
+ ExiosError.ERR_BAD_OPTION_VALUE
1222
+ );
1223
+ }
1224
+ }
1225
+
1226
+ // src/core/Exios.ts
1227
+ var isThenable = (v) => typeof v === "object" && v !== null && typeof v.then === "function";
1228
+ var Exios = class {
1229
+ defaults;
1230
+ interceptors = {
1231
+ request: new InterceptorManager(),
1232
+ response: new InterceptorManager()
1233
+ };
1234
+ breaker;
1235
+ registry;
1236
+ constructor(defaults) {
1237
+ this.defaults = defaults;
1238
+ this.registry = new BreakerRegistry(
1239
+ () => resolveBreaker(this.defaults.breaker)
1240
+ );
1241
+ this.breaker = {
1242
+ state: (key) => this.registry.state(key),
1243
+ reset: (key) => this.registry.reset(key)
1244
+ };
1245
+ }
1246
+ async request(configOrUrl, config) {
1247
+ const cfg = typeof configOrUrl === "string" ? { ...config, url: configOrUrl } : { ...configOrUrl };
1248
+ assertRequestBreaker(cfg.breaker);
1249
+ const resolved = resolveConfig(mergeConfig(this.defaults, cfg));
1250
+ const requestChain = [];
1251
+ let synchronous = true;
1252
+ this.interceptors.request.forEach((h) => {
1253
+ if (h.runWhen && h.runWhen(resolved) === false) return;
1254
+ synchronous = synchronous && h.synchronous;
1255
+ requestChain.unshift(h);
1256
+ });
1257
+ const dispatch = (c) => dispatchRequest(finalizeConfig(c), this.registry);
1258
+ let promise;
1259
+ if (synchronous) {
1260
+ promise = this.runSync(requestChain, resolved, dispatch);
1261
+ } else {
1262
+ promise = Promise.resolve(resolved);
1263
+ for (const h of requestChain)
1264
+ promise = promise.then(
1265
+ h.fulfilled ?? void 0,
1266
+ h.rejected ?? void 0
1267
+ );
1268
+ promise = promise.then(dispatch);
1269
+ }
1270
+ this.interceptors.response.forEach((h) => {
1271
+ promise = promise.then(h.fulfilled ?? void 0, h.rejected ?? void 0);
1272
+ });
1273
+ return promise;
1274
+ }
1275
+ /** Runs every request interceptor in this tick with promise-chain semantics, then dispatches. */
1276
+ runSync(chain, config, dispatch) {
1277
+ let value = config;
1278
+ let failed = false;
1279
+ let error;
1280
+ for (const h of chain) {
1281
+ try {
1282
+ if (!failed) {
1283
+ if (h.fulfilled) value = h.fulfilled(value);
1284
+ } else if (h.rejected) {
1285
+ value = h.rejected(error);
1286
+ failed = false;
1287
+ }
1288
+ } catch (e) {
1289
+ failed = true;
1290
+ error = e;
1291
+ }
1292
+ }
1293
+ if (failed) return Promise.reject(error);
1294
+ return isThenable(value) ? Promise.resolve(value).then((c) => dispatch(c)) : dispatch(value);
1295
+ }
1296
+ getUri(config) {
1297
+ const c = mergeConfig(this.defaults, config);
1298
+ return buildURL(
1299
+ buildFullPath(c.baseURL, c.url, c.allowAbsoluteUrls),
1300
+ c.params,
1301
+ c.paramsSerializer
1302
+ );
1303
+ }
1304
+ noData(method, url, config) {
1305
+ return this.request({ ...config, method, url });
1306
+ }
1307
+ withData(method, url, data, config, form = false) {
1308
+ const c = { ...config, method, url, data };
1309
+ if (form) {
1310
+ const h = config?.headers;
1311
+ const plain = typeof Headers !== "undefined" && h instanceof Headers ? normalizeHeaders(h) : h;
1312
+ c.headers = {
1313
+ ...plain,
1314
+ "content-type": "multipart/form-data"
1315
+ };
1316
+ }
1317
+ return this.request(c);
1318
+ }
1319
+ get(url, config) {
1320
+ return this.noData("get", url, config);
1321
+ }
1322
+ delete(url, config) {
1323
+ return this.noData("delete", url, config);
1324
+ }
1325
+ head(url, config) {
1326
+ return this.noData("head", url, config);
1327
+ }
1328
+ options(url, config) {
1329
+ return this.noData("options", url, config);
1330
+ }
1331
+ post(url, data, config) {
1332
+ return this.withData("post", url, data, config);
1333
+ }
1334
+ put(url, data, config) {
1335
+ return this.withData("put", url, data, config);
1336
+ }
1337
+ patch(url, data, config) {
1338
+ return this.withData("patch", url, data, config);
1339
+ }
1340
+ postForm(url, data, config) {
1341
+ return this.withData("post", url, data, config, true);
1342
+ }
1343
+ putForm(url, data, config) {
1344
+ return this.withData("put", url, data, config, true);
1345
+ }
1346
+ patchForm(url, data, config) {
1347
+ return this.withData("patch", url, data, config, true);
1348
+ }
1349
+ };
1350
+ var METHODS = [
1351
+ "request",
1352
+ "getUri",
1353
+ "get",
1354
+ "delete",
1355
+ "head",
1356
+ "options",
1357
+ "post",
1358
+ "put",
1359
+ "patch",
1360
+ "postForm",
1361
+ "putForm",
1362
+ "patchForm"
1363
+ ];
1364
+ var isPlainObject4 = (v) => typeof v === "object" && v !== null && [Object.prototype, null].includes(Object.getPrototypeOf(v));
1365
+ function detachDefaults(d) {
1366
+ const out = { ...d };
1367
+ const headers = isPlainObject4(out.headers) ? out.headers : normalizeHeaders(out.headers);
1368
+ out.headers = Object.assign(createHeaderBuckets(), headers);
1369
+ for (const b of HEADER_BUCKETS) {
1370
+ const existing = Object.keys(headers).find((k) => k.toLowerCase() === b);
1371
+ if (existing !== void 0 && existing !== b) {
1372
+ out.headers[b] = out.headers[existing];
1373
+ delete out.headers[existing];
1374
+ }
1375
+ }
1376
+ out.retry ??= { ...DEFAULT_RETRY };
1377
+ out.breaker ??= { ...DEFAULT_BREAKER };
1378
+ for (const k of [
1379
+ "transitional",
1380
+ "fetchOptions",
1381
+ "auth",
1382
+ "breaker"
1383
+ ]) {
1384
+ if (isPlainObject4(out[k])) out[k] = { ...out[k] };
1385
+ }
1386
+ if (isPlainObject4(out.retry)) {
1387
+ out.retry = { ...out.retry };
1388
+ if (Array.isArray(out.retry.methods))
1389
+ out.retry.methods = [...out.retry.methods];
1390
+ if (Array.isArray(out.retry.statusCodes))
1391
+ out.retry.statusCodes = [...out.retry.statusCodes];
1392
+ }
1393
+ for (const k of ["transformRequest", "transformResponse"]) {
1394
+ if (Array.isArray(out[k])) out[k] = [...out[k]];
1395
+ }
1396
+ return out;
1397
+ }
1398
+ function createInstance(defaults) {
1399
+ const context = new Exios(defaults);
1400
+ const instance = ((configOrUrl, config) => context.request(configOrUrl, config));
1401
+ for (const m of METHODS)
1402
+ instance[m] = context[m].bind(
1403
+ context
1404
+ );
1405
+ Object.defineProperty(instance, "defaults", {
1406
+ get: () => context.defaults,
1407
+ set: (v) => context.defaults = v,
1408
+ enumerable: true
1409
+ });
1410
+ instance.interceptors = context.interceptors;
1411
+ instance.breaker = context.breaker;
1412
+ instance.create = (cfg) => createInstance(detachDefaults(mergeConfig(context.defaults, cfg)));
1413
+ return instance;
1414
+ }
1415
+
1416
+ // src/index.ts
1417
+ var statics = {
1418
+ ExiosError,
1419
+ CanceledError,
1420
+ CircuitOpenError,
1421
+ isExiosError,
1422
+ isCancel,
1423
+ mergeConfig,
1424
+ toFormData
1425
+ };
1426
+ var exios = Object.assign(
1427
+ createInstance(createDefaults()),
1428
+ statics
1429
+ );
1430
+ var create = exios.create;
1431
+ var index_default = exios;
1432
+ export {
1433
+ CanceledError,
1434
+ CircuitOpenError,
1435
+ ExiosError,
1436
+ create,
1437
+ index_default as default,
1438
+ isCancel,
1439
+ isExiosError,
1440
+ mergeConfig,
1441
+ toFormData
1442
+ };