@bereasoftware/nexa 1.0.4 → 1.1.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/nexa.es.js CHANGED
@@ -1,61 +1,68 @@
1
- /*! Nexa v1.0.4 | (c) 2026 Berea-Soft | MIT License | https://github.com/Berea-Soft/Nexa */
2
- //#region src/types/index.ts
3
- var e = (e) => ({
1
+ /*! Nexa v1.1.0 | (c) 2026 Berea-Soft | MIT License | https://github.com/Berea-Soft/Nexa */
2
+ //#region \0rolldown/runtime.js
3
+ var e = Object.defineProperty, t = (e, t) => () => (e && (t = e(e = 0)), t), n = (t, n) => {
4
+ let r = {};
5
+ for (var i in t) e(r, i, {
6
+ get: t[i],
7
+ enumerable: !0
8
+ });
9
+ return n || e(r, Symbol.toStringTag, { value: "Module" }), r;
10
+ }, r = (e) => ({
4
11
  ok: !0,
5
12
  value: e
6
- }), t = (e) => ({
13
+ }), i = (e) => ({
7
14
  ok: !1,
8
15
  error: e
9
16
  });
10
17
  //#endregion
11
18
  //#region src/utils/index.ts
12
- function n(n) {
13
- return { validate(r) {
14
- let i = r;
15
- for (let [e, r] of Object.entries(n)) if (!r(i[e])) return t({
16
- message: `Validation failed: field "${e}" is invalid`,
19
+ function a(e) {
20
+ return { validate(t) {
21
+ let n = t;
22
+ for (let [t, r] of Object.entries(e)) if (!r(n[t])) return i({
23
+ message: `Validation failed: field "${t}" is invalid`,
17
24
  code: "VALIDATION_ERROR"
18
25
  });
19
- return e(r);
26
+ return r(t);
20
27
  } };
21
28
  }
22
- function r(n) {
23
- return { validate(r) {
24
- let i = r, a = n.filter((e) => !(e in i));
25
- return a.length > 0 ? t({
29
+ function o(e) {
30
+ return { validate(t) {
31
+ let n = t, a = e.filter((e) => !(e in n));
32
+ return a.length > 0 ? i({
26
33
  message: `Validation failed: missing fields: ${a.join(", ")}`,
27
34
  code: "VALIDATION_ERROR"
28
- }) : e(r);
35
+ }) : r(t);
29
36
  } };
30
37
  }
31
- var i = { validate(n) {
32
- return Array.isArray(n) ? e(n) : t({
38
+ var s = { validate(e) {
39
+ return Array.isArray(e) ? r(e) : i({
33
40
  message: "Expected array response",
34
41
  code: "VALIDATION_ERROR"
35
42
  });
36
- } }, a = { validate(n) {
37
- return n && typeof n == "object" && !Array.isArray(n) ? e(n) : t({
43
+ } }, c = { validate(e) {
44
+ return e && typeof e == "object" && !Array.isArray(e) ? r(e) : i({
38
45
  message: "Expected object response",
39
46
  code: "VALIDATION_ERROR"
40
47
  });
41
- } }, o = { transform(e) {
42
- return g(e, m);
43
- } }, s = { transform(e) {
44
- return g(e, h);
45
- } }, c = { transform(e) {
46
- return _(e);
48
+ } }, l = { transform(e) {
49
+ return v(e, _);
50
+ } }, u = { transform(e) {
51
+ return v(e, ee);
52
+ } }, d = { transform(e) {
53
+ return y(e);
47
54
  } };
48
- function l(e) {
55
+ function f(e) {
49
56
  return { transform(t) {
50
- return Array.isArray(t) ? t.map((t) => v(t, e)) : v(t, e);
57
+ return Array.isArray(t) ? t.map((t) => b(t, e)) : b(t, e);
51
58
  } };
52
59
  }
53
- function u(e) {
60
+ function p(e) {
54
61
  return { transform(t) {
55
62
  return { [e]: t };
56
63
  } };
57
64
  }
58
- var d = class {
65
+ var m = class {
59
66
  maxAttempts;
60
67
  constructor(e = 5) {
61
68
  this.maxAttempts = e;
@@ -66,7 +73,7 @@ var d = class {
66
73
  delayMs(e) {
67
74
  return e * 50;
68
75
  }
69
- }, f = class {
76
+ }, h = class {
70
77
  retryableStatuses = [
71
78
  408,
72
79
  429,
@@ -85,7 +92,7 @@ var d = class {
85
92
  delayMs(e) {
86
93
  return Math.min(1e3 * 2 ** (e - 1), 1e4);
87
94
  }
88
- }, p = class {
95
+ }, g = class {
89
96
  failureCount = 0;
90
97
  lastFailureTime = 0;
91
98
  maxAttempts;
@@ -104,50 +111,50 @@ var d = class {
104
111
  this.failureCount = 0, this.lastFailureTime = 0;
105
112
  }
106
113
  };
107
- function m(e) {
114
+ function _(e) {
108
115
  return e.replace(/_([a-z])/g, (e, t) => t.toUpperCase());
109
116
  }
110
- function h(e) {
117
+ function ee(e) {
111
118
  return e.replace(/[A-Z]/g, (e) => `_${e.toLowerCase()}`);
112
119
  }
113
- function g(e, t) {
120
+ function v(e, t) {
114
121
  if (!e || typeof e != "object") return e;
115
- if (Array.isArray(e)) return e.map((e) => g(e, t));
122
+ if (Array.isArray(e)) return e.map((e) => v(e, t));
116
123
  let n = {};
117
- for (let [r, i] of Object.entries(e)) n[t(r)] = g(i, t);
124
+ for (let [r, i] of Object.entries(e)) n[t(r)] = v(i, t);
118
125
  return n;
119
126
  }
120
- function _(e, t = "") {
127
+ function y(e, t = "") {
121
128
  let n = {};
122
129
  if (Array.isArray(e)) e.forEach((e, r) => {
123
130
  let i = t ? `${t}[${r}]` : `[${r}]`;
124
- Object.assign(n, _(e, i));
131
+ Object.assign(n, y(e, i));
125
132
  });
126
133
  else if (e && typeof e == "object") for (let [r, i] of Object.entries(e)) {
127
134
  let e = t ? `${t}.${r}` : r;
128
- i && typeof i == "object" && !Array.isArray(i) ? Object.assign(n, _(i, e)) : n[e] = i;
135
+ i && typeof i == "object" && !Array.isArray(i) ? Object.assign(n, y(i, e)) : n[e] = i;
129
136
  }
130
137
  return n;
131
138
  }
132
- function v(e, t) {
139
+ function b(e, t) {
133
140
  if (!e || typeof e != "object") return {};
134
141
  let n = e, r = {};
135
142
  for (let e of t) e in n && (r[e] = n[e]);
136
143
  return r;
137
144
  }
138
- function y(e) {
145
+ function te(e) {
139
146
  let t = new AbortController(), n = setTimeout(() => t.abort(), e);
140
147
  return t.signal.addEventListener("abort", () => clearTimeout(n), { once: !0 }), t;
141
148
  }
142
- async function b(e, t = 3) {
149
+ async function x(e, t = 3) {
143
150
  try {
144
151
  return await e();
145
152
  } catch (n) {
146
153
  if (t <= 0) throw n;
147
- return b(e, t - 1);
154
+ return x(e, t - 1);
148
155
  }
149
156
  }
150
- var x = class {
157
+ var S = class {
151
158
  cache = /* @__PURE__ */ new Map();
152
159
  get(e) {
153
160
  let t = this.cache.get(e);
@@ -171,8 +178,8 @@ var x = class {
171
178
  this.cache.delete(e);
172
179
  }
173
180
  };
174
- function S(e = {}) {
175
- let t = e.cache || new x(), n = e.ttlMs || 6e4, r = e.cacheableStatuses || [200, 304];
181
+ function C(e = {}) {
182
+ let t = e.cache || new S(), n = e.ttlMs || 6e4, r = e.cacheableStatuses || [200, 304];
176
183
  return async (e, i) => {
177
184
  let a = (e.request.method || "GET").toUpperCase(), o = a === "GET", s = `${a}:${e.request.url}`;
178
185
  if (o && t.has(s)) {
@@ -185,7 +192,7 @@ function S(e = {}) {
185
192
  await i(), o && e.response && r.includes(e.response.status) && (t.set(s, e.response, n), e.state.cacheMiss = !0);
186
193
  };
187
194
  }
188
- var C = S(), w = class {
195
+ var ne = C(), w = class {
189
196
  pending = /* @__PURE__ */ new Map();
190
197
  async execute(e, t) {
191
198
  if (this.pending.has(e)) return this.pending.get(e);
@@ -215,8 +222,68 @@ function T(e = {}) {
215
222
  }
216
223
  };
217
224
  }
218
- var E = T();
219
- function D(e) {
225
+ var re = T();
226
+ function E(e = {
227
+ maxRequests: 100,
228
+ windowMs: 6e4
229
+ }) {
230
+ let t = e.windowMs ?? 6e4, n = e.maxRequests, r = e.keyGenerator ?? ((e) => `${e.request.method}:${e.request.url}`), i = /* @__PURE__ */ new Map();
231
+ return async (a, o) => {
232
+ let s = r(a), c = Date.now();
233
+ if (i.size > 1e3) for (let [e, t] of i.entries()) c > t.resetTime && i.delete(e);
234
+ let l = i.get(s);
235
+ if ((!l || c > l.resetTime) && (l = {
236
+ count: 0,
237
+ resetTime: c + t
238
+ }, i.set(s, l)), l.count >= n) {
239
+ a.response = {
240
+ status: e.errorResponse?.status ?? 429,
241
+ headers: { "Content-Type": "application/json" },
242
+ body: e.errorResponse?.body ?? {
243
+ error: "Too Many Requests",
244
+ message: "Rate limit exceeded"
245
+ }
246
+ }, a.state.rateLimited = !0;
247
+ return;
248
+ }
249
+ l.count++, a.state.rateLimit = {
250
+ limit: n,
251
+ remaining: n - l.count,
252
+ reset: l.resetTime
253
+ }, await o();
254
+ };
255
+ }
256
+ var ie = E();
257
+ function D(e = {}) {
258
+ let t = e.failureThreshold ?? 5, n = e.resetTimeout ?? 3e4, r = e.isFailure ?? ((e) => e.response.status >= 500), i = e.keyGenerator ?? ((e) => `${e.request.method}:${e.request.url}`), a = /* @__PURE__ */ new Map();
259
+ return async (e, o) => {
260
+ let s = i(e), c = a.get(s);
261
+ if (c || (c = {
262
+ state: "closed",
263
+ failures: 0,
264
+ lastFailure: 0,
265
+ successCount: 0
266
+ }, a.set(s, c)), c.state === "open") if (Date.now() - c.lastFailure > n) c.state = "half-open", c.successCount = 0;
267
+ else {
268
+ e.response = {
269
+ status: 503,
270
+ headers: { "Content-Type": "application/json" },
271
+ body: {
272
+ error: "Service Unavailable",
273
+ message: "Circuit breaker is open"
274
+ }
275
+ }, e.state.circuitOpen = !0;
276
+ return;
277
+ }
278
+ try {
279
+ await o(), r(e) ? (c.failures++, c.lastFailure = Date.now(), (c.failures >= t || c.state === "half-open") && (c.state = "open")) : (c.failures = 0, c.state === "half-open" && (c.successCount++, c.successCount >= 3 && (c.state = "closed", c.successCount = 0)));
280
+ } catch (e) {
281
+ throw c.failures++, c.lastFailure = Date.now(), (c.failures >= t || c.state === "half-open") && (c.state = "open"), e;
282
+ }
283
+ };
284
+ }
285
+ var ae = D();
286
+ function O(e) {
220
287
  return async (t) => {
221
288
  let n = -1;
222
289
  async function r(i) {
@@ -228,7 +295,7 @@ function D(e) {
228
295
  await r(0);
229
296
  };
230
297
  }
231
- var O = class {
298
+ var oe = class {
232
299
  middlewares = [];
233
300
  use(e) {
234
301
  return this.middlewares.push(e), this;
@@ -236,7 +303,7 @@ var O = class {
236
303
  async execute(e) {
237
304
  if (e && typeof e == "object" && "request" in e && "response" in e) {
238
305
  let t = e;
239
- return await D(this.middlewares.map((e) => typeof e == "function" && e.length === 2 ? e : async (t, n) => {
306
+ return await O(this.middlewares.map((e) => typeof e == "function" && e.length === 2 ? e : async (t, n) => {
240
307
  let r = e;
241
308
  t.response.body = await r(t.response.body), await n();
242
309
  }))(t), t.response.body;
@@ -249,7 +316,7 @@ var O = class {
249
316
  this.middlewares = [];
250
317
  }
251
318
  };
252
- function k(e, t, n, r = {}) {
319
+ function se(e, t, n, r = {}) {
253
320
  return {
254
321
  ok: e >= 200 && e < 300,
255
322
  data: t,
@@ -258,7 +325,7 @@ function k(e, t, n, r = {}) {
258
325
  headers: r
259
326
  };
260
327
  }
261
- function A(e) {
328
+ function k(e) {
262
329
  return async (t, n) => {
263
330
  let r = e.path, i;
264
331
  switch (e.method) {
@@ -282,13 +349,13 @@ function A(e) {
282
349
  return i;
283
350
  };
284
351
  }
285
- function j(e) {
352
+ function ce(e) {
286
353
  return { request: async (t, n, r) => {
287
354
  let i = e[n];
288
- return await A(i)(t, r);
355
+ return await k(i)(t, r);
289
356
  } };
290
357
  }
291
- var M = class e {
358
+ var le = class e {
292
359
  subscribers = [];
293
360
  errorSubscribers = [];
294
361
  completeSubscribers = [];
@@ -317,19 +384,19 @@ var M = class e {
317
384
  }, (e) => n.error(e), () => n.complete()), n;
318
385
  }
319
386
  };
320
- function N(e) {
387
+ function ue(e) {
321
388
  return (t) => {
322
389
  if (!e(t)) throw TypeError("Value does not match expected type");
323
390
  return t;
324
391
  };
325
392
  }
326
- function P(e) {
393
+ function A(e) {
327
394
  return e;
328
395
  }
329
- function F(e) {
330
- return P(e);
396
+ function de(e) {
397
+ return A(e);
331
398
  }
332
- var I = class {
399
+ var fe = class {
333
400
  _promise;
334
401
  resolveFunc;
335
402
  rejectFunc;
@@ -351,7 +418,7 @@ var I = class {
351
418
  return this._promise;
352
419
  }
353
420
  };
354
- async function L(e, t = {}) {
421
+ async function j(e, t = {}) {
355
422
  let n = e.body?.getReader();
356
423
  if (!n) throw Error("Response body is not readable");
357
424
  let r = [], i = 0, a = parseInt(e.headers.get("content-length") || "0", 10);
@@ -360,22 +427,22 @@ async function L(e, t = {}) {
360
427
  if (e) break;
361
428
  r.push(o), i += o.length, t.onChunk && await t.onChunk(o), t.onProgress && a > 0 && t.onProgress(i, a);
362
429
  }
363
- return R(r, i);
430
+ return M(r, i);
364
431
  }
365
- function R(e, t) {
432
+ function M(e, t) {
366
433
  let n = new Uint8Array(t), r = 0;
367
434
  for (let t of e) n.set(t, r), r += t.byteLength;
368
435
  return n;
369
436
  }
370
- async function z(e, t) {
371
- let n = await L(e);
437
+ async function pe(e, t) {
438
+ let n = await j(e);
372
439
  if (typeof window > "u") await (await import("fs").then((e) => e.promises)).writeFile(t, n);
373
440
  else {
374
441
  let e = new Blob([n.buffer], { type: "application/octet-stream" }), r = URL.createObjectURL(e), i = document.createElement("a");
375
442
  i.href = r, i.download = t, i.click(), URL.revokeObjectURL(r);
376
443
  }
377
444
  }
378
- function B(e = {}) {
445
+ function N(e = {}) {
379
446
  return async (t, n) => {
380
447
  if (await n(), t.response && t.response.body && typeof t.response.body == "object" && "getReader" in t.response.body) {
381
448
  let n = t.response.body.getReader(), r = [], i = 0, a = parseInt(t.response.headers?.["content-length"] || "0", 10);
@@ -385,7 +452,7 @@ function B(e = {}) {
385
452
  if (o) break;
386
453
  r.push(s), i += s.length, e.onChunk && await e.onChunk(s), e.onProgress && a > 0 && e.onProgress(i, a), t.state.streamedChunks = t.state.streamedChunks || [], t.state.streamedChunks.push(s);
387
454
  }
388
- let o = R(r, i);
455
+ let o = M(r, i);
389
456
  t.response.body = o, t.state.streaming = !0, t.state.streamedBytes = i;
390
457
  } finally {
391
458
  n.releaseLock();
@@ -393,14 +460,14 @@ function B(e = {}) {
393
460
  }
394
461
  };
395
462
  }
396
- var V = B({ onProgress: (e, t) => {
463
+ var me = N({ onProgress: (e, t) => {
397
464
  if (t > 0) {
398
465
  let n = Math.round(e / t * 100);
399
466
  console.log(`⬇️ Streaming: ${n}% (${e}/${t} bytes)`);
400
467
  }
401
- } }), H = class {
468
+ } }), P = class {
402
469
  plugins = [];
403
- cache = new x();
470
+ cache = new S();
404
471
  deduplicator = new w();
405
472
  middlewares = [];
406
473
  listeners = /* @__PURE__ */ new Map();
@@ -417,7 +484,7 @@ var V = B({ onProgress: (e, t) => {
417
484
  return this.deduplicator;
418
485
  }
419
486
  getPipeline() {
420
- return D(this.middlewares);
487
+ return O(this.middlewares);
421
488
  }
422
489
  async executePipeline(e) {
423
490
  await this.getPipeline()(e);
@@ -438,7 +505,7 @@ var V = B({ onProgress: (e, t) => {
438
505
  clear() {
439
506
  this.plugins = [], this.middlewares = [], this.listeners.clear(), this.cache.clear(), this.deduplicator.clear();
440
507
  }
441
- }, U = {
508
+ }, he = {
442
509
  name: "logger",
443
510
  setup(e) {
444
511
  e.on("request:start", (...e) => {
@@ -452,7 +519,7 @@ var V = B({ onProgress: (e, t) => {
452
519
  console.error(`❌ Request failed: ${t}`, n);
453
520
  });
454
521
  }
455
- }, W = class {
522
+ }, ge = class {
456
523
  name = "metrics";
457
524
  metrics = {
458
525
  requests: 0,
@@ -469,22 +536,294 @@ var V = B({ onProgress: (e, t) => {
469
536
  getMetrics() {
470
537
  return { ...this.metrics };
471
538
  }
472
- }, G = class {
539
+ }, _e = class {
473
540
  name = "cache";
474
541
  ttlMs;
475
542
  constructor(e = 6e4) {
476
543
  this.ttlMs = e;
477
544
  }
478
545
  setup(e) {
479
- e.addMiddleware(S({ ttlMs: this.ttlMs }));
546
+ e.addMiddleware(C({ ttlMs: this.ttlMs }));
480
547
  }
481
- }, K = class {
548
+ }, ve = class {
482
549
  name = "dedupe";
483
550
  setup(e) {
484
551
  e.addMiddleware(T());
485
552
  }
486
- }, q = class {
487
- store = new x();
553
+ }, ye = class {
554
+ name = "rate-limit";
555
+ options;
556
+ constructor(e = {}) {
557
+ this.options = e;
558
+ }
559
+ setup(e) {
560
+ e.addMiddleware(E({
561
+ maxRequests: this.options.maxRequests ?? 100,
562
+ windowMs: this.options.windowMs ?? 6e4,
563
+ keyGenerator: this.options.keyGenerator,
564
+ errorResponse: this.options.errorResponse
565
+ }));
566
+ }
567
+ }, be = class {
568
+ name = "circuit-breaker";
569
+ options;
570
+ constructor(e = {}) {
571
+ this.options = e;
572
+ }
573
+ setup(e) {
574
+ e.addMiddleware(D({
575
+ failureThreshold: this.options.failureThreshold ?? 5,
576
+ resetTimeout: this.options.resetTimeout ?? 3e4,
577
+ isFailure: this.options.isFailure,
578
+ keyGenerator: this.options.keyGenerator
579
+ }));
580
+ }
581
+ }, F = /* @__PURE__ */ n({
582
+ Http2SessionPool: () => B,
583
+ closeHttp2SessionPool: () => De,
584
+ getHttp2SessionPoolStats: () => Oe,
585
+ nodeHttp2Adapter: () => Ee,
586
+ nodeHttpAdapter: () => Te
587
+ });
588
+ async function xe() {
589
+ return L || (L = await import("http"), R = await import("https")), {
590
+ http: L,
591
+ https: R
592
+ };
593
+ }
594
+ async function Se() {
595
+ return z ||= await import("http2"), z;
596
+ }
597
+ function I(e, t) {
598
+ let n, r, i, a, o;
599
+ if (typeof e == "string") n = e, r = t?.method || "GET", i = t?.headers || {}, a = t?.body, o = t?.signal === null ? void 0 : t?.signal;
600
+ else {
601
+ n = e.url, r = t?.method || e.method || "GET";
602
+ let s = new Headers(e.headers), c = new Headers(t?.headers), l = new Headers(s);
603
+ c.forEach((e, t) => l.set(t, e)), i = Object.fromEntries(l.entries()), a = t?.body ?? e.body ?? void 0, o = t?.signal === null ? e.signal : t?.signal;
604
+ }
605
+ return {
606
+ url: n,
607
+ method: r,
608
+ headers: i,
609
+ body: a,
610
+ signal: o
611
+ };
612
+ }
613
+ function Ce(e, t, n, r, i = !1) {
614
+ if (i) return null;
615
+ let a = e.startsWith("https:") ? n.Agent : t.Agent, o = {
616
+ keepAlive: r?.keepAlive ?? !0,
617
+ maxSockets: r?.maxSockets ?? 50,
618
+ maxFreeSockets: r?.maxFreeSockets ?? 10,
619
+ timeout: r?.timeout ?? 6e4
620
+ };
621
+ return r?.maxRequestsPerSocket !== void 0 && (o.maxRequestsPerSocket = r.maxRequestsPerSocket), new a(o);
622
+ }
623
+ async function we(e) {
624
+ let t = new Headers();
625
+ for (let [n, r] of Object.entries(e.headers)) Array.isArray(r) ? r.forEach((e) => t.append(n, e)) : r !== void 0 && t.set(n, String(r));
626
+ let n = [];
627
+ return e.on("data", (e) => n.push(e)), new Promise((r) => {
628
+ e.on("end", () => {
629
+ let i = Buffer.concat(n);
630
+ r(new Response(i, {
631
+ status: e.statusCode || 200,
632
+ statusText: e.statusMessage || "OK",
633
+ headers: t
634
+ }));
635
+ });
636
+ });
637
+ }
638
+ async function Te(e, t, n) {
639
+ let { http: r, https: i } = await xe(), { url: a, method: o, headers: s, body: c, signal: l } = I(e, t), u = new URL(a), d = u.protocol === "https:", f = d ? i : r, p = Ce(a, r, i, n, !1);
640
+ return new Promise((e, t) => {
641
+ let r = f.request({
642
+ hostname: u.hostname,
643
+ port: u.port || (d ? 443 : 80),
644
+ path: u.pathname + u.search,
645
+ method: o,
646
+ headers: s,
647
+ agent: p
648
+ });
649
+ if (l) {
650
+ if (l.aborted) {
651
+ r.destroy(), t(/* @__PURE__ */ Error("Request aborted"));
652
+ return;
653
+ }
654
+ let e = () => {
655
+ r.destroy(), t(/* @__PURE__ */ Error("Request aborted"));
656
+ };
657
+ l.addEventListener("abort", e);
658
+ let n = () => l.removeEventListener("abort", e);
659
+ r.on("close", n), r.on("error", n);
660
+ }
661
+ r.setTimeout(n?.timeout ?? 6e4, () => {
662
+ r.destroy(), t(/* @__PURE__ */ Error("Request timed out"));
663
+ }), r.on("response", async (n) => {
664
+ try {
665
+ e(await we(n));
666
+ } catch (e) {
667
+ t(e);
668
+ }
669
+ }), r.on("error", t), c && (typeof c == "string" ? r.write(c) : c instanceof Uint8Array ? r.write(Buffer.from(c)) : Buffer.isBuffer(c) ? r.write(c) : typeof c == "object" && r.write(JSON.stringify(c))), r.end();
670
+ });
671
+ }
672
+ async function Ee(e, t, n) {
673
+ let { url: r, method: i, headers: a, body: o, signal: s } = I(e, t), c = new URL(r), l = c.origin;
674
+ return new Promise(async (e, t) => {
675
+ let r, u, d = !1, f = () => {
676
+ d || (d = !0, V.releaseSession(l));
677
+ }, p = (e) => {
678
+ f(), t(e);
679
+ }, m = (t) => {
680
+ f(), e(t);
681
+ };
682
+ try {
683
+ if (r = await V.getSession(l, n), s?.aborted) {
684
+ p(/* @__PURE__ */ Error("Request aborted"));
685
+ return;
686
+ }
687
+ if (u = r.request({
688
+ ":path": c.pathname + c.search,
689
+ ":method": i,
690
+ ...a
691
+ }), n?.timeout && u.setTimeout(n.timeout, () => {
692
+ u.close(), p(/* @__PURE__ */ Error("Request timed out"));
693
+ }), s) {
694
+ let e = () => {
695
+ u.close(), p(/* @__PURE__ */ Error("Request aborted"));
696
+ };
697
+ s.addEventListener("abort", e);
698
+ let t = () => s.removeEventListener("abort", e);
699
+ u.on("close", t), u.on("error", t);
700
+ }
701
+ let e = [];
702
+ u.on("data", (t) => e.push(Buffer.isBuffer(t) ? t : Buffer.from(t))), u.on("response", (t) => {
703
+ let n = Number(t[":status"]) || 200, r = new Headers();
704
+ for (let [e, n] of Object.entries(t)) e.startsWith(":") || (Array.isArray(n) ? n.forEach((t) => r.append(e, t)) : n !== void 0 && r.set(e, String(n)));
705
+ u.on("end", () => {
706
+ let t = Buffer.concat(e);
707
+ m(new Response(t, {
708
+ status: n,
709
+ statusText: "OK",
710
+ headers: r
711
+ }));
712
+ });
713
+ }), u.on("error", (e) => {
714
+ p(e);
715
+ }), o && (typeof o == "string" || o instanceof Uint8Array || Buffer.isBuffer(o) ? u.write(o) : typeof o == "object" && u.write(JSON.stringify(o))), u.end();
716
+ } catch (e) {
717
+ p(e instanceof Error ? e : Error(String(e)));
718
+ }
719
+ });
720
+ }
721
+ function De() {
722
+ V.closeAll();
723
+ }
724
+ function Oe() {
725
+ let e = V.getStats();
726
+ return {
727
+ sessionCount: e.sessionCount,
728
+ origins: e.origins
729
+ };
730
+ }
731
+ var L, R, z, B, V, H = t((() => {
732
+ B = class {
733
+ sessions = /* @__PURE__ */ new Map();
734
+ cleanupInterval = null;
735
+ maxIdleTime = 3e4;
736
+ maxRequestsPerSession = 1e3;
737
+ constructor() {
738
+ this.startCleanup();
739
+ }
740
+ startCleanup() {
741
+ this.cleanupInterval ||= setInterval(() => this.cleanup(), 1e4);
742
+ }
743
+ cleanup() {
744
+ let e = Date.now();
745
+ for (let t of this.sessions.values()) !t.closing && e - t.lastUsed > this.maxIdleTime && this.closeSession(t, "idle timeout"), !t.closing && t.requestCount >= this.maxRequestsPerSession && this.closeSession(t, "max requests exceeded");
746
+ }
747
+ closeSession(e, t) {
748
+ e.closing = !0, e.session.close(), this.sessions.delete(e.origin);
749
+ }
750
+ async getSession(e, t) {
751
+ let n = this.sessions.get(e);
752
+ if (n && !n.session.closed && !n.session.destroyed) return n.lastUsed = Date.now(), n.requestCount++, n.session;
753
+ let r = (await Se()).connect(e, { settings: t?.http2Settings });
754
+ return r.on("error", (t) => {
755
+ this.sessions.delete(e);
756
+ }), r.on("close", () => {
757
+ this.sessions.delete(e);
758
+ }), n = {
759
+ session: r,
760
+ lastUsed: Date.now(),
761
+ requestCount: 1,
762
+ origin: e,
763
+ closing: !1
764
+ }, this.sessions.set(e, n), r;
765
+ }
766
+ releaseSession(e) {
767
+ let t = this.sessions.get(e);
768
+ t && (t.lastUsed = Date.now());
769
+ }
770
+ getStats() {
771
+ return {
772
+ sessionCount: this.sessions.size,
773
+ origins: Array.from(this.sessions.keys()),
774
+ sessions: Array.from(this.sessions.values()).map((e) => ({
775
+ origin: e.origin,
776
+ requestCount: e.requestCount,
777
+ lastUsed: e.lastUsed,
778
+ closing: e.closing,
779
+ sessionAlive: !e.session.closed && !e.session.destroyed
780
+ }))
781
+ };
782
+ }
783
+ closeAll() {
784
+ for (let e of this.sessions.values()) e.closing || e.session.close();
785
+ this.sessions.clear(), this.cleanupInterval &&= (clearInterval(this.cleanupInterval), null);
786
+ }
787
+ }, V = new B();
788
+ }));
789
+ //#endregion
790
+ //#region src/http-client/http-client.ts
791
+ function ke() {
792
+ return typeof window > "u" && typeof process < "u" && process.versions?.node !== void 0;
793
+ }
794
+ function Ae() {
795
+ let e = globalThis;
796
+ return typeof window > "u" && e.Deno !== void 0 && e.Deno.version?.deno !== void 0;
797
+ }
798
+ function je() {
799
+ let e = globalThis;
800
+ return e.Bun !== void 0 && e.Bun.version !== void 0;
801
+ }
802
+ function Me() {
803
+ let e = globalThis;
804
+ return e.caches !== void 0 && e.WebSocketPair !== void 0;
805
+ }
806
+ function Ne(e, t) {
807
+ if (!e || e === "fetch") return fetch;
808
+ if (e === "node" || e === "http2") {
809
+ if (!ke()) throw Error(`Transport '${e}' is only available in Node.js environment`);
810
+ return (n, r) => e === "http2" ? Promise.resolve().then(() => (H(), F)).then((e) => e.nodeHttp2Adapter(n, r, t)) : Promise.resolve().then(() => (H(), F)).then((e) => e.nodeHttpAdapter(n, r, t));
811
+ }
812
+ switch (e) {
813
+ case "deno":
814
+ if (!Ae()) throw Error("Transport 'deno' is only available in Deno environment");
815
+ return fetch;
816
+ case "bun":
817
+ if (!je()) throw Error("Transport 'bun' is only available in Bun environment");
818
+ return fetch;
819
+ case "cloudflare":
820
+ if (!Me()) throw Error("Transport 'cloudflare' is only available in Cloudflare Workers environment");
821
+ return fetch;
822
+ default: return fetch;
823
+ }
824
+ }
825
+ var Pe = class {
826
+ store = new S();
488
827
  get(e) {
489
828
  return this.store.get(e);
490
829
  }
@@ -497,7 +836,7 @@ var V = B({ onProgress: (e, t) => {
497
836
  clear() {
498
837
  this.store.clear();
499
838
  }
500
- }, J = class {
839
+ }, Fe = class {
501
840
  maxAttempts;
502
841
  baseDelayMs;
503
842
  constructor(e = 3, t = 100) {
@@ -511,7 +850,24 @@ var V = B({ onProgress: (e, t) => {
511
850
  let t = this.baseDelayMs * 2 ** (e - 1), n = Math.random() * t * .1;
512
851
  return Math.min(t + n, 3e4);
513
852
  }
514
- }, Y = class {
853
+ }, Ie = class {
854
+ maxAttempts;
855
+ baseDelayMs;
856
+ condition;
857
+ constructor(e = 3, t = 100, n) {
858
+ this.maxAttempts = e, this.baseDelayMs = t, this.condition = n;
859
+ }
860
+ shouldRetry(e, t) {
861
+ if (e >= this.maxAttempts) return !1;
862
+ if (this.condition) return this.condition(t, e);
863
+ let n = t.status !== void 0 && t.status >= 500, r = t.code === "NETWORK_ERROR";
864
+ return n || r || t.code === "TIMEOUT";
865
+ }
866
+ delayMs(e) {
867
+ let t = this.baseDelayMs * 2 ** (e - 1), n = Math.random() * t * .1;
868
+ return Math.min(t + n, 3e4);
869
+ }
870
+ }, Le = class {
515
871
  running = 0;
516
872
  queue = [];
517
873
  maxConcurrent;
@@ -541,38 +897,66 @@ var V = B({ onProgress: (e, t) => {
541
897
  return this.running;
542
898
  }
543
899
  };
544
- function X(e) {
545
- return e == null ? {
900
+ function U(e) {
901
+ return e == null ? !1 : typeof Blob < "u" && e instanceof Blob || typeof File < "u" && e instanceof File ? !0 : Array.isArray(e) ? e.some((e) => U(e)) : typeof e == "object" ? Object.values(e).some((e) => U(e)) : !1;
902
+ }
903
+ function W(e, t, n) {
904
+ let r = t || new FormData();
905
+ for (let [t, i] of Object.entries(e)) {
906
+ let e = n ? `${n}[${t}]` : t;
907
+ i != null && (typeof Blob < "u" && i instanceof Blob ? r.append(e, i) : Array.isArray(i) ? i.some((e) => U(e)) ? i.forEach((t) => {
908
+ U(t) ? r.append(e, t) : r.append(e, JSON.stringify(t));
909
+ }) : r.append(e, JSON.stringify(i)) : typeof i == "object" && !(i instanceof Blob) ? W(i, r, e) : r.append(e, String(i)));
910
+ }
911
+ return r;
912
+ }
913
+ function Re(e, t) {
914
+ return !t || e == null || typeof FormData < "u" && e instanceof FormData || typeof Blob < "u" && e instanceof Blob || typeof URLSearchParams < "u" && e instanceof URLSearchParams || e instanceof ArrayBuffer || ArrayBuffer.isView(e) || typeof ReadableStream < "u" && e instanceof ReadableStream || typeof e == "string" ? e : typeof e == "object" && U(e) ? W(e) : e;
915
+ }
916
+ function ze(e, t = !0) {
917
+ let n = Re(e, t);
918
+ return n == null ? {
546
919
  serialized: void 0,
547
920
  contentType: null
548
- } : typeof FormData < "u" && e instanceof FormData ? {
549
- serialized: e,
921
+ } : typeof FormData < "u" && n instanceof FormData ? {
922
+ serialized: n,
550
923
  contentType: null
551
- } : typeof URLSearchParams < "u" && e instanceof URLSearchParams ? {
552
- serialized: e,
924
+ } : typeof URLSearchParams < "u" && n instanceof URLSearchParams ? {
925
+ serialized: n,
553
926
  contentType: "application/x-www-form-urlencoded"
554
- } : typeof Blob < "u" && e instanceof Blob ? {
555
- serialized: e,
556
- contentType: e.type || "application/octet-stream"
557
- } : e instanceof ArrayBuffer || ArrayBuffer.isView(e) || typeof ReadableStream < "u" && e instanceof ReadableStream ? {
558
- serialized: e,
927
+ } : typeof Blob < "u" && n instanceof Blob ? {
928
+ serialized: n,
929
+ contentType: n.type || "application/octet-stream"
930
+ } : n instanceof ArrayBuffer || ArrayBuffer.isView(n) || typeof ReadableStream < "u" && n instanceof ReadableStream ? {
931
+ serialized: n,
559
932
  contentType: "application/octet-stream"
560
- } : typeof e == "string" ? {
561
- serialized: e,
933
+ } : typeof n == "string" ? {
934
+ serialized: n,
562
935
  contentType: "text/plain"
563
936
  } : {
564
- serialized: JSON.stringify(e),
937
+ serialized: JSON.stringify(n),
565
938
  contentType: "application/json"
566
939
  };
567
940
  }
568
- function Z(e, t) {
941
+ function G(e, t) {
569
942
  return t ? e.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g, (e, n) => {
570
943
  let r = t[n];
571
944
  if (r === void 0) throw Error(`Missing path parameter: :${n}`);
572
945
  return encodeURIComponent(String(r));
573
946
  }) : e;
574
947
  }
575
- var Q = class n {
948
+ function K(e, t) {
949
+ if (e !== void 0) return e;
950
+ if (t !== void 0) return t ? "include" : "same-origin";
951
+ }
952
+ function Be(e) {
953
+ return typeof e == "number" ? { total: e } : typeof e == "object" && e ? {
954
+ connection: e.connection,
955
+ response: e.response,
956
+ total: e.total
957
+ } : {};
958
+ }
959
+ var q = class e {
576
960
  requestInterceptors = [];
577
961
  responseInterceptors = [];
578
962
  cache;
@@ -585,71 +969,104 @@ var Q = class n {
585
969
  defaultHeaders: e.defaultHeaders ?? { "Content-Type": "application/json" },
586
970
  defaultTimeout: e.defaultTimeout ?? 3e4,
587
971
  validateStatus: e.validateStatus ?? ((e) => e >= 200 && e < 300),
588
- cacheStrategy: e.cacheStrategy ?? new q(),
972
+ cacheStrategy: e.cacheStrategy ?? new Pe(),
589
973
  maxConcurrent: e.maxConcurrent ?? 0,
590
974
  defaultResponseType: e.defaultResponseType ?? "auto",
591
- defaultHooks: e.defaultHooks ?? {}
592
- }, this.cache = this.config.cacheStrategy, this.requestQueue = this.config.maxConcurrent > 0 ? new Y(this.config.maxConcurrent) : null;
593
- }
594
- async request(n) {
595
- let r = {
975
+ defaultHooks: e.defaultHooks ?? {},
976
+ transformRequest: e.transformRequest,
977
+ credentials: K(e.credentials, e.withCredentials),
978
+ adapter: e.adapter,
979
+ autoFormData: e.autoFormData ?? !0,
980
+ debug: e.debug,
981
+ logger: e.logger,
982
+ transport: e.transport,
983
+ nodeOptions: e.nodeOptions
984
+ }, this.cache = this.config.cacheStrategy, this.requestQueue = this.config.maxConcurrent > 0 ? new Le(this.config.maxConcurrent) : null;
985
+ }
986
+ logDebug(e, t, n, r, i) {
987
+ let a = e ?? this.config.debug;
988
+ if (!a || a === !0 && t === "verbose") return;
989
+ let o = "[Nexa HTTP] " + n, s = i ?? this.config.logger ?? console.log;
990
+ r === void 0 ? s(o) : s(o, r);
991
+ }
992
+ async request(e) {
993
+ let t = {
596
994
  ...this.config.defaultHooks,
597
- ...n.hooks
598
- }, i = this.getMaxAttempts(n.retry), a = this.getRetryStrategy(n.retry), o = Symbol("request");
599
- r.onStart?.(this.buildRequest(n)), this.requestQueue && await this.requestQueue.acquire();
995
+ ...e.hooks
996
+ }, n = e.debug ?? this.config.debug, a = e.logger ?? this.config.logger, o = this.getMaxAttempts(e.retry), s = this.getRetryStrategy(e.retry), c = Symbol("request");
997
+ t.onStart?.(this.buildRequest(e)), this.requestQueue && await this.requestQueue.acquire();
600
998
  try {
601
- for (let s = 1; s <= i; s++) try {
602
- if ((n.method === "GET" || !n.method) && n.cache?.enabled) {
603
- let t = this.getCacheKey(n), i = this.cache.get(t);
604
- if (i) {
605
- let t = i;
606
- return r.onSuccess?.(t), r.onFinally?.(), e(t);
999
+ for (let l = 1; l <= o; l++) {
1000
+ let u;
1001
+ try {
1002
+ if ((e.method === "GET" || !e.method) && e.cache?.enabled) {
1003
+ let i = this.getCacheKey(e), o = this.cache.get(i);
1004
+ if (o) {
1005
+ let i = o;
1006
+ return this.logDebug(n, "info", `Cache hit for ${e.url}`, i, a), t.onSuccess?.(i), t.onFinally?.(), r(i);
1007
+ }
607
1008
  }
1009
+ u = this.buildRequest(e), this.logDebug(n, "info", `${u.method || "GET"} ${u.url}`, u, a);
1010
+ for (let e of this.requestInterceptors) u = await e.onRequest(u);
1011
+ this.logDebug(n, "verbose", "Request after interceptors", u, a), u = this.applyTransformRequestToRequest(u, e), this.logDebug(n, "verbose", "Request after transformRequest", u, a);
1012
+ let i = Be(e.timeout ?? this.config.defaultTimeout), s = new AbortController();
1013
+ this.pendingRequests.set(c, s), e.signal && e.signal.addEventListener("abort", () => s.abort(), { once: !0 }), this.logDebug(n, "info", `Fetching (attempt ${l}/${o})`, {
1014
+ url: u.url,
1015
+ method: u.method
1016
+ }, a);
1017
+ let d = performance.now(), f = await this.fetchWithTimeout(u, i, s), p = performance.now() - d;
1018
+ this.logDebug(n, "info", `Response ${f.status} ${f.statusText}`, {
1019
+ duration: p,
1020
+ status: f.status,
1021
+ attempt: l
1022
+ }, a);
1023
+ let m = f;
1024
+ e.onDownloadProgress && f.body && (m = this.trackDownloadProgress(f, e.onDownloadProgress));
1025
+ let h = e.responseType ?? this.config.defaultResponseType, g = await this.parseResponse(m, u, p, h, i.response);
1026
+ if (!this.config.validateStatus(g.status)) throw {
1027
+ message: `Request failed with status ${g.status}`,
1028
+ status: g.status,
1029
+ statusText: g.statusText,
1030
+ code: "HTTP_ERROR",
1031
+ request: u,
1032
+ response: g,
1033
+ config: e
1034
+ };
1035
+ if (e.validate) {
1036
+ let t = e.validate.validate(g.data);
1037
+ if (!t.ok) return t;
1038
+ }
1039
+ e.transform && (g.data = e.transform.transform(g.data));
1040
+ let _ = g;
1041
+ for (let e of this.responseInterceptors) _ = await e.onResponse(_);
1042
+ if ((e.method === "GET" || !e.method) && e.cache?.enabled) {
1043
+ let t = this.getCacheKey(e);
1044
+ this.cache.set(t, _, e.cache.ttlMs);
1045
+ }
1046
+ return t.onSuccess?.(_), this.logDebug(n, "verbose", "Response data", _.data, a), this.pendingRequests.delete(c), r(_);
1047
+ } catch (r) {
1048
+ let d = this.normalizeError(r, u, e);
1049
+ if (this.logDebug(n, "info", `Error: ${d.message}`, {
1050
+ error: d,
1051
+ attempt: l
1052
+ }, a), l < o && s.shouldRetry(l, d)) {
1053
+ t.onRetry?.(l, d);
1054
+ let e = s.delayMs(l);
1055
+ this.logDebug(n, "info", `Retrying after ${e}ms (attempt ${l + 1}/${o})`, { error: d }, a), await this.delay(e);
1056
+ continue;
1057
+ }
1058
+ let f = d;
1059
+ for (let e of this.responseInterceptors) e.onError && (f = await e.onError(f));
1060
+ return t.onError?.(f), this.pendingRequests.delete(c), i(f);
608
1061
  }
609
- let t = this.buildRequest(n);
610
- for (let e of this.requestInterceptors) t = await e.onRequest(t);
611
- let i = new AbortController();
612
- this.pendingRequests.set(o, i), n.signal && n.signal.addEventListener("abort", () => i.abort(), { once: !0 });
613
- let a = performance.now(), s = await this.fetchWithTimeout(t, n.timeout ?? this.config.defaultTimeout, i), c = performance.now() - a, l = s;
614
- n.onDownloadProgress && s.body && (l = this.trackDownloadProgress(s, n.onDownloadProgress));
615
- let u = n.responseType ?? this.config.defaultResponseType, d = await this.parseResponse(l, t, c, u);
616
- if (!this.config.validateStatus(d.status)) throw {
617
- message: `Request failed with status ${d.status}`,
618
- status: d.status,
619
- statusText: d.statusText,
620
- code: "HTTP_ERROR"
621
- };
622
- if (n.validate) {
623
- let e = n.validate.validate(d.data);
624
- if (!e.ok) return e;
625
- }
626
- n.transform && (d.data = n.transform.transform(d.data));
627
- let f = d;
628
- for (let e of this.responseInterceptors) f = await e.onResponse(f);
629
- if ((n.method === "GET" || !n.method) && n.cache?.enabled) {
630
- let e = this.getCacheKey(n);
631
- this.cache.set(e, f, n.cache.ttlMs);
632
- }
633
- return r.onSuccess?.(f), this.pendingRequests.delete(o), e(f);
634
- } catch (e) {
635
- let n = this.isHttpErrorDetails(e) ? e : this.normalizeError(e);
636
- if (s < i && a.shouldRetry(s, n)) {
637
- r.onRetry?.(s, n);
638
- let e = a.delayMs(s);
639
- await this.delay(e);
640
- continue;
641
- }
642
- let c = n;
643
- for (let e of this.responseInterceptors) e.onError && (c = await e.onError(c));
644
- return r.onError?.(c), this.pendingRequests.delete(o), t(c);
645
1062
  }
646
- let s = {
1063
+ let l = {
647
1064
  message: "Max retries exceeded",
648
1065
  code: "MAX_RETRIES"
649
1066
  };
650
- return r.onError?.(s), t(s);
1067
+ return this.logDebug(n, "info", "Max retries exceeded", l, a), t.onError?.(l), i(l);
651
1068
  } finally {
652
- r.onFinally?.(), this.requestQueue && this.requestQueue.release();
1069
+ t.onFinally?.(), this.requestQueue && this.requestQueue.release();
653
1070
  }
654
1071
  }
655
1072
  get(e, t) {
@@ -735,26 +1152,30 @@ var Q = class n {
735
1152
  pending: this.requestQueue?.pending ?? 0
736
1153
  };
737
1154
  }
738
- extend(e = {}) {
739
- let t = new n({
740
- baseURL: e.baseURL ?? this.config.baseURL,
1155
+ extend(t = {}) {
1156
+ let n = new e({
1157
+ baseURL: t.baseURL ?? this.config.baseURL,
741
1158
  defaultHeaders: {
742
1159
  ...this.config.defaultHeaders,
743
- ...e.defaultHeaders
1160
+ ...t.defaultHeaders
744
1161
  },
745
- defaultTimeout: e.defaultTimeout ?? this.config.defaultTimeout,
746
- validateStatus: e.validateStatus ?? this.config.validateStatus,
747
- cacheStrategy: e.cacheStrategy ?? this.cache,
748
- maxConcurrent: e.maxConcurrent ?? this.config.maxConcurrent,
749
- defaultResponseType: e.defaultResponseType ?? this.config.defaultResponseType,
1162
+ credentials: K(t.credentials, t.withCredentials) ?? this.config.credentials,
1163
+ defaultTimeout: t.defaultTimeout ?? this.config.defaultTimeout,
1164
+ validateStatus: t.validateStatus ?? this.config.validateStatus,
1165
+ cacheStrategy: t.cacheStrategy ?? this.cache,
1166
+ maxConcurrent: t.maxConcurrent ?? this.config.maxConcurrent,
1167
+ defaultResponseType: t.defaultResponseType ?? this.config.defaultResponseType,
750
1168
  defaultHooks: {
751
1169
  ...this.config.defaultHooks,
752
- ...e.defaultHooks
753
- }
1170
+ ...t.defaultHooks
1171
+ },
1172
+ transformRequest: t.transformRequest ?? this.config.transformRequest,
1173
+ adapter: t.adapter ?? this.config.adapter,
1174
+ autoFormData: t.autoFormData ?? this.config.autoFormData
754
1175
  });
755
- for (let e of this.requestInterceptors) t.addRequestInterceptor(e);
756
- for (let e of this.responseInterceptors) t.addResponseInterceptor(e);
757
- return t;
1176
+ for (let e of this.requestInterceptors) n.addRequestInterceptor(e);
1177
+ for (let e of this.responseInterceptors) n.addResponseInterceptor(e);
1178
+ return n;
758
1179
  }
759
1180
  async *paginate(e, t, n = {}) {
760
1181
  let r = { ...n };
@@ -767,30 +1188,38 @@ var Q = class n {
767
1188
  r = i;
768
1189
  }
769
1190
  }
770
- async poll(e, n, r = {}) {
771
- let i = n.maxAttempts ?? 0;
772
- for (let t = 1; i === 0 || t <= i; t++) {
773
- let a = await this.get(e, r);
774
- if (!a.ok || (n.onPoll?.(a.value.data, t), n.until(a.value.data))) return a;
775
- if (i > 0 && t >= i) break;
776
- await this.delay(n.intervalMs);
1191
+ async poll(e, t, n = {}) {
1192
+ let r = t.maxAttempts ?? 0;
1193
+ for (let i = 1; r === 0 || i <= r; i++) {
1194
+ let a = await this.get(e, n);
1195
+ if (!a.ok || (t.onPoll?.(a.value.data, i), t.until(a.value.data))) return a;
1196
+ if (r > 0 && i >= r) break;
1197
+ await this.delay(t.intervalMs);
777
1198
  }
778
- return t({
779
- message: `Polling exhausted after ${i} attempts`,
1199
+ return i({
1200
+ message: `Polling exhausted after ${r} attempts`,
780
1201
  code: "POLL_EXHAUSTED"
781
1202
  });
782
1203
  }
783
1204
  buildRequest(e) {
784
- let t = Z(e.url, e.params);
1205
+ let t = G(e.url, e.params), n = this.buildUrl(t, e.query), r = K(e.credentials, e.withCredentials) ?? this.config.credentials, i = e.transport ?? this.config.transport, a = e.nodeOptions ?? this.config.nodeOptions;
785
1206
  return {
786
- url: this.buildUrl(t, e.query),
1207
+ url: n,
787
1208
  method: e.method ?? "GET",
788
1209
  headers: {
789
1210
  ...this.config.defaultHeaders,
790
1211
  ...e.headers
791
1212
  },
792
1213
  body: e.body,
793
- params: e.params
1214
+ query: e.query,
1215
+ params: e.params,
1216
+ timeout: e.timeout,
1217
+ signal: e.signal,
1218
+ credentials: r,
1219
+ adapter: e.adapter,
1220
+ autoFormData: e.autoFormData ?? this.config.autoFormData,
1221
+ transport: i,
1222
+ nodeOptions: a
794
1223
  };
795
1224
  }
796
1225
  buildUrl(e, t) {
@@ -803,27 +1232,44 @@ var Q = class n {
803
1232
  }
804
1233
  return n;
805
1234
  }
1235
+ applyTransformRequestToRequest(e, t) {
1236
+ let n = this.config.transformRequest, r = t.transformRequest, i = [];
1237
+ if (n && (Array.isArray(n) ? i.push(...n) : i.push(n)), r && (Array.isArray(r) ? i.push(...r) : i.push(r)), i.length === 0) return e;
1238
+ let a = e.body, o = e.headers ?? {};
1239
+ for (let e of i) a = e(a, o);
1240
+ return {
1241
+ ...e,
1242
+ body: a,
1243
+ headers: o
1244
+ };
1245
+ }
806
1246
  getCacheKey(e) {
807
- let t = Z(e.url, e.params), n = e.query ? JSON.stringify(e.query) : "";
1247
+ let t = G(e.url, e.params), n = e.query ? JSON.stringify(e.query) : "";
808
1248
  return `${e.method ?? "GET"}:${t}${n ? ":" + n : ""}`;
809
1249
  }
810
1250
  fetchWithTimeout(e, t, n) {
811
- let { serialized: r, contentType: i } = X(e.body), a = { ...e.headers };
812
- return i ? a["Content-Type"] = i : i === null && r instanceof FormData && delete a["Content-Type"], new Promise((i, o) => {
813
- let s = setTimeout(() => {
1251
+ let { serialized: r, contentType: i } = ze(e.body, e.autoFormData), a = { ...e.headers };
1252
+ i ? a["Content-Type"] = i : i === null && r instanceof FormData && delete a["Content-Type"];
1253
+ let o = t.total ?? t.connection;
1254
+ return new Promise((t, i) => {
1255
+ let s = null;
1256
+ o !== void 0 && (s = setTimeout(() => {
814
1257
  n.abort();
815
1258
  let e = /* @__PURE__ */ Error("Request timed out");
816
- e.name = "TimeoutError", o(e);
817
- }, t);
818
- fetch(e.url, {
1259
+ e.name = "TimeoutError", i(e);
1260
+ }, o));
1261
+ let c = {
819
1262
  method: e.method,
820
1263
  headers: a,
821
1264
  body: r,
822
1265
  signal: n.signal
823
- }).then((e) => {
824
- clearTimeout(s), i(e);
1266
+ };
1267
+ e.credentials !== void 0 && (c.credentials = e.credentials);
1268
+ let l = e.transport ?? this.config.transport ?? "fetch", u = e.nodeOptions ?? this.config.nodeOptions, d = e.adapter ?? this.config.adapter;
1269
+ d ||= Ne(l, u), d(e.url, c).then((e) => {
1270
+ s && clearTimeout(s), t(e);
825
1271
  }, (e) => {
826
- clearTimeout(s), o(e);
1272
+ s && clearTimeout(s), i(e);
827
1273
  });
828
1274
  });
829
1275
  }
@@ -848,75 +1294,98 @@ var Q = class n {
848
1294
  statusText: e.statusText
849
1295
  });
850
1296
  }
851
- async parseResponse(e, t, n, r) {
852
- let i = await this.parseBody(e, r);
1297
+ withTimeout(e, t, n = "Operation timed out") {
1298
+ return t <= 0 ? e : new Promise((r, i) => {
1299
+ let a = setTimeout(() => {
1300
+ let e = Error(n);
1301
+ e.name = "TimeoutError", i(e);
1302
+ }, t);
1303
+ e.then((e) => {
1304
+ clearTimeout(a), r(e);
1305
+ }, (e) => {
1306
+ clearTimeout(a), i(e);
1307
+ });
1308
+ });
1309
+ }
1310
+ async parseResponse(e, t, n, r, i) {
1311
+ let a = await this.parseBody(e, r, i);
853
1312
  return {
854
1313
  status: e.status,
855
1314
  statusText: e.statusText,
856
1315
  headers: e.headers,
857
- data: i,
1316
+ data: a,
858
1317
  request: t,
859
1318
  duration: n
860
1319
  };
861
1320
  }
862
- async parseBody(e, t) {
1321
+ async parseBody(e, t, n) {
1322
+ let r = async (e) => n !== void 0 && n > 0 ? this.withTimeout(e, n, "Response timeout") : e;
863
1323
  switch (t) {
864
- case "json": return await e.json();
865
- case "text": return await e.text();
866
- case "blob": return await e.blob();
867
- case "arrayBuffer": return await e.arrayBuffer();
868
- case "formData": return await e.formData();
1324
+ case "json": return await r(e.json());
1325
+ case "text": return await r(e.text());
1326
+ case "blob": return await r(e.blob());
1327
+ case "arrayBuffer": return await r(e.arrayBuffer());
1328
+ case "formData": return await r(e.formData());
869
1329
  case "stream": return e.body;
870
1330
  default: {
871
1331
  let t = e.headers.get("content-type") ?? "";
872
- if (t.includes("application/json")) return await e.json();
873
- if (t.includes("text/")) return await e.text();
874
- if (t.includes("multipart/form-data")) return await e.formData();
875
- if (t.includes("application/octet-stream") || t.includes("image/") || t.includes("audio/") || t.includes("video/")) return await e.blob();
1332
+ if (t.includes("application/json")) return await r(e.json());
1333
+ if (t.includes("text/")) return await r(e.text());
1334
+ if (t.includes("multipart/form-data")) return await r(e.formData());
1335
+ if (t.includes("application/octet-stream") || t.includes("image/") || t.includes("audio/") || t.includes("video/")) return await r(e.blob());
876
1336
  try {
877
- return await e.json();
1337
+ return await r(e.json());
878
1338
  } catch {
879
- return await e.text();
1339
+ return await r(e.text());
880
1340
  }
881
1341
  }
882
1342
  }
883
1343
  }
884
- normalizeError(e) {
885
- return e instanceof Error && e.name === "TimeoutError" ? {
886
- message: "Request timed out",
887
- code: "TIMEOUT"
888
- } : e instanceof DOMException && e.name === "AbortError" ? {
889
- message: "Request aborted",
890
- code: "ABORTED"
891
- } : e instanceof Error ? e.name === "AbortError" || e.message.includes("abort") ? {
892
- message: "Request aborted",
893
- code: "ABORTED"
894
- } : {
1344
+ normalizeError(e, t, n) {
1345
+ let r = (r, i) => ({
1346
+ message: i,
1347
+ code: r,
1348
+ originalError: e,
1349
+ request: t,
1350
+ config: n
1351
+ });
1352
+ return e instanceof Error && e.name === "TimeoutError" ? e.message.includes("Response timeout") ? r("RESPONSE_TIMEOUT", e.message) : r("TIMEOUT", "Request timed out") : e instanceof DOMException && e.name === "AbortError" ? r("ABORTED", "Request aborted") : e instanceof Error ? e.name === "AbortError" || e.message.includes("abort") ? r("ABORTED", "Request aborted") : {
895
1353
  message: e.message,
896
1354
  code: e.name === "TypeError" ? "NETWORK_ERROR" : "UNKNOWN_ERROR",
897
- originalError: e
1355
+ originalError: e,
1356
+ request: t,
1357
+ config: n
1358
+ } : this.isHttpErrorDetails(e) ? {
1359
+ ...e,
1360
+ request: e.request ?? t,
1361
+ config: e.config ?? n
898
1362
  } : {
899
1363
  message: String(e),
900
1364
  code: "UNKNOWN_ERROR",
901
- originalError: e
1365
+ originalError: e,
1366
+ request: t,
1367
+ config: n
902
1368
  };
903
1369
  }
904
1370
  isHttpErrorDetails(e) {
905
1371
  return typeof e == "object" && !!e && "message" in e && "code" in e;
906
1372
  }
907
1373
  getMaxAttempts(e) {
908
- return e ? "maxAttempts" in e ? e.maxAttempts : 100 : 1;
1374
+ return e ? "shouldRetry" in e ? 100 : e.maxAttempts ?? 3 : 1;
909
1375
  }
910
1376
  getRetryStrategy(e) {
911
- return e ? "shouldRetry" in e ? e : new J(e.maxAttempts, e.backoffMs) : {
1377
+ if (!e) return {
912
1378
  shouldRetry: () => !1,
913
1379
  delayMs: () => 0
914
1380
  };
1381
+ if ("shouldRetry" in e) return e;
1382
+ let t = e;
1383
+ return t.on ? new Ie(t.maxAttempts ?? 3, t.backoffMs ?? 100, t.on) : new Fe(t.maxAttempts ?? 3, t.backoffMs ?? 100);
915
1384
  }
916
1385
  delay(e) {
917
1386
  return new Promise((t) => setTimeout(t, e));
918
1387
  }
919
- }, $ = class extends Error {
1388
+ }, J = class extends Error {
920
1389
  status;
921
1390
  code;
922
1391
  response;
@@ -924,11 +1393,565 @@ var Q = class n {
924
1393
  super(e), this.name = "HttpError", this.status = t, this.code = n, this.response = r;
925
1394
  }
926
1395
  };
927
- function ee(e) {
928
- return e instanceof $;
1396
+ function Ve(e) {
1397
+ return e instanceof J;
929
1398
  }
930
- function te(e) {
931
- return new Q(e);
1399
+ function He(e) {
1400
+ return new q(e);
1401
+ }
1402
+ //#endregion
1403
+ //#region src/realtime/websocket-client.ts
1404
+ function Y() {
1405
+ return typeof window > "u" && typeof process < "u" && process.versions?.node !== void 0;
1406
+ }
1407
+ var Ue = class {
1408
+ url;
1409
+ options;
1410
+ pluginManager;
1411
+ status = "closed";
1412
+ reconnectAttempt = 0;
1413
+ reconnectTimer = null;
1414
+ heartbeatTimer = null;
1415
+ stats = {
1416
+ messagesSent: 0,
1417
+ messagesReceived: 0,
1418
+ connectionTime: 0,
1419
+ reconnectAttempts: 0
1420
+ };
1421
+ connectionStartTime = 0;
1422
+ listeners = {
1423
+ open: /* @__PURE__ */ new Set(),
1424
+ close: /* @__PURE__ */ new Set(),
1425
+ error: /* @__PURE__ */ new Set(),
1426
+ message: /* @__PURE__ */ new Set()
1427
+ };
1428
+ constructor(e, t = {}) {
1429
+ this.url = e, this.options = t, this.pluginManager = new P();
1430
+ }
1431
+ updateStatus(e) {
1432
+ this.status = e, e === "open" ? this.connectionStartTime = Date.now() : e === "closed" && this.connectionStartTime > 0 && (this.stats.connectionTime += Date.now() - this.connectionStartTime, this.connectionStartTime = 0);
1433
+ }
1434
+ emitOpen(e) {
1435
+ this.pluginManager.emit("websocket:open", this.url, e);
1436
+ for (let t of this.listeners.open) t(e);
1437
+ }
1438
+ emitClose(e) {
1439
+ this.pluginManager.emit("websocket:close", this.url, e);
1440
+ for (let t of this.listeners.close) t(e);
1441
+ }
1442
+ emitError(e) {
1443
+ let t;
1444
+ e instanceof Error ? (t = new Event("error"), t.error = e) : t = e, this.pluginManager.emit("websocket:error", this.url, t);
1445
+ for (let e of this.listeners.error) e(t);
1446
+ }
1447
+ emitMessage(e) {
1448
+ this.pluginManager.emit("websocket:message", this.url, e);
1449
+ for (let t of this.listeners.message) t(e);
1450
+ }
1451
+ onOpen(e) {
1452
+ return this.listeners.open.add(e), () => this.listeners.open.delete(e);
1453
+ }
1454
+ onClose(e) {
1455
+ return this.listeners.close.add(e), () => this.listeners.close.delete(e);
1456
+ }
1457
+ onError(e) {
1458
+ return this.listeners.error.add(e), () => this.listeners.error.delete(e);
1459
+ }
1460
+ onMessage(e) {
1461
+ return this.listeners.message.add(e), () => this.listeners.message.delete(e);
1462
+ }
1463
+ getStatus() {
1464
+ return this.status;
1465
+ }
1466
+ getStats() {
1467
+ return {
1468
+ ...this.stats,
1469
+ connectionTime: this.stats.connectionTime + (this.connectionStartTime > 0 ? Date.now() - this.connectionStartTime : 0)
1470
+ };
1471
+ }
1472
+ scheduleReconnect() {
1473
+ if (this.options.reconnect?.enabled === !1) return;
1474
+ let e = this.options.reconnect?.maxAttempts ?? Infinity;
1475
+ if (this.reconnectAttempt >= e) {
1476
+ this.pluginManager.emit("websocket:reconnect:failed", this.url, this.reconnectAttempt);
1477
+ return;
1478
+ }
1479
+ let t = this.options.reconnect?.baseDelay ?? 1e3, n = this.options.reconnect?.maxDelay ?? 3e4, r = Math.min(n, t * 2 ** this.reconnectAttempt);
1480
+ this.reconnectAttempt++, this.stats.reconnectAttempts = this.reconnectAttempt, this.options.reconnect?.onReconnecting?.(this.reconnectAttempt, r), this.pluginManager.emit("websocket:reconnecting", this.url, this.reconnectAttempt, r), this.reconnectTimer = setTimeout(() => {
1481
+ this.connect().catch((e) => {
1482
+ this.emitError(e instanceof Error ? e : Error(String(e)));
1483
+ });
1484
+ }, r);
1485
+ }
1486
+ startHeartbeat() {
1487
+ if (!this.options.heartbeat) return;
1488
+ let e = this.options.heartbeat.interval ?? 3e4, t = this.options.heartbeat.pingMessage ?? "ping", n = this.options.heartbeat.pongMessage ?? "pong", r = !0, i = () => {
1489
+ if (!r) {
1490
+ this.pluginManager.emit("websocket:heartbeat:timeout", this.url), this.disconnect();
1491
+ return;
1492
+ }
1493
+ r = !1, this.send(t), this.heartbeatTimer = setTimeout(i, e);
1494
+ };
1495
+ this.onMessage((e) => {
1496
+ let t = e.raw;
1497
+ typeof t == "string" && t === n && (r = !0);
1498
+ }), this.heartbeatTimer = setTimeout(i, e);
1499
+ }
1500
+ stopHeartbeat() {
1501
+ this.heartbeatTimer &&= (clearTimeout(this.heartbeatTimer), null);
1502
+ }
1503
+ cleanup() {
1504
+ this.reconnectTimer &&= (clearTimeout(this.reconnectTimer), null), this.stopHeartbeat();
1505
+ }
1506
+ }, X = class extends Ue {
1507
+ socket = null;
1508
+ messageTypeListeners = /* @__PURE__ */ new Map();
1509
+ constructor(e, t = {}) {
1510
+ super(e, t);
1511
+ }
1512
+ async connect() {
1513
+ if (!(this.status === "connecting" || this.status === "open")) return this.updateStatus("connecting"), this.pluginManager.emit("websocket:connect:start", this.url), new Promise((e, t) => {
1514
+ let n = this.options.timeout ?? 1e4, r = setTimeout(() => {
1515
+ this.updateStatus("closed"), this.socket?.close(), this.socket = null;
1516
+ let e = /* @__PURE__ */ Error(`WebSocket connection timeout after ${n}ms`);
1517
+ this.emitError(e), t(e);
1518
+ }, n);
1519
+ try {
1520
+ this.socket = new WebSocket(this.url, this.options.protocols), this.socket.onopen = (t) => {
1521
+ clearTimeout(r), this.updateStatus("open"), this.reconnectAttempt = 0, this.emitOpen(t), this.options.onOpen?.(t), this.startHeartbeat(), this.pluginManager.emit("websocket:connect:success", this.url), e();
1522
+ }, this.socket.onclose = (e) => {
1523
+ clearTimeout(r), this.updateStatus("closed"), this.emitClose(e), this.options.onClose?.(e), this.stopHeartbeat(), this.pluginManager.emit("websocket:disconnected", this.url, e.code, e.reason), e.code !== 1e3 && !e.wasClean && this.scheduleReconnect();
1524
+ }, this.socket.onerror = (e) => {
1525
+ clearTimeout(r), this.updateStatus("closed"), this.emitError(e), this.options.onError?.(e), this.pluginManager.emit("websocket:connect:error", this.url, e), t(e);
1526
+ }, this.socket.onmessage = (e) => {
1527
+ this.stats.messagesReceived++;
1528
+ let t = {
1529
+ data: this.tryParseData(e.data),
1530
+ raw: e.data,
1531
+ type: "message",
1532
+ timestamp: Date.now()
1533
+ };
1534
+ this.emitMessage(t), this.pluginManager.emit("websocket:message:received", this.url, t);
1535
+ };
1536
+ } catch (e) {
1537
+ clearTimeout(r), this.updateStatus("closed"), this.pluginManager.emit("websocket:connect:error", this.url, e), t(e);
1538
+ }
1539
+ });
1540
+ }
1541
+ disconnect() {
1542
+ this.cleanup(), this.socket && (this.updateStatus("closing"), this.socket.close(1e3, "Client disconnected"), this.socket = null, this.updateStatus("closed"));
1543
+ }
1544
+ send(e) {
1545
+ if (!this.socket || this.socket.readyState !== WebSocket.OPEN) throw Error("WebSocket is not connected");
1546
+ this.socket.send(e), this.stats.messagesSent++, this.pluginManager.emit("websocket:message:sent", this.url, e);
1547
+ }
1548
+ sendJson(e) {
1549
+ this.send(JSON.stringify(e));
1550
+ }
1551
+ onMessageType(e, t) {
1552
+ return this.messageTypeListeners.has(e) || this.messageTypeListeners.set(e, /* @__PURE__ */ new Set()), this.messageTypeListeners.get(e).add(t), () => {
1553
+ let n = this.messageTypeListeners.get(e);
1554
+ n && (n.delete(t), n.size === 0 && this.messageTypeListeners.delete(e));
1555
+ };
1556
+ }
1557
+ tryParseData(e) {
1558
+ if (typeof e == "string") try {
1559
+ return JSON.parse(e);
1560
+ } catch {
1561
+ return e;
1562
+ }
1563
+ return e;
1564
+ }
1565
+ }, We = class extends X {
1566
+ async connect() {
1567
+ if (Y()) try {
1568
+ let { default: e } = await import("ws");
1569
+ return super.connect();
1570
+ } catch {
1571
+ throw Error("WebSocket client for Node.js requires the \"ws\" package. Please install it: npm install ws");
1572
+ }
1573
+ return super.connect();
1574
+ }
1575
+ };
1576
+ function Ge(e, t = {}) {
1577
+ return Y() ? new We(e, t) : new X(e, t);
1578
+ }
1579
+ //#endregion
1580
+ //#region src/realtime/sse-client.ts
1581
+ function Z() {
1582
+ return typeof window > "u" && typeof process < "u" && process.versions?.node !== void 0;
1583
+ }
1584
+ var Ke = class {
1585
+ url;
1586
+ options;
1587
+ _source = null;
1588
+ pluginManager;
1589
+ status = "closed";
1590
+ reconnectAttempt = 0;
1591
+ reconnectTimer = null;
1592
+ stats = {
1593
+ messagesSent: 0,
1594
+ messagesReceived: 0,
1595
+ connectionTime: 0,
1596
+ reconnectAttempts: 0
1597
+ };
1598
+ connectionStartTime = 0;
1599
+ listeners = {
1600
+ open: /* @__PURE__ */ new Set(),
1601
+ close: /* @__PURE__ */ new Set(),
1602
+ error: /* @__PURE__ */ new Set(),
1603
+ message: /* @__PURE__ */ new Set(),
1604
+ event: /* @__PURE__ */ new Map()
1605
+ };
1606
+ _lastEventId = null;
1607
+ constructor(e, t = {}) {
1608
+ this.url = e, this.options = t, this.pluginManager = new P();
1609
+ }
1610
+ updateStatus(e) {
1611
+ this.status = e, e === "open" ? this.connectionStartTime = Date.now() : e === "closed" && this.connectionStartTime > 0 && (this.stats.connectionTime += Date.now() - this.connectionStartTime, this.connectionStartTime = 0);
1612
+ }
1613
+ async connect() {
1614
+ if (!(this.status === "connecting" || this.status === "open")) return this.updateStatus("connecting"), this.pluginManager.emit("sse:connect:start", this.url), new Promise((e, t) => {
1615
+ let n = this.options.timeout ?? 1e4, r = setTimeout(() => {
1616
+ this.updateStatus("closed"), this._source?.close(), this._source = null;
1617
+ let e = /* @__PURE__ */ Error(`SSE connection timeout after ${n}ms`);
1618
+ this.emitError(e), t(e);
1619
+ }, n);
1620
+ try {
1621
+ this._source = new EventSource(this.url), this._source.onopen = (t) => {
1622
+ clearTimeout(r), this.updateStatus("open"), this.reconnectAttempt = 0, this.emitOpen(t), this.options.onOpen?.(t), this.pluginManager.emit("sse:connect:success", this.url), e();
1623
+ }, this._source.onerror = (e) => {
1624
+ clearTimeout(r), this.updateStatus("closed"), this.emitError(e), this.options.onError?.(e), this.pluginManager.emit("sse:connect:error", this.url, e), this._source?.readyState === EventSource.CLOSED && (this.emitClose(), this.options.onClose?.(), this.scheduleReconnect()), t(e);
1625
+ }, this._source.onmessage = (e) => {
1626
+ this.stats.messagesReceived++, this._lastEventId = e.lastEventId || this._lastEventId;
1627
+ let t = {
1628
+ data: this.tryParseData(e.data),
1629
+ raw: e.data,
1630
+ type: e.type || "message",
1631
+ timestamp: Date.now()
1632
+ };
1633
+ this.emitMessage(t), this.pluginManager.emit("sse:message:received", this.url, t);
1634
+ let n = e.type || "message", r = this.listeners.event.get(n);
1635
+ if (r) for (let e of r) e(t.data);
1636
+ }, this._source.addEventListener = this._source.addEventListener.bind(this._source);
1637
+ } catch (e) {
1638
+ clearTimeout(r), this.updateStatus("closed"), this.pluginManager.emit("sse:connect:error", this.url, e), t(e);
1639
+ }
1640
+ });
1641
+ }
1642
+ disconnect() {
1643
+ this.cleanup(), this._source && (this.updateStatus("closing"), this._source.close(), this._source = null, this.updateStatus("closed"), this.emitClose(), this.options.onClose?.());
1644
+ }
1645
+ send(e) {
1646
+ throw Error("SSE is a receive-only protocol. Use HTTP requests to send data to server.");
1647
+ }
1648
+ onMessage(e) {
1649
+ return this.listeners.message.add(e), () => this.listeners.message.delete(e);
1650
+ }
1651
+ onOpen(e) {
1652
+ return this.listeners.open.add(e), () => this.listeners.open.delete(e);
1653
+ }
1654
+ onClose(e) {
1655
+ return this.listeners.close.add(e), () => this.listeners.close.delete(e);
1656
+ }
1657
+ onError(e) {
1658
+ return this.listeners.error.add(e), () => this.listeners.error.delete(e);
1659
+ }
1660
+ onEvent(e, t) {
1661
+ return this.listeners.event.has(e) || this.listeners.event.set(e, /* @__PURE__ */ new Set()), this.listeners.event.get(e).add(t), this._source && !this._source[`on${e}`] && this._source.addEventListener(e, (n) => {
1662
+ t({
1663
+ data: this.tryParseData(n.data),
1664
+ raw: n.data,
1665
+ type: e,
1666
+ timestamp: Date.now()
1667
+ }.data);
1668
+ }), () => {
1669
+ let n = this.listeners.event.get(e);
1670
+ n && (n.delete(t), n.size === 0 && this.listeners.event.delete(e));
1671
+ };
1672
+ }
1673
+ getStatus() {
1674
+ return this.status;
1675
+ }
1676
+ getStats() {
1677
+ return {
1678
+ ...this.stats,
1679
+ connectionTime: this.stats.connectionTime + (this.connectionStartTime > 0 ? Date.now() - this.connectionStartTime : 0)
1680
+ };
1681
+ }
1682
+ get lastEventId() {
1683
+ return this._lastEventId;
1684
+ }
1685
+ get source() {
1686
+ return this._source;
1687
+ }
1688
+ emitOpen(e) {
1689
+ this.pluginManager.emit("sse:open", this.url, e);
1690
+ for (let t of this.listeners.open) t(e);
1691
+ }
1692
+ emitClose() {
1693
+ this.pluginManager.emit("sse:close", this.url);
1694
+ for (let e of this.listeners.close) e();
1695
+ }
1696
+ emitError(e) {
1697
+ let t;
1698
+ e instanceof Error ? (t = new Event("error"), t.error = e) : t = e, this.pluginManager.emit("sse:error", this.url, t);
1699
+ for (let e of this.listeners.error) e(t);
1700
+ }
1701
+ emitMessage(e) {
1702
+ this.pluginManager.emit("sse:message", this.url, e);
1703
+ for (let t of this.listeners.message) t(e);
1704
+ }
1705
+ scheduleReconnect() {
1706
+ if (this.options.reconnect?.enabled === !1) return;
1707
+ let e = this.options.reconnect?.maxAttempts ?? Infinity;
1708
+ if (this.reconnectAttempt >= e) {
1709
+ this.pluginManager.emit("sse:reconnect:failed", this.url, this.reconnectAttempt);
1710
+ return;
1711
+ }
1712
+ let t = this.options.reconnect?.baseDelay ?? 1e3, n = this.options.reconnect?.maxDelay ?? 3e4, r = Math.min(n, t * 2 ** this.reconnectAttempt);
1713
+ this.reconnectAttempt++, this.stats.reconnectAttempts = this.reconnectAttempt, this.options.reconnect?.onReconnecting?.(this.reconnectAttempt, r), this.pluginManager.emit("sse:reconnecting", this.url, this.reconnectAttempt, r), this.reconnectTimer = setTimeout(() => {
1714
+ this.connect().catch((e) => {
1715
+ this.emitError(e instanceof Error ? e : Error(String(e)));
1716
+ });
1717
+ }, r);
1718
+ }
1719
+ cleanup() {
1720
+ this.reconnectTimer &&= (clearTimeout(this.reconnectTimer), null);
1721
+ }
1722
+ tryParseData(e) {
1723
+ try {
1724
+ return JSON.parse(e);
1725
+ } catch {
1726
+ return e;
1727
+ }
1728
+ }
1729
+ }, qe = class extends Ke {
1730
+ async connect() {
1731
+ if (Z()) throw Error("SSE client for Node.js requires a polyfill or custom implementation. Consider using a library like \"eventsource\" or implement using fetch with streaming.");
1732
+ return super.connect();
1733
+ }
1734
+ };
1735
+ function Je(e, t = {}) {
1736
+ return Z() ? new qe(e, t) : new Ke(e, t);
1737
+ }
1738
+ //#endregion
1739
+ //#region src/realtime/plugin.ts
1740
+ var Ye = class {
1741
+ name = "realtime";
1742
+ setup(e) {
1743
+ e.on("websocket:connect:start", (...t) => {
1744
+ let n = t[0];
1745
+ e.emit("realtime:connect:start", "websocket", n);
1746
+ }), e.on("websocket:connect:success", (...t) => {
1747
+ let n = t[0];
1748
+ e.emit("realtime:connect:success", "websocket", n);
1749
+ }), e.on("websocket:message:received", (...t) => {
1750
+ let n = t[0], r = t[1];
1751
+ e.emit("realtime:message", "websocket", n, r);
1752
+ }), e.on("sse:connect:start", (...t) => {
1753
+ let n = t[0];
1754
+ e.emit("realtime:connect:start", "sse", n);
1755
+ }), e.on("sse:connect:success", (...t) => {
1756
+ let n = t[0];
1757
+ e.emit("realtime:connect:success", "sse", n);
1758
+ }), e.on("sse:message:received", (...t) => {
1759
+ let n = t[0], r = t[1];
1760
+ e.emit("realtime:message", "sse", n, r);
1761
+ });
1762
+ }
1763
+ };
1764
+ function Xe() {
1765
+ return new Ye();
1766
+ }
1767
+ //#endregion
1768
+ //#region src/testing/mock-client.ts
1769
+ var Q = class {
1770
+ adapter;
1771
+ method;
1772
+ urlPattern;
1773
+ constructor(e, t, n) {
1774
+ this.adapter = e, this.method = t, this.urlPattern = n;
1775
+ }
1776
+ reply(e, t, n) {
1777
+ let r;
1778
+ return r = typeof e == "number" ? {
1779
+ status: e,
1780
+ data: t,
1781
+ headers: n
1782
+ } : e, this.adapter.addRoute(this.method, this.urlPattern, r), this.adapter;
1783
+ }
1784
+ replyOnce(e, t, n) {
1785
+ let r;
1786
+ return r = typeof e == "number" ? {
1787
+ status: e,
1788
+ data: t,
1789
+ headers: n
1790
+ } : e, this.adapter.addRoute(this.method, this.urlPattern, r, { times: 1 }), this.adapter;
1791
+ }
1792
+ networkError(e = "Network Error") {
1793
+ return this.adapter.addRoute(this.method, this.urlPattern, {
1794
+ networkError: !0,
1795
+ errorMessage: e
1796
+ }), this.adapter;
1797
+ }
1798
+ timeout() {
1799
+ return this.adapter.addRoute(this.method, this.urlPattern, {
1800
+ status: 408,
1801
+ statusText: "Request Timeout"
1802
+ }), this.adapter;
1803
+ }
1804
+ }, $ = class {
1805
+ routes = [];
1806
+ originalAdapter;
1807
+ mockClient;
1808
+ options;
1809
+ defaultResponse = {
1810
+ status: 200,
1811
+ statusText: "OK",
1812
+ headers: { "content-type": "application/json" }
1813
+ };
1814
+ constructor(e, t = {}) {
1815
+ this.options = t;
1816
+ let n = this.createAdapter();
1817
+ if (typeof e.extend == "function") this.mockClient = e.extend({ adapter: n });
1818
+ else throw Error("MockAdapter requires an HttpClient instance with extend() method");
1819
+ }
1820
+ get client() {
1821
+ return this.mockClient;
1822
+ }
1823
+ createAdapter() {
1824
+ return async (e, t) => {
1825
+ let n = typeof e == "string" ? e : e.url, r = t?.method || "GET", i = {
1826
+ url: n,
1827
+ method: r,
1828
+ headers: t?.headers,
1829
+ body: t?.body,
1830
+ signal: t?.signal ?? void 0
1831
+ }, a = this.findMatchingRoute(r, n);
1832
+ if (!a) return this.options.passthrough ? (this.originalAdapter || fetch)(e, t) : new Response(JSON.stringify({ error: "No mock route matched" }), {
1833
+ status: 404,
1834
+ statusText: "Not Found",
1835
+ headers: { "content-type": "application/json" }
1836
+ });
1837
+ a.timesCalled++;
1838
+ let o;
1839
+ if (o = typeof a.response == "function" ? await a.response(i) : a.response, o.networkError) throw TypeError(o.errorMessage || "Network Error");
1840
+ let s = Object.fromEntries(Object.entries(o).filter(([e, t]) => t !== void 0)), c = {
1841
+ ...this.defaultResponse,
1842
+ ...s
1843
+ };
1844
+ if (o.headers && "content-type" in o.headers || (c.data instanceof Uint8Array || ArrayBuffer.isView(c.data) ? c.headers = {
1845
+ ...c.headers,
1846
+ "content-type": "application/octet-stream"
1847
+ } : c.data && typeof c.data == "object" && (c.headers = {
1848
+ ...c.headers,
1849
+ "content-type": "application/json"
1850
+ })), c.delay || this.options.delay) {
1851
+ let e = c.delay ?? this.options.delay;
1852
+ if (e && e > 0) {
1853
+ let n = t?.signal;
1854
+ n ? (n.throwIfAborted(), await new Promise((t, r) => {
1855
+ let i = setTimeout(t, e), a = () => {
1856
+ clearTimeout(i), r(new DOMException("Aborted", "AbortError"));
1857
+ };
1858
+ n.addEventListener("abort", a, { once: !0 }), setTimeout(() => {
1859
+ n.removeEventListener("abort", a);
1860
+ }, e);
1861
+ })) : await new Promise((t) => setTimeout(t, e));
1862
+ }
1863
+ }
1864
+ let l = new Headers(c.headers), u = c.data;
1865
+ (c.status === 204 || c.status === 205) && l.delete("content-type");
1866
+ let d;
1867
+ if (u == null) d = "";
1868
+ else if (typeof u == "string") d = u;
1869
+ else if (u instanceof Uint8Array || ArrayBuffer.isView(u)) {
1870
+ let e;
1871
+ if (u.buffer instanceof ArrayBuffer) e = u.buffer.slice(u.byteOffset, u.byteOffset + u.byteLength);
1872
+ else {
1873
+ let t = new Uint8Array(u.byteLength);
1874
+ t.set(new Uint8Array(u.buffer, u.byteOffset, u.byteLength)), e = t.buffer;
1875
+ }
1876
+ return new Response(e, {
1877
+ status: c.status,
1878
+ statusText: c.statusText,
1879
+ headers: l
1880
+ });
1881
+ } else d = JSON.stringify(u);
1882
+ let f = d;
1883
+ return (c.status === 204 || c.status === 205 || f === "") && (f = null), f === null && l.delete("content-type"), new Response(f, {
1884
+ status: c.status,
1885
+ statusText: c.statusText,
1886
+ headers: l
1887
+ });
1888
+ };
1889
+ }
1890
+ onGet(e) {
1891
+ return new Q(this, "GET", e);
1892
+ }
1893
+ onPost(e) {
1894
+ return new Q(this, "POST", e);
1895
+ }
1896
+ onPut(e) {
1897
+ return new Q(this, "PUT", e);
1898
+ }
1899
+ onPatch(e) {
1900
+ return new Q(this, "PATCH", e);
1901
+ }
1902
+ onDelete(e) {
1903
+ return new Q(this, "DELETE", e);
1904
+ }
1905
+ onAny(e) {
1906
+ return new Q(this, "ANY", e);
1907
+ }
1908
+ addRoute(e, t, n, r) {
1909
+ return this.routes.push({
1910
+ method: e.toUpperCase(),
1911
+ urlPattern: t,
1912
+ response: n,
1913
+ timesCalled: 0,
1914
+ times: r?.times
1915
+ }), this;
1916
+ }
1917
+ reset() {
1918
+ this.routes = [];
1919
+ }
1920
+ restore() {}
1921
+ static reply(e, t, n) {
1922
+ return {
1923
+ status: e,
1924
+ data: t,
1925
+ headers: n
1926
+ };
1927
+ }
1928
+ static networkError(e = "Network Error") {
1929
+ return {
1930
+ networkError: !0,
1931
+ errorMessage: e
1932
+ };
1933
+ }
1934
+ findMatchingRoute(e, t) {
1935
+ let n = t;
1936
+ if (this.options.baseURL && t.startsWith(this.options.baseURL)) n = t.slice(this.options.baseURL.length);
1937
+ else try {
1938
+ if (n.includes("://")) {
1939
+ let e = new URL(n);
1940
+ n = e.pathname + e.search;
1941
+ }
1942
+ } catch {}
1943
+ for (let t of this.routes) {
1944
+ if (t.times && t.timesCalled >= t.times || t.method !== "ANY" && t.method !== e.toUpperCase()) continue;
1945
+ let r = !1;
1946
+ if (typeof t.urlPattern == "string" ? r = n === t.urlPattern || n.startsWith(t.urlPattern) : t.urlPattern instanceof RegExp && (r = t.urlPattern.test(n)), r) return t;
1947
+ }
1948
+ return null;
1949
+ }
1950
+ };
1951
+ function Ze(e, t = {}) {
1952
+ return new $(e, t);
932
1953
  }
933
1954
  //#endregion
934
- export { d as AggressiveRetry, G as CachePlugin, x as CacheStore, p as CircuitBreakerRetry, f as ConservativeRetry, K as DedupePlugin, I as Defer, t as Err, Q as HttpClient, $ as HttpError, U as LoggerPlugin, W as MetricsPlugin, O as MiddlewarePipeline, e as Ok, H as PluginManager, w as RequestDeduplicator, M as TypedObservable, C as cacheMiddleware, F as createApiUrl, S as createCacheMiddleware, T as createDedupeMiddleware, te as createHttpClient, D as createPipeline, l as createProjectionTransformer, r as createRequiredFieldsValidator, n as createSchemaValidator, B as createStreamingMiddleware, N as createTypeGuard, j as createTypedApiClient, A as createTypedRequest, k as createTypedResponse, P as createUrl, u as createWrapperTransformer, E as dedupeMiddleware, L as handleStream, ee as isHttpError, b as retry, z as streamToFile, V as streamingMiddleware, s as transformCamelToSnake, c as transformFlatten, o as transformSnakeToCamel, i as validatorIsArray, a as validatorIsObject, y as withTimeout };
1955
+ export { m as AggressiveRetry, _e as CachePlugin, S as CacheStore, be as CircuitBreakerPlugin, g as CircuitBreakerRetry, h as ConservativeRetry, ve as DedupePlugin, fe as Defer, i as Err, q as HttpClient, J as HttpError, he as LoggerPlugin, ge as MetricsPlugin, oe as MiddlewarePipeline, $ as MockAdapter, r as Ok, P as PluginManager, ye as RateLimitPlugin, w as RequestDeduplicator, le as TypedObservable, ne as cacheMiddleware, ae as circuitBreakerMiddleware, de as createApiUrl, C as createCacheMiddleware, D as createCircuitBreakerMiddleware, T as createDedupeMiddleware, He as createHttpClient, Ze as createMockClient, O as createPipeline, f as createProjectionTransformer, E as createRateLimitMiddleware, Xe as createRealtimePlugin, o as createRequiredFieldsValidator, Je as createSSEClient, a as createSchemaValidator, N as createStreamingMiddleware, ue as createTypeGuard, ce as createTypedApiClient, k as createTypedRequest, se as createTypedResponse, A as createUrl, Ge as createWebSocketClient, p as createWrapperTransformer, re as dedupeMiddleware, j as handleStream, Ve as isHttpError, ie as rateLimitMiddleware, x as retry, pe as streamToFile, me as streamingMiddleware, u as transformCamelToSnake, d as transformFlatten, l as transformSnakeToCamel, s as validatorIsArray, c as validatorIsObject, te as withTimeout };
1956
+
1957
+ //# sourceMappingURL=nexa.es.js.map