@indra211/exios 3.2.0 → 3.3.1

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.
@@ -63,6 +63,51 @@ function redactConfig(config) {
63
63
  if (c.data !== void 0) c.data = REDACTED;
64
64
  return c;
65
65
  }
66
+ var SENSITIVE_QUERY_PARAMS = /* @__PURE__ */ new Set([
67
+ "access_token",
68
+ "api_key",
69
+ "apikey",
70
+ "auth",
71
+ "client_secret",
72
+ "id_token",
73
+ "key",
74
+ "password",
75
+ "refresh_token",
76
+ "secret",
77
+ "sig",
78
+ "signature",
79
+ "token",
80
+ "awsaccesskeyid",
81
+ "x-amz-credential",
82
+ "x-amz-security-token",
83
+ "x-amz-signature",
84
+ "x-goog-credential",
85
+ "x-goog-signature"
86
+ ]);
87
+ function redactURL(url) {
88
+ const absolute = /^[a-z][a-z\d+\-.]*:\/\//i.test(url);
89
+ let u;
90
+ try {
91
+ u = absolute ? new URL(url) : new URL(url, "http://exios.invalid");
92
+ } catch {
93
+ const q2 = url.indexOf("?");
94
+ return q2 === -1 ? url : url.slice(0, q2);
95
+ }
96
+ u.username = "";
97
+ u.password = "";
98
+ let changed = false;
99
+ const params = new URLSearchParams(u.search);
100
+ for (const k of new Set(params.keys()))
101
+ if (SENSITIVE_QUERY_PARAMS.has(k.toLowerCase())) {
102
+ params.set(k, REDACTED);
103
+ changed = true;
104
+ }
105
+ if (changed) u.search = params.toString().replaceAll("%5BREDACTED%5D", REDACTED);
106
+ if (absolute) return u.href;
107
+ const q = url.indexOf("?");
108
+ const path = q === -1 ? url : url.slice(0, q);
109
+ return changed ? path + u.search : url;
110
+ }
66
111
 
67
112
  // src/errors/ExiosError.ts
