@bymax-one/nest-logger 1.4.8 → 1.4.10

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
@@ -11,6 +11,126 @@ heading here.
11
11
 
12
12
  ## [Unreleased]
13
13
 
14
+ ## [1.4.10] - 2026-11-06
15
+
16
+ ### Security
17
+
18
+ - **A database error is recognised from its SQLSTATE `code` alone.** 1.4.9 also required an own
19
+ `severity` and an own `routine`. The PostgreSQL protocol sends the SQLSTATE `code` and the message
20
+ on every error but `routine` only when the server includes it, and a client library or proxy may
21
+ not expose `severity`, so a database error that arrived without them kept `detail`, `where` and
22
+ `internalQuery`, which can quote the row. An error whose own `code` is a string of five characters
23
+ from `0-9A-Z`, the first not `E`, now loses those three fields; its other fields stay. The first
24
+ character rules out the operating-system codes of the same length (`EPIPE`, `EPERM`), and no class
25
+ of the PostgreSQL error codes starts with `E`. An error with any other `code`, or none, is written
26
+ as before.
27
+
28
+ ### Changed
29
+
30
+ - **One redaction call stops expanding after 200000 containers.** The name redaction walks an object
31
+ once per path that reaches it, so a value in which objects share references (a graph where each
32
+ level holds the next twice) took time and produced output that doubled with each level: a graph 20
33
+ levels deep took 570 ms and wrote 19 MB. A call now counts the containers it visits (an object, an
34
+ array or an error, and also what an object's `toJSON` returns and an error's `cause` and `errors`,
35
+ each of which is walked as a container of its own), and from the 200001st on it writes
36
+ `'[REDACTION_BUDGET_EXCEEDED]'` in place of each container, keeping the primitives beside them, as
37
+ `'[REDACTION_DEPTH_EXCEEDED]'` does for depth. Nothing is passed through unwalked. The added
38
+ `type` and `message` of a nested `Error` also count against the cause-chain budget, as `cause` and
39
+ `errors` do.
40
+ - **A stack is written at most 16384 characters long.** The engine builds the stack header from an
41
+ error's `name` and `message`, and when those are themselves errors it stringifies them, so a
42
+ single `stack` could reach hundreds of megabytes (about 54 MB in one measured line). The stack is
43
+ now cut at 16384 characters, after the dependency frames are dropped and the control characters
44
+ escaped, and ends with `…[truncated]`; a cut never leaves half of a surrogate pair. It applies to
45
+ every stack the logger writes: the root `err`, each `cause` and `errors` link, a nested `Error` in
46
+ the metadata, the semconv `exception.stacktrace`, the `stack` argument of `error(message, stack)`
47
+ (cut, with its frames left as given) and the stack in a destination's shutdown-failure report on
48
+ stderr.
49
+
50
+ #### Apply to a derived backend
51
+
52
+ Nothing to change in code. A stack longer than 16384 characters is cut and ends with `…[truncated]`;
53
+ an ordinary stack is far shorter. A single log call that makes more than 200000 container visits,
54
+ such as an array of 250000 objects in the metadata (an object with a `toJSON` counts twice, once for
55
+ itself and once for what it returns), now has its last containers replaced by the marker; a filter
56
+ or alert that reads the whole array should read the part that is kept, or the array should be
57
+ summarised before it is logged. Ordinary entries are unaffected.
58
+
59
+ ## [1.4.9] - 2026-11-06
60
+
61
+ ### Security
62
+
63
+ - **Error entries no longer carry what a failed driver call was given or quoted.** A driver puts the
64
+ call that failed on its error (a Redis reply error carries `command: { name, args }`, a query
65
+ error `parameters`) and a PostgreSQL error quotes the row in `detail` and the statement in `where`
66
+ and `internalQuery`. The key-name redaction cannot see a value inside such a string, so it reached
67
+ the entry. The `args` and `parameters` own fields of an error are now omitted, a `command` object
68
+ is reduced to its `name`, and an error that PostgreSQL raised loses `detail`, `where` and
69
+ `internalQuery` while its other fields stay. This holds for the root `err`, for every `cause` and
70
+ `errors` link, for an `Error` nested in the metadata, and for a driver error held as a field of
71
+ another error (a `driverError` or a `parent` field, for instance). `args` and `parameters` match
72
+ in any case. A field of those names that you attach yourself to an error is no longer logged
73
+ either; put it under a different name, or in the metadata, where name-based redaction applies.
74
+
75
+ This covers the carriers above, not every driver: a field that carries a query's text or values
76
+ under another name (a SQL string, `bindings`, an HTTP client's request body) is still written as
77
+ the error holds it. Do not put such values on an error you log, or keep them out of its own fields
78
+ before it reaches the logger.
79
+
80
+ ### Changed
81
+
82
+ - **An `Error` nested in the metadata is logged with its content.** `{ inner: new Error('x') }` was
83
+ written as `inner: {}`, because `JSON.stringify` skips an `Error`'s non-enumerable `message` and
84
+ `stack`; the same held inside arrays and inside another `Error`'s own fields, and a nested `cause` or
85
+ `AggregateError.errors` was lost with it. Outside a record-root key that has a serializer, such an
86
+ `Error` is now written as what it was written as before (its own enumerable fields, censored by name,
87
+ or the output of its `toJSON`) with `type`, `message`, `stack`, `cause` and `errors` added. A part is
88
+ added only where the node has no key of that name, so nothing written before is replaced or removed,
89
+ and a part that cannot be read is left out and the node carries `_errorFieldsIncomplete: true`. A
90
+ `cause` or `errors` value that is not an `Error` is written as data and censored by name; it is never
91
+ turned into text. The added chain and `errors` are bounded as the root `err`'s are, each ending in a
92
+ `_truncated` marker; these limits apply to the added parts only.
93
+
94
+ #### Apply to a derived backend
95
+
96
+ Nothing to change in code. What can differ at run time:
97
+
98
+ - A nested `Error` that was written as `{}` is now written with its content, so a filter or alert that
99
+ matched `inner: {}` stops matching, and a parser of nested errors gets new fields. Entries that hold
100
+ one are larger, because the stack is included.
101
+ - A string `cause` is now logged exactly as a `message` is, and the root `err` already did so. Do not
102
+ put secrets in an `Error`'s `message` or `cause`: the redaction works on field names and cannot see
103
+ a secret inside a string.
104
+ - An own enumerable field of an `Error` named `type`, `message`, `stack`, `cause` or `errors` is kept
105
+ as it was written, and the added part of that name is not written.
106
+ - The added `type` is censored when `type` or `name` is a covered name, and the added `stack` when
107
+ `stack`, `name` or `message` is: both carry that text. Without such a covered name they are written.
108
+ - A custom serializer on a record-root key receives the same value it received before, censored as
109
+ before and with any `Error` inside it still an instance. What a serializer returns is written as
110
+ the serializer returned it, so an `Error` in its output is still `{}`: the added parts are for the
111
+ metadata walk only. The one exception is the Security entry above: the arguments and quoted values
112
+ of a failed driver call are omitted from an `Error` there too.
113
+ - This applies where the name redaction runs on the record, which is the default
114
+ (`redactStrategy: 'names'` with at least one name covered). Under `'paths'`, or with no name covered,
115
+ the record is not walked and a nested `Error` is written as before.
116
+
117
+ ### Internal
118
+
119
+ - The server bundle budget (`scripts/check-size.mjs`) is raised to 32 KiB, re-derived from the built
120
+ artifact with the usual headroom; the calibration history there has the measurements. The growth
121
+ is executable code, not comment weight.
122
+ - The mutation inventory now exempts the two specs that judge no mutant, each with its reason
123
+ (`scripts/mutation-inventory.exempt.json`): one spawns a script and imports nothing from `src/`, the
124
+ other scans the text of the sources and the README.
125
+
126
+ ### Tests
127
+
128
+ - The shapes of a nested `Error` are judged against the output recorded
129
+ from 1.4.8: none may throw or fail the record where 1.4.8 did not, show a secret marker 1.4.8 did not,
130
+ or drop a value 1.4.8 emitted.
131
+ - `LOGGER_ERROR_CODES`, `RESERVED_LOG_KEYS` and `RESERVED_LOG_KEYS_NOT_EMITTED` are compared whole
132
+ against written-out lists, so an added, removed or renamed entry fails a spec.
133
+
14
134
  ## [1.4.8] - 2026-11-01
15
135
 
16
136
  ### Fixed
@@ -2338,7 +2458,9 @@ published `dist/` is identical — no runtime behaviour changes for consumers.
2338
2458
  - Professional CI suite: `ci.yml`, `bench.yml`, `codeql.yml`, `scorecard.yml`,
2339
2459
  `release.yml`, Dependabot, and issue templates
2340
2460
 
2341
- [Unreleased]: https://github.com/bymaxone/nest-logger/compare/v1.4.8...HEAD
2461
+ [Unreleased]: https://github.com/bymaxone/nest-logger/compare/v1.4.10...HEAD
2462
+ [1.4.10]: https://github.com/bymaxone/nest-logger/compare/v1.4.9...v1.4.10
2463
+ [1.4.9]: https://github.com/bymaxone/nest-logger/compare/v1.4.8...v1.4.9
2342
2464
  [1.4.8]: https://github.com/bymaxone/nest-logger/compare/v1.4.7...v1.4.8
2343
2465
  [1.4.7]: https://github.com/bymaxone/nest-logger/compare/v1.4.6...v1.4.7
2344
2466
  [1.4.6]: https://github.com/bymaxone/nest-logger/compare/v1.4.5...v1.4.6
package/README.md CHANGED
@@ -725,12 +725,18 @@ field the serializer derives, and they pass through the same name-based redactio
725
725
  any other serializer output.
726
726
 
727
727
  An error's own enumerable properties (`code`, `statusCode`, domain fields) are carried through, as
728
- Pino's standard serializer did.
728
+ Pino's standard serializer did, with one exception: the arguments of a failed driver call are not
729
+ written. The fields `args` and `parameters` are omitted, a `command` object is reduced to its
730
+ `name`, and an error with a SQLSTATE `code` (five characters from `0-9A-Z`, the first not `E`) loses `detail`, `where` and `internalQuery`, which quote the row and
731
+ the statement (its other fields stay), because the redaction
732
+ matches key names and cannot see a value inside a string.
729
733
 
730
734
  When those properties cannot be read (a Proxy whose `ownKeys` throws, or a getter that throws), none of them is copied and the error node carries `_errorFieldsIncomplete: true`, so an entry without its `code` is never mistaken for a complete one.
731
735
 
732
736
  An `Error` that cannot be read at all does not cost the record its `logKey`, `userId` or metadata: the node is replaced by its sanitized form, which keeps `name` and `message` and carries the same marker unless `name` or `message` itself is unreadable, in which case it is `{ type: 'SanitizeFailed' }`. Filter on `err._errorFieldsIncomplete: true` or `SanitizeFailed` to find these entries.
733
737
 
738
+ An `Error` nested in the metadata (under a key, inside an array, or inside another `Error`) is written as its own enumerable fields, censored by name (or as its `toJSON` decides), with `type`, `message`, `stack`, `cause` and `errors` added where the node has no key of that name. The added cause chain and `errors` are bounded as the root `err`'s are, each with a `_truncated` marker. A string `cause` is logged like a `message`: do not put secrets in either. Whatever sits under a record-root key that has a serializer, `err` or a key of `serializers`, reaches that serializer censored by name, with its `Error`s still instances, and what a serializer returns is written as returned, so an `Error` in that output stays `{}` (the arguments and quoted values of a failed driver call are omitted from it, as everywhere).
739
+
734
740
  ### 7. Context propagation with `LogContextService`
735
741
 
736
742
  ```typescript
@@ -1242,6 +1248,8 @@ Every `write()` runs inside a try/catch. A destination that throws or rejects pr
1242
1248
 
1243
1249
  ### What redaction covers, and what it cannot
1244
1250
 
1251
+ The walk is bounded: a container nested more than 100 levels deep is written as `[REDACTION_DEPTH_EXCEEDED]`, and a call that visits more than 200000 containers writes `[REDACTION_BUDGET_EXCEEDED]` in place of each further one. Nothing past either bound is passed through unwalked. A stack is written at most 16384 characters long and ends with `…[truncated]` when it was cut.
1252
+
1245
1253
  Redaction here matches **field names**, not values. Under the default `redactStrategy: 'names'` a secret stored under a covered name is censored at any depth — under the legacy `'paths'` strategy the four-level `fast-redact` ceiling applies instead, and a deeper field is not covered. Either way, the same secret **embedded inside a string** under an uncovered name travels intact. Measured:
1246
1254
 
1247
1255
  ```json
@@ -438,10 +438,27 @@ function toSanitizedError(value, seen, depth2, maxDepth) {
438
438
  return { name: "SanitizeFailed", message: "Failed to sanitize the thrown value" };
439
439
  }
440
440
  }
