All files / src sw.js

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

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                                                                                                                                                                                                                                                                                                                                                                 
/* eslint-env serviceworker */
/**
 * Missing Table service worker.
 *
 * Generated into dist/sw.js by vite-plugin-pwa in `injectManifest` mode. The
 * plugin injects `self.__WB_MANIFEST` with the precache list at build time;
 * the rest is hand-written so we can attach push + notificationclick handlers
 * that `generateSW` doesn't allow.
 *
 * What this SW does:
 *  1. Precaches the app shell (HTML, JS, CSS, icons).
 *  2. Runtime-caches read-only API responses (standings, teams, etc.) with
 *     stale-while-revalidate.
 *  3. Runtime-caches Google Fonts cache-first.
 *  4. Serves /index.html for SPA navigation requests when offline.
 *  5. Receives Web Push messages and displays notifications.
 *  6. Routes notification clicks to the live match view (or app root).
 *
 * Update behavior:
 *  - skipWaiting fires on the SKIP_WAITING message (below), triggered
 *    automatically by usePwaUpdate's onNeedRefresh so new builds activate +
 *    reload without waiting for a user click (avoids stale cached bundles
 *    after a deploy). UpdateAvailablePrompt remains a manual fallback.
 */

import { precacheAndRoute, createHandlerBoundToURL } from 'workbox-precaching';
import { registerRoute, NavigationRoute } from 'workbox-routing';
import {
  CacheFirst,
  NetworkFirst,
  StaleWhileRevalidate,
} from 'workbox-strategies';
import { CacheableResponsePlugin } from 'workbox-cacheable-response';
import { ExpirationPlugin } from 'workbox-expiration';
import { isReferenceApi, isResultsApi } from './utils/swRoutes';

// ---------------------------------------------------------------------------
// Precache (app shell)
// ---------------------------------------------------------------------------

precacheAndRoute(self.__WB_MANIFEST);

// SPA navigation fallback — any client-side route serves /index.html so the
// Vue router can render the right view. /api/* is denylisted so we never
// shadow real API responses.
registerRoute(
  new NavigationRoute(createHandlerBoundToURL('/index.html'), {
    denylist: [/^\/api\//],
  })
);

// ---------------------------------------------------------------------------
// Runtime caching
// ---------------------------------------------------------------------------

// Reference APIs. Stale-while-revalidate: serve cache instantly, refresh in
// background, next render is fresh. Safe here because this data only changes
// when an admin edits it. NOT cached: auth, writes, live-match state.
registerRoute(
  ({ url, request }) =>
    request.method === 'GET' && isReferenceApi(url.pathname + url.search),
  new StaleWhileRevalidate({
    cacheName: 'mt-reference-and-standings-v1',
    plugins: [
      new ExpirationPlugin({ maxEntries: 50, maxAgeSeconds: 60 * 60 * 24 * 7 }),
      new CacheableResponsePlugin({ statuses: [0, 200] }),
    ],
  }),
  'GET'
);

// Score-bearing APIs — standings and tournaments both change the moment a
// match ends, so a cached copy is wrong exactly when someone cares most
// (SB-908). Network first, with a short timeout so a touchline phone on a bad
// connection still renders from cache instead of hanging.
registerRoute(
  ({ url, request }) =>
    request.method === 'GET' && isResultsApi(url.pathname + url.search),
  new NetworkFirst({
    cacheName: 'mt-results-v1',
    networkTimeoutSeconds: 4,
    plugins: [
      new ExpirationPlugin({ maxEntries: 50, maxAgeSeconds: 60 * 60 * 24 }),
      new CacheableResponsePlugin({ statuses: [0, 200] }),
    ],
  }),
  'GET'
);

// Google Fonts — versioned URLs, rarely change, cache-first.
registerRoute(
  ({ url }) => /^https:\/\/fonts\.(googleapis|gstatic)\.com\/.*/.test(url.href),
  new CacheFirst({
    cacheName: 'google-fonts-v1',
    plugins: [
      new ExpirationPlugin({
        maxEntries: 20,
        maxAgeSeconds: 60 * 60 * 24 * 365,
      }),
      new CacheableResponsePlugin({ statuses: [0, 200] }),
    ],
  })
);

// ---------------------------------------------------------------------------
// Update flow
// ---------------------------------------------------------------------------

// When the page asks us to activate immediately (usePwaUpdate auto-triggers
// this on a new build; UpdateAvailablePrompt's reload button is the fallback).
self.addEventListener('message', event => {
  if (event.data && event.data.type === 'SKIP_WAITING') {
    self.skipWaiting();
  }
});

// ---------------------------------------------------------------------------
// Push notifications (SB-47)
// ---------------------------------------------------------------------------

self.addEventListener('push', event => {
  let data = {};
  try {
    data = event.data ? event.data.json() : {};
  } catch {
    data = { title: 'Missing Table', body: event.data?.text?.() ?? '' };
  }

  const {
    title = 'Missing Table',
    body = '',
    icon = '/pwa/icon-192.png',
    badge = '/pwa/icon-192.png',
    tag,
    data: payloadData,
  } = data;

  event.waitUntil(
    self.registration.showNotification(title, {
      body,
      icon,
      badge,
      tag,
      data: payloadData,
      // Match events are time-sensitive — don't sit silent in the background.
      requireInteraction: false,
      renotify: false,
    })
  );
});

self.addEventListener('notificationclick', event => {
  event.notification.close();
  const targetUrl = event.notification.data?.url || '/';

  event.waitUntil(
    clients
      .matchAll({ type: 'window', includeUncontrolled: true })
      .then(windowClients => {
        // If an MT window is already open, focus it and navigate inside.
        const scope = self.registration.scope;
        const existing = windowClients.find(client =>
          client.url.startsWith(scope)
        );
        if (existing) {
          existing.focus();
          if ('navigate' in existing) {
            return existing.navigate(targetUrl);
          }
          return;
        }
        // Otherwise open a new window/tab at the target URL.
        return clients.openWindow(targetUrl);
      })
  );
});