-
Notifications
You must be signed in to change notification settings - Fork 13
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
It was mistakenly removed in 4c71c4a
- Loading branch information
Showing
1 changed file
with
65 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
/// <reference types="@sveltejs/kit" /> | ||
/// <reference no-default-lib="true"/> | ||
/// <reference lib="webworker" /> | ||
|
||
declare const self: ServiceWorkerGlobalScope; | ||
|
||
import {build, files, prerendered, version} from '$service-worker'; | ||
|
||
const CACHE = `cache-${version}`; | ||
|
||
const ASSETS = [...build.map((file) => file.replace(/\/index\.html$/, '/')), ...prerendered, ...files]; | ||
|
||
const splitAssets = (assets: string[]) => { | ||
const withHash: string[] = []; | ||
const withoutHash: string[] = []; | ||
const hashRegExp = /[.-]\w{8,}\.\w{2,4}$/; | ||
for (const asset of assets) { | ||
(hashRegExp.test(asset) ? withHash : withoutHash).push(asset); | ||
} | ||
return {withHash, withoutHash}; | ||
}; | ||
|
||
self.addEventListener('install', (event) => { | ||
event.waitUntil( | ||
(async () => { | ||
const cache = await caches.open(CACHE); | ||
const {withHash, withoutHash} = splitAssets(ASSETS); | ||
const missingWithHash: string[] = []; | ||
await Promise.all( | ||
withHash.map(async (url) => { | ||
const response = await caches.match(url); | ||
if (response?.ok) { | ||
cache.put(url, response); | ||
} else { | ||
missingWithHash.push(url); | ||
} | ||
}) | ||
); | ||
await cache.addAll([...missingWithHash, ...withoutHash]); | ||
await self.skipWaiting(); | ||
})() | ||
); | ||
}); | ||
|
||
self.addEventListener('activate', (event) => { | ||
event.waitUntil( | ||
(async () => { | ||
await self.clients.claim(); | ||
await Promise.all((await caches.keys()).filter((key) => key !== CACHE).map((key) => caches.delete(key))); | ||
})() | ||
); | ||
}); | ||
|
||
self.addEventListener('fetch', (event) => { | ||
const url = new URL(event.request.url); | ||
if (event.request.method === 'GET' && ASSETS.includes(url.pathname)) { | ||
event.respondWith( | ||
(async () => { | ||
const cache = await caches.open(CACHE); | ||
const response = await cache.match(url.pathname); | ||
return response!; | ||
})() | ||
); | ||
} | ||
}); |