forked from ChelseaKR/habitable
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathservice-worker.js
More file actions
94 lines (85 loc) · 2.5 KB
/
Copy pathservice-worker.js
File metadata and controls
94 lines (85 loc) · 2.5 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
87
88
89
90
91
92
93
94
// SPDX-License-Identifier: AGPL-3.0-or-later
// habitable — offline shell cache. API responses are never cached.
"use strict";
// Bump whenever an authenticated shell asset changes. Keeping the old cache name
// would let a pre-auth app.js survive an upgrade and send tokenless API requests.
var CACHE = "habitable-shell-v9-repair-trail";
// Relative URLs so the worker matches however the shell is served.
var SHELL = [
"./",
"index.html",
"styles.css",
"app.js",
"i18n/en.json",
"i18n/es.json",
"manifest.webmanifest",
"fonts/BarlowCondensed-SemiBold.ttf",
"fonts/BarlowCondensed-ExtraBold.ttf",
"icons/icon.svg",
"icons/icon-192.png",
"icons/icon-512.png",
"icons/icon-maskable-512.png",
"icons/apple-touch-icon.png"
];
self.addEventListener("install", function (event) {
event.waitUntil(
caches.open(CACHE).then(function (cache) {
return cache.addAll(SHELL);
}).then(function () {
return self.skipWaiting();
})
);
});
self.addEventListener("activate", function (event) {
event.waitUntil(
caches.keys().then(function (keys) {
return Promise.all(
keys.map(function (key) {
if (key !== CACHE) {
return caches.delete(key);
}
return null;
})
);
}).then(function () {
return self.clients.claim();
})
);
});
self.addEventListener("fetch", function (event) {
var request = event.request;
// Only handle GET; let writes (POST etc.) go straight to the network.
if (request.method !== "GET") {
return;
}
var url = new URL(request.url);
// Network-only for the API: never cache evidence or status responses.
if (url.pathname.indexOf("/api/") === 0) {
event.respondWith(fetch(request));
return;
}
// Cache-first for the static shell, with a network fallback that
// refreshes the cache opportunistically.
event.respondWith(
caches.match(request).then(function (cached) {
if (cached) {
return cached;
}
return fetch(request).then(function (response) {
if (response && response.ok && url.origin === self.location.origin) {
var copy = response.clone();
caches.open(CACHE).then(function (cache) {
cache.put(request, copy);
});
}
return response;
});
}).catch(function () {
// Last resort for navigations when fully offline.
if (request.mode === "navigate") {
return caches.match("index.html");
}
return Response.error();
})
);
});