Files
HellCon/public/sw.js
T
SchluffeandClaude Opus 5.5 b6b6e7c29b Lint and format with Biome, and retire used share codes
Biome formats and lints the TypeScript, the Vue templates and the CSS:
pnpm lint checks, pnpm format fixes. It keeps the existing style, single
quotes and 120 columns, and leaves the vendored logo alone. Besides its
recommended rules it looks for promises nobody awaits. Rules that only
flagged deliberate code are off: non-null assertions that state what the
code guarantees, CSS order where no two rules set the same property, and
fieldset for role="group". The one-time formatting pass mostly splits
long chains.

Promises that are deliberately not awaited are marked with void, none of
them can reject today. Buttons say type="button", the any for peer
messages and the checkbox switch keep their reasons in ignore comments.

The sender's code also counts as no longer valid once a transfer started:
that closes the trackers, so another receiver would wait for nothing,
yet the card still offered the code with Copy. The tracker transfer
tests check it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 18:46:33 +02:00

89 lines
3.7 KiB
JavaScript

// Streams received files into the browser's download manager. It is the only script besides the app
// because service workers can only be registered from a same-origin script URL. Registered with the
// scope download/ by src/core.ts, it sees no other requests.
// Downloads by id while the page sends chunks: the queue, the stream controller, its wake up, the
// reply port and how many bytes the download manager has read.
const downloads = new Map();
// Responses by download id, until the download navigation fetches them. Each is served only once.
const responses = new Map();
function open(id, { name, size }, port) {
// The page checks the sender's offer already. Anything else would throw below or lie to the browser.
if (typeof name !== 'string' || !Number.isSafeInteger(size) || size < 0) return port.postMessage('failed');
const download = { chunks: [], wake: () => {}, port, read: 0, reported: 0 };
const body = new ReadableStream(
{
start: (controller) => (download.controller = controller),
// With highWaterMark 0 the download manager pulls only when it wants more, so reaching the end
// marker here means it has read every byte.
async pull(controller) {
while (!download.chunks.length) await new Promise((resolve) => (download.wake = resolve));
const chunk = download.chunks.shift();
if (chunk) {
download.read += chunk.byteLength;
// Every MiB, src/core.ts forwards it to the sender for its flow control window.
if (download.read - download.reported >= 2 ** 20) {
download.reported = download.read;
port.postMessage(download.read);
}
return controller.enqueue(chunk);
}
controller.close();
downloads.delete(id);
port.postMessage('finished');
},
// The user cancelled the download.
cancel: () => {
downloads.delete(id);
port.postMessage('cancelled');
},
},
{ highWaterMark: 0 },
);
downloads.set(id, download);
// RFC 8187 encoding, which leaves nothing in the name that could end the header value.
const encoded = encodeURIComponent(name.toWellFormed()).replace(
/['()*]/g,
(char) => `%${char.charCodeAt(0).toString(16)}`,
);
const headers = {
'Content-Type': 'application/octet-stream',
'Content-Length': String(size),
'Content-Disposition': `attachment; filename*=UTF-8''${encoded}`,
};
responses.set(id, new Response(body, { headers }));
port.postMessage('ready');
}
// The page posts the metadata with a reply port first, then every chunk as its own message and
// finally done (queued as the end marker null) or an error. Pings come in between.
self.addEventListener('message', ({ data, ports: [port] }) => {
// Only keeps this worker alive while a transfer stalls, see KEEPALIVE in src/core.ts.
if (data.ping) return;
if (port) return open(data.id, data, port);
const download = downloads.get(data.id);
if (!download) return;
if (data.error) {
download.controller.error(new Error(data.error));
downloads.delete(data.id);
download.port.postMessage('failed');
} else {
download.chunks.push(data.chunk ? new Uint8Array(data.chunk) : null);
download.wake();
}
});
self.addEventListener('fetch', (event) => {
const id = new URL(event.request.url).pathname.split('/').pop();
// download/ itself is the empty page src/core.ts keeps open to hold this worker during a transfer.
if (!id)
return event.respondWith(
new Response('<!doctype html>', { headers: { 'Content-Type': 'text/html; charset=utf-8' } }),
);
const response = responses.get(id);
responses.delete(id);
event.respondWith(response ?? new Response('download expired', { status: 404 }));
});