@bymax-one/nest-telemetry 1.0.4 → 1.0.6

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.
@@ -1,9 +1,18 @@
1
- import { register } from 'module';
1
+ import { register, createRequire } from 'module';
2
+ import { join } from 'path';
2
3
 
3
4
  // src/register/boot.ts
4
5
 
5
6
  // src/sdk/environment.ts
6
7
  var MAX_TIMER_MS = 2147483647;
8
+ var RATIO_SAMPLERS = ["traceidratio", "parentbased_traceidratio"];
9
+ var SAMPLER_NAMES = [
10
+ "always_on",
11
+ "always_off",
12
+ "parentbased_always_on",
13
+ "parentbased_always_off",
14
+ ...RATIO_SAMPLERS
15
+ ];
7
16
  function readExporterList(raw) {
8
17
  return (raw ?? "").split(",").map((name) => name.trim()).filter((name) => name !== "");
9
18
  }
@@ -50,6 +59,41 @@ function readTelemetryEnvironment(source = process.env) {
50
59
  resourceDetectors: detectors === void 0 || detectors.trim() === "" ? void 0 : readExporterList(detectors)
51
60
  };
52
61
  }
62
+ function readRatioSampler(source = process.env) {
63
+ const name = source["OTEL_TRACES_SAMPLER"];
64
+ const arg = source["OTEL_TRACES_SAMPLER_ARG"];
65
+ return name !== void 0 && RATIO_SAMPLERS.includes(name) ? { name, arg } : void 0;
66
+ }
67
+ function readSamplerNearMiss(source = process.env) {
68
+ const name = source["OTEL_TRACES_SAMPLER"];
69
+ if (name === void 0 || SAMPLER_NAMES.includes(name)) return void 0;
70
+ const folded = name.trim().toLowerCase();
71
+ return SAMPLER_NAMES.find((known) => known === folded);
72
+ }
73
+
74
+ // src/sdk/error-code.ts
75
+ var CODE_TOKEN = /^[A-Z0-9_]{1,40}$/;
76
+ var PACKAGE = /@opentelemetry\/[a-z0-9-]+/;
77
+ function codeOf(error) {
78
+ try {
79
+ const code = Reflect.get(Object(error), "code");
80
+ if (typeof code !== "string" && typeof code !== "number") return "UNKNOWN";
81
+ const text = String(code);
82
+ return CODE_TOKEN.test(text) ? text : "UNKNOWN";
83
+ } catch {
84
+ return "UNKNOWN";
85
+ }
86
+ }
87
+ function describeFailure(error) {
88
+ const code = `code ${codeOf(error)}`;
89
+ try {
90
+ const message = Reflect.get(Object(error), "message");
91
+ const named = typeof message === "string" ? PACKAGE.exec(message)?.[0] : void 0;
92
+ return named === void 0 ? code : `${code}, package ${named}`;
93
+ } catch {
94
+ return code;
95
+ }
96
+ }
53
97
 
54
98
  // src/sdk/redaction.ts
55
99
  var REDACTED_QUERY_VALUE = "[redacted]";
@@ -106,6 +150,19 @@ function serializeRedisCommandName(commandName) {
106
150
  return commandName;
107
151
  }
108
152
 
153
+ // src/sdk/warning-sink.ts
154
+ var SINK_KEY = /* @__PURE__ */ Symbol.for("@bymax-one/nest-telemetry/warning-sink");
155
+ function reportWarning(warning) {
156
+ try {
157
+ const sink = Reflect.get(globalThis, SINK_KEY);
158
+ if (sink?.(warning) === true) {
159
+ return;
160
+ }
161
+ } catch {
162
+ }
163
+ process.emitWarning(warning.text, { type: "Warning", code: warning.code });
164
+ }
165
+
109
166
  // src/sdk/assembly.ts
110
167
  var FS_INSTRUMENTATION = "@opentelemetry/instrumentation-fs";
111
168
  var HTTP_INSTRUMENTATION = "@opentelemetry/instrumentation-http";
@@ -130,6 +187,25 @@ function planSignals(env) {
130
187
  sendLogs: !env.logsExporters.includes("none") && env.logsExporters.some((name) => LOG_EXPORTERS.has(name))
131
188
  };
132
189
  }
