@ai-growth/nextjs
Version:
Seamlessly integrate Sanity CMS with Next.js applications for automated blog routing and rendering
340 lines • 10.4 kB
TypeScript
/**
* Centralized error logging and monitoring system for AI Growth Next.js
*
* Features:
* - Standardized error capturing and formatting
* - Integration with monitoring services (Sentry, LogRocket, etc.)
* - Context information attachment (user, app state, environment)
* - Error categorization and severity levels
* - Batching for non-critical errors
* - Rate limiting and filtering
* - Performance monitoring
*/
import { type ErrorDetails } from '../components/ErrorBoundary';
/**
* Error severity levels for categorization
*/
export declare enum ErrorSeverity {
LOW = "low",
WARNING = "warning",
ERROR = "error",
CRITICAL = "critical",
FATAL = "fatal"
}
/**
* Error categories for better organization
*/
export declare enum ErrorCategory {
NETWORK = "network",
AUTHENTICATION = "authentication",
VALIDATION = "validation",
PERMISSION = "permission",
RUNTIME = "runtime",
PERFORMANCE = "performance",
UI = "ui",
CMS = "cms",
INTEGRATION = "integration",
UNKNOWN = "unknown"
}
/**
* Environment context information
*/
export interface EnvironmentContext {
/** Current environment (development, staging, production) */
environment: string;
/** Application version */
version: string;
/** Build number or commit hash */
buildId?: string | undefined;
/** Feature flags that are enabled */
featureFlags?: Record<string, boolean> | undefined;
/** A/B test variants */
experiments?: Record<string, string> | undefined;
}
/**
* User context information
*/
export interface UserContext {
/** User ID (anonymized if needed) */
userId?: string;
/** User role or permissions level */
role?: string;
/** User preferences that might affect errors */
preferences?: Record<string, any>;
/** Session ID for tracking user sessions */
sessionId?: string;
/** User agent string */
userAgent?: string;
/** IP address (anonymized) */
ipAddress?: string;
}
/**
* Application state context
*/
export interface ApplicationContext {
/** Current route/page */
route?: string | undefined;
/** Previous route for navigation context */
previousRoute?: string | undefined;
/** Component that triggered the error */
component?: string | undefined;
/** Action that led to the error */
action?: string | undefined;
/** Redux/state store snapshot (sanitized) */
stateSnapshot?: Record<string, any> | undefined;
/** Recent user interactions */
userInteractions?: Array<{
type: string;
timestamp: Date;
element?: string | undefined;
data?: any;
}>;
}
/**
* Performance context information
*/
export interface PerformanceContext {
/** Page load time */
pageLoadTime?: number;
/** Memory usage */
memoryUsage?: {
used: number;
total: number;
percentage: number;
};
/** Network connection information */
connection?: {
effectiveType?: string;
downlink?: number;
rtt?: number;
};
/** Render performance metrics */
renderMetrics?: {
timeToFirstByte?: number;
firstContentfulPaint?: number;
largestContentfulPaint?: number;
cumulativeLayoutShift?: number;
};
}
/**
* Complete error context with all available information
*/
export interface ErrorContext {
/** Environment information */
environment?: EnvironmentContext;
/** User information */
user?: UserContext;
/** Application state */
application?: ApplicationContext;
/** Performance metrics */
performance?: PerformanceContext;
/** Custom context data */
custom?: Record<string, any>;
}
/**
* Standardized error log entry
*/
export interface ErrorLogEntry {
/** Unique identifier for this error occurrence */
id: string;
/** When the error occurred */
timestamp: Date;
/** Error severity level */
severity: ErrorSeverity;
/** Error category */
category: ErrorCategory;
/** Error message */
message: string;
/** Error name/type */
name: string;
/** Stack trace */
stack?: string | undefined;
/** File where error occurred */
filename?: string | undefined;
/** Line number where error occurred */
lineNumber?: number | undefined;
/** Column number where error occurred */
columnNumber?: number | undefined;
/** Complete context information */
context: ErrorContext;
/** Additional metadata */
metadata?: Record<string, any> | undefined;
/** Whether this error has been sent to monitoring service */
transmitted?: boolean | undefined;
/** Number of times this exact error has occurred */
occurrenceCount?: number | undefined;
/** Hash for deduplication */
fingerprint?: string | undefined;
}
/**
* Configuration for error logging behavior
*/
export interface ErrorLoggerConfig {
/** Whether logging is enabled */
enabled: boolean;
/** Maximum number of errors to store locally */
maxStoredErrors: number;
/** Batch size for sending errors to monitoring service */
batchSize: number;
/** How often to send batches (milliseconds) */
batchInterval: number;
/** Whether to capture console errors */
captureConsoleErrors: boolean;
/** Whether to capture unhandled promise rejections */
captureUnhandledRejections: boolean;
/** Whether to capture window errors */
captureWindowErrors: boolean;
/** Minimum severity level to log */
minSeverity: ErrorSeverity;
/** Rate limiting: max errors per minute */
maxErrorsPerMinute: number;
/** Whether to include stack traces */
includeStackTrace: boolean;
/** Whether to include performance context */
includePerformanceContext: boolean;
/** Custom error filters */
errorFilters?: Array<(error: Error) => boolean>;
/** Custom context providers */
contextProviders?: Array<() => Partial<ErrorContext>>;
}
/**
* Interface for monitoring service integrations
*/
export interface MonitoringService {
/** Service name */
name: string;
/** Initialize the service */
initialize: (config: any) => Promise<void>;
/** Send a single error */
reportError: (entry: ErrorLogEntry) => Promise<void>;
/** Send multiple errors in batch */
reportErrors: (entries: ErrorLogEntry[]) => Promise<void>;
/** Set user context */
setUserContext: (context: UserContext) => void;
/** Set custom context */
setCustomContext: (context: Record<string, any>) => void;
/** Check if service is available */
isAvailable: () => boolean;
}
/**
* Sentry monitoring service integration
*/
export declare class SentryMonitoringService implements MonitoringService {
name: string;
private initialized;
initialize(config: {
dsn: string;
environment?: string;
release?: string;
}): Promise<void>;
reportError(entry: ErrorLogEntry): Promise<void>;
reportErrors(entries: ErrorLogEntry[]): Promise<void>;
setUserContext(context: UserContext): void;
setCustomContext(context: Record<string, any>): void;
isAvailable(): boolean;
private mapSeverityToSentryLevel;
}
/**
* Console monitoring service (for development and fallback)
*/
export declare class ConsoleMonitoringService implements MonitoringService {
name: string;
initialize(): Promise<void>;
reportError(entry: ErrorLogEntry): Promise<void>;
reportErrors(entries: ErrorLogEntry[]): Promise<void>;
setUserContext(context: UserContext): void;
setCustomContext(context: Record<string, any>): void;
isAvailable(): boolean;
private getConsoleMethod;
}
/**
* Centralized error logging and monitoring system
*/
export declare class ErrorLogger {
private config;
private errorStore;
private batchTimer;
private rateLimitCounts;
private monitoringServices;
private contextProviders;
constructor(config?: Partial<ErrorLoggerConfig>);
/**
* Add a monitoring service integration
*/
addMonitoringService(service: MonitoringService): void;
/**
* Add a custom context provider
*/
addContextProvider(provider: () => Partial<ErrorContext>): void;
/**
* Log an error with additional context
*/
logError(error: Error, severity?: ErrorSeverity, category?: ErrorCategory, customContext?: Partial<ErrorContext>): Promise<void>;
/**
* Process a batch of errors to send to monitoring services
*/
private processBatch;
/**
* Setup window error listeners - safely for tests
*/
private setupGlobalErrorHandlers;
/**
* Retrieve errors by category
*/
getErrorsByCategory(category: ErrorCategory): ErrorLogEntry[];
/**
* Retrieve errors by severity
*/
getErrorsBySeverity(severity: ErrorSeverity): ErrorLogEntry[];
/**
* Get stored errors array (for testing)
*/
getStoredErrors(): ErrorLogEntry[];
/**
* Clear all stored errors
*/
clearStoredErrors(): void;
/**
* Manually flush pending errors
*/
flushErrors(): Promise<void>;
/**
* Update configuration
*/
updateConfig(newConfig: Partial<ErrorLoggerConfig>): void;
/**
* Get current configuration
*/
getConfig(): ErrorLoggerConfig;
private startBatchProcessor;
private gatherContext;
private transmitError;
private transmitErrors;
private getSeverityLevel;
/**
* Log an error from ErrorBoundary
*/
logErrorBoundaryError(errorDetails: ErrorDetails): Promise<void>;
}
/**
* Default error logger instance
*/
export declare const errorLogger: ErrorLogger;
/**
* Log an error with automatic categorization
*/
export declare function logError(error: Error, customContext?: Partial<ErrorContext>): Promise<void>;
/**
* Log a warning
*/
export declare function logWarning(message: string, customContext?: Partial<ErrorContext>): Promise<void>;
/**
* Log a critical error
*/
export declare function logCriticalError(error: Error, category?: ErrorCategory, customContext?: Partial<ErrorContext>): Promise<void>;
/**
* Create a custom error logger with specific configuration
*/
export declare function createErrorLogger(config: Partial<ErrorLoggerConfig>): ErrorLogger;
export default errorLogger;
//# sourceMappingURL=ErrorLogger.d.ts.map