/** * @file Memory Guardian System * @description PhD-level proactive memory management with automatic leak prevention, * cleanup orchestration, and memory pressure handling for React applications. * * Features: * - Real-time memory pressure monitoring * - Automatic cleanup orchestration * - Component memory budget tracking * - Leak detection and prevention * - GC hint coordination * - Subscription and listener tracking * - WeakRef-based cache management */ /** * Memory pressure levels */ export type MemoryPressureLevel = 'normal' | 'moderate' | 'critical'; /** * Memory snapshot */ export interface MemorySnapshot { /** Used JS heap size in bytes */ usedJSHeapSize: number; /** Total JS heap size in bytes */ totalJSHeapSize: number; /** Heap size limit in bytes */ jsHeapSizeLimit: number; /** Usage percentage (0-100) */ usagePercent: number; /** Current pressure level */ pressureLevel: MemoryPressureLevel; /** Timestamp */ timestamp: number; } /** * Cleanup handler registration */ export interface CleanupHandler { /** Unique identifier */ id: string; /** Cleanup priority (higher runs first) */ priority: number; /** The cleanup function */ cleanup: () => void | Promise; /** Component or context name */ context?: string; /** Estimated memory freed */ estimatedBytes?: number; } /** * Memory budget for a component */ export interface ComponentMemoryBudget { /** Component identifier */ componentId: string; /** Maximum allowed memory in bytes */ maxBytes: number; /** Current usage in bytes */ currentBytes: number; /** Warning threshold (0-1) */ warningThreshold: number; /** Cleanup callback when exceeded */ onExceed?: () => void; } /** * Subscription tracker entry */ export interface TrackedSubscription { /** Unique ID */ id: string; /** Subscription type */ type: 'event' | 'interval' | 'timeout' | 'observer' | 'websocket' | 'custom'; /** Context/component name */ context: string; /** Unsubscribe function */ unsubscribe: () => void; /** Creation timestamp */ createdAt: number; /** Whether it's been cleaned up */ cleaned: boolean; } /** * Memory guardian configuration */ export interface MemoryGuardianConfig { /** Enable automatic monitoring */ autoMonitor?: boolean; /** Monitoring interval in ms */ monitorInterval?: number; /** Moderate pressure threshold (0-1) */ moderateThreshold?: number; /** Critical pressure threshold (0-1) */ criticalThreshold?: number; /** Enable automatic cleanup on pressure */ autoCleanup?: boolean; /** Enable debug logging */ debug?: boolean; /** Maximum tracked subscriptions */ maxTrackedSubscriptions?: number; } /** * Proactive memory management guardian */ export declare class MemoryGuardian { private static instance; private config; private cleanupHandlers; private componentBudgets; private subscriptions; private memoryHistory; private monitorIntervalId; private pressureCallbacks; private lastPressureLevel; private subscriptionIdCounter; private cleanupIdCounter; constructor(config?: MemoryGuardianConfig); /** * Get singleton instance */ static getInstance(config?: MemoryGuardianConfig): MemoryGuardian; /** * Reset singleton (for testing) */ static reset(): void; /** * Format bytes for display */ static formatBytes(bytes: number): string; /** * Start memory monitoring */ startMonitoring(): void; /** * Stop memory monitoring */ stopMonitoring(): void; /** * Check current memory status */ checkMemory(): MemorySnapshot; /** * Get current memory snapshot */ getMemorySnapshot(): MemorySnapshot; /** * Subscribe to pressure changes */ onPressureChange(callback: (level: MemoryPressureLevel) => void): () => void; /** * Register a cleanup handler */ registerCleanup(cleanup: () => void | Promise, options?: { priority?: number; context?: string; estimatedBytes?: number; }): string; /** * Unregister a cleanup handler */ unregisterCleanup(id: string): boolean; /** * Trigger cleanup based on pressure level */ triggerCleanup(pressureLevel: MemoryPressureLevel): Promise; /** * Set memory budget for a component */ setComponentBudget(componentId: string, budget: Omit): void; /** * Update component memory usage */ updateComponentMemory(componentId: string, bytes: number): void; /** * Remove component budget */ removeComponentBudget(componentId: string): void; /** * Track a subscription for automatic cleanup */ trackSubscription(type: TrackedSubscription['type'], context: string, unsubscribe: () => void): string; /** * Untrack and cleanup a subscription */ untrackSubscription(id: string): boolean; /** * Clean up subscriptions for a context */ cleanupContext(context: string): number; /** * Get subscription statistics */ getSubscriptionStats(): { total: number; byType: Record; byContext: Record; }; /** * Detect potential memory leaks */ detectLeaks(): { potentialLeaks: boolean; growthRate: number; suggestions: string[]; }; /** * Get memory trend */ getMemoryTrend(): 'increasing' | 'stable' | 'decreasing'; /** * Notify pressure change callbacks */ private notifyPressureChange; /** * Hint garbage collection (non-blocking) */ private hintGC; /** * Check all component budgets */ private checkComponentBudgets; /** * Clean stale subscriptions (older than 5 minutes) */ private cleanStaleSubscriptions; /** * Debug logging */ private log; } /** * Hook for component-level memory management */ export declare function useMemoryGuard(componentId: string, options?: { maxBytes?: number; warningThreshold?: number; onExceed?: () => void; }): { updateUsage: (bytes: number) => void; snapshot: MemorySnapshot | null; pressureLevel: MemoryPressureLevel; }; /** * Hook for automatic subscription cleanup */ export declare function useTrackedSubscription(context: string): { track: (type: TrackedSubscription['type'], unsubscribe: () => void) => string; untrack: (id: string) => void; cleanupAll: () => void; }; /** * Hook for registering cleanup handlers */ export declare function useCleanupHandler(cleanup: () => void | Promise, options?: { priority?: number; context?: string; estimatedBytes?: number; }): void; /** * Hook for memory pressure awareness * Performance optimized: memoizes expensive getMemoryTrend() and detectLeaks() calls */ export declare function useMemoryPressureAwareness(): { pressureLevel: MemoryPressureLevel; isUnderPressure: boolean; snapshot: MemorySnapshot | null; trend: 'increasing' | 'stable' | 'decreasing'; leakDetection: { potentialLeaks: boolean; growthRate: number; suggestions: string[]; }; }; /** * Get the global memory guardian instance */ export declare function getMemoryGuardian(config?: MemoryGuardianConfig): MemoryGuardian; /** * Reset the global guardian (for testing) */ export declare function resetMemoryGuardian(): void; /** * Trigger cleanup manually */ export declare function triggerMemoryCleanup(pressureLevel?: MemoryPressureLevel): Promise; /** * Check current memory status */ export declare function checkMemory(): MemorySnapshot; /** * Format bytes helper */ export declare const formatBytes: (bytes: number) => string; declare const _default: { MemoryGuardian: typeof MemoryGuardian; getMemoryGuardian: typeof getMemoryGuardian; resetMemoryGuardian: typeof resetMemoryGuardian; triggerMemoryCleanup: typeof triggerMemoryCleanup; checkMemory: typeof checkMemory; formatBytes: (bytes: number) => string; useMemoryGuard: typeof useMemoryGuard; useTrackedSubscription: typeof useTrackedSubscription; useCleanupHandler: typeof useCleanupHandler; useMemoryPressureAwareness: typeof useMemoryPressureAwareness; }; export default _default;