@safaricom-mxl/node-sdk 0.0.18 → 0.0.20

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 (144) hide show
  1. package/README.md +13 -0
  2. package/dist/bin/opentelemetry-instrument.cjs +6 -6
  3. package/dist/bin/opentelemetry-instrument.mjs +2 -3
  4. package/dist/{evlog-BII4D1ne.d.mts → evlog-BBvPZ6Un.d.cts} +3 -7
  5. package/dist/evlog-BBvPZ6Un.d.cts.map +1 -0
  6. package/dist/{evlog-DP7bcV7t.d.cts → evlog-DnsHTU1C.d.mts} +3 -7
  7. package/dist/evlog-DnsHTU1C.d.mts.map +1 -0
  8. package/dist/{express-Bhkoez1P.d.cts → express-DWWuahjk.d.mts} +1 -3
  9. package/dist/express-DWWuahjk.d.mts.map +1 -0
  10. package/dist/{fastify-OrlGsmbX.d.cts → fastify-DAufwt8Z.d.mts} +1 -3
  11. package/dist/fastify-DAufwt8Z.d.mts.map +1 -0
  12. package/dist/{gcp-CKISiuHV.d.mts → gcp-DTKJr0BW.d.mts} +2 -4
  13. package/dist/gcp-DTKJr0BW.d.mts.map +1 -0
  14. package/dist/gcp.cjs +8 -11
  15. package/dist/gcp.d.cts +6 -2
  16. package/dist/gcp.d.cts.map +1 -0
  17. package/dist/gcp.d.mts +1 -1
  18. package/dist/gcp.mjs +8 -11
  19. package/dist/gcp.mjs.map +1 -1
  20. package/dist/{index-Bz-SovV2.d.cts → index-B9yoUw0E.d.mts} +18 -26
  21. package/dist/index-B9yoUw0E.d.mts.map +1 -0
  22. package/dist/{index-DQ6mCen2.d.mts → index-DUzuYLlh.d.cts} +21 -27
  23. package/dist/index-DUzuYLlh.d.cts.map +1 -0
  24. package/dist/index.cjs +9 -11
  25. package/dist/index.d.cts +12 -12
  26. package/dist/index.d.mts +12 -12
  27. package/dist/index.mjs +9 -11
  28. package/dist/index.mjs.map +1 -1
  29. package/dist/{initSDK-CA5vGy0p.mjs → initSDK-BQAwICCw.mjs} +466 -119
  30. package/dist/initSDK-BQAwICCw.mjs.map +1 -0
  31. package/dist/{initSDK-BwgQ0ed7.cjs → initSDK-WUqhxMoV.cjs} +470 -123
  32. package/dist/integrations/express.cjs +2 -3
  33. package/dist/integrations/express.d.cts +18 -2
  34. package/dist/integrations/express.d.cts.map +1 -0
  35. package/dist/integrations/express.d.mts +1 -1
  36. package/dist/integrations/express.mjs +2 -3
  37. package/dist/integrations/express.mjs.map +1 -1
  38. package/dist/integrations/fastify.cjs +2 -3
  39. package/dist/integrations/fastify.d.cts +6 -2
  40. package/dist/integrations/fastify.d.cts.map +1 -0
  41. package/dist/integrations/fastify.d.mts +1 -1
  42. package/dist/integrations/fastify.mjs +2 -3
  43. package/dist/integrations/fastify.mjs.map +1 -1
  44. package/dist/integrations/koa.cjs +2 -3
  45. package/dist/integrations/koa.d.cts +4 -2
  46. package/dist/integrations/koa.d.cts.map +1 -0
  47. package/dist/integrations/koa.d.mts +1 -1
  48. package/dist/integrations/koa.mjs +2 -3
  49. package/dist/integrations/nest.cjs +1 -2
  50. package/dist/integrations/nest.d.cts +4 -2
  51. package/dist/integrations/nest.d.cts.map +1 -0
  52. package/dist/integrations/nest.d.mts +1 -1
  53. package/dist/integrations/nest.mjs +1 -2
  54. package/dist/{json-DSW-bpAR.cjs → json-CbEbCXvy.cjs} +2 -3
  55. package/dist/{json-DVwqENiw.mjs → json-D8GZ_Psl.mjs} +2 -3
  56. package/dist/{json-DVwqENiw.mjs.map → json-D8GZ_Psl.mjs.map} +1 -1
  57. package/dist/{koa-B1Ko1p06.d.cts → koa-D2Ce046w.d.mts} +1 -3
  58. package/dist/koa-D2Ce046w.d.mts.map +1 -0
  59. package/dist/logger/evlog.cjs +3 -4
  60. package/dist/logger/evlog.d.cts +1 -1
  61. package/dist/logger/evlog.d.mts +1 -1
  62. package/dist/logger/evlog.mjs +3 -4
  63. package/dist/logger/evlog.mjs.map +1 -1
  64. package/dist/logger/nest.cjs +2 -3
  65. package/dist/logger/nest.d.cts +12 -2
  66. package/dist/logger/nest.d.cts.map +1 -0
  67. package/dist/logger/nest.d.mts +1 -1
  68. package/dist/logger/nest.mjs +2 -3
  69. package/dist/logger/nest.mjs.map +1 -1
  70. package/dist/logger/pino.cjs +5 -6
  71. package/dist/logger/pino.d.cts +31 -2
  72. package/dist/logger/pino.d.cts.map +1 -0
  73. package/dist/logger/pino.d.mts +1 -1
  74. package/dist/logger/pino.mjs +3 -4
  75. package/dist/logger/winston.cjs +6 -7
  76. package/dist/logger/winston.d.cts +28 -2
  77. package/dist/logger/winston.d.cts.map +1 -0
  78. package/dist/logger/winston.d.mts +1 -1
  79. package/dist/logger/winston.mjs +3 -4
  80. package/dist/logger/winston.mjs.map +1 -1
  81. package/dist/nest-D23C_cT5.d.mts +5 -0
  82. package/dist/nest-D23C_cT5.d.mts.map +1 -0
  83. package/dist/{nest-B5ufrE__.d.mts → nest-VvyIAhum.d.mts} +2 -4
  84. package/dist/nest-VvyIAhum.d.mts.map +1 -0
  85. package/dist/{otelLogger-BCV0GOWq.cjs → otelLogger-CPrxphm8.cjs} +6 -10
  86. package/dist/{otelLogger-DcLZFC1y.mjs → otelLogger-z2g8OuAd.mjs} +7 -11
  87. package/dist/{otelLogger-DcLZFC1y.mjs.map → otelLogger-z2g8OuAd.mjs.map} +1 -1
  88. package/dist/{pino-B-lO5HxK.d.cts → pino-CRzjSHO1.d.mts} +2 -4
  89. package/dist/pino-CRzjSHO1.d.mts.map +1 -0
  90. package/dist/{recordException-DTepFVfN.mjs → recordException-D4LkyJPb.mjs} +2 -3
  91. package/dist/{recordException-DTepFVfN.mjs.map → recordException-D4LkyJPb.mjs.map} +1 -1
  92. package/dist/{recordException-mVorhCzj.cjs → recordException-zcmSkhl5.cjs} +1 -2
  93. package/dist/{rolldown-runtime-VH7oDXx4.cjs → rolldown-runtime-CmQyd0Gu.cjs} +1 -2
  94. package/dist/tracing.cjs +2 -3
  95. package/dist/tracing.d.cts +2 -4
  96. package/dist/tracing.d.cts.map +1 -1
  97. package/dist/tracing.d.mts +2 -4
  98. package/dist/tracing.d.mts.map +1 -1
  99. package/dist/tracing.mjs +2 -3
  100. package/dist/{types-Duv0_o_x.d.mts → types-Cfpz8pqb.d.cts} +10 -5
  101. package/dist/types-Cfpz8pqb.d.cts.map +1 -0
  102. package/dist/{types-DdKOwAmI.d.cts → types-Dpuoi1cv.d.mts} +9 -4
  103. package/dist/types-Dpuoi1cv.d.mts.map +1 -0
  104. package/dist/{types-BsieoQtI.d.cts → types-TwVQ-GEN.d.cts} +2 -4
  105. package/dist/types-TwVQ-GEN.d.cts.map +1 -0
  106. package/dist/{types-Dtp1_OwC.d.mts → types-hBHUXkBe.d.mts} +2 -4
  107. package/dist/types-hBHUXkBe.d.mts.map +1 -0
  108. package/dist/{winston-BmRwq75d.d.mts → winston-Bi-Tdd0D.d.mts} +2 -4
  109. package/dist/winston-Bi-Tdd0D.d.mts.map +1 -0
  110. package/package.json +23 -22
  111. package/dist/evlog-BII4D1ne.d.mts.map +0 -1
  112. package/dist/evlog-DP7bcV7t.d.cts.map +0 -1
  113. package/dist/express-Bhkoez1P.d.cts.map +0 -1
  114. package/dist/express-Bhkoez1P.d.mts +0 -20
  115. package/dist/express-Bhkoez1P.d.mts.map +0 -1
  116. package/dist/fastify-OrlGsmbX.d.cts.map +0 -1
  117. package/dist/fastify-OrlGsmbX.d.mts +0 -8
  118. package/dist/fastify-OrlGsmbX.d.mts.map +0 -1
  119. package/dist/gcp-CKISiuHV.d.mts.map +0 -1
  120. package/dist/gcp-DWryQGf5.d.cts +0 -9
  121. package/dist/gcp-DWryQGf5.d.cts.map +0 -1
  122. package/dist/index-Bz-SovV2.d.cts.map +0 -1
  123. package/dist/index-DQ6mCen2.d.mts.map +0 -1
  124. package/dist/initSDK-CA5vGy0p.mjs.map +0 -1
  125. package/dist/koa-B1Ko1p06.d.cts.map +0 -1
  126. package/dist/koa-B1Ko1p06.d.mts +0 -7
  127. package/dist/koa-B1Ko1p06.d.mts.map +0 -1
  128. package/dist/nest-8gUTpgCB.d.cts +0 -7
  129. package/dist/nest-8gUTpgCB.d.cts.map +0 -1
  130. package/dist/nest-B5ufrE__.d.mts.map +0 -1
  131. package/dist/nest-C6fqfCBa.d.cts +0 -15
  132. package/dist/nest-C6fqfCBa.d.cts.map +0 -1
  133. package/dist/nest-Df9hU7gJ.d.mts +0 -7
  134. package/dist/nest-Df9hU7gJ.d.mts.map +0 -1
  135. package/dist/pino-B-lO5HxK.d.cts.map +0 -1
  136. package/dist/pino-D6VfyKmW.d.mts +0 -33
  137. package/dist/pino-D6VfyKmW.d.mts.map +0 -1
  138. package/dist/types-BsieoQtI.d.cts.map +0 -1
  139. package/dist/types-DdKOwAmI.d.cts.map +0 -1
  140. package/dist/types-Dtp1_OwC.d.mts.map +0 -1
  141. package/dist/types-Duv0_o_x.d.mts.map +0 -1
  142. package/dist/winston-BmRwq75d.d.mts.map +0 -1
  143. package/dist/winston-DvH6EQ93.d.cts +0 -31
  144. package/dist/winston-DvH6EQ93.d.cts.map +0 -1
