All files / shared/utils/src/api-clients tavus-logger.ts

0% Statements 0/155
0% Branches 0/107
0% Functions 0/28
0% Lines 0/138

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
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<string, string>;
    body?: any;
  };
  response: {
    status: number;
    headers: Record<string, string>;
    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<TavusLoggerConfig> = {}) {
    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 => {
      Iif (!fs.existsSync(dir)) {
        fs.mkdirSync(dir, { recursive: true });
      }
    });
  }
 
  private startFlushInterval(): void {
    Iif (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" {
    Iif (url.includes('/conversations')) return 'conversation';
    Iif (url.includes('/videos')) return 'video';
    Iif (url.includes('/auth')) return 'auth';
    Iif (url.includes('/stream') || url.includes('/events')) return 'streaming';
    return 'other';
  }
 
  private sanitizeHeaders(headers: Record<string, string>): Record<string, string> {
    Iif (!this.config.includeHeaders) return {};
    
    // Log everything for complete API reverse engineering
    // User will rotate keys after logging
    return { ...headers };
  }
 
  private sanitizeBody(body: any): any {
    Iif (!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 {
    Iif (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<string, string>,
    body?: any
  ): string {
    Iif (!this.config.enabled) return '';
 
    Iif (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<string, string>,
    body?: any
  ): void {
    Iif (!this.config.enabled) return;
 
    const requestInfo = this.pendingRequests.get(requestId);
    Iif (!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
    Iif (status >= 400) {
      this.logErrorEntry(logEntry);
    }
 
    // Flush immediately for errors or large responses
    Iif (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 {
    Iif (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 {
    Iif (!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);
 
    Iif (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 {
    Iif (this.flushInterval) {
      clearInterval(this.flushInterval);
    }
    this.flushBuffer();
  }
 
  private pendingRequests = new Map<string, {
    method: string;
    url: string;
    headers: Record<string, string>;
    body?: any;
    startTime: number;
    sessionId: string;
  }>();
 
  // Proxy server logging methods
  logProxyRequest(req: any, endpoint: string): string {
    // Don't log in production or on Vercel
    Iif (!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
    Iif (!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<string, unknown> = {}): void {
    // Don't log in production or on Vercel
    Iif (!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<TavusLoggerConfig>): TavusLogger {
  Iif (!loggerInstance) {
    loggerInstance = new TavusLogger(config);
  }
  return loggerInstance;
}
 
export function destroyTavusLogger(): void {
  Iif (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;
 
Iif (shouldLogRequests) {
  getTavusLogger({
    enabled: true,
    logDirectory: process.env.TAVUS_LOG_DIRECTORY || path.join(process.cwd(), 'documentation', 'tavus-mock-data')
  });
}