@stefan.inc/game-networking 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/types.ts ADDED
@@ -0,0 +1,164 @@
1
+ import { DEFAULT_ROOM, ID_PATTERN } from "./signal-protocol.ts";
2
+ import type { Transport } from "./transport.ts";
3
+
4
+ export type PeerId = string & { readonly __brand: "PeerId" };
5
+
6
+ export function peerId(value: string): PeerId {
7
+ if (!ID_PATTERN.test(value))
8
+ throw new TypeError(`Invalid peer id ${JSON.stringify(value)}: use 1-64 of [A-Za-z0-9_-]`);
9
+ return value as PeerId;
10
+ }
11
+
12
+ export function createPeerId(): PeerId {
13
+ return peerId(crypto.randomUUID());
14
+ }
15
+
16
+ /** Letters and digits that are hard to mistake for one another when read aloud or typed. */
17
+ const ROOM_CODE_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
18
+
19
+ /**
20
+ * A random room name short enough to say out loud. Nothing reserves it: a host that finds the room taken
21
+ * (`host-taken`) makes another.
22
+ */
23
+ export function createRoomCode(length = 4, alphabet = ROOM_CODE_ALPHABET): string {
24
+ if (!Number.isInteger(length) || length < 1 || length > 64)
25
+ throw new RangeError("A room code has 1-64 characters");
26
+ if (alphabet.length < 2 || !ID_PATTERN.test(alphabet))
27
+ throw new TypeError("A room code alphabet is 2-64 of [A-Za-z0-9_-]");
28
+ // The largest multiple of the alphabet's size that fits a byte: bytes above it would favour the first letters.
29
+ const fair = 256 - (256 % alphabet.length);
30
+ let code = "";
31
+ while (code.length < length)
32
+ for (const byte of crypto.getRandomValues(new Uint8Array(length)))
33
+ if (byte < fair && code.length < length) code += alphabet[byte % alphabet.length];
34
+ return code;
35
+ }
36
+
37
+ export function roomName(value: string = DEFAULT_ROOM): string {
38
+ if (!ID_PATTERN.test(value))
39
+ throw new TypeError(`Invalid room ${JSON.stringify(value)}: use 1-64 of [A-Za-z0-9_-]`);
40
+ return value;
41
+ }
42
+
43
+ export type ConnectionStatus = "connecting" | "connected" | "reconnecting" | "closed";
44
+
45
+ export type PeerInfo = { id: PeerId; name: string; connected: boolean };
46
+
47
+ /**
48
+ * Fatal codes end the session: `unauthorized` (wrong secret), `host-taken` (another client hosts the room),
49
+ * `replaced` (the same selfId connected from a newer tab, or another client took the room over) and `removed` (the
50
+ * host took this player out of the room; the message is the host's reason). The rest report something dropped and
51
+ * the session carries on: `no-host` is a peer finding nobody hosting its room, which it goes on waiting for.
52
+ */
53
+ export type NetErrorCode =
54
+ | "unauthorized"
55
+ | "host-taken"
56
+ | "replaced"
57
+ | "removed"
58
+ | "no-host"
59
+ | "invalid-message"
60
+ | "invalid-presence"
61
+ | "invalid-state"
62
+ | "protocol";
63
+
64
+ const FATAL: ReadonlySet<NetErrorCode> = new Set([
65
+ "unauthorized",
66
+ "host-taken",
67
+ "replaced",
68
+ "removed",
69
+ ]);
70
+
71
+ export class NetError extends Error {
72
+ override readonly name = "NetError";
73
+ readonly code: NetErrorCode;
74
+
75
+ constructor(code: NetErrorCode, message: string, options?: ErrorOptions) {
76
+ super(message, options);
77
+ this.code = code;
78
+ }
79
+
80
+ get fatal(): boolean {
81
+ return FATAL.has(this.code);
82
+ }
83
+ }
84
+
85
+ export type SessionEvents<Msg, Presence, State> = {
86
+ message: (msg: Msg, from: PeerId) => void;
87
+ presence: (presence: Presence, from: PeerId) => void;
88
+ /** Full roster, host included, same list on every client. */
89
+ peers: (peers: PeerInfo[]) => void;
90
+ /** On a peer: the host's state, or this player's view of it, each time it changes. Never fired on the host. */
91
+ state: (state: State) => void;
92
+ status: (status: ConnectionStatus) => void;
93
+ error: (error: NetError) => void;
94
+ };
95
+
96
+ /** `State` is what this client holds: on a peer, the view of the state the host sends it. */
97
+ export interface Session<Msg, Presence, State = unknown> {
98
+ readonly role: "host" | "peer";
99
+ readonly selfId: PeerId;
100
+ readonly room: string;
101
+ readonly status: ConnectionStatus;
102
+ readonly peers: PeerInfo[];
103
+ /** On the host, the state last set. On a peer, the last one received, frozen. Undefined before the first. */
104
+ readonly state: State | undefined;
105
+ /**
106
+ * Host: broadcast, send to one peer, or broadcast to everyone but one (a relay of what that peer sent). Peer: always
107
+ * goes to the host; `to` is rejected. Returns false when there was no link to send on and the message was dropped,
108
+ * so gate game actions on `status === 'connected'`.
109
+ */
110
+ send(msg: Msg, to?: PeerId | { except: PeerId }): boolean;
111
+ /** Lossy. Coalesced to the latest value and rate limited. The host relays it to the other peers. */
112
+ sendPresence(presence: Presence): void;
113
+ on<E extends keyof SessionEvents<Msg, Presence, State>>(
114
+ event: E,
115
+ handler: SessionEvents<Msg, Presence, State>[E],
116
+ ): () => void;
117
+ close(): void;
118
+ }
119
+
120
+ export interface HostSession<Msg, Presence, State = unknown> extends Session<Msg, Presence, State> {
121
+ readonly role: "host";
122
+ /**
123
+ * The state every peer mirrors. A peer is sent the whole of it when it connects and what changed after that, in
124
+ * order with the messages sent around it. `state` is plain JSON and is never changed after it is given here: pass a
125
+ * new value that shares what did not change, as an immer or a reducer state does.
126
+ */
127
+ setState(state: State): void;
128
+ /**
129
+ * Takes a player out of the room: its session ends with a `removed` error carrying `reason`, and it leaves the
130
+ * roster. Also how the host forgets a player who is gone. Nothing stops the player joining again.
131
+ */
132
+ remove(peer: PeerId, reason?: string): void;
133
+ /** What the room list shows for this room: any JSON up to 2048 characters, or null to take it off the list. */
134
+ publish(info: unknown): void;
135
+ }
136
+
137
+ export type SessionOptions<Msg, Presence> = {
138
+ /** Stable across reloads; the caller persists it. */
139
+ selfId: PeerId;
140
+ name: string;
141
+ transport: Transport;
142
+ /** 1-64 of [A-Za-z0-9_-]. A game with one table leaves it out. */
143
+ room?: string;
144
+ /** Boundary validation. Throws on bad input. */
145
+ parseMsg: (raw: unknown) => Msg;
146
+ parsePresence: (raw: unknown) => Presence;
147
+ /** Default 30. */
148
+ presenceHz?: number;
149
+ };
150
+
151
+ export type HostOptions<Msg, Presence, State, View> = SessionOptions<Msg, Presence> & {
152
+ /**
153
+ * What one player may know of the state, when that is not all of it. Called for each peer on every change, so
154
+ * return the same object for a part that did not change. Without it every peer mirrors the whole state.
155
+ */
156
+ view?: (state: State, peer: PeerId) => View;
157
+ /** Host the room even when another client is hosting it, such as a host that vanished without closing. */
158
+ takeover?: boolean;
159
+ };
160
+
161
+ export type PeerOptions<Msg, Presence, State> = SessionOptions<Msg, Presence> & {
162
+ /** Boundary validation of a whole state from the host. Throws on bad input. Changes after it are not checked. */
163
+ parseState?: (raw: unknown) => State;
164
+ };
package/src/webrtc.ts ADDED
@@ -0,0 +1,480 @@
1
+ import {
2
+ ID_PATTERN,
3
+ KEEPALIVE,
4
+ SignalClose,
5
+ type ClientMessage,
6
+ type IceServer,
7
+ type RoomListing,
8
+ type ServerMessage,
9
+ type SignalRole,
10
+ } from "./signal-protocol.ts";
11
+ import type { Lane, Link, LinkHandlers, Transport } from "./transport.ts";
12
+ import { NetError, type PeerId } from "./types.ts";
13
+
14
+ export type WebRtcTransportOptions = {
15
+ /** Where the signaling Worker answers, e.g. `https://game.example.com/signal` or `ws://127.0.0.1:8787` under `wrangler dev`. */
16
+ signalUrl: string;
17
+ /** The Worker's `SIGNAL_SECRET`. Left out for a Worker that runs open. */
18
+ secret?: string;
19
+ /** Added after Cloudflare's STUN server, e.g. a TURN server for players behind strict NATs. */
20
+ iceServers?: RTCIceServer[];
21
+ };
22
+
23
+ const STUN: RTCIceServer = { urls: "stun:stun.cloudflare.com:3478" };
24
+ const KEEPALIVE_MS = 30_000;
25
+ /** How long a connection to a host that answered may take to open before the attempt is given up for a new one. */
26
+ const NEGOTIATION_TIMEOUT_MS = 15_000;
27
+ /** Above this the reliable lane queues in JS instead of growing the browser's send buffer, which throws when full. */
28
+ const RELIABLE_HIGH_WATER = 1024 * 1024;
29
+ const RELIABLE_LOW_WATER = 256 * 1024;
30
+ const LOSSY_HIGH_WATER = 16 * 1024;
31
+
32
+ type SignalData = {
33
+ attempt: string;
34
+ sdp?: RTCSessionDescriptionInit;
35
+ candidate?: RTCIceCandidateInit;
36
+ };
37
+
38
+ export function createWebRtcTransport(options: WebRtcTransportOptions): Transport {
39
+ const endpoint = parseSignalUrl(options.signalUrl);
40
+ const { secret } = options;
41
+ if (secret !== undefined && (typeof secret !== "string" || secret === ""))
42
+ throw new TypeError("secret must be a non-empty string, or left out for an open Worker");
43
+ const extra = options.iceServers ?? [];
44
+ if (
45
+ !Array.isArray(extra) ||
46
+ !extra.every((server) => typeof server?.urls === "string" || Array.isArray(server?.urls))
47
+ )
48
+ throw new TypeError("iceServers must be RTCIceServer objects with `urls`");
49
+ // The signaling Worker hands out relay servers, when it has any, before it sends anything that starts a connection.
50
+ const rtcConfig = (relays: IceServer[]): RTCConfiguration => ({
51
+ iceServers: [STUN, ...extra, ...relays],
52
+ });
53
+
54
+ const socketUrl = (role: SignalRole, params: Record<string, string> = {}) => {
55
+ const url = new URL(endpoint);
56
+ url.searchParams.set("role", role);
57
+ for (const [key, value] of Object.entries(params)) url.searchParams.set(key, value);
58
+ if (secret !== undefined) url.searchParams.set("secret", secret);
59
+ return url;
60
+ };
61
+
62
+ return {
63
+ listen(room, selfId, handlers, listenOptions) {
64
+ const pending = new Map<PeerId, { attempt: string; pc: RTCPeerConnection; link: Link }>();
65
+ let socket: SignalSocket | null = null;
66
+ let relays: IceServer[] = [];
67
+ /** What the room list shows for this room. Sent again whenever the signaling socket comes back. */
68
+ let info: unknown = null;
69
+ let ready = false;
70
+ /** Only the first socket takes the room over: one that reconnects must not evict whoever hosts it by then. */
71
+ let takeover = listenOptions?.takeover === true;
72
+ let closed = false;
73
+ let failures = 0;
74
+ let retry: ReturnType<typeof setTimeout> | undefined;
75
+
76
+ const onSignal = (from: PeerId, data: SignalData) => {
77
+ if (data.sdp?.type === "offer") {
78
+ pending.get(from)?.link.close();
79
+ const pc = new RTCPeerConnection(rtcConfig(relays));
80
+ const connection = wireConnection(pc, from);
81
+ const entry = { attempt: data.attempt, pc, link: connection.link };
82
+ pending.set(from, entry);
83
+ const reply = (payload: Omit<SignalData, "attempt">) =>
84
+ socket?.send({ t: "signal", to: from, data: { attempt: data.attempt, ...payload } });
85
+ pc.onicecandidate = (event) => {
86
+ if (event.candidate) reply({ candidate: event.candidate.toJSON() });
87
+ };
88
+ const answer = async () => {
89
+ await pc.setRemoteDescription(data.sdp!);
90
+ await pc.setLocalDescription();
91
+ reply({ sdp: pc.localDescription!.toJSON() });
92
+ };
93
+ answer().catch(() => connection.link.close());
94
+ connection.ready.then(
95
+ () => {
96
+ if (pending.get(from) === entry) pending.delete(from);
97
+ connection.attach(handlers.link(connection.link));
98
+ },
99
+ () => {
100
+ if (pending.get(from) === entry) pending.delete(from);
101
+ },
102
+ );
103
+ } else if (data.candidate) {
104
+ const entry = pending.get(from);
105
+ if (entry?.attempt === data.attempt)
106
+ entry.pc.addIceCandidate(data.candidate).catch(() => {});
107
+ }
108
+ };
109
+
110
+ const open = () => {
111
+ const params = { room, id: selfId, ...(takeover ? { takeover: "1" } : {}) };
112
+ takeover = false;
113
+ socket = openSignalSocket(socketUrl("host", params), {
114
+ message(msg) {
115
+ if (msg.t === "ice") relays = msg.servers;
116
+ else if (msg.t === "ready") {
117
+ failures = 0;
118
+ ready = true;
119
+ if (info !== null) socket?.send({ t: "publish", info });
120
+ handlers.status("connected");
121
+ } else if (msg.t === "signal") {
122
+ const from = asPeerId(msg.from);
123
+ const data = parseSignalData(msg.data);
124
+ if (from && data) onSignal(from, data);
125
+ }
126
+ },
127
+ close(code) {
128
+ socket = null;
129
+ ready = false;
130
+ if (closed) return;
131
+ const fatal = closeError(code);
132
+ if (fatal) {
133
+ shutdown();
134
+ return handlers.fail(fatal);
135
+ }
136
+ handlers.status("reconnecting");
137
+ retry = setTimeout(open, Math.min(5_000, 250 * 2 ** failures++));
138
+ },
139
+ });
140
+ };
141
+
142
+ const shutdown = () => {
143
+ closed = true;
144
+ clearTimeout(retry);
145
+ socket?.close();
146
+ for (const entry of pending.values()) entry.link.close();
147
+ pending.clear();
148
+ };
149
+
150
+ open();
151
+ return {
152
+ publish(next) {
153
+ info = next;
154
+ if (ready) socket?.send({ t: "publish", info });
155
+ },
156
+ close: shutdown,
157
+ };
158
+ },
159
+
160
+ watchRooms(handler) {
161
+ let socket: SignalSocket | null = null;
162
+ let closed = false;
163
+ let failures = 0;
164
+ let retry: ReturnType<typeof setTimeout> | undefined;
165
+ const open = () => {
166
+ socket = openSignalSocket(socketUrl("watch"), {
167
+ message(msg) {
168
+ if (msg.t !== "rooms") return;
169
+ failures = 0;
170
+ handler(msg.rooms);
171
+ },
172
+ close(code) {
173
+ socket = null;
174
+ if (closed) return;
175
+ const fatal = closeError(code);
176
+ if (fatal) return console.warn(`[net] ${fatal.code}: the room list is closed. ${fatal.message}`);
177
+ retry = setTimeout(open, Math.min(5_000, 250 * 2 ** failures++));
178
+ },
179
+ });
180
+ };
181
+ open();
182
+ return () => {
183
+ closed = true;
184
+ clearTimeout(retry);
185
+ socket?.close();
186
+ };
187
+ },
188
+
189
+ connect(room, selfId, handlers, signal) {
190
+ return new Promise<Link>((resolve, reject) => {
191
+ const attempt = crypto.randomUUID();
192
+ let settled = false;
193
+ let pc: RTCPeerConnection | null = null;
194
+ let link: Link | null = null;
195
+ let hostId: PeerId | null = null;
196
+ let relays: IceServer[] = [];
197
+
198
+ let timeout: ReturnType<typeof setTimeout> | undefined;
199
+
200
+ const finish = (error?: unknown) => {
201
+ if (settled) return;
202
+ settled = true;
203
+ clearTimeout(timeout);
204
+ signal.removeEventListener("abort", onAbort);
205
+ socket.close();
206
+ if (error === undefined) return resolve(link!);
207
+ link?.close();
208
+ reject(error);
209
+ };
210
+ const onAbort = () => finish(signal.reason ?? new Error("Connection attempt aborted"));
211
+
212
+ const send = (payload: Omit<SignalData, "attempt">) =>
213
+ hostId && socket.send({ t: "signal", to: hostId, data: { attempt, ...payload } });
214
+
215
+ const start = (id: PeerId) => {
216
+ hostId = id;
217
+ timeout = setTimeout(
218
+ () => finish(new Error(`The connection to ${id} did not open in time`)),
219
+ NEGOTIATION_TIMEOUT_MS,
220
+ );
221
+ pc = new RTCPeerConnection(rtcConfig(relays));
222
+ const connection = wireConnection(pc, id);
223
+ link = connection.link;
224
+ connection.attach(handlers);
225
+ pc.onicecandidate = (event) => {
226
+ if (event.candidate) send({ candidate: event.candidate.toJSON() });
227
+ };
228
+ const offer = async () => {
229
+ await pc!.setLocalDescription();
230
+ send({ sdp: pc!.localDescription!.toJSON() });
231
+ };
232
+ offer().catch(finish);
233
+ connection.ready.then(() => finish(), finish);
234
+ };
235
+
236
+ const socket = openSignalSocket(socketUrl("peer", { room, id: selfId }), {
237
+ message(msg) {
238
+ if (msg.t === "ice") relays = msg.servers;
239
+ else if (msg.t === "host" && !pc) {
240
+ if (msg.id === null) return handlers.noHost();
241
+ const id = asPeerId(msg.id);
242
+ if (id) start(id);
243
+ } else if (msg.t === "signal" && pc && msg.from === hostId) {
244
+ const data = parseSignalData(msg.data);
245
+ if (data?.attempt !== attempt) return;
246
+ if (data.sdp?.type === "answer") pc.setRemoteDescription(data.sdp).catch(finish);
247
+ else if (data.candidate) pc.addIceCandidate(data.candidate).catch(() => {});
248
+ }
249
+ },
250
+ close(code) {
251
+ finish(
252
+ closeError(code) ?? new Error(`Signaling closed (${code}) before the host answered`),
253
+ );
254
+ },
255
+ });
256
+
257
+ if (signal.aborted) onAbort();
258
+ else signal.addEventListener("abort", onAbort);
259
+ });
260
+ },
261
+ };
262
+ }
263
+
264
+ /**
265
+ * Both data channels are negotiated with fixed ids, so neither side waits for `ondatachannel`. Frames that arrive
266
+ * before `attach` are held, because the host learns its handlers only once both lanes are open.
267
+ */
268
+ function wireConnection(pc: RTCPeerConnection, remoteId: PeerId) {
269
+ const reliable = pc.createDataChannel("reliable", { negotiated: true, id: 0, ordered: true });
270
+ const lossy = pc.createDataChannel("lossy", {
271
+ negotiated: true,
272
+ id: 1,
273
+ ordered: false,
274
+ maxRetransmits: 0,
275
+ });
276
+ reliable.binaryType = "arraybuffer";
277
+ lossy.binaryType = "arraybuffer";
278
+ reliable.bufferedAmountLowThreshold = RELIABLE_LOW_WATER;
279
+
280
+ let state: "opening" | "open" | "closed" = "opening";
281
+ let handlers: LinkHandlers | null = null;
282
+ const early: [Lane, Uint8Array][] = [];
283
+ const backlog: Uint8Array<ArrayBuffer>[] = [];
284
+ const { promise: ready, resolve, reject } = Promise.withResolvers<void>();
285
+
286
+ const teardown = () => {
287
+ const wasOpen = state === "open";
288
+ state = "closed";
289
+ pc.close();
290
+ backlog.length = 0;
291
+ reject(new Error(`Connection to ${remoteId} failed before opening`));
292
+ return wasOpen;
293
+ };
294
+ const lost = () => {
295
+ if (state !== "closed" && teardown()) handlers?.close();
296
+ };
297
+ const onOpen = () => {
298
+ if (state !== "opening" || reliable.readyState !== "open" || lossy.readyState !== "open")
299
+ return;
300
+ state = "open";
301
+ resolve();
302
+ };
303
+ const onFrame = (lane: Lane) => (event: MessageEvent<ArrayBuffer>) => {
304
+ const frame = new Uint8Array(event.data);
305
+ if (handlers) handlers.frame(lane, frame);
306
+ else early.push([lane, frame]);
307
+ };
308
+
309
+ reliable.onopen = onOpen;
310
+ lossy.onopen = onOpen;
311
+ reliable.onclose = lost;
312
+ lossy.onclose = lost;
313
+ reliable.onmessage = onFrame("reliable");
314
+ lossy.onmessage = onFrame("lossy");
315
+ reliable.onbufferedamountlow = () => {
316
+ while (
317
+ backlog.length > 0 &&
318
+ reliable.readyState === "open" &&
319
+ reliable.bufferedAmount < RELIABLE_HIGH_WATER
320
+ )
321
+ reliable.send(backlog.shift()!);
322
+ };
323
+ // Chrome reports `disconnected` about 5 s after a remote dies without closing and `failed` 10 s after that.
324
+ // Rebuilding a link takes a few hundred ms, so reconnecting on a transient blip beats a 15 s frozen game.
325
+ pc.onconnectionstatechange = () => {
326
+ if (["disconnected", "failed", "closed"].includes(pc.connectionState)) lost();
327
+ };
328
+
329
+ const link: Link = {
330
+ remoteId,
331
+ // A channel that is closing throws on `send` before its `close` event says so.
332
+ sendReliable(frame) {
333
+ if (state !== "open") return;
334
+ const owned = new Uint8Array(frame);
335
+ if (backlog.length > 0 || reliable.bufferedAmount >= RELIABLE_HIGH_WATER) backlog.push(owned);
336
+ else if (reliable.readyState === "open") reliable.send(owned);
337
+ else lost();
338
+ },
339
+ sendLossy(frame) {
340
+ if (state !== "open" || lossy.readyState !== "open") return false;
341
+ if (lossy.bufferedAmount > LOSSY_HIGH_WATER) return false;
342
+ lossy.send(new Uint8Array(frame));
343
+ return true;
344
+ },
345
+ close() {
346
+ if (state !== "closed") teardown();
347
+ },
348
+ };
349
+
350
+ return {
351
+ link,
352
+ ready,
353
+ attach(next: LinkHandlers) {
354
+ handlers = next;
355
+ for (const [lane, frame] of early.splice(0)) next.frame(lane, frame);
356
+ },
357
+ };
358
+ }
359
+
360
+ type SignalSocket = { send(msg: ClientMessage): void; close(): void };
361
+
362
+ function openSignalSocket(
363
+ url: URL,
364
+ handlers: { message: (msg: ServerMessage) => void; close: (code: number) => void },
365
+ ): SignalSocket {
366
+ const ws = new WebSocket(url);
367
+ let keepalive: ReturnType<typeof setInterval> | undefined;
368
+ let closed = false;
369
+ ws.onopen = () => {
370
+ keepalive = setInterval(() => ws.send(KEEPALIVE.ping), KEEPALIVE_MS);
371
+ };
372
+ ws.onmessage = (event) => {
373
+ const msg = typeof event.data === "string" ? parseServerMessage(event.data) : null;
374
+ if (msg) handlers.message(msg);
375
+ };
376
+ ws.onclose = (event) => {
377
+ clearInterval(keepalive);
378
+ if (closed) return;
379
+ closed = true;
380
+ handlers.close(event.code);
381
+ };
382
+ return {
383
+ send(msg) {
384
+ if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(msg));
385
+ },
386
+ close() {
387
+ closed = true;
388
+ clearInterval(keepalive);
389
+ ws.close();
390
+ },
391
+ };
392
+ }
393
+
394
+ function parseSignalUrl(value: string): URL {
395
+ let url: URL;
396
+ try {
397
+ url = new URL(value);
398
+ } catch {
399
+ throw new TypeError(`signalUrl is not a URL: ${JSON.stringify(value)}`);
400
+ }
401
+ const protocols: Record<string, string> = {
402
+ "http:": "ws:",
403
+ "https:": "wss:",
404
+ "ws:": "ws:",
405
+ "wss:": "wss:",
406
+ };
407
+ const protocol = protocols[url.protocol];
408
+ if (!protocol) throw new TypeError(`signalUrl must be http(s) or ws(s), got ${url.protocol}`);
409
+ url.protocol = protocol;
410
+ return url;
411
+ }
412
+
413
+ function closeError(code: number): NetError | null {
414
+ if (code === SignalClose.unauthorized)
415
+ return new NetError("unauthorized", "The signaling Worker rejected the secret");
416
+ if (code === SignalClose.hostTaken)
417
+ return new NetError("host-taken", "Another client is already hosting this room");
418
+ if (code === SignalClose.replaced)
419
+ return new NetError(
420
+ "replaced",
421
+ "This id is in the room from another tab, or another client took the room over",
422
+ );
423
+ return null;
424
+ }
425
+
426
+ function asPeerId(value: unknown): PeerId | null {
427
+ return typeof value === "string" && ID_PATTERN.test(value) ? (value as PeerId) : null;
428
+ }
429
+
430
+ function parseServerMessage(text: string): ServerMessage | null {
431
+ try {
432
+ const raw: unknown = JSON.parse(text);
433
+ if (typeof raw !== "object" || raw === null || !("t" in raw)) return null;
434
+ if (raw.t === "ice" && !isIceServers((raw as { servers?: unknown }).servers)) return null;
435
+ if (raw.t === "rooms" && !isRoomListings((raw as { rooms?: unknown }).rooms)) return null;
436
+ return raw as ServerMessage;
437
+ } catch {
438
+ return null;
439
+ }
440
+ }
441
+
442
+ function isIceServers(value: unknown): value is IceServer[] {
443
+ const isUrls = (urls: unknown) =>
444
+ typeof urls === "string" ||
445
+ (Array.isArray(urls) && urls.every((url) => typeof url === "string"));
446
+ return (
447
+ Array.isArray(value) &&
448
+ value.every((server) => typeof server === "object" && server !== null && isUrls(server.urls))
449
+ );
450
+ }
451
+
452
+ function isRoomListings(value: unknown): value is RoomListing[] {
453
+ return (
454
+ Array.isArray(value) &&
455
+ value.every(
456
+ (entry) =>
457
+ typeof entry === "object" &&
458
+ entry !== null &&
459
+ typeof entry.room === "string" &&
460
+ typeof entry.host === "string" &&
461
+ "info" in entry,
462
+ )
463
+ );
464
+ }
465
+
466
+ function parseSignalData(raw: unknown): SignalData | null {
467
+ if (typeof raw !== "object" || raw === null) return null;
468
+ const { attempt, sdp, candidate } = raw as Record<string, unknown>;
469
+ if (typeof attempt !== "string") return null;
470
+ const data: SignalData = { attempt };
471
+ if (
472
+ typeof sdp === "object" &&
473
+ sdp !== null &&
474
+ typeof (sdp as RTCSessionDescriptionInit).type === "string"
475
+ )
476
+ data.sdp = sdp as RTCSessionDescriptionInit;
477
+ if (typeof candidate === "object" && candidate !== null)
478
+ data.candidate = candidate as RTCIceCandidateInit;
479
+ return data;
480
+ }