voltlog-io 1.0.1

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.
@@ -0,0 +1,1142 @@
1
+ /**
2
+ * @module voltlog-io
3
+ * @description Type definitions for the OCPP-aware structured logger.
4
+ */
5
+ declare const LogLevel: {
6
+ readonly TRACE: 10;
7
+ readonly DEBUG: 20;
8
+ readonly INFO: 30;
9
+ readonly WARN: 40;
10
+ readonly ERROR: 50;
11
+ readonly FATAL: 60;
12
+ readonly SILENT: number;
13
+ };
14
+ type LogLevelName = keyof typeof LogLevel;
15
+ /** Numeric log level value */
16
+ type LogLevelValue = (typeof LogLevel)[LogLevelName];
17
+ /** Map from level name (lowercase) to numeric value */
18
+ declare const LogLevelNameMap: Record<string, number>;
19
+ /** Map from numeric value to level name */
20
+ declare const LogLevelValueMap: Record<number, LogLevelName>;
21
+ interface LogEntry<TMeta = Record<string, unknown>> {
22
+ /** Unique log ID (cuid2) */
23
+ id: string;
24
+ /** Numeric log level */
25
+ level: number;
26
+ /** Human-readable level name */
27
+ levelName: LogLevelName;
28
+ /** Log message */
29
+ message: string;
30
+ /** Unix epoch timestamp (ms) */
31
+ timestamp: number;
32
+ /** User-defined structured metadata (type-safe via generics) */
33
+ meta: TMeta;
34
+ /** Bound context from child logger (e.g. chargePointId, sessionId) */
35
+ context?: Record<string, unknown>;
36
+ /** Correlation ID for tracing across async operations */
37
+ correlationId?: string;
38
+ /** Error information */
39
+ error?: LogError;
40
+ }
41
+ interface LogError {
42
+ message: string;
43
+ stack?: string;
44
+ code?: string;
45
+ name?: string;
46
+ }
47
+ interface OcppExchangeMeta {
48
+ /** Charge point / station identity */
49
+ chargePointId?: string;
50
+ /** OCPP message type */
51
+ messageType?: "CALL" | "CALLRESULT" | "CALLERROR";
52
+ /** OCPP action name (e.g. BootNotification) */
53
+ action?: string;
54
+ /** Message direction */
55
+ direction?: "IN" | "OUT";
56
+ /** Correlation ID for request/response matching */
57
+ correlationId?: string;
58
+ /** Negotiated OCPP protocol version */
59
+ protocol?: string;
60
+ /** Serialized payload size in bytes */
61
+ payloadSize?: number;
62
+ /** Latency in milliseconds */
63
+ latencyMs?: number;
64
+ /** Response status (e.g. Accepted, Rejected) */
65
+ status?: string;
66
+ }
67
+ /**
68
+ * A Transport receives formatted log entries and delivers them
69
+ * to a destination (console, file, webhook, database, etc.).
70
+ *
71
+ * Transports are async-safe — `write()` can return a Promise.
72
+ */
73
+ interface Transport<TMeta = Record<string, unknown>> {
74
+ /** Unique name for this transport */
75
+ name: string;
76
+ /** Optional per-transport level filter */
77
+ level?: LogLevelName;
78
+ /** Process a log entry */
79
+ write(entry: LogEntry<TMeta>): void | Promise<void>;
80
+ /** Flush any buffered entries */
81
+ flush?(): void | Promise<void>;
82
+ /** Graceful shutdown */
83
+ close?(): void | Promise<void>;
84
+ }
85
+ /**
86
+ * Middleware intercepts log entries before they reach transports.
87
+ * Used for redaction, sampling, enrichment, alerting, etc.
88
+ *
89
+ * Call `next(entry)` to continue the pipeline.
90
+ * Omit `next()` to drop the entry (e.g. sampling).
91
+ */
92
+ type LogMiddleware<TMeta = Record<string, unknown>> = (entry: LogEntry<TMeta>, next: (entry: LogEntry<TMeta>) => void) => void;
93
+ /**
94
+ * Alert rules evaluate log entries and fire callbacks
95
+ * when configurable conditions are met.
96
+ */
97
+ interface AlertRule<TMeta = Record<string, unknown>> {
98
+ /** Alert name (for identification) */
99
+ name: string;
100
+ /** Condition — return true if this entry should count toward the alert */
101
+ when: (entry: LogEntry<TMeta>) => boolean;
102
+ /** Number of matching entries required to fire (default: 1) */
103
+ threshold?: number;
104
+ /** Time window in ms for threshold counting */
105
+ windowMs?: number;
106
+ /** Minimum cooldown in ms between alert firings (default: 0) */
107
+ cooldownMs?: number;
108
+ /** Callback fired when alert conditions are met */
109
+ onAlert: (entries: LogEntry<TMeta>[]) => void | Promise<void>;
110
+ }
111
+ interface LoggerOptions<TMeta = Record<string, unknown>> {
112
+ /** Minimum log level (default: INFO) */
113
+ level?: LogLevelName;
114
+ /** Transports for log output */
115
+ transports?: Transport<TMeta>[];
116
+ /** Middleware pipeline */
117
+ middleware?: LogMiddleware<TMeta>[];
118
+ /** Alert rules */
119
+ alerts?: AlertRule<TMeta>[];
120
+ /** Default bound context for all log entries */
121
+ context?: Record<string, unknown>;
122
+ /** Field paths to auto-redact (e.g. ['idToken', 'password']) */
123
+ redact?: string[];
124
+ /**
125
+ * When to include error stack traces:
126
+ * - `true` — always include
127
+ * - `false` — never include
128
+ * - `LogLevelName` — include at this level and above
129
+ * Default: 'ERROR'
130
+ */
131
+ includeStack?: boolean | LogLevelName;
132
+ /**
133
+ * Exchange log mode:
134
+ * - `true` — exchange logs alongside normal logs
135
+ * - `'only'` — only exchange-formatted logs
136
+ * - `false` — disabled (default)
137
+ */
138
+ exchangeLog?: boolean | "only";
139
+ /** Custom timestamp function (default: Date.now) */
140
+ timestamp?: () => number;
141
+ }
142
+ interface Logger<TMeta = Record<string, unknown>> {
143
+ trace(message: string, meta?: Partial<TMeta>): void;
144
+ debug(message: string, meta?: Partial<TMeta>): void;
145
+ info(message: string, meta?: Partial<TMeta>): void;
146
+ warn(message: string, meta?: Partial<TMeta>): void;
147
+ error(message: string, metaOrError?: Partial<TMeta> | Error, error?: Error): void;
148
+ fatal(message: string, metaOrError?: Partial<TMeta> | Error, error?: Error): void;
149
+ /** Create a child logger with additional bound context */
150
+ child(context: Record<string, unknown>): Logger<TMeta>;
151
+ /** Add a transport at runtime */
152
+ addTransport(transport: Transport<TMeta>): void;
153
+ /** Remove a transport by name */
154
+ removeTransport(name: string): void;
155
+ /** Add middleware at runtime */
156
+ addMiddleware(middleware: LogMiddleware<TMeta>): void;
157
+ /** Flush all transports */
158
+ flush(): Promise<void>;
159
+ /** Close all transports gracefully */
160
+ close(): Promise<void>;
161
+ }
162
+
163
+ /**
164
+ * @module voltlog-io
165
+ * @description Log level utilities — filtering, comparison, resolution.
166
+ */
167
+
168
+ /**
169
+ * Resolve a level name string to its numeric value.
170
+ * Case-insensitive. Returns INFO if unrecognized.
171
+ */
172
+ declare function resolveLevel(level: string | LogLevelName): number;
173
+ /**
174
+ * Check if a log entry at `entryLevel` passes the `filterLevel`.
175
+ */
176
+ declare function shouldLog(entryLevel: number, filterLevel: number): boolean;
177
+ /**
178
+ * Determine whether to include stack trace for a given entry level.
179
+ */
180
+ declare function shouldIncludeStack(entryLevel: number, includeStack: boolean | LogLevelName): boolean;
181
+
182
+ /**
183
+ * @module voltlog-io
184
+ * @description Core Logger class — zero external dependencies (only cuid2), runtime-agnostic.
185
+ *
186
+ * @example Basic usage
187
+ * ```ts
188
+ * import { createLogger, consoleTransport } from 'voltlog-io';
189
+ *
190
+ * const logger = createLogger({
191
+ * level: 'INFO',
192
+ * transports: [consoleTransport()],
193
+ * });
194
+ *
195
+ * logger.info('Server started', { port: 9000 });
196
+ * ```
197
+ *
198
+ * @example Child logger with bound context
199
+ * ```ts
200
+ * const cpLogger = logger.child({ chargePointId: 'CP-101' });
201
+ * cpLogger.info('BootNotification received');
202
+ * // → auto-includes context: { chargePointId: 'CP-101' }
203
+ * ```
204
+ *
205
+ * @example Error with stack trace
206
+ * ```ts
207
+ * logger.error('Connection failed', new Error('ETIMEDOUT'));
208
+ * logger.error('Handler crashed', { action: 'BootNotification' }, new Error('null ref'));
209
+ * ```
210
+ *
211
+ * @example With ocpp-ws-io (if user has both packages)
212
+ * ```ts
213
+ * import { createLogger } from 'ocpp-ws-io/logger'; // re-export
214
+ * ```
215
+ */
216
+
217
+ /**
218
+ * Create a new logger instance.
219
+ *
220
+ * @example Minimal
221
+ * ```ts
222
+ * const logger = createLogger();
223
+ * logger.info('Hello');
224
+ * ```
225
+ *
226
+ * @example Full options
227
+ * ```ts
228
+ * import { createLogger, consoleTransport, prettyTransport } from 'voltlog-io';
229
+ *
230
+ * const logger = createLogger({
231
+ * level: 'DEBUG',
232
+ * transports: [prettyTransport()],
233
+ * redact: ['password', 'idToken'],
234
+ * includeStack: 'ERROR',
235
+ * });
236
+ * ```
237
+ *
238
+ * @example OCPP-aware with child loggers
239
+ * ```ts
240
+ * import { createLogger, prettyTransport } from 'voltlog-io';
241
+ * import type { OcppExchangeMeta } from 'voltlog-io';
242
+ *
243
+ * const logger = createLogger<OcppExchangeMeta>({
244
+ * level: 'INFO',
245
+ * transports: [prettyTransport()],
246
+ * });
247
+ *
248
+ * // Per-connection child logger
249
+ * const cpLog = logger.child({ chargePointId: 'CP-101' });
250
+ * cpLog.info('OCPP message', {
251
+ * messageType: 'CALL',
252
+ * action: 'BootNotification',
253
+ * direction: 'IN',
254
+ * });
255
+ * ```
256
+ */
257
+ declare function createLogger<TMeta = Record<string, unknown>>(options?: LoggerOptions<TMeta>): Logger<TMeta>;
258
+
259
+ /**
260
+ * @module voltlog-io
261
+ * @description AI Enrichment middleware — enriches logs with AI analysis (e.g. error explanation).
262
+ * @universal Works in all environments (uses `fetch`).
263
+ *
264
+ * > **Security Note**: Requires an API Key. Using this in the browser will expose your key to the client.
265
+ * > Recommended for server-side use only.
266
+ */
267
+
268
+ interface AiEnrichmentOptions {
269
+ /**
270
+ * Only trigger for logs at or above this level.
271
+ * Default: ERROR
272
+ */
273
+ level?: LogLevelName;
274
+ /**
275
+ * Field name to store the analysis result in `entry.meta`.
276
+ * Default: 'ai_analysis'
277
+ */
278
+ targetField?: string;
279
+ /**
280
+ * Custom analyzer function.
281
+ * Return a string (analysis) or object (structured data) to attach to `meta[targetField]`.
282
+ */
283
+ analyzer: (entry: LogEntry) => Promise<string | Record<string, unknown> | null>;
284
+ /**
285
+ * Timeout in milliseconds for the AI call.
286
+ * Default: 2000ms (fail fast to avoid blocking for too long)
287
+ */
288
+ timeout?: number;
289
+ /**
290
+ * If true, errors in the analyzer are swallowed (logged to console.error but don't crash).
291
+ * Default: true
292
+ */
293
+ swallowErrors?: boolean;
294
+ }
295
+ /**
296
+ * Enriches log entries by calling an asynchronous AI analyzer.
297
+ * Appends result to `entry.meta[targetField]`.
298
+ *
299
+ * @example
300
+ * ```ts
301
+ * const ai = aiEnrichmentMiddleware({
302
+ * analyzer: createOpenAiErrorAnalyzer(process.env.OPENAI_API_KEY!),
303
+ * level: "ERROR",
304
+ * targetField: "error_explanation"
305
+ * });
306
+ * ```
307
+ */
308
+ declare function aiEnrichmentMiddleware<TMeta = Record<string, unknown>>(options: AiEnrichmentOptions): LogMiddleware<TMeta>;
309
+ /**
310
+ * Helper to create an OpenAI-compatible analyzer specifically for Error explanation.
311
+ */
312
+ declare function createOpenAiErrorAnalyzer(apiKey: string, model?: string, systemPrompt?: string): (entry: LogEntry) => Promise<string | null>;
313
+
314
+ /**
315
+ * @module voltlog-io
316
+ * @description Alert middleware — checks logs against rules and triggers alerts.
317
+ * @universal Works in all environments.
318
+ * @example
319
+ * ```ts
320
+ * import { createLogger, consoleTransport, alertMiddleware } from 'voltlog-io';
321
+ *
322
+ * const logger = createLogger({
323
+ * transports: [consoleTransport()],
324
+ * middleware: [
325
+ * alertMiddleware([
326
+ * {
327
+ * name: 'error-spike',
328
+ * when: (entry) => entry.level >= 50, // ERROR+
329
+ * threshold: 10,
330
+ * windowMs: 60_000,
331
+ * cooldownMs: 300_000,
332
+ * onAlert: async (entries) => {
333
+ * await sendEmail({ subject: `${entries.length} errors in 1 min` });
334
+ * },
335
+ * },
336
+ * {
337
+ * name: 'callerror-alert',
338
+ * when: (entry) => entry.meta.messageType === 'CALLERROR',
339
+ * threshold: 5,
340
+ * windowMs: 60_000,
341
+ * onAlert: (entries) => sendSlackNotification(entries),
342
+ * },
343
+ * ]),
344
+ * ],
345
+ * });
346
+ * ```
347
+ */
348
+
349
+ /**
350
+ * Create an alert middleware that evaluates rules against every log entry.
351
+ *
352
+ * Alerts are non-blocking — `onAlert` failures are silently caught
353
+ * to never interfere with the logging pipeline.
354
+ */
355
+ declare function alertMiddleware<TMeta = Record<string, unknown>>(rules: AlertRule<TMeta>[]): LogMiddleware<TMeta>;
356
+
357
+ /**
358
+ * @module voltlog-io
359
+ * @description Correlation ID middleware — adds tracing IDs to logs.
360
+ * @universal Works in all environments.
361
+ * Useful for tracking requests across microservices.
362
+ */
363
+
364
+ interface CorrelationIdOptions {
365
+ /**
366
+ * Header name or meta key to check for existing ID.
367
+ * Default: 'x-correlation-id' (and checks 'traceId', 'correlationId')
368
+ */
369
+ header?: string;
370
+ /**
371
+ * Function to generate new IDs.
372
+ * Default: cuid2
373
+ */
374
+ generator?: () => string;
375
+ }
376
+ /**
377
+ * Middleware that ensures every log entry has a correlation ID.
378
+ * checks:
379
+ * 1. entry.correlationId
380
+ * 2. entry.meta.correlationId
381
+ * 3. entry.meta.traceId
382
+ * 4. entry.meta[header]
383
+ *
384
+ * If none found, generates a new one.
385
+ */
386
+ declare function correlationIdMiddleware<TMeta = Record<string, unknown>>(options?: CorrelationIdOptions): LogMiddleware<TMeta>;
387
+
388
+ /**
389
+ * Helper to create a type-safe middleware function.
390
+ *
391
+ * @example
392
+ * const myMiddleware = createMiddleware((entry, next) => {
393
+ * entry.meta.foo = 'bar';
394
+ * next(entry);
395
+ * });
396
+ */
397
+ declare function createMiddleware<TMeta = Record<string, unknown>>(fn: LogMiddleware<TMeta>): LogMiddleware<TMeta>;
398
+
399
+ /**
400
+ * @module voltlog-io
401
+ * @description Deduplication middleware — groups identical logs in a time window.
402
+ * @universal Works in all environments.
403
+ */
404
+
405
+ interface DeduplicationOptions<TMeta = Record<string, unknown>> {
406
+ /**
407
+ * Time window in ms to group logs.
408
+ * Logs matching the key within this window will be aggregated.
409
+ * Default: 1000ms
410
+ */
411
+ windowMs?: number;
412
+ /**
413
+ * Function to generate a unique key for deduplication.
414
+ * Default: uses `entry.message` + `entry.level`
415
+ */
416
+ keyFn?: (entry: LogEntry<TMeta>) => string;
417
+ }
418
+ /**
419
+ * Deduplication middleware.
420
+ * Buffers logs for `windowMs`. If identical logs arrive, increments a counter.
421
+ * Emits the log once at the end of the window with `meta.duplicateCount`.
422
+ */
423
+ declare function deduplicationMiddleware<TMeta = Record<string, unknown>>(options?: DeduplicationOptions<TMeta>): LogMiddleware<TMeta>;
424
+
425
+ /**
426
+ * @module voltlog-io
427
+ * @description Heap usage middleware — adds memory stats to logs.
428
+ * @universal Works in all environments, but only adds data in Node.js/Bun/Deno.
429
+ * Checks for `process.memoryUsage` presence before execution.
430
+ */
431
+
432
+ interface HeapUsageOptions {
433
+ /**
434
+ * Field name to store memory stats in `entry.meta`.
435
+ * Default: 'memory'
436
+ */
437
+ fieldName?: string;
438
+ }
439
+ /**
440
+ * Adds `rss`, `heapTotal`, and `heapUsed` to log metadata.
441
+ * Only works in environments where `process.memoryUsage` is available (Node.js/Bun/Deno).
442
+ */
443
+ declare function heapUsageMiddleware<TMeta = Record<string, unknown>>(options?: HeapUsageOptions): LogMiddleware<TMeta>;
444
+
445
+ /**
446
+ * @module voltlog-io
447
+ * @description IP middleware — extracts client IP from headers (x-forwarded-for, etc.).
448
+ * @universal Works in any environment where headers are available in metadata.
449
+ */
450
+
451
+ interface IpMiddlewareOptions {
452
+ /**
453
+ * Field name to store the extracted IP in `entry.meta`.
454
+ * Default: 'ip'
455
+ */
456
+ fieldName?: string;
457
+ /**
458
+ * Custom list of headers/keys to check for IP address.
459
+ * Default: ['x-forwarded-for', 'x-real-ip', 'req.ip', 'ip']
460
+ */
461
+ headerKeys?: string[];
462
+ }
463
+ /**
464
+ * Extracts IP address from commonly used headers in `entry.meta`.
465
+ */
466
+ declare function ipMiddleware<TMeta = Record<string, unknown>>(options?: IpMiddlewareOptions): LogMiddleware<TMeta>;
467
+
468
+ /**
469
+ * @module voltlog-io
470
+ * @description Level Override middleware — allows forcing a log level for specific requests.
471
+ * @universal Works in all environments.
472
+ * Useful for debugging specific users/requests in production without changing global config.
473
+ */
474
+
475
+ interface LevelOverrideOptions {
476
+ /**
477
+ * Header name or meta key to trigger override.
478
+ * Default: 'x-log-level'
479
+ */
480
+ key?: string;
481
+ /**
482
+ * If true, removes the trigger key from metadata before logging.
483
+ * Default: true
484
+ */
485
+ cleanup?: boolean;
486
+ }
487
+ /**
488
+ * Dynamically changes the log entry level if a specific key is found in meta/context.
489
+ * E.g. passing `x-log-level: DEBUG` allows a specific request to bypass INFO filters.
490
+ */
491
+ declare function levelOverrideMiddleware<TMeta = Record<string, unknown>>(options?: LevelOverrideOptions): LogMiddleware<TMeta>;
492
+
493
+ /**
494
+ * @module voltlog-io
495
+ * @description OCPP middleware — masks sensitive fields and calculates latency for OCPP messages.
496
+ * @universal Works in all environments.
497
+ *
498
+ * @example
499
+ * ```ts
500
+ * import { createLogger, consoleTransport, ocppMiddleware } from 'voltlog-io';
501
+ * import type { OcppExchangeMeta } from 'voltlog-io';
502
+ *
503
+ * const logger = createLogger<OcppExchangeMeta>({
504
+ * transports: [consoleTransport()],
505
+ * middleware: [ocppMiddleware()],
506
+ * });
507
+ *
508
+ * // The middleware auto-computes payloadSize and adds correlationId to the entry
509
+ * logger.info('Message received', {
510
+ * action: 'BootNotification',
511
+ * messageType: 'CALL',
512
+ * direction: 'IN',
513
+ * });
514
+ * ```
515
+ */
516
+
517
+ interface OcppMiddlewareOptions {
518
+ /**
519
+ * Automatically compute payload size from meta if not set.
520
+ * Default: true
521
+ */
522
+ autoPayloadSize?: boolean;
523
+ /**
524
+ * Propagate correlationId from meta to entry.correlationId.
525
+ * Default: true
526
+ */
527
+ propagateCorrelationId?: boolean;
528
+ }
529
+ /**
530
+ * Create an OCPP enrichment middleware.
531
+ * Enriches log entries with computed OCPP metadata.
532
+ */
533
+ declare function ocppMiddleware(options?: OcppMiddlewareOptions): LogMiddleware<OcppExchangeMeta>;
534
+
535
+ /**
536
+ * @module voltlog-io
537
+ * @description Redaction middleware — masks sensitive data in log entries.
538
+ * @universal Works in all environments.
539
+ *
540
+ * @example
541
+ * ```ts
542
+ * import { createLogger, consoleTransport, redactionMiddleware } from 'voltlog-io';
543
+ *
544
+ * const logger = createLogger({
545
+ * transports: [consoleTransport()],
546
+ * middleware: [redactionMiddleware({ paths: ['password', 'idToken', 'authorization'] })],
547
+ * });
548
+ *
549
+ * logger.info('Auth attempt', { password: 's3cret', user: 'admin' });
550
+ * // → { password: '[REDACTED]', user: 'admin' }
551
+ * ```
552
+ */
553
+
554
+ interface RedactionOptions {
555
+ /** Field paths to redact (case-insensitive matching) */
556
+ paths: string[];
557
+ /** Replacement value (default: '[REDACTED]') */
558
+ replacement?: string;
559
+ /** Also redact matching keys in nested objects (default: true) */
560
+ deep?: boolean;
561
+ }
562
+ /**
563
+ * Create a redaction middleware that replaces sensitive field values.
564
+ */
565
+ declare function redactionMiddleware<TMeta = Record<string, unknown>>(options: RedactionOptions): LogMiddleware<TMeta>;
566
+
567
+ /**
568
+ * @module voltlog-io
569
+ * @description Sampling middleware — rate limits or probabilistically samples logs.
570
+ * @universal Works in all environments.
571
+ * @example
572
+ * ```ts
573
+ * import { createLogger, consoleTransport, samplingMiddleware } from 'voltlog-io';
574
+ *
575
+ * const logger = createLogger({
576
+ * transports: [consoleTransport()],
577
+ * middleware: [
578
+ * samplingMiddleware({
579
+ * keyFn: (entry) => `${entry.meta.action}:${entry.meta.chargePointId}`,
580
+ * maxPerWindow: 10,
581
+ * windowMs: 60_000, // 10 logs per minute per action+CP combo
582
+ * }),
583
+ * ],
584
+ * });
585
+ * ```
586
+ */
587
+
588
+ interface SamplingOptions<TMeta = Record<string, unknown>> {
589
+ /**
590
+ * Function to extract a sampling key from a log entry.
591
+ * Entries with the same key share a rate limit.
592
+ * Default: uses `entry.message`
593
+ */
594
+ keyFn?: (entry: LogEntry<TMeta>) => string;
595
+ /** Maximum entries allowed per key per window (default: 100) */
596
+ maxPerWindow?: number;
597
+ /** Time window in ms (default: 60000 = 1 minute) */
598
+ windowMs?: number;
599
+ /** Probability to keep a log (0 to 1). Default: 1 (keep all) */
600
+ sampleRate?: number;
601
+ /** Logs at this level or higher always pass. Default: 40 (WARN) */
602
+ priorityLevel?: number;
603
+ }
604
+ /**
605
+ * Create a sampling middleware that drops logs exceeding the rate limit.
606
+ */
607
+ declare function samplingMiddleware<TMeta = Record<string, unknown>>(options?: SamplingOptions<TMeta>): LogMiddleware<TMeta>;
608
+
609
+ /**
610
+ * @module voltlog-io
611
+ * @description User Agent middleware — parses UA strings into browser/os/device info.
612
+ * @universal Works in all environments (Server/Browser).
613
+ * Lightweight regex-based parsing to avoid heavy dependencies.
614
+ */
615
+
616
+ interface UserAgentOptions {
617
+ /**
618
+ * Field to look for user agent string (source).
619
+ * Default checks `entry.meta.userAgent`, `entry.meta['user-agent']`, or context.
620
+ */
621
+ sourceField?: string;
622
+ /**
623
+ * Field to store the parsed info (target).
624
+ * Default: 'client'
625
+ */
626
+ targetField?: string;
627
+ }
628
+ /**
629
+ * Parses user-agent string into structured data (browser, os).
630
+ */
631
+ declare function userAgentMiddleware<TMeta = Record<string, unknown>>(options?: UserAgentOptions): LogMiddleware<TMeta>;
632
+
633
+ /**
634
+ * @module voltlog-io
635
+ * @description Batch transformer — wraps another transformer and buffers logs.
636
+ * @universal Works in all environments.
637
+ *
638
+ * @example
639
+ * ```ts
640
+ * import { createLogger, batchTransport, consoleTransport } from 'voltlog-io';
641
+ *
642
+ * // Batch console output: flush every 100 entries or every 2 seconds
643
+ * const logger = createLogger({
644
+ * transports: [
645
+ * batchTransport(consoleTransport(), { batchSize: 100, flushIntervalMs: 2000 }),
646
+ * ],
647
+ * });
648
+ * ```
649
+ */
650
+
651
+ interface BatchTransportOptions {
652
+ /** Number of entries to buffer before flushing (default: 100) */
653
+ batchSize?: number;
654
+ /** Max time in ms to wait before flushing a partial batch (default: 5000) */
655
+ flushIntervalMs?: number;
656
+ }
657
+ /**
658
+ * Wrap any transport with batching. Entries are buffered and flushed
659
+ * either when the batch is full or the timer fires.
660
+ */
661
+ declare function batchTransport(inner: Transport, options?: BatchTransportOptions): Transport;
662
+
663
+ /**
664
+ * @module voltlog-io
665
+ * @description Browser stream transformer — writes newline-delimited JSON to a WHATWG WritableStream.
666
+ * @browser-only Depends on WHATWG Streams API (typical in Browsers/Edge).
667
+ * Useful for streaming logs in browser environments (e.g. to `fetch` streams or ServiceWorkers).
668
+ */
669
+
670
+ interface BrowserJsonStreamTransportOptions {
671
+ /**
672
+ * Writable stream to output to.
673
+ * Must be a standard WHATWG WritableStream (available in modern browsers).
674
+ */
675
+ stream: WritableStream<string>;
676
+ /** Per-transport level filter */
677
+ level?: LogLevelName;
678
+ /**
679
+ * Custom serializer. Return the string to write.
680
+ * Default: JSON.stringify(entry) + '\n'
681
+ */
682
+ serializer?: (entry: LogEntry) => string;
683
+ }
684
+ /**
685
+ * Create a JSON stream transport for browsers that writes to a WritableStream.
686
+ */
687
+ declare function browserJsonStreamTransport(options: BrowserJsonStreamTransportOptions): Transport;
688
+
689
+ /**
690
+ * @module voltlog-io
691
+ * @description Console transformer — writes to `console.log`, `console.error`, etc.
692
+ * @universal Works in all environments. Works in Node.js, browsers, and all runtimes.
693
+ *
694
+ * @example
695
+ * ```ts
696
+ * import { createLogger, consoleTransport } from 'voltlog-io';
697
+ *
698
+ * const logger = createLogger({
699
+ * transports: [consoleTransport()],
700
+ * });
701
+ * ```
702
+ */
703
+
704
+ interface ConsoleTransportOptions {
705
+ /** Per-transport level filter */
706
+ level?: LogLevelName;
707
+ /**
708
+ * Use appropriate console method per level (console.warn, console.error, etc.).
709
+ * Default: true
710
+ */
711
+ useConsoleLevels?: boolean;
712
+ /**
713
+ * Format the entry before outputting. Return any value that console.log can handle.
714
+ * Default: serializes to JSON string.
715
+ */
716
+ formatter?: (entry: LogEntry) => unknown;
717
+ }
718
+ /**
719
+ * Create a console transport. Outputs structured JSON to the console.
720
+ */
721
+ declare function consoleTransport(options?: ConsoleTransportOptions): Transport;
722
+
723
+ /**
724
+ * @module voltlog-io
725
+ * @description Helper to create custom transports easily.
726
+ * @universal Works in all environments.
727
+ */
728
+
729
+ /**
730
+ * Helper to build a transport without manually defining the object structure.
731
+ *
732
+ * @example
733
+ * const myTransport = createTransport('my-api', async (entry) => {
734
+ * await fetch('https://api.example.com/logs', { body: JSON.stringify(entry) });
735
+ * });
736
+ *
737
+ * @param name - Unique name for the transport
738
+ * @param write - Function to process log entries
739
+ * @param options - Optional overrides (level, flush, close)
740
+ */
741
+ declare function createTransport(name: string, write: (entry: LogEntry) => void | Promise<void>, options?: Partial<Omit<Transport, "name" | "write">>): Transport;
742
+
743
+ /**
744
+ * @module voltlog-io
745
+ * @description Datadog transformer — sends logs directly to Datadog Intake API.
746
+ * @universal Works in all environments (uses `fetch`).
747
+ *
748
+ * > **Security Note**: Using this in the browser will expose your API Key.
749
+ * > Recommended for server-side use only.
750
+ */
751
+
752
+ interface DatadogTransportOptions {
753
+ /** Datadog API Key */
754
+ apiKey: string;
755
+ /** Datadog Site (default: datadoghq.com) */
756
+ site?: string;
757
+ /** Service name tag */
758
+ service?: string;
759
+ /** Source tag (default: nodejs) */
760
+ ddSource?: string;
761
+ /** Hostname override */
762
+ hostname?: string;
763
+ /** Tags (comma separated: env:prod,version:1.0) */
764
+ tags?: string;
765
+ /** Transport level filter */
766
+ level?: LogLevelName;
767
+ }
768
+ /**
769
+ * Sends logs to Datadog via HTTP POST.
770
+ * Uses built-in batching (not implemented here for brevity, typically would use batchTransport wrapper).
771
+ * This implementation sends immediately for simplicity or relies on `batchTransport` composition.
772
+ */
773
+ declare function datadogTransport(options: DatadogTransportOptions): Transport;
774
+
775
+ /**
776
+ * @module voltlog-io
777
+ * @description Discord transformer — sends logs to Discord via Webhook.
778
+ * @universal Works in all environments (uses `fetch`).
779
+ *
780
+ * > **Security Note**: Using this in the browser will expose your Webhook URL.
781
+ * > Recommended for server-side use only.
782
+ */
783
+
784
+ interface DiscordTransportOptions {
785
+ /** Discord Webhook URL */
786
+ webhookUrl: string;
787
+ /** Minimum log level (default: ERROR) */
788
+ level?: LogLevelName;
789
+ /** Username override */
790
+ username?: string;
791
+ /** Avatar URL override */
792
+ avatarUrl?: string;
793
+ }
794
+ /**
795
+ * Sends formatted embeds to Discord.
796
+ * Best used for Alerts/Errors.
797
+ */
798
+ declare function discordTransport(options: DiscordTransportOptions): Transport;
799
+
800
+ /**
801
+ * @module voltlog-io
802
+ * @description File transformer — writes logs to disk with daily rotation.
803
+ * @server-only
804
+ * This transport relies on the `node:fs` module to write files to the local filesystem.
805
+ * Browsers do not have direct access to the filesystem for security reasons.
806
+ */
807
+
808
+ interface FileTransportOptions {
809
+ /** Directory to store logs. Created if missing. */
810
+ dir: string;
811
+ /**
812
+ * Filename pattern. Use `%DATE%` for YYYY-MM-DD.
813
+ * Default: `app-%DATE%.log`
814
+ */
815
+ filename?: string;
816
+ /** Per-transport level filter */
817
+ level?: LogLevelName;
818
+ }
819
+ /**
820
+ * Creates a file transport that writes newline-delimited JSON.
821
+ * Rotates files daily based on the `%DATE%` pattern.
822
+ */
823
+ declare function fileTransport(options: FileTransportOptions): Transport;
824
+
825
+ /**
826
+ * @module voltlog-io
827
+ * @description JSON stream transformer — writes newline-delimited JSON to any writable stream.
828
+ * @server-only
829
+ * This transport relies on Node.js-style `Writable` streams (e.g. `process.stdout`, `fs.createWriteStream`).
830
+ * Browser streams (WHATWG Streams API) use a different interface.
831
+ *
832
+ * Useful for file logging, piping to external tools, etc.
833
+ *
834
+ * @example Write to file
835
+ * ```ts
836
+ * import { createWriteStream } from 'node:fs';
837
+ * import { createLogger, jsonStreamTransport } from 'voltlog-io';
838
+ *
839
+ * const logger = createLogger({
840
+ * transports: [
841
+ * jsonStreamTransport({ stream: createWriteStream('./app.log', { flags: 'a' }) }),
842
+ * ],
843
+ * });
844
+ * ```
845
+ *
846
+ * @example Write to stdout
847
+ * ```ts
848
+ * const logger = createLogger({
849
+ * transports: [jsonStreamTransport({ stream: process.stdout })],
850
+ * });
851
+ * ```
852
+ */
853
+
854
+ interface JsonStreamTransportOptions {
855
+ /** Writable stream to output to (e.g. fs.createWriteStream, process.stdout) */
856
+ stream: NodeJS.WritableStream;
857
+ /** Per-transport level filter */
858
+ level?: LogLevelName;
859
+ /**
860
+ * Custom serializer. Return the string to write.
861
+ * Default: JSON.stringify(entry) + '\n'
862
+ */
863
+ serializer?: (entry: LogEntry) => string;
864
+ }
865
+ /**
866
+ * Create a JSON stream transport that writes newline-delimited JSON.
867
+ */
868
+ declare function jsonStreamTransport(options: JsonStreamTransportOptions): Transport;
869
+
870
+ /**
871
+ * @module voltlog-io
872
+ * @description Loki transformer — pushes logs to Grafana Loki.
873
+ * @universal Works in all environments (uses `fetch`).
874
+ *
875
+ * > **Security Note**: Using this in the browser exposes auth details and may face CORS issues.
876
+ * > Recommended for server-side use.
877
+ */
878
+
879
+ interface LokiTransportOptions {
880
+ /** Loki URL (e.g. http://localhost:3100) */
881
+ host: string;
882
+ /** Basic Auth username */
883
+ basicAuthUser?: string;
884
+ /** Basic Auth password/token */
885
+ basicAuthPassword?: string;
886
+ /** Tenant ID (header X-Scope-OrgID) */
887
+ tenantId?: string;
888
+ /** Labels to attach to every stream (e.g. { app: 'volt-server' }) */
889
+ labels?: Record<string, string>;
890
+ /** Transport level filter */
891
+ level?: LogLevelName;
892
+ /** Batch size (default: 10) */
893
+ batchSize?: number;
894
+ /** Batch interval ms (default: 5000) */
895
+ interval?: number;
896
+ }
897
+ /**
898
+ * Pushes logs to Grafana Loki via HTTP API.
899
+ * Uses batching to improve performance.
900
+ */
901
+ declare function lokiTransport(options: LokiTransportOptions): Transport;
902
+
903
+ /**
904
+ * @module voltlog-io
905
+ * @description Pretty transformer — human-readable colored output with OCPP exchange formatting.
906
+ * @universal Works in all environments (uses ANSI codes, supported by many browser consoles or stripped).
907
+ *
908
+ * @example Dev mode
909
+ * ```ts
910
+ * import { createLogger, prettyTransport } from 'voltlog-io';
911
+ *
912
+ * const logger = createLogger({
913
+ * transports: [prettyTransport()],
914
+ * });
915
+ *
916
+ * logger.info('Server started', { port: 9000 });
917
+ * // → ℹ 2024-01-15T10:30:00.000Z INFO Server started { port: 9000 }
918
+ * ```
919
+ *
920
+ * @example OCPP exchange logs
921
+ * ```ts
922
+ * logger.info('OCPP exchange', {
923
+ * chargePointId: 'CP-101',
924
+ * action: 'BootNotification',
925
+ * messageType: 'CALL',
926
+ * direction: 'IN',
927
+ * latencyMs: 34,
928
+ * status: 'Accepted',
929
+ * });
930
+ * // → ⚡ CP-101 → BootNotification [IN] CALL
931
+ * // → ✔ Accepted (34ms)
932
+ * ```
933
+ */
934
+
935
+ interface PrettyTransportOptions {
936
+ /** Per-transport level filter */
937
+ level?: LogLevelName;
938
+ /** Show timestamps (default: true) */
939
+ timestamps?: boolean;
940
+ /** Use colors in output (default: true) */
941
+ colors?: boolean;
942
+ }
943
+ /**
944
+ * Create a pretty-print transport for dev/debug use.
945
+ * Includes OCPP exchange log prettification.
946
+ */
947
+ declare function prettyTransport(options?: PrettyTransportOptions): Transport;
948
+
949
+ /**
950
+ * @module voltlog-io
951
+ * @description Redis Streams transformer — publishes log entries to a Redis Stream.
952
+ * @server-only
953
+ * Designed for standard Redis clients (like `ioredis`) which use TCP sockets (unavailable in browsers).
954
+ * For HTTP-based Redis (e.g. Upstash), use a custom transformer or `webhookTransport`.
955
+ *
956
+ * Users can then subscribe (XREAD/XREADGROUP) for real-time dashboards, monitoring, etc.
957
+ *
958
+ * Requires `ioredis` — user brings their own client instance (no hard dep).
959
+ *
960
+ * @example Basic
961
+ * ```ts
962
+ * import Redis from 'ioredis';
963
+ * import { createLogger, redisTransport } from 'voltlog-io';
964
+ *
965
+ * const redis = new Redis();
966
+ * const logger = createLogger({
967
+ * transports: [
968
+ * redisTransport({ client: redis, streamKey: 'logs:ocpp' }),
969
+ * ],
970
+ * });
971
+ *
972
+ * logger.info('CP connected', { chargePointId: 'CP-101' });
973
+ * // → XADD logs:ocpp * level INFO message "CP connected" ...
974
+ * ```
975
+ *
976
+ * @example With TTL and max stream length
977
+ * ```ts
978
+ * redisTransport({
979
+ * client: redis,
980
+ * streamKey: 'logs:ocpp',
981
+ * maxLen: 10_000, // keep last 10k entries (approximate trim)
982
+ * })
983
+ * ```
984
+ *
985
+ * @example Subscribing (consumer side)
986
+ * ```ts
987
+ * // In your dashboard / monitoring service:
988
+ * const redis = new Redis();
989
+ *
990
+ * // Read new entries from the stream
991
+ * const entries = await redis.xread('BLOCK', 0, 'STREAMS', 'logs:ocpp', '$');
992
+ *
993
+ * // Or use consumer groups for at-least-once delivery:
994
+ * await redis.xgroup('CREATE', 'logs:ocpp', 'dashboard', '$', 'MKSTREAM');
995
+ * const entries = await redis.xreadgroup(
996
+ * 'GROUP', 'dashboard', 'worker-1',
997
+ * 'BLOCK', 0, 'STREAMS', 'logs:ocpp', '>'
998
+ * );
999
+ * ```
1000
+ */
1001
+
1002
+ /**
1003
+ * Minimal interface for the Redis client methods we need.
1004
+ * Compatible with `ioredis` — user provides their own instance.
1005
+ */
1006
+ interface RedisClient {
1007
+ xadd(...args: (string | number)[]): Promise<string | null>;
1008
+ quit?(): Promise<void>;
1009
+ }
1010
+ interface RedisTransportOptions {
1011
+ /** Redis client instance (e.g. `new Redis()` from ioredis) */
1012
+ client: RedisClient;
1013
+ /** Redis Stream key to publish to (default: 'logs') */
1014
+ streamKey?: string;
1015
+ /**
1016
+ * Max approximate stream length — older entries are trimmed.
1017
+ * Uses MAXLEN ~ (approximate) to keep the stream bounded.
1018
+ * Default: no limit.
1019
+ */
1020
+ maxLen?: number;
1021
+ /** Per-transport level filter */
1022
+ level?: LogLevelName;
1023
+ /**
1024
+ * Custom field mapper — convert LogEntry to flat key-value pairs for Redis.
1025
+ * Default: serializes the entire entry as JSON under a single 'data' field.
1026
+ */
1027
+ fieldMapper?: (entry: LogEntry) => Record<string, string>;
1028
+ }
1029
+ /**
1030
+ * Create a Redis Streams transport.
1031
+ *
1032
+ * Publishes each log entry via XADD to a Redis Stream.
1033
+ * Fire-and-forget — errors are silently swallowed to avoid blocking.
1034
+ */
1035
+ declare function redisTransport(options: RedisTransportOptions): Transport;
1036
+
1037
+ /**
1038
+ * @module voltlog-io
1039
+ * @description Sentry transformer — pushes errors to Sentry.
1040
+ * @universal Works in both Server and Browser (depends on provided Sentry instance).
1041
+ */
1042
+
1043
+ /**
1044
+ * Minimal Sentry client interface to avoid hard dependency on @sentry/* packages.
1045
+ * Users pass their Sentry instance (e.g. `import * as Sentry from '@sentry/node'`).
1046
+ */
1047
+ interface SentryInstance {
1048
+ captureException(exception: unknown, hint?: unknown): string;
1049
+ captureMessage(message: string, level?: unknown): string;
1050
+ addBreadcrumb(breadcrumb: unknown): void;
1051
+ Severity?: unknown;
1052
+ }
1053
+ interface SentryTransportOptions {
1054
+ /** Configured Sentry instance/hub */
1055
+ sentry: SentryInstance;
1056
+ /** Minimum level to trigger captureException (default: ERROR) */
1057
+ errorLevel?: LogLevelName;
1058
+ /** Minimum level to send breadcrumbs (default: INFO) */
1059
+ breadcrumbLevel?: LogLevelName;
1060
+ }
1061
+ /**
1062
+ * Integrates with an existing Sentry instance.
1063
+ * - Logs >= errorLevel -> sent as Exceptions
1064
+ * - Logs >= breadcrumbLevel -> sent as Breadcrumbs
1065
+ */
1066
+ declare function sentryTransport(options: SentryTransportOptions): Transport;
1067
+
1068
+ /**
1069
+ * @module voltlog-io
1070
+ * @description Slack transformer — sends rich notifications to Slack via Incoming Webhook.
1071
+ * @universal Works in all environments (uses `fetch`).
1072
+ *
1073
+ * > **Security Note**: Using this in the browser will expose your Webhook URL.
1074
+ * > Recommended for server-side use only.
1075
+ * Best used with a filter (e.g. ERROR only) or alert middleware.
1076
+ */
1077
+
1078
+ interface SlackTransportOptions {
1079
+ /** Slack Incoming Webhook URL */
1080
+ webhookUrl: string;
1081
+ /** Filter level (default: ERROR) */
1082
+ level?: LogLevelName;
1083
+ /** Custom username (overrides webhook default) */
1084
+ username?: string;
1085
+ /** Custom icon emoji (overrides webhook default) */
1086
+ iconEmoji?: string;
1087
+ }
1088
+ /**
1089
+ * Sends logs to Slack with formatting.
1090
+ * Best suited for ERROR/FATAL logs or specific alerts.
1091
+ */
1092
+ declare function slackTransport(options: SlackTransportOptions): Transport;
1093
+
1094
+ /**
1095
+ * @module voltlog-io
1096
+ * @description Webhook transformer — sends logs via HTTP POST.
1097
+ * @universal Works in all environments (uses `fetch`).
1098
+ * Supports batching for performance.
1099
+ *
1100
+ * @example
1101
+ * ```ts
1102
+ * import { createLogger, webhookTransport } from 'voltlog-io';
1103
+ *
1104
+ * const logger = createLogger({
1105
+ * transports: [
1106
+ * webhookTransport({
1107
+ * url: 'https://my-api.com/logs',
1108
+ * headers: { Authorization: 'Bearer token123' },
1109
+ * batchSize: 50,
1110
+ * flushIntervalMs: 5000,
1111
+ * }),
1112
+ * ],
1113
+ * });
1114
+ * ```
1115
+ */
1116
+
1117
+ interface WebhookTransportOptions {
1118
+ /** Target URL to POST log entries to */
1119
+ url: string;
1120
+ /** HTTP method (default: POST) */
1121
+ method?: string;
1122
+ /** Additional HTTP headers */
1123
+ headers?: Record<string, string>;
1124
+ /** Number of entries to batch before sending (default: 1 = no batching) */
1125
+ batchSize?: number;
1126
+ /** Max time in ms to wait before flushing a partial batch (default: 5000) */
1127
+ flushIntervalMs?: number;
1128
+ /** Per-transport level filter */
1129
+ level?: LogLevelName;
1130
+ /** Custom body serializer. Default: JSON.stringify({ entries: [...] }) */
1131
+ serializer?: (entries: LogEntry[]) => string;
1132
+ /** Retry failed requests (default: false) */
1133
+ retry?: boolean;
1134
+ /** Max retries (default: 3) */
1135
+ maxRetries?: number;
1136
+ }
1137
+ /**
1138
+ * Create a webhook transport that POSTs log entries to an HTTP endpoint.
1139
+ */
1140
+ declare function webhookTransport(options: WebhookTransportOptions): Transport;
1141
+
1142
+ export { type AiEnrichmentOptions, type AlertRule, type BatchTransportOptions, type BrowserJsonStreamTransportOptions, type ConsoleTransportOptions, type CorrelationIdOptions, type DatadogTransportOptions, type DeduplicationOptions, type DiscordTransportOptions, type FileTransportOptions, type JsonStreamTransportOptions, type LevelOverrideOptions, type LogEntry, type LogError, LogLevel, type LogLevelName, LogLevelNameMap, type LogLevelValue, LogLevelValueMap, type LogMiddleware, type Logger, type LoggerOptions, type LokiTransportOptions, type OcppExchangeMeta, type OcppMiddlewareOptions, type PrettyTransportOptions, type RedactionOptions, type RedisClient, type RedisTransportOptions, type SamplingOptions, type SentryInstance, type SentryTransportOptions, type SlackTransportOptions, type Transport, type UserAgentOptions, type WebhookTransportOptions, aiEnrichmentMiddleware, alertMiddleware, batchTransport, browserJsonStreamTransport, consoleTransport, correlationIdMiddleware, createLogger, createMiddleware, createOpenAiErrorAnalyzer, createTransport, datadogTransport, deduplicationMiddleware, discordTransport, fileTransport, heapUsageMiddleware, ipMiddleware, jsonStreamTransport, levelOverrideMiddleware, lokiTransport, ocppMiddleware, prettyTransport, redactionMiddleware, redisTransport, resolveLevel, samplingMiddleware, sentryTransport, shouldIncludeStack, shouldLog, slackTransport, userAgentMiddleware, webhookTransport };