-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsw.js
More file actions
86 lines (77 loc) · 2.33 KB
/
sw.js
File metadata and controls
86 lines (77 loc) · 2.33 KB
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
const CACHE = 'bookshelf-v8';
const PRECACHE = [
'/viewer.html',
'/publications/the-next-frontier.md',
'/publications/agent-event-loop.md',
'/publications/the-verification-trap.md',
'/logo-v2.png',
'/books/',
'/books/index.html',
'/static/marked.min.js',
'/static/highlight/highlight.min.js',
'/static/highlight/github-dark.min.css',
'/static/mermaid.min.js',
'/static/fonts/fonts.css',
'/static/fonts/Outfit-300.ttf',
'/static/fonts/Outfit-400.ttf',
'/static/fonts/Outfit-500.ttf',
'/static/fonts/Outfit-600.ttf',
'/static/fonts/Outfit-700.ttf',
'/static/fonts/JetBrainsMono-400.ttf',
'/static/fonts/JetBrainsMono-500.ttf',
'/static/fonts/JetBrainsMono-600.ttf'
];
// Install: pre-cache all assets
self.addEventListener('install', event => {
event.waitUntil(
caches.open(CACHE).then(cache =>
cache.addAll(PRECACHE)
).then(() => self.skipWaiting())
);
});
// Activate: clean old caches, take control immediately
self.addEventListener('activate', event => {
event.waitUntil(
caches.keys().then(keys =>
Promise.all(
keys.filter(k => k !== CACHE).map(k => caches.delete(k))
)
).then(() => self.clients.claim())
);
});
// Fetch: cache-first for all self-hosted assets (no external deps)
self.addEventListener('fetch', event => {
const url = new URL(event.request.url);
// Only handle GET requests
if (event.request.method !== 'GET') return;
// Skip non-http(s) protocols
if (!url.protocol.startsWith('http')) return;
// For our own domain — cache-first with stale-while-revalidate
if (url.origin === self.location.origin) {
event.respondWith(cacheFirst(event.request));
return;
}
// Everything else — network only
});
async function cacheFirst(request) {
const cached = await caches.match(request);
if (cached) {
// Stale-while-revalidate: serve cached, update in background
fetch(request).then(response => {
if (response.ok) {
caches.open(CACHE).then(cache => cache.put(request, response));
}
}).catch(() => {});
return cached;
}
try {
const response = await fetch(request);
if (response.ok) {
const clone = response.clone();
caches.open(CACHE).then(cache => cache.put(request, clone));
}
return response;
} catch (err) {
return new Response('Offline', { status: 503 });
}
}