@bymax-one/nest-telemetry 1.0.7 → 1.0.9

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.
package/CHANGELOG.md CHANGED
@@ -10,6 +10,79 @@ heading here.
10
10
 
11
11
  ## [Unreleased]
12
12
 
13
+ ## [1.0.9] - 2026-11-20
14
+
15
+ ### Fixed
16
+
17
+ - **The start reads `unsafe` and `instrumentations` once, each field once, and `ignoreIncomingRequest` once.** The
18
+ warning about turned-off redactions, the SDK build and the instrumentation config each read `unsafe` (and its
19
+ fields), the winston transport warning and the config each read `instrumentations`, and the config read
20
+ `ignoreIncomingRequest` twice, so an option object with a getter, on the option or on one of its fields, could
21
+ make a warning and the effect disagree: a first read of `{}` gave no warning while the host id, the process
22
+ command line and the raw URL were exported. The start now copies both options into a plain object, reading each
23
+ field once, and every step works from the copy. This replaces the per-step reads that 1.0.8 described.
24
+ - **An option that throws when read can no longer leave a started SDK without a handle.** `shutdownTimeoutMs` was
25
+ read after the SDK had started, so a getter that threw there made the start reject while the SDK kept running
26
+ and nothing could stop it. It is read before the start now, with the other options, and every position at which
27
+ an operation on the options fails ends in that error with no SDK started.
28
+
29
+ ### Documentation
30
+
31
+ - **The README says that the sampler ratio warning does not repeat a blank value.** It repeats the value only when
32
+ it is not blank; a blank one is called blank.
33
+ - **1.0.7's note on a rejecting `TELEMETRY_LOGGER` is superseded.** It says a rejection is dropped silently; since
34
+ 1.0.8 the report goes to the Nest logger (a failed flush) or to a process warning (a shutdown timeout, a failed
35
+ export), and the README's logger paragraph says so. The README also says that starting twice returns the running
36
+ handle unless `enabled: false`, which returns a disabled one.
37
+ - **The README says what `startTelemetry` rejects with.** The error that was thrown, as it was thrown: there is no
38
+ library error class for a start. When an option cannot be read, the start ends with that error, with no SDK
39
+ started and no handle left.
40
+
41
+ ### Apply to a derived backend
42
+
43
+ The public declarations did not change. A derived backend acts on this behaviour:
44
+
45
+ 1. An options object whose `unsafe` or `instrumentations` is a getter, or whose fields are getters (a computed or lazy
46
+ option), is now read once, each field once, for the whole start, so the redaction warning and the redaction the
47
+ SDK applies come from the same values. An option that answers differently on each read no longer splits them.
48
+
49
+ ## [1.0.8] - 2026-11-20
50
+
51
+ ### Fixed
52
+
53
+ - **The sampler ratio warning escapes direction and invisible characters in the value it repeats.** It quoted the
54
+ operator's `OTEL_TRACES_SAMPLER_ARG` with `JSON.stringify`, which leaves the control characters from the delete
55
+ character to the C1 range, every format character (the soft hyphen, the zero-width characters, the direction
56
+ marks and overrides, the invisible operators and the byte order mark) and the line and paragraph separators as
57
+ they are, so a value could reorder or hide the warning line. They are now written as `\uXXXX`, or `\u{X}`
58
+ beyond the first plane, chosen by Unicode category.
59
+ - **The unsafe options are read once for each step that needs them.** The SDK build read `options.unsafe` three
60
+ times and the warning about turned-off redactions four times, so an option object whose `unsafe` is a getter
61
+ could make the warning and the SDK disagree. Each step reads it once.
62
+ - **A bound logger whose promise rejects no longer swallows the report.** The hook absorbed the rejection of a
63
+ `TELEMETRY_LOGGER` method (1.0.7) but then wrote nothing, so a failed flush, a shutdown that hit its deadline or
64
+ a failed span export vanished with it. The failed flush now goes to the Nest logger under `TRACING_FLUSH_FAILED`
65
+ with a short code, and the other two take a process warning, as they do with no logger bound.
66
+
67
+ ### Documentation
68
+
69
+ - **The README says that an unknown sampler name is not warned about.** A name that is not a sampler name
70
+ up to case and whitespace, such as `xyz` or `always_offf`, samples every trace without a warning. It also names
71
+ `app.useLogger()` next to `Logger.overrideLogger`, which it calls, and says where a rejected report goes.
72
+ - **The README `env` option row says where the two sampler variables come from.** `OTEL_TRACES_SAMPLER` and
73
+ `OTEL_TRACES_SAMPLER_ARG` are always read from the process environment, whatever the `env` option holds, as the
74
+ SDK reads them.
75
+
76
+ ### Apply to a derived backend
77
+
78
+ The declarations changed only by a private method on `TelemetryShutdownHook` (`reportToNestLogger`), which no
79
+ backend can call, so nothing in your types changes. A derived backend acts on these behaviours:
80
+
81
+ 1. A sampler ratio warning now shows a direction or invisible character in the value as an escape, so a log match
82
+ on that text sees the escape.
83
+ 2. If a `TELEMETRY_LOGGER` method returns a promise that rejects, you now also get the Nest logger entry
84
+ `TRACING_FLUSH_FAILED` or a process warning, where 1.0.7 wrote nothing.
85
+
13
86
  ## [1.0.7] - 2026-11-20
14
87
 
15
88
  ### Fixed
@@ -338,6 +411,8 @@ First release.
338
411
  - Verification from the packed tarball: real `node --import` processes in a CommonJS and a native-ESM
339
412
  application, with planted secrets absent from the exported body and negative controls.
340
413
 
414
+ [1.0.9]: https://github.com/bymaxone/nest-telemetry/releases/tag/v1.0.9
415
+ [1.0.8]: https://github.com/bymaxone/nest-telemetry/releases/tag/v1.0.8
341
416
  [1.0.7]: https://github.com/bymaxone/nest-telemetry/releases/tag/v1.0.7
342
417
  [1.0.6]: https://github.com/bymaxone/nest-telemetry/releases/tag/v1.0.6
343
418
  [1.0.5]: https://github.com/bymaxone/nest-telemetry/releases/tag/v1.0.5