@@ -1,28 +1,29 @@
1
- import { a as parseHeaderAttributeMap, c as DEFAULT_METRIC_EXPORT_TIMEOUT_MS, d as DEFAULT_TRACE_TIMEOUT_MS, f as NODE_SDK_NAME, i as getStringFromEnv, n as resolveOtlpExporterUrl, o as parseOtlpHeaders, p as NODE_SDK_VERSION, r as getBooleanFromEnv, s as DEFAULT_METRIC_EXPORT_INTERVAL_MS, t as OTelLogger } from "./otelLogger-DcLZFC1y.mjs";
2
- import { parseWinstonLog } from "./logger/winston.mjs";
3
- import { t as recordException } from "./recordException-DTepFVfN.mjs";
4
- import { createRequire } from "node:module";
5
- import opentelemetry, { ROOT_CONTEXT, diag } from "@opentelemetry/api";
6
- import { ATTR_SERVICE_NAME, ATTR_SERVICE_VERSION, ATTR_TELEMETRY_SDK_NAME, ATTR_TELEMETRY_SDK_VERSION } from "@opentelemetry/semantic-conventions";
1
+ import opentelemetry, { ROOT_CONTEXT, TraceFlags, diag } from "@opentelemetry/api";
7
2
  import { getNodeAutoInstrumentations } from "@opentelemetry/auto-instrumentations-node";
