@warlock.js/logger 5.29.0 → 5.30.0

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 (62) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.md +6 -6
  3. package/cjs/index.cjs +233 -29
  4. package/cjs/index.cjs.map +1 -1
  5. package/esm/channels/console-log.d.mts +1 -1
  6. package/esm/channels/console-log.d.mts.map +1 -1
  7. package/esm/channels/console-log.mjs +1 -1
  8. package/esm/channels/console-log.mjs.map +1 -1
  9. package/esm/channels/file-log.d.mts +1 -1
  10. package/esm/channels/file-log.d.mts.map +1 -1
  11. package/esm/channels/file-log.mjs +1 -1
  12. package/esm/channels/file-log.mjs.map +1 -1
  13. package/esm/channels/json-file-log.d.mts +1 -1
  14. package/esm/channels/json-file-log.d.mts.map +1 -1
  15. package/esm/channels/json-file-log.mjs +1 -1
  16. package/esm/channels/json-file-log.mjs.map +1 -1
  17. package/esm/channels/sentry-log.d.mts +1 -1
  18. package/esm/channels/sentry-log.d.mts.map +1 -1
  19. package/esm/channels/sentry-log.mjs +1 -1
  20. package/esm/channels/sentry-log.mjs.map +1 -1
  21. package/esm/index.d.mts +4 -3
  22. package/esm/index.mjs +3 -2
  23. package/esm/log-channel.d.mts +1 -1
  24. package/esm/log-channel.d.mts.map +1 -1
  25. package/esm/log-channel.mjs +1 -1
  26. package/esm/log-channel.mjs.map +1 -1
  27. package/esm/logger.d.mts +73 -18
  28. package/esm/logger.d.mts.map +1 -1
  29. package/esm/logger.mjs +152 -20
  30. package/esm/logger.mjs.map +1 -1
  31. package/esm/redact/default-keys.d.mts +1 -1
  32. package/esm/redact/default-keys.d.mts.map +1 -1
  33. package/esm/redact/default-keys.mjs +1 -1
  34. package/esm/redact/default-keys.mjs.map +1 -1
  35. package/esm/redact/index.mjs +1 -0
  36. package/esm/redact/mask-email.d.mts +40 -0
  37. package/esm/redact/mask-email.d.mts.map +1 -0
  38. package/esm/redact/mask-email.mjs +70 -0
  39. package/esm/redact/mask-email.mjs.map +1 -0
  40. package/esm/redact/redact.d.mts +1 -1
  41. package/esm/redact/redact.d.mts.map +1 -1
  42. package/esm/redact/redact.mjs +1 -1
  43. package/esm/redact/redact.mjs.map +1 -1
  44. package/esm/types.d.mts +9 -2
  45. package/esm/types.d.mts.map +1 -1
  46. package/esm/utils/capture-unhandled-errors.d.mts +1 -1
  47. package/esm/utils/capture-unhandled-errors.d.mts.map +1 -1
  48. package/esm/utils/capture-unhandled-errors.mjs +1 -1
  49. package/esm/utils/capture-unhandled-errors.mjs.map +1 -1
  50. package/esm/utils/clear-message.d.mts +1 -1
  51. package/esm/utils/clear-message.d.mts.map +1 -1
  52. package/esm/utils/clear-message.mjs +1 -1
  53. package/esm/utils/clear-message.mjs.map +1 -1
  54. package/esm/utils/safe-json-stringify.d.mts +1 -1
  55. package/esm/utils/safe-json-stringify.d.mts.map +1 -1
  56. package/esm/utils/safe-json-stringify.mjs +1 -1
  57. package/esm/utils/safe-json-stringify.mjs.map +1 -1
  58. package/llms-full.txt +6 -6
  59. package/package.json +4 -3
  60. package/skills/flush-logs-on-shutdown/SKILL.md +2 -2
  61. package/skills/logger-basics/SKILL.md +3 -3
  62. package/skills/write-custom-log-channel/SKILL.md +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"logger.d.mts","names":[],"sources":["../../../../../../logger/src/logger.ts"],"mappings":";;;;cAoCa,MAAA;;AAAb;;EAIS,QAAA,EAAU,UAAA;EAEV,EAAA;EA4BoB;;;;;EAAA,QArBnB,iBAAA;EA0EY;;;;;;EAAA,QAlEZ,QAAA;EAkLI;;;;;;EAAA,QA1KJ,YAAA;EAoMuB;;;EA/LxB,UAAA,CAAW,OAAA,EAAS,UAAA;EAsNX;;;EA7MT,SAAA,CAAU,MAAA;IACf,QAAA,GAAW,UAAA;IACX,WAAA,GAAc,cAAA;IACd,QAAA,GAAW,QAAA;IACX,MAAA,GAAS,YAAA;EAAA;EAsPU;;;;;;;;;;;EAtN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d,MAAA,WACA,OAAA,QACA,OAAA,GAAU,MAAA;EA0FV;;;EAjFK,IAAA,CACL,YAAA,EAAc,kBAAA,WACd,MAAA,WACA,OAAA,QACA,OAAA,GAAU,MAAA;EAgFV;;;EAvEK,IAAA,CACL,YAAA,EAAc,kBAAA,WACd,MAAA,WACA,OAAA,QACA,OAAA,GAAU,MAAA;EAsFA;;;EA7EL,KAAA,CACL,YAAA,EAAc,kBAAA,WACd,MAAA,WACA,OAAA,QACA,OAAA,GAAU,MAAA;EAuFe;;;EA9EpB,OAAA,CACL,YAAA,EAAc,kBAAA,WACd,MAAA,WACA,OAAA,QACA,OAAA,GAAU,MAAA;EAoHkB;;;;;;;;;EApGvB,KAAA,CACL,YAAA,EAAc,kBAAA,WACd,MAAA,WACA,OAAA,QACA,OAAA,GAAU,MAAA;EAmOD;;;;AAAwB;AA4CrC;;;;EA/PS,MAAA,CACL,SAAA,WACA,MAAA,UACA,MAAA,UACA,OAAA,OACA,OAAA,GAAU,MAAA;;;;;;;;;;;EAgBL,KAAA,CACL,MAAA,UACA,MAAA,YACE,KAAA,GAAQ,MAAA;;;;EAcL,OAAA,CAAQ,IAAA,WAAY,UAAA,CAdT,sBAAA;;;;EAqBX,SAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAmCM,KAAA,CAAM,OAAA;IAAW,OAAA;EAAA,IAA0B,OAAA;;;;;UA0D1C,YAAA;;;;;;;;;;;;;;;;;;;EAiCP,eAAA,CAAgB,MAAA,EAAQ,cAAA;;;;;EAyBxB,gBAAA;AAAA;;;;;cAeI,wBAAA;;;;;;;;;;;;;;;cA4CA,GAAA,EAAG,MAAe"}
package/esm/logger.mjs CHANGED
@@ -3,7 +3,7 @@ import "./redact/index.mjs";
3
3
  import { clearMessage } from "./utils/clear-message.mjs";
4
4
  import { Random } from "@mongez/reinforcements";
5
5
 
