declare module 'api-reporter' { // ============================================================================= // Core Types // ============================================================================= /** * Main API Reporter class and default export */ export interface ApiReporter { /** * Initialize the API Reporter with configuration * Now supports dynamic configuration fetching from backend */ init(config: ApiReporterConfig): Promise; /** * Destroy the reporter and clean up resources */ destroy(): void; /** * Log a custom event */ logEvent(data: CustomEventData): void; /** * Set user profile data */ setUserProfile(profile: UserProfile): void; /** * Get current user profile */ getUserProfile(): UserProfile; /** * Force send all queued events */ sendEvents(): Promise; /** * Clear all queued events */ clearEvents(): void; /** * Toggle debug mode */ debugMode(enabled: boolean): void; /** * Get current queue status */ getQueueStatus(): QueueStatus; /** * Get performance metrics (if performance monitoring enabled) */ getPerformanceMetrics(): PerformanceMetrics | null; /** * Get P1 Flow Monitor instance (if P1 monitoring enabled) */ getP1FlowMonitor(): P1FlowMonitor | null; /** * Get Core Web Vitals Monitor instance (if Core Web Vitals monitoring enabled) */ getCoreWebVitalsMonitor(): CoreWebVitalsMonitor | null; /** * Get current Core Web Vitals metrics */ getCoreWebVitalsMetrics(): CoreWebVitalsMetrics | null; /** * Get Core Web Vitals performance insights */ getCoreWebVitalsInsights(): CoreWebVitalsInsights | null; /** * Generate a comprehensive Core Web Vitals report */ generateCoreWebVitalsReport(): CoreWebVitalsReport | null; /** * Update Core Web Vitals thresholds */ updateCoreWebVitalsThresholds(thresholds: Partial): void; /** * Check if an endpoint should be monitored */ isMonitoredEndpoint(url: string): boolean; /** * Check if fields should be extracted from URL and source */ shouldExtractFields(url: string, source: string): boolean; /** * Extract user context from response/request data */ extractUserContextFromBody(params: { data: any; source: 'request' | 'response'; url: string; }): Record; } // ============================================================================= // Configuration Types // ============================================================================= export interface ApiReporterConfig { /** * Remote configuration URL for dynamic config fetching * If provided, the reporter will fetch configuration from this endpoint * @example '/api/reporter-config' */ remoteConfigUrl?: string; /** * Alternative name for remote configuration URL (legacy support) * @deprecated Use remoteConfigUrl instead */ backendConfigUrl?: string; /** * URL patterns to monitor (e.g., ['/api/', '/graphql'] or ['*']) * Can be overridden by remote configuration */ endpoints?: string[] | string; /** * Domains to track (e.g., ['api.example.com']) * Supports dynamic expressions like 'window.location.hostname' which will be evaluated at runtime * Can be overridden by remote configuration */ domainsToTrack?: string[] | string; /** * Service configuration - either service name or custom service instance */ service: 'sumologic' | CustomService; /** * Service-specific options */ serviceOptions?: ServiceOptions; /** * Application name for event tagging */ appName?: string; /** * Environment (e.g., 'development', 'staging', 'production') */ environment?: string; /** * Enable debug logging */ debug?: boolean; /** * Enable performance monitoring */ monitorPerformance?: boolean; /** * Threshold for slow request detection (milliseconds) * @default 2000 */ slowRequestThreshold?: number; /** * Threshold for average response time alerts (milliseconds) * @default 2500 */ averageAlertThreshold?: number; /** * Enable resource error monitoring (CSS, JS, images) */ logResourceErrors?: boolean; /** * Log OPTIONS preflight requests */ logPreflight?: boolean; /** * PostMessage monitoring configuration */ monitorPostMessages?: PostMessageConfig; /** * Enable P1 Flow Monitoring */ enableP1FlowMonitoring?: boolean; /** * P1 Flow configuration */ p1Config?: P1FlowConfig; /** * Enable Core Web Vitals monitoring * @default true */ enableCoreWebVitals?: boolean; /** * Core Web Vitals configuration */ coreWebVitalsConfig?: CoreWebVitalsConfig; /** * Rules for extracting user data from API responses */ fieldsToExtract?: FieldExtractionRule[]; /** * Maximum number of events in queue * @default 1000 */ maxQueueSize?: number; /** * Number of events to send per batch * @default 10 */ batchSize?: number; /** * Retry interval in milliseconds * @default 30000 */ retryIntervalMs?: number; /** * Event deduplication window in milliseconds * @default 60000 */ deduplicationWindowMs?: number; /** * Maximum retry attempts for failed events * @default 3 */ maxRetries?: number; /** * Event types to ignore */ ignoreEventTypes?: string[]; /** * LocalStorage keys to include in event context */ localStorageEnrichmentKeys?: string[]; /** * Function to add custom user data to events */ addCustomUserData?: () => Record; } // ============================================================================= // Service Types // ============================================================================= export interface CustomService { /** * Send an event to the service */ send(event: ApiEvent): Promise; /** * Optional: Update debug mode */ updateDebugMode?(debug: boolean): void; } export interface ServiceOptions { /** * Service endpoint URL (required for SumoLogic) */ endpoint?: string; /** * API key or authentication token */ apiKey?: string; /** * Additional service-specific options */ [key: string]: any; } // ============================================================================= // PostMessage Configuration // ============================================================================= export interface PostMessageConfig { /** * Whitelist of allowed origins ('*' allows all) */ postMessageOriginWhitelist?: string[]; /** * Event types to exclude from monitoring */ excludePostMessagesEvents?: string[]; /** * Specific event types to monitor (empty = monitor all) */ monitorSpecificPostMessagesEvents?: string[]; } // ============================================================================= // P1 Flow Monitoring // ============================================================================= export interface P1FlowConfig { /** * Enable P1 monitoring */ enabled?: boolean; /** * Flow definitions */ flows?: P1Flow[]; /** * Capture screenshots during P1 incidents * @default true */ captureScreenshot?: boolean; /** * Screenshot scale factor (0.1 - 1.0) * @default 0.5 */ screenshotScale?: number; /** * Screenshot quality (0.1 - 1.0) * @default 0.7 */ screenshotQuality?: number; /** * Maximum screenshot size in bytes * @default 500000 */ maxScreenshotSize?: number; /** * Maximum inline screenshot size (larger ones uploaded separately) * @default 100000 */ maxInlineScreenshotSize?: number; /** * Capture DOM snapshots * @default false */ captureDomSnapshot?: boolean; /** * Capture console errors * @default true */ captureConsoleErrors?: boolean; /** * Maximum console errors to store * @default 50 */ maxConsoleErrors?: number; /** * Real-time notification API endpoint */ realTimeNotificationApi?: string; /** * Screenshot upload endpoint (for large screenshots) */ screenshotUploadEndpoint?: string; /** * API key for notifications and uploads */ apiKey?: string; } export interface P1Flow { /** * Flow identifier (e.g., 'checkout', 'login') */ flow: string; /** * Enable this flow */ enabled: boolean; /** * Number of failures to trigger P1 alert * @default 1 */ failureThreshold?: number; /** * Time window for flow completion (milliseconds) * @default 30000 */ completionWindow?: number; /** * Critical API endpoints (any failure triggers immediate P1) */ criticalEndpoints?: string[]; /** * Critical PostMessage events (any occurrence triggers immediate P1) */ criticalPostMessageEvents?: string[]; /** * URL patterns to exclude from this flow */ exclude?: string[]; } export interface P1FlowMonitor { /** * Track an HTTP request for P1 monitoring */ trackRequest(request: RequestData): void; /** * Track a PostMessage event for P1 monitoring */ trackPostMessage(event: PostMessageEvent): void; /** * Check if URL belongs to a P1 flow */ isP1Flow(url: string): P1Flow | null; /** * Get the current active flow */ getCurrentFlow(): P1Flow | null; /** * Update P1 configuration */ updateConfig(config: P1FlowConfig): void; /** * Capture visual context (screenshot, DOM, etc.) */ captureP1Context(): Promise; /** * Destroy and clean up */ destroy(): void; } // ============================================================================= // Field Extraction // ============================================================================= export interface FieldExtractionRule { /** * API URL pattern to match ('*' matches all) */ api: string; /** * Source to extract from ('request', 'response', or '*') */ source: 'request' | 'response' | '*'; /** * Fields to extract - can be: * - Array of field names * - Object mapping new names to original names * - Array of regex patterns */ fields: string[] | Record | RegExp[]; } // ============================================================================= // Event Types // ============================================================================= export interface ApiEvent { /** * Unique event identifier */ id: string; /** * Event type */ type: EventType; /** * Event timestamp */ timestamp: number; /** * Application version */ appVersion: string; /** * Application name */ appName: string; /** * Environment */ environment: string; /** * Source interceptor */ interceptor: 'fetch' | 'xhr' | 'resource' | 'postMessage' | 'manual'; /** * Request details */ request: RequestData; /** * Event context and metadata */ context: EventContext; /** * Performance data (if available) */ performance?: PerformanceData; /** * P1 incident data (for P1 events) */ p1Data?: P1IncidentData; /** * Metrics data */ metrics?: Record; /** * Event severity */ severity?: 'low' | 'medium' | 'high' | 'critical'; /** * Custom message */ message?: string; /** * PostMessage event type (for PostMessage events) */ postMessageEvent?: string; } export interface CustomEventData { /** * Event type */ type: string; /** * Optional request data */ request?: Partial; /** * Event context */ context?: Record; /** * Additional event data */ extraData?: Record; /** * Performance data */ performance?: PerformanceData; /** * P1 data (for P1 incidents) */ p1Data?: P1IncidentData; /** * Metrics */ metrics?: Record; /** * Severity level */ severity?: string; /** * Custom message */ message?: string; } export interface RequestData { /** * HTTP method */ method: string; /** * Request URL */ url: string; /** * Domain name */ domain: string; /** * URL path */ path: string; /** * HTTP status code */ status: number; /** * HTTP status text */ statusText: string; /** * Response data */ response: any; /** * Request/response headers */ headers?: Record; /** * Source interceptor */ interceptor: string; } export interface EventContext { /** * Script origin */ scriptOrigin: string; /** * Script origin path */ scriptOriginPath: string; /** * Current page URL */ pageUrl: string; /** * User agent string */ userAgent: string; /** * Whether endpoint is monitored */ isMonitored: boolean; /** * Force log this event */ forceLog?: boolean; /** * User profile data */ user: UserProfile; /** * LocalStorage context data */ localStorage: Record; /** * Additional context fields */ [key: string]: any; } export interface UserProfile { /** * Unique user identifier */ uniqId?: string; /** * User ID */ userId?: string; /** * Email address */ email?: string; /** * User role */ role?: string; /** * Profile creation timestamp */ createdAt?: string; /** * Additional user fields */ [key: string]: any; } // ============================================================================= // Performance Types // ============================================================================= export interface PerformanceData { /** * Request duration in milliseconds */ duration: number; /** * Request duration in seconds */ durationSeconds: number; /** * Performance threshold */ threshold?: number; /** * Endpoint pattern */ endpoint?: string; } export interface PerformanceMetrics { /** * Average request duration (ms) */ average: number; /** * Average request duration (seconds) */ averageSeconds: number; /** * Median request duration (ms) */ median: number; /** * Median request duration (seconds) */ medianSeconds: number; /** * Total number of requests */ totalRequests: number; /** * Number of slow requests */ slowRequests: number; /** * Percentage of slow requests */ slowRequestPercentage: number; /** * Slowest endpoints */ slowestEndpoints: SlowEndpoint[]; /** * Session duration */ sessionDuration: number; } export interface SlowEndpoint { /** * Endpoint pattern */ endpoint: string; /** * Average duration in seconds */ avgDuration: number; /** * Number of requests */ requestCount: number; } // ============================================================================= // P1 Types // ============================================================================= export interface P1IncidentData { /** * Flow identifier */ flow: string; /** * Failure reason */ reason: string; /** * Failed endpoints/events */ failedEndpoints: FailedEndpoint[]; /** * Flow configuration */ flowConfig: { failureThreshold: number; criticalEndpoints?: string[]; criticalPostMessageEvents?: string[]; }; /** * User context at time of incident */ userContext: UserProfile; /** * Visual context data */ visualContext: { hasScreenshot: boolean; screenshotSize: number; hasDomSnapshot: boolean; domSnapshotSize: number; consoleErrorCount: number; viewport: ViewportInfo; performanceMetrics: Record; }; } export interface FailedEndpoint { /** * URL or origin */ url: string; /** * HTTP status or 0 for PostMessage */ status: number; /** * HTTP method or 'POSTMESSAGE' */ method: string; /** * Event type (for PostMessage) */ eventType?: string; /** * Type of failure */ type: 'http' | 'postMessage'; /** * Whether this endpoint is marked as critical for the flow */ isCritical?: boolean; } export interface VisualContext { /** * Base64 encoded screenshot */ screenshot: string | null; /** * HTML DOM snapshot */ domSnapshot: string | null; /** * Recent console errors */ consoleErrors: ConsoleError[]; /** * Performance metrics */ performanceMetrics: Record; /** * Viewport information */ viewport: ViewportInfo; /** * Capture timestamp */ timestamp: number; } export interface ConsoleError { /** * Error timestamp */ timestamp: number; /** * Error message */ message: string; } export interface ViewportInfo { /** * Viewport width */ width: number; /** * Viewport height */ height: number; /** * Device pixel ratio */ devicePixelRatio: number; } export interface PostMessageEvent { /** * Event type detected */ eventType: string; /** * Message origin */ origin: string; /** * Message direction */ direction: 'incoming' | 'outgoing'; /** * Event timestamp */ timestamp: number; } // ============================================================================= // Status Types // ============================================================================= export interface QueueStatus { /** * Number of events in queue */ queueSize: number; /** * Whether events are currently being sent */ isSending: boolean; /** * Whether reporter is initialized */ isInitialized: boolean; /** * Active service name */ service: string; /** * Configuration source ('backend', 'local', 'backend+local') */ configSource: string; /** * Configuration version from backend */ configVersion: string; } // ============================================================================= // Event Type Constants // ============================================================================= export type EventType = | 'fetch_http_error' | 'fetch_network_error' | 'fetch_silent_login_failure' | 'fetch_slow_request' | 'xhr_http_error' | 'xhr_network_error' | 'xhr_timeout_error' | 'xhr_aborted_error' | 'xhr_silent_login_failure' | 'xhr_slow_request' | 'resource_load_error' | 'postmessage_communication' | 'postmessage_cross_origin' | 'postmessage_large_payload' | 'postmessage_suspicious_origin' | 'postmessage_error' | 'performance_degradation_alert' | 'p1_incident_alert' | 'core_web_vital' | 'custom_api_error' | 'unknown_error' | string; // Allow custom event types // ============================================================================= // Core Web Vitals Types // ============================================================================= export interface CoreWebVitalsMetricsConfig { lcp: boolean; fid: boolean; cls: boolean; inp: boolean; ttfb: boolean; fcp: boolean; } export type PartialCoreWebVitalsMetricsConfig = Partial; export type CoreWebVitalsMetricType = 'lcp' | 'fid' | 'cls' | 'inp' | 'ttfb' | 'fcp'; export interface CoreWebVitalsConfig { /** * Whether to use the web-vitals library for measurements * @default true */ useWebVitalsLibrary?: boolean; /** * Whether to collect LCP (Largest Contentful Paint) metrics * @default true */ collectLCP?: boolean; /** * Whether to collect FID (First Input Delay) metrics * @default true */ collectFID?: boolean; /** * Whether to collect CLS (Cumulative Layout Shift) metrics * @default true */ collectCLS?: boolean; /** * Whether to collect INP (Interaction to Next Paint) metrics * @default true */ collectINP?: boolean; /** * Whether to collect TTFB (Time to First Byte) metrics * @default true */ collectTTFB?: boolean; /** * Whether to collect FCP (First Contentful Paint) metrics * @default true */ collectFCP?: boolean; /** * Metric collection settings object * @default { lcp: true, fid: true, cls: true, inp: true, ttfb: true, fcp: true } */ collectMetrics?: PartialCoreWebVitalsMetricsConfig; /** * Whether reporting is enabled * @default true */ reportingEnabled?: boolean; /** * Threshold for reporting metrics * @default 'needsImprovement' */ reportThreshold?: 'good' | 'needsImprovement' | 'poor'; /** * Custom thresholds for Core Web Vitals */ thresholds?: Partial; /** * Enable debug mode * @default false */ debug?: boolean; } export interface CoreWebVitalsThresholds { lcp: { good: number; needsImprovement: number }; fid: { good: number; needsImprovement: number }; cls: { good: number; needsImprovement: number }; inp: { good: number; needsImprovement: number }; ttfb: { good: number; needsImprovement: number }; fcp: { good: number; needsImprovement: number }; } export interface CoreWebVitalsMetric { type: CoreWebVitalsMetricType; value: number; id: string; timestamp: number; rating: 'good' | 'needs-improvement' | 'poor'; delta?: number; entries?: number; navigationType?: string; element?: string; url?: string; eventType?: string; interactionId?: number; fallback?: boolean; } export interface CoreWebVitalsMetrics { [key: string]: CoreWebVitalsMetric; } export interface CoreWebVitalsInsights { overall: 'good' | 'needs-improvement' | 'poor'; issues: string[]; recommendations: string[]; summary: { [key: string]: { value: number; rating: 'good' | 'needs-improvement' | 'poor'; threshold: { good: number; needsImprovement: number }; }; }; score: number; } export interface CoreWebVitalsReport { timestamp: number; url: string; userAgent: string; metrics: CoreWebVitalsMetrics; insights: CoreWebVitalsInsights; thresholds: CoreWebVitalsThresholds; config: { collectMetrics: CoreWebVitalsMetricsConfig; reportThreshold: string; useWebVitalsLibrary: boolean; }; } export interface CoreWebVitalsMonitor { /** * Get all collected metrics */ getAllMetrics(): CoreWebVitalsMetrics; /** * Get a specific metric */ getMetric(type: string): CoreWebVitalsMetric | undefined; /** * Register a callback for metric updates */ onMetric(callback: (metric: CoreWebVitalsMetric) => void): void; /** * Get performance insights */ getPerformanceInsights(): CoreWebVitalsInsights; /** * Generate a comprehensive report */ generateReport(): CoreWebVitalsReport; /** * Get current thresholds */ getThresholds(): CoreWebVitalsThresholds; /** * Update thresholds */ updateThresholds(thresholds: Partial): void; /** * Destroy the monitor and clean up resources */ destroy(): void; } // ============================================================================= // Global Window Extension // ============================================================================= export interface Window { /** * Global API Reporter instance */ apiReporter: ApiReporter; } // ============================================================================= // Default Export // ============================================================================= const apiReporter: ApiReporter; export default apiReporter; } // ============================================================================= // Global Declaration // ============================================================================= declare global { interface Window { apiReporter: import('api-reporter').ApiReporter; } } export {};