8
3
  import { RuntimeNodeInstrumentation } from "@opentelemetry/instrumentation-runtime-node";
9
4
  import { NodeSDK } from "@opentelemetry/sdk-node";
10
- import { InstrumentationBase, InstrumentationNodeModuleDefinition } from "@opentelemetry/instrumentation";
11
- import isObject from "lodash.isobject";
12
- import isPlainObject from "lodash.isplainobject";
13
5
  import { AsyncLocalStorage } from "node:async_hooks";
14
6
  import { EventEmitter } from "node:events";
15
- import { defaultServiceName, resourceFromAttributes } from "@opentelemetry/resources";
16
- import * as http from "node:http";
17
- import { PassThrough } from "node:stream";
18
- import zlib from "node:zlib";
19
- import { AlwaysOffSampler, AlwaysOnSampler, BatchSpanProcessor, ParentBasedSampler, TraceIdRatioBasedSampler } from "@opentelemetry/sdk-trace-base";
20
7
  import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-grpc";
21
8
  import { OTLPMetricExporter as OTLPMetricExporter$1 } from "@opentelemetry/exporter-metrics-otlp-proto";
22
9
  import { PeriodicExportingMetricReader } from "@opentelemetry/sdk-metrics";
10
+ import { a as parseHeaderAttributeMap, c as DEFAULT_METRIC_EXPORT_TIMEOUT_MS, d as DEFAULT_TRACE_TIMEOUT_MS, f as NODE_SDK_NAME, i as getStringFromEnv, n as resolveOtlpExporterUrl, o as parseOtlpHeaders, p as NODE_SDK_VERSION, r as getBooleanFromEnv, s as DEFAULT_METRIC_EXPORT_INTERVAL_MS, t as OTelLogger } from "./otelLogger-z2g8OuAd.mjs";
23
11
  import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-grpc";
24
12
  import { OTLPTraceExporter as OTLPTraceExporter$1 } from "@opentelemetry/exporter-trace-otlp-proto";
25
- //#region src/context/AbstractAsyncHooksContextManager.ts
13
+ import { createRequire } from "node:module";
14
+ import { InstrumentationBase, InstrumentationNodeModuleDefinition } from "@opentelemetry/instrumentation";
15
+ import isObject from "lodash.isobject";
16
+ import isPlainObject from "lodash.isplainobject";
17
+ import { parseWinstonLog } from "./logger/winston.mjs";
18
+ import { t as recordException } from "./recordException-D4LkyJPb.mjs";
19
+ import { PassThrough } from "node:stream";
20
+ import zlib from "node:zlib";
21
+ import * as http from "node:http";
22
+ import { AlwaysOffSampler, AlwaysOnSampler, BatchSpanProcessor, ParentBasedSampler, TraceIdRatioBasedSampler } from "@opentelemetry/sdk-trace-base";
23
+ import { Session } from "node:inspector";
24
+ import { defaultServiceName, resourceFromAttributes } from "@opentelemetry/resources";
25
+ import { ATTR_SERVICE_NAME, ATTR_SERVICE_VERSION, ATTR_TELEMETRY_SDK_NAME, ATTR_TELEMETRY_SDK_VERSION } from "@opentelemetry/semantic-conventions";
26
+ // src/context/AbstractAsyncHooksContextManager.ts
26
27
  const ADD_LISTENER_METHODS = [
27
28
  "addListener",
28
29
  "on",
@@ -113,8 +114,7 @@ var AbstractAsyncHooksContextManager = class {
113
114
  _kOtListeners = Symbol("OtListeners");
114
115
  _wrapped = false;
115
116
  };
116
- //#endregion
117
- //#region src/context/MutableAsyncLocalStorageContextManager.ts
117
+ // src/context/MutableAsyncLocalStorageContextManager.ts
118
118
  var MutableAsyncLocalStorageContextManager = class extends AbstractAsyncHooksContextManager {
119
119
  asyncLocalStorage;
120
120
  constructor() {
@@ -143,8 +143,7 @@ var MutableAsyncLocalStorageContextManager = class extends AbstractAsyncHooksCon
143
143
  return this;
144
144
  }
145
145
  };
146
- //#endregion
147
- //#region src/context/contextManager.ts
146
+ // src/context/contextManager.ts
148
147
  let mutableContextManager;
149
148
  function setMutableContextManager(manager) {
150
149
  mutableContextManager = manager;
@@ -159,8 +158,59 @@ function getTraceAttributes() {
159
158
  if (!mutableContext) return {};
160
159
  return Object.fromEntries(mutableContext.traceAttributes);
161
160
  }
162
- //#endregion
163
- //#region src/instrumentations/console.ts
161
+ // src/exporters/metricReader.ts
162
+ function createMetricReader(config) {
163
+ const url = resolveOtlpExporterUrl({
164
+ kind: "metric",
165
+ endpoint: config.otlpEndpoint
166
+ });
167
+ const headers = parseOtlpHeaders(config.otlpHeaders);
168
+ const exporter = config.otlpProtocol === "grpc" ? new OTLPMetricExporter({
169
+ url,
170
+ headers
171
+ }) : new OTLPMetricExporter$1({
172
+ url,
173
+ headers
174
+ });
175
+ return new PeriodicExportingMetricReader({
176
+ exporter,
177
+ exportIntervalMillis: DEFAULT_METRIC_EXPORT_INTERVAL_MS,
178
+ exportTimeoutMillis: DEFAULT_METRIC_EXPORT_TIMEOUT_MS
179
+ });
180
+ }
181
+ // src/exporters/traceExporter.ts
182
+ function createTraceExporter(config) {
183
+ const url = resolveOtlpExporterUrl({
184
+ kind: "trace",
185
+ endpoint: config.otlpEndpoint,
186
+ explicitUrl: config.traceExporterUrl
187
+ });
188
+ const headers = parseOtlpHeaders(config.otlpHeaders);
189
+ if (config.otlpProtocol === "grpc") return new OTLPTraceExporter({
190
+ url,
191
+ timeoutMillis: DEFAULT_TRACE_TIMEOUT_MS,
192
+ headers
193
+ });
194
+ return new OTLPTraceExporter$1({
195
+ url,
196
+ timeoutMillis: DEFAULT_TRACE_TIMEOUT_MS,
197
+ headers
198
+ });
199
+ }
200
+ // src/instrumentations/exceptions/sentry.ts
201
+ const require = createRequire(import.meta.url);
202
+ function createSentryBridge(enabled) {
203
+ if (!enabled) return;
204
+ try {
205
+ const sentry = require("@sentry/node");
206
+ return { captureException(error) {
207
+ sentry.captureException(error);
208
+ } };
209
+ } catch {
210
+ return;
211
+ }
212
+ }
213
+ // src/instrumentations/console.ts
164
214
  const PACKAGE_NAME = "@safaricom-mxl/instrumentation-console";
165
215
  const PACKAGE_VERSION = "0.0.4";
166
216
  function parseConsoleArgs(args) {
@@ -236,8 +286,7 @@ var ConsoleInstrumentation = class extends InstrumentationBase {
236
286
  })];
237
287
  }
