@dimchansky/meshpost 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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Dmitrij Koniajev
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,294 @@
1
- # Temporary Holding Version
1
+ # Meshpost
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
+ [![CI](https://github.com/dimchansky/meshpost/actions/workflows/ci.yml/badge.svg)](https://github.com/dimchansky/meshpost/actions/workflows/ci.yml)
4
+ [![npm](https://img.shields.io/npm/v/%40dimchansky%2Fmeshpost)](https://www.npmjs.com/package/@dimchansky/meshpost)
5
+
6
+ **Live demo:** [dimchansky.github.io/meshpost](https://dimchansky.github.io/meshpost/) — open on two devices or browser tabs to test direct peer-to-peer cursors and chat.
7
+
8
+ Meshpost connects browsers directly to send small binary packets (up to 16 KiB) with no backend server for app traffic.
9
+
10
+ - **Direct peer-to-peer:** Browsers connect directly to each other. There is no host or central relay for your data.
11
+ - **Two delivery modes:** Send fast unreliable packets (for cursors or game positions) or ordered reliable packets (for chat or commands).
12
+ - **Resilient:** Connected peers keep talking even if the first person leaves or the discovery server goes offline.
13
+ - **Zero runtime dependencies:** TypeScript ES modules built on native browser WebRTC.
14
+
15
+ ## Quick start: 2-browser chat in 30 lines
16
+
17
+ 1. Install from npm, or clone and build from source (requires Node.js 22+):
18
+
19
+ ```sh
20
+ npm install @dimchansky/meshpost
21
+ ```
22
+
23
+ Or build from source:
24
+
25
+ ```sh
26
+ git clone https://github.com/dimchansky/meshpost.git
27
+ cd meshpost
28
+ npm ci
29
+ npm run build
30
+ ```
31
+
32
+ 2. Import `joinRoom` and a signaling adapter (used only to help browsers find each other) in your browser app (use `@dimchansky/meshpost` if installed as a package, or `./dist/index.js` from a local build):
33
+
34
+ ```ts
35
+ import { joinRoom, mqttSignaling } from '@dimchansky/meshpost'
36
+
37
+ const encoder = new TextEncoder()
38
+ const decoder = new TextDecoder()
39
+
40
+ // Join a room. Browsers with the same appId and room name connect automatically.
41
+ const room = joinRoom('lobby', {
42
+ appId: 'my-chat-app',
43
+ signaling: mqttSignaling()
44
+ })
45
+
46
+ room.onPeerJoin((peerId) => console.log('Joined:', peerId))
47
+ room.onPeerLeave((peerId) => console.log('Left:', peerId))
48
+
49
+ // Receive binary packets and decode text.
50
+ const stop = room.onPacket((from, bytes, delivery) => {
51
+ if (delivery === 'reliable') {
52
+ console.log(from, decoder.decode(bytes))
53
+ }
54
+ })
55
+
56
+ // Send a reliable message to all connected peers.
57
+ // Note: delivery defaults to 'unreliable'. Set 'reliable' for messages that must arrive.
58
+ function sendMessage(text: string) {
59
+ const results = room.send(encoder.encode(text), { delivery: 'reliable' })
60
+ for (const [peerId, status] of results) {
61
+ console.log(peerId, status) // 'accepted' | 'busy' | 'unavailable' | 'too-large'
62
+ }
63
+ }
64
+
65
+ // Clean up when the tab closes.
66
+ window.addEventListener(
67
+ 'pagehide',
68
+ () => {
69
+ stop()
70
+ room.leave()
71
+ },
72
+ { once: true }
73
+ )
74
+ ```
75
+
76
+ 3. Use `createChannel` when your app has multiple message types (so modules do not collide):
77
+
78
+ ```ts
79
+ import { createChannel } from './dist/index.js'
80
+
81
+ const cursors = createChannel(room, 'cursor', { delivery: 'unreliable' })
82
+ const chat = createChannel(room, 'chat', { delivery: 'reliable' })
83
+
84
+ cursors.onPacket((from, bytes) => updateCursor(from, bytes))
85
+ chat.onPacket((from, bytes) => showChat(from, decoder.decode(bytes)))
86
+
87
+ // Broadcast a cursor update to everyone.
88
+ cursors.send(cursorBytes)
89
+
90
+ // Send a reliable command to one specific peer and inspect the result.
91
+ const status = chat.send(encoder.encode('hello'), { to: peerId }).get(peerId)
92
+ ```
93
+
94
+ ## Choose a signaling adapter
95
+
96
+ Browsers need a signaling adapter only to find each other and start the connection. After that, data travels directly between browsers.
97
+
98
+ | Adapter | Best for | Server needed? |
99
+ | --------------------------- | ------------------------------------------------------------------------------ | ------------------ |
100
+ | `mqttSignaling(options?)` | Different browsers, devices, and networks out of the box | No (public relays) |
101
+ | `tabSignaling()` | Multiple tabs in the same browser profile (works offline) | No |
102
+ | `manualSignaling(outgoing)` | Completely offline browsers (no network needed) by copying and pasting text | No |
103
+ | Custom `Signaling` | Production apps with your own server (such as WebSocket or Server-Sent Events) | Your server |
104
+
105
+ ### Local tabs (`tabSignaling`)
106
+
107
+ ```ts
108
+ import { joinRoom, tabSignaling } from './dist/index.js'
109
+
110
+ const room = joinRoom('arena', {
111
+ appId: 'my-game',
112
+ signaling: tabSignaling()
113
+ })
114
+ ```
115
+
116
+ ### Offline copy-paste (`manualSignaling`)
117
+
118
+ ```ts
119
+ import { joinRoom, manualSignaling } from './dist/index.js'
120
+
121
+ const manual = manualSignaling((toPeerId, replyText) => {
122
+ // Show replyText to the user to send to `toPeerId`.
123
+ })
124
+
125
+ const room = joinRoom('offline-room', {
126
+ appId: 'my-app',
127
+ signaling: manual.signaling,
128
+ handshakeTimeoutMs: 180_000
129
+ })
130
+
131
+ const myContactCard = manual.contact() // Share this text with the other browser.
132
+ manual.accept(pastedTextFromPeer) // Paste incoming contact cards and replies here.
133
+ manual.forget(oldPeerId) // Optional: stop retrying an old contact.
134
+ ```
135
+
136
+ > **Password note:** Pass `password: 'secret'` to `joinRoom()` so only peers with the same password can join the room. With `mqttSignaling()`, this also encrypts setup messages. Browsers allow encryption only on `https://` pages or `http://localhost` (`127.0.0.1`), so using `password` with `mqttSignaling()` on `file://` or plain `http://<lan-ip>` throws an error. (`tabSignaling()` and `manualSignaling()` support `password` everywhere.)
137
+
138
+ ## Public API reference
139
+
140
+ ### `joinRoom(name, options)`
141
+
142
+ Creates a room, assigns a random peer ID (`room.id`), and immediately starts looking for other peers.
143
+
144
+ - `name`: Room name. Must match `^[a-zA-Z0-9_-]{1,64}$`.
145
+ - Throws an error immediately if `name`, `appId`, `password`, timeouts, `maxPeers`, or `rtcConfig` are invalid.
146
+
147
+ | `RoomOptions` field | Type | Default | Purpose |
148
+ | ----------------------- | ------------------------- | ------------------- | ---------------------------------------------------------------------------------------------------------------- |
149
+ | `signaling` | `Signaling` | _(required)_ | Adapter that helps browsers find each other and start direct connections. |
150
+ | `appId` | `string` | `'meshpost'` | Keeps your app's rooms separate from other apps on the same relay (`[a-zA-Z0-9._-]{1,64}`). |
151
+ | `password` | `string` | `undefined` | Optional shared password. Keeps rooms separate and encrypts setup messages on MQTT. |
152
+ | `turnConfig` | `readonly RTCIceServer[]` | `[]` | Extra TURN (or STUN) servers appended to `rtcConfig.iceServers` (or `defaultIceServers` when omitted). |
153
+ | `rtcConfig` | `RTCConfiguration` | `defaultIceServers` | Custom WebRTC config. Keeps `defaultIceServers` unless you set `iceServers` (pass `{ iceServers: [] }` offline). |
154
+ | `handshakeTimeoutMs` | `number` | `35_000` | Max time to wait per connection attempt before retrying. |
155
+ | `iceGatheringTimeoutMs` | `number` | `2_500` | Max time to wait for network addresses before starting a connection. |
156
+ | `maxPeers` | `number` | `32` | Maximum simultaneous peer connections. |
157
+
158
+ ### `Room`
159
+
160
+ | Member | Description |
161
+ | ------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
162
+ | `room.id` | Your peer ID (`string`). A page reload creates a new peer ID. |
163
+ | `room.peers` | Current list of connected peer IDs (returns a fresh copy each time). |
164
+ | `room.signalingState` | Current adapter state: `'connecting' \| 'online' \| 'offline' \| 'closed'`. |
165
+ | `room.send(bytes, options?: SendOptions)` | Sends a `Uint8Array`. `options` accepts `{ to?: string, delivery?: Delivery }` (`Delivery` is `'unreliable' \| 'reliable'`, default `'unreliable'`). Returns `ReadonlyMap<string, SendResult>`. |
166
+ | `room.getStats(peerId)` | Returns `Promise<PeerStats \| null>` with ping, route, byte counts, and send buffer sizes (`null` if not connected). |
167
+ | `room.onPacket((from, bytes, delivery) => ...)` | Runs when a packet arrives. Returns an unsubscribe function. |
168
+ | `room.onDrain((peerId, delivery) => ...)` | Runs when a full send buffer has space again (after `send()` returned `'busy'`). Returns unsubscribe. |
169
+ | `room.onPeerJoin((peerId) => ...)` | Runs when a peer finishes connecting and is ready to exchange packets. Returns unsubscribe. |
170
+ | `room.onPeerLeave((peerId) => ...)` | Runs when a connected peer disconnects. Returns unsubscribe. |
171
+ | `room.onSignalingChange((state, reason?) => ...)` | Runs on future `signalingState` changes. Returns unsubscribe. |
172
+ | `room.leave()` | Leaves the room, tells peers you left, and closes all connections. Safe to call more than once. |
173
+
174
+ ### `SendResult`
175
+
176
+ `room.send()` and `channel.send()` return a `ReadonlyMap<string, SendResult>` immediately. Meshpost does not queue failed packets in the background:
177
+
178
+ | Value | Meaning |
179
+ | --------------- | ----------------------------------------------------------------------------------- |
180
+ | `'accepted'` | Browser accepted the packet for sending. |
181
+ | `'busy'` | Send buffer is full (`64 KiB` unreliable / `256 KiB` reliable). Wait for `onDrain`. |
182
+ | `'unavailable'` | Target peer is not connected, unknown, or is yourself. |
183
+ | `'too-large'` | Packet is larger than 16,384 bytes (or larger than the other browser allows). |
184
+
185
+ ### `PeerStats`
186
+
187
+ `await room.getStats(peerId)` returns a read-only snapshot for a connected peer, or `null` if the peer is not connected or the room is closed:
188
+
189
+ | Field | Type | Meaning |
190
+ | -------------------- | ---------------- | ----------------------------------------------------------------------------------------------------- |
191
+ | `rttMs` | `number \| null` | Current round-trip ping in whole milliseconds (`null` if not measured yet). |
192
+ | `route` | `PeerRoute` | `'direct'` for peer-to-peer, `'relay'` through a TURN server, or `'unknown'` if not reported yet. |
193
+ | `bytesSent` | `number` | Total app payload bytes sent to this peer across both delivery modes (unreliable and reliable). |
194
+ | `bytesReceived` | `number` | Total app payload bytes received from this peer across both delivery modes (unreliable and reliable). |
195
+ | `bufferedUnreliable` | `number` | Bytes currently waiting in the unreliable send buffer. |
196
+ | `bufferedReliable` | `number` | Bytes currently waiting in the reliable send buffer. |
197
+
198
+ ### `createChannel(room, name, options?: ChannelOptions)`
199
+
200
+ Creates a named message stream (such as `'chat'` or `'cursor'`) on your existing room connections. Each channel only receives packets sent to its own name.
201
+
202
+ - `name`: 1–64 UTF-8 bytes. Uses `1 + nameBytes.length` bytes of the 16,384-byte packet limit.
203
+ - `options` (`ChannelOptions`): `{ delivery?: Delivery }`. Defaults to `'unreliable'`.
204
+ - Returns a `Channel` with `{ name, delivery, send(bytes, options?: ChannelSendOptions), onPacket((from, bytes) => ...) }` (`ChannelSendOptions` is `{ to?: string }`).
205
+
206
+ ### Signaling exports
207
+
208
+ - `mqttSignaling({ urls?, appId?, password?, handshakeTimeoutMs? })` — Connects browsers across different devices and networks using built-in public MQTT relay servers (`defaultMqttRelays`).
209
+ - `tabSignaling()` — Connects tabs open to the same site (same protocol, domain, and port) in the same browser. Works offline with no server.
210
+ - `manualSignaling(outgoing)` — Connects completely offline browsers by copying and pasting text. Returns `{ signaling, contact(), accept(text), forget(peerId) }`.
211
+ - `defaultIceServers` — Built-in Cloudflare and Google public servers (STUN) that help browsers find their public network address.
212
+ - Custom adapter types and helpers: `Signaling`, `Discovery`, `SignalingSession`, `SignalingState`, `Signal`, `ManualSignaling`, `MqttSignalingOptions`, `isSignal`, `isUuid`, and `withLoopbackFallback` (adds a local `127.0.0.1` fallback for same-machine connections).
213
+
214
+ ## Connecting through strict firewalls (TURN)
215
+
216
+ - Most home, mobile, and same-computer connections work out of the box using Meshpost's built-in public STUN servers (`defaultIceServers`) and local-device fallback.
217
+ - Strict corporate firewalls and restrictive routers block direct connections. For those networks, add a TURN relay server (a server that forwards traffic when a direct link fails).
218
+ - Add your TURN credentials without replacing the default servers:
219
+
220
+ ```ts
221
+ const room = joinRoom('lobby', {
222
+ appId: 'my-app',
223
+ signaling: mqttSignaling(),
224
+ turnConfig: [{ urls: 'turns:turn.example.org:5349', username: 'user', credential: 'secret' }]
225
+ })
226
+ ```
227
+
228
+ ## Try the interactive playground
229
+
230
+ ### Option 1: Local dev server (recommended)
231
+
232
+ ```sh
233
+ npm ci
234
+ npm run demo:tabs
235
+ ```
236
+
237
+ Open the printed URL (for example `http://127.0.0.1:4173`) and click **Join room**. New rooms pre-fill a strong random password automatically.
238
+
239
+ - To join from another tab, click **Open another participant**.
240
+ - To join from **another browser** (such as Safari or Firefox) or another device, click **Copy invite link** and open that URL there (or enter the same room name and password).
241
+ - To test from another device on your LAN, run `HOST=0.0.0.0 npm run demo:tabs`.
242
+ - Stopping the server does not disconnect active peer-to-peer links.
243
+
244
+ ### Option 2: Standalone single HTML file (zero server)
245
+
246
+ ```sh
247
+ npm run demo
248
+ ```
249
+
250
+ Open **dist/playground.html** directly in two browsers (`file://`). Enter the same room name and click **Join room**.
251
+
252
+ - By default, `dist/playground.html` uses `mqttSignaling()` when opened via `file://` or hosted on a public `https://` origin (such as GitHub Pages).
253
+ - For completely offline copy-paste exchange with zero network requests, open `dist/playground.html#mode=manual` (or click **Offline mode** on the join screen).
254
+ - When hosted on `localhost` or a LAN host without the demo's local `/events` relay server, it automatically falls back to `tabSignaling()` (same-browser tabs only).
255
+
256
+ ### Read the example code
257
+
258
+ - [examples/playground/app.js](examples/playground/app.js) — Shows `joinRoom` (with auto-generated password and invite links), `createChannel('pointer')` (unreliable cursor and click ripples, ignoring out-of-order updates), `createChannel('draw')` (reliable collaborative canvas strokes, late-join snapshots, and clear actions), `createChannel('chat')` (group messages), `createChannel('direct')` (private messages to one peer), `createChannel('profile')` (display names without a server), `room.getStats()` (live ping and route tooltips), checking `SendResult`, and manual exchange.
259
+ - [examples/playground/relay.js](examples/playground/relay.js) — Shows how to write a custom `Signaling` adapter using Server-Sent Events with a fallback to `tabSignaling()`.
260
+ - [examples/playground/index.html](examples/playground/index.html) — Minimal HTML markup for the playground.
261
+ - [examples/turn-worker/](examples/turn-worker/README.md) — Ready-to-deploy Cloudflare Worker template that issues short-lived TURN credentials (supporting Metered Open Relay, Cloudflare Realtime TURN, and self-hosted `coturn`) behind an `Origin` allowlist and shared access key.
262
+
263
+ ## Project layout and tests
264
+
265
+ | Path | Purpose |
266
+ | ----------------------- | ------------------------------------------------------------------------------ |
267
+ | `src/` | Core room lifecycle, channels, and signaling adapters |
268
+ | `examples/playground/` | Interactive demo source |
269
+ | `examples/turn-worker/` | Optional Cloudflare Worker credential broker for Metered, CF TURN, or `coturn` |
270
+ | `examples/build.mjs` | Bundles the playground into one portable HTML file |
271
+ | `examples/serve.mjs` | Local dev server with a Server-Sent Events signaling relay |
272
+ | `tests/` | Playwright E2E tests using real browser WebRTC data channels |
273
+ | `dist/` | Built ES modules, `.d.ts` declarations, and `playground.html` |
274
+
275
+ Run the test suite:
276
+
277
+ ```sh
278
+ npm ci
279
+ npx playwright install chromium
280
+ npm test
281
+ ```
282
+
283
+ To use an already-installed Google Chrome instead of downloading Chromium, run `MESHPOST_CHROME_CHANNEL=chrome npm test`.
284
+
285
+ For full limits, wire protocol details, edge cases, and the security model, read [docs/behavior.md](docs/behavior.md).
286
+
287
+ ## Browser support
288
+
289
+ - Runs in modern browsers (Chrome, Firefox, Safari) with WebRTC `RTCDataChannel`, `WebSocket`, and `BroadcastChannel`. Meshpost is a browser library (not for Node.js).
290
+ - `mqttSignaling()` with `password` uses browser Web Crypto (`crypto.subtle`), which requires `https://` or `http://localhost` (`127.0.0.1`).
291
+
292
+ ## License
293
+
294
+ MIT — see [LICENSE](LICENSE).
@@ -0,0 +1,26 @@
1
+ import type { Delivery, Room, SendResult } from './room.js';
2
+ export interface ChannelOptions {
3
+ /** Delivery mode for this logical channel. @default 'unreliable' */
4
+ delivery?: Delivery;
5
+ }
6
+ export interface ChannelSendOptions {
7
+ /** Optional target peer ID. Omit to broadcast to all connected peers. */
8
+ to?: string;
9
+ }
10
+ /** Named logical message stream multiplexed over a Room's existing data channels. */
11
+ export interface Channel {
12
+ /** Logical channel name (1-64 UTF-8 bytes). */
13
+ readonly name: string;
14
+ /** Delivery mode configured for this channel. */
15
+ readonly delivery: Delivery;
16
+ /** Send a binary packet on this named channel synchronously. Returns a per-recipient result map. */
17
+ send(bytes: Uint8Array, options?: ChannelSendOptions): ReadonlyMap<string, SendResult>;
18
+ /** Subscribe to packets sent to this channel name. Returns an unsubscribe function. */
19
+ onPacket(fn: (from: string, bytes: Uint8Array) => void): () => void;
20
+ }
21
+ /**
22
+ * Create a named logical channel multiplexed over a Room's existing data channels.
23
+ * Adds a compact length-prefixed UTF-8 header (`[len, ...nameBytes, ...payload]`)
24
+ * without opening additional WebRTC RTCDataChannels.
25
+ */
26
+ export declare function createChannel(room: Room, name: string, options?: ChannelOptions): Channel;
@@ -0,0 +1,43 @@
1
+ const encoder = new TextEncoder();
2
+ const maxNameBytes = 64;
3
+ /**
4
+ * Create a named logical channel multiplexed over a Room's existing data channels.
5
+ * Adds a compact length-prefixed UTF-8 header (`[len, ...nameBytes, ...payload]`)
6
+ * without opening additional WebRTC RTCDataChannels.
7
+ */
8
+ export function createChannel(room, name, options = {}) {
9
+ if (typeof name !== 'string' || name.length === 0)
10
+ throw new TypeError('Invalid channel name');
11
+ const nameBytes = encoder.encode(name);
12
+ if (nameBytes.length === 0 || nameBytes.length > maxNameBytes)
13
+ throw new RangeError('Channel name must be 1-64 UTF-8 bytes');
14
+ const delivery = options.delivery ?? 'unreliable';
15
+ if (delivery !== 'unreliable' && delivery !== 'reliable')
16
+ throw new TypeError('Invalid delivery mode');
17
+ const prefix = new Uint8Array(1 + nameBytes.length);
18
+ prefix[0] = nameBytes.length;
19
+ prefix.set(nameBytes, 1);
20
+ return {
21
+ name,
22
+ delivery,
23
+ send(bytes, sendOptions = {}) {
24
+ if (!(bytes instanceof Uint8Array))
25
+ throw new TypeError('Expected a Uint8Array');
26
+ const framed = new Uint8Array(prefix.length + bytes.byteLength);
27
+ framed.set(prefix, 0);
28
+ framed.set(bytes, prefix.length);
29
+ return room.send(framed, sendOptions.to === undefined ? { delivery } : { to: sendOptions.to, delivery });
30
+ },
31
+ onPacket(fn) {
32
+ return room.onPacket((from, bytes, mode) => {
33
+ if (mode !== delivery || bytes.byteLength < prefix.length)
34
+ return;
35
+ for (let i = 0; i < prefix.length; i++) {
36
+ if (bytes[i] !== prefix[i])
37
+ return;
38
+ }
39
+ fn(from, bytes.subarray(prefix.length));
40
+ });
41
+ }
42
+ };
43
+ }
@@ -0,0 +1,11 @@
1
+ export { defaultIceServers, joinRoom } from './room.js';
2
+ export type { Delivery, PeerRoute, PeerStats, Room, RoomOptions, SendOptions, SendResult } from './room.js';
3
+ export { createChannel } from './channel.js';
4
+ export type { Channel, ChannelOptions, ChannelSendOptions } from './channel.js';
5
+ export { tabSignaling } from './tabs.js';
6
+ export { manualSignaling } from './manual.js';
7
+ export type { ManualSignaling } from './manual.js';
8
+ export { defaultMqttRelays, mqttSignaling } from './mqtt.js';
9
+ export type { MqttSignalingOptions } from './mqtt.js';
10
+ export { isSignal, isUuid, withLoopbackFallback } from './signaling.js';
11
+ export type { Discovery, Signal, Signaling, SignalingSession, SignalingState } from './signaling.js';
package/dist/index.js ADDED
@@ -0,0 +1,6 @@
1
+ export { defaultIceServers, joinRoom } from './room.js';
2
+ export { createChannel } from './channel.js';
3
+ export { tabSignaling } from './tabs.js';
4
+ export { manualSignaling } from './manual.js';
5
+ export { defaultMqttRelays, mqttSignaling } from './mqtt.js';
6
+ export { isSignal, isUuid, withLoopbackFallback } from './signaling.js';
@@ -0,0 +1,13 @@
1
+ import { type Signaling } from './signaling.js';
2
+ export interface ManualSignaling {
3
+ /** Pass this adapter into `joinRoom(name, { signaling: manual.signaling })`. */
4
+ readonly signaling: Signaling;
5
+ /** Return your contact card JSON to share with another peer. */
6
+ contact(): string;
7
+ /** Apply an incoming contact card or reply JSON from another peer. */
8
+ accept(text: string): void;
9
+ /** Stop requesting new attempts for this contact. Existing data channels stay open. */
10
+ forget(peerId: string): void;
11
+ }
12
+ /** One instance per room. Users carry the generated text between trusted browsers. */
13
+ export declare function manualSignaling(outgoing: (to: string, text: string) => void): ManualSignaling;
package/dist/manual.js ADDED
@@ -0,0 +1,109 @@
1
+ import { isSignal, isUuid, namespaceHash } from './signaling.js';
2
+ function authTag(d) {
3
+ return d.password !== undefined
4
+ ? namespaceHash(d.appId + ':' + d.room + ':' + d.password)
5
+ : undefined;
6
+ }
7
+ /** One instance per room. Users carry the generated text between trusted browsers. */
8
+ export function manualSignaling(outgoing) {
9
+ let active;
10
+ let suppressNeedFor;
11
+ const known = new Set();
12
+ const lastNeed = new Map();
13
+ const encode = (d, fields) => {
14
+ const auth = authTag(d);
15
+ return JSON.stringify({
16
+ v: 1,
17
+ app: d.appId,
18
+ room: d.room,
19
+ from: d.self,
20
+ ...(auth !== undefined ? { auth } : {}),
21
+ ...fields
22
+ });
23
+ };
24
+ const signaling = (d) => {
25
+ if (active)
26
+ throw new Error('Manual adapter already in use');
27
+ active = d;
28
+ queueMicrotask(() => {
29
+ if (active === d)
30
+ d.status('online');
31
+ });
32
+ return {
33
+ send(to, signal) {
34
+ if (active !== d)
35
+ return false;
36
+ const text = encode(d, { to, signal });
37
+ if (signal.kind === 'need') {
38
+ if (suppressNeedFor === to || lastNeed.get(to) === text)
39
+ return true;
40
+ lastNeed.set(to, text);
41
+ }
42
+ else {
43
+ lastNeed.delete(to);
44
+ }
45
+ outgoing(to, text);
46
+ return true;
47
+ },
48
+ close() {
49
+ if (active !== d)
50
+ return;
51
+ active = undefined;
52
+ suppressNeedFor = undefined;
53
+ known.clear();
54
+ lastNeed.clear();
55
+ }
56
+ };
57
+ };
58
+ return {
59
+ signaling,
60
+ contact() {
61
+ if (!active)
62
+ throw new Error('Join a room first');
63
+ return encode(active, {});
64
+ },
65
+ accept(text) {
66
+ const d = active;
67
+ if (!d)
68
+ throw new Error('Join a room first');
69
+ if (text.length > 128 * 1024)
70
+ throw new RangeError('Connection text is too large');
71
+ const msg = JSON.parse(text);
72
+ if (!msg ||
73
+ msg.v !== 1 ||
74
+ msg.app !== d.appId ||
75
+ msg.room !== d.room ||
76
+ msg.auth !== authTag(d) ||
77
+ !isUuid(msg.from) ||
78
+ msg.from === d.self)
79
+ throw new Error('Wrong room, app, password, or sender');
80
+ if (msg.signal !== undefined || msg.to !== undefined) {
81
+ if (msg.to !== d.self || !isSignal(msg.signal))
82
+ throw new Error('Invalid or misaddressed signal');
83
+ }
84
+ if (!known.has(msg.from)) {
85
+ known.add(msg.from);
86
+ if (msg.signal?.kind === 'offer') {
87
+ suppressNeedFor = msg.from;
88
+ try {
89
+ d.roster([...known]);
90
+ }
91
+ finally {
92
+ suppressNeedFor = undefined;
93
+ }
94
+ }
95
+ else {
96
+ d.roster([...known]);
97
+ }
98
+ }
99
+ if (msg.signal)
100
+ d.receive(msg.from, msg.signal);
101
+ },
102
+ /** Stop requesting new attempts for this contact. Existing data channels stay open. */
103
+ forget(peer) {
104
+ lastNeed.delete(peer);
105
+ if (known.delete(peer))
106
+ active?.roster([...known]);
107
+ }
108
+ };
109
+ }
package/dist/mqtt.d.ts ADDED
@@ -0,0 +1,20 @@
1
+ import { type Signaling } from './signaling.js';
2
+ /** Built-in public MQTT-over-WebSocket relay URLs used by default. */
3
+ export declare const defaultMqttRelays: readonly string[];
4
+ export interface MqttSignalingOptions {
5
+ /** MQTT-over-WebSocket broker URLs to connect to in parallel for redundancy. @default defaultMqttRelays */
6
+ urls?: readonly string[];
7
+ /** Application namespace mixed into the hashed room topic. */
8
+ appId?: string;
9
+ /** Optional shared password to encrypt signaling payloads with AES-256-GCM (requires secure context). */
10
+ password?: string;
11
+ /** Maximum time in milliseconds to wait for CONNECT -> CONNACK -> SUBACK per broker. @default 10000 */
12
+ handshakeTimeoutMs?: number;
13
+ }
14
+ /**
15
+ * Zero-backend signaling over public (or custom) MQTT-over-WebSocket brokers.
16
+ * Connects to multiple brokers in parallel for redundancy, splits presence and unicast topics,
17
+ * deduplicates multi-broker traffic, works even from `file://`, and optionally encrypts
18
+ * handshakes with AES-256-GCM (+ topic AAD and timestamp anti-replay) when `password` is provided.
19
+ */
20
+ export declare function mqttSignaling(options?: MqttSignalingOptions): Signaling;