68
113
  var ExiosError = class _ExiosError extends Error {
@@ -2543,7 +2588,7 @@ var InflightRequests = class {
2543
2588
  };
2544
2589
 
2545
2590
  // src/core/plugins.ts
2546
- var HOOKS = ["setup", "beforeRequest", "afterResponse", "onError"];
2591
+ var HOOKS = ["setup", "beforeRequest", "afterResponse", "onError", "onCancel"];
2547
2592
  function invalid(message) {
2548
2593
  throw new ExiosError(`ERR_BAD_OPTION_VALUE: ${message}`, ExiosError.ERR_BAD_OPTION_VALUE);
2549
2594
  }
@@ -2586,7 +2631,17 @@ var PluginRegistry = class {
2586
2631
  try {
2587
2632
  response = await layer(i + 1, c);
2588
2633
  } catch (err) {
2589
- if (!p.onError || isCancel(err)) throw err;
2634
+ if (isCancel(err)) {
2635
+ if (p.onCancel) {
2636
+ try {
2637
+ p.onCancel(err, c);
2638
+ } catch (hookErr) {
2639
+ report(p.name, hookErr);
2640
+ }
2641
+ }
2642
+ throw err;
2643
+ }
2644
+ if (!p.onError) throw err;
2590
2645
  const recovered = await p.onError(err, c);
2591
2646
  if (recovered == null) throw err;
2592
2647
  return recovered;
@@ -2596,6 +2651,9 @@ var PluginRegistry = class {
2596
2651
  return layer(0, config);
2597
2652
  }
2598
2653
  };
2654
+ function report(name, err) {
2655
+ if (typeof console !== "undefined") console.error(`[exios] plugin "${name}" onCancel failed:`, err);
2656
+ }
2599
2657
 
2600
2658
  // src/core/requestCache.ts
2601
2659
  var SAFE_METHODS = Object.freeze(["get", "head"]);
@@ -2646,7 +2704,21 @@ function hash(str) {
2646
2704
  h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507) ^ Math.imul(h1 ^ h1 >>> 13, 3266489909);
2647
2705
  return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(36);
2648
2706
  }
2649
- var CACHE_DIRECTIVE_HEADERS = /* @__PURE__ */ new Set(["cache-control", "pragma"]);
2707
+ var KEY_IGNORED_HEADERS = /* @__PURE__ */ new Set([
2708
+ "cache-control",
2709
+ "pragma",
2710
+ "traceparent",
2711
+ "tracestate",
2712
+ "baggage",
2713
+ "b3",
2714
+ "x-b3-traceid",
2715
+ "x-b3-spanid",
2716
+ "x-b3-parentspanid",
2717
+ "x-b3-sampled",
2718
+ "x-b3-flags",
2719
+ "uber-trace-id",
2720
+ "sentry-trace"
2721
+ ]);
2650
2722
  function requestTarget(config) {
2651
2723
  const url = buildURL(
2652
2724
  buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls),
@@ -2659,7 +2731,7 @@ function defaultRequestKey(config, scope = "cache") {
2659
2731
  const skip = config.correlationIdHeader?.toLowerCase();
2660
2732
  const parts = [];
2661
2733
  for (const k of Object.keys(config.headers).sort())
2662
- if (k !== skip && !CACHE_DIRECTIVE_HEADERS.has(k)) parts.push(`${k}:${config.headers[k]}`);
2734
+ if (k !== skip && !KEY_IGNORED_HEADERS.has(k)) parts.push(`${k}:${config.headers[k]}`);
2663
2735
  if (config.auth) parts.push(`auth:${config.auth.username}:${config.auth.password}`);
2664
2736
  parts.push(`rt:${config.responseType ?? ""}`);
2665
2737
  parts.push(
@@ -3313,7 +3385,106 @@ function createInstance(defaults) {
3313
3385
 
3314
3386
  // src/core/internals.ts
3315
3387
  var INTERNALS = /* @__PURE__ */ Symbol.for("@indra211/exios/internals");
3316
- var internals = { abortError, buildFullPath, finishResponse, prepareRequest };
3388
+ var internals = {
3389
+ abortError,
3390
+ buildFullPath,
3391
+ buildURL,
3392
+ createRequestId,
3393
+ finishResponse,
3394
+ prepareRequest,
3395
+ redactURL
3396
+ };
3397
+
3398
+ // src/core/logger.ts
3399
+ var RANK = { debug: 10, info: 20, warn: 30, error: 40, silent: 99 };
3400
+ function createLoggerPlugin(options = {}) {
3401
+ const min = RANK[options.level ?? "info"];
3402
+ if (min === void 0) throw new TypeError(`createLoggerPlugin: unknown level ${String(options.level)}`);
3403
+ const target = options.logger ?? (typeof console !== "undefined" ? console : void 0);
3404
+ const write = (level, message, fields) => {
3405
+ if (RANK[level] < min) return;
3406
+ if (options.log) return options.log(level, message, fields);
3407
+ const fn = target?.[level];
3408
+ if (typeof fn === "function") fn.call(target, message, fields);
3409
+ };
3410
+ const base = (e) => {
3411
+ const url = redactURL(e.url);
3412
+ const fields = {
3413
+ label: `${e.method.toUpperCase()} ${url}`,
3414
+ event: "request",
3415
+ requestId: e.requestId,
3416
+ method: e.method.toUpperCase(),
3417
+ url
3418
+ };
3419
+ if (e.correlationId !== void 0) fields.correlationId = e.correlationId;
3420
+ if (options.metadata && e.metadata) fields.metadata = e.metadata;
3421
+ return fields;
3422
+ };
3423
+ const entry = (level, msg, f) => {
3424
+ const { label, ...fields } = f;
3425
+ write(level, `[exios] ${msg(label)}`, fields);
3426
+ };
3427
+ return {
3428
+ name: options.name ?? "logger",
3429
+ setup(instance) {
3430
+ if (min === RANK.silent) return;
3431
+ const offs = [
3432
+ instance.on("request", (e) => {
3433
+ const f = base(e);
3434
+ if (options.headers) f.headers = redactHeaders(e.config.headers);
3435
+ entry("debug", (l) => `\u2192 ${l}`, f);
3436
+ }),
3437
+ instance.on("response", (e) => {
3438
+ const f = { ...base(e), event: "response", status: e.status, attempts: e.attempts, durationMs: e.durationMs };
3439
+ const retries = e.attempts > 1 ? `, ${e.attempts} attempts` : "";
3440
+ entry(e.status >= 400 ? "warn" : "info", (l) => `\u2190 ${e.status} ${l} (${e.durationMs}ms${retries})`, f);
3441
+ }),
3442
+ instance.on("retry", (e) => {
3443
+ const reason = e.status !== void 0 ? `status ${e.status}` : e.error?.code ?? "error";
3444
+ const f = { ...base(e), event: "retry", attempt: e.attempt, delayMs: e.delayMs };
3445
+ if (e.status !== void 0) f.status = e.status;
3446
+ if (e.error?.code) f.code = e.error.code;
3447
+ entry("warn", (l) => `\u21BB ${l} attempt ${e.attempt} failed (${reason}), retrying in ${e.delayMs}ms`, f);
3448
+ }),
3449
+ instance.on("timeout", (e) => {
3450
+ const f = { ...base(e), event: "timeout", attempt: e.attempt, timeoutMs: e.timeoutMs };
3451
+ if (e.error.code) f.code = e.error.code;
3452
+ entry("warn", (l) => `\u23F1 ${l} ${e.kind === "total" ? "total timeout" : "timeout"} of ${e.timeoutMs}ms`, f);
3453
+ }),
3454
+ instance.on("error", (e) => {
3455
+ const f = { ...base(e), event: "error", attempts: e.attempts, durationMs: e.durationMs };
3456
+ if (e.status !== void 0) f.status = e.status;
3457
+ if (e.code !== void 0) f.code = e.code;
3458
+ const what = e.status !== void 0 ? `${e.status}` : e.code ?? "failed";
3459
+ entry("error", (l) => `\u2715 ${l} ${what} (${e.durationMs}ms)`, f);
3460
+ }),
3461
+ instance.on("canceled", (e) => {
3462
+ entry("debug", (l) => `\u2298 ${l} canceled`, { ...base(e), event: "canceled", attempts: e.attempts, durationMs: e.durationMs });
3463
+ }),
3464
+ ...["circuitOpen", "circuitHalfOpen", "circuitClose"].map(
3465
+ (name) => instance.on(name, (e) => {
3466
+ const fields = { event: name, key: e.key, from: e.from, to: e.to };
3467
+ write(name === "circuitOpen" ? "warn" : "info", `[exios] circuit ${e.key} ${e.from} \u2192 ${e.to}`, fields);
3468
+ })
3469
+ )
3470
+ ];
3471
+ return () => {
3472
+ for (const off of offs) off();
3473
+ };
3474
+ },
3475
+ // Cache hits and deduplicated followers make no network request, so they emit no events.
3476
+ afterResponse(response, config) {
3477
+ const source = response.meta.cached ? "cached" : response.meta.deduped ? "deduped" : void 0;
3478
+ if (!source || RANK.debug < min) return;
3479
+ const c = response.config ?? config;
3480
+ const url = redactURL(buildFullPath(c.baseURL, c.url, c.allowAbsoluteUrls));
3481
+ const fields = { event: "cache", source, method: c.method.toUpperCase(), url, status: response.status };
3482
+ if (c.requestId !== void 0) fields.requestId = c.requestId;
3483
+ if (c.correlationId !== void 0) fields.correlationId = c.correlationId;
3484
+ write("debug", `[exios] \u26A1 ${fields.method} ${url} ${source} (${response.status})`, fields);
3485
+ }
3486
+ };
3487
+ }
3317
3488
 
3318
3489
  // src/index.ts
3319
3490
  registerXhrAdapter();
@@ -3327,7 +3498,8 @@ var statics = {
3327
3498
  isCancel,
3328
3499
  mergeConfig,
3329
3500
  toFormData,
3330
- MemoryCache
3501
+ MemoryCache,
3502
+ createLoggerPlugin
3331
3503
  };
3332
3504
  var exios = Object.assign(
3333
3505
  createInstance(createDefaults()),
@@ -27,6 +27,51 @@ function redactConfig(config) {
27
27
  if (c.data !== void 0) c.data = REDACTED;
28
28
  return c;
29
29
  }
30
+ var SENSITIVE_QUERY_PARAMS = /* @__PURE__ */ new Set([
31
+ "access_token",
32
+ "api_key",
33
+ "apikey",
34
+ "auth",
35
+ "client_secret",
36
+ "id_token",
37
+ "key",
38
+ "password",
39
+ "refresh_token",
40
+ "secret",
41
+ "sig",
42
+ "signature",
43
+ "token",
44
+ "awsaccesskeyid",
45
+ "x-amz-credential",
46
+ "x-amz-security-token",
47
+ "x-amz-signature",
48
+ "x-goog-credential",
49
+ "x-goog-signature"
50
+ ]);
51
+ function redactURL(url) {
52
+ const absolute = /^[a-z][a-z\d+\-.]*:\/\//i.test(url);
53
+ let u;
54
+ try {
55
+ u = absolute ? new URL(url) : new URL(url, "http://exios.invalid");
56
+ } catch {
57
+ const q2 = url.indexOf("?");
58
+ return q2 === -1 ? url : url.slice(0, q2);
59
+ }
60
+ u.username = "";
61
+ u.password = "";
62
+ let changed = false;
63
+ const params = new URLSearchParams(u.search);
64
+ for (const k of new Set(params.keys()))
65
+ if (SENSITIVE_QUERY_PARAMS.has(k.toLowerCase())) {
66
+ params.set(k, REDACTED);
67
+ changed = true;
68
+ }
69
+ if (changed) u.search = params.toString().replaceAll("%5BREDACTED%5D", REDACTED);
70
+ if (absolute) return u.href;
71
+ const q = url.indexOf("?");
72
+ const path = q === -1 ? url : url.slice(0, q);
73
+ return changed ? path + u.search : url;
74
+ }
30
75
 
31
76
  // src/errors/ExiosError.ts
32
77
  var ExiosError = class _ExiosError extends Error {
@@ -2507,7 +2552,7 @@ var InflightRequests = class {
2507
2552
  };
2508
2553
 
2509
2554
  // src/core/plugins.ts
2510
- var HOOKS = ["setup", "beforeRequest", "afterResponse", "onError"];
2555
+ var HOOKS = ["setup", "beforeRequest", "afterResponse", "onError", "onCancel"];
2511
2556
  function invalid(message) {
2512
2557
  throw new ExiosError(`ERR_BAD_OPTION_VALUE: ${message}`, ExiosError.ERR_BAD_OPTION_VALUE);
2513
2558
  }
@@ -2550,7 +2595,17 @@ var PluginRegistry = class {
2550
2595
  try {
2551
2596
  response = await layer(i + 1, c);
2552
2597
  } catch (err) {
2553
- if (!p.onError || isCancel(err)) throw err;
2598
+ if (isCancel(err)) {
2599
+ if (p.onCancel) {
2600
+ try {
2601
+ p.onCancel(err, c);
2602
+ } catch (hookErr) {
2603
+ report(p.name, hookErr);
2604
+ }
2605
+ }
2606
+ throw err;
2607
+ }
2608
+ if (!p.onError) throw err;
2554
2609
  const recovered = await p.onError(err, c);
2555
2610
  if (recovered == null) throw err;
2556
2611
  return recovered;
@@ -2560,6 +2615,9 @@ var PluginRegistry = class {
2560
2615
  return layer(0, config);
2561
2616
  }
2562
2617
  };
2618
+ function report(name, err) {
2619
+ if (typeof console !== "undefined") console.error(`[exios] plugin "${name}" onCancel failed:`, err);
2620
+ }
2563
2621
 
2564
2622
  // src/core/requestCache.ts
2565
2623
  var SAFE_METHODS = Object.freeze(["get", "head"]);
@@ -2610,7 +2668,21 @@ function hash(str) {
2610
2668
  h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507) ^ Math.imul(h1 ^ h1 >>> 13, 3266489909);
2611
2669
  return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(36);
2612
2670
  }
2613
- var CACHE_DIRECTIVE_HEADERS = /* @__PURE__ */ new Set(["cache-control", "pragma"]);
2671
+ var KEY_IGNORED_HEADERS = /* @__PURE__ */ new Set([
2672
+ "cache-control",
2673
+ "pragma",
2674
+ "traceparent",
2675
+ "tracestate",
2676
+ "baggage",
2677
+ "b3",
2678
+ "x-b3-traceid",
2679
+ "x-b3-spanid",
2680
+ "x-b3-parentspanid",
2681
+ "x-b3-sampled",
2682
+ "x-b3-flags",
2683
+ "uber-trace-id",
2684
+ "sentry-trace"
2685
+ ]);
2614
2686
  function requestTarget(config) {
2615
2687
  const url = buildURL(
2616
2688
  buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls),
@@ -2623,7 +2695,7 @@ function defaultRequestKey(config, scope = "cache") {
2623
2695
  const skip = config.correlationIdHeader?.toLowerCase();
2624
2696
  const parts = [];
2625
2697
  for (const k of Object.keys(config.headers).sort())
2626
- if (k !== skip && !CACHE_DIRECTIVE_HEADERS.has(k)) parts.push(`${k}:${config.headers[k]}`);
2698
+ if (k !== skip && !KEY_IGNORED_HEADERS.has(k)) parts.push(`${k}:${config.headers[k]}`);
2627
2699
  if (config.auth) parts.push(`auth:${config.auth.username}:${config.auth.password}`);
2628
2700
  parts.push(`rt:${config.responseType ?? ""}`);
2629
2701
  parts.push(
@@ -3277,7 +3349,106 @@ function createInstance(defaults) {
3277
3349
 
3278
3350
  // src/core/internals.ts
3279
3351
  var INTERNALS = /* @__PURE__ */ Symbol.for("@indra211/exios/internals");
3280
- var internals = { abortError, buildFullPath, finishResponse, prepareRequest };
3352
+ var internals = {
3353
+ abortError,
3354
+ buildFullPath,
3355
+ buildURL,
3356
+ createRequestId,
3357
+ finishResponse,
3358
+ prepareRequest,
3359
+ redactURL
3360
+ };
3361
+
3362
+ // src/core/logger.ts
3363
+ var RANK = { debug: 10, info: 20, warn: 30, error: 40, silent: 99 };
3364
+ function createLoggerPlugin(options = {}) {
3365
+ const min = RANK[options.level ?? "info"];
3366
+ if (min === void 0) throw new TypeError(`createLoggerPlugin: unknown level ${String(options.level)}`);
3367
+ const target = options.logger ?? (typeof console !== "undefined" ? console : void 0);
3368
+ const write = (level, message, fields) => {
3369
+ if (RANK[level] < min) return;
3370
+ if (options.log) return options.log(level, message, fields);
3371
+ const fn = target?.[level];
3372
+ if (typeof fn === "function") fn.call(target, message, fields);
3373
+ };
3374
+ const base = (e) => {
3375
+ const url = redactURL(e.url);
3376
+ const fields = {
3377
+ label: `${e.method.toUpperCase()} ${url}`,
3378
+ event: "request",
3379
+ requestId: e.requestId,
3380
+ method: e.method.toUpperCase(),
3381
+ url
3382
+ };
3383
+ if (e.correlationId !== void 0) fields.correlationId = e.correlationId;
3384
+ if (options.metadata && e.metadata) fields.metadata = e.metadata;
3385
+ return fields;
3386
+ };
3387
+ const entry = (level, msg, f) => {
3388
+ const { label, ...fields } = f;
3389
+ write(level, `[exios] ${msg(label)}`, fields);
3390
+ };
3391
+ return {
3392
+ name: options.name ?? "logger",
3393
+ setup(instance) {
3394
+ if (min === RANK.silent) return;
3395
+ const offs = [
3396
+ instance.on("request", (e) => {
3397
+ const f = base(e);
3398
+ if (options.headers) f.headers = redactHeaders(e.config.headers);
3399
+ entry("debug", (l) => `\u2192 ${l}`, f);
3400
+ }),
3401
+ instance.on("response", (e) => {
3402
+ const f = { ...base(e), event: "response", status: e.status, attempts: e.attempts, durationMs: e.durationMs };
3403
+ const retries = e.attempts > 1 ? `, ${e.attempts} attempts` : "";
3404
+ entry(e.status >= 400 ? "warn" : "info", (l) => `\u2190 ${e.status} ${l} (${e.durationMs}ms${retries})`, f);
3405
+ }),
3406
+ instance.on("retry", (e) => {
3407
+ const reason = e.status !== void 0 ? `status ${e.status}` : e.error?.code ?? "error";
3408
+ const f = { ...base(e), event: "retry", attempt: e.attempt, delayMs: e.delayMs };
3409
+ if (e.status !== void 0) f.status = e.status;
3410
+ if (e.error?.code) f.code = e.error.code;
3411
+ entry("warn", (l) => `\u21BB ${l} attempt ${e.attempt} failed (${reason}), retrying in ${e.delayMs}ms`, f);
3412
+ }),
3413
+ instance.on("timeout", (e) => {
3414
+ const f = { ...base(e), event: "timeout", attempt: e.attempt, timeoutMs: e.timeoutMs };
3415
+ if (e.error.code) f.code = e.error.code;
3416
+ entry("warn", (l) => `\u23F1 ${l} ${e.kind === "total" ? "total timeout" : "timeout"} of ${e.timeoutMs}ms`, f);
3417
+ }),
3418
+ instance.on("error", (e) => {
3419
+ const f = { ...base(e), event: "error", attempts: e.attempts, durationMs: e.durationMs };
3420
+ if (e.status !== void 0) f.status = e.status;
3421
+ if (e.code !== void 0) f.code = e.code;
3422
+ const what = e.status !== void 0 ? `${e.status}` : e.code ?? "failed";
3423
+ entry("error", (l) => `\u2715 ${l} ${what} (${e.durationMs}ms)`, f);
3424
+ }),
3425
+ instance.on("canceled", (e) => {
3426
+ entry("debug", (l) => `\u2298 ${l} canceled`, { ...base(e), event: "canceled", attempts: e.attempts, durationMs: e.durationMs });
3427
+ }),
3428
+ ...["circuitOpen", "circuitHalfOpen", "circuitClose"].map(
3429
+ (name) => instance.on(name, (e) => {
3430
+ const fields = { event: name, key: e.key, from: e.from, to: e.to };
3431
+ write(name === "circuitOpen" ? "warn" : "info", `[exios] circuit ${e.key} ${e.from} \u2192 ${e.to}`, fields);
3432
+ })
3433
+ )
3434
+ ];
3435
+ return () => {
3436
+ for (const off of offs) off();
3437
+ };
3438
+ },
3439
+ // Cache hits and deduplicated followers make no network request, so they emit no events.
3440
+ afterResponse(response, config) {
3441
+ const source = response.meta.cached ? "cached" : response.meta.deduped ? "deduped" : void 0;
3442
+ if (!source || RANK.debug < min) return;
3443
+ const c = response.config ?? config;
3444
+ const url = redactURL(buildFullPath(c.baseURL, c.url, c.allowAbsoluteUrls));
3445
+ const fields = { event: "cache", source, method: c.method.toUpperCase(), url, status: response.status };
3446
+ if (c.requestId !== void 0) fields.requestId = c.requestId;
3447
+ if (c.correlationId !== void 0) fields.correlationId = c.correlationId;
3448
+ write("debug", `[exios] \u26A1 ${fields.method} ${url} ${source} (${response.status})`, fields);
3449
+ }
3450
+ };
3451
+ }
3281
3452
 
3282
3453
  // src/index.ts
3283
3454
  registerXhrAdapter();
@@ -3291,7 +3462,8 @@ var statics = {
3291
3462
  isCancel,
3292
3463
  mergeConfig,
3293
3464
  toFormData,
3294
- MemoryCache
3465
+ MemoryCache,
3466
+ createLoggerPlugin
3295
3467
  };
3296
3468
  var exios = Object.assign(
3297
3469
  createInstance(createDefaults()),
@@ -3311,6 +3483,7 @@ export {
3311
3483
  ExiosError,
3312
3484
  MemoryCache,
3313
3485
  create,
3486
+ createLoggerPlugin,
3314
3487
  node_default as default,
3315
3488
  isCancel,
3316
3489
  isExiosError,
package/dist/otel.cjs ADDED
@@ -0,0 +1,199 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/otel/index.ts
31
+ var otel_exports = {};
32
+ __export(otel_exports, {
33
+ createOtelPlugin: () => createOtelPlugin
34
+ });
35
+ module.exports = __toCommonJS(otel_exports);
36
+ var import_exios = __toESM(require("@indra211/exios"), 1);
37
+
38
+ // src/core/internals.ts
39
+ var INTERNALS = /* @__PURE__ */ Symbol.for("@indra211/exios/internals");
40
+
41
+ // src/otel/index.ts
42
+ var core = import_exios.default[INTERNALS];
43
+ if (!core)
44
+ throw new Error("@indra211/exios/otel: the installed @indra211/exios is too old (needs 3.3.0 or newer)");
45
+ var { buildFullPath, buildURL, createRequestId, redactURL } = core;
46
+ var SPAN_KIND_CLIENT = 2;
47
+ var STATUS_ERROR = 2;
48
+ var KNOWN_METHODS = /* @__PURE__ */ new Set(["CONNECT", "DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT", "TRACE"]);
49
+ var DURATION_BUCKETS = [5e-3, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5, 7.5, 10];
50
+ var now = () => typeof performance !== "undefined" ? performance.now() : Date.now();
51
+ function createOtelPlugin(options) {
52
+ const api = options?.api;
53
+ if (!api?.trace || !api.context || !api.propagation)
54
+ throw new TypeError("createOtelPlugin: pass the @opentelemetry/api module as `api`");
55
+ const name = options.name ?? "@indra211/exios";
56
+ const tracer = api.trace.getTracer(name, options.version);
57
+ const histogram = options.metrics !== false && api.metrics ? api.metrics.getMeter(name, options.version).createHistogram("http.client.request.duration", {
58
+ description: "Duration of HTTP client requests.",
59
+ unit: "s",
60
+ advice: { explicitBucketBoundaries: DURATION_BUCKETS }
61
+ }) : void 0;
62
+ const shouldPropagate = propagationRule(options.propagate);
63
+ const byConfig = /* @__PURE__ */ new WeakMap();
64
+ const byId = /* @__PURE__ */ new Map();
65
+ const finish = (config, outcome) => {
66
+ const state = byConfig.get(config);
67
+ if (!state) return;
68
+ byConfig.delete(config);
69
+ if (config.requestId !== void 0 && byId.get(config.requestId) === state) byId.delete(config.requestId);
70
+ const { span } = state;
71
+ const status = outcome.response?.status ?? outcome.status;
72
+ let errorType = outcome.errorType;
73
+ if (errorType === void 0 && status !== void 0 && status >= 400) errorType = String(status);
74
+ const end = {};
75
+ if (status !== void 0) end["http.response.status_code"] = status;
76
+ if (errorType !== void 0) end["error.type"] = errorType;
77
+ const meta = outcome.response?.meta;
78
+ const attempts = meta?.attempts ?? outcome.attempts;
79
+ if (attempts !== void 0) {
80
+ end["exios.attempts"] = attempts;
81
+ if (attempts > 1) end["http.request.resend_count"] = attempts - 1;
82
+ }
83
+ if (meta?.cached) end["exios.cached"] = true;
84
+ if (meta?.deduped) end["exios.deduped"] = true;
85
+ try {
86
+ span.setAttributes(end);
87
+ if (outcome.error !== void 0) {
88
+ const err = outcome.error;
89
+ span.recordException(err instanceof Error ? err : String(err));
90
+ }
91
+ if (errorType !== void 0 && errorType !== "ERR_CANCELED") {
92
+ const message = outcome.error instanceof Error ? outcome.error.message : void 0;
93
+ span.setStatus(message === void 0 ? { code: STATUS_ERROR } : { code: STATUS_ERROR, message });
94
+ }
95
+ span.end();
96
+ histogram?.record((now() - state.start) / 1e3, {
97
+ ...state.common,
98
+ ...status !== void 0 ? { "http.response.status_code": status } : {},
99
+ ...errorType !== void 0 ? { "error.type": errorType } : {}
100
+ });
101
+ } catch (e) {
102
+ report(e);
103
+ }
104
+ };
105
+ return {
106
+ name: options.pluginName ?? "otel",
107
+ setup(instance) {
108
+ return instance.on("retry", (e) => {
109
+ const state = byId.get(e.requestId);
110
+ if (!state) return;
111
+ const attrs = { "exios.retry.attempt": e.attempt, "exios.retry.delay_ms": e.delayMs };
112
+ if (e.status !== void 0) attrs["http.response.status_code"] = e.status;
113
+ if (e.error?.code !== void 0) attrs["error.type"] = e.error.code;
114
+ state.span.addEvent("exios.retry", attrs);
115
+ });
116
+ },
117
+ beforeRequest(config) {
118
+ try {
119
+ config.requestId ??= createRequestId();
120
+ const url = buildURL(
121
+ buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls),
122
+ config.params,
123
+ config.paramsSerializer
124
+ );
125
+ const method = config.method.toUpperCase();
126
+ const common = { "http.request.method": KNOWN_METHODS.has(method) ? method : "_OTHER" };
127
+ const target = parseURL(url);
128
+ if (target) {
129
+ common["server.address"] = target.hostname.replace(/^\[|\]$/g, "");
130
+ common["server.port"] = Number(target.port) || (target.protocol === "https:" ? 443 : 80);
131
+ common["url.scheme"] = target.protocol.replace(/:$/, "");
132
+ }
133
+ const attributes = {
134
+ ...common,
135
+ "url.full": redactURL(target ? target.href : url),
136
+ "exios.request_id": config.requestId,
137
+ ...KNOWN_METHODS.has(method) ? {} : { "http.request.method_original": method },
138
+ ...options.attributes?.(config)
139
+ };
140
+ const parent = api.context.active();
141
+ const span = tracer.startSpan(options.spanName?.(config) ?? (KNOWN_METHODS.has(method) ? method : "HTTP"), { kind: SPAN_KIND_CLIENT, attributes }, parent);
142
+ const state = { span, start: now(), common };
143
+ byConfig.set(config, state);
144
+ byId.set(config.requestId, state);
145
+ if (shouldPropagate(target ? target.href : url, target)) {
146
+ const carrier = {};
147
+ api.propagation.inject(api.trace.setSpan(parent, span), carrier);
148
+ for (const [k, v] of Object.entries(carrier))
149
+ if (config.headers[k] === void 0) config.headers[k] = v;
150
+ }
151
+ } catch (e) {
152
+ report(e);
153
+ }
154
+ return config;
155
+ },
156
+ afterResponse(response, config) {
157
+ finish(config, { response });
158
+ },
159
+ onError(error, config) {
160
+ const e = error;
161
+ const status = e?.response?.status ?? e?.status;
162
+ const outcome = {
163
+ error,
164
+ // Semantic conventions: the status code when there was an error response, else the error kind.
165
+ errorType: status !== void 0 ? String(status) : e?.code ?? e?.name ?? "_OTHER"
166
+ };
167
+ if (status !== void 0) outcome.status = status;
168
+ if (e?.meta?.attempts !== void 0) outcome.attempts = e.meta.attempts;
169
+ finish(config, outcome);
170
+ },
171
+ onCancel(error, config) {
172
+ finish(config, { errorType: "ERR_CANCELED", attempts: error.meta.attempts });
173
+ }
174
+ };
175
+ }
176
+ function parseURL(url) {
177
+ try {
178
+ const base = typeof location !== "undefined" ? location.href : void 0;
179
+ return base === void 0 ? new URL(url) : new URL(url, base);
180
+ } catch {
181
+ return void 0;
182
+ }
183
+ }
184
+ function propagationRule(rule) {
185
+ if (rule === false) return () => false;
186
+ if (rule === true) return () => true;
187
+ if (typeof rule === "function") return rule;
188
+ if (rule instanceof RegExp)
189
+ return (url) => {
190
+ rule.lastIndex = 0;
191
+ return rule.test(url);
192
+ };
193
+ if (rule !== void 0) throw new TypeError("createOtelPlugin: propagate must be a boolean, a RegExp or a function");
194
+ if (typeof location === "undefined" || !location.origin || location.origin === "null") return () => true;
195
+ return (_url, target) => target?.origin === location.origin;
196
+ }
197
+ function report(err) {
198
+ if (typeof console !== "undefined") console.error("[exios] otel plugin failed:", err);
199
+ }