@c9up/spectrum 0.1.20 → 0.1.21

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 (68) hide show
  1. package/README.md +12 -3
  2. package/dist/Logger.d.ts.map +1 -1
  3. package/dist/Logger.js +55 -24
  4. package/dist/Logger.js.map +1 -1
  5. package/dist/LoggerManager.d.ts +2 -1
  6. package/dist/LoggerManager.d.ts.map +1 -1
  7. package/dist/LoggerManager.js +15 -9
  8. package/dist/LoggerManager.js.map +1 -1
  9. package/dist/SpectrumProvider.d.ts.map +1 -1
  10. package/dist/SpectrumProvider.js +10 -5
  11. package/dist/SpectrumProvider.js.map +1 -1
  12. package/dist/channels/FileChannel.d.ts.map +1 -1
  13. package/dist/channels/FileChannel.js +10 -4
  14. package/dist/channels/FileChannel.js.map +1 -1
  15. package/dist/config.d.ts +10 -0
  16. package/dist/config.d.ts.map +1 -1
  17. package/dist/config.js +21 -3
  18. package/dist/config.js.map +1 -1
  19. package/dist/errors.d.ts +31 -6
  20. package/dist/errors.d.ts.map +1 -1
  21. package/dist/errors.js +33 -10
  22. package/dist/errors.js.map +1 -1
  23. package/dist/format.d.ts +23 -0
  24. package/dist/format.d.ts.map +1 -0
  25. package/dist/format.js +109 -0
  26. package/dist/format.js.map +1 -0
  27. package/dist/index.d.ts +1 -1
  28. package/dist/index.d.ts.map +1 -1
  29. package/dist/index.js +1 -1
  30. package/dist/index.js.map +1 -1
  31. package/dist/jsonLine.js +2 -2
  32. package/dist/jsonLine.js.map +1 -1
  33. package/dist/redact.d.ts.map +1 -1
  34. package/dist/redact.js +33 -6
  35. package/dist/redact.js.map +1 -1
  36. package/dist/services/main.d.ts.map +1 -1
  37. package/dist/services/main.js +2 -2
  38. package/dist/services/main.js.map +1 -1
  39. package/dist/stdSerializers.d.ts +10 -3
  40. package/dist/stdSerializers.d.ts.map +1 -1
  41. package/dist/stdSerializers.js +86 -6
  42. package/dist/stdSerializers.js.map +1 -1
  43. package/dist/targets.d.ts.map +1 -1
  44. package/dist/targets.js +24 -8
  45. package/dist/targets.js.map +1 -1
  46. package/dist/testing/FakeLogger.d.ts.map +1 -1
  47. package/dist/testing/FakeLogger.js +84 -26
  48. package/dist/testing/FakeLogger.js.map +1 -1
  49. package/dist/types.d.ts.map +1 -1
  50. package/dist/types.js +6 -2
  51. package/dist/types.js.map +1 -1
  52. package/package.json +7 -4
  53. package/src/Logger.ts +61 -34
  54. package/src/LoggerManager.ts +18 -12
  55. package/src/SpectrumProvider.ts +13 -10
  56. package/src/channels/FileChannel.ts +7 -10
  57. package/src/config.ts +27 -5
  58. package/src/errors.ts +92 -11
  59. package/src/format.ts +105 -0
  60. package/src/index.ts +1 -1
  61. package/src/jsonLine.ts +3 -3
  62. package/src/redact.ts +32 -7
  63. package/src/services/main.ts +2 -4
  64. package/src/stdSerializers.ts +89 -6
  65. package/src/targets.ts +23 -28
  66. package/src/testing/FakeLogger.ts +85 -31
  67. package/src/types.ts +6 -5
  68. package/stubs/config/logger.stub +8 -4
package/src/redact.ts CHANGED
@@ -9,7 +9,7 @@
9
9
  * password is written out in full.
10
10
  */
11
11
 
12
- import { SpectrumError } from "./errors.js";
12
+ import { E_SPECTRUM_INVALID_REDACT_PATH } from "./errors.js";
13
13
 
14
14
  /**
15
15
  * fast-redact's own tokenizer: a run of characters that is not `.`, `[` or
@@ -17,8 +17,8 @@ import { SpectrumError } from "./errors.js";
17
17
  */
