@c9up/spectrum 0.1.18 → 0.1.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/README.md +33 -7
  2. package/dist/Logger.d.ts +6 -2
  3. package/dist/Logger.d.ts.map +1 -1
  4. package/dist/Logger.js +214 -80
  5. package/dist/Logger.js.map +1 -1
  6. package/dist/LoggerManager.d.ts +5 -0
  7. package/dist/LoggerManager.d.ts.map +1 -1
  8. package/dist/LoggerManager.js +10 -3
  9. package/dist/LoggerManager.js.map +1 -1
  10. package/dist/RustLogBridge.d.ts +27 -2
  11. package/dist/RustLogBridge.d.ts.map +1 -1
  12. package/dist/RustLogBridge.js +45 -31
  13. package/dist/RustLogBridge.js.map +1 -1
  14. package/dist/SpectrumProvider.d.ts +6 -2
  15. package/dist/SpectrumProvider.d.ts.map +1 -1
  16. package/dist/SpectrumProvider.js +18 -12
  17. package/dist/SpectrumProvider.js.map +1 -1
  18. package/dist/channels/ConsoleChannel.d.ts +8 -1
  19. package/dist/channels/ConsoleChannel.d.ts.map +1 -1
  20. package/dist/channels/ConsoleChannel.js +18 -14
  21. package/dist/channels/ConsoleChannel.js.map +1 -1
  22. package/dist/channels/FileChannel.d.ts +32 -9
  23. package/dist/channels/FileChannel.d.ts.map +1 -1
  24. package/dist/channels/FileChannel.js +264 -202
  25. package/dist/channels/FileChannel.js.map +1 -1
  26. package/dist/errors.d.ts +9 -0
  27. package/dist/errors.d.ts.map +1 -0
  28. package/dist/errors.js +13 -0
  29. package/dist/errors.js.map +1 -0
  30. package/dist/index.d.ts +7 -4
  31. package/dist/index.d.ts.map +1 -1
  32. package/dist/index.js +4 -2
  33. package/dist/index.js.map +1 -1
  34. package/dist/jsonLine.d.ts +49 -0
  35. package/dist/jsonLine.d.ts.map +1 -0
  36. package/dist/jsonLine.js +165 -0
  37. package/dist/jsonLine.js.map +1 -0
  38. package/dist/redact.d.ts +16 -3
  39. package/dist/redact.d.ts.map +1 -1
  40. package/dist/redact.js +121 -10
  41. package/dist/redact.js.map +1 -1
  42. package/dist/sanitize.d.ts +11 -5
  43. package/dist/sanitize.d.ts.map +1 -1
  44. package/dist/sanitize.js +36 -12
  45. package/dist/sanitize.js.map +1 -1
  46. package/dist/services/main.d.ts.map +1 -1
  47. package/dist/services/main.js +12 -1
  48. package/dist/services/main.js.map +1 -1
  49. package/dist/stdSerializers.d.ts +48 -0
  50. package/dist/stdSerializers.d.ts.map +1 -0
  51. package/dist/stdSerializers.js +129 -0
  52. package/dist/stdSerializers.js.map +1 -0
  53. package/dist/stringify.d.ts +33 -0
  54. package/dist/stringify.d.ts.map +1 -0
  55. package/dist/stringify.js +148 -0
  56. package/dist/stringify.js.map +1 -0
  57. package/dist/targets.d.ts +29 -7
  58. package/dist/targets.d.ts.map +1 -1
  59. package/dist/targets.js +130 -31
  60. package/dist/targets.js.map +1 -1
  61. package/dist/testing/FakeLogger.js +20 -5
  62. package/dist/testing/FakeLogger.js.map +1 -1
  63. package/dist/types.d.ts +71 -3
  64. package/dist/types.d.ts.map +1 -1
  65. package/dist/types.js +21 -3
  66. package/dist/types.js.map +1 -1
  67. package/package.json +1 -1
  68. package/src/Logger.ts +277 -85
  69. package/src/LoggerManager.ts +10 -3
  70. package/src/RustLogBridge.ts +59 -30
  71. package/src/SpectrumProvider.ts +31 -18
  72. package/src/channels/ConsoleChannel.ts +30 -14
  73. package/src/channels/FileChannel.ts +319 -220
  74. package/src/errors.ts +13 -0
  75. package/src/index.ts +17 -3
  76. package/src/jsonLine.ts +223 -0
  77. package/src/redact.ts +133 -9
  78. package/src/sanitize.ts +36 -12
  79. package/src/services/main.ts +13 -1
  80. package/src/stdSerializers.ts +147 -0
  81. package/src/stringify.ts +175 -0
  82. package/src/targets.ts +193 -42
  83. package/src/testing/FakeLogger.ts +23 -5
  84. package/src/types.ts +100 -5
  85. package/stubs/config/logger.stub +11 -1
