voltlog-io 1.0.2 → 1.0.4

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,1746 @@
1
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
+ }) : x)(function(x) {
4
+ if (typeof require !== "undefined") return require.apply(this, arguments);
5
+ throw Error('Dynamic require of "' + x + '" is not supported');
6
+ });
7
+
8
+ // node_modules/tsup/assets/esm_shims.js
9
+ import path from "path";
10
+ import { fileURLToPath } from "url";
11
+ var getFilename = () => fileURLToPath(import.meta.url);
12
+ var __filename = /* @__PURE__ */ getFilename();
13
+
14
+ // src/core/types.ts
15
+ var LogLevel = {
16
+ TRACE: 10,
17
+ DEBUG: 20,
18
+ INFO: 30,
19
+ WARN: 40,
20
+ ERROR: 50,
21
+ FATAL: 60,
22
+ SILENT: Infinity
23
+ };
24
+ var LogLevelNameMap = Object.fromEntries(
25
+ Object.entries(LogLevel).map(([k, v]) => [k.toLowerCase(), v])
26
+ );
27
+ var LogLevelValueMap = Object.fromEntries(
28
+ Object.entries(LogLevel).filter(([, v]) => Number.isFinite(v)).map(([k, v]) => [v, k])
29
+ );
30
+
31
+ // src/core/levels.ts
32
+ function resolveLevel(level) {
33
+ const n = LogLevelNameMap[level.toLowerCase()];
34
+ return n !== void 0 ? n : LogLevel.INFO;
35
+ }
36
+ function shouldLog(entryLevel, filterLevel) {
37
+ return entryLevel >= filterLevel;
38
+ }
39
+ function shouldIncludeStack(entryLevel, includeStack) {
40
+ if (typeof includeStack === "boolean") return includeStack;
41
+ return entryLevel >= resolveLevel(includeStack);
42
+ }
43
+
44
+ // src/core/pipeline.ts
45
+ function composeMiddleware(middleware, final) {
46
+ if (middleware.length === 0) return final;
47
+ return (entry) => {
48
+ let index = 0;
49
+ const next = (e) => {
50
+ if (index < middleware.length) {
51
+ const mw = middleware[index++];
52
+ mw(e, next);
53
+ } else {
54
+ final(e);
55
+ }
56
+ };
57
+ next(entry);
58
+ };
59
+ }
60
+ function fanOutToTransports(entry, transports, loggerLevel) {
61
+ for (const t of transports) {
62
+ const tLevel = t.level ? resolveLevel(t.level) : loggerLevel;
63
+ if (!shouldLog(entry.level, tLevel)) continue;
64
+ try {
65
+ const result = t.write(entry);
66
+ if (result && typeof result.catch === "function") {
67
+ result.catch(() => {
68
+ });
69
+ }
70
+ } catch {
71
+ }
72
+ }
73
+ }
74
+
75
+ // src/core/logger.ts
76
+ var randomUUID = typeof globalThis.crypto?.randomUUID === "function" ? () => globalThis.crypto.randomUUID() : () => "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
77
+ const r = Math.random() * 16 | 0;
78
+ return (c === "x" ? r : r & 3 | 8).toString(16);
79
+ });
80
+ var LoggerImpl = class {
81
+ _level;
82
+ _transports;
83
+ _middlewareList;
84
+ _pipeline;
85
+ _context;
86
+ _includeStack;
87
+ _timestampFn;
88
+ _idFn;
89
+ constructor(options = {}) {
90
+ this._level = resolveLevel(options.level ?? "INFO");
91
+ this._transports = [...options.transports ?? []];
92
+ this._middlewareList = [...options.middleware ?? []];
93
+ this._context = options.context ? { ...options.context } : {};
94
+ this._includeStack = options.includeStack ?? "ERROR";
95
+ this._timestampFn = options.timestamp ?? Date.now;
96
+ this._idFn = options.idGenerator !== void 0 ? options.idGenerator : randomUUID;
97
+ this._pipeline = this._buildPipeline();
98
+ }
99
+ // ─── Log Methods ────────────────────────────────────────────
100
+ trace(message, meta) {
101
+ if (10 < this._level) return;
102
+ this._log(10, "TRACE", message, meta);
103
+ }
104
+ debug(message, meta) {
105
+ if (20 < this._level) return;
106
+ this._log(20, "DEBUG", message, meta);
107
+ }
108
+ info(message, meta) {
109
+ if (30 < this._level) return;
110
+ this._log(30, "INFO", message, meta);
111
+ }
112
+ warn(message, meta) {
113
+ if (40 < this._level) return;
114
+ this._log(40, "WARN", message, meta);
115
+ }
116
+ error(message, metaOrError, error) {
117
+ if (50 < this._level) return;
118
+ if (metaOrError instanceof Error) {
119
+ this._log(50, "ERROR", message, void 0, metaOrError);
120
+ } else {
121
+ this._log(50, "ERROR", message, metaOrError, error);
122
+ }
123
+ }
124
+ fatal(message, metaOrError, error) {
125
+ if (metaOrError instanceof Error) {
126
+ this._log(60, "FATAL", message, void 0, metaOrError);
127
+ } else {
128
+ this._log(60, "FATAL", message, metaOrError, error);
129
+ }
130
+ }
131
+ // ─── Child Logger ───────────────────────────────────────────
132
+ child(context) {
133
+ return new ChildLoggerImpl(this, { ...this._context, ...context });
134
+ }
135
+ // ─── Dynamic Configuration ─────────────────────────────────
136
+ addTransport(transport) {
137
+ this._transports.push(transport);
138
+ }
139
+ removeTransport(name) {
140
+ this._transports = this._transports.filter((t) => t.name !== name);
141
+ }
142
+ addMiddleware(middleware) {
143
+ this._middlewareList.push(middleware);
144
+ this._pipeline = this._buildPipeline();
145
+ }
146
+ removeMiddleware(middleware) {
147
+ this._middlewareList = this._middlewareList.filter((m) => m !== middleware);
148
+ this._pipeline = this._buildPipeline();
149
+ }
150
+ // ─── Level Control ─────────────────────────────────────────
151
+ setLevel(level) {
152
+ this._level = resolveLevel(level);
153
+ }
154
+ getLevel() {
155
+ return LogLevelValueMap[this._level] ?? "INFO";
156
+ }
157
+ isLevelEnabled(level) {
158
+ return resolveLevel(level) >= this._level;
159
+ }
160
+ // ─── Timer ─────────────────────────────────────────────────
161
+ startTimer(level) {
162
+ const start = performance.now();
163
+ const logLevel = level ?? "INFO";
164
+ return {
165
+ done: (message, meta) => {
166
+ const durationMs = Math.round(performance.now() - start);
167
+ const merged = { ...meta, durationMs };
168
+ const methodKey = logLevel.toLowerCase();
169
+ this[methodKey](message, merged);
170
+ },
171
+ elapsed: () => Math.round(performance.now() - start)
172
+ };
173
+ }
174
+ // ─── Lifecycle ──────────────────────────────────────────────
175
+ async flush() {
176
+ await Promise.all(this._transports.map((t) => t.flush?.()).filter(Boolean));
177
+ }
178
+ async close() {
179
+ await this.flush();
180
+ await Promise.all(this._transports.map((t) => t.close?.()).filter(Boolean));
181
+ }
182
+ // ─── Internal ───────────────────────────────────────────────
183
+ /** @internal */
184
+ _log(level, levelName, message, meta, error) {
185
+ this._logWithContext(level, levelName, message, this._context, meta, error);
186
+ }
187
+ /** @internal — used by child loggers to inject bound context */
188
+ _logWithContext(level, levelName, message, context, meta, error) {
189
+ if (!shouldLog(level, this._level)) return;
190
+ const entry = {
191
+ id: this._idFn ? this._idFn() : "",
192
+ level,
193
+ levelName,
194
+ message,
195
+ timestamp: this._timestampFn(),
196
+ meta: meta ?? {},
197
+ context: Object.keys(context).length > 0 ? context : void 0
198
+ };
199
+ if (error) {
200
+ entry.error = serializeError(
201
+ error,
202
+ shouldIncludeStack(level, this._includeStack)
203
+ );
204
+ }
205
+ this._pipeline(entry);
206
+ }
207
+ _buildPipeline() {
208
+ return composeMiddleware(this._middlewareList, (entry) => {
209
+ fanOutToTransports(entry, this._transports, this._level);
210
+ });
211
+ }
212
+ };
213
+ function serializeError(error, includeStack, depth = 0) {
214
+ const logError = {
215
+ message: error.message,
216
+ name: error.name,
217
+ code: error.code
218
+ };
219
+ if (includeStack) {
220
+ logError.stack = error.stack;
221
+ }
222
+ if (error.cause instanceof Error && depth < 5) {
223
+ logError.cause = serializeError(error.cause, includeStack, depth + 1);
224
+ }
225
+ return logError;
226
+ }
227
+ var ChildLoggerImpl = class _ChildLoggerImpl {
228
+ constructor(_parent, _context) {
229
+ this._parent = _parent;
230
+ this._context = _context;
231
+ }
232
+ trace(message, meta) {
233
+ this._parent._logWithContext(10, "TRACE", message, this._context, meta);
234
+ }
235
+ debug(message, meta) {
236
+ this._parent._logWithContext(20, "DEBUG", message, this._context, meta);
237
+ }
238
+ info(message, meta) {
239
+ this._parent._logWithContext(30, "INFO", message, this._context, meta);
240
+ }
241
+ warn(message, meta) {
242
+ this._parent._logWithContext(40, "WARN", message, this._context, meta);
243
+ }
244
+ error(message, metaOrError, error) {
245
+ if (metaOrError instanceof Error) {
246
+ this._parent._logWithContext(
247
+ 50,
248
+ "ERROR",
249
+ message,
250
+ this._context,
251
+ void 0,
252
+ metaOrError
253
+ );
254
+ } else {
255
+ this._parent._logWithContext(
256
+ 50,
257
+ "ERROR",
258
+ message,
259
+ this._context,
260
+ metaOrError,
261
+ error
262
+ );
263
+ }
264
+ }
265
+ fatal(message, metaOrError, error) {
266
+ if (metaOrError instanceof Error) {
267
+ this._parent._logWithContext(
268
+ 60,
269
+ "FATAL",
270
+ message,
271
+ this._context,
272
+ void 0,
273
+ metaOrError
274
+ );
275
+ } else {
276
+ this._parent._logWithContext(
277
+ 60,
278
+ "FATAL",
279
+ message,
280
+ this._context,
281
+ metaOrError,
282
+ error
283
+ );
284
+ }
285
+ }
286
+ child(context) {
287
+ return new _ChildLoggerImpl(this._parent, {
288
+ ...this._context,
289
+ ...context
290
+ });
291
+ }
292
+ addTransport(transport) {
293
+ this._parent.addTransport(transport);
294
+ }
295
+ removeTransport(name) {
296
+ this._parent.removeTransport(name);
297
+ }
298
+ addMiddleware(middleware) {
299
+ this._parent.addMiddleware(middleware);
300
+ }
301
+ removeMiddleware(middleware) {
302
+ this._parent.removeMiddleware(middleware);
303
+ }
304
+ setLevel(level) {
305
+ this._parent.setLevel(level);
306
+ }
307
+ getLevel() {
308
+ return this._parent.getLevel();
309
+ }
310
+ isLevelEnabled(level) {
311
+ return this._parent.isLevelEnabled(level);
312
+ }
313
+ startTimer(level) {
314
+ return this._parent.startTimer(level);
315
+ }
316
+ flush() {
317
+ return this._parent.flush();
318
+ }
319
+ close() {
320
+ return this._parent.close();
321
+ }
322
+ };
323
+ function createLogger(options) {
324
+ return new LoggerImpl(options);
325
+ }
326
+
327
+ // src/middleware/ai-enrichment.ts
328
+ function aiEnrichmentMiddleware(options) {
329
+ const minLevel = resolveLevel(options.level ?? "ERROR");
330
+ const timeoutMs = options.timeout ?? 2e3;
331
+ const swallow = options.swallowErrors ?? true;
332
+ const fieldName = options.targetField ?? "ai_analysis";
333
+ return async (entry, next) => {
334
+ if (entry.level < minLevel) {
335
+ next(entry);
336
+ return;
337
+ }
338
+ try {
339
+ const analysisPromise = options.analyzer(entry);
340
+ const timeoutPromise = new Promise(
341
+ (_, reject) => setTimeout(() => reject(new Error("AI Analysis Timeout")), timeoutMs)
342
+ );
343
+ const result = await Promise.race([analysisPromise, timeoutPromise]);
344
+ if (result) {
345
+ entry.meta = {
346
+ ...entry.meta,
347
+ [fieldName]: result
348
+ };
349
+ }
350
+ } catch (err) {
351
+ if (!swallow) {
352
+ throw err;
353
+ }
354
+ }
355
+ next(entry);
356
+ };
357
+ }
358
+ function createOpenAiErrorAnalyzer(apiKey, model = "gpt-3.5-turbo", systemPrompt = "You are a log analyzer. Explain this error briefly and suggest a fix in 1 sentence.") {
359
+ return async (entry) => {
360
+ try {
361
+ const response = await fetch(
362
+ "https://api.openai.com/v1/chat/completions",
363
+ {
364
+ method: "POST",
365
+ headers: {
366
+ "Content-Type": "application/json",
367
+ Authorization: `Bearer ${apiKey}`
368
+ },
369
+ body: JSON.stringify({
370
+ model,
371
+ messages: [
372
+ { role: "system", content: systemPrompt },
373
+ {
374
+ role: "user",
375
+ content: `Error Message: ${entry.message}
376
+ Context: ${JSON.stringify(entry.meta)}`
377
+ }
378
+ ],
379
+ max_tokens: 150
380
+ })
381
+ }
382
+ );
383
+ if (!response.ok) return null;
384
+ const data = await response.json();
385
+ return data.choices?.[0]?.message?.content ?? null;
386
+ } catch {
387
+ return null;
388
+ }
389
+ };
390
+ }
391
+
392
+ // src/middleware/alert.ts
393
+ function alertMiddleware(rules) {
394
+ const states = /* @__PURE__ */ new Map();
395
+ for (const rule of rules) {
396
+ states.set(rule.name, { entries: [], lastFired: -Infinity });
397
+ }
398
+ return (entry, next) => {
399
+ const now = entry.timestamp;
400
+ for (const rule of rules) {
401
+ if (!rule.when(entry)) continue;
402
+ const state = states.get(rule.name);
403
+ const windowMs = rule.windowMs ?? Infinity;
404
+ const threshold = rule.threshold ?? 1;
405
+ const cooldownMs = rule.cooldownMs ?? 0;
406
+ if (Number.isFinite(windowMs)) {
407
+ state.entries = state.entries.filter(
408
+ (e) => now - e.timestamp < windowMs
409
+ );
410
+ }
411
+ state.entries.push(entry);
412
+ if (state.entries.length >= threshold && now - state.lastFired >= cooldownMs) {
413
+ const alertEntries = [...state.entries];
414
+ state.entries = [];
415
+ state.lastFired = now;
416
+ try {
417
+ const result = rule.onAlert(alertEntries);
418
+ if (result && typeof result.catch === "function") {
419
+ result.catch(() => {
420
+ });
421
+ }
422
+ } catch {
423
+ }
424
+ }
425
+ }
426
+ next(entry);
427
+ };
428
+ }
429
+
430
+ // src/middleware/create-middleware.ts
431
+ function createMiddleware(fn) {
432
+ return fn;
433
+ }
434
+
435
+ // src/middleware/deduplication.ts
436
+ function deduplicationMiddleware(options = {}) {
437
+ const windowMs = options.windowMs ?? 1e3;
438
+ const keyFn = options.keyFn ?? ((e) => `${e.level}:${e.message}:${e.error?.message ?? ""}`);
439
+ const buffer = /* @__PURE__ */ new Map();
440
+ return (entry, next) => {
441
+ const key = keyFn(entry);
442
+ if (buffer.has(key)) {
443
+ const state = buffer.get(key);
444
+ state.count++;
445
+ return;
446
+ }
447
+ const timer = setTimeout(() => {
448
+ const state = buffer.get(key);
449
+ if (state) {
450
+ buffer.delete(key);
451
+ if (state.count > 1) {
452
+ state.entry.meta = {
453
+ ...state.entry.meta,
454
+ duplicateCount: state.count
455
+ };
456
+ }
457
+ next(state.entry);
458
+ }
459
+ }, windowMs);
460
+ buffer.set(key, {
461
+ entry,
462
+ count: 1,
463
+ timer
464
+ });
465
+ };
466
+ }
467
+
468
+ // src/middleware/heap-usage.ts
469
+ function heapUsageMiddleware(options = {}) {
470
+ const fieldName = options.fieldName ?? "memory";
471
+ return (entry, next) => {
472
+ if (typeof process !== "undefined" && process.memoryUsage) {
473
+ const memory = process.memoryUsage();
474
+ entry.meta = {
475
+ ...entry.meta,
476
+ [fieldName]: {
477
+ rss: memory.rss,
478
+ heapTotal: memory.heapTotal,
479
+ heapUsed: memory.heapUsed
480
+ }
481
+ };
482
+ }
483
+ next(entry);
484
+ };
485
+ }
486
+
487
+ // src/middleware/http.ts
488
+ var nodeHttpMappers = {
489
+ req: {
490
+ getMethod: (req) => req.method || "UNKNOWN",
491
+ getUrl: (req) => req.originalUrl || req.url || "/",
492
+ getIp: (req) => req.ip || req.socket?.remoteAddress || req.headers?.["x-forwarded-for"] || void 0,
493
+ getUserAgent: (req) => req.headers?.["user-agent"] || void 0,
494
+ getHeader: (req, name) => req.headers?.[name] || void 0
495
+ },
496
+ res: {
497
+ getStatusCode: (res) => res.statusCode || 200,
498
+ onFinish: (res, callback) => {
499
+ if (typeof res.on === "function") {
500
+ res.on("finish", callback);
501
+ res.on("close", callback);
502
+ } else {
503
+ callback();
504
+ }
505
+ }
506
+ }
507
+ };
508
+ function createHttpLogger(logger, options) {
509
+ const {
510
+ reqMapper,
511
+ resMapper,
512
+ level = "INFO",
513
+ skip,
514
+ extractContext
515
+ } = options;
516
+ return (req, res) => {
517
+ if (skip?.(req)) {
518
+ return;
519
+ }
520
+ const startTime = performance.now();
521
+ let finished = false;
522
+ resMapper.onFinish(res, () => {
523
+ if (finished) return;
524
+ finished = true;
525
+ const durationMs = Math.round(performance.now() - startTime);
526
+ const statusCode = resMapper.getStatusCode(res);
527
+ const method = reqMapper.getMethod(req);
528
+ const url = reqMapper.getUrl(req);
529
+ const meta = {
530
+ method,
531
+ url,
532
+ statusCode,
533
+ durationMs,
534
+ ip: reqMapper.getIp ? reqMapper.getIp(req) : void 0,
535
+ userAgent: reqMapper.getUserAgent ? reqMapper.getUserAgent(req) : void 0
536
+ };
537
+ if (extractContext) {
538
+ Object.assign(meta, extractContext(req, res));
539
+ }
540
+ let finalLevel = level;
541
+ if (statusCode >= 500) finalLevel = "ERROR";
542
+ else if (statusCode >= 400 && level === "INFO") finalLevel = "WARN";
543
+ const methodKey = finalLevel.toLowerCase();
544
+ logger[methodKey](
545
+ `${method} ${url} - ${statusCode} (${durationMs}ms)`,
546
+ meta
547
+ );
548
+ });
549
+ };
550
+ }
551
+
552
+ // src/middleware/ip.ts
553
+ function ipMiddleware(options = {}) {
554
+ const targetField = options.fieldName ?? "ip";
555
+ const keysToCheck = options.headerKeys ?? [
556
+ "x-forwarded-for",
557
+ "x-real-ip",
558
+ "req.ip",
559
+ "ip",
560
+ "x-client-ip"
561
+ ];
562
+ return (entry, next) => {
563
+ const meta = entry.meta;
564
+ const headers = meta.headers || {};
565
+ const req = meta.req || {};
566
+ let foundIp;
567
+ for (const key of keysToCheck) {
568
+ if (typeof meta[key] === "string") {
569
+ foundIp = meta[key];
570
+ break;
571
+ }
572
+ if (typeof headers[key] === "string") {
573
+ foundIp = headers[key];
574
+ break;
575
+ }
576
+ if (typeof req[key] === "string") {
577
+ foundIp = req[key];
578
+ break;
579
+ }
580
+ if (key === "req.ip" && typeof req.ip === "string") {
581
+ foundIp = req.ip;
582
+ break;
583
+ }
584
+ }
585
+ if (foundIp) {
586
+ const firstIp = typeof foundIp === "string" ? foundIp.split(",")[0].trim() : String(foundIp);
587
+ entry.meta = {
588
+ ...entry.meta,
589
+ [targetField]: firstIp
590
+ };
591
+ }
592
+ next(entry);
593
+ };
594
+ }
595
+
596
+ // src/middleware/level-override.ts
597
+ function levelOverrideMiddleware(options = {}) {
598
+ const key = options.key ?? "x-log-level";
599
+ const cleanup = options.cleanup ?? true;
600
+ return (entry, next) => {
601
+ const meta = entry.meta;
602
+ const context = entry.context;
603
+ const levelName = meta[key] || context?.[key] || meta.headers?.[key];
604
+ if (levelName && typeof levelName === "string") {
605
+ const upperName = levelName.toUpperCase();
606
+ if (LogLevel[upperName]) {
607
+ entry.level = LogLevel[upperName];
608
+ entry.levelName = upperName;
609
+ if (cleanup) {
610
+ delete meta[key];
611
+ if (meta.headers) {
612
+ delete meta.headers[key];
613
+ }
614
+ }
615
+ }
616
+ }
617
+ next(entry);
618
+ };
619
+ }
620
+
621
+ // src/middleware/ocpp.ts
622
+ function ocppMiddleware(options = {}) {
623
+ const autoPayloadSize = options.autoPayloadSize ?? true;
624
+ const propagateCorrelationId = options.propagateCorrelationId ?? true;
625
+ return (entry, next) => {
626
+ const enriched = { ...entry, meta: { ...entry.meta } };
627
+ if (autoPayloadSize && enriched.meta.payloadSize === void 0 && enriched.meta.action) {
628
+ try {
629
+ enriched.meta.payloadSize = JSON.stringify(enriched.meta).length;
630
+ } catch {
631
+ }
632
+ }
633
+ if (propagateCorrelationId && enriched.meta.correlationId && !enriched.correlationId) {
634
+ enriched.correlationId = enriched.meta.correlationId;
635
+ }
636
+ next(enriched);
637
+ };
638
+ }
639
+
640
+ // src/middleware/otel-trace.ts
641
+ function otelTraceMiddleware(options = {}) {
642
+ let traceApi = options.traceApi ?? null;
643
+ let resolved = !!traceApi;
644
+ if (!resolved) {
645
+ try {
646
+ const { createRequire } = __require("module");
647
+ const dynamicRequire = createRequire(__filename);
648
+ const api = dynamicRequire("@opentelemetry/api");
649
+ traceApi = api;
650
+ resolved = true;
651
+ } catch {
652
+ }
653
+ }
654
+ return (entry, next) => {
655
+ if (resolved && traceApi?.trace) {
656
+ try {
657
+ const activeSpan = traceApi.trace.getActiveSpan?.();
658
+ if (activeSpan) {
659
+ const spanContext = activeSpan.spanContext?.();
660
+ if (spanContext) {
661
+ const meta = entry.meta;
662
+ meta.traceId = spanContext.traceId;
663
+ meta.spanId = spanContext.spanId;
664
+ meta.traceFlags = spanContext.traceFlags;
665
+ if (!entry.correlationId) {
666
+ entry.correlationId = spanContext.traceId;
667
+ }
668
+ }
669
+ }
670
+ } catch {
671
+ }
672
+ }
673
+ next(entry);
674
+ };
675
+ }
676
+
677
+ // src/middleware/redaction.ts
678
+ var DEFAULT_REDACT_VALUE = "[REDACTED]";
679
+ function redactionMiddleware(options) {
680
+ const paths = new Set(options.paths.map((p) => p.toLowerCase()));
681
+ const replacement = options.replacement ?? DEFAULT_REDACT_VALUE;
682
+ const deep = options.deep ?? true;
683
+ function redactObject(obj) {
684
+ const result = {};
685
+ for (const [key, value] of Object.entries(obj)) {
686
+ if (paths.has(key.toLowerCase())) {
687
+ result[key] = replacement;
688
+ } else if (deep && value !== null && typeof value === "object" && !Array.isArray(value)) {
689
+ result[key] = redactObject(value);
690
+ } else {
691
+ result[key] = value;
692
+ }
693
+ }
694
+ return result;
695
+ }
696
+ return (entry, next) => {
697
+ const redacted = { ...entry };
698
+ if (entry.meta && typeof entry.meta === "object") {
699
+ redacted.meta = redactObject(
700
+ entry.meta
701
+ );
702
+ }
703
+ if (entry.context && typeof entry.context === "object") {
704
+ redacted.context = redactObject(entry.context);
705
+ }
706
+ next(redacted);
707
+ };
708
+ }
709
+
710
+ // src/middleware/sampling.ts
711
+ function samplingMiddleware(options = {}) {
712
+ const keyFn = options.keyFn ?? ((entry) => entry.message);
713
+ const maxPerWindow = options.maxPerWindow ?? 100;
714
+ const windowMs = options.windowMs ?? 6e4;
715
+ const sampleRate = options.sampleRate ?? 1;
716
+ const priorityLevel = options.priorityLevel ?? 40;
717
+ const buckets = /* @__PURE__ */ new Map();
718
+ return (entry, next) => {
719
+ if (entry.level >= priorityLevel) {
720
+ return next(entry);
721
+ }
722
+ if (sampleRate < 1 && Math.random() > sampleRate) {
723
+ return;
724
+ }
725
+ const key = keyFn(entry);
726
+ const now = entry.timestamp;
727
+ let bucket = buckets.get(key);
728
+ if (!bucket || now - bucket.windowStart >= windowMs) {
729
+ bucket = { count: 0, windowStart: now };
730
+ buckets.set(key, bucket);
731
+ }
732
+ if (bucket.count < maxPerWindow) {
733
+ bucket.count++;
734
+ next(entry);
735
+ }
736
+ if (buckets.size > 2e3) {
737
+ const expireBefore = now - windowMs * 2;
738
+ for (const [k, b] of buckets) {
739
+ if (b.windowStart < expireBefore) {
740
+ buckets.delete(k);
741
+ }
742
+ }
743
+ }
744
+ };
745
+ }
746
+
747
+ // src/middleware/user-agent.ts
748
+ function userAgentMiddleware(options = {}) {
749
+ const sourceField = options.sourceField;
750
+ const targetField = options.targetField ?? "client";
751
+ return (entry, next) => {
752
+ const meta = entry.meta;
753
+ const context = entry.context;
754
+ const ua = (sourceField ? meta[sourceField] : void 0) || meta.userAgent || meta["user-agent"] || context?.userAgent || context?.["user-agent"];
755
+ if (ua) {
756
+ const info = parseUserAgent(ua);
757
+ entry.meta = {
758
+ ...entry.meta,
759
+ [targetField]: info
760
+ };
761
+ }
762
+ next(entry);
763
+ };
764
+ }
765
+ function parseUserAgent(ua) {
766
+ const browser = /(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i.exec(ua) || [];
767
+ let name = browser[1] ? browser[1].toLowerCase() : "unknown";
768
+ let version = browser[2] || "unknown";
769
+ if (/trident/i.test(name)) {
770
+ name = "ie";
771
+ } else if (name === "chrome") {
772
+ const edge = /edg(e)?\/(\d+)/i.exec(ua);
773
+ if (edge) {
774
+ name = "edge";
775
+ version = edge[2];
776
+ }
777
+ }
778
+ const osResult = /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.exec(
779
+ ua
780
+ );
781
+ const os = osResult ? osResult[0].toLowerCase() : "desktop";
782
+ return { browser: name, version, os };
783
+ }
784
+
785
+ // src/transports/batch.ts
786
+ function batchTransport(inner, options = {}) {
787
+ const batchSize = options.batchSize ?? 100;
788
+ const flushIntervalMs = options.flushIntervalMs ?? 5e3;
789
+ let buffer = [];
790
+ let flushTimer = null;
791
+ function scheduleFlush() {
792
+ if (flushTimer) return;
793
+ flushTimer = setTimeout(() => {
794
+ flushTimer = null;
795
+ doFlush();
796
+ }, flushIntervalMs);
797
+ }
798
+ function doFlush() {
799
+ if (buffer.length === 0) return;
800
+ const batch = buffer;
801
+ buffer = [];
802
+ for (const entry of batch) {
803
+ try {
804
+ const result = inner.write(entry);
805
+ if (result && typeof result.catch === "function") {
806
+ result.catch(() => {
807
+ });
808
+ }
809
+ } catch {
810
+ }
811
+ }
812
+ }
813
+ return {
814
+ name: `batch(${inner.name})`,
815
+ level: inner.level,
816
+ write(entry) {
817
+ buffer.push(entry);
818
+ if (buffer.length >= batchSize) {
819
+ doFlush();
820
+ } else {
821
+ scheduleFlush();
822
+ }
823
+ },
824
+ async flush() {
825
+ if (flushTimer) {
826
+ clearTimeout(flushTimer);
827
+ flushTimer = null;
828
+ }
829
+ doFlush();
830
+ await inner.flush?.();
831
+ },
832
+ async close() {
833
+ await this.flush?.();
834
+ await inner.close?.();
835
+ }
836
+ };
837
+ }
838
+
839
+ // src/transports/browser-json-stream.ts
840
+ function browserJsonStreamTransport(options) {
841
+ const stream = options.stream;
842
+ const writer = stream.getWriter();
843
+ const serialize = options.serializer ?? ((entry) => `${JSON.stringify(entry)}
844
+ `);
845
+ return {
846
+ name: "browser-stream",
847
+ level: options.level,
848
+ async write(entry) {
849
+ try {
850
+ const data = serialize(entry);
851
+ await writer.ready;
852
+ await writer.write(data);
853
+ } catch (err) {
854
+ console.error("[voltlog] Failed to write to browser stream", err);
855
+ }
856
+ },
857
+ async close() {
858
+ try {
859
+ await writer.close();
860
+ } catch (_err) {
861
+ }
862
+ }
863
+ };
864
+ }
865
+
866
+ // src/transports/console.ts
867
+ function consoleTransport(options = {}) {
868
+ const useConsoleLevels = options.useConsoleLevels ?? true;
869
+ const formatter = options.formatter ?? ((entry) => JSON.stringify(entry));
870
+ return {
871
+ name: "console",
872
+ level: options.level,
873
+ write(entry) {
874
+ const output = formatter(entry);
875
+ if (!useConsoleLevels) {
876
+ console.log(output);
877
+ return;
878
+ }
879
+ if (entry.level >= LogLevel.FATAL) {
880
+ console.error(output);
881
+ } else if (entry.level >= LogLevel.ERROR) {
882
+ console.error(output);
883
+ } else if (entry.level >= LogLevel.WARN) {
884
+ console.warn(output);
885
+ } else if (entry.level >= LogLevel.INFO) {
886
+ console.info(output);
887
+ } else if (entry.level >= LogLevel.DEBUG) {
888
+ console.debug(output);
889
+ } else {
890
+ console.log(output);
891
+ }
892
+ }
893
+ };
894
+ }
895
+
896
+ // src/transports/create-transport.ts
897
+ function createTransport(name, write, options = {}) {
898
+ return {
899
+ name,
900
+ write,
901
+ ...options
902
+ };
903
+ }
904
+
905
+ // src/transports/datadog.ts
906
+ function datadogTransport(options) {
907
+ const {
908
+ apiKey,
909
+ site = "datadoghq.com",
910
+ service,
911
+ ddSource = "nodejs",
912
+ hostname,
913
+ tags,
914
+ level
915
+ } = options;
916
+ const url = `https://http-intake.logs.${site}/api/v2/logs`;
917
+ return {
918
+ name: "datadog",
919
+ level,
920
+ async write(entry) {
921
+ const payload = {
922
+ ddsource: ddSource,
923
+ ddtags: tags,
924
+ hostname,
925
+ service,
926
+ message: entry.message,
927
+ status: entry.levelName.toLowerCase(),
928
+ // Datadog uses lowercase status
929
+ ...entry.meta,
930
+ timestamp: entry.timestamp
931
+ // Datadog auto-parses this
932
+ };
933
+ try {
934
+ await fetch(url, {
935
+ method: "POST",
936
+ headers: {
937
+ "Content-Type": "application/json",
938
+ "DD-API-KEY": apiKey
939
+ },
940
+ body: JSON.stringify(payload)
941
+ });
942
+ } catch (err) {
943
+ console.error("[voltlog] Datadog push failed", err);
944
+ }
945
+ }
946
+ };
947
+ }
948
+
949
+ // src/transports/discord.ts
950
+ function discordTransport(options) {
951
+ const { webhookUrl, username, avatarUrl, level = "ERROR" } = options;
952
+ return {
953
+ name: "discord",
954
+ level,
955
+ async write(entry) {
956
+ try {
957
+ await fetch(webhookUrl, {
958
+ method: "POST",
959
+ headers: { "Content-Type": "application/json" },
960
+ body: JSON.stringify(
961
+ formatDiscordPayload(entry, username, avatarUrl)
962
+ )
963
+ });
964
+ } catch (_err) {
965
+ }
966
+ }
967
+ };
968
+ }
969
+ function formatDiscordPayload(entry, username, avatar_url) {
970
+ const color = getLevelColor(entry.level);
971
+ return {
972
+ username: username || "VoltLog",
973
+ avatar_url,
974
+ embeds: [
975
+ {
976
+ title: `${entry.levelName} - ${entry.message}`,
977
+ color,
978
+ timestamp: new Date(entry.timestamp).toISOString(),
979
+ fields: [
980
+ {
981
+ name: "Meta",
982
+ value: `\`\`\`json
983
+ ${JSON.stringify(entry.meta, null, 2).slice(
984
+ 0,
985
+ 1e3
986
+ )}
987
+ \`\`\``
988
+ },
989
+ entry.error?.stack ? {
990
+ name: "Stack",
991
+ value: `\`\`\`js
992
+ ${entry.error.stack.slice(0, 1e3)}
993
+ \`\`\``
994
+ } : null
995
+ ].filter(Boolean)
996
+ }
997
+ ]
998
+ };
999
+ }
1000
+ function getLevelColor(level) {
1001
+ if (level >= 50) return 15158332;
1002
+ if (level >= 40) return 16776960;
1003
+ if (level >= 30) return 3447003;
1004
+ return 9807270;
1005
+ }
1006
+
1007
+ // src/transports/loki.ts
1008
+ function lokiTransport(options) {
1009
+ const { host, level } = options;
1010
+ const staticLabels = options.labels ?? { app: "voltlog" };
1011
+ const batchSize = options.batchSize ?? 10;
1012
+ const interval = options.interval ?? 5e3;
1013
+ const includeMetadata = options.includeMetadata !== false;
1014
+ const retryEnabled = options.retry ?? false;
1015
+ const maxRetries = options.maxRetries ?? 3;
1016
+ const url = `${host.replace(/\/$/, "")}/loki/api/v1/push`;
1017
+ const headers = {
1018
+ "Content-Type": "application/json"
1019
+ };
1020
+ if (options.basicAuthUser && options.basicAuthPassword) {
1021
+ const creds = btoa(`${options.basicAuthUser}:${options.basicAuthPassword}`);
1022
+ headers.Authorization = `Basic ${creds}`;
1023
+ }
1024
+ if (options.tenantId) {
1025
+ headers["X-Scope-OrgID"] = options.tenantId;
1026
+ }
1027
+ let buffer = [];
1028
+ let timer = null;
1029
+ function buildLogLine(entry) {
1030
+ const payload = {
1031
+ level: entry.levelName,
1032
+ message: entry.message,
1033
+ ...entry.meta
1034
+ };
1035
+ if (includeMetadata) {
1036
+ if (entry.correlationId) {
1037
+ payload.correlationId = entry.correlationId;
1038
+ }
1039
+ if (entry.context) {
1040
+ payload.context = entry.context;
1041
+ }
1042
+ if (entry.error) {
1043
+ payload.error = entry.error;
1044
+ }
1045
+ }
1046
+ return JSON.stringify(payload);
1047
+ }
1048
+ function buildStreams(batch) {
1049
+ if (!options.dynamicLabels) {
1050
+ return [
1051
+ {
1052
+ stream: staticLabels,
1053
+ values: batch.map((e) => [
1054
+ String(e.timestamp * 1e6),
1055
+ // Loki wants nanoseconds
1056
+ buildLogLine(e)
1057
+ ])
1058
+ }
1059
+ ];
1060
+ }
1061
+ const grouped = /* @__PURE__ */ new Map();
1062
+ for (const entry of batch) {
1063
+ const dynamic = options.dynamicLabels(entry);
1064
+ const merged = { ...staticLabels };
1065
+ for (const [k, v] of Object.entries(dynamic)) {
1066
+ if (v !== void 0) merged[k] = v;
1067
+ }
1068
+ const key = JSON.stringify(merged);
1069
+ let group = grouped.get(key);
1070
+ if (!group) {
1071
+ group = { labels: merged, values: [] };
1072
+ grouped.set(key, group);
1073
+ }
1074
+ group.values.push([
1075
+ String(entry.timestamp * 1e6),
1076
+ buildLogLine(entry)
1077
+ ]);
1078
+ }
1079
+ return Array.from(grouped.values()).map((g) => ({
1080
+ stream: g.labels,
1081
+ values: g.values
1082
+ }));
1083
+ }
1084
+ async function pushWithRetry(batch) {
1085
+ const body = JSON.stringify({ streams: buildStreams(batch) });
1086
+ let lastError;
1087
+ const attempts = retryEnabled ? maxRetries : 1;
1088
+ for (let attempt = 0; attempt < attempts; attempt++) {
1089
+ try {
1090
+ const response = await fetch(url, { method: "POST", headers, body });
1091
+ if (response.ok) return;
1092
+ if (response.status >= 400 && response.status < 500) {
1093
+ console.error(`[voltlog] Loki push failed: ${response.status}`);
1094
+ return;
1095
+ }
1096
+ lastError = new Error(`Loki HTTP ${response.status}`);
1097
+ } catch (err) {
1098
+ lastError = err;
1099
+ }
1100
+ if (attempt < attempts - 1) {
1101
+ await new Promise((r) => setTimeout(r, 100 * 2 ** attempt));
1102
+ }
1103
+ }
1104
+ console.error("[voltlog] Loki push failed after retries", lastError);
1105
+ }
1106
+ const doFlush = async () => {
1107
+ if (buffer.length === 0) return;
1108
+ const batch = buffer;
1109
+ buffer = [];
1110
+ await pushWithRetry(batch);
1111
+ };
1112
+ const schedule = () => {
1113
+ if (!timer) {
1114
+ timer = setTimeout(() => {
1115
+ timer = null;
1116
+ doFlush();
1117
+ }, interval);
1118
+ }
1119
+ };
1120
+ return {
1121
+ name: "loki",
1122
+ level,
1123
+ write(entry) {
1124
+ buffer.push(entry);
1125
+ if (buffer.length >= batchSize) {
1126
+ if (timer) clearTimeout(timer);
1127
+ timer = null;
1128
+ doFlush();
1129
+ } else {
1130
+ schedule();
1131
+ }
1132
+ },
1133
+ async flush() {
1134
+ if (timer) clearTimeout(timer);
1135
+ await doFlush();
1136
+ },
1137
+ async close() {
1138
+ await this.flush?.();
1139
+ }
1140
+ };
1141
+ }
1142
+
1143
+ // src/transports/otel.ts
1144
+ var OTEL_SEVERITY_MAP = {
1145
+ TRACE: { number: 1, text: "TRACE" },
1146
+ DEBUG: { number: 5, text: "DEBUG" },
1147
+ INFO: { number: 9, text: "INFO" },
1148
+ WARN: { number: 13, text: "WARN" },
1149
+ ERROR: { number: 17, text: "ERROR" },
1150
+ FATAL: { number: 21, text: "FATAL" }
1151
+ };
1152
+ function otelTransport(options) {
1153
+ const { endpoint, serviceName, level, resource = {} } = options;
1154
+ const batchSize = options.batchSize ?? 20;
1155
+ const interval = options.interval ?? 5e3;
1156
+ const url = `${endpoint.replace(/\/$/, "")}/v1/logs`;
1157
+ const headers = {
1158
+ "Content-Type": "application/json",
1159
+ ...options.headers
1160
+ };
1161
+ const resourceAttributes = [
1162
+ { key: "service.name", value: { stringValue: serviceName } },
1163
+ ...Object.entries(resource).map(([key, val]) => ({
1164
+ key,
1165
+ value: { stringValue: val }
1166
+ }))
1167
+ ];
1168
+ let buffer = [];
1169
+ let timer = null;
1170
+ function toOtlpLogRecord(entry) {
1171
+ const severity = OTEL_SEVERITY_MAP[entry.levelName] ?? OTEL_SEVERITY_MAP.INFO;
1172
+ const attributes = [];
1173
+ if (entry.meta && typeof entry.meta === "object") {
1174
+ for (const [key, val] of Object.entries(entry.meta)) {
1175
+ if (key === "traceId" || key === "spanId" || key === "traceFlags")
1176
+ continue;
1177
+ if (val !== void 0 && val !== null) {
1178
+ attributes.push({
1179
+ key,
1180
+ value: typeof val === "number" ? { intValue: val } : { stringValue: String(val) }
1181
+ });
1182
+ }
1183
+ }
1184
+ }
1185
+ if (entry.context) {
1186
+ for (const [key, val] of Object.entries(entry.context)) {
1187
+ if (val !== void 0 && val !== null) {
1188
+ attributes.push({
1189
+ key: `context.${key}`,
1190
+ value: { stringValue: String(val) }
1191
+ });
1192
+ }
1193
+ }
1194
+ }
1195
+ if (entry.error) {
1196
+ attributes.push({
1197
+ key: "error.message",
1198
+ value: { stringValue: entry.error.message }
1199
+ });
1200
+ if (entry.error.name) {
1201
+ attributes.push({
1202
+ key: "error.type",
1203
+ value: { stringValue: entry.error.name }
1204
+ });
1205
+ }
1206
+ if (entry.error.stack) {
1207
+ attributes.push({
1208
+ key: "error.stack",
1209
+ value: { stringValue: entry.error.stack }
1210
+ });
1211
+ }
1212
+ }
1213
+ const record = {
1214
+ timeUnixNano: String(entry.timestamp * 1e6),
1215
+ // ms → ns
1216
+ severityNumber: severity?.number,
1217
+ severityText: severity?.text,
1218
+ body: { stringValue: entry.message },
1219
+ attributes
1220
+ };
1221
+ const meta = entry.meta;
1222
+ if (meta?.traceId) {
1223
+ record.traceId = meta.traceId;
1224
+ }
1225
+ if (meta?.spanId) {
1226
+ record.spanId = meta.spanId;
1227
+ }
1228
+ if (meta?.traceFlags !== void 0) {
1229
+ record.flags = meta.traceFlags;
1230
+ }
1231
+ return record;
1232
+ }
1233
+ async function sendBatch(batch) {
1234
+ const payload = {
1235
+ resourceLogs: [
1236
+ {
1237
+ resource: { attributes: resourceAttributes },
1238
+ scopeLogs: [
1239
+ {
1240
+ scope: { name: "voltlog-io" },
1241
+ logRecords: batch.map(toOtlpLogRecord)
1242
+ }
1243
+ ]
1244
+ }
1245
+ ]
1246
+ };
1247
+ try {
1248
+ const response = await fetch(url, {
1249
+ method: "POST",
1250
+ headers,
1251
+ body: JSON.stringify(payload)
1252
+ });
1253
+ if (!response.ok) {
1254
+ console.error(
1255
+ `[voltlog] OTLP push failed: ${response.status} ${response.statusText}`
1256
+ );
1257
+ }
1258
+ } catch (err) {
1259
+ console.error("[voltlog] OTLP push failed", err);
1260
+ }
1261
+ }
1262
+ function flush() {
1263
+ if (buffer.length === 0) return;
1264
+ const batch = buffer;
1265
+ buffer = [];
1266
+ sendBatch(batch).catch(() => {
1267
+ });
1268
+ }
1269
+ function schedule() {
1270
+ if (!timer) {
1271
+ timer = setTimeout(() => {
1272
+ timer = null;
1273
+ flush();
1274
+ }, interval);
1275
+ }
1276
+ }
1277
+ return {
1278
+ name: "otel",
1279
+ level,
1280
+ write(entry) {
1281
+ buffer.push(entry);
1282
+ if (buffer.length >= batchSize) {
1283
+ if (timer) clearTimeout(timer);
1284
+ timer = null;
1285
+ flush();
1286
+ } else {
1287
+ schedule();
1288
+ }
1289
+ },
1290
+ async flush() {
1291
+ if (timer) clearTimeout(timer);
1292
+ timer = null;
1293
+ if (buffer.length === 0) return;
1294
+ const batch = buffer;
1295
+ buffer = [];
1296
+ await sendBatch(batch);
1297
+ },
1298
+ async close() {
1299
+ await this.flush?.();
1300
+ }
1301
+ };
1302
+ }
1303
+
1304
+ // src/transports/pretty.ts
1305
+ var RESET = "\x1B[0m";
1306
+ var DIM = "\x1B[2m";
1307
+ var BOLD = "\x1B[1m";
1308
+ var COLORS = {
1309
+ TRACE: "\x1B[90m",
1310
+ // gray
1311
+ DEBUG: "\x1B[36m",
1312
+ // cyan
1313
+ INFO: "\x1B[32m",
1314
+ // green
1315
+ WARN: "\x1B[33m",
1316
+ // yellow
1317
+ ERROR: "\x1B[31m",
1318
+ // red
1319
+ FATAL: "\x1B[35;1m"
1320
+ // bold magenta
1321
+ };
1322
+ var ICONS = {
1323
+ TRACE: "\u{1F50D}",
1324
+ DEBUG: "\u{1F41B}",
1325
+ INFO: "\u2139",
1326
+ WARN: "\u26A0",
1327
+ ERROR: "\u2716",
1328
+ FATAL: "\u{1F480}"
1329
+ };
1330
+ var EXCHANGE_ICONS = {
1331
+ CALL: "\u26A1",
1332
+ CALLRESULT: "\u2714",
1333
+ CALLERROR: "\u{1F6A8}"
1334
+ };
1335
+ var DIRECTION_ARROWS = {
1336
+ IN: "\u2192",
1337
+ OUT: "\u2190"
1338
+ };
1339
+ function prettyTransport(options = {}) {
1340
+ const showTimestamps = options.timestamps ?? true;
1341
+ const useColors = options.colors ?? true;
1342
+ const hideMeta = options.hideMeta ?? false;
1343
+ const prettyMeta = options.prettyMeta ?? false;
1344
+ function colorize(text, color) {
1345
+ return useColors ? `${color}${text}${RESET}` : text;
1346
+ }
1347
+ function formatExchange(entry) {
1348
+ const meta = entry.meta;
1349
+ if (!meta || !meta.action || !meta.messageType) return null;
1350
+ const icon = EXCHANGE_ICONS[meta.messageType] ?? "\u2022";
1351
+ const arrow = DIRECTION_ARROWS[meta.direction ?? "IN"] ?? "\u2192";
1352
+ const cpId = meta.chargePointId ?? "unknown";
1353
+ const action = meta.action;
1354
+ const msgType = meta.messageType;
1355
+ const dir = meta.direction ?? "";
1356
+ let line = `${icon} ${colorize(cpId, BOLD)} ${arrow} ${colorize(
1357
+ action,
1358
+ BOLD
1359
+ )} [${dir}] ${colorize(msgType, DIM)}`;
1360
+ if (meta.status || meta.latencyMs !== void 0) {
1361
+ const statusIcon = meta.messageType === "CALLERROR" ? "\u274C" : "\u2714";
1362
+ const status = meta.status ?? "";
1363
+ const latency = meta.latencyMs !== void 0 ? `(${meta.latencyMs}ms)` : "";
1364
+ line += `
1365
+ ${statusIcon} ${status} ${colorize(latency, DIM)}`;
1366
+ }
1367
+ return line;
1368
+ }
1369
+ function formatStandard(entry) {
1370
+ const icon = ICONS[entry.levelName] ?? "\u2022";
1371
+ const levelColor = COLORS[entry.levelName] ?? "";
1372
+ const level = colorize(entry.levelName.padEnd(5), levelColor);
1373
+ const ts = showTimestamps ? `${colorize(new Date(entry.timestamp).toISOString(), DIM)} ` : "";
1374
+ let line = `${icon} ${ts}${level} ${entry.message}`;
1375
+ if (entry.context && Object.keys(entry.context).length > 0) {
1376
+ const kvStr = Object.entries(entry.context).map(
1377
+ ([k, v]) => `${k}:${typeof v === "string" ? v : JSON.stringify(v)}`
1378
+ ).join(" ");
1379
+ line += ` ${colorize(kvStr, DIM)}`;
1380
+ }
1381
+ if (!hideMeta && entry.meta && Object.keys(entry.meta).length > 0) {
1382
+ if (prettyMeta) {
1383
+ const metaEntries = Object.entries(
1384
+ entry.meta
1385
+ );
1386
+ const parts = metaEntries.map(([key, value]) => {
1387
+ const valStr = typeof value === "string" ? value : JSON.stringify(value);
1388
+ return `${colorize(`${key}:`, DIM)}${valStr}`;
1389
+ });
1390
+ line += ` ${parts.join(" ")}`;
1391
+ } else {
1392
+ const kvStr = Object.entries(entry.meta).map(
1393
+ ([k, v]) => `${k}:${typeof v === "string" ? v : JSON.stringify(v)}`
1394
+ ).join(" ");
1395
+ line += ` ${colorize(kvStr, DIM)}`;
1396
+ }
1397
+ }
1398
+ if (entry.error) {
1399
+ line += `
1400
+ ${colorize(
1401
+ `${entry.error.name ?? "Error"}: ${entry.error.message}`,
1402
+ COLORS.ERROR ?? ""
1403
+ )}`;
1404
+ if (entry.error.stack) {
1405
+ line += `
1406
+ ${colorize(entry.error.stack, DIM)}`;
1407
+ }
1408
+ }
1409
+ return line;
1410
+ }
1411
+ return {
1412
+ name: "pretty",
1413
+ level: options.level,
1414
+ write(entry) {
1415
+ const exchangeOutput = formatExchange(entry);
1416
+ if (exchangeOutput) {
1417
+ console.log(exchangeOutput);
1418
+ return;
1419
+ }
1420
+ const output = formatStandard(entry);
1421
+ if (entry.level >= LogLevel.ERROR) {
1422
+ console.error(output);
1423
+ } else if (entry.level >= LogLevel.WARN) {
1424
+ console.warn(output);
1425
+ } else {
1426
+ console.log(output);
1427
+ }
1428
+ }
1429
+ };
1430
+ }
1431
+
1432
+ // src/transports/ring-buffer.ts
1433
+ function ringBufferTransport(options = {}) {
1434
+ const maxSize = options.maxSize ?? 1e3;
1435
+ const buffer = [];
1436
+ let head = 0;
1437
+ let count = 0;
1438
+ return {
1439
+ name: "ring-buffer",
1440
+ level: options.level,
1441
+ write(entry) {
1442
+ if (count < maxSize) {
1443
+ buffer.push(entry);
1444
+ count++;
1445
+ } else {
1446
+ buffer[head] = entry;
1447
+ }
1448
+ head = (head + 1) % maxSize;
1449
+ },
1450
+ getEntries(query) {
1451
+ let entries;
1452
+ if (count < maxSize) {
1453
+ entries = buffer.slice();
1454
+ } else {
1455
+ entries = [...buffer.slice(head), ...buffer.slice(0, head)];
1456
+ }
1457
+ if (query?.level) {
1458
+ const minLevel = resolveLevel(query.level);
1459
+ entries = entries.filter((e) => e.level >= minLevel);
1460
+ }
1461
+ if (query?.since) {
1462
+ const since = query.since;
1463
+ entries = entries.filter((e) => e.timestamp >= since);
1464
+ }
1465
+ if (query?.limit) {
1466
+ entries = entries.slice(-query.limit);
1467
+ }
1468
+ return entries;
1469
+ },
1470
+ clear() {
1471
+ buffer.length = 0;
1472
+ head = 0;
1473
+ count = 0;
1474
+ },
1475
+ get size() {
1476
+ return count;
1477
+ }
1478
+ };
1479
+ }
1480
+
1481
+ // src/transports/sentry.ts
1482
+ function sentryTransport(options) {
1483
+ const { sentry } = options;
1484
+ const errorLevelValue = resolveLevel(options.errorLevel ?? "ERROR");
1485
+ const breadcrumbLevelValue = resolveLevel(options.breadcrumbLevel ?? "INFO");
1486
+ return {
1487
+ name: "sentry",
1488
+ write(entry) {
1489
+ if (entry.level >= errorLevelValue) {
1490
+ if (entry.error) {
1491
+ sentry.captureException(entry.error, {
1492
+ extra: {
1493
+ ...entry.meta,
1494
+ context: entry.context
1495
+ },
1496
+ level: "error"
1497
+ });
1498
+ } else {
1499
+ sentry.captureMessage(entry.message, "error");
1500
+ }
1501
+ }
1502
+ if (entry.level >= breadcrumbLevelValue) {
1503
+ sentry.addBreadcrumb({
1504
+ category: "log",
1505
+ message: entry.message,
1506
+ level: mapLevelToSentry(entry.level),
1507
+ data: { ...entry.meta, ...entry.context },
1508
+ timestamp: entry.timestamp / 1e3
1509
+ });
1510
+ }
1511
+ }
1512
+ };
1513
+ }
1514
+ function mapLevelToSentry(level) {
1515
+ if (level >= 60) return "fatal";
1516
+ if (level >= 50) return "error";
1517
+ if (level >= 40) return "warning";
1518
+ if (level >= 30) return "info";
1519
+ return "debug";
1520
+ }
1521
+
1522
+ // src/transports/slack.ts
1523
+ function slackTransport(options) {
1524
+ const { webhookUrl, username, iconEmoji, level } = options;
1525
+ return {
1526
+ name: "slack",
1527
+ level: level ?? "ERROR",
1528
+ // Default to ERROR to prevent spamming
1529
+ async write(entry) {
1530
+ try {
1531
+ const payload = formatSlackMessage(entry, username, iconEmoji);
1532
+ const response = await fetch(webhookUrl, {
1533
+ method: "POST",
1534
+ headers: { "Content-Type": "application/json" },
1535
+ body: JSON.stringify(payload)
1536
+ });
1537
+ if (!response.ok) {
1538
+ }
1539
+ } catch (_err) {
1540
+ }
1541
+ }
1542
+ };
1543
+ }
1544
+ function formatSlackMessage(entry, username, icon_emoji) {
1545
+ const levelEmoji = getLevelEmoji(entry.level);
1546
+ const color = getLevelColor2(entry.level);
1547
+ const blocks = [
1548
+ {
1549
+ type: "header",
1550
+ text: {
1551
+ type: "plain_text",
1552
+ text: `${levelEmoji} ${entry.levelName}: ${entry.message}`,
1553
+ emoji: true
1554
+ }
1555
+ },
1556
+ {
1557
+ type: "context",
1558
+ elements: [
1559
+ {
1560
+ type: "mrkdwn",
1561
+ text: `*Time:* ${new Date(entry.timestamp).toISOString()}`
1562
+ },
1563
+ {
1564
+ type: "mrkdwn",
1565
+ text: `*ID:* \`${entry.id}\``
1566
+ }
1567
+ ]
1568
+ }
1569
+ ];
1570
+ if (entry.correlationId) {
1571
+ blocks[1].elements.push({
1572
+ type: "mrkdwn",
1573
+ text: `*Trace:* \`${entry.correlationId}\``
1574
+ });
1575
+ }
1576
+ if (Object.keys(entry.meta).length > 0) {
1577
+ blocks.push({
1578
+ type: "section",
1579
+ text: {
1580
+ type: "mrkdwn",
1581
+ text: `*Metadata:*
1582
+ \`\`\`${JSON.stringify(entry.meta, null, 2)}\`\`\``,
1583
+ emoji: true
1584
+ }
1585
+ });
1586
+ }
1587
+ if (entry.error?.stack) {
1588
+ blocks.push({
1589
+ type: "section",
1590
+ text: {
1591
+ type: "mrkdwn",
1592
+ text: `*Error Stack:*
1593
+ \`\`\`${entry.error.stack}\`\`\``,
1594
+ emoji: true
1595
+ }
1596
+ });
1597
+ }
1598
+ return {
1599
+ username,
1600
+ icon_emoji,
1601
+ attachments: [
1602
+ {
1603
+ color,
1604
+ blocks
1605
+ }
1606
+ ]
1607
+ };
1608
+ }
1609
+ function getLevelEmoji(level) {
1610
+ if (level >= 60) return "\u{1F525}";
1611
+ if (level >= 50) return "\u{1F6A8}";
1612
+ if (level >= 40) return "\u26A0\uFE0F";
1613
+ if (level >= 30) return "\u2139\uFE0F";
1614
+ if (level >= 20) return "\u{1F41B}";
1615
+ return "\u{1F50D}";
1616
+ }
1617
+ function getLevelColor2(level) {
1618
+ if (level >= 60) return "#ff0000";
1619
+ if (level >= 50) return "#ff4444";
1620
+ if (level >= 40) return "#ffbb33";
1621
+ if (level >= 30) return "#33b5e5";
1622
+ if (level >= 20) return "#99cc00";
1623
+ return "#aa66cc";
1624
+ }
1625
+
1626
+ // src/transports/webhook.ts
1627
+ function webhookTransport(options) {
1628
+ const {
1629
+ url,
1630
+ method = "POST",
1631
+ headers = {},
1632
+ batchSize = 1,
1633
+ flushIntervalMs = 5e3,
1634
+ retry = false,
1635
+ maxRetries = 3
1636
+ } = options;
1637
+ const serialize = options.serializer ?? ((entries) => JSON.stringify({
1638
+ entries,
1639
+ count: entries.length,
1640
+ timestamp: Date.now()
1641
+ }));
1642
+ let buffer = [];
1643
+ let flushTimer = null;
1644
+ async function sendBatch(entries, attempt = 0) {
1645
+ try {
1646
+ const response = await fetch(url, {
1647
+ method,
1648
+ headers: {
1649
+ "Content-Type": "application/json",
1650
+ ...headers
1651
+ },
1652
+ body: serialize(entries)
1653
+ });
1654
+ if (!response.ok && retry && attempt < maxRetries) {
1655
+ const delay = Math.min(1e3 * 2 ** attempt, 3e4);
1656
+ await new Promise((r) => setTimeout(r, delay));
1657
+ return sendBatch(entries, attempt + 1);
1658
+ }
1659
+ } catch {
1660
+ if (retry && attempt < maxRetries) {
1661
+ const delay = Math.min(1e3 * 2 ** attempt, 3e4);
1662
+ await new Promise((r) => setTimeout(r, delay));
1663
+ return sendBatch(entries, attempt + 1);
1664
+ }
1665
+ }
1666
+ }
1667
+ function scheduleFlush() {
1668
+ if (flushTimer) return;
1669
+ flushTimer = setTimeout(() => {
1670
+ flushTimer = null;
1671
+ doFlush();
1672
+ }, flushIntervalMs);
1673
+ }
1674
+ function doFlush() {
1675
+ if (buffer.length === 0) return;
1676
+ const batch = buffer;
1677
+ buffer = [];
1678
+ sendBatch(batch).catch(() => {
1679
+ });
1680
+ }
1681
+ return {
1682
+ name: "webhook",
1683
+ level: options.level,
1684
+ write(entry) {
1685
+ buffer.push(entry);
1686
+ if (buffer.length >= batchSize) {
1687
+ doFlush();
1688
+ } else {
1689
+ scheduleFlush();
1690
+ }
1691
+ },
1692
+ async flush() {
1693
+ if (flushTimer) {
1694
+ clearTimeout(flushTimer);
1695
+ flushTimer = null;
1696
+ }
1697
+ if (buffer.length > 0) {
1698
+ const batch = buffer;
1699
+ buffer = [];
1700
+ await sendBatch(batch);
1701
+ }
1702
+ },
1703
+ async close() {
1704
+ await this.flush?.();
1705
+ }
1706
+ };
1707
+ }
1708
+
1709
+ export {
1710
+ LogLevel,
1711
+ LogLevelNameMap,
1712
+ LogLevelValueMap,
1713
+ resolveLevel,
1714
+ shouldLog,
1715
+ shouldIncludeStack,
1716
+ createLogger,
1717
+ aiEnrichmentMiddleware,
1718
+ createOpenAiErrorAnalyzer,
1719
+ alertMiddleware,
1720
+ createMiddleware,
1721
+ deduplicationMiddleware,
1722
+ heapUsageMiddleware,
1723
+ nodeHttpMappers,
1724
+ createHttpLogger,
1725
+ ipMiddleware,
1726
+ levelOverrideMiddleware,
1727
+ ocppMiddleware,
1728
+ otelTraceMiddleware,
1729
+ redactionMiddleware,
1730
+ samplingMiddleware,
1731
+ userAgentMiddleware,
1732
+ batchTransport,
1733
+ browserJsonStreamTransport,
1734
+ consoleTransport,
1735
+ createTransport,
1736
+ datadogTransport,
1737
+ discordTransport,
1738
+ lokiTransport,
1739
+ otelTransport,
1740
+ prettyTransport,
1741
+ ringBufferTransport,
1742
+ sentryTransport,
1743
+ slackTransport,
1744
+ webhookTransport
1745
+ };
1746
+ //# sourceMappingURL=chunk-DAFMRCAN.mjs.map