@nestjs/observe 0.0.1 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/README.md +16 -0
  2. package/dist/.tsbuildinfo +1 -1
  3. package/dist/agent/detached-observe-worker.js +98 -1
  4. package/dist/agent/observe-agent.shared-buffer.d.ts +82 -0
  5. package/dist/agent/observe-agent.shared-buffer.js +94 -3
  6. package/dist/agent/observe-agent.worker.d.ts +28 -0
  7. package/dist/agent/observe-agent.worker.js +59 -5
  8. package/dist/custom-metrics/counter.d.ts +124 -0
  9. package/dist/custom-metrics/counter.js +93 -0
  10. package/dist/custom-metrics/gauge.d.ts +116 -0
  11. package/dist/custom-metrics/gauge.js +55 -0
  12. package/dist/custom-metrics/summary.d.ts +102 -0
  13. package/dist/custom-metrics/summary.js +100 -0
  14. package/dist/encoders/custom-metrics.encoder.js +18 -0
  15. package/dist/encoders/remap-keys.util.d.ts +11 -0
  16. package/dist/encoders/remap-keys.util.js +15 -0
  17. package/dist/encoders/trace.encoder.d.ts +7 -0
  18. package/dist/encoders/trace.encoder.js +12 -0
  19. package/dist/instrument/create-instance-decorator.instrument.d.ts +8 -0
  20. package/dist/instrument/create-instance-decorator.instrument.js +67 -0
  21. package/dist/interfaces/custom-metric.interface.d.ts +74 -0
  22. package/dist/interfaces/graphql.interfaces.d.ts +16 -0
  23. package/dist/interfaces/job-snapshot.interface.d.ts +70 -0
  24. package/dist/interfaces/node-runtime-metrics.interface.d.ts +5 -0
  25. package/dist/interfaces/observe-options.interface.d.ts +358 -0
  26. package/dist/interfaces/request-snapshot.interface.d.ts +62 -0
  27. package/dist/interfaces/trace-events.interfaces.d.ts +51 -0
  28. package/dist/interfaces/trace-span.interface.d.ts +29 -0
  29. package/dist/observe.module.js +29 -0
  30. package/dist/profiling/cpu-profiler.service.d.ts +65 -0
  31. package/dist/profiling/cpu-profiler.service.js +80 -0
  32. package/dist/profiling/fold-profile.util.d.ts +20 -0
  33. package/dist/profiling/fold-profile.util.js +0 -0
  34. package/dist/profiling/profile-uploader.d.ts +26 -0
  35. package/dist/profiling/profile-uploader.js +52 -0
  36. package/dist/profiling/span-slice-recorder.d.ts +51 -0
  37. package/dist/profiling/span-slice-recorder.js +77 -0
  38. package/dist/protocols/graphql-observe-agent.service.d.ts +128 -0
  39. package/dist/protocols/graphql-observe-agent.service.js +166 -0
  40. package/dist/protocols/graphql-operation-parser.d.ts +26 -0
  41. package/dist/protocols/graphql-operation-parser.js +66 -0
  42. package/dist/protocols/http-observe-agent.service.d.ts +19 -0
  43. package/dist/protocols/http-observe-agent.service.js +34 -0
  44. package/dist/protocols/queue-observe-agent.service.d.ts +8 -0
  45. package/dist/protocols/queue-observe-agent.service.js +32 -0
  46. package/dist/protocols/rpc-observe-agent.service.d.ts +7 -0
  47. package/dist/protocols/rpc-observe-agent.service.js +12 -0
  48. package/dist/services/logger-patcher.service.d.ts +4 -0
  49. package/dist/services/logger-patcher.service.js +13 -1
  50. package/dist/services/node-runtime-metrics.service.js +24 -8
  51. package/dist/services/operation-trace.registry.d.ts +56 -1
  52. package/dist/services/operation-trace.registry.js +145 -6
  53. package/dist/services/stdout-forwarder.service.d.ts +19 -0
  54. package/dist/services/stdout-forwarder.service.js +62 -0
  55. package/dist/services/trace-sampler.service.d.ts +6 -0
  56. package/dist/services/trace-sampler.service.js +3 -3
  57. package/dist/services/tracer.service.d.ts +91 -0
  58. package/dist/services/tracer.service.js +56 -1
  59. package/dist/trace-span.delegate.d.ts +11 -0
  60. package/dist/trace-span.delegate.js +11 -0
  61. package/dist/types/path-value.type.d.ts +4 -0
  62. package/dist/utils/default-trace-id-generator.util.js +11 -0
  63. package/dist/utils/log-line.parser.d.ts +14 -0
  64. package/dist/utils/log-line.parser.js +37 -0
  65. package/dist/utils/log-redactor.js +65 -0
  66. package/dist/utils/redact-url-query.d.ts +17 -0
  67. package/dist/utils/redact-url-query.js +38 -0
  68. package/dist/utils/source-context.util.d.ts +22 -0
  69. package/dist/utils/source-context.util.js +60 -0
  70. package/dist/utils/source-map-resolver.util.d.ts +13 -0
  71. package/dist/utils/source-map-resolver.util.js +26 -28
  72. package/package.json +1 -1
