@sailfish-ai/sf-veritas 0.3.2 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/dist/contextManager-B1hI1vbB.cjs +1 -0
  2. package/dist/{contextManager-CZy0w11U.js → contextManager-CE9FcHd2.js} +55 -47
  3. package/dist/plugins/funcspanEsbuildPlugin.cjs +1 -1
  4. package/dist/plugins/funcspanEsbuildPlugin.mjs +1 -1
  5. package/dist/plugins/funcspanRollupPlugin.cjs +1 -1
  6. package/dist/plugins/funcspanRollupPlugin.mjs +1 -1
  7. package/dist/plugins/funcspanTscPlugin.cjs +1 -1
  8. package/dist/plugins/funcspanTscPlugin.mjs +1 -1
  9. package/dist/plugins/funcspanVitePlugin.cjs +1 -1
  10. package/dist/plugins/funcspanVitePlugin.mjs +1 -1
  11. package/dist/plugins/funcspanWebpackPlugin.cjs +1 -1
  12. package/dist/plugins/funcspanWebpackPlugin.mjs +1 -1
  13. package/dist/{runtimeConfig-ButdW4zP.js → runtimeConfig-B6ERoLRD.js} +279 -277
  14. package/dist/{runtimeConfig-C4_zc4Zg.cjs → runtimeConfig-BgTE3gmS.cjs} +4 -4
  15. package/dist/sf-veritas.cjs +27 -19
  16. package/dist/sf-veritas.mjs +1657 -612
  17. package/dist/types/baseTransmitter.d.ts +1 -0
  18. package/dist/types/constants.d.ts +6 -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/setupConfig.d.ts +3 -0
  32. package/dist/worker-pool-capture.cjs +1 -1
  33. package/dist/worker-pool-capture.mjs +1 -1
  34. package/dist/{workerPoolSpanCapture-BomWTMM2.js → workerPoolSpanCapture-B5AjE5B9.js} +115 -115
  35. package/dist/workerPoolSpanCapture-CVp5eCI6.cjs +83 -0
  36. package/package.json +2 -1
  37. package/dist/contextManager-qXvO_a5y.cjs +0 -1
  38. package/dist/workerPoolSpanCapture-BUFN_RMW.cjs +0 -83
@@ -1,28 +1,28 @@
1
1
  var Q = Object.defineProperty;
2
2
  var X = (n, t, s) => t in n ? Q(n, t, { enumerable: !0, configurable: !0, writable: !0, value: s }) : n[t] = s;
3
- var y = (n, t, s) => X(n, typeof t != "symbol" ? t + "" : t, s);
3
+ var _ = (n, t, s) => X(n, typeof t != "symbol" ? t + "" : t, s);
4
4
  import { AsyncLocalStorage as Z, AsyncResource as Y } from "async_hooks";
5
5
  import { appendFileSync as ee } from "fs";
6
6
  import { Worker as te, threadId as O } from "worker_threads";
7
- import { g as S, C as L, v as j, a as M } from "./contextManager-CZy0w11U.js";
7
+ import { g as m, C as L, v as j, a as M } from "./contextManager-CE9FcHd2.js";
8
8
  import { dirname as ne, join as re } from "path";
9
9
  import { fileURLToPath as se } from "url";
