@c9up/spectrum 0.1.19 → 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 (69) hide show
  1. package/README.md +21 -3
  2. package/dist/Logger.d.ts.map +1 -1
  3. package/dist/Logger.js +77 -30
  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 +16 -7
  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.d.ts.map +1 -1
  32. package/dist/jsonLine.js +4 -3
  33. package/dist/jsonLine.js.map +1 -1
  34. package/dist/redact.d.ts.map +1 -1
  35. package/dist/redact.js +33 -6
  36. package/dist/redact.js.map +1 -1
  37. package/dist/services/main.d.ts.map +1 -1
  38. package/dist/services/main.js +2 -2
  39. package/dist/services/main.js.map +1 -1
  40. package/dist/stdSerializers.d.ts +12 -4
  41. package/dist/stdSerializers.d.ts.map +1 -1
  42. package/dist/stdSerializers.js +88 -7
  43. package/dist/stdSerializers.js.map +1 -1
  44. package/dist/targets.d.ts.map +1 -1
  45. package/dist/targets.js +24 -8
  46. package/dist/targets.js.map +1 -1
  47. package/dist/testing/FakeLogger.d.ts.map +1 -1
  48. package/dist/testing/FakeLogger.js +84 -26
  49. package/dist/testing/FakeLogger.js.map +1 -1
  50. package/dist/types.d.ts.map +1 -1
  51. package/dist/types.js +9 -3
  52. package/dist/types.js.map +1 -1
  53. package/package.json +7 -4
  54. package/src/Logger.ts +84 -40
  55. package/src/LoggerManager.ts +18 -12
  56. package/src/SpectrumProvider.ts +19 -12
  57. package/src/channels/FileChannel.ts +7 -10
  58. package/src/config.ts +27 -5
  59. package/src/errors.ts +92 -11
  60. package/src/format.ts +105 -0
  61. package/src/index.ts +1 -1
  62. package/src/jsonLine.ts +5 -4
  63. package/src/redact.ts +32 -7
  64. package/src/services/main.ts +2 -4
  65. package/src/stdSerializers.ts +91 -7
  66. package/src/targets.ts +23 -28
  67. package/src/testing/FakeLogger.ts +85 -31
  68. package/src/types.ts +9 -6
  69. package/stubs/config/logger.stub +15 -1
package/src/Logger.ts CHANGED
@@ -13,9 +13,12 @@
13
13
  * @implements FR54, FR55, FR56, FR58
14
14
  */
15
15
 
16
- import { format } from "node:util";
17
- import { SpectrumError } from "./errors.js";
16
+ import {
17
+ E_SPECTRUM_INVALID_STRINGIFY_LIMIT,
18
+ E_SPECTRUM_UNSUPPORTED_OPTION,
19
+ } from "./errors.js";
18
20
  import { emitLog, hasLogListeners } from "./events.js";
