|
1 | | -// Service Worker for handling push notifications |
| 1 | +/// <reference no-default-lib="true"/> |
| 2 | +/// <reference lib="esnext" /> |
| 3 | +/// <reference lib="webworker" /> |
| 4 | +/// <reference types="@sveltejs/kit" /> |
2 | 5 |
|
3 | | -const CACHE_NAME = 'programmerbar-v1'; |
| 6 | +import { build, files, version } from '$service-worker'; |
4 | 7 |
|
5 | | -self.addEventListener('install', () => { |
6 | | - console.log('[Service Worker] Installing...'); |
7 | | - self.skipWaiting(); |
| 8 | +const self = globalThis.self as unknown as ServiceWorkerGlobalScope; |
| 9 | + |
| 10 | +const CACHE = `cache-${version}`; |
| 11 | +const ASSETS = [...build, ...files]; |
| 12 | + |
| 13 | +self.addEventListener('install', (event) => { |
| 14 | + console.log('[Service Worker] Install event'); |
| 15 | + |
| 16 | + async function addFilesToCache() { |
| 17 | + const cache = await caches.open(CACHE); |
| 18 | + await cache.addAll(ASSETS); |
| 19 | + } |
| 20 | + |
| 21 | + event.waitUntil(addFilesToCache()); |
8 | 22 | }); |
9 | 23 |
|
10 | | -// Activate event |
11 | 24 | self.addEventListener('activate', (event) => { |
12 | | - console.log('[Service Worker] Activating...'); |
13 | | - event.waitUntil(self.clients.claim()); |
| 25 | + console.log('[Service Worker] Activate event'); |
| 26 | + |
| 27 | + async function deleteOldCaches() { |
| 28 | + for (const key of await caches.keys()) { |
| 29 | + if (key !== CACHE) await caches.delete(key); |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + event.waitUntil(deleteOldCaches()); |
14 | 34 | }); |
15 | 35 |
|
16 | 36 | // Push event -> show notification |
@@ -80,7 +100,7 @@ self.addEventListener('pushsubscriptionchange', (event) => { |
80 | 100 | console.log('[Service Worker] Push subscription changed'); |
81 | 101 |
|
82 | 102 | event.waitUntil( |
83 | | - self.registration.pushManager.subscribe(event.oldSubscription.options).then((subscription) => { |
| 103 | + self.registration.pushManager.subscribe(event.oldSubscription?.options).then((subscription) => { |
84 | 104 | console.log('[Service Worker] Resubscribed:', subscription); |
85 | 105 | return fetch('/api/push/subscribe', { |
86 | 106 | method: 'POST', |
|
0 commit comments