-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsw.js
More file actions
64 lines (52 loc) · 1.93 KB
/
sw.js
File metadata and controls
64 lines (52 loc) · 1.93 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
// Service Worker for streaming downloads
// Used as a fallback when File System Access API is not available
self.addEventListener('install', () => {
self.skipWaiting();
});
self.addEventListener('activate', (event) => {
event.waitUntil(self.clients.claim());
});
const map = new Map();
self.addEventListener('message', (event) => {
if (event.data.action === 'stream-download') {
// Register a new stream for download
const { filename, streamPort } = event.data;
// We generate a unique ID for this download
const id = Math.random().toString(36).slice(2);
map.set(id, { filename, streamPort });
// Tell the client where to redirect to trigger the download
event.ports[0].postMessage({ downloadUrl: `./download-${id}` });
}
});
self.addEventListener('fetch', (event) => {
const url = new URL(event.request.url);
const match = url.pathname.match(/\/download-([a-z0-9]+)$/);
if (match) {
const id = match[1];
const data = map.get(id);
if (data) {
map.delete(id);
const { filename, streamPort } = data;
const stream = new ReadableStream({
start(controller) {
streamPort.onmessage = (event) => {
if (event.data.action === 'data') {
controller.enqueue(event.data.chunk);
} else if (event.data.action === 'end') {
controller.close();
} else if (event.data.action === 'error') {
controller.error(event.data.error);
}
};
}
});
const headers = new Headers({
'Content-Type': 'application/octet-stream',
'Content-Disposition': `attachment; filename="${encodeURIComponent(filename)}"`,
// We don't know the size in advance for streaming, but if we did we could set Content-Length
'X-Content-Type-Options': 'nosniff'
});
event.respondWith(new Response(stream, { headers }));
}
}
});