All files / lib/policies PolicyManager.ts

0% Statements 0/42
0% Branches 0/1
0% Functions 0/1
0% Lines 0/42

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                                                                                                                     
/**
 * @file PolicyManager.ts
 * Responsible for detecting device context & performance profile
 * and generating a responsive policy snapshot.
 */
 
export interface PolicySnapshot {
  device: 'mobile' | 'desktop';
  performance: 'low' | 'medium' | 'high';
  motion: 'reduced' | 'full';
  network: 'offline' | 'slow' | 'fast';
  timestamp: string;
}
 
export class PolicyManager {
  /** Detects device type based on window width & user agent */
  static detectDevice(): 'mobile' | 'desktop' {
    if (typeof window === 'undefined') return 'desktop';
    const width = window.innerWidth || 1024;
    return width < 768 ? 'mobile' : 'desktop';
  }
 
  /** Estimates performance using frame timing & hardware info */
  static detectPerformance(): 'low' | 'medium' | 'high' {
    if (typeof performance === 'undefined') return 'medium';
    const cores = (navigator as any)?.hardwareConcurrency || 4;
    if (cores <= 2) return 'low';
    if (cores >= 8) return 'high';
    return 'medium';
  }
 
  /** Detects user motion preference */
  static detectMotion(): 'reduced' | 'full' {
    if (typeof window === 'undefined') return 'full';
    return window.matchMedia('(prefers-reduced-motion: reduce)').matches ? 'reduced' : 'full';
  }
 
  /** Estimates network condition */
  static detectNetwork(): 'offline' | 'slow' | 'fast' {
    const nav = navigator as any;
    if (!nav?.connection) return 'fast';
    const { effectiveType } = nav.connection;
    if (!navigator.onLine) return 'offline';
    if (effectiveType.includes('2g')) return 'slow';
    return 'fast';
  }
 
  /** Generates complete snapshot of current context */
  static detect(): PolicySnapshot {
    return {
      device: this.detectDevice(),
      performance: this.detectPerformance(),
      motion: this.detectMotion(),
      network: this.detectNetwork(),
      timestamp: new Date().toISOString(),
    };
  }
}