@nestjs/observe 0.3.25 → 0.3.26

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 (94) hide show
  1. package/README.md +17 -0
  2. package/dist/agent/detached-observe-worker.js +50 -6
  3. package/dist/agent/observe-agent.shared-buffer.d.ts +44 -0
  4. package/dist/agent/observe-agent.shared-buffer.js +196 -19
  5. package/dist/agent/observe-agent.worker.d.ts +22 -2
  6. package/dist/agent/observe-agent.worker.js +43 -7
  7. package/dist/agent/telemetry-wire-contract.js +7 -1
  8. package/dist/cli/agent-notes.js +16 -4
  9. package/dist/cli/link.js +28 -3
  10. package/dist/cli/observe-cli.js +1 -19
  11. package/dist/cli/open-url.d.ts +27 -0
  12. package/dist/cli/open-url.js +63 -0
  13. package/dist/cli/project-files.d.ts +42 -1
  14. package/dist/cli/project-files.js +146 -7
  15. package/dist/cli/project-setup.d.ts +6 -0
  16. package/dist/cli/project-setup.js +14 -1
  17. package/dist/cli/wire-application.js +6 -0
  18. package/dist/custom-metrics/counter.d.ts +13 -2
  19. package/dist/custom-metrics/counter.js +33 -16
  20. package/dist/custom-metrics/finite-value.util.d.ts +14 -0
  21. package/dist/custom-metrics/finite-value.util.js +33 -1
  22. package/dist/custom-metrics/gauge.d.ts +2 -0
  23. package/dist/custom-metrics/gauge.js +41 -17
  24. package/dist/custom-metrics/label-values.util.d.ts +37 -0
  25. package/dist/custom-metrics/label-values.util.js +51 -0
  26. package/dist/custom-metrics/summary.d.ts +23 -0
  27. package/dist/custom-metrics/summary.js +73 -2
  28. package/dist/instrument/create-instance-decorator.instrument.js +158 -96
  29. package/dist/interfaces/observe-options.interface.d.ts +3 -1
  30. package/dist/objectives/objectives.registry.js +12 -0
  31. package/dist/observe.module.js +119 -3
  32. package/dist/otlp/otlp-encoders.js +22 -5
  33. package/dist/otlp/otlp-span.mapper.js +7 -3
  34. package/dist/otlp/otlp-trace-exporter.service.js +63 -5
  35. package/dist/outgoing/http.integration.d.ts +8 -4
  36. package/dist/outgoing/http.integration.js +13 -6
  37. package/dist/outgoing/llm/llm-fetch.integration.js +62 -1
  38. package/dist/outgoing/llm/llm-providers.d.ts +16 -4
  39. package/dist/outgoing/llm/llm-providers.js +72 -22
  40. package/dist/outgoing/llm/llm-usage.d.ts +11 -6
  41. package/dist/outgoing/llm/llm-usage.js +72 -25
  42. package/dist/outgoing/mssql.integration.js +16 -2
  43. package/dist/outgoing/mysql2.integration.js +17 -1
  44. package/dist/outgoing/outgoing-observe-agent.service.js +15 -3
  45. package/dist/outgoing/outgoing-span.recorder.js +17 -3
  46. package/dist/outgoing/pg.integration.d.ts +3 -2
  47. package/dist/outgoing/pg.integration.js +39 -11
  48. package/dist/outgoing/sql-statement.util.js +106 -14
  49. package/dist/outgoing/undici.integration.d.ts +13 -0
  50. package/dist/outgoing/undici.integration.js +68 -0
  51. package/dist/protocols/bull-observe-agent.service.js +2 -12
  52. package/dist/protocols/deferred-trace-completion.d.ts +9 -1
  53. package/dist/protocols/deferred-trace-completion.js +36 -6
  54. package/dist/protocols/graphql-observe-agent.service.d.ts +36 -5
  55. package/dist/protocols/graphql-observe-agent.service.js +166 -5
  56. package/dist/protocols/graphql-operation-parser.js +72 -18
  57. package/dist/protocols/http-observe-agent.service.d.ts +43 -9
  58. package/dist/protocols/http-observe-agent.service.js +177 -59
  59. package/dist/protocols/job-trace-runner.d.ts +35 -3
  60. package/dist/protocols/job-trace-runner.js +126 -29
  61. package/dist/protocols/queue-observe-agent.service.js +44 -20
  62. package/dist/protocols/rpc-observe-agent.service.d.ts +50 -8
  63. package/dist/protocols/rpc-observe-agent.service.js +187 -47
  64. package/dist/protocols/ws-observe-agent.service.d.ts +55 -5
  65. package/dist/protocols/ws-observe-agent.service.js +226 -20
  66. package/dist/services/index.d.ts +1 -1
  67. package/dist/services/index.js +1 -1
  68. package/dist/services/logger-patcher.service.js +3 -4
  69. package/dist/services/operation-trace.registry.d.ts +45 -1
  70. package/dist/services/operation-trace.registry.js +418 -35
  71. package/dist/services/stdout-forwarder.service.d.ts +69 -0
  72. package/dist/services/stdout-forwarder.service.js +288 -51
  73. package/dist/services/tracer.service.d.ts +23 -0
  74. package/dist/services/tracer.service.js +91 -5
  75. package/dist/utils/capture-request.util.d.ts +3 -1
  76. package/dist/utils/capture-request.util.js +100 -12
  77. package/dist/utils/fit-to-length.util.js +33 -10
  78. package/dist/utils/log-line.parser.d.ts +14 -0
  79. package/dist/utils/log-line.parser.js +7 -3
  80. package/dist/utils/log-redactor.d.ts +14 -0
  81. package/dist/utils/log-redactor.js +512 -61
  82. package/dist/utils/operation-state.util.d.ts +39 -0
  83. package/dist/utils/operation-state.util.js +50 -0
  84. package/dist/utils/redact-url-query.d.ts +26 -4
  85. package/dist/utils/redact-url-query.js +184 -32
  86. package/dist/utils/sensitive-keys.d.ts +4 -1
  87. package/dist/utils/sensitive-keys.js +48 -10
  88. package/dist/utils/shared-hook-slot.util.d.ts +48 -0
  89. package/dist/utils/shared-hook-slot.util.js +103 -0
  90. package/dist/utils/source-context.util.d.ts +8 -0
  91. package/dist/utils/source-context.util.js +88 -24
  92. package/dist/utils/source-map-resolver.util.js +8 -2
  93. package/dist/utils/trace-context.util.js +21 -6
  94. package/package.json +2 -2