18
18
  const PATH_TOKEN = /[^.[\]]+|\[(?:.)*?\]/g;
19
19
 
20
- function invalidPath(detail: string): SpectrumError {
21
- return new SpectrumError("E_SPECTRUM_INVALID_REDACT_PATH", detail);
20
+ function invalidPath(detail: string): Error {
21
+ return new E_SPECTRUM_INVALID_REDACT_PATH([detail]);
22
22
  }
23
23
 
24
24
  /**
@@ -117,16 +117,17 @@ export function redactPath(
117
117
  return node;
118
118
  }
119
119
 
120
- const keys = selectKeys(node, segment);
120
+ const view = writtenView(node, trail[trail.length - 1] ?? "");
121
+ const keys = selectKeys(view, segment);
121
122
  if (keys.length === 0) return node;
122
123
 
123
124
  const isLast = depth === tokens.length - 1;
124
125
  let copy: Record<string, unknown> | unknown[] | null = null;
125
126
  for (const key of keys) {
126
- const current = readKey(node, key);
127
+ const current = readKey(view, key);
127
128
  const path = [...trail, key];
128
129
  if (isLast && action.remove) {
129
- copy ??= Array.isArray(node) ? [...node] : copyObject(node);
130
+ copy ??= Array.isArray(view) ? [...view] : copyObject(view);
130
131
  removeKey(copy, key);
131
132
  continue;
132
133
  }
@@ -134,12 +135,36 @@ export function redactPath(
134
135
  ? action.censor(current, path)
135
136
  : redactPath(current, tokens, action, depth + 1, path);
136
137
  if (next === current) continue;
137
- copy ??= Array.isArray(node) ? [...node] : copyObject(node);
138
+ copy ??= Array.isArray(view) ? [...view] : copyObject(view);
138
139
  writeKey(copy, key, next);
139
140
  }
140
141
  return copy ?? node;
141
142
  }
142
143
 
144
+ /**
145
+ * The object a node is written as: what its `toJSON()` returns when it has
146
+ * one, else the node itself.
147
+ *
148
+ * NAMED DEVIATION — upstream's redactor walks the raw object and the line
149
+ * calls `toJSON()` afterwards. On a class instance whose fields are methods
150
+ * (an HTTP request: `headers()`), a path such as `req.headers.authorization`
151
+ * named no own key, matched nothing, and `toJSON()` then wrote the header in
152
+ * clear. A path is written against the shape the line shows, so it is
153
+ * applied to that shape. When nothing matches, the node is passed through
154
+ * untouched.
155
+ */
156
+ function writtenView(node: object, key: string): object {
157
+ if (Array.isArray(node)) return node;
158
+ try {
159
+ const toJSON: unknown = Reflect.get(node, "toJSON");
160
+ if (typeof toJSON !== "function") return node;
161
+ const view: unknown = Reflect.apply(toJSON, node, [key]);
162
+ return typeof view === "object" && view !== null ? view : node;
163
+ } catch {
164
+ return node;
165
+ }
166
+ }
167
+
143
168
  function removeKey(
144
169
  node: Record<string, unknown> | unknown[],
145
170
  key: string,
@@ -9,6 +9,7 @@
9
9
  * Populated by `SpectrumProvider.boot()`.
10
10
  */
11
11
 
12
+ import { E_SPECTRUM_NOT_BOOTED } from "../errors.js";
12
13
  import type { Logger } from "../Logger.js";
13
14
 
14
15
  let instance: Logger | undefined;
@@ -50,10 +51,7 @@ const logger: Logger = new Proxy(target, {
50
51
  return undefined;
51
52
  }
52
53
  if (!instance) {
53
- throw new Error(
54
- "[spectrum] Logger singleton accessed before SpectrumProvider.boot() ran. " +
55
- "Check that `@c9up/spectrum/provider` is listed in your reamrc.ts providers.",
56
- );
54
+ throw new E_SPECTRUM_NOT_BOOTED();
57
55
  }
58
56
  const value = Reflect.get(instance, prop, instance);
59
57
  return typeof value === "function" ? value.bind(instance) : value;
@@ -1,6 +1,7 @@
1
1
  /**
2
2
  * The standard serializers, in the shapes upstream's `stdSerializers` write:
3
- * `err` for errors, `req` and `res` for Node's HTTP request and response.
3
+ * `err` for errors, `req` and `res` for an HTTP request and response — Node's,
4
+ * or the framework's, whose fields are methods.
4
5
  *
5
6
  * new Logger({ serializers: { req: stdSerializers.req, res: stdSerializers.res } })
6
7
  */
@@ -64,14 +65,87 @@ function isRecord(value: unknown): value is Record<string, unknown> {
64
65
  return typeof value === "object" && value !== null;
65
66
  }
66
67
 
68
+ /**
69
+ * Call `target[name]()` when it is a method; `undefined` when it is not, or
70
+ * when it throws — a serializer must not take the line down with it.
71
+ */
72
+ function callMethod(target: object, name: string): unknown {
73
+ const method: unknown = Reflect.get(target, name);
74
+ if (typeof method !== "function") return undefined;
75
+ try {
76
+ return Reflect.apply(method, target, []);
77
+ } catch {
78
+ return undefined;
79
+ }
80
+ }
81
+
82
+ /** A copy of a record with at least one key, else `undefined`. */
83
+ function nonEmpty(value: unknown): Record<string, unknown> | undefined {
84
+ if (!isRecord(value) || Object.keys(value).length === 0) return undefined;
85
+ return { ...value };
86
+ }
87
+
88
+ /**
89
+ * A request whose fields are methods (`method()`, `url()`, `headers()`), as
90
+ * the framework's own request is. Recognised by its shape, so spectrum does
91
+ * not depend on the framework.
92
+ */
93
+ function isMethodRequest(value: object): boolean {
94
+ return (
95
+ typeof Reflect.get(value, "method") === "function" &&
96
+ typeof Reflect.get(value, "url") === "function" &&
97
+ typeof Reflect.get(value, "headers") === "function"
98
+ );
99
+ }
100
+
101
+ /**
102
+ * The headers of a method request: from its `serializeSafe()` view when it
103
+ * offers one (credential headers already blanked by the request itself),
104
+ * else from `headers()`. A plain copy either way, so the redaction paths
105
+ * written against `req.headers.*` reach them.
106
+ */
107
+ function methodRequestHeaders(value: object): Record<string, unknown> {
108
+ const safe = callMethod(value, "serializeSafe");
109
+ const safeHeaders = isRecord(safe) ? Reflect.get(safe, "headers") : undefined;
110
+ if (isRecord(safeHeaders)) return { ...safeHeaders };
111
+ const headers = callMethod(value, "headers");
112
+ return isRecord(headers) ? { ...headers } : {};
113
+ }
114
+
115
+ /**
116
+ * NAMED DEVIATION — upstream's `req` serializer knows only Node's
117
+ * `IncomingMessage`, whose fields are properties. On the framework's request
118
+ * they are methods: read as properties they were functions, JSON left them
119
+ * out, and the line said `"req":{}`. The same fields are written here by
120
+ * calling the methods. `url` is the path and the query string is written
121
+ * apart, parsed, so a redaction path can reach a token it carries
122
+ * (`req.query.token`) where it could not reach into a URL string. Never the
123
+ * body and never the cookie map: they are not part of the shape.
124
+ */
125
+ function serializeMethodRequest(value: object): Record<string, unknown> {
126
+ const query = nonEmpty(callMethod(value, "qs"));
127
+ const params = nonEmpty(callMethod(value, "params"));
128
+ return {
129
+ id: callMethod(value, "id"),
130
+ method: callMethod(value, "method"),
131
+ url: callMethod(value, "url"),
132
+ ...(query ? { query } : {}),
133
+ ...(params ? { params } : {}),
134
+ headers: methodRequestHeaders(value),
135
+ remoteAddress: callMethod(value, "ip"),
136
+ };
137
+ }
138
+
67
139
  /**
68
140
  * An HTTP request as upstream's `req` serializer writes it: id, method, url,
69
141
  * query, params, headers and the remote address. Every header is written as
70
142
  * it is, `cookie` and `authorization` included — censoring them is what
71
- * `redact` is for, and the generated config lists them.
143
+ * `redact` is for, and the generated config lists them. The framework's own
144
+ * request, whose fields are methods, is read through those methods.
72
145
  */
73
146
  export function serializeRequest(value: unknown): unknown {
74
147
  if (!isRecord(value)) return value;
148
+ if (isMethodRequest(value)) return serializeMethodRequest(value);
75
149
  const info = Reflect.get(value, "info");
76
150
  const connection = isRecord(info) ? info : Reflect.get(value, "socket");
77
151
  const id = Reflect.get(value, "id");
@@ -105,14 +179,23 @@ export function serializeRequest(value: unknown): unknown {
105
179
  };
106
180
  }
107
181
 
108
- /** An HTTP response as upstream's `res` serializer writes it: status and headers. */
182
+ /**
183
+ * An HTTP response as upstream's `res` serializer writes it: status and
184
+ * headers. The framework's response has no `statusCode` property: its
185
+ * `getStatus()` is read instead (it is set on the response before it is
186
+ * sent, so it is written whether or not the headers went out).
187
+ */
109
188
  export function serializeResponse(value: unknown): unknown {
110
189
  if (!isRecord(value)) return value;
111
190
  const getHeaders = Reflect.get(value, "getHeaders");
191
+ const getStatus = Reflect.get(value, "getStatus");
112
192
  return {
113
- statusCode: Reflect.get(value, "headersSent")
114
- ? Reflect.get(value, "statusCode")
115
- : null,
193
+ statusCode:
194
+ typeof getStatus === "function"
195
+ ? callMethod(value, "getStatus")
196
+ : Reflect.get(value, "headersSent")
197
+ ? Reflect.get(value, "statusCode")
198
+ : null,
116
199
  headers:
117
200
  typeof getHeaders === "function"
118
201
  ? Reflect.apply(getHeaders, value, [])
package/src/targets.ts CHANGED
@@ -16,7 +16,11 @@
16
16
 
17
17
  import { ConsoleChannel } from "./channels/ConsoleChannel.js";
18
18
  import { FileChannel } from "./channels/FileChannel.js";
19
- import { SpectrumError } from "./errors.js";
19
+ import {
20
+ E_SPECTRUM_INVALID_FILE_OPTIONS,
21
+ E_SPECTRUM_UNKNOWN_LEVEL,
22
+ E_SPECTRUM_UNSUPPORTED_TARGET,
23
+ } from "./errors.js";
20
24
  import { jsonLine } from "./jsonLine.js";
21
25
  import type {
22
26
  LineWritable,
@@ -162,10 +166,11 @@ function atLevel(channel: LogChannel, level: string | undefined): LogChannel {
162
166
  if (!isLogLevelWithSilent(level)) {
163
167
  // A level nobody can act on is a config error, and the failure mode of
164
168
  // ignoring it is the destination receiving everything.
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.`,
168
- );
169
+ throw new E_SPECTRUM_UNKNOWN_LEVEL([
170
+ "Unknown transport target",
171
+ `"${level}"`,
172
+ `${Object.keys(LOG_LEVEL_ORDER).join(", ")}, silent`,
173
+ ]);
169
174
  }
170
175
  const threshold = levelThreshold(level);
171
176
  // `trace` admits everything the logger already let through.
@@ -187,10 +192,9 @@ function descriptorChannel(destination: unknown): LogChannel {
187
192
  return new ConsoleChannel("json", { stream: "stderr" });
188
193
  if (typeof destination === "number")
189
194
  return new FileChannel({ fd: destination });
190
- throw new SpectrumError(
191
- "E_SPECTRUM_INVALID_FILE_OPTIONS",
195
+ throw new E_SPECTRUM_INVALID_FILE_OPTIONS([
192
196
  `pino/file destination must be a path or a file descriptor, got ${typeof destination}`,
193
- );
197
+ ]);
194
198
  }
195
199
 
196
200
  /**
@@ -238,10 +242,9 @@ function channelForTarget(entry: TransportTargetOptions): LogChannel {
238
242
  maxBufferBytes: optionalNumber(options, "maxBufferBytes"),
239
243
  });
240
244
  }
241
- throw new SpectrumError(
242
- "E_SPECTRUM_UNSUPPORTED_TARGET",
245
+ throw new E_SPECTRUM_UNSUPPORTED_TARGET([
243
246
  `Transport target "${target}" is not supported: spectrum builds "pino-pretty" and "pino/file". Pass a LogChannel as the target to write anywhere else.`,
244
- );
247
+ ]);
245
248
  }
246
249
 
247
250
  function prettyChannel(destination: unknown): LogChannel {
@@ -250,10 +253,9 @@ function prettyChannel(destination: unknown): LogChannel {
250
253
  return new ConsoleChannel("pretty", { stream: "stdout" });
251
254
  if (destination === 2)
252
255
  return new ConsoleChannel("pretty", { stream: "stderr" });
253
- throw new SpectrumError(
254
- "E_SPECTRUM_UNSUPPORTED_TARGET",
256
+ throw new E_SPECTRUM_UNSUPPORTED_TARGET([
255
257
  `pino-pretty destination ${JSON.stringify(destination)} is not supported: use 1 or 2, or a pino/file target for a file.`,
256
- );
258
+ ]);
257
259
  }
258
260
 
259
261
  /** A number option, or undefined when absent; any other type is a config error. */
@@ -276,15 +278,10 @@ function optionalBoolean(
276
278
  throw invalidOption(key, "boolean", value);
277
279
  }
278
280
 
279
- function invalidOption(
280
- key: string,
281
- type: string,
282
- value: unknown,
283
- ): SpectrumError {
284
- return new SpectrumError(
285
- "E_SPECTRUM_INVALID_FILE_OPTIONS",
281
+ function invalidOption(key: string, type: string, value: unknown): Error {
282
+ return new E_SPECTRUM_INVALID_FILE_OPTIONS([
286
283
  `pino/file option ${key} must be a ${type}, got ${typeof value}`,
287
- );
284
+ ]);
288
285
  }
289
286
 
290
287
  /** JSON lines to anything with a `write(line)` method. */
@@ -316,10 +313,9 @@ export function destinationChannel(destination: unknown): LogChannel {
316
313
  return new FileChannel({ path: destination });
317
314
  if (typeof destination === "number") return descriptorChannel(destination);
318
315
  if (isLineWritable(destination)) return new WritableChannel(destination);
319
- throw new SpectrumError(
320
- "E_SPECTRUM_UNSUPPORTED_TARGET",
316
+ throw new E_SPECTRUM_UNSUPPORTED_TARGET([
321
317
  "destination must be a path, a file descriptor or an object with a write(line) method",
322
- );
318
+ ]);
323
319
  }
324
320
 
325
321
  /**
@@ -339,10 +335,9 @@ export function channelsFromConfig(
339
335
  if (transport === undefined) return undefined;
340
336
  if ("target" in transport) return channelsFromTargets([transport], level);
341
337
  if (Reflect.get(transport, "pipeline") !== undefined) {
342
- throw new SpectrumError(
343
- "E_SPECTRUM_UNSUPPORTED_TARGET",
338
+ throw new E_SPECTRUM_UNSUPPORTED_TARGET([
344
339
  "transport.pipeline is not supported: declare targets, or pass channels",
345
- );
340
+ ]);
346
341
  }
347
342
  if (transport.targets === undefined || transport.targets.length === 0) {
348
343
  return undefined;
@@ -8,6 +8,10 @@
8
8
  * `@c9up/spectrum/testing`.
9
9
  */
10
10
 
11
+ import {
12
+ E_SPECTRUM_ASSERTION_FAILED,
13
+ E_SPECTRUM_INVALID_PREDICATE,
14
+ } from "../errors.js";
11
15
  import type { LogChannel, LogEntry, LogLevel } from "../types.js";
12
16
  import { LOG_LEVEL_ORDER, logEntryExtras } from "../types.js";
13
17
 
@@ -45,17 +49,17 @@ export class FakeLogger implements LogChannel {
45
49
  assertLogged(level: LogLevel, predicate?: FakeLoggerPredicateArg): void {
46
50
  const match = makeMatcher(level, predicate);
47
51
  if (this.#captured.some(match)) return;
48
- throw new Error(
52
+ throw new E_SPECTRUM_ASSERTION_FAILED([
49
53
  `logger.assertLogged('${level}'${describePredicate(predicate)}) failed — no captured entry matches.\n${describeCaptured(this.#captured)}`,
50
- );
54
+ ]);
51
55
  }
52
56
 
53
57
  assertNotLogged(level: LogLevel, predicate?: FakeLoggerPredicateArg): void {
54
58
  const match = makeMatcher(level, predicate);
55
59
  if (!this.#captured.some(match)) return;
56
- throw new Error(
60
+ throw new E_SPECTRUM_ASSERTION_FAILED([
57
61
  `logger.assertNotLogged('${level}'${describePredicate(predicate)}) failed — at least one captured entry matches.\n${describeCaptured(this.#captured)}`,
58
- );
62
+ ]);
59
63
  }
60
64
  }
61
65
 
@@ -73,9 +77,7 @@ function makeMatcher(
73
77
  // Array.some short-circuits on an empty array, so a check inside
74
78
  // the matcher would silently pass when nothing was captured.
75
79
  if (predicate.containing === "") {
76
- throw new Error(
77
- "FakeLogger: `containing` predicate cannot be an empty string — it would match every captured message.",
78
- );
80
+ throw new E_SPECTRUM_INVALID_PREDICATE();
79
81
  }
80
82
  return (e) => {
81
83
  if (e.level !== level) return false;
@@ -113,21 +115,34 @@ function describeCaptured(captured: LogEntry[]): string {
113
115
  return `Captured (${captured.length}):\n${lines.join("\n")}`;
114
116
  }
115
117
 
116
- /** `JSON.stringify` with circular-ref + function-field handling.
117
- * Functions render as `<function>`, circular refs as `<circular>`,
118
- * unstringifiable values as `<unstringifiable>` — so an assertion
119
- * failure message never gets eaten by a JSON throw. */
118
+ /**
119
+ * `JSON.stringify` for an assertion message: a function renders as
120
+ * `<function>`, a BigInt as `<digits>n`, a cycle as `<circular>`, and a value
121
+ * that still cannot be written as `<unstringifiable>` — so a failure message
122
+ * is never eaten by a JSON throw.
123
+ *
124
+ * Only a cycle is cut. `path` holds the objects from the root to the value
125
+ * being written, so a value reached through two keys is written under both, as
126
+ * `JSON.stringify` writes it; remembering every object seen dropped the second
127
+ * one. The same rule as `@c9up/ream`'s `src/utils/safeStringify.ts`, kept as a
128
+ * local copy because this message format differs from a response body's.
129
+ */
120
130
  function safeStringify(value: unknown): string {
121
- const seen = new WeakSet<object>();
131
+ const path: object[] = [];
122
132
  try {
123
- return JSON.stringify(value, (_key, v: unknown) => {
124
- if (typeof v === "function") return "<function>";
125
- if (typeof v === "object" && v !== null) {
126
- if (seen.has(v)) return "<circular>";
127
- seen.add(v);
128
- }
129
- return v;
130
- });
133
+ const out: string | undefined = JSON.stringify(
134
+ value,
135
+ function replace(this: unknown, _key: string, v: unknown) {
136
+ if (typeof v === "function") return "<function>";
137
+ if (typeof v === "bigint") return `${v}n`;
138
+ if (typeof v !== "object" || v === null) return v;
139
+ while (path.length > 0 && path[path.length - 1] !== this) path.pop();
140
+ if (path.includes(v)) return "<circular>";
141
+ path.push(v);
142
+ return v;
143
+ },
144
+ );
145
+ return out ?? "undefined";
131
146
  } catch {
132
147
  return "<unstringifiable>";
133
148
  }
@@ -137,18 +152,57 @@ function deepClone(entry: LogEntry): LogEntry {
137
152
  try {
138
153
  return structuredClone(entry);
139
154
  } catch {
140
- // `data` can carry functions / class instances that structuredClone
141
- // rejects (DataCloneError). For a test capture a perfect clone isn't
142
- // needed — round-trip through safeStringify (functions → "<function>",
143
- // circular → "<circular>") so the entry is still CAPTURED and assertable
144
- // instead of thrown away (the throw propagated into Logger.log's swallow,
145
- // dropping the entry and making assertLogged fail with "no entry").
146
- try {
147
- const parsed: unknown = JSON.parse(safeStringify(entry));
148
- return isLogEntry(parsed) ? parsed : entry;
149
- } catch {
150
- return entry;
155
+ // `data` can carry a function, which structuredClone rejects
156
+ // (DataCloneError). The entry must still be CAPTURED and assertable —
157
+ // the throw used to propagate into Logger.log's swallow, dropping the
158
+ // entry and making assertLogged fail with "no entry". So it is copied
159
+ // by hand: plain objects and arrays anew, a value reached twice copied
160
+ // once and shared again, a cycle kept a cycle, a function kept as it is.
161
+ // The JSON round-trip this replaces turned functions into strings and
162
+ // dropped a value's second reference.
163
+ const copy = copyValue(entry, new Map());
164
+ return isLogEntry(copy) ? copy : entry;
165
+ }
166
+ }
167
+
168
+ /**
169
+ * A copy of `value` for a test capture. `copies` maps every object already
170
+ * copied to its copy, so sharing and cycles come out as they went in.
171
+ */
172
+ function copyValue(value: unknown, copies: Map<object, unknown>): unknown {
173
+ if (typeof value !== "object" || value === null) return value;
174
+ if (copies.has(value)) return copies.get(value);
175
+ if (Array.isArray(value)) {
176
+ const out: unknown[] = [];
177
+ copies.set(value, out);
178
+ for (const item of value) out.push(copyValue(item, copies));
179
+ return out;
180
+ }
181
+ const proto: unknown = Object.getPrototypeOf(value);
182
+ if (proto === Object.prototype || proto === null) {
183
+ const out: Record<string, unknown> =
184
+ proto === null ? Object.create(null) : {};
185
+ copies.set(value, out);
186
+ for (const [key, item] of Object.entries(value)) {
187
+ // defineProperty, not assignment: an own `__proto__` key stays a key.
188
+ Object.defineProperty(out, key, {
189
+ value: copyValue(item, copies),
190
+ enumerable: true,
191
+ writable: true,
192
+ configurable: true,
193
+ });
151
194
  }
195
+ return out;
196
+ }
197
+ // Anything else (a Date, a Map, a class instance) is cloned whole when
198
+ // structuredClone can, and kept as it is when it cannot.
199
+ try {
200
+ const out: unknown = structuredClone(value);
201
+ copies.set(value, out);
202
+ return out;
203
+ } catch {
204
+ copies.set(value, value);
205
+ return value;
152
206
  }
153
207
  }
154
208
 
package/src/types.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { SpectrumError } from "./errors.js";
1
+ import { E_SPECTRUM_UNKNOWN_LEVEL } from "./errors.js";
2
2
  import type { LineFormatters, TimestampOption } from "./jsonLine.js";
3
3
  import type { TransportTargetOptions } from "./targets.js";
4
4
  /**
@@ -57,10 +57,11 @@ export function isLogLevelWithSilent(
57
57
  */
58
58
  export function assertLogLevel(value: unknown): LogLevelWithSilent {
59
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
- );
60
+ throw new E_SPECTRUM_UNKNOWN_LEVEL([
61
+ "unknown",
62
+ JSON.stringify(value) ?? String(value),
63
+ [...CONFIGURED_LEVELS].join(", "),
64
+ ]);
64
65
  }
65
66
 
66
67
  /**
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  to: config/logger.ts
3
3
  ---
4
- import { defineConfig, logLevel, targets } from '@c9up/spectrum'
4
+ import { defineConfig, logLevel, stdSerializers, targets } from '@c9up/spectrum'
5
5
 
6
6
  const inProduction = process.env.NODE_ENV === 'production'
7
7
 
@@ -14,9 +14,13 @@ export default defineConfig({
14
14
  // LOG_LEVEL comes from outside the program, so it is checked rather than
15
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.
17
+ // A request or a response logged under `req` / `res` is written as its
18
+ // method, url, query, params, status and headers: never its body or its
19
+ // cookie map. Its headers come as they arrived: the session cookie, the
20
+ // bearer token and the cookies set in reply are kept out of the line by
21
+ // the paths below. Anything logged under another key is written as it
22
+ // is: censor it with a path of its own.
23
+ serializers: { req: stdSerializers.req, res: stdSerializers.res },
20
24
  redact: {
21
25
  paths: [
22
26
  'req.headers.authorization',