File size: 1,696 Bytes
529090e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import { EventEmitter } from 'events';
import { randomUUID } from 'crypto';

export type LogLevel = 'info' | 'warn' | 'error' | 'debug';

export interface LogEntry {
  id: string;
  timestamp: string;
  level: LogLevel;
  source: string;
  message: string;
  meta?: Record<string, unknown>;
}

interface FilterOptions {
  limit?: number;
  level?: LogLevel;
  source?: string;
}

class LogStream extends EventEmitter {
  private buffer: LogEntry[] = [];
  private readonly maxEntries = 500;

  push(entry: Omit<LogEntry, 'id' | 'timestamp'> & { id?: string; timestamp?: string }): void {
    const normalized: LogEntry = {
      id: entry.id || randomUUID(),
      timestamp: entry.timestamp || new Date().toISOString(),
      level: entry.level,
      source: entry.source || 'backend',
      message: entry.message,
      meta: entry.meta,
    };

    this.buffer.unshift(normalized);
    if (this.buffer.length > this.maxEntries) {
      this.buffer.pop();
    }

    this.emit('log', normalized);
  }

  getRecent(options: FilterOptions = {}): LogEntry[] {
    const { limit = 100, level, source } = options;
    const normalizedLimit = Math.min(Math.max(limit, 1), this.maxEntries);

    return this.buffer
      .filter((entry) => {
        if (level && entry.level !== level) return false;
        if (source && entry.source !== source) return false;
        return true;
      })
      .slice(0, normalizedLimit);
  }

  getSources(): string[] {
    const sources = new Set<string>();
    this.buffer.forEach((entry) => sources.add(entry.source));
    return Array.from(sources);
  }
}

export const logStream = new LogStream();
export type LogStreamListener = (entry: LogEntry) => void;