@@ -19,12 +19,24 @@ import { Counter } from "../custom-metrics/counter.js";
19
19
  import { TraceSpanDelegate } from "../trace-span.delegate.js";
20
20
  import { CALLER_METADATA_KEY, OBSERVE_OPTIONS, TRACE_REGISTRY_KEY, } from "../observe.constants.js";
21
21
  import { OperationTraceRegistry } from "./operation-trace.registry.js";
22
+ import { liveTraceId } from "../utils/operation-state.util.js";
22
23
  /**
23
24
  * Longest operation id the collector stores, counted by code point as it
24
25
  * counts. A longer one is cut there anyway; cut here, a name built from a
25
26
  * request body cannot grow the batch it rides in without bound.
26
27
  */
27
28
  const MAX_OPERATION_ID_LENGTH = 255;
29
+ /**
30
+ * Most metrics reported, counters, gauges and summaries together.
31
+ *
32
+ * A metric is kept for the life of the process and puts an entry of its own
33
+ * in every batch it changes in, and the collector refuses a batch whose
34
+ * `custom` section holds more than 5,000 - every request, error, job and log
35
+ * of the window with it. A name built from what a client sent made one per
36
+ * request. A fixed set of names is far below this; what varies belongs in a
37
+ * label, whose series each metric already bounds.
38
+ */
39
+ const MAX_METRICS = 1_000;
28
40
  let TracerService = TracerService_1 = class TracerService {
29
41
  operationTraceRegistry;
30
42
  als;
@@ -38,6 +50,9 @@ let TracerService = TracerService_1 = class TracerService {
38
50
  summaries = new Map();
39
51
  logger = new Logger(TracerService_1.name);
40
52
  hasReportedUnusableOperationId = false;
53
+ hasReportedMetricLimit = false;
54
+ hasReportedUncapturedError = false;
55
+ hasReportedErrorOutsideContext = false;
41
56
  constructor(operationTraceRegistry, als, observeAgentSharedBuffer, options) {
42
57
  this.operationTraceRegistry = operationTraceRegistry;
43
58
  this.als = als;
@@ -98,11 +113,22 @@ let TracerService = TracerService_1 = class TracerService {
98
113
  /**
99
114
  * Captures an error and associates it with the current trace.
100
115
  * This method should be called within an async context where the AsyncLocalStorage is active.
116
+ *
117
+ * The details of at most 20 errors are recorded per trace; the span an
118
+ * error is captured on after that is marked as failed, and its tags are
119
+ * still recorded.
120
+ *
121
+ * Called outside any async context, it records nothing and says so once.
101
122
  */
102
123
  async captureError(error, tags) {
103
124
  const store = this.als.getStore();
104
125
  if (!store) {
105
- throw new Error('AsyncLocalStorage is not initialized. Ensure that you are using the "captureError" method within an async context.');
126
+ // Reporting an error must not raise one. A handler that reports a
127
+ // failure from a `catch` and answers with a fallback failed over the
128
+ // report instead, and one that did not await it ended the process -
129
+ // wherever the context was lost, by the agent or by the application.
130
+ this.reportErrorOutsideContext();
131
+ return;
106
132
  }
107
133
  const traceId = store.get(TRACE_REGISTRY_KEY) ?? store.get(this.options.traceIdKey);
108
134
  if (typeof traceId !== "string") {
@@ -116,7 +142,41 @@ let TracerService = TracerService_1 = class TracerService {
116
142
  return;
117
143
  }
118
144
  const callerId = store.get(CALLER_METADATA_KEY);
119
- this.operationTraceRegistry.captureError(traceId, callerId, error, tags ?? {}, this.reportedTraceId(store, traceId));
145
+ try {
146
+ this.operationTraceRegistry.captureError(traceId, callerId, error, tags ?? {}, this.reportedTraceId(store, traceId));
147
+ }
148
+ catch (failure) {
149
+ // For the same reason: a handler that reports a failure and answers
150
+ // with a fallback must not answer 500 over the report, nor - when it
151
+ // does not await this call - take the process down with it.
152
+ this.reportUncapturedError(failure);
153
+ }
154
+ }
155
+ /** Said once: a call site outside any context is outside it every time. */
156
+ reportErrorOutsideContext() {
157
+ if (this.hasReportedErrorOutsideContext) {
158
+ return;
159
+ }
160
+ this.hasReportedErrorOutsideContext = true;
161
+ this.logger.warn('captureError was called outside an async context, so the error is not recorded. Ensure that you are using the "captureError" method within an async context. Later calls outside one are not reported.');
162
+ }
163
+ /**
164
+ * A failure to record an error comes from the same call site on every
165
+ * request, so it is reported once rather than once per request.
166
+ */
167
+ reportUncapturedError(failure) {
168
+ if (this.hasReportedUncapturedError) {
169
+ return;
170
+ }
171
+ this.hasReportedUncapturedError = true;
172
+ let reason;
173
+ try {
174
+ reason = failure instanceof Error ? failure.message : String(failure);
175
+ }
176
+ catch {
177
+ reason = "an unprintable error";
178
+ }
179
+ this.logger.warn(`captureError could not record an error, and the operation goes on without it. Later failures are not reported: ${reason}`);
120
180
  }
121
181
  counter(name, attributes) {
122
182
  const existingRef = this.counters.get(name);
@@ -138,6 +198,9 @@ let TracerService = TracerService_1 = class TracerService {
138
198
  return existingRef;
139
199
  }
140
200
  const counter = new Counter(name, attributes?.description, attributes?.initialValue, attributes?.labels);
201
+ if (!this.admitsMetric(name)) {
202
+ return counter;
203
+ }
141
204
  this.registerCounterChangeHandler(counter);
142
205
  this.counters.set(name, counter);
143
206
  return counter;
@@ -165,6 +228,9 @@ let TracerService = TracerService_1 = class TracerService {
165
228
  return existingRef;
166
229
  }
167
230
  const gauge = new Gauge(name, attributes ?? {});
231
+ if (!this.admitsMetric(name)) {
232
+ return gauge;
233
+ }
168
234
  this.registerGaugeChangeHandler(gauge);
169
235
  this.gauges.set(name, gauge);
170
236
  return gauge;
@@ -182,6 +248,9 @@ let TracerService = TracerService_1 = class TracerService {
182
248
  return existingRef;
183
249
  }
184
250
  const summary = new Summary(name, attributes ?? {});
251
+ if (!this.admitsMetric(name)) {
252
+ return summary;
253
+ }
185
254
  this.registerSummaryChangeHandler(summary);
186
255
  this.summaries.set(name, summary);
187
256
  return summary;
@@ -197,9 +266,9 @@ let TracerService = TracerService_1 = class TracerService {
197
266
  * propagate an id that simply isn't there yet.
198
267
  */
199
268
  currentTraceId() {
200
- const store = this.als.getStore();
201
- const traceId = store?.get(this.options.traceIdKey);
202
- return typeof traceId === "string" ? traceId : null;
269
+ // Null once the operation is over, past a grace period: a timer the
270
+ // operation left armed is outside any trace in flight.
271
+ return liveTraceId(this.als.getStore(), this.options.traceIdKey) ?? null;
203
272
  }
204
273
  /**
205
274
  * Sets the operation id reported for the current request trace, in place of
@@ -294,6 +363,23 @@ let TracerService = TracerService_1 = class TracerService {
294
363
  const traceId = store.get(this.options.traceIdKey);
295
364
  return typeof traceId === "string" ? traceId : registryKey;
296
365
  }
366
+ /**
367
+ * Whether a metric not yet registered is, under `MAX_METRICS`. One that is
368
+ * not is still handed to the caller, so the code around it runs as it
369
+ * would, but it is neither reported nor kept: each call gets a new one.
370
+ * Reported once, as it comes from the same call site every time.
371
+ */
372
+ admitsMetric(name) {
373
+ if (this.counters.size + this.gauges.size + this.summaries.size <
374
+ MAX_METRICS) {
375
+ return true;
376
+ }
377
+ if (!this.hasReportedMetricLimit) {
378
+ this.hasReportedMetricLimit = true;
379
+ this.logger.warn(`Metric "${name.slice(0, 100)}" is not reported: at most ${MAX_METRICS} metrics are. Name metrics from a fixed set, and put a value that varies - an id, a client's input - in a label. Later metrics past this limit are not reported either, nor logged.`);
380
+ }
381
+ return false;
382
+ }
297
383
  registerCounterChangeHandler(counter) {
298
384
  counter["_onChange"] = (self) => {
299
385
  this.observeAgentSharedBuffer.upsertCustomMetric(self);
@@ -54,4 +54,6 @@ export declare function shouldCaptureRequest(snapshot: {
54
54
  * and forwarded logs - sensitive keys by name, secrets by pattern - before it
55
55
  * is handed back.
56
56
  */
57
- export declare function captureRequest(req: unknown, options: HttpCaptureOptions | false | undefined, redactor: LogRedactor | null): CapturedRequest | undefined;
57
+ export declare function captureRequest(req: unknown, options: HttpCaptureOptions | false | undefined, redactor: LogRedactor | null,
58
+ /** `http.queryParamsObfuscateRegex`, global. */
59
+ obfuscateUrl?: RegExp): CapturedRequest | undefined;
@@ -41,7 +41,9 @@ export function shouldCaptureRequest(snapshot, options) {
41
41
  * and forwarded logs - sensitive keys by name, secrets by pattern - before it
42
42
  * is handed back.
43
43
  */
44
- export function captureRequest(req, options, redactor) {
44
+ export function captureRequest(req, options, redactor,
45
+ /** `http.queryParamsObfuscateRegex`, global. */
46
+ obfuscateUrl) {
45
47
  if (options === false || typeof req !== "object" || req === null) {
46
48
  return undefined;
47
49
  }
@@ -56,20 +58,30 @@ export function captureRequest(req, options, redactor) {
56
58
  if (typeof value !== "string" || value.length === 0) {
57
59
  continue;
58
60
  }
59
- const bounded = value.slice(0, MAX_HEADER_VALUE_LENGTH);
60
- // A referer is a URL, and its query string is where the tokens live.
61
- headers[key] =
62
- key === "referer" ? redactUrlQuery(bounded, redactor) : bounded;
61
+ // Any header can carry a URL - `referer`, `x-forwarded-uri`,
62
+ // `x-original-url` - and its query string is where the tokens live.
63
+ // Masking is by key, so a value that is no URL comes back untouched.
64
+ headers[key] = redactUrlQuery(value, redactor, obfuscateUrl);
63
65
  }
64
66
  if (Object.keys(headers).length > 0) {
65
- captured.headers = (redactor ? redactor.redactAttributes(headers) : headers);
67
+ // Redacted whole and cut afterwards, as the body is: the rules that
68
+ // recognise a secret by its end - a JWT's last dot, a closing quote, a
69
+ // card's last digits - stop matching once the cut goes through it, and
70
+ // the head of the secret would be sent.
71
+ const redacted = redactor ? redactor.redactAttributes(headers) : headers;
72
+ captured.headers = Object.fromEntries(Object.entries(redacted ?? {}).map(([key, value]) => [
73
+ key,
74
+ typeof value === "string"
75
+ ? value.slice(0, MAX_HEADER_VALUE_LENGTH)
76
+ : value,
77
+ ]));
66
78
  }
67
79
  }
68
80
  if (options?.body && request.body !== undefined && request.body !== null) {
69
81
  const maxBytes = Math.min(typeof options.body === "object" && options.body.maxBytes
70
82
  ? options.body.maxBytes
71
83
  : DEFAULT_CAPTURED_BODY_BYTES, MAX_CAPTURED_BODY_BYTES);
72
- const serialized = serializeBody(request.body, redactor);
84
+ const serialized = serializeBody(request.body, redactor, maxBytes);
73
85
  if (serialized !== undefined) {
74
86
  if (Buffer.byteLength(serialized) > maxBytes) {
75
87
  const bytes = Buffer.from(serialized);
@@ -94,19 +106,28 @@ export function captureRequest(req, options, redactor) {
94
106
  * Redaction runs on the parsed structure, before serialization and before the
95
107
  * cut - key-based rules need the keys, and truncating first could ship the
96
108
  * surviving half of a secret.
109
+ *
110
+ * A body that arrived as a string but is JSON (sent as `text/plain`, say) is
111
+ * parsed first, so it is held to the same key rules as one the framework
112
+ * parsed.
97
113
  */
98
- function serializeBody(body, redactor) {
114
+ function serializeBody(body, redactor, maxBytes) {
99
115
  if (typeof body === "string") {
100
- return redactor ? redactor.redactMessage(body) : body;
116
+ const parsed = parseJsonDocument(body);
117
+ if (parsed === undefined) {
118
+ return redactor ? redactor.redactMessage(body) : body;
119
+ }
120
+ body = parsed;
101
121
  }
102
- if (Buffer.isBuffer(body) || typeof body !== "object") {
122
+ if (Buffer.isBuffer(body) || typeof body !== "object" || body === null) {
103
123
  // A raw buffer is a file or an unparsed stream - nothing readable to show.
104
124
  return undefined;
105
125
  }
106
126
  try {
127
+ const bounded = boundToCap(body, { nodes: maxBytes }, new Set());
107
128
  const redacted = redactor
108
- ? redactor.redactAttributes(body)
109
- : body;
129
+ ? redactor.redactAttributes(bounded)
130
+ : bounded;
110
131
  return JSON.stringify(redacted);
111
132
  }
112
133
  catch {
@@ -114,3 +135,70 @@ function serializeBody(body, redactor) {
114
135
  return undefined;
115
136
  }
116
137
  }
138
+ function parseJsonDocument(body) {
139
+ const first = body.trimStart()[0];
140
+ if (first !== "{" && first !== "[") {
141
+ return undefined;
142
+ }
143
+ try {
144
+ const parsed = JSON.parse(body);
145
+ return typeof parsed === "object" && parsed !== null ? parsed : undefined;
146
+ }
147
+ catch {
148
+ return undefined;
149
+ }
150
+ }
151
+ /** Deeper than the redactor descends, so nothing it would read is cut off. */
152
+ const MAX_BOUNDED_DEPTH = 10;
153
+ /**
154
+ * A copy of the body holding only the nodes that can still show up in the
155
+ * first `maxBytes` of its JSON, in the order JSON writes them. Every value
156
+ * and key takes at least a byte, so past `maxBytes` of them the rest is cut
157
+ * anyway - and the rest can be enormous: multer turns `f[1000000]=x` into an
158
+ * array of a million holes, each written out as `null`, from one short field.
159
+ */
160
+ function boundToCap(value, budget,
161
+ /** The objects above this one, to refuse a cycle as JSON.stringify would. */
162
+ ancestors) {
163
+ budget.nodes -= 1;
164
+ // What JSON.stringify would write for it: a Date its ISO string, and so on.
165
+ const toJSON = value !== null && typeof value === "object"
166
+ ? value.toJSON
167
+ : undefined;
168
+ if (typeof toJSON === "function") {
169
+ value = toJSON.call(value);
170
+ }
171
+ if (value === null || typeof value !== "object") {
172
+ return value;
173
+ }
174
+ if (ancestors.has(value)) {
175
+ throw new TypeError("Converting circular structure to JSON");
176
+ }
177
+ if (ancestors.size >= MAX_BOUNDED_DEPTH) {
178
+ return "[REDACTED]";
179
+ }
180
+ ancestors.add(value);
181
+ try {
182
+ if (Array.isArray(value)) {
183
+ const items = [];
184
+ for (let i = 0; i < value.length && budget.nodes > 0; i++) {
185
+ items.push(boundToCap(value[i], budget, ancestors));
186
+ }
187
+ return items;
188
+ }
189
+ const entries = {};
190
+ for (const key in value) {
191
+ if (budget.nodes <= 0) {
192
+ break;
193
+ }
194
+ if (Object.prototype.hasOwnProperty.call(value, key)) {
195
+ budget.nodes -= 1;
196
+ entries[key] = boundToCap(value[key], budget, ancestors);
197
+ }
198
+ }
199
+ return entries;
200
+ }
201
+ finally {
202
+ ancestors.delete(value);
203
+ }
204
+ }
@@ -8,6 +8,17 @@ const HASH_LENGTH = 8;
8
8
  */
9
9
  const fitted = new Map();
10
10
  const MAX_REMEMBERED = 1_000;
11
+ /**
12
+ * Longest value that is remembered, and most of a value that is hashed.
13
+ *
14
+ * A value is as long as whoever named the thing made it - a span or a metric
15
+ * named after a client's string - and a whole read of it, by the hash or as a
16
+ * key of the cache, cost as much as it was long, on every value; the cache
17
+ * then held a thousand of them whole. Past this, the hash covers the head and
18
+ * the length, so values that share a head stay apart unless they also share
19
+ * a length.
20
+ */
21
+ const MAX_READ_LENGTH = 1024;
11
22
  /**
12
23
  * `value`, at most `maxLength` characters long, for a field the collector
13
24
  * bounds. The collector does not cut a longer value down: it refuses the whole
@@ -21,8 +32,9 @@ export function fitToLength(value, maxLength) {
21
32
  if (value.length <= maxLength) {
22
33
  return value;
23
34
  }
24
- const key = `${maxLength}:${value}`;
25
- const remembered = fitted.get(key);
35
+ const remembers = value.length <= MAX_READ_LENGTH;
36
+ const key = remembers ? `${maxLength}:${value}` : undefined;
37
+ const remembered = key === undefined ? undefined : fitted.get(key);
26
38
  if (remembered !== undefined) {
27
39
  return remembered;
28
40
  }
@@ -31,14 +43,25 @@ export function fitToLength(value, maxLength) {
31
43
  if (last >= 0xd800 && last <= 0xdbff) {
32
44
  head -= 1;
33
45
  }
34
- const hash = createHash("sha256")
35
- .update(value)
36
- .digest("hex")
37
- .slice(0, HASH_LENGTH);
38
- const cut = `${value.slice(0, head)}~${hash}`;
39
- if (fitted.size >= MAX_REMEMBERED) {
40
- fitted.clear();
46
+ const hash = createHash("sha256");
47
+ if (remembers) {
48
+ hash.update(value);
49
+ }
50
+ else {
51
+ hash.update(value.slice(0, MAX_READ_LENGTH)).update(`:${value.length}`);
52
+ }
53
+ // Its own copy: a slice keeps the whole of the value it was cut from alive
54
+ // for as long as the cut is held - by the cache, by the batch.
55
+ const cut = copyOf(`${value.slice(0, head)}~${hash.digest("hex").slice(0, HASH_LENGTH)}`);
56
+ if (key !== undefined) {
57
+ if (fitted.size >= MAX_REMEMBERED) {
58
+ fitted.clear();
59
+ }
60
+ fitted.set(key, cut);
41
61
  }
42
- fitted.set(key, cut);
43
62
  return cut;
44
63
  }
64
+ /** A flat string of its own, sharing nothing with what it was built from. */
65
+ function copyOf(text) {
66
+ return JSON.parse(JSON.stringify(text));
67
+ }
@@ -17,8 +17,22 @@ export interface ParsedLogLine {
17
17
  level?: LogLevel;
18
18
  context?: string;
19
19
  message: string;
20
+ /**
21
+ * On a text line whose context was read off a bracket: the bracket and the
22
+ * message as they were written, in one piece. The bracket is only a guess
23
+ * at a context - a line logged without one reads the same when its message
24
+ * opens with `[` - so whoever redacts the two needs them whole.
25
+ */
26
+ unsplit?: string;
20
27
  traceId?: string;
21
28
  attributes?: Record<string, unknown>;
29
+ /**
30
+ * What the line was read as: a record of a JSON logger, a line carrying
31
+ * Nest's text prefix, or neither. A JSON record is always a whole message;
32
+ * a `plain` line may be the rest of a message whose prefix was on the line
33
+ * above it.
34
+ */
35
+ format: "json" | "nest" | "plain";
22
36
  }
23
37
  export declare function stripAnsi(value: string): string;
24
38
  export declare function parseLogLine(line: string): ParsedLogLine;
@@ -35,7 +35,7 @@ const ANSI_PATTERN = /\x1B\[[0-9;]*[A-Za-z]/g;
35
35
  * The timestamp opens with a non-space, exactly one whitespace character
36
36
  * precedes the level, and nothing after the level can fail.
37
37
  */
38
- const NEST_TEXT_PATTERN = /^\[Nest\]\s+\d+\s+-\s+\S.*?\s(FATAL|ERROR|WARN|LOG|DEBUG|VERBOSE)\s+(?:\[([^\]]+)\]\s*)?([\s\S]*)$/;
38
+ const NEST_TEXT_PATTERN = /^\[Nest\]\s+\d+\s+-\s+\S.*?\s(FATAL|ERROR|WARN|LOG|DEBUG|VERBOSE)\s+(\[([^\]]+)\]\s*)?([\s\S]*)$/;
39
39
  /**
40
40
  * Marker LoggerPatcherService puts before the trace id it appends when a trace
41
41
  * is in scope. Parsing the id back off recovers it even for lines whose async
@@ -80,7 +80,8 @@ export function stripAnsi(value) {
80
80
  }
81
81
  export function parseLogLine(line) {
82
82
  const clean = stripAnsi(line).trimEnd();
83
- return parseStructured(clean) ?? parseNestText(clean) ?? { message: clean };
83
+ return (parseStructured(clean) ??
84
+ parseNestText(clean) ?? { message: clean, format: "plain" });
84
85
  }
85
86
  function parseStructured(line) {
86
87
  // Cheap guard so the common text case never pays for a thrown parse error.
@@ -114,6 +115,7 @@ function parseStructured(line) {
114
115
  traceId: typeof record.traceId === "string" ? record.traceId : undefined,
115
116
  message: record.message,
116
117
  attributes: Object.keys(attributes).length > 0 ? attributes : undefined,
118
+ format: "json",
117
119
  };
118
120
  }
119
121
  function parseNestText(line) {
@@ -121,13 +123,15 @@ function parseNestText(line) {
121
123
  if (!match) {
122
124
  return null;
123
125
  }
124
- const [, level, context, rest] = match;
126
+ const [, level, bracket, context, rest] = match;
125
127
  const { message, traceId } = splitTraceIdSuffix(rest);
126
128
  return {
127
129
  level: toLogLevel(level),
128
130
  context: context || undefined,
129
131
  traceId,
130
132
  message,
133
+ unsplit: bracket === undefined ? undefined : bracket + message,
134
+ format: "nest",
131
135
  };
132
136
  }
133
137
  /**
@@ -12,6 +12,12 @@ export declare class LogRedactor {
12
12
  * reach (a URL's query string) is held to the same list.
13
13
  */
14
14
  isSensitiveKey(key: string): boolean;
15
+ /**
16
+ * Colour codes are taken out first. The forwarder strips them off a raw
17
+ * line, but a JSON logger writes the escape as `\u001b`, so they only come
18
+ * back once the line is decoded - and between a key and its value, or in
19
+ * front of a card number, they stop every rule matching.
20
+ */
15
21
  redactMessage(message: string): string;
16
22
  /**
17
23
  * Redacts lines of source code read for a code frame.
@@ -27,4 +33,12 @@ export declare class LogRedactor {
27
33
  private apply;
28
34
  redactAttributes(attributes: Record<string, unknown> | undefined): Record<string, unknown> | undefined;
29
35
  private redactValue;
36
+ /**
37
+ * A key is a name, but not always: a JSON body parsed as a form is one key
38
+ * holding the whole document. Only a key long enough to hold a secret, or
39
+ * holding a pair, is read - the rest are the ordinary names they look like.
40
+ */
41
+ private redactKey;
42
+ /** A card number written as a JSON number: `{"number": 4111111111111111}`. */
43
+ private isCardNumber;
30
44
  }