@@ -0,0 +1,175 @@
1
+ /**
2
+ * How a log line is turned into JSON without ever losing it.
3
+ *
4
+ * A bare `JSON.stringify(entry)` throws on a circular reference or a BigInt,
5
+ * and a throw there costs the whole line — every field of it, on every
6
+ * channel. Circular payloads are ordinary (an ORM model with a back-reference,
7
+ * an HTTP client error carrying its request), so the line that explains a
8
+ * failure is the one most likely to vanish.
9
+ *
10
+ * pino's answer, mirrored: `JSON.stringify` first, because it is fast and
11
+ * exact; when it throws, the field is written again by a bounded walker that
12
+ * prints a cycle as `"[Circular]"`, a BigInt as a number, anything deeper than
13
+ * `depthLimit` as `"[Object]"` / `"[Array]"`, and stops after `edgeLimit`
14
+ * entries. Each top-level field falls back on its own, so one bad field does
15
+ * not degrade the others.
16
+ */
17
+
18
+ export interface StringifyLimits {
19
+ /** How deep the fallback walks before writing `"[Object]"`. Default 5. */
20
+ depthLimit: number;
21
+ /** How many entries of one object or array the fallback writes. Default 100. */
22
+ edgeLimit: number;
23
+ }
24
+
25
+ export const DEFAULT_STRINGIFY_LIMITS: StringifyLimits = {
26
+ depthLimit: 5,
27
+ edgeLimit: 100,
28
+ };
29
+
30
+ const UNSERIALIZABLE =
31
+ '"[unable to serialize, circular reference is too complex to analyze]"';
32
+
33
+ /** Whether a configured limit is one the walker can honour. */
34
+ export function isStringifyLimit(value: unknown): value is number {
35
+ return typeof value === "number" && Number.isInteger(value) && value > 0;
36
+ }
37
+
38
+ /**
39
+ * One JSON object, never throwing. Keys whose value is `undefined` or a
40
+ * function are left out, as `JSON.stringify` leaves them out.
41
+ */
42
+ export function stringifyRecord(
43
+ record: Record<string, unknown>,
44
+ limits: StringifyLimits = DEFAULT_STRINGIFY_LIMITS,
45
+ ): string {
46
+ try {
47
+ return JSON.stringify(record);
48
+ } catch {
49
+ // Field by field, so the fallback's limits count from each field and a
50
+ // field that cannot be written at all is the only one that says so.
51
+ let out = "";
52
+ for (const key of Object.keys(record)) {
53
+ const value = stringifyValue(readField(record, key), limits);
54
+ if (value === undefined) continue;
55
+ out += `${out === "" ? "" : ","}${JSON.stringify(key)}:${value}`;
56
+ }
57
+ return `{${out}}`;
58
+ }
59
+ }
60
+
61
+ /** One value, never throwing; `undefined` when JSON would omit it. */
62
+ export function stringifyValue(
63
+ value: unknown,
64
+ limits: StringifyLimits = DEFAULT_STRINGIFY_LIMITS,
65
+ ): string | undefined {
66
+ try {
67
+ return JSON.stringify(value);
68
+ } catch {
69
+ try {
70
+ return walk("", value, [], limits);
71
+ } catch {
72
+ return UNSERIALIZABLE;
73
+ }
74
+ }
75
+ }
76
+
77
+ /** A getter that throws is a value that cannot be written, not a lost line. */
78
+ function readField(record: object, key: string): unknown {
79
+ try {
80
+ return Reflect.get(record, key);
81
+ } catch {
82
+ return "[unreadable]";
83
+ }
84
+ }
85
+
86
+ function hasToJSON(value: object): value is { toJSON(key: string): unknown } {
87
+ return "toJSON" in value && typeof value.toJSON === "function";
88
+ }
89
+
90
+ function itemCount(count: number): string {
91
+ return count === 1 ? "1 item" : `${count} items`;
92
+ }
93
+
94
+ /**
95
+ * The bounded fallback. `stack` holds the objects on the current path, so a
96
+ * value shared by two branches is written twice and only a real cycle is cut.
97
+ */
98
+ function walk(
99
+ key: string,
100
+ input: unknown,
101
+ stack: object[],
102
+ limits: StringifyLimits,
103
+ ): string | undefined {
104
+ let value = input;
105
+ if (typeof value === "object" && value !== null && hasToJSON(value)) {
106
+ value = value.toJSON(key);
107
+ }
108
+ switch (typeof value) {
109
+ case "string":
110
+ return JSON.stringify(value);
111
+ case "number":
112
+ return Number.isFinite(value) ? String(value) : "null";
113
+ case "boolean":
114
+ return value ? "true" : "false";
115
+ case "bigint":
116
+ return String(value);
117
+ case "object": {
118
+ if (value === null) return "null";
119
+ if (stack.includes(value)) return '"[Circular]"';
120
+ if (Array.isArray(value)) return walkArray(value, stack, limits);
121
+ return walkObject(value, stack, limits);
122
+ }
123
+ default:
124
+ // undefined, function, symbol: omitted, as JSON omits them.
125
+ return undefined;
126
+ }
127
+ }
128
+
129
+ function walkArray(
130
+ value: unknown[],
131
+ stack: object[],
132
+ limits: StringifyLimits,
133
+ ): string {
134
+ if (value.length === 0) return "[]";
135
+ if (stack.length + 1 > limits.depthLimit) return '"[Array]"';
136
+ stack.push(value);
137
+ const shown = Math.min(value.length, limits.edgeLimit);
138
+ const parts: string[] = [];
139
+ for (let i = 0; i < shown; i++) {
140
+ parts.push(walk(String(i), value[i], stack, limits) ?? "null");
141
+ }
142
+ if (value.length > shown) {
143
+ parts.push(
144
+ JSON.stringify(`... ${itemCount(value.length - shown)} not stringified`),
145
+ );
146
+ }
147
+ stack.pop();
148
+ return `[${parts.join(",")}]`;
149
+ }
150
+
151
+ function walkObject(
152
+ value: object,
153
+ stack: object[],
154
+ limits: StringifyLimits,
155
+ ): string {
156
+ const keys = Object.keys(value);
157
+ if (keys.length === 0) return "{}";
158
+ if (stack.length + 1 > limits.depthLimit) return '"[Object]"';
159
+ stack.push(value);
160
+ const shown = Math.min(keys.length, limits.edgeLimit);
161
+ const parts: string[] = [];
162
+ for (let i = 0; i < shown; i++) {
163
+ const key = keys[i];
164
+ if (key === undefined) continue;
165
+ const written = walk(key, readField(value, key), stack, limits);
166
+ if (written !== undefined) parts.push(`${JSON.stringify(key)}:${written}`);
167
+ }
168
+ if (keys.length > shown) {
169
+ parts.push(
170
+ `"...":${JSON.stringify(`${itemCount(keys.length - shown)} not stringified`)}`,
171
+ );
172
+ }
173
+ stack.pop();
174
+ return `{${parts.join(",")}}`;
175
+ }
package/src/targets.ts CHANGED
@@ -16,16 +16,30 @@
16
16
 