190
+ function isPresent(value) {
191
+ return value !== void 0 && value !== null;
192
+ }
193
+ function readEachOption(options) {
194
+ return {
195
+ enabled: options.enabled,
196
+ serviceName: options.serviceName,
197
+ serviceVersion: options.serviceVersion,
198
+ ignoreIncomingRequest: options.ignoreIncomingRequest,
199
+ instrumentations: options.instrumentations,
200
+ extraRedactedQueryParams: options.extraRedactedQueryParams,
201
+ unsafe: options.unsafe,
202
+ shutdownTimeoutMs: options.shutdownTimeoutMs,
203
+ env: options.env
204
+ };
205
+ }
206
+ function definedEntries(config) {
207
+ return Object.fromEntries(Object.entries(config).filter(([, value]) => isPresent(value)));
208
+ }
133
209
  function nonBlank(value) {
134
210
  const trimmed = value?.trim();
135
211
  return trimmed === "" ? void 0 : trimmed;
@@ -146,7 +222,7 @@ function buildInstrumentationConfig(options, signals) {
146
222
  const instrumentations = options.instrumentations ?? {};
147
223
  const overrides = {};
148
224
  for (const [name, config] of Object.entries(instrumentations.overrides ?? {})) {
149
- if (config !== void 0) overrides[name] = { ...config };
225
+ if (isPresent(config)) overrides[name] = definedEntries(config);
150
226
  }
151
227
  const redactRedis = options.unsafe?.disableRedisArgumentRedaction !== true;
152
228
  const disableLogSending = !(instrumentations.sendLogs ?? signals.sendLogs);
@@ -169,7 +245,7 @@ function buildInstrumentationConfig(options, signals) {
169
245
  ...options.extraRedactedQueryParams ?? []
170
246
  ])
171
247
  };
172
- if (options.ignoreIncomingRequest !== void 0) {
248
+ if (isPresent(options.ignoreIncomingRequest)) {
173
249
  merged[HTTP_INSTRUMENTATION]["ignoreIncomingRequestHook"] = options.ignoreIncomingRequest;
174
250
  }
175
251
  if (redactRedis) {
@@ -213,6 +289,24 @@ function warnAboutUnsafeOptions(options) {
213
289
  );
214
290
  }
215
291
  }
