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>
This commit is contained in:
1 parent
2167b528b2
commit
b6b6e7c29b
9 files changed
+371
-122
No files matched your search
+71
-55
@@ -106,6 +106,7 @@ function createPeerConnection(signal: AbortSignal) {
|
||||
|
||||
// Peers and trackers send JSON objects. Anything else, malformed or not an object, counts as nothing.
|
||||
// Whatever is read from one has to be checked, the any only saves the casts for that.
|
||||
// biome-ignore lint/suspicious/noExplicitAny: checked field by field, see above
|
||||
type Message = Record<string, any>;
|
||||
|
||||
function parse(data: unknown): Message | undefined {
|
||||
@@ -185,7 +186,12 @@ async function gatherIce(pc: RTCPeerConnection) {
|
||||
// versa, otherwise someone interposed on the signaling.
|
||||
function securityCheck(pc: RTCPeerConnection) {
|
||||
const short = (sdp = '') =>
|
||||
sdp.match(/a=fingerprint:\S+ ([0-9A-F:]+)/i)?.[1]?.toUpperCase().split(':').slice(0, 8).join(' ') ?? '?';
|
||||
sdp
|
||||
.match(/a=fingerprint:\S+ ([0-9A-F:]+)/i)?.[1]
|
||||
?.toUpperCase()
|
||||
.split(':')
|
||||
.slice(0, 8)
|
||||
.join(' ') ?? '?';
|
||||
return { local: short(pc.localDescription?.sdp), remote: short(pc.remoteDescription?.sdp) };
|
||||
}
|
||||
|
||||
@@ -308,7 +314,10 @@ async function sendFile(
|
||||
await new Promise<void>((resolve) => (wake = resolve));
|
||||
}
|
||||
// E.g. the file was changed or deleted since it was picked.
|
||||
const chunk = await file.slice(offset, offset + CHUNK_SIZE).arrayBuffer().catch(() => undefined);
|
||||
const chunk = await file
|
||||
.slice(offset, offset + CHUNK_SIZE)
|
||||
.arrayBuffer()
|
||||
.catch(() => undefined);
|
||||
if (!chunk) return stop(`could not read ${file.name} anymore`);
|
||||
if (!open()) return;
|
||||
channel.send(chunk);
|
||||
@@ -381,9 +390,9 @@ function receiveFile(
|
||||
let complete = false;
|
||||
let ended = false;
|
||||
// Chunks can arrive before the worker is held, chaining every post on this keeps them in order.
|
||||
let worker: Promise<ServiceWorker | void> = Promise.resolve();
|
||||
let worker: Promise<ServiceWorker | undefined> = Promise.resolve(undefined);
|
||||
const post = (message: object, transfer: Transferable[] = []) =>
|
||||
worker.then((worker) => worker?.postMessage({ id, ...message }, transfer));
|
||||
void worker.then((worker) => worker?.postMessage({ id, ...message }, transfer));
|
||||
// To the sender, see sendFile.
|
||||
const reply = (message: object) => channel.readyState === 'open' && channel.send(JSON.stringify(message));
|
||||
// A data channel closes only after sending what it buffered, so the last reply still arrives.
|
||||
@@ -409,51 +418,54 @@ function receiveFile(
|
||||
}
|
||||
|
||||
function startDownload() {
|
||||
worker = holdWorker().then(({ frame, worker }) => {
|
||||
frames.push(frame);
|
||||
keepalive = setInterval(() => post({ ping: true }), KEEPALIVE);
|
||||
// Only if something else than an update stops it, e.g. clearing the site data. It can't answer.
|
||||
worker.addEventListener('statechange', () => {
|
||||
if (worker.state !== 'redundant') return;
|
||||
fail('service worker stopped');
|
||||
release();
|
||||
});
|
||||
const { port1, port2 } = new MessageChannel();
|
||||
port1.onmessage = ({ data }) => {
|
||||
if (typeof data === 'number') {
|
||||
read = data;
|
||||
events.progress(read, meta!.size);
|
||||
return reply({ read });
|
||||
}
|
||||
if (data === 'ready' && !ended) {
|
||||
// A navigation, not fetch(): only navigations hand the response to the download manager.
|
||||
const download = document.createElement('iframe');
|
||||
download.hidden = true;
|
||||
download.src = `download/${id}`;
|
||||
document.body.append(download);
|
||||
frames.push(download);
|
||||
return;
|
||||
}
|
||||
if (data === 'failed') fail('the service worker refused it');
|
||||
if (data === 'finished') {
|
||||
events.log('download complete');
|
||||
events.progress(meta!.size, meta!.size);
|
||||
reply({ done: true });
|
||||
}
|
||||
if (data === 'cancelled' && !ended) {
|
||||
events.log('download cancelled');
|
||||
reply({ error: 'download cancelled' });
|
||||
}
|
||||
ended = true;
|
||||
channel.close();
|
||||
release();
|
||||
};
|
||||
worker.postMessage({ id, ...meta }, [port2]);
|
||||
return worker;
|
||||
}, (error) => fail(String(error)));
|
||||
worker = holdWorker().then(
|
||||
({ frame, worker }) => {
|
||||
frames.push(frame);
|
||||
keepalive = setInterval(() => post({ ping: true }), KEEPALIVE);
|
||||
// Only if something else than an update stops it, e.g. clearing the site data. It can't answer.
|
||||
worker.addEventListener('statechange', () => {
|
||||
if (worker.state !== 'redundant') return;
|
||||
fail('service worker stopped');
|
||||
release();
|
||||
});
|
||||
const { port1, port2 } = new MessageChannel();
|
||||
port1.onmessage = ({ data }) => {
|
||||
if (typeof data === 'number') {
|
||||
read = data;
|
||||
events.progress(read, meta!.size);
|
||||
return reply({ read });
|
||||
}
|
||||
if (data === 'ready' && !ended) {
|
||||
// A navigation, not fetch(): only navigations hand the response to the download manager.
|
||||
const download = document.createElement('iframe');
|
||||
download.hidden = true;
|
||||
download.src = `download/${id}`;
|
||||
document.body.append(download);
|
||||
frames.push(download);
|
||||
return;
|
||||
}
|
||||
if (data === 'failed') fail('the service worker refused it');
|
||||
if (data === 'finished') {
|
||||
events.log('download complete');
|
||||
events.progress(meta!.size, meta!.size);
|
||||
reply({ done: true });
|
||||
}
|
||||
if (data === 'cancelled' && !ended) {
|
||||
events.log('download cancelled');
|
||||
reply({ error: 'download cancelled' });
|
||||
}
|
||||
ended = true;
|
||||
channel.close();
|
||||
release();
|
||||
};
|
||||
worker.postMessage({ id, ...meta }, [port2]);
|
||||
return worker;
|
||||
},
|
||||
(error) => void fail(String(error)),
|
||||
);
|
||||
}
|
||||
|
||||
handshake.checked.then(() => {
|
||||
void handshake.checked.then(() => {
|
||||
confirmed = true;
|
||||
reply({ ok: true });
|
||||
events.log('waiting for the sender');
|
||||
@@ -528,8 +540,7 @@ export async function createOffer(file: File, events: Events, signal: AbortSigna
|
||||
events = live(events, signal);
|
||||
const pc = createPeerConnection(signal);
|
||||
const channel = pc.createDataChannel('file');
|
||||
channel.onopen = () =>
|
||||
sendFile(pc, channel, file, events, connected(pc, channel, 'manual exchange', events), signal);
|
||||
channel.onopen = () => sendFile(pc, channel, file, events, connected(pc, channel, 'manual exchange', events), signal);
|
||||
failUnconnected(pc, () => channel.readyState !== 'connecting', events);
|
||||
await pc.setLocalDescription();
|
||||
await gatherIce(pc);
|
||||
@@ -655,7 +666,7 @@ export async function sendViaTracker(file: File, events: Events, signal: AbortSi
|
||||
let shared = false;
|
||||
let expired = false;
|
||||
// The latest offer that came while busy, answered once that peer is out.
|
||||
let waiting: (() => void) | undefined;
|
||||
let waiting: (() => Promise<void>) | undefined;
|
||||
|
||||
// Without a tracker no further receiver can find the share.
|
||||
const stranded = () => !shared && !busy && !trackers.some((tracker) => tracker.alive());
|
||||
@@ -678,10 +689,14 @@ export async function sendViaTracker(file: File, events: Events, signal: AbortSi
|
||||
events.log('waiting for the next receiver');
|
||||
const offer = waiting;
|
||||
waiting = undefined;
|
||||
offer?.();
|
||||
void offer?.();
|
||||
}
|
||||
|
||||
async function answer(ws: WebSocket, url: string, msg: { offer: { sdp: string }; peer_id: string; offer_id: string }) {
|
||||
async function answer(
|
||||
ws: WebSocket,
|
||||
url: string,
|
||||
msg: { offer: { sdp: string }; peer_id: string; offer_id: string },
|
||||
) {
|
||||
busy = true;
|
||||
events.log(`offer via ${url}`);
|
||||
const pc = createPeerConnection(signal);
|
||||
@@ -708,7 +723,7 @@ export async function sendViaTracker(file: File, events: Events, signal: AbortSi
|
||||
expiry.close();
|
||||
for (const tracker of trackers) tracker.close();
|
||||
};
|
||||
sendFile(pc, channel, file, events, { ...handshake, start }, signal);
|
||||
void sendFile(pc, channel, file, events, { ...handshake, start }, signal);
|
||||
};
|
||||
pc.addEventListener('connectionstatechange', () => {
|
||||
if (pc.connectionState === 'failed') giveUp('receiver did not connect');
|
||||
@@ -740,7 +755,7 @@ export async function sendViaTracker(file: File, events: Events, signal: AbortSi
|
||||
if (typeof msg.offer_id !== 'string') return;
|
||||
const offer = { offer: { sdp: msg.offer.sdp }, peer_id: msg.peer_id, offer_id: msg.offer_id };
|
||||
if (busy) waiting = () => answer(tracker.ws, url, offer);
|
||||
else answer(tracker.ws, url, offer);
|
||||
else void answer(tracker.ws, url, offer);
|
||||
},
|
||||
() => stranded() && end(noTracker(trackers)),
|
||||
() => announce(tracker.ws, hash, peerId, { left: 0 }),
|
||||
@@ -830,7 +845,8 @@ export async function receiveViaTracker(code: string, events: ReceiveEvents, sig
|
||||
receiveFile(pc, channel, events, { ...handshake, start }, signal);
|
||||
};
|
||||
pc.addEventListener('connectionstatechange', () => {
|
||||
if (pc.connectionState === 'failed' && channel.readyState === 'connecting') retry(`sender via ${url} did not connect`);
|
||||
if (pc.connectionState === 'failed' && channel.readyState === 'connecting')
|
||||
retry(`sender via ${url} did not connect`);
|
||||
});
|
||||
|
||||
pc.setLocalDescription()
|
||||
|
||||
Reference in new issue
Block a user