|
| 1 | +const CACHE_VERSION = process.env.GI_VERSION |
| 2 | +const CURRENT_CACHES = { |
| 3 | + assets: `assets-cache_v${CACHE_VERSION}` |
| 4 | +} |
| 5 | + |
| 6 | +if ( |
| 7 | + typeof Cache === 'function' && |
| 8 | + typeof CacheStorage === 'function' && |
| 9 | + typeof caches === 'object' && |
| 10 | + (caches instanceof CacheStorage) |
| 11 | +) { |
| 12 | + const locationUrl = new URL(self.location) |
| 13 | + const routerBase = locationUrl.searchParams.get('routerBase') ?? '/app' |
| 14 | + |
| 15 | + self.addEventListener('install', (event) => { |
| 16 | + event.waitUntil( |
| 17 | + caches |
| 18 | + .open(CURRENT_CACHES.assets) |
| 19 | + .then((cache) => |
| 20 | + cache.addAll([ |
| 21 | + '/assets/pwa-manifest.webmanifest', |
| 22 | + '/assets/images/group-income-icon-transparent.png', |
| 23 | + '/assets/images/pwa-icons/group-income-icon-maskable_192x192.png', |
| 24 | + '/assets/css/main.css', |
| 25 | + '/assets/js/main.js', |
| 26 | + `${routerBase}/` |
| 27 | + ]).catch(e => { |
| 28 | + console.error('Error adding initial entries to cache', e) |
| 29 | + }) |
| 30 | + ) |
| 31 | + ) |
| 32 | + }, false) |
| 33 | + |
| 34 | + // Taken from the MDN example: |
| 35 | + // <https://developer.mozilla.org/en-US/docs/Web/API/Cache> |
| 36 | + self.addEventListener('activate', (event) => { |
| 37 | + const expectedCacheNamesSet = new Set(Object.values(CURRENT_CACHES)) |
| 38 | + |
| 39 | + event.waitUntil( |
| 40 | + caches.keys().then((cacheNames) => |
| 41 | + Promise.allSettled( |
| 42 | + cacheNames.map((cacheName) => { |
| 43 | + if (!expectedCacheNamesSet.has(cacheName)) { |
| 44 | + // If this cache name isn't present in the set of |
| 45 | + // "expected" cache names, then delete it. |
| 46 | + console.log('Deleting out of date cache:', cacheName) |
| 47 | + return caches.delete(cacheName) |
| 48 | + } |
| 49 | + |
| 50 | + return undefined |
| 51 | + }) |
| 52 | + ) |
| 53 | + ) |
| 54 | + ) |
| 55 | + }, false) |
| 56 | + |
| 57 | + self.addEventListener('fetch', function (event) { |
| 58 | + console.debug(`[sw] fetch : ${event.request.method} - ${event.request.url}`) |
| 59 | + |
| 60 | + if (!['GET', 'HEAD', 'OPTIONS'].includes(event.request.method)) { |
| 61 | + return |
| 62 | + } |
| 63 | + |
| 64 | + // Needed mostly for Cypress |
| 65 | + let cacheKey = event.request |
| 66 | + try { |
| 67 | + const url = new URL(event.request.url) |
| 68 | + |
| 69 | + if (url.origin !== self.location.origin) { |
| 70 | + return |
| 71 | + } |
| 72 | + |
| 73 | + if ( |
| 74 | + ['/eventsAfter/', '/name/', '/latestHEADinfo/', '/file/', '/kv/', '/zkpp/'].some(prefix => url.pathname.startsWith(prefix)) || |
| 75 | + url.pathname === '/time' |
| 76 | + ) { |
| 77 | + return |
| 78 | + } |
| 79 | + |
| 80 | + // If the route starts with `${routerBase}/` or `/`, redirect to |
| 81 | + // `${routerBase}/`, since the HTML content is presumed to be the same. |
| 82 | + // This is _crucial_ for the offline PWA to work, since currently the app |
| 83 | + // uses different paths. |
| 84 | + if ( |
| 85 | + url.pathname === '/' || |
| 86 | + (url.pathname.startsWith(`${routerBase}/`) && url.pathname !== `${routerBase}/`) |
| 87 | + ) { |
| 88 | + if (window.Cypress) { |
| 89 | + // Apparently, Cypress doesn't like redirects, so we rewrite the |
| 90 | + // cache key instead |
| 91 | + cacheKey = new Request(`${routerBase}/`) |
| 92 | + } else { |
| 93 | + event.respondWith(Response.redirect(`${routerBase}/`, 302)) |
| 94 | + return |
| 95 | + } |
| 96 | + } |
| 97 | + } catch (e) { |
| 98 | + return |
| 99 | + } |
| 100 | + |
| 101 | + event.respondWith( |
| 102 | + caches.match(event.request, { ignoreSearch: true, ignoreVary: true }) |
| 103 | + .then((cachedResponse) => { |
| 104 | + // If a cached response exists, return it. Not only does this |
| 105 | + // improve performance, but it also makes the app work 'offline' |
| 106 | + // (`navigator.onLine` is unreliable; can be `true` even when |
| 107 | + // offline). The downside of this approach is that we may return |
| 108 | + // stale assets when the app is updated. Fortunately, so long as the |
| 109 | + // version is updated (GI_VERSION), existing cache entries will be |
| 110 | + // deleted. This will happen with SW updates, so, ideally, we won't |
| 111 | + // serve stale resources for too long. |
| 112 | + if (cachedResponse) { |
| 113 | + return cachedResponse |
| 114 | + } |
| 115 | + |
| 116 | + // We use the original `event.request` for the network fetch |
| 117 | + // instead of the possibly re-written `request` (used as a cache |
| 118 | + // key) because the re-written request makes tests fail. |
| 119 | + return caches.open(CURRENT_CACHES.assets).then((cache) => { |
| 120 | + return fetch(event.request).then((response) => { |
| 121 | + if ( |
| 122 | + // Save successful reponses |
| 123 | + response.status >= 200 && |
| 124 | + response.status < 400 && |
| 125 | + response.status !== 206 && // Partial response |
| 126 | + response.status !== 304 && // Not modified |
| 127 | + // Which don't have a 'no-store' directive |
| 128 | + !response.headers.get('cache-control')?.split(',').some(x => x.trim() === 'no-store') |
| 129 | + ) { |
| 130 | + event.waitUntil(cache.put(cacheKey, response.clone()).catch(e => { |
| 131 | + console.error('Error adding request to cache') |
| 132 | + })) |
| 133 | + } else if (response.status < 500) { |
| 134 | + // For 5xx responses (server errors, we don't delete the cache |
| 135 | + // entry. This is so that, in the event of a 5xx error, |
| 136 | + // the offline app still works.) |
| 137 | + event.waitUntil(cache.delete(cacheKey)) |
| 138 | + } |
| 139 | + |
| 140 | + return response |
| 141 | + }) |
| 142 | + }) |
| 143 | + }) |
| 144 | + ) |
| 145 | + }, false) |
| 146 | +} |
0 commit comments