292
+ var SHOWN_VALUE_LENGTH = 40;
293
+ function warnAboutSamplerRatio(sampler) {
294
+ if (sampler === void 0) return;
295
+ const ratio = sampler.arg?.trim() === "" ? Number.NaN : Number(sampler.arg);
296
+ if (ratio >= 0 && ratio <= 1) return;
297
+ const given = sampler.arg === void 0 ? "not set" : sampler.arg.trim() === "" ? "blank" : `${JSON.stringify(sampler.arg.slice(0, SHOWN_VALUE_LENGTH))}, which is not a number from 0 to 1`;
298
+ reportWarning({
299
+ code: "BYMAX_TELEMETRY_SAMPLER_ARG_INVALID",
300
+ text: `OTEL_TRACES_SAMPLER is ${sampler.name}, but OTEL_TRACES_SAMPLER_ARG is ${given}, so the SDK samples every trace. Set it to the share of traces to keep, from 0 to 1, such as 0.1.`
301
+ });
302
+ }
303
+ function warnAboutSamplerName(meant) {
304
+ if (meant === void 0) return;
305
+ reportWarning({
306
+ code: "BYMAX_TELEMETRY_SAMPLER_NAME_UNKNOWN",
307
+ text: `OTEL_TRACES_SAMPLER differs from "${meant}" only in letter case or whitespace. The SDK compares the name exactly, so it ignores the value and samples every trace. Write it as "${meant}".`
308
+ });
309
+ }
216
310
  function warnAboutOversizedTimers(env) {
217
311
  for (const name of env.oversizedTimers) {
218
312
  process.emitWarning(
@@ -223,7 +317,7 @@ function warnAboutOversizedTimers(env) {
223
317
  }
224
318
  function warnAboutIgnoredOptions(options) {
225
319
  const stop = options.enabled === false;
226
- if (stop || Object.values(options).some((v) => v !== void 0)) {
320
+ if (stop || Object.values(readEachOption(options)).some(isPresent)) {
227
321
  process.emitWarning(
228
322
  stop ? "startTelemetry({ enabled: false }) was called while telemetry is already running. It does not stop the running SDK: call shutdownTelemetry() for that." : "startTelemetry was called while telemetry is already running, so the options of this call were ignored. Pass them to the first call.",
229
323
  IGNORED_WARNING
@@ -231,32 +325,22 @@ function warnAboutIgnoredOptions(options) {
231
325
  }
232
326
  }
233
327
 
234
- // src/sdk/warning-sink.ts
235
- var SINK_KEY = /* @__PURE__ */ Symbol.for("@bymax-one/nest-telemetry/warning-sink");
236
- function reportWarning(warning) {
237
- try {
238
- const sink = Reflect.get(globalThis, SINK_KEY);
239
- if (sink?.(warning) === true) {
240
- return;
241
- }
242
- } catch {
243
- }
244
- process.emitWarning(warning.text, { type: "Warning", code: warning.code });
245
- }
246
-
247
328
  // src/sdk/export-failure.ts
248
329
  var WINDOW_MS = 6e4;
249
- var SUCCESS = 0;
250
- var CODE_TOKEN = /^[A-Z0-9_]{1,40}$/;
251
- function codeOf(error) {
252
- const code = String(Reflect.get(Object(error), "code"));
253
- return CODE_TOKEN.test(code) ? code : "UNKNOWN";
330
+ var COUNT_KEY = /* @__PURE__ */ Symbol.for("@bymax-one/nest-telemetry/export-failures");
331
+ function exportFailureCount() {
332
+ const count = Reflect.get(globalThis, COUNT_KEY);
333
+ return typeof count === "number" ? count : 0;
254
334
  }
335
+ var SUCCESS = 0;
255
336
  function warnOnExportFailure(exporter, kind, clock = () => performance.now()) {
256
337
  const original = exporter.export.bind(exporter);
257
338
  let lastWarning = Number.NEGATIVE_INFINITY;
258
339
  exporter.export = (spans, done) => {
259
340
  original(spans, (result) => {
341
+ if (result.code !== SUCCESS) {
342
+ Reflect.set(globalThis, COUNT_KEY, exportFailureCount() + 1);
343
+ }
260
344
  if (result.code !== SUCCESS && clock() - lastWarning >= WINDOW_MS) {
261
345
  lastWarning = clock();
262
346
  try {
@@ -402,6 +486,33 @@ function selectResourceDetectors(selection, detectors, keeps) {
402
486
  }
403
487
  return [...new Set(chosen)].map((name) => available[name]);
404
488
  }
489
+ var TRANSPORT = "@opentelemetry/winston-transport";
490
+ var BUNDLE = "@opentelemetry/auto-instrumentations-node";
491
+ var INSTRUMENTATION = "@opentelemetry/instrumentation-winston";
492
+ var MESSAGE = `Log forwarding is on and winston is installed, but ${TRANSPORT} cannot be resolved from ${INSTRUMENTATION}, so winston records will not be forwarded. Install ${TRANSPORT} as a direct dependency of the application, or set instrumentations.sendLogs to false. Ignore this if the application never creates a winston logger, or if OTEL_LOGS_EXPORTER is none: nothing is forwarded then either way.`;
493
+ var resolveFrom = (id, from) => {
494
+ try {
495
+ return createRequire(from).resolve(id);
496
+ } catch {
497
+ return void 0;
498
+ }
499
+ };
500
+ function entryFile(argv = process.argv, cwd = process.cwd()) {
501
+ return argv[1] ?? join(cwd, "entry.js");
502
+ }
503
+ function transportMissing(entry, resolve) {
504
+ if (resolve("winston", entry) === void 0) return false;
505
+ const bundle = resolve(BUNDLE, entry);
506
+ if (bundle === void 0) return false;
507
+ const instrumentation = resolve(INSTRUMENTATION, bundle);
508
+ if (instrumentation === void 0) return false;
509
+ return resolve(TRANSPORT, instrumentation) === void 0;
510
+ }
511
+ function warnAboutMissingWinstonTransport(sendLogs, entry = entryFile(), resolve = resolveFrom) {
512
+ if (sendLogs && transportMissing(entry, resolve)) {
513
+ reportWarning({ code: "BYMAX_TELEMETRY_WINSTON_TRANSPORT_MISSING", text: MESSAGE });
514
+ }
515
+ }
405
516
 
406
517
  // src/sdk/start.ts
407
518
  var RESTART_MESSAGE = "Telemetry cannot start again after it was shut down in the same process: the modules the first start instrumented stay patched against its tracer provider, so a second SDK would export nothing for them. Start telemetry once per process; in a test suite, start it once in a global setup.";
@@ -410,7 +521,7 @@ var DISABLED_HANDLE = {
410
521
  shutdown: () => Promise.resolve()
411
522
  };
412
523
  async function startTelemetry(options = {}) {
413
- const env = readTelemetryEnvironment(options.env);
524
+ const env = readTelemetryEnvironment(options.env ?? void 0);
414
525
  if (options.enabled === false || env.sdkDisabled) {
415
526
  if (currentHandle()?.stopping === false || pendingStart()) warnAboutIgnoredOptions(options);
416
527
  return DISABLED_HANDLE;
@@ -487,6 +598,9 @@ async function boot(options, env) {
487
598
  warnAboutUnsafeOptions(options);
488
599
  warnAboutMissingServiceName(options, env);
489
600
  warnAboutOversizedTimers(env);
601
+ warnAboutSamplerName(readSamplerNearMiss());
602
+ warnAboutSamplerRatio(readRatioSampler());
603
+ warnAboutMissingWinstonTransport(options.instrumentations?.sendLogs ?? planSignals(env).sendLogs);
490
604
  const sdk = buildSdk(await loadPackages(), options, env);
491
605
  sdk.start();
492
606
  const handle = createHandle(() => sdk.shutdown(), options.shutdownTimeoutMs);
@@ -518,7 +632,7 @@ async function startOrWarn(start, options) {
518
632
  return await start(options);
519
633
  } catch (error) {
520
634
  process.emitWarning(
521
- `Telemetry could not be started (${String(error)}), so the application continues without it.`,
635
+ `Telemetry could not be started (${describeFailure(error)}), so the application continues without it.`,
522
636
  { type: "Warning", code: "BYMAX_TELEMETRY_START_FAILED" }
523
637
  );
524
638
  return { enabled: false, shutdown: () => Promise.resolve() };
@@ -529,7 +643,7 @@ function registerLoaderHook(register2, parentUrl) {
529
643
  register2(ESM_HOOK_SPECIFIER, parentUrl);
530
644
  } catch (error) {
531
645
  process.emitWarning(
532
- `The OpenTelemetry loader hook could not be registered (${String(error)}), so native ES modules are not instrumented. Install @opentelemetry/instrumentation to instrument them; CommonJS code is unaffected.`,
646
+ `The OpenTelemetry loader hook could not be registered (${describeFailure(error)}), so native ES modules are not instrumented. Install @opentelemetry/instrumentation to instrument them; CommonJS code is unaffected.`,
533
647
  { type: "Warning", code: HOOK_WARNING_CODE }
534
648
  );
535
649
  }
@@ -1,5 +1,8 @@
1
1
  'use strict';
2
2
 
3
+ var module$1 = require('module');
4
+ var path = require('path');
5
+
3
6
  // src/sdk/redaction.ts
4
7
  var REDACTED_QUERY_VALUE = "[redacted]";
5
8
  var URL_QUERY_ATTRIBUTE = "url.query";
@@ -184,6 +187,25 @@ function planSignals(env) {
184
187
  sendLogs: !env.logsExporters.includes("none") && env.logsExporters.some((name) => LOG_EXPORTERS.has(name))
185
188
  };
186
189
  }
190
+ function isPresent(value) {
191
+ return value !== void 0 && value !== null;
192
+ }
193
+ function readEachOption(options) {
194
+ return {
195
+ enabled: options.enabled,
196
+ serviceName: options.serviceName,
197
+ serviceVersion: options.serviceVersion,
198
+ ignoreIncomingRequest: options.ignoreIncomingRequest,
199
+ instrumentations: options.instrumentations,
200
+ extraRedactedQueryParams: options.extraRedactedQueryParams,
201
+ unsafe: options.unsafe,
202
+ shutdownTimeoutMs: options.shutdownTimeoutMs,
203
+ env: options.env
204
+ };
205
+ }
206
+ function definedEntries(config) {
207
+ return Object.fromEntries(Object.entries(config).filter(([, value]) => isPresent(value)));
208
+ }
187
209
  function nonBlank(value) {
188
210
  const trimmed = value?.trim();
189
211
  return trimmed === "" ? void 0 : trimmed;
@@ -200,7 +222,7 @@ function buildInstrumentationConfig(options, signals) {
200
222
  const instrumentations = options.instrumentations ?? {};
201
223
  const overrides = {};
202
224
  for (const [name, config] of Object.entries(instrumentations.overrides ?? {})) {
203
- if (config !== void 0) overrides[name] = { ...config };
225
+ if (isPresent(config)) overrides[name] = definedEntries(config);
204
226
  }
205
227
  const redactRedis = options.unsafe?.disableRedisArgumentRedaction !== true;
206
228
  const disableLogSending = !(instrumentations.sendLogs ?? signals.sendLogs);
@@ -223,7 +245,7 @@ function buildInstrumentationConfig(options, signals) {
223
245
  ...options.extraRedactedQueryParams ?? []
224
246
  ])
225
247
  };
226
- if (options.ignoreIncomingRequest !== void 0) {
248
+ if (isPresent(options.ignoreIncomingRequest)) {
227
249
  merged[HTTP_INSTRUMENTATION]["ignoreIncomingRequestHook"] = options.ignoreIncomingRequest;
228
250
  }
229
251
  if (redactRedis) {
@@ -267,6 +289,24 @@ function warnAboutUnsafeOptions(options) {
267
289
  );
268
290
  }
269
291
  }
292
+ var SHOWN_VALUE_LENGTH = 40;
293
+ function warnAboutSamplerRatio(sampler) {
294
+ if (sampler === void 0) return;
295
+ const ratio = sampler.arg?.trim() === "" ? Number.NaN : Number(sampler.arg);
296
+ if (ratio >= 0 && ratio <= 1) return;
297
+ const given = sampler.arg === void 0 ? "not set" : sampler.arg.trim() === "" ? "blank" : `${JSON.stringify(sampler.arg.slice(0, SHOWN_VALUE_LENGTH))}, which is not a number from 0 to 1`;
298
+ reportWarning({
299
+ code: "BYMAX_TELEMETRY_SAMPLER_ARG_INVALID",
300
+ text: `OTEL_TRACES_SAMPLER is ${sampler.name}, but OTEL_TRACES_SAMPLER_ARG is ${given}, so the SDK samples every trace. Set it to the share of traces to keep, from 0 to 1, such as 0.1.`
301
+ });
302
+ }
303
+ function warnAboutSamplerName(meant) {
304
+ if (meant === void 0) return;
305
+ reportWarning({
306
+ code: "BYMAX_TELEMETRY_SAMPLER_NAME_UNKNOWN",
307
+ text: `OTEL_TRACES_SAMPLER differs from "${meant}" only in letter case or whitespace. The SDK compares the name exactly, so it ignores the value and samples every trace. Write it as "${meant}".`
308
+ });
309
+ }
270
310
  function warnAboutOversizedTimers(env) {
271
311
  for (const name of env.oversizedTimers) {
272
312
  process.emitWarning(
@@ -277,7 +317,7 @@ function warnAboutOversizedTimers(env) {
277
317
  }
278
318
  function warnAboutIgnoredOptions(options) {
279
319
  const stop = options.enabled === false;
280
- if (stop || Object.values(options).some((v) => v !== void 0)) {
320
+ if (stop || Object.values(readEachOption(options)).some(isPresent)) {
281
321
  process.emitWarning(
282
322
  stop ? "startTelemetry({ enabled: false }) was called while telemetry is already running. It does not stop the running SDK: call shutdownTelemetry() for that." : "startTelemetry was called while telemetry is already running, so the options of this call were ignored. Pass them to the first call.",
283
323
  IGNORED_WARNING
@@ -287,6 +327,14 @@ function warnAboutIgnoredOptions(options) {
287
327
 
288
328
  // src/sdk/environment.ts
289
329
  var MAX_TIMER_MS = 2147483647;
330
+ var RATIO_SAMPLERS = ["traceidratio", "parentbased_traceidratio"];
331
+ var SAMPLER_NAMES = [
332
+ "always_on",
333
+ "always_off",
334
+ "parentbased_always_on",
335
+ "parentbased_always_off",
336
+ ...RATIO_SAMPLERS
337
+ ];
290
338
  function readExporterList(raw) {
291
339
  return (raw ?? "").split(",").map((name) => name.trim()).filter((name) => name !== "");
292
340
  }
@@ -333,20 +381,47 @@ function readTelemetryEnvironment(source = process.env) {
333
381
  resourceDetectors: detectors === void 0 || detectors.trim() === "" ? void 0 : readExporterList(detectors)
334
382
  };
335
383
  }
384
+ function readRatioSampler(source = process.env) {
385
+ const name = source["OTEL_TRACES_SAMPLER"];
386
+ const arg = source["OTEL_TRACES_SAMPLER_ARG"];
387
+ return name !== void 0 && RATIO_SAMPLERS.includes(name) ? { name, arg } : void 0;
388
+ }
389
+ function readSamplerNearMiss(source = process.env) {
390
+ const name = source["OTEL_TRACES_SAMPLER"];
391
+ if (name === void 0 || SAMPLER_NAMES.includes(name)) return void 0;
392
+ const folded = name.trim().toLowerCase();
393
+ return SAMPLER_NAMES.find((known) => known === folded);
394
+ }
336
395
 
337
- // src/sdk/export-failure.ts
338
- var WINDOW_MS = 6e4;
339
- var SUCCESS = 0;
396
+ // src/sdk/error-code.ts
340
397
  var CODE_TOKEN = /^[A-Z0-9_]{1,40}$/;
341
398
  function codeOf(error) {
342
- const code = String(Reflect.get(Object(error), "code"));
343
- return CODE_TOKEN.test(code) ? code : "UNKNOWN";
399
+ try {
400
+ const code = Reflect.get(Object(error), "code");
401
+ if (typeof code !== "string" && typeof code !== "number") return "UNKNOWN";
402
+ const text = String(code);
403
+ return CODE_TOKEN.test(text) ? text : "UNKNOWN";
404
+ } catch {
405
+ return "UNKNOWN";
406
+ }
407
+ }
408
+
409
+ // src/sdk/export-failure.ts
410
+ var WINDOW_MS = 6e4;
411
+ var COUNT_KEY = /* @__PURE__ */ Symbol.for("@bymax-one/nest-telemetry/export-failures");
412
+ function exportFailureCount() {
413
+ const count = Reflect.get(globalThis, COUNT_KEY);
414
+ return typeof count === "number" ? count : 0;
344
415
  }
416
+ var SUCCESS = 0;
345
417
  function warnOnExportFailure(exporter, kind, clock = () => performance.now()) {
346
418
  const original = exporter.export.bind(exporter);
347
419
  let lastWarning = Number.NEGATIVE_INFINITY;
348
420
  exporter.export = (spans, done) => {
349
421
  original(spans, (result) => {
422
+ if (result.code !== SUCCESS) {
423
+ Reflect.set(globalThis, COUNT_KEY, exportFailureCount() + 1);
424
+ }
350
425
  if (result.code !== SUCCESS && clock() - lastWarning >= WINDOW_MS) {
351
426
  lastWarning = clock();
352
427
  try {
@@ -420,6 +495,33 @@ function selectResourceDetectors(selection, detectors, keeps) {
420
495
  }
421
496
  return [...new Set(chosen)].map((name) => available[name]);
422
497
  }
498
+ var TRANSPORT = "@opentelemetry/winston-transport";
499
+ var BUNDLE = "@opentelemetry/auto-instrumentations-node";
500
+ var INSTRUMENTATION = "@opentelemetry/instrumentation-winston";
501
+ var MESSAGE = `Log forwarding is on and winston is installed, but ${TRANSPORT} cannot be resolved from ${INSTRUMENTATION}, so winston records will not be forwarded. Install ${TRANSPORT} as a direct dependency of the application, or set instrumentations.sendLogs to false. Ignore this if the application never creates a winston logger, or if OTEL_LOGS_EXPORTER is none: nothing is forwarded then either way.`;
502
+ var resolveFrom = (id, from) => {
503
+ try {
504
+ return module$1.createRequire(from).resolve(id);
505
+ } catch {
506
+ return void 0;
507
+ }
508
+ };
509
+ function entryFile(argv = process.argv, cwd = process.cwd()) {
510
+ return argv[1] ?? path.join(cwd, "entry.js");
511
+ }
512
+ function transportMissing(entry, resolve) {
513
+ if (resolve("winston", entry) === void 0) return false;
514
+ const bundle = resolve(BUNDLE, entry);
515
+ if (bundle === void 0) return false;
516
+ const instrumentation = resolve(INSTRUMENTATION, bundle);
517
+ if (instrumentation === void 0) return false;
518
+ return resolve(TRANSPORT, instrumentation) === void 0;
519
+ }
520
+ function warnAboutMissingWinstonTransport(sendLogs, entry = entryFile(), resolve = resolveFrom) {
521
+ if (sendLogs && transportMissing(entry, resolve)) {
522
+ reportWarning({ code: "BYMAX_TELEMETRY_WINSTON_TRANSPORT_MISSING", text: MESSAGE });
523
+ }
524
+ }
423
525
 
424
526
  // src/sdk/start.ts
425
527
  var RESTART_MESSAGE = "Telemetry cannot start again after it was shut down in the same process: the modules the first start instrumented stay patched against its tracer provider, so a second SDK would export nothing for them. Start telemetry once per process; in a test suite, start it once in a global setup.";
@@ -428,7 +530,7 @@ var DISABLED_HANDLE = {
428
530
  shutdown: () => Promise.resolve()
429
531
  };
430
532
  async function startTelemetry(options = {}) {
431
- const env = readTelemetryEnvironment(options.env);
533
+ const env = readTelemetryEnvironment(options.env ?? void 0);
432
534
  if (options.enabled === false || env.sdkDisabled) {
433
535
  if (currentHandle()?.stopping === false || pendingStart()) warnAboutIgnoredOptions(options);
434
536
  return DISABLED_HANDLE;
@@ -505,6 +607,9 @@ async function boot(options, env) {
505
607
  warnAboutUnsafeOptions(options);
506
608
  warnAboutMissingServiceName(options, env);
507
609
  warnAboutOversizedTimers(env);
610
+ warnAboutSamplerName(readSamplerNearMiss());
611
+ warnAboutSamplerRatio(readRatioSampler());
612
+ warnAboutMissingWinstonTransport(options.instrumentations?.sendLogs ?? planSignals(env).sendLogs);
508
613
  const sdk = buildSdk(await loadPackages(), options, env);
509
614
  sdk.start();
510
615
  const handle = createHandle(() => sdk.shutdown(), options.shutdownTimeoutMs);
@@ -1,3 +1,6 @@
1
+ import { createRequire } from 'module';
2
+ import { join } from 'path';
3
+
1
4
  // src/sdk/redaction.ts
2
5
  var REDACTED_QUERY_VALUE = "[redacted]";
3
6
  var URL_QUERY_ATTRIBUTE = "url.query";
@@ -182,6 +185,25 @@ function planSignals(env) {
182
185
  sendLogs: !env.logsExporters.includes("none") && env.logsExporters.some((name) => LOG_EXPORTERS.has(name))
183
186
  };
184
187
  }
188
+ function isPresent(value) {
189
+ return value !== void 0 && value !== null;
190
+ }
191
+ function readEachOption(options) {
192
+ return {
193
+ enabled: options.enabled,
194
+ serviceName: options.serviceName,
195
+ serviceVersion: options.serviceVersion,
196
+ ignoreIncomingRequest: options.ignoreIncomingRequest,
197
+ instrumentations: options.instrumentations,
198
+ extraRedactedQueryParams: options.extraRedactedQueryParams,
199
+ unsafe: options.unsafe,
200
+ shutdownTimeoutMs: options.shutdownTimeoutMs,
201
+ env: options.env
202
+ };
203
+ }
204
+ function definedEntries(config) {
205
+ return Object.fromEntries(Object.entries(config).filter(([, value]) => isPresent(value)));
206
+ }
185
207
  function nonBlank(value) {
186
208
  const trimmed = value?.trim();
187
209
  return trimmed === "" ? void 0 : trimmed;
@@ -198,7 +220,7 @@ function buildInstrumentationConfig(options, signals) {
198
220
  const instrumentations = options.instrumentations ?? {};
199
221
  const overrides = {};
200
222
  for (const [name, config] of Object.entries(instrumentations.overrides ?? {})) {
201
- if (config !== void 0) overrides[name] = { ...config };
223
+ if (isPresent(config)) overrides[name] = definedEntries(config);
202
224
  }
203
225
  const redactRedis = options.unsafe?.disableRedisArgumentRedaction !== true;
204
226
  const disableLogSending = !(instrumentations.sendLogs ?? signals.sendLogs);
@@ -221,7 +243,7 @@ function buildInstrumentationConfig(options, signals) {
221
243
  ...options.extraRedactedQueryParams ?? []
222
244
  ])
223
245
  };
224
- if (options.ignoreIncomingRequest !== void 0) {
246
+ if (isPresent(options.ignoreIncomingRequest)) {
225
247
  merged[HTTP_INSTRUMENTATION]["ignoreIncomingRequestHook"] = options.ignoreIncomingRequest;
226
248
  }
227
249
  if (redactRedis) {
@@ -265,6 +287,24 @@ function warnAboutUnsafeOptions(options) {
265
287
  );
266
288
  }
267
289
  }
290
+ var SHOWN_VALUE_LENGTH = 40;
291
+ function warnAboutSamplerRatio(sampler) {
292
+ if (sampler === void 0) return;
293
+ const ratio = sampler.arg?.trim() === "" ? Number.NaN : Number(sampler.arg);
294
+ if (ratio >= 0 && ratio <= 1) return;
295
+ const given = sampler.arg === void 0 ? "not set" : sampler.arg.trim() === "" ? "blank" : `${JSON.stringify(sampler.arg.slice(0, SHOWN_VALUE_LENGTH))}, which is not a number from 0 to 1`;
296
+ reportWarning({
297
+ code: "BYMAX_TELEMETRY_SAMPLER_ARG_INVALID",
298
+ text: `OTEL_TRACES_SAMPLER is ${sampler.name}, but OTEL_TRACES_SAMPLER_ARG is ${given}, so the SDK samples every trace. Set it to the share of traces to keep, from 0 to 1, such as 0.1.`
299
+ });
300
+ }
301
+ function warnAboutSamplerName(meant) {
302
+ if (meant === void 0) return;
303
+ reportWarning({
304
+ code: "BYMAX_TELEMETRY_SAMPLER_NAME_UNKNOWN",
305
+ text: `OTEL_TRACES_SAMPLER differs from "${meant}" only in letter case or whitespace. The SDK compares the name exactly, so it ignores the value and samples every trace. Write it as "${meant}".`
306
+ });
307
+ }
268
308
  function warnAboutOversizedTimers(env) {
269
309
  for (const name of env.oversizedTimers) {
270
310
  process.emitWarning(
@@ -275,7 +315,7 @@ function warnAboutOversizedTimers(env) {
275
315
  }
276
316
  function warnAboutIgnoredOptions(options) {
277
317
  const stop = options.enabled === false;
278
- if (stop || Object.values(options).some((v) => v !== void 0)) {
318
+ if (stop || Object.values(readEachOption(options)).some(isPresent)) {
279
319
  process.emitWarning(
280
320
  stop ? "startTelemetry({ enabled: false }) was called while telemetry is already running. It does not stop the running SDK: call shutdownTelemetry() for that." : "startTelemetry was called while telemetry is already running, so the options of this call were ignored. Pass them to the first call.",
281
321
  IGNORED_WARNING
@@ -285,6 +325,14 @@ function warnAboutIgnoredOptions(options) {
285
325
 
286
326
  // src/sdk/environment.ts
287
327
  var MAX_TIMER_MS = 2147483647;
328
+ var RATIO_SAMPLERS = ["traceidratio", "parentbased_traceidratio"];
329
+ var SAMPLER_NAMES = [
330
+ "always_on",
331
+ "always_off",
332
+ "parentbased_always_on",
333
+ "parentbased_always_off",
334
+ ...RATIO_SAMPLERS
335
+ ];
288
336
  function readExporterList(raw) {
289
337
  return (raw ?? "").split(",").map((name) => name.trim()).filter((name) => name !== "");
290
338
  }
@@ -331,20 +379,47 @@ function readTelemetryEnvironment(source = process.env) {
331
379
  resourceDetectors: detectors === void 0 || detectors.trim() === "" ? void 0 : readExporterList(detectors)
332
380
  };
333
381
  }
382
+ function readRatioSampler(source = process.env) {
383
+ const name = source["OTEL_TRACES_SAMPLER"];
384
+ const arg = source["OTEL_TRACES_SAMPLER_ARG"];
385
+ return name !== void 0 && RATIO_SAMPLERS.includes(name) ? { name, arg } : void 0;
386
+ }
387
+ function readSamplerNearMiss(source = process.env) {
388
+ const name = source["OTEL_TRACES_SAMPLER"];
389
+ if (name === void 0 || SAMPLER_NAMES.includes(name)) return void 0;
390
+ const folded = name.trim().toLowerCase();
391
+ return SAMPLER_NAMES.find((known) => known === folded);
392
+ }
334
393
 
335
- // src/sdk/export-failure.ts
336
- var WINDOW_MS = 6e4;
337
- var SUCCESS = 0;
394
+ // src/sdk/error-code.ts
338
395
  var CODE_TOKEN = /^[A-Z0-9_]{1,40}$/;
339
396
  function codeOf(error) {
340
- const code = String(Reflect.get(Object(error), "code"));
341
- return CODE_TOKEN.test(code) ? code : "UNKNOWN";
397
+ try {
398
+ const code = Reflect.get(Object(error), "code");
399
+ if (typeof code !== "string" && typeof code !== "number") return "UNKNOWN";
400
+ const text = String(code);
401
+ return CODE_TOKEN.test(text) ? text : "UNKNOWN";
402
+ } catch {
403
+ return "UNKNOWN";
404
+ }
405
+ }
406
+
407
+ // src/sdk/export-failure.ts
408
+ var WINDOW_MS = 6e4;
409
+ var COUNT_KEY = /* @__PURE__ */ Symbol.for("@bymax-one/nest-telemetry/export-failures");
410
+ function exportFailureCount() {
411
+ const count = Reflect.get(globalThis, COUNT_KEY);
412
+ return typeof count === "number" ? count : 0;
342
413
  }
414
+ var SUCCESS = 0;
343
415
  function warnOnExportFailure(exporter, kind, clock = () => performance.now()) {
344
416
  const original = exporter.export.bind(exporter);
345
417
  let lastWarning = Number.NEGATIVE_INFINITY;
346
418
  exporter.export = (spans, done) => {
347
419
  original(spans, (result) => {
420
+ if (result.code !== SUCCESS) {
421
+ Reflect.set(globalThis, COUNT_KEY, exportFailureCount() + 1);
422
+ }
348
423
  if (result.code !== SUCCESS && clock() - lastWarning >= WINDOW_MS) {
349
424
  lastWarning = clock();
350
425
  try {
@@ -418,6 +493,33 @@ function selectResourceDetectors(selection, detectors, keeps) {
418
493
  }
419
494
  return [...new Set(chosen)].map((name) => available[name]);
420
495
  }
496
+ var TRANSPORT = "@opentelemetry/winston-transport";
497
+ var BUNDLE = "@opentelemetry/auto-instrumentations-node";
498
+ var INSTRUMENTATION = "@opentelemetry/instrumentation-winston";
499
+ var MESSAGE = `Log forwarding is on and winston is installed, but ${TRANSPORT} cannot be resolved from ${INSTRUMENTATION}, so winston records will not be forwarded. Install ${TRANSPORT} as a direct dependency of the application, or set instrumentations.sendLogs to false. Ignore this if the application never creates a winston logger, or if OTEL_LOGS_EXPORTER is none: nothing is forwarded then either way.`;
500
+ var resolveFrom = (id, from) => {
501
+ try {
502
+ return createRequire(from).resolve(id);
503
+ } catch {
504
+ return void 0;
505
+ }
506
+ };
507
+ function entryFile(argv = process.argv, cwd = process.cwd()) {
508
+ return argv[1] ?? join(cwd, "entry.js");
509
+ }
510
+ function transportMissing(entry, resolve) {
511
+ if (resolve("winston", entry) === void 0) return false;
512
+ const bundle = resolve(BUNDLE, entry);
513
+ if (bundle === void 0) return false;
514
+ const instrumentation = resolve(INSTRUMENTATION, bundle);
515
+ if (instrumentation === void 0) return false;
516
+ return resolve(TRANSPORT, instrumentation) === void 0;
517
+ }
518
+ function warnAboutMissingWinstonTransport(sendLogs, entry = entryFile(), resolve = resolveFrom) {
519
+ if (sendLogs && transportMissing(entry, resolve)) {
520
+ reportWarning({ code: "BYMAX_TELEMETRY_WINSTON_TRANSPORT_MISSING", text: MESSAGE });
521
+ }
522
+ }
421
523
 
422
524
  // src/sdk/start.ts
423
525
  var RESTART_MESSAGE = "Telemetry cannot start again after it was shut down in the same process: the modules the first start instrumented stay patched against its tracer provider, so a second SDK would export nothing for them. Start telemetry once per process; in a test suite, start it once in a global setup.";
@@ -426,7 +528,7 @@ var DISABLED_HANDLE = {
426
528
  shutdown: () => Promise.resolve()
427
529
  };
428
530
  async function startTelemetry(options = {}) {
429
- const env = readTelemetryEnvironment(options.env);
531
+ const env = readTelemetryEnvironment(options.env ?? void 0);
430
532
  if (options.enabled === false || env.sdkDisabled) {
431
533
  if (currentHandle()?.stopping === false || pendingStart()) warnAboutIgnoredOptions(options);
432
534
  return DISABLED_HANDLE;
@@ -503,6 +605,9 @@ async function boot(options, env) {
503
605
  warnAboutUnsafeOptions(options);
504
606
  warnAboutMissingServiceName(options, env);
505
607
  warnAboutOversizedTimers(env);
608
+ warnAboutSamplerName(readSamplerNearMiss());
609
+ warnAboutSamplerRatio(readRatioSampler());
610
+ warnAboutMissingWinstonTransport(options.instrumentations?.sendLogs ?? planSignals(env).sendLogs);
506
611
  const sdk = buildSdk(await loadPackages(), options, env);
507
612
  sdk.start();
508
613
  const handle = createHandle(() => sdk.shutdown(), options.shutdownTimeoutMs);