All files / src/lib service-worker.ts

22.72% Statements 5/22
11.11% Branches 2/18
16.66% Functions 1/6
22.72% Lines 5/22

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  3x                                                         3x 4x                 3x           3x              
// Service Worker registration and utilities
export const registerServiceWorker = async (): Promise<void> => {
  if ('serviceWorker' in navigator && process.env.NODE_ENV === 'production') {
    try {
      const registration = await navigator.serviceWorker.register('/sw.js');
      console.log('Service Worker registered successfully:', registration);
 
      // Listen for updates
      registration.addEventListener('updatefound', () => {
        const newWorker = registration.installing;
        if (newWorker) {
          newWorker.addEventListener('statechange', () => {
            if (
              newWorker.state === 'installed' &&
              navigator.serviceWorker.controller
            ) {
              // New service worker is available
              console.log('New service worker available');
              // You could show a toast notification here
            }
          });
        }
      });
    } catch (error) {
      console.error('Service Worker registration failed:', error);
    }
  }
};
 
// Send prefetch request to service worker
export const prefetchWithServiceWorker = (url: string): void => {
  Iif ('serviceWorker' in navigator && navigator.serviceWorker.controller) {
    navigator.serviceWorker.controller.postMessage({
      type: 'PREFETCH_ROUTE',
      url,
    });
  }
};
 
// Check if service worker is available
export const isServiceWorkerAvailable = (): boolean => {
  return 'serviceWorker' in navigator;
};
 
// Get service worker registration
export const getServiceWorkerRegistration =
  async (): Promise<ServiceWorkerRegistration | null> => {
    if ('serviceWorker' in navigator) {
      const registration = await navigator.serviceWorker.getRegistration();
      return registration || null;
    }
    return null;
  };