17
17
  import { ConsoleChannel } from "./channels/ConsoleChannel.js";
18
18
  import { FileChannel } from "./channels/FileChannel.js";
19
- import type { LogChannel, LogEntry, LogLevelWithSilent } from "./types.js";
19
+ import { SpectrumError } from "./errors.js";
20
+ import { jsonLine } from "./jsonLine.js";
21
+ import type {
22
+ LineWritable,
23
+ LogChannel,
24
+ LogConfig,
25
+ LogEntry,
26
+ LogLevelWithSilent,
27
+ } from "./types.js";
20
28
  import {
21
29
  isLogLevelWithSilent,
22
30
  LOG_LEVEL_ORDER,
23
31
  levelThreshold,
24
32
  } from "./types.js";
25
33
 
26
- /** One transport entry (AdonisJS `TransportTargetOptions`). */
34
+ /**
35
+ * One transport entry (AdonisJS `TransportTargetOptions`).
36
+ *
37
+ * `target` names `pino-pretty` or `pino/file`, or is a {@link LogChannel}:
38
+ * a destination spectrum has no built-in channel for is plugged in that way,
39
+ * with the target's own level.
40
+ */
27
41
  export interface TransportTargetOptions {
28
- target: string;
42
+ target: string | LogChannel;
29
43
  options?: Record<string, unknown>;
30
44
  level?: LogLevelWithSilent | string;
31
45
  }
