Files
HellCon/scripts/browser-context.ts
T

104 lines
4.4 KiB
TypeScript

// These functions are serialized into isolated browser pages by the checks.
// Keep their dependencies inside the function or on window.__hellcon.
export function installBrowserContext() {
function element<E extends Element>(selector: string): E {
const value = document.querySelector<E>(selector);
if (!value) throw new Error(`Missing element: ${selector}`);
return value;
}
const context = {
element,
peers: [] as RTCPeerConnection[],
aborted: false,
releaseWrite: undefined as (() => void) | undefined,
click(label: string) {
const button = [...document.querySelectorAll('button')].find(button => button.textContent?.trim() === label);
if (!button || button.disabled) throw new Error(`Unavailable button: ${label}`);
button.click();
},
input(selector: string, value: string) {
const input = element<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>(selector);
input.value = value;
input.dispatchEvent(new Event(input.tagName === 'SELECT' ? 'change' : 'input', { bubbles: true }));
},
chooseFile(size: number, name: string) {
const input = element<HTMLInputElement>('#file-input');
const files = new DataTransfer();
files.items.add(new File([new Uint8Array(size).fill(123)], name));
input.files = files.files;
input.dispatchEvent(new Event('change', { bubbles: true }));
},
async wait<T>(check: () => T | Promise<T>): Promise<NonNullable<Awaited<T>>> {
const deadline = Date.now() + 36000;
while (Date.now() < deadline) {
const value = await check();
if (value) return value;
await new Promise<void>(resolve => setTimeout(resolve, 20));
}
throw new Error('UI condition timed out: ' + document.body.innerText);
},
};
window.__hellcon = context;
}
declare global {
interface Window {
__hellcon: {
element<E extends Element>(selector: string): E;
peers: RTCPeerConnection[];
aborted: boolean;
releaseWrite?: () => void;
click(label: string): void;
input(selector: string, value: string): void;
chooseFile(size: number, name: string): void;
wait<T>(check: () => T | Promise<T>): Promise<NonNullable<Awaited<T>>>;
};
}
}
export function forceRelay(transport: 'udp' | 'tcp') {
const NativePC = window.RTCPeerConnection;
window.RTCPeerConnection = class extends NativePC {
constructor(config?: RTCConfiguration) {
super({ ...config, iceTransportPolicy: 'relay' });
window.__hellcon.peers.push(this);
}
override setConfiguration(config: RTCConfiguration) {
const iceServers = (config.iceServers ?? []).filter(server => server.username).map(server => ({
...server,
urls: (Array.isArray(server.urls) ? server.urls : [server.urls]).filter(url => url.endsWith(`transport=${transport}`)),
}));
super.setConfiguration({ ...config, iceServers, iceTransportPolicy: 'relay' });
}
};
}
export async function relayCandidateTypes() {
for (let attempt = 0; attempt < 50; attempt++) {
const pc = window.__hellcon.peers.at(-1);
if (!pc) throw new Error('No peer connection');
const stats = await pc.getStats();
const transport = [...stats.values()].find((entry: RTCStats) => entry.type === 'transport') as RTCTransportStats | undefined;
const pair = transport?.selectedCandidatePairId ? stats.get(transport.selectedCandidatePairId) as RTCIceCandidatePairStats | undefined : undefined;
if (pair) {
const local = stats.get(pair.localCandidateId) as (RTCStats & { candidateType: RTCIceCandidateType }) | undefined;
const remote = stats.get(pair.remoteCandidateId) as (RTCStats & { candidateType: RTCIceCandidateType }) | undefined;
return [local?.candidateType, remote?.candidateType];
}
await new Promise<void>(resolve => setTimeout(resolve, 100));
}
throw new Error('No selected ICE candidate pair in WebRTC statistics');
}
export function simulateSlowDisk() {
window.__hellcon.aborted = false;
// Only the methods used by the app are implemented by this browser test double.
window.showSaveFilePicker = async () => ({
createWritable: async () => ({
write() { return new Promise<void>(resolve => { window.__hellcon.releaseWrite = resolve; }); },
async close() {},
async abort() { window.__hellcon.aborted = true; window.__hellcon.releaseWrite?.(); },
}),
});
}