@bymax-one/nest-logger 1.4.13 → 1.4.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  import { join } from 'path';
2
2
  import { fileURLToPath } from 'url';
3
3
  import { Injectable, Inject, HttpStatus, Catch, ConfigurableModuleBuilder, Module, HttpException, SetMetadata } from '@nestjs/common';
4
- import { APP_INTERCEPTOR, APP_FILTER } from '@nestjs/core';
4
+ import { HttpAdapterHost, APP_INTERCEPTOR, APP_FILTER } from '@nestjs/core';
5
5
  import { types } from 'util';
6
6
  import { tap, catchError, throwError } from 'rxjs';
7
7
  import { randomUUID } from 'crypto';
@@ -28,7 +28,8 @@ var DEFAULT_HTTP = {
28
28
  shouldCaptureExceptions: true,
29
29
  shouldGenerateRequestId: true,
30
30
  excludePaths: [/^\/health$/, /^\/health\/live$/, /^\/health\/ready$/, /^\/metrics$/],
31
- tenantIdHeader: "x-tenant-id"
31
+ tenantIdHeader: "x-tenant-id",
32
+ tenantIdResolver: void 0
32
33
  };
33
34
  var DEFAULT_OTEL = {
34
35
  shouldAutoInjectTraceContext: true,
@@ -293,7 +294,14 @@ function validateHttp(options) {
293
294
  }
294
295
  });
295
296
  }
296
- checkNonEmptyString("http.tenantIdHeader", http["tenantIdHeader"]);
297
+ const tenantIdHeader = http["tenantIdHeader"];
298
+ if (tenantIdHeader !== void 0 && tenantIdHeader !== false && !isNonEmptyString(tenantIdHeader)) {
299
+ reject("http.tenantIdHeader", "must be a non-empty string or false", tenantIdHeader);
300
+ }
301
+ const tenantIdResolver = http["tenantIdResolver"];
302
+ if (tenantIdResolver !== void 0 && typeof tenantIdResolver !== "function") {
303
+ reject("http.tenantIdResolver", "must be a function", tenantIdResolver);
304
+ }
297
305
  }
