@c9up/spectrum 0.1.17 → 0.1.19

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 (90) hide show
  1. package/README.md +23 -6
  2. package/dist/Logger.d.ts +6 -2
  3. package/dist/Logger.d.ts.map +1 -1
  4. package/dist/Logger.js +195 -72
  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 +51 -11
  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/events.d.ts +38 -0
  31. package/dist/events.d.ts.map +1 -0
  32. package/dist/events.js +55 -0
  33. package/dist/events.js.map +1 -0
  34. package/dist/index.d.ts +8 -4
  35. package/dist/index.d.ts.map +1 -1
  36. package/dist/index.js +5 -2
  37. package/dist/index.js.map +1 -1
  38. package/dist/jsonLine.d.ts +49 -0
  39. package/dist/jsonLine.d.ts.map +1 -0
  40. package/dist/jsonLine.js +164 -0
  41. package/dist/jsonLine.js.map +1 -0
  42. package/dist/redact.d.ts +16 -3
  43. package/dist/redact.d.ts.map +1 -1
  44. package/dist/redact.js +121 -10
  45. package/dist/redact.js.map +1 -1
  46. package/dist/sanitize.d.ts +11 -5
  47. package/dist/sanitize.d.ts.map +1 -1
  48. package/dist/sanitize.js +36 -12
  49. package/dist/sanitize.js.map +1 -1
  50. package/dist/services/main.d.ts.map +1 -1
  51. package/dist/services/main.js +12 -1
  52. package/dist/services/main.js.map +1 -1
  53. package/dist/stdSerializers.d.ts +47 -0
  54. package/dist/stdSerializers.d.ts.map +1 -0
  55. package/dist/stdSerializers.js +128 -0
  56. package/dist/stdSerializers.js.map +1 -0
  57. package/dist/stringify.d.ts +33 -0
  58. package/dist/stringify.d.ts.map +1 -0
  59. package/dist/stringify.js +148 -0
  60. package/dist/stringify.js.map +1 -0
  61. package/dist/targets.d.ts +29 -7
  62. package/dist/targets.d.ts.map +1 -1
  63. package/dist/targets.js +130 -31
  64. package/dist/targets.js.map +1 -1
  65. package/dist/testing/FakeLogger.js +20 -5
  66. package/dist/testing/FakeLogger.js.map +1 -1
  67. package/dist/types.d.ts +71 -3
  68. package/dist/types.d.ts.map +1 -1
  69. package/dist/types.js +18 -2
  70. package/dist/types.js.map +1 -1
  71. package/package.json +1 -1
  72. package/src/Logger.ts +259 -79
  73. package/src/LoggerManager.ts +10 -3
  74. package/src/RustLogBridge.ts +59 -30
  75. package/src/SpectrumProvider.ts +69 -17
  76. package/src/channels/ConsoleChannel.ts +30 -14
  77. package/src/channels/FileChannel.ts +319 -220
  78. package/src/errors.ts +13 -0
  79. package/src/events.ts +62 -0
  80. package/src/index.ts +18 -3
  81. package/src/jsonLine.ts +222 -0
  82. package/src/redact.ts +133 -9
  83. package/src/sanitize.ts +36 -12
  84. package/src/services/main.ts +13 -1
  85. package/src/stdSerializers.ts +146 -0
  86. package/src/stringify.ts +175 -0
  87. package/src/targets.ts +193 -42
  88. package/src/testing/FakeLogger.ts +23 -5
  89. package/src/types.ts +97 -4
  90. package/stubs/config/logger.stub +1 -1
@@ -1,16 +1,30 @@
1
1
  import "./augmentations.js";
2
2
  import { ConsoleChannel } from "./channels/ConsoleChannel.js";
3
+ import { SpectrumError } from "./errors.js";
4
+ import { onLog } from "./events.js";
3
5
  import { Logger } from "./Logger.js";
4
6
  import { LoggerManager } from "./LoggerManager.js";
5
7
  import { clearLogger, getLogger, setLogger } from "./services/main.js";
6
- import { channelsFromTargets } from "./targets.js";
8
+ import { channelsFromConfig } from "./targets.js";
7
9
  import type {
8
10
  LogChannel,
9
11
  LogConfig,
10
12
  LoggerManagerConfig,
11
13
  LogLevelWithSilent,
12
14
  } from "./types.js";
13
- import { isLogLevelWithSilent, logLevel } from "./types.js";
15
+ import { assertLogLevel, logLevel } from "./types.js";
16
+
17
+ /** An emitter, as far as this provider is concerned. Structural: no import. */
18
+ function hasEmit(
19
+ value: unknown,
20
+ ): value is { emit(event: string, payload: unknown): unknown } {
21
+ return (
22
+ typeof value === "object" &&
23
+ value !== null &&
24
+ "emit" in value &&
25
+ typeof value.emit === "function"
26
+ );
27
+ }
14
28
 