@@ -17,15 +17,50 @@ import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.j
17
17
  import { parseLogLine } from "../utils/log-line.parser.js";
18
18
  import { LogRedactor } from "../utils/log-redactor.js";
19
19
  import { CALLER_METADATA_KEY, OBSERVE_OPTIONS } from "../observe.constants.js";
20
+ /**
21
+ * Cap on the unterminated tail held between writes.
22
+ *
23
+ * A process that writes a long stretch without a newline (a progress bar, a
24
+ * streamed response) would otherwise grow this string without bound. At the cap
25
+ * the tail is forwarded as-is rather than discarded - a partial line is still
26
+ * evidence.
27
+ */
20
28
  const MAX_PARTIAL_LINE_LENGTH = 8 * 1024;
29
+ /**
30
+ * Most of a line the parser and redactor are ever given.
31
+ *
32
+ * Everything in `toLogEntry` runs synchronously inside the patched
33
+ * `process.stdout.write`, on the application's own hot path, and the redactor
34
+ * is a set of regular expressions whose cost grows with input length. A single
35
+ * multi-megabyte line - a dumped payload, and payloads can carry content an
36
+ * outside caller chose - must not be able to hold the event loop while every
37
+ * rule walks it.
38
+ *
39
+ * The bound is safe because it is four times what can ship: the shared buffer
40
+ * truncates entries to 4 KB, so bytes beyond this window were never going to
41
+ * leave the process - and a secret straddling the 4 KB cut still sits whole
42
+ * inside this window, so it is redacted before the cut can split it.
43
+ */
21
44
  const MAX_PARSED_LINE_LENGTH = 16 * 1024;
