@sailfish-ai/sf-veritas 0.3.1 → 0.4.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.
Files changed (41) hide show
  1. package/README.md +35 -0
  2. package/dist/{contextManager-D2ijKL-E.js → contextManager-C2ONL8XY.js} +68 -61
  3. package/dist/contextManager-CL0Qs7uI.cjs +1 -0
  4. package/dist/plugins/funcspanEsbuildPlugin.cjs +1 -1
  5. package/dist/plugins/funcspanEsbuildPlugin.mjs +1 -1
  6. package/dist/plugins/funcspanRollupPlugin.cjs +1 -1
  7. package/dist/plugins/funcspanRollupPlugin.mjs +1 -1
  8. package/dist/plugins/funcspanTscPlugin.cjs +1 -1
  9. package/dist/plugins/funcspanTscPlugin.mjs +1 -1
  10. package/dist/plugins/funcspanVitePlugin.cjs +1 -1
  11. package/dist/plugins/funcspanVitePlugin.mjs +1 -1
  12. package/dist/plugins/funcspanWebpackPlugin.cjs +1 -1
  13. package/dist/plugins/funcspanWebpackPlugin.mjs +1 -1
  14. package/dist/runtimeConfig-BUJ13zxm.js +474 -0
  15. package/dist/runtimeConfig-xahsyRmN.cjs +5 -0
  16. package/dist/sf-veritas.cjs +13 -13
  17. package/dist/sf-veritas.mjs +1664 -575
  18. package/dist/types/constants.d.ts +13 -0
  19. package/dist/types/contextManager.d.ts +15 -0
  20. package/dist/types/index.d.ts +2 -0
  21. package/dist/types/patches/asyncQueues/_stubs/bee-queue.d.ts +10 -0
  22. package/dist/types/patches/asyncQueues/_stubs/rabbitmq.d.ts +11 -0
  23. package/dist/types/patches/asyncQueues/_stubs/sqs.d.ts +9 -0
  24. package/dist/types/patches/asyncQueues/asyncQueueTracer.d.ts +127 -0
  25. package/dist/types/patches/asyncQueues/asyncQueues.bench.d.ts +1 -0
  26. package/dist/types/patches/asyncQueues/bullmq.d.ts +27 -0
  27. package/dist/types/patches/asyncQueues/bullmqPro.d.ts +3 -0
  28. package/dist/types/patches/asyncQueues/confluentKafkaJs.d.ts +3 -0
  29. package/dist/types/patches/asyncQueues/index.d.ts +15 -0
  30. package/dist/types/patches/asyncQueues/kafkajs.d.ts +7 -0
  31. package/dist/types/requestTransmitter.d.ts +30 -0
  32. package/dist/types/setupConfig.d.ts +19 -0
  33. package/dist/types/urlMatch.d.ts +19 -0
  34. package/dist/worker-pool-capture.cjs +1 -1
  35. package/dist/worker-pool-capture.mjs +1 -1
  36. package/dist/{workerPoolSpanCapture-DzCJnMDA.cjs → workerPoolSpanCapture-C3T98kWy.cjs} +1 -1
  37. package/dist/{workerPoolSpanCapture-hyxgVqUF.js → workerPoolSpanCapture-DL8wfDIr.js} +1 -1
  38. package/package.json +2 -1
  39. package/dist/contextManager-BsolAr_q.cjs +0 -1
  40. package/dist/runtimeConfig-C4mv7SVM.js +0 -484
  41. package/dist/runtimeConfig-XIm4yAFB.cjs +0 -6
