Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .prettierrc
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
{
"useTabs": true,
"useTabs": false,
"tabWidth": 4,
"singleQuote": true,
"trailingComma": "none",
"printWidth": 100,
Expand Down
76 changes: 76 additions & 0 deletions src/service-worker.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/// <reference types="@sveltejs/kit" />
/// <reference no-default-lib="true"/>
/// <reference lib="esnext" />
/// <reference lib="webworker" />

import { build, files, version } from '$service-worker';

// Create a unique cache name for this deployment
const CACHE = `cache-${version}`;

const ASSETS = [
...build, // the app itself
...files // everything in `static`
];

const sw = self as unknown as ServiceWorkerGlobalScope;

sw.addEventListener('install', (event) => {
// Create a new cache and add all files to it
async function addFilesToCache() {
const cache = await caches.open(CACHE);
await cache.addAll(ASSETS);
}

event.waitUntil(addFilesToCache());
});

sw.addEventListener('activate', (event) => {
// Remove previous cached data from disk
async function deleteOldCaches() {
for (const key of await caches.keys()) {
if (key !== CACHE) await caches.delete(key);
}
}

event.waitUntil(deleteOldCaches());
});

sw.addEventListener('fetch', async (event) => {
// ignore POST requests etc
if (event.request.method !== 'GET') return;

const url = new URL(event.request.url);
// ignore requests from protocols like chrome-extension
if (!url.protocol.startsWith('http')) return;

async function respond(url: URL): Promise<Response> {
const cache = await caches.open(CACHE);

if (url.protocol)
if (ASSETS.includes(url.pathname)) {
// `build`/`files` can always be served from the cache
return cache.match(url.pathname) as Promise<Response>;
}

// for everything else, try the network first, but
// fall back to the cache if we're offline
try {
const response = await fetch(event.request);

if (response.status === 200) {
cache.put(event.request, response.clone());
}

return response;
} catch (error) {
const match = await cache.match(event.request);

if (!match) throw error;

return match;
}
}

event.respondWith(respond(url));
});