22
45
  let StdoutForwarderService = StdoutForwarderService_1 = class StdoutForwarderService {
23
46
  options;
24
47
  observeAgentSharedBuffer;
25
48
  als;
26
49
  logger = new Logger(StdoutForwarderService_1.name);
50
+ /**
51
+ * stdout arrives in chunks, not lines: a single write can carry half a line,
52
+ * several lines, or a line split across two calls. Parsing a chunk directly
53
+ * would mangle every log that straddles a boundary, so the trailing fragment
54
+ * is held here until its newline shows up.
55
+ */
27
56
  partialLine = "";
28
57
  originalWrite = null;
58
+ /**
59
+ * Null only when redaction has been switched off explicitly. Defaulting to on
60
+ * matters more here than anywhere else in the agent: enabling `forwardLogs`
61
+ * moves every log line onto another machine, and the failure mode of getting
62
+ * it wrong is a credential in someone else's database.
63
+ */
29
64
  redactor;
30
65
  constructor(options, observeAgentSharedBuffer, als) {
31
66
  this.options = options;
@@ -51,19 +86,34 @@ let StdoutForwarderService = StdoutForwarderService_1 = class StdoutForwarderSer
51
86
  if (this.originalWrite) {
52
87
  return;
53
88
  }
89
+ // The unbound original is kept, so `restore` puts back exactly what was
90
+ // there. Storing the bound copy instead meant every start/restore cycle
91
+ // left one more `bind` wrapper on the stream - and this module is designed
92
+ // to be torn down and recreated.
54
93
  this.originalWrite = process.stdout.write;
55
94
  const originalWrite = process.stdout.write.bind(process.stdout);
56
95
  process.stdout.write = ((chunk, encoding, callback) => {
57
96
  if (typeof chunk === "string") {
97
+ // Never let a forwarding failure take down the write it wrapped -
98
+ // stdout has to keep working even if telemetry does not.
58
99
  try {
59
100
  this.consume(chunk);
60
101
  }
61
102
  catch {
103
+ // Intentionally silent: logging here would re-enter this same patched
104
+ // write and recurse.
62
105
  }
63
106
  }
64
107
  return originalWrite(chunk, encoding, callback);
65
108
  });
66
109
  }
110
+ /**
111
+ * Restores the original stdout.write.
112
+ *
113
+ * Without this the patch outlives the module - which matters in tests, where
114
+ * a torn-down app would keep pushing into a buffer nobody drains, and in any
115
+ * process that recreates the Nest application.
116
+ */
67
117
  restore() {
68
118
  if (!this.originalWrite) {
69
119
  return;
@@ -75,6 +125,8 @@ let StdoutForwarderService = StdoutForwarderService_1 = class StdoutForwarderSer
75
125
  consume(chunk) {
76
126
  const combined = this.partialLine + chunk;
77
127
  const segments = combined.split("\n");
128
+ // The final segment has no newline yet, so it is either an incomplete line
129
+ // or the empty string left by a chunk that ended cleanly.
78
130
  this.partialLine = segments.pop() ?? "";
79
131
  const entries = segments
80
132
  .filter((line) => line.trim().length > 0)
@@ -101,15 +153,25 @@ let StdoutForwarderService = StdoutForwarderService_1 = class StdoutForwarderSer
101
153
  const parsed = parseLogLine(line);
102
154
  const store = this.als.getStore();
103
155
  const contextTraceId = store?.get(this.options.traceIdKey);
156
+ // The line's own trace id wins: it was captured when the log was written,
157
+ // whereas the async store is read now and may already have moved on.
104
158
  const traceId = parsed.traceId ?? contextTraceId;
105
159
  return {
106
160
  timestamp: Date.now(),
107
161
  traceId,
162
+ // Only meaningful alongside the store's own trace. When the line carried a
163
+ // trace id of its own and it disagrees, the store has moved on to a
164
+ // different operation and its span belongs to that one - naming it here
165
+ // would file the line under a span it was never written inside.
108
166
  spanId: traceId === contextTraceId
109
167
  ? store?.get(CALLER_METADATA_KEY)
110
168
  : undefined,
111
169
  level: parsed.level,
112
170
  context: parsed.context,
171
+ // Redaction happens here, before the entry reaches the shared buffer -
172
+ // which is also before the buffer truncates oversized lines. That order is
173
+ // deliberate: truncating first would cut a long secret in half and ship
174
+ // the surviving half.
113
175
  attributes: this.redactor
114
176
  ? this.redactor.redactAttributes(parsed.attributes)
115
177
  : parsed.attributes,
@@ -2,6 +2,12 @@ import { ObserveModuleOptionsWithDefaults } from "../interfaces/observe-options.
2
2
  export declare class TraceSamplerService {
3
3
  private readonly options;
4
4
  constructor(options: ObserveModuleOptionsWithDefaults);
5
+ /**
6
+ * Determines if a trace should be captured based on the protocol and attributes.
7
+ * @param protocol - The protocol type ('http', 'rpc', 'grpc' or 'graphql').
8
+ * @param attributes - The attributes relevant to the protocol.
9
+ * @returns boolean indicating whether the trace should be captured.
10
+ */
5
11
  shouldCapture(protocol: "http", attributes: {
6
12
  url: string;
7
13
  method: string;
@@ -19,13 +19,13 @@ let TraceSamplerService = class TraceSamplerService {
19
19
  }
20
20
  shouldCapture(protocol, attributes) {
21
21
  if (!this.options.tracesSampleRate) {
22
- return true;
22
+ return true; // Always capture if sample rate is not set
23
23
  }
24
24
  if (typeof this.options.tracesSampleRate === "number") {
25
25
  if (this.options.tracesSampleRate >= 1) {
26
- return true;
26
+ return true; // Capture all traces if sample rate is 100%
27
27
  }
28
- return Math.random() < this.options.tracesSampleRate;
28
+ return Math.random() < this.options.tracesSampleRate; // Randomly capture traces based on sample rate
29
29
  }
30
30
  return this.options.tracesSampleRate(protocol, attributes);
31
31
  }
@@ -16,31 +16,122 @@ export declare class TracerService<Store extends Record<string | symbol, unknown
16
16
  private readonly gauges;
17
17
  private readonly summaries;
18
18
  constructor(operationTraceRegistry: OperationTraceRegistry, als: AsyncLocalStorage<Map<KeyOf<Store> | TraceKey, any>>, observeAgentSharedBuffer: ObserveAgentSharedBuffer, options: ObserveModuleOptionsWithDefaults);
19
+ /**
20
+ * Creates a new trace span with the given name and executes the provided callback within that span.
21
+ * The callback can be synchronous or asynchronous.
22
+ */
19
23
  createSpan(name: string, callback: (span: TraceSpanDelegate) => unknown | Promise<unknown>): Promise<any>;
24
+ /**
25
+ * Retrieves the active span for the current request.
26
+ * This method should be called within an async context where the AsyncLocalStorage is active.
27
+ * If no active span is found, an error is thrown.
28
+ * @returns {Promise<TraceSpanDelegate>} A promise that resolves to the active span delegate.
29
+ */
20
30
  activeSpan(): Promise<TraceSpanDelegate>;
31
+ /**
32
+ * Captures an error and associates it with the current trace.
33
+ * This method should be called within an async context where the AsyncLocalStorage is active.
34
+ */
21
35
  captureError(error: Error, tags?: Record<string, string | number | boolean>): Promise<void>;
36
+ /**
37
+ * Creates or retrieves a counter metric with the specified name.
38
+ * If a counter with the same name already exists, it returns the existing counter.
39
+ * Otherwise, it creates a new counter with the provided parameters.
40
+ * @param name The name of the counter.
41
+ * @returns A Counter instance with the specified name.
42
+ */
22
43
  counter<TLabel extends string = "default">(name: string): Counter<TLabel>;
44
+ /**
45
+ * Creates or retrieves a counter metric with the specified name, description, and initial value.
46
+ * If a counter with the same name already exists, it returns the existing counter.
47
+ * Otherwise, it creates a new counter with the provided parameters.
48
+ * @param name The name of the counter.
49
+ * @param attributes An object containing optional description, initialValue, and labels for the counter.
50
+ * @returns A Counter instance with the specified name, description, and initial value.
51
+ */
23
52
  counter<TLabel extends string = "default">(name: string, attributes: {
24
53
  description?: string;
25
54
  initialValue?: number;
26
55
  labels?: TLabel[];
27
56
  }): Counter<TLabel>;
57
+ /**
58
+ * Creates or retrieves a gauge metric with the specified name.
59
+ * If a gauge with the same name already exists, it returns the existing gauge.
60
+ * Otherwise, it creates a new gauge with the provided parameters.
61
+ * The default gauge's kind is "ratio".
62
+ * @param name The name of the gauge.
63
+ * @returns A Gauge instance with the specified name.
64
+ */
28
65
  gauge<TLabel extends string = "default">(name: string): Gauge<TLabel>;
66
+ /**
67
+ * Creates or retrieves a gauge metric with the specified name, description, and initial value.
68
+ * If a gauge with the same name already exists, it returns the existing gauge.
69
+ * Otherwise, it creates a new gauge with the provided parameters.
70
+ * @param name The name of the gauge.
71
+ * @param attributes An object containing optional description, initialValue, and labels for the gauge. Can also include kind (e.g., "additive" or "ratio").
72
+ * @returns A Gauge instance with the specified name, description, kind, and initial value.
73
+ */
29
74
  gauge<TLabel extends string = "default">(name: string, attributes: {
30
75
  description?: string;
31
76
  initialValue?: number;
32
77
  labels?: TLabel[];
33
78
  kind?: GaugeKind;
34
79
  }): Gauge<TLabel>;
80
+ /**
81
+ * Creates or retrieves a summary metric with the specified name.
82
+ * If a summary with the same name already exists, it returns the existing summary.
83
+ * Otherwise, it creates a new summary with the provided parameters.
84
+ * @param name The name of the summary.
85
+ * @returns A Summary instance with the specified name.
86
+ */
35
87
  summary<TLabel extends string = "default">(name: string): Summary<TLabel>;
88
+ /**
89
+ * Creates or retrieves a summary metric with the specified name and description.
90
+ * If a summary with the same name already exists, it returns the existing summary.
91
+ * Otherwise, it creates a new summary with the provided parameters.
92
+ * @param name The name of the summary.
93
+ * @param attributes An object containing optional description and labels for the
94
+ * summary, plus `sampleSize` - how many observations per label are retained to
95
+ * compute quantiles from, which bounds the summary's memory under load.
96
+ * @returns A Summary instance with the specified name and description.
97
+ */
36
98
  summary<TLabel extends string = "default">(name: string, attributes: {
37
99
  description?: string;
38
100
  labels?: TLabel[];
39
101
  sampleSize?: number;
40
102
  }): Summary<TLabel>;
103
+ /**
104
+ * The id of the trace currently in flight, or `null` outside one.
105
+ *
106
+ * Unlike `getAttribute`/`activeSpan`, this does not throw when there is no
107
+ * active store - reading the trace id to forward it downstream (an outgoing
108
+ * HTTP header, gRPC metadata, a queued job payload) is exactly the kind of
109
+ * call that may legitimately happen outside a traced context, and a thrown
110
+ * error there would force every caller to wrap it in a try/catch just to
111
+ * propagate an id that simply isn't there yet.
112
+ */
41
113
  currentTraceId(): string | null;
114
+ /**
115
+ * Sets an attribute on the current trace.
116
+ * For example, you can use this to add metadata to the current request trace for later use and retrieval.
117
+ * This method should be called within an async context where the AsyncLocalStorage is active.
118
+ * @param key The attribute key.
119
+ * @param value The attribute value.
120
+ */
42
121
  setAttribute<P extends Path<Store>>(key: P, value: PathValue<Store, P>): void;
122
+ /**
123
+ * Retrieves an attribute from the current trace (request context).
124
+ * This allows you to access metadata that was set earlier in the request lifecycle.
125
+ * This method should be called within an async context where the AsyncLocalStorage is active.
126
+ * @param key The attribute key.
127
+ * @returns The attribute value or undefined if not found.
128
+ */
43
129
  getAttribute<P extends Path<Store>>(key: P): PathValue<Store, P> | undefined;
130
+ /**
131
+ * Reads the trace id the request was opened under. Its absence means the call
132
+ * is outside any traced operation, which is the same mistake as calling these
133
+ * methods with no async context at all - and is reported the same way.
134
+ */
44
135
  private requireTraceId;
45
136
  private registerCounterChangeHandler;
46
137
  private registerGaugeChangeHandler;
@@ -23,6 +23,9 @@ let TracerService = class TracerService {
23
23
  als;
24
24
  observeAgentSharedBuffer;
25
25
  options;
26
+ // Each entry has its own label union, so the maps hold the label-agnostic
27
+ // form: pinning them to `Counter<"default">` only forced a cast back out on
28
+ // every read and another one on every write.
26
29
  counters = new Map();
27
30
  gauges = new Map();
28
31
  summaries = new Map();
@@ -32,7 +35,12 @@ let TracerService = class TracerService {
32
35
  this.observeAgentSharedBuffer = observeAgentSharedBuffer;
33
36
  this.options = options;
34
37
  }
38
+ /**
39
+ * Creates a new trace span with the given name and executes the provided callback within that span.
40
+ * The callback can be synchronous or asynchronous.
41
+ */
35
42
  async createSpan(name, callback) {
43
+ // await new Promise(resolve => setImmediate(resolve));
36
44
  const store = this.als.getStore();
37
45
  if (!store) {
38
46
  throw new Error('AsyncLocalStorage is not initialized. Ensure that you are using the "createSpan" method within an async context.');
@@ -41,7 +49,14 @@ let TracerService = class TracerService {
41
49
  const callerId = store.get(CALLER_METADATA_KEY);
42
50
  return this.operationTraceRegistry.createManualSpan(traceId, callerId, name, callback);
43
51
  }
52
+ /**
53
+ * Retrieves the active span for the current request.
54
+ * This method should be called within an async context where the AsyncLocalStorage is active.
55
+ * If no active span is found, an error is thrown.
56
+ * @returns {Promise<TraceSpanDelegate>} A promise that resolves to the active span delegate.
57
+ */
44
58
  async activeSpan() {
59
+ // await new Promise((resolve) => setImmediate(resolve));
45
60
  const store = this.als.getStore();
46
61
  if (!store) {
47
62
  throw new Error('AsyncLocalStorage is not initialized. Ensure that you are using the "activeSpan" method within an async context.');
@@ -57,16 +72,27 @@ let TracerService = class TracerService {
57
72
  tags = {};
58
73
  activeOngoingEvent.tags = tags;
59
74
  }
60
- const traceSpanDelegate = new TraceSpanDelegate(activeOngoingEvent.spanId ?? "", activeOngoingEvent.name, tags);
75
+ const traceSpanDelegate = new TraceSpanDelegate(
76
+ // Optional on the shared `TraceSpan` interface, always set on the nodes
77
+ // the registry builds - and `getActiveSpan` only ever returns one of
78
+ // those.
79
+ activeOngoingEvent.spanId ?? "", activeOngoingEvent.name, tags);
61
80
  return traceSpanDelegate;
62
81
  }
82
+ /**
83
+ * Captures an error and associates it with the current trace.
84
+ * This method should be called within an async context where the AsyncLocalStorage is active.
85
+ */
63
86
  async captureError(error, tags) {
87
+ // await new Promise((resolve) => setImmediate(resolve));
64
88
  const store = this.als.getStore();
65
89
  if (!store) {
66
90
  throw new Error('AsyncLocalStorage is not initialized. Ensure that you are using the "captureError" method within an async context.');
67
91
  }
68
92
  const traceId = store.get(this.options.traceIdKey);
69
93
  if (typeof traceId !== "string") {
94
+ // Reporting an error must not raise one. The registry warned and gave up
95
+ // in this case anyway, so the outcome is unchanged.
70
96
  return;
71
97
  }
72
98
  const callerId = store.get(CALLER_METADATA_KEY);
@@ -134,11 +160,28 @@ let TracerService = class TracerService {
134
160
  this.summaries.set(name, summary);
135
161
  return summary;
136
162
  }
163
+ /**
164
+ * The id of the trace currently in flight, or `null` outside one.
165
+ *
166
+ * Unlike `getAttribute`/`activeSpan`, this does not throw when there is no
167
+ * active store - reading the trace id to forward it downstream (an outgoing
168
+ * HTTP header, gRPC metadata, a queued job payload) is exactly the kind of
169
+ * call that may legitimately happen outside a traced context, and a thrown
170
+ * error there would force every caller to wrap it in a try/catch just to
171
+ * propagate an id that simply isn't there yet.
172
+ */
137
173
  currentTraceId() {
138
174
  const store = this.als.getStore();
139
175
  const traceId = store?.get(this.options.traceIdKey);
140
176
  return typeof traceId === "string" ? traceId : null;
141
177
  }
178
+ /**
179
+ * Sets an attribute on the current trace.
180
+ * For example, you can use this to add metadata to the current request trace for later use and retrieval.
181
+ * This method should be called within an async context where the AsyncLocalStorage is active.
182
+ * @param key The attribute key.
183
+ * @param value The attribute value.
184
+ */
142
185
  setAttribute(key, value) {
143
186
  const store = this.als.getStore();
144
187
  if (!store) {
@@ -146,6 +189,13 @@ let TracerService = class TracerService {
146
189
  }
147
190
  store.set(key, value);
148
191
  }
192
+ /**
193
+ * Retrieves an attribute from the current trace (request context).
194
+ * This allows you to access metadata that was set earlier in the request lifecycle.
195
+ * This method should be called within an async context where the AsyncLocalStorage is active.
196
+ * @param key The attribute key.
197
+ * @returns The attribute value or undefined if not found.
198
+ */
149
199
  getAttribute(key) {
150
200
  const store = this.als.getStore();
151
201
  if (!store) {
@@ -153,6 +203,11 @@ let TracerService = class TracerService {
153
203
  }
154
204
  return store.get(key);
155
205
  }
206
+ /**
207
+ * Reads the trace id the request was opened under. Its absence means the call
208
+ * is outside any traced operation, which is the same mistake as calling these
209
+ * methods with no async context at all - and is reported the same way.
210
+ */
156
211
  requireTraceId(store, method) {
157
212
  const traceId = store.get(this.options.traceIdKey);
158
213
  if (typeof traceId !== "string") {
@@ -5,6 +5,17 @@ export declare class TraceSpanDelegate {
5
5
  get id(): string;
6
6
  get name(): string | undefined;
7
7
  constructor(_id: string, _name: string | undefined, _tags: Record<string, string | number | boolean>);
8
+ /**
9
+ * Sets a tag on the trace span.
10
+ * @param key - The key for the tag.
11
+ * @param value - The value for the tag. This can be a string, number, or boolean.
12
+ * @returns The current instance of the TraceSpanDelegate for method chaining.
13
+ */
8
14
  setTag(key: string, value: string | number | boolean): TraceSpanDelegate;
15
+ /**
16
+ * Adds multiple tags to the trace span.
17
+ * @param tags - An object containing key-value pairs for the tags.
18
+ * @returns The current instance of the TraceSpanDelegate for method chaining.
19
+ */
9
20
  addTags(tags: Record<string, string | number | boolean>): TraceSpanDelegate;
10
21
  }
@@ -13,10 +13,21 @@ export class TraceSpanDelegate {
13
13
  this._name = _name;
14
14
  this._tags = _tags;
15
15
  }
16
+ /**
17
+ * Sets a tag on the trace span.
18
+ * @param key - The key for the tag.
19
+ * @param value - The value for the tag. This can be a string, number, or boolean.
20
+ * @returns The current instance of the TraceSpanDelegate for method chaining.
21
+ */
16
22
  setTag(key, value) {
17
23
  this._tags[key] = value;
18
24
  return this;
19
25
  }
26
+ /**
27
+ * Adds multiple tags to the trace span.
28
+ * @param tags - An object containing key-value pairs for the tags.
29
+ * @returns The current instance of the TraceSpanDelegate for method chaining.
30
+ */
20
31
  addTags(tags) {
21
32
  Object.assign(this._tags, tags);
22
33
  return this;
@@ -1,3 +1,7 @@
1
+ /**
2
+ * Evaluates to `true` if `T` is `any`. `false` otherwise.
3
+ * (c) https://stackoverflow.com/a/68633327/5290447
4
+ */
1
5
  type IsAny<T> = unknown extends T ? [keyof T] extends [never] ? false : true : false;
2
6
  export type PathImpl<T, Key extends keyof T> = Key extends string ? IsAny<T[Key]> extends true ? never : T[Key] extends Record<string, any> ? `${Key}.${PathImpl<T[Key], Exclude<keyof T[Key], keyof any[]>> & string}` | `${Key}.${Exclude<keyof T[Key], keyof any[]> & string}` : never : never;
3
7
  export type PathImpl2<T> = PathImpl<T, keyof T> | keyof T;
@@ -1,4 +1,15 @@
1
1
  import { randomUUID } from "crypto";
2
+ /**
3
+ * What an inbound `x-request-id` must look like to be adopted as the trace id.
4
+ *
5
+ * The header is client-supplied, so it is honoured only when it is a single,
6
+ * short, unambiguous token. Anything else - an array (Node folds repeated
7
+ * headers into one), an oversized value, control characters, exotic symbols -
8
+ * falls back to a random id: the header exists to let a proxy correlate its
9
+ * own logs with a trace, not to let an arbitrary caller choose what gets
10
+ * written into the telemetry store, collide with an existing trace, or inflate
11
+ * a row with an unbounded value.
12
+ */
2
13
  const REQUEST_ID_PATTERN = /^[A-Za-z0-9._:-]{1,128}$/;
3
14
  export function defaultTraceIdGenerator(req) {
4
15
  if (typeof req === "object" && req !== null && "headers" in req) {
@@ -1,3 +1,17 @@
1
+ /**
2
+ * Turns a line of stdout into a structured log entry.
3
+ *
4
+ * Two shapes arrive here and neither can be assumed: a service running Nest's
5
+ * JSON logger emits one object per line, while the default logger emits
6
+ * formatted text - and plenty of lines are neither, because anything that writes
7
+ * to stdout ends up in this path. Detection is therefore per line rather than
8
+ * per service: a line that parses as a recognisable JSON log is treated as
9
+ * structured, everything else falls back to text parsing, and a line that
10
+ * matches nothing is still forwarded with its full text as the message.
11
+ *
12
+ * Nothing is ever dropped for being unparseable. A log the agent does not
13
+ * understand is still the log the user is looking for.
14
+ */
1
15
  export interface ParsedLogLine {
2
16
  level?: string;
3
17
  context?: string;
@@ -1,6 +1,40 @@
1
+ /**
2
+ * Turns a line of stdout into a structured log entry.
3
+ *
4
+ * Two shapes arrive here and neither can be assumed: a service running Nest's
5
+ * JSON logger emits one object per line, while the default logger emits
6
+ * formatted text - and plenty of lines are neither, because anything that writes
7
+ * to stdout ends up in this path. Detection is therefore per line rather than
8
+ * per service: a line that parses as a recognisable JSON log is treated as
9
+ * structured, everything else falls back to text parsing, and a line that
10
+ * matches nothing is still forwarded with its full text as the message.
11
+ *
12
+ * Nothing is ever dropped for being unparseable. A log the agent does not
13
+ * understand is still the log the user is looking for.
14
+ */
15
+ /**
16
+ * CSI escape sequences - colour codes and cursor moves. Narrower than a
17
+ * general-purpose ANSI stripper on purpose: this only has to undo what console
18
+ * loggers emit, and a tight pattern cannot eat real log content.
19
+ */
20
+ // eslint-disable-next-line no-control-regex
1
21
  const ANSI_PATTERN = /\x1B\[[0-9;]*[A-Za-z]/g;
22
+ /**
23
+ * Nest's default ConsoleLogger line:
24
+ * [Nest] 1234 - 07/29/2026, 10:42:18 AM LOG [AppController] message
25
+ * The context bracket is optional - `logger.log()` without a context omits it.
26
+ */
2
27
  const NEST_TEXT_PATTERN = /^\[Nest\]\s+\d+\s+-\s+.+?\s{2,}(FATAL|ERROR|WARN|LOG|DEBUG|VERBOSE)\s+(?:\[([^\]]+)\]\s*)?([\s\S]*)$/;
28
+ /**
29
+ * Suffix appended by LoggerPatcherService when a trace is in scope. Parsing it
30
+ * back off recovers the trace id even for lines whose async context is gone by
31
+ * the time the forwarder sees them.
32
+ */
3
33
  const TRACE_ID_SUFFIX_PATTERN = /\s*Trace ID:\s*(\S+)\s*$/;
34
+ /**
35
+ * Keys the JSON logger sets that map onto modelled columns; anything else a
36
+ * service attaches is preserved under `attributes`.
37
+ */
4
38
  const STRUCTURED_KEYS = new Set([
5
39
  "level",
6
40
  "message",
@@ -17,6 +51,7 @@ export function parseLogLine(line) {
17
51
  return parseStructured(clean) ?? parseNestText(clean) ?? { message: clean };
18
52
  }
19
53
  function parseStructured(line) {
54
+ // Cheap guard so the common text case never pays for a thrown parse error.
20
55
  if (!line.startsWith("{")) {
21
56
  return null;
22
57
  }
@@ -31,6 +66,8 @@ function parseStructured(line) {
31
66
  return null;
32
67
  }
33
68
  const record = parsed;
69
+ // A JSON line with no message is some other program's output that happens to
70
+ // be JSON - not a log we can model, so let the text path have it.
34
71
  if (typeof record.message !== "string") {
35
72
  return null;
36
73
  }