@kerf-js/realtime-webrtc 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 ADDED
@@ -0,0 +1,16 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ravonus
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
6
+ documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
7
+ rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
8
+ persons to whom the Software is furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
11
+ Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
14
+ WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
15
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
16
+ OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,221 @@
1
- # Temporary Holding Version
1
+ <p align="center">
2
+ <a href="https://github.com/Ravonus/kerf">
3
+ <img src="https://raw.githubusercontent.com/Ravonus/kerf/main/site/public/logo.svg" width="88" height="88" alt="Kerf">
4
+ </a>
5
+ </p>
2
6
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
7
+ <h1 align="center">@kerf-js/realtime-webrtc</h1>
8
+
9
+ <p align="center">
10
+ <strong>Live cursors browser to browser, over WebRTC data channels.</strong><br>
11
+ Signalled through your channel, so the server still vouches for who each peer is.
12
+ </p>
13
+
14
+ <p align="center">
15
+ <a href="https://www.npmjs.com/package/@kerf-js/realtime-webrtc"><img src="https://img.shields.io/npm/v/@kerf-js/realtime-webrtc?color=145c3c&label=npm" alt="npm version"></a>
16
+ <a href="https://github.com/Ravonus/kerf/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-MIT-145c3c" alt="MIT license"></a>
17
+ <a href="https://github.com/Ravonus/kerf/actions"><img src="https://img.shields.io/github/actions/workflow/status/Ravonus/kerf/quality.yml?branch=main&label=checks" alt="checks"></a>
18
+ </p>
19
+
20
+ <p align="center">
21
+ <a href="#quick-start">Quick start</a> ·
22
+ <a href="https://github.com/Ravonus/kerf/tree/main/docs">Docs</a> ·
23
+ <a href="https://github.com/Ravonus/kerf/tree/main/examples">Examples</a> ·
24
+ <a href="https://github.com/Ravonus/kerf/blob/main/CHANGELOG.md">Changelog</a> ·
25
+ <a href="https://github.com/Ravonus/kerf">GitHub</a>
26
+ </p>
27
+
28
+ > [!IMPORTANT]
29
+ > **Early release (0.1.x).** APIs can change between minor versions. Pin the version and read the
30
+ > [changelog](https://github.com/Ravonus/kerf/blob/main/CHANGELOG.md) before you upgrade.
31
+
32
+ A cursor transport for [`@kerf-js/multiplayer`](https://www.npmjs.com/package/@kerf-js/multiplayer) <sup>[source](https://github.com/Ravonus/kerf/tree/main/packages/multiplayer)</sup>. By
33
+ default cursors go through your server over the channel's socket. With `webrtc()`, each browser opens a data channel to
34
+ every other one and sends its cursor directly. Offers and ICE candidates go through the channel, so a frame's sender is
35
+ the peer the server named when the connection was made. There is no extra service to run, only STUN, and TURN when
36
+ peers are on different networks.
37
+
38
+ ## Highlights
39
+
40
+ - **No server in the path.** Cursors go peer to peer. Your server only carries the signalling.
41
+ - **Identity from the room.** Offers and candidates are signals through the channel, stamped by the server with who
42
+ sent them. Signals from a connection that isn't in the room are ignored.
43
+ - **Built for cursors.** Data channels are unordered with no retransmits (`ordered: false, maxRetransmits: 0`): a lost
44
+ position is replaced by the next.
45
+ - **A mesh, with a ceiling.** Each peer holds one connection per other peer. Past `max` peers (default 8) it doesn't
46
+ open any and stays on the socket.
47
+ - **Falls back on its own.** The link is `up` only when every peer's data channel is open. Until then, and for a peer
48
+ with no working path, cursors go over the socket.
49
+ - **Perfect negotiation.** When two peers offer at once, the one with the lower id gives way, so a connection settles
50
+ without a retry loop.
51
+
52
+ ## Install
53
+
54
+ ```bash
55
+ # npm
56
+ npm install @kerf-js/multiplayer @kerf-js/realtime-webrtc
57
+
58
+ # pnpm
59
+ pnpm add @kerf-js/multiplayer @kerf-js/realtime-webrtc
60
+
61
+ # bun
62
+ bun add @kerf-js/multiplayer @kerf-js/realtime-webrtc
63
+ ```
64
+
65
+ Or install `@kerf-js/multiplayer`, then let the `kerf` CLI install this package and add its plugin to
66
+ `kerf.config.ts`:
67
+
68
+ ```bash
69
+ npm install @kerf-js/multiplayer
70
+ npx kerf add realtime-webrtc
71
+ ```
72
+
73
+ `@kerf-js/multiplayer` is a peer dependency, so add it too. The package has no runtime dependencies: it uses the
74
+ browser's `RTCPeerConnection`.
75
+
76
+ `kerf add` puts its plugin in `kerf.config.ts`:
77
+
78
+ ```ts
79
+ // kerf.config.ts
80
+ import { defineConfig } from '@kerf-js/core/config'
81
+ import realtimeWebrtc from '@kerf-js/realtime-webrtc/plugin'
82
+
83
+ export default defineConfig({
84
+ plugins: [realtimeWebrtc()],
85
+ })
86
+ ```
87
+
88
+ The plugin fills no slot. Listed, it puts what the browser reaches on the record (`browser:peers`,
89
+ `browser:ice-servers`): STUN, TURN and other browsers, none of which goes through your server. The transport itself is
90
+ passed to `presence()` in a page.
91
+
92
+ ## Setup
93
+
94
+ | Network | What you need |
95
+ | ------- | ------------- |
96
+ | Peers on one network | Nothing. The default `iceServers` is empty. |
97
+ | Peers on different networks | A STUN server, so each browser learns its public address. |
98
+ | Peers behind strict NATs or firewalls | A TURN server, which relays the data when no direct path exists. |
99
+
100
+ Pass them as standard `RTCIceServer` entries. TURN credentials are visible to the page, so use short-lived ones.
101
+
102
+ ## Quick start
103
+
104
+ The channel needs nothing extra: signalling uses the `mp.signal` message `multiplayer()` already defines.
105
+
106
+ ```ts
107
+ // src/server/doc.ts
108
+ import { channel } from '@kerf-js/start'
109
+ import { multiplayer } from '@kerf-js/multiplayer/server'
110
+ import { z } from 'zod'
111
+
112
+ const mp = multiplayer<{ id: string }>({
113
+ user: ({ ctx }) => ({ id: ctx.user!.id, name: ctx.user!.name }),
114
+ })
115
+
116
+ export const doc = channel({
117
+ params: z.object({ id: z.string().max(64) }),
118
+ authorize: ({ ctx }) => !!ctx.user,
119
+ client: { ...mp.client },
120
+ server: { ...mp.server },
121
+ on: { ...mp.on },
122
+ left: mp.left,
123
+ })
124
+ ```
125
+
126
+ ```tsx
127
+ // src/routes/room.tsx
128
+ import { cursors, presence } from '@kerf-js/multiplayer'
129
+ import { Cursors } from '@kerf-js/multiplayer/ui'
130
+ import { webrtc } from '@kerf-js/realtime-webrtc'
131
+ import { doc } from '#/server/doc'
132
+
133
+ export default function Room() {
134
+ const chat = doc.connect({ id: 'lobby' })
135
+ const live = presence(chat, {
136
+ transport: webrtc({
137
+ iceServers: [{ urls: 'stun:stun.example.com' }],
138
+ }),
139
+ })
140
+ return (
141
+ <main>
142
+ <p>Cursors via {live.via.value}</p>
143
+ <Cursors of={cursors(live)} />
144
+ </main>
145
+ )
146
+ }
147
+ ```
148
+
149
+ `live.via.value` is `'socket'` until every peer's data channel is open, then `'webrtc'`.
150
+
151
+ ## How it works
152
+
153
+ 1. When `presence` learns this connection's id, it opens the transport. For each peer in the room, it creates an
154
+ `RTCPeerConnection`. The peer with the lower id creates the data channel, named `kerf`.
155
+ 2. Offers, answers and ICE candidates are sent with `signal(to, data)`, which goes through the channel as
156
+ `mp.signal`. The server stamps each with its sender and forwards it to that one peer only.
157
+ 3. A signal from a connection that isn't in the room, or that isn't an object, is ignored. A bad offer or candidate
158
+ costs that peer its link; frames to it stay on the socket.
159
+ 4. A message on a data channel is passed on only when it's a string under 1024 characters, and then checked again by
160
+ `presence` like any frame off a transport.
161
+ 5. A peer that leaves the room has its connection closed. Over `max` peers, no new connections open.
162
+
163
+ ## API reference
164
+
165
+ ### `@kerf-js/realtime-webrtc`
166
+
167
+ `webrtc(options?): PeerTransport`: the transport, for `presence(conn, { transport })`.
168
+
169
+ | Option | Type | Default | What it does |
170
+ | ------------ | ---------------- | ------- | ------------ |
171
+ | `iceServers` | `RTCIceServer[]` | `[]` | STUN and TURN servers. Empty works for peers on one network. |
172
+ | `max` | `number` | `8` | With more peers than this, it stays on the socket: a mesh costs each peer one connection per other. |
173
+
174
+ Type: `WebRtcOptions`.
175
+
176
+ ### `@kerf-js/realtime-webrtc/plugin`
177
+
178
+ The plugin for `kerf.config.ts`, as a default export and as the named export `webrtc`. Import the default, or rename
179
+ the named one, so it doesn't clash with the transport of the same name.
180
+
181
+ ## Limits
182
+
183
+ - Only cursors ride WebRTC. Presence state, `@kerf-js/multiplayer`'s relay events and signalling stay on the channel,
184
+ where the server checks them.
185
+ - One connection per pair of peers, so cost grows with the square of the room's size. Above `max` (8) the room stays
186
+ on the socket.
187
+ - A signal is up to 16384 bytes of JSON (`@kerf-js/multiplayer`'s limit), and a frame under 1024 characters.
188
+ - It needs a browser. During server rendering nothing is opened.
189
+
190
+ ## Troubleshooting
191
+
192
+ | Symptom | Cause | Fix |
193
+ | ------- | ----- | --- |
194
+ | `via` stays `'socket'` on different networks | No STUN, so peers can't find a path. | Add a STUN server to `iceServers`. |
195
+ | `via` stays `'socket'` for some users | A strict NAT or firewall blocks direct paths. | Add a TURN server. |
196
+ | `via` stays `'socket'` in a big room | More than `max` peers. | Expected: raise `max` only if each browser can hold that many connections. |
197
+ | `kerf check` stops after `kerf add` | A newly added plugin's permissions must be approved. | `kerf plugins approve @kerf-js/realtime-webrtc`. |
198
+
199
+ ## Related packages
200
+
201
+ | Package | What it is |
202
+ | ------- | ---------- |
203
+ | [`@kerf-js/multiplayer`](https://www.npmjs.com/package/@kerf-js/multiplayer) | Presence, cursors and the relay that this transport carries cursors for. |
204
+ | [`@kerf-js/realtime-livekit`](https://www.npmjs.com/package/@kerf-js/realtime-livekit) | Cursors over a LiveKit room, which also carries audio and video. |
205
+ | [`@kerf-js/realtime-socketio`](https://www.npmjs.com/package/@kerf-js/realtime-socketio) | Cursors through a Socket.IO relay you run. |
206
+ | [`@kerf-js/realtime-redis`](https://www.npmjs.com/package/@kerf-js/realtime-redis) | A `realtime.bus` over Redis: how server instances reach each other, not a cursor transport. |
207
+ | [`@kerf-js/realtime-nats`](https://www.npmjs.com/package/@kerf-js/realtime-nats) | A `realtime.bus` over NATS. |
208
+ | [`@kerf-js/realtime-durable-object`](https://www.npmjs.com/package/@kerf-js/realtime-durable-object) | A `realtime.bus` on Cloudflare Durable Objects. |
209
+ | [`@kerf-js/core`](https://www.npmjs.com/package/@kerf-js/core) | The compiler and reactive runtime, the Vite plugin, the plugin system and test utilities. |
210
+ | [`@kerf-js/start`](https://www.npmjs.com/package/@kerf-js/start) | The full-stack runtime: routes, server functions, `channel`, `realtime()` and the realtime hub. |
211
+
212
+ ## Contributing
213
+
214
+ See [CONTRIBUTING.md](https://github.com/Ravonus/kerf/blob/main/CONTRIBUTING.md). From the repository,
215
+ `pnpm --filter @kerf-js/realtime-webrtc test` runs what holds without a browser. `RTCPeerConnection` needs one, so the
216
+ real check is `@kerf-js/multiplayer`'s end-to-end test with `--via webrtc`, which runs two Chromium contexts in one
217
+ room.
218
+
219
+ ## License
220
+
221
+ [MIT](https://github.com/Ravonus/kerf/blob/main/LICENSE)
package/package.json CHANGED
@@ -1,6 +1,41 @@
1
1
  {
2
2
  "name": "@kerf-js/realtime-webrtc",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "@kerf-js/realtime-webrtc: cursors over WebRTC data channels, signalled through the room",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/Ravonus/kerf.git",
9
+ "directory": "packages/realtime-webrtc"
10
+ },
11
+ "homepage": "https://github.com/Ravonus/kerf/tree/main/packages/realtime-webrtc#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/Ravonus/kerf/issues"
14
+ },
15
+ "type": "module",
16
+ "exports": {
17
+ ".": "./src/index.ts",
18
+ "./plugin": "./plugin.mjs"
19
+ },
20
+ "peerDependencies": {
21
+ "@kerf-js/start": "^0.1.0",
22
+ "@kerf-js/core": "^0.1.0",
23
+ "@kerf-js/multiplayer": "^0.1.0"
24
+ },
25
+ "engines": {
26
+ "node": ">=24"
27
+ },
28
+ "keywords": [
29
+ "kerf"
30
+ ],
31
+ "files": [
32
+ "src",
33
+ "plugin.mjs",
34
+ "plugin.d.mts",
35
+ "README.md",
36
+ "LICENSE"
37
+ ],
38
+ "publishConfig": {
39
+ "access": "public"
40
+ }
6
41
  }
package/plugin.d.mts ADDED
@@ -0,0 +1,5 @@
1
+ import type { PluginInstance } from '@kerf-js/core/plugin'
2
+
3
+ declare const plugin: (options?: Record<string, unknown>) => PluginInstance<unknown>
4
+ /** `webrtc()` for `kerf.config.ts`: puts peers and ICE servers on the record of what the app reaches. A page passes the transport to `presence`. */
5
+ export default plugin
package/plugin.mjs ADDED
@@ -0,0 +1,18 @@
1
+ // webrtc() for kerf.config.ts: no slot, since a page passes the transport to `presence`. Listed, what it reaches is on
2
+ // the record. A browser talks to STUN, TURN and peers directly, and none of that goes through the server.
3
+ import { definePlugin } from '@kerf-js/core/plugin'
4
+
5
+ export const webrtc = definePlugin({
6
+ name: '@kerf-js/realtime-webrtc',
7
+ version: '0.1.0',
8
+ kerf: '*',
9
+ permissions: { net: ['browser:peers', 'browser:ice-servers'] },
10
+ contribute: () => ({
11
+ agents: {
12
+ title: 'Peer transport (WebRTC)',
13
+ text: '`presence(conn, { transport: webrtc({ iceServers }) })` sends cursors directly between browsers, and the socket carries them until every peer is connected. Only cursors ride it: state and the relay stay on the server, which checks them.',
14
+ },
15
+ }),
16
+ })
17
+
18
+ export default webrtc
package/src/index.ts ADDED
@@ -0,0 +1,153 @@
1
+ // Cursors over WebRTC data channels: a full mesh, with offers and candidates through the room, so `from` on a frame is
2
+ // the peer the server vouched for when the connection was made. Unordered and without retries, like what it carries. A
3
+ // page without a working path to a peer stays on the socket: `up` is true only when every peer is connected.
4
+ //
5
+ // presence(chat, { transport: webrtc({ iceServers: [{ urls: 'stun:stun.example.com' }] }) })
6
+
7
+ import { createRoot, derived, effect, state, untrack } from '@kerf-js/core'
8
+ import type { PeerLink, PeerRoom, PeerTransport } from '@kerf-js/multiplayer'
9
+
10
+ /** Options of `webrtc()`. */
11
+ export interface WebRtcOptions {
12
+ /** STUN and TURN. Default none: peers on one network. */
13
+ iceServers?: RTCIceServer[]
14
+ /** More peers than this and it stays on the socket: a mesh costs each peer one connection per other. Default 8. */
15
+ max?: number
16
+ }
17
+
18
+ interface Conn {
19
+ pc: RTCPeerConnection
20
+ dc?: RTCDataChannel
21
+ makingOffer: boolean
22
+ }
23
+ interface Signal {
24
+ description?: RTCSessionDescriptionInit
25
+ candidate?: RTCIceCandidateInit
26
+ }
27
+
28
+ function connections(
29
+ room: PeerRoom,
30
+ iceServers: RTCIceServer[],
31
+ conns: Map<string, Conn>,
32
+ open: { value: number },
33
+ ) {
34
+ const channel = (id: string, c: Conn, dc: RTCDataChannel) => {
35
+ c.dc = dc
36
+ dc.onopen = () => {
37
+ open.value++
38
+ }
39
+ dc.onclose = () => {
40
+ open.value++
41
+ }
42
+ dc.onmessage = (e) => {
43
+ if (typeof e.data === 'string' && e.data.length < 1024) room.receive(id, e.data)
44
+ }
45
+ }
46
+ const connect = (id: string) => {
47
+ const had = conns.get(id)
48
+ if (had) return had
49
+ const c: Conn = { pc: new RTCPeerConnection({ iceServers }), makingOffer: false }
50
+ conns.set(id, c)
51
+ c.pc.onicecandidate = (e) => {
52
+ if (e.candidate) room.signal(id, { candidate: e.candidate.toJSON() })
53
+ }
54
+ c.pc.onconnectionstatechange = () => {
55
+ open.value++
56
+ }
57
+ c.pc.ondatachannel = (e) => channel(id, c, e.channel)
58
+ c.pc.onnegotiationneeded = async () => {
59
+ try {
60
+ c.makingOffer = true
61
+ await c.pc.setLocalDescription()
62
+ room.signal(id, { description: c.pc.localDescription!.toJSON() })
63
+ } catch {
64
+ // The other side's offer won: its handler takes over.
65
+ } finally {
66
+ c.makingOffer = false
67
+ }
68
+ }
69
+ return c
70
+ }
71
+ return { channel, connect }
72
+ }
73
+
74
+ function signalHandler(room: PeerRoom, connect: (id: string) => Conn) {
75
+ return async (from: string, data: unknown) => {
76
+ if (!untrack(() => room.peers.value).includes(from) || typeof data !== 'object' || !data) return
77
+ const { description, candidate } = data as Signal
78
+ const c = connect(from)
79
+ try {
80
+ if (description) {
81
+ // Perfect negotiation: the lower id gives way when both offer at once.
82
+ const collision =
83
+ description.type === 'offer' && (c.makingOffer || c.pc.signalingState !== 'stable')
84
+ if (collision && room.self > from) return
85
+ await c.pc.setRemoteDescription(description)
86
+ if (description.type === 'offer') {
87
+ await c.pc.setLocalDescription()
88
+ room.signal(from, { description: c.pc.localDescription!.toJSON() })
89
+ }
90
+ } else if (candidate) await c.pc.addIceCandidate(candidate).catch(() => {})
91
+ } catch {
92
+ // A bad frame from a peer costs that peer its link: frames for it stay on the socket.
93
+ }
94
+ }
95
+ }
96
+
97
+ /** A peer transport over a mesh of WebRTC data channels, for `presence(conn, { transport })`. */
98
+ export function webrtc({ iceServers = [], max = 8 }: WebRtcOptions = {}): PeerTransport {
99
+ return {
100
+ name: 'webrtc',
101
+ open(room: PeerRoom): PeerLink {
102
+ return createRoot((dispose) => {
103
+ const conns = new Map<string, Conn>()
104
+ const open = state(0)
105
+ const { channel, connect } = connections(room, iceServers, conns, open)
106
+ const answer = signalHandler(room, connect)
107
+ const stop = room.onSignal((from, data) => void answer(from, data))
108
+ const close = (id: string) => {
109
+ conns.get(id)?.pc.close()
110
+ conns.delete(id)
111
+ open.value++
112
+ }
113
+ effect(
114
+ () => room.peers.value,
115
+ (ids) => {
116
+ if (ids.length > max) return
117
+ for (const id of ids) {
118
+ if (conns.has(id)) continue
119
+ const c = connect(id)
120
+ if (room.self < id)
121
+ channel(
122
+ id,
123
+ c,
124
+ c.pc.createDataChannel('kerf', { ordered: false, maxRetransmits: 0 }),
125
+ )
126
+ }
127
+ for (const id of conns.keys()) if (!ids.includes(id)) close(id)
128
+ },
129
+ )
130
+ const up = derived(() => {
131
+ void open.value
132
+ const ids = room.peers.value
133
+ return (
134
+ ids.length > 0 &&
135
+ ids.length <= max &&
136
+ ids.every((id) => conns.get(id)?.dc?.readyState === 'open')
137
+ )
138
+ })
139
+ return {
140
+ up,
141
+ send(text) {
142
+ for (const c of conns.values()) if (c.dc?.readyState === 'open') c.dc.send(text)
143
+ },
144
+ close() {
145
+ stop()
146
+ for (const id of conns.keys()) close(id)
147
+ dispose()
148
+ },
149
+ }
150
+ })
151
+ },
152
+ }
153
+ }