441
+ var ARGUMENT_FIELDS = /* @__PURE__ */ new Set(["args", "parameters"]);
442
+ var DATABASE_VALUE_FIELDS = /* @__PURE__ */ new Set(["detail", "where", "internalQuery"]);
443
+ var SQLSTATE = /^[0-9A-DF-Z][0-9A-Z]{4}$/;
444
+ var OMIT_OWN_FIELD = /* @__PURE__ */ Symbol("omit-own-field");
445
+ function isDatabaseError(source) {
446
+ const code = Object.getOwnPropertyDescriptor(source, "code")?.value;
447
+ return typeof code === "string" && SQLSTATE.test(code);
448
+ }
449
+ function ownFieldForLog(source, key, value) {
450
+ if (ARGUMENT_FIELDS.has(key.toLowerCase())) return OMIT_OWN_FIELD;
451
+ if (DATABASE_VALUE_FIELDS.has(key) && isDatabaseError(source)) return OMIT_OWN_FIELD;
452
+ if (key !== "command" || typeof value !== "object" || value === null) return value;
453
+ const name = Object.getOwnPropertyDescriptor(value, "name")?.value;
454
+ return typeof name === "string" ? { name } : OMIT_OWN_FIELD;
455
+ }
441
456
  function assignOwnErrorFields(target, source) {
442
457
  try {
443
458
  const own = Array.isArray(source) ? {} : source;
444
- for (const [key, value] of Object.entries(own)) {
459
+ for (const [key, field] of Object.entries(own)) {
460
+ const value = ownFieldForLog(own, key, field);
461
+ if (value === OMIT_OWN_FIELD) continue;
445
462
  if (!Object.hasOwn(target, key) && !DERIVED_ERROR_FIELDS.has(key)) {
446
463
  Object.defineProperty(target, key, { value, enumerable: true });
447
464
  }
@@ -471,10 +488,24 @@ function readAggregatedErrors(value) {
471
488
  const candidate = value.errors;
472
489
  return Array.isArray(candidate) ? candidate : void 0;
473
490
  }
491
+ var MAX_STACK_LENGTH = 16384;
492
+ var STACK_TRUNCATED = "\u2026[truncated]";
493
+ var MAX_STACK_SCAN = 8 * MAX_STACK_LENGTH;
474
494
  function scrubStack(stack) {
475
- return escapeControlCharacters(
476
- stack.split("\n").filter((line) => !line.includes("node_modules")).join("\n")
495
+ const scrubbed = escapeControlCharacters(
496
+ stack.slice(0, MAX_STACK_SCAN).split("\n").filter((line) => !line.includes("node_modules")).join("\n")
477
497
  );
498
+ return cutAtLimit(scrubbed, stack.length > MAX_STACK_SCAN);
499
+ }
500
+ function cutAtLimit(text, alreadyCut) {
501
+ if (!alreadyCut && text.length <= MAX_STACK_LENGTH) return text;
502
+ const head = text.slice(0, MAX_STACK_LENGTH);
503
+ const last = head.charCodeAt(head.length - 1);
504
+ const whole = last >= 55296 && last <= 56319 ? head.slice(0, -1) : head;
505
+ return whole + STACK_TRUNCATED;
506
+ }
507
+ function cutStack(stack) {
508
+ return cutAtLimit(stack, false);
478
509
  }
479
510
  function isObject(value) {
480
511
  return typeof value === "object" && value !== null;
@@ -590,7 +621,7 @@ exports.PinoLoggerService = class PinoLoggerService {
590
621
  const context = typeof optionalParams[1] === "string" ? optionalParams[1] : this.context;
591
622
  const payload = {};
592
623
  assignIfDefined(payload, "context", context);
593
- assignIfDefined(payload, "stack", stack);
624
+ assignIfDefined(payload, "stack", stack === void 0 ? stack : cutStack(stack));
594
625
  assignIfDefined(payload, "err", findErrorParam(optionalParams));
595
626
  this.pino.error(payload, safeLogMessage(message));
596
627
  }
@@ -1456,6 +1487,8 @@ function destinationToStream(destination, health) {
1456
1487
  // src/server/utils/redact-by-name.util.ts
1457
1488
  var REDACT_MAX_TRAVERSAL_DEPTH = 100;
1458
1489
  var REDACT_DEPTH_EXCEEDED = "[REDACTION_DEPTH_EXCEEDED]";
1490
+ var REDACT_MAX_VISITS = 2e5;
1491
+ var REDACT_BUDGET_EXCEEDED = "[REDACTION_BUDGET_EXCEEDED]";
1459
1492
  var REDACT_CIRCULAR = "[Circular]";
1460
1493
  function resolveToJson(value) {
1461
1494
  let getter;
@@ -1491,19 +1524,19 @@ var BUFFER_TO_JSON = Buffer.prototype.toJSON;
1491
1524
  function defineOwn(target, key, value) {
1492
1525
  Reflect.defineProperty(target, key, { value, enumerable: true });
1493
1526
  }
1494
- function walkArray(value, sensitive, censor, depth2, ancestors) {
1527
+ function walkArray(value, rules, depth2, ancestors, inSerialized) {
1495
1528
  const length = value.length;
1496
1529
  const copy = [];
1497
1530
  for (let index = 0; index < length; index++) {
1498
1531
  Reflect.set(
1499
1532
  copy,
1500
1533
  index,
1501
- walk(Reflect.get(value, index), sensitive, censor, depth2 + 1, ancestors)
1534
+ walk(Reflect.get(value, index), rules, depth2 + 1, ancestors, true, inSerialized)
1502
1535
  );
1503
1536
  }
1504
1537
  return copy;
1505
1538
  }
1506
- function walk(value, sensitive, censor, depth2, ancestors, honorToJson = true) {
1539
+ function walk(value, rules, depth2, ancestors, honorToJson = true, inSerialized = false) {
1507
1540
  if (value === null) {
1508
1541
  return value;
1509
1542
  }
@@ -1513,22 +1546,26 @@ function walk(value, sensitive, censor, depth2, ancestors, honorToJson = true) {
1513
1546
  if (depth2 > REDACT_MAX_TRAVERSAL_DEPTH) {
1514
1547
  return REDACT_DEPTH_EXCEEDED;
1515
1548
  }
1549
+ if (++rules.visits.count > rules.maxVisits) {
1550
+ return REDACT_BUDGET_EXCEEDED;
1551
+ }
1516
1552
  if (ancestors.has(value)) {
1517
1553
  return REDACT_CIRCULAR;
1518
1554
  }
1519
1555
  if (value instanceof Error) {
1520
- return walkError(value, sensitive, censor, depth2, ancestors, honorToJson);
1556
+ return walkError(value, rules, depth2, ancestors, honorToJson, inSerialized);
1521
1557
  }
1522
- return walkObject(value, sensitive, censor, depth2, ancestors, honorToJson);
1558
+ return walkObject(value, rules, depth2, ancestors, honorToJson, inSerialized);
1523
1559
  }
1524
- function walkError(error, sensitive, censor, depth2, ancestors, honorToJson) {
1560
+ function walkError(error, rules, depth2, ancestors, honorToJson, inSerialized) {
1525
1561
  try {
1526
- return walkObject(error, sensitive, censor, depth2, ancestors, honorToJson);
1562
+ return walkObject(error, rules, depth2, ancestors, honorToJson, inSerialized);
1527
1563
  } catch {
1528
- return walk(sanitizeError(error), sensitive, censor, depth2, ancestors, honorToJson);
1564
+ rules.visits.count--;
1565
+ return walk(sanitizeError(error), rules, depth2, ancestors, honorToJson, inSerialized);
1529
1566
  }
1530
1567
  }
1531
- function walkObject(value, sensitive, censor, depth2, ancestors, honorToJson) {
1568
+ function walkObject(value, rules, depth2, ancestors, honorToJson, inSerialized) {
1532
1569
  const resolvedToJson = resolveToJson(value);
1533
1570
  if (!resolvedToJson.fromAccessor && resolvedToJson.method === BUFFER_TO_JSON) {
1534
1571
  return value;
@@ -1537,38 +1574,120 @@ function walkObject(value, sensitive, censor, depth2, ancestors, honorToJson) {
1537
1574
  try {
1538
1575
  const toJson = honorToJson ? resolvedToJson.method : void 0;
1539
1576
  if (toJson !== void 0) {
1540
- if (Object.keys(value).some((key) => sensitive.has(key.toLowerCase()))) {
1541
- return censor;
1577
+ if (Object.keys(value).some((key) => rules.sensitive.has(key.toLowerCase()))) {
1578
+ return rules.censor;
1542
1579
  }
1543
- return walk(toJson.call(value), sensitive, censor, depth2 + 1, ancestors);
1580
+ return walk(toJson.call(value), rules, depth2 + 1, ancestors, true, inSerialized);
1544
1581
  }
1545
1582
  if (typeof value === "function") {
1546
1583
  return value;
1547
1584
  }
1548
1585
  if (Array.isArray(value)) {
1549
- return walkArray(value, sensitive, censor, depth2, ancestors);
1586
+ return walkArray(value, rules, depth2, ancestors, inSerialized);
1550
1587
  }
1551
1588
  const source = value;
1552
1589
  const keys = Object.keys(source);
1553
- const copy = value instanceof Error ? cloneError(value) : {};
1590
+ const asData = value instanceof Error && rules.errorsAsData && !inSerialized;
1591
+ const clone = value instanceof Error ? cloneError(value) : void 0;
1592
+ const copy = clone !== void 0 && !asData ? clone : {};
1593
+ const scrubbed = value instanceof Error && !inSerialized;
1554
1594
  for (const key of keys) {
1555
- const current = Reflect.get(source, key);
1595
+ const current = scrubbed ? ownFieldForLog(source, key, Reflect.get(source, key)) : Reflect.get(source, key);
1596
+ if (current === OMIT_OWN_FIELD) {
1597
+ Reflect.deleteProperty(copy, key);
1598
+ continue;
1599
+ }
1556
1600
  defineOwn(
1557
1601
  copy,
1558
1602
  key,
1559
- sensitive.has(key.toLowerCase()) ? censor : walk(current, sensitive, censor, depth2 + 1, ancestors)
1603
+ rules.sensitive.has(key.toLowerCase()) ? rules.censor : walk(
1604
+ current,
1605
+ rules,
1606
+ depth2 + 1,
1607
+ ancestors,
1608
+ true,
1609
+ inSerialized || !honorToJson && rules.serializedKeys.has(key)
1610
+ )
1560
1611
  );
1561
1612
  }
1613
+ if (asData) addErrorParts(copy, value, keys, rules, depth2, ancestors);
1562
1614
  return copy;
1563
1615
  } finally {
1564
1616
  ancestors.delete(value);
1565
1617
  }
1566
1618
  }
1567
- function createNameRedactor(fieldNames, censor) {
1568
- const sensitive = new Set(fieldNames.map((name) => name.toLowerCase()));
1619
+ var linkDepths = /* @__PURE__ */ new WeakMap();
1620
+ var INCOMPLETE_KEY = "_errorFieldsIncomplete";
1621
+ function capErrors(errors) {
1622
+ if (!Array.isArray(errors) || errors.length <= MAX_AGGREGATE_ERRORS) return errors;
1623
+ if (resolveToJson(errors).method !== void 0) return errors;
1624
+ const kept = [];
1625
+ for (let index = 0; index < MAX_AGGREGATE_ERRORS; index++) kept.push(Reflect.get(errors, index));
1626
+ kept.push(createWidthMarker(errors.length - MAX_AGGREGATE_ERRORS));
1627
+ return kept;
1628
+ }
1629
+ function linkTargets(value) {
1630
+ const targets = [];
1631
+ const take = (link) => {
1632
+ if (typeof link === "object" && link !== null) targets.push(link);
1633
+ };
1634
+ if (!Array.isArray(value)) take(value);
1635
+ else for (let index = 0; index < value.length; index++) take(Reflect.get(value, index));
1636
+ return targets;
1637
+ }
1638
+ function walkChainPart(value, level, rules, depth2, ancestors) {
1639
+ const targets = linkTargets(value);
1640
+ if (targets.length > 0 && level + 1 > DEFAULT_MAX_CAUSE_DEPTH) return createDepthMarker();
1641
+ const before = new Map(targets.map((target) => [target, linkDepths.get(target)]));
1642
+ for (const target of targets) linkDepths.set(target, level + 1);
1643
+ try {
1644
+ return walk(value, rules, depth2 + 1, ancestors);
1645
+ } finally {
1646
+ before.forEach((earlier, target) => {
1647
+ if (earlier === void 0) linkDepths.delete(target);
1648
+ else linkDepths.set(target, earlier);
1649
+ });
1650
+ }
1651
+ }
1652
+ function addErrorParts(copy, error, ownKeys, rules, depth2, ancestors) {
1653
+ const taken = new Set(ownKeys);
1654
+ const level = linkDepths.get(error) ?? 0;
1655
+ let incomplete = false;
1656
+ const add = (key, covers, read, write = (value) => walkChainPart(value, level, rules, depth2, ancestors)) => {
1657
+ if (taken.has(key)) return;
1658
+ try {
1659
+ const written = write(read());
1660
+ if (written === void 0) return;
1661
+ const covered = covers.some((name) => rules.sensitive.has(name));
1662
+ defineOwn(copy, key, covered ? rules.censor : written);
1663
+ } catch {
1664
+ incomplete = true;
1665
+ }
1666
+ };
1667
+ add("type", ["type", "name"], () => error.name);
1668
+ add("message", ["message"], () => error.message);
1669
+ add(
1670
+ "stack",
1671
+ ["stack", "name", "message"],
1672
+ () => error.stack,
1673
+ (stack) => typeof stack === "string" ? scrubStack(stack) : void 0
1674
+ );
1675
+ add("cause", ["cause"], () => error.cause);
1676
+ add("errors", ["errors"], () => capErrors(error.errors));
1677
+ if (incomplete && !taken.has(INCOMPLETE_KEY)) defineOwn(copy, INCOMPLETE_KEY, true);
1678
+ }
1679
+ function createNameRedactor(fieldNames, censor, serializedKeys, maxVisits = REDACT_MAX_VISITS) {
1680
+ const rules = {
1681
+ sensitive: new Set(fieldNames.map((name) => name.toLowerCase())),
1682
+ censor,
1683
+ serializedKeys: new Set(serializedKeys),
1684
+ errorsAsData: serializedKeys !== void 0,
1685
+ maxVisits
1686
+ };
1569
1687
  return (value, isRecordRoot = false) => {
1570
1688
  try {
1571
- return walk(value, sensitive, censor, 0, /* @__PURE__ */ new Set(), !isRecordRoot);
1689
+ const call = { ...rules, visits: { count: 0 } };
1690
+ return walk(value, call, 0, /* @__PURE__ */ new Set(), !isRecordRoot);
1572
1691
  } catch {
1573
1692
  return {
1574
1693
  _redactionFailed: true,
@@ -1806,9 +1925,9 @@ function resolveNameRedactor(options) {
1806
1925
  if (options.redactStrategy !== "names") {
1807
1926
  return PASS_THROUGH;
1808
1927
  }
1809
- return buildNameRedactor(options);
1928
+ return buildNameRedactor(options, true);
1810
1929
  }
1811
- function buildNameRedactor(options) {
1930
+ function buildNameRedactor(options, nestedErrorsAsData = false) {
1812
1931
  const names = [
1813
1932
  ...options.shouldDisableDefaultRedact ? [] : REDACT_COMMON_FIELDS,
1814
1933
  ...options.redactPaths.flatMap((path) => leafNameOf(path) ?? [])
@@ -1816,7 +1935,7 @@ function buildNameRedactor(options) {
1816
1935
  if (names.length === 0) {
1817
1936
  return PASS_THROUGH;
1818
1937
  }
1819
- return createNameRedactor(names, options.redactCensor);
1938
+ return nestedErrorsAsData ? createNameRedactor(names, options.redactCensor, ["err", ...Object.keys(options.serializers)]) : createNameRedactor(names, options.redactCensor);
1820
1939
  }
1821
1940
  function resolveRedactOption(options) {
1822
1941
  const paths = options.redactStrategy === "paths" ? compileRedactPaths(options.redactPaths, options.shouldDisableDefaultRedact) : [...new Set(options.redactPaths)];
@@ -2332,7 +2451,7 @@ var DestinationRegistry = class {
2332
2451
  let detail = "UnknownError";
2333
2452
  try {
2334
2453
  const stack = isErrorLike(cause) ? cause.stack : void 0;
2335
- detail = stack === void 0 ? toSingleLineMessage(isErrorLike(cause) ? String(cause.message) : String(cause)) : escapeControlCharacters(String(stack));
2454
+ detail = stack === void 0 ? toSingleLineMessage(isErrorLike(cause) ? String(cause.message) : String(cause)) : escapeControlCharacters(cutStack(String(stack)));
2336
2455
  } catch {
2337
2456
  }
2338
2457
  writeStderrSafely(`[DestinationRegistry] Shutdown failed for "${name}": ${detail}
@@ -435,10 +435,27 @@ function toSanitizedError(value, seen, depth2, maxDepth) {
435
435
  return { name: "SanitizeFailed", message: "Failed to sanitize the thrown value" };
436
436
  }
437
437
  }
438
+ var ARGUMENT_FIELDS = /* @__PURE__ */ new Set(["args", "parameters"]);
439
+ var DATABASE_VALUE_FIELDS = /* @__PURE__ */ new Set(["detail", "where", "internalQuery"]);
440
+ var SQLSTATE = /^[0-9A-DF-Z][0-9A-Z]{4}$/;
441
+ var OMIT_OWN_FIELD = /* @__PURE__ */ Symbol("omit-own-field");
442
+ function isDatabaseError(source) {
443
+ const code = Object.getOwnPropertyDescriptor(source, "code")?.value;
444
+ return typeof code === "string" && SQLSTATE.test(code);
445
+ }
446
+ function ownFieldForLog(source, key, value) {
447
+ if (ARGUMENT_FIELDS.has(key.toLowerCase())) return OMIT_OWN_FIELD;
448
+ if (DATABASE_VALUE_FIELDS.has(key) && isDatabaseError(source)) return OMIT_OWN_FIELD;
449
+ if (key !== "command" || typeof value !== "object" || value === null) return value;
450
+ const name = Object.getOwnPropertyDescriptor(value, "name")?.value;
451
+ return typeof name === "string" ? { name } : OMIT_OWN_FIELD;
452
+ }
438
453
  function assignOwnErrorFields(target, source) {
439
454
  try {
440
455
  const own = Array.isArray(source) ? {} : source;
441
- for (const [key, value] of Object.entries(own)) {
456
+ for (const [key, field] of Object.entries(own)) {
457
+ const value = ownFieldForLog(own, key, field);
458
+ if (value === OMIT_OWN_FIELD) continue;
442
459
  if (!Object.hasOwn(target, key) && !DERIVED_ERROR_FIELDS.has(key)) {
443
460
  Object.defineProperty(target, key, { value, enumerable: true });
444
461
  }
@@ -468,10 +485,24 @@ function readAggregatedErrors(value) {
468
485
  const candidate = value.errors;
469
486
  return Array.isArray(candidate) ? candidate : void 0;
470
487
  }
488
+ var MAX_STACK_LENGTH = 16384;
489
+ var STACK_TRUNCATED = "\u2026[truncated]";
490
+ var MAX_STACK_SCAN = 8 * MAX_STACK_LENGTH;
471
491
  function scrubStack(stack) {
472
- return escapeControlCharacters(
473
- stack.split("\n").filter((line) => !line.includes("node_modules")).join("\n")
492
+ const scrubbed = escapeControlCharacters(
493
+ stack.slice(0, MAX_STACK_SCAN).split("\n").filter((line) => !line.includes("node_modules")).join("\n")
474
494
  );
495
+ return cutAtLimit(scrubbed, stack.length > MAX_STACK_SCAN);
496
+ }
497
+ function cutAtLimit(text, alreadyCut) {
498
+ if (!alreadyCut && text.length <= MAX_STACK_LENGTH) return text;
499
+ const head = text.slice(0, MAX_STACK_LENGTH);
500
+ const last = head.charCodeAt(head.length - 1);
501
+ const whole = last >= 55296 && last <= 56319 ? head.slice(0, -1) : head;
502
+ return whole + STACK_TRUNCATED;
503
+ }
504
+ function cutStack(stack) {
505
+ return cutAtLimit(stack, false);
475
506
  }
476
507
  function isObject(value) {
477
508
  return typeof value === "object" && value !== null;
@@ -587,7 +618,7 @@ var PinoLoggerService = class {
587
618
  const context = typeof optionalParams[1] === "string" ? optionalParams[1] : this.context;
588
619
  const payload = {};
589
620
  assignIfDefined(payload, "context", context);
590
- assignIfDefined(payload, "stack", stack);
621
+ assignIfDefined(payload, "stack", stack === void 0 ? stack : cutStack(stack));
591
622
  assignIfDefined(payload, "err", findErrorParam(optionalParams));
592
623
  this.pino.error(payload, safeLogMessage(message));
593
624
  }
@@ -1453,6 +1484,8 @@ function destinationToStream(destination, health) {
1453
1484
  // src/server/utils/redact-by-name.util.ts
1454
1485
  var REDACT_MAX_TRAVERSAL_DEPTH = 100;
1455
1486
  var REDACT_DEPTH_EXCEEDED = "[REDACTION_DEPTH_EXCEEDED]";
1487
+ var REDACT_MAX_VISITS = 2e5;
1488
+ var REDACT_BUDGET_EXCEEDED = "[REDACTION_BUDGET_EXCEEDED]";
1456
1489
  var REDACT_CIRCULAR = "[Circular]";
1457
1490
  function resolveToJson(value) {
1458
1491
  let getter;
@@ -1488,19 +1521,19 @@ var BUFFER_TO_JSON = Buffer.prototype.toJSON;
1488
1521
  function defineOwn(target, key, value) {
1489
1522
  Reflect.defineProperty(target, key, { value, enumerable: true });
1490
1523
  }
1491
- function walkArray(value, sensitive, censor, depth2, ancestors) {
1524
+ function walkArray(value, rules, depth2, ancestors, inSerialized) {
1492
1525
  const length = value.length;
1493
1526
  const copy = [];
1494
1527
  for (let index = 0; index < length; index++) {
1495
1528
  Reflect.set(
1496
1529
  copy,
1497
1530
  index,
1498
- walk(Reflect.get(value, index), sensitive, censor, depth2 + 1, ancestors)
1531
+ walk(Reflect.get(value, index), rules, depth2 + 1, ancestors, true, inSerialized)
1499
1532
  );
1500
1533
  }
1501
1534
  return copy;
1502
1535
  }
1503
- function walk(value, sensitive, censor, depth2, ancestors, honorToJson = true) {
1536
+ function walk(value, rules, depth2, ancestors, honorToJson = true, inSerialized = false) {
1504
1537
  if (value === null) {
1505
1538
  return value;
1506
1539
  }
@@ -1510,22 +1543,26 @@ function walk(value, sensitive, censor, depth2, ancestors, honorToJson = true) {
1510
1543
  if (depth2 > REDACT_MAX_TRAVERSAL_DEPTH) {
1511
1544
  return REDACT_DEPTH_EXCEEDED;
1512
1545
  }
1546
+ if (++rules.visits.count > rules.maxVisits) {
1547
+ return REDACT_BUDGET_EXCEEDED;
1548
+ }
1513
1549
  if (ancestors.has(value)) {
1514
1550
  return REDACT_CIRCULAR;
1515
1551
  }
1516
1552
  if (value instanceof Error) {
1517
- return walkError(value, sensitive, censor, depth2, ancestors, honorToJson);
1553
+ return walkError(value, rules, depth2, ancestors, honorToJson, inSerialized);
1518
1554
  }
1519
- return walkObject(value, sensitive, censor, depth2, ancestors, honorToJson);
1555
+ return walkObject(value, rules, depth2, ancestors, honorToJson, inSerialized);
1520
1556
  }
1521
- function walkError(error, sensitive, censor, depth2, ancestors, honorToJson) {
1557
+ function walkError(error, rules, depth2, ancestors, honorToJson, inSerialized) {
1522
1558
  try {
1523
- return walkObject(error, sensitive, censor, depth2, ancestors, honorToJson);
1559
+ return walkObject(error, rules, depth2, ancestors, honorToJson, inSerialized);
1524
1560
  } catch {
1525
- return walk(sanitizeError(error), sensitive, censor, depth2, ancestors, honorToJson);
1561
+ rules.visits.count--;
1562
+ return walk(sanitizeError(error), rules, depth2, ancestors, honorToJson, inSerialized);
1526
1563
  }
1527
1564
  }
1528
- function walkObject(value, sensitive, censor, depth2, ancestors, honorToJson) {
1565
+ function walkObject(value, rules, depth2, ancestors, honorToJson, inSerialized) {
1529
1566
  const resolvedToJson = resolveToJson(value);
1530
1567
  if (!resolvedToJson.fromAccessor && resolvedToJson.method === BUFFER_TO_JSON) {
1531
1568
  return value;
@@ -1534,38 +1571,120 @@ function walkObject(value, sensitive, censor, depth2, ancestors, honorToJson) {
1534
1571
  try {
1535
1572
  const toJson = honorToJson ? resolvedToJson.method : void 0;
1536
1573
  if (toJson !== void 0) {
1537
- if (Object.keys(value).some((key) => sensitive.has(key.toLowerCase()))) {
1538
- return censor;
1574
+ if (Object.keys(value).some((key) => rules.sensitive.has(key.toLowerCase()))) {
1575
+ return rules.censor;
1539
1576
  }
1540
- return walk(toJson.call(value), sensitive, censor, depth2 + 1, ancestors);
1577
+ return walk(toJson.call(value), rules, depth2 + 1, ancestors, true, inSerialized);
1541
1578
  }
1542
1579
  if (typeof value === "function") {
1543
1580
  return value;
1544
1581
  }
1545
1582
  if (Array.isArray(value)) {
1546
- return walkArray(value, sensitive, censor, depth2, ancestors);
1583
+ return walkArray(value, rules, depth2, ancestors, inSerialized);
1547
1584
  }
1548
1585
  const source = value;
1549
1586
  const keys = Object.keys(source);
1550
- const copy = value instanceof Error ? cloneError(value) : {};
1587
+ const asData = value instanceof Error && rules.errorsAsData && !inSerialized;
1588
+ const clone = value instanceof Error ? cloneError(value) : void 0;
1589
+ const copy = clone !== void 0 && !asData ? clone : {};
1590
+ const scrubbed = value instanceof Error && !inSerialized;
1551
1591
  for (const key of keys) {
1552
- const current = Reflect.get(source, key);
1592
+ const current = scrubbed ? ownFieldForLog(source, key, Reflect.get(source, key)) : Reflect.get(source, key);
1593
+ if (current === OMIT_OWN_FIELD) {
1594
+ Reflect.deleteProperty(copy, key);
1595
+ continue;
1596
+ }
1553
1597
  defineOwn(
1554
1598
  copy,
1555
1599
  key,
1556
- sensitive.has(key.toLowerCase()) ? censor : walk(current, sensitive, censor, depth2 + 1, ancestors)
1600
+ rules.sensitive.has(key.toLowerCase()) ? rules.censor : walk(
1601
+ current,
1602
+ rules,
1603
+ depth2 + 1,
1604
+ ancestors,
1605
+ true,
1606
+ inSerialized || !honorToJson && rules.serializedKeys.has(key)
1607
+ )
1557
1608
  );
1558
1609
  }
1610
+ if (asData) addErrorParts(copy, value, keys, rules, depth2, ancestors);
1559
1611
  return copy;
1560
1612
  } finally {
1561
1613
  ancestors.delete(value);
1562
1614
  }
1563
1615
  }
1564
- function createNameRedactor(fieldNames, censor) {
1565
- const sensitive = new Set(fieldNames.map((name) => name.toLowerCase()));
1616
+ var linkDepths = /* @__PURE__ */ new WeakMap();
1617
+ var INCOMPLETE_KEY = "_errorFieldsIncomplete";
1618
+ function capErrors(errors) {
1619
+ if (!Array.isArray(errors) || errors.length <= MAX_AGGREGATE_ERRORS) return errors;
1620
+ if (resolveToJson(errors).method !== void 0) return errors;
1621
+ const kept = [];
1622
+ for (let index = 0; index < MAX_AGGREGATE_ERRORS; index++) kept.push(Reflect.get(errors, index));
1623
+ kept.push(createWidthMarker(errors.length - MAX_AGGREGATE_ERRORS));
1624
+ return kept;
1625
+ }
1626
+ function linkTargets(value) {
1627
+ const targets = [];
1628
+ const take = (link) => {
1629
+ if (typeof link === "object" && link !== null) targets.push(link);
1630
+ };
1631
+ if (!Array.isArray(value)) take(value);
1632
+ else for (let index = 0; index < value.length; index++) take(Reflect.get(value, index));
1633
+ return targets;
1634
+ }
1635
+ function walkChainPart(value, level, rules, depth2, ancestors) {
1636
+ const targets = linkTargets(value);
1637
+ if (targets.length > 0 && level + 1 > DEFAULT_MAX_CAUSE_DEPTH) return createDepthMarker();
1638
+ const before = new Map(targets.map((target) => [target, linkDepths.get(target)]));
1639
+ for (const target of targets) linkDepths.set(target, level + 1);
1640
+ try {
1641
+ return walk(value, rules, depth2 + 1, ancestors);
1642
+ } finally {
1643
+ before.forEach((earlier, target) => {
1644
+ if (earlier === void 0) linkDepths.delete(target);
1645
+ else linkDepths.set(target, earlier);
1646
+ });
1647
+ }
1648
+ }
1649
+ function addErrorParts(copy, error, ownKeys, rules, depth2, ancestors) {
1650
+ const taken = new Set(ownKeys);
1651
+ const level = linkDepths.get(error) ?? 0;
1652
+ let incomplete = false;
1653
+ const add = (key, covers, read, write = (value) => walkChainPart(value, level, rules, depth2, ancestors)) => {
1654
+ if (taken.has(key)) return;
1655
+ try {
1656
+ const written = write(read());
1657
+ if (written === void 0) return;
1658
+ const covered = covers.some((name) => rules.sensitive.has(name));
1659
+ defineOwn(copy, key, covered ? rules.censor : written);
1660
+ } catch {
1661
+ incomplete = true;
1662
+ }
1663
+ };
1664
+ add("type", ["type", "name"], () => error.name);
1665
+ add("message", ["message"], () => error.message);
1666
+ add(
1667
+ "stack",
1668
+ ["stack", "name", "message"],
1669
+ () => error.stack,
1670
+ (stack) => typeof stack === "string" ? scrubStack(stack) : void 0
1671
+ );
1672
+ add("cause", ["cause"], () => error.cause);
1673
+ add("errors", ["errors"], () => capErrors(error.errors));
1674
+ if (incomplete && !taken.has(INCOMPLETE_KEY)) defineOwn(copy, INCOMPLETE_KEY, true);
1675
+ }
1676
+ function createNameRedactor(fieldNames, censor, serializedKeys, maxVisits = REDACT_MAX_VISITS) {
1677
+ const rules = {
1678
+ sensitive: new Set(fieldNames.map((name) => name.toLowerCase())),
1679
+ censor,
1680
+ serializedKeys: new Set(serializedKeys),
1681
+ errorsAsData: serializedKeys !== void 0,
1682
+ maxVisits
1683
+ };
1566
1684
  return (value, isRecordRoot = false) => {
1567
1685
  try {
1568
- return walk(value, sensitive, censor, 0, /* @__PURE__ */ new Set(), !isRecordRoot);
1686
+ const call = { ...rules, visits: { count: 0 } };
1687
+ return walk(value, call, 0, /* @__PURE__ */ new Set(), !isRecordRoot);
1569
1688
  } catch {
1570
1689
  return {
1571
1690
  _redactionFailed: true,
@@ -1803,9 +1922,9 @@ function resolveNameRedactor(options) {
1803
1922
  if (options.redactStrategy !== "names") {
1804
1923
  return PASS_THROUGH;
1805
1924
  }
1806
- return buildNameRedactor(options);
1925
+ return buildNameRedactor(options, true);
1807
1926
  }
1808
- function buildNameRedactor(options) {
1927
+ function buildNameRedactor(options, nestedErrorsAsData = false) {
1809
1928
  const names = [
1810
1929
  ...options.shouldDisableDefaultRedact ? [] : REDACT_COMMON_FIELDS,
1811
1930
  ...options.redactPaths.flatMap((path2) => leafNameOf(path2) ?? [])
@@ -1813,7 +1932,7 @@ function buildNameRedactor(options) {
1813
1932
  if (names.length === 0) {
1814
1933
  return PASS_THROUGH;
1815
1934
  }
1816
- return createNameRedactor(names, options.redactCensor);
1935
+ return nestedErrorsAsData ? createNameRedactor(names, options.redactCensor, ["err", ...Object.keys(options.serializers)]) : createNameRedactor(names, options.redactCensor);
1817
1936
  }
1818
1937
  function resolveRedactOption(options) {
1819
1938
  const paths = options.redactStrategy === "paths" ? compileRedactPaths(options.redactPaths, options.shouldDisableDefaultRedact) : [...new Set(options.redactPaths)];
@@ -2329,7 +2448,7 @@ var DestinationRegistry = class {
2329
2448
  let detail = "UnknownError";
2330
2449
  try {
2331
2450
  const stack = isErrorLike(cause) ? cause.stack : void 0;
2332
- detail = stack === void 0 ? toSingleLineMessage(isErrorLike(cause) ? String(cause.message) : String(cause)) : escapeControlCharacters(String(stack));
2451
+ detail = stack === void 0 ? toSingleLineMessage(isErrorLike(cause) ? String(cause.message) : String(cause)) : escapeControlCharacters(cutStack(String(stack)));
2333
2452
  } catch {
2334
2453
  }
2335
2454
  writeStderrSafely(`[DestinationRegistry] Shutdown failed for "${name}": ${detail}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bymax-one/nest-logger",
3
- "version": "1.4.8",
3
+ "version": "1.4.10",
4
4
  "description": "Structured JSON logging for NestJS based on Pino 10, with optional OpenTelemetry correlation.",
5
5
  "author": "Bymax One <support@bymax.one>",
6
6
  "license": "MIT",