blob: 290f9a8cd7c0038379d2d7c9519098f85128378b (
plain)
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
|
/**
* A scriptable fake WebSocket for the connection tests. It records outbound
* frames and lets tests drive `open` / `message` / `close` from either side.
*/
import type { Transport } from '$lib/protocol/connection';
export class FakeSocket implements Transport {
onopen: ((ev?: unknown) => void) | null = null;
onclose: ((ev?: unknown) => void) | null = null;
onerror: ((ev?: unknown) => void) | null = null;
onmessage: ((ev: { data: unknown }) => void) | null = null;
readyState = 1; // CONNECTING
readonly sent: string[] = [];
closed = false;
send(data: string): void {
if (this.readyState !== 0) throw new Error('not open');
this.sent.push(data);
}
close(): void {
if (this.closed) return;
this.closed = true;
this.readyState = 3;
this.onclose?.();
}
// test drivers --------------------------------------------------------
open(): void {
this.readyState = 0;
this.onopen?.();
}
/** Deliver a raw server frame. */
serverSend(obj: object | string): void {
const data = typeof obj === 'string' ? obj : JSON.stringify(obj);
this.onmessage?.({ data });
}
/** The socket drops (server-side close). */
serverClose(): void {
if (this.closed) return;
this.closed = true;
this.readyState = 3;
this.onclose?.();
}
lastJson(): Record<string, unknown> | null {
if (this.sent.length === 0) return null;
return JSON.parse(this.sent[this.sent.length - 1]);
}
}
/** Creates and tracks a sequence of fake sockets handed to a connection. */
export class SocketSequence {
readonly sockets: FakeSocket[] = [];
// Arrow field so `this` survives being passed as a bare transport factory.
factory = (_url: string): Transport => {
const socket = new FakeSocket();
this.sockets.push(socket);
return socket;
};
get current(): FakeSocket {
return this.sockets[this.sockets.length - 1];
}
}
|