All files / use-memory-monitor/src store.ts

100% Statements 65/65
100% Branches 22/22
96.96% Functions 32/33
100% Lines 54/54

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                      76x 76x           64x 64x 41x               373x             1x             150x             65x   64x         64x             10x   9x         9x             9x   8x         8x             60x   57x         57x             9x   5x         5x             5x     5x 4x     5x   4x 4x             3x 3x             5x     76x                                             75x             2x   1x 1x 1x 1x               1x       1x             55x   54x           54x   52x                       4x   3x 3x   1x                 5x   4x   4x         4x   1x      
import type { MemoryInfo, MemoryStoreState, Severity } from "./types";
import { SSR_INITIAL_STATE } from "./constants";
import { isServer } from "./utils/detection";
 
type Listener = () => void;
 
/**
 * Creates an external store for memory state management.
 * Compatible with useSyncExternalStore for React 18+ concurrent rendering.
 */
function createMemoryStore() {
  let state: MemoryStoreState = { ...SSR_INITIAL_STATE };
  const listeners = new Set<Listener>();
 
  /**
   * Subscribe to store updates
   */
  function subscribe(listener: Listener): () => void {
    listeners.add(listener);
    return () => {
      listeners.delete(listener);
    };
  }
 
  /**
   * Get current state snapshot
   */
  function getSnapshot(): MemoryStoreState {
    return state;
  }
 
  /**
   * Get SSR-safe server snapshot
   */
  function getServerSnapshot(): MemoryStoreState {
    return SSR_INITIAL_STATE;
  }
 
  /**
   * Notify all listeners of state change
   */
  function notify(): void {
    listeners.forEach((listener) => listener());
  }
 
  /**
   * Update memory info in store
   */
  function updateMemory(memory: MemoryInfo | null): void {
    if (state.memory === memory) return;
 
    state = {
      ...state,
      memory,
      lastUpdated: Date.now(),
    };
    notify();
  }
 
  /**
   * Update DOM node count
   */
  function updateDOMNodes(count: number | null): void {
    if (state.domNodes === count) return;
 
    state = {
      ...state,
      domNodes: count,
      lastUpdated: Date.now(),
    };
    notify();
  }
 
  /**
   * Update event listener count
   */
  function updateEventListeners(count: number | null): void {
    if (state.eventListeners === count) return;
 
    state = {
      ...state,
      eventListeners: count,
      lastUpdated: Date.now(),
    };
    notify();
  }
 
  /**
   * Update monitoring status
   */
  function updateMonitoringStatus(isMonitoring: boolean): void {
    if (state.isMonitoring === isMonitoring) return;
 
    state = {
      ...state,
      isMonitoring,
      lastUpdated: Date.now(),
    };
    notify();
  }
 
  /**
   * Update severity level
   */
  function updateSeverity(severity: Severity): void {
    if (state.severity === severity) return;
 
    state = {
      ...state,
      severity,
      lastUpdated: Date.now(),
    };
    notify();
  }
 
  /**
   * Batch update multiple state properties
   */
  function batchUpdate(updates: Partial<MemoryStoreState>): void {
    const newState = { ...state, ...updates, lastUpdated: Date.now() };
 
    // Check if anything actually changed
    const hasChanges = Object.keys(updates).some(
      (key) => state[key as keyof MemoryStoreState] !== updates[key as keyof MemoryStoreState]
    );
 
    if (!hasChanges) return;
 
    state = newState;
    notify();
  }
 
  /**
   * Reset store to initial state
   */
  function reset(): void {
    state = { ...SSR_INITIAL_STATE };
    notify();
  }
 
  /**
   * Get current subscriber count (for debugging)
   */
  function getSubscriberCount(): number {
    return listeners.size;
  }
 
  return {
    subscribe,
    getSnapshot,
    getServerSnapshot,
    updateMemory,
    updateDOMNodes,
    updateEventListeners,
    updateMonitoringStatus,
    updateSeverity,
    batchUpdate,
    reset,
    getSubscriberCount,
  };
}
 
// Export store type
export type MemoryStore = ReturnType<typeof createMemoryStore>;
 
/**
 * Creates a new memory store instance.
 * Each hook instance should create its own store to maintain isolation.
 */
export function createStore(): MemoryStore {
  return createMemoryStore();
}
 
/**
 * Creates an SSR-safe store that returns static values on the server.
 */
export function createSSRSafeStore(): MemoryStore {
  if (isServer()) {
    // Return a no-op store for SSR
    return {
      subscribe: () => () => {},
      getSnapshot: () => SSR_INITIAL_STATE,
      getServerSnapshot: () => SSR_INITIAL_STATE,
      updateMemory: () => {},
      updateDOMNodes: () => {},
      updateEventListeners: () => {},
      updateMonitoringStatus: () => {},
      updateSeverity: () => {},
      batchUpdate: () => {},
      reset: () => {},
      getSubscriberCount: () => 0,
    };
  }
 
  return createMemoryStore();
}
 
/**
 * Read current memory from performance.memory API
 */
export function readMemoryFromAPI(): MemoryInfo | null {
  if (isServer()) return null;
 
  const memory = (performance as { memory?: {
    usedJSHeapSize: number;
    totalJSHeapSize: number;
    jsHeapSizeLimit: number;
  } }).memory;
 
  if (!memory) return null;
 
  return {
    heapUsed: Math.max(0, memory.usedJSHeapSize),
    heapTotal: Math.max(0, memory.totalJSHeapSize),
    heapLimit: Math.max(0, memory.jsHeapSizeLimit),
    timestamp: Date.now(),
  };
}
 
/**
 * Count DOM nodes in the document
 */
export function countDOMNodes(): number | null {
  if (isServer()) return null;
 
  try {
    return document.querySelectorAll("*").length;
  } catch {
    return null;
  }
}
 
/**
 * Estimate event listener count based on interactive elements.
 * This is an approximation since there's no direct API to count listeners.
 */
export function estimateEventListeners(): number | null {
  if (isServer()) return null;
 
  try {
    // Count elements that commonly have event listeners
    const interactiveElements = document.querySelectorAll(
      'button, a, input, select, textarea, [onclick], [onchange], [onkeydown], [onkeyup], [onmouseover], [onmouseout], [onfocus], [onblur], [tabindex]'
    );
 
    // Rough estimate: each interactive element has ~1.5 listeners on average
    return Math.round(interactiveElements.length * 1.5);
  } catch {
    return null;
  }
}