@weft-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,9 @@
1
- # Temporary Holding Version
1
+ # @weft-js/realtime-webrtc
2
2
 
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.
3
+ > **Early release (0.1.0).** APIs will change between minor versions.
4
+
5
+ Cursors over WebRTC data channels, signalled through the room.
6
+
7
+ ```bash
8
+ npm install @weft-js/realtime-webrtc
9
+ ```
package/package.json CHANGED
@@ -1,6 +1,32 @@
1
1
  {
2
2
  "name": "@weft-js/realtime-webrtc",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "@weft-js/realtime-webrtc: cursors over WebRTC data channels, signalled through the room",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "exports": {
8
+ ".": "./src/index.ts",
9
+ "./plugin": "./plugin.mjs"
10
+ },
11
+ "peerDependencies": {
12
+ "@weft-js/start": "^0.1.0",
13
+ "@weft-js/core": "^0.1.0",
14
+ "@weft-js/multiplayer": "^0.1.0"
15
+ },
16
+ "engines": {
17
+ "node": ">=26"
18
+ },
19
+ "keywords": [
20
+ "weft"
21
+ ],
22
+ "files": [
23
+ "src",
24
+ "plugin.mjs",
25
+ "plugin.d.mts",
26
+ "README.md",
27
+ "LICENSE"
28
+ ],
29
+ "publishConfig": {
30
+ "access": "public"
31
+ }
32
+ }
package/plugin.d.mts ADDED
@@ -0,0 +1,5 @@
1
+ import type { PluginInstance } from '@weft-js/core/plugin'
2
+
3
+ declare const plugin: (options?: Record<string, unknown>) => PluginInstance<unknown>
4
+ /** `webrtc()` for `weft.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,15 @@
1
+ // webrtc() for weft.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 '@weft-js/core/plugin'
4
+
5
+ export const webrtc = definePlugin({
6
+ name: '@weft-js/realtime-webrtc',
7
+ version: '0.1.0',
8
+ weft: '*',
9
+ permissions: { net: ['browser:peers', 'browser:ice-servers'] },
10
+ contribute: () => ({
11
+ agents: { title: 'Peer transport (WebRTC)', 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.' },
12
+ }),
13
+ })
14
+
15
+ export default webrtc
package/src/index.ts ADDED
@@ -0,0 +1,107 @@
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 '@weft-js/core'
8
+ import type { PeerLink, PeerRoom, PeerTransport } from '@weft-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 { pc: RTCPeerConnection; dc?: RTCDataChannel; makingOffer: boolean }
19
+ interface Signal { description?: RTCSessionDescriptionInit; candidate?: RTCIceCandidateInit }
20
+
21
+ /** A peer transport over a mesh of WebRTC data channels, for `presence(conn, { transport })`. */
22
+ export function webrtc({ iceServers = [], max = 8 }: WebRtcOptions = {}): PeerTransport {
23
+ return {
24
+ name: 'webrtc',
25
+ open(room: PeerRoom): PeerLink {
26
+ return createRoot(dispose => {
27
+ const conns = new Map<string, Conn>()
28
+ const open = state(0)
29
+ const channel = (id: string, c: Conn, dc: RTCDataChannel) => {
30
+ c.dc = dc
31
+ dc.onopen = () => { open.value++ }
32
+ dc.onclose = () => { open.value++ }
33
+ dc.onmessage = e => { if (typeof e.data === 'string' && e.data.length < 1024) room.receive(id, e.data) }
34
+ }
35
+ const connect = (id: string) => {
36
+ const had = conns.get(id)
37
+ if (had) return had
38
+ const c: Conn = { pc: new RTCPeerConnection({ iceServers }), makingOffer: false }
39
+ conns.set(id, c)
40
+ c.pc.onicecandidate = e => { if (e.candidate) room.signal(id, { candidate: e.candidate.toJSON() }) }
41
+ c.pc.onconnectionstatechange = () => { open.value++ }
42
+ c.pc.ondatachannel = e => channel(id, c, e.channel)
43
+ c.pc.onnegotiationneeded = async () => {
44
+ try {
45
+ c.makingOffer = true
46
+ await c.pc.setLocalDescription()
47
+ room.signal(id, { description: c.pc.localDescription!.toJSON() })
48
+ } catch {
49
+ // The other side's offer won: its handler takes over.
50
+ } finally {
51
+ c.makingOffer = false
52
+ }
53
+ }
54
+ return c
55
+ }
56
+ const answer = async (from: string, data: unknown) => {
57
+ if (!untrack(() => room.peers.value).includes(from) || typeof data !== 'object' || !data) return
58
+ const { description, candidate } = data as Signal
59
+ const c = connect(from)
60
+ try {
61
+ if (description) {
62
+ // Perfect negotiation: the lower id gives way when both offer at once.
63
+ const collision = description.type === 'offer' && (c.makingOffer || c.pc.signalingState !== 'stable')
64
+ if (collision && room.self > from) return
65
+ await c.pc.setRemoteDescription(description)
66
+ if (description.type === 'offer') {
67
+ await c.pc.setLocalDescription()
68
+ room.signal(from, { description: c.pc.localDescription!.toJSON() })
69
+ }
70
+ } else if (candidate) await c.pc.addIceCandidate(candidate).catch(() => {})
71
+ } catch {
72
+ // A bad frame from a peer costs that peer its link: frames for it stay on the socket.
73
+ }
74
+ }
75
+ const stop = room.onSignal((from, data) => void answer(from, data))
76
+ const close = (id: string) => {
77
+ conns.get(id)?.pc.close()
78
+ conns.delete(id)
79
+ open.value++
80
+ }
81
+ effect(() => room.peers.value, ids => {
82
+ if (ids.length > max) return
83
+ for (const id of ids) {
84
+ if (conns.has(id)) continue
85
+ const c = connect(id)
86
+ if (room.self < id) channel(id, c, c.pc.createDataChannel('weft', { ordered: false, maxRetransmits: 0 }))
87
+ }
88
+ for (const id of conns.keys()) if (!ids.includes(id)) close(id)
89
+ })
90
+ const up = derived(() => {
91
+ void open.value
92
+ const ids = room.peers.value
93
+ return ids.length > 0 && ids.length <= max && ids.every(id => conns.get(id)?.dc?.readyState === 'open')
94
+ })
95
+ return {
96
+ up,
97
+ send(text) { for (const c of conns.values()) if (c.dc?.readyState === 'open') c.dc.send(text) },
98
+ close() {
99
+ stop()
100
+ for (const id of conns.keys()) close(id)
101
+ dispose()
102
+ },
103
+ }
104
+ })
105
+ },
106
+ }
107
+ }