Repository navigation
Expand file tree
/
Copy pathsw.ts
More file actions
178 lines (160 loc) · 6.55 KB
/
Copy pathsw.ts
File metadata and controls
178 lines (160 loc) · 6.55 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
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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
import { defaultCache } from "@serwist/next/worker";
import { NetworkOnly, Serwist } from "serwist";
import type { PrecacheEntry, SerwistGlobalConfig } from "serwist";
// This declares the value of `injectionPoint` to TypeScript.
// `injectionPoint` is the string that will be replaced by the
// actual precache manifest. By default, this string is set to
// `"self.__SW_MANIFEST"`.
declare global {
interface WorkerGlobalScope extends SerwistGlobalConfig {
__SW_MANIFEST: (PrecacheEntry | string)[] | undefined;
}
}
declare const self: ServiceWorkerGlobalScope;
const treePdfCacheString = "tree-data-v"; // IMPORTANT: This string should NEVER be changed, otherwise the old caches will not be identifyable anymore
const currentTreePdfVersion = 1; // Current Tree PDF version, needs to be increased every time new PDFs are deployed
const TREE_CACHE_NAME = `${treePdfCacheString}${currentTreePdfVersion}`; // Cache name for Tree profile data
// Create an array of 'tree-data-v[1 - currentVersion]' strings for the caches to be removed
const OLD_TREE_PDF_CACHES = Array.from(Array(currentTreePdfVersion).keys()).map(
(version) => `${treePdfCacheString}${version}`,
);
const soPdfCacheString = "so-data-v"; // IMPORTANT: This string should NEVER be changed, otherwise the old caches will not be identifyable anymore
const currentSoPdfVersion = 3; // Current SO PDF version, needs to be increased every time new PDFs are deployed
const SO_CACHE_NAME = `${soPdfCacheString}${currentSoPdfVersion}`; // Cache name for SO profile data
// Create an array of 'so-data-v[1 - currentVersion]' strings for the caches to be removed
const OLD_SO_PDF_CACHES = Array.from(Array(currentSoPdfVersion).keys()).map(
(version) => `${soPdfCacheString}${version}`,
);
const tileCacheString = "tree-app-tiles-v"; // IMPORTANT: This string should NEVER be changed, otherwise the old caches will not be identifyable anymore
const currentTileVersion = 27; // Current tile version, needs to be increased every time new tiles are deployed
const TILE_CACHE_NAME = `${tileCacheString}${currentTileVersion}`;
// Create an array of 'tree-app-tiles-v[1 - currentVersion]' strings for the caches to be removed
const OLD_TILE_CACHES = Array.from(Array(currentTileVersion).keys()).map(
(version) => `${tileCacheString}${version}`,
);
// This allows the web app to trigger skipWaiting via
// registration.waiting.postMessage({type: 'SKIP_WAITING'})
self.addEventListener("message", (event) => {
if (event.data && (event.data as MessageEvent).type === "SKIP_WAITING") {
void self.skipWaiting();
}
});
[...OLD_SO_PDF_CACHES, ...OLD_TILE_CACHES, ...OLD_TREE_PDF_CACHES].forEach(
(OLD_CACHE) => void caches.delete(OLD_CACHE),
);
self.addEventListener("install", (event) => {
const soPdfEndpoint = process.env.NEXT_PUBLIC_SO_PDF_ENDPOINT;
const vectorTilesEndpoint = process.env.NEXT_PUBLIC_VECTOR_TILES_ENDPOINT;
const treePdfEndpoint = process.env.NEXT_PUBLIC_TREE_PDF_ENDPOINT;
event.waitUntil(
(async () => {
await caches.open(TILE_CACHE_NAME).then((cache) =>
fetch(`${vectorTilesEndpoint}/tiles.txt`)
.then((response) => response.text())
.then(async (response) => {
const tiles = response.split(/\r?\n/);
// eslint-disable-next-line no-plusplus
for (const tile of tiles) {
const tileUrl = `${vectorTilesEndpoint}/${tile}`;
// eslint-disable-next-line no-await-in-loop
if (tile && !(await cache.match(tileUrl))) {
try {
// eslint-disable-next-line no-await-in-loop
const tileResponse = await fetch(tileUrl);
void cache.put(tileUrl, tileResponse);
} catch (error) {
// Some tiles do not exist.
}
}
}
return true;
}),
);
await caches.open(SO_CACHE_NAME).then((cache) =>
fetch(`${soPdfEndpoint}/list.txt`)
.then((response) => response.text())
.then(async (response) => {
const forestTypes = response.split(/\r?\n/);
for (const forestType of forestTypes) {
const pdfUrl = `${soPdfEndpoint}/${forestType}`;
if (forestType && !(await cache.match(pdfUrl))) {
try {
const pdfResponse = await fetch(pdfUrl);
await cache.put(pdfUrl, pdfResponse);
} catch (error) {
// Some PDFs do not exist.
}
}
}
return true;
}),
);
await caches.open(TREE_CACHE_NAME).then((cache) =>
fetch(`${treePdfEndpoint}/list.txt`)
.then((response) => response.text())
.then(async (response) => {
const treeTypes = response.split(/\r?\n/);
for (const treeType of treeTypes) {
const pdfUrl = `${treePdfEndpoint}/${treeType}`;
if (treeType && !(await cache.match(pdfUrl))) {
try {
const pdfResponse = await fetch(pdfUrl);
await cache.put(pdfUrl, pdfResponse);
} catch (error) {
// Some PDFs do not exist.
}
}
}
return true;
}),
);
})(),
);
});
self.addEventListener("activate", (event) => {
event.waitUntil(
(async () => {
const clients = await self.clients.matchAll({
includeUncontrolled: true,
});
clients.forEach((client) => {
client.postMessage({ type: "CACHE_READY" });
});
})(),
);
});
// eslint-disable-next-line no-restricted-globals
self.addEventListener("fetch", (event) => {
const cacheUrls = [
process.env.NEXT_PUBLIC_VECTOR_TILES_ENDPOINT,
process.env.NEXT_PUBLIC_SO_PDF_ENDPOINT,
process.env.NEXT_PUBLIC_TREE_PDF_ENDPOINT,
];
const shouldFetchFromCache = cacheUrls.some(
(url) => url && event.request.url.startsWith(url),
);
if (shouldFetchFromCache) {
event.respondWith(
caches
.match(event.request)
.then((response) => response ?? fetch(event.request)),
);
}
});
const serwist = new Serwist({
clientsClaim: true,
navigationPreload: true,
precacheEntries: self.__SW_MANIFEST,
runtimeCaching: [
...defaultCache,
{
handler: new NetworkOnly(),
matcher: ({ url }) =>
/^https:\/\/wmts10\.geo\.admin\.ch\/1\.0\.0\/ch\.swisstopo\.(pixelkarte-grau|swissimage)\/default\/current\/3857\/.*\.jpeg$/i.test(
url.href,
),
},
],
skipWaiting: true,
});
serwist.addEventListeners();