238
288
  };
239
- //#endregion
240
- //#region src/instrumentations/exceptions/ExceptionInstrumentation.ts
289
+ // src/instrumentations/exceptions/ExceptionInstrumentation.ts
241
290
  var ExceptionInstrumentation = class extends InstrumentationBase {
242
291
  forceFlush;
243
292
  uncaughtExceptionListener;
@@ -276,22 +325,7 @@ var ExceptionInstrumentation = class extends InstrumentationBase {
276
325
  this.unhandledRejectionListener = void 0;
277
326
  }
278
327
  };
279
- //#endregion
280
- //#region src/instrumentations/exceptions/sentry.ts
281
- const require = createRequire(import.meta.url);
282
- function createSentryBridge(enabled) {
283
- if (!enabled) return;
284
- try {
285
- const sentry = require("@sentry/node");
286
- return { captureException(error) {
287
- sentry.captureException(error);
288
- } };
289
- } catch {
290
- return;
291
- }
292
- }
293
- //#endregion
294
- //#region src/instrumentations/http.ts
328
+ // src/instrumentations/http.ts
295
329
  const SENSITIVE_DATA_SUBSTITUTE = "[Filtered]";
296
330
  const DEFAULT_DENYLIST = [
297
331
  "password",
@@ -475,8 +509,7 @@ function getAdvancedHttpInstrumentationConfig({ captureBodyKeywordsFilter, captu
475
509
  }
476
510
  };
477
511
  }
