@usefy/use-memory-monitor 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,537 @@
1
+ /**
2
+ * Memory information at a point in time
3
+ */
4
+ interface MemoryInfo {
5
+ /** Used JS heap size in bytes */
6
+ heapUsed: number;
7
+ /** Total JS heap size in bytes */
8
+ heapTotal: number;
9
+ /** JS heap size limit in bytes */
10
+ heapLimit: number;
11
+ /** Timestamp when this measurement was taken */
12
+ timestamp: number;
13
+ }
14
+ /**
15
+ * A named memory snapshot for comparison
16
+ */
17
+ interface MemorySnapshot {
18
+ /** Unique identifier for this snapshot */
19
+ id: string;
20
+ /** Memory information at snapshot time */
21
+ memory: MemoryInfo;
22
+ /** Number of DOM nodes (if tracking enabled) */
23
+ domNodes?: number;
24
+ /** Estimated event listener count (if tracking enabled) */
25
+ eventListeners?: number;
26
+ /** Timestamp when snapshot was taken */
27
+ timestamp: number;
28
+ }
29
+ /**
30
+ * Result of comparing two memory snapshots
31
+ */
32
+ interface SnapshotDiff {
33
+ /** Difference in heap usage (bytes) */
34
+ heapDelta: number;
35
+ /** Percentage change in heap usage */
36
+ heapPercentChange: number;
37
+ /** Difference in DOM node count */
38
+ domNodesDelta?: number;
39
+ /** Difference in event listener count */
40
+ eventListenersDelta?: number;
41
+ /** Time elapsed between snapshots (ms) */
42
+ timeDelta: number;
43
+ }
44
+ /**
45
+ * Result of memory leak analysis
46
+ */
47
+ interface LeakAnalysis {
48
+ /** Whether a memory leak is detected */
49
+ isLeaking: boolean;
50
+ /** Probability of memory leak (0-100) */
51
+ probability: number;
52
+ /** Memory usage trend */
53
+ trend: Trend;
54
+ /** Average memory growth per interval (bytes) */
55
+ averageGrowth: number;
56
+ /** R-squared value indicating regression fit quality (0-1) */
57
+ rSquared: number;
58
+ /** Samples used for analysis */
59
+ samples: MemoryInfo[];
60
+ /** Human-readable recommendation */
61
+ recommendation?: string;
62
+ }
63
+ /**
64
+ * Information about why memory monitoring is not supported
65
+ */
66
+ interface UnsupportedInfo {
67
+ /** Reason for lack of support */
68
+ reason: UnsupportedReason;
69
+ /** Browser name if detected */
70
+ browser?: string;
71
+ /** Available fallback strategies */
72
+ availableFallbacks: FallbackStrategy[];
73
+ }
74
+ /**
75
+ * Reason why memory API is not supported
76
+ */
77
+ type UnsupportedReason = "no-api" | "server-side" | "insecure-context" | "browser-restriction";
78
+ /**
79
+ * Level of memory API support
80
+ */
81
+ type SupportLevel = "full" | "partial" | "none";
82
+ /**
83
+ * Available memory metrics based on browser support
84
+ */
85
+ type AvailableMetric = "heapUsed" | "heapTotal" | "heapLimit" | "domNodes" | "eventListeners";
86
+ /**
87
+ * Memory usage severity level
88
+ */
89
+ type Severity = "normal" | "warning" | "critical";
90
+ /**
91
+ * Memory usage trend direction
92
+ */
93
+ type Trend = "stable" | "increasing" | "decreasing";
94
+ /**
95
+ * Fallback strategy for unsupported browsers
96
+ */
97
+ type FallbackStrategy = "none" | "estimation" | "dom-only";
98
+ /**
99
+ * Leak detection sensitivity level
100
+ */
101
+ type LeakSensitivity = "low" | "medium" | "high";
102
+ /**
103
+ * Warning data passed to onWarning callback
104
+ */
105
+ interface MemoryWarning {
106
+ /** Current memory info */
107
+ memory: MemoryInfo;
108
+ /** Current usage percentage */
109
+ usagePercentage: number;
110
+ /** Warning threshold that was exceeded */
111
+ threshold: number;
112
+ /** Timestamp of warning */
113
+ timestamp: number;
114
+ }
115
+ /**
116
+ * Critical alert data passed to onCritical callback
117
+ */
118
+ interface MemoryCritical {
119
+ /** Current memory info */
120
+ memory: MemoryInfo;
121
+ /** Current usage percentage */
122
+ usagePercentage: number;
123
+ /** Critical threshold that was exceeded */
124
+ threshold: number;
125
+ /** Timestamp of critical alert */
126
+ timestamp: number;
127
+ }
128
+ /**
129
+ * Browser support detection result
130
+ */
131
+ interface BrowserSupport {
132
+ /** Level of support */
133
+ level: SupportLevel;
134
+ /** Available metrics in this browser */
135
+ availableMetrics: AvailableMetric[];
136
+ /** Any limitations or caveats */
137
+ limitations: string[];
138
+ /** Whether secure context requirements are met */
139
+ isSecureContext: boolean;
140
+ /** Whether cross-origin isolated */
141
+ isCrossOriginIsolated: boolean;
142
+ /** Whether precise memory API is available */
143
+ hasPreciseMemoryAPI: boolean;
144
+ }
145
+ /**
146
+ * Formatted memory values for display
147
+ */
148
+ interface FormattedMemory {
149
+ /** Formatted heap used (e.g., "45.2 MB") */
150
+ heapUsed: string;
151
+ /** Formatted heap total (e.g., "100 MB") */
152
+ heapTotal: string;
153
+ /** Formatted heap limit (e.g., "2 GB") */
154
+ heapLimit: string;
155
+ /** Formatted DOM node count */
156
+ domNodes?: string;
157
+ /** Formatted event listener count */
158
+ eventListeners?: string;
159
+ }
160
+ /**
161
+ * Leak detection configuration
162
+ */
163
+ interface LeakDetectionOptions {
164
+ /** Enable leak detection */
165
+ enabled?: boolean;
166
+ /** Detection sensitivity */
167
+ sensitivity?: LeakSensitivity;
168
+ /** Number of samples to analyze */
169
+ windowSize?: number;
170
+ /** Custom growth rate threshold (bytes/sample) */
171
+ threshold?: number;
172
+ }
173
+ /**
174
+ * Threshold configuration for alerts
175
+ */
176
+ interface ThresholdOptions {
177
+ /** Warning threshold percentage (0-100) */
178
+ warning?: number;
179
+ /** Critical threshold percentage (0-100) */
180
+ critical?: number;
181
+ }
182
+ /**
183
+ * Configuration options for useMemoryMonitor hook
184
+ */
185
+ interface UseMemoryMonitorOptions {
186
+ /** Monitoring interval in milliseconds (default: 5000) */
187
+ interval?: number;
188
+ /** Auto-start monitoring on mount (default: true) */
189
+ autoStart?: boolean;
190
+ /** Enable monitoring (default: true) */
191
+ enabled?: boolean;
192
+ /** Enable history recording (default: false) */
193
+ enableHistory?: boolean;
194
+ /** Maximum history size (default: 50) */
195
+ historySize?: number;
196
+ /** Threshold configuration for warnings/alerts */
197
+ thresholds?: ThresholdOptions;
198
+ /** Leak detection configuration */
199
+ leakDetection?: LeakDetectionOptions;
200
+ /** Enable development mode features (default: false) */
201
+ devMode?: boolean;
202
+ /** Track DOM node count (default: false) */
203
+ trackDOMNodes?: boolean;
204
+ /** Track event listener count (default: false) */
205
+ trackEventListeners?: boolean;
206
+ /** Log updates to console (default: false) */
207
+ logToConsole?: boolean;
208
+ /** Called on each memory update */
209
+ onUpdate?: (memory: MemoryInfo) => void;
210
+ /** Called when warning threshold is exceeded */
211
+ onWarning?: (data: MemoryWarning) => void;
212
+ /** Called when critical threshold is exceeded */
213
+ onCritical?: (data: MemoryCritical) => void;
214
+ /** Called when memory leak is detected */
215
+ onLeakDetected?: (analysis: LeakAnalysis) => void;
216
+ /** Called when monitoring is not supported */
217
+ onUnsupported?: (info: UnsupportedInfo) => void;
218
+ /** Disable in production builds (default: false) */
219
+ disableInProduction?: boolean;
220
+ /** Fallback strategy for unsupported browsers (default: 'dom-only') */
221
+ fallbackStrategy?: FallbackStrategy;
222
+ }
223
+ /**
224
+ * Return type for useMemoryMonitor hook
225
+ */
226
+ interface UseMemoryMonitorReturn {
227
+ /** Current memory information (null if unsupported) */
228
+ memory: MemoryInfo | null;
229
+ /** Used JS heap in bytes (null if unsupported) */
230
+ heapUsed: number | null;
231
+ /** Total JS heap in bytes (null if unsupported) */
232
+ heapTotal: number | null;
233
+ /** JS heap limit in bytes (null if unsupported) */
234
+ heapLimit: number | null;
235
+ /** Memory usage percentage (null if unsupported) */
236
+ usagePercentage: number | null;
237
+ /** Current DOM node count (null if not tracking) */
238
+ domNodes: number | null;
239
+ /** Estimated event listener count (null if not tracking) */
240
+ eventListeners: number | null;
241
+ /** Whether memory API is supported */
242
+ isSupported: boolean;
243
+ /** Whether monitoring is currently active */
244
+ isMonitoring: boolean;
245
+ /** Whether a memory leak is detected */
246
+ isLeakDetected: boolean;
247
+ /** Current severity level */
248
+ severity: Severity;
249
+ /** Level of API support */
250
+ supportLevel: SupportLevel;
251
+ /** List of available metrics */
252
+ availableMetrics: AvailableMetric[];
253
+ /** Memory history array (empty if history disabled) */
254
+ history: MemoryInfo[];
255
+ /** Memory usage trend */
256
+ trend: Trend;
257
+ /** Probability of memory leak (0-100) */
258
+ leakProbability: number;
259
+ /** Start monitoring */
260
+ start: () => void;
261
+ /** Stop monitoring */
262
+ stop: () => void;
263
+ /** Take a named snapshot */
264
+ takeSnapshot: (id: string) => MemorySnapshot | null;
265
+ /** Compare two snapshots */
266
+ compareSnapshots: (id1: string, id2: string) => SnapshotDiff | null;
267
+ /** Clear history */
268
+ clearHistory: () => void;
269
+ /** Request garbage collection hint */
270
+ requestGC: () => void;
271
+ /** Formatted memory values for display */
272
+ formatted: FormattedMemory;
273
+ }
274
+
275
+ /**
276
+ * A React hook for monitoring browser memory usage in real-time.
277
+ * Detects memory leaks, provides threshold alerts, and supports snapshot comparison.
278
+ *
279
+ * Features:
280
+ * - Real-time memory tracking (JS Heap, DOM Nodes)
281
+ * - Memory leak detection with configurable sensitivity
282
+ * - Threshold-based warnings (warning/critical levels)
283
+ * - Memory snapshot comparison
284
+ * - SSR compatible
285
+ * - Graceful degradation for unsupported browsers
286
+ *
287
+ * @param options - Configuration options
288
+ * @returns Memory monitoring state and control functions
289
+ *
290
+ * @example
291
+ * ```tsx
292
+ * // Basic usage
293
+ * function MemoryDisplay() {
294
+ * const { heapUsed, formatted, isSupported } = useMemoryMonitor();
295
+ *
296
+ * if (!isSupported) {
297
+ * return <p>Memory monitoring not available</p>;
298
+ * }
299
+ *
300
+ * return <p>Memory: {formatted.heapUsed}</p>;
301
+ * }
302
+ * ```
303
+ *
304
+ * @example
305
+ * ```tsx
306
+ * // With leak detection
307
+ * const monitor = useMemoryMonitor({
308
+ * enableHistory: true,
309
+ * leakDetection: { enabled: true, sensitivity: 'medium' },
310
+ * onLeakDetected: (analysis) => {
311
+ * console.warn('Leak detected:', analysis);
312
+ * },
313
+ * });
314
+ * ```
315
+ *
316
+ * @example
317
+ * ```tsx
318
+ * // With threshold alerts
319
+ * const monitor = useMemoryMonitor({
320
+ * thresholds: { warning: 70, critical: 90 },
321
+ * onWarning: (data) => console.warn('Memory warning:', data),
322
+ * onCritical: (data) => console.error('Memory critical:', data),
323
+ * });
324
+ * ```
325
+ */
326
+ declare function useMemoryMonitor(options?: UseMemoryMonitorOptions): UseMemoryMonitorReturn;
327
+
328
+ /**
329
+ * Format bytes to human-readable string (e.g., "45.2 MB")
330
+ *
331
+ * @param bytes - Number of bytes to format
332
+ * @param decimals - Number of decimal places (default: 2)
333
+ * @returns Formatted string with unit
334
+ */
335
+ declare function formatBytes(bytes: number | null | undefined, decimals?: number): string;
336
+ /**
337
+ * Format a percentage value
338
+ *
339
+ * @param percentage - Percentage value (0-100)
340
+ * @param decimals - Number of decimal places (default: 1)
341
+ * @returns Formatted percentage string
342
+ */
343
+ declare function formatPercentage(percentage: number | null | undefined, decimals?: number): string;
344
+ /**
345
+ * Format a number with thousand separators
346
+ *
347
+ * @param value - Number to format
348
+ * @returns Formatted string with thousand separators
349
+ */
350
+ declare function formatNumber(value: number | null | undefined): string;
351
+ /**
352
+ * Calculate usage percentage from memory info
353
+ *
354
+ * @param heapUsed - Used heap size in bytes
355
+ * @param heapLimit - Heap limit in bytes
356
+ * @returns Usage percentage (0-100) or null if invalid
357
+ */
358
+ declare function calculateUsagePercentage(heapUsed: number | null | undefined, heapLimit: number | null | undefined): number | null;
359
+ /**
360
+ * Format time duration in milliseconds to human-readable string
361
+ *
362
+ * @param ms - Duration in milliseconds
363
+ * @returns Formatted duration string
364
+ */
365
+ declare function formatDuration(ms: number): string;
366
+
367
+ /**
368
+ * Check if running in a server-side environment
369
+ */
370
+ declare function isServer(): boolean;
371
+ /**
372
+ * Check if running in a client-side environment
373
+ */
374
+ declare function isClient(): boolean;
375
+ /**
376
+ * Check if the legacy performance.memory API is available (Chrome/Edge)
377
+ */
378
+ declare function hasLegacyMemoryAPI(): boolean;
379
+ /**
380
+ * Check if the modern measureUserAgentSpecificMemory API is available
381
+ */
382
+ declare function hasPreciseMemoryAPI(): boolean;
383
+ /**
384
+ * Attempt to detect the browser name
385
+ */
386
+ declare function detectBrowser(): string | undefined;
387
+ /**
388
+ * Comprehensive browser support detection
389
+ */
390
+ declare function detectSupport(): BrowserSupport;
391
+ /**
392
+ * Check if any memory monitoring is possible
393
+ */
394
+ declare function canMonitorMemory(): boolean;
395
+
396
+ /**
397
+ * A fixed-size circular buffer (ring buffer) for efficient history storage.
398
+ * Provides O(1) push operations and automatically overwrites oldest entries
399
+ * when capacity is reached.
400
+ *
401
+ * @template T - Type of items stored in the buffer
402
+ */
403
+ declare class CircularBuffer<T> {
404
+ private buffer;
405
+ private head;
406
+ private tail;
407
+ private _size;
408
+ private readonly _capacity;
409
+ /**
410
+ * Create a new circular buffer with the specified capacity
411
+ *
412
+ * @param capacity - Maximum number of items the buffer can hold
413
+ * @throws Error if capacity is less than 1
414
+ */
415
+ constructor(capacity: number);
416
+ /**
417
+ * Add an item to the buffer.
418
+ * If the buffer is full, the oldest item will be overwritten.
419
+ *
420
+ * @param item - Item to add
421
+ */
422
+ push(item: T): void;
423
+ /**
424
+ * Get all items in the buffer as an array, from oldest to newest.
425
+ *
426
+ * @returns Array of items in insertion order (oldest first)
427
+ */
428
+ toArray(): T[];
429
+ /**
430
+ * Get the most recent N items from the buffer.
431
+ *
432
+ * @param count - Number of items to retrieve
433
+ * @returns Array of most recent items (oldest first within the slice)
434
+ */
435
+ getRecent(count: number): T[];
436
+ /**
437
+ * Get the most recently added item.
438
+ *
439
+ * @returns The most recent item, or undefined if buffer is empty
440
+ */
441
+ get last(): T | undefined;
442
+ /**
443
+ * Get the oldest item in the buffer.
444
+ *
445
+ * @returns The oldest item, or undefined if buffer is empty
446
+ */
447
+ get first(): T | undefined;
448
+ /**
449
+ * Get an item at a specific index (0 = oldest).
450
+ *
451
+ * @param index - Index of the item to retrieve
452
+ * @returns The item at the index, or undefined if out of bounds
453
+ */
454
+ at(index: number): T | undefined;
455
+ /**
456
+ * Current number of items in the buffer.
457
+ */
458
+ get size(): number;
459
+ /**
460
+ * Maximum capacity of the buffer.
461
+ */
462
+ get capacity(): number;
463
+ /**
464
+ * Check if the buffer is empty.
465
+ */
466
+ get isEmpty(): boolean;
467
+ /**
468
+ * Check if the buffer is full.
469
+ */
470
+ get isFull(): boolean;
471
+ /**
472
+ * Clear all items from the buffer.
473
+ */
474
+ clear(): void;
475
+ /**
476
+ * Iterate over all items in the buffer (oldest to newest).
477
+ */
478
+ [Symbol.iterator](): Iterator<T>;
479
+ /**
480
+ * Apply a function to each item in the buffer.
481
+ *
482
+ * @param callback - Function to call for each item
483
+ */
484
+ forEach(callback: (item: T, index: number) => void): void;
485
+ /**
486
+ * Map items to a new array.
487
+ *
488
+ * @param callback - Function to transform each item
489
+ * @returns Array of transformed items
490
+ */
491
+ map<U>(callback: (item: T, index: number) => U): U[];
492
+ /**
493
+ * Filter items based on a predicate.
494
+ *
495
+ * @param predicate - Function to test each item
496
+ * @returns Array of items that pass the test
497
+ */
498
+ filter(predicate: (item: T, index: number) => boolean): T[];
499
+ }
500
+
501
+ /**
502
+ * Result of linear regression analysis
503
+ */
504
+ interface RegressionResult {
505
+ /** Slope of the regression line (bytes per sample) */
506
+ slope: number;
507
+ /** Y-intercept of the regression line */
508
+ intercept: number;
509
+ /** R-squared value (coefficient of determination, 0-1) */
510
+ rSquared: number;
511
+ }
512
+ /**
513
+ * Perform simple linear regression on a set of points.
514
+ * Uses the least squares method.
515
+ *
516
+ * @param points - Array of [x, y] coordinate pairs
517
+ * @returns Regression result with slope, intercept, and R-squared
518
+ */
519
+ declare function linearRegression(points: [number, number][]): RegressionResult;
520
+ /**
521
+ * Calculate the memory trend from samples.
522
+ *
523
+ * @param samples - Array of memory info samples
524
+ * @returns Trend direction
525
+ */
526
+ declare function calculateTrend(samples: MemoryInfo[]): Trend;
527
+ /**
528
+ * Analyze memory samples for potential leaks.
529
+ *
530
+ * @param samples - Array of memory info samples (minimum 5 recommended)
531
+ * @param sensitivity - Detection sensitivity level
532
+ * @param customThreshold - Optional custom growth threshold (bytes/sample)
533
+ * @returns Leak analysis result
534
+ */
535
+ declare function analyzeLeakProbability(samples: MemoryInfo[], sensitivity?: LeakSensitivity, customThreshold?: number): LeakAnalysis;
536
+
537
+ export { type AvailableMetric, type BrowserSupport, CircularBuffer, type FallbackStrategy, type FormattedMemory, type LeakAnalysis, type LeakDetectionOptions, type LeakSensitivity, type MemoryCritical, type MemoryInfo, type MemorySnapshot, type MemoryWarning, type RegressionResult, type Severity, type SnapshotDiff, type SupportLevel, type ThresholdOptions, type Trend, type UnsupportedInfo, type UnsupportedReason, type UseMemoryMonitorOptions, type UseMemoryMonitorReturn, analyzeLeakProbability, calculateTrend, calculateUsagePercentage, canMonitorMemory, detectBrowser, detectSupport, formatBytes, formatDuration, formatNumber, formatPercentage, hasLegacyMemoryAPI, hasPreciseMemoryAPI, isClient, isServer, linearRegression, useMemoryMonitor };