@@ -33,13 +47,20 @@ export interface TransportTargetOptions {
33
47
  /** Options `targets.file()` accepts. `destination` is a path, or an fd. */
34
48
  export interface FileTargetOptions {
35
49
  destination?: string | number;
50
+ /** `false` starts the file over instead of appending. Default true. */
51
+ append?: boolean;
36
52
  maxSizeBytes?: number;
37
53
  maxFiles?: number;
54
+ maxBufferBytes?: number;
38
55
  [key: string]: unknown;
39
56
  }
40
57
 
41
- /** Options `targets.pretty()` accepts (pino-pretty's, which we ignore). */
58
+ /**
59
+ * Options `targets.pretty()` accepts. `destination` (1 or 2) sends every
60
+ * level to that stream; pino-pretty's formatting options are not read.
61
+ */
42
62
  export interface PrettyTargetOptions {
63
+ destination?: number;
43
64
  [key: string]: unknown;
44
65
  }
45
66
 
@@ -126,11 +147,12 @@ class LeveledChannel implements LogChannel {
126
147
 
127
148
  /**
128
149
  * Forwarded because the wrapper is now what the provider holds, and a
129
- * FileChannel that is never closed keeps its stream open past shutdown.
150
+ * FileChannel that is never closed keeps its file open past shutdown.
151
+ * The inner promise is handed back: dropping it let shutdown resolve
152
+ * before any line of a file target was flushed.
130
153
  */
131
- close(): void {
132
- const inner: LogChannel & { close?: () => void } = this.#inner;
133
- inner.close?.();
154
+ close(): void | Promise<void> {
155
+ return this.#inner.close?.();
134
156
  }
135
157
  }
136
158
 
@@ -140,8 +162,9 @@ function atLevel(channel: LogChannel, level: string | undefined): LogChannel {
140
162
  if (!isLogLevelWithSilent(level)) {
141
163
  // A level nobody can act on is a config error, and the failure mode of
142
164
  // ignoring it is the destination receiving everything.
143
- throw new Error(
144
- `[spectrum] Unknown transport target level "${level}". Use one of: ${Object.keys(LOG_LEVEL_ORDER).join(", ")}, silent.`,
165
+ throw new SpectrumError(
166
+ "E_SPECTRUM_UNKNOWN_LEVEL",
167
+ `Unknown transport target level "${level}". Use one of: ${Object.keys(LOG_LEVEL_ORDER).join(", ")}, silent.`,
145
168
  );
146
169
  }
147
170
  const threshold = levelThreshold(level);
@@ -150,13 +173,33 @@ function atLevel(channel: LogChannel, level: string | undefined): LogChannel {
150
173
  return new LeveledChannel(channel, threshold);
151
174
  }
152
175
 
176
+ /**
177
+ * JSON to a file descriptor, every level to that one descriptor, as pino's
178
+ * file target writes it. Splitting by level sent a `destination: 1` app's
179
+ * errors to stderr, where a collector reading stdout never saw them, and
180
+ * ignored any other descriptor. No destination means 1, as upstream.
181
+ */
182
+ function descriptorChannel(destination: unknown): LogChannel {
183
+ if (destination === undefined || destination === 1) {
184
+ return new ConsoleChannel("json", { stream: "stdout" });
185
+ }
186
+ if (destination === 2)
187
+ return new ConsoleChannel("json", { stream: "stderr" });
188
+ if (typeof destination === "number")
189
+ return new FileChannel({ fd: destination });
190
+ throw new SpectrumError(
191
+ "E_SPECTRUM_INVALID_FILE_OPTIONS",
192
+ `pino/file destination must be a path or a file descriptor, got ${typeof destination}`,
193
+ );
194
+ }
195
+
153
196
  /**
154
197
  * Turn transport targets into the channels spectrum actually writes through.
155
198
  *
156
199
  * `pino-pretty` is the human-readable console; `pino/file` writes JSON — to a
157
- * file when `destination` is a path, and to the console when it is a file
158
- * descriptor, which is what `destination: 1` means in a containerised app that
159
- * ships stdout to its log collector.
200
+ * file when `destination` is a path, and to that descriptor when it is one:
201
+ * `destination: 1` is stdout, which a containerised app ships to its log
202
+ * collector.
160
203
  *
161
204
  * A target with no level of its own inherits `inheritedLevel`, the level of the
162
205
  * logger it belongs to — upstream's `defineConfig` fills the same gap, by
@@ -167,34 +210,142 @@ export function channelsFromTargets(
167
210
  list: readonly TransportTargetOptions[],
168
211
  inheritedLevel?: LogLevelWithSilent | string,
169
212
  ): LogChannel[] {
170
- const channels: LogChannel[] = [];
171
- for (const entry of list) {
172
- const level = entry.level ?? inheritedLevel;
173
- if (entry.target === "pino-pretty") {
174
- channels.push(atLevel(new ConsoleChannel("pretty"), level));
175
- continue;
176
- }
177
- const destination = entry.options?.destination;
178
- if (typeof destination === "string") {
179
- channels.push(
180
- atLevel(
181
- new FileChannel({
182
- path: destination,
183
- ...(typeof entry.options?.maxSizeBytes === "number"
184
- ? { maxSizeBytes: entry.options.maxSizeBytes }
185
- : {}),
186
- ...(typeof entry.options?.maxFiles === "number"
187
- ? { maxFiles: entry.options.maxFiles }
188
- : {}),
189
- }),
190
- level,
191
- ),
192
- );
193
- continue;
194
- }
195
- // A descriptor (or nothing) means the process's own output, as JSON —
196
- // the shape a log collector parses.
197
- channels.push(atLevel(new ConsoleChannel("json"), level));
213
+ return list.map((entry) =>
214
+ atLevel(channelForTarget(entry), entry.level ?? inheritedLevel),
215
+ );
216
+ }
217
+
218
+ /**
219
+ * The channel a target describes.
220
+ *
221
+ * Any other target name used to fall through to JSON on stdout, so a config
222
+ * shipping logs to Loki or a socket booted fine and nothing reached the sink.
223
+ * Upstream fails when it cannot load a target; so does this.
224
+ */
225
+ function channelForTarget(entry: TransportTargetOptions): LogChannel {
226
+ const { target } = entry;
227
+ const options = entry.options ?? {};
228
+ if (typeof target !== "string") return target;
229
+ if (target === "pino-pretty") return prettyChannel(options.destination);
230
+ if (target === "pino/file") {
231
+ const destination = options.destination;
232
+ if (typeof destination !== "string") return descriptorChannel(destination);
233
+ return new FileChannel({
234
+ path: destination,
235
+ append: optionalBoolean(options, "append"),
236
+ maxSizeBytes: optionalNumber(options, "maxSizeBytes"),
237
+ maxFiles: optionalNumber(options, "maxFiles"),
238
+ maxBufferBytes: optionalNumber(options, "maxBufferBytes"),
239
+ });
240
+ }
241
+ throw new SpectrumError(
242
+ "E_SPECTRUM_UNSUPPORTED_TARGET",
243
+ `Transport target "${target}" is not supported: spectrum builds "pino-pretty" and "pino/file". Pass a LogChannel as the target to write anywhere else.`,
244
+ );
245
+ }
246
+
247
+ function prettyChannel(destination: unknown): LogChannel {
248
+ if (destination === undefined) return new ConsoleChannel("pretty");
249
+ if (destination === 1)
250
+ return new ConsoleChannel("pretty", { stream: "stdout" });
251
+ if (destination === 2)
252
+ return new ConsoleChannel("pretty", { stream: "stderr" });
253
+ throw new SpectrumError(
254
+ "E_SPECTRUM_UNSUPPORTED_TARGET",
255
+ `pino-pretty destination ${JSON.stringify(destination)} is not supported: use 1 or 2, or a pino/file target for a file.`,
256
+ );
257
+ }
258
+
259
+ /** A number option, or undefined when absent; any other type is a config error. */
260
+ function optionalNumber(
261
+ options: Record<string, unknown>,
262
+ key: string,
263
+ ): number | undefined {
264
+ const value = options[key];
265
+ if (value === undefined || typeof value === "number") return value;
266
+ throw invalidOption(key, "number", value);
267
+ }
268
+
269
+ /** A boolean option, or undefined when absent; any other type is a config error. */
270
+ function optionalBoolean(
271
+ options: Record<string, unknown>,
272
+ key: string,
273
+ ): boolean | undefined {
274
+ const value = options[key];
275
+ if (value === undefined || typeof value === "boolean") return value;
276
+ throw invalidOption(key, "boolean", value);
277
+ }
278
+
279
+ function invalidOption(
280
+ key: string,
281
+ type: string,
282
+ value: unknown,
283
+ ): SpectrumError {
284
+ return new SpectrumError(
285
+ "E_SPECTRUM_INVALID_FILE_OPTIONS",
286
+ `pino/file option ${key} must be a ${type}, got ${typeof value}`,
287
+ );
288
+ }
289
+
290
+ /** JSON lines to anything with a `write(line)` method. */
291
+ class WritableChannel implements LogChannel {
292
+ readonly name = "destination";
293
+ readonly #target: LineWritable;
294
+
295
+ constructor(target: LineWritable) {
296
+ this.#target = target;
297
+ }
298
+
299
+ write(entry: LogEntry): void {
300
+ this.#target.write(`${jsonLine(entry)}\n`);
301
+ }
302
+ }
303
+
304
+ function isLineWritable(value: unknown): value is LineWritable {
305
+ return (
306
+ typeof value === "object" &&
307
+ value !== null &&
308
+ "write" in value &&
309
+ typeof value.write === "function"
310
+ );
311
+ }
312
+
313
+ /** The channel a logger's `destination` option names. */
314
+ export function destinationChannel(destination: unknown): LogChannel {
315
+ if (typeof destination === "string")
316
+ return new FileChannel({ path: destination });
317
+ if (typeof destination === "number") return descriptorChannel(destination);
318
+ if (isLineWritable(destination)) return new WritableChannel(destination);
319
+ throw new SpectrumError(
320
+ "E_SPECTRUM_UNSUPPORTED_TARGET",
321
+ "destination must be a path, a file descriptor or an object with a write(line) method",
322
+ );
323
+ }
324
+
325
+ /**
326
+ * The channels a config's `destination` or `transport` describe, or
327
+ * `undefined` when it declares neither. `destination` wins over `transport`,
328
+ * as upstream; a transport is either a `targets` list or one
329
+ * `{ target, options }`.
330
+ */
331
+ export function channelsFromConfig(
332
+ config: Pick<LogConfig, "destination" | "transport">,
333
+ level: LogLevelWithSilent | string | undefined,
334
+ ): LogChannel[] | undefined {
335
+ if (config.destination !== undefined) {
336
+ return [destinationChannel(config.destination)];
337
+ }
338
+ const transport = config.transport;
339
+ if (transport === undefined) return undefined;
340
+ if ("target" in transport) return channelsFromTargets([transport], level);
341
+ if (Reflect.get(transport, "pipeline") !== undefined) {
342
+ throw new SpectrumError(
343
+ "E_SPECTRUM_UNSUPPORTED_TARGET",
344
+ "transport.pipeline is not supported: declare targets, or pass channels",
345
+ );
346
+ }
347
+ if (transport.targets === undefined || transport.targets.length === 0) {
348
+ return undefined;
198
349
  }
199
- return channels;
350
+ return channelsFromTargets(transport.targets, level);
200
351
  }
@@ -9,7 +9,7 @@
9
9
  */
10
10
 
11
11
  import type { LogChannel, LogEntry, LogLevel } from "../types.js";
12
- import { logEntryExtras } from "../types.js";
12
+ import { LOG_LEVEL_ORDER, logEntryExtras } from "../types.js";
13
13
 
14
14
  export interface FakeLoggerPredicate {
15
15
  /** Substring match against `entry.message`. */
@@ -133,9 +133,9 @@ function safeStringify(value: unknown): string {
133
133
  }
134
134
  }
135
135
 
136
- function deepClone<T>(value: T): T {
136
+ function deepClone(entry: LogEntry): LogEntry {
137
137
  try {
138
- return structuredClone(value);
138
+ return structuredClone(entry);
139
139
  } catch {
140
140
  // `data` can carry functions / class instances that structuredClone
141
141
  // rejects (DataCloneError). For a test capture a perfect clone isn't
@@ -144,9 +144,27 @@ function deepClone<T>(value: T): T {
144
144
  // instead of thrown away (the throw propagated into Logger.log's swallow,
145
145
  // dropping the entry and making assertLogged fail with "no entry").
146
146
  try {
147
- return JSON.parse(safeStringify(value));
147
+ const parsed: unknown = JSON.parse(safeStringify(entry));
148
+ return isLogEntry(parsed) ? parsed : entry;
148
149
  } catch {
149
- return value;
150
+ return entry;
150
151
  }
151
152
  }
152
153
  }
154
+
155
+ /** What came back from the JSON round-trip still has the shape of an entry. */
156
+ function isLogEntry(value: unknown): value is LogEntry {
157
+ return (
158
+ typeof value === "object" &&
159
+ value !== null &&
160
+ "level" in value &&
161
+ typeof value.level === "string" &&
162
+ value.level in LOG_LEVEL_ORDER &&
163
+ "message" in value &&
164
+ typeof value.message === "string" &&
165
+ "module" in value &&
166
+ typeof value.module === "string" &&
167
+ "timestamp" in value &&
168
+ typeof value.timestamp === "string"
169
+ );
170
+ }
package/src/types.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import { SpectrumError } from "./errors.js";
2
+ import type { LineFormatters, TimestampOption } from "./jsonLine.js";
1
3
  import type { TransportTargetOptions } from "./targets.js";
2
4
  /**
3
5
  * Spectrum types.
@@ -46,9 +48,25 @@ export function isLogLevelWithSilent(
46
48
  return typeof value === "string" && CONFIGURED_LEVELS.has(value);
47
49
  }
48
50
 
51
+ /**
52
+ * A configured level, checked.
53
+ *
54
+ * An unknown level is a config error, as it is upstream ("unknown level"):
55
+ * reading `ERROR` or `warning` as `info` meant an operator quieting production
56
+ * got more output, and no word about it.
57
+ */
58
+ export function assertLogLevel(value: unknown): LogLevelWithSilent {
59
+ if (isLogLevelWithSilent(value)) return value;
60
+ throw new SpectrumError(
61
+ "E_SPECTRUM_UNKNOWN_LEVEL",
62
+ `unknown level ${JSON.stringify(value) ?? String(value)}. Use one of: ${[...CONFIGURED_LEVELS].join(", ")}.`,
63
+ );
64
+ }
65
+
49
66
  /**
50
67
  * Narrow an untyped level — `process.env.LOG_LEVEL`, a CLI flag — to one the
51
- * config can name, falling back to `info`.
68
+ * config can name. Absent (or empty) falls back to `fallback`; set to
69
+ * something that is no level, it throws.
52
70
  *
53
71
  * Without it a config file has to assert the env string into the union, and an
54
72
  * assertion is the wrong tool for a value that comes from outside the program:
@@ -58,7 +76,8 @@ export function logLevel(
58
76
  raw: unknown,
59
77
  fallback: LogLevelWithSilent = "info",
60
78
  ): LogLevelWithSilent {
61
- return isLogLevelWithSilent(raw) ? raw : fallback;
79
+ if (raw === undefined || raw === "") return fallback;
80
+ return assertLogLevel(raw);
62
81
  }
63
82
 
64
83
  export interface LogEntry {
@@ -103,7 +122,44 @@ export type LogSerializer = (value: unknown) => unknown;
103
122
  /** Redaction config (pino `redact` parity). */
104
123
  export interface RedactOptions {
105
124
  paths: string[];
106
- censor?: string;
125
+ /**
126
+ * What a matched value becomes. A function is called with the value and
127
+ * the path it was found at (wildcards resolved). Default `[Redacted]`.
128
+ */
129
+ censor?: string | ((value: unknown, path: string[]) => unknown);
130
+ /** Remove matched keys instead of censoring them. */
131
+ remove?: boolean;
132
+ }
133
+
134
+ /** Called with each log call's arguments; calls `method` to write (pino `hooks.logMethod`). */
135
+ export type LogMethodHook = (
136
+ this: unknown,
137
+ args: unknown[],
138
+ method: (...args: unknown[]) => void,
139
+ level: number,
140
+ ) => void;
141
+
142
+ /** Fields to add to every line, computed per call (pino `mixin`). */
143
+ export type LogMixin = (
144
+ mergeObject: Record<string, unknown>,
145
+ level: number,
146
+ logger: unknown,
147
+ ) => Record<string, unknown>;
148
+
149
+ /** Options of `logger.child(bindings, options)`. */
150
+ export interface ChildOptions {
151
+ level?: LogLevelWithSilent;
152
+ /** Replaces the parent's redaction for this child. */
153
+ redact?: string[] | RedactOptions;
154
+ /** Added to (and overriding) the parent's serializers. */
155
+ serializers?: Record<string, LogSerializer>;
156
+ /** Appended to the parent's prefix, written before every message. */
157
+ msgPrefix?: string;
158
+ }
159
+
160
+ /** Anything with a `write(line)` method, used as a JSON destination. */
161
+ export interface LineWritable {
162
+ write(line: string): unknown;
107
163
  }
108
164
 
109
165
  /**
@@ -132,13 +188,50 @@ export interface LogConfig {
132
188
  * drives real output instead of being quietly ignored. Explicit `channels`
133
189
  * win when both are given.
134
190
  */
135
- transport?: { targets?: readonly TransportTargetOptions[] };
191
+ transport?:
192
+ | { targets?: readonly TransportTargetOptions[] }
193
+ | TransportTargetOptions;
194
+ /**
195
+ * Where JSON lines go when no `channels` are given: a file path, a file
196
+ * descriptor, or anything with a `write(line)` method. Wins over
197
+ * `transport`, as upstream.
198
+ */
199
+ destination?: string | number | LineWritable;
136
200
  /** Per-module level overrides — spectrum divergence. */
137
201
  modules?: Record<string, LogLevelWithSilent>;
138
202
  /** Keys / dot-paths to redact on the merging object before writing. */
139
203
  redact?: string[] | RedactOptions;
140
204
  /** Per-key value serializers (`err`/`error` handled by default). */
141
205
  serializers?: Record<string, LogSerializer>;
206
+ /**
207
+ * How deep a value JSON cannot write (a cycle, a BigInt) is walked before
208
+ * `"[Object]"` stands in for the rest. Default 5, as pino.
209
+ */
210
+ depthLimit?: number;
211
+ /** How many entries of one such object or array are written. Default 100, as pino. */
212
+ edgeLimit?: number;
213
+ /** The key a JSON line carries the message under. Default `msg`. */
214
+ messageKey?: string;
215
+ /** How a JSON line writes `time`. Default `'epoch'` (milliseconds). */
216
+ timestamp?: TimestampOption;
217
+ /** Fields on every JSON line. Default `{ pid, hostname }`; `null` for none. */
218
+ base?: Record<string, unknown> | null;
219
+ /** Reshape the level part and the merged fields of a JSON line. */
220
+ formatters?: LineFormatters;
221
+ /** The key an Error passed to a log call is written under. Default `err`. */
222
+ errorKey?: string;
223
+ /** Written before every message. */
224
+ msgPrefix?: string;
225
+ /** Fields added to every line, computed per call. A merging object wins over them. */
226
+ mixin?: LogMixin;
227
+ /** How the mixin's fields and the merging object combine. Default: merging object wins. */
228
+ mixinMergeStrategy?: (
229
+ mergeObject: Record<string, unknown>,
230
+ mixinObject: Record<string, unknown>,
231
+ ) => Record<string, unknown>;
232
+ hooks?: { logMethod?: LogMethodHook };
233
+ /** Called with every child logger created. */
234
+ onChild?: (child: unknown) => void;
142
235
  }
143
236
 
144
237
  /**
@@ -161,7 +254,9 @@ const RESERVED_ENTRY_KEYS = new Set<string>([
161
254
 
162
255
  /** Root-level merged fields (everything that is not a structural LogEntry key). */
163
256
  export function logEntryExtras(entry: LogEntry): Record<string, unknown> {
164
- const extras: Record<string, unknown> = {};
257
+ // Null prototype: a merged key named `__proto__` is a field to write, and
258
+ // assigned on an ordinary object it set the prototype and vanished.
259
+ const extras: Record<string, unknown> = Object.create(null);
165
260
  for (const key of Object.keys(entry)) {
166
261
  if (!RESERVED_ENTRY_KEYS.has(key)) extras[key] = entry[key];
167
262
  }
@@ -12,8 +12,18 @@ export default defineConfig({
12
12
  enabled: true,
13
13
  name: process.env.APP_NAME ?? 'app',
14
14
  // LOG_LEVEL comes from outside the program, so it is checked rather than
15
- // asserted: anything that is not a level reads as 'info'.
15
+ // asserted: unset reads as 'info', and a value that is no level throws.
16
16
  level: logLevel(process.env.LOG_LEVEL),
17
+ // A logged request or response carries every header as it came: the
18
+ // session cookie, the bearer token and the cookies set in reply are
19
+ // kept out of the line here.
20
+ redact: {
21
+ paths: [
22
+ 'req.headers.authorization',
23
+ 'req.headers.cookie',
24
+ 'res.headers["set-cookie"]',
25
+ ],
26
+ },
17
27
  transport: {
18
28
  targets: targets()
19
29
  .pushIf(!inProduction, targets.pretty())