21
+ import { formatMessage } from "./format.js";
19
22
  import {
20
23
  attachLineOptions,
21
24
  type JsonLineOptions,
@@ -28,6 +31,7 @@ import {
28
31
  DEFAULT_STRINGIFY_LIMITS,
29
32
  isStringifyLimit,
30
33
  type StringifyLimits,
34
+ stringifyValue,
31
35
  } from "./stringify.js";
32
36
  import { channelsFromConfig } from "./targets.js";
33
37
  import type {
@@ -47,9 +51,6 @@ import {
47
51
 
48
52
  export type { LogLevel };
49
53
 
50
- /** printf-style tokens understood by `util.format`. */
51
- const PRINTF_TOKEN = /%[sdifjoOc%]/;
52
-
53
54
  function isLogLevel(value: string): value is LogLevel {
54
55
  return value in LOG_LEVEL_ORDER;
55
56
  }
@@ -72,10 +73,7 @@ function stringifyLimits(config: LogConfig): StringifyLimits {
72
73
  ["edgeLimit", edgeLimit],
73
74
  ] as const) {
74
75
  if (value !== undefined && !isStringifyLimit(value)) {
75
- throw new SpectrumError(
76
- "E_SPECTRUM_INVALID_STRINGIFY_LIMIT",
77
- `${name} must be a positive integer, got ${String(value)}`,
78
- );
76
+ throw new E_SPECTRUM_INVALID_STRINGIFY_LIMIT([name, String(value)]);
79
77
  }
80
78
  }
81
79
  return {
@@ -121,10 +119,7 @@ function rejectUnsupportedOptions(config: LogConfig): void {
121
119
  for (const option of UNSUPPORTED_OPTIONS) {
122
120
  const value: unknown = Reflect.get(config, option);
123
121
  if (value !== undefined) {
124
- throw new SpectrumError(
125
- "E_SPECTRUM_UNSUPPORTED_OPTION",
126
- `the "${option}" logger option is not supported`,
127
- );
122
+ throw new E_SPECTRUM_UNSUPPORTED_OPTION([option]);
128
123
  }
129
124
  }
130
125
  const streamWrite: unknown =
@@ -132,10 +127,7 @@ function rejectUnsupportedOptions(config: LogConfig): void {
132
127
  ? undefined
133
128
  : Reflect.get(config.hooks, "streamWrite");
134
129
  if (streamWrite !== undefined) {
135
- throw new SpectrumError(
136
- "E_SPECTRUM_UNSUPPORTED_OPTION",
137
- 'the "hooks.streamWrite" logger option is not supported',
138
- );
130
+ throw new E_SPECTRUM_UNSUPPORTED_OPTION(["hooks.streamWrite"]);
139
131
  }
140
132
  }
141
133
 
@@ -161,10 +153,27 @@ function redactAction(redact: LogConfig["redact"]): RedactAction {
161
153
  };
162
154
  }
163
155
 
164
- const DEFAULT_SERIALIZERS: Record<string, LogSerializer> = {
165
- err: serializeError,
166
- error: serializeError,
167
- };
156
+ /**
157
+ * The serializers a key is looked up in, on a null prototype as pino builds
158
+ * its own: every own key of a merging object (a request body, often) is read
159
+ * here, and on an ordinary object `valueOf`, `hasOwnProperty` or `__proto__`
160
+ * answered an `Object.prototype` member — called as a serializer, it threw
161
+ * out of the log call or rewrote the field.
162
+ */
163
+ function serializerBag(
164
+ configured: Record<string, LogSerializer> | undefined,
165
+ ): Record<string, LogSerializer> {
166
+ const bag: Record<string, LogSerializer> = Object.create(null);
167
+ bag.err = serializeError;
168
+ bag.error = serializeError;
169
+ if (configured !== undefined) {
170
+ for (const key of Object.keys(configured)) {
171
+ const serializer = configured[key];
172
+ if (typeof serializer === "function") bag[key] = serializer;
173
+ }
174
+ }
175
+ return bag;
176
+ }
168
177
 
169
178
  export class Logger {
170
179
  #config: LogConfig;
@@ -425,10 +434,14 @@ export class Logger {
425
434
  *
426
435
  * - `(object, message?, ...values)` → object merged at root (pino).
427
436
  * - `(error, message?, ...values)` → `{ err }` merged (pino err serializer).
428
- * - `(message, ...values)` → printf via `util.format` (pino).
429
- * - `(message, singleObject)` with no printf token → merged as structured
430
- * fields. This is spectrum's message-first ergonomic (ream ContextLogger
431
- * particularity) preserved on top of pino's message-first form.
437
+ * - `(message, ...values)` → printf, with pino's formatter rules.
438
+ * - `(message, singleObject)` → the object merged as structured fields,
439
+ * the message written as given; `(message, singleError)` → `{ err }`.
440
+ *
441
+ * NAMED DEVIATION — the last form is spectrum's own (ream's request logger
442
+ * is `info(message, data)`), and it no longer looks at the message to
443
+ * decide: a `%j` or `%c` that request data put into the message used to
444
+ * turn the fields into clear text inside `msg`, or swallow them.
432
445
  */
433
446
  #resolveArgs(
434
447
  arg0: unknown,
@@ -455,14 +468,14 @@ export class Logger {
455
468
  if (arg0 instanceof Error) {
456
469
  const message =
457
470
  typeof rest[0] === "string"
458
- ? format(rest[0], ...rest.slice(1))
471
+ ? this.#format(rest[0], rest.slice(1))
459
472
  : arg0.message;
460
473
  return { message, mergingObject: { [errorKey]: arg0 }, given: true };
461
474
  }
462
475
  if (isMergeableObject(arg0)) {
463
476
  if (typeof rest[0] === "string") {
464
477
  return {
465
- message: format(rest[0], ...rest.slice(1)),
478
+ message: this.#format(rest[0], rest.slice(1)),
466
479
  mergingObject: arg0,
467
480
  given: true,
468
481
  };
@@ -476,15 +489,42 @@ export class Logger {
476
489
  }
477
490
 
478
491
  const template = typeof arg0 === "string" ? arg0 : String(arg0);
479
- if (
480
- rest.length === 1 &&
481
- isMergeableObject(rest[0]) &&
482
- !PRINTF_TOKEN.test(template)
483
- ) {
484
- return { message: template, mergingObject: rest[0], given: true };
492
+ if (rest.length === 1) {
493
+ const only = rest[0];
494
+ if (only instanceof Error) {
495
+ return {
496
+ message: template,
497
+ mergingObject: { [errorKey]: only },
498
+ given: true,
499
+ };
500
+ }
501
+ if (isMergeableObject(only)) {
502
+ return { message: template, mergingObject: only, given: true };
503
+ }
485
504
  }
486
- const message = rest.length > 0 ? format(template, ...rest) : template;
487
- return { message, given: true };
505
+ return { message: this.#format(template, rest), given: true };
506
+ }
507
+
508
+ /** printf interpolation; an object goes in serialised and redacted. */
509
+ #format(template: string, values: readonly unknown[]): string {
510
+ return formatMessage(template, values, (value) =>
511
+ this.#interpolated(value),
512
+ );
513
+ }
514
+
515
+ /**
516
+ * An object a `%j`, `%o` or `%O` writes into the message: through the
517
+ * serializers and the redaction paths, as a merging object goes. pino
518
+ * redacts an interpolated object with the logger's full path list; a
519
+ * value that skipped it would put the very field the config censors in
520
+ * clear text, one key away from where the config looks for it.
521
+ */
522
+ #interpolated(value: unknown): string {
523
+ let out: unknown = value;
524
+ if (value instanceof Error) out = serializeError(value);
525
+ else if (isMergeableObject(value)) out = this.#applySerializers(value);
526
+ out = this.#redactValue(out);
527
+ return stringifyValue(out, this.#lineOptions?.limits) ?? "undefined";
488
528
  }
489
529
 
490
530
  /** The merging object with the mixin's fields; the merging object wins by default. */
@@ -503,14 +543,14 @@ export class Logger {
503
543
  }
504
544
 
505
545
  #applySerializers(bag: Record<string, unknown>): Record<string, unknown> {
506
- const serializers = { ...DEFAULT_SERIALIZERS, ...this.#config.serializers };
546
+ const serializers = serializerBag(this.#config.serializers);
507
547
  const errorKey = this.#config.errorKey ?? "err";
508
548
  let out: Record<string, unknown> | null = null;
509
549
  for (const key of Object.keys(bag)) {
510
550
  // The error key takes the `err` serializer unless it has its own.
511
551
  const serializer =
512
552
  serializers[key] ?? (key === errorKey ? serializers.err : undefined);
513
- if (serializer) {
553
+ if (serializer !== undefined) {
514
554
  if (!out) out = { ...bag };
515
555
  out[key] = serializer(bag[key]);
516
556
  }
@@ -519,12 +559,16 @@ export class Logger {
519
559
  }
520
560
 
521
561
  #applyRedact(bag: Record<string, unknown>): Record<string, unknown> {
522
- if (this.#redactPaths.length === 0) return bag;
523
- let out: unknown = bag;
562
+ const out = this.#redactValue(bag);
563
+ return isMergeableObject(out) ? out : bag;
564
+ }
565
+
566
+ #redactValue(value: unknown): unknown {
567
+ let out = value;
524
568
  for (const tokens of this.#redactPaths) {
525
569
  out = redactPath(out, tokens, this.#redactAction);
526
570
  }
527
- return isMergeableObject(out) ? out : bag;
571
+ return out;
528
572
  }
529
573
 
530
574
  #write(
@@ -5,6 +5,11 @@
5
5
  * loggers forever, and exposes `use()` / `create()`.
6
6
  */
7
7
 
8
+ import { declaredLogger } from "./config.js";
9
+ import {
10
+ E_SPECTRUM_UNKNOWN_DEFAULT_LOGGER,
11
+ E_SPECTRUM_UNKNOWN_LOGGER,
12
+ } from "./errors.js";
8
13
  import { Logger } from "./Logger.js";
9
14
  import type { LogConfig, LoggerManagerConfig } from "./types.js";
10
15
 
@@ -13,13 +18,13 @@ export class LoggerManager extends Logger {
13
18
  #loggers: Map<string, Logger> = new Map();
14
19
 
15
20
  constructor(config: LoggerManagerConfig) {
16
- const selected = config.loggers[config.default];
21
+ const selected = declaredLogger(config.loggers, config.default);
17
22
  if (selected === undefined) {
18
23
  // Naming a logger that is not in `loggers` used to build a manager
19
24
  // around undefined and fail on the first line written.
20
- throw new Error(
21
- `[spectrum] config.logger names '${config.default}', which is not in \`loggers\`. Declared: ${Object.keys(config.loggers).join(", ") || "(none)"}.`,
22
- );
25
+ throw new E_SPECTRUM_UNKNOWN_DEFAULT_LOGGER([
26
+ `config.logger names '${config.default}', which is not in \`loggers\`. Declared: ${Object.keys(config.loggers).join(", ") || "(none)"}.`,
27
+ ]);
23
28
  }
24
29
  super(selected);
25
30
  this.#config = config;
@@ -32,11 +37,12 @@ export class LoggerManager extends Logger {
32
37
  const cached = this.#loggers.get(key);
33
38
  if (cached) return cached;
34
39
 
35
- const config = this.#config.loggers[key];
36
- if (!config) {
37
- throw new Error(
38
- `[spectrum] Unknown logger "${key}". Registered: ${Object.keys(this.#config.loggers).join(", ")}`,
39
- );
40
+ const config = declaredLogger(this.#config.loggers, key);
41
+ if (config === undefined) {
42
+ throw new E_SPECTRUM_UNKNOWN_LOGGER([
43
+ key,
44
+ Object.keys(this.#config.loggers).join(", "),
45
+ ]);
40
46
  }
41
47
  const logger = this.createLogger(key, config);
42
48
  this.#loggers.set(key, logger);
@@ -45,11 +51,11 @@ export class LoggerManager extends Logger {
45
51
 
46
52
  /**
47
53
  * Build a named logger: the config's `name` defaults to the name it is
48
- * registered under. Not cached; `use()` caches what this returns.
54
+ * registered under. Not cached; `use()` caches what this returns. The
55
+ * config handed in is not written to: the name goes on a copy.
49
56
  */
50
57
  createLogger(name: string, config: LogConfig): Logger {
51
- if (!config.name) config.name = name;
52
- return new Logger(config);
58
+ return new Logger(config.name ? config : { ...config, name });
53
59
  }
54
60
 
55
61
  /**
@@ -1,6 +1,10 @@
1
1
  import "./augmentations.js";
2
2
  import { ConsoleChannel } from "./channels/ConsoleChannel.js";
3
- import { SpectrumError } from "./errors.js";
3
+ import { declaredLogger } from "./config.js";
4
+ import {
5
+ E_SPECTRUM_LOGGER_NOT_BOUND,
6
+ E_SPECTRUM_UNKNOWN_DEFAULT_LOGGER,
7
+ } from "./errors.js";
4
8
  import { onLog } from "./events.js";
5
9
  import { Logger } from "./Logger.js";
6
10
  import { LoggerManager } from "./LoggerManager.js";
@@ -96,10 +100,7 @@ export default class SpectrumProvider {
96
100
  async boot() {
97
101
  const logger = await this.app.container.resolve(Logger);
98
102
  if (!(logger instanceof Logger)) {
99
- throw new SpectrumError(
100
- "E_SPECTRUM_LOGGER_NOT_BOUND",
101
- "the container resolved something other than a Logger for the Logger token",
102
- );
103
+ throw new E_SPECTRUM_LOGGER_NOT_BOUND();
103
104
  }
104
105
  this.#owned = logger;
105
106
  setLogger(logger);
@@ -180,17 +181,19 @@ export default class SpectrumProvider {
180
181
  */
181
182
  #normalize(raw: unknown): LoggerManagerConfig {
182
183
  if (isManagerConfig(raw)) {
183
- const loggers: Record<string, LogConfig> = {};
184
+ // On a null prototype: a logger declared as `__proto__` is an entry
185
+ // here, not the prototype of the map.
186
+ const loggers: Record<string, LogConfig> = Object.create(null);
184
187
  for (const [name, cfg] of Object.entries(raw.loggers)) {
185
188
  loggers[name] = this.#normalizeLogger(cfg);
186
189
  }
187
190
  // Fail loud at boot if `default` references a missing logger — else
188
191
  // LoggerManager builds with `loggers[default] === undefined` and crashes
189
192
  // with a cryptic TypeError on the first log. Mirrors defineConfig().
190
- if (!loggers[raw.default]) {
191
- throw new Error(
192
- `[spectrum] Missing "loggers.${raw.default}". It is referenced by the "default" logger`,
193
- );
193
+ if (declaredLogger(loggers, raw.default) === undefined) {
194
+ throw new E_SPECTRUM_UNKNOWN_DEFAULT_LOGGER([
195
+ `Missing "loggers.${raw.default}". It is referenced by the "default" logger`,
196
+ ]);
194
197
  }
195
198
  return { default: raw.default, loggers };
196
199
  }
@@ -215,12 +218,16 @@ export default class SpectrumProvider {
215
218
  return { ...cfg, level, channels };
216
219
  }
217
220
 
218
- /** Explicit channels, else the declared destination or targets, else a pretty console. */
221
+ /**
222
+ * Explicit channels, else the declared destination or targets, else a pretty
223
+ * console. An explicit `[]` is kept: it is how a logger is silenced, and the
224
+ * Logger reads it the same way — only a missing `channels` takes a default.
225
+ */
219
226
  #channelsFor(
220
227
  cfg: Partial<LogConfig>,
221
228
  level: LogLevelWithSilent,
222
229
  ): LogChannel[] {
223
- if (cfg.channels && cfg.channels.length > 0) return cfg.channels;
230
+ if (cfg.channels !== undefined) return cfg.channels;
224
231
  return channelsFromConfig(cfg, level) ?? [new ConsoleChannel("pretty")];
225
232
  }
226
233
  }
@@ -19,7 +19,7 @@ import * as fs from "node:fs";
19
19
  import * as fsp from "node:fs/promises";
20
20
  import * as path from "node:path";
21
21
  import { promisify } from "node:util";
22
- import { SpectrumError } from "../errors.js";
22
+ import { E_SPECTRUM_INVALID_FILE_OPTIONS } from "../errors.js";
23
23
  import { jsonLine } from "../jsonLine.js";
24
24
  import type { LogChannel, LogEntry } from "../types.js";
25
25
 
@@ -65,10 +65,9 @@ function positiveInteger(
65
65
  ): number {
66
66
  if (value === undefined) return fallback;
67
67
  if (!Number.isInteger(value) || value <= 0) {
68
- throw new SpectrumError(
69
- "E_SPECTRUM_INVALID_FILE_OPTIONS",
68
+ throw new E_SPECTRUM_INVALID_FILE_OPTIONS([
70
69
  `FileChannel ${name} must be a positive integer, got ${String(value)}`,
71
- );
70
+ ]);
72
71
  }
73
72
  return value;
74
73
  }
@@ -107,16 +106,14 @@ export class FileChannel implements LogChannel {
107
106
  constructor(config: FileChannelConfig) {
108
107
  const { path: filePath, fd } = config;
109
108
  if ((filePath === undefined) === (fd === undefined)) {
110
- throw new SpectrumError(
111
- "E_SPECTRUM_INVALID_FILE_OPTIONS",
109
+ throw new E_SPECTRUM_INVALID_FILE_OPTIONS([
112
110
  "FileChannel needs exactly one of `path` and `fd`",
113
- );
111
+ ]);
114
112
  }
115
113
  if (fd !== undefined && !(Number.isInteger(fd) && fd >= 0)) {
116
- throw new SpectrumError(
117
- "E_SPECTRUM_INVALID_FILE_OPTIONS",
114
+ throw new E_SPECTRUM_INVALID_FILE_OPTIONS([
118
115
  `FileChannel fd must be a non-negative integer, got ${String(fd)}`,
119
- );
116
+ ]);
120
117
  }
121
118
  this.#filePath = filePath ?? `fd ${String(fd)}`;
122
119
  this.#fdGiven = fd !== undefined;
package/src/config.ts CHANGED
@@ -1,5 +1,27 @@
1
+ import {
2
+ E_SPECTRUM_MISSING_DEFAULT_LOGGER,
3
+ E_SPECTRUM_UNKNOWN_DEFAULT_LOGGER,
4
+ } from "./errors.js";
1
5
  import type { LogConfig, LoggerManagerConfig } from "./types.js";
2
6
 
7
+ /**
8
+ * The logger `name` declares, read as an OWN key of `loggers`.
9
+ *
10
+ * NAMED DEVIATION — upstream reads `loggers[name]`, which answers
11
+ * `Object.prototype` for `__proto__` and a function for `constructor` or
12
+ * `toString`. The first then had `name` written onto it — onto every object
13
+ * of the process — and the others built a logger with no channel that wrote
14
+ * nothing. A name that is not declared is unknown, whatever it is spelled.
15
+ */
16
+ export function declaredLogger(
17
+ loggers: Record<string, LogConfig>,
18
+ name: string,
19
+ ): LogConfig | undefined {
20
+ if (!Object.hasOwn(loggers, name)) return undefined;
21
+ const config = loggers[name];
22
+ return typeof config === "object" && config !== null ? config : undefined;
23
+ }
24
+
3
25
  /**
4
26
  * Define the logger config. Accepts either the Adonis multi-logger shape
5
27
  * (`{ default, loggers }`) or the legacy flat shape (`{ level, channels,
@@ -13,12 +35,12 @@ export function defineConfig(
13
35
  ): LoggerManagerConfig {
14
36
  if ("loggers" in config) {
15
37
  if (!config.default) {
16
- throw new Error('[spectrum] Missing "default" property in logger config');
38
+ throw new E_SPECTRUM_MISSING_DEFAULT_LOGGER();
17
39
  }
18
- if (!config.loggers[config.default]) {
19
- throw new Error(
20
- `[spectrum] Missing "loggers.${config.default}". It is referenced by the "default" logger`,
21
- );
40
+ if (declaredLogger(config.loggers, config.default) === undefined) {
41
+ throw new E_SPECTRUM_UNKNOWN_DEFAULT_LOGGER([
42
+ `Missing "loggers.${config.default}". It is referenced by the "default" logger`,
43
+ ]);
22
44
  }
23
45
  return config;
24
46
  }
package/src/errors.ts CHANGED
@@ -1,13 +1,94 @@
1
1
  /**
2
- * A spectrum configuration or usage error, carrying an `E_SPECTRUM_*` code an
3
- * application can filter on.
2
+ * Spectrum errors, one class per code. An application branches on
3
+ * `error.code` or on `error instanceof errors.E_…`; every one is a flare
4
+ * `Exception`, with the HTTP status an exception handler answers with.
4
5
  */
5
- export class SpectrumError extends Error {
6
- readonly code: string;
7
-
8
- constructor(code: string, message: string) {
9
- super(`[spectrum] ${message}`);
10
- this.name = "SpectrumError";
11
- this.code = code;
12
- }
13
- }
6
+
7
+ import { createError } from "@c9up/flare";
8
+
9
+ /** A configured level, a target level or `logLevel()` input is not a level. */
10
+ export const E_SPECTRUM_UNKNOWN_LEVEL = createError<[string, string, string]>(
11
+ "[spectrum] %s level %s. Use one of: %s.",
12
+ "E_SPECTRUM_UNKNOWN_LEVEL",
13
+ );
14
+
15
+ /** A transport target or destination spectrum cannot build. */
16
+ export const E_SPECTRUM_UNSUPPORTED_TARGET = createError<[string]>(
17
+ "[spectrum] %s",
18
+ "E_SPECTRUM_UNSUPPORTED_TARGET",
19
+ );
20
+
21
+ /** A file destination's options are invalid. */
22
+ export const E_SPECTRUM_INVALID_FILE_OPTIONS = createError<[string]>(
23
+ "[spectrum] %s",
24
+ "E_SPECTRUM_INVALID_FILE_OPTIONS",
25
+ );
26
+
27
+ /** `messageKey`, `timestamp`, `base` or `formatters` is invalid. */
28
+ export const E_SPECTRUM_INVALID_LINE_OPTIONS = createError<[string]>(
29
+ "[spectrum] %s",
30
+ "E_SPECTRUM_INVALID_LINE_OPTIONS",
31
+ );
32
+
33
+ /** A `redact` path cannot be parsed. */
34
+ export const E_SPECTRUM_INVALID_REDACT_PATH = createError<[string]>(
35
+ "[spectrum] %s",
36
+ "E_SPECTRUM_INVALID_REDACT_PATH",
37
+ );
38
+
39
+ /** `depthLimit` or `edgeLimit` is not a positive integer. */
40
+ export const E_SPECTRUM_INVALID_STRINGIFY_LIMIT = createError<
41
+ [string, unknown]
42
+ >(
43
+ "[spectrum] %s must be a positive integer, got %s",
44
+ "E_SPECTRUM_INVALID_STRINGIFY_LIMIT",
45
+ );
46
+
47
+ /** The config sets an option spectrum does not support. */
48
+ export const E_SPECTRUM_UNSUPPORTED_OPTION = createError<[string]>(
49
+ '[spectrum] the "%s" logger option is not supported',
50
+ "E_SPECTRUM_UNSUPPORTED_OPTION",
51
+ );
52
+
53
+ /** At boot, the container resolves something other than a `Logger`. */
54
+ export const E_SPECTRUM_LOGGER_NOT_BOUND = createError(
55
+ "[spectrum] the container resolved something other than a Logger for the Logger token",
56
+ "E_SPECTRUM_LOGGER_NOT_BOUND",
57
+ );
58
+
59
+ /** A multi-logger config names no `default` logger. */
60
+ export const E_SPECTRUM_MISSING_DEFAULT_LOGGER = createError(
61
+ '[spectrum] Missing "default" property in logger config',
62
+ "E_SPECTRUM_MISSING_DEFAULT_LOGGER",
63
+ );
64
+
65
+ /** The `default` logger is not declared in `loggers`. */
66
+ export const E_SPECTRUM_UNKNOWN_DEFAULT_LOGGER = createError<[string]>(
67
+ "[spectrum] %s",
68
+ "E_SPECTRUM_UNKNOWN_DEFAULT_LOGGER",
69
+ );
70
+
71
+ /** `logger.use(name)` names a logger that is not in `loggers`. */
72
+ export const E_SPECTRUM_UNKNOWN_LOGGER = createError<[string, string]>(
73
+ '[spectrum] Unknown logger "%s". Registered: %s',
74
+ "E_SPECTRUM_UNKNOWN_LOGGER",
75
+ );
76
+
77
+ /** The `services/main` logger was used before `SpectrumProvider` booted. */
78
+ export const E_SPECTRUM_NOT_BOOTED = createError(
79
+ "[spectrum] Logger singleton accessed before SpectrumProvider.boot() ran. " +
80
+ "Check that `@c9up/spectrum/provider` is listed in your reamrc.ts providers.",
81
+ "E_SPECTRUM_NOT_BOOTED",
82
+ );
83
+
84
+ /** A `FakeLogger` assertion failed. */
85
+ export const E_SPECTRUM_ASSERTION_FAILED = createError<[string]>(
86
+ "[spectrum] %s",
87
+ "E_SPECTRUM_ASSERTION_FAILED",
88
+ );
89
+
90
+ /** A `FakeLogger` assertion got an empty `containing`. */
91
+ export const E_SPECTRUM_INVALID_PREDICATE = createError(
92
+ "[spectrum] FakeLogger: `containing` predicate cannot be an empty string — it would match every captured message.",
93
+ "E_SPECTRUM_INVALID_PREDICATE",
94
+ );
package/src/format.ts ADDED
@@ -0,0 +1,105 @@
1
+ /**
2
+ * printf interpolation of a log message, with upstream's rules.
3
+ *
4
+ * Node's `util.format` is not what upstream runs, and the difference is a
5
+ * leak: it inspects an object for `%s`, `%o` and `%O` with no redaction, knows
6
+ * `%c` (which swallows an argument), and appends every argument no token took
7
+ * to the end of the message. A message that carries request data then decides,
8
+ * by its content, what of the remaining arguments ends up in clear in `msg`.
9
+ *
10
+ * These are the rules of the formatter upstream uses: `%s` is `String(value)`,
11
+ * `%d` / `%f` a number, `%i` an integer, `%%` a percent sign that consumes
12
+ * nothing, `%j` / `%o` / `%O` the value through `stringify` — which the logger
13
+ * hands in already serialised and redacted — and an argument no token takes
14
+ * is dropped. Any other `%x` is left as written.
15
+ */
16
+
17
+ /** Turns a value interpolated by `%j`, `%o` or `%O` into text. */
18
+ export type InterpolationStringify = (value: unknown) => string;
19
+
20
+ const PERCENT = 37;
21
+ const LOWER_D = 100;
22
+ const LOWER_F = 102;
23
+ const LOWER_I = 105;
24
+ const LOWER_J = 106;
25
+ const LOWER_O = 111;
26
+ const UPPER_O = 79;
27
+ const LOWER_S = 115;
28
+
29
+ /** `String(value)`, without letting a throwing `toString` take the line down. */
30
+ function asText(value: unknown): string {
31
+ try {
32
+ return String(value);
33
+ } catch {
34
+ return "[unprintable]";
35
+ }
36
+ }
37
+
38
+ /** `Number(value)`, which throws on a symbol or an object without a primitive. */
39
+ function asNumber(value: unknown, integer: boolean): string {
40
+ try {
41
+ const number = Number(value);
42
+ return String(integer ? Math.floor(number) : number);
43
+ } catch {
44
+ return "NaN";
45
+ }
46
+ }
47
+
48
+ /**
49
+ * The message with its tokens replaced by `args`. Without arguments the
50
+ * template is returned as written, `%%` included.
51
+ */
52
+ export function formatMessage(
53
+ template: string,
54
+ args: readonly unknown[],
55
+ stringify: InterpolationStringify,
56
+ ): string {
57
+ if (args.length === 0) return template;
58
+ let out = "";
59
+ let argIndex = 0;
60
+ let lastPos = -1;
61
+ const length = template.length;
62
+ for (let i = 0; i < length; i++) {
63
+ if (template.charCodeAt(i) !== PERCENT || i + 1 >= length) continue;
64
+ lastPos = lastPos > -1 ? lastPos : 0;
65
+ const arg = args[argIndex];
66
+ const available = argIndex < args.length;
67
+ let replacement: string | undefined;
68
+ switch (template.charCodeAt(i + 1)) {
69
+ case LOWER_D:
70
+ case LOWER_F:
71
+ if (available && arg != null) replacement = asNumber(arg, false);
72
+ break;
73
+ case LOWER_I:
74
+ if (available && arg != null) replacement = asNumber(arg, true);
75
+ break;
76
+ case LOWER_J:
77
+ case LOWER_O:
78
+ case UPPER_O:
79
+ if (!available || arg === undefined) break;
80
+ if (typeof arg === "string") replacement = `'${arg}'`;
81
+ else if (typeof arg === "function") {
82
+ replacement = arg.name || "<anonymous>";
83
+ } else replacement = stringify(arg);
84
+ break;
85
+ case LOWER_S:
86
+ if (available) replacement = asText(arg);
87
+ break;
88
+ case PERCENT:
89
+ replacement = "%";
90
+ // A literal percent takes no argument.
91
+ argIndex--;
92
+ break;
93
+ }
94
+ if (replacement !== undefined) {
95
+ if (lastPos < i) out += template.slice(lastPos, i);
96
+ out += replacement;
97
+ lastPos = i + 2;
98
+ i++;
99
+ }
100
+ argIndex++;
101
+ }
102
+ if (lastPos === -1) return template;
103
+ if (lastPos < length) out += template.slice(lastPos);
104
+ return out;
105
+ }
package/src/index.ts CHANGED
@@ -13,7 +13,7 @@ export {
13
13
  export { FileChannel, type FileChannelConfig } from "./channels/FileChannel.js";
14
14
  export { defineConfig } from "./config.js";
15
15
  export { configure } from "./configure.js";
16
- export { SpectrumError } from "./errors.js";
16
+ export * as errors from "./errors.js";
17
17
  export { clearLogListeners, type LogListener, onLog } from "./events.js";
18
18
  export type { LineFormatters, TimestampOption } from "./jsonLine.js";
19
19
  export { Logger, type LogLevel } from "./Logger.js";