This repository was archived by the owner on Aug 3, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathservice-worker.ts
126 lines (109 loc) · 4.26 KB
/
service-worker.ts
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
/// <reference lib="webworker" />
// Courtesy of https://dev.to/100lvlmaster/create-a-pwa-with-sveltekit-svelte-a36
import { build, files, version } from '$service-worker';
import { handleRequestsWith } from 'worker-request-response';
import { createPartialResponse } from 'workbox-range-requests';
import type {
CheckStatusRequest,
QueryDownloadsRequest,
ServiceWorkerRequest,
} from '$lib/shared/lib';
const worker = self as unknown as ServiceWorkerGlobalScope;
const cacheName = `cache-${version}`;
// `build` is an array of all the files generated by the bundler,
// `files` is an array of everything in the `static` directory
const toCache = build.concat(files);
const staticAssets = new Set(toCache);
worker.addEventListener('install', (event) => {
event.waitUntil(
caches
.open(cacheName)
.then((cache) => cache.addAll(toCache))
.then(() => worker.skipWaiting())
);
});
worker.addEventListener('activate', (event) => {
event.waitUntil(
caches.keys().then(async (keys) => {
// delete old caches
await Promise.all(keys.filter((key) => key !== cacheName).map((key) => caches.delete(key)));
await worker.clients.claim();
})
);
});
/**
* Fetch the asset from the network and store it in the cache.
* Fall back to the cache if the user is offline.
*/
async function fetchAndCache(request: Request) {
const cache = await caches.open(`offline-${version}`);
const isAudio = request.url.endsWith('.mp3');
if (isAudio) {
const cached = await cache.match(request.url);
if (cached) {
if (request.headers.has('Range')) {
return createPartialResponse(request, cached);
}
return cached;
}
}
const shouldCache = new URL(request.url).searchParams.get('download') === 'true';
try {
const response = await fetch(request);
// Don't cache partial responses
const isFull = !response.headers.has('content-range');
if ((!isAudio && isFull) || shouldCache) {
const url = new URL(request.url);
url.searchParams.delete('download');
cache.put(url.toString(), response.clone());
}
return response;
} catch (err) {
const response = await cache.match(request);
if (response) return response;
throw err;
}
}
worker.addEventListener('fetch', (event) => {
if (event.request.method !== 'GET') return;
const url = new URL(event.request.url);
// don't try to handle e.g. data: URIs
const isHttp = url.protocol.startsWith('http');
const isDevServerRequest =
url.hostname === self.location.hostname && url.port !== self.location.port;
const isStaticAsset = url.host === self.location.host && staticAssets.has(url.pathname);
const skipBecauseUncached = event.request.cache === 'only-if-cached' && !isStaticAsset;
if (isHttp && !isDevServerRequest && !skipBecauseUncached) {
event.respondWith(
(async () => {
// always serve static files and bundler-generated assets from cache.
// if your application has other URLs with data that will never change,
// set this variable to true for them and they will only be fetched once.
const cachedAsset = isStaticAsset && (await caches.match(event.request));
return cachedAsset || fetchAndCache(event.request);
})()
);
}
});
async function isFilenameInCache(event: MessageEvent<CheckStatusRequest>): Promise<boolean> {
const cache = await caches.open(`offline-${version}`);
const cacheKeys = await cache.keys();
return cacheKeys.some((request) => request.url.startsWith(event.data.payload));
}
async function getCachedEpisodes(_event: MessageEvent<QueryDownloadsRequest>): Promise<string[]> {
const cache = await caches.open(`offline-${version}`);
const cacheKeys = await cache.keys();
const urls = cacheKeys.map((request) => request.url);
return urls.filter((url) => new URL(url).pathname.endsWith('.mp3'));
}
self.addEventListener('message', (e: MessageEvent<{ payload: ServiceWorkerRequest }>) => {
// TODO: figure out how to type this properly to use an object mapping instead
switch (e.data.payload.type) {
case 'check-download-status':
return handleRequestsWith(isFilenameInCache)(e);
case 'query-downloaded-episodes':
return handleRequestsWith(getCachedEpisodes)(e);
default:
console.error('Unrecognized message:', e.data);
}
});