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