15
29
  /** A channel that owns a resource (e.g. a FileChannel WriteStream) to release on shutdown. */
16
30
  function hasClose(
@@ -32,13 +46,17 @@ function isPartialLogConfig(value: unknown): value is Partial<LogConfig> {
32
46
  return typeof value === "object" && value !== null;
33
47
  }
34
48
 
49
+ /**
50
+ * The slice of a container the provider uses. Answers `unknown` rather than a
51
+ * caller-chosen `T`: what comes back is checked, not asserted.
52
+ */
35
53
  interface SpectrumContainer {
36
54
  singleton(token: unknown, factory: () => unknown): void;
37
- resolve<T = unknown>(token: unknown): Promise<T>;
55
+ resolve(token: unknown): Promise<unknown>;
38
56
  }
39
57
 
40
58
  interface SpectrumConfigStore {
41
- get<T = unknown>(key: string): T | undefined;
59
+ get(key: string): unknown;
42
60
  }
43
61
 
44
62
  export interface SpectrumAppContext {
@@ -55,7 +73,7 @@ export default class SpectrumProvider {
55
73
  constructor(protected app: SpectrumAppContext) {}
56
74
 
57
75
  register() {
58
- const raw = this.app.config.get<unknown>("logger");
76
+ const raw = this.app.config.get("logger");
59
77
  const managerConfig = this.#normalize(raw);
60
78
 
61
79
  // Collect every channel across all loggers so shutdown can release them.
@@ -70,18 +88,51 @@ export default class SpectrumProvider {
70
88
  // token stays bound beside it: it is what every existing
71
89
  // `container.make(...)` asks for, and a token is not worth breaking an
72
90
  // application over.
73
- const logger = (): Promise<Logger> =>
74
- this.app.container.resolve<Logger>(Logger);
91
+ const logger = (): Promise<unknown> => this.app.container.resolve(Logger);
75
92
  this.app.container.singleton("spectrum.logger", logger);
76
93
  this.app.container.singleton("logger", logger);
77
94
  }
78
95
 
79
96
  async boot() {
80
- const logger = await this.app.container.resolve<Logger>(Logger);
97
+ const logger = await this.app.container.resolve(Logger);
98
+ 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
+ }
81
104
  this.#owned = logger;
82
105
  setLogger(logger);
106
+ await this.#bridgeLogEvents();
83
107
  }
84
108
 
109
+ /**
110
+ * Bridge spectrum's `onLog` registry onto the app emitter as `log:line`,
111
+ * the way atlas bridges its queries as `db:query`.
112
+ *
113
+ * That is what lets something outside the logger — the debug toolbar's log
114
+ * panel — see a line without importing spectrum. No-op when the container
115
+ * exposes no `events` emitter; `onLog` stays the way to observe.
116
+ */
117
+ async #bridgeLogEvents(): Promise<void> {
118
+ let emitter: unknown;
119
+ try {
120
+ emitter = await this.app.container.resolve("events");
121
+ } catch {
122
+ return; // no emitter bound
123
+ }
124
+ if (!hasEmit(emitter)) return;
125
+ // Idempotent: a boot that failed past this point and retried would
126
+ // otherwise emit every line twice.
127
+ this.#logBridge?.();
128
+ this.#logBridge = onLog((entry) => {
129
+ emitter.emit("log:line", entry);
130
+ });
131
+ }
132
+
133
+ /** Unsubscribe for the `onLog` → app-emitter bridge, torn down on shutdown. */
134
+ #logBridge: (() => void) | undefined;
135
+
85
136
  /**
86
137
  * Release channel resources (e.g. FileChannel WriteStreams) on shutdown.
87
138
  *
@@ -94,6 +145,8 @@ export default class SpectrumProvider {
94
145
  // Release the module-level singleton first, while it is still ours: past
95
146
  // this point the channels are closing, and a logger reachable through
96
147
  // `services/main` would be writing into streams that have ended.
148
+ this.#logBridge?.();
149
+ this.#logBridge = undefined;
97
150
  if (this.#owned !== undefined && getLogger() === this.#owned) clearLogger();
98
151
  this.#owned = undefined;
99
152
  const results = await Promise.allSettled(
@@ -146,9 +199,12 @@ export default class SpectrumProvider {
146
199
  }
147
200
 
148
201
  #normalizeLogger(cfg: Partial<LogConfig>): LogConfig {
149
- const level = isLogLevelWithSilent(cfg.level)
150
- ? cfg.level
151
- : logLevel(process.env.LOG_LEVEL);
202
+ // An invalid level in the config is a config error, not a cue to take
203
+ // whatever the environment says instead.
204
+ const level =
205
+ cfg.level === undefined
206
+ ? logLevel(process.env.LOG_LEVEL)
207
+ : assertLogLevel(cfg.level);
152
208
  // An AdonisJS `config/logger.ts` declares its output as
153
209
  // `transport.targets`, not as channels. It has to be converted HERE:
154
210
  // filling `channels` in with the console fallback below is what stopped
@@ -159,16 +215,12 @@ export default class SpectrumProvider {
159
215
  return { ...cfg, level, channels };
160
216
  }
161
217
 
162
- /** Explicit channels, else the declared targets, else a pretty console. */
218
+ /** Explicit channels, else the declared destination or targets, else a pretty console. */
163
219
  #channelsFor(
