@bymax-one/nest-logger 1.4.21 → 1.4.23

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.
@@ -22,6 +22,73 @@ var __decorateParam = (index, decorator) => (target, key) => decorator(target, k
22
22
  var getFilename = () => fileURLToPath(import.meta.url);
23
23
  var __filename$1 = /* @__PURE__ */ getFilename();
24
24
 
25
+ // src/server/config/drop-unset-options.ts
26
+ var OPTION_KEYS = {
27
+ service: true,
28
+ level: true,
29
+ isGlobal: true,
30
+ shouldUseAsNestLogger: true,
31
+ redactPaths: true,
32
+ redactStrategy: true,
33
+ resourceFormat: true,
34
+ eventNameField: true,
35
+ errorFormat: true,
36
+ redactCensor: true,
37
+ shouldDisableDefaultRedact: true,
38
+ destinations: true,
39
+ http: true,
40
+ otel: true,
41
+ maxEntrySizeBytes: true,
42
+ maxStringLength: true,
43
+ destinationHookTimeoutMs: true,
44
+ shutdown: true,
45
+ destinationQueue: true,
46
+ errorOwnFields: true,
47
+ errorOwnFieldNames: true,
48
+ serializers: true,
49
+ timestamp: true
50
+ };
51
+ var GROUP_KEYS = {
52
+ http: {
53
+ isEnabled: true,
54
+ shouldCaptureExceptions: true,
55
+ shouldGenerateRequestId: true,
56
+ excludePaths: true,
57
+ secretPathSegments: true,
58
+ tenantIdHeader: true,
59
+ tenantIdResolver: true
60
+ },
61
+ otel: {
62
+ shouldAutoInjectTraceContext: true,
63
+ fieldFormat: true,
64
+ traceIdField: true,
65
+ spanIdField: true,
66
+ traceFlagsField: true
67
+ },
68
+ shutdown: { timeoutMs: true, drainTimeoutMs: true },
69
+ destinationQueue: { maxBytes: true }
70
+ };
71
+ var GROUP_NAMES = Object.keys(GROUP_KEYS);
72
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
73
+ function readSet(source, keys) {
74
+ const set = {};
75
+ for (const key of keys) {
76
+ const value = Reflect.get(source, key);
77
+ if (value !== void 0 && value !== null) Reflect.set(set, key, value);
78
+ }
79
+ return set;
80
+ }
81
+ function dropUnsetOptions(options) {
82
+ if (!isRecord(options)) return options;
83
+ const set = readSet(options, Object.keys(OPTION_KEYS));
84
+ for (const group of GROUP_NAMES) {
85
+ const value = Reflect.get(set, group);
86
+ if (isRecord(value))
87
+ Reflect.set(set, group, readSet(value, Object.keys(Reflect.get(GROUP_KEYS, group))));
88
+ }
89
+ return set;
90
+ }
91
+
25
92
  // src/server/constants/lifecycle-timeouts.constants.ts
26
93
  var DEFAULT_HOOK_TIMEOUT_MS = 1e4;
27
94
  var DEFAULT_SHUTDOWN_TIMEOUT_MS = 1e4;
@@ -29,6 +96,9 @@ var DEFAULT_DRAIN_TIMEOUT_MS = 5e3;
29
96
  var DEFAULT_QUEUE_MAX_BYTES = 33554432;
30
97
  var MIN_QUEUE_MAX_BYTES = 1024;
31
98
  var MAX_QUEUE_MAX_BYTES = 2147483647;
99
+ var MAX_ENTRY_SIZE_BYTES = 2147483647;
100
+ var MIN_STRING_LENGTH_LIMIT = 64;
101
+ var MAX_STRING_LENGTH_LIMIT = 2147483647;
32
102
 
33
103
  // src/server/config/default-options.ts
34
104
  var DEFAULT_HTTP = {
@@ -66,7 +136,8 @@ function applyOtelFieldFormat(merged, user) {
66
136
  }
67
137
  return merged;
68
138
  }
69
- function applyDefaults(options) {
139
+ function applyDefaults(given) {
140
+ const options = dropUnsetOptions(given);
70
141
  const isProduction = process.env["NODE_ENV"] === "production";
71
142
  const http = { ...DEFAULT_HTTP, ...options.http ?? {} };
72
143
  const otel = applyOtelFieldFormat(
@@ -98,6 +169,7 @@ function applyDefaults(options) {
98
169
  }),
99
170
  otel: Object.freeze(otel),
100
171
  maxEntrySizeBytes: options.maxEntrySizeBytes ?? DEFAULT_MAX_ENTRY_SIZE_BYTES,
172
+ maxStringLength: options.maxStringLength,
101
173
  destinationHookTimeoutMs: options.destinationHookTimeoutMs ?? DEFAULT_HOOK_TIMEOUT_MS,
102
174
  shutdown: resolveShutdown(options.shutdown),
103
175
  destinationQueue: Object.freeze({
@@ -137,19 +209,32 @@ var LOG_LEVEL_PRIORITY = Object.freeze([
137
209
  ]);
138
210
 
139
211
  // src/server/config/validate-options.ts
140
- function reject(path2, rule, got) {
141
- const received = got === void 0 ? "" : `. Got: ${describeValue(got)}`;
212
+ function reject(path2, rule, got, wasGiven = got !== void 0) {
213
+ const received = wasGiven ? `. Received ${describeValue(got)}` : "";
142
214
  throw new Error(`[BymaxLoggerModule] options.${path2} ${rule}${received}`);
143
215
  }
144
216
  function describeValue(value) {
145
- if (value === null) return "null";
146
- if (Array.isArray(value)) return "an array";
147
- if (typeof value === "object") return "an object";
148
- if (typeof value === "function") return "a function";
149
- if (typeof value === "string") return JSON.stringify(value);
150
- return String(value);
151
- }
152
- var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
217
+ switch (typeof value) {
218
+ case "number":
219
+ return Number.isFinite(value) ? `the number ${String(value)}` : "a number that is not finite";
220
+ case "string":
221
+ return "a string";
222
+ case "boolean":
223
+ return "a boolean";
224
+ case "bigint":
225
+ return "a bigint";
226
+ case "symbol":
227
+ return "a symbol";
228
+ case "function":
229
+ return "a function";
230
+ case "undefined":
231
+ return "undefined";
232
+ default:
233
+ if (value === null) return "null";
234
+ return Array.isArray(value) ? "an array" : "an object";
235
+ }
236
+ }
237
+ var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
153
238
  var isNonEmptyString = (value) => typeof value === "string" && value.length > 0;
154
239
  function checkBoolean(path2, value) {
155
240
  if (value !== void 0 && typeof value !== "boolean") {
@@ -163,7 +248,7 @@ function checkNonEmptyString(path2, value) {
163
248
  }
164
249
  function checkGroup(path2, value) {
165
250
  if (value === void 0) return void 0;
166
- if (!isRecord(value)) reject(path2, "must be an object", value);
251
+ if (!isRecord2(value)) reject(path2, "must be an object", value);
167
252
  return value;
168
253
  }
169
254
  var MAX_TIMER_MS = 2147483647;
@@ -185,6 +270,26 @@ function validateQueue(options) {
185
270
  );
186
271
  }
187
272
  }
273
+ function validateStringLimit(options) {
274
+ const limit = options.maxStringLength;
275
+ if (limit === void 0) return;
276
+ if (typeof limit !== "number" || !Number.isInteger(limit) || limit < MIN_STRING_LENGTH_LIMIT || limit > MAX_STRING_LENGTH_LIMIT) {
277
+ reject(
278
+ "maxStringLength",
279
+ `must be an integer from ${String(MIN_STRING_LENGTH_LIMIT)} to ${String(MAX_STRING_LENGTH_LIMIT)}`,
280
+ limit
281
+ );
282
+ }
283
+ refuseCensorBeyondLimit(options.redactCensor, limit);
284
+ }
285
+ function refuseCensorBeyondLimit(censor, limit) {
286
+ if (typeof censor === "string" && censor.length > limit) {
287
+ reject(
288
+ "redactCensor",
289
+ `must be at most ${String(limit)} characters when maxStringLength is set`
290
+ );
291
+ }
292
+ }
188
293
  function validateLifecycle(options) {
189
294
  checkTimerMs("destinationHookTimeoutMs", options.destinationHookTimeoutMs);
190
295
  const shutdown = checkGroup("shutdown", options.shutdown);
@@ -202,61 +307,46 @@ function validateLifecycle(options) {
202
307
  }
203
308
  }
204
309
  function validateCore(options) {
205
- if (!options.service) {
310
+ const service = options.service;
311
+ if (service === void 0) {
206
312
  throw new Error("[BymaxLoggerModule] options.service is required");
207
313
  }
208
- if (typeof options.service.name !== "string" || options.service.name.trim() === "") {
209
- throw new Error("[BymaxLoggerModule] options.service.name must be a non-empty string");
210
- }
211
- if (typeof options.service.version !== "string" || options.service.version.trim() === "") {
212
- throw new Error("[BymaxLoggerModule] options.service.version must be a non-empty string");
314
+ if (!isRecord2(service)) reject("service", "must be an object", service);
315
+ for (const field of ["name", "version"]) {
316
+ const given = service[field];
317
+ if (typeof given !== "string" || given.trim() === "") {
318
+ reject(`service.${field}`, "must be a non-empty string", given);
319
+ }
213
320
  }
214
321
  if (options.level !== void 0 && !LOG_LEVEL_PRIORITY.includes(options.level)) {
215
- throw new Error(
216
- `[BymaxLoggerModule] options.level must be one of: ${LOG_LEVEL_PRIORITY.join(
217
- ", "
218
- )}. Got: ${String(options.level)}`
219
- );
322
+ reject("level", `must be one of: ${LOG_LEVEL_PRIORITY.join(", ")}`, options.level);
220
323
  }
221
324
  const size = options.maxEntrySizeBytes;
222
325
  if (size !== void 0 && !Number.isFinite(size)) {
223
326
  reject("maxEntrySizeBytes", "must be a finite number", size);
224
327
  }
225
328
  if (options.maxEntrySizeBytes !== void 0 && options.maxEntrySizeBytes <= 0) {
226
- throw new Error("[BymaxLoggerModule] options.maxEntrySizeBytes must be > 0");
329
+ reject("maxEntrySizeBytes", "must be > 0", options.maxEntrySizeBytes);
227
330
  }
228
331
  if (size !== void 0 && !Number.isInteger(size)) {
229
332
  reject("maxEntrySizeBytes", "must be an integer", size);
230
333
  }
334
+ if (options.maxEntrySizeBytes !== void 0 && options.maxEntrySizeBytes > MAX_ENTRY_SIZE_BYTES) {
335
+ reject("maxEntrySizeBytes", `must be at most ${String(MAX_ENTRY_SIZE_BYTES)}`, size);
336
+ }
231
337
  }
232
338
  function validateClosedSets(options) {
233
339
  if (options.redactStrategy !== void 0 && options.redactStrategy !== "names" && options.redactStrategy !== "paths") {
234
- throw new Error(
235
- `[BymaxLoggerModule] options.redactStrategy must be 'names' or 'paths'. Got: ${String(
236
- options.redactStrategy
237
- )}`
238
- );
340
+ reject("redactStrategy", "must be 'names' or 'paths'", options.redactStrategy);
239
341
  }
240
342
  if (options.resourceFormat !== void 0 && options.resourceFormat !== "nested" && options.resourceFormat !== "flat") {
241
- throw new Error(
242
- `[BymaxLoggerModule] options.resourceFormat must be 'nested' or 'flat'. Got: ${String(
243
- options.resourceFormat
244
- )}`
245
- );
343
+ reject("resourceFormat", "must be 'nested' or 'flat'", options.resourceFormat);
246
344
  }
247
345
  if (options.errorFormat !== void 0 && options.errorFormat !== "pino" && options.errorFormat !== "semconv" && options.errorFormat !== "both") {
248
- throw new Error(
249
- `[BymaxLoggerModule] options.errorFormat must be 'pino', 'semconv' or 'both'. Got: ${String(
250
- options.errorFormat
251
- )}`
252
- );
346
+ reject("errorFormat", "must be 'pino', 'semconv' or 'both'", options.errorFormat);
253
347
  }
254
348
  if (options.eventNameField !== void 0 && options.eventNameField !== false && (typeof options.eventNameField !== "string" || options.eventNameField.length === 0)) {
255
- throw new Error(
256
- `[BymaxLoggerModule] options.eventNameField must be a non-empty string or false. Got: ${String(
257
- options.eventNameField
258
- )}`
259
- );
349
+ reject("eventNameField", "must be a non-empty string or false", options.eventNameField);
260
350
  }
261
351
  }
262
352
  function validateCustomization(options) {
@@ -273,16 +363,16 @@ function validateCustomization(options) {
273
363
  if (!Array.isArray(paths)) reject("redactPaths", "must be an array of strings", paths);
274
364
  paths.forEach((entry, index) => {
275
365
  if (!isNonEmptyString(entry)) {
276
- reject(`redactPaths[${String(index)}]`, "must be a non-empty string", entry);
366
+ reject(`redactPaths[${String(index)}]`, "must be a non-empty string", entry, true);
277
367
  }
278
368
  });
279
369
  }
280
370
  const serializers = options.serializers;
281
371
  if (serializers !== void 0) {
282
- if (!isRecord(serializers)) reject("serializers", "must be an object", serializers);
283
- for (const [key, serializer] of Object.entries(serializers)) {
372
+ if (!isRecord2(serializers)) reject("serializers", "must be an object", serializers);
373
+ for (const serializer of Object.values(serializers)) {
284
374
  if (typeof serializer !== "function") {
285
- reject(`serializers.${key}`, "must be a function", serializer);
375
+ reject("serializers", "must map every serializer key to a function", serializer);
286
376
  }
287
377
  }
288
378
  }
@@ -297,7 +387,7 @@ function validateErrorFields(options) {
297
387
  if (!Array.isArray(names)) reject("errorOwnFieldNames", "must be an array of strings", names);
298
388
  names.forEach((entry, index) => {
299
389
  if (!isNonEmptyString(entry)) {
300
- reject(`errorOwnFieldNames[${String(index)}]`, "must be a non-empty string", entry);
390
+ reject(`errorOwnFieldNames[${String(index)}]`, "must be a non-empty string", entry, true);
301
391
  }
302
392
  });
303
393
  }
@@ -311,8 +401,8 @@ function readMember(destination, key) {
311
401
  }
312
402
  function validateDestination(entry, index) {
313
403
  const path2 = `destinations[${String(index)}]`;
314
- if (!isRecord(entry)) {
315
- reject(path2, "must be an object implementing ILogDestination", entry);
404
+ if (!isRecord2(entry)) {
405
+ reject(path2, "must be an object implementing ILogDestination", entry, true);
316
406
  }
317
407
  const write = readMember(entry, "write");
318
408
  if (write !== UNREADABLE && typeof write !== "function") {
@@ -344,7 +434,7 @@ function checkRegExpList(path2, value) {
344
434
  }
345
435
  value.forEach((pattern, index) => {
346
436
  if (!types.isRegExp(pattern)) {
347
- reject(`${path2}[${String(index)}]`, "must be a RegExp", pattern);
437
+ reject(`${path2}[${String(index)}]`, "must be a RegExp", pattern, true);
348
438
  }
349
439
  });
350
440
  }
@@ -377,7 +467,8 @@ function validateOtel(options) {
377
467
  checkNonEmptyString("otel.spanIdField", otel["spanIdField"]);
378
468
  checkNonEmptyString("otel.traceFlagsField", otel["traceFlagsField"]);
379
469
  }
380
- function validateOptions(options) {
470
+ function validateOptions(given) {
471
+ const options = dropUnsetOptions(given);
381
472
  validateCore(options);
382
473
  validateClosedSets(options);
383
474
  validateCustomization(options);
@@ -385,6 +476,7 @@ function validateOptions(options) {
385
476
  validateDestinations(options);
386
477
  validateLifecycle(options);
387
478
  validateQueue(options);
479
+ validateStringLimit(options);
388
480
  validateHttp(options);
389
481
  validateOtel(options);
390
482
  }
@@ -445,14 +537,28 @@ var TEXT_TRUNCATED = "\u2026[truncated]";
445
537
  function cutIfText(value) {
446
538
  return typeof value === "string" ? cutText(value) : value;
447
539
  }
448
- function cutText(text, alreadyCut = false) {
449
- if (!alreadyCut && text.length <= MAX_TEXT_LENGTH) return text;
450
- const head = text.slice(0, MAX_TEXT_LENGTH);
540
+ function cutText(text, alreadyCut = false, limit = MAX_TEXT_LENGTH) {
541
+ if (!alreadyCut && text.length <= limit) return text;
542
+ const head = text.slice(0, limit);
451
543
  const last = head.charCodeAt(head.length - 1);
452
544
  const whole = last >= 55296 && last <= 56319 ? head.slice(0, -1) : head;
453
545
  return whole + TEXT_TRUNCATED;
454
546
  }
455
547
 
548
+ // src/server/utils/entry-text-finisher.util.ts
549
+ var ENTRY_TEXT_FINISHER = /* @__PURE__ */ Symbol("bymax.entryTextFinisher");
550
+ function createEntryTextFinisher(redact, limit) {
551
+ return (key, text) => {
552
+ try {
553
+ const censored = Reflect.get(redact({ [key]: text }, true), key);
554
+ if (typeof censored !== "string") return "";
555
+ return limit === void 0 ? censored : cutText(censored, false, limit);
556
+ } catch {
557
+ return "";
558
+ }
559
+ };
560
+ }
561
+
456
562
  // src/server/utils/escape-log-text.util.ts
457
563
  var LINE_TERMINATORS = /* @__PURE__ */ new Set(["\r", "\n", "\x85", "\u2028", "\u2029"]);
458
564
  var UNSAFE_IN_SINGLE_LINE = /[\u0000-\u0008\u000A-\u001F\u007F-\u009F\u2028\u2029]/g;
@@ -472,6 +578,16 @@ function toBoundedMessage(text) {
472
578
  function escapeControlCharacters(text) {
473
579
  return text.replace(UNSAFE_IN_MULTILINE, toEscapeSequence);
474
580
  }
581
+
582
+ // src/server/utils/is-plain-record.util.ts
583
+ function isPlainRecord(node) {
584
+ try {
585
+ const prototype = Object.getPrototypeOf(node);
586
+ return prototype === Object.prototype || prototype === null;
587
+ } catch {
588
+ return false;
589
+ }
590
+ }
475
591
  function isError(value) {
476
592
  try {
477
593
  return types.isNativeError(value) || value instanceof Error;
@@ -668,14 +784,22 @@ function createWidthMarker(omitted) {
668
784
 
669
785
  // src/server/services/pino-logger.service.ts
670
786
  var OWNED_PAYLOAD_KEYS = ["logKey", "userId", "context"];
671
- function withoutOwnedKeys(metadata) {
787
+ var ENTRY_STRUCTURE_KEYS = /* @__PURE__ */ new Set([
788
+ "level",
789
+ "time",
790
+ "msg",
791
+ "service",
792
+ "deployment"
793
+ ]);
794
+ var isEntryStructureKey = (key) => ENTRY_STRUCTURE_KEYS.has(key) || key.startsWith("service.") || key.startsWith("deployment.");
795
+ function withoutOwnedKeys(metadata, omit) {
672
796
  if (metadata === void 0) {
673
797
  return {};
674
798
  }
675
799
  try {
676
800
  const safe = {};
677
801
  for (const key of Object.keys(metadata)) {
678
- if (!OWNED_PAYLOAD_KEYS.includes(key) && !PROTOTYPE_POLLUTING_KEYS.has(key)) {
802
+ if (key !== omit && !OWNED_PAYLOAD_KEYS.includes(key) && !isEntryStructureKey(key) && !PROTOTYPE_POLLUTING_KEYS.has(key)) {
679
803
  Reflect.set(safe, key, Reflect.get(metadata, key));
680
804
  }
681
805
  }
@@ -694,6 +818,23 @@ function safeErrorMessage(error) {
694
818
  return "Unreadable error message";
695
819
  }
696
820
  }
821
+ function objectMessageText(fields) {
822
+ for (const key of ["message", "event"]) {
823
+ try {
824
+ const value = Reflect.get(fields, key);
825
+ if (typeof value === "string") return { key, text: value };
826
+ } catch {
827
+ }
828
+ }
829
+ return void 0;
830
+ }
831
+ function readObjectMessage(message) {
832
+ const fields = isPlainRecord(message) && !isErrorLike(message) ? message : void 0;
833
+ const text = fields === void 0 ? void 0 : objectMessageText(fields);
834
+ const omit = text?.key === "message" ? "message" : void 0;
835
+ const payload = withoutOwnedKeys(fields, omit);
836
+ return { fields, text, payload };
837
+ }
697
838
  function safeLogMessage(message) {
698
839
  try {
699
840
  return toBoundedMessage(typeof message === "string" ? message : String(message));
@@ -768,11 +909,11 @@ var PinoLoggerService = class {
768
909
  }
769
910
  const stack = typeof optionalParams[0] === "string" ? optionalParams[0] : void 0;
770
911
  const context = typeof optionalParams[1] === "string" ? optionalParams[1] : this.context;
771
- const payload = {};
912
+ const { fields, text, payload } = readObjectMessage(message);
772
913
  assignIfDefined(payload, "context", context);
773
914
  assignIfDefined(payload, "stack", stack === void 0 ? stack : cutText(stack));
774
915
  assignIfDefined(payload, "err", findErrorParam(optionalParams));
775
- this.pino.error(payload, safeLogMessage(message));
916
+ this.pino.error(payload, this.nestStyleMessage(void 0, fields, text, message));
776
917
  }
777
918
  /**
778
919
  * NestJS `warn` (warn level).
@@ -924,12 +1065,30 @@ var PinoLoggerService = class {
924
1065
  }
925
1066
  }
926
1067
  /** Emit a NestJS-style variadic log, dispatching by level without computed indexing. */
1068
+ nestStyleMessage(leading, fields, text, message) {
1069
+ if (leading !== void 0) return safeErrorMessage(leading);
1070
+ if (fields !== void 0) return toBoundedMessage(this.censorText(text));
1071
+ return safeLogMessage(message);
1072
+ }
1073
+ /**
1074
+ * The entry text of an object message, censored under the names of the field it came from and cut
1075
+ * like that field: the text is a copy of it, and a copy made outside the pipeline would carry a
1076
+ * value the pipeline censors or cuts in the field itself.
1077
+ *
1078
+ * @param text - The text and the member it came from.
1079
+ * @returns The censored text, or an empty one when the redactor cannot be applied.
1080
+ */
1081
+ censorText(text) {
1082
+ if (text === void 0) return "";
1083
+ const finish = Reflect.get(this.pino, ENTRY_TEXT_FINISHER) ?? createEntryTextFinisher(this.redact, void 0);
1084
+ return finish(text.key, text.text);
1085
+ }
927
1086
  emitNestStyle(level, message, optionalParams) {
928
- const payload = {};
1087
+ const { fields, text, payload } = readObjectMessage(message);
929
1088
  assignIfDefined(payload, "context", this.resolveContext(optionalParams));
930
1089
  const leading = isErrorLike(message) ? message : void 0;
931
1090
  assignIfDefined(payload, "err", leading ?? findErrorParam(optionalParams));
932
- const msg = leading === void 0 ? safeLogMessage(message) : safeErrorMessage(leading);
1091
+ const msg = this.nestStyleMessage(leading, fields, text, message);
933
1092
  switch (level) {
934
1093
  case "info":
935
1094
  this.pino.info(payload, msg);
@@ -2152,6 +2311,26 @@ function compileRedactPaths(extraPaths, shouldSkipDefaults) {
2152
2311
  const sources = shouldSkipDefaults ? [extraPaths] : [DEFAULT_REDACT_PATHS, extraPaths];
2153
2312
  return Array.from(new Set(sources.flat()));
2154
2313
  }
2314
+
2315
+ // src/server/utils/cut-strings.util.ts
2316
+ function cutNode(node, limit) {
2317
+ if (typeof node === "string") return cutText(node, false, limit);
2318
+ if (Array.isArray(node)) return node.map((child) => cutNode(child, limit));
2319
+ if (isPlainRecord(node)) {
2320
+ return Object.fromEntries(
2321
+ Object.entries(node).map(([key, child]) => [key, cutNode(child, limit)])
2322
+ );
2323
+ }
2324
+ return node;
2325
+ }
2326
+ function cutStrings(record, limit, exempt) {
2327
+ return Object.fromEntries(
2328
+ Object.entries(record).map(([key, child]) => [
2329
+ key,
2330
+ exempt.has(key) ? child : cutNode(child, limit)
2331
+ ])
2332
+ );
2333
+ }
2155
2334
  function reportWriteFailure(destination, cause, due) {
2156
2335
  const name = safeDestinationName(destination);
2157
2336
  reportDestinationFailure(
@@ -2289,6 +2468,30 @@ function destinationToStream(destination, health, maxQueueBytes = 0) {
2289
2468
  return stream;
2290
2469
  }
2291
2470
 
2471
+ // src/server/utils/merge-mixin-safely.util.ts
2472
+ var PROTOTYPE_KEY = "__proto__";
2473
+ var EXPLICIT_USER_KEY = "userId";
2474
+ function mergeMixinSafely(mergeObject, mixinObject) {
2475
+ try {
2476
+ const merged = {};
2477
+ for (const key of Object.keys(mergeObject)) {
2478
+ if (key !== PROTOTYPE_KEY) Reflect.set(merged, key, Reflect.get(mergeObject, key));
2479
+ }
2480
+ for (const [key, value] of Object.entries(mixinObject)) {
2481
+ if (value === void 0) continue;
2482
+ if (key === EXPLICIT_USER_KEY && Reflect.get(merged, key) !== void 0) continue;
2483
+ Reflect.set(merged, key, value);
2484
+ }
2485
+ return merged;
2486
+ } catch {
2487
+ return {
2488
+ ...mixinObject,
2489
+ _redactionFailed: true,
2490
+ _logKey: RESERVED_LOG_KEYS.LOGGER_REDACTION_FAILED
2491
+ };
2492
+ }
2493
+ }
2494
+
2292
2495
  // src/server/utils/censor-raw-headers.util.ts
2293
2496
  function censorRawHeaders(raw, sensitive, censor) {
2294
2497
  return raw.map((entry, index) => {
@@ -2875,20 +3078,31 @@ var PASS_THROUGH = (value) => value;
2875
3078
  function resolveNameRedactor(options) {
2876
3079
  return buildNameRedactor(options, true, options.redactStrategy === "names");
2877
3080
  }
3081
+ function resolveRecordRedactor(options) {
3082
+ return buildNameRedactor(
3083
+ options,
3084
+ true,
3085
+ options.redactStrategy === "names",
3086
+ options.maxStringLength !== void 0
3087
+ );
3088
+ }
3089
+ function wholeRootKeys(options) {
3090
+ return /* @__PURE__ */ new Set(["logKey", "err", ...Object.keys(options.serializers)]);
3091
+ }
2878
3092
  function ownFieldPolicyOf(options) {
2879
3093
  return createOwnFieldPolicy(options.errorOwnFields, options.errorOwnFieldNames);
2880
3094
  }
2881
3095
  function namesInsideErrors(options) {
2882
3096
  return options.shouldDisableDefaultRedact ? void 0 : REDACT_COMMON_FIELDS;
2883
3097
  }
2884
- function buildNameRedactor(options, nestedErrorsAsData = false, coversNames = true) {
3098
+ function buildNameRedactor(options, nestedErrorsAsData = false, coversNames = true, forcesWalk = false) {
2885
3099
  const allNames = [
2886
3100
  ...options.shouldDisableDefaultRedact ? [] : REDACT_COMMON_FIELDS,
2887
3101
  ...options.redactPaths.flatMap((path2) => leafNameOf(path2) ?? [])
2888
3102
  ];
2889
3103
  const names = coversNames ? allNames : [];
2890
3104
  const ownFields = ownFieldPolicyOf(options);
2891
- const walks = names.length > 0 || ownFields.safe;
3105
+ const walks = names.length > 0 || ownFields.safe || forcesWalk;
2892
3106
  if (!walks && resolveRedactOption(options) === void 0) {
2893
3107
  return PASS_THROUGH;
2894
3108
  }
@@ -2929,16 +3143,10 @@ function buildSerializers(options, redactSerialized, ownFields) {
2929
3143
  )
2930
3144
  };
2931
3145
  }
2932
- function mergeMixinSafely(mergeObject, mixinObject) {
2933
- try {
2934
- return Object.assign({}, mixinObject, mergeObject);
2935
- } catch {
2936
- return {
2937
- ...mixinObject,
2938
- _redactionFailed: true,
2939
- _logKey: RESERVED_LOG_KEYS.LOGGER_REDACTION_FAILED
2940
- };
2941
- }
3146
+ function withEntryTextFinisher(logger, options) {
3147
+ const redact = buildNameRedactor(options);
3148
+ Reflect.set(logger, ENTRY_TEXT_FINISHER, createEntryTextFinisher(redact, options.maxStringLength));
3149
+ return logger;
2942
3150
  }
2943
3151
  function buildStreams(options, destinations, health) {
2944
3152
  return destinations.map((destination) => {
@@ -2954,8 +3162,20 @@ function buildStreams(options, destinations, health) {
2954
3162
  };
2955
3163
  });
2956
3164
  }
2957
- function buildFormatters(options, redactRecord) {
3165
+ function buildRecordFormatter(options, redactRecord) {
2958
3166
  const hostSerializesRequest = Object.hasOwn(options.serializers, "req");
3167
+ const maxStringLength = options.maxStringLength;
3168
+ const wholeRoots = wholeRootKeys(options);
3169
+ return (record) => {
3170
+ const redacted = redactRecord(
3171
+ hostSerializesRequest ? record : withSerializedRequest(record, options.http.secretPathSegments),
3172
+ true
3173
+ );
3174
+ const bounded = maxStringLength === void 0 ? redacted : cutStrings(redacted, maxStringLength, wholeRoots);
3175
+ return withSemconvException(withEventName(bounded, options.eventNameField), options.errorFormat);
3176
+ };
3177
+ }
3178
+ function buildFormatters(options, redactRecord, redactBindings) {
2959
3179
  return {
2960
3180
  // Emit the level as a string label instead of the numeric code — easier
2961
3181
  // for log aggregators. Trace context is injected via `mixin`, never via
@@ -2970,26 +3190,20 @@ function buildFormatters(options, redactRecord) {
2970
3190
  // consumer's extra metadata instead of silently dropping it. Runs ONCE, at
2971
3191
  // logger construction — no per-entry cost. `true`: bindings are a record
2972
3192
  // root, iterated rather than serialized.
2973
- bindings: (bindings) => redactRecord(bindings, true),
3193
+ bindings: (bindings) => redactBindings(bindings, true),
2974
3194
  // The name-walk redactor runs here, on the merged record (mixin output +
2975
3195
  // the caller's object), which is exactly the surface a caller controls.
2976
3196
  // `base` and child bindings are NOT visible at this hook — they are
2977
3197
  // library-owned (`service`, the `@InjectLogger` context) and carry nothing
2978
3198
  // sensitive, which `pino-factory.spec.ts` pins.
2979
- log: (record) => withSemconvException(
2980
- withEventName(
2981
- redactRecord(
2982
- hostSerializesRequest ? record : withSerializedRequest(record, options.http.secretPathSegments),
2983
- true
2984
- ),
2985
- options.eventNameField
2986
- ),
2987
- options.errorFormat
2988
- )
3199
+ log: buildRecordFormatter(options, redactRecord)
2989
3200
  };
2990
3201
  }
2991
3202
  function buildPinoInstance(options, logContext, destinations, health) {
2992
- const redactRecord = resolveNameRedactor(options);
3203
+ if (options.maxStringLength !== void 0) {
3204
+ refuseCensorBeyondLimit(options.redactCensor, options.maxStringLength);
3205
+ }
3206
+ const redactRecord = resolveRecordRedactor(options);
2993
3207
  const redactSerialized = buildNameRedactor(options);
2994
3208
  const ownFields = ownFieldPolicyOf(options);
2995
3209
  const redactOption = resolveRedactOption(options);
@@ -3009,12 +3223,13 @@ function buildPinoInstance(options, logContext, destinations, health) {
3009
3223
  // is encoded as a JSON string here: a quote, a backslash or a newline in it must
3010
3224
  // neither break the line nor add fields to it.
3011
3225
  timestamp: () => `,"time":${JSON.stringify(String(options.timestamp()))}`,
3012
- formatters: buildFormatters(options, redactRecord),
3226
+ formatters: buildFormatters(options, redactRecord, resolveNameRedactor(options)),
3013
3227
  serializers: buildSerializers(options, redactSerialized, ownFields),
3014
3228
  mixin: createTraceContextMixin(logContext, options.otel),
3015
3229
  mixinMergeStrategy: mergeMixinSafely
3016
3230
  };
3017
- return pino(pinoOptions, pino.multistream(buildStreams(options, destinations, health)));
3231
+ const streams = pino.multistream(buildStreams(options, destinations, health));
3232
+ return withEntryTextFinisher(pino(pinoOptions, streams), options);
3018
3233
  }
3019
3234
  var DROP_REPORT_INTERVAL_MS = 1e4;
3020
3235
  function countInWindow(records, destination, now) {
@@ -3907,6 +4122,30 @@ function describeFailure(cause) {
3907
4122
  return "unreadable value";
3908
4123
  }
3909
4124
  }
4125
+ function productionRefusal() {
4126
+ return new Error(
4127
+ "[PrettyDevDestination] refused in production (NODE_ENV=production): it renders ANSI colour through a main-thread transform. Use DefaultStdoutDestination, or register PrettyDevDestination only outside production."
4128
+ );
4129
+ }
4130
+ async function buildTransform(view) {
4131
+ const { build } = await import('pino-pretty');
4132
+ return build({
4133
+ ...DEFAULT_VIEW,
4134
+ ...view,
4135
+ // AFTER the consumer's view, deliberately. Omitting `destination` from
4136
+ // `PrettyViewOptions` states that the library owns the sink; applying it
4137
+ // last is what ENFORCES it, including against an untyped caller reaching
4138
+ // in from JavaScript. A redirected stream would route around the fan-out
4139
+ // and the last-resort rescue.
4140
+ destination: process.stdout
4141
+ });
4142
+ }
4143
+ function initFailure(cause) {
4144
+ return new Error(
4145
+ isPinoPrettyMissing(cause) ? "[PrettyDevDestination] pino-pretty is not installed. Install it as a peer dependency (`pnpm add -D pino-pretty`) or remove PrettyDevDestination from `destinations`." : `[PrettyDevDestination] pino-pretty failed to start: ${describeFailure(cause)}`,
4146
+ { cause }
4147
+ );
4148
+ }
3910
4149
  var PrettyDevDestination = class {
3911
4150
  /**
3912
4151
  * @param opts.minLevel — Optional minimum level filter applied by the
@@ -3961,11 +4200,15 @@ var PrettyDevDestination = class {
3961
4200
  * message telling the consumer to install it or drop this destination.
3962
4201
  */
3963
4202
  async onInit() {
3964
- this.refuseInProduction();
4203
+ if (process.env["NODE_ENV"] === "production") {
4204
+ this.initFailed = true;
4205
+ throw productionRefusal();
4206
+ }
3965
4207
  try {
3966
- this.stream = await this.buildTransform();
4208
+ this.stream = await buildTransform(this.view);
3967
4209
  } catch (cause) {
3968
- throw this.initFailure(cause);
4210
+ this.initFailed = true;
4211
+ throw initFailure(cause);
3969
4212
  }
3970
4213
  this.flushBuffer((payload) => {
3971
4214
  try {
@@ -3975,46 +4218,6 @@ var PrettyDevDestination = class {
3975
4218
  }
3976
4219
  });
3977
4220
  }
3978
- /** Refuse to start when `NODE_ENV` is `production`. */
3979
- refuseInProduction() {
3980
- if (process.env["NODE_ENV"] === "production") {
3981
- this.initFailed = true;
3982
- throw new Error(
3983
- "[PrettyDevDestination] refused in production (NODE_ENV=production): it renders ANSI colour through a main-thread transform. Use DefaultStdoutDestination, or register PrettyDevDestination only outside production."
3984
- );
3985
- }
3986
- }
3987
- /**
3988
- * Resolve `pino-pretty` and build the colorized transform that renders to `process.stdout`.
3989
- *
3990
- * @returns The transform every entry is written to.
3991
- */
3992
- async buildTransform() {
3993
- const { build } = await import('pino-pretty');
3994
- return build({
3995
- ...DEFAULT_VIEW,
3996
- ...this.view,
3997
- // AFTER the consumer's view, deliberately. Omitting `destination` from
3998
- // `PrettyViewOptions` states that the library owns the sink; applying it
3999
- // last is what ENFORCES it, including against an untyped caller reaching
4000
- // in from JavaScript. A redirected stream would route around the fan-out
4001
- // and the last-resort rescue.
4002
- destination: process.stdout
4003
- });
4004
- }
4005
- /**
4006
- * Mark the destination as failed and build the error `onInit` rejects with.
4007
- *
4008
- * @param cause - What the import or `build()` threw.
4009
- * @returns The error to throw.
4010
- */
4011
- initFailure(cause) {
4012
- this.initFailed = true;
4013
- return new Error(
4014
- isPinoPrettyMissing(cause) ? "[PrettyDevDestination] pino-pretty is not installed. Install it as a peer dependency (`pnpm add -D pino-pretty`) or remove PrettyDevDestination from `destinations`." : `[PrettyDevDestination] pino-pretty failed to start: ${describeFailure(cause)}`,
4015
- { cause }
4016
- );
4017
- }
4018
4221
  /**
4019
4222
  * Write a serialized NDJSON entry to the pretty transform.
4020
4223
  *
@@ -4355,23 +4558,23 @@ var MAX_CODE_LENGTH = 128;
4355
4558
  function isCount(value) {
4356
4559
  return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
4357
4560
  }
4358
- function isRecord2(value) {
4561
+ function isRecord3(value) {
4359
4562
  return typeof value === "object" && value !== null;
4360
4563
  }
4361
4564
  function exceptionFields(error) {
4362
4565
  try {
4363
- if (!isRecord2(error) || typeof error["getResponse"] !== "function") return {};
4566
+ if (!isRecord3(error) || typeof error["getResponse"] !== "function") return {};
4364
4567
  const response = error["getResponse"]();
4365
- if (!isRecord2(response)) return {};
4568
+ if (!isRecord3(response)) return {};
4366
4569
  const nested = response["error"];
4367
- const carrier = isRecord2(nested) && typeof nested["code"] === "string" ? nested : response;
4570
+ const carrier = isRecord3(nested) && typeof nested["code"] === "string" ? nested : response;
4368
4571
  const fields = {};
4369
4572
  const code = carrier["code"];
4370
4573
  if (typeof code === "string") {
4371
4574
  fields["errorCode"] = code.slice(0, MAX_CODE_LENGTH);
4372
4575
  }
4373
4576
  const details = carrier["details"];
4374
- if (isRecord2(details)) {
4577
+ if (isRecord3(details)) {
4375
4578
  fields["errorDetails"] = details;
4376
4579
  }
4377
4580
  return fields;