File indexing completed on 2024-05-12 03:53:40

0001 /**
0002  * SPDX-FileCopyrightText: 2020 Carson Black <uhhadd@gmail.com>
0003  *
0004  * SPDX-License-Identifier: BSD-2-Clause
0005  */
0006 
0007 const ServiceWorkerVersion = 0
0008 const AssetCacheName = `assets-${ServiceWorkerVersion}`
0009 
0010 self.addEventListener("install", event => {
0011     event.waitUntil(
0012         caches.open(AssetCacheName).then(cache => {
0013             return cache.addAll([
0014                 "/resources",
0015                 "/index.html",
0016             ])
0017         })
0018     )
0019 })
0020 
0021 self.addEventListener("activate", event => {
0022     event.waitUntil(
0023         caches.keys().then(cacheNames => {
0024             return Promise.all(
0025                 cacheNames.map(cacheName => {
0026                     if (cacheName != AssetCacheName) {
0027                         return caches.delete(cacheName)
0028                     }
0029                 })
0030             )
0031         })
0032     )
0033 })
0034 
0035 self.addEventListener("fetch", event => {
0036     event.respondWith(
0037         caches.open(AssetCacheName).then(cache => {
0038             return cache.match(event.request).then(response => {
0039                 if (response) {
0040                     return response
0041                 }
0042 
0043                 return fetch(event.request.clone()).then(requestResponse => {
0044                     if (requestResponse.status < 400) {
0045                         cache.put(event.request, requestResponse.clone())
0046                     }
0047 
0048                     return requestResponse
0049                 })
0050             }, error => {
0051                 console.log(`Error in cache match: ${error}`)
0052                 throw error
0053             })
0054         }, error => {
0055             console.log(`Error in cache opening: ${error}`)
0056             throw error
0057         })
0058     )
0059 })
0060 
0061 self.addEventListener("message", (ev) => {
0062     if (ev.data && ev.data.type === "CONSIDER_CACHING") {
0063         let url = ev.data.url
0064         if (url.includes('/html/')) {
0065             let toCache = url.split('/html/')[0]
0066             caches.open(AssetCacheName).then(cache => {
0067                 return cache.addAll([
0068                     toCache
0069                 ])
0070             })
0071         }
0072     }
0073 })