-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathInflate.service.js
99 lines (81 loc) · 2.67 KB
/
Inflate.service.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
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
/** @type { (byteLength: number) => (Uint8Array) } */
let malloc;
/** @type { (Uint8Array) => (void) } */
let free;
/** @type { (byteOffset: number, byteLength: number) => (ArrayBuffer) } */
let inflate;
/** @type { WebAssembly.Memory } */
let memory;
/**
*
* @param { number } byteOffset
* @param { number } byteLength
* @returns { ArrayBuffer }
*/
function copyToArrayBuffer(byteOffset, byteLength) {
return memory.buffer.slice(byteOffset, byteOffset + byteLength);
}
async function fetchInflate() {
const instance = (await WebAssembly.instantiateStreaming(fetch('./inflate.wasm'))
.catch(async _ => {
return await WebAssembly.instantiate(await (await fetch('./inflate.wasm')).arrayBuffer(), {
jsinterop: {
copyToArrayBuffer
},
env: {
emscripten_notify_memory_growth(_) {}
}
});
})).instance.exports;
/**
* @param { ArrayBuffer } arrayBuffer
*/
malloc = function(byteLength) {
const bufferPointer = instance["malloc"](byteLength);
return new Uint8Array(memory.buffer, bufferPointer, byteLength);
};
/**
* @param { Uint8Array } u8Array
*/
free = function(u8Array) {
instance["free"](u8Array.byteOffset);
};
inflate = instance["inflateFromBuffer"];
memory = instance.memory;
}
const inflatePromise = fetchInflate();
self.addEventListener('fetch', function(e) {
e.respondWith(
(async function() {
if (!e.request.url.endsWith(".wasm")) {
return await fetch(e.request);
}
const gzResponse = await fetch(e.request.url + '.gz');
if (gzResponse.status === 200) {
await inflatePromise;
const gzBuffer = await gzResponse.arrayBuffer();
const allocatedMemory = malloc(gzBuffer.byteLength);
allocatedMemory.set(new Uint8Array(gzBuffer));
const decompressed = inflate(allocatedMemory.byteOffset, allocatedMemory.byteLength);
free(allocatedMemory);
return new Response(
decompressed,
{
headers: {
'Content-Type': 'application/wasm'
}
}
);
}
return await fetch(e.request);
})()
)
});
self.addEventListener('install', e => {
console.log("install event");
e.waitUntil(self.skipWaiting());
});
self.addEventListener('activate', e => {
console.log("activate event");
e.waitUntil(self.clients.claim());
});