@bymax-one/nest-logger 1.4.11 → 1.4.13

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.
@@ -4,11 +4,11 @@ import { Injectable, Inject, HttpStatus, Catch, ConfigurableModuleBuilder, Modul
4
4
  import { APP_INTERCEPTOR, APP_FILTER } from '@nestjs/core';
5
5
  import { types } from 'util';
6
6
  import { tap, catchError, throwError } from 'rxjs';
7
+ import { randomUUID } from 'crypto';
8
+ import { AsyncLocalStorage, AsyncResource } from 'async_hooks';
7
9
  import pino from 'pino';
8
10
  import { createRequire } from 'module';
9
11
  import { Writable } from 'stream';
10
- import { AsyncLocalStorage, AsyncResource } from 'async_hooks';
11
- import { randomUUID } from 'crypto';
12
12
 
13
13
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
14
14
  var __decorateClass = (decorators, target, key, kind) => {
@@ -962,6 +962,23 @@ DefaultStdoutDestination = __decorateClass([
962
962
  Injectable()
963
963
  ], DefaultStdoutDestination);
964
964
 
965
+ // src/server/utils/exposed-client-error.util.ts
966
+ var MIN_CLIENT_STATUS = 400;
967
+ var MAX_CLIENT_STATUS = 499;
968
+ function readExposedClientError(value) {
969
+ try {
970
+ const candidate = value;
971
+ const status = candidate.status ?? candidate.statusCode;
972
+ const message = value.message;
973
+ const isClientStatus = typeof status === "number" && Number.isInteger(status) && status >= MIN_CLIENT_STATUS && status <= MAX_CLIENT_STATUS;
974
+ if (candidate.expose !== true || !isClientStatus || typeof message !== "string")
975
+ return void 0;
976
+ return { status, message };
977
+ } catch {
978
+ return void 0;
979
+ }
980
+ }
981
+
965
982
  // src/server/utils/normalize-url.util.ts
966
983
  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;
967
984
  var ULID_REGEX = /\/[0-9A-HJKMNP-TV-Z]{26}(?![0-9A-HJKMNP-TV-Z])/g;
@@ -1004,9 +1021,9 @@ var HttpExceptionFilter = class {
1004
1021
  const userId = req.user?.sub ?? req.user?.id;
1005
1022
  const url = stripQueryString(req.url);
1006
1023
  if (exception instanceof HttpException) {
1007
- const status2 = exception.getStatus();
1008
- const metadata = { method: req.method, url, status: status2 };
1009
- if (status2 >= HttpStatus.INTERNAL_SERVER_ERROR) {
1024
+ const status = exception.getStatus();
1025
+ const metadata = { method: req.method, url, status };
1026
+ if (status >= HttpStatus.INTERNAL_SERVER_ERROR) {
1010
1027
  this.logger.errorStructured(
1011
1028
  RESERVED_LOG_KEYS.HTTP_EXCEPTION_UNHANDLED,
1012
1029
  sanitizeError(exception),
@@ -1021,19 +1038,51 @@ var HttpExceptionFilter = class {
1021
1038
  metadata
1022
1039
  );
1023
1040
  }
1024
- res.status(status2).json(exception.getResponse());
1041
+ res.status(status).json(exception.getResponse());
1042
+ return;
1043
+ }
1044
+ const clientError = readExposedClientError(exception);
1045
+ if (clientError !== void 0) {
1046
+ this.answerClientError(clientError, res, { method: req.method, url, userId });
1025
1047
  return;
1026
1048
  }
1049
+ this.answerUnhandled(exception, res, { method: req.method, url, userId });
1050
+ }
1051
+ /**
1052
+ * Log an exposed client error as handled and answer it with its own status and message.
1053
+ *
1054
+ * @param clientError - The status and message the error exposes.
1055
+ * @param res - The response to write.
1056
+ * @param request - The request facts every entry carries.
1057
+ */
1058
+ answerClientError(clientError, res, request) {
1059
+ const { method, url, userId } = request;
1060
+ this.logger.warnStructured(
1061
+ RESERVED_LOG_KEYS.HTTP_EXCEPTION_HANDLED,
1062
+ clientError.message,
1063
+ userId,
1064
+ { method, url, status: clientError.status }
1065
+ );
1066
+ res.status(clientError.status).json({
1067
+ statusCode: clientError.status,
1068
+ message: clientError.message
1069
+ });
1070
+ }
1071
+ /**
1072
+ * Log any other non-`HttpException` as unhandled and answer it with the fixed 500 body.
1073
+ *
1074
+ * @param exception - The thrown value.
1075
+ * @param res - The response to write.
1076
+ * @param request - The request facts every entry carries.
1077
+ */
1078
+ answerUnhandled(exception, res, request) {
1079
+ const { method, url, userId } = request;
1027
1080
  const status = HttpStatus.INTERNAL_SERVER_ERROR;
1028
1081
  this.logger.errorStructured(
1029
1082
  RESERVED_LOG_KEYS.HTTP_EXCEPTION_UNHANDLED,
1030
1083
  sanitizeError(exception),
1031
1084
  userId,
1032
- {
1033
- method: req.method,
1034
- url,
1035
- status
1036
- }
1085
+ { method, url, status }
1037
1086
  );
1038
1087
  res.status(status).json(INTERNAL_ERROR_BODY);
1039
1088
  }
@@ -1214,8 +1263,8 @@ var HttpLoggingInterceptor = class {
1214
1263
  }
1215
1264
  /**
1216
1265
  * Log a thrown completion: SERVER_ERROR (error level, with stack) for 5xx,
1217
- * CLIENT_ERROR (warn level) for an `HttpException` below 500. A non-`HttpException`
1218
- * always maps to 500, so it is reported as a server error.
1266
+ * CLIENT_ERROR (warn level) for an `HttpException` below 500 or an exposed `http-errors`
1267
+ * client error. Any other non-`HttpException` maps to 500, so it is reported as a server error.
1219
1268
  *
1220
1269
  * @param err - The thrown value (anything).
1221
1270
  * @param method - The HTTP method.
@@ -1243,6 +1292,11 @@ var HttpLoggingInterceptor = class {
1243
1292
  }
1244
1293
  return;
1245
1294
  }
1295
+ const clientError = readExposedClientError(err);
1296
+ if (clientError !== void 0) {
1297
+ this.logClientError(clientError, method, url, userId, duration);
1298
+ return;
1299
+ }
1246
1300
  this.logger.errorStructured(RESERVED_LOG_KEYS.HTTP_REQUEST_SERVER_ERROR, toError(err), userId, {
1247
1301
  method,
1248
1302
  url,
@@ -1250,6 +1304,29 @@ var HttpLoggingInterceptor = class {
1250
1304
  duration
1251
1305
  });
1252
1306
  }
1307
+ /**
1308
+ * Log an exposed `http-errors` client error as CLIENT_ERROR at warn level.
1309
+ *
1310
+ * @param clientError - The status and message the error exposes.
1311
+ * @param method - The HTTP method.
1312
+ * @param url - The normalized request URL.
1313
+ * @param userId - The acting user id, when known.
1314
+ * @param duration - The elapsed time in milliseconds.
1315
+ */
1316
+ logClientError(clientError, method, url, userId, duration) {
1317
+ this.logger.warnStructured(
1318
+ RESERVED_LOG_KEYS.HTTP_REQUEST_CLIENT_ERROR,
1319
+ `${method} ${url} \u2192 ${clientError.status}`,
1320
+ userId,
1321
+ {
1322
+ method,
1323
+ url,
1324
+ statusCode: clientError.status,
1325
+ duration,
1326
+ errorMessage: cutIfText(clientError.message)
1327
+ }
1328
+ );
1329
+ }
1253
1330
  };
1254
1331
  HttpLoggingInterceptor = __decorateClass([
1255
1332
  Injectable(),
@@ -1283,146 +1360,443 @@ var {
1283
1360
  // disabled" without a dead nullish branch.
1284
1361
  global: extras.isGlobal !== false
1285
1362
  })).build();
1286
-
1287
- // src/server/constants/default-redact-paths.constants.ts
1288
- var REDACT_MAX_DEPTH = 4;
1289
- var WILDCARD_PREFIXES = Array.from(
1290
- { length: REDACT_MAX_DEPTH },
1291
- (_, idx) => "*" + ".*".repeat(idx)
1292
- );
1293
- var depth = (field) => WILDCARD_PREFIXES.map((prefix) => `${prefix}.${field}`);
1294
- var REDACT_COMMON_FIELDS = [
1295
- // Passwords (5)
1296
- "password",
1297
- "passwordHash",
1298
- "passwordConfirm",
1299
- "newPassword",
1300
- "oldPassword",
1301
- // Tokens (6)
1302
- "token",
1303
- "accessToken",
1304
- "refreshToken",
1305
- "idToken",
1306
- "apiKey",
1307
- "apiSecret",
1308
- // MFA (3)
1309
- "mfaSecret",
1310
- "mfaRecoveryCodes",
1311
- "totpSecret",
1312
- // Payment / PCI DSS (5)
1313
- "cardNumber",
1314
- "cardCvv",
1315
- "cvv",
1316
- "cvc",
1317
- "cardExpiry",
1318
- // Personal documents — BR / LGPD (3)
1319
- "cpf",
1320
- "cnpj",
1321
- "rg",
1322
- // Generic secrets (4) — the most common short-form credential field names
1323
- "secret",
1324
- "clientSecret",
1325
- "signingSecret",
1326
- "privateKey",
1327
- // Conservative PII (1) — consumer can disable if logging email is justified
1328
- "email",
1329
- // Credential-bearing HTTP header names (5). These also appear in
1330
- // {@link REDACT_ABSOLUTE_PATHS}, pinned to the `req.headers` / `res.headers`
1331
- // shapes — which covered ONLY those two shapes. A headers bag logged under any
1332
- // other key (`logger.info(k, m, u, { headers: req.headers })`, one of the most
1333
- // common things written while debugging an integration) wrote the bearer token
1334
- // in clear. Listed here as bare names, they are caught wherever they appear.
1335
- // Node lower-cases inbound header names, so the lower-case spelling is the one
1336
- // that can actually reach a log.
1337
- "authorization",
1338
- "cookie",
1339
- "set-cookie",
1340
- "x-api-key",
1341
- "x-auth-token"
1342
- ];
1343
- var REDACT_ABSOLUTE_PATHS = [
1344
- "req.headers.authorization",
1345
- "req.headers.cookie",
1346
- 'req.headers["x-api-key"]',
1347
- 'req.headers["x-auth-token"]',
1348
- 'res.headers["set-cookie"]'
1349
- ];
1350
- var DEFAULT_REDACT_PATHS = [
1351
- ...REDACT_COMMON_FIELDS,
1352
- ...REDACT_COMMON_FIELDS.flatMap((field) => depth(field)),
1353
- ...REDACT_ABSOLUTE_PATHS
1354
- ];
1355
-
1356
- // src/server/utils/report-destination-failure.util.ts
1357
- function reportDestinationFailure(logKey, name, cause, msg) {
1358
- writeStderrSafely(
1359
- JSON.stringify({
1360
- level: "error",
1361
- logKey,
1362
- destination: toSingleLineMessage(name),
1363
- err: describeCause(cause),
1364
- msg: toSingleLineMessage(msg)
1365
- }) + "\n"
1366
- );
1367
- }
1368
- var UNREADABLE_CAUSE = { type: "UnknownError", message: "unreadable value" };
1369
- function describeCause(cause) {
1370
- try {
1371
- return isError(cause) ? {
1372
- type: toBoundedMessage(String(cause.name)),
1373
- message: toBoundedMessage(String(cause.message))
1374
- } : { type: "UnknownError", message: toBoundedMessage(String(cause)) };
1375
- } catch {
1376
- return UNREADABLE_CAUSE;
1377
- }
1378
- }
1379
- function safeDestinationName(destination) {
1380
- try {
1381
- return String(destination.name);
1382
- } catch {
1383
- return "unknown";
1384
- }
1385
- }
1386
- function isLogLevel(value) {
1387
- return LOG_LEVEL_PRIORITY.includes(value);
1388
- }
1389
- var resolvedMinLevels = /* @__PURE__ */ new WeakMap();
1390
- function safeMinLevel(destination) {
1391
- if (resolvedMinLevels.has(destination)) {
1392
- return resolvedMinLevels.get(destination);
1363
+ var FORBIDDEN_CONTEXT_KEYS = PROTOTYPE_POLLUTING_KEYS;
1364
+ var LogContextService = class {
1365
+ constructor() {
1366
+ this.als = new AsyncLocalStorage();
1393
1367
  }
1394
- let resolved;
1395
- try {
1396
- const read = destination.minLevel;
1397
- resolved = isLogLevel(read) ? read : void 0;
1398
- } catch {
1368
+ /**
1369
+ * Run `callback` inside a fresh context scope. Every log emitted
1370
+ * synchronously or asynchronously within the callback inherits `context`.
1371
+ *
1372
+ * **A nested `run()` REPLACES the enclosing context, it does not extend it.**
1373
+ * The scope starts from `context` alone, so a field an outer scope had set —
1374
+ * a `tenantId` resolved at the edge, say — is absent for the whole inner
1375
+ * scope: nothing throws, `get()` simply returns `undefined`, and the field is
1376
+ * missing from every entry the callback emits. Reach for {@link runMerged}
1377
+ * when the inner scope should extend the outer one.
1378
+ *
1379
+ * Replacement is the deliberate default because the opposite leaks: a
1380
+ * background job started inside a request scope would silently inherit the
1381
+ * caller's `userId` and attribute its entries to a user who never triggered
1382
+ * it. A missing field is visibly missing; an inherited one is wrong while
1383
+ * looking right.
1384
+ *
1385
+ * @typeParam T - Return type of the callback.
1386
+ * @param context - Initial context bag for the scope. Becomes the WHOLE scope.
1387
+ * @param callback - Function executed within the scope.
1388
+ * @returns Whatever `callback` returns.
1389
+ * @example
1390
+ * logContext.run({ requestId: 'r_1', tenantId: 't_1' }, async () => {
1391
+ * await userService.create(dto) // logs carry requestId + tenantId
1392
+ * })
1393
+ */
1394
+ run(context, callback) {
1395
+ return this.als.run(this.sanitizeContext(context), callback);
1399
1396
  }
1400
- resolvedMinLevels.set(destination, resolved);
1401
- return resolved;
1402
- }
1403
-
1404
- // src/server/utils/otel-detector.ts
1405
- var brokenInstallWarned = false;
1406
- function isOtelApiMissing(cause) {
1407
- try {
1408
- const { code, message } = cause;
1409
- return code === "MODULE_NOT_FOUND" && /^Cannot find module '@opentelemetry\/api'/.test(String(message));
1410
- } catch {
1411
- return false;
1397
+ /**
1398
+ * Run `callback` inside a scope that EXTENDS the enclosing one: the active
1399
+ * context's fields are carried in, and `context` overrides them key by key.
1400
+ *
1401
+ * The explicit counterpart to {@link run}'s replacement semantics, for the
1402
+ * case where an inner scope is genuinely a refinement of the outer — adding a
1403
+ * `userId` once authentication resolved it, without having to restate the
1404
+ * `requestId` the middleware already set.
1405
+ *
1406
+ * Outside any scope there is nothing to merge and this behaves exactly like
1407
+ * {@link run}. Writes inside the new scope never reach the enclosing one: the
1408
+ * merge produces a fresh object, so the outer context is intact after the
1409
+ * callback returns.
1410
+ *
1411
+ * @typeParam T - Return type of the callback.
1412
+ * @param context - Fields to add or override on top of the active context.
1413
+ * @param callback - Function executed within the merged scope.
1414
+ * @returns Whatever `callback` returns.
1415
+ * @example
1416
+ * logContext.run({ requestId: 'r_1' }, () => {
1417
+ * logContext.runMerged({ userId: 'u_1' }, () => {
1418
+ * logContext.get('requestId') // 'r_1' — carried in from the outer scope
1419
+ * })
1420
+ * })
1421
+ */
1422
+ runMerged(context, callback) {
1423
+ const merged = { ...this.als.getStore(), ...this.sanitizeContext(context) };
1424
+ return this.als.run(merged, callback);
1412
1425
  }
1413
- }
1414
- function loadTraceApiFrom(anchor) {
1415
- let from;
1416
- try {
1417
- from = anchor();
1418
- } catch {
1419
- return { api: void 0 };
1426
+ /**
1427
+ * Read the active context, or `undefined` when called outside any scope.
1428
+ *
1429
+ * @returns The active `LogContext`, or `undefined`.
1430
+ */
1431
+ getStore() {
1432
+ return this.als.getStore();
1420
1433
  }
1421
- try {
1422
- const mod = createRequire(from)("@opentelemetry/api");
1423
- const trace = typeof mod === "object" && mod !== null || typeof mod === "function" ? mod.trace : void 0;
1424
- if (typeof trace?.getActiveSpan !== "function") {
1425
- throw new TypeError("@opentelemetry/api resolved but exports no usable `trace` namespace");
1434
+ /**
1435
+ * Add or override a single field on the active context.
1436
+ *
1437
+ * @param key - Field name to set.
1438
+ * @param value - Field value.
1439
+ * @throws Error When called outside a `run()` scope, or with a prototype-polluting key.
1440
+ */
1441
+ set(key, value) {
1442
+ const store = this.als.getStore();
1443
+ if (!store) {
1444
+ throw new Error("[LogContextService] set() called outside run() scope");
1445
+ }
1446
+ if (FORBIDDEN_CONTEXT_KEYS.has(key)) {
1447
+ throw new Error(`[LogContextService] Refusing to set unsafe context key: ${key}`);
1448
+ }
1449
+ Reflect.set(store, key, value);
1450
+ }
1451
+ /**
1452
+ * Read a single field from the active context.
1453
+ *
1454
+ * @typeParam T - Expected value type (caller-asserted).
1455
+ * @param key - Field name to read.
1456
+ * @returns The value cast to `T`, or `undefined` when unset / out of scope.
1457
+ */
1458
+ get(key) {
1459
+ const store = this.als.getStore();
1460
+ if (!store) {
1461
+ return void 0;
1462
+ }
1463
+ return Reflect.get(store, key);
1464
+ }
1465
+ /**
1466
+ * Strip prototype-polluting keys from a caller-supplied context so an own
1467
+ * `__proto__` / `constructor` / `prototype` key (e.g. from `JSON.parse` of an
1468
+ * untrusted payload) can never reach the store — and, via the trace mixin's
1469
+ * `Object.assign`, the emitted log entry. Mirrors the guard `set()` enforces,
1470
+ * but drops the key rather than throwing: a logging concern must never crash
1471
+ * the request that produced it.
1472
+ *
1473
+ * @param context - The raw context bag passed to `run()`.
1474
+ * @returns A shallow copy with any forbidden keys removed.
1475
+ */
1476
+ sanitizeContext(context) {
1477
+ const safe = {};
1478
+ for (const key of Object.keys(context)) {
1479
+ if (!FORBIDDEN_CONTEXT_KEYS.has(key)) {
1480
+ Reflect.set(safe, key, Reflect.get(context, key));
1481
+ }
1482
+ }
1483
+ return safe;
1484
+ }
1485
+ };
1486
+ LogContextService = __decorateClass([
1487
+ Injectable()
1488
+ ], LogContextService);
1489
+
1490
+ // src/server/middlewares/request-id.middleware.ts
1491
+ var REQUEST_ID_HEADER = "x-request-id";
1492
+ var MAX_CORRELATION_ID_LENGTH = 256;
1493
+ var CORRELATION_ID_CHARSET = /^[A-Za-z0-9._:/+=-]+$/;
1494
+ var INHERITABLE_CONTEXT_KEYS = ["requestId", "tenantId"];
1495
+ function isAcceptableHeaderValue(value) {
1496
+ return typeof value === "string" && value.length <= MAX_CORRELATION_ID_LENGTH && CORRELATION_ID_CHARSET.test(value);
1497
+ }
1498
+ var RequestIdMiddleware = class {
1499
+ /**
1500
+ * @param logContext - The AsyncLocalStorage-backed context service. Injected by
1501
+ * token explicitly: the package is bundled without `emitDecoratorMetadata`,
1502
+ * so implicit class-type injection would not resolve.
1503
+ * @param options - Resolved module options (read for `http.tenantIdHeader` and
1504
+ * `http.shouldGenerateRequestId`).
1505
+ */
1506
+ constructor(logContext, options) {
1507
+ this.logContext = logContext;
1508
+ this.tenantIdHeader = options.http.tenantIdHeader;
1509
+ this.shouldGenerateRequestId = options.http.shouldGenerateRequestId;
1510
+ }
1511
+ /**
1512
+ * Echo or mint the `x-request-id`, expose it on the response, and run the
1513
+ * remainder of the request inside its own log-context scope.
1514
+ *
1515
+ * Idempotent: mounting this middleware twice on the same request mints one id,
1516
+ * not two. The request gets its OWN store, started from the enclosing scope's
1517
+ * correlation fields — see {@link INHERITABLE_CONTEXT_KEYS} — and nothing
1518
+ * else, because no other field can be known to belong to this request.
1519
+ *
1520
+ * An enclosing scope's `requestId` is never adopted and never echoed: adoption
1521
+ * reads a value this middleware recorded on the REQUEST, which a scope opened
1522
+ * elsewhere does not have. What the two generation modes do with one, measured
1523
+ * on two requests sharing a long-lived enclosing scope:
1524
+ *
1525
+ * - `shouldGenerateRequestId: true` (default) — each request mints its own
1526
+ * id, the two requests differ, and the enclosing value reaches neither the
1527
+ * header nor the entries.
1528
+ * - `shouldGenerateRequestId: false` with no inbound header — nothing is
1529
+ * minted, so the request scope inherits the enclosing `requestId` and every
1530
+ * request inside that scope logs under it. No header is exposed. That is
1531
+ * the consumer's own scope being inherited, not correlation being reused,
1532
+ * and it is the configuration that says the gateway owns the id.
1533
+ *
1534
+ * @param req - The incoming request (Express satisfies the contract).
1535
+ * @param res - The outgoing response (Express satisfies the contract).
1536
+ * @param next - The next handler in the chain.
1537
+ */
1538
+ use(req, res, next) {
1539
+ if (isCorrelationOpened(req)) {
1540
+ const ownRequestId = readOwnRequestId(req);
1541
+ if (ownRequestId !== void 0) {
1542
+ this.adoptExistingScope(ownRequestId, req, res);
1543
+ }
1544
+ next();
1545
+ return;
1546
+ }
1547
+ markCorrelationOpened(req);
1548
+ const context = this.inheritableContext();
1549
+ const requestId = this.resolveRequestId(req);
1550
+ if (requestId !== void 0) {
1551
+ res.setHeader(REQUEST_ID_HEADER, requestId);
1552
+ context.requestId = requestId;
1553
+ markOwnRequestId(req, requestId);
1554
+ }
1555
+ if (context.tenantId === void 0) {
1556
+ const tenantId = this.resolveTenantId(req);
1557
+ if (tenantId !== void 0) {
1558
+ context.tenantId = tenantId;
1559
+ }
1560
+ }
1561
+ this.logContext.run(context, () => next());
1562
+ }
1563
+ /**
1564
+ * The enclosing scope's fields that a request scope may start from.
1565
+ *
1566
+ * Plain `run()` would discard everything the caller had set and a plain merge
1567
+ * would carry identity across requests; {@link INHERITABLE_CONTEXT_KEYS} is
1568
+ * the middle a request scope actually needs.
1569
+ *
1570
+ * @returns A fresh bag, never the enclosing store itself, so writes inside the
1571
+ * request never reach the scope that opened it.
1572
+ */
1573
+ inheritableContext() {
1574
+ const store = { ...this.logContext.getStore() };
1575
+ const inherited = {};
1576
+ for (const key of INHERITABLE_CONTEXT_KEYS) {
1577
+ const value = Reflect.get(store, key);
1578
+ if (value !== void 0) {
1579
+ Reflect.set(inherited, key, value);
1580
+ }
1581
+ }
1582
+ return inherited;
1583
+ }
1584
+ /**
1585
+ * Second mount on a request that already carries a correlation id: echo the id
1586
+ * onto the response and fill in a tenant the scope does not have yet, without
1587
+ * opening another scope.
1588
+ *
1589
+ * Nothing is minted and nothing already set is overwritten, so a third mount —
1590
+ * or a thirtieth — changes nothing. The response header is written on every
1591
+ * pass because the enclosing scope may have been opened by consumer code that
1592
+ * never exposed it.
1593
+ *
1594
+ * @param requestId - The id already in scope, which wins.
1595
+ * @param req - The incoming request, read for the tenant header.
1596
+ * @param res - The outgoing response, where the effective id is exposed.
1597
+ */
1598
+ adoptExistingScope(requestId, req, res) {
1599
+ res.setHeader(REQUEST_ID_HEADER, requestId);
1600
+ this.logContext.set("requestId", requestId);
1601
+ if (this.logContext.get("tenantId") === void 0) {
1602
+ const tenantId = this.resolveTenantId(req);
1603
+ if (tenantId !== void 0) {
1604
+ this.logContext.set("tenantId", tenantId);
1605
+ }
1606
+ }
1607
+ }
1608
+ /**
1609
+ * The correlation id for this request: the inbound header when acceptable,
1610
+ * otherwise a fresh UUID — or nothing at all when `shouldGenerateRequestId` is
1611
+ * off and the caller sent none, which leaves correlation to the upstream
1612
+ * gateway.
1613
+ *
1614
+ * @param req - The incoming request.
1615
+ * @returns The id, or `undefined` when none is available and none is minted.
1616
+ */
1617
+ resolveRequestId(req) {
1618
+ const incoming = Reflect.get(req.headers, REQUEST_ID_HEADER);
1619
+ const fromHeader = isAcceptableHeaderValue(incoming) ? incoming : void 0;
1620
+ return fromHeader ?? (this.shouldGenerateRequestId ? randomUUID() : void 0);
1621
+ }
1622
+ /**
1623
+ * The tenant id carried by the configured header, when it is acceptable.
1624
+ *
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.
1627
+ *
1628
+ * @param req - The incoming request.
1629
+ * @returns The tenant id, or `undefined`.
1630
+ */
1631
+ resolveTenantId(req) {
1632
+ const raw = Reflect.get(req.headers, this.tenantIdHeader);
1633
+ return isAcceptableHeaderValue(raw) ? raw : void 0;
1634
+ }
1635
+ };
1636
+ RequestIdMiddleware = __decorateClass([
1637
+ Injectable(),
1638
+ __decorateParam(0, Inject(LogContextService)),
1639
+ __decorateParam(1, Inject(LOGGER_OPTIONS_TOKEN))
1640
+ ], RequestIdMiddleware);
1641
+
1642
+ // src/server/middlewares/apply-request-context.ts
1643
+ function applyRequestContext(app) {
1644
+ let requestId;
1645
+ try {
1646
+ requestId = new RequestIdMiddleware(
1647
+ app.get(LogContextService),
1648
+ app.get(LOGGER_OPTIONS_TOKEN)
1649
+ );
1650
+ } catch (cause) {
1651
+ throw new Error(
1652
+ "[BymaxLoggerModule] useRequestContext(app) called but BymaxLoggerModule was not imported",
1653
+ { cause }
1654
+ );
1655
+ }
1656
+ app.use((req, res, next) => {
1657
+ requestId.use(req, res, next);
1658
+ });
1659
+ }
1660
+
1661
+ // src/server/constants/default-redact-paths.constants.ts
1662
+ var REDACT_MAX_DEPTH = 4;
1663
+ var WILDCARD_PREFIXES = Array.from(
1664
+ { length: REDACT_MAX_DEPTH },
1665
+ (_, idx) => "*" + ".*".repeat(idx)
1666
+ );
1667
+ var depth = (field) => WILDCARD_PREFIXES.map((prefix) => `${prefix}.${field}`);
1668
+ var REDACT_COMMON_FIELDS = [
1669
+ // Passwords (5)
1670
+ "password",
1671
+ "passwordHash",
1672
+ "passwordConfirm",
1673
+ "newPassword",
1674
+ "oldPassword",
1675
+ // Tokens (6)
1676
+ "token",
1677
+ "accessToken",
1678
+ "refreshToken",
1679
+ "idToken",
1680
+ "apiKey",
1681
+ "apiSecret",
1682
+ // MFA (3)
1683
+ "mfaSecret",
1684
+ "mfaRecoveryCodes",
1685
+ "totpSecret",
1686
+ // Payment / PCI DSS (5)
1687
+ "cardNumber",
1688
+ "cardCvv",
1689
+ "cvv",
1690
+ "cvc",
1691
+ "cardExpiry",
1692
+ // Personal documents — BR / LGPD (3)
1693
+ "cpf",
1694
+ "cnpj",
1695
+ "rg",
1696
+ // Generic secrets (4) — the most common short-form credential field names
1697
+ "secret",
1698
+ "clientSecret",
1699
+ "signingSecret",
1700
+ "privateKey",
1701
+ // Conservative PII (1) — consumer can disable if logging email is justified
1702
+ "email",
1703
+ // Credential-bearing HTTP header names (5). These also appear in
1704
+ // {@link REDACT_ABSOLUTE_PATHS}, pinned to the `req.headers` / `res.headers`
1705
+ // shapes — which covered ONLY those two shapes. A headers bag logged under any
1706
+ // other key (`logger.info(k, m, u, { headers: req.headers })`, one of the most
1707
+ // common things written while debugging an integration) wrote the bearer token
1708
+ // in clear. Listed here as bare names, they are caught wherever they appear.
1709
+ // Node lower-cases inbound header names, so the lower-case spelling is the one
1710
+ // that can actually reach a log.
1711
+ "authorization",
1712
+ "cookie",
1713
+ "set-cookie",
1714
+ "x-api-key",
1715
+ "x-auth-token"
1716
+ ];
1717
+ var REDACT_ABSOLUTE_PATHS = [
1718
+ "req.headers.authorization",
1719
+ "req.headers.cookie",
1720
+ 'req.headers["x-api-key"]',
1721
+ 'req.headers["x-auth-token"]',
1722
+ 'res.headers["set-cookie"]'
1723
+ ];
1724
+ var DEFAULT_REDACT_PATHS = [
1725
+ ...REDACT_COMMON_FIELDS,
1726
+ ...REDACT_COMMON_FIELDS.flatMap((field) => depth(field)),
1727
+ ...REDACT_ABSOLUTE_PATHS
1728
+ ];
1729
+
1730
+ // src/server/utils/report-destination-failure.util.ts
1731
+ function reportDestinationFailure(logKey, name, cause, msg) {
1732
+ writeStderrSafely(
1733
+ JSON.stringify({
1734
+ level: "error",
1735
+ logKey,
1736
+ destination: toSingleLineMessage(name),
1737
+ err: describeCause(cause),
1738
+ msg: toSingleLineMessage(msg)
1739
+ }) + "\n"
1740
+ );
1741
+ }
1742
+ var UNREADABLE_CAUSE = { type: "UnknownError", message: "unreadable value" };
1743
+ function describeCause(cause) {
1744
+ try {
1745
+ return isError(cause) ? {
1746
+ type: toBoundedMessage(String(cause.name)),
1747
+ message: toBoundedMessage(String(cause.message))
1748
+ } : { type: "UnknownError", message: toBoundedMessage(String(cause)) };
1749
+ } catch {
1750
+ return UNREADABLE_CAUSE;
1751
+ }
1752
+ }
1753
+ function safeDestinationName(destination) {
1754
+ try {
1755
+ return String(destination.name);
1756
+ } catch {
1757
+ return "unknown";
1758
+ }
1759
+ }
1760
+ function isLogLevel(value) {
1761
+ return LOG_LEVEL_PRIORITY.includes(value);
1762
+ }
1763
+ var resolvedMinLevels = /* @__PURE__ */ new WeakMap();
1764
+ function safeMinLevel(destination) {
1765
+ if (resolvedMinLevels.has(destination)) {
1766
+ return resolvedMinLevels.get(destination);
1767
+ }
1768
+ let resolved;
1769
+ try {
1770
+ const read = destination.minLevel;
1771
+ resolved = isLogLevel(read) ? read : void 0;
1772
+ } catch {
1773
+ }
1774
+ resolvedMinLevels.set(destination, resolved);
1775
+ return resolved;
1776
+ }
1777
+
1778
+ // src/server/utils/otel-detector.ts
1779
+ var brokenInstallWarned = false;
1780
+ function isOtelApiMissing(cause) {
1781
+ try {
1782
+ const { code, message } = cause;
1783
+ return code === "MODULE_NOT_FOUND" && /^Cannot find module '@opentelemetry\/api'/.test(String(message));
1784
+ } catch {
1785
+ return false;
1786
+ }
1787
+ }
1788
+ function loadTraceApiFrom(anchor) {
1789
+ let from;
1790
+ try {
1791
+ from = anchor();
1792
+ } catch {
1793
+ return { api: void 0 };
1794
+ }
1795
+ try {
1796
+ const mod = createRequire(from)("@opentelemetry/api");
1797
+ const trace = typeof mod === "object" && mod !== null || typeof mod === "function" ? mod.trace : void 0;
1798
+ if (typeof trace?.getActiveSpan !== "function") {
1799
+ throw new TypeError("@opentelemetry/api resolved but exports no usable `trace` namespace");
1426
1800
  }
1427
1801
  return { api: trace };
1428
1802
  } catch (cause) {
@@ -1734,69 +2108,76 @@ function walkObject(value, rules, depth2, ancestors, honorToJson, inSerialized)
1734
2108
  if (ArrayBuffer.isView(value)) {
1735
2109
  return withBinaryAsSize(value);
1736
2110
  }
1737
- const plain = rules.ownFields.safe;
1738
- const resolvedToJson = resolveToJson(value, plain);
2111
+ const method = resolveToJson(value, rules.ownFields.safe).method;
1739
2112
  ancestors.add(value);
1740
2113
  try {
1741
- const ownsItsForm = rules.ownFields.safe && isError(value);
1742
- const toJson = honorToJson && !ownsItsForm ? resolvedToJson.method : void 0;
1743
- if (toJson !== void 0) {
1744
- if (Object.keys(value).some((key) => rules.sensitive.has(key.toLowerCase()))) {
1745
- return rules.censor;
1746
- }
1747
- return walk(toJson.call(value), rules, depth2 + 1, ancestors, true, inSerialized);
1748
- }
1749
- if (typeof value === "function") {
1750
- return plain ? void 0 : value;
1751
- }
1752
- if (Array.isArray(value)) {
1753
- return walkArray(value, rules, depth2, ancestors, inSerialized);
1754
- }
1755
- const source = value;
1756
- const keys = Object.keys(source);
1757
- const asData = isError(value) && (plain || rules.errorsAsData && !inSerialized);
1758
- const clone = isError(value) ? cloneError(value) : void 0;
1759
- const copy = clone !== void 0 && !asData ? clone : {};
1760
- const scrubbed = isError(value) && (plain || !inSerialized);
1761
- const omitted = /* @__PURE__ */ new Set();
1762
- for (const key of keys) {
1763
- const read = Reflect.get(source, key);
1764
- const current = scrubbed ? ownFieldForLog(source, key, read, rules.ownFields) : read;
1765
- if (current === OMIT_OWN_FIELD) {
1766
- Reflect.deleteProperty(copy, key);
1767
- omitted.add(key);
1768
- continue;
1769
- }
1770
- defineOwn(
1771
- copy,
1772
- key,
1773
- rules.sensitive.has(key.toLowerCase()) ? rules.censor : walk(
1774
- // An own enumerable `name`, `message` or `stack` of an `Error` is the same text as
1775
- // the part the walk would add, so it is cut the same way.
1776
- scrubbed && ERROR_TEXT_FIELDS.has(key) ? cutIfText(current) : current,
1777
- rules,
1778
- depth2 + 1,
1779
- ancestors,
1780
- true,
1781
- inSerialized || !honorToJson && rules.serializedKeys.has(key)
1782
- )
1783
- );
1784
- }
1785
- if (asData) {
1786
- const written = keys.filter((key) => !omitted.has(key));
1787
- addErrorParts(
1788
- copy,
1789
- value,
1790
- written,
1791
- errorPartsHost(rules, ancestors, inSerialized),
1792
- depth2
1793
- );
1794
- }
1795
- return copy;
2114
+ return walkForm(value, method, rules, depth2, ancestors, honorToJson, inSerialized);
1796
2115
  } finally {
1797
2116
  ancestors.delete(value);
1798
2117
  }
1799
2118
  }
2119
+ function walkForm(value, method, rules, depth2, ancestors, honorToJson, inSerialized) {
2120
+ const plain = rules.ownFields.safe;
2121
+ const toJson = honorToJson && !(plain && isError(value)) ? method : void 0;
2122
+ if (toJson !== void 0) {
2123
+ return walkToJsonOutput(value, toJson, rules, depth2, ancestors, inSerialized);
2124
+ }
2125
+ if (typeof value === "function") {
2126
+ return plain ? void 0 : value;
2127
+ }
2128
+ if (Array.isArray(value)) {
2129
+ return walkArray(value, rules, depth2, ancestors, inSerialized);
2130
+ }
2131
+ return walkProperties(value, rules, depth2, ancestors, honorToJson, inSerialized);
2132
+ }
2133
+ function walkToJsonOutput(value, toJson, rules, depth2, ancestors, inSerialized) {
2134
+ if (Object.keys(value).some((key) => rules.sensitive.has(key.toLowerCase()))) {
2135
+ return rules.censor;
2136
+ }
2137
+ return walk(toJson.call(value), rules, depth2 + 1, ancestors, true, inSerialized);
2138
+ }
2139
+ function walkProperties(value, rules, depth2, ancestors, honorToJson, inSerialized) {
2140
+ const source = value;
2141
+ const keys = Object.keys(source);
2142
+ const { safe } = rules.ownFields;
2143
+ const asData = isError(value) && (safe || rules.errorsAsData && !inSerialized);
2144
+ const copy = startCopy(value, asData);
2145
+ const scrubbed = isError(value) && (safe || !inSerialized);
2146
+ const omitted = /* @__PURE__ */ new Set();
2147
+ for (const key of keys) {
2148
+ const read = Reflect.get(source, key);
2149
+ const current = scrubbed ? ownFieldForLog(source, key, read, rules.ownFields) : read;
2150
+ if (current === OMIT_OWN_FIELD) {
2151
+ Reflect.deleteProperty(copy, key);
2152
+ omitted.add(key);
2153
+ continue;
2154
+ }
2155
+ defineOwn(
2156
+ copy,
2157
+ key,
2158
+ rules.sensitive.has(key.toLowerCase()) ? rules.censor : walk(
2159
+ scrubbed && ERROR_TEXT_FIELDS.has(key) ? cutIfText(current) : current,
2160
+ rules,
2161
+ depth2 + 1,
2162
+ ancestors,
2163
+ true,
2164
+ inSerialized || !honorToJson && rules.serializedKeys.has(key)
2165
+ )
2166
+ );
2167
+ }
2168
+ if (asData) {
2169
+ const host = errorPartsHost(rules, ancestors, inSerialized);
2170
+ addErrorParts(copy, value, without(keys, omitted), host, depth2);
2171
+ }
2172
+ return copy;
2173
+ }
2174
+ function without(keys, omitted) {
2175
+ return keys.filter((key) => !omitted.has(key));
2176
+ }
2177
+ function startCopy(value, asData) {
2178
+ const clone = isError(value) ? cloneError(value) : void 0;
2179
+ return clone !== void 0 && !asData ? clone : {};
2180
+ }
1800
2181
  function errorPartsHost(rules, ancestors, inSerialized) {
1801
2182
  return {
1802
2183
  sensitive: rules.sensitive,
@@ -2559,190 +2940,64 @@ var DestinationRegistry = class {
2559
2940
  } catch (cause) {
2560
2941
  this.reportShutdownFailure(destination, cause);
2561
2942
  }
2562
- }
2563
- }
2564
- /**
2565
- * Report a failing `onShutdown` on stderr without letting the report itself
2566
- * abort the teardown of the destinations still queued behind it.
2567
- *
2568
- * The coercion is INSIDE the guard, not above it. Reading `stack`/`message` on
2569
- * an `Error` with hostile getters, and `String(cause)` on a value with a
2570
- * throwing `toString`/`Symbol.toPrimitive`, both throw — and this runs inside
2571
- * the `catch` that exists to keep one bad sink from mattering, so an escape
2572
- * here would propagate out of `onApplicationShutdown` and skip every remaining
2573
- * destination's flush. The never-throw contract has to cover READING the value,
2574
- * not just writing it, which is the same correction `reportDestinationFailure`
2575
- * already carries.
2576
- *
2577
- * The text is escaped for the same reason every other terminal-bound path is:
2578
- * a stack is legitimately multi-line, so `escapeControlCharacters` keeps its
2579
- * newlines and neutralizes everything else that can drive a terminal.
2580
- *
2581
- * The DESTINATION is passed rather than its name, so that read happens in here
2582
- * too. `name` is declared `readonly name: string` but nothing stops a consumer
2583
- * implementing it as a getter, and reading it at the call site would put it back
2584
- * outside the guard — inside the `catch`, where a throw has the same cost.
2585
- *
2586
- * Two separate guards, not one: a name that cannot be read must not also cost
2587
- * the failure detail, and a detail that cannot be read must not cost the name.
2588
- * Either alone still identifies which sink failed.
2589
- *
2590
- * @param destination - The destination whose `onShutdown` threw.
2591
- * @param cause - The thrown value, of any shape.
2592
- */
2593
- reportShutdownFailure(destination, cause) {
2594
- const name = toSingleLineMessage(safeDestinationName(destination));
2595
- let detail = "UnknownError";
2596
- try {
2597
- const stack = isErrorLike(cause) ? cause.stack : void 0;
2598
- detail = stack === void 0 ? toBoundedMessage(isErrorLike(cause) ? String(cause.message) : String(cause)) : escapeControlCharacters(cutText(String(stack)));
2599
- } catch {
2600
- }
2601
- writeStderrSafely(`[DestinationRegistry] Shutdown failed for "${name}": ${detail}
2602
- `);
2603
- }
2604
- /**
2605
- * The destinations that initialized successfully.
2606
- *
2607
- * @returns A read-only view of the active destination set.
2608
- */
2609
- getActive() {
2610
- return this.active;
2611
- }
2612
- };
2613
- DestinationRegistry = __decorateClass([
2614
- Injectable(),
2615
- __decorateParam(0, Inject(LOGGER_DESTINATIONS_TOKEN)),
2616
- __decorateParam(1, Inject(PinoLoggerService)),
2617
- __decorateParam(2, Inject(LOGGER_OPTIONS_TOKEN)),
2618
- __decorateParam(3, Inject(DestinationHealth))
2619
- ], DestinationRegistry);
2620
- var FORBIDDEN_CONTEXT_KEYS = PROTOTYPE_POLLUTING_KEYS;
2621
- var LogContextService = class {
2622
- constructor() {
2623
- this.als = new AsyncLocalStorage();
2624
- }
2625
- /**
2626
- * Run `callback` inside a fresh context scope. Every log emitted
2627
- * synchronously or asynchronously within the callback inherits `context`.
2628
- *
2629
- * **A nested `run()` REPLACES the enclosing context, it does not extend it.**
2630
- * The scope starts from `context` alone, so a field an outer scope had set —
2631
- * a `tenantId` resolved at the edge, say — is absent for the whole inner
2632
- * scope: nothing throws, `get()` simply returns `undefined`, and the field is
2633
- * missing from every entry the callback emits. Reach for {@link runMerged}
2634
- * when the inner scope should extend the outer one.
2635
- *
2636
- * Replacement is the deliberate default because the opposite leaks: a
2637
- * background job started inside a request scope would silently inherit the
2638
- * caller's `userId` and attribute its entries to a user who never triggered
2639
- * it. A missing field is visibly missing; an inherited one is wrong while
2640
- * looking right.
2641
- *
2642
- * @typeParam T - Return type of the callback.
2643
- * @param context - Initial context bag for the scope. Becomes the WHOLE scope.
2644
- * @param callback - Function executed within the scope.
2645
- * @returns Whatever `callback` returns.
2646
- * @example
2647
- * logContext.run({ requestId: 'r_1', tenantId: 't_1' }, async () => {
2648
- * await userService.create(dto) // logs carry requestId + tenantId
2649
- * })
2650
- */
2651
- run(context, callback) {
2652
- return this.als.run(this.sanitizeContext(context), callback);
2653
- }
2654
- /**
2655
- * Run `callback` inside a scope that EXTENDS the enclosing one: the active
2656
- * context's fields are carried in, and `context` overrides them key by key.
2657
- *
2658
- * The explicit counterpart to {@link run}'s replacement semantics, for the
2659
- * case where an inner scope is genuinely a refinement of the outer — adding a
2660
- * `userId` once authentication resolved it, without having to restate the
2661
- * `requestId` the middleware already set.
2662
- *
2663
- * Outside any scope there is nothing to merge and this behaves exactly like
2664
- * {@link run}. Writes inside the new scope never reach the enclosing one: the
2665
- * merge produces a fresh object, so the outer context is intact after the
2666
- * callback returns.
2667
- *
2668
- * @typeParam T - Return type of the callback.
2669
- * @param context - Fields to add or override on top of the active context.
2670
- * @param callback - Function executed within the merged scope.
2671
- * @returns Whatever `callback` returns.
2672
- * @example
2673
- * logContext.run({ requestId: 'r_1' }, () => {
2674
- * logContext.runMerged({ userId: 'u_1' }, () => {
2675
- * logContext.get('requestId') // 'r_1' — carried in from the outer scope
2676
- * })
2677
- * })
2678
- */
2679
- runMerged(context, callback) {
2680
- const merged = { ...this.als.getStore(), ...this.sanitizeContext(context) };
2681
- return this.als.run(merged, callback);
2943
+ }
2682
2944
  }
2683
2945
  /**
2684
- * Read the active context, or `undefined` when called outside any scope.
2946
+ * Report a failing `onShutdown` on stderr without letting the report itself
2947
+ * abort the teardown of the destinations still queued behind it.
2685
2948
  *
2686
- * @returns The active `LogContext`, or `undefined`.
2687
- */
2688
- getStore() {
2689
- return this.als.getStore();
2690
- }
2691
- /**
2692
- * Add or override a single field on the active context.
2949
+ * The coercion is INSIDE the guard, not above it. Reading `stack`/`message` on
2950
+ * an `Error` with hostile getters, and `String(cause)` on a value with a
2951
+ * throwing `toString`/`Symbol.toPrimitive`, both throw — and this runs inside
2952
+ * the `catch` that exists to keep one bad sink from mattering, so an escape
2953
+ * here would propagate out of `onApplicationShutdown` and skip every remaining
2954
+ * destination's flush. The never-throw contract has to cover READING the value,
2955
+ * not just writing it, which is the same correction `reportDestinationFailure`
2956
+ * already carries.
2693
2957
  *
2694
- * @param key - Field name to set.
2695
- * @param value - Field value.
2696
- * @throws Error When called outside a `run()` scope, or with a prototype-polluting key.
2697
- */
2698
- set(key, value) {
2699
- const store = this.als.getStore();
2700
- if (!store) {
2701
- throw new Error("[LogContextService] set() called outside run() scope");
2702
- }
2703
- if (FORBIDDEN_CONTEXT_KEYS.has(key)) {
2704
- throw new Error(`[LogContextService] Refusing to set unsafe context key: ${key}`);
2705
- }
2706
- Reflect.set(store, key, value);
2707
- }
2708
- /**
2709
- * Read a single field from the active context.
2958
+ * The text is escaped for the same reason every other terminal-bound path is:
2959
+ * a stack is legitimately multi-line, so `escapeControlCharacters` keeps its
2960
+ * newlines and neutralizes everything else that can drive a terminal.
2710
2961
  *
2711
- * @typeParam T - Expected value type (caller-asserted).
2712
- * @param key - Field name to read.
2713
- * @returns The value cast to `T`, or `undefined` when unset / out of scope.
2962
+ * The DESTINATION is passed rather than its name, so that read happens in here
2963
+ * too. `name` is declared `readonly name: string` but nothing stops a consumer
2964
+ * implementing it as a getter, and reading it at the call site would put it back
2965
+ * outside the guard — inside the `catch`, where a throw has the same cost.
2966
+ *
2967
+ * Two separate guards, not one: a name that cannot be read must not also cost
2968
+ * the failure detail, and a detail that cannot be read must not cost the name.
2969
+ * Either alone still identifies which sink failed.
2970
+ *
2971
+ * @param destination - The destination whose `onShutdown` threw.
2972
+ * @param cause - The thrown value, of any shape.
2714
2973
  */
2715
- get(key) {
2716
- const store = this.als.getStore();
2717
- if (!store) {
2718
- return void 0;
2974
+ reportShutdownFailure(destination, cause) {
2975
+ const name = toSingleLineMessage(safeDestinationName(destination));
2976
+ let detail = "UnknownError";
2977
+ try {
2978
+ const stack = isErrorLike(cause) ? cause.stack : void 0;
2979
+ detail = stack === void 0 ? toBoundedMessage(isErrorLike(cause) ? String(cause.message) : String(cause)) : escapeControlCharacters(cutText(String(stack)));
2980
+ } catch {
2719
2981
  }
2720
- return Reflect.get(store, key);
2982
+ writeStderrSafely(`[DestinationRegistry] Shutdown failed for "${name}": ${detail}
2983
+ `);
2721
2984
  }
2722
2985
  /**
2723
- * Strip prototype-polluting keys from a caller-supplied context so an own
2724
- * `__proto__` / `constructor` / `prototype` key (e.g. from `JSON.parse` of an
2725
- * untrusted payload) can never reach the store — and, via the trace mixin's
2726
- * `Object.assign`, the emitted log entry. Mirrors the guard `set()` enforces,
2727
- * but drops the key rather than throwing: a logging concern must never crash
2728
- * the request that produced it.
2986
+ * The destinations that initialized successfully.
2729
2987
  *
2730
- * @param context - The raw context bag passed to `run()`.
2731
- * @returns A shallow copy with any forbidden keys removed.
2988
+ * @returns A read-only view of the active destination set.
2732
2989
  */
2733
- sanitizeContext(context) {
2734
- const safe = {};
2735
- for (const key of Object.keys(context)) {
2736
- if (!FORBIDDEN_CONTEXT_KEYS.has(key)) {
2737
- Reflect.set(safe, key, Reflect.get(context, key));
2738
- }
2739
- }
2740
- return safe;
2990
+ getActive() {
2991
+ return this.active;
2741
2992
  }
2742
2993
  };
2743
- LogContextService = __decorateClass([
2744
- Injectable()
2745
- ], LogContextService);
2994
+ DestinationRegistry = __decorateClass([
2995
+ Injectable(),
2996
+ __decorateParam(0, Inject(LOGGER_DESTINATIONS_TOKEN)),
2997
+ __decorateParam(1, Inject(PinoLoggerService)),
2998
+ __decorateParam(2, Inject(LOGGER_OPTIONS_TOKEN)),
2999
+ __decorateParam(3, Inject(DestinationHealth))
3000
+ ], DestinationRegistry);
2746
3001
 
2747
3002
  // src/server/logger.module.ts
2748
3003
  function resolveDestinations(options) {
@@ -2910,6 +3165,26 @@ var BymaxLoggerModule = class extends BymaxLoggerModuleBase {
2910
3165
  app.useLogger(logger);
2911
3166
  app.flushLogs();
2912
3167
  }
3168
+ /**
3169
+ * Open the request-id correlation scope ahead of the body parser, so a request the parser
3170
+ * refuses (malformed JSON, an unsupported content encoding, a body over the limit) still has its
3171
+ * `requestId`, and the `x-request-id` response header, where an exception filter reads it.
3172
+ *
3173
+ * Call once in `main.ts` AFTER creating the app and BEFORE `app.init()` / `app.listen(...)`.
3174
+ * It mounts only the scope. `applyAccessLog(app)` and `applyRequestIdMiddleware(consumer)` can
3175
+ * be used as well: a second mount of the middleware reuses the scope this one opened.
3176
+ *
3177
+ * @param app - The Nest application returned by `NestFactory.create()`.
3178
+ * @throws Error When `BymaxLoggerModule` was not imported.
3179
+ * @example
3180
+ * const app = await NestFactory.create(AppModule, { bufferLogs: true })
3181
+ * BymaxLoggerModule.useNestLogger(app)
3182
+ * BymaxLoggerModule.useRequestContext(app)
3183
+ * await app.listen(3000)
3184
+ */
3185
+ static useRequestContext(app) {
3186
+ applyRequestContext(app);
3187
+ }
2913
3188
  };
2914
3189
  BymaxLoggerModule = __decorateClass([
2915
3190
  Module({})
@@ -3260,156 +3535,6 @@ HttpAccessLogMiddleware = __decorateClass([
3260
3535
  __decorateParam(1, Inject(LogContextService)),
3261
3536
  __decorateParam(2, Inject(LOGGER_OPTIONS_TOKEN))
3262
3537
  ], HttpAccessLogMiddleware);
3263
- var REQUEST_ID_HEADER = "x-request-id";
3264
- var MAX_CORRELATION_ID_LENGTH = 256;
3265
- var CORRELATION_ID_CHARSET = /^[A-Za-z0-9._:/+=-]+$/;
3266
- var INHERITABLE_CONTEXT_KEYS = ["requestId", "tenantId"];
3267
- function isAcceptableHeaderValue(value) {
3268
- return typeof value === "string" && value.length <= MAX_CORRELATION_ID_LENGTH && CORRELATION_ID_CHARSET.test(value);
3269
- }
3270
- var RequestIdMiddleware = class {
3271
- /**
3272
- * @param logContext - The AsyncLocalStorage-backed context service. Injected by
3273
- * token explicitly: the package is bundled without `emitDecoratorMetadata`,
3274
- * so implicit class-type injection would not resolve.
3275
- * @param options - Resolved module options (read for `http.tenantIdHeader` and
3276
- * `http.shouldGenerateRequestId`).
3277
- */
3278
- constructor(logContext, options) {
3279
- this.logContext = logContext;
3280
- this.tenantIdHeader = options.http.tenantIdHeader;
3281
- this.shouldGenerateRequestId = options.http.shouldGenerateRequestId;
3282
- }
3283
- /**
3284
- * Echo or mint the `x-request-id`, expose it on the response, and run the
3285
- * remainder of the request inside its own log-context scope.
3286
- *
3287
- * Idempotent: mounting this middleware twice on the same request mints one id,
3288
- * not two. The request gets its OWN store, started from the enclosing scope's
3289
- * correlation fields — see {@link INHERITABLE_CONTEXT_KEYS} — and nothing
3290
- * else, because no other field can be known to belong to this request.
3291
- *
3292
- * An enclosing scope's `requestId` is never adopted and never echoed: adoption
3293
- * reads a value this middleware recorded on the REQUEST, which a scope opened
3294
- * elsewhere does not have. What the two generation modes do with one, measured
3295
- * on two requests sharing a long-lived enclosing scope:
3296
- *
3297
- * - `shouldGenerateRequestId: true` (default) — each request mints its own
3298
- * id, the two requests differ, and the enclosing value reaches neither the
3299
- * header nor the entries.
3300
- * - `shouldGenerateRequestId: false` with no inbound header — nothing is
3301
- * minted, so the request scope inherits the enclosing `requestId` and every
3302
- * request inside that scope logs under it. No header is exposed. That is
3303
- * the consumer's own scope being inherited, not correlation being reused,
3304
- * and it is the configuration that says the gateway owns the id.
3305
- *
3306
- * @param req - The incoming request (Express satisfies the contract).
3307
- * @param res - The outgoing response (Express satisfies the contract).
3308
- * @param next - The next handler in the chain.
3309
- */
3310
- use(req, res, next) {
3311
- if (isCorrelationOpened(req)) {
3312
- const ownRequestId = readOwnRequestId(req);
3313
- if (ownRequestId !== void 0) {
3314
- this.adoptExistingScope(ownRequestId, req, res);
3315
- }
3316
- next();
3317
- return;
3318
- }
3319
- markCorrelationOpened(req);
3320
- const context = this.inheritableContext();
3321
- const requestId = this.resolveRequestId(req);
3322
- if (requestId !== void 0) {
3323
- res.setHeader(REQUEST_ID_HEADER, requestId);
3324
- context.requestId = requestId;
3325
- markOwnRequestId(req, requestId);
3326
- }
3327
- if (context.tenantId === void 0) {
3328
- const tenantId = this.resolveTenantId(req);
3329
- if (tenantId !== void 0) {
3330
- context.tenantId = tenantId;
3331
- }
3332
- }
3333
- this.logContext.run(context, () => next());
3334
- }
3335
- /**
3336
- * The enclosing scope's fields that a request scope may start from.
3337
- *
3338
- * Plain `run()` would discard everything the caller had set and a plain merge
3339
- * would carry identity across requests; {@link INHERITABLE_CONTEXT_KEYS} is
3340
- * the middle a request scope actually needs.
3341
- *
3342
- * @returns A fresh bag, never the enclosing store itself, so writes inside the
3343
- * request never reach the scope that opened it.
3344
- */
3345
- inheritableContext() {
3346
- const store = { ...this.logContext.getStore() };
3347
- const inherited = {};
3348
- for (const key of INHERITABLE_CONTEXT_KEYS) {
3349
- const value = Reflect.get(store, key);
3350
- if (value !== void 0) {
3351
- Reflect.set(inherited, key, value);
3352
- }
3353
- }
3354
- return inherited;
3355
- }
3356
- /**
3357
- * Second mount on a request that already carries a correlation id: echo the id
3358
- * onto the response and fill in a tenant the scope does not have yet, without
3359
- * opening another scope.
3360
- *
3361
- * Nothing is minted and nothing already set is overwritten, so a third mount —
3362
- * or a thirtieth — changes nothing. The response header is written on every
3363
- * pass because the enclosing scope may have been opened by consumer code that
3364
- * never exposed it.
3365
- *
3366
- * @param requestId - The id already in scope, which wins.
3367
- * @param req - The incoming request, read for the tenant header.
3368
- * @param res - The outgoing response, where the effective id is exposed.
3369
- */
3370
- adoptExistingScope(requestId, req, res) {
3371
- res.setHeader(REQUEST_ID_HEADER, requestId);
3372
- this.logContext.set("requestId", requestId);
3373
- if (this.logContext.get("tenantId") === void 0) {
3374
- const tenantId = this.resolveTenantId(req);
3375
- if (tenantId !== void 0) {
3376
- this.logContext.set("tenantId", tenantId);
3377
- }
3378
- }
3379
- }
3380
- /**
3381
- * The correlation id for this request: the inbound header when acceptable,
3382
- * otherwise a fresh UUID — or nothing at all when `shouldGenerateRequestId` is
3383
- * off and the caller sent none, which leaves correlation to the upstream
3384
- * gateway.
3385
- *
3386
- * @param req - The incoming request.
3387
- * @returns The id, or `undefined` when none is available and none is minted.
3388
- */
3389
- resolveRequestId(req) {
3390
- const incoming = Reflect.get(req.headers, REQUEST_ID_HEADER);
3391
- const fromHeader = isAcceptableHeaderValue(incoming) ? incoming : void 0;
3392
- return fromHeader ?? (this.shouldGenerateRequestId ? randomUUID() : void 0);
3393
- }
3394
- /**
3395
- * The tenant id carried by the configured header, when it is acceptable.
3396
- *
3397
- * Never minted: a tenant is an assertion about who the request belongs to, and
3398
- * inventing one would be a fabricated claim rather than a correlation aid.
3399
- *
3400
- * @param req - The incoming request.
3401
- * @returns The tenant id, or `undefined`.
3402
- */
3403
- resolveTenantId(req) {
3404
- const raw = Reflect.get(req.headers, this.tenantIdHeader);
3405
- return isAcceptableHeaderValue(raw) ? raw : void 0;
3406
- }
3407
- };
3408
- RequestIdMiddleware = __decorateClass([
3409
- Injectable(),
3410
- __decorateParam(0, Inject(LogContextService)),
3411
- __decorateParam(1, Inject(LOGGER_OPTIONS_TOKEN))
3412
- ], RequestIdMiddleware);
3413
3538
 
3414
3539
  // src/server/middlewares/apply-access-log.ts
3415
3540
  function resolveDependencies(app) {