@bereasoftware/nexa 1.2.0 → 1.3.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,68 +1,61 @@
1
- /*! Nexa v1.2.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) => ({
1
+ /*! Nexa v1.3.0 | (c) 2026 Berea-Soft | MIT License | https://github.com/Berea-Soft/Nexa */
2
+ //#region src/types/index.ts
3
+ var e = (e) => ({
11
4
  ok: !0,
12
5
  value: e
13
- }), i = (e) => ({
6
+ }), t = (e) => ({
14
7
  ok: !1,
15
8
  error: e
16
9
  });
17
10
  //#endregion
18
11
  //#region src/utils/index.ts
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`,
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`,
24
17
  code: "VALIDATION_ERROR"
25
18
  });
26
- return r(t);
19
+ return e(r);
27
20
  } };
28
21
  }
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({
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({
33
26
  message: `Validation failed: missing fields: ${a.join(", ")}`,
34
27
  code: "VALIDATION_ERROR"
35
- }) : r(t);
28
+ }) : e(r);
36
29
  } };
37
30
  }
38
- var s = { validate(e) {
39
- return Array.isArray(e) ? r(e) : i({
31
+ var i = { validate(n) {
32
+ return Array.isArray(n) ? e(n) : t({
40
33
  message: "Expected array response",
41
34
  code: "VALIDATION_ERROR"
42
35
  });
43
- } }, c = { validate(e) {
44
- return e && typeof e == "object" && !Array.isArray(e) ? r(e) : i({
36
+ } }, a = { validate(n) {
37
+ return n && typeof n == "object" && !Array.isArray(n) ? e(n) : t({
45
38
  message: "Expected object response",
46
39
  code: "VALIDATION_ERROR"
47
40
  });
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);
41
+ } }, o = { transform(e) {
42
+ return m(e, ee);
43
+ } }, s = { transform(e) {
44
+ return m(e, te);
45
+ } }, c = { transform(e) {
46
+ return h(e);
54
47
  } };
55
- function f(e) {
48
+ function l(e) {
56
49
  return { transform(t) {
57
- return Array.isArray(t) ? t.map((t) => b(t, e)) : b(t, e);
50
+ return Array.isArray(t) ? t.map((t) => g(t, e)) : g(t, e);
58
51
  } };
59
52
  }
60
- function p(e) {
53
+ function u(e) {
61
54
  return { transform(t) {
62
55
  return { [e]: t };
63
56
  } };
64
57
  }
65
- var m = class {
58
+ var d = class {
66
59
  maxAttempts;
67
60
  constructor(e = 5) {
68
61
  this.maxAttempts = e;
@@ -73,7 +66,7 @@ var m = class {
73
66
  delayMs(e) {
74
67
  return e * 50;
75
68
  }
76
- }, h = class {
69
+ }, f = class {
77
70
  retryableStatuses = [
78
71
  408,
79
72
  429,
@@ -92,7 +85,7 @@ var m = class {
92
85
  delayMs(e) {
93
86
  return Math.min(1e3 * 2 ** (e - 1), 1e4);
94
87
  }
95
- }, g = class {
88
+ }, p = class {
96
89
  failureCount = 0;
97
90
  lastFailureTime = 0;
98
91
  maxAttempts;
@@ -111,50 +104,50 @@ var m = class {
111
104
  this.failureCount = 0, this.lastFailureTime = 0;
112
105
  }
113
106
  };
114
- function _(e) {
107
+ function ee(e) {
115
108
  return e.replace(/_([a-z])/g, (e, t) => t.toUpperCase());
116
109
  }
117
- function ee(e) {
110
+ function te(e) {
118
111
  return e.replace(/[A-Z]/g, (e) => `_${e.toLowerCase()}`);
119
112
  }
120
- function v(e, t) {
113
+ function m(e, t) {
121
114
  if (!e || typeof e != "object") return e;
122
- if (Array.isArray(e)) return e.map((e) => v(e, t));
115
+ if (Array.isArray(e)) return e.map((e) => m(e, t));
123
116
  let n = {};
124
- for (let [r, i] of Object.entries(e)) n[t(r)] = v(i, t);
117
+ for (let [r, i] of Object.entries(e)) n[t(r)] = m(i, t);
125
118
  return n;
126
119
  }
127
- function y(e, t = "") {
120
+ function h(e, t = "") {
128
121
  let n = {};
129
122
  if (Array.isArray(e)) e.forEach((e, r) => {
130
123
  let i = t ? `${t}[${r}]` : `[${r}]`;
131
- Object.assign(n, y(e, i));
124
+ Object.assign(n, h(e, i));
132
125
  });
133
126
  else if (e && typeof e == "object") for (let [r, i] of Object.entries(e)) {
134
127
  let e = t ? `${t}.${r}` : r;
135
- i && typeof i == "object" && !Array.isArray(i) ? Object.assign(n, y(i, e)) : n[e] = i;
128
+ i && typeof i == "object" && !Array.isArray(i) ? Object.assign(n, h(i, e)) : n[e] = i;
136
129
  }
137
130
  return n;
138
131
  }
139
- function b(e, t) {
132
+ function g(e, t) {
140
133
  if (!e || typeof e != "object") return {};
141
134
  let n = e, r = {};
142
135
  for (let e of t) e in n && (r[e] = n[e]);
143
136
  return r;
144
137
  }
145
- function te(e) {
138
+ function ne(e) {
146
139
  let t = new AbortController(), n = setTimeout(() => t.abort(), e);
147
140
  return t.signal.addEventListener("abort", () => clearTimeout(n), { once: !0 }), t;
148
141
  }
149
- async function x(e, t = 3) {
142
+ async function _(e, t = 3) {
150
143
  try {
151
144
  return await e();
152
145
  } catch (n) {
153
146
  if (t <= 0) throw n;
154
- return x(e, t - 1);
147
+ return _(e, t - 1);
155
148
  }
156
149
  }
157
- var S = class {
150
+ var v = class {
158
151
  cache = /* @__PURE__ */ new Map();
159
152
  get(e) {
160
153
  let t = this.cache.get(e);
@@ -178,8 +171,8 @@ var S = class {
178
171
  this.cache.delete(e);
179
172
  }
180
173
  };
181
- function C(e = {}) {
182
- let t = e.cache || new S(), n = e.ttlMs || 6e4, r = e.cacheableStatuses || [200, 304];
174
+ function y(e = {}) {
175
+ let t = e.cache || new v(), n = e.ttlMs || 6e4, r = e.cacheableStatuses || [200, 304];
183
176
  return async (e, i) => {
184
177
  let a = (e.request.method || "GET").toUpperCase(), o = a === "GET", s = `${a}:${e.request.url}`;
185
178
  if (o && t.has(s)) {
@@ -192,7 +185,7 @@ function C(e = {}) {
192
185
  await i(), o && e.response && r.includes(e.response.status) && (t.set(s, e.response, n), e.state.cacheMiss = !0);
193
186
  };
194
187
  }
195
- var ne = C(), w = class {
188
+ var b = y(), x = class {
196
189
  pending = /* @__PURE__ */ new Map();
197
190
  async execute(e, t) {
198
191
  if (this.pending.has(e)) return this.pending.get(e);
@@ -205,8 +198,8 @@ var ne = C(), w = class {
205
198
  this.pending.clear();
206
199
  }
207
200
  };
208
- function T(e = {}) {
209
- let t = e.deduplicator || new w(), n = e.includeBody ?? !1, r = e.methods || ["GET"];
201
+ function S(e = {}) {
202
+ let t = e.deduplicator || new x(), n = e.includeBody ?? !1, r = e.methods || ["GET"];
210
203
  return async (e, i) => {
211
204
  let a = (e.request.method || "GET").toUpperCase();
212
205
  if (!r.includes(a)) {
@@ -222,68 +215,8 @@ function T(e = {}) {
222
215
  }
223
216
  };
224
217
  }
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) {
218
+ var re = S();
219
+ function C(e) {
287
220
  return async (t) => {
288
221
  let n = -1;
289
222
  async function r(i) {
@@ -295,7 +228,7 @@ function O(e) {
295
228
  await r(0);
296
229
  };
297
230
  }
298
- var oe = class {
231
+ var ie = class {
299
232
  middlewares = [];
300
233
  use(e) {
301
234
  return this.middlewares.push(e), this;
@@ -303,7 +236,7 @@ var oe = class {
303
236
  async execute(e) {
304
237
  if (e && typeof e == "object" && "request" in e && "response" in e) {
305
238
  let t = e;
306
- return await O(this.middlewares.map((e) => typeof e == "function" && e.length === 2 ? e : async (t, n) => {
239
+ return await C(this.middlewares.map((e) => typeof e == "function" && e.length === 2 ? e : async (t, n) => {
307
240
  let r = e;
308
241
  t.response.body = await r(t.response.body), await n();
309
242
  }))(t), t.response.body;
@@ -316,7 +249,7 @@ var oe = class {
316
249
  this.middlewares = [];
317
250
  }
318
251
  };
319
- function se(e, t, n, r = {}) {
252
+ function w(e, t, n, r = {}) {
320
253
  return {
321
254
  ok: e >= 200 && e < 300,
322
255
  data: t,
@@ -325,7 +258,7 @@ function se(e, t, n, r = {}) {
325
258
  headers: r
326
259
  };
327
260
  }
328
- function k(e) {
261
+ function T(e) {
329
262
  return async (t, n) => {
330
263
  let r = e.path, i;
331
264
  switch (e.method) {
@@ -349,13 +282,13 @@ function k(e) {
349
282
  return i;
350
283
  };
351
284
  }
352
- function ce(e) {
285
+ function E(e) {
353
286
  return { request: async (t, n, r) => {
354
287
  let i = e[n];
355
- return await k(i)(t, r);
288
+ return await T(i)(t, r);
356
289
  } };
357
290
  }
358
- var le = class e {
291
+ var D = class e {
359
292
  subscribers = [];
360
293
  errorSubscribers = [];
361
294
  completeSubscribers = [];
@@ -384,19 +317,19 @@ var le = class e {
384
317
  }, (e) => n.error(e), () => n.complete()), n;
385
318
  }
386
319
  };
387
- function ue(e) {
320
+ function ae(e) {
388
321
  return (t) => {
389
322
  if (!e(t)) throw TypeError("Value does not match expected type");
390
323
  return t;
391
324
  };
392
325
  }
393
- function A(e) {
326
+ function O(e) {
394
327
  return e;
395
328
  }
396
- function de(e) {
397
- return A(e);
329
+ function oe(e) {
330
+ return O(e);
398
331
  }
399
- var fe = class {
332
+ var se = class {
400
333
  _promise;
401
334
  resolveFunc;
402
335
  rejectFunc;
@@ -418,7 +351,7 @@ var fe = class {
418
351
  return this._promise;
419
352
  }
420
353
  };
421
- async function j(e, t = {}) {
354
+ async function k(e, t = {}) {
422
355
  let n = e.body?.getReader();
423
356
  if (!n) throw Error("Response body is not readable");
424
357
  let r = [], i = 0, a = parseInt(e.headers.get("content-length") || "0", 10);
@@ -427,22 +360,22 @@ async function j(e, t = {}) {
427
360
  if (e) break;
428
361
  r.push(o), i += o.length, t.onChunk && await t.onChunk(o), t.onProgress && a > 0 && t.onProgress(i, a);
429
362
  }
430
- return M(r, i);
363
+ return A(r, i);
431
364
  }
432
- function M(e, t) {
365
+ function A(e, t) {
433
366
  let n = new Uint8Array(t), r = 0;
434
367
  for (let t of e) n.set(t, r), r += t.byteLength;
435
368
  return n;
436
369
  }
437
- async function pe(e, t) {
438
- let n = await j(e);
370
+ async function ce(e, t) {
371
+ let n = await k(e);
439
372
  if (typeof window > "u") await (await import("fs").then((e) => e.promises)).writeFile(t, n);
440
373
  else {
441
374
  let e = new Blob([n.buffer], { type: "application/octet-stream" }), r = URL.createObjectURL(e), i = document.createElement("a");
442
375
  i.href = r, i.download = t, i.click(), URL.revokeObjectURL(r);
443
376
  }
444
377
  }
445
- function N(e = {}) {
378
+ function j(e = {}) {
446
379
  return async (t, n) => {
447
380
  if (await n(), t.response && t.response.body && typeof t.response.body == "object" && "getReader" in t.response.body) {
448
381
  let n = t.response.body.getReader(), r = [], i = 0, a = parseInt(t.response.headers?.["content-length"] || "0", 10);
@@ -452,7 +385,7 @@ function N(e = {}) {
452
385
  if (o) break;
453
386
  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);
454
387
  }
455
- let o = M(r, i);
388
+ let o = A(r, i);
456
389
  t.response.body = o, t.state.streaming = !0, t.state.streamedBytes = i;
457
390
  } finally {
458
391
  n.releaseLock();
@@ -460,15 +393,15 @@ function N(e = {}) {
460
393
  }
461
394
  };
462
395
  }
463
- var me = N({ onProgress: (e, t) => {
396
+ var le = j({ onProgress: (e, t) => {
464
397
  if (t > 0) {
465
398
  let n = Math.round(e / t * 100);
466
- console.log(`⬇️ Streaming: ${n}% (${e}/${t} bytes)`);
399
+ console.warn(`Streaming: ${n}% (${e}/${t} bytes)`);
467
400
  }
468
- } }), P = class {
401
+ } }), M = class {
469
402
  plugins = [];
470
- cache = new S();
471
- deduplicator = new w();
403
+ cache = new v();
404
+ deduplicator = new x();
472
405
  middlewares = [];
473
406
  listeners = /* @__PURE__ */ new Map();
474
407
  register(e) {
@@ -484,13 +417,15 @@ var me = N({ onProgress: (e, t) => {
484
417
  return this.deduplicator;
485
418
  }
486
419
  getPipeline() {
487
- return O(this.middlewares);
420
+ return C(this.middlewares);
488
421
  }
489
422
  async executePipeline(e) {
490
423
  await this.getPipeline()(e);
491
424
  }
492
425
  on(e, t) {
493
- return this.listeners.has(e) || this.listeners.set(e, /* @__PURE__ */ new Set()), this.listeners.get(e)?.add(t), this;
426
+ this.listeners.has(e) || this.listeners.set(e, /* @__PURE__ */ new Set());
427
+ let n = this.listeners.get(e), r = t;
428
+ return n && n.add(r), this;
494
429
  }
495
430
  emit(e, ...t) {
496
431
  let n = this.listeners.get(e);
@@ -505,21 +440,21 @@ var me = N({ onProgress: (e, t) => {
505
440
  clear() {
506
441
  this.plugins = [], this.middlewares = [], this.listeners.clear(), this.cache.clear(), this.deduplicator.clear();
507
442
  }
508
- }, he = {
443
+ }, ue = {
509
444
  name: "logger",
510
445
  setup(e) {
511
446
  e.on("request:start", (...e) => {
512
447
  let t = e[0];
513
- console.log(`📤 Request started: ${t}`);
448
+ console.warn(`Request started: ${t}`);
514
449
  }), e.on("request:success", (...e) => {
515
450
  let t = e[0], n = e[1];
516
- console.log(`✅ Request succeeded: ${t} (${n})`);
451
+ console.warn(`Request succeeded: ${t} (${n})`);
517
452
  }), e.on("request:error", (...e) => {
518
453
  let t = e[0], n = e[1];
519
454
  console.error(`❌ Request failed: ${t}`, n);
520
455
  });
521
456
  }
522
- }, ge = class {
457
+ }, N = class {
523
458
  name = "metrics";
524
459
  metrics = {
525
460
  requests: 0,
@@ -536,294 +471,22 @@ var me = N({ onProgress: (e, t) => {
536
471
  getMetrics() {
537
472
  return { ...this.metrics };
538
473
  }
539
- }, _e = class {
474
+ }, P = class {
540
475
  name = "cache";
541
476
  ttlMs;
542
477
  constructor(e = 6e4) {
543
478
  this.ttlMs = e;
544
479
  }
545
480
  setup(e) {
546
- e.addMiddleware(C({ ttlMs: this.ttlMs }));
481
+ e.addMiddleware(y({ ttlMs: this.ttlMs }));
547
482
  }
548
- }, ve = class {
483
+ }, F = class {
549
484
  name = "dedupe";
550
485
  setup(e) {
551
- e.addMiddleware(T());
552
- }
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
- }));
486
+ e.addMiddleware(S());
566
487
  }
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
+ }, I = class {
489
+ store = new v();
827
490
  get(e) {
828
491
  return this.store.get(e);
829
492
  }
@@ -836,7 +499,7 @@ var Pe = class {
836
499
  clear() {
837
500
  this.store.clear();
838
501
  }
839
- }, Fe = class {
502
+ }, L = class {
840
503
  maxAttempts;
841
504
  baseDelayMs;
842
505
  constructor(e = 3, t = 100) {
@@ -850,24 +513,7 @@ var Pe = class {
850
513
  let t = this.baseDelayMs * 2 ** (e - 1), n = Math.random() * t * .1;
851
514
  return Math.min(t + n, 3e4);
852
515
  }
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 {
516
+ }, R = class {
871
517
  running = 0;
872
518
  queue = [];
873
519
  maxConcurrent;
@@ -897,176 +543,269 @@ var Pe = class {
897
543
  return this.running;
898
544
  }
899
545
  };
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
+ function z(e) {
547
+ return e == null ? {
919
548
  serialized: void 0,
920
549
  contentType: null
921
- } : typeof FormData < "u" && n instanceof FormData ? {
922
- serialized: n,
550
+ } : typeof e == "string" ? {
551
+ serialized: e,
552
+ contentType: "text/plain"
553
+ } : typeof FormData < "u" && e instanceof FormData ? {
554
+ serialized: e,
923
555
  contentType: null
924
- } : typeof URLSearchParams < "u" && n instanceof URLSearchParams ? {
925
- serialized: n,
556
+ } : typeof URLSearchParams < "u" && e instanceof URLSearchParams ? {
557
+ serialized: e,
926
558
  contentType: "application/x-www-form-urlencoded"
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
+ } : typeof Blob < "u" && e instanceof Blob ? {
560
+ serialized: e,
561
+ contentType: e.type || "application/octet-stream"
562
+ } : e instanceof ArrayBuffer || ArrayBuffer.isView(e) || typeof ReadableStream < "u" && e instanceof ReadableStream ? {
563
+ serialized: e,
932
564
  contentType: "application/octet-stream"
933
- } : typeof n == "string" ? {
934
- serialized: n,
935
- contentType: "text/plain"
936
565
  } : {
937
- serialized: JSON.stringify(n),
566
+ serialized: JSON.stringify(e),
938
567
  contentType: "application/json"
939
568
  };
940
569
  }
941
- function G(e, t) {
570
+ function B(e, t) {
942
571
  return t ? e.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g, (e, n) => {
943
572
  let r = t[n];
944
573
  if (r === void 0) throw Error(`Missing path parameter: :${n}`);
945
574
  return encodeURIComponent(String(r));
946
575
  }) : e;
947
576
  }
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 {
577
+ var V = class n {
960
578
  requestInterceptors = [];
961
579
  responseInterceptors = [];
962
580
  cache;
581
+ devTracker;
963
582
  config;
964
583
  requestQueue;
965
- pendingRequests = /* @__PURE__ */ new Map();
584
+ pendingRequests = /* @__PURE__ */ new Set();
966
585
  constructor(e = {}) {
967
586
  this.config = {
968
587
  baseURL: e.baseURL ?? "",
969
588
  defaultHeaders: e.defaultHeaders ?? { "Content-Type": "application/json" },
970
589
  defaultTimeout: e.defaultTimeout ?? 3e4,
971
590
  validateStatus: e.validateStatus ?? ((e) => e >= 200 && e < 300),
972
- cacheStrategy: e.cacheStrategy ?? new Pe(),
591
+ cacheStrategy: e.cacheStrategy ?? new I(),
973
592
  maxConcurrent: e.maxConcurrent ?? 0,
974
593
  defaultResponseType: e.defaultResponseType ?? "auto",
975
594
  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 = {
595
+ adapter: e.adapter
596
+ }, this.cache = this.config.cacheStrategy, this.requestQueue = this.config.maxConcurrent > 0 ? new R(this.config.maxConcurrent) : null, this.devTracker = e.devTracker ?? null;
597
+ }
598
+ async request(n) {
599
+ if (!this.requestInterceptors.length && !this.responseInterceptors.length && !n.cache?.enabled && !n.hooks && !Object.keys(this.config.defaultHooks).length && !n.retry && !n.validate && !n.transform && !this.requestQueue && !n.onDownloadProgress && !n.signal) return this.fastPath(n);
600
+ let r = n.hooks ? {
994
601
  ...this.config.defaultHooks,
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();
602
+ ...n.hooks
603
+ } : this.config.defaultHooks, i = this.getMaxAttempts(n.retry), a = this.getRetryStrategy(n.retry), o = this.buildRequest(n);
604
+ r.onStart?.(o), this.requestQueue && await this.requestQueue.acquire();
998
605
  try {
999
- for (let l = 1; l <= o; l++) {
1000
- let u;
606
+ for (let s = 1; s <= i; s++) {
607
+ let c;
1001
608
  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);
609
+ if ((n.method === "GET" || !n.method) && n.cache?.enabled) {
610
+ let t = this.getCacheKey(n), i = this.cache.get(t);
611
+ if (i) {
612
+ let t = i;
613
+ return this.trackDev({
614
+ method: n.method ?? "GET",
615
+ url: o.url,
616
+ status: t.status,
617
+ duration: t.duration,
618
+ cached: !0,
619
+ ok: !0,
620
+ headers: { ...o.headers },
621
+ body: n.body,
622
+ retryCount: 0
623
+ }), r.onSuccess?.(t), r.onFinally?.(), e(t);
1007
624
  }
1008
625
  }
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,
626
+ let t = o;
627
+ for (let e of this.requestInterceptors) t = await e.onRequest(t);
628
+ c = new AbortController(), this.pendingRequests.add(c), n.signal && n.signal.addEventListener("abort", () => c.abort(), { once: !0 });
629
+ let i = performance.now(), a = await this.fetchWithTimeout(t, this.resolveTimeoutMs(n.timeout ?? this.config.defaultTimeout), c), l = performance.now() - i, u = a;
630
+ n.onDownloadProgress && a.body && (u = this.trackDownloadProgress(a, n.onDownloadProgress));
631
+ let d = n.responseType ?? this.config.defaultResponseType, f = await this.parseResponse(u, t, l, d);
632
+ if (!this.config.validateStatus(f.status)) throw {
633
+ message: `Request failed with status ${f.status}`,
1020
634
  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
635
+ statusText: f.statusText,
636
+ code: "HTTP_ERROR"
1034
637
  };
1035
- if (e.validate) {
1036
- let t = e.validate.validate(g.data);
1037
- if (!t.ok) return t;
638
+ if (n.validate) {
639
+ let e = n.validate.validate(f.data);
640
+ if (!e.ok) return e;
1038
641
  }
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);
642
+ n.transform && (f.data = n.transform.transform(f.data));
643
+ let p = f;
644
+ for (let e of this.responseInterceptors) p = await e.onResponse(p);
645
+ if ((n.method === "GET" || !n.method) && n.cache?.enabled) {
646
+ let e = this.getCacheKey(n);
647
+ this.cache.set(e, p, n.cache.ttlMs);
1045
648
  }
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);
649
+ return r.onSuccess?.(p), this.pendingRequests.delete(c), this.trackDev({
650
+ method: n.method ?? "GET",
651
+ url: o.url,
652
+ status: p.status,
653
+ duration: p.duration,
654
+ cached: !1,
655
+ ok: !0,
656
+ headers: { ...o.headers },
657
+ body: n.body,
658
+ retryCount: s - 1
659
+ }), e(p);
660
+ } catch (e) {
661
+ let l;
662
+ if (l = e instanceof DOMException ? e.name === "TimeoutError" ? {
663
+ message: "Request timed out",
664
+ code: "TIMEOUT"
665
+ } : e.name === "AbortError" ? {
666
+ message: "Request aborted",
667
+ code: "ABORTED"
668
+ } : {
669
+ message: e.message,
670
+ code: "UNKNOWN_ERROR",
671
+ originalError: e
672
+ } : this.isHttpErrorDetails(e) ? e : this.normalizeError(e), s < i && a.shouldRetry(s, l)) {
673
+ r.onRetry?.(s, l);
674
+ let e = a.delayMs(s);
675
+ await this.delay(e);
1056
676
  continue;
1057
677
  }
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);
678
+ let u = l;
679
+ for (let e of this.responseInterceptors) e.onError && (u = await e.onError(u));
680
+ return r.onError?.(u), c && this.pendingRequests.delete(c), this.trackDev({
681
+ method: n.method ?? "GET",
682
+ url: o.url,
683
+ status: u.status,
684
+ duration: 0,
685
+ cached: !1,
686
+ ok: !1,
687
+ code: u.code,
688
+ headers: { ...o.headers },
689
+ body: n.body,
690
+ retryCount: s - 1
691
+ }), t(u);
1061
692
  }
1062
693
  }
1063
- let l = {
694
+ let s = {
1064
695
  message: "Max retries exceeded",
1065
696
  code: "MAX_RETRIES"
1066
697
  };
1067
- return this.logDebug(n, "info", "Max retries exceeded", l, a), t.onError?.(l), i(l);
698
+ return r.onError?.(s), this.trackDev({
699
+ method: n.method ?? "GET",
700
+ url: o.url,
701
+ duration: 0,
702
+ cached: !1,
703
+ ok: !1,
704
+ code: "MAX_RETRIES",
705
+ headers: { ...o.headers },
706
+ body: n.body,
707
+ retryCount: i
708
+ }), t(s);
1068
709
  } finally {
1069
- t.onFinally?.(), this.requestQueue && this.requestQueue.release();
710
+ r.onFinally?.(), this.requestQueue && this.requestQueue.release();
711
+ }
712
+ }
713
+ async fastPath(n) {
714
+ let r = B(n.url, n.params), i = this.buildUrl(r, n.query), { serialized: a, contentType: o } = z(n.body), s = {
715
+ ...this.config.defaultHeaders,
716
+ ...n.headers
717
+ };
718
+ o ? s["Content-Type"] = o : a instanceof FormData && delete s["Content-Type"];
719
+ let c = new AbortController(), l = this.resolveTimeoutMs(n.timeout ?? this.config.defaultTimeout);
720
+ this.pendingRequests.add(c);
721
+ try {
722
+ let r = performance.now(), a = await this.fetchWithTimeout({
723
+ url: i,
724
+ method: n.method ?? "GET",
725
+ headers: s,
726
+ body: n.body,
727
+ params: n.params
728
+ }, l, c), o = performance.now() - r, u = await this.parseBody(a, n.responseType ?? this.config.defaultResponseType);
729
+ if (!this.config.validateStatus(a.status)) {
730
+ let e = t({
731
+ message: `Request failed with status ${a.status}`,
732
+ status: a.status,
733
+ statusText: a.statusText,
734
+ code: "HTTP_ERROR"
735
+ });
736
+ return this.trackDev({
737
+ method: n.method ?? "GET",
738
+ url: i,
739
+ status: a.status,
740
+ duration: o,
741
+ cached: !1,
742
+ ok: !1,
743
+ code: "HTTP_ERROR",
744
+ headers: s,
745
+ body: n.body,
746
+ retryCount: 0
747
+ }), this.pendingRequests.delete(c), e;
748
+ }
749
+ return this.pendingRequests.delete(c), this.trackDev({
750
+ method: n.method ?? "GET",
751
+ url: i,
752
+ status: a.status,
753
+ duration: o,
754
+ cached: !1,
755
+ ok: !0,
756
+ headers: s,
757
+ body: n.body,
758
+ retryCount: 0
759
+ }), e({
760
+ status: a.status,
761
+ statusText: a.statusText,
762
+ headers: a.headers,
763
+ data: u,
764
+ request: {
765
+ url: i,
766
+ method: n.method ?? "GET",
767
+ headers: s,
768
+ body: n.body,
769
+ params: n.params
770
+ },
771
+ duration: o
772
+ });
773
+ } catch (e) {
774
+ this.pendingRequests.delete(c);
775
+ let r = "UNKNOWN_ERROR";
776
+ if (e instanceof DOMException ? e.name === "TimeoutError" ? r = "TIMEOUT" : e.name === "AbortError" && (r = "ABORTED") : e instanceof Error && (e.name === "TimeoutError" ? r = "TIMEOUT" : e.name === "AbortError" || e.message.includes("abort") ? r = "ABORTED" : e.name === "TypeError" && (r = "NETWORK_ERROR")), this.trackDev({
777
+ method: n.method ?? "GET",
778
+ url: i,
779
+ duration: performance.now() - (performance.now() - 0),
780
+ cached: !1,
781
+ ok: !1,
782
+ code: r,
783
+ headers: s,
784
+ body: n.body,
785
+ retryCount: 0
786
+ }), e instanceof DOMException) {
787
+ if (e.name === "TimeoutError") return t({
788
+ message: "Request timed out",
789
+ code: "TIMEOUT"
790
+ });
791
+ if (e.name === "AbortError") return t({
792
+ message: "Request aborted",
793
+ code: "ABORTED"
794
+ });
795
+ }
796
+ return e instanceof Error ? e.name === "TimeoutError" ? t({
797
+ message: "Request timed out",
798
+ code: "TIMEOUT"
799
+ }) : e.name === "AbortError" || e.message.includes("abort") ? t({
800
+ message: "Request aborted",
801
+ code: "ABORTED"
802
+ }) : t({
803
+ message: e.message,
804
+ code: e.name === "TypeError" ? "NETWORK_ERROR" : "UNKNOWN_ERROR"
805
+ }) : t({
806
+ message: String(e),
807
+ code: "UNKNOWN_ERROR"
808
+ });
1070
809
  }
1071
810
  }
1072
811
  get(e, t) {
@@ -1140,7 +879,7 @@ var q = class e {
1140
879
  this.cache.clear();
1141
880
  }
1142
881
  cancelAll() {
1143
- for (let e of this.pendingRequests.values()) e.abort();
882
+ for (let e of this.pendingRequests) e.abort();
1144
883
  this.pendingRequests.clear();
1145
884
  }
1146
885
  get activeRequests() {
@@ -1152,30 +891,27 @@ var q = class e {
1152
891
  pending: this.requestQueue?.pending ?? 0
1153
892
  };
1154
893
  }
1155
- extend(t = {}) {
1156
- let n = new e({
1157
- baseURL: t.baseURL ?? this.config.baseURL,
894
+ extend(e = {}) {
895
+ let t = new n({
896
+ baseURL: e.baseURL ?? this.config.baseURL,
1158
897
  defaultHeaders: {
1159
898
  ...this.config.defaultHeaders,
1160
- ...t.defaultHeaders
899
+ ...e.defaultHeaders
1161
900
  },
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,
901
+ defaultTimeout: e.defaultTimeout ?? this.config.defaultTimeout,
902
+ validateStatus: e.validateStatus ?? this.config.validateStatus,
903
+ cacheStrategy: e.cacheStrategy ?? this.cache,
904
+ maxConcurrent: e.maxConcurrent ?? this.config.maxConcurrent,
905
+ defaultResponseType: e.defaultResponseType ?? this.config.defaultResponseType,
1168
906
  defaultHooks: {
1169
907
  ...this.config.defaultHooks,
1170
- ...t.defaultHooks
908
+ ...e.defaultHooks
1171
909
  },
1172
- transformRequest: t.transformRequest ?? this.config.transformRequest,
1173
- adapter: t.adapter ?? this.config.adapter,
1174
- autoFormData: t.autoFormData ?? this.config.autoFormData
910
+ adapter: e.adapter
1175
911
  });
1176
- for (let e of this.requestInterceptors) n.addRequestInterceptor(e);
1177
- for (let e of this.responseInterceptors) n.addResponseInterceptor(e);
1178
- return n;
912
+ for (let e of this.requestInterceptors) t.addRequestInterceptor(e);
913
+ for (let e of this.responseInterceptors) t.addResponseInterceptor(e);
914
+ return t;
1179
915
  }
1180
916
  async *paginate(e, t, n = {}) {
1181
917
  let r = { ...n };
@@ -1188,88 +924,63 @@ var q = class e {
1188
924
  r = i;
1189
925
  }
1190
926
  }
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);
927
+ async poll(e, n, r = {}) {
928
+ let i = n.maxAttempts ?? 0;
929
+ for (let t = 1; i === 0 || t <= i; t++) {
930
+ let a = await this.get(e, r);
931
+ if (!a.ok || (n.onPoll?.(a.value.data, t), n.until(a.value.data))) return a;
932
+ if (i > 0 && t >= i) break;
933
+ await this.delay(n.intervalMs);
1198
934
  }
1199
- return i({
1200
- message: `Polling exhausted after ${r} attempts`,
935
+ return t({
936
+ message: `Polling exhausted after ${i} attempts`,
1201
937
  code: "POLL_EXHAUSTED"
1202
938
  });
1203
939
  }
1204
940
  buildRequest(e) {
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;
941
+ let t = B(e.url, e.params);
1206
942
  return {
1207
- url: n,
943
+ url: this.buildUrl(t, e.query),
1208
944
  method: e.method ?? "GET",
1209
945
  headers: {
1210
946
  ...this.config.defaultHeaders,
1211
947
  ...e.headers
1212
948
  },
1213
949
  body: e.body,
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
950
+ params: e.params
1223
951
  };
1224
952
  }
1225
953
  buildUrl(e, t) {
1226
954
  let n = this.config.baseURL + e;
1227
- if (t && Object.keys(t).length > 0) {
1228
- let e = new URLSearchParams();
1229
- Object.entries(t).forEach(([t, n]) => {
1230
- e.append(t, String(n));
1231
- }), n += `?${e.toString()}`;
955
+ if (t) {
956
+ let e = Object.keys(t);
957
+ if (e.length > 0) {
958
+ let r = new URLSearchParams();
959
+ for (let n = 0; n < e.length; n++) r.append(e[n], String(t[e[n]]));
960
+ n += `?${r.toString()}`;
961
+ }
1232
962
  }
1233
963
  return n;
1234
964
  }
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
- }
1246
965
  getCacheKey(e) {
1247
- let t = G(e.url, e.params), n = e.query ? JSON.stringify(e.query) : "";
966
+ let t = B(e.url, e.params), n = e.query ? JSON.stringify(e.query) : "";
1248
967
  return `${e.method ?? "GET"}:${t}${n ? ":" + n : ""}`;
1249
968
  }
1250
969
  fetchWithTimeout(e, t, n) {
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(() => {
1257
- n.abort();
1258
- let e = /* @__PURE__ */ Error("Request timed out");
1259
- e.name = "TimeoutError", i(e);
1260
- }, o));
1261
- let c = {
970
+ let { serialized: r, contentType: i } = z(e.body), a = { ...e.headers };
971
+ return i ? a["Content-Type"] = i : r instanceof FormData && delete a["Content-Type"], new Promise((i, o) => {
972
+ let s = setTimeout(() => {
973
+ n.abort(), o(new DOMException("Request timed out", "TimeoutError"));
974
+ }, t);
975
+ (this.config.adapter ?? fetch)(e.url, {
1262
976
  method: e.method,
1263
977
  headers: a,
1264
978
  body: r,
1265
979
  signal: n.signal
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);
980
+ }).then((e) => {
981
+ clearTimeout(s), i(e);
1271
982
  }, (e) => {
1272
- s && clearTimeout(s), i(e);
983
+ clearTimeout(s), o(e);
1273
984
  });
1274
985
  });
1275
986
  }
@@ -1294,98 +1005,88 @@ var q = class e {
1294
1005
  statusText: e.statusText
1295
1006
  });
1296
1007
  }
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);
1008
+ async parseResponse(e, t, n, r) {
1009
+ let i = await this.parseBody(e, r);
1312
1010
  return {
1313
1011
  status: e.status,
1314
1012
  statusText: e.statusText,
1315
1013
  headers: e.headers,
1316
- data: a,
1014
+ data: i,
1317
1015
  request: t,
1318
1016
  duration: n
1319
1017
  };
1320
1018
  }
1321
- async parseBody(e, t, n) {
1322
- let r = async (e) => n !== void 0 && n > 0 ? this.withTimeout(e, n, "Response timeout") : e;
1019
+ async parseBody(e, t) {
1323
1020
  switch (t) {
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());
1021
+ case "json": return await e.json();
1022
+ case "text": return await e.text();
1023
+ case "blob": return await e.blob();
1024
+ case "arrayBuffer": return await e.arrayBuffer();
1025
+ case "formData": return await e.formData();
1329
1026
  case "stream": return e.body;
1330
1027
  default: {
1331
1028
  let t = e.headers.get("content-type") ?? "";
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());
1029
+ if (t.includes("application/json")) return await e.json();
1030
+ if (t.includes("text/")) return await e.text();
1031
+ if (t.includes("multipart/form-data")) return await e.formData();
1032
+ if (t.includes("application/octet-stream") || t.includes("image/") || t.includes("audio/") || t.includes("video/")) return await e.blob();
1336
1033
  try {
1337
- return await r(e.json());
1034
+ return await e.json();
1338
1035
  } catch {
1339
- return await r(e.text());
1036
+ return await e.text();
1340
1037
  }
1341
1038
  }
1342
1039
  }
1343
1040
  }
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") : {
1041
+ normalizeError(e) {
1042
+ if (e instanceof DOMException) {
1043
+ if (e.name === "TimeoutError") return {
1044
+ message: "Request timed out",
1045
+ code: "TIMEOUT"
1046
+ };
1047
+ if (e.name === "AbortError") return {
1048
+ message: "Request aborted",
1049
+ code: "ABORTED"
1050
+ };
1051
+ }
1052
+ return e instanceof Error ? e.name === "TimeoutError" ? {
1053
+ message: "Request timed out",
1054
+ code: "TIMEOUT"
1055
+ } : e.name === "AbortError" || e.message.includes("abort") ? {
1056
+ message: "Request aborted",
1057
+ code: "ABORTED"
1058
+ } : {
1353
1059
  message: e.message,
1354
1060
  code: e.name === "TypeError" ? "NETWORK_ERROR" : "UNKNOWN_ERROR",
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
1061
+ originalError: e
1362
1062
  } : {
1363
1063
  message: String(e),
1364
1064
  code: "UNKNOWN_ERROR",
1365
- originalError: e,
1366
- request: t,
1367
- config: n
1065
+ originalError: e
1368
1066
  };
1369
1067
  }
1370
1068
  isHttpErrorDetails(e) {
1371
1069
  return typeof e == "object" && !!e && "message" in e && "code" in e;
1372
1070
  }
1373
1071
  getMaxAttempts(e) {
1374
- return e ? "shouldRetry" in e ? 100 : e.maxAttempts ?? 3 : 1;
1072
+ return e ? "maxAttempts" in e ? e.maxAttempts ?? 1 : 100 : 1;
1375
1073
  }
1376
1074
  getRetryStrategy(e) {
1377
- if (!e) return {
1075
+ return e ? "shouldRetry" in e ? e : new L(e.maxAttempts, e.backoffMs) : {
1378
1076
  shouldRetry: () => !1,
1379
1077
  delayMs: () => 0
1380
1078
  };
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);
1079
+ }
1080
+ resolveTimeoutMs(e) {
1081
+ return typeof e == "number" ? e : e.total ?? e.response ?? e.connection ?? 3e4;
1384
1082
  }
1385
1083
  delay(e) {
1386
1084
  return new Promise((t) => setTimeout(t, e));
1387
1085
  }
1388
- }, J = class extends Error {
1086
+ trackDev(e) {
1087
+ this.devTracker && this.devTracker.track(e);
1088
+ }
1089
+ }, H = class extends Error {
1389
1090
  status;
1390
1091
  code;
1391
1092
  response;
@@ -1393,18 +1094,18 @@ var q = class e {
1393
1094
  super(e), this.name = "HttpError", this.status = t, this.code = n, this.response = r;
1394
1095
  }
1395
1096
  };
1396
- function Ve(e) {
1397
- return e instanceof J;
1097
+ function U(e) {
1098
+ return e instanceof H;
1398
1099
  }
1399
- function He(e) {
1400
- return new q(e);
1100
+ function de(e) {
1101
+ return new V(e);
1401
1102
  }
1402
1103
  //#endregion
1403
1104
  //#region src/realtime/websocket-client.ts
1404
- function Y() {
1105
+ function W() {
1405
1106
  return typeof window > "u" && typeof process < "u" && process.versions?.node !== void 0;
1406
1107
  }
1407
- var Ue = class {
1108
+ var fe = class {
1408
1109
  url;
1409
1110
  options;
1410
1111
  pluginManager;
@@ -1426,7 +1127,7 @@ var Ue = class {
1426
1127
  message: /* @__PURE__ */ new Set()
1427
1128
  };
1428
1129
  constructor(e, t = {}) {
1429
- this.url = e, this.options = t, this.pluginManager = new P();
1130
+ this.url = e, this.options = t, this.pluginManager = new M();
1430
1131
  }
1431
1132
  updateStatus(e) {
1432
1133
  this.status = e, e === "open" ? this.connectionStartTime = Date.now() : e === "closed" && this.connectionStartTime > 0 && (this.stats.connectionTime += Date.now() - this.connectionStartTime, this.connectionStartTime = 0);
@@ -1503,7 +1204,7 @@ var Ue = class {
1503
1204
  cleanup() {
1504
1205
  this.reconnectTimer &&= (clearTimeout(this.reconnectTimer), null), this.stopHeartbeat();
1505
1206
  }
1506
- }, X = class extends Ue {
1207
+ }, G = class extends fe {
1507
1208
  socket = null;
1508
1209
  messageTypeListeners = /* @__PURE__ */ new Map();
1509
1210
  constructor(e, t = {}) {
@@ -1562,9 +1263,9 @@ var Ue = class {
1562
1263
  }
1563
1264
  return e;
1564
1265
  }
1565
- }, We = class extends X {
1266
+ }, pe = class extends G {
1566
1267
  async connect() {
1567
- if (Y()) try {
1268
+ if (W()) try {
1568
1269
  let { default: e } = await import("ws");
1569
1270
  return super.connect();
1570
1271
  } catch {
@@ -1573,15 +1274,15 @@ var Ue = class {
1573
1274
  return super.connect();
1574
1275
  }
1575
1276
  };
1576
- function Ge(e, t = {}) {
1577
- return Y() ? new We(e, t) : new X(e, t);
1277
+ function me(e, t = {}) {
1278
+ return W() ? new pe(e, t) : new G(e, t);
1578
1279
  }
1579
1280
  //#endregion
1580
1281
  //#region src/realtime/sse-client.ts
1581
- function Z() {
1282
+ function K() {
1582
1283
  return typeof window > "u" && typeof process < "u" && process.versions?.node !== void 0;
1583
1284
  }
1584
- var Ke = class {
1285
+ var q = class {
1585
1286
  url;
1586
1287
  options;
1587
1288
  _source = null;
@@ -1605,7 +1306,7 @@ var Ke = class {
1605
1306
  };
1606
1307
  _lastEventId = null;
1607
1308
  constructor(e, t = {}) {
1608
- this.url = e, this.options = t, this.pluginManager = new P();
1309
+ this.url = e, this.options = t, this.pluginManager = new M();
1609
1310
  }
1610
1311
  updateStatus(e) {
1611
1312
  this.status = e, e === "open" ? this.connectionStartTime = Date.now() : e === "closed" && this.connectionStartTime > 0 && (this.stats.connectionTime += Date.now() - this.connectionStartTime, this.connectionStartTime = 0);
@@ -1726,18 +1427,18 @@ var Ke = class {
1726
1427
  return e;
1727
1428
  }
1728
1429
  }
1729
- }, qe = class extends Ke {
1430
+ }, he = class extends q {
1730
1431
  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.");
1432
+ if (K()) 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
1433
  return super.connect();
1733
1434
  }
1734
1435
  };
1735
- function Je(e, t = {}) {
1736
- return Z() ? new qe(e, t) : new Ke(e, t);
1436
+ function ge(e, t = {}) {
1437
+ return K() ? new he(e, t) : new q(e, t);
1737
1438
  }
1738
1439
  //#endregion
1739
1440
  //#region src/realtime/plugin.ts
1740
- var Ye = class {
1441
+ var _e = class {
1741
1442
  name = "realtime";
1742
1443
  setup(e) {
1743
1444
  e.on("websocket:connect:start", (...t) => {
@@ -1761,197 +1462,709 @@ var Ye = class {
1761
1462
  });
1762
1463
  }
1763
1464
  };
1764
- function Xe() {
1765
- return new Ye();
1465
+ function ve() {
1466
+ return new _e();
1766
1467
  }
1767
1468
  //#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
- });
1469
+ //#region src/dev-overlay/tracker.ts
1470
+ var J = class {
1471
+ history = [];
1472
+ maxHistory;
1473
+ listeners = /* @__PURE__ */ new Set();
1474
+ startTime = Date.now();
1475
+ config;
1476
+ constructor(e = {}) {
1477
+ this.maxHistory = e.maxHistory ?? 500, this.config = {
1478
+ enabled: e.enabled ?? !0,
1479
+ maxHistory: this.maxHistory,
1480
+ keyboardShortcut: e.keyboardShortcut ?? "ctrl+shift+n",
1481
+ position: e.position ?? "bottom-right",
1482
+ theme: e.theme ?? "dark"
1888
1483
  };
1889
1484
  }
1890
- onGet(e) {
1891
- return new Q(this, "GET", e);
1892
- }
1893
- onPost(e) {
1894
- return new Q(this, "POST", e);
1485
+ track(e) {
1486
+ let t = {
1487
+ ...e,
1488
+ id: this.generateId(),
1489
+ timestamp: Date.now()
1490
+ };
1491
+ this.history.unshift(t), this.history.length > this.maxHistory && this.history.pop();
1492
+ for (let e of this.listeners) e(t);
1493
+ return t;
1895
1494
  }
1896
- onPut(e) {
1897
- return new Q(this, "PUT", e);
1495
+ getHistory() {
1496
+ return this.history;
1898
1497
  }
1899
- onPatch(e) {
1900
- return new Q(this, "PATCH", e);
1498
+ getMetrics() {
1499
+ let e = this.history.map((e) => e.duration), t = (Date.now() - this.startTime) / 1e3;
1500
+ return {
1501
+ totalRequests: this.history.length,
1502
+ successfulRequests: this.history.filter((e) => e.ok).length,
1503
+ failedRequests: this.history.filter((e) => !e.ok).length,
1504
+ cachedRequests: this.history.filter((e) => e.cached).length,
1505
+ avgDuration: e.length ? e.reduce((e, t) => e + t, 0) / e.length : 0,
1506
+ maxDuration: e.length ? Math.max(...e) : 0,
1507
+ minDuration: e.length ? Math.min(...e) : 0,
1508
+ requestsPerSecond: t > 0 ? this.history.length / t : 0,
1509
+ slowestRequests: [...this.history].sort((e, t) => t.duration - e.duration).slice(0, 5)
1510
+ };
1901
1511
  }
1902
- onDelete(e) {
1903
- return new Q(this, "DELETE", e);
1512
+ clear() {
1513
+ this.history = [], this.startTime = Date.now();
1514
+ }
1515
+ onChange(e) {
1516
+ return this.listeners.add(e), () => this.listeners.delete(e);
1517
+ }
1518
+ getConfig() {
1519
+ return this.config;
1520
+ }
1521
+ generateId() {
1522
+ return `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
1523
+ }
1524
+ }, Y = {
1525
+ close: "<svg width=\"16\" height=\"16\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M18 6L6 18M6 6l12 12\"/></svg>",
1526
+ chevron: "<svg width=\"12\" height=\"12\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M9 18l6-6-6-6\"/></svg>",
1527
+ back: "<svg width=\"14\" height=\"14\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M19 12H5M12 19l-7-7 7-7\"/></svg>",
1528
+ retry: "<svg width=\"14\" height=\"14\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M1 4v6h6M23 20v-6h-6\"/><path d=\"M20.49 9A9 9 0 005.64 5.64L1 10m22 4l-4.64 4.36A9 9 0 013.51 15\"/></svg>",
1529
+ clear: "<svg width=\"14\" height=\"14\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M3 6h18M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6m3 0V4a2 2 0 012-2h4a2 2 0 012 2v2\"/></svg>",
1530
+ search: "<svg width=\"14\" height=\"14\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><circle cx=\"11\" cy=\"11\" r=\"8\"/><path d=\"M21 21l-4.35-4.35\"/></svg>",
1531
+ clock: "<svg width=\"12\" height=\"12\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\"><circle cx=\"12\" cy=\"12\" r=\"10\"/><path d=\"M12 6v6l4 2\"/></svg>",
1532
+ zap: "<svg width=\"12\" height=\"12\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\"><polygon points=\"13 2 3 14 12 14 11 22 21 10 12 10 13 2\"/></svg>"
1533
+ }, X = {
1534
+ bg: "#09090b",
1535
+ bgElevated: "#18181b",
1536
+ border: "#27272a",
1537
+ borderFocus: "#3f3f46",
1538
+ text: "#fafafa",
1539
+ textMuted: "#a1a1aa",
1540
+ textDim: "#71717a",
1541
+ accent: "#3b82f6",
1542
+ accentHover: "#2563eb",
1543
+ success: "#22c55e",
1544
+ successBg: "rgba(34, 197, 94, 0.1)",
1545
+ error: "#ef4444",
1546
+ errorBg: "rgba(239, 68, 68, 0.1)",
1547
+ warning: "#f59e0b",
1548
+ get: "#22c55e",
1549
+ post: "#3b82f6",
1550
+ put: "#f59e0b",
1551
+ patch: "#a855f7",
1552
+ delete: "#ef4444"
1553
+ }, Z = `
1554
+ #nexa-dev-overlay * { margin: 0; padding: 0; box-sizing: border-box; }
1555
+ #nexa-dev-overlay {
1556
+ font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
1557
+ background: ${X.bg};
1558
+ color: ${X.text};
1559
+ border: 1px solid ${X.border};
1560
+ border-radius: 16px;
1561
+ box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5), 0 0 0 1px rgba(255,255,255,0.03);
1562
+ overflow: hidden;
1563
+ }
1564
+ #nexa-dev-overlay .nexa-header {
1565
+ display: flex;
1566
+ align-items: center;
1567
+ justify-content: space-between;
1568
+ padding: 16px 20px;
1569
+ border-bottom: 1px solid ${X.border};
1570
+ background: ${X.bgElevated};
1571
+ }
1572
+ #nexa-dev-overlay .nexa-header-left {
1573
+ display: flex;
1574
+ align-items: center;
1575
+ gap: 12px;
1576
+ }
1577
+ #nexa-dev-overlay .nexa-logo {
1578
+ width: 32px;
1579
+ height: 32px;
1580
+ display: flex;
1581
+ align-items: center;
1582
+ justify-content: center;
1583
+ background: ${X.bgElevated};
1584
+ border-radius: 8px;
1585
+ overflow: hidden;
1586
+ }
1587
+ #nexa-dev-overlay .nexa-title {
1588
+ font-size: 15px;
1589
+ font-weight: 600;
1590
+ letter-spacing: -0.02em;
1591
+ }
1592
+ #nexa-dev-overlay .nexa-header-actions {
1593
+ display: flex;
1594
+ gap: 4px;
1595
+ }
1596
+ #nexa-dev-overlay .nexa-icon-btn {
1597
+ width: 32px;
1598
+ height: 32px;
1599
+ display: flex;
1600
+ align-items: center;
1601
+ justify-content: center;
1602
+ background: transparent;
1603
+ border: none;
1604
+ border-radius: 8px;
1605
+ color: ${X.textMuted};
1606
+ cursor: pointer;
1607
+ transition: all 0.15s;
1608
+ }
1609
+ #nexa-dev-overlay .nexa-icon-btn:hover {
1610
+ background: ${X.border};
1611
+ color: ${X.text};
1612
+ }
1613
+ #nexa-dev-overlay .nexa-metrics-bar {
1614
+ display: flex;
1615
+ gap: 4px;
1616
+ padding: 12px 16px;
1617
+ background: ${X.bg};
1618
+ border-bottom: 1px solid ${X.border};
1619
+ }
1620
+ #nexa-dev-overlay .nexa-metric {
1621
+ flex: 1;
1622
+ display: flex;
1623
+ flex-direction: column;
1624
+ align-items: center;
1625
+ gap: 2px;
1626
+ padding: 8px 12px;
1627
+ background: ${X.bgElevated};
1628
+ border-radius: 10px;
1629
+ transition: all 0.2s;
1630
+ }
1631
+ #nexa-dev-overlay .nexa-metric:hover {
1632
+ background: ${X.border};
1633
+ }
1634
+ #nexa-dev-overlay .nexa-metric-value {
1635
+ font-size: 18px;
1636
+ font-weight: 700;
1637
+ letter-spacing: -0.03em;
1638
+ color: ${X.text};
1639
+ }
1640
+ #nexa-dev-overlay .nexa-metric-ok .nexa-metric-value { color: ${X.success}; }
1641
+ #nexa-dev-overlay .nexa-metric-err .nexa-metric-value { color: ${X.error}; }
1642
+ #nexa-dev-overlay .nexa-metric-label {
1643
+ font-size: 11px;
1644
+ color: ${X.textDim};
1645
+ text-transform: uppercase;
1646
+ letter-spacing: 0.05em;
1647
+ }
1648
+ #nexa-dev-overlay .nexa-search {
1649
+ padding: 12px 16px;
1650
+ border-bottom: 1px solid ${X.border};
1651
+ position: relative;
1652
+ }
1653
+ #nexa-dev-overlay .nexa-search-icon {
1654
+ position: absolute;
1655
+ left: 28px;
1656
+ top: 50%;
1657
+ transform: translateY(-50%);
1658
+ color: ${X.textDim};
1659
+ }
1660
+ #nexa-dev-overlay .nexa-search-input {
1661
+ width: 100%;
1662
+ padding: 10px 12px 10px 38px;
1663
+ background: ${X.bg};
1664
+ border: 1px solid ${X.border};
1665
+ border-radius: 10px;
1666
+ color: ${X.text};
1667
+ font-size: 13px;
1668
+ outline: none;
1669
+ transition: all 0.15s;
1670
+ }
1671
+ #nexa-dev-overlay .nexa-search-input:focus {
1672
+ border-color: ${X.accent};
1673
+ box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.15);
1674
+ }
1675
+ #nexa-dev-overlay .nexa-search-input::placeholder { color: ${X.textDim}; }
1676
+ #nexa-dev-overlay .nexa-tabs {
1677
+ display: flex;
1678
+ gap: 4px;
1679
+ padding: 8px 16px;
1680
+ border-bottom: 1px solid ${X.border};
1681
+ }
1682
+ #nexa-dev-overlay .nexa-tab {
1683
+ display: flex;
1684
+ align-items: center;
1685
+ gap: 8px;
1686
+ padding: 8px 14px;
1687
+ background: transparent;
1688
+ border: none;
1689
+ border-radius: 8px;
1690
+ color: ${X.textMuted};
1691
+ font-size: 13px;
1692
+ font-weight: 500;
1693
+ cursor: pointer;
1694
+ transition: all 0.15s;
1695
+ }
1696
+ #nexa-dev-overlay .nexa-tab:hover { color: ${X.text}; background: ${X.bgElevated}; }
1697
+ #nexa-dev-overlay .nexa-tab-active { color: ${X.text}; background: ${X.accent} !important; }
1698
+ #nexa-dev-overlay .nexa-tab-count {
1699
+ font-size: 11px;
1700
+ padding: 2px 6px;
1701
+ background: rgba(255,255,255,0.1);
1702
+ border-radius: 10px;
1703
+ }
1704
+ #nexa-dev-overlay .nexa-body { flex: 1; overflow: hidden; display: flex; }
1705
+ #nexa-dev-overlay .nexa-panel { display: none; width: 100%; overflow-y: auto; }
1706
+ #nexa-dev-overlay .nexa-panel-active { display: block; }
1707
+ #nexa-dev-overlay .nexa-request-list {
1708
+ padding: 8px;
1709
+ display: flex;
1710
+ flex-direction: column;
1711
+ gap: 4px;
1712
+ }
1713
+ #nexa-dev-overlay .nexa-request-item {
1714
+ display: flex;
1715
+ align-items: center;
1716
+ justify-content: space-between;
1717
+ padding: 12px 14px;
1718
+ background: ${X.bgElevated};
1719
+ border: 1px solid transparent;
1720
+ border-radius: 12px;
1721
+ cursor: pointer;
1722
+ transition: all 0.15s;
1723
+ animation: nexaFadeIn 0.2s ease forwards;
1724
+ opacity: 0;
1725
+ }
1726
+ @keyframes nexaFadeIn { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; transform: translateY(0); } }
1727
+ #nexa-dev-overlay .nexa-request-item:hover {
1728
+ background: ${X.border};
1729
+ border-color: ${X.borderFocus};
1730
+ transform: translateX(2px);
1731
+ }
1732
+ #nexa-dev-overlay .nexa-req-left {
1733
+ display: flex;
1734
+ align-items: center;
1735
+ gap: 10px;
1736
+ }
1737
+ #nexa-dev-overlay .nexa-method {
1738
+ font-size: 11px;
1739
+ font-weight: 700;
1740
+ padding: 4px 8px;
1741
+ border-radius: 6px;
1742
+ text-transform: uppercase;
1743
+ letter-spacing: 0.03em;
1744
+ }
1745
+ #nexa-dev-overlay .nexa-method-get { background: ${X.successBg}; color: ${X.get}; }
1746
+ #nexa-dev-overlay .nexa-method-post { background: rgba(59, 130, 246, 0.15); color: ${X.post}; }
1747
+ #nexa-dev-overlay .nexa-method-put { background: rgba(245, 158, 11, 0.15); color: ${X.put}; }
1748
+ #nexa-dev-overlay .nexa-method-patch { background: rgba(168, 85, 247, 0.15); color: ${X.patch}; }
1749
+ #nexa-dev-overlay .nexa-method-delete { background: ${X.errorBg}; color: ${X.delete}; }
1750
+ #nexa-dev-overlay .nexa-status {
1751
+ font-size: 12px;
1752
+ font-weight: 600;
1753
+ padding: 4px 8px;
1754
+ border-radius: 6px;
1755
+ min-width: 36px;
1756
+ text-align: center;
1757
+ }
1758
+ #nexa-dev-overlay .nexa-ok { background: ${X.successBg}; color: ${X.success}; }
1759
+ #nexa-dev-overlay .nexa-err { background: ${X.errorBg}; color: ${X.error}; }
1760
+ #nexa-dev-overlay .nexa-url {
1761
+ font-size: 13px;
1762
+ color: ${X.textMuted};
1763
+ max-width: 180px;
1764
+ overflow: hidden;
1765
+ text-overflow: ellipsis;
1766
+ white-space: nowrap;
1767
+ }
1768
+ #nexa-dev-overlay .nexa-req-right {
1769
+ display: flex;
1770
+ align-items: center;
1771
+ gap: 8px;
1772
+ }
1773
+ #nexa-dev-overlay .nexa-badge {
1774
+ font-size: 10px;
1775
+ font-weight: 600;
1776
+ padding: 3px 6px;
1777
+ border-radius: 6px;
1778
+ text-transform: uppercase;
1779
+ letter-spacing: 0.03em;
1780
+ }
1781
+ #nexa-dev-overlay .nexa-badge-cache { background: rgba(168, 85, 247, 0.15); color: #a855f7; }
1782
+ #nexa-dev-overlay .nexa-badge-retry { background: rgba(245, 158, 11, 0.15); color: ${X.warning}; }
1783
+ #nexa-dev-overlay .nexa-duration {
1784
+ font-size: 12px;
1785
+ font-weight: 600;
1786
+ color: ${X.textDim};
1787
+ font-variant-numeric: tabular-nums;
1788
+ }
1789
+ #nexa-dev-overlay .nexa-slow { color: ${X.warning}; }
1790
+ #nexa-dev-overlay .nexa-empty {
1791
+ display: flex;
1792
+ flex-direction: column;
1793
+ align-items: center;
1794
+ justify-content: center;
1795
+ padding: 48px 24px;
1796
+ text-align: center;
1797
+ color: ${X.textDim};
1798
+ }
1799
+ #nexa-dev-overlay .nexa-empty svg { margin-bottom: 16px; opacity: 0.4; }
1800
+ #nexa-dev-overlay .nexa-empty p { font-size: 14px; color: ${X.textMuted}; margin-bottom: 4px; }
1801
+ #nexa-dev-overlay .nexa-empty span { font-size: 12px; color: ${X.textDim}; }
1802
+ #nexa-dev-overlay .nexa-detail {
1803
+ flex-direction: column;
1804
+ padding: 16px;
1805
+ display: none;
1806
+ overflow-y: auto;
1807
+ max-height: 100%;
1808
+ }
1809
+ #nexa-dev-overlay .nexa-detail-active { display: flex; }
1810
+ #nexa-dev-overlay .nexa-detail-header {
1811
+ display: flex;
1812
+ align-items: center;
1813
+ justify-content: space-between;
1814
+ margin-bottom: 16px;
1815
+ }
1816
+ #nexa-dev-overlay .nexa-btn {
1817
+ display: flex;
1818
+ align-items: center;
1819
+ gap: 6px;
1820
+ padding: 8px 14px;
1821
+ background: ${X.bgElevated};
1822
+ border: 1px solid ${X.border};
1823
+ border-radius: 8px;
1824
+ color: ${X.textMuted};
1825
+ font-size: 13px;
1826
+ font-weight: 500;
1827
+ cursor: pointer;
1828
+ transition: all 0.15s;
1829
+ }
1830
+ #nexa-dev-overlay .nexa-btn:hover { background: ${X.border}; color: ${X.text}; }
1831
+ #nexa-dev-overlay .nexa-btn-retry { background: ${X.successBg}; border-color: transparent; color: ${X.success}; }
1832
+ #nexa-dev-overlay .nexa-btn-retry:hover { background: ${X.success}; color: white; }
1833
+ #nexa-dev-overlay .nexa-card {
1834
+ background: ${X.bgElevated};
1835
+ border: 1px solid ${X.border};
1836
+ border-radius: 12px;
1837
+ padding: 16px;
1838
+ margin-bottom: 12px;
1839
+ }
1840
+ #nexa-dev-overlay .nexa-card h3 {
1841
+ font-size: 12px;
1842
+ font-weight: 600;
1843
+ color: ${X.textDim};
1844
+ text-transform: uppercase;
1845
+ letter-spacing: 0.05em;
1846
+ margin-bottom: 12px;
1847
+ }
1848
+ #nexa-dev-overlay .nexa-row {
1849
+ display: flex;
1850
+ justify-content: space-between;
1851
+ align-items: center;
1852
+ padding: 6px 0;
1853
+ font-size: 13px;
1854
+ border-bottom: 1px solid ${X.border};
1855
+ }
1856
+ #nexa-dev-overlay .nexa-row:last-child { border-bottom: none; }
1857
+ #nexa-dev-overlay .nexa-row span { color: ${X.textMuted}; }
1858
+ #nexa-dev-overlay .nexa-row strong { color: ${X.text}; font-weight: 500; font-variant-numeric: tabular-nums; }
1859
+ #nexa-dev-overlay .nexa-row .nexa-ok { color: ${X.success}; }
1860
+ #nexa-dev-overlay .nexa-row .nexa-err { color: ${X.error}; }
1861
+ #nexa-dev-overlay .nexa-code {
1862
+ background: ${X.bg};
1863
+ border-radius: 8px;
1864
+ padding: 12px;
1865
+ font-size: 11px;
1866
+ font-family: 'JetBrains Mono', 'Fira Code', monospace;
1867
+ color: ${X.textMuted};
1868
+ overflow-x: auto;
1869
+ white-space: pre;
1870
+ max-height: 200px;
1871
+ line-height: 1.6;
1872
+ }
1873
+ #nexa-dev-overlay .nexa-url-full {
1874
+ font-size: 12px;
1875
+ word-break: break-all;
1876
+ color: ${X.accent};
1877
+ }
1878
+ #nexa-dev-overlay .nexa-metrics-content {
1879
+ padding: 16px;
1880
+ display: flex;
1881
+ flex-direction: column;
1882
+ gap: 12px;
1883
+ }
1884
+ #nexa-dev-overlay .nexa-slow-req {
1885
+ display: flex;
1886
+ align-items: center;
1887
+ gap: 8px;
1888
+ }
1889
+ `, ye = class {
1890
+ panel = null;
1891
+ tracker;
1892
+ visible = !1;
1893
+ selectedRequest = null;
1894
+ config;
1895
+ searchQuery = "";
1896
+ constructor(e) {
1897
+ this.tracker = e, this.config = e.getConfig(), this.setupKeyboardShortcut(), this.createPanel();
1898
+ }
1899
+ show() {
1900
+ this.panel && (this.panel.style.display = "flex", this.panel.style.opacity = "0", this.panel.style.transform = "scale(0.96) translateY(8px)", requestAnimationFrame(() => {
1901
+ this.panel.style.transition = "all 0.25s cubic-bezier(0.16, 1, 0.3, 1)", this.panel.style.opacity = "1", this.panel.style.transform = "scale(1) translateY(0)";
1902
+ }), this.visible = !0);
1903
+ }
1904
+ hide() {
1905
+ this.panel && (this.panel.style.transition = "all 0.15s ease-out", this.panel.style.opacity = "0", this.panel.style.transform = "scale(0.96) translateY(8px)", setTimeout(() => {
1906
+ this.panel && (this.panel.style.display = "none");
1907
+ }, 150), this.visible = !1);
1908
+ }
1909
+ toggle() {
1910
+ this.visible ? this.hide() : this.show();
1911
+ }
1912
+ destroy() {
1913
+ this.panel?.remove(), this.panel = null;
1914
+ }
1915
+ setupKeyboardShortcut() {
1916
+ let e = this.config.keyboardShortcut.split("+"), t = new Set(e.map((e) => e.toLowerCase()));
1917
+ document.addEventListener("keydown", (e) => {
1918
+ let n = /* @__PURE__ */ new Set();
1919
+ e.ctrlKey && n.add("ctrl"), e.metaKey && (n.add("meta"), n.add("cmd"), n.add("ctrl")), e.shiftKey && n.add("shift"), e.altKey && n.add("alt"), (e.key && e.key.length === 1 || e.key.length > 1) && n.add(e.key.toLowerCase());
1920
+ let r = !0;
1921
+ for (let e of t) if (!n.has(e)) {
1922
+ r = !1;
1923
+ break;
1924
+ }
1925
+ r && n.size === t.size && (e.preventDefault(), this.toggle());
1926
+ });
1904
1927
  }
1905
- onAny(e) {
1906
- return new Q(this, "ANY", e);
1928
+ createPanel() {
1929
+ this.panel = document.createElement("div"), this.panel.id = "nexa-dev-overlay";
1930
+ let e = this.config.position, t = e.includes("bottom"), n = e.includes("right");
1931
+ this.panel.style.cssText = `
1932
+ position: fixed;
1933
+ ${t ? "bottom: 24px;" : "top: 24px;"}
1934
+ ${n ? "right: 24px;" : "left: 24px;"}
1935
+ width: 420px;
1936
+ max-height: 70vh;
1937
+ z-index: 2147483647;
1938
+ display: flex;
1939
+ flex-direction: column;
1940
+ overflow: hidden;
1941
+ `, this.panel.innerHTML = `<style>${Z}</style>
1942
+
1943
+ <div class="nexa-header">
1944
+ <div class="nexa-header-left">
1945
+ <div class="nexa-logo">
1946
+ <img src="/src/assets/faviconNew.png" width="18" height="18" style="border-radius:4px;object-fit:contain;display:block;" alt="Nexa" onerror="this.style.display='none';this.nextElementSibling.style.display='flex';" />
1947
+ <span style="display:none;align-items:center;justify-content:center;font-size:14px;font-weight:700;color:#fff;background:linear-gradient(135deg,#3b82f6,#238636);width:18px;height:18px;border-radius:4px;">N</span>
1948
+ </div>
1949
+ <span class="nexa-title">Nexa DevTools</span>
1950
+ </div>
1951
+ <div class="nexa-header-actions">
1952
+ <button class="nexa-icon-btn nexa-btn-clear" title="Clear history">${Y.clear}</button>
1953
+ <button class="nexa-icon-btn nexa-btn-close" title="Close (Esc)">${Y.close}</button>
1954
+ </div>
1955
+ </div>
1956
+
1957
+ <div class="nexa-metrics-bar">
1958
+ <div class="nexa-metric"><span class="nexa-metric-value" data-metric="total">0</span><span class="nexa-metric-label">Requests</span></div>
1959
+ <div class="nexa-metric"><span class="nexa-metric-value" data-metric="avg">0ms</span><span class="nexa-metric-label">Avg</span></div>
1960
+ <div class="nexa-metric"><span class="nexa-metric-value" data-metric="rate">0/s</span><span class="nexa-metric-label">Throughput</span></div>
1961
+ <div class="nexa-metric nexa-metric-ok"><span class="nexa-metric-value" data-metric="success">0</span><span class="nexa-metric-label">Success</span></div>
1962
+ <div class="nexa-metric nexa-metric-err"><span class="nexa-metric-value" data-metric="fail">0</span><span class="nexa-metric-label">Failed</span></div>
1963
+ </div>
1964
+
1965
+ <div class="nexa-search">
1966
+ <span class="nexa-search-icon">${Y.search}</span>
1967
+ <input type="text" class="nexa-search-input" placeholder="Filter by URL, method, or status..." />
1968
+ </div>
1969
+
1970
+ <div class="nexa-tabs">
1971
+ <button class="nexa-tab nexa-tab-active" data-tab="requests"><span>Requests</span><span class="nexa-tab-count" data-count="requests">0</span></button>
1972
+ <button class="nexa-tab" data-tab="metrics"><span>Metrics</span></button>
1973
+ </div>
1974
+
1975
+ <div class="nexa-body">
1976
+ <div class="nexa-panel nexa-panel-active" data-panel="requests"><div class="nexa-request-list"></div></div>
1977
+ <div class="nexa-panel" data-panel="metrics"><div class="nexa-metrics-content"></div></div>
1978
+ </div>
1979
+
1980
+ <div class="nexa-detail" style="display:none">
1981
+ <div class="nexa-detail-header">
1982
+ <button class="nexa-btn nexa-btn-back">${Y.back} Back</button>
1983
+ <button class="nexa-btn nexa-btn-retry">${Y.retry} Retry</button>
1984
+ </div>
1985
+ <div class="nexa-detail-body"></div>
1986
+ </div>
1987
+ `, document.body.appendChild(this.panel), this.bindEvents(), this.tracker.onChange(() => this.render()), this.hide(), document.addEventListener("keydown", (e) => {
1988
+ if (e.key === "Escape" && this.visible) {
1989
+ this.hide();
1990
+ return;
1991
+ }
1992
+ if (this.visible && (e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "f") {
1993
+ e.preventDefault();
1994
+ let t = this.panel?.querySelector(".nexa-search-input");
1995
+ t?.focus(), t?.select();
1996
+ }
1997
+ });
1907
1998
  }
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;
1999
+ bindEvents() {
2000
+ this.panel && (this.panel.querySelector(".nexa-btn-close")?.addEventListener("click", () => this.hide()), this.panel.querySelector(".nexa-btn-clear")?.addEventListener("click", () => {
2001
+ this.tracker.clear(), this.render();
2002
+ }), this.panel.querySelector(".nexa-btn-back")?.addEventListener("click", () => this.showMainView()), this.panel.querySelector(".nexa-btn-retry")?.addEventListener("click", () => this.retrySelected()), this.panel.querySelector(".nexa-search-input")?.addEventListener("input", (e) => {
2003
+ this.searchQuery = e.target.value.toLowerCase(), this.renderRequestList();
2004
+ }), this.panel.querySelectorAll(".nexa-tab").forEach((e) => {
2005
+ e.addEventListener("click", () => {
2006
+ this.panel.querySelectorAll(".nexa-tab").forEach((e) => e.classList.remove("nexa-tab-active")), this.panel.querySelectorAll(".nexa-panel").forEach((e) => e.classList.remove("nexa-panel-active")), e.classList.add("nexa-tab-active"), this.panel.querySelector(`[data-panel="${e.dataset.tab}"]`)?.classList.add("nexa-panel-active"), e.dataset.tab === "metrics" && this.renderMetrics();
2007
+ });
2008
+ }));
1916
2009
  }
1917
- reset() {
1918
- this.routes = [];
2010
+ render() {
2011
+ !this.panel || !this.visible || (this.renderMetricsBar(), this.renderRequestList());
2012
+ }
2013
+ renderMetricsBar() {
2014
+ let e = this.tracker.getMetrics(), t = this.panel;
2015
+ t && (t.querySelector("[data-metric=\"total\"]").textContent = String(e.totalRequests), t.querySelector("[data-metric=\"avg\"]").textContent = `${e.avgDuration.toFixed(0)}ms`, t.querySelector("[data-metric=\"rate\"]").textContent = `${e.requestsPerSecond.toFixed(1)}`, t.querySelector("[data-metric=\"success\"]").textContent = String(e.successfulRequests), t.querySelector("[data-metric=\"fail\"]").textContent = String(e.failedRequests), t.querySelector("[data-count=\"requests\"]").textContent = String(e.totalRequests));
2016
+ }
2017
+ renderRequestList() {
2018
+ let e = this.panel?.querySelector(".nexa-request-list");
2019
+ if (!e) return;
2020
+ let t = this.tracker.getHistory();
2021
+ if (this.searchQuery && (t = t.filter((e) => e.url.toLowerCase().includes(this.searchQuery) || e.method.toLowerCase().includes(this.searchQuery) || String(e.status).includes(this.searchQuery))), t.length === 0) {
2022
+ e.innerHTML = `
2023
+ <div class="nexa-empty">
2024
+ <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
2025
+ <circle cx="12" cy="12" r="10"/><path d="M8 12h8M12 8v8"/>
2026
+ </svg>
2027
+ <p>${this.searchQuery ? "No matching requests" : "No requests yet"}</p>
2028
+ <span>${this.searchQuery ? "Try a different search term" : "Make a request to see it here"}</span>
2029
+ </div>`;
2030
+ return;
2031
+ }
2032
+ e.innerHTML = t.map((e, t) => `
2033
+ <div class="nexa-request-item" data-id="${e.id}" style="animation-delay: ${Math.min(t * 20, 300)}ms">
2034
+ <div class="nexa-req-left">
2035
+ <span class="nexa-method nexa-method-${e.method.toLowerCase()}">${e.method}</span>
2036
+ <span class="nexa-status ${e.ok ? "nexa-ok" : "nexa-err"}">${e.status || "ERR"}</span>
2037
+ <span class="nexa-url" title="${e.url}">${this.truncateUrl(e.url)}</span>
2038
+ </div>
2039
+ <div class="nexa-req-right">
2040
+ ${e.cached ? "<span class=\"nexa-badge nexa-badge-cache\">Cache</span>" : ""}
2041
+ ${e.retryCount > 0 ? `<span class="nexa-badge nexa-badge-retry">${e.retryCount}R</span>` : ""}
2042
+ <span class="nexa-duration ${e.duration > 500 ? "nexa-slow" : ""}">${e.duration.toFixed(0)}ms</span>
2043
+ ${Y.chevron}
2044
+ </div>
2045
+ </div>
2046
+ `).join(""), e.querySelectorAll(".nexa-request-item").forEach((e) => {
2047
+ e.addEventListener("click", () => {
2048
+ let n = e.dataset.id, r = t.find((e) => e.id === n);
2049
+ r && this.showDetail(r);
2050
+ });
2051
+ });
1919
2052
  }
1920
- restore() {}
1921
- static reply(e, t, n) {
1922
- return {
1923
- status: e,
1924
- data: t,
1925
- headers: n
1926
- };
2053
+ renderMetrics() {
2054
+ let e = this.tracker.getMetrics(), t = this.panel?.querySelector(".nexa-metrics-content");
2055
+ if (!t) return;
2056
+ let n = e.totalRequests > 0 ? (e.successfulRequests / e.totalRequests * 100).toFixed(1) : "0";
2057
+ t.innerHTML = `
2058
+ <div class="nexa-card">
2059
+ <h3>Overview</h3>
2060
+ <div class="nexa-row"><span>Total Requests</span><strong>${e.totalRequests}</strong></div>
2061
+ <div class="nexa-row"><span>Successful</span><strong class="nexa-ok">${e.successfulRequests}</strong></div>
2062
+ <div class="nexa-row"><span>Failed</span><strong class="nexa-err">${e.failedRequests}</strong></div>
2063
+ <div class="nexa-row"><span>Cached</span><strong>${e.cachedRequests}</strong></div>
2064
+ <div class="nexa-row"><span>Success Rate</span><strong>${n}%</strong></div>
2065
+ </div>
2066
+ <div class="nexa-card">
2067
+ <h3>Performance</h3>
2068
+ <div class="nexa-row"><span>Average</span><strong>${e.avgDuration.toFixed(1)}ms</strong></div>
2069
+ <div class="nexa-row"><span>Fastest</span><strong class="nexa-ok">${e.minDuration.toFixed(1)}ms</strong></div>
2070
+ <div class="nexa-row"><span>Slowest</span><strong class="nexa-err">${e.maxDuration.toFixed(1)}ms</strong></div>
2071
+ <div class="nexa-row"><span>Throughput</span><strong>${e.requestsPerSecond.toFixed(2)} req/s</strong></div>
2072
+ </div>
2073
+ ${e.slowestRequests.length > 0 ? `
2074
+ <div class="nexa-card">
2075
+ <h3>Slowest Requests</h3>
2076
+ ${e.slowestRequests.map((e) => `
2077
+ <div class="nexa-row nexa-slow-req">
2078
+ <span><span class="nexa-method nexa-method-${e.method.toLowerCase()}" style="font-size:10px;padding:2px 5px;">${e.method}</span> ${this.truncateUrl(e.url, 25)}</span>
2079
+ <strong class="nexa-err">${e.duration.toFixed(0)}ms</strong>
2080
+ </div>
2081
+ `).join("")}
2082
+ </div>
2083
+ ` : ""}`;
2084
+ }
2085
+ showDetail(e) {
2086
+ this.selectedRequest = e;
2087
+ let t = this.panel?.querySelector(".nexa-body"), n = this.panel?.querySelector(".nexa-detail"), r = this.panel?.querySelector(".nexa-detail-body");
2088
+ !t || !n || !r || (t.style.display = "none", n.style.display = "flex", r.innerHTML = `
2089
+ <div class="nexa-card">
2090
+ <h3>Request</h3>
2091
+ <div class="nexa-row"><span>Method</span><strong style="color:${e.method === "GET" ? X.get : e.method === "POST" ? X.post : e.method === "DELETE" ? X.delete : X.warning}">${e.method}</strong></div>
2092
+ <div class="nexa-row"><span>URL</span><span class="nexa-url-full">${e.url}</span></div>
2093
+ <div class="nexa-row"><span>Status</span><strong class="${e.ok ? "nexa-ok" : "nexa-err"}">${e.status || "N/A"}</strong></div>
2094
+ <div class="nexa-row"><span>Duration</span><strong>${e.duration.toFixed(1)}ms</strong></div>
2095
+ <div class="nexa-row"><span>Cached</span><strong>${e.cached ? "Yes" : "No"}</strong></div>
2096
+ <div class="nexa-row"><span>Retries</span><strong>${e.retryCount}</strong></div>
2097
+ <div class="nexa-row"><span>Timestamp</span><strong>${new Date(e.timestamp).toLocaleTimeString()}</strong></div>
2098
+ </div>
2099
+ ${e.body === void 0 ? "" : `
2100
+ <div class="nexa-card">
2101
+ <h3>Request Body</h3>
2102
+ <pre class="nexa-code">${this.formatJson(e.body)}</pre>
2103
+ </div>
2104
+ `}
2105
+ ${Object.keys(e.headers).length > 0 ? `
2106
+ <div class="nexa-card">
2107
+ <h3>Headers</h3>
2108
+ <pre class="nexa-code">${this.formatJson(e.headers)}</pre>
2109
+ </div>
2110
+ ` : ""}`);
2111
+ }
2112
+ showMainView() {
2113
+ let e = this.panel?.querySelector(".nexa-body"), t = this.panel?.querySelector(".nexa-detail");
2114
+ e && (e.style.display = "flex"), t && (t.style.display = "none"), this.selectedRequest = null;
2115
+ }
2116
+ retrySelected() {
2117
+ if (!this.selectedRequest) return;
2118
+ let { method: e, url: t, body: n, headers: r } = this.selectedRequest;
2119
+ fetch(t, {
2120
+ method: e,
2121
+ headers: r,
2122
+ body: n ? JSON.stringify(n) : void 0
2123
+ }).then(async (e) => {
2124
+ this.selectedRequest && (this.selectedRequest = {
2125
+ ...this.selectedRequest,
2126
+ status: e.status,
2127
+ ok: e.ok,
2128
+ duration: this.selectedRequest.duration,
2129
+ timestamp: Date.now()
2130
+ }, this.showDetail(this.selectedRequest));
2131
+ }).catch(() => {});
1927
2132
  }
1928
- static networkError(e = "Network Error") {
1929
- return {
1930
- networkError: !0,
1931
- errorMessage: e
1932
- };
2133
+ truncateUrl(e, t = 35) {
2134
+ try {
2135
+ let t = new URL(e);
2136
+ return t.pathname + (t.search || "");
2137
+ } catch {
2138
+ return e.length > t ? e.slice(0, t) + "..." : e;
2139
+ }
1933
2140
  }
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;
2141
+ formatJson(e) {
2142
+ try {
2143
+ return JSON.stringify(e, null, 2);
2144
+ } catch {
2145
+ return String(e);
1947
2146
  }
1948
- return null;
1949
2147
  }
1950
- };
1951
- function Ze(e, t = {}) {
1952
- return new $(e, t);
2148
+ }, Q = null, $ = null;
2149
+ function be(e = {}) {
2150
+ return Q ? {
2151
+ tracker: $,
2152
+ ui: Q
2153
+ } : ($ = new J(e), Q = new ye($), Q.show(), {
2154
+ tracker: $,
2155
+ ui: Q
2156
+ });
2157
+ }
2158
+ function xe() {
2159
+ return {
2160
+ tracker: $,
2161
+ ui: Q
2162
+ };
2163
+ }
2164
+ function Se() {
2165
+ Q?.destroy(), Q = null, $ = null;
1953
2166
  }
1954
2167
  //#endregion
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 };
2168
+ export { d as AggressiveRetry, P as CachePlugin, v as CacheStore, p as CircuitBreakerRetry, f as ConservativeRetry, F as DedupePlugin, se as Defer, t as Err, V as HttpClient, H as HttpError, ue as LoggerPlugin, N as MetricsPlugin, ie as MiddlewarePipeline, e as Ok, M as PluginManager, x as RequestDeduplicator, J as RequestTracker, D as TypedObservable, b as cacheMiddleware, oe as createApiUrl, y as createCacheMiddleware, S as createDedupeMiddleware, be as createDevOverlay, de as createHttpClient, C as createPipeline, l as createProjectionTransformer, ve as createRealtimePlugin, r as createRequiredFieldsValidator, ge as createSSEClient, n as createSchemaValidator, j as createStreamingMiddleware, ae as createTypeGuard, E as createTypedApiClient, T as createTypedRequest, w as createTypedResponse, O as createUrl, me as createWebSocketClient, u as createWrapperTransformer, re as dedupeMiddleware, Se as destroyDevOverlay, xe as getDevOverlay, k as handleStream, U as isHttpError, _ as retry, ce as streamToFile, le as streamingMiddleware, s as transformCamelToSnake, c as transformFlatten, o as transformSnakeToCamel, i as validatorIsArray, a as validatorIsObject, ne as withTimeout };
1956
2169
 
1957
2170
  //# sourceMappingURL=nexa.es.js.map