164
220
  cfg: Partial<LogConfig>,
165
221
  level: LogLevelWithSilent,
166
222
  ): LogChannel[] {
167
223
  if (cfg.channels && cfg.channels.length > 0) return cfg.channels;
168
- const declared = cfg.transport?.targets;
169
- if (declared && declared.length > 0) {
170
- return channelsFromTargets(declared, level);
171
- }
172
- return [new ConsoleChannel("pretty")];
224
+ return channelsFromConfig(cfg, level) ?? [new ConsoleChannel("pretty")];
173
225
  }
174
226
  }
@@ -4,16 +4,31 @@
4
4
  * @implements FR57, FR58
5
5
  */
6
6
 
7
+ import { jsonLine, lineOptionsFor } from "../jsonLine.js";
7
8
  import { sanitizeLogValue } from "../sanitize.js";
9
+ import { stringifyRecord } from "../stringify.js";
8
10
  import type { LogChannel, LogEntry } from "../types.js";
9
11
  import { logEntryExtras } from "../types.js";
10
12
 
13
+ export interface ConsoleChannelOptions {
14
+ /**
15
+ * Write every level to this one stream. Without it, error and fatal go to
16
+ * stderr and the rest to stdout.
17
+ */
18
+ stream?: "stdout" | "stderr";
19
+ }
20
+
11
21
  export class ConsoleChannel implements LogChannel {
12
22
  name = "console";
13
23
  #format: "pretty" | "json";
24
+ readonly #stream: "stdout" | "stderr" | undefined;
14
25
 
15
- constructor(format: "pretty" | "json" = "pretty") {
26
+ constructor(
27
+ format: "pretty" | "json" = "pretty",
28
+ options: ConsoleChannelOptions = {},
29
+ ) {
16
30
  this.#format = format;
31
+ this.#stream = options.stream;
17
32
  }
18
33
 
19
34
  write(entry: LogEntry): void {
@@ -27,15 +42,7 @@ export class ConsoleChannel implements LogChannel {
27
42
  #writeJson(entry: LogEntry): void {
28
43
  // Structural fields first, then merged root fields spread flat (pino
29
44
  // output parity). Legacy `data` (if present) stays under its own key.
30
- const output = JSON.stringify({
31
- timestamp: entry.timestamp,
32
- level: entry.level,
33
- module: entry.module,
34
- message: entry.message,
35
- correlationId: entry.correlationId,
36
- data: entry.data,
37
- ...logEntryExtras(entry),
38
- });
45
+ const output = jsonLine(entry);
39
46
  this.#writeToStream(entry.level, `${output}\n`);
40
47
  }
41
48
 
@@ -58,11 +65,14 @@ export class ConsoleChannel implements LogChannel {
58
65
  : "";
59
66
  const cid = cidRaw ? ` cid=${this.#sanitize(cidRaw)}` : "";
60
67
  // Prefer legacy `data`; otherwise render the merged root fields. JSON
61
- // encoding escapes control chars, so no CRLF can leak into the line.
68
+ // escapes C0 controls but not DEL, C1 or U+2028/2029, so the rendered
69
+ // data goes through the same sanitizer as the message.
62
70
  const extras = logEntryExtras(entry);
63
71
  const payload =
64
72
  entry.data ?? (Object.keys(extras).length > 0 ? extras : undefined);
65
- const dataStr = payload ? ` ${JSON.stringify(payload)}` : "";
73
+ const dataStr = payload
74
+ ? ` ${this.#sanitize(stringifyRecord(payload, lineOptionsFor(entry).limits))}`
75
+ : "";
66
76
  const message = this.#sanitize(entry.message);
67
77
  const module = this.#sanitize(entry.module);
68
78
 
@@ -72,9 +82,15 @@ export class ConsoleChannel implements LogChannel {
72
82
  );
73
83
  }
74
84
 
75
- /** Route error/fatal to stderr, others to stdout. */
85
+ /** The configured stream, else error/fatal to stderr and others to stdout. */
76
86
  #writeToStream(level: string, output: string): void {
77
- if (level === "error" || level === "fatal") {
87
+ if (this.#stream === "stdout") {
88
+ process.stdout.write(output);
89
+ } else if (
90
+ this.#stream === "stderr" ||
91
+ level === "error" ||
92
+ level === "fatal"
93
+ ) {
78
94
  process.stderr.write(output);
79
95
  } else {
80
96
  process.stdout.write(output);