import { v4 as uuidv4 } from 'uuid'; import { isRecord, type TavusLogEntry, type TavusLoggerConfig, type HttpBody, type LogEntryMetadata, type PendingRequest, type NetworkInfo, type SampledVideoPayload, type TruncatedPayload, type SessionSummary } from '@buzztrail/shared-types'; class TavusLoggerBrowser { private config: TavusLoggerConfig; private currentSessionId: string; private sessionStartTime: number; private logBuffer: TavusLogEntry[] = []; private flushInterval: number | null = null; constructor(config: Partial = {}) { this.config = { enabled: true, includeHeaders: true, includeBody: true, maxBodySize: 1024 * 1024, // 1MB sessionTimeout: 30, // 30 minutes logVideoData: false, // don't log video data by default logErrors: true, // always log errors logAllStatusCodes: true, // log all status codes sampleLargePayloads: true, // sample large payloads maxVideoPayloadSize: 1024 * 10, // 10KB for video payloads // Enhanced logging for API reverse engineering logRawData: true, // log raw request/response data logQueryParams: true, // log URL query parameters logUserAgent: true, // log user agent string logReferrer: true, // log referrer information logTimestamps: true, // log detailed timestamps logRequestIds: true, // log unique request IDs logContentTypes: true, // log content type information logContentLengths: true, // log content length headers logAllHeaders: true, // log all headers (including sensitive ones) logStackTraces: true, // log error stack traces logNetworkInfo: true, // log network-related information ...config }; this.currentSessionId = uuidv4(); this.sessionStartTime = Date.now(); this.startFlushInterval(); } private startFlushInterval(): void { if (this.flushInterval) { clearInterval(this.flushInterval); } this.flushInterval = window.setInterval(() => { void this.flushBuffer(); // Handle async flush }, 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): NonNullable { 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 {}; const sanitized: Record = {}; const sensitiveKeys = ['authorization', 'cookie', 'x-api-key', 'token']; Object.entries(headers).forEach(([key, value]) => { const lowerKey = key.toLowerCase(); if (sensitiveKeys.includes(lowerKey) && !this.config.logAllHeaders) { sanitized[key] = '[REDACTED]'; } else { sanitized[key] = value; } }); return sanitized; } private extractQueryParams(url: string): Record { if (!this.config.logQueryParams) return {}; try { const urlObj = new URL(url); const params: Record = {}; urlObj.searchParams.forEach((value, key) => { params[key] = value; }); return params; } catch { return {}; } } private getNetworkInfo(): NetworkInfo { if (!this.config.logNetworkInfo) return {}; const info: NetworkInfo = {}; // Browser network information if ('connection' in navigator) { const connection = (navigator as unknown as { connection?: unknown }).connection; if (isRecord(connection)) { if (typeof connection.effectiveType === 'string') info.effectiveType = connection.effectiveType; if (typeof connection.downlink === 'number') info.downlink = connection.downlink; if (typeof connection.rtt === 'number') info.rtt = connection.rtt; if (typeof connection.saveData === 'boolean') info.saveData = connection.saveData; } } // Performance timing if (performance?.timing) { info.navigationStart = performance.timing.navigationStart; info.fetchStart = performance.timing.fetchStart; info.domainLookupStart = performance.timing.domainLookupStart; info.domainLookupEnd = performance.timing.domainLookupEnd; info.connectStart = performance.timing.connectStart; info.connectEnd = performance.timing.connectEnd; info.requestStart = performance.timing.requestStart; info.responseStart = performance.timing.responseStart; info.responseEnd = performance.timing.responseEnd; } return info; } private sanitizeBody(body: T, isVideoData = false): T | SampledVideoPayload | TruncatedPayload | undefined { if (!this.config.includeBody || !body) return undefined; const bodyStr = typeof body === 'string' ? body : JSON.stringify(body); const maxSize = isVideoData ? (this.config.maxVideoPayloadSize || this.config.maxBodySize) : this.config.maxBodySize; if (bodyStr.length > maxSize) { if (this.config.sampleLargePayloads && isVideoData) { // For video data, sample the payload instead of truncating return this.sampleVideoPayload(bodyStr); } else { return { truncated: true, size: bodyStr.length, preview: bodyStr.substring(0, 1000) + '...', type: isVideoData ? 'video' : 'regular' }; } } return body; } private sampleVideoPayload(payload: string): SampledVideoPayload { // Sample video payload by taking chunks from beginning, middle, and end const totalLength = payload.length; const sampleSize = Math.min(1000, Math.floor(totalLength * 0.01)); // 1% or 1000 chars const start = payload.substring(0, sampleSize); const middle = payload.substring(Math.floor(totalLength / 2), Math.floor(totalLength / 2) + sampleSize); const end = payload.substring(totalLength - sampleSize); return { sampled: true, totalSize: totalLength, sampleSize: sampleSize, samples: { start: start, middle: middle, end: end }, type: 'video' }; } private isBinaryData(data: unknown): 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?: HttpBody ): string { if (!this.config.enabled) return ''; if (this.shouldStartNewSession()) { this.currentSessionId = uuidv4(); this.sessionStartTime = Date.now(); } const requestId = uuidv4(); const startTime = Date.now(); // Enhanced request logging with all details const requestInfo = { method, url, headers: this.sanitizeHeaders(headers), body: this.sanitizeBody(body), startTime, sessionId: this.currentSessionId, // Additional metadata for API reverse engineering queryParams: this.extractQueryParams(url), fullUrl: url, bodySize: body ? (typeof body === 'string' ? body.length : JSON.stringify(body).length) : 0, bodyType: body ? typeof body : 'undefined', contentType: headers['content-type'] || headers['Content-Type'], contentLength: headers['content-length'] || headers['Content-Length'], userAgent: this.config.logUserAgent ? navigator.userAgent : undefined, referrer: this.config.logReferrer ? document.referrer : undefined, timestamp: this.config.logTimestamps ? Date.now() : undefined, requestId: this.config.logRequestIds ? requestId : undefined, networkInfo: this.getNetworkInfo() }; // Store request info for later response logging this.pendingRequests.set(requestId, requestInfo); // Log raw request data if enabled if (this.config.logRawData) { console.log(`[TavusLogger] Raw Request ${requestId}:`, { method, url, headers, body, timestamp: new Date().toISOString(), sessionId: this.currentSessionId }); } return requestId; } logResponse( requestId: string, status: number, headers: Record, body?: HttpBody, response?: Response ): 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; // Determine if this is video data const isVideoData = this.isVideoData(requestInfo.url, headers, body); // Check if we should log this response const shouldLog = this.shouldLogResponse(status, isVideoData); if (!shouldLog) { console.log(`[TavusLogger] Skipping ${requestInfo.method} ${requestInfo.url} -> ${status} (${duration}ms) - ${isVideoData ? 'video data' : 'filtered'}`); return; } const sanitizedBody = this.sanitizeBody(body, isVideoData); 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, bodySize: requestInfo.bodySize, bodyType: requestInfo.bodyType, queryParams: requestInfo.queryParams, fullUrl: requestInfo.fullUrl }, response: { status, statusText: response?.statusText || '', headers: this.sanitizeHeaders(headers), body: sanitizedBody, bodySize: typeof sanitizedBody === 'string' ? sanitizedBody.length : JSON.stringify(sanitizedBody).length, bodyType: typeof sanitizedBody, duration, ok: response?.ok ?? (status >= 200 && status < 300), redirected: response?.redirected || false, type: response?.type || 'default' }, metadata: { endpoint: new URL(requestInfo.url).pathname, requestType: this.getEndpointType(requestInfo.url), hasBinaryData, binaryDataSize, isVideoData, shouldLog, contentType: requestInfo.contentType, contentLength: requestInfo.contentLength ? parseInt(requestInfo.contentLength, 10) : undefined, userAgent: requestInfo.userAgent, referrer: requestInfo.referrer, timestamp: requestInfo.timestamp, requestId: requestInfo.requestId }, raw: this.config.logRawData ? { requestHeaders: headers, responseHeaders: headers, requestBody: requestInfo.body, responseBody: body, url: requestInfo.url, method: requestInfo.method } : undefined }; this.logBuffer.push(logEntry); // Log errors separately if (status >= 400 && this.config.logErrors) { this.logError(logEntry); } // Flush immediately for errors or large responses if (status >= 400 || hasBinaryData || isVideoData) { void this.flushBuffer(); } // Log to console for debugging const logLevel = status >= 400 ? 'ERROR' : status >= 300 ? 'WARN' : 'INFO'; console.log(`[TavusLogger] ${logLevel} ${requestInfo.method} ${requestInfo.url} -> ${status} (${duration}ms)${isVideoData ? ' [VIDEO]' : ''}`); } private shouldLogResponse(status: number, isVideoData: boolean): boolean { // Always log errors if (status >= 400 && this.config.logErrors) { return true; } // Log all status codes if configured if (this.config.logAllStatusCodes) { return true; } // Don't log video data unless specifically enabled if (isVideoData && !this.config.logVideoData) { return false; } // Log successful responses return status >= 200 && status < 300; } private isVideoData(url: string, headers: Record, body?: HttpBody): boolean { // Check URL patterns if (url.includes('/video') || url.includes('/stream') || url.includes('/media')) { return true; } // Check content type headers const contentType = headers['content-type'] || headers['Content-Type'] || ''; if (contentType.includes('video/') || contentType.includes('audio/') || contentType.includes('application/octet-stream')) { return true; } // Check for large binary data in body if (body && typeof body === 'string' && body.length > 10000) { // Check if it looks like base64 encoded video/audio data if (/^[A-Za-z0-9+/]*={0,2}$/.test(body) && body.length > 50000) { return true; } } return false; } private logError(logEntry: TavusLogEntry): void { const errorInfo = { method: logEntry.request.method, url: logEntry.request.url, status: logEntry.response.status, statusText: logEntry.response.statusText, duration: logEntry.response.duration, timestamp: logEntry.timestamp, sessionId: logEntry.sessionId, requestId: logEntry.metadata?.requestId, headers: logEntry.response.headers, body: logEntry.response.body, raw: logEntry.raw }; console.error(`[TavusLogger] Error: ${logEntry.request.method} ${logEntry.request.url} -> ${logEntry.response.status}`, errorInfo); // Log detailed error information if enabled if (this.config.logStackTraces) { console.error(`[TavusLogger] Error Stack Trace:`, new Error().stack); } } private async flushBuffer(): Promise { if (this.logBuffer.length === 0) return; // Send logs to the local log server const logServerUrl = 'http://localhost:3002'; try { // Prepare entries for the log server const entries = this.logBuffer.map(entry => ({ method: entry.request.method, url: entry.request.url, headers: entry.request.headers, body: entry.request.body, status: entry.response.status, responseHeaders: entry.response.headers, responseBody: entry.response.body, duration: entry.response.duration })); // Send to log server const response = await fetch(`${logServerUrl}/log/batch`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ entries }) }); if (response.ok) { const result = await response.json(); console.log(`[TavusLogger] Sent ${this.logBuffer.length} logs to server:`, result); } else { console.warn(`[TavusLogger] Failed to send logs to server: ${response.status}`); // Fallback to console logging this.logBuffer.forEach((entry, index) => { console.log(`[TavusLogger] Entry ${index + 1}:`, entry); }); } } catch (error) { console.error('[TavusLogger] Failed to send logs to server:', error); // Fallback to console logging console.group(`[TavusLogger] Flushed ${this.logBuffer.length} log entries (console fallback)`); this.logBuffer.forEach((entry, index) => { console.log(`Entry ${index + 1}:`, entry); }); console.groupEnd(); } this.logBuffer = []; } logStreamingEvent( method: string, url: string, eventType: string, data: unknown ): 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, statusText: 'OK', headers: { 'content-type': 'text/event-stream' }, body: { eventType, data }, bodySize: JSON.stringify({ eventType, data }).length, bodyType: 'object', duration: 0, ok: true, redirected: false, type: 'default' }, metadata: { endpoint: new URL(url).pathname, requestType: 'streaming', hasBinaryData: false } }; this.logBuffer.push(logEntry); console.log(`[TavusLogger] Streaming event: ${eventType}`, data); } getSessionSummary(): SessionSummary { 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; } // In browser, we'll log to console and offer download const sessionData = JSON.stringify(sessionRequests, null, 2); console.log(`[TavusLogger] Session ${targetSessionId} exported:`, sessionRequests); // Create downloadable file const blob = new Blob([sessionData], { type: 'application/json' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = `tavus-session-${targetSessionId}-${Date.now()}.json`; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url); console.log(`[TavusLogger] Session ${targetSessionId} downloaded with ${sessionRequests.length} requests`); } destroy(): void { if (this.flushInterval) { clearInterval(this.flushInterval); } void this.flushBuffer(); } private pendingRequests = new Map(); } // Singleton instance let loggerInstance: TavusLoggerBrowser | null = null; export function getTavusLogger(config?: Partial): TavusLoggerBrowser { if (!loggerInstance) { loggerInstance = new TavusLoggerBrowser(config); } return loggerInstance; } export function destroyTavusLogger(): void { if (loggerInstance) { loggerInstance.destroy(); loggerInstance = null; } } // Environment-based configuration const isDevelopment = typeof process !== 'undefined' ? process.env.NODE_ENV === 'development' : true; // 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.) const shouldLogRequests = (typeof process !== 'undefined' && process.env.TAVUS_LOG_REQUESTS === 'true' || isDevelopment) && isLocalhost; if (shouldLogRequests) { getTavusLogger({ enabled: true, includeHeaders: true, includeBody: true, logVideoData: false, // Set to true to log video data logErrors: true, logAllStatusCodes: true, sampleLargePayloads: true, maxVideoPayloadSize: 1024 * 10 // 10KB for video payloads }); }