298
306
  function validateOtel(options) {
299
307
  const otel = checkGroup("otel", options.otel);
@@ -965,6 +973,15 @@ DefaultStdoutDestination = __decorateClass([
965
973
  // src/server/utils/exposed-client-error.util.ts
966
974
  var MIN_CLIENT_STATUS = 400;
967
975
  var MAX_CLIENT_STATUS = 499;
976
+ var FIXED_MESSAGES = /* @__PURE__ */ new Map([
977
+ ["encoding.unsupported", "unsupported content encoding"],
978
+ ["charset.unsupported", "unsupported charset"]
979
+ ]);
980
+ var FIXED_LOG_MESSAGES = new Map([
981
+ ...FIXED_MESSAGES,
982
+ ["entity.parse.failed", "request body could not be parsed"],
983
+ ["entity.verify.failed", "request body verification failed"]
984
+ ]);
968
985
  function readExposedClientError(value) {
969
986
  try {
970
987
  const candidate = value;
@@ -973,12 +990,66 @@ function readExposedClientError(value) {
973
990
  const isClientStatus = typeof status === "number" && Number.isInteger(status) && status >= MIN_CLIENT_STATUS && status <= MAX_CLIENT_STATUS;
974
991
  if (candidate.expose !== true || !isClientStatus || typeof message !== "string")
975
992
  return void 0;
976
- return { status, message };
993
+ const type = candidate.type;
994
+ const sent = FIXED_MESSAGES.get(type) ?? message;
995
+ const logged = FIXED_LOG_MESSAGES.get(type);
996
+ return logged === void 0 ? { status, message: sent, logMessage: sent } : { status, message: sent, logMessage: logged, bodyParserType: type };
977
997
  } catch {
978
998
  return void 0;
979
999
  }
980
1000
  }
981
1001
 
1002
+ // src/server/utils/http-log-state.util.ts
1003
+ var HTTP_REDIRECT_MIN = 300;
1004
+ var HTTP_CLIENT_ERROR_MIN = 400;
1005
+ var HTTP_SERVER_ERROR_MIN = 500;
1006
+ var UNKNOWN_USER_AGENT = "unknown";
1007
+ var RECORDER_ACTIVE = /* @__PURE__ */ Symbol("bymax-one/nest-logger:recorder");
1008
+ var RECORDED_ERROR = /* @__PURE__ */ Symbol("bymax-one/nest-logger:error");
1009
+ var PARSER_ERROR = /* @__PURE__ */ Symbol("bymax-one/nest-logger:parser-error");
1010
+ var OWN_REQUEST_ID = /* @__PURE__ */ Symbol("bymax-one/nest-logger:request-id");
1011
+ var CORRELATION_OPENED = /* @__PURE__ */ Symbol("bymax-one/nest-logger:correlation");
1012
+ function markRecorderActive(req) {
1013
+ Reflect.set(req, RECORDER_ACTIVE, true);
1014
+ }
1015
+ function isRecorderActive(req) {
1016
+ return Reflect.get(req, RECORDER_ACTIVE) === true;
1017
+ }
1018
+ function markCorrelationOpened(req) {
1019
+ Reflect.set(req, CORRELATION_OPENED, true);
1020
+ }
1021
+ function isCorrelationOpened(req) {
1022
+ return Reflect.get(req, CORRELATION_OPENED) === true;
1023
+ }
1024
+ function markOwnRequestId(req, requestId) {
1025
+ Reflect.set(req, OWN_REQUEST_ID, requestId);
1026
+ }
1027
+ function readOwnRequestId(req) {
1028
+ return Reflect.get(req, OWN_REQUEST_ID);
1029
+ }
1030
+ function recordError(req, error) {
1031
+ Reflect.set(req, RECORDED_ERROR, { error });
1032
+ }
1033
+ function readRecordedError(req) {
1034
+ return Reflect.get(req, RECORDED_ERROR);
1035
+ }
1036
+ function recordParserError(req, error) {
1037
+ Reflect.set(req, PARSER_ERROR, error);
1038
+ }
1039
+ function readRecordedParserError(req) {
1040
+ return Reflect.get(req, PARSER_ERROR);
1041
+ }
1042
+ function toError(thrown) {
1043
+ return isError(thrown) ? thrown : new Error(String(thrown));
1044
+ }
1045
+ function readUserId(req) {
1046
+ return req.user?.sub ?? req.user?.id;
1047
+ }
1048
+ function readUserAgent(req) {
1049
+ const raw = req.headers["user-agent"];
1050
+ return typeof raw === "string" ? raw : UNKNOWN_USER_AGENT;
1051
+ }
1052
+
982
1053
  // src/server/utils/normalize-url.util.ts
983
1054
  var UUID_REGEX = /\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}(?![0-9a-f])/gi;
984
1055
  var ULID_REGEX = /\/[0-9A-HJKMNP-TV-Z]{26}(?![0-9A-HJKMNP-TV-Z])/g;
@@ -992,6 +1063,20 @@ function stripQueryString(url) {
992
1063
  const queryStart = url.indexOf("?");
993
1064
  return queryStart === -1 ? url : url.slice(0, queryStart);
994
1065
  }
1066
+ function withoutRequestQuery(text, ...urls) {
1067
+ let result = text;
1068
+ for (const url of urls) {
1069
+ if (url === void 0) continue;
1070
+ const queryStart = url.indexOf("?");
1071
+ if (queryStart !== -1 && url.length - queryStart > 1) {
1072
+ result = result.split(url.slice(queryStart)).join("");
1073
+ }
1074
+ }
1075
+ return result;
1076
+ }
1077
+ function withoutRequestQueryIfText(value, ...urls) {
1078
+ return typeof value === "string" ? withoutRequestQuery(value, ...urls) : value;
1079
+ }
995
1080
 
996
1081
  // src/server/filters/http-exception.filter.ts
997
1082
  var INTERNAL_ERROR_BODY = {
@@ -1022,7 +1107,13 @@ var HttpExceptionFilter = class {
1022
1107
  const url = stripQueryString(req.url);
1023
1108
  if (exception instanceof HttpException) {
1024
1109
  const status = exception.getStatus();
1025
- const metadata = { method: req.method, url, status };
1110
+ const parserError = readRecordedParserError(req);
1111
+ const metadata = {
1112
+ method: req.method,
1113
+ url,
1114
+ status,
1115
+ bodyParserType: parserError?.bodyParserType
1116
+ };
1026
1117
  if (status >= HttpStatus.INTERNAL_SERVER_ERROR) {
1027
1118
  this.logger.errorStructured(
1028
1119
  RESERVED_LOG_KEYS.HTTP_EXCEPTION_UNHANDLED,
@@ -1033,7 +1124,7 @@ var HttpExceptionFilter = class {
1033
1124
  } else {
1034
1125
  this.logger.warnStructured(
1035
1126
  RESERVED_LOG_KEYS.HTTP_EXCEPTION_HANDLED,
1036
- exception.message,
1127
+ parserError?.logMessage ?? withoutRequestQuery(exception.message, req.originalUrl, req.url),
1037
1128
  userId,
1038
1129
  metadata
1039
1130
  );
@@ -1043,7 +1134,10 @@ var HttpExceptionFilter = class {
1043
1134
  }
1044
1135
  const clientError = readExposedClientError(exception);
1045
1136
  if (clientError !== void 0) {
1046
- this.answerClientError(clientError, res, { method: req.method, url, userId });
1137
+ this.answerClientError(clientError, res, { method: req.method, url, userId }, [
1138
+ req.originalUrl,
1139
+ req.url
1140
+ ]);
1047
1141
  return;
1048
1142
  }
1049
1143
  this.answerUnhandled(exception, res, { method: req.method, url, userId });
@@ -1054,14 +1148,20 @@ var HttpExceptionFilter = class {
1054
1148
  * @param clientError - The status and message the error exposes.
1055
1149
  * @param res - The response to write.
1056
1150
  * @param request - The request facts every entry carries.
1151
+ * @param rawUrls - The request's own URLs, whose query string a logged message must not carry.
1057
1152
  */
1058
- answerClientError(clientError, res, request) {
1153
+ answerClientError(clientError, res, request, rawUrls) {
1059
1154
  const { method, url, userId } = request;
1060
1155
  this.logger.warnStructured(
1061
1156
  RESERVED_LOG_KEYS.HTTP_EXCEPTION_HANDLED,
1062
- clientError.message,
1157
+ withoutRequestQuery(clientError.logMessage, ...rawUrls),
1063
1158
  userId,
1064
- { method, url, status: clientError.status }
1159
+ {
1160
+ method,
1161
+ url,
1162
+ status: clientError.status,
1163
+ bodyParserType: clientError.bodyParserType
1164
+ }
1065
1165
  );
1066
1166
  res.status(clientError.status).json({
1067
1167
  statusCode: clientError.status,
@@ -1092,50 +1192,6 @@ HttpExceptionFilter = __decorateClass([
1092
1192
  __decorateParam(0, Inject(PinoLoggerService))
1093
1193
  ], HttpExceptionFilter);
1094
1194
 
1095
- // src/server/utils/http-log-state.util.ts
1096
- var HTTP_REDIRECT_MIN = 300;
1097
- var HTTP_CLIENT_ERROR_MIN = 400;
1098
- var HTTP_SERVER_ERROR_MIN = 500;
1099
- var UNKNOWN_USER_AGENT = "unknown";
1100
- var RECORDER_ACTIVE = /* @__PURE__ */ Symbol("bymax-one/nest-logger:recorder");
1101
- var RECORDED_ERROR = /* @__PURE__ */ Symbol("bymax-one/nest-logger:error");
1102
- var OWN_REQUEST_ID = /* @__PURE__ */ Symbol("bymax-one/nest-logger:request-id");
1103
- var CORRELATION_OPENED = /* @__PURE__ */ Symbol("bymax-one/nest-logger:correlation");
1104
- function markRecorderActive(req) {
1105
- Reflect.set(req, RECORDER_ACTIVE, true);
1106
- }
1107
- function isRecorderActive(req) {
1108
- return Reflect.get(req, RECORDER_ACTIVE) === true;
1109
- }
1110
- function markCorrelationOpened(req) {
1111
- Reflect.set(req, CORRELATION_OPENED, true);
1112
- }
1113
- function isCorrelationOpened(req) {
1114
- return Reflect.get(req, CORRELATION_OPENED) === true;
1115
- }
1116
- function markOwnRequestId(req, requestId) {
1117
- Reflect.set(req, OWN_REQUEST_ID, requestId);
1118
- }
1119
- function readOwnRequestId(req) {
1120
- return Reflect.get(req, OWN_REQUEST_ID);
1121
- }
1122
- function recordError(req, error) {
1123
- Reflect.set(req, RECORDED_ERROR, { error });
1124
- }
1125
- function readRecordedError(req) {
1126
- return Reflect.get(req, RECORDED_ERROR);
1127
- }
1128
- function toError(thrown) {
1129
- return isError(thrown) ? thrown : new Error(String(thrown));
1130
- }
1131
- function readUserId(req) {
1132
- return req.user?.sub ?? req.user?.id;
1133
- }
1134
- function readUserAgent(req) {
1135
- const raw = req.headers["user-agent"];
1136
- return typeof raw === "string" ? raw : UNKNOWN_USER_AGENT;
1137
- }
1138
-
1139
1195
  // src/server/utils/matches-exclude-path.util.ts
1140
1196
  function matchesExcludePath(patterns, path2) {
1141
1197
  return patterns.some((pattern) => {
@@ -1207,7 +1263,10 @@ var HttpLoggingInterceptor = class {
1207
1263
  this.logSuccess(res.statusCode, method, normalizedUrl, userId, Date.now() - start);
1208
1264
  }),
1209
1265
  catchError((err) => {
1210
- this.logError(err, method, normalizedUrl, userId, Date.now() - start);
1266
+ this.logError(err, method, normalizedUrl, userId, Date.now() - start, [
1267
+ req.originalUrl,
1268
+ url
1269
+ ]);
1211
1270
  return throwError(() => err);
1212
1271
  })
1213
1272
  );
@@ -1271,8 +1330,9 @@ var HttpLoggingInterceptor = class {
1271
1330
  * @param url - The normalized request URL.
1272
1331
  * @param userId - The acting user id, when known.
1273
1332
  * @param duration - The elapsed time in milliseconds.
1333
+ * @param rawUrls - The request's own URLs, whose query string a logged message must not carry.
1274
1334
  */
1275
- logError(err, method, url, userId, duration) {
1335
+ logError(err, method, url, userId, duration, rawUrls) {
1276
1336
  if (err instanceof HttpException) {
1277
1337
  const statusCode = err.getStatus();
1278
1338
  if (statusCode >= HTTP_SERVER_ERROR_MIN) {
@@ -1287,14 +1347,20 @@ var HttpLoggingInterceptor = class {
1287
1347
  RESERVED_LOG_KEYS.HTTP_REQUEST_CLIENT_ERROR,
1288
1348
  `${method} ${url} \u2192 ${statusCode}`,
1289
1349
  userId,
1290
- { method, url, statusCode, duration, errorMessage: cutIfText(err.message) }
1350
+ {
1351
+ method,
1352
+ url,
1353
+ statusCode,
1354
+ duration,
1355
+ errorMessage: cutIfText(withoutRequestQueryIfText(err.message, ...rawUrls))
1356
+ }
1291
1357
  );
1292
1358
  }
1293
1359
  return;
1294
1360
  }
1295
1361
  const clientError = readExposedClientError(err);
1296
1362
  if (clientError !== void 0) {
1297
- this.logClientError(clientError, method, url, userId, duration);
1363
+ this.logClientError(clientError, method, url, userId, duration, rawUrls);
1298
1364
  return;
1299
1365
  }
1300
1366
  this.logger.errorStructured(RESERVED_LOG_KEYS.HTTP_REQUEST_SERVER_ERROR, toError(err), userId, {
@@ -1312,8 +1378,9 @@ var HttpLoggingInterceptor = class {
1312
1378
  * @param url - The normalized request URL.
1313
1379
  * @param userId - The acting user id, when known.
1314
1380
  * @param duration - The elapsed time in milliseconds.
1381
+ * @param rawUrls - The request's own URLs, whose query string a logged message must not carry.
1315
1382
  */
1316
- logClientError(clientError, method, url, userId, duration) {
1383
+ logClientError(clientError, method, url, userId, duration, rawUrls) {
1317
1384
  this.logger.warnStructured(
1318
1385
  RESERVED_LOG_KEYS.HTTP_REQUEST_CLIENT_ERROR,
1319
1386
  `${method} ${url} \u2192 ${clientError.status}`,
@@ -1323,7 +1390,8 @@ var HttpLoggingInterceptor = class {
1323
1390
  url,
1324
1391
  statusCode: clientError.status,
1325
1392
  duration,
1326
- errorMessage: cutIfText(clientError.message)
1393
+ errorMessage: cutIfText(withoutRequestQueryIfText(clientError.logMessage, ...rawUrls)),
1394
+ bodyParserType: clientError.bodyParserType
1327
1395
  }
1328
1396
  );
1329
1397
  }
@@ -1491,6 +1559,9 @@ LogContextService = __decorateClass([
1491
1559
  var REQUEST_ID_HEADER = "x-request-id";
1492
1560
  var MAX_CORRELATION_ID_LENGTH = 256;
1493
1561
  var CORRELATION_ID_CHARSET = /^[A-Za-z0-9._:/+=-]+$/;
1562
+ function settleLate(answer) {
1563
+ Promise.resolve(answer).catch(() => void 0);
1564
+ }
1494
1565
  var INHERITABLE_CONTEXT_KEYS = ["requestId", "tenantId"];
1495
1566
  function isAcceptableHeaderValue(value) {
1496
1567
  return typeof value === "string" && value.length <= MAX_CORRELATION_ID_LENGTH && CORRELATION_ID_CHARSET.test(value);
@@ -1506,6 +1577,7 @@ var RequestIdMiddleware = class {
1506
1577
  constructor(logContext, options) {
1507
1578
  this.logContext = logContext;
1508
1579
  this.tenantIdHeader = options.http.tenantIdHeader;
1580
+ this.tenantIdResolver = options.http.tenantIdResolver;
1509
1581
  this.shouldGenerateRequestId = options.http.shouldGenerateRequestId;
1510
1582
  }
1511
1583
  /**
@@ -1620,18 +1692,36 @@ var RequestIdMiddleware = class {
1620
1692
  return fromHeader ?? (this.shouldGenerateRequestId ? randomUUID() : void 0);
1621
1693
  }
1622
1694
  /**
1623
- * The tenant id carried by the configured header, when it is acceptable.
1695
+ * The tenant id of the request, when it is acceptable.
1624
1696
  *
1625
- * Never minted: a tenant is an assertion about who the request belongs to, and
1626
- * inventing one would be a fabricated claim rather than a correlation aid.
1697
+ * From the host's resolver when it gave one, else from the configured header, else none. Never
1698
+ * minted: a tenant is an assertion about who the request belongs to, and inventing one would be a
1699
+ * fabricated claim rather than a correlation aid.
1627
1700
  *
1628
1701
  * @param req - The incoming request.
1629
1702
  * @returns The tenant id, or `undefined`.
1630
1703
  */
1631
1704
  resolveTenantId(req) {
1705
+ if (this.tenantIdResolver !== void 0)
1706
+ return this.resolvedTenantId(this.tenantIdResolver, req);
1707
+ if (this.tenantIdHeader === false) return void 0;
1632
1708
  const raw = Reflect.get(req.headers, this.tenantIdHeader);
1633
1709
  return isAcceptableHeaderValue(raw) ? raw : void 0;
1634
1710
  }
1711
+ /**
1712
+ * The answer of the host's resolver, when it is acceptable. A resolver that throws gives none: a
1713
+ * log context never costs the request.
1714
+ */
1715
+ resolvedTenantId(resolver, req) {
1716
+ try {
1717
+ const answer = resolver(req);
1718
+ if (isAcceptableHeaderValue(answer)) return answer;
1719
+ settleLate(answer);
1720
+ return void 0;
1721
+ } catch {
1722
+ return void 0;
1723
+ }
1724
+ }
1635
1725
  };
1636
1726
  RequestIdMiddleware = __decorateClass([
1637
1727
  Injectable(),
@@ -1658,6 +1748,16 @@ function applyRequestContext(app) {
1658
1748
  });
1659
1749
  }
1660
1750
 
1751
+ // src/server/middlewares/record-parser-error.middleware.ts
1752
+ function recordParserErrorMiddleware(error, req, _res, next) {
1753
+ try {
1754
+ const exposed = readExposedClientError(error);
1755
+ if (exposed?.bodyParserType !== void 0) recordParserError(req, exposed);
1756
+ } catch {
1757
+ }
1758
+ next(error);
1759
+ }
1760
+
1661
1761
  // src/server/constants/default-redact-paths.constants.ts
1662
1762
  var REDACT_MAX_DEPTH = 4;
1663
1763
  var WILDCARD_PREFIXES = Array.from(
@@ -1935,9 +2035,35 @@ function destinationToStream(destination, health) {
1935
2035
  });
1936
2036
  }
1937
2037
 
2038
+ // src/server/utils/redact-error-clone.util.ts
2039
+ function shadowHook(target) {
2040
+ Reflect.defineProperty(target, "toJSON", { value: void 0, configurable: true });
2041
+ }
2042
+ function withoutEnumerableKeys(clone) {
2043
+ for (const key of Object.keys(clone)) Reflect.deleteProperty(clone, key);
2044
+ }
2045
+ function discardWrite() {
2046
+ }
2047
+ function cloneError(error) {
2048
+ const descriptors = Object.getOwnPropertyDescriptors(error);
2049
+ for (const descriptor of Object.values(descriptors)) {
2050
+ descriptor.configurable = true;
2051
+ if ("value" in descriptor) descriptor.writable = true;
2052
+ else descriptor.set ??= discardWrite;
2053
+ }
2054
+ const clone = Object.create(Object.getPrototypeOf(error), descriptors);
2055
+ const { stack } = error;
2056
+ if (typeof stack === "string") {
2057
+ Reflect.defineProperty(clone, "stack", { value: stack, enumerable: false, writable: true });
2058
+ }
2059
+ withoutEnumerableKeys(clone);
2060
+ shadowHook(clone);
2061
+ return clone;
2062
+ }
2063
+
1938
2064
  // src/server/utils/redact-error-parts.util.ts
1939
2065
  function defineOwn(target, key, value) {
1940
- Reflect.defineProperty(target, key, { value, enumerable: true });
2066
+ Reflect.defineProperty(target, key, { value, enumerable: true, writable: true });
1941
2067
  }
1942
2068
  var linkDepths = /* @__PURE__ */ new WeakMap();
1943
2069
  var ERROR_TEXT_FIELDS = /* @__PURE__ */ new Set(["name", "message", "stack"]);
@@ -2033,28 +2159,23 @@ var REDACT_BUDGET_EXCEEDED = "[REDACTION_BUDGET_EXCEEDED]";
2033
2159
  var REDACT_CIRCULAR = "[Circular]";
2034
2160
  function resolveToJson(value, viaGet = false) {
2035
2161
  let candidate = viaGet ? Reflect.get(value, "toJSON") : void 0;
2162
+ let accessor = false;
2163
+ let proxied = false;
2036
2164
  let current = viaGet ? null : value;
2037
2165
  while (current !== null) {
2166
+ proxied = proxied || types.isProxy(current);
2038
2167
  const descriptor = Object.getOwnPropertyDescriptor(current, "toJSON");
2039
2168
  if (descriptor !== void 0) {
2169
+ accessor = descriptor.get !== void 0;
2040
2170
  candidate = descriptor.get === void 0 ? descriptor.value : descriptor.get.call(value);
2041
2171
  break;
2042
2172
  }
2043
2173
  current = Object.getPrototypeOf(current);
2044
2174
  }
2045
- return { method: typeof candidate === "function" ? candidate : void 0 };
2046
- }
2047
- function cloneError(error) {
2048
- const descriptors = Object.getOwnPropertyDescriptors(error);
2049
- for (const descriptor of Object.values(descriptors)) {
2050
- descriptor.configurable = true;
2051
- }
2052
- const clone = Object.create(Object.getPrototypeOf(error), descriptors);
2053
- const { stack } = error;
2054
- if (typeof stack === "string") {
2055
- Reflect.defineProperty(clone, "stack", { value: stack, enumerable: false });
2056
- }
2057
- return clone;
2175
+ return {
2176
+ method: typeof candidate === "function" ? candidate : void 0,
2177
+ volatile: accessor || proxied
2178
+ };
2058
2179
  }
2059
2180
  function walkArray(value, rules, depth2, ancestors, inSerialized) {
2060
2181
  const length = value.length;
@@ -2068,6 +2189,9 @@ function walkArray(value, rules, depth2, ancestors, inSerialized) {
2068
2189
  }
2069
2190
  return copy;
2070
2191
  }
2192
+ function errorRules(rules) {
2193
+ return rules.insideErrors ?? rules;
2194
+ }
2071
2195
  function walk(value, rules, depth2, ancestors, honorToJson, inSerialized = false) {
2072
2196
  if (value === null) {
2073
2197
  return value;
@@ -2085,7 +2209,7 @@ function walk(value, rules, depth2, ancestors, honorToJson, inSerialized = false
2085
2209
  return REDACT_CIRCULAR;
2086
2210
  }
2087
2211
  if (isError(value)) {
2088
- return walkError(value, rules, depth2, ancestors, honorToJson, inSerialized);
2212
+ return walkError(value, errorRules(rules), depth2, ancestors, honorToJson, inSerialized);
2089
2213
  }
2090
2214
  return walkObject(value, rules, depth2, ancestors, honorToJson, inSerialized);
2091
2215
  }
@@ -2108,22 +2232,22 @@ function walkObject(value, rules, depth2, ancestors, honorToJson, inSerialized)
2108
2232
  if (ArrayBuffer.isView(value)) {
2109
2233
  return withBinaryAsSize(value);
2110
2234
  }
2111
- const method = resolveToJson(value, rules.ownFields.safe).method;
2235
+ const resolved = resolveToJson(value, rules.ownFields.safe);
2112
2236
  ancestors.add(value);
2113
2237
  try {
2114
- return walkForm(value, method, rules, depth2, ancestors, honorToJson, inSerialized);
2238
+ return walkForm(value, resolved, rules, depth2, ancestors, honorToJson, inSerialized);
2115
2239
  } finally {
2116
2240
  ancestors.delete(value);
2117
2241
  }
2118
2242
  }
2119
- function walkForm(value, method, rules, depth2, ancestors, honorToJson, inSerialized) {
2243
+ function walkForm(value, resolved, rules, depth2, ancestors, honorToJson, inSerialized) {
2120
2244
  const plain = rules.ownFields.safe;
2121
- const toJson = honorToJson && !(plain && isError(value)) ? method : void 0;
2245
+ const toJson = honorToJson && !(plain && isError(value)) ? resolved.method : void 0;
2122
2246
  if (toJson !== void 0) {
2123
2247
  return walkToJsonOutput(value, toJson, rules, depth2, ancestors, inSerialized);
2124
2248
  }
2125
2249
  if (typeof value === "function") {
2126
- return plain ? void 0 : value;
2250
+ return plain || resolved.volatile ? void 0 : value;
2127
2251
  }
2128
2252
  if (Array.isArray(value)) {
2129
2253
  return walkArray(value, rules, depth2, ancestors, inSerialized);
@@ -2147,11 +2271,12 @@ function walkProperties(value, rules, depth2, ancestors, honorToJson, inSerializ
2147
2271
  for (const key of keys) {
2148
2272
  const read = Reflect.get(source, key);
2149
2273
  const current = scrubbed ? ownFieldForLog(source, key, read, rules.ownFields) : read;
2150
- if (current === OMIT_OWN_FIELD) {
2151
- Reflect.deleteProperty(copy, key);
2274
+ const hook = honorToJson && key === "toJSON" && typeof current === "function";
2275
+ if (current === OMIT_OWN_FIELD || hook) {
2152
2276
  omitted.add(key);
2153
2277
  continue;
2154
2278
  }
2279
+ Reflect.deleteProperty(copy, key);
2155
2280
  defineOwn(
2156
2281
  copy,
2157
2282
  key,
@@ -2191,7 +2316,7 @@ function errorPartsHost(rules, ancestors, inSerialized) {
2191
2316
  hasToJson: (value) => !rules.ownFields.safe && resolveToJson(value).method !== void 0
2192
2317
  };
2193
2318
  }
2194
- function createNameRedactor(fieldNames, censor, serializedKeys, maxVisits = REDACT_MAX_VISITS, ownFields = ALL_OWN_FIELDS) {
2319
+ function createNameRedactor(fieldNames, censor, serializedKeys, maxVisits = REDACT_MAX_VISITS, ownFields = ALL_OWN_FIELDS, errorOnlyNames) {
2195
2320
  const rules = {
2196
2321
  sensitive: new Set(Array.from(fieldNames, (name) => name.toLowerCase())),
2197
2322
  censor,
@@ -2200,9 +2325,15 @@ function createNameRedactor(fieldNames, censor, serializedKeys, maxVisits = REDA
2200
2325
  maxVisits,
2201
2326
  ownFields
2202
2327
  };
2328
+ const insideNames = errorOnlyNames === void 0 ? void 0 : new Set(Array.from(errorOnlyNames, (name) => name.toLowerCase()));
2203
2329
  return (value, isRecordRoot = false) => {
2204
2330
  try {
2205
- const call = { ...rules, visits: { count: 0 } };
2331
+ const visits = { count: 0 };
2332
+ const call = {
2333
+ ...rules,
2334
+ visits,
2335
+ insideErrors: insideNames === void 0 ? void 0 : { ...rules, sensitive: insideNames, visits, insideErrors: void 0 }
2336
+ };
2206
2337
  return walk(value, call, 0, /* @__PURE__ */ new Set(), !isRecordRoot);
2207
2338
  } catch {
2208
2339
  return {
@@ -2443,6 +2574,9 @@ function resolveNameRedactor(options) {
2443
2574
  function ownFieldPolicyOf(options) {
2444
2575
  return createOwnFieldPolicy(options.errorOwnFields, options.errorOwnFieldNames);
2445
2576
  }
2577
+ function namesInsideErrors(options) {
2578
+ return options.shouldDisableDefaultRedact ? void 0 : REDACT_COMMON_FIELDS;
2579
+ }
2446
2580
  function buildNameRedactor(options, nestedErrorsAsData = false, coversNames = true) {
2447
2581
  const names = coversNames ? [
2448
2582
  ...options.shouldDisableDefaultRedact ? [] : REDACT_COMMON_FIELDS,
@@ -2453,12 +2587,13 @@ function buildNameRedactor(options, nestedErrorsAsData = false, coversNames = tr
2453
2587
  if (!walks && resolveRedactOption(options) === void 0) {
2454
2588
  return PASS_THROUGH;
2455
2589
  }
2456
- return nestedErrorsAsData && walks ? createNameRedactor(
2590
+ return nestedErrorsAsData && (walks || !coversNames) ? createNameRedactor(
2457
2591
  names,
2458
2592
  options.redactCensor,
2459
2593
  ["err", ...Object.keys(options.serializers)],
2460
2594
  void 0,
2461
- ownFields
2595
+ ownFields,
2596
+ coversNames ? void 0 : namesInsideErrors(options)
2462
2597
  ) : createNameRedactor(names, options.redactCensor, void 0, void 0, ownFields);
2463
2598
  }
2464
2599
  function resolveRedactOption(options) {
@@ -3070,6 +3205,26 @@ function augmentLoggerModule(base, providers) {
3070
3205
  };
3071
3206
  }
3072
3207
  var BymaxLoggerModule = class extends BymaxLoggerModuleBase {
3208
+ /**
3209
+ * @param httpAdapterHost - The HTTP adapter, absent in an application with no HTTP server.
3210
+ */
3211
+ constructor(httpAdapterHost) {
3212
+ super();
3213
+ this.httpAdapterHost = httpAdapterHost;
3214
+ }
3215
+ /**
3216
+ * Mount the error layer that keeps the type of a body-parser error for the exception filter.
3217
+ * It runs after the body parser, which Nest registers first, and before Nest's exception
3218
+ * handler, and it passes every error on. Only the Express adapter has such a layer.
3219
+ *
3220
+ * @param _consumer - The middleware consumer, unused: an error layer is not consumer middleware.
3221
+ */
3222
+ configure(_consumer) {
3223
+ const adapter = this.httpAdapterHost.httpAdapter;
3224
+ if (adapter?.getType() === "express") {
3225
+ adapter.getInstance().use(recordParserErrorMiddleware);
3226
+ }
3227
+ }
3073
3228
  /**
3074
3229
  * Synchronous registration.
3075
3230
  *
@@ -3187,7 +3342,8 @@ var BymaxLoggerModule = class extends BymaxLoggerModuleBase {
3187
3342
  }
3188
3343
  };
3189
3344
  BymaxLoggerModule = __decorateClass([
3190
- Module({})
3345
+ Module({}),
3346
+ __decorateParam(0, Inject(HttpAdapterHost))
3191
3347
  ], BymaxLoggerModule);
3192
3348
 
3193
3349
  // src/server/destinations/pretty-dev.destination.ts
@@ -3517,7 +3673,12 @@ var HttpAccessLogMiddleware = class {
3517
3673
  RESERVED_LOG_KEYS.HTTP_REQUEST_CLIENT_ERROR,
3518
3674
  `${method} ${url} \u2192 ${statusCode}`,
3519
3675
  userId,
3520
- recorded === void 0 ? meta : { ...meta, errorMessage: cutIfText(recorded.error.message) }
3676
+ recorded === void 0 ? meta : {
3677
+ ...meta,
3678
+ errorMessage: cutIfText(
3679
+ withoutRequestQueryIfText(recorded.error.message, req.originalUrl, req.url)
3680
+ )
3681
+ }
3521
3682
  );
3522
3683
  return;
3523
3684
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bymax-one/nest-logger",
3
- "version": "1.4.13",
3
+ "version": "1.4.15",
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",
@@ -63,7 +63,8 @@
63
63
  "check:published": "node scripts/check-published-surface.mjs",
64
64
  "check:file-length": "node scripts/check-file-length.mjs",
65
65
  "clean": "rm -rf dist coverage",
66
- "lint": "eslint src scripts test bench '*.config.ts' '*.config.mjs' '*.config.cjs'",
66
+ "check:socket-gate": "node scripts/check-socket-gate.mjs",
67
+ "lint": "eslint src scripts test bench '*.config.ts' '*.config.mjs' '*.config.cjs' && pnpm check:socket-gate",
67
68
  "lint:fix": "eslint src scripts test bench '*.config.ts' '*.config.mjs' '*.config.cjs' --fix",
68
69
  "mutation": "stryker run",
69
70
  "mutation:full": "node -e \"require('node:fs').rmSync('reports/stryker-incremental.json',{force:true,recursive:true})\" && stryker run",