package/README.md CHANGED
@@ -156,7 +156,7 @@ const telemetry = await startTelemetry({
156
156
  await telemetry.shutdown()
157
157
  ```
158
158
 
159
- This package installs no signal handler and shows none, because handling signals belongs to the application: a `SIGTERM` listener replaces Node's default termination, so it has to end the process itself once its work is done. `startTelemetry` resolves to a handle with `enabled` and `shutdown()`. Starting twice returns the handle already running, including across two copies of the module (an ES-module preload and a CommonJS application share the handle through `globalThis`). A later call that passes options is told they were ignored, and `enabled: false` against a running SDK is told it does not stop it: `shutdownTelemetry()` does.
159
+ This package installs no signal handler and shows none, because handling signals belongs to the application: a `SIGTERM` listener replaces Node's default termination, so it has to end the process itself once its work is done. `startTelemetry` resolves to a handle with `enabled` and `shutdown()`. Starting twice returns the handle already running (unless `enabled: false`, which returns a disabled handle), including across two copies of the module (an ES-module preload and a CommonJS application share the handle through `globalThis`). A later call that passes options is told they were ignored, and `enabled: false` against a running SDK is told it does not stop it: `shutdownTelemetry()` does.
160
160
 
161
161
  ---
162
162
 
@@ -166,22 +166,22 @@ This package installs no signal handler and shows none, because handling signals
166
166
 
167
167
  Every field is the host's policy, and none is required.
168
168
 
169
- | Option | Default | What it does |
170
- | -------------------------------------- | ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
171
- | `enabled` | `true` | `false` never starts the SDK. `OTEL_SDK_DISABLED=true` disables it regardless. |
172
- | `serviceName` | `unknown_service:node` | The service name. `OTEL_SERVICE_NAME` overrides it. |
173
- | `serviceVersion` | none | The service version. |
174
- | `ignoreIncomingRequest` | none | Returns `true` for an incoming request that must produce no server span. `ignorePaths(patterns)` builds one from anchored patterns. |
175
- | `instrumentations.fs` | `false` | File-system instrumentation. |
176
- | `instrumentations.sendLogs` | follows `OTEL_LOGS_EXPORTER` | Whether the records of pino, winston and bunyan are forwarded to the OpenTelemetry logs pipeline. Winston also needs `@opentelemetry/winston-transport` installed by your application, see [Forwarding log records](#forwarding-log-records). |
177
- | `instrumentations.overrides` | none | Per-instrumentation configuration, merged over the library's. Redaction settings cannot be replaced here. |
178
- | `extraRedactedQueryParams` | none | Names added to the list redacted from outgoing request URLs. They add to the defaults and never replace them. |
179
- | `unsafe.disableUrlRedaction` | off | Keeps `url.query`, `url.full`, `http.url` and `http.target` as recorded. Literal `true`. Warns. |
180
- | `unsafe.disableRedisArgumentRedaction` | off | Keeps Redis command arguments in `db.query.text`. Literal `true`. Warns. |
181
- | `unsafe.exportProcessCommandArgs` | off | Keeps `process.command_args`, `process.command_line` and `process.command` in the resource. Literal `true`. Warns. |
182
- | `unsafe.exportHostId` | off | Keeps `host.id`, the machine identifier, in the resource. Literal `true`. Warns. |
183
- | `shutdownTimeoutMs` | `5000` | The longest shutdown waits for the final flush. Past it, shutdown warns and resolves. A value that is not a finite number above zero, or is above `120000`, means the default. |
184
- | `env` | the process environment | The environment the library reads. The OpenTelemetry SDK itself always reads the process environment. |
169
+ | Option | Default | What it does |
170
+ | -------------------------------------- | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
171
+ | `enabled` | `true` | `false` never starts the SDK. `OTEL_SDK_DISABLED=true` disables it regardless. |
172
+ | `serviceName` | `unknown_service:node` | The service name. `OTEL_SERVICE_NAME` overrides it. |
173
+ | `serviceVersion` | none | The service version. |
174
+ | `ignoreIncomingRequest` | none | Returns `true` for an incoming request that must produce no server span. `ignorePaths(patterns)` builds one from anchored patterns. |
175
+ | `instrumentations.fs` | `false` | File-system instrumentation. |
176
+ | `instrumentations.sendLogs` | follows `OTEL_LOGS_EXPORTER` | Whether the records of pino, winston and bunyan are forwarded to the OpenTelemetry logs pipeline. Winston also needs `@opentelemetry/winston-transport` installed by your application, see [Forwarding log records](#forwarding-log-records). |
177
+ | `instrumentations.overrides` | none | Per-instrumentation configuration, merged over the library's. Redaction settings cannot be replaced here. |
178
+ | `extraRedactedQueryParams` | none | Names added to the list redacted from outgoing request URLs. They add to the defaults and never replace them. |
179
+ | `unsafe.disableUrlRedaction` | off | Keeps `url.query`, `url.full`, `http.url` and `http.target` as recorded. Literal `true`. Warns. |
180
+ | `unsafe.disableRedisArgumentRedaction` | off | Keeps Redis command arguments in `db.query.text`. Literal `true`. Warns. |
181
+ | `unsafe.exportProcessCommandArgs` | off | Keeps `process.command_args`, `process.command_line` and `process.command` in the resource. Literal `true`. Warns. |
182
+ | `unsafe.exportHostId` | off | Keeps `host.id`, the machine identifier, in the resource. Literal `true`. Warns. |
183
+ | `shutdownTimeoutMs` | `5000` | The longest shutdown waits for the final flush. Past it, shutdown warns and resolves. A value that is not a finite number above zero, or is above `120000`, means the default. |
184
+ | `env` | the process environment | The environment the library reads its variables from, except `OTEL_TRACES_SAMPLER` and `OTEL_TRACES_SAMPLER_ARG`, which are always read from the process environment, as the SDK reads them. The SDK itself always reads the process environment. |
185
185
 
186
186
  A key set to `undefined` or `null` in any option is the same as no key. An override is copied by its own enumerable keys, so pass a plain object: getters on a class prototype are not read.
187
187
 
@@ -216,7 +216,7 @@ The start emits these warnings:
216
216
  | `BYMAX_TELEMETRY_ESM_HOOK_UNAVAILABLE` | The loader hook could not be registered. Native-ESM code is not instrumented. The warning names the error's code and package in the same way. |
217
217
  | `BYMAX_TELEMETRY_SERVICE_NAME_MISSING` | No service name is set; spans use `unknown_service:node`. |
218
218
  | `BYMAX_TELEMETRY_UNSAFE_REDACTION_DISABLED` | A redaction was turned off through an `unsafe` option. |
219
- | `BYMAX_TELEMETRY_OPTIONS_IGNORED` | A `startTelemetry` call reached an SDK that was already running, so its options were ignored, or `enabled: false` did not stop it. Any defined option counts, `env` included. |
219
+ | `BYMAX_TELEMETRY_OPTIONS_IGNORED` | A `startTelemetry` call reached an SDK that was already running, so its options were ignored, or `enabled: false` did not stop it. Any option that is neither `undefined` nor `null` counts, `env` included. |
220
220
  | `BYMAX_TELEMETRY_RESTART_UNSUPPORTED` | `startTelemetry` was called after a shutdown in the same process, and is refused. |
221
221
  | `BYMAX_TELEMETRY_SHUTDOWN_TIMEOUT` | The final flush did not finish within `shutdownTimeoutMs`. Shutdown resolved without it, and spans still queued may be lost. With `TelemetryModule` and a bound `TELEMETRY_LOGGER`, it is reported through `errorStructured` under `TRACING_SHUTDOWN_TIMEOUT` instead. |
222
222
  | `BYMAX_TELEMETRY_EXPORT_FAILED` | A span export failed, so the batch was dropped. The warning names the exporter and a short error code, never the payload or the endpoint, and repeats at most once a minute. With `TelemetryModule` and a bound `TELEMETRY_LOGGER` that has `warnStructured`, it is reported through it under `TRACING_EXPORT_FAILED` instead. |
@@ -225,7 +225,7 @@ The start emits these warnings:
225
225
  | `BYMAX_TELEMETRY_WINSTON_TRANSPORT_MISSING` | Log forwarding is on and winston is installed, but `@opentelemetry/winston-transport` cannot be resolved from the winston instrumentation, so winston records are not forwarded. Install it as a direct dependency of the application, or ignore the warning when your application never creates a winston logger or `OTEL_LOGS_EXPORTER` is `none`. |
226
226
  | `BYMAX_TELEMETRY_BSP_VALUE_IGNORED` | An `OTEL_BSP_SCHEDULE_DELAY` or `OTEL_BSP_EXPORT_TIMEOUT` above 2147483647 ms was ignored, because a timer cannot hold it and Node would clamp it to 1 ms. The default applies. |
227
227
 
228
- The programmatic `startTelemetry` keeps its rejection when the SDK cannot start, for callers that want it.
228
+ The programmatic `startTelemetry` keeps its rejection when the SDK cannot start, for callers that want it. It rejects with the error that was thrown, as it was thrown: the library has no error class of its own for a start, so an option whose getter throws (or a proxy that fails an operation) ends the start with that error, with no SDK started and no handle left.
229
229
 
230
230
  ### What is traced
231
231
 
@@ -289,7 +289,7 @@ A start after a shutdown in the same process is refused: `startTelemetry` reject
289
289
 
290
290
  Every figure here was measured on one laptop, with Node 24 and a handler that does nothing but answer. Read them as orders of magnitude for your own measurement to confirm, not as promises.
291
291
 
292
- - **Sampling.** The default samples every trace. For high traffic set `OTEL_TRACES_SAMPLER=parentbased_traceidratio` and `OTEL_TRACES_SAMPLER_ARG=0.1`. Of 2,000 spans created in one run each, the default exported all of them, a ratio of `0.1` exported 210 and a ratio of `0.01` exported 25. A ratio sampler needs `OTEL_TRACES_SAMPLER_ARG` to be a number from 0 to 1. When it is unset, empty or only whitespace, not a number or outside that range, the SDK falls back to a ratio of 1 and samples every trace, noting it only on a diagnostic channel; the start warns once with `BYMAX_TELEMETRY_SAMPLER_ARG_INVALID`, naming the variable and, when one was given, the value (a blank value is called blank, not unset). The SDK matches the sampler name exactly: `always_on`, `always_off`, `traceidratio`, `parentbased_always_on`, `parentbased_always_off` and `parentbased_traceidratio`, in lower case and without surrounding whitespace. Any other value, `TraceIdRatio` included, is replaced by its default and samples every trace; when the value differs from one of those names only in letter case or surrounding whitespace, the start warns once with `BYMAX_TELEMETRY_SAMPLER_NAME_UNKNOWN`, naming the name that was meant and not repeating the value. It reads the process environment, as the SDK does, and not the `env` option.
292
+ - **Sampling.** The default samples every trace. For high traffic set `OTEL_TRACES_SAMPLER=parentbased_traceidratio` and `OTEL_TRACES_SAMPLER_ARG=0.1`. Of 2,000 spans created in one run each, the default exported all of them, a ratio of `0.1` exported 210 and a ratio of `0.01` exported 25. A ratio sampler needs `OTEL_TRACES_SAMPLER_ARG` to be a number from 0 to 1. When it is unset, empty or only whitespace, not a number or outside that range, the SDK falls back to a ratio of 1 and samples every trace, noting it only on a diagnostic channel; the start warns once with `BYMAX_TELEMETRY_SAMPLER_ARG_INVALID`, naming the variable and, when a non-blank value was given, the value (a blank value is called blank, not unset, and is not repeated). The SDK matches the sampler name exactly: `always_on`, `always_off`, `traceidratio`, `parentbased_always_on`, `parentbased_always_off` and `parentbased_traceidratio`, in lower case and without surrounding whitespace. Any other value, `TraceIdRatio` included, is replaced by its default and samples every trace; when the value differs from one of those names only in letter case or surrounding whitespace, the start warns once with `BYMAX_TELEMETRY_SAMPLER_NAME_UNKNOWN`, naming the name that was meant and not repeating the value. A name that is not one of those up to case and whitespace, such as `xyz` or a misspelling like `always_offf`, is not warned about: it samples every trace as well, so check the spelling of the variable. It reads the process environment, as the SDK does, and not the `env` option.
293
293
  - **TLS to the collector.** Against a collector whose certificate Node does not trust, every export failed with `self-signed certificate`. Setting `OTEL_EXPORTER_OTLP_CERTIFICATE` to the CA file, or `NODE_EXTRA_CA_CERTS`, exported all 2,000 spans in the same setup.
294
294
  - **A collector that is down.** The batch is dropped and the library emits `BYMAX_TELEMETRY_EXPORT_FAILED`, at most once a minute. Shutdown stops waiting at `shutdownTimeoutMs`, 5 seconds by default. Before that deadline existed, shutdown against a closed port took 7,048 ms and 7,214 ms in two runs.
295
295
  - **CPU.** One process, 4 runs per mode, median CPU time per request: 25 µs without the library, 26 µs with it loaded and disabled, 58 µs with a healthy collector (range 35 to 66) and 43 µs with the collector down (range 26 to 65). The extra cost in that handler is roughly 10 to 40 µs per request, and a handler that does real I/O dilutes it. The same configuration varied by up to a factor of two between runs.
@@ -462,7 +462,7 @@ No exports. `node --import @bymax-one/nest-telemetry/register` registers the loa
462
462
  | `TELEMETRY_EXPORT_FAILED_KEY` | constant | The stable key, `TRACING_EXPORT_FAILED`, under which a failed span export is reported, with the exporter kind and the error code as metadata |
463
463
  | `ITelemetryErrorLogger` | type | The shape `TELEMETRY_LOGGER` provides: `errorStructured(logKey, error)` and an optional `warnStructured` |
464
464
 
465
- **A logger that throws or rejects.** The hook's job is to keep shutdown from failing, so every way it reports is guarded. A logger that throws synchronously, whether it is a `TELEMETRY_LOGGER` or the logger the application installed with `Logger.overrideLogger` or `app.useLogger()`, is absorbed, and the shutdown still resolves. A promise that a `TELEMETRY_LOGGER` method returns is not awaited, and its rejection is absorbed. Nest does not do the same for the logger it routes through: an asynchronous `error` method installed with `overrideLogger` that rejects is not caught by Nest or by this library, and Node reports it as an unhandled rejection, which ends the process by default. Write a logger for Nest so that `error` never rejects.
465
+ **A logger that throws or rejects.** The hook's job is to keep shutdown from failing, so every way it reports is guarded. A logger that throws synchronously, whether it is a `TELEMETRY_LOGGER` or the logger the application installed with `Logger.overrideLogger` or `app.useLogger()`, is absorbed, and the shutdown still resolves. A promise that a `TELEMETRY_LOGGER` method returns is not awaited, and its rejection is absorbed; the entry the logger did not take goes to the channel that needs no logger, the Nest logger for a failed flush and a process warning for a shutdown timeout or a failed export. Nest does not do the same for the logger it routes through: an asynchronous `error` method installed with `overrideLogger` or `app.useLogger()` that rejects is not caught by Nest or by this library, and Node reports it as an unhandled rejection, which ends the process by default. Write a logger for Nest so that `error` never rejects.
466
466
 
467
467
  ### Observability: `@bymax-one/nest-telemetry/observability`
468
468
 
@@ -36,6 +36,9 @@ function registerWarningSink(sink) {
36
36
  }
37
37
  };
38
38
  }
39
+ function emitAsProcessWarning(warning) {
40
+ process.emitWarning(warning.text, { type: "Warning", code: warning.code });
41
+ }
39
42
 
40
43
  // src/sdk/handle.ts
41
44
  var HANDLE_KEY = /* @__PURE__ */ Symbol.for("@bymax-one/nest-telemetry/handle");
@@ -57,8 +60,8 @@ var TELEMETRY_FLUSH_FAILED_KEY = "TRACING_FLUSH_FAILED";
57
60
  var TELEMETRY_SHUTDOWN_TIMEOUT_KEY = "TRACING_SHUTDOWN_TIMEOUT";
58
61
  var TELEMETRY_EXPORT_FAILED_KEY = "TRACING_EXPORT_FAILED";
59
62
  var TELEMETRY_LOGGER = /* @__PURE__ */ Symbol("TELEMETRY_LOGGER");
60
- function absorbRejection(result) {
61
- Promise.resolve(result).catch(() => void 0);
63
+ function absorbRejection(result, fallback) {
64
+ Promise.resolve(result).catch(fallback).catch(() => void 0);
62
65
  }
63
66
  exports.TelemetryShutdownHook = class TelemetryShutdownHook {
64
67
  /**
@@ -107,7 +110,8 @@ exports.TelemetryShutdownHook = class TelemetryShutdownHook {
107
110
  const logger = this.structuredLogger();
108
111
  if (warning.code === "BYMAX_TELEMETRY_SHUTDOWN_TIMEOUT" && typeof logger?.errorStructured === "function") {
109
112
  absorbRejection(
110
- logger.errorStructured(TELEMETRY_SHUTDOWN_TIMEOUT_KEY, new Error(warning.text))
113
+ logger.errorStructured(TELEMETRY_SHUTDOWN_TIMEOUT_KEY, new Error(warning.text)),
114
+ () => emitAsProcessWarning(warning)
111
115
  );
112
116
  return true;
113
117
  }
@@ -115,7 +119,8 @@ exports.TelemetryShutdownHook = class TelemetryShutdownHook {
115
119
  absorbRejection(
116
120
  logger.warnStructured(TELEMETRY_EXPORT_FAILED_KEY, warning.text, void 0, {
117
121
  ...warning.fields
118
- })
122
+ }),
123
+ () => emitAsProcessWarning(warning)
119
124
  );
120
125
  return true;
121
126
  }
@@ -136,11 +141,24 @@ exports.TelemetryShutdownHook = class TelemetryShutdownHook {
136
141
  try {
137
142
  const logger = this.structuredLogger();
138
143
  if (typeof logger?.errorStructured === "function") {
139
- absorbRejection(logger.errorStructured(TELEMETRY_FLUSH_FAILED_KEY, failure));
144
+ absorbRejection(
145
+ logger.errorStructured(TELEMETRY_FLUSH_FAILED_KEY, failure),
146
+ () => this.reportToNestLogger(failure)
147
+ );
140
148
  return;
141
149
  }
142
150
  } catch {
143
151
  }
152
+ this.reportToNestLogger(failure);
153
+ }
154
+ /**
155
+ * Writes the failed flush to the Nest logger, which needs nothing the application bound. It never
156
+ * throws: nothing is left to report through when this one fails, and the shutdown must still not
157
+ * fail.
158
+ *
159
+ * @param failure - The failure, of which only a short code is written.
160
+ */
161
+ reportToNestLogger(failure) {
144
162
  try {
145
163
  new common.Logger("Telemetry").error(
146
164
  `${TELEMETRY_FLUSH_FAILED_KEY}: the telemetry flush failed (code ${codeOf(failure)}). Bind TELEMETRY_LOGGER to receive the error itself.`
@@ -85,6 +85,14 @@ declare class TelemetryShutdownHook implements OnApplicationShutdown, OnModuleIn
85
85
  * `toString` could throw here.
86
86
  */
87
87
  private report;
88
+ /**
89
+ * Writes the failed flush to the Nest logger, which needs nothing the application bound. It never
90
+ * throws: nothing is left to report through when this one fails, and the shutdown must still not
91
+ * fail.
92
+ *
93
+ * @param failure - The failure, of which only a short code is written.
94
+ */
95
+ private reportToNestLogger;
88
96
  /**
89
97
  * Looks the structured logger up.
90
98
  *
@@ -85,6 +85,14 @@ declare class TelemetryShutdownHook implements OnApplicationShutdown, OnModuleIn
85
85
  * `toString` could throw here.
86
86
  */
87
87
  private report;
88
+ /**
89
+ * Writes the failed flush to the Nest logger, which needs nothing the application bound. It never
90
+ * throws: nothing is left to report through when this one fails, and the shutdown must still not
91
+ * fail.
92
+ *
93
+ * @param failure - The failure, of which only a short code is written.
94
+ */
95
+ private reportToNestLogger;
88
96
  /**
89
97
  * Looks the structured logger up.
90
98
  *
@@ -34,6 +34,9 @@ function registerWarningSink(sink) {
34
34
  }
35
35
  };
36
36
  }
37
+ function emitAsProcessWarning(warning) {
38
+ process.emitWarning(warning.text, { type: "Warning", code: warning.code });
39
+ }
37
40
 
38
41
  // src/sdk/handle.ts
39
42
  var HANDLE_KEY = /* @__PURE__ */ Symbol.for("@bymax-one/nest-telemetry/handle");
@@ -55,8 +58,8 @@ var TELEMETRY_FLUSH_FAILED_KEY = "TRACING_FLUSH_FAILED";
55
58
  var TELEMETRY_SHUTDOWN_TIMEOUT_KEY = "TRACING_SHUTDOWN_TIMEOUT";
56
59
  var TELEMETRY_EXPORT_FAILED_KEY = "TRACING_EXPORT_FAILED";
57
60
  var TELEMETRY_LOGGER = /* @__PURE__ */ Symbol("TELEMETRY_LOGGER");
58
- function absorbRejection(result) {
59
- Promise.resolve(result).catch(() => void 0);
61
+ function absorbRejection(result, fallback) {
62
+ Promise.resolve(result).catch(fallback).catch(() => void 0);
60
63
  }
61
64
  var TelemetryShutdownHook = class {
62
65
  /**
@@ -105,7 +108,8 @@ var TelemetryShutdownHook = class {
105
108
  const logger = this.structuredLogger();
106
109
  if (warning.code === "BYMAX_TELEMETRY_SHUTDOWN_TIMEOUT" && typeof logger?.errorStructured === "function") {
107
110
  absorbRejection(
108
- logger.errorStructured(TELEMETRY_SHUTDOWN_TIMEOUT_KEY, new Error(warning.text))
111
+ logger.errorStructured(TELEMETRY_SHUTDOWN_TIMEOUT_KEY, new Error(warning.text)),
112
+ () => emitAsProcessWarning(warning)
109
113
  );
110
114
  return true;
111
115
  }
@@ -113,7 +117,8 @@ var TelemetryShutdownHook = class {
113
117
  absorbRejection(
114
118
  logger.warnStructured(TELEMETRY_EXPORT_FAILED_KEY, warning.text, void 0, {
115
119
  ...warning.fields
116
- })
120
+ }),
121
+ () => emitAsProcessWarning(warning)
117
122
  );
118
123
  return true;
119
124
  }
@@ -134,11 +139,24 @@ var TelemetryShutdownHook = class {
134
139
  try {
135
140
  const logger = this.structuredLogger();
136
141
  if (typeof logger?.errorStructured === "function") {
137
- absorbRejection(logger.errorStructured(TELEMETRY_FLUSH_FAILED_KEY, failure));
142
+ absorbRejection(
143
+ logger.errorStructured(TELEMETRY_FLUSH_FAILED_KEY, failure),
144
+ () => this.reportToNestLogger(failure)
145
+ );
138
146
  return;
139
147
  }
140
148
  } catch {
141
149
  }
150
+ this.reportToNestLogger(failure);
151
+ }
152
+ /**
153
+ * Writes the failed flush to the Nest logger, which needs nothing the application bound. It never
154
+ * throws: nothing is left to report through when this one fails, and the shutdown must still not
155
+ * fail.
156
+ *
157
+ * @param failure - The failure, of which only a short code is written.
158
+ */
159
+ reportToNestLogger(failure) {
142
160
  try {
143
161
  new Logger("Telemetry").error(
144
162
  `${TELEMETRY_FLUSH_FAILED_KEY}: the telemetry flush failed (code ${codeOf(failure)}). Bind TELEMETRY_LOGGER to receive the error itself.`
@@ -160,6 +160,9 @@ function reportWarning(warning) {
160
160
  }
161
161
  } catch {
162
162
  }
163
+ emitAsProcessWarning(warning);
164
+ }
165
+ function emitAsProcessWarning(warning) {
163
166
  process.emitWarning(warning.text, { type: "Warning", code: warning.code });
164
167
  }
165
168
 
@@ -218,8 +221,23 @@ function buildResourceAttributes(options, env) {
218
221
  if (version !== void 0) attributes["service.version"] = version;
219
222
  return attributes;
220
223
  }
224
+ function settleUnsafe(unsafe) {
225
+ return {
226
+ disableUrlRedaction: unsafe?.disableUrlRedaction === true,
227
+ disableRedisArgumentRedaction: unsafe?.disableRedisArgumentRedaction === true,
228
+ exportProcessCommandArgs: unsafe?.exportProcessCommandArgs === true,
229
+ exportHostId: unsafe?.exportHostId === true
230
+ };
231
+ }
232
+ function settleInstrumentations(instrumentations) {
233
+ return {
234
+ fs: instrumentations?.fs,
235
+ sendLogs: instrumentations?.sendLogs,
236
+ overrides: instrumentations?.overrides
237
+ };
238
+ }
221
239
  function buildInstrumentationConfig(options, signals) {
222
- const instrumentations = options.instrumentations ?? {};
240
+ const instrumentations = settleInstrumentations(options.instrumentations);
223
241
  const overrides = {};
224
242
  for (const [name, config] of Object.entries(instrumentations.overrides ?? {})) {
225
243
  if (isPresent(config)) overrides[name] = definedEntries(config);
@@ -245,8 +263,9 @@ function buildInstrumentationConfig(options, signals) {
245
263
  ...options.extraRedactedQueryParams ?? []
246
264
  ])
247
265
  };
248
- if (isPresent(options.ignoreIncomingRequest)) {
249
- merged[HTTP_INSTRUMENTATION]["ignoreIncomingRequestHook"] = options.ignoreIncomingRequest;
266
+ const ignoreIncomingRequest = options.ignoreIncomingRequest;
267
+ if (isPresent(ignoreIncomingRequest)) {
268
+ merged[HTTP_INSTRUMENTATION]["ignoreIncomingRequestHook"] = ignoreIncomingRequest;
250
269
  }
251
270
  if (redactRedis) {
252
271
  for (const name of [IOREDIS_INSTRUMENTATION, REDIS_INSTRUMENTATION]) {
@@ -264,25 +283,26 @@ function warnAboutMissingServiceName(options, env) {
264
283
  }
265
284
  }
266
285
  function warnAboutUnsafeOptions(options) {
267
- if (options.unsafe?.disableUrlRedaction === true) {
286
+ const unsafe = options.unsafe;
287
+ if (unsafe?.disableUrlRedaction === true) {
268
288
  process.emitWarning(
269
289
  "URL redaction is disabled: url.query, url.full, http.url and http.target are exported as recorded.",
270
290
  WARNING_OPTIONS
271
291
  );
272
292
  }
273
- if (options.unsafe?.exportProcessCommandArgs === true) {
293
+ if (unsafe?.exportProcessCommandArgs === true) {
274
294
  process.emitWarning(
275
295
  "Process command-line redaction is disabled: process.command_args, process.command_line and process.command are exported in the resource, and command-line arguments can carry secrets.",
276
296
  WARNING_OPTIONS
277
297
  );
278
298
  }
279
- if (options.unsafe?.exportHostId === true) {
299
+ if (unsafe?.exportHostId === true) {
280
300
  process.emitWarning(
281
301
  "Host id redaction is disabled: host.id, the machine identifier, is exported in the resource, and it identifies the machine to every collector and backend.",
282
302
  WARNING_OPTIONS
283
303
  );
284
304
  }
285
- if (options.unsafe?.disableRedisArgumentRedaction === true) {
305
+ if (unsafe?.disableRedisArgumentRedaction === true) {
286
306
  process.emitWarning(
287
307
  "Redis argument redaction is disabled: command arguments, EVAL and EVALSHA payloads included, are exported in db.query.text.",
288
308
  WARNING_OPTIONS
@@ -290,11 +310,18 @@ function warnAboutUnsafeOptions(options) {
290
310
  }
291
311
  }
292
312
  var SHOWN_VALUE_LENGTH = 40;
313
+ var UNSAFE_IN_LOG = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu;
314
+ function quoteOperatorValue(value) {
315
+ return JSON.stringify(value.slice(0, SHOWN_VALUE_LENGTH)).replace(UNSAFE_IN_LOG, (char) => {
316
+ const hex = Number(char.codePointAt(0)).toString(16);
317
+ return hex.length > 4 ? `\\u{${hex}}` : `\\u${hex.padStart(4, "0")}`;
318
+ });
319
+ }
293
320
  function warnAboutSamplerRatio(sampler) {
294
321
  if (sampler === void 0) return;
295
322
  const ratio = sampler.arg?.trim() === "" ? Number.NaN : Number(sampler.arg);
296
323
  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`;
324
+ const given = sampler.arg === void 0 ? "not set" : sampler.arg.trim() === "" ? "blank" : `${quoteOperatorValue(sampler.arg)}, which is not a number from 0 to 1`;
298
325
  reportWarning({
299
326
  code: "BYMAX_TELEMETRY_SAMPLER_ARG_INVALID",
300
327
  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.`
@@ -561,9 +588,10 @@ async function loadPackages() {
561
588
  ]);
562
589
  return { sdkNode, sdkTrace, autoInstrumentations, exporter, resources };
563
590
  }
564
- function buildSdk(packages, options, env) {
591
+ function buildSdk(packages, options, env, read) {
565
592
  const { sdkNode, sdkTrace, autoInstrumentations, exporter, resources } = packages;
566
593
  const signals = planSignals(env);
594
+ const { instrumentations, unsafe } = read;
567
595
  return new sdkNode.NodeSDK({
568
596
  ...signals.overrides,
569
597
  resource: resources.resourceFromAttributes(buildResourceAttributes(options, env)),
@@ -577,33 +605,46 @@ function buildSdk(packages, options, env) {
577
605
  serviceinstance: resources.serviceInstanceIdDetector
578
606
  },
579
607
  {
580
- keepCommandLine: options.unsafe?.exportProcessCommandArgs === true,
581
- keepHostId: options.unsafe?.exportHostId === true
608
+ keepCommandLine: unsafe?.exportProcessCommandArgs === true,
609
+ keepHostId: unsafe?.exportHostId === true
582
610
  }
583
611
  ),
584
612
  spanProcessors: [
585
613
  // Ordered before the batch processor, so each span is redacted in place before it is exported.
586
- ...options.unsafe?.disableUrlRedaction === true ? [] : [createUrlQueryRedactor()],
614
+ ...unsafe?.disableUrlRedaction === true ? [] : [createUrlQueryRedactor()],
587
615
  new sdkTrace.BatchSpanProcessor({
588
616
  exporter: warnOnExportFailure(new exporter.OTLPTraceExporter(), "otlp-http traces"),
589
617
  ...env.batchSpanProcessor
590
618
  })
591
619
  ],
592
620
  instrumentations: [
593
- autoInstrumentations.getNodeAutoInstrumentations(buildInstrumentationConfig(options, signals))
621
+ autoInstrumentations.getNodeAutoInstrumentations(
622
+ buildInstrumentationConfig(
623
+ {
624
+ instrumentations,
625
+ unsafe,
626
+ extraRedactedQueryParams: options.extraRedactedQueryParams,
627
+ ignoreIncomingRequest: options.ignoreIncomingRequest
628
+ },
629
+ signals
630
+ )
631
+ )
594
632
  ]
595
633
  });
596
634
  }
597
635
  async function boot(options, env) {
598
- warnAboutUnsafeOptions(options);
636
+ const unsafe = settleUnsafe(options.unsafe);
637
+ const instrumentations = settleInstrumentations(options.instrumentations);
638
+ warnAboutUnsafeOptions({ unsafe });
599
639
  warnAboutMissingServiceName(options, env);
600
640
  warnAboutOversizedTimers(env);
601
641
  warnAboutSamplerName(readSamplerNearMiss());
602
642
  warnAboutSamplerRatio(readRatioSampler());
603
- warnAboutMissingWinstonTransport(options.instrumentations?.sendLogs ?? planSignals(env).sendLogs);
604
- const sdk = buildSdk(await loadPackages(), options, env);
643
+ warnAboutMissingWinstonTransport(instrumentations.sendLogs ?? planSignals(env).sendLogs);
644
+ const shutdownTimeoutMs = options.shutdownTimeoutMs;
645
+ const sdk = buildSdk(await loadPackages(), options, env, { instrumentations, unsafe });
605
646
  sdk.start();
606
- const handle = createHandle(() => sdk.shutdown(), options.shutdownTimeoutMs);
647
+ const handle = createHandle(() => sdk.shutdown(), shutdownTimeoutMs);
607
648
  registerHandle(handle);
608
649
  return handle;
609
650
  }
@@ -84,6 +84,9 @@ function reportWarning(warning) {
84
84
  }
85
85
  } catch {
86
86
  }
87
+ emitAsProcessWarning(warning);
88
+ }
89
+ function emitAsProcessWarning(warning) {
87
90
  process.emitWarning(warning.text, { type: "Warning", code: warning.code });
88
91
  }
89
92
 
@@ -218,8 +221,23 @@ function buildResourceAttributes(options, env) {
218
221
  if (version !== void 0) attributes["service.version"] = version;
219
222
  return attributes;
220
223
  }
224
+ function settleUnsafe(unsafe) {
225
+ return {
226
+ disableUrlRedaction: unsafe?.disableUrlRedaction === true,
227
+ disableRedisArgumentRedaction: unsafe?.disableRedisArgumentRedaction === true,
228
+ exportProcessCommandArgs: unsafe?.exportProcessCommandArgs === true,
229
+ exportHostId: unsafe?.exportHostId === true
230
+ };
231
+ }
232
+ function settleInstrumentations(instrumentations) {
233
+ return {
234
+ fs: instrumentations?.fs,
235
+ sendLogs: instrumentations?.sendLogs,
236
+ overrides: instrumentations?.overrides
237
+ };
238
+ }
221
239
  function buildInstrumentationConfig(options, signals) {
222
- const instrumentations = options.instrumentations ?? {};
240
+ const instrumentations = settleInstrumentations(options.instrumentations);
223
241
  const overrides = {};
224
242
  for (const [name, config] of Object.entries(instrumentations.overrides ?? {})) {
225
243
  if (isPresent(config)) overrides[name] = definedEntries(config);
@@ -245,8 +263,9 @@ function buildInstrumentationConfig(options, signals) {
245
263
  ...options.extraRedactedQueryParams ?? []
246
264
  ])
247
265
  };
248
- if (isPresent(options.ignoreIncomingRequest)) {
249
- merged[HTTP_INSTRUMENTATION]["ignoreIncomingRequestHook"] = options.ignoreIncomingRequest;
266
+ const ignoreIncomingRequest = options.ignoreIncomingRequest;
267
+ if (isPresent(ignoreIncomingRequest)) {
268
+ merged[HTTP_INSTRUMENTATION]["ignoreIncomingRequestHook"] = ignoreIncomingRequest;
250
269
  }
251
270
  if (redactRedis) {
252
271
  for (const name of [IOREDIS_INSTRUMENTATION, REDIS_INSTRUMENTATION]) {
@@ -264,25 +283,26 @@ function warnAboutMissingServiceName(options, env) {
264
283
  }
265
284
  }
266
285
  function warnAboutUnsafeOptions(options) {
267
- if (options.unsafe?.disableUrlRedaction === true) {
286
+ const unsafe = options.unsafe;
287
+ if (unsafe?.disableUrlRedaction === true) {
268
288
  process.emitWarning(
269
289
  "URL redaction is disabled: url.query, url.full, http.url and http.target are exported as recorded.",
270
290
  WARNING_OPTIONS
271
291
  );
272
292
  }
273
- if (options.unsafe?.exportProcessCommandArgs === true) {
293
+ if (unsafe?.exportProcessCommandArgs === true) {
274
294
  process.emitWarning(
275
295
  "Process command-line redaction is disabled: process.command_args, process.command_line and process.command are exported in the resource, and command-line arguments can carry secrets.",
276
296
  WARNING_OPTIONS
277
297
  );
278
298
  }
279
- if (options.unsafe?.exportHostId === true) {
299
+ if (unsafe?.exportHostId === true) {
280
300
  process.emitWarning(
281
301
  "Host id redaction is disabled: host.id, the machine identifier, is exported in the resource, and it identifies the machine to every collector and backend.",
282
302
  WARNING_OPTIONS
283
303
  );
284
304
  }
285
- if (options.unsafe?.disableRedisArgumentRedaction === true) {
305
+ if (unsafe?.disableRedisArgumentRedaction === true) {
286
306
  process.emitWarning(
287
307
  "Redis argument redaction is disabled: command arguments, EVAL and EVALSHA payloads included, are exported in db.query.text.",
288
308
  WARNING_OPTIONS
@@ -290,11 +310,18 @@ function warnAboutUnsafeOptions(options) {
290
310
  }
291
311
  }
292
312
  var SHOWN_VALUE_LENGTH = 40;
313
+ var UNSAFE_IN_LOG = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu;
314
+ function quoteOperatorValue(value) {
315
+ return JSON.stringify(value.slice(0, SHOWN_VALUE_LENGTH)).replace(UNSAFE_IN_LOG, (char) => {
316
+ const hex = Number(char.codePointAt(0)).toString(16);
317
+ return hex.length > 4 ? `\\u{${hex}}` : `\\u${hex.padStart(4, "0")}`;
318
+ });
319
+ }
293
320
  function warnAboutSamplerRatio(sampler) {
294
321
  if (sampler === void 0) return;
295
322
  const ratio = sampler.arg?.trim() === "" ? Number.NaN : Number(sampler.arg);
296
323
  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`;
324
+ const given = sampler.arg === void 0 ? "not set" : sampler.arg.trim() === "" ? "blank" : `${quoteOperatorValue(sampler.arg)}, which is not a number from 0 to 1`;
298
325
  reportWarning({
299
326
  code: "BYMAX_TELEMETRY_SAMPLER_ARG_INVALID",
300
327
  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.`
@@ -570,9 +597,10 @@ async function loadPackages() {
570
597
  ]);
571
598
  return { sdkNode, sdkTrace, autoInstrumentations, exporter, resources };
572
599
  }
573
- function buildSdk(packages, options, env) {
600
+ function buildSdk(packages, options, env, read) {
574
601
  const { sdkNode, sdkTrace, autoInstrumentations, exporter, resources } = packages;
575
602
  const signals = planSignals(env);
603
+ const { instrumentations, unsafe } = read;
576
604
  return new sdkNode.NodeSDK({
577
605
  ...signals.overrides,
578
606
  resource: resources.resourceFromAttributes(buildResourceAttributes(options, env)),
@@ -586,33 +614,46 @@ function buildSdk(packages, options, env) {
586
614
  serviceinstance: resources.serviceInstanceIdDetector
587
615
  },
588
616
  {
589
- keepCommandLine: options.unsafe?.exportProcessCommandArgs === true,
590
- keepHostId: options.unsafe?.exportHostId === true
617
+ keepCommandLine: unsafe?.exportProcessCommandArgs === true,
618
+ keepHostId: unsafe?.exportHostId === true
591
619
  }
592
620
  ),
593
621
  spanProcessors: [
594
622
  // Ordered before the batch processor, so each span is redacted in place before it is exported.
595
- ...options.unsafe?.disableUrlRedaction === true ? [] : [createUrlQueryRedactor()],
623
+ ...unsafe?.disableUrlRedaction === true ? [] : [createUrlQueryRedactor()],
596
624
  new sdkTrace.BatchSpanProcessor({
597
625
  exporter: warnOnExportFailure(new exporter.OTLPTraceExporter(), "otlp-http traces"),
598
626
  ...env.batchSpanProcessor
599
627
  })
600
628
  ],
601
629
  instrumentations: [
602
- autoInstrumentations.getNodeAutoInstrumentations(buildInstrumentationConfig(options, signals))
630
+ autoInstrumentations.getNodeAutoInstrumentations(
631
+ buildInstrumentationConfig(
632
+ {
633
+ instrumentations,
634
+ unsafe,
635
+ extraRedactedQueryParams: options.extraRedactedQueryParams,
636
+ ignoreIncomingRequest: options.ignoreIncomingRequest
637
+ },
638
+ signals
639
+ )
640
+ )
603
641
  ]
604
642
  });
605
643
  }
606
644
  async function boot(options, env) {
607
- warnAboutUnsafeOptions(options);
645
+ const unsafe = settleUnsafe(options.unsafe);
646
+ const instrumentations = settleInstrumentations(options.instrumentations);
647
+ warnAboutUnsafeOptions({ unsafe });
608
648
  warnAboutMissingServiceName(options, env);
609
649
  warnAboutOversizedTimers(env);
610
650
  warnAboutSamplerName(readSamplerNearMiss());
611
651
  warnAboutSamplerRatio(readRatioSampler());
612
- warnAboutMissingWinstonTransport(options.instrumentations?.sendLogs ?? planSignals(env).sendLogs);
613
- const sdk = buildSdk(await loadPackages(), options, env);
652
+ warnAboutMissingWinstonTransport(instrumentations.sendLogs ?? planSignals(env).sendLogs);
653
+ const shutdownTimeoutMs = options.shutdownTimeoutMs;
654
+ const sdk = buildSdk(await loadPackages(), options, env, { instrumentations, unsafe });
614
655
  sdk.start();
615
- const handle = createHandle(() => sdk.shutdown(), options.shutdownTimeoutMs);
656
+ const handle = createHandle(() => sdk.shutdown(), shutdownTimeoutMs);
616
657
  registerHandle(handle);
617
658
  return handle;
618
659
  }
@@ -82,6 +82,9 @@ function reportWarning(warning) {
82
82
  }
83
83
  } catch {
84
84
  }
85
+ emitAsProcessWarning(warning);
86
+ }
87
+ function emitAsProcessWarning(warning) {
85
88
  process.emitWarning(warning.text, { type: "Warning", code: warning.code });
86
89
  }
87
90
 
@@ -216,8 +219,23 @@ function buildResourceAttributes(options, env) {
216
219
  if (version !== void 0) attributes["service.version"] = version;
217
220
  return attributes;
218
221
  }
222
+ function settleUnsafe(unsafe) {
223
+ return {
224
+ disableUrlRedaction: unsafe?.disableUrlRedaction === true,
225
+ disableRedisArgumentRedaction: unsafe?.disableRedisArgumentRedaction === true,
226
+ exportProcessCommandArgs: unsafe?.exportProcessCommandArgs === true,
227
+ exportHostId: unsafe?.exportHostId === true
228
+ };
229
+ }
230
+ function settleInstrumentations(instrumentations) {
231
+ return {
232
+ fs: instrumentations?.fs,
233
+ sendLogs: instrumentations?.sendLogs,
234
+ overrides: instrumentations?.overrides
235
+ };
236
+ }
219
237
  function buildInstrumentationConfig(options, signals) {
220
- const instrumentations = options.instrumentations ?? {};
238
+ const instrumentations = settleInstrumentations(options.instrumentations);
221
239
  const overrides = {};
222
240
  for (const [name, config] of Object.entries(instrumentations.overrides ?? {})) {
223
241
  if (isPresent(config)) overrides[name] = definedEntries(config);
@@ -243,8 +261,9 @@ function buildInstrumentationConfig(options, signals) {
243
261
  ...options.extraRedactedQueryParams ?? []
244
262
  ])
245
263
  };
246
- if (isPresent(options.ignoreIncomingRequest)) {
247
- merged[HTTP_INSTRUMENTATION]["ignoreIncomingRequestHook"] = options.ignoreIncomingRequest;
264
+ const ignoreIncomingRequest = options.ignoreIncomingRequest;
265
+ if (isPresent(ignoreIncomingRequest)) {
266
+ merged[HTTP_INSTRUMENTATION]["ignoreIncomingRequestHook"] = ignoreIncomingRequest;
248
267
  }
249
268
  if (redactRedis) {
250
269
  for (const name of [IOREDIS_INSTRUMENTATION, REDIS_INSTRUMENTATION]) {
@@ -262,25 +281,26 @@ function warnAboutMissingServiceName(options, env) {
262
281
  }
263
282
  }
264
283
  function warnAboutUnsafeOptions(options) {
265
- if (options.unsafe?.disableUrlRedaction === true) {
284
+ const unsafe = options.unsafe;
285
+ if (unsafe?.disableUrlRedaction === true) {
266
286
  process.emitWarning(
267
287
  "URL redaction is disabled: url.query, url.full, http.url and http.target are exported as recorded.",
268
288
  WARNING_OPTIONS
269
289
  );
270
290
  }
271
- if (options.unsafe?.exportProcessCommandArgs === true) {
291
+ if (unsafe?.exportProcessCommandArgs === true) {
272
292
  process.emitWarning(
273
293
  "Process command-line redaction is disabled: process.command_args, process.command_line and process.command are exported in the resource, and command-line arguments can carry secrets.",
274
294
  WARNING_OPTIONS
275
295
  );
276
296
  }
277
- if (options.unsafe?.exportHostId === true) {
297
+ if (unsafe?.exportHostId === true) {
278
298
  process.emitWarning(
279
299
  "Host id redaction is disabled: host.id, the machine identifier, is exported in the resource, and it identifies the machine to every collector and backend.",
280
300
  WARNING_OPTIONS
281
301
  );
282
302
  }
283
- if (options.unsafe?.disableRedisArgumentRedaction === true) {
303
+ if (unsafe?.disableRedisArgumentRedaction === true) {
284
304
  process.emitWarning(
285
305
  "Redis argument redaction is disabled: command arguments, EVAL and EVALSHA payloads included, are exported in db.query.text.",
286
306
  WARNING_OPTIONS
@@ -288,11 +308,18 @@ function warnAboutUnsafeOptions(options) {
288
308
  }
289
309
  }
290
310
  var SHOWN_VALUE_LENGTH = 40;
311
+ var UNSAFE_IN_LOG = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu;
312
+ function quoteOperatorValue(value) {
313
+ return JSON.stringify(value.slice(0, SHOWN_VALUE_LENGTH)).replace(UNSAFE_IN_LOG, (char) => {
314
+ const hex = Number(char.codePointAt(0)).toString(16);
315
+ return hex.length > 4 ? `\\u{${hex}}` : `\\u${hex.padStart(4, "0")}`;
316
+ });
317
+ }
291
318
  function warnAboutSamplerRatio(sampler) {
292
319
  if (sampler === void 0) return;
293
320
  const ratio = sampler.arg?.trim() === "" ? Number.NaN : Number(sampler.arg);
294
321
  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`;
322
+ const given = sampler.arg === void 0 ? "not set" : sampler.arg.trim() === "" ? "blank" : `${quoteOperatorValue(sampler.arg)}, which is not a number from 0 to 1`;
296
323
  reportWarning({
297
324
  code: "BYMAX_TELEMETRY_SAMPLER_ARG_INVALID",
298
325
  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.`
@@ -568,9 +595,10 @@ async function loadPackages() {
568
595
  ]);
569
596
  return { sdkNode, sdkTrace, autoInstrumentations, exporter, resources };
570
597
  }
571
- function buildSdk(packages, options, env) {
598
+ function buildSdk(packages, options, env, read) {
572
599
  const { sdkNode, sdkTrace, autoInstrumentations, exporter, resources } = packages;
573
600
  const signals = planSignals(env);
601
+ const { instrumentations, unsafe } = read;
574
602
  return new sdkNode.NodeSDK({
575
603
  ...signals.overrides,
576
604
  resource: resources.resourceFromAttributes(buildResourceAttributes(options, env)),
@@ -584,33 +612,46 @@ function buildSdk(packages, options, env) {
584
612
  serviceinstance: resources.serviceInstanceIdDetector
585
613
  },
586
614
  {
587
- keepCommandLine: options.unsafe?.exportProcessCommandArgs === true,
588
- keepHostId: options.unsafe?.exportHostId === true
615
+ keepCommandLine: unsafe?.exportProcessCommandArgs === true,
616
+ keepHostId: unsafe?.exportHostId === true
589
617
  }
590
618
  ),
591
619
  spanProcessors: [
592
620
  // Ordered before the batch processor, so each span is redacted in place before it is exported.
593
- ...options.unsafe?.disableUrlRedaction === true ? [] : [createUrlQueryRedactor()],
621
+ ...unsafe?.disableUrlRedaction === true ? [] : [createUrlQueryRedactor()],
594
622
  new sdkTrace.BatchSpanProcessor({
595
623
  exporter: warnOnExportFailure(new exporter.OTLPTraceExporter(), "otlp-http traces"),
596
624
  ...env.batchSpanProcessor
597
625
  })
598
626
  ],
599
627
  instrumentations: [
600
- autoInstrumentations.getNodeAutoInstrumentations(buildInstrumentationConfig(options, signals))
628
+ autoInstrumentations.getNodeAutoInstrumentations(
629
+ buildInstrumentationConfig(
630
+ {
631
+ instrumentations,
632
+ unsafe,
633
+ extraRedactedQueryParams: options.extraRedactedQueryParams,
634
+ ignoreIncomingRequest: options.ignoreIncomingRequest
635
+ },
636
+ signals
637
+ )
638
+ )
601
639
  ]
602
640
  });
603
641
  }
604
642
  async function boot(options, env) {
605
- warnAboutUnsafeOptions(options);
643
+ const unsafe = settleUnsafe(options.unsafe);
644
+ const instrumentations = settleInstrumentations(options.instrumentations);
645
+ warnAboutUnsafeOptions({ unsafe });
606
646
  warnAboutMissingServiceName(options, env);
607
647
  warnAboutOversizedTimers(env);
608
648
  warnAboutSamplerName(readSamplerNearMiss());
609
649
  warnAboutSamplerRatio(readRatioSampler());
610
- warnAboutMissingWinstonTransport(options.instrumentations?.sendLogs ?? planSignals(env).sendLogs);
611
- const sdk = buildSdk(await loadPackages(), options, env);
650
+ warnAboutMissingWinstonTransport(instrumentations.sendLogs ?? planSignals(env).sendLogs);
651
+ const shutdownTimeoutMs = options.shutdownTimeoutMs;
652
+ const sdk = buildSdk(await loadPackages(), options, env, { instrumentations, unsafe });
612
653
  sdk.start();
613
- const handle = createHandle(() => sdk.shutdown(), options.shutdownTimeoutMs);
654
+ const handle = createHandle(() => sdk.shutdown(), shutdownTimeoutMs);
614
655
  registerHandle(handle);
615
656
  return handle;
616
657
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bymax-one/nest-telemetry",
3
- "version": "1.0.7",
3
+ "version": "1.0.9",
4
4
  "description": "OpenTelemetry tracing for NestJS 11 and plain Node: starts the SDK before your app loads, redacts secrets from spans by default, and flushes on shutdown. Optional peers, zero cost when disabled.",
5
5
  "author": "Bymax One <support@bymax.one>",
6
6
  "license": "MIT",