@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/LICENSE +21 -0
- package/README.md +147 -2
- package/package.json +54 -4
- package/src/index.ts +32 -0
- package/src/memory.ts +187 -0
- package/src/patch.ts +138 -0
- package/src/session.ts +594 -0
- package/src/signal-protocol.ts +48 -0
- package/src/transport.ts +70 -0
- package/src/types.ts +164 -0
- package/src/webrtc.ts +480 -0
- package/src/wire.ts +167 -0
- package/src/worker/index.ts +287 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Stefan Mirea
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,148 @@
|
|
|
1
|
-
#
|
|
1
|
+
# game-networking
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Peer-to-peer networking for small browser games played among friends. One player hosts a room and owns the game state. Every other player connects straight to the host over WebRTC data channels, and the host relays what players need to see of each other. A Cloudflare Worker only introduces players when they connect or reconnect, and keeps the list of rooms. Game traffic never touches it.
|
|
4
|
+
|
|
5
|
+
It is for trusted groups: nothing stops a player from reading what their browser is sent or from claiming another player's id. A game with hidden information sends each player only their own view, and everything else is the game's own business.
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
bun add @stefan.inc/game-networking
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
The package ships TypeScript source with no build step and has no dependencies. A game's bundler compiles it, and its `tsconfig.json` needs `allowImportingTsExtensions`, since the compiler checks the source it imports.
|
|
12
|
+
|
|
13
|
+
## Use it
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { createHost, createWebRtcTransport, joinHost, peerId } from "@stefan.inc/game-networking";
|
|
17
|
+
|
|
18
|
+
const transport = createWebRtcTransport({ signalUrl: "https://game.example.com/signal", secret });
|
|
19
|
+
const options = {
|
|
20
|
+
selfId: peerId(localStorage.playerId), // persist it so a reload rejoins as the same player
|
|
21
|
+
name: "Ada",
|
|
22
|
+
transport,
|
|
23
|
+
room: "KQXM", // leave it out for a game with one table
|
|
24
|
+
parseMsg: (raw: unknown) => GameMsg.parse(raw), // throw on bad input
|
|
25
|
+
parsePresence: (raw: unknown) => Cursor.parse(raw),
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
// The host owns the state. Every peer mirrors it.
|
|
29
|
+
const host = createHost<GameMsg, Cursor, GameState>(options);
|
|
30
|
+
actor.subscribe((snapshot) => host.setState(snapshot.context));
|
|
31
|
+
host.on("message", (msg, from) => actor.send({ ...msg, from }));
|
|
32
|
+
|
|
33
|
+
// A peer holds what the host sends and sends commands.
|
|
34
|
+
const session = joinHost<GameMsg, Cursor, GameState>(options);
|
|
35
|
+
session.on("state", (state) => render(state));
|
|
36
|
+
session.on("status", (status) => setOnline(status === "connected"));
|
|
37
|
+
session.on("error", (error) => console.warn(error.code, error.message));
|
|
38
|
+
button.onclick = () => session.send({ type: "play", card });
|
|
39
|
+
|
|
40
|
+
// Both: cursors on the lossy lane, and the roster.
|
|
41
|
+
session.on("peers", (peers) => renderPlayers(peers));
|
|
42
|
+
session.on("presence", (cursor, from) => drawCursor(from, cursor));
|
|
43
|
+
window.addEventListener("pointermove", (e) => session.sendPresence({ x: e.clientX, y: e.clientY }));
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
Each connection has two lanes:
|
|
47
|
+
|
|
48
|
+
- A reliable, ordered lane for the state and for messages (`send`). Anything of any size is split into 16 KiB frames and put back together on arrival.
|
|
49
|
+
- A lossy, unordered lane for cursors (`sendPresence`). It sends only the newest value, at most `presenceHz` times a second, and drops a value instead of queueing it when the lane is backed up.
|
|
50
|
+
|
|
51
|
+
## State
|
|
52
|
+
|
|
53
|
+
`host.setState(state)` is how a game stays in step. A peer is sent the whole state when it connects or reconnects, and after that only what each change touched, in order with the messages sent around it. On the peer, a change keeps every untouched part of the state as the object it was, frozen, so a UI redraws only what moved.
|
|
54
|
+
|
|
55
|
+
- The state is plain JSON, and a state given to `setState` is never changed afterwards. Pass a new value that shares what did not change, as an immer or reducer state does.
|
|
56
|
+
- `diff`, `applyPatches` and `frozen` are exported for a game that records its own changes.
|
|
57
|
+
- A game that sends something else alongside the state, such as an animation cue or a rejection, sends it with `send` after `setState`. It arrives after the state it belongs to.
|
|
58
|
+
|
|
59
|
+
### Hidden information
|
|
60
|
+
|
|
61
|
+
Give the host a `view` and each peer is sent only that:
|
|
62
|
+
|
|
63
|
+
```ts
|
|
64
|
+
const host = createHost<GameMsg, Cursor, GameState, PlayerView>({
|
|
65
|
+
...options,
|
|
66
|
+
view: (state, peer) => ({ board: state.board, hand: state.hands[peer], deck: state.deck.length }),
|
|
67
|
+
});
|
|
68
|
+
const session = joinHost<GameMsg, Cursor, PlayerView>(options);
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
`view` runs for every peer on every change, so return the same object for a part that did not change (`state.board` above). The host's own browser holds the whole state: it calls `view(state, host.selfId)` itself to draw its own player's screen.
|
|
72
|
+
|
|
73
|
+
## Rooms
|
|
74
|
+
|
|
75
|
+
A transport is a whole deployment and a session is one room in it. Rooms are independent: each has its own host, roster and state.
|
|
76
|
+
|
|
77
|
+
- `createRoomCode()` makes a four-letter code from letters and digits that are hard to confuse; `createRoomCode(6)` makes a longer one. Nothing reserves a code. A host that gets `host-taken` makes another.
|
|
78
|
+
- A room exists while someone hosts it. A peer that joins a room nobody hosts gets a `no-host` error and goes on waiting, so a lobby can say "no game in room KQXM" or "waiting for the host".
|
|
79
|
+
- `host.publish(info)` puts the room on the room list with any JSON the game wants to show (a title, the players, the phase), and `host.publish(null)` takes it off. `transport.watchRooms((rooms) => ...)` gives a lobby the list, now and after every change. A room nobody published is joined by its name alone.
|
|
80
|
+
- `host.remove(peer, reason)` takes a player out of the room. Their session ends with a `removed` error carrying the reason, and they leave the roster. It is also how a game enforces a full table or a closed lobby, and how the host forgets a player who is gone for good.
|
|
81
|
+
|
|
82
|
+
### When the host leaves
|
|
83
|
+
|
|
84
|
+
The game lives in the host's browser, so it pauses while the host is away. Peers keep retrying and reconnect when the host is back; a host that reloads restores its own state (from `localStorage`, say) and calls `setState` again.
|
|
85
|
+
|
|
86
|
+
When the host is not coming back, any peer can carry on with the state it holds: close its session and `createHost` in the same room. The Worker lets one client host a room at a time, so if two try, one gets `host-taken`. The other peers follow whoever hosts the room without doing anything. `takeover: true` hosts a room even while another client holds it, which ends that client's session as `replaced` (it applies when the session starts, not each time its signaling reconnects); a host that went silent without closing (a sleeping laptop) stops holding its room after two and a half minutes anyway. With a `view`, peers do not hold the whole state, so such a game needs its own answer for what a new host starts from.
|
|
87
|
+
|
|
88
|
+
## Behavior
|
|
89
|
+
|
|
90
|
+
- `peers` carries the full roster, host included, in the same order on every client. A player who drops stays in the list with `connected: false` until the host removes them.
|
|
91
|
+
- A peer that loses the host goes to `reconnecting`, tries again at once and then with backoff, until `close()`. A host that dies without closing is noticed in about 6 seconds, which is Chrome's ICE consent timeout plus the reconnect.
|
|
92
|
+
- `send` from a peer always goes to the host. It returns false when the link is down and the message was dropped, so disable game actions unless `status` is `connected`.
|
|
93
|
+
- Every value from the wire passes through `parseMsg`, `parsePresence` or `parseState` (a whole state only; the changes after it are applied as sent). A value that fails is dropped and reported as an `error` event with code `invalid-message`, `invalid-presence` or `invalid-state`.
|
|
94
|
+
- These `error` codes are fatal and close the session: `unauthorized` (wrong secret), `host-taken` (another client hosts the room), `replaced` and `removed`.
|
|
95
|
+
- One tab per player in a room. The same `selfId` connecting from a newer tab ends the older tab's session as `replaced`. The exception is a tab that joins the room its own player hosts: closing the host would end the game, so the newcomer is the one turned away.
|
|
96
|
+
- Bad options throw from `createHost`, `joinHost` and `createWebRtcTransport`, not at the first send.
|
|
97
|
+
|
|
98
|
+
Tests and solo play use `createMemoryTransport()` instead of WebRTC. One instance stands in for the whole network, rooms and room list included: pass it to the host and every peer. `drop(id)` cuts a player's link and `setCongested(id, true)` backs up their lossy lane.
|
|
99
|
+
|
|
100
|
+
## The signaling Worker
|
|
101
|
+
|
|
102
|
+
Mount the handler in the game's own Worker, on the path the game uses as `signalUrl`:
|
|
103
|
+
|
|
104
|
+
```ts
|
|
105
|
+
import { handleSignal, SignalHub } from "@stefan.inc/game-networking/worker";
|
|
106
|
+
|
|
107
|
+
export { SignalHub };
|
|
108
|
+
|
|
109
|
+
export default {
|
|
110
|
+
fetch(request, env) {
|
|
111
|
+
if (new URL(request.url).pathname === "/signal") return handleSignal(request, env);
|
|
112
|
+
return env.ASSETS.fetch(request);
|
|
113
|
+
},
|
|
114
|
+
} satisfies ExportedHandler<Env>;
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
```jsonc
|
|
118
|
+
// wrangler.jsonc
|
|
119
|
+
{
|
|
120
|
+
"compatibility_date": "2026-11-15", // 2026-04-07 or later
|
|
121
|
+
"durable_objects": { "bindings": [{ "name": "SIGNAL_HUB", "class_name": "SignalHub" }] },
|
|
122
|
+
"migrations": [{ "tag": "v1", "new_sqlite_classes": ["SignalHub"] }],
|
|
123
|
+
}
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
- `SIGNAL_SECRET` is the passphrase every client sends (`wrangler secret put SIGNAL_SECRET`). Without it every connection fails, unless the handler is mounted as `handleSignal(request, env, { open: true })`, where knowing a room's name is all it takes to join. The secret travels in the WebSocket URL, because browsers cannot set headers on a WebSocket, so anyone who can read the Worker's logs can see it.
|
|
127
|
+
- `TURN_KEY_ID` and `TURN_KEY_API_TOKEN` are an optional [Cloudflare TURN key](https://developers.cloudflare.com/realtime/turn/). With one, the Worker hands each browser relay servers for players whom no direct connection reaches. Without one, players connect directly or not at all, which works on most home networks.
|
|
128
|
+
- One Durable Object holds every room of the deployment and stores nothing. The free Workers plan covers it: a connection takes about six signaling messages, an idle hibernating WebSocket costs nothing, and the keepalive every 30 seconds is answered without waking the object.
|
|
129
|
+
|
|
130
|
+
`example/` is a Worker that does only this, with the demo page that the checks drive.
|
|
131
|
+
|
|
132
|
+
## What it does not do
|
|
133
|
+
|
|
134
|
+
- Run a game with nobody's browser open. A game that must go on unattended, or keep history across groups, needs a server of its own.
|
|
135
|
+
- Pick a new host by itself. The game decides who carries on.
|
|
136
|
+
- Seats, turns, votes, chat or reconnect tokens. Those are game state and game messages, keyed by the stable `selfId`.
|
|
137
|
+
|
|
138
|
+
## Develop
|
|
139
|
+
|
|
140
|
+
```sh
|
|
141
|
+
bun install
|
|
142
|
+
bun run hooks # once per checkout: the git hooks
|
|
143
|
+
bun run test # the wire, room and state rules, in-process
|
|
144
|
+
bun run dev # the example Worker and the demo page, to try by hand
|
|
145
|
+
bun run netcheck # the same, driven in real browsers over real WebRTC
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
`AGENTS.md` has the conventions and how a release is made.
|
package/package.json
CHANGED
|
@@ -1,6 +1,56 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@stefan.inc/game-networking",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Peer-to-peer networking for small browser games among friends: one player hosts and owns the state, the others connect to it over WebRTC, and a Cloudflare Worker only introduces them.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"board-game",
|
|
7
|
+
"cloudflare-workers",
|
|
8
|
+
"durable-objects",
|
|
9
|
+
"multiplayer",
|
|
10
|
+
"p2p",
|
|
11
|
+
"state-sync",
|
|
12
|
+
"webrtc"
|
|
13
|
+
],
|
|
14
|
+
"homepage": "https://github.com/smirea/game-networking#readme",
|
|
15
|
+
"license": "MIT",
|
|
16
|
+
"repository": {
|
|
17
|
+
"type": "git",
|
|
18
|
+
"url": "git+https://github.com/smirea/game-networking.git"
|
|
19
|
+
},
|
|
20
|
+
"files": [
|
|
21
|
+
"src",
|
|
22
|
+
"!src/**/*.test.ts",
|
|
23
|
+
"!src/**/tsconfig.json"
|
|
24
|
+
],
|
|
25
|
+
"type": "module",
|
|
26
|
+
"exports": {
|
|
27
|
+
".": "./src/index.ts",
|
|
28
|
+
"./worker": "./src/worker/index.ts",
|
|
29
|
+
"./package.json": "./package.json"
|
|
30
|
+
},
|
|
31
|
+
"publishConfig": {
|
|
32
|
+
"access": "public"
|
|
33
|
+
},
|
|
34
|
+
"scripts": {
|
|
35
|
+
"hooks": "lefthook install",
|
|
36
|
+
"worktree:setup": "bun run hooks",
|
|
37
|
+
"lint": "oxlint --fix",
|
|
38
|
+
"lint:ci": "oxlint",
|
|
39
|
+
"typecheck": "bun check && bun check -p tsconfig.consumer.json && bun check -p src/worker",
|
|
40
|
+
"test": "bun test --pass-with-no-tests",
|
|
41
|
+
"package": "bun .github/scripts/check-package.ts",
|
|
42
|
+
"dev": "scripts/dev.ts",
|
|
43
|
+
"netcheck": "scripts/netcheck.ts"
|
|
44
|
+
},
|
|
45
|
+
"devDependencies": {
|
|
46
|
+
"@changesets/cli": "3.0.3",
|
|
47
|
+
"@cloudflare/workers-types": "^5.20261129.1",
|
|
48
|
+
"@types/bun": "^1.4.5",
|
|
49
|
+
"lefthook": "^2.2.4",
|
|
50
|
+
"oxlint": "^1.95.0",
|
|
51
|
+
"playwright": "1.65.1",
|
|
52
|
+
"typescript": "^7.0.2",
|
|
53
|
+
"wrangler": "^4.169.0"
|
|
54
|
+
},
|
|
55
|
+
"packageManager": "bun@1.4.5"
|
|
56
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
export { createMemoryTransport, type MemoryTransport } from "./memory.ts";
|
|
2
|
+
export { applyPatches, diff, frozen, type Patch } from "./patch.ts";
|
|
3
|
+
export { createHost, joinHost } from "./session.ts";
|
|
4
|
+
export { DEFAULT_ROOM, MAX_ROOM_INFO_LENGTH, type RoomListing } from "./signal-protocol.ts";
|
|
5
|
+
export {
|
|
6
|
+
MAX_FRAME_BYTES,
|
|
7
|
+
type ConnectHandlers,
|
|
8
|
+
type Lane,
|
|
9
|
+
type Link,
|
|
10
|
+
type LinkHandlers,
|
|
11
|
+
type ListenHandlers,
|
|
12
|
+
type ListenOptions,
|
|
13
|
+
type Listener,
|
|
14
|
+
type Transport,
|
|
15
|
+
} from "./transport.ts";
|
|
16
|
+
export {
|
|
17
|
+
NetError,
|
|
18
|
+
createPeerId,
|
|
19
|
+
createRoomCode,
|
|
20
|
+
peerId,
|
|
21
|
+
type ConnectionStatus,
|
|
22
|
+
type HostOptions,
|
|
23
|
+
type HostSession,
|
|
24
|
+
type NetErrorCode,
|
|
25
|
+
type PeerId,
|
|
26
|
+
type PeerInfo,
|
|
27
|
+
type PeerOptions,
|
|
28
|
+
type Session,
|
|
29
|
+
type SessionEvents,
|
|
30
|
+
type SessionOptions,
|
|
31
|
+
} from "./types.ts";
|
|
32
|
+
export { createWebRtcTransport, type WebRtcTransportOptions } from "./webrtc.ts";
|
package/src/memory.ts
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
import type { RoomListing } from "./signal-protocol.ts";
|
|
2
|
+
import {
|
|
3
|
+
MAX_FRAME_BYTES,
|
|
4
|
+
type Link,
|
|
5
|
+
type LinkHandlers,
|
|
6
|
+
type ListenHandlers,
|
|
7
|
+
type Transport,
|
|
8
|
+
} from "./transport.ts";
|
|
9
|
+
import { NetError, type PeerId } from "./types.ts";
|
|
10
|
+
|
|
11
|
+
export type MemoryTransport = Transport & {
|
|
12
|
+
/** Severs every link `id` is part of, as a network failure would. Both sides see `close`. */
|
|
13
|
+
drop(id: PeerId): void;
|
|
14
|
+
/** While congested, lossy sends from `id` report backpressure and drop. */
|
|
15
|
+
setCongested(id: PeerId, congested: boolean): void;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
type HostEntry = { id: PeerId; handlers: ListenHandlers; info: unknown };
|
|
19
|
+
type Room = { host: HostEntry | null; waiters: Set<() => void> };
|
|
20
|
+
type Pair = { ids: [PeerId, PeerId]; fail(): void };
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* An in-process network: one instance stands in for the signaling Worker, its rooms and every WebRTC connection.
|
|
24
|
+
* Delivery is asynchronous and ordered per direction, like a data channel.
|
|
25
|
+
*/
|
|
26
|
+
export function createMemoryTransport(): MemoryTransport {
|
|
27
|
+
const rooms = new Map<string, Room>();
|
|
28
|
+
const watchers = new Set<(rooms: RoomListing[]) => void>();
|
|
29
|
+
const pairs = new Set<Pair>();
|
|
30
|
+
const congested = new Set<PeerId>();
|
|
31
|
+
|
|
32
|
+
const roomOf = (name: string) => {
|
|
33
|
+
let room = rooms.get(name);
|
|
34
|
+
if (!room) rooms.set(name, (room = { host: null, waiters: new Set() }));
|
|
35
|
+
return room;
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
const listing = (): RoomListing[] =>
|
|
39
|
+
[...rooms].flatMap(([room, { host }]) =>
|
|
40
|
+
host && host.info !== null
|
|
41
|
+
? [{ room, host: host.id, info: JSON.parse(JSON.stringify(host.info)) }]
|
|
42
|
+
: [],
|
|
43
|
+
);
|
|
44
|
+
const announce = () => {
|
|
45
|
+
for (const watcher of watchers) queueMicrotask(() => watchers.has(watcher) && watcher(listing()));
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
const createPair = (hostId: PeerId, peerId: PeerId) => {
|
|
49
|
+
const handlers: [LinkHandlers | null, LinkHandlers | null] = [null, null];
|
|
50
|
+
/** Which side closed it, or `failed` when the network severed both. */
|
|
51
|
+
let closed: 0 | 1 | "failed" | null = null;
|
|
52
|
+
const deliverFrame = (to: 0 | 1, lane: "reliable" | "lossy", frame: Uint8Array) =>
|
|
53
|
+
queueMicrotask(() => {
|
|
54
|
+
if (closed !== to && closed !== "failed") handlers[to]?.frame(lane, frame);
|
|
55
|
+
});
|
|
56
|
+
const deliverClose = (to: 0 | 1) => queueMicrotask(() => handlers[to]?.close());
|
|
57
|
+
const pair: Pair = {
|
|
58
|
+
ids: [hostId, peerId],
|
|
59
|
+
fail() {
|
|
60
|
+
if (closed !== null) return;
|
|
61
|
+
closed = "failed";
|
|
62
|
+
pairs.delete(pair);
|
|
63
|
+
deliverClose(0);
|
|
64
|
+
deliverClose(1);
|
|
65
|
+
},
|
|
66
|
+
};
|
|
67
|
+
pairs.add(pair);
|
|
68
|
+
|
|
69
|
+
const end = (self: 0 | 1): Link => {
|
|
70
|
+
const other = self === 0 ? 1 : 0;
|
|
71
|
+
const selfId = pair.ids[self];
|
|
72
|
+
const send = (lane: "reliable" | "lossy", frame: Uint8Array) => {
|
|
73
|
+
if (frame.length > MAX_FRAME_BYTES)
|
|
74
|
+
throw new RangeError(`Frame of ${frame.length} bytes exceeds ${MAX_FRAME_BYTES}`);
|
|
75
|
+
deliverFrame(other, lane, frame.slice());
|
|
76
|
+
};
|
|
77
|
+
return {
|
|
78
|
+
remoteId: pair.ids[other],
|
|
79
|
+
sendReliable(frame) {
|
|
80
|
+
if (closed === null) send("reliable", frame);
|
|
81
|
+
},
|
|
82
|
+
sendLossy(frame) {
|
|
83
|
+
if (closed !== null || congested.has(selfId)) return false;
|
|
84
|
+
send("lossy", frame);
|
|
85
|
+
return true;
|
|
86
|
+
},
|
|
87
|
+
close() {
|
|
88
|
+
if (closed !== null) return;
|
|
89
|
+
closed = self;
|
|
90
|
+
pairs.delete(pair);
|
|
91
|
+
deliverClose(other);
|
|
92
|
+
},
|
|
93
|
+
};
|
|
94
|
+
};
|
|
95
|
+
return {
|
|
96
|
+
hostEnd: end(0),
|
|
97
|
+
peerEnd: end(1),
|
|
98
|
+
attach(side: 0 | 1, h: LinkHandlers) {
|
|
99
|
+
handlers[side] = h;
|
|
100
|
+
},
|
|
101
|
+
};
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
const waitForHost = (room: Room, signal: AbortSignal) =>
|
|
105
|
+
new Promise<HostEntry>((resolve, reject) => {
|
|
106
|
+
const check = () => {
|
|
107
|
+
if (signal.aborted) return finish(() => reject(signal.reason));
|
|
108
|
+
if (room.host) {
|
|
109
|
+
const found = room.host;
|
|
110
|
+
finish(() => resolve(found));
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
const finish = (settle: () => void) => {
|
|
114
|
+
room.waiters.delete(check);
|
|
115
|
+
signal.removeEventListener("abort", check);
|
|
116
|
+
settle();
|
|
117
|
+
};
|
|
118
|
+
room.waiters.add(check);
|
|
119
|
+
signal.addEventListener("abort", check);
|
|
120
|
+
check();
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
return {
|
|
124
|
+
listen(name, selfId, handlers, options) {
|
|
125
|
+
const room = roomOf(name);
|
|
126
|
+
const sitting = room.host;
|
|
127
|
+
if (sitting && sitting.id !== selfId && !options?.takeover) {
|
|
128
|
+
const taken = new NetError("host-taken", `${sitting.id} is already hosting ${name}`);
|
|
129
|
+
queueMicrotask(() => handlers.fail(taken));
|
|
130
|
+
return { publish() {}, close() {} };
|
|
131
|
+
}
|
|
132
|
+
if (sitting)
|
|
133
|
+
queueMicrotask(() =>
|
|
134
|
+
sitting.handlers.fail(new NetError("replaced", `${selfId} is hosting ${name} now`)),
|
|
135
|
+
);
|
|
136
|
+
const entry: HostEntry = { id: selfId, handlers, info: null };
|
|
137
|
+
room.host = entry;
|
|
138
|
+
queueMicrotask(() => {
|
|
139
|
+
if (room.host === entry) handlers.status("connected");
|
|
140
|
+
});
|
|
141
|
+
for (const wake of room.waiters) wake();
|
|
142
|
+
if (sitting && sitting.info !== null) announce();
|
|
143
|
+
return {
|
|
144
|
+
publish(info) {
|
|
145
|
+
if (room.host !== entry) return;
|
|
146
|
+
entry.info = info;
|
|
147
|
+
announce();
|
|
148
|
+
},
|
|
149
|
+
close() {
|
|
150
|
+
if (room.host !== entry) return;
|
|
151
|
+
room.host = null;
|
|
152
|
+
if (entry.info !== null) announce();
|
|
153
|
+
},
|
|
154
|
+
};
|
|
155
|
+
},
|
|
156
|
+
|
|
157
|
+
async connect(name, selfId, handlers, signal) {
|
|
158
|
+
const room = roomOf(name);
|
|
159
|
+
if (!room.host)
|
|
160
|
+
queueMicrotask(() => {
|
|
161
|
+
if (!room.host && !signal.aborted) handlers.noHost();
|
|
162
|
+
});
|
|
163
|
+
const target = await waitForHost(room, signal);
|
|
164
|
+
if (target.id === selfId)
|
|
165
|
+
throw new NetError("replaced", `${selfId} is in ${name} as its host, from another tab`);
|
|
166
|
+
const { hostEnd, peerEnd, attach } = createPair(target.id, selfId);
|
|
167
|
+
attach(1, handlers);
|
|
168
|
+
attach(0, target.handlers.link(hostEnd));
|
|
169
|
+
return peerEnd;
|
|
170
|
+
},
|
|
171
|
+
|
|
172
|
+
watchRooms(handler) {
|
|
173
|
+
watchers.add(handler);
|
|
174
|
+
queueMicrotask(() => watchers.has(handler) && handler(listing()));
|
|
175
|
+
return () => void watchers.delete(handler);
|
|
176
|
+
},
|
|
177
|
+
|
|
178
|
+
drop(id) {
|
|
179
|
+
for (const pair of pairs) if (pair.ids.includes(id)) pair.fail();
|
|
180
|
+
},
|
|
181
|
+
|
|
182
|
+
setCongested(id, on) {
|
|
183
|
+
if (on) congested.add(id);
|
|
184
|
+
else congested.delete(id);
|
|
185
|
+
},
|
|
186
|
+
};
|
|
187
|
+
}
|
package/src/patch.ts
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One change to a JSON value. `v` sets the value at the path, `del` removes the key, `len` cuts an
|
|
3
|
+
* array to that length, and `shift` drops that many items from the front of an array.
|
|
4
|
+
*/
|
|
5
|
+
export type Patch = {
|
|
6
|
+
p: (string | number)[];
|
|
7
|
+
v?: unknown;
|
|
8
|
+
del?: true;
|
|
9
|
+
len?: number;
|
|
10
|
+
shift?: number;
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
type Json = Record<string, unknown> | unknown[];
|
|
14
|
+
|
|
15
|
+
const isJson = (value: unknown): value is Json => typeof value === "object" && value !== null;
|
|
16
|
+
|
|
17
|
+
/** The keys JSON would write: a key whose value is undefined is a key that is not there. */
|
|
18
|
+
const keysOf = (value: Record<string, unknown>) =>
|
|
19
|
+
Object.keys(value).filter((key) => value[key] !== undefined);
|
|
20
|
+
|
|
21
|
+
function equal(a: unknown, b: unknown): boolean {
|
|
22
|
+
if (a === b) return true;
|
|
23
|
+
if (!isJson(a) || !isJson(b) || Array.isArray(a) !== Array.isArray(b)) return false;
|
|
24
|
+
if (Array.isArray(a)) {
|
|
25
|
+
const other = b as unknown[];
|
|
26
|
+
return a.length === other.length && a.every((item, index) => equal(item, other[index]));
|
|
27
|
+
}
|
|
28
|
+
const left = a as Record<string, unknown>;
|
|
29
|
+
const right = b as Record<string, unknown>;
|
|
30
|
+
const keys = keysOf(left);
|
|
31
|
+
return (
|
|
32
|
+
keys.length === keysOf(right).length &&
|
|
33
|
+
keys.every((key) => right[key] !== undefined && equal(left[key], right[key]))
|
|
34
|
+
);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** How many items left the front of `before`, when what remains is how `after` begins. Zero when that is not what happened. */
|
|
38
|
+
function shifted(before: unknown[], after: unknown[]): number {
|
|
39
|
+
if (before.length < 2 || after.length === 0 || equal(before[0], after[0])) return 0;
|
|
40
|
+
for (let dropped = 1; dropped < before.length; dropped++) {
|
|
41
|
+
const kept = before.length - dropped;
|
|
42
|
+
if (kept > after.length || !equal(before[dropped], after[0])) continue;
|
|
43
|
+
let same = true;
|
|
44
|
+
for (let index = 1; index < kept && same; index++)
|
|
45
|
+
same = equal(before[dropped + index], after[index]);
|
|
46
|
+
if (same) return dropped;
|
|
47
|
+
}
|
|
48
|
+
return 0;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function walk(before: unknown, after: unknown, path: (string | number)[], out: Patch[]) {
|
|
52
|
+
if (before === after) return;
|
|
53
|
+
if (!isJson(before) || !isJson(after) || Array.isArray(before) !== Array.isArray(after)) {
|
|
54
|
+
if (!equal(before, after)) out.push({ p: path, v: after });
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
if (Array.isArray(before)) {
|
|
58
|
+
const next = after as unknown[];
|
|
59
|
+
const dropped = shifted(before, next);
|
|
60
|
+
const base = dropped ? before.slice(dropped) : before;
|
|
61
|
+
const changes: Patch[] = [];
|
|
62
|
+
if (dropped) changes.push({ p: path, shift: dropped });
|
|
63
|
+
const shared = Math.min(base.length, next.length);
|
|
64
|
+
for (let index = 0; index < shared; index++)
|
|
65
|
+
walk(base[index], next[index], [...path, index], changes);
|
|
66
|
+
for (let index = shared; index < next.length; index++)
|
|
67
|
+
changes.push({ p: [...path, index], v: next[index] });
|
|
68
|
+
if (next.length < base.length) changes.push({ p: path, len: next.length });
|
|
69
|
+
// A card taken out of the middle of a sorted pile moves every card after it, one patch each. A list of plain
|
|
70
|
+
// values is then shorter sent whole.
|
|
71
|
+
const whole: Patch = { p: path, v: next };
|
|
72
|
+
const plain =
|
|
73
|
+
changes.length > 1 && next.every((item) => typeof item !== "object" || item === null);
|
|
74
|
+
if (plain && JSON.stringify(whole).length < JSON.stringify(changes).length) out.push(whole);
|
|
75
|
+
else out.push(...changes);
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
const left = before as Record<string, unknown>;
|
|
79
|
+
const right = after as Record<string, unknown>;
|
|
80
|
+
const keys = keysOf(right);
|
|
81
|
+
const kept = keysOf(left).filter((key) => right[key] !== undefined);
|
|
82
|
+
// Patching keeps the keys that stay in the order they had and adds the new ones after them. When `after` lists
|
|
83
|
+
// them any other way, only the whole object carries its order.
|
|
84
|
+
if (!kept.every((key, index) => keys[index] === key)) {
|
|
85
|
+
out.push({ p: path, v: after });
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
for (const key of keysOf(left))
|
|
89
|
+
if (right[key] === undefined) out.push({ p: [...path, key], del: true });
|
|
90
|
+
for (const key of keys) {
|
|
91
|
+
if (left[key] !== undefined) walk(left[key], right[key], [...path, key], out);
|
|
92
|
+
else out.push({ p: [...path, key], v: right[key] });
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** The changes that turn `before` into `after`. Both are plain JSON values. */
|
|
97
|
+
export function diff(before: unknown, after: unknown): Patch[] {
|
|
98
|
+
const out: Patch[] = [];
|
|
99
|
+
walk(before, after, [], out);
|
|
100
|
+
return out;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function applyOne(value: unknown, patch: Patch, depth: number): unknown {
|
|
104
|
+
if (depth === patch.p.length) {
|
|
105
|
+
if (patch.shift !== undefined) return (value as unknown[]).slice(patch.shift);
|
|
106
|
+
if (patch.len !== undefined) return (value as unknown[]).slice(0, patch.len);
|
|
107
|
+
return patch.v;
|
|
108
|
+
}
|
|
109
|
+
const key = patch.p[depth]!;
|
|
110
|
+
const last = depth === patch.p.length - 1;
|
|
111
|
+
if (Array.isArray(value)) {
|
|
112
|
+
const copy = [...value];
|
|
113
|
+
copy[key as number] = applyOne(copy[key as number], patch, depth + 1);
|
|
114
|
+
return copy;
|
|
115
|
+
}
|
|
116
|
+
const copy = { ...(value as Record<string, unknown>) };
|
|
117
|
+
if (last && patch.del) delete copy[key];
|
|
118
|
+
else copy[key] = applyOne(copy[key], patch, depth + 1);
|
|
119
|
+
return copy;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** Applies patches without touching `state`. Untouched branches are shared with it. */
|
|
123
|
+
export function applyPatches<T>(state: T, patches: Patch[]): T {
|
|
124
|
+
let next: unknown = state;
|
|
125
|
+
for (const patch of patches) next = applyOne(next, patch, 0);
|
|
126
|
+
return next as T;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* `value` with every object in it frozen. A branch already frozen is taken as frozen all the way down, so freezing a
|
|
131
|
+
* state built from one before it costs only what changed. What reads a state may then keep answers by the identity of
|
|
132
|
+
* its parts.
|
|
133
|
+
*/
|
|
134
|
+
export function frozen<T>(value: T): T {
|
|
135
|
+
if (typeof value !== "object" || value === null || Object.isFrozen(value)) return value;
|
|
136
|
+
for (const child of Object.values(value)) frozen(child);
|
|
137
|
+
return Object.freeze(value);
|
|
138
|
+
}
|