478
- //#endregion
479
- //#region src/processors/CompositeSpanProcessor.ts
512
+ // src/processors/CompositeSpanProcessor.ts
480
513
  var CompositeSpanProcessor = class {
481
514
  processors;
482
515
  constructor(processors) {
@@ -499,8 +532,7 @@ var CompositeSpanProcessor = class {
499
532
  for (const processor of this.processors) processor.onEnd(span);
500
533
  }
501
534
  };
502
- //#endregion
503
- //#region src/processors/FilterWhenDrainedSpanProcessor.ts
535
+ // src/processors/FilterWhenDrainedSpanProcessor.ts
504
536
  var FilterWhenDrainedSpanProcessor = class {
505
537
  delegate;
506
538
  drained = false;
@@ -526,8 +558,7 @@ var FilterWhenDrainedSpanProcessor = class {
526
558
  return this.delegate.shutdown();
527
559
  }
528
560
  };
529
- //#endregion
530
- //#region src/processors/NodeSpanProcessor.ts
561
+ // src/processors/NodeSpanProcessor.ts
531
562
  var NodeSpanProcessor = class extends BatchSpanProcessor {
532
563
  constructor(exporter) {
533
564
  super(exporter);
@@ -547,8 +578,343 @@ var NodeSpanProcessor = class extends BatchSpanProcessor {
547
578
  super.onEnd(span);
548
579
  }
549
580
  };
550
- //#endregion
551
- //#region src/resources/nodeSdkResource.ts
581
+ // src/profiling/ProfilingSpanProcessor.ts
582
+ var ProfilingSpanProcessor = class {
583
+ #timeline;
584
+ #stack = [];
585
+ constructor(timeline) {
586
+ this.#timeline = timeline;
587
+ }
588
+ onStart(span, _parentContext) {
589
+ const context = span.spanContext();
590
+ const current = (context.traceFlags & TraceFlags.SAMPLED) === TraceFlags.SAMPLED ? {
591
+ traceId: context.traceId,
592
+ spanId: context.spanId
593
+ } : void 0;
594
+ this.#stack.push(current);
595
+ this.#timeline.note(current);
596
+ }
597
+ onEnd(_span) {
598
+ this.#stack.pop();
599
+ this.#timeline.note(this.#stack.at(-1));
600
+ }
601
+ forceFlush() {
602
+ return Promise.resolve();
603
+ }
604
+ shutdown() {
605
+ return Promise.resolve();
606
+ }
607
+ };
608
+ // src/profiling/span-timeline.ts
609
+ const SPAN_EVENT_CAPACITY = 1 << 17;
610
+ const makeSpanTimeline = (options = {}) => {
611
+ const capacity = options.capacity ?? 131072;
612
+ const now = options.now ?? (() => performance.now());
613
+ let times = new Float64Array(capacity);
614
+ let spans = [];
615
+ let length = 0;
616
+ let overflowed = false;
617
+ let recording = false;
618
+ let current;
619
+ const push = (span) => {
620
+ if (length >= capacity) {
621
+ overflowed = true;
622
+ return;
623
+ }
624
+ times[length] = now();
625
+ spans[length] = span;
626
+ length += 1;
627
+ };
628
+ return {
629
+ note: (span) => {
630
+ current = span;
631
+ if (recording) push(span);
632
+ },
633
+ setRecording: (next) => {
634
+ if (next && !recording && current !== void 0) push(current);
635
+ recording = next;
636
+ },
637
+ drain: () => {
638
+ const drained = {
639
+ times,
640
+ spans,
641
+ length,
642
+ overflowed
643
+ };
644
+ times = new Float64Array(capacity);
645
+ spans = [];
646
+ length = 0;
647
+ overflowed = false;
648
+ if (recording && current !== void 0) push(current);
649
+ return drained;
650
+ }
651
+ };
652
+ };
653
+ const spanAt = (events, timeMs) => {
654
+ if (events.length === 0 || timeMs < (events.times[0] ?? Number.POSITIVE_INFINITY)) return;
655
+ const last = events.length - 1;
656
+ if (events.overflowed && timeMs > (events.times[last] ?? 0)) return;
657
+ let low = 0;
658
+ let high = last;
659
+ while (low < high) {
660
+ const middle = low + high + 1 >>> 1;
661
+ if ((events.times[middle] ?? Number.POSITIVE_INFINITY) <= timeMs) low = middle;
662
+ else high = middle - 1;
663
+ }
664
+ return events.spans[low];
665
+ };
666
+ // src/profiling/cpu-profile.ts
667
+ const IDLE = "(idle)";
668
+ const ROOT = "(root)";
669
+ const FILE_SCHEME = "file://";
670
+ const nanos = (epochMs) => (BigInt(Math.round(epochMs * 1e3)) * 1000n).toString();
671
+ var Interner = class {
672
+ table;
673
+ #index = /* @__PURE__ */ new Map();
674
+ constructor(zero) {
675
+ this.table = [zero];
676
+ }
677
+ intern(key, make) {
678
+ const existing = this.#index.get(key);
679
+ if (existing !== void 0) return existing;
680
+ const index = this.table.length;
681
+ this.table.push(make());
682
+ this.#index.set(key, index);
683
+ return index;
684
+ }
685
+ };
686
+ const encodeCpuProfile = (profile, options) => {
687
+ const samples = profile.samples ?? [];
688
+ const deltas = profile.timeDeltas ?? [];
689
+ const nodes = new Map(profile.nodes.map((node) => [node.id, node]));
690
+ const parents = /* @__PURE__ */ new Map();
691
+ for (const node of profile.nodes) for (const child of node.children ?? []) parents.set(child, node.id);
692
+ const strings = new Interner("");
693
+ const string = (value) => value === "" ? 0 : strings.intern(value, () => value);
694
+ const functions = new Interner({});
695
+ const locations = new Interner({});
696
+ const stacks = new Interner({});
697
+ const links = new Interner({});
698
+ const locationOf = (nodeId) => {
699
+ const frame = nodes.get(nodeId)?.callFrame;
700
+ if (frame === void 0 || frame.functionName === ROOT) return void 0;
701
+ const file = frame.url.startsWith(FILE_SCHEME) ? frame.url.slice(7) : frame.url;
702
+ const line = frame.lineNumber >= 0 ? frame.lineNumber + 1 : 0;
703
+ const key = `${frame.functionName}\u0000${file}\u0000${line}`;
704
+ return locations.intern(key, () => ({ lines: [{
705
+ functionIndex: functions.intern(key, () => ({
706
+ nameStrindex: string(frame.functionName === "" ? "(anonymous)" : frame.functionName),
707
+ filenameStrindex: string(file),
708
+ startLine: line
709
+ })),
710
+ line
711
+ }] }));
712
+ };
713
+ const stackOf = (nodeId) => stacks.intern(String(nodeId), () => {
714
+ const locationIndices = [];
715
+ for (let current = nodeId; current !== void 0; current = parents.get(current)) {
716
+ const location = locationOf(current);
717
+ if (location !== void 0) locationIndices.push(location);
718
+ }
719
+ return { locationIndices };
720
+ });
721
+ const maxSampleMicros = options.samplingIntervalMicros;
722
+ const groups = /* @__PURE__ */ new Map();
723
+ let elapsedMicros = 0;
724
+ for (let index = 0; index < samples.length; index++) {
725
+ elapsedMicros += deltas[index] ?? 0;
726
+ const nodeId = samples[index];
727
+ if (nodeId === void 0 || nodes.get(nodeId)?.callFrame.functionName === IDLE) continue;
728
+ const valueMicros = Math.min(Math.max(deltas[index + 1] ?? options.samplingIntervalMicros, 0), maxSampleMicros);
729
+ const offsetMs = elapsedMicros / 1e3;
730
+ const span = options.spanEvents === void 0 ? void 0 : spanAt(options.spanEvents, options.startedAtPerfMs + offsetMs);
731
+ const linkIndex = span === void 0 ? 0 : links.intern(span.spanId, () => ({
732
+ traceId: span.traceId,
733
+ spanId: span.spanId
734
+ }));
735
+ const key = `${nodeId}|${linkIndex}`;
736
+ const group = groups.get(key);
737
+ if (group === void 0) groups.set(key, {
738
+ nodeId,
739
+ linkIndex,
740
+ valueNanos: valueMicros * 1e3,
741
+ firstEpochMs: options.startedAtEpochMs + offsetMs
742
+ });
743
+ else group.valueNanos += valueMicros * 1e3;
744
+ }
745
+ if (groups.size === 0) return void 0;
746
+ const cpu = {
747
+ typeStrindex: string("cpu"),
748
+ unitStrindex: string("nanoseconds")
749
+ };
750
+ const profileSamples = [...groups.values()].map((group) => ({
751
+ stackIndex: stackOf(group.nodeId),
752
+ linkIndex: group.linkIndex,
753
+ values: [String(group.valueNanos)],
754
+ timestampsUnixNano: [nanos(group.firstEpochMs)]
755
+ }));
756
+ return {
757
+ resourceProfiles: [{
758
+ resource: options.resource,
759
+ scopeProfiles: [{
760
+ scope: { name: "@safaricom-mxl/node-sdk/profiling" },
761
+ profiles: [{
762
+ sampleType: cpu,
763
+ samples: profileSamples,
764
+ timeUnixNano: nanos(options.startedAtEpochMs),
765
+ durationNano: String(Math.round(options.durationMs * 1e6)),
766
+ periodType: cpu,
767
+ period: String(options.samplingIntervalMicros * 1e3),
768
+ profileId: options.profileId
769
+ }]
770
+ }]
771
+ }],
772
+ dictionary: {
773
+ mappingTable: [{}],
774
+ locationTable: locations.table,
775
+ functionTable: functions.table,
776
+ linkTable: links.table,
777
+ stringTable: strings.table,
778
+ attributeTable: [{}],
779
+ stackTable: stacks.table
780
+ }
781
+ };
782
+ };
783
+ // src/profiling/profiling.ts
784
+ const DEFAULT_PROFILE_WINDOW_MS = 6e4;
785
+ const MIN_PROFILE_WINDOW_MS = 1e3;
786
+ const MIN_SAMPLING_INTERVAL_MICROS = 100;
787
+ const DEFAULT_SAMPLING_INTERVAL_MICROS = 1e4;
788
+ const PROFILER_SETUP_TIMEOUT_MS = 5e3;
789
+ const PROFILER_COMMAND_TIMEOUT_MS = 5e3;
790
+ const EXPORT_TIMEOUT_MS = 1e4;
791
+ const PROFILES_PATH = "/v1development/profiles";
792
+ const profileWindowMs = (window) => Math.max(MIN_PROFILE_WINDOW_MS, window === void 0 || !Number.isFinite(window) || window <= 0 ? DEFAULT_PROFILE_WINDOW_MS : window);
793
+ const samplingIntervalOf = (micros) => micros === void 0 || !Number.isFinite(micros) || micros <= 0 ? DEFAULT_SAMPLING_INTERVAL_MICROS : Math.max(MIN_SAMPLING_INTERVAL_MICROS, Math.round(micros));
794
+ const post = (session, method, params, timeoutMs) => new Promise((resolve, reject) => {
795
+ let settled = false;
796
+ const timer = setTimeout(() => {
797
+ if (settled) return;
798
+ settled = true;
799
+ reject(/* @__PURE__ */ new Error(`${method} got no answer within ${timeoutMs} ms`));
800
+ }, timeoutMs);
801
+ session.post(method, params, (error, reply) => {
802
+ if (settled) return;
803
+ settled = true;
804
+ clearTimeout(timer);
805
+ if (error) reject(error);
806
+ else resolve(reply);
807
+ });
808
+ });
809
+ const randomHex = (bytes) => Buffer.from(crypto.getRandomValues(new Uint8Array(bytes))).toString("hex");
810
+ const withTimeout = (promise, ms, message) => {
811
+ const timeout = new Promise((_, reject) => {
812
+ setTimeout(() => reject(new Error(message)), ms);
813
+ });
814
+ return Promise.race([promise, timeout]);
815
+ };
816
+ let profilerHolders = 0;
817
+ const startCpuProfiler = (options) => {
818
+ profilerHolders += 1;
819
+ if (profilerHolders > 1) return { stop: async () => {
820
+ profilerHolders = Math.max(0, profilerHolders - 1);
821
+ } };
822
+ let stopped = false;
823
+ let loop;
824
+ let session;
825
+ const windowMs = profileWindowMs(options.profiling.window);
826
+ const samplingIntervalMicros = samplingIntervalOf(options.profiling.samplingIntervalMicros);
827
+ const url = `${options.baseUrl.replace(/\/$/, "")}${PROFILES_PATH}`;
828
+ let overflowWarned = false;
829
+ const send = async (body) => {
830
+ const controller = new AbortController();
831
+ const timer = setTimeout(() => controller.abort(), EXPORT_TIMEOUT_MS);
832
+ try {
833
+ await (await fetch(url, {
834
+ method: "POST",
835
+ headers: {
836
+ "content-type": "application/json",
837
+ "OTLP-Profiles-Development-Version": "1",
838
+ ...options.headers
839
+ },
840
+ body: JSON.stringify(body),
841
+ signal: controller.signal
842
+ })).arrayBuffer();
843
+ } finally {
844
+ clearTimeout(timer);
845
+ }
846
+ };
847
+ const run = async () => {
848
+ const inspectorSession = new Session();
849
+ session = inspectorSession;
850
+ inspectorSession.connect();
851
+ const command = (method, params = {}) => post(inspectorSession, method, params, PROFILER_COMMAND_TIMEOUT_MS);
852
+ await withTimeout(command("Profiler.enable"), PROFILER_SETUP_TIMEOUT_MS, "the inspector did not answer");
853
+ await withTimeout(command("Profiler.setSamplingInterval", { interval: samplingIntervalMicros }), PROFILER_SETUP_TIMEOUT_MS, "the inspector did not answer");
854
+ const startWindow = async () => {
855
+ const started = {
856
+ startedAtPerfMs: performance.now(),
857
+ startedAtEpochMs: Date.now()
858
+ };
859
+ await command("Profiler.start");
860
+ return started;
861
+ };
862
+ options.timeline?.setRecording(true);
863
+ let current = await startWindow();
864
+ const exportWindow = async (started, reply, spanEvents) => {
865
+ if (spanEvents?.overflowed === true && !overflowWarned) {
866
+ overflowWarned = true;
867
+ diag.warn(`@safaricom-mxl/node-sdk: more than ${SPAN_EVENT_CAPACITY} span switches in one window; later samples in it are not linked to spans`);
868
+ }
869
+ const profile = reply?.profile;
870
+ if (profile === void 0) return;
871
+ const body = encodeCpuProfile(profile, {
872
+ resource: options.resource,
873
+ ...started,
874
+ durationMs: performance.now() - started.startedAtPerfMs,
875
+ samplingIntervalMicros,
876
+ spanEvents,
877
+ profileId: randomHex(16)
878
+ });
879
+ if (body !== void 0) await send(body);
880
+ };
881
+ while (!stopped) {
882
+ await new Promise((resolve) => setTimeout(resolve, windowMs));
883
+ if (stopped) break;
884
+ const ended = current;
885
+ const reply = await command("Profiler.stop");
886
+ const spanEvents = options.timeline?.drain();
887
+ current = await startWindow();
888
+ await exportWindow(ended, reply, spanEvents).catch((error) => {
889
+ diag.warn("@safaricom-mxl/node-sdk: profile export failed", error);
890
+ });
891
+ }
892
+ const last = await command("Profiler.stop").catch(() => void 0);
893
+ await exportWindow(current, last, options.timeline?.drain()).catch((error) => {
894
+ diag.warn("@safaricom-mxl/node-sdk: final profile export skipped", error);
895
+ });
896
+ };
897
+ loop = run().catch((error) => {
898
+ options.timeline?.setRecording(false);
899
+ diag.warn("@safaricom-mxl/node-sdk: profiling is off: this runtime has no CPU profiler the SDK can drive", error);
900
+ });
901
+ return { stop: async () => {
902
+ stopped = true;
903
+ options.timeline?.setRecording(false);
904
+ profilerHolders = Math.max(0, profilerHolders - 1);
905
+ const timeout = options.shutdownTimeoutMs ?? 3e3;
906
+ await Promise.race([loop ?? Promise.resolve(), new Promise((resolve) => setTimeout(resolve, timeout))]);
907
+ try {
908
+ session?.disconnect();
909
+ } catch {}
910
+ } };
911
+ };
912
+ const normalizeProfiling = (profiling) => {
913
+ if (profiling === true) return {};
914
+ if (profiling === false || profiling === void 0) return void 0;
915
+ return profiling;
916
+ };
917
+ // src/resources/nodeSdkResource.ts
552
918
  function createNodeSdkResource(config) {
553
919
  return resourceFromAttributes({
554
920
  [ATTR_SERVICE_NAME]: config.serviceName || defaultServiceName(),
@@ -560,71 +926,7 @@ function createNodeSdkResource(config) {
560
926
  ...config.additionalResourceAttributes
561
927
  });
562
928
  }
563
- //#endregion
564
- //#region src/exporters/metricReader.ts
565
- function createMetricReader(config) {
566
- const url = resolveOtlpExporterUrl({
567
- kind: "metric",
568
- endpoint: config.otlpEndpoint
569
- });
570
- const headers = parseOtlpHeaders(config.otlpHeaders);
571
- const exporter = config.otlpProtocol === "grpc" ? new OTLPMetricExporter({
572
- url,
573
- headers
574
- }) : new OTLPMetricExporter$1({
575
- url,
576
- headers
577
- });
578
- return new PeriodicExportingMetricReader({
579
- exporter,
580
- exportIntervalMillis: DEFAULT_METRIC_EXPORT_INTERVAL_MS,
581
- exportTimeoutMillis: DEFAULT_METRIC_EXPORT_TIMEOUT_MS
582
- });
583
- }
584
- //#endregion
585
- //#region src/exporters/traceExporter.ts
586
- function createTraceExporter(config) {
587
- const url = resolveOtlpExporterUrl({
588
- kind: "trace",
589
- endpoint: config.otlpEndpoint,
590
- explicitUrl: config.traceExporterUrl
591
- });
592
- const headers = parseOtlpHeaders(config.otlpHeaders);
593
- if (config.otlpProtocol === "grpc") return new OTLPTraceExporter({
594
- url,
595
- timeoutMillis: DEFAULT_TRACE_TIMEOUT_MS,
596
- headers
597
- });
598
- return new OTLPTraceExporter$1({
599
- url,
600
- timeoutMillis: DEFAULT_TRACE_TIMEOUT_MS,
601
- headers
602
- });
603
- }
604
- //#endregion
605
- //#region src/sdk/sampler.ts
606
- const DEFAULT_RATIO = 1;
607
- function resolveTraceSampler(traceSampler, traceSamplerArg) {
608
- if (typeof traceSampler !== "string") return traceSampler;
609
- switch (traceSampler) {
610
- case "always_on": return new AlwaysOnSampler();
611
- case "always_off": return new AlwaysOffSampler();
612
- case "parentbased_always_on": return new ParentBasedSampler({ root: new AlwaysOnSampler() });
613
- case "parentbased_always_off": return new ParentBasedSampler({ root: new AlwaysOffSampler() });
614
- case "traceidratio": return new TraceIdRatioBasedSampler(resolveSamplerRatio(traceSamplerArg));
615
- case "parentbased_traceidratio": return new ParentBasedSampler({ root: new TraceIdRatioBasedSampler(resolveSamplerRatio(traceSamplerArg)) });
616
- default:
617
- diag.error(`@safaricom-mxl/node-sdk: unknown sampler "${traceSampler}", defaulting to always_on`);
618
- return new AlwaysOnSampler();
619
- }
620
- }
621
- function resolveSamplerRatio(arg) {
622
- const parsed = Number(arg);
623
- if (!Number.isFinite(parsed) || parsed < 0 || parsed > 1) return DEFAULT_RATIO;
624
- return parsed;
625
- }
626
- //#endregion
627
- //#region src/sdk/config.ts
929
+ // src/sdk/config.ts
628
930
  function resolveSDKConfig(config = {}) {
629
931
  return {
630
932
  additionalInstrumentations: config.additionalInstrumentations ?? [],
@@ -651,6 +953,7 @@ function resolveSDKConfig(config = {}) {
651
953
  otlpEndpoint: config.otlpEndpoint ?? getStringFromEnv("OTEL_EXPORTER_OTLP_ENDPOINT"),
652
954
  otlpHeaders: config.otlpHeaders ?? getStringFromEnv("OTEL_EXPORTER_OTLP_HEADERS"),
653
955
  otlpProtocol: config.otlpProtocol ?? getStringFromEnv("OTEL_EXPORTER_OTLP_PROTOCOL") ?? "http/protobuf",
956
+ profiling: config.profiling,
654
957
  sentryIntegrationEnabled: config.sentryIntegrationEnabled ?? getBooleanFromEnv("MXL_NODE_SENTRY_INTEGRATION_ENABLED") ?? false,
655
958
  serviceName: config.serviceName ?? getStringFromEnv("OTEL_SERVICE_NAME") ?? "app",
656
959
  spanLimits: config.spanLimits,
@@ -661,8 +964,28 @@ function resolveSDKConfig(config = {}) {
661
964
  traceSamplerArg: config.traceSamplerArg ?? getStringFromEnv("OTEL_TRACES_SAMPLER_ARG") ?? "1"
662
965
  };
663
966
  }
664
- //#endregion
665
- //#region src/sdk/state.ts
967
+ // src/sdk/sampler.ts
968
+ const DEFAULT_RATIO = 1;
969
+ function resolveTraceSampler(traceSampler, traceSamplerArg) {
970
+ if (typeof traceSampler !== "string") return traceSampler;
971
+ switch (traceSampler) {
972
+ case "always_on": return new AlwaysOnSampler();
973
+ case "always_off": return new AlwaysOffSampler();
974
+ case "parentbased_always_on": return new ParentBasedSampler({ root: new AlwaysOnSampler() });
975
+ case "parentbased_always_off": return new ParentBasedSampler({ root: new AlwaysOffSampler() });
976
+ case "traceidratio": return new TraceIdRatioBasedSampler(resolveSamplerRatio(traceSamplerArg));
977
+ case "parentbased_traceidratio": return new ParentBasedSampler({ root: new TraceIdRatioBasedSampler(resolveSamplerRatio(traceSamplerArg)) });
978
+ default:
979
+ diag.error(`@safaricom-mxl/node-sdk: unknown sampler "${traceSampler}", defaulting to always_on`);
980
+ return new AlwaysOnSampler();
981
+ }
982
+ }
983
+ function resolveSamplerRatio(arg) {
984
+ const parsed = Number(arg);
985
+ if (!Number.isFinite(parsed) || parsed < 0 || parsed > 1) return DEFAULT_RATIO;
986
+ return parsed;
987
+ }
988
+ // src/sdk/state.ts
666
989
  let activeConfig;
667
990
  function setActiveSDKConfig(config) {
668
991
  activeConfig = config;
@@ -670,12 +993,12 @@ function setActiveSDKConfig(config) {
670
993
  function getActiveSDKConfig() {
671
994
  return activeConfig;
672
995
  }
673
- //#endregion
674
- //#region src/sdk/initSDK.ts
996
+ // src/sdk/initSDK.ts
675
997
  let sdk;
676
998
  let logger;
677
999
  let contextManager;
678
1000
  let drainableSpanProcessor;
1001
+ let cpuProfiler;
679
1002
  let signalHandlersRegistered = false;
680
1003
  const terminationHandlers = [];
681
1004
  function initSDK(config = {}) {
@@ -699,7 +1022,13 @@ function initSDK(config = {}) {
699
1022
  };
700
1023
  logger = new OTelLogger({ config: resolved });
701
1024
  const traceProcessor = new NodeSpanProcessor(createTraceExporter(resolved));
702
- const spanProcessors = resolved.disableTracing ? [] : [drainableSpanProcessor = new FilterWhenDrainedSpanProcessor(new CompositeSpanProcessor([traceProcessor, ...resolved.spanProcessors]))];
1025
+ const profiling = normalizeProfiling(resolved.profiling);
1026
+ const timeline = profiling !== void 0 && profiling.linkSpans !== false && !resolved.disableTracing ? makeSpanTimeline() : void 0;
1027
+ const spanProcessors = resolved.disableTracing ? [] : [drainableSpanProcessor = new FilterWhenDrainedSpanProcessor(new CompositeSpanProcessor([
1028
+ traceProcessor,
1029
+ ...resolved.spanProcessors,
1030
+ ...timeline === void 0 ? [] : [new ProfilingSpanProcessor(timeline)]
1031
+ ]))];
703
1032
  const instrumentations = [
704
1033
  ...getNodeAutoInstrumentations(autoInstrumentationConfig),
705
1034
  new RuntimeNodeInstrumentation(),
@@ -722,6 +1051,23 @@ function initSDK(config = {}) {
722
1051
  });
723
1052
  sdk.start();
724
1053
  logger.setGlobalProvider();
1054
+ if (profiling !== void 0) {
1055
+ const tracesUrl = resolveOtlpExporterUrl({
1056
+ kind: "trace",
1057
+ endpoint: resolved.otlpEndpoint,
1058
+ explicitUrl: resolved.traceExporterUrl
1059
+ });
1060
+ cpuProfiler = startCpuProfiler({
1061
+ baseUrl: tracesUrl.replace(/\/v1\/traces\/?$/, ""),
1062
+ resource: { attributes: [{
1063
+ key: "service.name",
1064
+ value: { stringValue: resolved.serviceName }
1065
+ }] },
1066
+ headers: parseOtlpHeaders(resolved.otlpHeaders),
1067
+ profiling,
1068
+ timeline
1069
+ });
1070
+ }
725
1071
  if (resolved.stopOnTerminationSignals && !signalHandlersRegistered) registerTerminationHandlers();
726
1072
  if (!resolved.disableStartupLogs) diag.info("@safaricom-mxl/node-sdk: initialized");
727
1073
  return getControl();
@@ -760,6 +1106,8 @@ async function shutdown() {
760
1106
  signalHandlersRegistered = false;
761
1107
  }
762
1108
  drainableSpanProcessor?.drain();
1109
+ await cpuProfiler?.stop();
1110
+ cpuProfiler = void 0;
763
1111
  await Promise.allSettled([logger?.shutdown(), sdk?.shutdown()]);
764
1112
  sdk = void 0;
765
1113
  logger = void 0;
@@ -774,7 +1122,6 @@ function getControl() {
774
1122
  setTraceAttributes
775
1123
  };
776
1124
  }
777
- //#endregion
778
1125
  export { getActiveSDKConfig as a, setTraceAttributes as c, shutdown as i, getInitializedOTelLogger as n, resolveSDKConfig as o, initSDK as r, getTraceAttributes as s, forceFlush as t };
779
1126
 
780
- //# sourceMappingURL=initSDK-CA5vGy0p.mjs.map
1127
+ //# sourceMappingURL=initSDK-BQAwICCw.mjs.map