10
- class oe {
10
+ class ae {
11
11
  constructor() {
12
- y(this, "apiKey");
13
- y(this, "endpoint");
14
- y(this, "queryType", "mutation");
15
- y(this, "operationName", "");
16
- y(this, "serviceUUID", S().serviceUUID);
17
- y(this, "contextManager");
18
- this.apiKey = S().apiKey, this.endpoint = S().apiGraphqlEndpoint, this.contextManager = L.getInstance();
12
+ _(this, "apiKey");
13
+ _(this, "endpoint");
14
+ _(this, "queryType", "mutation");
15
+ _(this, "operationName", "");
16
+ _(this, "serviceUUID", m().serviceUUID);
17
+ _(this, "contextManager");
18
+ this.apiKey = m().apiKey, this.endpoint = m().apiGraphqlEndpoint, this.contextManager = L.getInstance();
19
19
  }
20
20
  get queryName() {
21
21
  return this.operationName ? this.operationName.charAt(0).toLowerCase() + this.operationName.slice(1) : "";
22
22
  }
23
23
  getDefaultVariables() {
24
- const t = Date.now().toString(), s = this.contextManager.getOrSetSfTraceId(), a = this.contextManager.getCurrentFunctionSpanId();
25
- return { apiKey: this.apiKey, serviceUuid: this.serviceUUID, sessionId: s, timestampMs: t, parentSpanId: a };
24
+ const t = Date.now().toString(), s = this.contextManager.getOrSetSfTraceId(), o = this.contextManager.getCurrentFunctionSpanId();
25
+ return { apiKey: this.apiKey, serviceUuid: this.serviceUUID, sessionId: s, timestampMs: t, parentSpanId: o, dataSensitivityLevel: m().dataSensitivityLevel };
26
26
  }
27
27
  getVariables(t = {}) {
28
28
  return { ...this.getDefaultVariables(), ...t };
@@ -37,70 +37,70 @@ class oe {
37
37
  this.serviceUUID = t;
38
38
  }
39
39
  }
40
- const ae = typeof __dirname < "u" ? __dirname : ne(se(import.meta.url)), ie = fetch;
41
- let b = !1;
42
- function ye() {
43
- return b;
40
+ const oe = typeof __dirname < "u" ? __dirname : ne(se(import.meta.url)), ie = fetch;
41
+ let I = !1;
42
+ function _e() {
43
+ return I;
44
44
  }
45
45
  const ue = process.env.SF_NBPOST_DISABLE_BATCHING === "1", A = parseInt(process.env.SF_MAIN_BATCH_SIZE || "0", 10);
46
- let m = null, k = !1;
46
+ let g = null, k = !1;
47
47
  function B() {
48
48
  if (k) return null;
49
- if (m) return m;
49
+ if (g) return g;
50
50
  try {
51
- const n = re(ae, "telemetryWorker.cjs");
52
- return m = new te(n, { env: { ...process.env, SF_NBPOST_BATCH_MAX: process.env.SF_NBPOST_BATCH_MAX || "50", SF_FLUSH_TELEMETRY_IN_BATCH: process.env.SF_FLUSH_TELEMETRY_IN_BATCH || "0", SF_BATCH_FLUSH_INTERVAL_MS: process.env.SF_BATCH_FLUSH_INTERVAL_MS || "50", SF_WORKER_MAX_CONCURRENT: process.env.SF_WORKER_MAX_CONCURRENT || "10" } }), m.unref(), m.on("error", () => {
53
- k = !0, m = null;
54
- }), m.on("exit", () => {
55
- m = null;
56
- }), m;
51
+ const n = re(oe, "telemetryWorker.cjs");
52
+ return g = new te(n, { env: { ...process.env, SF_NBPOST_BATCH_MAX: process.env.SF_NBPOST_BATCH_MAX || "50", SF_FLUSH_TELEMETRY_IN_BATCH: process.env.SF_FLUSH_TELEMETRY_IN_BATCH || "0", SF_BATCH_FLUSH_INTERVAL_MS: process.env.SF_BATCH_FLUSH_INTERVAL_MS || "50", SF_WORKER_MAX_CONCURRENT: process.env.SF_WORKER_MAX_CONCURRENT || "10" } }), g.unref(), g.on("error", () => {
53
+ k = !0, g = null;
54
+ }), g.on("exit", () => {
55
+ g = null;
56
+ }), g;
57
57
  } catch {
58
58
  return k = !0, null;
59
59
  }
60
60
  }
61
- let g = [], v = !1;
61
+ let S = [], b = !1;
62
62
  function R() {
63
- if (g.length === 0) return;
63
+ if (S.length === 0) return;
64
64
  const n = B();
65
65
  if (!n) {
66
- for (const t of g) U(t.url, t.item.operationName, t.item.query, t.item.variables);
67
- return g = [], void (v = !1);
66
+ for (const t of S) U(t.url, t.item.operationName, t.item.query, t.item.variables);
67
+ return S = [], void (b = !1);
68
68
  }
69
- g.length === 1 ? n.postMessage(g[0]) : n.postMessage({ batch: g }), g = [], v = !1;
69
+ S.length === 1 ? n.postMessage(S[0]) : n.postMessage({ batch: S }), S = [], b = !1;
70
70
  }
71
- async function V(n, t, s, a) {
72
- if (ue) return U(n, t, s, a);
73
- const o = { url: n, item: { query: s, variables: a, operationName: t } };
71
+ async function V(n, t, s, o) {
72
+ if (ue) return U(n, t, s, o);
73
+ const a = { url: n, item: { query: s, variables: o, operationName: t } };
74
74
  if (A === 1) {
75
75
  const i = B();
76
- return i ? void i.postMessage(o) : U(n, t, s, a);
76
+ return i ? void i.postMessage(a) : U(n, t, s, o);
77
77
  }
78
- g.push(o), A > 1 && g.length >= A ? R() : v || (v = !0, queueMicrotask(R));
78
+ S.push(a), A > 1 && S.length >= A ? R() : b || (b = !0, queueMicrotask(R));
79
79
  }
80
- async function U(n, t, s, a) {
80
+ async function U(n, t, s, o) {
81
81
  try {
82
- const o = S();
82
+ const a = m();
83
83
  let i;
84
84
  try {
85
- i = JSON.stringify({ query: s, variables: a, operationName: t });
85
+ i = JSON.stringify({ query: s, variables: o, operationName: t });
86
86
  } catch {
87
87
  i = JSON.stringify({ query: s, operationName: t });
88
88
  }
89
- b = !0, ie(n, { method: "POST", headers: { "Content-Type": "application/json" }, body: i }).then(async (e) => {
90
- if (b = !1, !e.ok) return void (o.sfDebug && console.error(`GraphQL request failed with status ${e.status} for ${t}`));
89
+ I = !0, ie(n, { method: "POST", headers: { "Content-Type": "application/json" }, body: i }).then(async (e) => {
90
+ if (I = !1, !e.ok) return void (a.sfDebug && console.error(`GraphQL request failed with status ${e.status} for ${t}`));
91
91
  const r = await e.json();
92
92
  r.errors?.length ? (function(u, d, l) {
93
93
  const p = u && typeof u == "object" && !Array.isArray(u) ? Object.keys(u)[0] : void 0;
94
94
  console.error(p === "identifyServiceDetails" ? `IdentifyServiceDetails NOT sent successfully for service: UUID=${l.serviceUUID}` : `GraphQL request failed with errors: ${JSON.stringify(d)} for operation key ${p}`);
95
- })(r.data, r.errors, o) : o.sfDebug && (function(u, d, l) {
95
+ })(r.data, r.errors, a) : a.sfDebug && (function(u, d, l) {
96
96
  const p = u && typeof u == "object" && !Array.isArray(u) ? Object.keys(u)[0] : void 0, c = u[p] || !1;
97
- p === "identifyServiceDetails" && (l.setServiceIdentificationReceived(c), S().sfDebug && console.log(`IdentifyServiceDetails sent successfully for service: UUID=${l.serviceUUID}; serviceIdentificationReceived=${p === "identifyServiceDetails" ? c : "N/A"}`));
98
- })(r.data, 0, o);
97
+ p === "identifyServiceDetails" && (l.setServiceIdentificationReceived(c), m().sfDebug && console.log(`IdentifyServiceDetails sent successfully for service: UUID=${l.serviceUUID}; serviceIdentificationReceived=${p === "identifyServiceDetails" ? c : "N/A"}`));
98
+ })(r.data, 0, a);
99
99
  }).catch((e) => {
100
- b = !1, o.sfDebug && (console.error(`[RequestUtils] Fetch error for ${t} to ${n}:`, e), e.cause && console.error("[RequestUtils] Error cause:", e.cause));
100
+ I = !1, a.sfDebug && (console.error(`[RequestUtils] Fetch error for ${t} to ${n}:`, e), e.cause && console.error("[RequestUtils] Error cause:", e.cause));
101
101
  });
102
- } catch (o) {
103
- b = !1, S().sfDebug && console.error("Error sending data to GraphQL server:", o);
102
+ } catch (a) {
103
+ I = !1, m().sfDebug && console.error("Error sending data to GraphQL server:", a);
104
104
  }
105
105
  }
106
106
  let J = !1;
@@ -125,7 +125,7 @@ function he() {
125
125
  function $e() {
126
126
  return { capture_arguments: !1, capture_return_value: !1, arg_limit_mb: 1, return_limit_mb: 1, autocapture_all_child_functions: !1, sample_rate: 0, enable_sampling: !1, capture_sf_veritas: !1, parse_json_strings: !1 };
127
127
  }
128
- function Ie(n) {
128
+ function ve(n) {
129
129
  try {
130
130
  const t = n.split("-");
131
131
  return t.length !== 9 ? (console.error(`[FuncSpan] Invalid header format: expected 9 parts, got ${t.length}`), null) : { capture_arguments: t[0] === "1", capture_return_value: t[1] === "1", arg_limit_mb: parseInt(t[2], 10), return_limit_mb: parseInt(t[3], 10), autocapture_all_child_functions: t[4] === "1", sample_rate: parseFloat(t[5]), enable_sampling: t[6] === "1", capture_sf_veritas: t[7] === "1", parse_json_strings: t[8] === "1" };
@@ -141,17 +141,17 @@ function $(n, t) {
141
141
  const C = "__sf_funcspanOverrideStorage";
142
142
  globalThis[C] || (globalThis[C] = new Z());
143
143
  const z = globalThis[C];
144
- function be(n) {
144
+ function Ie(n) {
145
145
  z.enterWith(n);
146
146
  }
147
- function ve() {
147
+ function be() {
148
148
  return z.getStore();
149
149
  }
150
150
  function Te() {
151
151
  }
152
152
  function Fe(...n) {
153
153
  const t = {};
154
- for (const s of n) for (const a in s) s[a] !== void 0 && (t[a] = s[a]);
154
+ for (const s of n) for (const o in s) s[o] !== void 0 && (t[o] = s[o]);
155
155
  return t;
156
156
  }
157
157
  function q(n, t) {
@@ -169,8 +169,8 @@ function N(n, t) {
169
169
  function x(n, t) {
170
170
  const s = process.env[n];
171
171
  if (s === void 0) return t;
172
- const a = parseFloat(s);
173
- return isNaN(a) ? t : a;
172
+ const o = parseFloat(s);
173
+ return isNaN(o) ? t : o;
174
174
  }
175
175
  function D() {
176
176
  return { enabled: N("SF_WORKER_POOL_ENABLED", !0), trackFs: N("SF_WORKER_POOL_TRACK_FS", !1), trackDns: N("SF_WORKER_POOL_TRACK_DNS", !1), trackCrypto: N("SF_WORKER_POOL_TRACK_CRYPTO", !1), trackZlib: N("SF_WORKER_POOL_TRACK_ZLIB", !1), captureArguments: N("SF_WORKER_POOL_CAPTURE_ARGUMENTS", !0), captureReturnValue: N("SF_WORKER_POOL_CAPTURE_RETURN_VALUE", !0), argLimitMb: x("SF_WORKER_POOL_ARG_LIMIT_MB", 1), returnLimitMb: x("SF_WORKER_POOL_RETURN_LIMIT_MB", 1) };
@@ -191,12 +191,12 @@ function Ae(n) {
191
191
  return !1;
192
192
  }
193
193
  }
194
- function G(n, t, s, a) {
195
- let o;
194
+ function G(n, t, s, o) {
195
+ let a;
196
196
  try {
197
197
  switch (n) {
198
198
  case "fs":
199
- o = (function(i, e) {
199
+ a = (function(i, e) {
200
200
  const r = {};
201
201
  switch (i) {
202
202
  case "readFile":
@@ -235,7 +235,7 @@ function G(n, t, s, a) {
235
235
  })(t, s);
236
236
  break;
237
237
  case "dns":
238
- o = (function(i, e) {
238
+ a = (function(i, e) {
239
239
  const r = {};
240
240
  switch (i) {
241
241
  case "lookup":
@@ -260,7 +260,7 @@ function G(n, t, s, a) {
260
260
  })(t, s);
261
261
  break;
262
262
  case "crypto":
263
- o = (function(i, e) {
263
+ a = (function(i, e) {
264
264
  const r = {};
265
265
  switch (i) {
266
266
  case "pbkdf2":
@@ -282,7 +282,7 @@ function G(n, t, s, a) {
282
282
  })(t, s);
283
283
  break;
284
284
  case "zlib":
285
- o = (function(i, e) {
285
+ a = (function(i, e) {
286
286
  const r = {};
287
287
  return Buffer.isBuffer(e[0]) ? (r.inputType = "Buffer", r.inputSize = e[0].length) : typeof e[0] == "string" ? (r.inputType = "string", r.inputSize = e[0].length) : r.inputType = typeof e[0], e[1] && typeof e[1] == "object" && typeof e[1] != "function" && (r.options = { ...e[1] }), r;
288
288
  })(0, s);
@@ -290,17 +290,17 @@ function G(n, t, s, a) {
290
290
  default:
291
291
  return null;
292
292
  }
293
- return a > 0 ? q(o, a) : o;
293
+ return o > 0 ? q(a, o) : a;
294
294
  } catch {
295
295
  return { error: "Failed to capture arguments", argsCount: s.length - 1 };
296
296
  }
297
297
  }
298
- function H(n, t, s, a) {
299
- let o;
298
+ function H(n, t, s, o) {
299
+ let a;
300
300
  try {
301
301
  switch (n) {
302
302
  case "fs":
303
- o = (function(i, e) {
303
+ a = (function(i, e) {
304
304
  if (!e) return null;
305
305
  switch (i) {
306
306
  case "readFile":
@@ -323,7 +323,7 @@ function H(n, t, s, a) {
323
323
  })(t, s);
324
324
  break;
325
325
  case "dns":
326
- o = (function(i, e) {
326
+ a = (function(i, e) {
327
327
  if (!e) return null;
328
328
  switch (i) {
329
329
  case "lookup":
@@ -344,7 +344,7 @@ function H(n, t, s, a) {
344
344
  })(t, s);
345
345
  break;
346
346
  case "crypto":
347
- o = (function(i, e) {
347
+ a = (function(i, e) {
348
348
  if (!e) return null;
349
349
  switch (i) {
350
350
  case "pbkdf2":
@@ -359,14 +359,14 @@ function H(n, t, s, a) {
359
359
  })(t, s);
360
360
  break;
361
361
  case "zlib":
362
- o = (function(i, e) {
362
+ a = (function(i, e) {
363
363
  return e ? Buffer.isBuffer(e) ? { type: "Buffer", size: e.length } : typeof e == "string" ? { type: "string", size: e.length } : { type: typeof e } : null;
364
364
  })(0, s);
365
365
  break;
366
366
  default:
367
367
  return null;
368
368
  }
369
- return a > 0 ? q(o, a) : o;
369
+ return o > 0 ? q(a, o) : a;
370
370
  } catch {
371
371
  return { error: "Failed to capture result", type: typeof s };
372
372
  }
@@ -374,41 +374,41 @@ function H(n, t, s, a) {
374
374
  function le(n) {
375
375
  return n.operationType === "worker_pool";
376
376
  }
377
- class ce extends oe {
377
+ class ce extends ae {
378
378
  constructor() {
379
379
  super(), this.operationName = "CollectFunctionSpans";
380
380
  }
381
381
  send(t) {
382
- const s = S().sfDebug;
382
+ const s = m().sfDebug;
383
383
  s && console.log(`[FunctionSpanTransmitter] Preparing to send ${t.length} function span(s)`);
384
- for (const a of t) try {
385
- if (le(a)) {
386
- this.sendWorkerPoolSpan(a, s);
384
+ for (const o of t) try {
385
+ if (le(o)) {
386
+ this.sendWorkerPoolSpan(o, s);
387
387
  continue;
388
388
  }
389
- const o = a;
389
+ const a = o;
390
390
  let i;
391
- if (o.result !== void 0 && o.result !== null) {
392
- const r = typeof o.result;
393
- i = JSON.stringify({ type: r, has_value: !0, value: o.result });
394
- } else i = o.result === null ? JSON.stringify({ type: "null", has_value: !0, value: null }) : JSON.stringify({ type: "undefined", has_value: !1, value: null });
395
- const e = this.getVariables({ library: "JS/TS BACKEND", version: S().version, spanId: o.spanId, parentSpanId: o.parentSpanId, filePath: o.filePath, lineNumber: o.metadata.line, columnNumber: o.metadata.column, functionName: o.functionName, arguments: JSON.stringify(o.args || {}), returnValue: i, startTimeNs: (1e6 * Date.now() - 1e6 * o.duration).toString(), durationNs: (1e6 * o.duration).toString() });
396
- s && (console.log(`[FunctionSpanTransmitter] Sending GraphQL mutation to ${this.endpoint}`), console.log("[FunctionSpanTransmitter] Variables:", JSON.stringify(e, null, 2))), V(this.endpoint, this.operationName, this.getQuery(), e), s && console.log(`[FunctionSpanTransmitter] Queued function span for ${o.functionName}`);
397
- } catch (o) {
398
- console.error(`[FunctionSpanTransmitter] Error preparing function span for ${a.functionName}:`, o);
391
+ if (a.result !== void 0 && a.result !== null) {
392
+ const r = typeof a.result;
393
+ i = JSON.stringify({ type: r, has_value: !0, value: a.result });
394
+ } else i = a.result === null ? JSON.stringify({ type: "null", has_value: !0, value: null }) : JSON.stringify({ type: "undefined", has_value: !1, value: null });
395
+ const e = this.getVariables({ library: "JS/TS BACKEND", version: m().version, spanId: a.spanId, parentSpanId: a.parentSpanId, filePath: a.filePath, lineNumber: a.metadata.line, columnNumber: a.metadata.column, functionName: a.functionName, arguments: JSON.stringify(a.args || {}), returnValue: i, startTimeNs: (1e6 * Date.now() - 1e6 * a.duration).toString(), durationNs: (1e6 * a.duration).toString() });
396
+ s && (console.log(`[FunctionSpanTransmitter] Sending GraphQL mutation to ${this.endpoint}`), console.log("[FunctionSpanTransmitter] Variables:", JSON.stringify(e, null, 2))), V(this.endpoint, this.operationName, this.getQuery(), e), s && console.log(`[FunctionSpanTransmitter] Queued function span for ${a.functionName}`);
397
+ } catch (a) {
398
+ console.error(`[FunctionSpanTransmitter] Error preparing function span for ${o.functionName}:`, a);
399
399
  }
400
400
  }
401
401
  sendWorkerPoolSpan(t, s) {
402
402
  try {
403
- let a;
403
+ let o;
404
404
  if (t.result !== void 0 && t.result !== null) {
405
405
  const i = typeof t.result;
406
- a = JSON.stringify({ type: i, has_value: !0, value: t.result });
407
- } else a = t.result === null ? JSON.stringify({ type: "null", has_value: !0, value: null }) : JSON.stringify({ type: "undefined", has_value: !1, value: null });
408
- const o = this.getVariables({ library: "JS/TS BACKEND", version: S().version, spanId: t.spanId, operationName: t.operationName, moduleName: t.moduleName, methodName: t.methodName, startTimeNs: t.startTimeNs, durationNs: t.durationNs, arguments: JSON.stringify(t.args || {}), returnValue: a, error: t.error, pid: t.pid, threadId: t.threadId });
409
- s && (console.log(`[FunctionSpanTransmitter] Sending worker pool span: ${t.operationName}`), console.log("[FunctionSpanTransmitter] Variables:", JSON.stringify(o, null, 2))), V(this.endpoint, "CollectWorkerPoolSpans", this.getWorkerPoolQuery(), o), s && console.log(`[FunctionSpanTransmitter] Queued worker pool span for ${t.operationName}`);
410
- } catch (a) {
411
- console.error(`[FunctionSpanTransmitter] Error preparing worker pool span for ${t.operationName}:`, a);
406
+ o = JSON.stringify({ type: i, has_value: !0, value: t.result });
407
+ } else o = t.result === null ? JSON.stringify({ type: "null", has_value: !0, value: null }) : JSON.stringify({ type: "undefined", has_value: !1, value: null });
408
+ const a = this.getVariables({ library: "JS/TS BACKEND", version: m().version, spanId: t.spanId, operationName: t.operationName, moduleName: t.moduleName, methodName: t.methodName, startTimeNs: t.startTimeNs, durationNs: t.durationNs, arguments: JSON.stringify(t.args || {}), returnValue: o, error: t.error, pid: t.pid, threadId: t.threadId });
409
+ s && (console.log(`[FunctionSpanTransmitter] Sending worker pool span: ${t.operationName}`), console.log("[FunctionSpanTransmitter] Variables:", JSON.stringify(a, null, 2))), V(this.endpoint, "CollectWorkerPoolSpans", this.getWorkerPoolQuery(), a), s && console.log(`[FunctionSpanTransmitter] Queued worker pool span for ${t.operationName}`);
410
+ } catch (o) {
411
+ console.error(`[FunctionSpanTransmitter] Error preparing worker pool span for ${t.operationName}:`, o);
412
412
  }
413
413
  }
414
414
  getWorkerPoolQuery() {
@@ -499,63 +499,63 @@ class ce extends oe {
499
499
  }
500
500
  }
501
501
  let P = null;
502
- function ke(n, t, s, a, o) {
502
+ function ke(n, t, s, o, a) {
503
503
  const i = M(), e = i?.sfDebug || !1;
504
504
  e && console.log(`[WorkerPool] Capturing ${n}.${t}`);
505
505
  const r = D(), u = L.getInstance().getCurrentFunctionSpanId(), d = j();
506
506
  e && console.log(`[WorkerPool] Span ID: ${d}, Parent: ${u || "none"}`);
507
507
  const l = new Y("WorkerPoolOperation"), p = process.hrtime.bigint();
508
508
  let c = null;
509
- r.captureArguments && (c = G(n, t, a, r.argLimitMb));
510
- const f = a.findIndex((h) => typeof h == "function");
511
- if (f === -1) return e && console.log(`[WorkerPool] No callback found for ${n}.${t}`), s.apply(o, a);
512
- const _ = a[f], I = [...a];
513
- return I[f] = function(h, ...T) {
509
+ r.captureArguments && (c = G(n, t, o, r.argLimitMb));
510
+ const f = o.findIndex((h) => typeof h == "function");
511
+ if (f === -1) return e && console.log(`[WorkerPool] No callback found for ${n}.${t}`), s.apply(a, o);
512
+ const y = o[f], v = [...o];
513
+ return v[f] = function(h, ...T) {
514
514
  const F = process.hrtime.bigint() - p, w = Number(F) / 1e6;
515
- _(h, ...T), l.runInAsyncScope(() => {
515
+ y(h, ...T), l.runInAsyncScope(() => {
516
516
  e && console.log(`[WorkerPool] ${n}.${t} completed in ${w.toFixed(3)}ms (${F}ns)`);
517
517
  let W = null, K = null;
518
518
  h ? K = h?.message || String(h) : r.captureReturnValue && T.length > 0 && (W = H(n, t, T[0], r.returnLimitMb)), E({ operationType: "worker_pool", operationName: `${n}.${t}`, moduleName: n, methodName: t, duration: w, durationNs: F.toString(), startTimeNs: p.toString(), args: c, result: W, error: K, spanId: d, parentSpanId: u, pid: process.pid, threadId: O });
519
519
  }), l.emitDestroy();
520
- }, s.apply(o, I);
520
+ }, s.apply(a, v);
521
521
  }
522
- function Pe(n, t, s, a, o) {
522
+ function Pe(n, t, s, o, a) {
523
523
  const i = M(), e = i?.sfDebug || !1;
524
524
  e && console.log(`[WorkerPool] Capturing ${n}.${t} (Promise)`);
525
525
  const r = D(), u = L.getInstance().getCurrentFunctionSpanId(), d = j();
526
526
  e && console.log(`[WorkerPool] Span ID: ${d}, Parent: ${u || "none"}`);
527
527
  const l = process.hrtime.bigint();
528
528
  let p = null;
529
- return r.captureArguments && (p = G(n, t, a, r.argLimitMb)), s.apply(o, a).then((c) => {
530
- const f = process.hrtime.bigint() - l, _ = Number(f) / 1e6;
531
- e && console.log(`[WorkerPool] ${n}.${t} completed in ${_.toFixed(3)}ms (${f}ns)`);
532
- let I = null;
533
- return r.captureReturnValue && (I = H(n, t, c, r.returnLimitMb)), E({ operationType: "worker_pool", operationName: `${n}.${t}`, moduleName: n, methodName: t, duration: _, durationNs: f.toString(), startTimeNs: l.toString(), args: p, result: I, error: null, spanId: d, parentSpanId: u, pid: process.pid, threadId: O }), c;
529
+ return r.captureArguments && (p = G(n, t, o, r.argLimitMb)), s.apply(a, o).then((c) => {
530
+ const f = process.hrtime.bigint() - l, y = Number(f) / 1e6;
531
+ e && console.log(`[WorkerPool] ${n}.${t} completed in ${y.toFixed(3)}ms (${f}ns)`);
532
+ let v = null;
533
+ return r.captureReturnValue && (v = H(n, t, c, r.returnLimitMb)), E({ operationType: "worker_pool", operationName: `${n}.${t}`, moduleName: n, methodName: t, duration: y, durationNs: f.toString(), startTimeNs: l.toString(), args: p, result: v, error: null, spanId: d, parentSpanId: u, pid: process.pid, threadId: O }), c;
534
534
  }, (c) => {
535
- const f = process.hrtime.bigint() - l, _ = Number(f) / 1e6;
536
- throw e && console.log(`[WorkerPool] ${n}.${t} failed in ${_.toFixed(3)}ms: ${c?.message || c}`), E({ operationType: "worker_pool", operationName: `${n}.${t}`, moduleName: n, methodName: t, duration: _, durationNs: f.toString(), startTimeNs: l.toString(), args: p, result: null, error: c?.message || String(c), spanId: d, parentSpanId: u, pid: process.pid, threadId: O }), c;
535
+ const f = process.hrtime.bigint() - l, y = Number(f) / 1e6;
536
+ throw e && console.log(`[WorkerPool] ${n}.${t} failed in ${y.toFixed(3)}ms: ${c?.message || c}`), E({ operationType: "worker_pool", operationName: `${n}.${t}`, moduleName: n, methodName: t, duration: y, durationNs: f.toString(), startTimeNs: l.toString(), args: p, result: null, error: c?.message || String(c), spanId: d, parentSpanId: u, pid: process.pid, threadId: O }), c;
537
537
  });
538
538
  }
539
539
  function E(n) {
540
540
  const t = M(), s = t?.sfDebug || !1;
541
541
  s && console.log("[WorkerPool] Capturing span:", { operation: n.operationName, duration: `${n.duration}ms`, error: n.error, spanId: n.spanId, parentSpanId: n.parentSpanId }), process.env.SF_FUNCSPAN_CONSOLE_OUTPUT === "true" && console.log(`
542
542
  ⚙️ Worker Pool Operation:`, { operation: n.operationName, duration: `${n.duration.toFixed(2)}ms`, arguments: n.args, result: n.error ? `Error: ${n.error}` : n.result, spanId: n.spanId, parentSpanId: n.parentSpanId || "none" });
543
- const a = process.env.SF_FUNCSPAN_JSONL_FILE;
544
- if (a) try {
545
- const o = a === "true" || a === "1" ? "funcspans.jsonl" : a, i = Date.now(), e = process.hrtime.bigint(), r = BigInt(n.startTimeNs), u = Number(e - r) / 1e6, d = new Date(i - u).toISOString(), l = JSON.stringify({ timestamp: d, operationType: n.operationType, operationName: n.operationName, moduleName: n.moduleName, methodName: n.methodName, 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, pid: n.pid, threadId: n.threadId }) + `
543
+ const o = process.env.SF_FUNCSPAN_JSONL_FILE;
544
+ if (o) try {
545
+ const a = o === "true" || o === "1" ? "funcspans.jsonl" : o, i = Date.now(), e = process.hrtime.bigint(), r = BigInt(n.startTimeNs), u = Number(e - r) / 1e6, d = new Date(i - u).toISOString(), l = JSON.stringify({ timestamp: d, operationType: n.operationType, operationName: n.operationName, moduleName: n.moduleName, methodName: n.methodName, 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, pid: n.pid, threadId: n.threadId }) + `
546
546
  `;
547
- ee(o, l, "utf-8");
548
- } catch (o) {
549
- console.error("[WorkerPool] Error writing to JSONL file:", o);
547
+ ee(a, l, "utf-8");
548
+ } catch (a) {
549
+ console.error("[WorkerPool] Error writing to JSONL file:", a);
550
550
  }
551
551
  if (s && console.log("[WorkerPool] Sending span to transmitter"), process.env.SF_FUNCSPAN_SKIP_BACKEND !== "true") try {
552
552
  (P || (P = new ce()), P).send([n]), s && console.log("[WorkerPool] Span sent successfully");
553
- } catch (o) {
554
- s && console.error("[WorkerPool] Error sending span:", o);
553
+ } catch (a) {
554
+ s && console.error("[WorkerPool] Error sending span:", a);
555
555
  }
556
556
  }
557
557
  export {
558
- oe as B,
558
+ ae as B,
559
559
  ce as F,
560
560
  $e as a,
561
561
  he as b,
@@ -563,13 +563,13 @@ export {
563
563
  Pe as d,
564
564
  Ae as e,
565
565
  z as f,
566
- ve as g,
566
+ be as g,
567
567
  Te as h,
568
- ye as i,
568
+ _e as i,
569
569
  Fe as m,
570
570
  V as n,
571
- Ie as p,
571
+ ve as p,
572
572
  Ne as r,
573
- be as s,
573
+ Ie as s,
574
574
  q as t
575
575
  };
@@ -0,0 +1,83 @@
1
+ "use strict";const j=require("async_hooks"),Q=require("fs"),$=require("worker_threads"),l=require("./contextManager-B1hI1vbB.cjs"),z=require("path"),X=require("url");class G{apiKey;endpoint;queryType="mutation";operationName="";serviceUUID=l.getConfig().serviceUUID;contextManager;constructor(){this.apiKey=l.getConfig().apiKey,this.endpoint=l.getConfig().apiGraphqlEndpoint,this.contextManager=l.ContextManager.getInstance()}get queryName(){return this.operationName?this.operationName.charAt(0).toLowerCase()+this.operationName.slice(1):""}getDefaultVariables(){const t=Date.now().toString(),o=this.contextManager.getOrSetSfTraceId(),a=this.contextManager.getCurrentFunctionSpanId();return{apiKey:this.apiKey,serviceUuid:this.serviceUUID,sessionId:o,timestampMs:t,parentSpanId:a,dataSensitivityLevel:l.getConfig().dataSensitivityLevel}}getVariables(t={}){return{...this.getDefaultVariables(),...t}}setOperationName(t){this.operationName=t}setEndpoint(t){this.endpoint=t}setServiceUUID(t){this.serviceUUID=t}}const Z=typeof __dirname<"u"?__dirname:z.dirname(X.fileURLToPath(require("node:url").pathToFileURL(__filename).href)),Y=fetch;let I=!1;const ee=process.env.SF_NBPOST_DISABLE_BATCHING==="1",k=parseInt(process.env.SF_MAIN_BATCH_SIZE||"0",10);let m=null,C=!1;function B(){if(C)return null;if(m)return m;try{const n=z.join(Z,"telemetryWorker.cjs");return m=new $.Worker(n,{env:{...process.env,SF_NBPOST_BATCH_MAX:process.env.SF_NBPOST_BATCH_MAX||"50",SF_FLUSH_TELEMETRY_IN_BATCH:process.env.SF_FLUSH_TELEMETRY_IN_BATCH||"0",SF_BATCH_FLUSH_INTERVAL_MS:process.env.SF_BATCH_FLUSH_INTERVAL_MS||"50",SF_WORKER_MAX_CONCURRENT:process.env.SF_WORKER_MAX_CONCURRENT||"10"}}),m.unref(),m.on("error",()=>{C=!0,m=null}),m.on("exit",()=>{m=null}),m}catch{return C=!0,null}}let S=[],b=!1;function U(){if(S.length===0)return;const n=B();if(!n){for(const t of S)L(t.url,t.item.operationName,t.item.query,t.item.variables);return S=[],void(b=!1)}S.length===1?n.postMessage(S[0]):n.postMessage({batch:S}),S=[],b=!1}async function E(n,t,o,a){if(ee)return L(n,t,o,a);const s={url:n,item:{query:o,variables:a,operationName:t}};if(k===1){const i=B();return i?void i.postMessage(s):L(n,t,o,a)}S.push(s),k>1&&S.length>=k?U():b||(b=!0,queueMicrotask(U))}async function L(n,t,o,a){try{const s=l.getConfig();let i;try{i=JSON.stringify({query:o,variables:a,operationName:t})}catch{i=JSON.stringify({query:o,operationName:t})}I=!0,Y(n,{method:"POST",headers:{"Content-Type":"application/json"},body:i}).then(async e=>{if(I=!1,!e.ok)return void(s.sfDebug&&console.error(`GraphQL request failed with status ${e.status} for ${t}`));const r=await e.json();r.errors?.length?(function(u,g,c){const d=u&&typeof u=="object"&&!Array.isArray(u)?Object.keys(u)[0]:void 0;console.error(d==="identifyServiceDetails"?`IdentifyServiceDetails NOT sent successfully for service: UUID=${c.serviceUUID}`:`GraphQL request failed with errors: ${JSON.stringify(g)} for operation key ${d}`)})(r.data,r.errors,s):s.sfDebug&&(function(u,g,c){const d=u&&typeof u=="object"&&!Array.isArray(u)?Object.keys(u)[0]:void 0,p=u[d]||!1;d==="identifyServiceDetails"&&(c.setServiceIdentificationReceived(p),l.getConfig().sfDebug&&console.log(`IdentifyServiceDetails sent successfully for service: UUID=${c.serviceUUID}; serviceIdentificationReceived=${d==="identifyServiceDetails"?p:"N/A"}`))})(r.data,0,s)}).catch(e=>{I=!1,s.sfDebug&&(console.error(`[RequestUtils] Fetch error for ${t} to ${n}:`,e),e.cause&&console.error("[RequestUtils] Error cause:",e.cause))})}catch(s){I=!1,l.getConfig().sfDebug&&console.error("Error sending data to GraphQL server:",s)}}let V=!1;function h(n,t){if(!n)return t;const o=n.toLowerCase();return o==="true"||o==="1"||o==="yes"}const M="__sf_funcspanOverrideStorage";globalThis[M]||(globalThis[M]=new j.AsyncLocalStorage);const P=globalThis[M];function D(n,t){try{const o=JSON.stringify(n).length/1048576;return o<=t?n:{_truncated:!0,_originalSizeMB:o.toFixed(2),_limitMB:t,_preview:JSON.stringify(n).substring(0,500)+"..."}}catch{return{_error:"Failed to serialize data",_type:typeof n}}}function y(n,t){const o=process.env[n];return o===void 0?t:o==="true"||o==="1"}function q(n,t){const o=process.env[n];if(o===void 0)return t;const a=parseFloat(o);return isNaN(a)?t:a}function A(){return{enabled:y("SF_WORKER_POOL_ENABLED",!0),trackFs:y("SF_WORKER_POOL_TRACK_FS",!1),trackDns:y("SF_WORKER_POOL_TRACK_DNS",!1),trackCrypto:y("SF_WORKER_POOL_TRACK_CRYPTO",!1),trackZlib:y("SF_WORKER_POOL_TRACK_ZLIB",!1),captureArguments:y("SF_WORKER_POOL_CAPTURE_ARGUMENTS",!0),captureReturnValue:y("SF_WORKER_POOL_CAPTURE_RETURN_VALUE",!0),argLimitMb:q("SF_WORKER_POOL_ARG_LIMIT_MB",1),returnLimitMb:q("SF_WORKER_POOL_RETURN_LIMIT_MB",1)}}function x(n,t,o,a){let s;try{switch(n){case"fs":s=(function(i,e){const r={};switch(i){case"readFile":case"writeFile":case"appendFile":r.path=String(e[0]||""),e[1]&&typeof e[1]=="object"?(r.encoding=e[1].encoding||null,r.flag=e[1].flag||null):typeof e[1]=="string"&&(r.encoding=e[1]),i!=="writeFile"&&i!=="appendFile"||(Buffer.isBuffer(e[1])?(r.dataType="Buffer",r.dataSize=e[1].length):typeof e[1]=="string"&&(r.dataType="string",r.dataSize=e[1].length));break;case"readdir":case"stat":case"lstat":case"access":case"chmod":case"mkdir":case"rmdir":case"unlink":r.path=String(e[0]||""),e[1]&&typeof e[1]=="object"&&(r.options={...e[1]},delete r.options.callback);break;case"rename":r.oldPath=String(e[0]||""),r.newPath=String(e[1]||"");break;case"open":r.path=String(e[0]||""),r.flags=e[1],r.mode=e[2];break;case"close":case"fstat":r.fd=e[0];break;case"read":case"write":r.fd=e[0],Buffer.isBuffer(e[1])&&(r.bufferSize=e[1].length),r.offset=e[2],r.length=e[3],r.position=e[4];break;default:r.argsCount=e.length-1}return r})(t,o);break;case"dns":s=(function(i,e){const r={};switch(i){case"lookup":r.hostname=String(e[0]||""),typeof e[1]=="object"?(r.family=e[1].family,r.all=e[1].all):typeof e[1]=="number"&&(r.family=e[1]);break;case"resolve":case"resolve4":case"resolve6":case"resolveAny":case"resolveMx":case"resolveNs":case"resolveTxt":r.hostname=String(e[0]||"");break;case"reverse":r.ip=String(e[0]||"");break;default:r.argsCount=e.length-1}return r})(t,o);break;case"crypto":s=(function(i,e){const r={};switch(i){case"pbkdf2":r.passwordType=typeof e[0],r.saltType=typeof e[1],r.iterations=e[2],r.keylen=e[3],r.digest=e[4];break;case"scrypt":r.passwordType=typeof e[0],r.saltType=typeof e[1],r.keylen=e[2],typeof e[3]=="object"&&(r.N=e[3].N,r.r=e[3].r,r.p=e[3].p);break;case"randomBytes":r.size=e[0];break;case"generateKeyPair":r.type=e[0],typeof e[1]=="object"&&(r.modulusLength=e[1].modulusLength,r.namedCurve=e[1].namedCurve);break;default:r.argsCount=e.length-1}return r})(t,o);break;case"zlib":s=(function(i,e){const r={};return Buffer.isBuffer(e[0])?(r.inputType="Buffer",r.inputSize=e[0].length):typeof e[0]=="string"?(r.inputType="string",r.inputSize=e[0].length):r.inputType=typeof e[0],e[1]&&typeof e[1]=="object"&&typeof e[1]!="function"&&(r.options={...e[1]}),r})(0,o);break;default:return null}return a>0?D(s,a):s}catch{return{error:"Failed to capture arguments",argsCount:o.length-1}}}function J(n,t,o,a){let s;try{switch(n){case"fs":s=(function(i,e){if(!e)return null;switch(i){case"readFile":return Buffer.isBuffer(e)?{type:"Buffer",size:e.length}:typeof e=="string"?{type:"string",size:e.length}:{type:typeof e};case"readdir":return{count:Array.isArray(e)?e.length:0,items:e};case"stat":case"lstat":case"fstat":return{size:e.size,mode:e.mode,isFile:e.isFile(),isDirectory:e.isDirectory()};case"open":return{fd:e};case"read":return{bytesRead:e};case"write":return{bytesWritten:e};default:return e}})(t,o);break;case"dns":s=(function(i,e){if(!e)return null;switch(i){case"lookup":return Array.isArray(e)?{count:e.length,addresses:e}:e;case"resolve":case"resolve4":case"resolve6":case"resolveAny":case"resolveMx":case"resolveNs":case"resolveTxt":return{count:Array.isArray(e)?e.length:0,records:e};case"reverse":return{hostnames:e};default:return e}})(t,o);break;case"crypto":s=(function(i,e){if(!e)return null;switch(i){case"pbkdf2":case"scrypt":case"randomBytes":return Buffer.isBuffer(e)?{type:"Buffer",size:e.length}:{type:typeof e};case"generateKeyPair":return{hasPublicKey:!!e?.publicKey,hasPrivateKey:!!e?.privateKey};default:return e}})(t,o);break;case"zlib":s=(function(i,e){return e?Buffer.isBuffer(e)?{type:"Buffer",size:e.length}:typeof e=="string"?{type:"string",size:e.length}:{type:typeof e}:null})(0,o);break;default:return null}return a>0?D(s,a):s}catch{return{error:"Failed to capture result",type:typeof o}}}function te(n){return n.operationType==="worker_pool"}class H extends G{constructor(){super(),this.operationName="CollectFunctionSpans"}send(t){const o=l.getConfig().sfDebug;o&&console.log(`[FunctionSpanTransmitter] Preparing to send ${t.length} function span(s)`);for(const a of t)try{if(te(a)){this.sendWorkerPoolSpan(a,o);continue}const s=a;let i;if(s.result!==void 0&&s.result!==null){const r=typeof s.result;i=JSON.stringify({type:r,has_value:!0,value:s.result})}else i=s.result===null?JSON.stringify({type:"null",has_value:!0,value:null}):JSON.stringify({type:"undefined",has_value:!1,value:null});const e=this.getVariables({library:"JS/TS BACKEND",version:l.getConfig().version,spanId:s.spanId,parentSpanId:s.parentSpanId,filePath:s.filePath,lineNumber:s.metadata.line,columnNumber:s.metadata.column,functionName:s.functionName,arguments:JSON.stringify(s.args||{}),returnValue:i,startTimeNs:(1e6*Date.now()-1e6*s.duration).toString(),durationNs:(1e6*s.duration).toString()});o&&(console.log(`[FunctionSpanTransmitter] Sending GraphQL mutation to ${this.endpoint}`),console.log("[FunctionSpanTransmitter] Variables:",JSON.stringify(e,null,2))),E(this.endpoint,this.operationName,this.getQuery(),e),o&&console.log(`[FunctionSpanTransmitter] Queued function span for ${s.functionName}`)}catch(s){console.error(`[FunctionSpanTransmitter] Error preparing function span for ${a.functionName}:`,s)}}sendWorkerPoolSpan(t,o){try{let a;if(t.result!==void 0&&t.result!==null){const i=typeof t.result;a=JSON.stringify({type:i,has_value:!0,value:t.result})}else a=t.result===null?JSON.stringify({type:"null",has_value:!0,value:null}):JSON.stringify({type:"undefined",has_value:!1,value:null});const s=this.getVariables({library:"JS/TS BACKEND",version:l.getConfig().version,spanId:t.spanId,operationName:t.operationName,moduleName:t.moduleName,methodName:t.methodName,startTimeNs:t.startTimeNs,durationNs:t.durationNs,arguments:JSON.stringify(t.args||{}),returnValue:a,error:t.error,pid:t.pid,threadId:t.threadId});o&&(console.log(`[FunctionSpanTransmitter] Sending worker pool span: ${t.operationName}`),console.log("[FunctionSpanTransmitter] Variables:",JSON.stringify(s,null,2))),E(this.endpoint,"CollectWorkerPoolSpans",this.getWorkerPoolQuery(),s),o&&console.log(`[FunctionSpanTransmitter] Queued worker pool span for ${t.operationName}`)}catch(a){console.error(`[FunctionSpanTransmitter] Error preparing worker pool span for ${t.operationName}:`,a)}}getWorkerPoolQuery(){return`
2
+ mutation CollectWorkerPoolSpans(
3
+ $apiKey: String!,
4
+ $serviceUuid: String!,
5
+ $sessionId: String!,
6
+ $timestampMs: String!,
7
+ $library: String!,
8
+ $version: String!,
9
+ $spanId: String!,
10
+ $operationName: String!,
11
+ $moduleName: String!,
12
+ $methodName: String!,
13
+ $startTimeNs: String!,
14
+ $durationNs: String!,
15
+ $parentSpanId: String,
16
+ $arguments: String,
17
+ $returnValue: String,
18
+ $error: String,
19
+ $pid: Int,
20
+ $threadId: Int
21
+ ) {
22
+ collectWorkerPoolSpans(
23
+ apiKey: $apiKey,
24
+ serviceUuid: $serviceUuid,
25
+ sessionId: $sessionId,
26
+ timestampMs: $timestampMs,
27
+ library: $library,
28
+ version: $version,
29
+ spanId: $spanId,
30
+ operationName: $operationName,
31
+ moduleName: $moduleName,
32
+ methodName: $methodName,
33
+ startTimeNs: $startTimeNs,
34
+ durationNs: $durationNs,
35
+ parentSpanId: $parentSpanId,
36
+ arguments: $arguments,
37
+ returnValue: $returnValue,
38
+ error: $error,
39
+ pid: $pid,
40
+ threadId: $threadId
41
+ )
42
+ }
43
+ `}getQuery(){return`
44
+ ${this.queryType} ${this.operationName}(
45
+ $apiKey: String!,
46
+ $serviceUuid: String!,
47
+ $sessionId: String!,
48
+ $timestampMs: String!,
49
+ $parentSpanId: String,
50
+ $library: String!,
51
+ $version: String!,
52
+ $spanId: String!,
53
+ $filePath: String!,
54
+ $lineNumber: Int!,
55
+ $columnNumber: Int!,
56
+ $functionName: String!,
57
+ $arguments: String!,
58
+ $returnValue: String,
59
+ $startTimeNs: String!,
60
+ $durationNs: String!
61
+ ) {
62
+ ${this.queryName}(
63
+ apiKey: $apiKey,
64
+ serviceUuid: $serviceUuid,
65
+ sessionId: $sessionId,
66
+ timestampMs: $timestampMs,
67
+ parentSpanId: $parentSpanId,
68
+ library: $library,
69
+ version: $version,
70
+ spanId: $spanId,
71
+ filePath: $filePath,
72
+ lineNumber: $lineNumber,
73
+ columnNumber: $columnNumber,
74
+ functionName: $functionName,
75
+ arguments: $arguments,
76
+ returnValue: $returnValue,
77
+ startTimeNs: $startTimeNs,
78
+ durationNs: $durationNs
79
+ )
80
+ }
81
+ `}}let O=null;function R(n){const t=l.getGlobalConfigUnsafe(),o=t?.sfDebug||!1;o&&console.log("[WorkerPool] Capturing span:",{operation:n.operationName,duration:`${n.duration}ms`,error:n.error,spanId:n.spanId,parentSpanId:n.parentSpanId}),process.env.SF_FUNCSPAN_CONSOLE_OUTPUT==="true"&&console.log(`
82
+ ⚙️ Worker Pool Operation:`,{operation:n.operationName,duration:`${n.duration.toFixed(2)}ms`,arguments:n.args,result:n.error?`Error: ${n.error}`:n.result,spanId:n.spanId,parentSpanId:n.parentSpanId||"none"});const a=process.env.SF_FUNCSPAN_JSONL_FILE;if(a)try{const s=a==="true"||a==="1"?"funcspans.jsonl":a,i=Date.now(),e=process.hrtime.bigint(),r=BigInt(n.startTimeNs),u=Number(e-r)/1e6,g=new Date(i-u).toISOString(),c=JSON.stringify({timestamp:g,operationType:n.operationType,operationName:n.operationName,moduleName:n.moduleName,methodName:n.methodName,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,pid:n.pid,threadId:n.threadId})+`
83
+ `;Q.appendFileSync(s,c,"utf-8")}catch(s){console.error("[WorkerPool] Error writing to JSONL file:",s)}if(o&&console.log("[WorkerPool] Sending span to transmitter"),process.env.SF_FUNCSPAN_SKIP_BACKEND!=="true")try{(O||(O=new H),O).send([n]),o&&console.log("[WorkerPool] Span sent successfully")}catch(s){o&&console.error("[WorkerPool] Error sending span:",s)}}exports.BaseTransmitter=G,exports.FunctionSpanTransmitter=H,exports.captureWorkerPoolOperation=function(n,t,o,a,s){const i=l.getGlobalConfigUnsafe(),e=i?.sfDebug||!1;e&&console.log(`[WorkerPool] Capturing ${n}.${t}`);const r=A(),u=l.ContextManager.getInstance().getCurrentFunctionSpanId(),g=l.v4();e&&console.log(`[WorkerPool] Span ID: ${g}, Parent: ${u||"none"}`);const c=new j.AsyncResource("WorkerPoolOperation"),d=process.hrtime.bigint();let p=null;r.captureArguments&&(p=x(n,t,a,r.argLimitMb));const f=a.findIndex(N=>typeof N=="function");if(f===-1)return e&&console.log(`[WorkerPool] No callback found for ${n}.${t}`),o.apply(s,a);const _=a[f],v=[...a];return v[f]=function(N,...T){const F=process.hrtime.bigint()-d,w=Number(F)/1e6;_(N,...T),c.runInAsyncScope(()=>{e&&console.log(`[WorkerPool] ${n}.${t} completed in ${w.toFixed(3)}ms (${F}ns)`);let W=null,K=null;N?K=N?.message||String(N):r.captureReturnValue&&T.length>0&&(W=J(n,t,T[0],r.returnLimitMb)),R({operationType:"worker_pool",operationName:`${n}.${t}`,moduleName:n,methodName:t,duration:w,durationNs:F.toString(),startTimeNs:d.toString(),args:p,result:W,error:K,spanId:g,parentSpanId:u,pid:process.pid,threadId:$.threadId})}),c.emitDestroy()},o.apply(s,v)},exports.captureWorkerPoolPromiseOperation=function(n,t,o,a,s){const i=l.getGlobalConfigUnsafe(),e=i?.sfDebug||!1;e&&console.log(`[WorkerPool] Capturing ${n}.${t} (Promise)`);const r=A(),u=l.ContextManager.getInstance().getCurrentFunctionSpanId(),g=l.v4();e&&console.log(`[WorkerPool] Span ID: ${g}, Parent: ${u||"none"}`);const c=process.hrtime.bigint();let d=null;return r.captureArguments&&(d=x(n,t,a,r.argLimitMb)),o.apply(s,a).then(p=>{const f=process.hrtime.bigint()-c,_=Number(f)/1e6;e&&console.log(`[WorkerPool] ${n}.${t} completed in ${_.toFixed(3)}ms (${f}ns)`);let v=null;return r.captureReturnValue&&(v=J(n,t,p,r.returnLimitMb)),R({operationType:"worker_pool",operationName:`${n}.${t}`,moduleName:n,methodName:t,duration:_,durationNs:f.toString(),startTimeNs:c.toString(),args:d,result:v,error:null,spanId:g,parentSpanId:u,pid:process.pid,threadId:$.threadId}),p},p=>{const f=process.hrtime.bigint()-c,_=Number(f)/1e6;throw e&&console.log(`[WorkerPool] ${n}.${t} failed in ${_.toFixed(3)}ms: ${p?.message||p}`),R({operationType:"worker_pool",operationName:`${n}.${t}`,moduleName:n,methodName:t,duration:_,durationNs:f.toString(),startTimeNs:c.toString(),args:d,result:null,error:p?.message||String(p),spanId:g,parentSpanId:u,pid:process.pid,threadId:$.threadId}),p})},exports.clearFuncspanOverride=function(){},exports.funcspanOverrideStorage=P,exports.getDefaultConfig=function(){return{capture_arguments:!1,capture_return_value:!1,arg_limit_mb:1,return_limit_mb:1,autocapture_all_child_functions:!1,sample_rate:0,enable_sampling:!1,capture_sf_veritas:!1,parse_json_strings:!1}},exports.getEnvConfig=function(){return{capture_arguments:h(process.env.SF_FUNCSPAN_CAPTURE_ARGUMENTS,!0),capture_return_value:h(process.env.SF_FUNCSPAN_CAPTURE_RETURN_VALUE,!0),arg_limit_mb:parseInt(process.env.SF_FUNCSPAN_ARG_LIMIT_MB||"1",10),return_limit_mb:parseInt(process.env.SF_FUNCSPAN_RETURN_LIMIT_MB||"1",10),autocapture_all_child_functions:h(process.env.SF_FUNCSPAN_AUTOCAPTURE_ALL_CHILD_FUNCTIONS,!1),sample_rate:parseFloat(process.env.SF_FUNCSPAN_SAMPLE_RATE||"1.0"),enable_sampling:h(process.env.SF_FUNCSPAN_ENABLE_SAMPLING,!1),capture_sf_veritas:h(process.env.SF_FUNCSPAN_CAPTURE_SF_VERITAS,!1),parse_json_strings:h(process.env.SF_FUNCSPAN_PARSE_JSON_STRINGS,!1)}},exports.getFuncspanOverride=function(){return P.getStore()},exports.isModuleTrackingEnabled=function(n){const t=A();if(!t.enabled)return!1;switch(n){case"fs":return t.trackFs;case"dns":return t.trackDns;case"crypto":return t.trackCrypto;case"zlib":return t.trackZlib;default:return!1}},exports.isSendingInternalTelemetry=function(){return I},exports.mergeConfigs=function(...n){const t={};for(const o of n)for(const a in o)o[a]!==void 0&&(t[a]=o[a]);return t},exports.nonBlockingPost=E,exports.parseHeaderOverride=function(n){try{const t=n.split("-");return t.length!==9?(console.error(`[FuncSpan] Invalid header format: expected 9 parts, got ${t.length}`),null):{capture_arguments:t[0]==="1",capture_return_value:t[1]==="1",arg_limit_mb:parseInt(t[2],10),return_limit_mb:parseInt(t[3],10),autocapture_all_child_functions:t[4]==="1",sample_rate:parseFloat(t[5]),enable_sampling:t[6]==="1",capture_sf_veritas:t[7]==="1",parse_json_strings:t[8]==="1"}}catch(t){return console.error(`[FuncSpan] Failed to parse header override "${n}":`,t),null}},exports.registerShutdownHooks=function(){if(V)return;V=!0;const n=()=>{try{(function(){U();const t=B();t&&t.postMessage("flush")})()}catch{}};process.on("beforeExit",n),process.on("SIGTERM",n),process.on("SIGINT",n)},exports.setFuncspanOverride=function(n){P.enterWith(n)},exports.truncateToLimit=D;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sailfish-ai/sf-veritas",
3
- "version": "0.3.2",
3
+ "version": "0.4.1",
4
4
  "publishPublicly": true,
5
5
  "description": "A versatile Edge Runtime-compatible package for JavaScript and TypeScript backend systems and scripts.",
6
6
  "main": "./dist/sf-veritas.cjs",
@@ -65,6 +65,7 @@
65
65
  "dev": "vite",
66
66
  "lint": "eslint ./src --ext .ts",
67
67
  "test": "vitest",
68
+ "bench": "vitest bench --environment=node src/patches/asyncQueues",
68
69
  "test:fake-document": "node scripts/test-fake-document.js",
69
70
  "check:no-dom-in-cjs": "node -e \"const fs=require('fs'),g=require('glob');const files=g.sync('dist/**/*.cjs');let bad=false;for(const f of files){const s=fs.readFileSync(f,'utf8');if(/document\\.|currentScript|baseURI/.test(s)){console.error('DOM polyfill in:',f);bad=true;}}if(bad)process.exit(1);console.log('No DOM polyfills in CJS');\"",
70
71
  "prebuild": "node --import 'data:text/javascript,import { register } from \"node:module\"; import { pathToFileURL } from \"node:url\"; register(\"ts-node/esm\", pathToFileURL(\"./\"));' scripts/build-script.ts",
@@ -1 +0,0 @@
1
- "use strict";const L=require("async_hooks"),G=require("child_process"),O=require("fs"),H=require("fs/promises"),V=require("os");function P(s){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const t in s)if(t!=="default"){const r=Object.getOwnPropertyDescriptor(s,t);Object.defineProperty(e,t,r.get?r:{enumerable:!0,get:()=>s[t]})}}return e.default=s,Object.freeze(e)}const F=P(H),m=P(V),i=[];for(let s=0;s<256;++s)i.push((s+256).toString(16).slice(1));let R;const k=new Uint8Array(16),N={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function I(s,e,t){if(N.randomUUID&&!s)return N.randomUUID();const r=(s=s||{}).random??s.rng?.()??(function(){if(!R){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");R=crypto.getRandomValues.bind(crypto)}return R(k)})();if(r.length<16)throw new Error("Random bytes length must be >= 16");return r[6]=15&r[6]|64,r[8]=63&r[8]|128,(function(n,o=0){return(i[n[o+0]]+i[n[o+1]]+i[n[o+2]]+i[n[o+3]]+"-"+i[n[o+4]]+i[n[o+5]]+"-"+i[n[o+6]]+i[n[o+7]]+"-"+i[n[o+8]]+i[n[o+9]]+"-"+i[n[o+10]]+i[n[o+11]]+i[n[o+12]]+i[n[o+13]]+i[n[o+14]]+i[n[o+15]]).toLowerCase()})(r)}class w{apiKey;apiGraphqlEndpoint;sfDebug;serviceIdentifier;serviceVersion;serviceUUID;serviceAdditionalMetadata;profilingModeEnabled;profilingMaxDepth;profilingMaxVariableSizeKb;domainsToNotPropagateHeadersTo;domainsToPropagateHeadersTo;nodeModulesToCollectLocalVariablesOn;printConfigurationStatuses;logLevel;stackDepthLocals;stackDepthCodeTraceDepth;packageLibraryType;version;gitSha;gitOrg;gitRepo;gitProvider;serviceDisplayName;infrastructureType;infrastructureDetails;framework;additionalFrameworks;serviceRole;setupInterceptorsFile;setupInterceptorsLine;logIgnoreRegex;captureRequestHeaders;captureResponseHeaders;captureRequestBody;captureResponseBody;requestBodyLimitBytes;responseBodyLimitBytes;retryOnClientError;_serviceIdentificationReceived=!1;constructor(e){this.apiKey=e.apiKey,this.apiGraphqlEndpoint=e?.apiGraphqlEndpoint||process.env.SAILFISH_GRAPHQL_ENDPOINT||"https://api-service.sailfishqa.com/graphql/",this.sfDebug=e?.debug===!0||process.env.SF_DEBUG==="true",this.serviceIdentifier=e?.serviceIdentifier||process.env.SERVICE_IDENTIFIER,this.serviceUUID=I(),this.serviceVersion=e?.serviceVersion||process.env.SERVICE_VERSION,this.gitSha=e?.gitSha||process.env.GIT_SHA||process.env.GITHUB_SHA||process.env.CI_COMMIT_SHA||process.env.BITBUCKET_COMMIT||process.env.VERCEL_GIT_COMMIT_SHA||process.env.CIRCLE_SHA1||process.env.HEROKU_SLUG_COMMIT||process.env.RENDER_GIT_COMMIT||process.env.RAILWAY_GIT_COMMIT_SHA||process.env.CODEBUILD_RESOLVED_SOURCE_VERSION;const t=process.env.GITHUB_REPOSITORY?.split("/");this.gitOrg=e?.gitOrg||process.env.GIT_ORG||(t&&t.length>=2?t[0]:void 0)||process.env.CI_PROJECT_NAMESPACE||process.env.BITBUCKET_REPO_OWNER||process.env.VERCEL_GIT_REPO_OWNER||process.env.CIRCLE_PROJECT_USERNAME,this.gitRepo=e?.gitRepo||process.env.GIT_REPO||(t&&t.length>=2?t.slice(1).join("/"):void 0)||process.env.CI_PROJECT_NAME||process.env.BITBUCKET_REPO_SLUG||process.env.VERCEL_GIT_REPO_SLUG||process.env.CIRCLE_PROJECT_REPONAME,this.gitProvider=e?.gitProvider||process.env.GIT_PROVIDER||(process.env.GITHUB_ACTIONS?"github":void 0)||(process.env.GITLAB_CI?"gitlab":void 0)||(process.env.BITBUCKET_PIPELINE_UUID?"bitbucket":void 0)||(process.env.CIRCLECI?"circleci":void 0),this.serviceDisplayName=e?.serviceDisplayName||process.env.SERVICE_DISPLAY_NAME,this.serviceAdditionalMetadata=e?.serviceAdditionalMetadata||{},this.profilingModeEnabled=e?.profilingModeEnabled??!1,this.profilingMaxDepth=e?.profilingMaxDepth??5,this.profilingMaxVariableSizeKb=e?.profilingMaxVariableSizeKb??25,this.domainsToNotPropagateHeadersTo=e?.domainsToNotPropagateHeadersTo||[],this.domainsToPropagateHeadersTo=e?.domainsToPropagateHeadersTo!==void 0?e.domainsToPropagateHeadersTo:["*"],this.nodeModulesToCollectLocalVariablesOn=e?.nodeModulesToCollectLocalVariablesOn||["_all_"],this.printConfigurationStatuses=process.env.PRINT_CONFIGURATION_STATUSES||"true",this.logLevel=process.env.LOG_LEVEL||"INFO",this.stackDepthLocals=process.env.SAILFISH_EXCEPTION_STACK_DEPTH_LOCALS!==void 0?parseInt(process.env.SAILFISH_EXCEPTION_STACK_DEPTH_LOCALS,10):5,isNaN(this.stackDepthLocals)&&(this.stackDepthLocals=-1),this.stackDepthCodeTraceDepth=process.env.SAILFISH_EXCEPTION_STACK_DEPTH_CODE_TRACE_DEPTH!==void 0?parseInt(process.env.SAILFISH_EXCEPTION_STACK_DEPTH_CODE_TRACE_DEPTH,10):-1,isNaN(this.stackDepthCodeTraceDepth)&&(this.stackDepthCodeTraceDepth=-1),this.packageLibraryType="JS/TS BACKEND",this.version=this.getPackageVersion();const r=(function(){return process.env.KUBERNETES_SERVICE_HOST||O.existsSync("/var/run/secrets/kubernetes.io/serviceaccount/token")?{type:"Kubernetes",details:{namespace:process.env.POD_NAMESPACE||"",podName:process.env.HOSTNAME||"",nodeName:process.env.NODE_NAME||""}}:process.env.AWS_LAMBDA_FUNCTION_NAME?{type:"AWS Lambda",details:{functionName:process.env.AWS_LAMBDA_FUNCTION_NAME||"",region:process.env.AWS_REGION||"",runtime:process.env.AWS_EXECUTION_ENV||""}}:process.env.AWS_EXECUTION_ENV?{type:"AWS",details:{executionEnv:process.env.AWS_EXECUTION_ENV||"",region:process.env.AWS_REGION||""}}:process.env.GOOGLE_CLOUD_PROJECT?{type:"Google Cloud",details:{project:process.env.GOOGLE_CLOUD_PROJECT||""}}:process.env.AZURE_FUNCTIONS_ENVIRONMENT?{type:"Azure Functions",details:{environment:process.env.AZURE_FUNCTIONS_ENVIRONMENT||""}}:process.env.VERCEL?{type:"Vercel",details:{env:process.env.VERCEL_ENV||"",region:process.env.VERCEL_REGION||""}}:process.env.NETLIFY?{type:"Netlify",details:{}}:process.env.FLY_APP_NAME?{type:"Fly.io",details:{appName:process.env.FLY_APP_NAME||"",region:process.env.FLY_REGION||""}}:process.env.RENDER_SERVICE_ID?{type:"Render",details:{serviceId:process.env.RENDER_SERVICE_ID||""}}:process.env.RAILWAY_ENVIRONMENT?{type:"Railway",details:{environment:process.env.RAILWAY_ENVIRONMENT||""}}:O.existsSync("/.dockerenv")?{type:"Docker",details:{}}:{type:"Unknown",details:{os:m.platform(),arch:m.arch(),nodeVersion:process.version}}})();this.infrastructureType=r.type,this.infrastructureDetails=r.details;const n=(function(){const b=[{pkg:"@nestjs/core",name:"nestjs"},{pkg:"@apollo/server",name:"apollo-server"},{pkg:"apollo-server",name:"apollo-server"},{pkg:"mercurius",name:"mercurius"},{pkg:"next",name:"nextjs"},{pkg:"nuxt",name:"nuxtjs"},{pkg:"express",name:"express"},{pkg:"fastify",name:"fastify"},{pkg:"koa",name:"koa"},{pkg:"@hapi/hapi",name:"hapi"},{pkg:"hono",name:"hono"}],d=[],g=new Set;for(const{pkg:v,name:S}of b)if(!g.has(S))try{require.resolve(v),d.push(S),g.add(S)}catch{}if(typeof process<"u"){if(!g.has("nuxtjs")&&globalThis._importMeta_!==void 0){let v=!1;try{(globalThis._importMeta_?.url||"").includes(".output/server")&&(v=!0)}catch{}v&&(d.unshift("nuxtjs"),g.add("nuxtjs"))}!g.has("meteorjs")&&process.env.METEOR_SHELL_DIR&&(d.unshift("meteorjs"),g.add("meteorjs"))}return{framework:d.length>0?d[0]:null,additionalFrameworks:d.slice(1),serviceRole:d.includes("nextjs")||d.includes("nuxtjs")?"fullstack":"backend"}})();this.framework=n.framework??void 0,this.additionalFrameworks=n.additionalFrameworks,this.serviceRole=n.serviceRole;const o=process.env.SF_LOG_IGNORE_REGEX;if(o)try{this.logIgnoreRegex=new RegExp(o)}catch{}this.captureRequestHeaders=process.env.SF_NETWORKHOP_CAPTURE_REQUEST_HEADERS==="true",this.captureResponseHeaders=process.env.SF_NETWORKHOP_CAPTURE_RESPONSE_HEADERS==="true",this.captureRequestBody=process.env.SF_NETWORKHOP_CAPTURE_REQUEST_BODY==="true",this.captureResponseBody=process.env.SF_NETWORKHOP_CAPTURE_RESPONSE_BODY==="true";const a=parseInt(process.env.SF_NETWORKHOP_REQUEST_LIMIT_MB||"1",10);this.requestBodyLimitBytes=1024*(isNaN(a)?1:a)*1024;const c=parseInt(process.env.SF_NETWORKHOP_RESPONSE_LIMIT_MB||"1",10);this.responseBodyLimitBytes=1024*(isNaN(c)?1:c)*1024;const u=(process.env.SF_RETRY_ON_CLIENT_ERROR||"").toLowerCase(),x=u==="all"||u==="idempotent"||u==="none"?u:void 0;this.retryOnClientError=x??e.retryOnClientError??"all"}getPackageVersion(){return"0.2.14"}get serviceIdentificationReceived(){return this._serviceIdentificationReceived}setServiceIdentificationReceived(e){this._serviceIdentificationReceived=e}}const U=Symbol.for("sailfish.sf_config");function T(){return globalThis[U]}function C(){const s=T();if(!s)throw new Error("Configuration has not been initialized. Call getOrCreateConfig(options) first.");return s}const A=Symbol.for("sf.ctx.storeAls"),p=globalThis,f=p[A]??(p[A]=new L.AsyncLocalStorage),M=["identitytoolkit.googleapis.com","t.co","*.twitter.com","*.gravatar.com","*.googleapis.com","*.amazonaws.com","*.smooch.io","*.zendesk.com"],D=Symbol.for("sf.ctx.als"),_=p[D]??(p[D]=new L.AsyncLocalStorage),y=Symbol.for("sf.ctx.sessionRegistry"),E=p[y]??(p[y]=new Map),h={handledExceptions:new Set,reentrancyGuardLoggingActive:!1,reentrancyGuardLoggingPreActive:!1,reentrancyGuardPrintActive:!1,reentrancyGuardPrintPreActive:!1,reentrancyGuardExceptionActive:!1,reentrancyGuardExceptionPreActive:!1,excludedDomains:new Set(M),supportedDomains:new Set};class l{static GLOBAL_MANAGER_SYMBOL=Symbol.for("sf.ctx.manager");constructor(){}current(){return f.getStore()}ensureStore(){const e=this.current();if(e)return e;const t=new Map;return f.enterWith(t),t}runWith(e,t){const r=this.current()??new Map,n=new Map(r);for(const[o,a]of Object.entries(e))n.set(o,a);return f.run(n,t)}static getInstance(){return p[l.GLOBAL_MANAGER_SYMBOL]||(p[l.GLOBAL_MANAGER_SYMBOL]=new l),p[l.GLOBAL_MANAGER_SYMBOL]}getCurrentContext(){return _.getStore()||h}setCurrentContext(e){const t=_.getStore()||h;_.enterWith({...t,...e})}ensureSession(e){let t=E.get(e);return t||(t={...h},E.set(e,t)),t}getContextFor(e){return E.get(e)??h}updateContextFor(e,t){const r=this.ensureSession(e);E.set(e,{...r,...t})}runWithSession(e,t){const r={...this.ensureSession(e)};return _.run(r,t)}deleteSession(e){E.delete(e)}getTraceId(){return this.getCurrentContext().traceId}getPageVisitUUID(){return this.getCurrentContext().pageVisitUUID}setTraceId(e){this.setCurrentContext({traceId:e})}setPageVisitUUID(e){this.setCurrentContext({pageVisitUUID:e})}getCurrentFunctionSpanId(){return this.getCurrentContext().currentFunctionSpanId}setCurrentFunctionSpanId(e){this.setCurrentContext({currentFunctionSpanId:e})}clearCurrentFunctionSpanId(){this.setCurrentContext({currentFunctionSpanId:void 0})}getOrSetSfTraceId(e,t=!1){let r=this.getTraceId();return r||(r=e||(t?I():`nonsession-applogs-v3/${C().apiKey}/${I()}`),this.setTraceId(r),C().sfDebug&&console.log(" Created new trace ID:",r),r)}getOrSetPageVisitUUID(){let e=this.getPageVisitUUID();return e||(e=I(),this.setPageVisitUUID(e),C().sfDebug&&console.log(" Created new page visit UUID:",e),e)}getHandledExceptions(){return this.getCurrentContext().handledExceptions}markExceptionHandled(e){const t=this.getHandledExceptions();t.add(e),this.setCurrentContext({handledExceptions:t})}hasHandledException(e){return this.getHandledExceptions().has(e)}resetHandledExceptions(){this.setCurrentContext({handledExceptions:new Set})}getExcludedDomains(){return this.getCurrentContext().excludedDomains}getSupportedDomains(){return this.getCurrentContext().supportedDomains}addSupportedDomains(e){this.getCurrentContext().supportedDomains.add(e.toLowerCase().trim())}setTraceIdFor(e,t){this.updateContextFor(e,{traceId:t})}setPageVisitUUIDFor(e,t){this.updateContextFor(e,{pageVisitUUID:t})}}exports.ContextManager=l,exports.DEFAULT_DOMAINS_TO_EXCLUDE=M,exports.backfillGitInfoAsync=async function(s){if(!(s.gitOrg&&s.gitRepo&&s.gitProvider))try{const e=await(async function(){let t="";try{t=await new Promise((r,n)=>{G.execFile("git",["remote","get-url","origin"],{timeout:3e3},(o,a)=>{o?n(o):r((a||"").trim())})})}catch{try{const r=(await F.readFile(".git/config","utf-8")).match(/\[remote "origin"\][^[]*url\s*=\s*(.+)/m);r&&(t=r[1].trim())}catch{}}return t?(function(r){let n,o,a;if(r.includes("github.com")?n="github":r.includes("gitlab.com")?n="gitlab":r.includes("bitbucket.org")&&(n="bitbucket"),r.startsWith("https://")||r.startsWith("http://")){const c=r.split("/");c.length>=5&&(o=c[3],a=c[4].replace(/\.git$/,""))}else{const c=r.indexOf(":");if(c>0){const u=r.substring(c+1).replace(/\.git$/,"").split("/");u.length>=2&&(o=u[0],a=u[1])}}return{org:o,repo:a,provider:n}})(t):{}})();s.gitOrg||(s.gitOrg=e.org),s.gitRepo||(s.gitRepo=e.repo),s.gitProvider||(s.gitProvider=e.provider)}catch{}},exports.getConfig=C,exports.getCurrentFunctionSpanId=function(){return l.getInstance().getCurrentFunctionSpanId()},exports.getGlobalConfigUnsafe=T,exports.getOrCreateConfig=function(s){const e=T();if(e)return{config:e};const t=new w(s);return(function(r){globalThis[U]=r})(t),t.sfDebug&&console.log("[[getOrCreateConfig]] Created global config:",t),{config:t}},exports.runWithContext=function(s){const e={...l.getInstance().getCurrentContext()};_.run(e,()=>{s()})},exports.v4=I;