@@ -1,32 +1,33 @@
1
- var ve = Object.defineProperty;
2
- var $e = (r, t, e) => t in r ? ve(r, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : r[t] = e;
3
- var b = (r, t, e) => $e(r, typeof t != "symbol" ? t + "" : t, e);
4
- import { g as a, C as ee, D as be, v as J, b as T, c as _e, d as Fe, a as fe } from "./contextManager-D2ijKL-E.js";
5
- import { r as Nt } from "./contextManager-D2ijKL-E.js";
6
- import { B as k, n as C, f as De, g as Q, p as X, a as ge, b as Ne, m as L, c as x, i as ne, d as we, e as q, r as Ee, t as K, F as Pe } from "./workerPoolSpanCapture-hyxgVqUF.js";
7
- import { h as Et, s as Pt } from "./workerPoolSpanCapture-hyxgVqUF.js";
8
- import { a as Re, C as Ce, i as w, b as Te, c as he, d as Ue, e as ke } from "./runtimeConfig-C4mv7SVM.js";
9
- import { f as Ct, g as Tt, s as Ut } from "./runtimeConfig-C4mv7SVM.js";
10
- import { createRequire as Oe } from "node:module";
11
- import * as Le from "fs";
12
- import { readFileSync as qe, appendFileSync as Ae } from "fs";
13
- import U from "http";
14
- import A from "https";
15
- import { s as He } from "./source-map-Cr6YkjTd.js";
16
- import * as re from "fs/promises";
17
- import * as P from "path";
18
- import { glob as Me } from "glob";
19
- import { threadId as H } from "worker_threads";
20
- import { s as Ot, t as Lt, a as qt } from "./funcSpanTransformer-S_WeAt_m.js";
21
- class O extends k {
1
+ var St = Object.defineProperty;
2
+ var bt = (n, t, e) => t in n ? St(n, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : n[t] = e;
3
+ var D = (n, t, e) => bt(n, typeof t != "symbol" ? t + "" : t, e);
4
+ import { g as m, C as x, D as It, v as G, b as H, N as vt, c as Et, d as $t, a as nt } from "./contextManager-C2ONL8XY.js";
5
+ import { r as Mn } from "./contextManager-C2ONL8XY.js";
6
+ import { B as X, n as j, f as _t, g as Ie, p as ve, a as rt, b as wt, m as te, c as ie, i as Te, d as kt, e as ne, r as Ut, t as de, F as Dt } from "./workerPoolSpanCapture-DL8wfDIr.js";
7
+ import { h as xn, s as jn } from "./workerPoolSpanCapture-DL8wfDIr.js";
8
+ import { a as Nt, C as Pt, i as A, b as Ft, c as ot, d as qt, e as Ct } from "./runtimeConfig-BUJ13zxm.js";
9
+ import { f as Qn, g as Jn, s as Wn } from "./runtimeConfig-BUJ13zxm.js";
10
+ import { createRequire as Tt } from "node:module";
11
+ import * as At from "fs";
12
+ import { readFileSync as Bt, appendFileSync as Rt } from "fs";
13
+ import Q from "http";
14
+ import re from "https";
15
+ import { s as Lt } from "./source-map-Cr6YkjTd.js";
16
+ import * as Ae from "fs/promises";
17
+ import * as B from "path";
18
+ import { glob as Ot } from "glob";
19
+ import { AsyncLocalStorage as Mt } from "async_hooks";
20
+ import { threadId as oe } from "worker_threads";
21
+ import { s as zn, t as Vn, a as Xn } from "./funcSpanTransformer-S_WeAt_m.js";
22
+ class ee extends X {
22
23
  constructor() {
23
24
  super(), this.setOperationName("IdentifyServiceDetails");
24
25
  }
25
26
  async doSend(t) {
26
- if (!a().serviceIdentificationReceived) try {
27
+ if (!m().serviceIdentificationReceived) try {
27
28
  this.send();
28
29
  } catch (e) {
29
- a().sfDebug && console.error(" Error during service identification:", e);
30
+ m().sfDebug && console.error(" Error during service identification:", e);
30
31
  }
31
32
  }
32
33
  async send() {
@@ -68,37 +69,37 @@ class O extends k {
68
69
  serviceRole: $serviceRole,
69
70
  )
70
71
  }
71
- `, e = a(), i = this.getVariables({ serviceIdentifier: e.serviceIdentifier, serviceVersion: e.serviceVersion, library: e.packageLibraryType, version: e.version, serviceAdditionalMetadata: e.serviceAdditionalMetadata, gitSha: e.gitSha || "", gitOrg: e.gitOrg || void 0, gitRepo: e.gitRepo || void 0, gitProvider: e.gitProvider || void 0, serviceDisplayName: e.serviceDisplayName || void 0, framework: e.framework || void 0, additionalFrameworks: e.additionalFrameworks.length > 0 ? e.additionalFrameworks : void 0, serviceRole: e.serviceRole || void 0 });
72
- C(this.endpoint, this.operationName, t, i);
72
+ `, e = m(), o = this.getVariables({ serviceIdentifier: e.serviceIdentifier, serviceVersion: e.serviceVersion, library: e.packageLibraryType, version: e.version, serviceAdditionalMetadata: e.serviceAdditionalMetadata, gitSha: e.gitSha || "", gitOrg: e.gitOrg || void 0, gitRepo: e.gitRepo || void 0, gitProvider: e.gitProvider || void 0, serviceDisplayName: e.serviceDisplayName || void 0, framework: e.framework || void 0, additionalFrameworks: e.additionalFrameworks.length > 0 ? e.additionalFrameworks : void 0, serviceRole: e.serviceRole || void 0 });
73
+ j(this.endpoint, this.operationName, t, o);
73
74
  }
74
75
  }
75
- class xe extends k {
76
+ class Ht extends X {
76
77
  constructor() {
77
78
  super();
78
- b(this, "serviceIdentifier", new O());
79
- b(this, "identifyStarted", !1);
79
+ D(this, "serviceIdentifier", new ee());
80
+ D(this, "identifyStarted", !1);
80
81
  this.setOperationName("CollectMetadata");
81
82
  }
82
83
  startBackgroundIdentify() {
83
84
  if (this.identifyStarted) return;
84
85
  this.identifyStarted = !0, this.serviceIdentifier.doSend({});
85
86
  const e = setInterval(() => {
86
- a().serviceIdentificationReceived ? clearInterval(e) : this.serviceIdentifier.doSend({});
87
+ m().serviceIdentificationReceived ? clearInterval(e) : this.serviceIdentifier.doSend({});
87
88
  }, 5e3);
88
89
  e && typeof e == "object" && "unref" in e && e.unref();
89
90
  }
90
- async doSend(e, i, n, s) {
91
- this.startBackgroundIdentify(), this.send(e, i, n, s);
91
+ async doSend(e, o, r, i) {
92
+ this.startBackgroundIdentify(), this.send(e, o, r, i);
92
93
  }
93
- async send(e, i, n, s) {
94
- if (!i && !s) throw new Error('Must pass in either traits or traits_json to "add_or_update_traits"');
95
- let l = [];
96
- if (!s) {
97
- const o = Re(i);
98
- s = o.traitsJson, l = o.excludedFields;
94
+ async send(e, o, r, i) {
95
+ if (!o && !i) throw new Error('Must pass in either traits or traits_json to "add_or_update_traits"');
96
+ let d = [];
97
+ if (!i) {
98
+ const a = Nt(o);
99
+ i = a.traitsJson, d = a.excludedFields;
99
100
  }
100
- const c = this.getVariables({ userId: e, traitsJson: s, excludedFields: l, override: n, library: a().packageLibraryType, version: a().version });
101
- C(this.endpoint, this.operationName, this.getQuery(), c);
101
+ const l = this.getVariables({ userId: e, traitsJson: i, excludedFields: d, override: r, library: m().packageLibraryType, version: m().version });
102
+ j(this.endpoint, this.operationName, this.getQuery(), l);
102
103
  }
103
104
  getQuery() {
104
105
  return `
@@ -108,30 +109,30 @@ class xe extends k {
108
109
  `;
109
110
  }
110
111
  }
111
- class me {
112
+ class st {
112
113
  constructor(t) {
113
- b(this, "metadataTransmitter");
114
- this.apiKey = t, this.metadataTransmitter = new xe();
114
+ D(this, "metadataTransmitter");
115
+ this.apiKey = t, this.metadataTransmitter = new Ht();
115
116
  }
116
- identify(t, e, i, n = !1) {
117
- e || i ? this.addOrUpdateMetadata(t, e, i, n) : this.addOrUpdateMetadata(t, {}, void 0, n);
117
+ identify(t, e, o, r = !1) {
118
+ e || o ? this.addOrUpdateMetadata(t, e, o, r) : this.addOrUpdateMetadata(t, {}, void 0, r);
118
119
  }
119
- addOrUpdateMetadata(t, e = {}, i, n = !1) {
120
- if (!e && !i) throw new Error('Must pass in either traits or traitsJson to "addOrUpdateMetadata"');
121
- a().sfDebug && console.log(" [[DEBUG - addOrUpdateMetadata]] Starting operation"), a().sfDebug && console.log(" addOrUpdateMetadata...SENDING DATA...", t, e, i), this.metadataTransmitter.doSend(t, e, n, i);
120
+ addOrUpdateMetadata(t, e = {}, o, r = !1) {
121
+ if (!e && !o) throw new Error('Must pass in either traits or traitsJson to "addOrUpdateMetadata"');
122
+ m().sfDebug && console.log(" [[DEBUG - addOrUpdateMetadata]] Starting operation"), m().sfDebug && console.log(" addOrUpdateMetadata...SENDING DATA...", t, e, o), this.metadataTransmitter.doSend(t, e, r, o);
122
123
  }
123
124
  }
124
- class te extends k {
125
+ class Ce extends X {
125
126
  constructor() {
126
127
  super();
127
- b(this, "serviceIdentifier", new O());
128
- b(this, "identifyStarted", !1);
128
+ D(this, "serviceIdentifier", new ee());
129
+ D(this, "identifyStarted", !1);
129
130
  }
130
131
  startBackgroundIdentify() {
131
132
  if (this.identifyStarted) return;
132
133
  this.identifyStarted = !0, this.serviceIdentifier.doSend({});
133
134
  const e = setInterval(() => {
134
- a().serviceIdentificationReceived ? clearInterval(e) : this.serviceIdentifier.doSend({});
135
+ m().serviceIdentificationReceived ? clearInterval(e) : this.serviceIdentifier.doSend({});
135
136
  }, 5e3);
136
137
  e && typeof e == "object" && "unref" in e && e.unref();
137
138
  }
@@ -140,10 +141,10 @@ class te extends k {
140
141
  }
141
142
  async send(e) {
142
143
  try {
143
- const i = Array.isArray(e) ? e : [e, "default", null, null], n = this.getVariables({ contents: i[0], level: i[1], sourceFile: i[2] || void 0, sourceLine: i[3] || void 0 });
144
- C(this.endpoint, this.operationName, this.getQuery(), n);
145
- } catch (i) {
146
- a().sfDebug && console.error("🚨 Error in send():", i);
144
+ const o = Array.isArray(e) ? e : [e, "default", null, null], r = this.getVariables({ contents: o[0], level: o[1], sourceFile: o[2] || void 0, sourceLine: o[3] || void 0 });
145
+ j(this.endpoint, this.operationName, this.getQuery(), r);
146
+ } catch (o) {
147
+ m().sfDebug && console.error("🚨 Error in send():", o);
147
148
  }
148
149
  }
149
150
  getQuery() {
@@ -174,36 +175,36 @@ class te extends k {
174
175
  `;
175
176
  }
176
177
  }
177
- class Be extends k {
178
+ class xt extends X {
178
179
  constructor() {
179
180
  super();
180
- b(this, "serviceIdentifier", new O());
181
- b(this, "supplementalFields", {});
182
- b(this, "identifyStarted", !1);
181
+ D(this, "serviceIdentifier", new ee());
182
+ D(this, "supplementalFields", {});
183
+ D(this, "identifyStarted", !1);
183
184
  this.setOperationName("CollectExceptions");
184
185
  }
185
186
  setSupplementalFields(e) {
186
187
  this.supplementalFields = { ...this.supplementalFields, ...e };
187
188
  }
188
189
  normalizedSupplementalForGraphQL() {
189
- const { isFromLocalService: e } = this.supplementalFields, i = {};
190
- return e !== void 0 && (i.isFromLocalService = e), i;
190
+ const { isFromLocalService: e } = this.supplementalFields, o = {};
191
+ return e !== void 0 && (o.isFromLocalService = e), o;
191
192
  }
192
193
  startBackgroundIdentify() {
193
194
  if (this.identifyStarted) return;
194
195
  this.identifyStarted = !0, this.serviceIdentifier.doSend({});
195
196
  const e = setInterval(() => {
196
- a().serviceIdentificationReceived ? clearInterval(e) : this.serviceIdentifier.doSend({});
197
+ m().serviceIdentificationReceived ? clearInterval(e) : this.serviceIdentifier.doSend({});
197
198
  }, 5e3);
198
199
  e && typeof e == "object" && "unref" in e && e.unref();
199
200
  }
200
- async doSend(e, i) {
201
- this.startBackgroundIdentify(), this.send(e, i);
201
+ async doSend(e, o) {
202
+ this.startBackgroundIdentify(), this.send(e, o);
202
203
  }
203
- async send(e, i) {
204
- a().sfDebug && console.log(" SENDING EXCEPTION...");
205
- const n = JSON.stringify(Ce.encode(i)), s = this.normalizedSupplementalForGraphQL(), l = this.getVariables({ exceptionMessage: e, traceJson: n, reentrancyGuardPreactive: !1, library: a().packageLibraryType, version: a().version, ...s });
206
- C(this.endpoint, this.operationName, this.getQuery(), l);
204
+ async send(e, o) {
205
+ m().sfDebug && console.log(" SENDING EXCEPTION...");
206
+ const r = JSON.stringify(Pt.encode(o)), i = this.normalizedSupplementalForGraphQL(), d = this.getVariables({ exceptionMessage: e, traceJson: r, reentrancyGuardPreactive: !1, library: m().packageLibraryType, version: m().version, ...i });
207
+ j(this.endpoint, this.operationName, this.getQuery(), d);
207
208
  }
208
209
  getQuery() {
209
210
  return `
@@ -237,51 +238,82 @@ class Be extends k {
237
238
  `;
238
239
  }
239
240
  }
240
- const ie = "getting request source code";
241
- var B = ((r) => (r.UNKNOWN = "unknown", r.ANONYMOUS = "anonymous", r.NOT_CAPTURED = "not captured", r))(B || {});
242
- const se = "http:", Ge = Oe(import.meta.url);
243
- let oe = !1;
244
- function Ke() {
245
- const r = a().sfDebug;
246
- if (oe) return void (r && w("[patchNodeHttpInbound] Already installed, skipping."));
241
+ const Y = "X-Sf3-Rid", Be = "X-Sf4-Prid", Re = "getting request source code";
242
+ var ae = ((n) => (n.UNKNOWN = "unknown", n.ANONYMOUS = "anonymous", n.NOT_CAPTURED = "not captured", n))(ae || {});
243
+ const Le = "http:", jt = Tt(import.meta.url);
244
+ let Oe = !1;
245
+ function Kt() {
246
+ const n = m().sfDebug;
247
+ if (Oe) return void (n && A("[patchNodeHttpInbound] Already installed, skipping."));
247
248
  let t;
248
- oe = !0;
249
+ Oe = !0;
249
250
  try {
250
- t = Ge("node:http"), r && w("[patchNodeHttpInbound] node:http required successfully.");
251
- } catch (n) {
252
- return void Te("Failed to require node:http:", n);
253
- }
254
- if (!t?.Server?.prototype) return void (r && w("[patchNodeHttpInbound] http.Server.prototype not found."));
255
- const e = t.Server.prototype, i = e.emit;
256
- i && !e.__sf_inbound_patched__ ? (Object.defineProperty(e, "__sf_inbound_patched__", { value: !0, enumerable: !1, configurable: !1, writable: !1 }), r && w("[patchNodeHttpInbound] Patching http.Server.prototype.emit."), e.emit = function(n, ...s) {
257
- if (n !== "request") return r && w(`[patchNodeHttpInbound] Passing through event: ${n}`), i.call(this, n, ...s);
258
- const l = s[0], c = s[1], o = (function(S) {
259
- const h = {};
260
- if (!S) return h;
261
- for (const [f, I] of Object.entries(S)) I != null && (Array.isArray(I) ? h[f.toLowerCase()] = I.join(", ") : h[f.toLowerCase()] = String(I));
262
- return h;
263
- })(l?.headers), d = o["x-sf3-rid"], p = o["x-sf3-functionspancaptureoverride"];
264
- r && (w("[patchNodeHttpInbound] Intercepted request event."), w("[patchNodeHttpInbound] Inbound headers:", o), w("[patchNodeHttpInbound] Trace header:", d), w("[patchNodeHttpInbound] FuncSpan override header:", p));
265
- const u = ee.getInstance();
266
- u.setTraceId(d);
267
- const y = u.getTraceId();
268
- r && w("[patchNodeHttpInbound] Context traceId set:", y);
269
- const $ = () => u.runWith({ inboundHeaders: o, ...d ? { traceId: d } : {} }, () => {
270
- d && u.setTraceId(d), r && w("[patchNodeHttpInbound] Running request handler in context.");
271
- const S = () => {
272
- r && w("[patchNodeHttpInbound] Response finished/closed for traceId:", u.getTraceId());
251
+ t = jt("node:http"), n && A("[patchNodeHttpInbound] node:http required successfully.");
252
+ } catch (r) {
253
+ return void Ft("Failed to require node:http:", r);
254
+ }
255
+ if (!t?.Server?.prototype) return void (n && A("[patchNodeHttpInbound] http.Server.prototype not found."));
256
+ const e = t.Server.prototype, o = e.emit;
257
+ o && !e.__sf_inbound_patched__ ? (Object.defineProperty(e, "__sf_inbound_patched__", { value: !0, enumerable: !1, configurable: !1, writable: !1 }), n && A("[patchNodeHttpInbound] Patching http.Server.prototype.emit."), e.emit = function(r, ...i) {
258
+ if (r !== "request") return n && A(`[patchNodeHttpInbound] Passing through event: ${r}`), o.call(this, r, ...i);
259
+ const d = i[0], l = i[1], a = (function(g) {
260
+ const f = {};
261
+ if (!g) return f;
262
+ for (const [y, S] of Object.entries(g)) S != null && (Array.isArray(S) ? f[y.toLowerCase()] = S.join(", ") : f[y.toLowerCase()] = String(S));
263
+ return f;
264
+ })(d?.headers), s = a["x-sf3-rid"], u = a["x-sf3-functionspancaptureoverride"];
265
+ n && (A("[patchNodeHttpInbound] Intercepted request event."), A("[patchNodeHttpInbound] Inbound headers:", a), A("[patchNodeHttpInbound] Trace header:", s), A("[patchNodeHttpInbound] FuncSpan override header:", u));
266
+ const c = x.getInstance();
267
+ c.setTraceId(s);
268
+ const p = c.getTraceId();
269
+ n && A("[patchNodeHttpInbound] Context traceId set:", p);
270
+ const h = () => c.runWith({ inboundHeaders: a, ...s ? { traceId: s } : {} }, () => {
271
+ s && c.setTraceId(s), n && A("[patchNodeHttpInbound] Running request handler in context.");
272
+ const g = () => {
273
+ n && A("[patchNodeHttpInbound] Response finished/closed for traceId:", c.getTraceId());
273
274
  };
274
- return c.on("finish", S), c.on("close", S), i.call(this, n, l, c);
275
+ return l.on("finish", g), l.on("close", g), o.call(this, r, d, l);
275
276
  });
276
- if (!p) return $();
277
+ if (!u) return h();
277
278
  try {
278
- return De.run(p, () => $());
279
+ return _t.run(u, () => h());
279
280
  } catch {
280
- return $();
281
+ return h();
281
282
  }
282
- }) : r && w("[patchNodeHttpInbound] Already patched, skipping.");
283
+ }) : n && A("[patchNodeHttpInbound] Already patched, skipping.");
283
284
  }
284
- class We extends te {
285
+ const Me = /* @__PURE__ */ new Map();
286
+ function pe(n, t) {
287
+ const e = `${n}|${t}`;
288
+ let o = Me.get(e);
289
+ return o || (o = new RegExp(n, t), Me.set(e, o)), o;
290
+ }
291
+ function fe(n, t) {
292
+ let e, o;
293
+ if (typeof n == "string" ? e = n : typeof URL < "u" && n instanceof URL ? e = n.href : typeof Request < "u" && n instanceof Request ? e = n.url : n != null && typeof n.toString == "function" && (e = n.toString()), !e) return !1;
294
+ try {
295
+ o = new URL(e, "http://localhost/");
296
+ } catch {
297
+ return !1;
298
+ }
299
+ const { hostname: r, pathname: i, port: d, protocol: l } = o;
300
+ if (!/^https?:$/.test(l)) return !1;
301
+ const a = r.startsWith("www.") ? r.slice(4).toLowerCase() : r.toLowerCase();
302
+ return t.some((s) => {
303
+ const u = String(s || "").replace(/^[a-zA-Z]+:\/\//, "");
304
+ if (!u) return !1;
305
+ let [c, p] = u.split("/", 2), h = "";
306
+ c.includes(":") && ([c, h] = c.split(":"));
307
+ const g = pe(`^${c.replace(/\./g, "\\.").replace(/\*/g, ".*")}$`, "i"), f = a.startsWith("www.") ? a.slice(4) : a;
308
+ if (h && d !== h) return !1;
309
+ if (c.startsWith("*.")) {
310
+ const y = c.slice(2).toLowerCase();
311
+ return a === y || f === y || a.endsWith("." + y) ? p ? pe(`^/${p.replace(/\*/g, ".*").replace(/\/$/, "")}`, "i").test(i) : !0 : !1;
312
+ }
313
+ return !g.test(f) && !g.test(a) ? !1 : p ? pe(`^/${p.replace(/\*/g, ".*").replace(/\/$/, "")}`, "i").test(i) : !0;
314
+ });
315
+ }
316
+ class Qt extends Ce {
285
317
  constructor() {
286
318
  super(), this.setOperationName("DomainsToNotPassHeaderTo");
287
319
  }
@@ -301,22 +333,22 @@ class We extends te {
301
333
  domains: $domains
302
334
  )
303
335
  }
304
- `, i = { apiKey: this.apiKey, serviceUuid: this.serviceUUID, domains: t };
305
- C(this.endpoint, this.operationName, e, i);
336
+ `, o = { apiKey: this.apiKey, serviceUuid: this.serviceUUID, domains: t };
337
+ j(this.endpoint, this.operationName, e, o);
306
338
  }
307
339
  }
308
- class je extends k {
340
+ class Jt extends X {
309
341
  constructor() {
310
342
  super();
311
- b(this, "serviceIdentifier", new O());
312
- b(this, "identifyStarted", !1);
343
+ D(this, "serviceIdentifier", new ee());
344
+ D(this, "identifyStarted", !1);
313
345
  this.setOperationName("CollectNetworkHops");
314
346
  }
315
347
  startBackgroundIdentify() {
316
348
  if (this.identifyStarted) return;
317
349
  this.identifyStarted = !0, this.serviceIdentifier.doSend({});
318
350
  const e = setInterval(() => {
319
- a().serviceIdentificationReceived ? clearInterval(e) : this.serviceIdentifier.doSend({});
351
+ m().serviceIdentificationReceived ? clearInterval(e) : this.serviceIdentifier.doSend({});
320
352
  }, 5e3);
321
353
  e && typeof e == "object" && "unref" in e && e.unref();
322
354
  }
@@ -324,8 +356,8 @@ class je extends k {
324
356
  this.startBackgroundIdentify(), this.send(e);
325
357
  }
326
358
  async send(e) {
327
- const { name: i, column: n, line: s, entrypoint: l, retryWithoutTraceId: c } = e, o = this.getVariables({ name: i, column: n, line: s, entrypoint: l, retryWithoutTraceId: c });
328
- C(this.endpoint, this.operationName, this.getQuery(), o);
359
+ const { name: o, column: r, line: i, entrypoint: d, retryWithoutTraceId: l } = e, a = this.getVariables({ name: o, column: r, line: i, entrypoint: d, retryWithoutTraceId: l });
360
+ j(this.endpoint, this.operationName, this.getQuery(), a);
329
361
  }
330
362
  getQuery() {
331
363
  return `
@@ -355,18 +387,18 @@ class je extends k {
355
387
  `;
356
388
  }
357
389
  }
358
- class Ve extends k {
390
+ class it extends X {
359
391
  constructor() {
360
392
  super();
361
- b(this, "serviceIdentifier", new O());
362
- b(this, "identifyStarted", !1);
393
+ D(this, "serviceIdentifier", new ee());
394
+ D(this, "identifyStarted", !1);
363
395
  this.setOperationName("CollectNetworkRequest");
364
396
  }
365
397
  startBackgroundIdentify() {
366
398
  if (this.identifyStarted) return;
367
399
  this.identifyStarted = !0, this.serviceIdentifier.doSend({});
368
400
  const e = setInterval(() => {
369
- a().serviceIdentificationReceived ? clearInterval(e) : this.serviceIdentifier.doSend({});
401
+ m().serviceIdentificationReceived ? clearInterval(e) : this.serviceIdentifier.doSend({});
370
402
  }, 5e3);
371
403
  e && typeof e == "object" && "unref" in e && e.unref();
372
404
  }
@@ -384,328 +416,349 @@ class Ve extends k {
384
416
  `;
385
417
  }
386
418
  async send(e) {
387
- const i = { data: { ...e } };
388
- await C(this.endpoint, this.operationName, this.getQuery(), i);
419
+ const o = { data: { ...e } };
420
+ await j(this.endpoint, this.operationName, this.getQuery(), o);
389
421
  }
390
422
  }
391
- const W = [400, 403];
392
- function j(r, t) {
393
- return t !== "none" && (t === "all" || r === "GET" || r === "HEAD" || r === "OPTIONS");
423
+ const he = [400, 403];
424
+ function ye(n, t) {
425
+ return t !== "none" && (t === "all" || n === "GET" || n === "HEAD" || n === "OPTIONS");
394
426
  }
395
- class ze {
427
+ class Wt {
396
428
  constructor(t = []) {
397
- b(this, "HEADER_TRACING", "X-Sf3-Rid");
398
- b(this, "HEADER_LOG_GUARD", "reentrancy_guard_logging_preactive");
399
- b(this, "HEADER_PRINT_GUARD", "reentrancy_guard_print_preactive");
400
- b(this, "HEADER_EXCEPTION_GUARD", "reentrancy_guard_exception_preactive");
401
- b(this, "contextManager");
402
- this.contextManager = ee.getInstance(), t?.forEach((e) => {
429
+ D(this, "HEADER_TRACING", "X-Sf3-Rid");
430
+ D(this, "HEADER_LOG_GUARD", "reentrancy_guard_logging_preactive");
431
+ D(this, "HEADER_PRINT_GUARD", "reentrancy_guard_print_preactive");
432
+ D(this, "HEADER_EXCEPTION_GUARD", "reentrancy_guard_exception_preactive");
433
+ D(this, "contextManager");
434
+ this.contextManager = x.getInstance(), t?.forEach((e) => {
403
435
  typeof e == "string" && e.trim() && this.contextManager.getExcludedDomains().add(e);
404
- }), a().sfDebug && console.log("[RequestInterceptor] Initialized with static excluded domains.");
436
+ }), m().sfDebug && console.log("[RequestInterceptor] Initialized with static excluded domains.");
405
437
  }
406
438
  extractIdsFromTraceHeader(t, e = this.HEADER_TRACING) {
407
- let i;
408
- if (t instanceof Headers) i = t.get(e) ?? void 0;
439
+ let o;
440
+ if (t instanceof Headers) o = t.get(e) ?? void 0;
409
441
  else {
410
- const s = e.toLowerCase();
411
- for (const [l, c] of Object.entries(t)) if (l.toLowerCase() === s) {
412
- i = c;
442
+ const i = e.toLowerCase();
443
+ for (const [d, l] of Object.entries(t)) if (d.toLowerCase() === i) {
444
+ o = l;
413
445
  break;
414
446
  }
415
447
  }
416
- if (!i) return {};
417
- const n = i.split("/").filter(Boolean);
418
- return n.length < 3 ? {} : { sessionId: n[0], pageVisitId: n[1], requestId: n[n.length - 1] };
448
+ if (!o) return {};
449
+ const r = o.split("/").filter(Boolean);
450
+ return r.length < 3 ? {} : { sessionId: r[0], pageVisitId: r[1], requestId: r[r.length - 1] };
419
451
  }
420
452
  parseStackFrame(t) {
421
453
  const e = /\((.*):(\d+):(\d+)\)$/.exec(t.trim());
422
454
  if (!e) return null;
423
- const [, i, n, s] = e;
424
- return { filePath: i, line: parseInt(n, 10), column: parseInt(s, 10) };
455
+ const [, o, r, i] = e;
456
+ return { filePath: o, line: parseInt(r, 10), column: parseInt(i, 10) };
425
457
  }
426
- async getOriginalPosition(t, e, i) {
427
- let n = { source: t, line: e, column: i, name: null };
428
- if (t.includes("://")) return { originalPos: n };
429
- const s = t + ".map";
458
+ async getOriginalPosition(t, e, o) {
459
+ let r = { source: t, line: e, column: o, name: null };
460
+ if (t.includes("://")) return { originalPos: r };
461
+ const i = t + ".map";
430
462
  try {
431
- const l = JSON.parse(qe(s, "utf-8"));
432
- let c = (await new He.SourceMapConsumer(l)).originalPositionFor({ line: e, column: i });
433
- c.source && (n = c);
434
- } catch (l) {
435
- a().sfDebug && console.error(`Could not read/parse map file at ${s}:`, l);
463
+ const d = JSON.parse(Bt(i, "utf-8"));
464
+ let l = (await new Lt.SourceMapConsumer(d)).originalPositionFor({ line: e, column: o });
465
+ l.source && (r = l);
466
+ } catch (d) {
467
+ m().sfDebug && console.error(`Could not read/parse map file at ${i}:`, d);
436
468
  }
437
- return { originalPos: n };
438
- }
439
- captureFirstUserLines(t, e = 10, i = !1) {
440
- const n = a().sfDebug ? 10 : e, s = Error.stackTraceLimit;
441
- Error.stackTraceLimit = Math.max(s, n);
442
- const l = new Error(ie);
443
- ie in Error && Error.captureStackTrace(l, this.captureFirstUserLines);
444
- const c = he(l.stack);
445
- Error.stackTraceLimit = s;
446
- const o = c.split(`
447
- `).slice(1), d = [];
448
- for (const p of o)
449
- if (!(p.includes("node:internal") || p.includes("internal/modules") || p.includes("internal/process") || p.includes("node_modules") || p.includes(".next/server/chunks") || p.includes("RequestInterceptor") || p.includes("contextManager") || p.includes("setupConfig")) && (d.push(p.trim()), d.length >= e)) break;
450
- for (const p of d) {
451
- const u = this.parseStackFrame(p);
452
- u ? (async () => {
453
- const { originalPos: y } = await this.getOriginalPosition(u.filePath, u.line, u.column);
454
- if (y) {
455
- a().sfDebug && console.log("[RequestInterceptor] First user code line:", y);
456
- const $ = { line: y.line?.toString() || B.UNKNOWN, column: y.column?.toString() || B.NOT_CAPTURED, name: y.name || B.NOT_CAPTURED, entrypoint: y.source, retryWithoutTraceId: i };
457
- t.doSend($);
469
+ return { originalPos: r };
470
+ }
471
+ captureFirstUserLines(t, e = 10, o = !1) {
472
+ const r = m().sfDebug ? 10 : e, i = Error.stackTraceLimit;
473
+ Error.stackTraceLimit = Math.max(i, r);
474
+ const d = new Error(Re);
475
+ Re in Error && Error.captureStackTrace(d, this.captureFirstUserLines);
476
+ const l = ot(d.stack);
477
+ Error.stackTraceLimit = i;
478
+ const a = l.split(`
479
+ `).slice(1), s = [];
480
+ for (const u of a)
481
+ if (!(u.includes("node:internal") || u.includes("internal/modules") || u.includes("internal/process") || u.includes("node_modules") || u.includes(".next/server/chunks") || u.includes("RequestInterceptor") || u.includes("contextManager") || u.includes("setupConfig")) && (s.push(u.trim()), s.length >= e)) break;
482
+ for (const u of s) {
483
+ const c = this.parseStackFrame(u);
484
+ c ? (async () => {
485
+ const { originalPos: p } = await this.getOriginalPosition(c.filePath, c.line, c.column);
486
+ if (p) {
487
+ m().sfDebug && console.log("[RequestInterceptor] First user code line:", p);
488
+ const h = { line: p.line?.toString() || ae.UNKNOWN, column: p.column?.toString() || ae.NOT_CAPTURED, name: p.name || ae.NOT_CAPTURED, entrypoint: p.source, retryWithoutTraceId: o };
489
+ t.doSend(h);
458
490
  }
459
- })() : a().sfDebug && console.error("Could not parse stack line:", p);
491
+ })() : m().sfDebug && console.error("Could not parse stack line:", u);
460
492
  }
461
493
  }
462
494
  addReentrancyGuardHeaders(t) {
463
495
  t.set(this.HEADER_LOG_GUARD, "true"), t.set(this.HEADER_PRINT_GUARD, "true"), t.set(this.HEADER_EXCEPTION_GUARD, "true");
464
496
  }
465
497
  shouldPropagateHeaders(t) {
466
- return !be.some((e) => new RegExp(`^${e.replace(/\*/g, ".*")}$`).test(t));
498
+ const e = m(), o = e.domainsToPropagateHeadersTo, r = e.domainsToNotPropagateHeadersTo || [], i = Array.from(It);
499
+ return !!fe(t, o) && !(r.length > 0 && fe(t, r)) && !fe(t, i);
467
500
  }
468
501
  addTracingHeaders(t, e) {
469
- const i = new URL(e).hostname, n = this.shouldPropagateHeaders(i);
470
- return n ? this.addTracingHeader(t, e) : a().sfDebug && console.error(`[RequestInterceptor] Excluded domain: ${i}`), n;
502
+ const o = this.shouldPropagateHeaders(e);
503
+ if (o) this.addTracingHeader(t, e);
504
+ else if (m().sfDebug) {
505
+ let r = e;
506
+ try {
507
+ r = new URL(e).hostname;
508
+ } catch {
509
+ }
510
+ console.error(`[RequestInterceptor] Excluded domain: ${r}`);
511
+ }
512
+ return o;
513
+ }
514
+ deriveTraceBaseAndParent(t) {
515
+ const e = t.split("/").filter(Boolean);
516
+ return e.length < 2 ? { base: t, parent: t } : { base: `${e[0]}/${e[1]}`, parent: t };
471
517
  }
472
518
  addTracingHeader(t, e) {
473
- const i = Q();
474
- if (i) {
475
- const c = X(i);
476
- if (c && c.sample_rate === 0) return void (a().sfDebug && console.log(`[RequestInterceptor] Function span tracking disabled (sample_rate=0), skipping tracing header for ${e}`));
519
+ const o = Ie();
520
+ if (o) {
521
+ const a = ve(o);
522
+ if (a && a.sample_rate === 0) return void (m().sfDebug && console.log(`[RequestInterceptor] Function span tracking disabled (sample_rate=0), skipping tracing header for ${e}`));
477
523
  }
478
- const n = this.contextManager.getOrSetSfTraceId(), s = this.contextManager.getOrSetPageVisitUUID(), l = J();
479
- t.set(this.HEADER_TRACING, `${n}/${s}/${l}`), a().sfDebug && console.log(`[RequestInterceptor] Added tracing header for ${e}`);
524
+ const r = this.contextManager.getOrSetSfTraceId(), { base: i, parent: d } = this.deriveTraceBaseAndParent(r), l = G();
525
+ t.set(this.HEADER_TRACING, `${i}/${l}`), t.set(Be, d), m().sfDebug && console.log(`[RequestInterceptor] Added tracing header for ${e}`);
480
526
  }
481
527
  patchFetch(t, e) {
482
- const i = globalThis.fetch;
483
- typeof i == "function" ? globalThis.fetch = async (n, s) => {
484
- const l = new Headers(s?.headers);
485
- if (l.get(this.HEADER_LOG_GUARD) === "true" || l.get(this.HEADER_PRINT_GUARD) === "true" || l.get(this.HEADER_EXCEPTION_GUARD) === "true") return i(n, s);
528
+ const o = globalThis.fetch;
529
+ typeof o == "function" ? globalThis.fetch = async (r, i) => {
530
+ const d = new Headers(i?.headers);
531
+ if (d.get(this.HEADER_LOG_GUARD) === "true" || d.get(this.HEADER_PRINT_GUARD) === "true" || d.get(this.HEADER_EXCEPTION_GUARD) === "true") return o(r, i);
486
532
  this.captureFirstUserLines(t);
487
- const c = Date.now();
488
- let o, d = "GET";
489
- if (typeof n == "string" || n instanceof URL) o = n.toString(), d = (s?.method || "GET").toUpperCase();
533
+ const l = Date.now();
534
+ let a, s = "GET";
535
+ if (typeof r == "string" || r instanceof URL) a = r.toString(), s = (i?.method || "GET").toUpperCase();
490
536
  else {
491
- if (!(n instanceof Request)) return a().sfDebug && console.error("[Sailfish RequestInterceptor] Invalid fetch input."), i(n, s);
492
- o = n.url, d = n.method.toUpperCase(), n.headers.forEach((g, D) => {
493
- l.set(D, g);
537
+ if (!(r instanceof Request)) return m().sfDebug && console.error("[Sailfish RequestInterceptor] Invalid fetch input."), o(r, i);
538
+ a = r.url, s = r.method.toUpperCase(), r.headers.forEach((I, v) => {
539
+ d.set(v, I);
494
540
  });
495
541
  }
496
- a().sfDebug && console.log("[RequestInterceptor] Fetching request to:", o);
497
- let p = "unknown";
542
+ m().sfDebug && console.log("[RequestInterceptor] Fetching request to:", a);
543
+ let u = "unknown";
498
544
  try {
499
- p = new URL(o).hostname;
545
+ u = new URL(a).hostname;
500
546
  } catch {
501
- return a().sfDebug && console.warn(`[RequestInterceptor] Could not parse URL '${o}' — passing through without tracing headers.`), i(n, s);
547
+ return m().sfDebug && console.warn(`[RequestInterceptor] Could not parse URL '${a}' — passing through without tracing headers.`), o(r, i);
502
548
  }
503
- const u = new Headers(l), y = this.addTracingHeaders(l, o), $ = (g) => n instanceof Request ? [new Request(n, { ...s || {}, headers: g }), void 0] : [o, { ...s, headers: g }], S = a().retryOnClientError;
504
- let h, f = !1;
549
+ const c = new Headers(d), p = this.addTracingHeaders(d, a), h = (I) => r instanceof Request ? [new Request(r, { ...i || {}, headers: I }), void 0] : [a, { ...i, headers: I }], g = m().retryOnClientError;
550
+ let f, y = !1;
505
551
  try {
506
- const [g, D] = $(l);
507
- if (h = await i(g, D), y && j(d, S) && W.includes(h.status)) {
508
- const [v, _] = $(u);
509
- h = await i(v, _), f = !0;
552
+ const [I, v] = h(d);
553
+ if (f = await o(I, v), p && ye(s, g) && he.includes(f.status)) {
554
+ const [_, E] = h(c);
555
+ f = await o(_, E), y = !0;
510
556
  try {
511
- this.captureFirstUserLines(t, 10, f);
512
- } catch (F) {
513
- a().sfDebug && console.error("[RequestInterceptor] captureFirstUserLines (retry) failed:", F);
557
+ this.captureFirstUserLines(t, 10, y);
558
+ } catch (k) {
559
+ m().sfDebug && console.error("[RequestInterceptor] captureFirstUserLines (retry) failed:", k);
514
560
  }
515
561
  } else try {
516
- this.contextManager.addSupportedDomains(p);
517
- } catch (v) {
518
- a().sfDebug && console.error("[RequestInterceptor] addSupportedDomains failed:", v);
562
+ this.contextManager.addSupportedDomains(u);
563
+ } catch (_) {
564
+ m().sfDebug && console.error("[RequestInterceptor] addSupportedDomains failed:", _);
519
565
  }
520
- } catch (g) {
521
- const D = Date.now();
522
- a().sfDebug && console.error(`[RequestInterceptor] Fetch failed: ${o}, Error: ${g}, Duration: ${D - c}ms`);
566
+ } catch (I) {
567
+ const v = Date.now();
568
+ m().sfDebug && console.error(`[RequestInterceptor] Fetch failed: ${a}, Error: ${I}, Duration: ${v - l}ms`);
523
569
  try {
524
- const { sessionId: v, pageVisitId: _, requestId: F } = this.extractIdsFromTraceHeader(l), R = a();
525
- e.doSend({ apiKey: R.apiKey, requestId: F, pageVisitId: _, recordingSessionId: v, serviceUuid: R.serviceUUID, timestampStart: c.toString(), timestampEnd: D.toString(), responseCode: 0, success: !1, error: g instanceof Error ? g.message : typeof g == "string" ? g : JSON.stringify(g), url: o, method: d, retryWithoutTraceId: f, parentSpanId: T() });
526
- } catch (v) {
527
- a().sfDebug && console.error("[RequestInterceptor] Error telemetry send failed:", v);
570
+ const { sessionId: _, pageVisitId: E, requestId: k } = this.extractIdsFromTraceHeader(d), q = m();
571
+ e.doSend({ apiKey: q.apiKey, requestId: k, pageVisitId: E, recordingSessionId: _, serviceUuid: q.serviceUUID, timestampStart: l.toString(), timestampEnd: v.toString(), responseCode: 0, success: !1, error: I instanceof Error ? I.message : typeof I == "string" ? I : JSON.stringify(I), url: a, method: s, retryWithoutTraceId: y, parentSpanId: H() });
572
+ } catch (_) {
573
+ m().sfDebug && console.error("[RequestInterceptor] Error telemetry send failed:", _);
528
574
  }
529
- throw g;
575
+ throw I;
530
576
  }
531
- const I = Date.now();
577
+ const S = Date.now();
532
578
  try {
533
- a().sfDebug && console.log(`[RequestInterceptor] Fetch completed: ${o}, Status: ${h.status}, Duration: ${I - c}ms`);
534
- const { sessionId: g, pageVisitId: D, requestId: v } = this.extractIdsFromTraceHeader(l), _ = a(), F = { apiKey: _.apiKey, requestId: v, pageVisitId: D, recordingSessionId: g, serviceUuid: _.serviceUUID, timestampStart: c.toString(), timestampEnd: I.toString(), responseCode: h.status, success: !0, error: null, url: o, method: d, retryWithoutTraceId: f, parentSpanId: T() };
535
- if (_.captureRequestHeaders) {
536
- const m = {};
537
- l.forEach((E, N) => {
538
- m[N] = E;
539
- }), F.requestHeaders = m;
579
+ m().sfDebug && console.log(`[RequestInterceptor] Fetch completed: ${a}, Status: ${f.status}, Duration: ${S - l}ms`);
580
+ const { sessionId: I, pageVisitId: v, requestId: _ } = this.extractIdsFromTraceHeader(d), E = m(), k = { apiKey: E.apiKey, requestId: _, pageVisitId: v, recordingSessionId: I, serviceUuid: E.serviceUUID, timestampStart: l.toString(), timestampEnd: S.toString(), responseCode: f.status, success: !0, error: null, url: a, method: s, retryWithoutTraceId: y, parentSpanId: H() };
581
+ if (E.captureRequestHeaders) {
582
+ const $ = {};
583
+ d.forEach((F, N) => {
584
+ $[N] = F;
585
+ }), k.requestHeaders = $;
540
586
  }
541
- if (_.captureResponseHeaders) {
542
- const m = {};
543
- h.headers.forEach((E, N) => {
544
- m[N] = E;
545
- }), F.responseHeaders = m;
587
+ if (E.captureResponseHeaders) {
588
+ const $ = {};
589
+ f.headers.forEach((F, N) => {
590
+ $[N] = F;
591
+ }), k.responseHeaders = $;
546
592
  }
547
- if (_.captureRequestBody && s?.body) {
548
- const m = s.body, E = _.requestBodyLimitBytes;
593
+ if (E.captureRequestBody && i?.body) {
594
+ const $ = i.body, F = E.requestBodyLimitBytes;
549
595
  try {
550
- if (typeof m == "string") F.requestBody = m.length > E ? m.substring(0, E) + "...[truncated]" : m;
551
- else if (m instanceof URLSearchParams) {
552
- const N = m.toString();
553
- F.requestBody = N.length > E ? N.substring(0, E) + "...[truncated]" : N;
554
- } else if (typeof ArrayBuffer < "u" && (m instanceof ArrayBuffer || ArrayBuffer.isView(m))) {
555
- const N = m.byteLength ?? m.byteLength;
556
- F.requestBody = `[binary body, ${N} bytes — not captured]`;
557
- } else if (typeof Blob < "u" && m instanceof Blob) F.requestBody = `[Blob, ${m.size} bytes, type=${m.type || "unknown"} — not captured]`;
558
- else if (typeof FormData < "u" && m instanceof FormData) F.requestBody = "[FormData — not captured]";
559
- else if (typeof ReadableStream < "u" && m instanceof ReadableStream) F.requestBody = "[ReadableStream — not captured]";
596
+ if (typeof $ == "string") k.requestBody = $.length > F ? $.substring(0, F) + "...[truncated]" : $;
597
+ else if ($ instanceof URLSearchParams) {
598
+ const N = $.toString();
599
+ k.requestBody = N.length > F ? N.substring(0, F) + "...[truncated]" : N;
600
+ } else if (typeof ArrayBuffer < "u" && ($ instanceof ArrayBuffer || ArrayBuffer.isView($))) {
601
+ const N = $.byteLength ?? $.byteLength;
602
+ k.requestBody = `[binary body, ${N} bytes — not captured]`;
603
+ } else if (typeof Blob < "u" && $ instanceof Blob) k.requestBody = `[Blob, ${$.size} bytes, type=${$.type || "unknown"} — not captured]`;
604
+ else if (typeof FormData < "u" && $ instanceof FormData) k.requestBody = "[FormData — not captured]";
605
+ else if (typeof ReadableStream < "u" && $ instanceof ReadableStream) k.requestBody = "[ReadableStream — not captured]";
560
606
  else {
561
- const N = JSON.stringify(m);
562
- N && N !== "{}" && (F.requestBody = N.length > E ? N.substring(0, E) + "...[truncated]" : N);
607
+ const N = JSON.stringify($);
608
+ N && N !== "{}" && (k.requestBody = N.length > F ? N.substring(0, F) + "...[truncated]" : N);
563
609
  }
564
610
  } catch {
565
611
  }
566
612
  }
567
- let R;
568
- if (_.captureResponseBody) {
569
- const m = (h.headers.get("content-type") || "").toLowerCase();
570
- if (!m || m.includes("json") || m.includes("xml") || m.includes("text/") || m.includes("javascript") || m.includes("ecmascript") || m.includes("x-www-form-urlencoded") || m.includes("application/graphql")) {
571
- const E = h.clone(), N = _.responseBodyLimitBytes;
572
- R = (async () => {
613
+ let q;
614
+ if (E.captureResponseBody) {
615
+ const $ = (f.headers.get("content-type") || "").toLowerCase();
616
+ if (!$ || $.includes("json") || $.includes("xml") || $.includes("text/") || $.includes("javascript") || $.includes("ecmascript") || $.includes("x-www-form-urlencoded") || $.includes("application/graphql")) {
617
+ const F = f.clone(), N = E.responseBodyLimitBytes;
618
+ q = (async () => {
573
619
  try {
574
- const G = await E.text(), Ie = G.length > N ? G.substring(0, N) + "...[truncated]" : G;
620
+ const M = await F.text(), K = M.length > N ? M.substring(0, N) + "...[truncated]" : M;
575
621
  try {
576
- e.doSend({ ...F, responseBody: Ie });
622
+ e.doSend({ ...k, responseBody: K });
577
623
  } catch {
578
624
  }
579
625
  } catch {
580
626
  }
581
- })(), R.catch(() => {
627
+ })(), q.catch(() => {
582
628
  });
583
- } else F.responseBody = `[non-text body, content-type=${m} — not captured]`;
629
+ } else k.responseBody = `[non-text body, content-type=${$} — not captured]`;
584
630
  }
585
- R || e.doSend(F);
586
- } catch (g) {
587
- a().sfDebug && console.error("[RequestInterceptor] Post-fetch telemetry failed (response still returned):", g);
631
+ q || e.doSend(k);
632
+ } catch (I) {
633
+ m().sfDebug && console.error("[RequestInterceptor] Post-fetch telemetry failed (response still returned):", I);
588
634
  }
589
- return h;
590
- } : a().sfDebug && console.error("[RequestInterceptor] Fetch not available.");
635
+ return f;
636
+ } : m().sfDebug && console.error("[RequestInterceptor] Fetch not available.");
591
637
  }
592
- setHeader(t, e, i) {
593
- t instanceof Headers ? t.set(e, i) : t[e] = i;
638
+ setHeader(t, e, o) {
639
+ t instanceof Headers ? t.set(e, o) : t[e] = o;
594
640
  }
595
641
  addTracingHeadersToPlainObject(t, e) {
596
- const i = new URL(e).hostname, n = this.shouldPropagateHeaders(i);
597
- if (n) {
598
- const s = Q();
599
- if (s) {
600
- const d = X(s);
601
- if (d && d.sample_rate === 0) return a().sfDebug && console.log(`[RequestInterceptor] Function span tracking disabled (sample_rate=0), skipping tracing header for ${e}`), !1;
642
+ const o = this.shouldPropagateHeaders(e);
643
+ if (o) {
644
+ const r = Ie();
645
+ if (r) {
646
+ const s = ve(r);
647
+ if (s && s.sample_rate === 0) return m().sfDebug && console.log(`[RequestInterceptor] Function span tracking disabled (sample_rate=0), skipping tracing header for ${e}`), !1;
602
648
  }
603
- const l = this.contextManager.getOrSetSfTraceId(), c = this.contextManager.getOrSetPageVisitUUID(), o = J();
604
- t[this.HEADER_TRACING] = `${l}/${c}/${o}`, a().sfDebug && console.log(`[RequestInterceptor] Added tracing header for ${e}`);
605
- } else a().sfDebug && console.error(`[RequestInterceptor] Excluded domain: ${i}`);
606
- return n;
649
+ const i = this.contextManager.getOrSetSfTraceId(), { base: d, parent: l } = this.deriveTraceBaseAndParent(i), a = G();
650
+ t[this.HEADER_TRACING] = `${d}/${a}`, t[Be] = l, m().sfDebug && console.log(`[RequestInterceptor] Added tracing header for ${e}`);
651
+ } else if (m().sfDebug) {
652
+ let r = e;
653
+ try {
654
+ r = new URL(e).hostname;
655
+ } catch {
656
+ }
657
+ console.error(`[RequestInterceptor] Excluded domain: ${r}`);
658
+ }
659
+ return o;
607
660
  }
608
661
  patchHttp(t, e) {
609
- if (a().sfDebug && console.log("[RequestInterceptor] Initializing HTTP/HTTPS request patch..."), !U || typeof U.request != "function") return void (a().sfDebug && console.log("[RequestInterceptor] HTTP/HTTPS not available."));
610
- const i = U.request.bind(U), n = A.request.bind(A), s = (o, d, p, u = se) => {
611
- let y, $;
612
- if (typeof o == "string" || o instanceof URL) {
613
- const S = typeof o == "string" ? new URL(o) : o;
614
- y = { ...typeof d == "object" && d !== null ? d : {}, protocol: S.protocol || u, hostname: S.hostname, port: S.port || void 0, path: S.pathname + S.search }, $ = typeof d == "function" ? d : p;
615
- } else y = { ...o }, y.protocol || (y.protocol = u), $ = typeof d == "function" ? d : void 0;
616
- return y.headers || (y.headers = {}), [y, $];
617
- }, l = (o, d, p) => {
618
- const [u, y] = s(o, d, p, se);
662
+ if (m().sfDebug && console.log("[RequestInterceptor] Initializing HTTP/HTTPS request patch..."), !Q || typeof Q.request != "function") return void (m().sfDebug && console.log("[RequestInterceptor] HTTP/HTTPS not available."));
663
+ const o = Q.request.bind(Q), r = re.request.bind(re), i = (a, s, u, c = Le) => {
664
+ let p, h;
665
+ if (typeof a == "string" || a instanceof URL) {
666
+ const g = typeof a == "string" ? new URL(a) : a;
667
+ p = { ...typeof s == "object" && s !== null ? s : {}, protocol: g.protocol || c, hostname: g.hostname, port: g.port || void 0, path: g.pathname + g.search }, h = typeof s == "function" ? s : u;
668
+ } else p = { ...a }, p.protocol || (p.protocol = c), h = typeof s == "function" ? s : void 0;
669
+ return p.headers || (p.headers = {}), [p, h];
670
+ }, d = (a, s, u) => {
671
+ const [c, p] = i(a, s, u, Le);
619
672
  try {
620
- const f = `${u.protocol}//${u.hostname}`;
621
- this.addTracingHeadersToPlainObject(u.headers, f), this.captureFirstUserLines(t);
622
- } catch (f) {
623
- a().sfDebug && console.error("[RequestInterceptor] Error while processing HTTP request options:", f);
673
+ const y = `${c.protocol}//${c.hostname}`;
674
+ this.addTracingHeadersToPlainObject(c.headers, y), this.captureFirstUserLines(t);
675
+ } catch (y) {
676
+ m().sfDebug && console.error("[RequestInterceptor] Error while processing HTTP request options:", y);
624
677
  }
625
- const $ = (u.method || "GET").toUpperCase(), S = a().retryOnClientError, h = (f, I, g) => {
678
+ const h = (c.method || "GET").toUpperCase(), g = m().retryOnClientError, f = (y, S, I) => {
626
679
  try {
627
- const { sessionId: D, pageVisitId: v, requestId: _ } = this.extractIdsFromTraceHeader(u.headers);
628
- e.doSend({ apiKey: a().apiKey, requestId: _, pageVisitId: v, recordingSessionId: D, serviceUuid: a().serviceUUID, timestampStart: Date.now().toString(), timestampEnd: Date.now().toString(), responseCode: f.statusCode || 0, success: !!f.statusCode && f.statusCode < 400, error: null, url: I, method: $, retryWithoutTraceId: g, parentSpanId: T() });
680
+ const { sessionId: v, pageVisitId: _, requestId: E } = this.extractIdsFromTraceHeader(c.headers);
681
+ e.doSend({ apiKey: m().apiKey, requestId: E, pageVisitId: _, recordingSessionId: v, serviceUuid: m().serviceUUID, timestampStart: Date.now().toString(), timestampEnd: Date.now().toString(), responseCode: y.statusCode || 0, success: !!y.statusCode && y.statusCode < 400, error: null, url: S, method: h, retryWithoutTraceId: I, parentSpanId: H() });
629
682
  } catch {
630
683
  }
631
- y?.(f);
684
+ p?.(y);
632
685
  };
633
- return i(u, (f) => {
634
- const I = `${u.protocol}//${u.hostname}`;
635
- let g = !1;
686
+ return o(c, (y) => {
687
+ const S = `${c.protocol}//${c.hostname}`;
688
+ let I = !1;
636
689
  try {
637
- g = this.shouldPropagateHeaders(new URL(I).hostname);
690
+ I = this.shouldPropagateHeaders(S);
638
691
  } catch {
639
- g = !1;
692
+ I = !1;
640
693
  }
641
- if (g && j($, S) && W.includes(f.statusCode || 0)) {
642
- f.resume();
694
+ if (I && ye(h, g) && he.includes(y.statusCode || 0)) {
695
+ y.resume();
643
696
  try {
644
- const { sessionId: v, pageVisitId: _, requestId: F } = this.extractIdsFromTraceHeader(u.headers);
645
- e.doSend({ apiKey: a().apiKey, requestId: F, pageVisitId: _, recordingSessionId: v, serviceUuid: a().serviceUUID, timestampStart: Date.now().toString(), timestampEnd: Date.now().toString(), responseCode: f.statusCode || 0, success: !1, error: null, url: I, method: $, retryWithoutTraceId: !1, parentSpanId: T() });
697
+ const { sessionId: _, pageVisitId: E, requestId: k } = this.extractIdsFromTraceHeader(c.headers);
698
+ e.doSend({ apiKey: m().apiKey, requestId: k, pageVisitId: E, recordingSessionId: _, serviceUuid: m().serviceUUID, timestampStart: Date.now().toString(), timestampEnd: Date.now().toString(), responseCode: y.statusCode || 0, success: !1, error: null, url: S, method: h, retryWithoutTraceId: !1, parentSpanId: H() });
646
699
  } catch {
647
700
  }
648
701
  try {
649
702
  this.captureFirstUserLines(t, 10, !0);
650
703
  } catch {
651
704
  }
652
- const D = { ...u, headers: { ...u.headers } };
653
- return delete D.headers[this.HEADER_TRACING], void i(D, (v) => {
654
- h(v, I, !0);
705
+ const v = { ...c, headers: { ...c.headers } };
706
+ return delete v.headers[this.HEADER_TRACING], void o(v, (_) => {
707
+ f(_, S, !0);
655
708
  }).end();
656
709
  }
657
- h(f, I, !1);
710
+ f(y, S, !1);
658
711
  });
659
- }, c = (o, d, p) => {
660
- const [u, y] = s(o, d, p, "https:");
712
+ }, l = (a, s, u) => {
713
+ const [c, p] = i(a, s, u, "https:");
661
714
  try {
662
- const f = `${u.protocol}//${u.hostname}`;
663
- this.addTracingHeadersToPlainObject(u.headers, f), this.captureFirstUserLines(t);
664
- } catch (f) {
665
- a().sfDebug && console.error("[RequestInterceptor] Error while processing HTTPS request options:", f);
715
+ const y = `${c.protocol}//${c.hostname}`;
716
+ this.addTracingHeadersToPlainObject(c.headers, y), this.captureFirstUserLines(t);
717
+ } catch (y) {
718
+ m().sfDebug && console.error("[RequestInterceptor] Error while processing HTTPS request options:", y);
666
719
  }
667
- const $ = (u.method || "GET").toUpperCase(), S = a().retryOnClientError, h = (f, I, g) => {
720
+ const h = (c.method || "GET").toUpperCase(), g = m().retryOnClientError, f = (y, S, I) => {
668
721
  try {
669
- const { sessionId: D, pageVisitId: v, requestId: _ } = this.extractIdsFromTraceHeader(u.headers);
670
- e.doSend({ apiKey: a().apiKey, requestId: _, pageVisitId: v, recordingSessionId: D, serviceUuid: a().serviceUUID, timestampStart: Date.now().toString(), timestampEnd: Date.now().toString(), responseCode: f.statusCode || 0, success: !!f.statusCode && f.statusCode < 400, error: null, url: I, method: $, retryWithoutTraceId: g, parentSpanId: T() });
722
+ const { sessionId: v, pageVisitId: _, requestId: E } = this.extractIdsFromTraceHeader(c.headers);
723
+ e.doSend({ apiKey: m().apiKey, requestId: E, pageVisitId: _, recordingSessionId: v, serviceUuid: m().serviceUUID, timestampStart: Date.now().toString(), timestampEnd: Date.now().toString(), responseCode: y.statusCode || 0, success: !!y.statusCode && y.statusCode < 400, error: null, url: S, method: h, retryWithoutTraceId: I, parentSpanId: H() });
671
724
  } catch {
672
725
  }
673
- y?.(f);
726
+ p?.(y);
674
727
  };
675
- return n(u, (f) => {
676
- const I = `${u.protocol}//${u.hostname}`;
677
- let g = !1;
728
+ return r(c, (y) => {
729
+ const S = `${c.protocol}//${c.hostname}`;
730
+ let I = !1;
678
731
  try {
679
- g = this.shouldPropagateHeaders(new URL(I).hostname);
732
+ I = this.shouldPropagateHeaders(S);
680
733
  } catch {
681
- g = !1;
734
+ I = !1;
682
735
  }
683
- if (g && j($, S) && W.includes(f.statusCode || 0)) {
684
- f.resume();
736
+ if (I && ye(h, g) && he.includes(y.statusCode || 0)) {
737
+ y.resume();
685
738
  try {
686
- const { sessionId: v, pageVisitId: _, requestId: F } = this.extractIdsFromTraceHeader(u.headers);
687
- e.doSend({ apiKey: a().apiKey, requestId: F, pageVisitId: _, recordingSessionId: v, serviceUuid: a().serviceUUID, timestampStart: Date.now().toString(), timestampEnd: Date.now().toString(), responseCode: f.statusCode || 0, success: !1, error: null, url: I, method: $, retryWithoutTraceId: !1, parentSpanId: T() });
739
+ const { sessionId: _, pageVisitId: E, requestId: k } = this.extractIdsFromTraceHeader(c.headers);
740
+ e.doSend({ apiKey: m().apiKey, requestId: k, pageVisitId: E, recordingSessionId: _, serviceUuid: m().serviceUUID, timestampStart: Date.now().toString(), timestampEnd: Date.now().toString(), responseCode: y.statusCode || 0, success: !1, error: null, url: S, method: h, retryWithoutTraceId: !1, parentSpanId: H() });
688
741
  } catch {
689
742
  }
690
743
  try {
691
744
  this.captureFirstUserLines(t, 10, !0);
692
745
  } catch {
693
746
  }
694
- const D = { ...u, headers: { ...u.headers } };
695
- return delete D.headers[this.HEADER_TRACING], void n(D, (v) => {
696
- h(v, I, !0);
747
+ const v = { ...c, headers: { ...c.headers } };
748
+ return delete v.headers[this.HEADER_TRACING], void r(v, (_) => {
749
+ f(_, S, !0);
697
750
  }).end();
698
751
  }
699
- h(f, I, !1);
752
+ f(y, S, !1);
700
753
  });
701
754
  };
702
- U.request = l, A.request = c, U.get = (o, d, p) => {
703
- const u = l(o, d, p);
704
- return u.end(), u;
705
- }, A.get = (o, d, p) => {
706
- const u = c(o, d, p);
707
- return u.end(), u;
708
- }, a().sfDebug && console.log("✅ HTTP and HTTPS request/get methods patched globally.");
755
+ Q.request = d, re.request = l, Q.get = (a, s, u) => {
756
+ const c = d(a, s, u);
757
+ return c.end(), c;
758
+ }, re.get = (a, s, u) => {
759
+ const c = l(a, s, u);
760
+ return c.end(), c;
761
+ }, m().sfDebug && console.log("✅ HTTP and HTTPS request/get methods patched globally.");
709
762
  }
710
763
  tryPatch(t, e) {
711
764
  try {
@@ -717,7 +770,7 @@ class ze {
717
770
  return [...this.contextManager.getExcludedDomains()];
718
771
  }
719
772
  }
720
- class Je extends te {
773
+ class Gt extends Ce {
721
774
  constructor() {
722
775
  super(), this.setOperationName("UpdateServiceDetails");
723
776
  }
@@ -767,386 +820,1422 @@ class Je extends te {
767
820
  serviceRole: $serviceRole,
768
821
  )
769
822
  }
770
- `, e = a(), i = this.getVariables({ serviceIdentifier: e.serviceIdentifier, serviceVersion: e.serviceVersion, serviceAdditionalMetadata: e.serviceAdditionalMetadata, gitSha: e.gitSha || "", gitOrg: e.gitOrg || void 0, gitRepo: e.gitRepo || void 0, gitProvider: e.gitProvider || void 0, serviceDisplayName: e.serviceDisplayName || void 0, infrastructureType: e.infrastructureType || void 0, infrastructureDetails: e.infrastructureDetails || void 0, setupInterceptorsFile: e.setupInterceptorsFile || void 0, setupInterceptorsLine: e.setupInterceptorsLine || void 0, framework: e.framework || void 0, additionalFrameworks: e.additionalFrameworks?.length > 0 ? e.additionalFrameworks : void 0, serviceRole: e.serviceRole || void 0 });
771
- C(this.endpoint, this.operationName, t, i);
823
+ `, e = m(), o = this.getVariables({ serviceIdentifier: e.serviceIdentifier, serviceVersion: e.serviceVersion, serviceAdditionalMetadata: e.serviceAdditionalMetadata, gitSha: e.gitSha || "", gitOrg: e.gitOrg || void 0, gitRepo: e.gitRepo || void 0, gitProvider: e.gitProvider || void 0, serviceDisplayName: e.serviceDisplayName || void 0, infrastructureType: e.infrastructureType || void 0, infrastructureDetails: e.infrastructureDetails || void 0, setupInterceptorsFile: e.setupInterceptorsFile || void 0, setupInterceptorsLine: e.setupInterceptorsLine || void 0, framework: e.framework || void 0, additionalFrameworks: e.additionalFrameworks?.length > 0 ? e.additionalFrameworks : void 0, serviceRole: e.serviceRole || void 0 });
824
+ j(this.endpoint, this.operationName, t, o);
772
825
  }
773
826
  }
774
- class Qe {
827
+ class zt {
775
828
  constructor(t = [process.cwd()], e = !1) {
776
- b(this, "rootPaths");
777
- b(this, "fileConfigs", /* @__PURE__ */ new Map());
778
- b(this, "functionConfigs", /* @__PURE__ */ new Map());
779
- b(this, "directoryConfigs", /* @__PURE__ */ new Map());
780
- b(this, "hasSailfishFiles", !1);
781
- b(this, "runtimeModeEnabled", !1);
782
- b(this, "debug");
829
+ D(this, "rootPaths");
830
+ D(this, "fileConfigs", /* @__PURE__ */ new Map());
831
+ D(this, "functionConfigs", /* @__PURE__ */ new Map());
832
+ D(this, "directoryConfigs", /* @__PURE__ */ new Map());
833
+ D(this, "hasSailfishFiles", !1);
834
+ D(this, "runtimeModeEnabled", !1);
835
+ D(this, "debug");
783
836
  this.rootPaths = t, this.debug = e || process.env.SF_DEBUG === "true";
784
837
  }
785
838
  async loadAllConfigs() {
786
839
  this.debug && console.log("[FuncSpan ConfigLoader] Scanning for .sailfish files in:", this.rootPaths);
787
840
  const t = [];
788
- for (const e of this.rootPaths) Le.existsSync(e) ? await this._walkDirectory(e, t) : this.debug && console.log(`[FuncSpan ConfigLoader] Root path does not exist: ${e}`);
841
+ for (const e of this.rootPaths) At.existsSync(e) ? await this._walkDirectory(e, t) : this.debug && console.log(`[FuncSpan ConfigLoader] Root path does not exist: ${e}`);
789
842
  t.length > 0 ? (this.hasSailfishFiles = !0, this.debug && (console.log(`[FuncSpan ConfigLoader] Found ${t.length} .sailfish files:`), t.forEach((e) => console.log(`[FuncSpan ConfigLoader] - ${e}`)))) : this.debug && console.log("[FuncSpan ConfigLoader] No .sailfish files found - function spans disabled by default");
790
843
  for (const e of t) await this._loadConfigFile(e);
791
844
  await this._resolveInheritance(), this.debug && console.log(`[FuncSpan ConfigLoader] Loaded ${this.fileConfigs.size} file configs, ${this.functionConfigs.size} function configs`);
792
845
  }
793
846
  getConfig(t, e) {
794
- const i = this.hasSailfishFiles ? Ne() : ge(), n = this._getDirectoryConfig(t), s = P.normalize(t), l = this.fileConfigs.get(s) || {};
795
- let c = {};
847
+ const o = this.hasSailfishFiles ? wt() : rt(), r = this._getDirectoryConfig(t), i = B.normalize(t), d = this.fileConfigs.get(i) || {};
848
+ let l = {};
796
849
  if (e) {
797
- const o = this.functionConfigs.get(s);
798
- o && (c = o.get(e) || {});
850
+ const a = this.functionConfigs.get(i);
851
+ a && (l = a.get(e) || {});
799
852
  }
800
- return L(i, n, l, c);
853
+ return te(o, r, d, l);
801
854
  }
802
855
  hasRuntimeMode() {
803
856
  return this.runtimeModeEnabled;
804
857
  }
805
858
  async _walkDirectory(t, e) {
806
859
  try {
807
- const i = await re.readdir(t, { withFileTypes: !0 });
808
- for (const n of i) {
809
- const s = P.join(t, n.name);
810
- n.isFile() && n.name === ".sailfish" ? e.push(s) : n.name === "node_modules" || n.isDirectory() && n.name.startsWith(".") && n.name !== ".sailfish" || n.isDirectory() && await this._walkDirectory(s, e);
860
+ const o = await Ae.readdir(t, { withFileTypes: !0 });
861
+ for (const r of o) {
862
+ const i = B.join(t, r.name);
863
+ r.isFile() && r.name === ".sailfish" ? e.push(i) : r.name === "node_modules" || r.isDirectory() && r.name.startsWith(".") && r.name !== ".sailfish" || r.isDirectory() && await this._walkDirectory(i, e);
811
864
  }
812
- } catch (i) {
813
- this.debug && console.error(`[FuncSpan ConfigLoader] Error walking directory ${t}:`, i);
865
+ } catch (o) {
866
+ this.debug && console.error(`[FuncSpan ConfigLoader] Error walking directory ${t}:`, o);
814
867
  }
815
868
  }
816
869
  async _loadConfigFile(t) {
817
870
  try {
818
- const e = await re.readFile(t, "utf-8"), i = P.dirname(t);
819
- let n = null;
871
+ const e = await Ae.readFile(t, "utf-8"), o = B.dirname(t);
872
+ let r = null;
820
873
  try {
821
- n = JSON.parse(e);
874
+ r = JSON.parse(e);
822
875
  } catch {
823
876
  try {
824
- n = require("toml").parse(e);
877
+ r = require("toml").parse(e);
825
878
  } catch {
826
879
  try {
827
- n = require("js-yaml").load(e);
828
- } catch (s) {
829
- return void (this.debug && console.error(`[FuncSpan ConfigLoader] Failed to parse ${t} as JSON, TOML, or YAML:`, s));
880
+ r = require("js-yaml").load(e);
881
+ } catch (i) {
882
+ return void (this.debug && console.error(`[FuncSpan ConfigLoader] Failed to parse ${t} as JSON, TOML, or YAML:`, i));
830
883
  }
831
884
  }
832
885
  }
833
- if (!n) return;
834
- n.runtime_mode === !0 && (this.runtimeModeEnabled = !0, this.debug && console.log(`[FuncSpan ConfigLoader] Runtime mode ENABLED in ${t}`)), n.default && this.directoryConfigs.set(i, n.default), n.files && await this._expandFileGlobs(i, n.files, n.default || {}), n.functions && this._storeFunctionConfigs(i, n.functions, n.default || {}), this.debug && (console.log(`[FuncSpan ConfigLoader] Loaded config from ${t}`), console.log(`[FuncSpan ConfigLoader] Directory: ${i}`), console.log(`[FuncSpan ConfigLoader] Has default: ${!!n.default}`), console.log(`[FuncSpan ConfigLoader] File patterns: ${Object.keys(n.files || {}).length}`), console.log(`[FuncSpan ConfigLoader] Functions: ${Object.keys(n.functions || {}).length}`));
886
+ if (!r) return;
887
+ r.runtime_mode === !0 && (this.runtimeModeEnabled = !0, this.debug && console.log(`[FuncSpan ConfigLoader] Runtime mode ENABLED in ${t}`)), r.default && this.directoryConfigs.set(o, r.default), r.files && await this._expandFileGlobs(o, r.files, r.default || {}), r.functions && this._storeFunctionConfigs(o, r.functions, r.default || {}), this.debug && (console.log(`[FuncSpan ConfigLoader] Loaded config from ${t}`), console.log(`[FuncSpan ConfigLoader] Directory: ${o}`), console.log(`[FuncSpan ConfigLoader] Has default: ${!!r.default}`), console.log(`[FuncSpan ConfigLoader] File patterns: ${Object.keys(r.files || {}).length}`), console.log(`[FuncSpan ConfigLoader] Functions: ${Object.keys(r.functions || {}).length}`));
835
888
  } catch (e) {
836
889
  this.debug && console.error(`[FuncSpan ConfigLoader] Error loading ${t}:`, e);
837
890
  }
838
891
  }
839
- async _expandFileGlobs(t, e, i) {
840
- for (const [n, s] of Object.entries(e)) try {
841
- const l = P.join(t, n), c = await Me(l, { absolute: !0, nodir: !0, ignore: ["**/node_modules/**", "**/.git/**"] });
842
- this.debug && console.log(`[FuncSpan ConfigLoader] Pattern '${n}' matched ${c.length} files`);
843
- for (const o of c) {
844
- const d = P.normalize(o), p = L(i, s);
845
- this.fileConfigs.set(d, p), this.debug && c.length <= 5 && console.log(`[FuncSpan ConfigLoader] - ${o}`);
892
+ async _expandFileGlobs(t, e, o) {
893
+ for (const [r, i] of Object.entries(e)) try {
894
+ const d = B.join(t, r), l = await Ot(d, { absolute: !0, nodir: !0, ignore: ["**/node_modules/**", "**/.git/**"] });
895
+ this.debug && console.log(`[FuncSpan ConfigLoader] Pattern '${r}' matched ${l.length} files`);
896
+ for (const a of l) {
897
+ const s = B.normalize(a), u = te(o, i);
898
+ this.fileConfigs.set(s, u), this.debug && l.length <= 5 && console.log(`[FuncSpan ConfigLoader] - ${a}`);
846
899
  }
847
- } catch (l) {
848
- this.debug && console.error(`[FuncSpan ConfigLoader] Error expanding glob '${n}':`, l);
900
+ } catch (d) {
901
+ this.debug && console.error(`[FuncSpan ConfigLoader] Error expanding glob '${r}':`, d);
849
902
  }
850
903
  }
851
- _storeFunctionConfigs(t, e, i) {
852
- for (const [n, s] of Object.entries(e)) {
853
- const l = n.split("::");
854
- if (l.length !== 2) {
855
- this.debug && console.warn(`[FuncSpan ConfigLoader] Invalid function pattern '${n}' (expected format: 'file.ts::functionName')`);
904
+ _storeFunctionConfigs(t, e, o) {
905
+ for (const [r, i] of Object.entries(e)) {
906
+ const d = r.split("::");
907
+ if (d.length !== 2) {
908
+ this.debug && console.warn(`[FuncSpan ConfigLoader] Invalid function pattern '${r}' (expected format: 'file.ts::functionName')`);
856
909
  continue;
857
910
  }
858
- const [c, o] = l, d = P.normalize(P.join(t, c));
859
- this.functionConfigs.has(d) || this.functionConfigs.set(d, /* @__PURE__ */ new Map());
860
- const p = this.functionConfigs.get(d), u = L(i, s);
861
- p.set(o, u), this.debug && console.log(`[FuncSpan ConfigLoader] Function config: ${d}::${o}`);
911
+ const [l, a] = d, s = B.normalize(B.join(t, l));
912
+ this.functionConfigs.has(s) || this.functionConfigs.set(s, /* @__PURE__ */ new Map());
913
+ const u = this.functionConfigs.get(s), c = te(o, i);
914
+ u.set(a, c), this.debug && console.log(`[FuncSpan ConfigLoader] Function config: ${s}::${a}`);
862
915
  }
863
916
  }
864
917
  async _resolveInheritance() {
865
918
  }
866
919
  _getDirectoryConfig(t) {
867
- let e = P.dirname(P.normalize(t));
868
- const i = [];
869
- for (; e && e !== P.dirname(e); ) {
870
- const n = this.directoryConfigs.get(e);
871
- n && i.unshift(n), e = P.dirname(e);
920
+ let e = B.dirname(B.normalize(t));
921
+ const o = [];
922
+ for (; e && e !== B.dirname(e); ) {
923
+ const r = this.directoryConfigs.get(e);
924
+ r && o.unshift(r), e = B.dirname(e);
872
925
  }
873
- return i.reduce((n, s) => L(n, s), {});
926
+ return o.reduce((r, i) => te(r, i), {});
874
927
  }
875
928
  }
876
- const ye = "__sf_globalConfigLoader";
877
- function Se() {
878
- return globalThis[ye] ?? null;
929
+ const at = "__sf_globalConfigLoader";
930
+ function ct() {
931
+ return globalThis[at] ?? null;
879
932
  }
880
- async function Xe(r, t) {
881
- const e = new Qe(r, t);
882
- (function(i) {
883
- globalThis[ye] = i;
933
+ async function Vt(n, t) {
934
+ const e = new zt(n, t);
935
+ (function(o) {
936
+ globalThis[at] = o;
884
937
  })(e), await e.loadAllConfigs();
885
938
  }
886
- function Ye(r, t) {
887
- const e = Se();
888
- return e ? e.getConfig(r, t) : (process.env.SF_DEBUG === "true" && console.log("[FuncSpan ConfigLoader] Config loader not initialized, using default config (disabled)"), ge());
939
+ function Xt(n, t) {
940
+ const e = ct();
941
+ return e ? e.getConfig(n, t) : (process.env.SF_DEBUG === "true" && console.log("[FuncSpan ConfigLoader] Config loader not initialized, using default config (disabled)"), rt());
889
942
  }
890
- function Ze() {
891
- return Se() !== null;
943
+ function Yt() {
944
+ return ct() !== null;
892
945
  }
893
- const et = ["readFile", "writeFile", "appendFile", "readdir", "stat", "lstat", "fstat", "access", "open", "close", "read", "write", "chmod", "mkdir", "rmdir", "unlink", "rename"], ae = ["lookup", "resolve", "resolve4", "resolve6", "resolveAny", "resolveMx", "resolveNs", "resolveTxt", "reverse"], tt = ["pbkdf2", "randomBytes", "scrypt", "generateKeyPair"], nt = ["gzip", "gunzip", "deflate", "inflate", "deflateRaw", "inflateRaw", "brotliCompress", "brotliDecompress"];
894
- let ce = !1;
895
- function rt(r) {
896
- if (typeof r != "string") return !1;
946
+ const Zt = ["readFile", "writeFile", "appendFile", "readdir", "stat", "lstat", "fstat", "access", "open", "close", "read", "write", "chmod", "mkdir", "rmdir", "unlink", "rename"], He = ["lookup", "resolve", "resolve4", "resolve6", "resolveAny", "resolveMx", "resolveNs", "resolveTxt", "reverse"], en = ["pbkdf2", "randomBytes", "scrypt", "generateKeyPair"], tn = ["gzip", "gunzip", "deflate", "inflate", "deflateRaw", "inflateRaw", "brotliCompress", "brotliDecompress"];
947
+ let xe = !1;
948
+ function nn(n) {
949
+ if (typeof n != "string") return !1;
897
950
  const t = process.env.SF_FUNCSPAN_JSONL_FILE;
898
- if (t && r.includes(t)) return !0;
951
+ if (t && n.includes(t)) return !0;
899
952
  const e = process.env.SF_WORKER_POOL_JSONL_FILE;
900
- return !(!e || !r.includes(e));
953
+ return !(!e || !n.includes(e));
901
954
  }
902
- let de = !1;
903
- function ue(r) {
904
- if (typeof r != "string") return !1;
905
- if (r === "localhost" || r === "127.0.0.1" || r === "::1") return !0;
955
+ let je = !1;
956
+ function Ke(n) {
957
+ if (typeof n != "string") return !1;
958
+ if (n === "localhost" || n === "127.0.0.1" || n === "::1") return !0;
906
959
  try {
907
960
  const t = process.env.API_GRAPHQL_ENDPOINT;
908
- if (t && r === new URL(t).hostname)
961
+ if (t && n === new URL(t).hostname)
909
962
  return !0;
910
963
  } catch {
911
964
  }
912
965
  return !1;
913
966
  }
914
- function it() {
915
- if (!de) try {
916
- let r;
967
+ function rn() {
968
+ if (!je) try {
969
+ let n;
917
970
  if (typeof require > "u") return void (process.env.SF_DEBUG === "true" && console.log("[WorkerPool] Skipping dns patching in pure ESM environment (require unavailable)"));
918
971
  try {
919
- r = require("node:dns");
972
+ n = require("node:dns");
920
973
  } catch (t) {
921
974
  return void (process.env.SF_DEBUG === "true" && console.log("[WorkerPool] Failed to require dns module:", t));
922
975
  }
923
- if (r.__sf_worker_pool_patched__) return;
924
- Object.defineProperty(r, "__sf_worker_pool_patched__", { value: !0, enumerable: !1, writable: !1, configurable: !1 });
925
- for (const t of ae) if (typeof r[t] == "function") {
926
- const e = r[t];
927
- r[t] = function(...i) {
928
- return ne() ? e.apply(this, i) : ue(i[0]) ? e.apply(this, i) : typeof i[i.length - 1] == "function" ? x("dns", t, e, i, this) : e.apply(this, i);
929
- }, Object.defineProperty(r[t], "name", { value: t, writable: !1 });
976
+ if (n.__sf_worker_pool_patched__) return;
977
+ Object.defineProperty(n, "__sf_worker_pool_patched__", { value: !0, enumerable: !1, writable: !1, configurable: !1 });
978
+ for (const t of He) if (typeof n[t] == "function") {
979
+ const e = n[t];
980
+ n[t] = function(...o) {
981
+ return Te() ? e.apply(this, o) : Ke(o[0]) ? e.apply(this, o) : typeof o[o.length - 1] == "function" ? ie("dns", t, e, o, this) : e.apply(this, o);
982
+ }, Object.defineProperty(n[t], "name", { value: t, writable: !1 });
930
983
  }
931
984
  (function(t) {
932
985
  if (!t.promises) return void (process.env.SF_DEBUG === "true" && console.log("[WorkerPool] dns.promises not available, skipping"));
933
986
  if (!t.promises.__sf_worker_pool_patched__) {
934
987
  Object.defineProperty(t.promises, "__sf_worker_pool_patched__", { value: !0, enumerable: !1, writable: !1, configurable: !1 });
935
- for (const e of ae) if (typeof t.promises[e] == "function") {
936
- const i = t.promises[e];
937
- t.promises[e] = function(...n) {
938
- return ne() ? i.apply(this, n) : ue(n[0]) ? i.apply(this, n) : we("dns", e, i, n, this);
988
+ for (const e of He) if (typeof t.promises[e] == "function") {
989
+ const o = t.promises[e];
990
+ t.promises[e] = function(...r) {
991
+ return Te() ? o.apply(this, r) : Ke(r[0]) ? o.apply(this, r) : kt("dns", e, o, r, this);
939
992
  }, Object.defineProperty(t.promises[e], "name", { value: e, writable: !1 });
940
993
  }
941
994
  process.env.SF_DEBUG === "true" && console.log("[WorkerPool] dns.promises module patched successfully");
942
995
  }
943
- })(r), de = !0, process.env.SF_DEBUG === "true" && console.log("[WorkerPool] dns module patched successfully");
944
- } catch (r) {
945
- console.error("[WorkerPool] Error patching dns module:", r);
996
+ })(n), je = !0, process.env.SF_DEBUG === "true" && console.log("[WorkerPool] dns module patched successfully");
997
+ } catch (n) {
998
+ console.error("[WorkerPool] Error patching dns module:", n);
946
999
  }
947
1000
  }
948
- let le = !1, pe = !1, Y = !1;
949
- function st() {
950
- if (Y) return;
951
- const r = process.env.SF_DEBUG === "true";
952
- r && console.log("[WorkerPool] Initializing worker pool patching..."), q("fs") && (r && console.log("[WorkerPool] Patching fs module..."), (function() {
953
- if (!ce) try {
1001
+ let Qe = !1, Je = !1, Ee = !1;
1002
+ function on() {
1003
+ if (Ee) return;
1004
+ const n = process.env.SF_DEBUG === "true";
1005
+ n && console.log("[WorkerPool] Initializing worker pool patching..."), ne("fs") && (n && console.log("[WorkerPool] Patching fs module..."), (function() {
1006
+ if (!xe) try {
954
1007
  const t = require("node:fs");
955
1008
  if (t.__sf_worker_pool_patched__) return;
956
1009
  Object.defineProperty(t, "__sf_worker_pool_patched__", { value: !0, enumerable: !1, writable: !1, configurable: !1 });
957
- for (const e of et) if (typeof t[e] == "function") {
958
- const i = t[e];
959
- t[e] = function(...n) {
960
- return rt(n[0]) ? i.apply(this, n) : typeof n[n.length - 1] == "function" ? x("fs", e, i, n, this) : i.apply(this, n);
1010
+ for (const e of Zt) if (typeof t[e] == "function") {
1011
+ const o = t[e];
1012
+ t[e] = function(...r) {
1013
+ return nn(r[0]) ? o.apply(this, r) : typeof r[r.length - 1] == "function" ? ie("fs", e, o, r, this) : o.apply(this, r);
961
1014
  }, Object.defineProperty(t[e], "name", { value: e, writable: !1 });
962
1015
  }
963
- ce = !0, process.env.SF_DEBUG === "true" && console.log("[WorkerPool] fs module patched successfully");
1016
+ xe = !0, process.env.SF_DEBUG === "true" && console.log("[WorkerPool] fs module patched successfully");
964
1017
  } catch (t) {
965
1018
  console.error("[WorkerPool] Error patching fs module:", t);
966
1019
  }
967
- })()), q("dns") && (r && console.log("[WorkerPool] Patching dns module..."), it()), q("crypto") && (r && console.log("[WorkerPool] Patching crypto module..."), (function() {
968
- if (!le) try {
1020
+ })()), ne("dns") && (n && console.log("[WorkerPool] Patching dns module..."), rn()), ne("crypto") && (n && console.log("[WorkerPool] Patching crypto module..."), (function() {
1021
+ if (!Qe) try {
969
1022
  const t = require("node:crypto");
970
1023
  if (t.__sf_worker_pool_patched__) return;
971
1024
  Object.defineProperty(t, "__sf_worker_pool_patched__", { value: !0, enumerable: !1, writable: !1, configurable: !1 });
972
- for (const e of tt) if (typeof t[e] == "function") {
973
- const i = t[e];
974
- t[e] = function(...n) {
975
- return typeof n[n.length - 1] == "function" ? x("crypto", e, i, n, this) : i.apply(this, n);
1025
+ for (const e of en) if (typeof t[e] == "function") {
1026
+ const o = t[e];
1027
+ t[e] = function(...r) {
1028
+ return typeof r[r.length - 1] == "function" ? ie("crypto", e, o, r, this) : o.apply(this, r);
976
1029
  }, Object.defineProperty(t[e], "name", { value: e, writable: !1 });
977
1030
  }
978
- le = !0, process.env.SF_DEBUG === "true" && console.log("[WorkerPool] crypto module patched successfully");
1031
+ Qe = !0, process.env.SF_DEBUG === "true" && console.log("[WorkerPool] crypto module patched successfully");
979
1032
  } catch (t) {
980
1033
  console.error("[WorkerPool] Error patching crypto module:", t);
981
1034
  }
982
- })()), q("zlib") && (r && console.log("[WorkerPool] Patching zlib module..."), (function() {
983
- if (!pe) try {
1035
+ })()), ne("zlib") && (n && console.log("[WorkerPool] Patching zlib module..."), (function() {
1036
+ if (!Je) try {
984
1037
  const t = require("node:zlib");
985
1038
  if (t.__sf_worker_pool_patched__) return;
986
1039
  Object.defineProperty(t, "__sf_worker_pool_patched__", { value: !0, enumerable: !1, writable: !1, configurable: !1 });
987
- for (const e of nt) if (typeof t[e] == "function") {
988
- const i = t[e];
989
- t[e] = function(...n) {
990
- return typeof n[n.length - 1] == "function" ? x("zlib", e, i, n, this) : i.apply(this, n);
1040
+ for (const e of tn) if (typeof t[e] == "function") {
1041
+ const o = t[e];
1042
+ t[e] = function(...r) {
1043
+ return typeof r[r.length - 1] == "function" ? ie("zlib", e, o, r, this) : o.apply(this, r);
991
1044
  }, Object.defineProperty(t[e], "name", { value: e, writable: !1 });
992
1045
  }
993
- pe = !0, process.env.SF_DEBUG === "true" && console.log("[WorkerPool] zlib module patched successfully");
1046
+ Je = !0, process.env.SF_DEBUG === "true" && console.log("[WorkerPool] zlib module patched successfully");
994
1047
  } catch (t) {
995
1048
  console.error("[WorkerPool] Error patching zlib module:", t);
996
1049
  }
997
- })()), Y = !0, r && console.log("[WorkerPool] Worker pool patching initialized");
1050
+ })()), Ee = !0, n && console.log("[WorkerPool] Worker pool patching initialized");
1051
+ }
1052
+ function sn() {
1053
+ return Ee;
1054
+ }
1055
+ const We = Y.toLowerCase();
1056
+ function W(n) {
1057
+ if (n != null) {
1058
+ if (Array.isArray(n)) {
1059
+ for (const t of n)
1060
+ if (!(!t || typeof t != "object") && Ge(t.key) === We)
1061
+ return t.value;
1062
+ } else if (typeof n == "object") {
1063
+ for (const [t, e] of Object.entries(n)) if (Ge(t) === We)
1064
+ return Array.isArray(e) ? e.length === 0 ? void 0 : e[0] : e;
1065
+ }
1066
+ }
1067
+ }
1068
+ function Ge(n) {
1069
+ if (typeof n == "string") return n.toLowerCase();
1070
+ if (Buffer.isBuffer(n)) try {
1071
+ return n.toString("utf8").toLowerCase();
1072
+ } catch {
1073
+ return null;
1074
+ }
1075
+ if (n instanceof Uint8Array) try {
1076
+ return Buffer.from(n).toString("utf8").toLowerCase();
1077
+ } catch {
1078
+ return null;
1079
+ }
1080
+ return null;
1081
+ }
1082
+ let ge = null;
1083
+ function ut() {
1084
+ return ge || (ge = new it()), ge;
1085
+ }
1086
+ function lt(n) {
1087
+ if (!n) return null;
1088
+ const t = n.split("/").filter(Boolean);
1089
+ return t.length < 3 ? null : { sessionId: t[0], pageVisitId: t[1], requestId: t[t.length - 1] };
1090
+ }
1091
+ const an = /^[A-Za-z0-9._:-]{1,128}$/;
1092
+ function z(n) {
1093
+ if (typeof n != "string" || n.length === 0 || n.length > 1024) return !1;
1094
+ const t = n.split("/").filter(Boolean);
1095
+ if (t.length < 3 || t.length > 6) return !1;
1096
+ for (const e of t) if (!an.test(e)) return !1;
1097
+ return !0;
1098
+ }
1099
+ function V(n) {
1100
+ const t = n.split("/");
1101
+ return t.length >= 3 ? (t[t.length - 1] = G(), t.join("/")) : `${n}/${G()}`;
1102
+ }
1103
+ function cn(n) {
1104
+ if (n == null) return null;
1105
+ if (typeof n == "string") return n;
1106
+ if (Buffer.isBuffer(n)) try {
1107
+ return n.toString("utf8");
1108
+ } catch {
1109
+ return null;
1110
+ }
1111
+ try {
1112
+ return JSON.stringify($e(n));
1113
+ } catch {
1114
+ return null;
1115
+ }
1116
+ }
1117
+ function $e(n, t = 0) {
1118
+ if (t > 10) return "[truncated-depth]";
1119
+ if (n == null) return n;
1120
+ const e = typeof n;
1121
+ if (e === "string" || e === "number" || e === "boolean") return n;
1122
+ if (e === "bigint") return n.toString();
1123
+ if (e !== "object") return;
1124
+ if (Buffer.isBuffer(n)) return `[Buffer ${n.length}b]`;
1125
+ if (ArrayBuffer.isView(n)) {
1126
+ const r = n;
1127
+ return `[${r.constructor?.name ?? "TypedArray"} ${r.byteLength}b]`;
1128
+ }
1129
+ if (n instanceof Date) try {
1130
+ return n.toISOString();
1131
+ } catch {
1132
+ return "[Date]";
1133
+ }
1134
+ if (n instanceof Map) return `[Map size=${n.size}]`;
1135
+ if (n instanceof Set) return `[Set size=${n.size}]`;
1136
+ if (Array.isArray(n)) return n.map((r) => $e(r, t + 1));
1137
+ const o = {};
1138
+ for (const r of Object.getOwnPropertyNames(n)) {
1139
+ const i = Object.getOwnPropertyDescriptor(n, r);
1140
+ i && typeof i.get != "function" && typeof i.set != "function" && (o[r] = $e(i.value, t + 1));
1141
+ }
1142
+ return o;
1143
+ }
1144
+ function dt(n) {
1145
+ if (!n) return null;
1146
+ try {
1147
+ const t = n.message;
1148
+ if (typeof t == "string" && t.length > 0) return t;
1149
+ } catch {
1150
+ }
1151
+ try {
1152
+ const t = String(n);
1153
+ if (typeof t == "string" && t.length > 0) return t;
1154
+ } catch {
1155
+ }
1156
+ try {
1157
+ const t = n.name;
1158
+ if (typeof t == "string" && t.length > 0) return t;
1159
+ } catch {
1160
+ }
1161
+ return "[unstringifiable error]";
1162
+ }
1163
+ function P(n) {
1164
+ const t = x.getInstance().getOrSetSfTraceId(), e = V(t), o = lt(e), r = Date.now(), i = m(), d = n.queueUri, l = n.method ?? "ENQUEUE", a = pt(n.messagePayload, i);
1165
+ return { traceId: e, hopEnd: (s) => {
1166
+ try {
1167
+ if (!o) return;
1168
+ const u = Date.now();
1169
+ let c = null;
1170
+ try {
1171
+ c = H() ?? null;
1172
+ } catch {
1173
+ }
1174
+ const p = { apiKey: i.apiKey, requestId: o.requestId, pageVisitId: o.pageVisitId, recordingSessionId: o.sessionId, serviceUuid: i.serviceUUID ?? null, timestampStart: r.toString(), timestampEnd: u.toString(), responseCode: s ? 500 : 0, success: !s, error: dt(s), url: d, method: l, parentSpanId: c };
1175
+ a !== null && (p.requestBody = a), ft(p);
1176
+ try {
1177
+ ut().doSend(p);
1178
+ } catch (h) {
1179
+ i.sfDebug && console.warn("[asyncQueues] producer hop transmit failed:", h);
1180
+ }
1181
+ } catch {
1182
+ }
1183
+ } };
1184
+ }
1185
+ function pt(n, t) {
1186
+ if (!t.captureRequestBody || n === void 0) return null;
1187
+ const e = cn(n);
1188
+ return e ? (function(o, r) {
1189
+ return !r || r <= 0 ? o : o.length > r ? o.substring(0, r) + "...[truncated]" : o;
1190
+ })(e, t.requestBodyLimitBytes) : null;
1191
+ }
1192
+ function L(n, t) {
1193
+ if (ze.getStore() === !0) return Promise.resolve(t());
1194
+ const e = x.getInstance(), o = m(), r = n.incomingTraceId !== void 0 && z(n.incomingTraceId) ? n.incomingTraceId : `${vt}-v3/${o.apiKey}/${G()}`, i = n.queueUri, d = n.method, l = n.library, a = pt(n.messagePayload, o);
1195
+ return ze.run(!0, () => e.runScoped({ traceId: r }, async () => {
1196
+ const s = Date.now();
1197
+ let u = null;
1198
+ try {
1199
+ const c = await Promise.resolve(t());
1200
+ return await (function(p) {
1201
+ return p !== null && typeof p == "object" && typeof p.subscribe == "function" ? new Promise((h, g) => {
1202
+ let f, y = !1;
1203
+ try {
1204
+ p.subscribe({ next: (S) => {
1205
+ f = S, y = !0;
1206
+ }, error: (S) => g(S), complete: () => h(y ? f : void 0) });
1207
+ } catch (S) {
1208
+ g(S);
1209
+ }
1210
+ }) : p;
1211
+ })(c);
1212
+ } catch (c) {
1213
+ throw u = c instanceof Error ? c : new Error(String(c)), c;
1214
+ } finally {
1215
+ (function(c, p, h, g, f, y) {
1216
+ try {
1217
+ const S = lt(h);
1218
+ if (!S) return;
1219
+ const I = m(), { graceful: v, tag: _ } = (function(M) {
1220
+ if (!M) return { graceful: !0, tag: null };
1221
+ let K;
1222
+ try {
1223
+ K = M.name;
1224
+ } catch {
1225
+ return { graceful: !1, tag: null };
1226
+ }
1227
+ return K === "AbortError" ? { graceful: !0, tag: "CONSUME_CANCELLED" } : K === "DelayedError" ? { graceful: !0, tag: "CONSUME_RESCHEDULED" } : K === "WaitingChildrenError" ? { graceful: !0, tag: "CONSUME_WAITING_CHILDREN" } : { graceful: !1, tag: null };
1228
+ })(y), E = !y && c.method ? c.method : _ ?? c.method ?? "CONSUME", k = !y || v, q = y && !v ? 500 : 0, $ = y && !v ? dt(y) : null;
1229
+ let F = null;
1230
+ try {
1231
+ F = H() ?? null;
1232
+ } catch {
1233
+ }
1234
+ const N = { apiKey: I.apiKey, requestId: S.requestId, pageVisitId: S.pageVisitId, recordingSessionId: S.sessionId, serviceUuid: I.serviceUUID ?? null, timestampStart: g.toString(), timestampEnd: f.toString(), responseCode: q, success: k, error: $, url: c.queueUri, method: E, parentSpanId: F };
1235
+ p !== null && (N.requestBody = p), ft(N);
1236
+ try {
1237
+ ut().doSend(N);
1238
+ } catch (M) {
1239
+ I.sfDebug && console.warn("[asyncQueues] consumer hop transmit failed:", M);
1240
+ }
1241
+ } catch {
1242
+ }
1243
+ })({ library: l, queueUri: i, method: d }, a, r, s, Date.now(), u);
1244
+ }
1245
+ }));
998
1246
  }
999
- function ot() {
1000
- return Y;
1247
+ const ze = new Mt();
1248
+ let _e = null;
1249
+ function Nn(n) {
1250
+ _e = n;
1001
1251
  }
1002
- let Z = !1, V = !1;
1003
- function St(r) {
1004
- if (V) console.warn("[setupInterceptors] ⚠️ Recursive call detected and blocked!");
1005
- else if (!Z) {
1006
- V = !0, Ee();
1252
+ function ft(n) {
1253
+ if (_e !== null) try {
1254
+ _e(n);
1255
+ } catch {
1256
+ }
1257
+ }
1258
+ const b = Symbol.for("sailfish.async-queues.patched"), w = Symbol.for("sailfish.async-queues.instance-wrapped"), we = [];
1259
+ function U(n, t, e) {
1260
+ if (we.some((r) => r.proto === n && r.key === t)) return !1;
1261
+ const o = typeof n?.[t] == "function" ? n[t] : void 0;
1262
+ try {
1263
+ return n[t] = e, we.push({ proto: n, key: t, original: o }), !0;
1264
+ } catch (r) {
1265
+ if (m().sfDebug) {
1266
+ const i = n?.constructor?.name ?? "<unknown>";
1267
+ console.warn(`[asyncQueues] could not install patch on ${i}.prototype.${t} (frozen / non-writable?):`, r);
1268
+ }
1269
+ return !1;
1270
+ }
1271
+ }
1272
+ function T(n, t) {
1273
+ try {
1274
+ return n();
1275
+ } catch (e) {
1276
+ return m().sfDebug && console.warn(`[asyncQueues] instrumentation rewrite threw in ${t} — falling back to original args, no hop emitted:`, e), null;
1277
+ }
1278
+ }
1279
+ function C(n, t) {
1280
+ let e = n || "unknown";
1281
+ if (typeof e == "string") {
1282
+ e.startsWith("bull:") && (e = e.slice(5));
1283
+ const o = /^\{([^}]+)\}:(.+)$/.exec(e);
1284
+ o && (e = `${o[1]}/${o[2]}`);
1285
+ }
1286
+ return `bullmq://redis/${e}/${t || "unknown"}`;
1287
+ }
1288
+ function ce(n) {
1289
+ return n?.queueQualifiedName ?? n?.queueName ?? n?.queue?.name ?? void 0;
1290
+ }
1291
+ function R(n, t) {
1292
+ const e = n ? { ...n } : {}, o = e.sf && typeof e.sf == "object" ? e.sf : {};
1293
+ return e.sf = { ...o, rid: t }, e;
1294
+ }
1295
+ function un(n) {
1296
+ let t = n;
1297
+ if (!t) try {
1298
+ t = require("bullmq");
1299
+ } catch {
1300
+ return "not-installed";
1301
+ }
1302
+ (function(a) {
1303
+ try {
1304
+ const s = a?.version ?? a?.Queue?.version;
1305
+ if (typeof s != "string") return;
1306
+ parseInt(s.split(".")[0] ?? "0", 10) < 3 && m().sfDebug && console.warn(`[sf-veritas] BullMQ ${s} detected. Async-queue tracing is best-supported on BullMQ ≥ 3.0. Some APIs (FlowProducer, upsertJobScheduler, Job.promote) may be missing on older versions and will be skipped silently.`);
1307
+ } catch {
1308
+ }
1309
+ })(t);
1310
+ const e = t.Queue, o = t.Worker;
1311
+ if (!e?.prototype || !o?.prototype) return m().sfDebug && console.warn("[asyncQueues][bullmq] Expected Queue/Worker classes not found on module — skipping patch."), "failed";
1312
+ (function(a) {
1313
+ const s = a.prototype.add;
1314
+ if (typeof s != "function" || s[b]) return;
1315
+ const u = async function(c, p, h) {
1316
+ if (h?.sf?.rid) return s.call(this, c, p, h);
1317
+ const g = T(() => {
1318
+ const y = P({ library: "bullmq", queueUri: C(this?.name, c), messagePayload: p });
1319
+ return { handle: y, nextOpts: R(h, y.traceId) };
1320
+ }, "bullmq.Queue.add");
1321
+ if (g === null) return s.call(this, c, p, h);
1322
+ let f = null;
1323
+ try {
1324
+ return await s.call(this, c, p, g.nextOpts);
1325
+ } catch (y) {
1326
+ throw f = y instanceof Error ? y : new Error(String(y)), y;
1327
+ } finally {
1328
+ g.handle.hopEnd(f);
1329
+ }
1330
+ };
1331
+ u[b] = !0, U(a.prototype, "add", u);
1332
+ })(e), (function(a) {
1333
+ const s = a.prototype.addBulk;
1334
+ if (typeof s != "function" || s[b]) return;
1335
+ const u = async function(c) {
1336
+ if (!Array.isArray(c) || c.length === 0) return s.call(this, c);
1337
+ if (c.every((f) => f?.opts?.sf?.rid)) return s.call(this, c);
1338
+ const p = m().bullmqBulkAggregateMode, h = T(() => {
1339
+ if (p) {
1340
+ const S = P({ library: "bullmq", queueUri: C(this?.name, `__bulk_${c.length}`), method: "ENQUEUE_BULK", messagePayload: { batchSize: c.length } }), I = c.map((v) => ({ ...v, opts: R(v?.opts, S.traceId) }));
1341
+ return { handles: [S], out: I };
1342
+ }
1343
+ const f = c.map((S) => P({ library: "bullmq", queueUri: C(this?.name, S?.name), messagePayload: S?.data })), y = c.map((S, I) => ({ ...S, opts: R(S?.opts, f[I].traceId) }));
1344
+ return { handles: f, out: y };
1345
+ }, "bullmq.Queue.addBulk");
1346
+ if (h === null) return s.call(this, c);
1347
+ let g = null;
1348
+ try {
1349
+ return await s.call(this, h.out);
1350
+ } catch (f) {
1351
+ throw g = f instanceof Error ? f : new Error(String(f)), f;
1352
+ } finally {
1353
+ for (const f of h.handles) f.hopEnd(g);
1354
+ }
1355
+ };
1356
+ u[b] = !0, U(a.prototype, "addBulk", u);
1357
+ })(e), (function(a) {
1358
+ const s = a.prototype.upsertJobScheduler;
1359
+ if (typeof s != "function" || s[b]) return;
1360
+ const u = async function(c, p, h) {
1361
+ const g = T(() => {
1362
+ const y = P({ library: "bullmq", queueUri: C(this?.name, h?.name ?? c), method: "ENQUEUE" });
1363
+ let S;
1364
+ if (h !== void 0) {
1365
+ const I = { ...h, opts: R(h.opts, y.traceId) };
1366
+ S = [c, p, I];
1367
+ } else S = [c, p];
1368
+ return { handle: y, callArgs: S };
1369
+ }, "bullmq.Queue.upsertJobScheduler");
1370
+ if (g === null) {
1371
+ const y = h !== void 0 ? [c, p, h] : [c, p];
1372
+ return s.call(this, ...y);
1373
+ }
1374
+ let f = null;
1375
+ try {
1376
+ return await s.call(this, ...g.callArgs);
1377
+ } catch (y) {
1378
+ throw f = y instanceof Error ? y : new Error(String(y)), y;
1379
+ } finally {
1380
+ g.handle.hopEnd(f);
1381
+ }
1382
+ };
1383
+ u[b] = !0, U(a.prototype, "upsertJobScheduler", u);
1384
+ })(e), (function(a) {
1385
+ const s = a.prototype.getNextJob;
1386
+ if (typeof s != "function" || s[b]) return;
1387
+ const u = async function(...c) {
1388
+ const p = await s.apply(this, c);
1389
+ if (p && z(p.opts?.sf?.rid)) try {
1390
+ x.getInstance().setTraceId(p.opts.sf.rid);
1391
+ } catch {
1392
+ }
1393
+ return p;
1394
+ };
1395
+ u[b] = !0, U(a.prototype, "getNextJob", u);
1396
+ })(e), (function(a) {
1397
+ const s = a.prototype.getJob;
1398
+ if (typeof s != "function" || s[b]) return;
1399
+ const u = async function(...c) {
1400
+ const p = await s.apply(this, c);
1401
+ if (p && z(p.opts?.sf?.rid)) try {
1402
+ const g = x.getInstance();
1403
+ (!(h = g.getTraceId()) || h.startsWith("nonsession-applogs-v3/")) && g.setTraceId(p.opts.sf.rid);
1404
+ } catch {
1405
+ }
1406
+ var h;
1407
+ return p;
1408
+ };
1409
+ u[b] = !0, U(a.prototype, "getJob", u);
1410
+ })(e), (function(a) {
1411
+ const s = a.prototype.processJob;
1412
+ if (typeof s != "function" || s[b]) return;
1413
+ const u = function(c, ...p) {
1414
+ const h = c?.opts?.sf?.rid, g = typeof c?.attemptsMade == "number" ? c.attemptsMade : 0, f = typeof c?.stalledCounter == "number" ? c.stalledCounter : 0, y = c?.repeatJobKey != null || c?.opts?.repeat != null, S = h && (g > 0 || f > 0 || y) ? V(h) : h;
1415
+ let I;
1416
+ return f > 0 ? I = "CONSUME_STALLED" : y && g === 0 && (I = "CONSUME_SCHEDULED"), L({ library: "bullmq", queueUri: C(ce(c) ?? this?.name, c?.name), incomingTraceId: S, messagePayload: c?.data, method: I }, () => s.call(this, c, ...p));
1417
+ };
1418
+ u[b] = !0, U(a.prototype, "processJob", u);
1419
+ })(o);
1420
+ const r = t.Job;
1421
+ r?.prototype && (function(a) {
1422
+ const s = ["retry", "moveToDelayed", "promote"];
1423
+ for (const u of s) {
1424
+ const c = a.prototype[u];
1425
+ if (typeof c != "function" || c[b]) continue;
1426
+ const p = u === "promote" ? "PROMOTE" : u === "moveToDelayed" ? "RESCHEDULE" : "ENQUEUE_RETRY", h = async function(...g) {
1427
+ const f = this?.opts?.sf?.rid;
1428
+ let y;
1429
+ if (f) y = V(f);
1430
+ else {
1431
+ const v = P({ queueUri: C(ce(this) ?? this?.name, this?.name), method: p });
1432
+ let _ = null;
1433
+ try {
1434
+ return await c.apply(this, g);
1435
+ } catch (E) {
1436
+ throw _ = E instanceof Error ? E : new Error(String(E)), E;
1437
+ } finally {
1438
+ v.hopEnd(_);
1439
+ }
1440
+ }
1441
+ this.opts && (this.opts = { ...this.opts, sf: { ...this.opts.sf || {}, rid: y } });
1442
+ const S = P({ queueUri: C(ce(this) ?? this?.name, this?.name), method: p });
1443
+ let I = null;
1444
+ try {
1445
+ return await c.apply(this, g);
1446
+ } catch (v) {
1447
+ throw I = v instanceof Error ? v : new Error(String(v)), v;
1448
+ } finally {
1449
+ S.hopEnd(I);
1450
+ }
1451
+ };
1452
+ h[b] = !0, U(a.prototype, u, h);
1453
+ }
1454
+ })(r);
1455
+ const i = t.QueueEvents;
1456
+ i?.prototype && (i.prototype[b] = !1);
1457
+ const d = t.FlowProducer;
1458
+ return d?.prototype && ((function(a) {
1459
+ const s = a.prototype.add;
1460
+ if (typeof s != "function" || s[b]) return;
1461
+ const u = async function(c, ...p) {
1462
+ if (!c || typeof c != "object") return s.call(this, c, ...p);
1463
+ if (c?.opts?.sf?.rid) return s.call(this, c, ...p);
1464
+ const h = T(() => {
1465
+ const f = [];
1466
+ return { hops: f, out: ke(c, f) };
1467
+ }, "bullmq.FlowProducer.add");
1468
+ if (h === null) return s.call(this, c, ...p);
1469
+ let g = null;
1470
+ try {
1471
+ return await s.call(this, h.out, ...p);
1472
+ } catch (f) {
1473
+ throw g = f instanceof Error ? f : new Error(String(f)), f;
1474
+ } finally {
1475
+ for (const f of h.hops) f.hopEnd(g);
1476
+ }
1477
+ };
1478
+ u[b] = !0, U(a.prototype, "add", u);
1479
+ })(d), (function(a) {
1480
+ const s = a.prototype.addBulk;
1481
+ if (typeof s != "function" || s[b]) return;
1482
+ const u = async function(c) {
1483
+ if (!Array.isArray(c) || c.length === 0) return s.call(this, c);
1484
+ if (c.every((f) => f?.opts?.sf?.rid)) return s.call(this, c);
1485
+ const p = m().bullmqBulkAggregateMode, h = T(() => {
1486
+ if (p) {
1487
+ const S = (E) => {
1488
+ let k = 1;
1489
+ if (Array.isArray(E?.children)) for (const q of E.children) k += S(q);
1490
+ return k;
1491
+ }, I = c.reduce((E, k) => E + S(k), 0), v = P({ library: "bullmq-flow", queueUri: C(c[0]?.queueName, `__flow_bulk_${c.length}`), method: "ENQUEUE_BULK", messagePayload: { batchSize: c.length, totalNodes: I } }), _ = c.map((E) => ht(E, v.traceId));
1492
+ return { hops: [v], out: _ };
1493
+ }
1494
+ const f = [], y = c.map((S) => ke(S, f));
1495
+ return { hops: f, out: y };
1496
+ }, "bullmq.FlowProducer.addBulk");
1497
+ if (h === null) return s.call(this, c);
1498
+ let g = null;
1499
+ try {
1500
+ return await s.call(this, h.out);
1501
+ } catch (f) {
1502
+ throw g = f instanceof Error ? f : new Error(String(f)), f;
1503
+ } finally {
1504
+ for (const f of h.hops) f.hopEnd(g);
1505
+ }
1506
+ };
1507
+ u[b] = !0, U(a.prototype, "addBulk", u);
1508
+ })(d)), t.QueueScheduler?.prototype && m().sfDebug && console.log("[sf-veritas] BullMQ QueueScheduler detected (v4 API). No direct instrumentation needed — delayed/repeatable jobs are traced when the Worker picks them up via the Worker.processJob wrap."), "installed";
1509
+ }
1510
+ function ke(n, t) {
1511
+ const e = P({ queueUri: C(n?.queueName, n?.name), messagePayload: n?.data });
1512
+ t.push(e);
1513
+ const o = { ...n, opts: R(n?.opts, e.traceId) };
1514
+ return Array.isArray(n?.children) && n.children.length > 0 && (o.children = n.children.map((r) => ke(r, t))), o;
1515
+ }
1516
+ function ht(n, t) {
1517
+ const e = { ...n, opts: R(n?.opts, t) };
1518
+ return Array.isArray(n?.children) && n.children.length > 0 && (e.children = n.children.map((o) => ht(o, t))), e;
1519
+ }
1520
+ function ln(n) {
1521
+ let t = n;
1522
+ if (!t) try {
1523
+ t = require("@taskforcesh/bullmq-pro");
1524
+ } catch {
1525
+ return "not-installed";
1526
+ }
1527
+ const e = t.QueuePro, o = t.WorkerPro;
1528
+ t.JobPro;
1529
+ const r = t.FlowProducerPro;
1530
+ return e?.prototype || o?.prototype ? (e?.prototype && ((function(i) {
1531
+ const d = i.prototype.add;
1532
+ if (typeof d != "function" || d[b]) return;
1533
+ const l = async function(a, s, u) {
1534
+ if (u?.sf?.rid) return d.call(this, a, s, u);
1535
+ const c = T(() => {
1536
+ const h = P({ library: "bullmq-pro", queueUri: C(this?.name, a), messagePayload: s });
1537
+ return { handle: h, nextOpts: R(u, h.traceId) };
1538
+ }, "bullmq-pro.QueuePro.add");
1539
+ if (c === null) return d.call(this, a, s, u);
1540
+ let p = null;
1541
+ try {
1542
+ return await d.call(this, a, s, c.nextOpts);
1543
+ } catch (h) {
1544
+ throw p = h instanceof Error ? h : new Error(String(h)), h;
1545
+ } finally {
1546
+ c.handle.hopEnd(p);
1547
+ }
1548
+ };
1549
+ l[b] = !0, U(i.prototype, "add", l);
1550
+ })(e), (function(i) {
1551
+ const d = i.prototype.addBulk;
1552
+ if (typeof d != "function" || d[b]) return;
1553
+ const l = async function(a) {
1554
+ if (!Array.isArray(a) || a.length === 0) return d.call(this, a);
1555
+ if (a.every((p) => p?.opts?.sf?.rid)) return d.call(this, a);
1556
+ const s = m().bullmqBulkAggregateMode, u = T(() => {
1557
+ if (s) {
1558
+ const g = P({ library: "bullmq-pro", queueUri: C(this?.name, `__bulk_${a.length}`), method: "ENQUEUE_BULK", messagePayload: { batchSize: a.length } }), f = a.map((y) => ({ ...y, opts: R(y?.opts, g.traceId) }));
1559
+ return { handles: [g], out: f };
1560
+ }
1561
+ const p = a.map((g) => P({ library: "bullmq-pro", queueUri: C(this?.name, g?.name), messagePayload: g?.data })), h = a.map((g, f) => ({ ...g, opts: R(g?.opts, p[f].traceId) }));
1562
+ return { handles: p, out: h };
1563
+ }, "bullmq-pro.QueuePro.addBulk");
1564
+ if (u === null) return d.call(this, a);
1565
+ let c = null;
1566
+ try {
1567
+ return await d.call(this, u.out);
1568
+ } catch (p) {
1569
+ throw c = p instanceof Error ? p : new Error(String(p)), p;
1570
+ } finally {
1571
+ for (const p of u.handles) p.hopEnd(c);
1572
+ }
1573
+ };
1574
+ l[b] = !0, U(i.prototype, "addBulk", l);
1575
+ })(e)), o?.prototype && ((function(i) {
1576
+ const d = i.prototype.processJob;
1577
+ typeof d != "function" || d[b] || Ve(i, "processJob", d);
1578
+ })(o), (function(i) {
1579
+ const d = i.prototype.getNextJob;
1580
+ if (typeof d != "function" || d[b]) return;
1581
+ const l = async function(...a) {
1582
+ const s = await d.apply(this, a);
1583
+ if (s && z(s.opts?.sf?.rid)) try {
1584
+ const c = x.getInstance();
1585
+ (!(u = c.getTraceId()) || u.startsWith("nonsession-applogs-v3/")) && c.setTraceId(s.opts.sf.rid);
1586
+ } catch {
1587
+ }
1588
+ var u;
1589
+ return s;
1590
+ };
1591
+ l[b] = !0, U(i.prototype, "getNextJob", l);
1592
+ })(o), typeof o.prototype.callProcessJob == "function" && (function(i) {
1593
+ const d = i.prototype.callProcessJob;
1594
+ typeof d != "function" || d[b] || Ve(i, "callProcessJob", d);
1595
+ })(o)), r?.prototype && (function(i) {
1596
+ const d = i.prototype.add;
1597
+ if (typeof d != "function" || d[b]) return;
1598
+ const l = async function(a, ...s) {
1599
+ if (!a || typeof a != "object") return d.call(this, a, ...s);
1600
+ if (a?.opts?.sf?.rid) return d.call(this, a, ...s);
1601
+ const u = T(() => {
1602
+ const p = [];
1603
+ return { hops: p, out: yt(a, p) };
1604
+ }, "bullmq-pro.FlowProducerPro.add");
1605
+ if (u === null) return d.call(this, a, ...s);
1606
+ let c = null;
1607
+ try {
1608
+ return await d.call(this, u.out, ...s);
1609
+ } catch (p) {
1610
+ throw c = p instanceof Error ? p : new Error(String(p)), p;
1611
+ } finally {
1612
+ for (const p of u.hops) p.hopEnd(c);
1613
+ }
1614
+ };
1615
+ l[b] = !0, U(i.prototype, "add", l);
1616
+ })(r), "installed") : (m().sfDebug && console.warn("[asyncQueues][bullmq-pro] No QueuePro/WorkerPro found — patch no-op."), "failed");
1617
+ }
1618
+ function Ve(n, t, e) {
1619
+ const o = function(r, ...i) {
1620
+ const d = r?.opts?.sf?.rid, l = typeof r?.attemptsMade == "number" ? r.attemptsMade : 0, a = typeof r?.stalledCounter == "number" ? r.stalledCounter : 0, s = r?.repeatJobKey != null || r?.opts?.repeat != null, u = z(d) && (l > 0 || a > 0 || s) ? V(d) : z(d) ? d : void 0;
1621
+ let c;
1622
+ return a > 0 ? c = "CONSUME_STALLED" : s && l === 0 && (c = "CONSUME_SCHEDULED"), L({ library: "bullmq-pro", queueUri: C(ce(r) ?? this?.name, r?.name), incomingTraceId: u, messagePayload: r?.data, method: c }, () => e.call(this, r, ...i));
1623
+ };
1624
+ o[b] = !0, U(n.prototype, t, o);
1625
+ }
1626
+ function yt(n, t, e = 0) {
1627
+ if (e > 100) return n;
1628
+ const o = P({ queueUri: C(n?.queueName, n?.name), messagePayload: n?.data });
1629
+ t.push(o);
1630
+ const r = { ...n, opts: R(n?.opts, o.traceId) };
1631
+ return Array.isArray(n?.children) && n.children.length > 0 && (r.children = n.children.map((i) => yt(i, t, e + 1))), r;
1632
+ }
1633
+ const Ue = Y.toLowerCase();
1634
+ function J(n) {
1635
+ if (n != null) {
1636
+ if (typeof n == "string") return n;
1637
+ if (Buffer.isBuffer(n)) try {
1638
+ return n.toString("utf8");
1639
+ } catch {
1640
+ return;
1641
+ }
1642
+ if (n instanceof Uint8Array) try {
1643
+ return Buffer.from(n).toString("utf8");
1644
+ } catch {
1645
+ return;
1646
+ }
1647
+ return String(n);
1648
+ }
1649
+ }
1650
+ function O(n, t = "broker") {
1651
+ return `kafka://${t}/${n ?? "unknown"}`;
1652
+ }
1653
+ function Z(n) {
1654
+ if (Array.isArray(n)) for (const t of n) {
1655
+ if (!t || typeof t != "object") continue;
1656
+ const e = t.key;
1657
+ if (typeof e == "string" && e.toLowerCase() === Ue) return J(t.value);
1658
+ }
1659
+ }
1660
+ function gt(n, t) {
1661
+ const e = [];
1662
+ if (Array.isArray(n)) {
1663
+ for (const o of n) if (o && typeof o == "object") {
1664
+ const r = o.key, i = o.value;
1665
+ typeof r == "string" && r.toLowerCase() === Ue || e.push({ key: String(r), value: Buffer.isBuffer(i) ? i : Buffer.from(String(i ?? "")) });
1666
+ }
1667
+ } else if (n && typeof n == "object") for (const [o, r] of Object.entries(n)) o.toLowerCase() !== Ue && e.push({ key: o, value: Buffer.isBuffer(r) ? r : Buffer.from(String(r ?? "")) });
1668
+ return e.push({ key: Y, value: Buffer.from(t) }), e;
1669
+ }
1670
+ function dn(n) {
1671
+ let t = n;
1672
+ if (!t) try {
1673
+ t = require("@confluentinc/kafka-javascript");
1674
+ } catch {
1675
+ return "not-installed";
1676
+ }
1677
+ let e = !1;
1678
+ t.KafkaProducer?.prototype && ((function(r) {
1679
+ const i = r.prototype.produce;
1680
+ if (typeof i != "function" || i[b]) return;
1681
+ const d = function(...l) {
1682
+ return l.length === 1 && l[0] && typeof l[0] == "object" && Array.isArray(l[0].messages) ? pn.call(this, i, l[0]) : fn.call(this, i, l);
1683
+ };
1684
+ d[b] = !0, U(r.prototype, "produce", d);
1685
+ })(t.KafkaProducer), e = !0), t.KafkaConsumer?.prototype && ((function(r) {
1686
+ const i = r.prototype.on;
1687
+ if (typeof i != "function" || i[b]) return;
1688
+ const d = function(l, a) {
1689
+ if (l !== "data" || typeof a != "function") return i.call(this, l, a);
1690
+ const s = function(u) {
1691
+ const c = Z(u?.headers), p = u?.topic, h = J(u?.value) ?? u?.value;
1692
+ return L({ library: "confluent-kafka-js", queueUri: O(p), incomingTraceId: c, messagePayload: h }, () => a.call(this, u));
1693
+ };
1694
+ return i.call(this, l, s);
1695
+ };
1696
+ d[b] = !0, U(r.prototype, "on", d);
1697
+ })(t.KafkaConsumer), e = !0);
1698
+ const o = t.KafkaJS ?? t;
1699
+ return o?.Producer?.prototype?.send && ((function(r) {
1700
+ const i = r.prototype.send;
1701
+ if (typeof i == "function" && !i[b]) {
1702
+ const a = De(i);
1703
+ a[b] = !0, U(r.prototype, "send", a);
1704
+ }
1705
+ const d = r.prototype.sendBatch;
1706
+ if (typeof d == "function" && !d[b]) {
1707
+ const a = Ne(d);
1708
+ a[b] = !0, U(r.prototype, "sendBatch", a);
1709
+ }
1710
+ const l = r.prototype.transaction;
1711
+ if (typeof l == "function" && !l[b]) {
1712
+ const a = Ye(l);
1713
+ a[b] = !0, U(r.prototype, "transaction", a);
1714
+ }
1715
+ })(o.Producer), e = !0), o?.Consumer?.prototype?.run && ((function(r) {
1716
+ const i = r.prototype.run;
1717
+ if (typeof i != "function" || i[b]) return;
1718
+ const d = async function(l) {
1719
+ if (!l || typeof l != "object") return i.call(this, l);
1720
+ const a = { ...l };
1721
+ if (typeof l.eachMessage == "function") {
1722
+ const s = l.eachMessage;
1723
+ a.eachMessage = (u) => {
1724
+ const c = J(W(u?.message?.headers)) ?? Z(u?.message?.headers), p = typeof u?.attempt == "number" ? u.attempt : 0, h = c && p > 0 ? V(c) : c;
1725
+ return L({ library: "confluent-kafka-js", queueUri: O(u?.topic), incomingTraceId: h }, () => s(u));
1726
+ };
1727
+ }
1728
+ if (typeof l.eachBatch == "function") {
1729
+ const s = l.eachBatch;
1730
+ a.eachBatch = (u) => {
1731
+ let c = !1;
1732
+ try {
1733
+ typeof u?.isStale == "function" && (c = !!u.isStale());
1734
+ } catch {
1735
+ }
1736
+ if (c) return s(u);
1737
+ const p = Array.isArray(u?.batch?.messages) ? u.batch.messages[0] : void 0, h = J(W(p?.headers)) ?? Z(p?.headers);
1738
+ return L({ library: "confluent-kafka-js", queueUri: O(u?.batch?.topic), incomingTraceId: h }, () => s(u));
1739
+ };
1740
+ }
1741
+ return i.call(this, a);
1742
+ };
1743
+ d[b] = !0, U(r.prototype, "run", d);
1744
+ })(o.Consumer), e = !0), typeof o?.Kafka == "function" && o.Kafka.prototype && ((function(r) {
1745
+ const i = r.prototype.producer;
1746
+ if (typeof i == "function" && !i[b]) {
1747
+ const l = function(...a) {
1748
+ const s = i.apply(this, a);
1749
+ return s && typeof s.send == "function" && !s.send[w] && (s.send = De(s.send.bind(s)), s.send[w] = !0), s && typeof s.sendBatch == "function" && !s.sendBatch[w] && (s.sendBatch = Ne(s.sendBatch.bind(s)), s.sendBatch[w] = !0), s && typeof s.transaction == "function" && !s.transaction[w] && (s.transaction = Ye(s.transaction.bind(s)), s.transaction[w] = !0), s;
1750
+ };
1751
+ l[b] = !0, U(r.prototype, "producer", l);
1752
+ }
1753
+ const d = r.prototype.consumer;
1754
+ if (typeof d == "function" && !d[b]) {
1755
+ const l = function(...a) {
1756
+ const s = d.apply(this, a);
1757
+ if (s && typeof s.run == "function" && !s.run[w]) {
1758
+ const u = s.run.bind(s);
1759
+ s.run = async function(c) {
1760
+ if (!c || typeof c != "object") return u(c);
1761
+ const p = { ...c };
1762
+ if (typeof c.eachMessage == "function") {
1763
+ const h = c.eachMessage;
1764
+ p.eachMessage = (g) => {
1765
+ const f = J(W(g?.message?.headers)) ?? Z(g?.message?.headers);
1766
+ return L({ library: "confluent-kafka-js", queueUri: O(g?.topic), incomingTraceId: f }, () => h(g));
1767
+ };
1768
+ }
1769
+ if (typeof c.eachBatch == "function") {
1770
+ const h = c.eachBatch;
1771
+ p.eachBatch = (g) => {
1772
+ let f = !1;
1773
+ try {
1774
+ typeof g?.isStale == "function" && (f = !!g.isStale());
1775
+ } catch {
1776
+ }
1777
+ if (f) return h(g);
1778
+ const y = Array.isArray(g?.batch?.messages) ? g.batch.messages[0] : void 0, S = J(W(y?.headers)) ?? Z(y?.headers);
1779
+ return L({ library: "confluent-kafka-js", queueUri: O(g?.batch?.topic), incomingTraceId: S }, () => h(g));
1780
+ };
1781
+ }
1782
+ return u(p);
1783
+ }, s.run[w] = !0;
1784
+ }
1785
+ return s;
1786
+ };
1787
+ l[b] = !0, U(r.prototype, "consumer", l);
1788
+ }
1789
+ })(o.Kafka), e = !0), e ? "installed" : (m().sfDebug && console.warn("[asyncQueues][confluentKafkaJs] No recognizable Producer/Consumer/Kafka class — patch no-op."), "failed");
1790
+ }
1791
+ function pn(n, t) {
1792
+ const e = T(() => {
1793
+ const r = t?.topic, i = t.messages.map(() => P({ library: "confluent-kafka-js", queueUri: O(r), method: "ENQUEUE_BUFFERED" })), d = t.messages.map((l, a) => ({ ...l, headers: gt(l?.headers, i[a].traceId) }));
1794
+ return { handles: i, outOptions: { ...t, messages: d } };
1795
+ }, "confluentKafkaJs.KafkaProducer.produce(object)");
1796
+ if (e === null) return n.call(this, t);
1797
+ let o = null;
1798
+ try {
1799
+ return n.call(this, e.outOptions);
1800
+ } catch (r) {
1801
+ throw o = r instanceof Error ? r : new Error(String(r)), r;
1802
+ } finally {
1803
+ for (const r of e.handles) r.hopEnd(o);
1804
+ }
1805
+ }
1806
+ function fn(n, t) {
1807
+ const [e, o, r, i, d, l, a] = t, s = T(() => {
1808
+ const c = P({ library: "confluent-kafka-js", queueUri: O(typeof e == "string" ? e : void 0), method: "ENQUEUE_BUFFERED" });
1809
+ return { handle: c, injectedHeaders: gt(a, c.traceId) };
1810
+ }, "confluentKafkaJs.KafkaProducer.produce(positional)");
1811
+ if (s === null) return n.call(this, e, o, r, i, d, l, a);
1812
+ let u = null;
1813
+ try {
1814
+ return n.call(this, e, o, r, i, d, l, s.injectedHeaders);
1815
+ } catch (c) {
1816
+ throw u = c instanceof Error ? c : new Error(String(c)), c;
1817
+ } finally {
1818
+ s.handle.hopEnd(u);
1819
+ }
1820
+ }
1821
+ function De(n, t = {}) {
1822
+ const e = t.method ?? "ENQUEUE", o = t.library ?? "confluent-kafka-js";
1823
+ return async function(r) {
1824
+ if (!r || !Array.isArray(r.messages)) return n.call(this, r);
1825
+ const i = T(() => {
1826
+ const l = r.messages.map(() => P({ library: o, queueUri: O(r.topic), method: e })), a = r.messages.map((s, u) => ({ ...s, headers: { ...s?.headers || {}, [Y]: Buffer.from(l[u].traceId) } }));
1827
+ return { handles: l, outPayload: { ...r, messages: a } };
1828
+ }, `confluentKafkaJs.Producer.${e}`);
1829
+ if (i === null) return n.call(this, r);
1830
+ let d = null;
1831
+ try {
1832
+ return await n.call(this, i.outPayload);
1833
+ } catch (l) {
1834
+ throw d = l instanceof Error ? l : new Error(String(l)), l;
1835
+ } finally {
1836
+ for (const l of i.handles) l.hopEnd(d);
1837
+ }
1838
+ };
1839
+ }
1840
+ function Ne(n, t = {}) {
1841
+ const e = t.method ?? "ENQUEUE", o = t.library ?? "confluent-kafka-js";
1842
+ return async function(r) {
1843
+ if (!r || !Array.isArray(r.topicMessages)) return n.call(this, r);
1844
+ const i = T(() => {
1845
+ const l = [], a = r.topicMessages.map((s) => {
1846
+ const u = (Array.isArray(s?.messages) ? s.messages : []).map((c) => {
1847
+ const p = P({ library: o, queueUri: O(s?.topic), method: e });
1848
+ return l.push(p), { ...c, headers: { ...c?.headers || {}, [Y]: Buffer.from(p.traceId) } };
1849
+ });
1850
+ return { ...s, messages: u };
1851
+ });
1852
+ return { handles: l, outPayload: { ...r, topicMessages: a } };
1853
+ }, `confluentKafkaJs.Producer.sendBatch[${e}]`);
1854
+ if (i === null) return n.call(this, r);
1855
+ let d = null;
1856
+ try {
1857
+ return await n.call(this, i.outPayload);
1858
+ } catch (l) {
1859
+ throw d = l instanceof Error ? l : new Error(String(l)), l;
1860
+ } finally {
1861
+ for (const l of i.handles) l.hopEnd(d);
1862
+ }
1863
+ };
1864
+ }
1865
+ function Xe(n, t) {
1866
+ return async function(...e) {
1867
+ const o = P({ queueUri: "kafka://broker/_tx", method: t });
1868
+ let r = null;
1869
+ try {
1870
+ return await n.apply(this, e);
1871
+ } catch (i) {
1872
+ throw r = i instanceof Error ? i : new Error(String(i)), i;
1873
+ } finally {
1874
+ o.hopEnd(r);
1875
+ }
1876
+ };
1877
+ }
1878
+ function Ye(n) {
1879
+ return async function(...t) {
1880
+ const e = await n.apply(this, t);
1881
+ return e && typeof e.send == "function" && !e.send[w] && (e.send = De(e.send.bind(e), { method: "ENQUEUE_TX", library: "confluent-kafka-js-tx" }), e.send[w] = !0), e && typeof e.sendBatch == "function" && !e.sendBatch[w] && (e.sendBatch = Ne(e.sendBatch.bind(e), { method: "ENQUEUE_TX", library: "confluent-kafka-js-tx" }), e.sendBatch[w] = !0), e && typeof e.commit == "function" && !e.commit[w] && (e.commit = Xe(e.commit.bind(e), "COMMIT_TX"), e.commit[w] = !0), e && typeof e.abort == "function" && !e.abort[w] && (e.abort = Xe(e.abort.bind(e), "ABORT_TX"), e.abort[w] = !0), e;
1882
+ };
1883
+ }
1884
+ function me(n) {
1885
+ if (n != null) {
1886
+ if (typeof n == "string") return n;
1887
+ if (Buffer.isBuffer(n)) try {
1888
+ return n.toString("utf8");
1889
+ } catch {
1890
+ return;
1891
+ }
1892
+ if (n instanceof Uint8Array) try {
1893
+ return Buffer.from(n).toString("utf8");
1894
+ } catch {
1895
+ return;
1896
+ }
1897
+ return String(n);
1898
+ }
1899
+ }
1900
+ function ue(n, t) {
1901
+ return `kafka://broker/${n ?? "unknown"}`;
1902
+ }
1903
+ function hn(n) {
1904
+ let t = n;
1905
+ if (!t) try {
1906
+ t = require("kafkajs");
1907
+ } catch {
1908
+ return "not-installed";
1909
+ }
1910
+ const e = t.Producer, o = t.Consumer;
1911
+ e?.prototype && typeof e.prototype.send == "function" && (function(i) {
1912
+ const d = i.prototype.send;
1913
+ if (typeof d == "function" && !d[b]) {
1914
+ const s = Pe(d);
1915
+ s[b] = !0, U(i.prototype, "send", s);
1916
+ }
1917
+ const l = i.prototype.sendBatch;
1918
+ if (typeof l == "function" && !l[b]) {
1919
+ const s = Fe(l);
1920
+ s[b] = !0, U(i.prototype, "sendBatch", s);
1921
+ }
1922
+ const a = i.prototype.transaction;
1923
+ if (typeof a == "function" && !a[b]) {
1924
+ const s = et(a);
1925
+ s[b] = !0, U(i.prototype, "transaction", s);
1926
+ }
1927
+ })(e), o?.prototype && typeof o.prototype.run == "function" && (function(i) {
1928
+ const d = i.prototype.run;
1929
+ if (typeof d != "function" || d[b]) return;
1930
+ const l = tt(d);
1931
+ l[b] = !0, U(i.prototype, "run", l);
1932
+ })(o);
1933
+ const r = t.Kafka;
1934
+ if (typeof r == "function" && r.prototype) (function(i) {
1935
+ const d = i.prototype.producer;
1936
+ if (typeof d == "function" && !d[b]) {
1937
+ const a = function(...s) {
1938
+ const u = d.apply(this, s);
1939
+ return u && typeof u.send == "function" && !u.send[w] && (u.send = Pe(u.send.bind(u)), u.send[w] = !0), u && typeof u.sendBatch == "function" && !u.sendBatch[w] && (u.sendBatch = Fe(u.sendBatch.bind(u)), u.sendBatch[w] = !0), u && typeof u.transaction == "function" && !u.transaction[w] && (u.transaction = et(u.transaction.bind(u)), u.transaction[w] = !0), u;
1940
+ };
1941
+ a[b] = !0, U(i.prototype, "producer", a);
1942
+ }
1943
+ const l = i.prototype.consumer;
1944
+ if (typeof l == "function" && !l[b]) {
1945
+ const a = function(...s) {
1946
+ const u = l.apply(this, s);
1947
+ return u && typeof u.run == "function" && !u.run[w] && (u.run = tt(u.run.bind(u)), u.run[w] = !0), u;
1948
+ };
1949
+ a[b] = !0, U(i.prototype, "consumer", a);
1950
+ }
1951
+ })(r);
1952
+ else if (!e?.prototype && !o?.prototype) return m().sfDebug && console.warn("[asyncQueues][kafkajs] No Kafka/Producer/Consumer class found — patch no-op."), "failed";
1953
+ return "installed";
1954
+ }
1955
+ function Pe(n, t = {}) {
1956
+ const e = t.method ?? "ENQUEUE", o = t.library ?? "kafkajs";
1957
+ return async function(r) {
1958
+ if (!r || !Array.isArray(r.messages)) return n.call(this, r);
1959
+ const i = T(() => {
1960
+ const l = r.topic, a = r.messages.map(() => P({ library: o, queueUri: ue(l), method: e })), s = r.messages.map((c, p) => mt(c, a[p].traceId)), u = { ...r, messages: s };
1961
+ return { handles: a, outPayload: u };
1962
+ }, `kafkajs.Producer.${e}`);
1963
+ if (i === null) return n.call(this, r);
1964
+ let d = null;
1965
+ try {
1966
+ return await n.call(this, i.outPayload);
1967
+ } catch (l) {
1968
+ throw d = l instanceof Error ? l : new Error(String(l)), l;
1969
+ } finally {
1970
+ for (const l of i.handles) l.hopEnd(d);
1971
+ }
1972
+ };
1973
+ }
1974
+ function Fe(n, t = {}) {
1975
+ const e = t.method ?? "ENQUEUE", o = t.library ?? "kafkajs";
1976
+ return async function(r) {
1977
+ if (!r || !Array.isArray(r.topicMessages)) return n.call(this, r);
1978
+ const i = T(() => {
1979
+ const l = [], a = r.topicMessages.map((u) => {
1980
+ const c = u?.topic, p = (Array.isArray(u?.messages) ? u.messages : []).map((h) => {
1981
+ const g = P({ library: o, queueUri: ue(c), method: e });
1982
+ return l.push(g), mt(h, g.traceId);
1983
+ });
1984
+ return { ...u, messages: p };
1985
+ }), s = { ...r, topicMessages: a };
1986
+ return { handles: l, outPayload: s };
1987
+ }, `kafkajs.Producer.sendBatch[${e}]`);
1988
+ if (i === null) return n.call(this, r);
1989
+ let d = null;
1990
+ try {
1991
+ return await n.call(this, i.outPayload);
1992
+ } catch (l) {
1993
+ throw d = l instanceof Error ? l : new Error(String(l)), l;
1994
+ } finally {
1995
+ for (const l of i.handles) l.hopEnd(d);
1996
+ }
1997
+ };
1998
+ }
1999
+ function Ze(n, t) {
2000
+ return async function(...e) {
2001
+ const o = P({ queueUri: "kafka://broker/_tx", method: t });
2002
+ let r = null;
2003
+ try {
2004
+ return await n.apply(this, e);
2005
+ } catch (i) {
2006
+ throw r = i instanceof Error ? i : new Error(String(i)), i;
2007
+ } finally {
2008
+ o.hopEnd(r);
2009
+ }
2010
+ };
2011
+ }
2012
+ function et(n) {
2013
+ return async function(...t) {
2014
+ const e = await n.apply(this, t);
2015
+ return e && typeof e.send == "function" && !e.send[w] && (e.send = Pe(e.send.bind(e), { method: "ENQUEUE_TX", library: "kafkajs-tx" }), e.send[w] = !0), e && typeof e.sendBatch == "function" && !e.sendBatch[w] && (e.sendBatch = Fe(e.sendBatch.bind(e), { method: "ENQUEUE_TX", library: "kafkajs-tx" }), e.sendBatch[w] = !0), e && typeof e.commit == "function" && !e.commit[w] && (e.commit = Ze(e.commit.bind(e), "COMMIT_TX"), e.commit[w] = !0), e && typeof e.abort == "function" && !e.abort[w] && (e.abort = Ze(e.abort.bind(e), "ABORT_TX"), e.abort[w] = !0), e;
2016
+ };
2017
+ }
2018
+ function mt(n, t) {
2019
+ const e = { ...n?.headers || {} };
2020
+ return e[Y] = Buffer.from(t), { ...n, headers: e };
2021
+ }
2022
+ function tt(n) {
2023
+ return async function(t) {
2024
+ if (!t || typeof t != "object") return n.call(this, t);
2025
+ const e = { ...t };
2026
+ if (typeof t.eachMessage == "function") {
2027
+ const o = t.eachMessage;
2028
+ e.eachMessage = (r) => (async function(i, d) {
2029
+ const l = i?.topic, a = i?.message, s = me(W(a?.headers)), u = typeof i?.attempt == "number" ? i.attempt : 0, c = s && u > 0 ? V(s) : s, p = me(a?.value) ?? a?.value;
2030
+ return L({ library: "kafkajs", queueUri: ue(l), incomingTraceId: c, messagePayload: p }, () => d(i));
2031
+ })(r, o);
2032
+ }
2033
+ if (typeof t.eachBatch == "function") {
2034
+ const o = t.eachBatch;
2035
+ e.eachBatch = (r) => (async function(i, d) {
2036
+ let l = !1;
2037
+ try {
2038
+ typeof i?.isStale == "function" && (l = !!i.isStale());
2039
+ } catch {
2040
+ }
2041
+ if (l) return d(i);
2042
+ const a = i?.batch?.topic, s = Array.isArray(i?.batch?.messages) ? i.batch.messages[0] : void 0, u = me(W(s?.headers));
2043
+ return L({ library: "kafkajs", queueUri: ue(a), incomingTraceId: u }, () => d(i));
2044
+ })(r, o);
2045
+ }
2046
+ return n.call(this, e);
2047
+ };
2048
+ }
2049
+ function yn(n) {
2050
+ return process.env[n] === "true";
2051
+ }
2052
+ const gn = [{ name: "bullmq", envDisableKey: "SF_DISABLE_BULLMQ", install: () => un() }, { name: "@taskforcesh/bullmq-pro", envDisableKey: "SF_DISABLE_BULLMQ_PRO", install: () => ln() }, { name: "kafkajs", envDisableKey: "SF_DISABLE_KAFKAJS", install: () => hn() }, { name: "@confluentinc/kafka-javascript", envDisableKey: "SF_DISABLE_CONFLUENT_KAFKA_JS", install: () => dn() }];
2053
+ let le = !1;
2054
+ function Pn() {
2055
+ return le;
2056
+ }
2057
+ function Fn() {
2058
+ const n = (function() {
2059
+ let t = 0;
2060
+ for (const { proto: e, key: o, original: r } of we.splice(0)) try {
2061
+ r === void 0 ? delete e[o] : e[o] = r, t += 1;
2062
+ } catch {
2063
+ }
2064
+ return t;
2065
+ })();
2066
+ return le = !1, n;
2067
+ }
2068
+ let qe = !1, Se = !1;
2069
+ function qn(n) {
2070
+ if (Se) console.warn("[setupInterceptors] ⚠️ Recursive call detected and blocked!");
2071
+ else if (!qe) {
2072
+ Se = !0, Ut();
1007
2073
  try {
1008
2074
  let t, e;
1009
- const i = he(new Error().stack);
1010
- if (i) {
1011
- const c = i.split(`
1012
- `)[2] || "", o = c.match(/\((.+):(\d+):\d+\)/) || c.match(/at (.+):(\d+):\d+/);
1013
- o && (t = o[1], e = parseInt(o[2], 10));
2075
+ const o = ot(new Error().stack);
2076
+ if (o) {
2077
+ const l = o.split(`
2078
+ `)[2] || "", a = l.match(/\((.+):(\d+):\d+\)/) || l.match(/at (.+):(\d+):\d+/);
2079
+ a && (t = a[1], e = parseInt(a[2], 10));
1014
2080
  }
1015
- if (!r || !r.apiKey) {
1016
- const c = `The required API Key is not provided: ${JSON.stringify(r)}`;
1017
- console.error(c);
2081
+ if (!n || !n.apiKey) {
2082
+ const l = `The required API Key is not provided: ${JSON.stringify(n)}`;
2083
+ console.error(l);
1018
2084
  }
1019
- const { config: n } = _e(r);
1020
- if (Fe(n).catch(() => {
1021
- }), t && (n.setupInterceptorsFile = t), e && (n.setupInterceptorsLine = e), n.sfDebug && console.log("Updated configuration after applying options:", n), !n.apiKey || !n.apiGraphqlEndpoint) {
1022
- const c = `The required config is not provided: ${JSON.stringify(n)}`;
1023
- throw console.error(c), new Error(c);
2085
+ const { config: r } = Et(n);
2086
+ if ($t(r).catch(() => {
2087
+ }), t && (r.setupInterceptorsFile = t), e && (r.setupInterceptorsLine = e), r.sfDebug && console.log("Updated configuration after applying options:", r), !r.apiKey || !r.apiGraphqlEndpoint) {
2088
+ const l = `The required config is not provided: ${JSON.stringify(r)}`;
2089
+ throw console.error(l), new Error(l);
1024
2090
  }
1025
- Ze() || Xe(void 0, n.sfDebug).catch((c) => {
1026
- n.sfDebug && console.error("[FuncSpan] Failed to initialize config loader:", c);
1027
- }), process.env.SF_WORKER_POOL_DISABLED === "true" ? n.sfDebug && console.log("[setupInterceptors] Worker pool patching DISABLED (SF_WORKER_POOL_DISABLED=true)") : ot() || (st(), n.sfDebug && console.log("[setupInterceptors] Worker pool patching initialized (DNS tracking enabled)"));
1028
- const s = new te();
1029
- s.setServiceUUID(n.serviceUUID), Ue(s), (function(c = []) {
1030
- const o = new ze(c);
1031
- new We().doSend(o.getExcludedDomains());
1032
- const d = new je(), p = new Ve();
1033
- o.patchFetch(d, p), o.patchHttp(d, p);
1034
- })(n.domainsToNotPropagateHeadersTo);
1035
- const l = new Be();
1036
- l.setServiceUUID(n.serviceUUID), ke(l), Ke(), new Je().send(), Z = !0, n.sfDebug && console.log("[setupInterceptors] ✅ Initialization complete");
2091
+ Yt() || Vt(void 0, r.sfDebug).catch((l) => {
2092
+ r.sfDebug && console.error("[FuncSpan] Failed to initialize config loader:", l);
2093
+ }), process.env.SF_WORKER_POOL_DISABLED === "true" ? r.sfDebug && console.log("[setupInterceptors] Worker pool patching DISABLED (SF_WORKER_POOL_DISABLED=true)") : sn() || (on(), r.sfDebug && console.log("[setupInterceptors] Worker pool patching initialized (DNS tracking enabled)"));
2094
+ const i = new Ce();
2095
+ i.setServiceUUID(r.serviceUUID), qt(i), (function(l = []) {
2096
+ const a = new Wt(l);
2097
+ new Qt().doSend(a.getExcludedDomains());
2098
+ const s = new Jt(), u = new it();
2099
+ a.patchFetch(s, u), a.patchHttp(s, u);
2100
+ })(r.domainsToNotPropagateHeadersTo);
2101
+ const d = new xt();
2102
+ d.setServiceUUID(r.serviceUUID), Ct(d), Kt(), new Gt().send(), (function() {
2103
+ if (le) return;
2104
+ if (le = !0, process.env.SF_DISABLE_QUEUE_PATCHES === "true") return void (m().sfDebug && console.log("[sf-veritas] Async queue tracing DISABLED via SF_DISABLE_QUEUE_PATCHES=true"));
2105
+ const l = m(), a = [], s = [], u = [], c = [];
2106
+ for (const { name: h, envDisableKey: g, install: f } of gn) {
2107
+ if (yn(g)) {
2108
+ u.push(h);
2109
+ continue;
2110
+ }
2111
+ let y = "failed";
2112
+ try {
2113
+ y = f();
2114
+ } catch (S) {
2115
+ l.sfDebug && console.warn(`[asyncQueues] Failed to install ${h} patch:`, S), c.push(h);
2116
+ continue;
2117
+ }
2118
+ y === "installed" ? a.push(h) : y === "not-installed" ? s.push(h) : c.push(h);
2119
+ }
2120
+ const p = [`active: ${a.length ? a.join(", ") : "(none)"}`];
2121
+ s.length && p.push(`skipped (not installed): ${s.join(", ")}`), u.length && p.push(`disabled by env: ${u.join(", ")}`), c.length && p.push(`failed: ${c.join(", ")}`), (l.sfDebug || c.length > 0) && console.log(`[sf-veritas] Async queue tracing — ${p.join("; ")}`);
2122
+ })(), qe = !0, r.sfDebug && console.log("[setupInterceptors] ✅ Initialization complete");
1037
2123
  } finally {
1038
- V = !1;
2124
+ Se = !1;
1039
2125
  }
1040
2126
  }
1041
2127
  }
1042
- function It() {
1043
- return Z;
2128
+ function Cn() {
2129
+ return qe;
1044
2130
  }
1045
- function vt(r, t, e, i = !1) {
1046
- const n = a();
1047
- new me(n.apiKey).identify(r, t, e, i);
2131
+ function Tn(n, t, e, o = !1) {
2132
+ const r = m();
2133
+ new st(r.apiKey).identify(n, t, e, o);
1048
2134
  }
1049
- function $t(r, t = {}, e, i = !1) {
1050
- const n = a();
1051
- new me(n.apiKey).addOrUpdateMetadata(r, t, e, i);
2135
+ function An(n, t = {}, e, o = !1) {
2136
+ const r = m();
2137
+ new st(r.apiKey).addOrUpdateMetadata(n, t, e, o);
1052
2138
  }
1053
- let z = null;
1054
- function bt(r, t, e, i) {
1055
- const n = function(...s) {
1056
- const l = fe(), c = l?.sfDebug || !1;
1057
- c && console.log(`[FuncSpan] captureFunctionSpan wrapper called for ${e}::${t}`);
1058
- const o = (function(h, f) {
1059
- const I = Q();
1060
- if (I) {
1061
- const g = X(I);
1062
- if (g) return process.env.SF_DEBUG === "true" && console.log(`[FuncSpan] Using HTTP header override for ${h}::${f}`), g;
2139
+ let be = null;
2140
+ function Bn(n, t, e, o) {
2141
+ const r = function(...i) {
2142
+ const d = nt(), l = d?.sfDebug || !1;
2143
+ l && console.log(`[FuncSpan] captureFunctionSpan wrapper called for ${e}::${t}`);
2144
+ const a = (function(f, y) {
2145
+ const S = Ie();
2146
+ if (S) {
2147
+ const I = ve(S);
2148
+ if (I) return process.env.SF_DEBUG === "true" && console.log(`[FuncSpan] Using HTTP header override for ${f}::${y}`), I;
1063
2149
  }
1064
2150
  try {
1065
- return Ye(h, f);
2151
+ return Xt(f, y);
1066
2152
  } catch {
1067
2153
  return { sample_rate: process.env.SF_FUNCSPAN_SAMPLE_RATE ? parseFloat(process.env.SF_FUNCSPAN_SAMPLE_RATE) : 1, capture_arguments: !0, capture_return_value: !0, arg_limit_mb: 1, return_limit_mb: 1, enable_sampling: !1, autocapture_all_child_functions: !1, capture_sf_veritas: !1, parse_json_strings: !1 };
1068
2154
  }
1069
2155
  })(e, t);
1070
- if (c && console.log(`[FuncSpan] Config for ${e}::${t}:`, o), o.enable_sampling && o.sample_rate < 1 && Math.random() > o.sample_rate) return c && console.log(`[FuncSpan] Skipping ${t} due to sampling`), r.apply(this, s);
1071
- if (o.sample_rate === 0) return c && console.log(`[FuncSpan] Skipping ${t} - sample_rate is 0.0`), r.apply(this, s);
1072
- c && console.log(`[FuncSpan] Capturing function span for ${t}`);
1073
- const d = ee.getInstance(), p = d.getCurrentFunctionSpanId(), u = J();
1074
- d.setCurrentFunctionSpanId(u);
1075
- const y = process.hrtime.bigint(), $ = Date.now();
1076
- let S = null;
1077
- o.capture_arguments && (S = {}, i.paramNames.forEach((h, f) => {
1078
- f < s.length && (S[h] = s[f]);
1079
- }), S && o.arg_limit_mb > 0 && (S = K(S, o.arg_limit_mb)));
2156
+ if (l && console.log(`[FuncSpan] Config for ${e}::${t}:`, a), a.enable_sampling && a.sample_rate < 1 && Math.random() > a.sample_rate) return l && console.log(`[FuncSpan] Skipping ${t} due to sampling`), n.apply(this, i);
2157
+ if (a.sample_rate === 0) return l && console.log(`[FuncSpan] Skipping ${t} - sample_rate is 0.0`), n.apply(this, i);
2158
+ l && console.log(`[FuncSpan] Capturing function span for ${t}`);
2159
+ const s = x.getInstance(), u = s.getCurrentFunctionSpanId(), c = G();
2160
+ s.setCurrentFunctionSpanId(c);
2161
+ const p = process.hrtime.bigint(), h = Date.now();
2162
+ let g = null;
2163
+ a.capture_arguments && (g = {}, o.paramNames.forEach((f, y) => {
2164
+ y < i.length && (g[f] = i[y]);
2165
+ }), g && a.arg_limit_mb > 0 && (g = de(g, a.arg_limit_mb)));
1080
2166
  try {
1081
- const h = r.apply(this, s);
1082
- if (h && typeof h.then == "function") return p ? d.setCurrentFunctionSpanId(p) : d.clearCurrentFunctionSpanId(), h.then((v) => {
1083
- const _ = process.hrtime.bigint(), F = Date.now(), R = Number(_ - y);
1084
- let m = null;
1085
- return o.capture_return_value && o.return_limit_mb > 0 && (m = K(v, o.return_limit_mb)), M({ functionName: t, filePath: e, metadata: i, args: S, result: m, error: null, duration: F - $, durationNs: R, startTimeNs: y.toString(), async: !0, spanId: u, parentSpanId: p, pid: process.pid, threadId: H }), v;
1086
- }, (v) => {
1087
- const _ = process.hrtime.bigint(), F = Date.now(), R = Number(_ - y);
1088
- throw M({ functionName: t, filePath: e, metadata: i, args: S, result: null, error: v?.message || String(v), duration: F - $, durationNs: R, startTimeNs: y.toString(), async: !0, spanId: u, parentSpanId: p, pid: process.pid, threadId: H }), v;
2167
+ const f = n.apply(this, i);
2168
+ if (f && typeof f.then == "function") return u ? s.setCurrentFunctionSpanId(u) : s.clearCurrentFunctionSpanId(), f.then((_) => {
2169
+ const E = process.hrtime.bigint(), k = Date.now(), q = Number(E - p);
2170
+ let $ = null;
2171
+ return a.capture_return_value && a.return_limit_mb > 0 && ($ = de(_, a.return_limit_mb)), se({ functionName: t, filePath: e, metadata: o, args: g, result: $, error: null, duration: k - h, durationNs: q, startTimeNs: p.toString(), async: !0, spanId: c, parentSpanId: u, pid: process.pid, threadId: oe }), _;
2172
+ }, (_) => {
2173
+ const E = process.hrtime.bigint(), k = Date.now(), q = Number(E - p);
2174
+ throw se({ functionName: t, filePath: e, metadata: o, args: g, result: null, error: _?.message || String(_), duration: k - h, durationNs: q, startTimeNs: p.toString(), async: !0, spanId: c, parentSpanId: u, pid: process.pid, threadId: oe }), _;
1089
2175
  });
1090
- const f = process.hrtime.bigint(), I = Date.now(), g = Number(f - y);
1091
- let D = null;
1092
- return o.capture_return_value && o.return_limit_mb > 0 && (D = K(h, o.return_limit_mb)), M({ functionName: t, filePath: e, metadata: i, args: S, result: D, error: null, duration: I - $, durationNs: g, startTimeNs: y.toString(), async: !1, spanId: u, parentSpanId: p, pid: process.pid, threadId: H }), p ? d.setCurrentFunctionSpanId(p) : d.clearCurrentFunctionSpanId(), h;
1093
- } catch (h) {
1094
- const f = process.hrtime.bigint(), I = Date.now(), g = Number(f - y);
1095
- throw M({ functionName: t, filePath: e, metadata: i, args: S, result: null, error: h?.message || String(h), duration: I - $, durationNs: g, startTimeNs: y.toString(), async: !1, spanId: u, parentSpanId: p, pid: process.pid, threadId: H }), p ? d.setCurrentFunctionSpanId(p) : d.clearCurrentFunctionSpanId(), h;
2176
+ const y = process.hrtime.bigint(), S = Date.now(), I = Number(y - p);
2177
+ let v = null;
2178
+ return a.capture_return_value && a.return_limit_mb > 0 && (v = de(f, a.return_limit_mb)), se({ functionName: t, filePath: e, metadata: o, args: g, result: v, error: null, duration: S - h, durationNs: I, startTimeNs: p.toString(), async: !1, spanId: c, parentSpanId: u, pid: process.pid, threadId: oe }), u ? s.setCurrentFunctionSpanId(u) : s.clearCurrentFunctionSpanId(), f;
2179
+ } catch (f) {
2180
+ const y = process.hrtime.bigint(), S = Date.now(), I = Number(y - p);
2181
+ throw se({ functionName: t, filePath: e, metadata: o, args: g, result: null, error: f?.message || String(f), duration: S - h, durationNs: I, startTimeNs: p.toString(), async: !1, spanId: c, parentSpanId: u, pid: process.pid, threadId: oe }), u ? s.setCurrentFunctionSpanId(u) : s.clearCurrentFunctionSpanId(), f;
1096
2182
  }
1097
2183
  };
1098
- Object.defineProperty(n, "name", { value: t, writable: !1 });
1099
- for (const s in r) r.hasOwnProperty(s) && (n[s] = r[s]);
1100
- return n;
1101
- }
1102
- function M(r) {
1103
- const t = fe(), e = t?.sfDebug || !1;
1104
- e && console.log("[FuncSpan] captureSpanData called for:", { function: r.functionName, file: r.filePath, duration: `${r.duration}ms`, async: r.async, error: r.error, spanId: r.spanId });
1105
- const i = { functionName: r.functionName, filePath: r.filePath, metadata: r.metadata, args: r.args, result: r.result, error: r.error, duration: r.duration, durationNs: r.durationNs, async: r.async, spanId: r.spanId, parentSpanId: r.parentSpanId };
2184
+ Object.defineProperty(r, "name", { value: t, writable: !1 });
2185
+ for (const i in n) n.hasOwnProperty(i) && (r[i] = n[i]);
2186
+ return r;
2187
+ }
2188
+ function se(n) {
2189
+ const t = nt(), e = t?.sfDebug || !1;
2190
+ e && console.log("[FuncSpan] captureSpanData called for:", { function: n.functionName, file: n.filePath, duration: `${n.duration}ms`, async: n.async, error: n.error, spanId: n.spanId });
2191
+ const o = { functionName: n.functionName, filePath: n.filePath, metadata: n.metadata, args: n.args, result: n.result, error: n.error, duration: n.duration, durationNs: n.durationNs, async: n.async, spanId: n.spanId, parentSpanId: n.parentSpanId };
1106
2192
  process.env.SF_FUNCSPAN_CONSOLE_OUTPUT === "true" && console.log(`
1107
- 📊 Function Span:`, { function: `${r.functionName} (${r.filePath}:${r.metadata.line}:${r.metadata.column})`, duration: `${r.duration.toFixed(2)}ms`, arguments: r.args, result: r.error ? `Error: ${r.error}` : r.result, spanId: r.spanId, parentSpanId: r.parentSpanId || "none" });
1108
- const n = process.env.SF_FUNCSPAN_JSONL_FILE;
1109
- if (n) try {
1110
- const s = n === "true" || n === "1" ? "funcspans.jsonl" : n, l = Date.now(), c = process.hrtime.bigint(), o = BigInt(r.startTimeNs), d = Number(c - o) / 1e6, p = new Date(l - d).toISOString(), u = JSON.stringify({ timestamp: p, functionName: r.functionName, filePath: r.filePath, line: r.metadata.line, column: r.metadata.column, duration: r.duration, durationNs: r.durationNs, startTimeNs: r.startTimeNs, arguments: r.args, returnValue: r.error ? { error: String(r.error) } : r.result, spanId: r.spanId, parentSpanId: r.parentSpanId, async: r.async, pid: r.pid, threadId: r.threadId }) + `
2193
+ 📊 Function Span:`, { function: `${n.functionName} (${n.filePath}:${n.metadata.line}:${n.metadata.column})`, duration: `${n.duration.toFixed(2)}ms`, arguments: n.args, result: n.error ? `Error: ${n.error}` : n.result, spanId: n.spanId, parentSpanId: n.parentSpanId || "none" });
2194
+ const r = process.env.SF_FUNCSPAN_JSONL_FILE;
2195
+ if (r) try {
2196
+ const i = r === "true" || r === "1" ? "funcspans.jsonl" : r, d = Date.now(), l = process.hrtime.bigint(), a = BigInt(n.startTimeNs), s = Number(l - a) / 1e6, u = new Date(d - s).toISOString(), c = JSON.stringify({ timestamp: u, functionName: n.functionName, filePath: n.filePath, line: n.metadata.line, column: n.metadata.column, duration: n.duration, durationNs: n.durationNs, startTimeNs: n.startTimeNs, arguments: n.args, returnValue: n.error ? { error: String(n.error) } : n.result, spanId: n.spanId, parentSpanId: n.parentSpanId, async: n.async, pid: n.pid, threadId: n.threadId }) + `
1111
2197
  `;
1112
- Ae(s, u, "utf-8");
1113
- } catch (s) {
1114
- console.error("[FuncSpan] Error writing to JSONL file:", s);
2198
+ Rt(i, c, "utf-8");
2199
+ } catch (i) {
2200
+ console.error("[FuncSpan] Error writing to JSONL file:", i);
1115
2201
  }
1116
- if (e && console.log("[FuncSpan] Sending function span to transmitter:", i), process.env.SF_FUNCSPAN_SKIP_BACKEND !== "true") try {
1117
- (z || (z = new Pe()), z).send([i]), e && console.log("[FuncSpan] Function span sent successfully");
1118
- } catch (s) {
1119
- e && console.error("[FuncSpan] Error sending function span:", s);
2202
+ if (e && console.log("[FuncSpan] Sending function span to transmitter:", o), process.env.SF_FUNCSPAN_SKIP_BACKEND !== "true") try {
2203
+ (be || (be = new Dt()), be).send([o]), e && console.log("[FuncSpan] Function span sent successfully");
2204
+ } catch (i) {
2205
+ e && console.error("[FuncSpan] Error sending function span:", i);
1120
2206
  }
1121
2207
  }
1122
- function _t(r) {
1123
- return !!r.includes("captureFunctionSpan(") || !!r.includes("@sailfish-ai/sf-veritas") || !(!r.includes("/* @sailfish-instrumented */") && !r.includes("// @sailfish-instrumented"));
2208
+ function Rn(n) {
2209
+ return !!n.includes("captureFunctionSpan(") || !!n.includes("@sailfish-ai/sf-veritas") || !(!n.includes("/* @sailfish-instrumented */") && !n.includes("// @sailfish-instrumented"));
1124
2210
  }
1125
2211
  export {
1126
- ee as ContextManager,
1127
- $t as addOrUpdateMetadata,
1128
- bt as captureFunctionSpan,
1129
- Et as clearFuncspanOverride,
1130
- T as getCurrentFunctionSpanId,
1131
- ge as getDefaultConfig,
1132
- Ne as getEnvConfig,
1133
- Q as getFuncspanOverride,
1134
- Ye as getGlobalConfig,
1135
- vt as identify,
1136
- Xe as initializeConfigLoader,
1137
- st as initializeWorkerPoolPatching,
1138
- _t as isAlreadyInstrumented,
1139
- Ze as isConfigLoaderInitialized,
1140
- Ct as isProductionEnvironment,
1141
- Tt as isRuntimeModeEnabled,
1142
- It as isSetupInterceptorsInitialized,
1143
- ot as isWorkerPoolInitialized,
1144
- X as parseHeaderOverride,
1145
- Nt as runWithContext,
1146
- Pt as setFuncspanOverride,
1147
- Ot as setSkipTypeScriptPlugin,
1148
- St as setupInterceptors,
1149
- Ut as shouldEnableRuntimeHooks,
1150
- Lt as transformFunctionSpans,
1151
- qt as transformFunctionSpansSync
2212
+ x as ContextManager,
2213
+ Nn as _setAsyncQueueHopSpy,
2214
+ An as addOrUpdateMetadata,
2215
+ Bn as captureFunctionSpan,
2216
+ xn as clearFuncspanOverride,
2217
+ H as getCurrentFunctionSpanId,
2218
+ rt as getDefaultConfig,
2219
+ wt as getEnvConfig,
2220
+ Ie as getFuncspanOverride,
2221
+ Xt as getGlobalConfig,
2222
+ Tn as identify,
2223
+ Vt as initializeConfigLoader,
2224
+ on as initializeWorkerPoolPatching,
2225
+ Rn as isAlreadyInstrumented,
2226
+ Pn as isAsyncQueuePatchesInstalled,
2227
+ Yt as isConfigLoaderInitialized,
2228
+ Qn as isProductionEnvironment,
2229
+ Jn as isRuntimeModeEnabled,
2230
+ Cn as isSetupInterceptorsInitialized,
2231
+ sn as isWorkerPoolInitialized,
2232
+ ve as parseHeaderOverride,
2233
+ Mn as runWithContext,
2234
+ jn as setFuncspanOverride,
2235
+ zn as setSkipTypeScriptPlugin,
2236
+ qn as setupInterceptors,
2237
+ Wn as shouldEnableRuntimeHooks,
2238
+ Vn as transformFunctionSpans,
2239
+ Xn as transformFunctionSpansSync,
2240
+ Fn as uninstallAsyncQueuePatches
1152
2241
  };