/* eslint-disable @typescript-eslint/no-explicit-any */ import { v4 as uuidv4 } from 'uuid'; import * as fs from 'fs'; import * as path from 'path'; export interface TavusLogEntry { sessionId: string; timestamp: string; request: { method: string; url: string; headers: Record; body?: any; }; response: { status: number; headers: Record; body?: any; duration: number; }; metadata?: { endpoint: string; requestType: 'conversation' | 'video' | 'auth' | 'streaming' | 'other'; hasBinaryData: boolean; binaryDataSize?: number; }; } export interface TavusLoggerConfig { enabled: boolean; logDirectory: string; includeHeaders: boolean; includeBody: boolean; maxBodySize: number; // in bytes sessionTimeout: number; // in minutes // Enhanced logging options logProxyRequests: boolean; // log incoming proxy requests logClientInfo: boolean; // log client IP, User-Agent, etc. logPerformance: boolean; // log timing and performance metrics logErrors: boolean; // log error details with context } class TavusLogger { private config: TavusLoggerConfig; private currentSessionId: string; private sessionStartTime: number; private logBuffer: TavusLogEntry[] = []; private flushInterval: NodeJS.Timeout | null = null; constructor(config: Partial = {}) { this.config = { enabled: true, logDirectory: path.join(process.cwd(), 'documentation', 'data', 'tavus-logs'), includeHeaders: true, includeBody: true, maxBodySize: 1024 * 1024, // 1MB sessionTimeout: 30, // 30 minutes // Enhanced logging defaults logProxyRequests: true, logClientInfo: true, logPerformance: true, logErrors: true, ...config }; this.currentSessionId = uuidv4(); this.sessionStartTime = Date.now(); this.ensureLogDirectory(); this.startFlushInterval(); } private ensureLogDirectory(): void { const dirs = [ this.config.logDirectory, path.join(this.config.logDirectory, 'requests'), path.join(this.config.logDirectory, 'sessions'), path.join(this.config.logDirectory, 'schemas'), path.join(this.config.logDirectory, 'errors') ]; dirs.forEach(dir => { if (!fs.existsSync(dir)) { fs.mkdirSync(dir, { recursive: true }); } }); } private startFlushInterval(): void { if (this.flushInterval) { clearInterval(this.flushInterval); } this.flushInterval = setInterval(() => { this.flushBuffer(); }, 5000); // Flush every 5 seconds } private shouldStartNewSession(): boolean { const sessionAge = Date.now() - this.sessionStartTime; return sessionAge > this.config.sessionTimeout * 60 * 1000; } private getEndpointType(url: string): "conversation" | "video" | "auth" | "streaming" | "other" { if (url.includes('/conversations')) return 'conversation'; if (url.includes('/videos')) return 'video'; if (url.includes('/auth')) return 'auth'; if (url.includes('/stream') || url.includes('/events')) return 'streaming'; return 'other'; } private sanitizeHeaders(headers: Record): Record { if (!this.config.includeHeaders) return {}; // Log everything for complete API reverse engineering // User will rotate keys after logging return { ...headers }; } private sanitizeBody(body: any): any { if (!this.config.includeBody || !body) return undefined; // Log everything for complete API reverse engineering // No truncation - capture full request/response data return body; } private isBinaryData(data: any): boolean { if (typeof data === 'string') { // Check if it's base64 encoded binary data return /^[A-Za-z0-9+/]*={0,2}$/.test(data) && data.length > 100; } return false; } logRequest( method: string, url: string, headers: Record, body?: any ): string { if (!this.config.enabled) return ''; if (this.shouldStartNewSession()) { this.currentSessionId = uuidv4(); this.sessionStartTime = Date.now(); } const requestId = uuidv4(); const startTime = Date.now(); // Store request info for later response logging this.pendingRequests.set(requestId, { method, url, headers: this.sanitizeHeaders(headers), body: this.sanitizeBody(body), startTime, sessionId: this.currentSessionId }); return requestId; } logResponse( requestId: string, status: number, headers: Record, body?: any ): void { if (!this.config.enabled) return; const requestInfo = this.pendingRequests.get(requestId); if (!requestInfo) { console.warn(`TavusLogger: No pending request found for ID ${requestId}`); return; } this.pendingRequests.delete(requestId); const duration = Date.now() - requestInfo.startTime; const sanitizedBody = this.sanitizeBody(body); const hasBinaryData = this.isBinaryData(sanitizedBody); const binaryDataSize = hasBinaryData && typeof sanitizedBody === 'string' ? sanitizedBody.length : undefined; const logEntry: TavusLogEntry = { sessionId: requestInfo.sessionId, timestamp: new Date().toISOString(), request: { method: requestInfo.method, url: requestInfo.url, headers: requestInfo.headers, body: requestInfo.body }, response: { status, headers: this.sanitizeHeaders(headers), body: sanitizedBody, duration }, metadata: { endpoint: new URL(requestInfo.url).pathname, requestType: this.getEndpointType(requestInfo.url), hasBinaryData, binaryDataSize } }; this.logBuffer.push(logEntry); // Log errors separately if (status >= 400) { this.logErrorEntry(logEntry); } // Flush immediately for errors or large responses if (status >= 400 || hasBinaryData) { this.flushBuffer(); } } private logErrorEntry(logEntry: TavusLogEntry): void { const errorFile = path.join( this.config.logDirectory, 'errors', `${logEntry.metadata?.requestType}-${logEntry.response.status}-${Date.now()}.json` ); try { fs.writeFileSync(errorFile, JSON.stringify(logEntry, null, 2)); } catch (error) { console.error('TavusLogger: Failed to write error log:', error); } } private flushBuffer(): void { if (this.logBuffer.length === 0) return; const timestamp = new Date().toISOString().replace(/[:.]/g, '-'); const requestFile = path.join( this.config.logDirectory, 'requests', `requests-${timestamp}.json` ); try { fs.writeFileSync(requestFile, JSON.stringify(this.logBuffer, null, 2)); this.logBuffer = []; } catch (error) { console.error('TavusLogger: Failed to write request log:', error); } } logStreamingEvent( method: string, url: string, eventType: string, data: any ): void { if (!this.config.enabled) return; const logEntry: TavusLogEntry = { sessionId: this.currentSessionId, timestamp: new Date().toISOString(), request: { method, url, headers: {}, body: { eventType, data } }, response: { status: 200, headers: { 'content-type': 'text/event-stream' }, body: { eventType, data }, duration: 0 }, metadata: { endpoint: new URL(url).pathname, requestType: 'streaming', hasBinaryData: false } }; this.logBuffer.push(logEntry); } getSessionSummary(): { sessionId: string; requestCount: number; errorCount: number; totalDuration: number; endpoints: string[]; } { const requests = this.logBuffer.filter(entry => entry.sessionId === this.currentSessionId); const errors = requests.filter(entry => entry.response.status >= 400); const endpoints = [...new Set(requests.map(entry => entry.metadata?.endpoint || ''))]; return { sessionId: this.currentSessionId, requestCount: requests.length, errorCount: errors.length, totalDuration: requests.reduce((sum, entry) => sum + entry.response.duration, 0), endpoints }; } exportSession(sessionId?: string): void { const targetSessionId = sessionId || this.currentSessionId; const sessionRequests = this.logBuffer.filter(entry => entry.sessionId === targetSessionId); if (sessionRequests.length === 0) { console.warn(`TavusLogger: No requests found for session ${targetSessionId}`); return; } const sessionFile = path.join( this.config.logDirectory, 'sessions', `session-${targetSessionId}-${Date.now()}.json` ); try { fs.writeFileSync(sessionFile, JSON.stringify(sessionRequests, null, 2)); console.log(`TavusLogger: Exported session ${targetSessionId} with ${sessionRequests.length} requests`); } catch (error) { console.error('TavusLogger: Failed to export session:', error); } } destroy(): void { if (this.flushInterval) { clearInterval(this.flushInterval); } this.flushBuffer(); } private pendingRequests = new Map; body?: any; startTime: number; sessionId: string; }>(); // Proxy server logging methods logProxyRequest(req: any, endpoint: string): string { // Don't log in production or on Vercel if (!this.config.logProxyRequests || isProduction || isVercel) return ''; const requestId = uuidv4(); const timestamp = new Date().toISOString(); const requestData = { requestId, timestamp, endpoint, method: req.method, url: req.url, originalUrl: req.originalUrl, path: req.path, query: req.query, params: req.params, headers: req.headers, body: req.body, rawBody: req.rawBody, ip: req.ip, ips: req.ips, hostname: req.hostname, protocol: req.protocol, secure: req.secure, userAgent: req.get?.('User-Agent'), referer: req.get?.('Referer'), origin: req.get?.('Origin'), contentType: req.get?.('Content-Type'), contentLength: req.get?.('Content-Length'), accept: req.get?.('Accept'), acceptEncoding: req.get?.('Accept-Encoding'), acceptLanguage: req.get?.('Accept-Language'), connection: req.get?.('Connection'), cacheControl: req.get?.('Cache-Control'), pragma: req.get?.('Pragma'), metadata: { isLocalhost: req.hostname === 'localhost' || req.hostname === '127.0.0.1', isCurl: req.get?.('User-Agent')?.includes('curl') || false, isPostman: req.get?.('User-Agent')?.includes('Postman') || false, isInsomnia: req.get?.('User-Agent')?.includes('Insomnia') || false, hasOrigin: !!req.get?.('Origin'), hasReferer: !!req.get?.('Referer'), requestSize: req.get?.('Content-Length') ? parseInt(req.get('Content-Length')) : 0, timestamp: Date.now() } }; // Store start time for duration calculation this.pendingRequests.set(requestId, { method: req.method, url: req.url, headers: req.headers, body: req.body, startTime: Date.now(), sessionId: this.currentSessionId }); // Write to file const filename = `proxy-request-${timestamp.replace(/[:.]/g, '-')}-${requestId}.json`; const filepath = path.join(this.config.logDirectory, 'requests', filename); try { fs.writeFileSync(filepath, JSON.stringify(requestData, null, 2)); console.log(`[TavusLogger] Logged proxy request: ${requestId} -> ${endpoint}`); } catch (error) { console.error('[TavusLogger] Failed to log proxy request:', error); } return requestId; } logProxyResponse(requestId: string, res: any, responseData: any, error: any = null): void { // Don't log in production or on Vercel if (!this.config.logProxyRequests || isProduction || isVercel) return; const pendingRequest = this.pendingRequests.get(requestId); const duration = pendingRequest ? Date.now() - pendingRequest.startTime : 0; const timestamp = new Date().toISOString(); const responseLog = { requestId, timestamp, statusCode: res.statusCode, statusMessage: res.statusMessage, headers: res.getHeaders?.() || {}, body: responseData, error: error ? { message: error.message, stack: error.stack, name: error.name, code: error.code } : null, duration, metadata: { isError: !!error, isSuccess: !error && res.statusCode < 400, responseSize: responseData ? JSON.stringify(responseData).length : 0, timestamp: Date.now() } }; // Write to file const filename = `proxy-response-${timestamp.replace(/[:.]/g, '-')}-${requestId}.json`; const filepath = path.join(this.config.logDirectory, 'responses', filename); try { fs.writeFileSync(filepath, JSON.stringify(responseLog, null, 2)); console.log(`[TavusLogger] Logged proxy response: ${requestId} -> ${res.statusCode} (${duration}ms)`); } catch (error) { console.error('[TavusLogger] Failed to log proxy response:', error); } // Clean up this.pendingRequests.delete(requestId); } logError(requestId: string, error: unknown, context: Record = {}): void { // Don't log in production or on Vercel if (!this.config.logErrors || isProduction || isVercel) return; const timestamp = new Date().toISOString(); const errorLog = { requestId, timestamp, error: { message: error instanceof Error ? error.message : String(error), stack: error instanceof Error ? error.stack : undefined, name: error instanceof Error ? error.name : 'UnknownError', code: error instanceof Error && 'code' in error ? (error as Error & { code?: string }).code : undefined }, context, metadata: { timestamp: Date.now() } }; // Write to file const filename = `error-${timestamp.replace(/[:.]/g, '-')}-${requestId || 'unknown'}.json`; const filepath = path.join(this.config.logDirectory, 'errors', filename); try { fs.writeFileSync(filepath, JSON.stringify(errorLog, null, 2)); console.error(`[TavusLogger] Logged error: ${requestId || 'unknown'} -> ${error instanceof Error ? error.message : String(error)}`); } catch (writeError) { console.error('[TavusLogger] Failed to log error:', writeError); } } } // Singleton instance let loggerInstance: TavusLogger | null = null; export function getTavusLogger(config?: Partial): TavusLogger { if (!loggerInstance) { loggerInstance = new TavusLogger(config); } return loggerInstance; } export function destroyTavusLogger(): void { if (loggerInstance) { loggerInstance.destroy(); loggerInstance = null; } } // Environment-based configuration const isDevelopment = process.env.NODE_ENV === 'development'; const isVercel = !!process.env.VERCEL || !!process.env.VERCEL_ENV; const isProduction = process.env.NODE_ENV === 'production'; // Check if we're in a browser environment const isLocalhost = typeof window !== 'undefined' && window.location ? ( window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1' || window.location.hostname.startsWith('192.168.') || window.location.hostname.startsWith('10.') || window.location.hostname.startsWith('172.') ) : true; // Allow logging in Node.js environments (test scripts, etc.) // Only log in development/local environments, never in production or on Vercel const shouldLogRequests = ( process.env.TAVUS_LOG_REQUESTS === 'true' || (isDevelopment && !isVercel) ) && isLocalhost && !isProduction; if (shouldLogRequests) { getTavusLogger({ enabled: true, logDirectory: process.env.TAVUS_LOG_DIRECTORY || path.join(process.cwd(), 'documentation', 'tavus-mock-data') }); }