-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsw.js
61 lines (51 loc) · 1.58 KB
/
sw.js
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
importScripts("wasm_exec.js");
const WASM_MODULE_FILEPATH = "/main.wasm";
const EXTENSION_REGEXP = /.*\.(.+)$/;
// getting wasm module from cache or fallback to network
// also update cache if network used
function getWasmResponse() {
const wasmRequest = new Request(WASM_MODULE_FILEPATH);
return caches.open("wasm-esbuild").then(function (cache) {
return cache.match(wasmRequest).then(function (match) {
return (
match ??
fetch(wasmRequest).then((response) => {
cache.put(wasmRequest, response);
return response;
})
);
});
});
}
self.addEventListener("install", function (event) {
event.waitUntil(
caches.open("wasm-esbuild").then(function (cache) {
cache.add(WASM_MODULE_FILEPATH);
})
);
});
self.addEventListener("fetch", async function (event) {
if (event.request.url.endsWith(".ts")) {
const wasmResponse = getWasmResponse();
const go = new Go();
return event.respondWith(
WebAssembly.instantiateStreaming(wasmResponse, go.importObject).then(
(result) => {
go.run(result.instance);
return fetch(event.request)
.then((response) => response.text())
.then((source) => {
const result = transform(source, { loader: "tsx" });
return new Response(result, {
status: 200,
headers: {
"Content-Type": "application/javascript; charset=UTF-8",
},
});
});
}
)
);
}
return event.respondWith(fetch(event.request));
});