6
- //#region ../logger/src/logger.ts
6
+ //#region ../../packages/logger/src/logger.ts
7
7
  const SIGNAL_EVENTS = new Set([
8
8
  "SIGINT",
9
9
  "SIGTERM",
@@ -31,6 +31,8 @@ var Logger = class {
31
31
  this.channels = [];
32
32
  this.id = "logger-" + Random.string(32);
33
33
  this.autoFlushHandlers = /* @__PURE__ */ new Map();
34
+ this.pendingDeliveries = /* @__PURE__ */ new Map();
35
+ this.channelErrorHandler = reportChannelError;
34
36
  }
35
37
  /**
36
38
  * Add a new channel
@@ -47,6 +49,21 @@ var Logger = class {
47
49
  if (config.autoFlushOn) this.enableAutoFlush(config.autoFlushOn);
48
50
  if (config.minLevel !== void 0) this.setMinLevel(config.minLevel);
49
51
  if (config.redact !== void 0) this.setRedact(config.redact);
52
+ if (config.onChannelError) this.onChannelError(config.onChannelError);
53
+ return this;
54
+ }
55
+ /**
56
+ * Handle a channel's delivery failure. Logging is fire-and-forget, so a
57
+ * channel that throws or rejects never reaches the call site and never
58
+ * becomes an unhandled rejection; it goes to this handler instead. The
59
+ * default writes one line to stderr. The handler must not log through this
60
+ * logger (a failing channel would loop).
61
+ *
62
+ * @example
63
+ * log.onChannelError((error, channel) => metrics.increment(`log.${channel.name}.failed`));
64
+ */
65
+ onChannelError(handler) {
66
+ this.channelErrorHandler = handler;
50
67
  return this;
51
68
  }
52
69
  /**
@@ -124,21 +141,62 @@ var Logger = class {
124
141
  * — each channel sees its own shallow clone so one channel cannot observe
125
142
  * another's mutations (e.g. a later terminal channel still sees the original
126
143
  * colored message).
144
+ *
145
+ * Synchronous and fire-and-forget: it returns the logger, not a promise.
146
+ * Async channel deliveries are tracked and awaited by {@link flush}; a
147
+ * channel that throws or rejects is isolated from the others and reported
148
+ * to {@link onChannelError}.
127
149
  */
128
- async log(data) {
150
+ log(data) {
129
151
  if (this.minLevel && LEVEL_RANK[data.type] < LEVEL_RANK[this.minLevel]) return this;
130
- const baseEntry = applyRedact(data, this.redactConfig);
131
- for (const channel of this.channels) {
152
+ let baseEntry;
153
+ try {
154
+ baseEntry = applyRedact(data, this.redactConfig);
155
+ } catch (error) {
156
+ for (const channel of this.channels) this.reportChannelError(error, channel, redactionFailedEntry(data));
157
+ return this;
158
+ }
159
+ for (const channel of this.channels) this.deliver(channel, data, baseEntry);
160
+ return this;
161
+ }
162
+ /**
163
+ * Prepare and hand one entry to one channel, isolating its failure (a
164
+ * channel redaction that throws included) and tracking an async delivery
165
+ * until it settles.
166
+ */
167
+ deliver(channel, data, baseEntry) {
168
+ let payload = baseEntry;
169
+ let result;
170
+ try {
132
171
  const channelRedact = channel.getRedactConfig?.();
133
- const effectiveRedact = channelRedact ? mergeRedact(this.redactConfig, channelRedact) : void 0;
134
- let payload = effectiveRedact ? applyRedact(data, effectiveRedact) : baseEntry;
172
+ if (channelRedact) payload = applyRedact(data, mergeRedact(this.redactConfig, channelRedact));
135
173
  if (channel.terminal === false) payload = {
136
174
  ...payload,
137
175
  message: clearMessage(payload.message)
138
176
  };
139
- channel.log(payload);
177
+ result = channel.log(payload);
178
+ } catch (error) {
179
+ this.reportChannelError(error, channel, payload);
180
+ return;
140
181
  }
141
- return this;
182
+ if (!result || typeof result.then !== "function") return;
183
+ let pending = this.pendingDeliveries.get(channel);
184
+ if (!pending) {
185
+ pending = /* @__PURE__ */ new Set();
186
+ this.pendingDeliveries.set(channel, pending);
187
+ }
188
+ const tracked = pending;
189
+ const delivery = Promise.resolve(result).catch((error) => this.reportChannelError(error, channel, payload)).finally(() => {
190
+ tracked.delete(delivery);
191
+ if (tracked.size === 0 && this.pendingDeliveries.get(channel) === tracked) this.pendingDeliveries.delete(channel);
192
+ });
193
+ tracked.add(delivery);
194
+ }
195
+ reportChannelError(error, channel, entry) {
196
+ try {
197
+ const outcome = this.channelErrorHandler(error, channel, entry);
198
+ if (outcome && typeof outcome.then === "function") outcome.then(void 0, () => {});
199
+ } catch {}
142
200
  }
143
201
  /**
144
202
  * Make debug log
@@ -234,7 +292,9 @@ var Logger = class {
234
292
  for (const channel of this.channels) if (channel.flushSync) channel.flushSync();
235
293
  }
236
294
  /**
237
- * Asynchronously drain every channel that implements `flush()`.
295
+ * Wait for every in-flight async delivery, then drain every channel that
296
+ * implements `flush()` — bounded by `timeout` (default
297
+ * {@link DEFAULT_FLUSH_TIMEOUT_MS}).
238
298
  *
239
299
  * Unlike {@link flushSync}, this awaits each channel's async I/O — the
240
300
  * correct call for a graceful shutdown that can afford to wait
@@ -242,24 +302,68 @@ var Logger = class {
242
302
  * `process.exit`). A channel whose delivery is async (a network transport,
243
303
  * an async disk write) implements `flush()`, not `flushSync()`.
244
304
  *
245
- * Channels are isolated: a channel whose flush rejects can neither prevent
246
- * the others from draining nor escape as an unhandled rejection. Channels
247
- * without `flush()` are skipped.
305
+ * Channels drain concurrently and independently: each waits for its own
306
+ * pending deliveries (including ones logged while the flush runs), then
307
+ * runs its `flush()`. A channel whose delivery hangs therefore cannot hold
308
+ * up another channel's drain, and a channel whose flush rejects can neither
309
+ * stop the others nor escape as an unhandled rejection. When `timeout`
310
+ * elapses, `flush()` resolves anyway and each channel still draining is
311
+ * reported to {@link onChannelError}. Channels without `flush()` only wait
312
+ * for their deliveries.
248
313
  *
249
314
  * @example
250
315
  * async function shutdown() {
251
316
  * await httpServer.close();
252
- * await log.flush();
317
+ * await log.flush({ timeout: 3000 });
253
318
  * process.exit(0);
254
319
  * }
255
320
  */
256
- async flush() {
257
- await Promise.allSettled(this.channels.map(async (channel) => {
258
- if (!channel.flush) return;
321
+ async flush(options = {}) {
322
+ const timeout = options.timeout ?? 5e3;
323
+ const draining = new Set(this.channels);
324
+ for (const channel of this.pendingDeliveries.keys()) draining.add(channel);
325
+ const unfinished = new Set(draining);
326
+ const drains = [...draining].map(async (channel) => {
259
327
  try {
260
- await channel.flush();
261
- } catch {}
262
- }));
328
+ await this.drainChannel(channel);
329
+ } catch {} finally {
330
+ unfinished.delete(channel);
331
+ }
332
+ });
333
+ const settled = Promise.allSettled(drains).then(() => false);
334
+ if (!Number.isFinite(timeout)) {
335
+ await settled;
336
+ return;
337
+ }
338
+ let resolveTimeout;
339
+ const timeoutReached = new Promise((resolve) => {
340
+ resolveTimeout = resolve;
341
+ });
342
+ const timer = setTimeout(() => resolveTimeout(true), Math.max(0, timeout));
343
+ timer.unref?.();
344
+ const timedOut = await Promise.race([settled, timeoutReached]);
345
+ clearTimeout(timer);
346
+ if (!timedOut) return;
347
+ for (const channel of unfinished) this.reportChannelError(/* @__PURE__ */ new Error(`flush timed out after ${timeout}ms; entries still in flight may be lost`), channel, {
348
+ type: "warn",
349
+ module: "logger",
350
+ action: "flush",
351
+ message: "flush timed out"
352
+ });
353
+ }
354
+ /**
355
+ * Wait until the channel has no delivery in flight, run its `flush()`, and
356
+ * repeat while that flush let new deliveries in.
357
+ */
358
+ async drainChannel(channel) {
359
+ do {
360
+ let pending = this.pendingDeliveries.get(channel);
361
+ while (pending && pending.size > 0) {
362
+ await Promise.allSettled([...pending]);
363
+ pending = this.pendingDeliveries.get(channel);
364
+ }
365
+ if (channel.flush) await channel.flush();
366
+ } while ((this.pendingDeliveries.get(channel)?.size ?? 0) > 0);
263
367
  }
264
368
  /**
265
369
  * Register one process-level handler per event that calls `flushSync()`
@@ -305,6 +409,34 @@ var Logger = class {
305
409
  }
306
410
  };
307
411
  /**
412
+ * Default `timeout` of {@link Logger.flush}: long enough for a healthy network
413
+ * channel, short enough that a hung one cannot eat a shutdown budget.
414
+ */
415
+ const DEFAULT_FLUSH_TIMEOUT_MS = 5e3;
416
+ /**
417
+ * What the error handler receives when the logger-wide redaction itself
418
+ * failed: the entry's identity only, never the unredacted message or context.
419
+ */
420
+ function redactionFailedEntry(data) {
421
+ return {
422
+ type: data.type,
423
+ module: data.module,
424
+ action: data.action,
425
+ message: "[entry dropped: redaction failed]"
426
+ };
427
+ }
428
+ /**
429
+ * Default {@link ChannelErrorHandler}: one stderr line per failure. Written
430
+ * directly to the stream, never through a logger, so a broken channel cannot
431
+ * recurse.
432
+ */
433
+ function reportChannelError(error, channel) {
434
+ const reason = error instanceof Error ? error.message : String(error);
435
+ try {
436
+ process.stderr.write(`[@warlock.js/logger] channel "${channel.name}" failed to log: ${reason}\n`);
437
+ } catch {}
438
+ }
439
+ /**
308
440
  * The package singleton. Use this for everyday logging — `log.info(...)`,
309
441
  * `log.error(...)`, `log.configure(...)`. Custom logger instances can be
310
442
  * created by instantiating `Logger` directly.
@@ -321,5 +453,5 @@ var Logger = class {
321
453
  const log = new Logger();
322
454
 
323
455
  //#endregion
324
- export { Logger, log };
456
+ export { DEFAULT_FLUSH_TIMEOUT_MS, Logger, log };
325
457
  //# sourceMappingURL=logger.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"logger.mjs","names":[],"sources":["../../../../../../logger/src/logger.ts"],"sourcesContent":["import { Random } from \"@mongez/reinforcements\";\nimport type { LogChannel } from \"./log-channel\";\nimport { applyRedact, mergeRedact } from \"./redact\";\nimport type {\n AutoFlushEvent,\n LoggingData,\n LogLevel,\n OmittedLoggingData,\n RedactConfig,\n} from \"./types\";\nimport { clearMessage } from \"./utils/clear-message\";\n\nconst SIGNAL_EVENTS: ReadonlySet<AutoFlushEvent> = new Set([\n \"SIGINT\",\n \"SIGTERM\",\n \"SIGHUP\",\n \"SIGBREAK\",\n \"SIGUSR2\",\n]);\n\n/**\n * Severity ranks used by `setMinLevel`. Higher number = more severe. The\n * ordering matches conventional log-level hierarchies: `debug` is noisiest\n * and easiest to drop; `error` is the loudest and never dropped by the\n * minimum-level filter. `success` sits beside `info` — it's an informational\n * outcome, not a warning.\n */\nconst LEVEL_RANK: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n success: 1,\n warn: 2,\n error: 3,\n fatal: 4,\n};\n\nexport class Logger {\n /**\n * Current channel\n */\n public channels: LogChannel[] = [];\n\n public id = \"logger-\" + Random.string(32);\n\n /**\n * Registered auto-flush handlers, keyed by event name. Stored so repeated\n * calls to `enableAutoFlush` replace rather than stack, and so\n * `disableAutoFlush` can remove them cleanly.\n */\n private autoFlushHandlers = new Map<AutoFlushEvent, () => void>();\n\n /**\n * Logger-wide minimum severity. When set, entries below this level are\n * dropped before any channel is invoked — cheaper than per-channel `levels`\n * filters because the fan-out loop is skipped entirely. `undefined` means\n * no minimum (every entry reaches every channel that accepts it).\n */\n private minLevel?: LogLevel;\n\n /**\n * Logger-wide redaction floor. Applied once before fan-out — every\n * channel receives an entry with these paths already censored. Channel\n * configs can extend the path list (additive); they cannot remove paths\n * set here.\n */\n private redactConfig?: RedactConfig;\n\n /**\n * Add a new channel\n */\n public addChannel(channel: LogChannel) {\n this.channels.push(channel);\n\n return this;\n }\n\n /**\n * Set base configurations\n */\n public configure(config: {\n channels?: LogChannel[];\n autoFlushOn?: AutoFlushEvent[];\n minLevel?: LogLevel;\n redact?: RedactConfig;\n }) {\n if (config.channels) {\n this.channels = config.channels;\n }\n\n if (config.autoFlushOn) {\n this.enableAutoFlush(config.autoFlushOn);\n }\n\n if (config.minLevel !== undefined) {\n this.setMinLevel(config.minLevel);\n }\n\n if (config.redact !== undefined) {\n this.setRedact(config.redact);\n }\n\n return this;\n }\n\n /**\n * Set the logger-wide redaction floor. Applied to every entry before\n * fan-out; channel configs add more paths on top, never fewer. Pass\n * `undefined` to clear.\n *\n * @example\n * log.setRedact({\n * paths: [\"context.password\", \"context.*.token\"],\n * censor: \"[REDACTED]\",\n * });\n */\n public setRedact(config: RedactConfig | undefined): this {\n this.redactConfig = config;\n return this;\n }\n\n /**\n * Read the active logger-wide redact config (or `undefined`).\n */\n public getRedact(): RedactConfig | undefined {\n return this.redactConfig;\n }\n\n /**\n * Drop every entry whose severity is below `level` before fan-out. Cheaper\n * than per-channel `levels` filters because the loop never runs and no\n * channel receives the entry. Pass `undefined` to clear and accept all\n * levels again.\n *\n * @example\n * // production: silence debug noise everywhere at once\n * logger.setMinLevel(\"info\");\n */\n public setMinLevel(level: LogLevel | undefined): this {\n this.minLevel = level;\n return this;\n }\n\n /**\n * Read the active minimum severity (or `undefined` when none is set).\n */\n public getMinLevel(): LogLevel | undefined {\n return this.minLevel;\n }\n\n /**\n * Set channels\n */\n public setChannels(channels: LogChannel[]) {\n this.channels = channels;\n\n return this;\n }\n\n /**\n * Normalize log data to a single object\n */\n private normalizeLogData(\n dataOrModule: LoggingData | OmittedLoggingData | string,\n action?: string,\n message: any = \"\",\n level?: LogLevel,\n context?: Record<string, any>,\n ): LoggingData {\n if (typeof dataOrModule === \"object\") {\n // If level is provided, override type\n return {\n type: (level || (dataOrModule as any).type || \"info\") as LogLevel,\n module: dataOrModule.module,\n action: dataOrModule.action,\n message: dataOrModule.message,\n ...(context ? { context } : dataOrModule.context ? { context: dataOrModule.context } : {}),\n };\n }\n return {\n type: (level || \"info\") as LogLevel,\n module: dataOrModule,\n action: action as string,\n message,\n ...(context ? { context } : {}),\n };\n }\n\n /**\n * Make log\n *\n * Fans out a single log entry to every registered channel. Non-terminal\n * channels receive a copy whose `message` has had ANSI color codes stripped\n * — each channel sees its own shallow clone so one channel cannot observe\n * another's mutations (e.g. a later terminal channel still sees the original\n * colored message).\n */\n public async log(data: LoggingData) {\n if (this.minLevel && LEVEL_RANK[data.type] < LEVEL_RANK[this.minLevel]) {\n return this;\n }\n\n // Apply the logger-wide redact floor once. Every channel sees the\n // result; no channel can undo a logger-wide redaction (additive-only\n // semantics).\n const baseEntry = applyRedact(data, this.redactConfig);\n\n for (const channel of this.channels) {\n const channelRedact = channel.getRedactConfig?.();\n const effectiveRedact = channelRedact\n ? mergeRedact(this.redactConfig, channelRedact)\n : undefined;\n\n // When the channel adds paths, redact again from `data` rather than\n // from `baseEntry` so the merged config (which already contains the\n // logger-wide paths) does the full pass — avoids double-cloning the\n // already-redacted base.\n let payload = effectiveRedact ? applyRedact(data, effectiveRedact) : baseEntry;\n\n if (channel.terminal === false) {\n payload = { ...payload, message: clearMessage(payload.message) };\n }\n\n channel.log(payload);\n }\n\n return this;\n }\n\n /**\n * Make debug log\n */\n public debug(\n dataOrModule: OmittedLoggingData | string,\n action?: string,\n message: any = \"\",\n context?: Record<string, any>,\n ) {\n const data = this.normalizeLogData(dataOrModule, action, message, \"debug\", context);\n return this.log(data);\n }\n\n /**\n * Make info log\n */\n public info(\n dataOrModule: OmittedLoggingData | string,\n action?: string,\n message: any = \"\",\n context?: Record<string, any>,\n ) {\n const data = this.normalizeLogData(dataOrModule, action, message, \"info\", context);\n return this.log(data);\n }\n\n /**\n * Make warn log\n */\n public warn(\n dataOrModule: OmittedLoggingData | string,\n action?: string,\n message: any = \"\",\n context?: Record<string, any>,\n ) {\n const data = this.normalizeLogData(dataOrModule, action, message, \"warn\", context);\n return this.log(data);\n }\n\n /**\n * Make error log\n */\n public error(\n dataOrModule: OmittedLoggingData | string,\n action?: string,\n message: any = \"\",\n context?: Record<string, any>,\n ) {\n const data = this.normalizeLogData(dataOrModule, action, message, \"error\", context);\n return this.log(data);\n }\n\n /**\n * Make success log\n */\n public success(\n dataOrModule: OmittedLoggingData | string,\n action?: string,\n message: any = \"\",\n context?: Record<string, any>,\n ) {\n const data = this.normalizeLogData(dataOrModule, action, message, \"success\", context);\n\n return this.log(data);\n }\n\n /**\n * Make fatal log — for unrecoverable failures where the application is going\n * down (failed bootstrap, lost connection to a required dependency that the\n * caller has decided not to retry, an `uncaughtException`).\n *\n * Identical shape to {@link error}; the level is purely informational —\n * `fatal` does NOT auto-flush or exit. The caller decides whether to call\n * `await log.flush()` and `process.exit(...)`.\n */\n public fatal(\n dataOrModule: OmittedLoggingData | string,\n action?: string,\n message: any = \"\",\n context?: Record<string, any>,\n ) {\n const data = this.normalizeLogData(dataOrModule, action, message, \"fatal\", context);\n\n return this.log(data);\n }\n\n /**\n * Log an `error` entry when `condition` is falsy. No-op otherwise — the\n * entry is never built and channels are not invoked, so this is genuinely\n * free in the happy path. Mirrors the spirit of `console.assert` but routes\n * through the logger pipeline so persistent channels capture failures.\n *\n * @example\n * log.assert(user !== null, \"auth\", \"session\", \"user vanished mid-flight\", { sessionId });\n */\n public assert(\n condition: unknown,\n module: string,\n action: string,\n message: any,\n context?: Record<string, any>,\n ): Promise<Logger> | Logger {\n if (condition) return this;\n return this.error(module, action, message, context);\n }\n\n /**\n * Start a duration timer. The returned function emits an `info` entry\n * with `completed in <ms>ms` and a `durationMs` field in `context` when\n * called. Pass an object to `end()` to merge extra fields into context.\n *\n * @example\n * const end = log.timer(\"db\", \"users.findById\");\n * const user = await usersRepo.findById(id);\n * end({ id, found: !!user });\n */\n public timer(\n module: string,\n action: string,\n ): (extra?: Record<string, any>) => Promise<Logger> {\n const startedAt = Date.now();\n return (extra?: Record<string, any>) => {\n const durationMs = Date.now() - startedAt;\n return this.info(module, action, `completed in ${durationMs}ms`, {\n durationMs,\n ...(extra ?? {}),\n });\n };\n }\n\n /**\n * Get channel by name\n */\n public channel(name: string) {\n return this.channels.find((channel) => channel.name === name);\n }\n\n /**\n * Synchronously flush logs\n */\n public flushSync() {\n for (const channel of this.channels) {\n if (channel.flushSync) {\n channel.flushSync();\n }\n }\n }\n\n /**\n * Asynchronously drain every channel that implements `flush()`.\n *\n * Unlike {@link flushSync}, this awaits each channel's async I/O — the\n * correct call for a graceful shutdown that can afford to wait\n * (`await log.flush()` after closing the HTTP server, before\n * `process.exit`). A channel whose delivery is async (a network transport,\n * an async disk write) implements `flush()`, not `flushSync()`.\n *\n * Channels are isolated: a channel whose flush rejects can neither prevent\n * the others from draining nor escape as an unhandled rejection. Channels\n * without `flush()` are skipped.\n *\n * @example\n * async function shutdown() {\n * await httpServer.close();\n * await log.flush();\n * process.exit(0);\n * }\n */\n public async flush(): Promise<void> {\n await Promise.allSettled(\n this.channels.map(async (channel) => {\n if (!channel.flush) {\n return;\n }\n\n try {\n await channel.flush();\n } catch {\n // A single channel must never break shutdown for the others —\n // a graceful drain is best-effort across every channel.\n }\n }),\n );\n }\n\n /**\n * Register one process-level handler per event that calls `flushSync()`\n * before the process terminates.\n *\n * For signal events (`SIGINT`, `SIGTERM`, `SIGHUP`, `SIGBREAK`, `SIGUSR2`)\n * the handler flushes and then re-raises the signal so Node's default exit\n * behavior runs. For `beforeExit`, the handler flushes in place — Node exits\n * naturally afterwards.\n *\n * Idempotent: calling with the same events replaces the previous handlers.\n * Call `disableAutoFlush()` to unregister.\n *\n * @example\n * log.configure({\n * channels: [new ConsoleLog(), new FileLog()],\n * autoFlushOn: [\"SIGINT\", \"SIGTERM\", \"beforeExit\"],\n * });\n */\n public enableAutoFlush(events: AutoFlushEvent[]): this {\n this.disableAutoFlush();\n\n for (const event of events) {\n const handler = SIGNAL_EVENTS.has(event)\n ? () => {\n this.flushSync();\n process.off(event, handler);\n process.kill(process.pid, event as NodeJS.Signals);\n }\n : () => {\n this.flushSync();\n };\n\n process.on(event, handler);\n this.autoFlushHandlers.set(event, handler);\n }\n\n return this;\n }\n\n /**\n * Remove every handler previously registered by `enableAutoFlush`.\n * Safe to call when no handlers are registered.\n */\n public disableAutoFlush(): this {\n for (const [event, handler] of this.autoFlushHandlers) {\n process.off(event, handler);\n }\n\n this.autoFlushHandlers.clear();\n\n return this;\n }\n}\n\n/**\n * The package singleton. Use this for everyday logging — `log.info(...)`,\n * `log.error(...)`, `log.configure(...)`. Custom logger instances can be\n * created by instantiating `Logger` directly.\n *\n * The name is intentionally short: `log` reads naturally at the call site\n * (`log.info(\"auth\", \"login\", \"ok\")`) and matches the convention used in\n * pino, bunyan, and most JS logging tutorials.\n *\n * Note that `log` is a `Logger` instance, **not** a function — the bare\n * callable form was removed when the dual `log` / `logger` exports were\n * collapsed into a single name. Use `log.info(...)` (or any other level\n * shortcut) to emit entries.\n */\nexport const log = new Logger();\n"],"mappings":";;;;;;AAYA,MAAM,gBAA6C,IAAI,IAAI;CACzD;CACA;CACA;CACA;CACA;AACF,CAAC;;;;;;;;AASD,MAAM,aAAuC;CAC3C,OAAO;CACP,MAAM;CACN,SAAS;CACT,MAAM;CACN,OAAO;CACP,OAAO;AACT;AAEA,IAAa,SAAb,MAAoB;;kBAIc,CAAC;YAErB,YAAY,OAAO,OAAO,EAAE;2CAOZ,IAAI,IAAgC;;;;;CAqBhE,AAAO,WAAW,SAAqB;EACrC,KAAK,SAAS,KAAK,OAAO;EAE1B,OAAO;CACT;;;;CAKA,AAA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I;EAC3B,QAAQ,UAAgC;GACtC,MAAM,aAAa,KAAK,IAAI,IAAI;GAChC,OAAO,KAAK,KAAK,QAAQ,QAAQ,gBAAgB,WAAW,KAAK;IAC/D;IACA,GAAI,SAAS,CAAC;GAChB,CAAC;EACH;CACF;;;;CAKA,AAAO,QAAQ,MAAc;EAC3B,OAAO,KAAK,SAAS,MAAM,YAAY,QAAQ,SAAS,IAAI;CAC9D;;;;CAKA,AAAO,YAAY;EACjB,KAAK,MAAM,WAAW,KAAK,UACzB,IAAI,QAAQ,WACV,QAAQ,UAAU;CAGxB;;;;;;;;;;;;;;;;;;;;;CAsBA,MAAa,QAAuB;EAClC,MAAM,QAAQ,WACZ,KAAK,SAAS,IAAI,OAAO,YAAY;GACnC,IAAI,CAAC,QAAQ,OACX;GAGF,IAAI;IACF,MAAM,QAAQ,MAAM;GACtB,QAAQ,CAGR;EACF,CAAC,CACH;CACF;;;;;;;;;;;;;;;;;;;CAoBA,AAAO,gBAAgB,QAAgC;EACrD,KAAK,iBAAiB;EAEtB,KAAK,MAAM,SAAS,QAAQ;GAC1B,MAAM,UAAU,cAAc,IAAI,KAAK,UAC7B;IACJ,KAAK,UAAU;IACf,QAAQ,IAAI,OAAO,OAAO;IAC1B,QAAQ,KAAK,QAAQ,KAAK,KAAuB;GACnD,UACM;IACJ,KAAK,UAAU;GACjB;GAEJ,QAAQ,GAAG,OAAO,OAAO;GACzB,KAAK,kBAAkB,IAAI,OAAO,OAAO;EAC3C;EAEA,OAAO;CACT;;;;;CAMA,AAAO,mBAAyB;EAC9B,KAAK,MAAM,CAAC,OAAO,YAAY,KAAK,mBAClC,QAAQ,IAAI,OAAO,OAAO;EAG5B,KAAK,kBAAkB,MAAM;EAE7B,OAAO;CACT;AACF;;;;;;;;;;;;;;;AAgBA,MAAa,MAAM,IAAI,OAAO"}
1
+ {"version":3,"file":"logger.mjs","names":[],"sources":["../../../../../../../packages/logger/src/logger.ts"],"sourcesContent":["import { Random } from \"@mongez/reinforcements\";\nimport type { LogChannel } from \"./log-channel\";\nimport { applyRedact, mergeRedact } from \"./redact\";\nimport type {\n AutoFlushEvent,\n ChannelErrorHandler,\n LogContract,\n LoggingData,\n LogLevel,\n OmittedLoggingData,\n RedactConfig,\n} from \"./types\";\nimport { clearMessage } from \"./utils/clear-message\";\n\nconst SIGNAL_EVENTS: ReadonlySet<AutoFlushEvent> = new Set([\n \"SIGINT\",\n \"SIGTERM\",\n \"SIGHUP\",\n \"SIGBREAK\",\n \"SIGUSR2\",\n]);\n\n/**\n * Severity ranks used by `setMinLevel`. Higher number = more severe. The\n * ordering matches conventional log-level hierarchies: `debug` is noisiest\n * and easiest to drop; `error` is the loudest and never dropped by the\n * minimum-level filter. `success` sits beside `info` — it's an informational\n * outcome, not a warning.\n */\nconst LEVEL_RANK: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n success: 1,\n warn: 2,\n error: 3,\n fatal: 4,\n};\n\nexport class Logger {\n /**\n * Current channel\n */\n public channels: LogChannel[] = [];\n\n public id = \"logger-\" + Random.string(32);\n\n /**\n * Registered auto-flush handlers, keyed by event name. Stored so repeated\n * calls to `enableAutoFlush` replace rather than stack, and so\n * `disableAutoFlush` can remove them cleanly.\n */\n private autoFlushHandlers = new Map<AutoFlushEvent, () => void>();\n\n /**\n * Logger-wide minimum severity. When set, entries below this level are\n * dropped before any channel is invoked — cheaper than per-channel `levels`\n * filters because the fan-out loop is skipped entirely. `undefined` means\n * no minimum (every entry reaches every channel that accepts it).\n */\n private minLevel?: LogLevel;\n\n /**\n * Logger-wide redaction floor. Applied once before fan-out — every\n * channel receives an entry with these paths already censored. Channel\n * configs can extend the path list (additive); they cannot remove paths\n * set here.\n */\n private redactConfig?: RedactConfig;\n\n /**\n * Deliveries still in flight on async channels, per channel. `log()` never\n * awaits them; `flush()` does, so a graceful shutdown still waits for every\n * entry. Kept per channel so one hung channel cannot hold up another's\n * drain.\n */\n private pendingDeliveries = new Map<LogChannel, Set<Promise<void>>>();\n\n /**\n * Receives a channel's delivery failure (a sync throw or a rejected async\n * `log()`). Defaults to a single stderr line, never back through the logger.\n */\n private channelErrorHandler: ChannelErrorHandler = reportChannelError;\n\n /**\n * Add a new channel\n */\n public addChannel(channel: LogChannel) {\n this.channels.push(channel);\n\n return this;\n }\n\n /**\n * Set base configurations\n */\n public configure(config: {\n channels?: LogChannel[];\n autoFlushOn?: AutoFlushEvent[];\n minLevel?: LogLevel;\n redact?: RedactConfig;\n onChannelError?: ChannelErrorHandler;\n }) {\n if (config.channels) {\n this.channels = config.channels;\n }\n\n if (config.autoFlushOn) {\n this.enableAutoFlush(config.autoFlushOn);\n }\n\n if (config.minLevel !== undefined) {\n this.setMinLevel(config.minLevel);\n }\n\n if (config.redact !== undefined) {\n this.setRedact(config.redact);\n }\n\n if (config.onChannelError) {\n this.onChannelError(config.onChannelError);\n }\n\n return this;\n }\n\n /**\n * Handle a channel's delivery failure. Logging is fire-and-forget, so a\n * channel that throws or rejects never reaches the call site and never\n * becomes an unhandled rejection; it goes to this handler instead. The\n * default writes one line to stderr. The handler must not log through this\n * logger (a failing channel would loop).\n *\n * @example\n * log.onChannelError((error, channel) => metrics.increment(`log.${channel.name}.failed`));\n */\n public onChannelError(handler: ChannelErrorHandler): this {\n this.channelErrorHandler = handler;\n return this;\n }\n\n /**\n * Set the logger-wide redaction floor. Applied to every entry before\n * fan-out; channel configs add more paths on top, never fewer. Pass\n * `undefined` to clear.\n *\n * @example\n * log.setRedact({\n * paths: [\"context.password\", \"context.*.token\"],\n * censor: \"[REDACTED]\",\n * });\n */\n public setRedact(config: RedactConfig | undefined): this {\n this.redactConfig = config;\n return this;\n }\n\n /**\n * Read the active logger-wide redact config (or `undefined`).\n */\n public getRedact(): RedactConfig | undefined {\n return this.redactConfig;\n }\n\n /**\n * Drop every entry whose severity is below `level` before fan-out. Cheaper\n * than per-channel `levels` filters because the loop never runs and no\n * channel receives the entry. Pass `undefined` to clear and accept all\n * levels again.\n *\n * @example\n * // production: silence debug noise everywhere at once\n * logger.setMinLevel(\"info\");\n */\n public setMinLevel(level: LogLevel | undefined): this {\n this.minLevel = level;\n return this;\n }\n\n /**\n * Read the active minimum severity (or `undefined` when none is set).\n */\n public getMinLevel(): LogLevel | undefined {\n return this.minLevel;\n }\n\n /**\n * Set channels\n */\n public setChannels(channels: LogChannel[]) {\n this.channels = channels;\n\n return this;\n }\n\n /**\n * Normalize log data to a single object\n */\n private normalizeLogData(\n dataOrModule: LoggingData | OmittedLoggingData | string,\n action?: string,\n message: any = \"\",\n level?: LogLevel,\n context?: Record<string, any>,\n ): LoggingData {\n if (typeof dataOrModule === \"object\") {\n // If level is provided, override type\n return {\n type: (level || (dataOrModule as any).type || \"info\") as LogLevel,\n module: dataOrModule.module,\n action: dataOrModule.action,\n message: dataOrModule.message,\n ...(context ? { context } : dataOrModule.context ? { context: dataOrModule.context } : {}),\n };\n }\n return {\n type: (level || \"info\") as LogLevel,\n module: dataOrModule,\n action: action as string,\n message,\n ...(context ? { context } : {}),\n };\n }\n\n /**\n * Make log\n *\n * Fans out a single log entry to every registered channel. Non-terminal\n * channels receive a copy whose `message` has had ANSI color codes stripped\n * — each channel sees its own shallow clone so one channel cannot observe\n * another's mutations (e.g. a later terminal channel still sees the original\n * colored message).\n *\n * Synchronous and fire-and-forget: it returns the logger, not a promise.\n * Async channel deliveries are tracked and awaited by {@link flush}; a\n * channel that throws or rejects is isolated from the others and reported\n * to {@link onChannelError}.\n */\n public log(data: LoggingData): this {\n if (this.minLevel && LEVEL_RANK[data.type] < LEVEL_RANK[this.minLevel]) {\n return this;\n }\n\n // Apply the logger-wide redact floor once. Every channel sees the\n // result; no channel can undo a logger-wide redaction (additive-only\n // semantics). A redaction that throws (a bad censor function) drops the\n // entry: delivering it unredacted would leak exactly what the config\n // exists to hide.\n let baseEntry: LoggingData;\n\n try {\n baseEntry = applyRedact(data, this.redactConfig);\n } catch (error) {\n for (const channel of this.channels) {\n this.reportChannelError(error, channel, redactionFailedEntry(data));\n }\n\n return this;\n }\n\n for (const channel of this.channels) {\n this.deliver(channel, data, baseEntry);\n }\n\n return this;\n }\n\n /**\n * Prepare and hand one entry to one channel, isolating its failure (a\n * channel redaction that throws included) and tracking an async delivery\n * until it settles.\n */\n private deliver(channel: LogChannel, data: LoggingData, baseEntry: LoggingData) {\n let payload: LoggingData = baseEntry;\n let result: void | Promise<void>;\n\n try {\n const channelRedact = channel.getRedactConfig?.();\n\n // When the channel adds paths, redact again from `data` rather than\n // from `baseEntry` so the merged config (which already contains the\n // logger-wide paths) does the full pass — avoids double-cloning the\n // already-redacted base.\n if (channelRedact) {\n payload = applyRedact(data, mergeRedact(this.redactConfig, channelRedact));\n }\n\n if (channel.terminal === false) {\n payload = { ...payload, message: clearMessage(payload.message) };\n }\n\n result = channel.log(payload);\n } catch (error) {\n // `payload` is the logger-wide redacted entry until the channel's own\n // redaction succeeded, so the handler never sees less-redacted data\n // than some channel would have.\n this.reportChannelError(error, channel, payload);\n return;\n }\n\n if (!result || typeof (result as Promise<void>).then !== \"function\") {\n return;\n }\n\n let pending = this.pendingDeliveries.get(channel);\n\n if (!pending) {\n pending = new Set();\n this.pendingDeliveries.set(channel, pending);\n }\n\n const tracked = pending;\n const delivery: Promise<void> = Promise.resolve(result)\n .catch((error) => this.reportChannelError(error, channel, payload))\n .finally(() => {\n tracked.delete(delivery);\n\n if (tracked.size === 0 && this.pendingDeliveries.get(channel) === tracked) {\n this.pendingDeliveries.delete(channel);\n }\n });\n\n tracked.add(delivery);\n }\n\n private reportChannelError(error: unknown, channel: LogContract, entry: LoggingData) {\n try {\n const outcome: unknown = this.channelErrorHandler(error, channel, entry);\n\n // An async handler that rejects must not become an unhandled rejection\n // (which an app may route straight back into this logger).\n if (outcome && typeof (outcome as Promise<unknown>).then === \"function\") {\n (outcome as Promise<unknown>).then(undefined, () => {});\n }\n } catch {\n // An error handler that throws must not turn logging into a crash.\n }\n }\n\n /**\n * Make debug log\n */\n public debug(\n dataOrModule: OmittedLoggingData | string,\n action?: string,\n message: any = \"\",\n context?: Record<string, any>,\n ) {\n const data = this.normalizeLogData(dataOrModule, action, message, \"debug\", context);\n return this.log(data);\n }\n\n /**\n * Make info log\n */\n public info(\n dataOrModule: OmittedLoggingData | string,\n action?: string,\n message: any = \"\",\n context?: Record<string, any>,\n ) {\n const data = this.normalizeLogData(dataOrModule, action, message, \"info\", context);\n return this.log(data);\n }\n\n /**\n * Make warn log\n */\n public warn(\n dataOrModule: OmittedLoggingData | string,\n action?: string,\n message: any = \"\",\n context?: Record<string, any>,\n ) {\n const data = this.normalizeLogData(dataOrModule, action, message, \"warn\", context);\n return this.log(data);\n }\n\n /**\n * Make error log\n */\n public error(\n dataOrModule: OmittedLoggingData | string,\n action?: string,\n message: any = \"\",\n context?: Record<string, any>,\n ) {\n const data = this.normalizeLogData(dataOrModule, action, message, \"error\", context);\n return this.log(data);\n }\n\n /**\n * Make success log\n */\n public success(\n dataOrModule: OmittedLoggingData | string,\n action?: string,\n message: any = \"\",\n context?: Record<string, any>,\n ) {\n const data = this.normalizeLogData(dataOrModule, action, message, \"success\", context);\n\n return this.log(data);\n }\n\n /**\n * Make fatal log — for unrecoverable failures where the application is going\n * down (failed bootstrap, lost connection to a required dependency that the\n * caller has decided not to retry, an `uncaughtException`).\n *\n * Identical shape to {@link error}; the level is purely informational —\n * `fatal` does NOT auto-flush or exit. The caller decides whether to call\n * `await log.flush()` and `process.exit(...)`.\n */\n public fatal(\n dataOrModule: OmittedLoggingData | string,\n action?: string,\n message: any = \"\",\n context?: Record<string, any>,\n ) {\n const data = this.normalizeLogData(dataOrModule, action, message, \"fatal\", context);\n\n return this.log(data);\n }\n\n /**\n * Log an `error` entry when `condition` is falsy. No-op otherwise — the\n * entry is never built and channels are not invoked, so this is genuinely\n * free in the happy path. Mirrors the spirit of `console.assert` but routes\n * through the logger pipeline so persistent channels capture failures.\n *\n * @example\n * log.assert(user !== null, \"auth\", \"session\", \"user vanished mid-flight\", { sessionId });\n */\n public assert(\n condition: unknown,\n module: string,\n action: string,\n message: any,\n context?: Record<string, any>,\n ): this {\n if (condition) return this;\n return this.error(module, action, message, context);\n }\n\n /**\n * Start a duration timer. The returned function emits an `info` entry\n * with `completed in <ms>ms` and a `durationMs` field in `context` when\n * called. Pass an object to `end()` to merge extra fields into context.\n *\n * @example\n * const end = log.timer(\"db\", \"users.findById\");\n * const user = await usersRepo.findById(id);\n * end({ id, found: !!user });\n */\n public timer(\n module: string,\n action: string,\n ): (extra?: Record<string, any>) => this {\n const startedAt = Date.now();\n return (extra?: Record<string, any>) => {\n const durationMs = Date.now() - startedAt;\n return this.info(module, action, `completed in ${durationMs}ms`, {\n durationMs,\n ...(extra ?? {}),\n });\n };\n }\n\n /**\n * Get channel by name\n */\n public channel(name: string) {\n return this.channels.find((channel) => channel.name === name);\n }\n\n /**\n * Synchronously flush logs\n */\n public flushSync() {\n for (const channel of this.channels) {\n if (channel.flushSync) {\n channel.flushSync();\n }\n }\n }\n\n /**\n * Wait for every in-flight async delivery, then drain every channel that\n * implements `flush()` — bounded by `timeout` (default\n * {@link DEFAULT_FLUSH_TIMEOUT_MS}).\n *\n * Unlike {@link flushSync}, this awaits each channel's async I/O — the\n * correct call for a graceful shutdown that can afford to wait\n * (`await log.flush()` after closing the HTTP server, before\n * `process.exit`). A channel whose delivery is async (a network transport,\n * an async disk write) implements `flush()`, not `flushSync()`.\n *\n * Channels drain concurrently and independently: each waits for its own\n * pending deliveries (including ones logged while the flush runs), then\n * runs its `flush()`. A channel whose delivery hangs therefore cannot hold\n * up another channel's drain, and a channel whose flush rejects can neither\n * stop the others nor escape as an unhandled rejection. When `timeout`\n * elapses, `flush()` resolves anyway and each channel still draining is\n * reported to {@link onChannelError}. Channels without `flush()` only wait\n * for their deliveries.\n *\n * @example\n * async function shutdown() {\n * await httpServer.close();\n * await log.flush({ timeout: 3000 });\n * process.exit(0);\n * }\n */\n public async flush(options: { timeout?: number } = {}): Promise<void> {\n const timeout = options.timeout ?? DEFAULT_FLUSH_TIMEOUT_MS;\n const draining = new Set<LogChannel>(this.channels);\n\n for (const channel of this.pendingDeliveries.keys()) {\n draining.add(channel);\n }\n\n const unfinished = new Set(draining);\n\n const drains = [...draining].map(async (channel) => {\n try {\n await this.drainChannel(channel);\n } catch {\n // A single channel must never break shutdown for the others —\n // a graceful drain is best-effort across every channel.\n } finally {\n unfinished.delete(channel);\n }\n });\n\n const settled = Promise.allSettled(drains).then(() => false);\n\n // `Infinity` (or any non-finite value) waits without a limit; setTimeout\n // would otherwise overflow it to an immediate timeout.\n if (!Number.isFinite(timeout)) {\n await settled;\n return;\n }\n\n let resolveTimeout!: (timedOut: boolean) => void;\n const timeoutReached = new Promise<boolean>((resolve) => {\n resolveTimeout = resolve;\n });\n const timer = setTimeout(() => resolveTimeout(true), Math.max(0, timeout));\n\n // Never keep the process alive just to time a flush out.\n (timer as { unref?: () => void }).unref?.();\n\n const timedOut = await Promise.race([settled, timeoutReached]);\n\n clearTimeout(timer);\n\n if (!timedOut) return;\n\n for (const channel of unfinished) {\n this.reportChannelError(\n new Error(`flush timed out after ${timeout}ms; entries still in flight may be lost`),\n channel,\n { type: \"warn\", module: \"logger\", action: \"flush\", message: \"flush timed out\" },\n );\n }\n }\n\n /**\n * Wait until the channel has no delivery in flight, run its `flush()`, and\n * repeat while that flush let new deliveries in.\n */\n private async drainChannel(channel: LogChannel) {\n do {\n let pending = this.pendingDeliveries.get(channel);\n\n while (pending && pending.size > 0) {\n await Promise.allSettled([...pending]);\n pending = this.pendingDeliveries.get(channel);\n }\n\n if (channel.flush) {\n await channel.flush();\n }\n } while ((this.pendingDeliveries.get(channel)?.size ?? 0) > 0);\n }\n\n /**\n * Register one process-level handler per event that calls `flushSync()`\n * before the process terminates.\n *\n * For signal events (`SIGINT`, `SIGTERM`, `SIGHUP`, `SIGBREAK`, `SIGUSR2`)\n * the handler flushes and then re-raises the signal so Node's default exit\n * behavior runs. For `beforeExit`, the handler flushes in place — Node exits\n * naturally afterwards.\n *\n * Idempotent: calling with the same events replaces the previous handlers.\n * Call `disableAutoFlush()` to unregister.\n *\n * @example\n * log.configure({\n * channels: [new ConsoleLog(), new FileLog()],\n * autoFlushOn: [\"SIGINT\", \"SIGTERM\", \"beforeExit\"],\n * });\n */\n public enableAutoFlush(events: AutoFlushEvent[]): this {\n this.disableAutoFlush();\n\n for (const event of events) {\n const handler = SIGNAL_EVENTS.has(event)\n ? () => {\n this.flushSync();\n process.off(event, handler);\n process.kill(process.pid, event as NodeJS.Signals);\n }\n : () => {\n this.flushSync();\n };\n\n process.on(event, handler);\n this.autoFlushHandlers.set(event, handler);\n }\n\n return this;\n }\n\n /**\n * Remove every handler previously registered by `enableAutoFlush`.\n * Safe to call when no handlers are registered.\n */\n public disableAutoFlush(): this {\n for (const [event, handler] of this.autoFlushHandlers) {\n process.off(event, handler);\n }\n\n this.autoFlushHandlers.clear();\n\n return this;\n }\n}\n\n/**\n * Default `timeout` of {@link Logger.flush}: long enough for a healthy network\n * channel, short enough that a hung one cannot eat a shutdown budget.\n */\nexport const DEFAULT_FLUSH_TIMEOUT_MS = 5000;\n\n/**\n * What the error handler receives when the logger-wide redaction itself\n * failed: the entry's identity only, never the unredacted message or context.\n */\nfunction redactionFailedEntry(data: LoggingData): LoggingData {\n return {\n type: data.type,\n module: data.module,\n action: data.action,\n message: \"[entry dropped: redaction failed]\",\n };\n}\n\n/**\n * Default {@link ChannelErrorHandler}: one stderr line per failure. Written\n * directly to the stream, never through a logger, so a broken channel cannot\n * recurse.\n */\nfunction reportChannelError(error: unknown, channel: LogContract) {\n const reason = error instanceof Error ? error.message : String(error);\n\n try {\n process.stderr.write(`[@warlock.js/logger] channel \"${channel.name}\" failed to log: ${reason}\\n`);\n } catch {\n // stderr itself is gone; nothing left to report to.\n }\n}\n\n/**\n * The package singleton. Use this for everyday logging — `log.info(...)`,\n * `log.error(...)`, `log.configure(...)`. Custom logger instances can be\n * created by instantiating `Logger` directly.\n *\n * The name is intentionally short: `log` reads naturally at the call site\n * (`log.info(\"auth\", \"login\", \"ok\")`) and matches the convention used in\n * pino, bunyan, and most JS logging tutorials.\n *\n * Note that `log` is a `Logger` instance, **not** a function — the bare\n * callable form was removed when the dual `log` / `logger` exports were\n * collapsed into a single name. Use `log.info(...)` (or any other level\n * shortcut) to emit entries.\n */\nexport const log = new Logger();\n"],"mappings":";;;;;;AAcA,MAAM,gBAA6C,IAAI,IAAI;CACzD;CACA;CACA;CACA;CACA;AACF,CAAC;;;;;;;;AASD,MAAM,aAAuC;CAC3C,OAAO;CACP,MAAM;CACN,SAAS;CACT,MAAM;CACN,OAAO;CACP,OAAO;AACT;AAEA,IAAa,SAAb,MAAoB;;kBAIc,CAAC;YAErB,YAAY,OAAO,OAAO,EAAE;2CAOZ,IAAI,IAAgC;2CAwBpC,IAAI,IAAoC;6BAMjB;;;;;CAKnD,AAAO,WAAW,SAAqB;EACrC,KAAK,SAAS,KAAK,OAAO;EAE1B,OAAO;CACT;;;;CAKA,AAAO,UAAU,QAMd;EACD,IAAI,OAAO,UACT,KAAK,WAAW,OAAO;EAGzB,IAAI,OAAO,aACT,KAAK,gBAAgB,OAAO,WAAW;EAGzC,IAAI,OAAO,aAAa,QACtB,KAAK,YAAY,OAAO,QAAQ;EAGlC,IAAI,OAAO,WAAW,QACpB,KAAK,UAAU,OAAO,MAAM;EAG9B,IAAI,OAAO,gBACT,KAAK,eAAe,OAAO,cAAc;EAG3C,OAAO;CACT;;;;;;;;;;;CAYA,AAAO,eAAe,SAAoC;EACxD,KAAK,sBAAsB;EAC3B,OAAO;CACT;;;;;;;;;;;;CAaA,AAAO,UAAU,QAAwC;EACvD,KAAK,eAAe;EACpB,OAAO;CACT;;;;CAKA,AAAO,YAAsC;EAC3C,OAAO,KAAK;CACd;;;;;;;;;;;CAYA,AAAO,YAAY,OAAmC;EACpD,KAAK,WAAW;EAChB,OAAO;CACT;;;;CAKA,AAAO,cAAoC;EACzC,OAAO,KAAK;CACd;;;;CAKA,AAAO,YAAY,UAAwB;EACzC,KAAK,WAAW;EAEhB,OAAO;CACT;;;;C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KAAK,kBAAkB,IAAI,OAAO,OAAO;EAC3C;EAEA,OAAO;CACT;;;;;CAMA,AAAO,mBAAyB;EAC9B,KAAK,MAAM,CAAC,OAAO,YAAY,KAAK,mBAClC,QAAQ,IAAI,OAAO,OAAO;EAG5B,KAAK,kBAAkB,MAAM;EAE7B,OAAO;CACT;AACF;;;;;AAMA,MAAa,2BAA2B;;;;;AAMxC,SAAS,qBAAqB,MAAgC;CAC5D,OAAO;EACL,MAAM,KAAK;EACX,QAAQ,KAAK;EACb,QAAQ,KAAK;EACb,SAAS;CACX;AACF;;;;;;AAOA,SAAS,mBAAmB,OAAgB,SAAsB;CAChE,MAAM,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;CAEpE,IAAI;EACF,QAAQ,OAAO,MAAM,iCAAiC,QAAQ,KAAK,mBAAmB,OAAO,GAAG;CAClG,QAAQ,CAER;AACF;;;;;;;;;;;;;;;AAgBA,MAAa,MAAM,IAAI,OAAO"}
@@ -1,4 +1,4 @@
1
- //#region ../logger/src/redact/default-keys.d.ts
1
+ //#region ../../packages/logger/src/redact/default-keys.d.ts
2
2
  /**
3
3
  * Built-in secret-key denylist — the redaction floor that applies with no
4
4
  * configuration at all.
@@ -1 +1 @@
1
- {"version":3,"file":"default-keys.d.mts","names":[],"sources":["../../../../../../../logger/src/redact/default-keys.ts"],"mappings":";;AA4CA;;;;AAA8C;AAa9C;;;;AAqEC;AAMD;;;;AAAgD;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAxFhC,kBAAA,CAAmB,GAAW;;;;;;;;;;cAajC,mBAAA;;;;;cA2EA,sBAAA,EAAwB,WAAW"}
1
+ {"version":3,"file":"default-keys.d.mts","names":[],"sources":["../../../../../../../../packages/logger/src/redact/default-keys.ts"],"mappings":";;AA4CA;;;;AAA8C;AAa9C;;;;AAqEC;AAMD;;;;AAAgD;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAxFhC,kBAAA,CAAmB,GAAW;;;;;;;;;;cAajC,mBAAA;;;;;cA2EA,sBAAA,EAAwB,WAAW"}
@@ -1,4 +1,4 @@
1
- //#region ../logger/src/redact/default-keys.ts
1
+ //#region ../../packages/logger/src/redact/default-keys.ts
2
2
  /**
3
3
  * Built-in secret-key denylist — the redaction floor that applies with no
4
4
  * configuration at all.
@@ -1 +1 @@
1
- {"version":3,"file":"default-keys.mjs","names":[],"sources":["../../../../../../../logger/src/redact/default-keys.ts"],"sourcesContent":["/**\n * Built-in secret-key denylist — the redaction floor that applies with no\n * configuration at all.\n *\n * ## Why a default list exists\n *\n * Path-based `redact.paths` is a *tool*; it only protects an application whose\n * every call site was configured correctly, and nothing warns you when one\n * wasn't. The overwhelmingly common leak is mundane and needs no attacker\n * input: `log.error(\"auth\", \"login\", \"failed\", { headers: req.headers, body:\n * req.body })` puts a live bearer token and a cleartext password into every\n * sink. A key denylist that runs by default turns redaction from a tool into a\n * default protection.\n *\n * ## Matching semantics — exact, on a normalized key\n *\n * Keys are compared after {@link normalizeRedactKey}: lower-cased with every\n * non-alphanumeric character removed. So one entry covers every spelling\n * convention a codebase might use —\n * `apiKey` / `api_key` / `API-KEY` / `apikey` all normalize to `apikey`.\n *\n * The match is **exact on the normalized key, not a substring**. That is a\n * deliberate trade: substring matching (`*token*`) would also swallow\n * `tokenCount`, `passwordUpdatedAt`, `secretsLoaded` — silent, hard-to-debug\n * data loss in the one place engineers look when something is broken. An exact\n * list is auditable: you can read it and know precisely what disappears. The\n * cost is that unusual spellings are missed, which is why the list carries the\n * concrete wire-format variants that actually show up in HTTP headers\n * (`x-api-key`, `proxy-authorization`, `set-cookie`) and why apps can extend it\n * with `redact.keys`.\n *\n * ## What is deliberately NOT here\n *\n * `key`, `auth`, `hash`, `signature`, `salt`, `id` — all too generic. Each\n * would redact far more non-secret fields than secret ones (`key` alone would\n * blank out every `key` in a keyed collection). Applications that want them\n * add them via `redact.keys`.\n */\n\n/**\n * Normalize a key for denylist comparison: lower-case, strip every\n * non-alphanumeric character. Collapses `apiKey`, `api_key`, `API-KEY`,\n * `Api Key` and `apikey` onto a single entry.\n */\nexport function normalizeRedactKey(key: string): string {\n return key.toLowerCase().replace(/[^a-z0-9]/g, \"\");\n}\n\n/**\n * The default denylist, in source spelling. Anything whose normalized key\n * matches one of these is replaced by the configured censor (`\"[REDACTED]\"`\n * by default) at any depth of `context`, `message`, or an `Error`'s own\n * enumerable properties.\n *\n * Exported so applications can inspect, log, or build on the exact set they\n * are getting rather than guessing at it.\n */\nexport const DEFAULT_REDACT_KEYS: readonly string[] = [\n // --- Passwords ---------------------------------------------------------\n \"password\",\n \"passwd\",\n \"pwd\",\n \"passphrase\",\n \"passwordHash\",\n \"currentPassword\",\n \"newPassword\",\n \"passwordConfirmation\",\n\n // --- Shared secrets ----------------------------------------------------\n \"secret\",\n \"clientSecret\",\n \"appSecret\",\n \"apiSecret\",\n \"secretKey\",\n\n // --- Tokens ------------------------------------------------------------\n \"token\",\n \"accessToken\",\n \"refreshToken\",\n \"idToken\",\n \"authToken\",\n \"apiToken\",\n \"bearerToken\",\n \"csrfToken\",\n \"sessionToken\",\n \"resetToken\",\n \"verificationToken\",\n \"jwt\",\n \"otp\",\n\n // --- Keys --------------------------------------------------------------\n \"apiKey\",\n \"privateKey\",\n \"encryptionKey\",\n \"signingKey\",\n\n // --- HTTP credential headers -------------------------------------------\n // Header names are matched in their wire spelling; normalization removes\n // the dashes, so `x-api-key` and `X_API_KEY` both land on `xapikey`.\n \"authorization\",\n \"proxyAuthorization\",\n \"x-api-key\",\n \"x-auth-token\",\n \"cookie\",\n \"set-cookie\",\n\n // --- Session / credential containers -----------------------------------\n // `sessionId` is a bearer credential: whoever reads it from a log can\n // replay the session. Teams that log it deliberately for correlation can\n // drop it via `redact.keys` + `defaultKeys: false`, or keep a prefix with a\n // function censor.\n \"sessionId\",\n \"credentials\",\n \"credential\",\n \"connectionString\",\n\n // --- Financial / high-sensitivity PII ----------------------------------\n \"creditCard\",\n \"creditCardNumber\",\n \"cardNumber\",\n \"cvv\",\n \"cvc\",\n \"ssn\",\n \"socialSecurityNumber\",\n \"iban\",\n \"taxId\",\n];\n\n/**\n * The default denylist, pre-normalized. Frozen at module load so the hot path\n * never rebuilds it.\n */\nexport const DEFAULT_REDACT_KEY_SET: ReadonlySet<string> = new Set(\n DEFAULT_REDACT_KEYS.map(normalizeRedactKey),\n);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4CA,SAAgB,mBAAmB,KAAqB;CACtD,OAAO,IAAI,YAAY,CAAC,CAAC,QAAQ,cAAc,EAAE;AACnD;;;;;;;;;;AAWA,MAAa,sBAAyC;CAEpD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAGA;CACA;CACA;CACA;CACA;CAGA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAGA;CACA;CACA;CACA;CAKA;CACA;CACA;CACA;CACA;CACA;CAOA;CACA;CACA;CACA;CAGA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;AAMA,MAAa,yBAA8C,IAAI,IAC7D,oBAAoB,IAAI,kBAAkB,CAC5C"}
1
+ {"version":3,"file":"default-keys.mjs","names":[],"sources":["../../../../../../../../packages/logger/src/redact/default-keys.ts"],"sourcesContent":["/**\n * Built-in secret-key denylist — the redaction floor that applies with no\n * configuration at all.\n *\n * ## Why a default list exists\n *\n * Path-based `redact.paths` is a *tool*; it only protects an application whose\n * every call site was configured correctly, and nothing warns you when one\n * wasn't. The overwhelmingly common leak is mundane and needs no attacker\n * input: `log.error(\"auth\", \"login\", \"failed\", { headers: req.headers, body:\n * req.body })` puts a live bearer token and a cleartext password into every\n * sink. A key denylist that runs by default turns redaction from a tool into a\n * default protection.\n *\n * ## Matching semantics — exact, on a normalized key\n *\n * Keys are compared after {@link normalizeRedactKey}: lower-cased with every\n * non-alphanumeric character removed. So one entry covers every spelling\n * convention a codebase might use —\n * `apiKey` / `api_key` / `API-KEY` / `apikey` all normalize to `apikey`.\n *\n * The match is **exact on the normalized key, not a substring**. That is a\n * deliberate trade: substring matching (`*token*`) would also swallow\n * `tokenCount`, `passwordUpdatedAt`, `secretsLoaded` — silent, hard-to-debug\n * data loss in the one place engineers look when something is broken. An exact\n * list is auditable: you can read it and know precisely what disappears. The\n * cost is that unusual spellings are missed, which is why the list carries the\n * concrete wire-format variants that actually show up in HTTP headers\n * (`x-api-key`, `proxy-authorization`, `set-cookie`) and why apps can extend it\n * with `redact.keys`.\n *\n * ## What is deliberately NOT here\n *\n * `key`, `auth`, `hash`, `signature`, `salt`, `id` — all too generic. Each\n * would redact far more non-secret fields than secret ones (`key` alone would\n * blank out every `key` in a keyed collection). Applications that want them\n * add them via `redact.keys`.\n */\n\n/**\n * Normalize a key for denylist comparison: lower-case, strip every\n * non-alphanumeric character. Collapses `apiKey`, `api_key`, `API-KEY`,\n * `Api Key` and `apikey` onto a single entry.\n */\nexport function normalizeRedactKey(key: string): string {\n return key.toLowerCase().replace(/[^a-z0-9]/g, \"\");\n}\n\n/**\n * The default denylist, in source spelling. Anything whose normalized key\n * matches one of these is replaced by the configured censor (`\"[REDACTED]\"`\n * by default) at any depth of `context`, `message`, or an `Error`'s own\n * enumerable properties.\n *\n * Exported so applications can inspect, log, or build on the exact set they\n * are getting rather than guessing at it.\n */\nexport const DEFAULT_REDACT_KEYS: readonly string[] = [\n // --- Passwords ---------------------------------------------------------\n \"password\",\n \"passwd\",\n \"pwd\",\n \"passphrase\",\n \"passwordHash\",\n \"currentPassword\",\n \"newPassword\",\n \"passwordConfirmation\",\n\n // --- Shared secrets ----------------------------------------------------\n \"secret\",\n \"clientSecret\",\n \"appSecret\",\n \"apiSecret\",\n \"secretKey\",\n\n // --- Tokens ------------------------------------------------------------\n \"token\",\n \"accessToken\",\n \"refreshToken\",\n \"idToken\",\n \"authToken\",\n \"apiToken\",\n \"bearerToken\",\n \"csrfToken\",\n \"sessionToken\",\n \"resetToken\",\n \"verificationToken\",\n \"jwt\",\n \"otp\",\n\n // --- Keys --------------------------------------------------------------\n \"apiKey\",\n \"privateKey\",\n \"encryptionKey\",\n \"signingKey\",\n\n // --- HTTP credential headers -------------------------------------------\n // Header names are matched in their wire spelling; normalization removes\n // the dashes, so `x-api-key` and `X_API_KEY` both land on `xapikey`.\n \"authorization\",\n \"proxyAuthorization\",\n \"x-api-key\",\n \"x-auth-token\",\n \"cookie\",\n \"set-cookie\",\n\n // --- Session / credential containers -----------------------------------\n // `sessionId` is a bearer credential: whoever reads it from a log can\n // replay the session. Teams that log it deliberately for correlation can\n // drop it via `redact.keys` + `defaultKeys: false`, or keep a prefix with a\n // function censor.\n \"sessionId\",\n \"credentials\",\n \"credential\",\n \"connectionString\",\n\n // --- Financial / high-sensitivity PII ----------------------------------\n \"creditCard\",\n \"creditCardNumber\",\n \"cardNumber\",\n \"cvv\",\n \"cvc\",\n \"ssn\",\n \"socialSecurityNumber\",\n \"iban\",\n \"taxId\",\n];\n\n/**\n * The default denylist, pre-normalized. Frozen at module load so the hot path\n * never rebuilds it.\n */\nexport const DEFAULT_REDACT_KEY_SET: ReadonlySet<string> = new Set(\n DEFAULT_REDACT_KEYS.map(normalizeRedactKey),\n);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4CA,SAAgB,mBAAmB,KAAqB;CACtD,OAAO,IAAI,YAAY,CAAC,CAAC,QAAQ,cAAc,EAAE;AACnD;;;;;;;;;;AAWA,MAAa,sBAAyC;CAEpD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAGA;CACA;CACA;CACA;CACA;CAGA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAGA;CACA;CACA;CACA;CAKA;CACA;CACA;CACA;CACA;CACA;CAOA;CACA;CACA;CACA;CAGA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;AAMA,MAAa,yBAA8C,IAAI,IAC7D,oBAAoB,IAAI,kBAAkB,CAC5C"}
@@ -1,4 +1,5 @@
1
1
  import { DEFAULT_REDACT_KEYS, DEFAULT_REDACT_KEY_SET, normalizeRedactKey } from "./default-keys.mjs";
2
2
  import { applyRedact, mergeRedact, resolveRedactKeys } from "./redact.mjs";
3
+ import { MASK_EMAILS_MAX_LENGTH, maskEmail, maskEmailsInText } from "./mask-email.mjs";
3
4
 
4
5
  export { };
@@ -0,0 +1,40 @@
1
+ //#region ../../packages/logger/src/redact/mask-email.d.ts
2
+ /**
3
+ * Longest text {@link maskEmailsInText} scans. Anything past it is cut off and
4
+ * replaced by a marker, so a huge cache key or message cannot cost more than a
5
+ * bounded amount of time per log line, and nothing past the cut can leak.
6
+ */
7
+ declare const MASK_EMAILS_MAX_LENGTH = 16384;
8
+ /**
9
+ * Mask one email address, keeping its first character and its domain:
10
+ * `member@example.com` → `m***@example.com`. A value without an `@` is
11
+ * returned as `***`.
12
+ *
13
+ * Key-based redaction cannot reach an address that sits inside a message
14
+ * string or a cache key; mask it before it is logged.
15
+ *
16
+ * @example
17
+ * log.info("mail", "send", `Sending mail to: ${maskEmail(to)}`);
18
+ */
19
+ declare function maskEmail(address: string): string;
20
+ /**
21
+ * Mask every email address the pattern above recognises in a piece of text
22
+ * with {@link maskEmail}. Text longer than {@link MASK_EMAILS_MAX_LENGTH}
23
+ * characters is truncated first (the cut is marked).
24
+ *
25
+ * Dots are valid in the local part of an address, so a dotted prefix that
26
+ * runs into the address is masked with it: in a cache key such as
27
+ * `email.member@example.com` the whole `email.member` reads as the local part.
28
+ *
29
+ * Not recognised (left as they are): quoted local parts (`"john doe"@x.com`),
30
+ * IP-literal domains (`user@[127.0.0.1]`) and percent-encoded addresses
31
+ * (`user%40example.com`).
32
+ *
33
+ * @example
34
+ * maskEmailsInText("sent to member@example.com") // "sent to m***@example.com"
35
+ * maskEmailsInText("email.member@example.com") // "e***@example.com"
36
+ */
37
+ declare function maskEmailsInText(text: string): string;
38
+ //#endregion
39
+ export { MASK_EMAILS_MAX_LENGTH, maskEmail, maskEmailsInText };
40
+ //# sourceMappingURL=mask-email.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mask-email.d.mts","names":[],"sources":["../../../../../../../../packages/logger/src/redact/mask-email.ts"],"mappings":";;AAoBA;;;;cAAa,sBAAA;AAab;;;;AAAyC;AA4BzC;;;;AAA6C;;AA5B7C,iBAAgB,SAAA,CAAU,OAAe;;;;;;;;;;;;;;;;;;iBA4BzB,gBAAA,CAAiB,IAAY"}
@@ -0,0 +1,70 @@
1
+ //#region ../../packages/logger/src/redact/mask-email.ts
2
+ /**
3
+ * Email addresses inside free text: a local part and a dotted domain, letters
4
+ * and digits from any script (`jöhn@exämple.de`). Kept deliberately simple (no
5
+ * quoted local parts, no IP-literal domains, no percent-encoded `@`): it masks
6
+ * the addresses that show up in log messages and cache keys, not every string
7
+ * RFC 5322 allows.
8
+ *
9
+ * Every repetition is bounded (local part 64, label 63, at most 12 labels), so
10
+ * matching stays linear in the input length. Cache keys and messages are often
11
+ * built from request input; an unbounded pattern backtracks quadratically on a
12
+ * long run of address-like characters with no domain.
13
+ */
14
+ const EMAIL_IN_TEXT = /[\p{L}\p{N}._%+-]{1,64}@[\p{L}\p{N}-]{1,63}(?:\.[\p{L}\p{N}-]{1,63}){0,10}\.\p{L}{2,63}/gu;
15
+ /**
16
+ * Longest text {@link maskEmailsInText} scans. Anything past it is cut off and
17
+ * replaced by a marker, so a huge cache key or message cannot cost more than a
18
+ * bounded amount of time per log line, and nothing past the cut can leak.
19
+ */
20
+ const MASK_EMAILS_MAX_LENGTH = 16384;
21
+ /**
22
+ * Mask one email address, keeping its first character and its domain:
23
+ * `member@example.com` → `m***@example.com`. A value without an `@` is
24
+ * returned as `***`.
25
+ *
26
+ * Key-based redaction cannot reach an address that sits inside a message
27
+ * string or a cache key; mask it before it is logged.
28
+ *
29
+ * @example
30
+ * log.info("mail", "send", `Sending mail to: ${maskEmail(to)}`);
31
+ */
32
+ function maskEmail(address) {
33
+ const at = address.lastIndexOf("@");
34
+ if (at <= 0) return "***";
35
+ return `${String.fromCodePoint(address.codePointAt(0))}***${address.slice(at)}`;
36
+ }
37
+ /**
38
+ * Mask every email address the pattern above recognises in a piece of text
39
+ * with {@link maskEmail}. Text longer than {@link MASK_EMAILS_MAX_LENGTH}
40
+ * characters is truncated first (the cut is marked).
41
+ *
42
+ * Dots are valid in the local part of an address, so a dotted prefix that
43
+ * runs into the address is masked with it: in a cache key such as
44
+ * `email.member@example.com` the whole `email.member` reads as the local part.
45
+ *
46
+ * Not recognised (left as they are): quoted local parts (`"john doe"@x.com`),
47
+ * IP-literal domains (`user@[127.0.0.1]`) and percent-encoded addresses
48
+ * (`user%40example.com`).
49
+ *
50
+ * @example
51
+ * maskEmailsInText("sent to member@example.com") // "sent to m***@example.com"
52
+ * maskEmailsInText("email.member@example.com") // "e***@example.com"
53
+ */
54
+ function maskEmailsInText(text) {
55
+ let scanned = text;
56
+ let marker = "";
57
+ if (scanned.length > 16384) {
58
+ let cut = MASK_EMAILS_MAX_LENGTH;
59
+ const last = scanned.charCodeAt(cut - 1);
60
+ if (last >= 55296 && last <= 56319) cut -= 1;
61
+ marker = `…[${scanned.length - cut} chars truncated]`;
62
+ scanned = scanned.slice(0, cut);
63
+ }
64
+ if (!scanned.includes("@")) return scanned + marker;
65
+ return scanned.replace(EMAIL_IN_TEXT, (match) => maskEmail(match)) + marker;
66
+ }
67
+
68
+ //#endregion
69
+ export { MASK_EMAILS_MAX_LENGTH, maskEmail, maskEmailsInText };
70
+ //# sourceMappingURL=mask-email.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mask-email.mjs","names":[],"sources":["../../../../../../../../packages/logger/src/redact/mask-email.ts"],"sourcesContent":["/**\n * Email addresses inside free text: a local part and a dotted domain, letters\n * and digits from any script (`jöhn@exämple.de`). Kept deliberately simple (no\n * quoted local parts, no IP-literal domains, no percent-encoded `@`): it masks\n * the addresses that show up in log messages and cache keys, not every string\n * RFC 5322 allows.\n *\n * Every repetition is bounded (local part 64, label 63, at most 12 labels), so\n * matching stays linear in the input length. Cache keys and messages are often\n * built from request input; an unbounded pattern backtracks quadratically on a\n * long run of address-like characters with no domain.\n */\nconst EMAIL_IN_TEXT =\n /[\\p{L}\\p{N}._%+-]{1,64}@[\\p{L}\\p{N}-]{1,63}(?:\\.[\\p{L}\\p{N}-]{1,63}){0,10}\\.\\p{L}{2,63}/gu;\n\n/**\n * Longest text {@link maskEmailsInText} scans. Anything past it is cut off and\n * replaced by a marker, so a huge cache key or message cannot cost more than a\n * bounded amount of time per log line, and nothing past the cut can leak.\n */\nexport const MASK_EMAILS_MAX_LENGTH = 16_384;\n\n/**\n * Mask one email address, keeping its first character and its domain:\n * `member@example.com` → `m***@example.com`. A value without an `@` is\n * returned as `***`.\n *\n * Key-based redaction cannot reach an address that sits inside a message\n * string or a cache key; mask it before it is logged.\n *\n * @example\n * log.info(\"mail\", \"send\", `Sending mail to: ${maskEmail(to)}`);\n */\nexport function maskEmail(address: string): string {\n const at = address.lastIndexOf(\"@\");\n\n if (at <= 0) return \"***\";\n\n // The first code point, not the first UTF-16 unit: never half an emoji.\n const first = String.fromCodePoint(address.codePointAt(0)!);\n\n return `${first}***${address.slice(at)}`;\n}\n\n/**\n * Mask every email address the pattern above recognises in a piece of text\n * with {@link maskEmail}. Text longer than {@link MASK_EMAILS_MAX_LENGTH}\n * characters is truncated first (the cut is marked).\n *\n * Dots are valid in the local part of an address, so a dotted prefix that\n * runs into the address is masked with it: in a cache key such as\n * `email.member@example.com` the whole `email.member` reads as the local part.\n *\n * Not recognised (left as they are): quoted local parts (`\"john doe\"@x.com`),\n * IP-literal domains (`user@[127.0.0.1]`) and percent-encoded addresses\n * (`user%40example.com`).\n *\n * @example\n * maskEmailsInText(\"sent to member@example.com\") // \"sent to m***@example.com\"\n * maskEmailsInText(\"email.member@example.com\") // \"e***@example.com\"\n */\nexport function maskEmailsInText(text: string): string {\n let scanned = text;\n let marker = \"\";\n\n if (scanned.length > MASK_EMAILS_MAX_LENGTH) {\n let cut = MASK_EMAILS_MAX_LENGTH;\n const last = scanned.charCodeAt(cut - 1);\n\n // Never end on the first half of a surrogate pair.\n if (last >= 0xd800 && last <= 0xdbff) cut -= 1;\n\n marker = `…[${scanned.length - cut} chars truncated]`;\n scanned = scanned.slice(0, cut);\n }\n\n if (!scanned.includes(\"@\")) return scanned + marker;\n\n return scanned.replace(EMAIL_IN_TEXT, (match) => maskEmail(match)) + marker;\n}\n"],"mappings":";;;;;;;;;;;;;AAYA,MAAM,gBACJ;;;;;;AAOF,MAAa,yBAAyB;;;;;;;;;;;;AAatC,SAAgB,UAAU,SAAyB;CACjD,MAAM,KAAK,QAAQ,YAAY,GAAG;CAElC,IAAI,MAAM,GAAG,OAAO;CAKpB,OAAO,GAFO,OAAO,cAAc,QAAQ,YAAY,CAAC,CAE1C,EAAE,KAAK,QAAQ,MAAM,EAAE;AACvC;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,iBAAiB,MAAsB;CACrD,IAAI,UAAU;CACd,IAAI,SAAS;CAEb,IAAI,QAAQ,gBAAiC;EAC3C,IAAI,MAAM;EACV,MAAM,OAAO,QAAQ,WAAW,MAAM,CAAC;EAGvC,IAAI,QAAQ,SAAU,QAAQ,OAAQ,OAAO;EAE7C,SAAS,KAAK,QAAQ,SAAS,IAAI;EACnC,UAAU,QAAQ,MAAM,GAAG,GAAG;CAChC;CAEA,IAAI,CAAC,QAAQ,SAAS,GAAG,GAAG,OAAO,UAAU;CAE7C,OAAO,QAAQ,QAAQ,gBAAgB,UAAU,UAAU,KAAK,CAAC,IAAI;AACvE"}
@@ -1,6 +1,6 @@
1
1
  import { LoggingData, RedactConfig } from "../types.mjs";
2
2
 
3
- //#region ../logger/src/redact/redact.d.ts
3
+ //#region ../../packages/logger/src/redact/redact.d.ts
4
4
  /**
5
5
  * Resolve the effective key denylist for a config: the built-in set (unless
6
6
  * `defaultKeys: false`) plus any `keys` the application added.
@@ -1 +1 @@
1
- {"version":3,"file":"redact.d.mts","names":[],"sources":["../../../../../../../logger/src/redact/redact.ts"],"mappings":";;;;;AAkVA;;;;;iBAAgB,iBAAA,CACd,MAAA,EAAQ,YAAA,eACP,WAAW;;;AAAA;AAiDd;;;;;;;;;;;;;;AAGc;AAgDd;;;;;;;;;;iBAnDgB,WAAA,CACd,IAAA,EAAM,WAAA,EACN,MAAA,EAAQ,YAAA,eACP,WAAA;;;;AAmDY;;;;;;;;;;;iBAHC,WAAA,CACd,IAAA,EAAM,YAAA,cACN,KAAA,EAAO,YAAA,eACN,YAAA"}
1
+ {"version":3,"file":"redact.d.mts","names":[],"sources":["../../../../../../../../packages/logger/src/redact/redact.ts"],"mappings":";;;;;AAkVA;;;;;iBAAgB,iBAAA,CACd,MAAA,EAAQ,YAAA,eACP,WAAW;;;AAAA;AAiDd;;;;;;;;;;;;;;AAGc;AAgDd;;;;;;;;;;iBAnDgB,WAAA,CACd,IAAA,EAAM,WAAA,EACN,MAAA,EAAQ,YAAA,eACP,WAAA;;;;AAmDY;;;;;;;;;;;iBAHC,WAAA,CACd,IAAA,EAAM,YAAA,cACN,KAAA,EAAO,YAAA,eACN,YAAA"}
@@ -1,6 +1,6 @@
1
1
  import { DEFAULT_REDACT_KEY_SET, normalizeRedactKey } from "./default-keys.mjs";
2
2
 
3
- //#region ../logger/src/redact/redact.ts
3
+ //#region ../../packages/logger/src/redact/redact.ts
4
4
  const DEFAULT_CENSOR = "[REDACTED]";
5
5
  /**
6
6
  * Values we copy by reference rather than walking. Expanding these with