@dimchansky/meshpost 0.3.0 → 0.4.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/README.md +266 -106
- package/dist/channel.d.ts +37 -2
- package/dist/channel.js +226 -12
- package/dist/crypto.d.ts +34 -0
- package/dist/crypto.js +158 -0
- package/dist/identity.d.ts +45 -0
- package/dist/identity.js +264 -0
- package/dist/index.d.ts +12 -4
- package/dist/index.js +5 -1
- package/dist/mqtt.d.ts +9 -1
- package/dist/mqtt.js +95 -87
- package/dist/nostr.d.ts +27 -0
- package/dist/nostr.js +1008 -0
- package/dist/room.d.ts +37 -13
- package/dist/room.js +584 -62
- package/dist/rpc.d.ts +48 -0
- package/dist/rpc.js +382 -0
- package/dist/signaling.d.ts +4 -8
- package/dist/signaling.js +10 -2
- package/dist/state.d.ts +56 -0
- package/dist/state.js +305 -0
- package/dist/voice.d.ts +28 -1
- package/dist/voice.js +349 -27
- package/dist/ws.d.ts +17 -2
- package/dist/ws.js +248 -33
- package/docs/behavior.md +93 -55
- package/package.json +67 -2
package/dist/state.js
ADDED
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
import { createChannel, isValidCodec, jsonCodec } from './channel.js';
|
|
2
|
+
import { isRoomClosed, onRoomClose } from './room.js';
|
|
3
|
+
const opSet = 0x01;
|
|
4
|
+
const opClear = 0x02;
|
|
5
|
+
const headerBytes = 5;
|
|
6
|
+
const maxPacketBytes = 16 * 1024;
|
|
7
|
+
const encoder = new TextEncoder();
|
|
8
|
+
function isNewerSeq(incoming, prev) {
|
|
9
|
+
if (prev === undefined)
|
|
10
|
+
return true;
|
|
11
|
+
if (incoming === prev)
|
|
12
|
+
return false;
|
|
13
|
+
return (incoming - prev) >>> 0 < 0x8000_0000;
|
|
14
|
+
}
|
|
15
|
+
function buildSetFrame(seq, payload) {
|
|
16
|
+
const frame = new Uint8Array(headerBytes + payload.byteLength);
|
|
17
|
+
frame[0] = opSet;
|
|
18
|
+
new DataView(frame.buffer).setUint32(1, seq >>> 0);
|
|
19
|
+
frame.set(payload, headerBytes);
|
|
20
|
+
return frame;
|
|
21
|
+
}
|
|
22
|
+
function buildClearFrame(seq) {
|
|
23
|
+
const frame = new Uint8Array(headerBytes);
|
|
24
|
+
frame[0] = opClear;
|
|
25
|
+
new DataView(frame.buffer).setUint32(1, seq >>> 0);
|
|
26
|
+
return frame;
|
|
27
|
+
}
|
|
28
|
+
function listeners() {
|
|
29
|
+
const entries = new Set();
|
|
30
|
+
let closed = false;
|
|
31
|
+
return {
|
|
32
|
+
add(fn, options) {
|
|
33
|
+
if (typeof fn !== 'function')
|
|
34
|
+
throw new TypeError('Expected a listener function');
|
|
35
|
+
const signal = options?.signal;
|
|
36
|
+
if (closed || signal?.aborted)
|
|
37
|
+
return () => { };
|
|
38
|
+
let removed = false;
|
|
39
|
+
const entry = {
|
|
40
|
+
fn,
|
|
41
|
+
once: Boolean(options?.once),
|
|
42
|
+
off() {
|
|
43
|
+
if (removed)
|
|
44
|
+
return;
|
|
45
|
+
removed = true;
|
|
46
|
+
entries.delete(entry);
|
|
47
|
+
signal?.removeEventListener('abort', entry.off);
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
entries.add(entry);
|
|
51
|
+
signal?.addEventListener('abort', entry.off, { once: true });
|
|
52
|
+
return entry.off;
|
|
53
|
+
},
|
|
54
|
+
fire(...args) {
|
|
55
|
+
for (const entry of [...entries]) {
|
|
56
|
+
if (!entries.has(entry))
|
|
57
|
+
continue;
|
|
58
|
+
if (entry.once)
|
|
59
|
+
entry.off();
|
|
60
|
+
try {
|
|
61
|
+
entry.fn(...args);
|
|
62
|
+
}
|
|
63
|
+
catch (error) {
|
|
64
|
+
globalThis.reportError?.(error);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
},
|
|
68
|
+
clear() {
|
|
69
|
+
closed = true;
|
|
70
|
+
for (const entry of [...entries])
|
|
71
|
+
entry.off();
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Create a single-writer per-peer state synchronization store over a named logical channel.
|
|
77
|
+
* Filters out-of-order updates via RFC 1982 `u32` sequence numbers, hydrates state reliably
|
|
78
|
+
* on `room.onPeerJoin`, cleans up on `room.onPeerLeave`, and optionally coalesces `'busy'` updates on `room.onDrain`.
|
|
79
|
+
*/
|
|
80
|
+
export function createPeerState(room, name, options = {}) {
|
|
81
|
+
if (!room ||
|
|
82
|
+
typeof room !== 'object' ||
|
|
83
|
+
typeof room.onPeerJoin !== 'function' ||
|
|
84
|
+
typeof room.onPeerLeave !== 'function' ||
|
|
85
|
+
typeof room.onDrain !== 'function' ||
|
|
86
|
+
!Array.isArray(room.peers)) {
|
|
87
|
+
throw new TypeError('Invalid room');
|
|
88
|
+
}
|
|
89
|
+
const delivery = options.delivery ?? 'reliable';
|
|
90
|
+
if (delivery !== 'unreliable' && delivery !== 'reliable') {
|
|
91
|
+
throw new TypeError('Invalid delivery mode');
|
|
92
|
+
}
|
|
93
|
+
const coalesce = options.coalesce ?? true;
|
|
94
|
+
if (typeof coalesce !== 'boolean') {
|
|
95
|
+
throw new TypeError('Invalid coalesce option');
|
|
96
|
+
}
|
|
97
|
+
const codec = options.codec !== undefined ? options.codec : jsonCodec();
|
|
98
|
+
if (!isValidCodec(codec))
|
|
99
|
+
throw new TypeError('Invalid codec');
|
|
100
|
+
const reliableChannel = createChannel(room, name, { delivery: 'reliable' });
|
|
101
|
+
const liveChannel = delivery === 'unreliable'
|
|
102
|
+
? createChannel(room, name, { delivery: 'unreliable' })
|
|
103
|
+
: reliableChannel;
|
|
104
|
+
const nameBytesLen = encoder.encode(name).length;
|
|
105
|
+
const maxPayloadBytes = maxPacketBytes - (1 + nameBytesLen) - headerBytes;
|
|
106
|
+
const encodeValidated = (value) => {
|
|
107
|
+
if (value === undefined) {
|
|
108
|
+
throw new TypeError('PeerState value cannot be undefined; call clear() instead');
|
|
109
|
+
}
|
|
110
|
+
const bytes = codec.encode(value);
|
|
111
|
+
if (!(bytes instanceof Uint8Array)) {
|
|
112
|
+
throw new TypeError('Codec encode() must return a Uint8Array');
|
|
113
|
+
}
|
|
114
|
+
if (bytes.byteLength > maxPayloadBytes) {
|
|
115
|
+
throw new RangeError('Encoded peer state exceeds 16 KiB packet limit');
|
|
116
|
+
}
|
|
117
|
+
return bytes;
|
|
118
|
+
};
|
|
119
|
+
let selfState;
|
|
120
|
+
let hasSelfState = false;
|
|
121
|
+
let localSeq = 0;
|
|
122
|
+
let currentFrame;
|
|
123
|
+
if (options.initial !== undefined) {
|
|
124
|
+
const initialBytes = encodeValidated(options.initial);
|
|
125
|
+
localSeq = (localSeq + 1) >>> 0;
|
|
126
|
+
selfState = options.initial;
|
|
127
|
+
hasSelfState = true;
|
|
128
|
+
currentFrame = buildSetFrame(localSeq, initialBytes);
|
|
129
|
+
}
|
|
130
|
+
const peersState = new Map();
|
|
131
|
+
const lastSeqByPeer = new Map();
|
|
132
|
+
const dirtyLive = new Set();
|
|
133
|
+
const dirtyReliable = new Set();
|
|
134
|
+
const changes = listeners();
|
|
135
|
+
let closed = isRoomClosed(room);
|
|
136
|
+
if (closed)
|
|
137
|
+
changes.clear();
|
|
138
|
+
const internalAbort = new AbortController();
|
|
139
|
+
const nextSeq = () => {
|
|
140
|
+
localSeq = (localSeq + 1) >>> 0;
|
|
141
|
+
return localSeq;
|
|
142
|
+
};
|
|
143
|
+
const recordReliableResults = (results) => {
|
|
144
|
+
if (!coalesce)
|
|
145
|
+
return;
|
|
146
|
+
for (const [peerId, status] of results) {
|
|
147
|
+
if (status === 'busy') {
|
|
148
|
+
dirtyReliable.add(peerId);
|
|
149
|
+
}
|
|
150
|
+
else {
|
|
151
|
+
dirtyReliable.delete(peerId);
|
|
152
|
+
dirtyLive.delete(peerId);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
};
|
|
156
|
+
const recordUnreliableResults = (results) => {
|
|
157
|
+
if (!coalesce)
|
|
158
|
+
return;
|
|
159
|
+
for (const [peerId, status] of results) {
|
|
160
|
+
if (status === 'busy') {
|
|
161
|
+
dirtyLive.add(peerId);
|
|
162
|
+
}
|
|
163
|
+
else {
|
|
164
|
+
dirtyLive.delete(peerId);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
};
|
|
168
|
+
const handleFrame = (from, bytes) => {
|
|
169
|
+
if (closed || bytes.byteLength < headerBytes || !room.peers.includes(from))
|
|
170
|
+
return;
|
|
171
|
+
const op = bytes[0];
|
|
172
|
+
const seq = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(1);
|
|
173
|
+
if (!isNewerSeq(seq, lastSeqByPeer.get(from)))
|
|
174
|
+
return;
|
|
175
|
+
if (op === opSet) {
|
|
176
|
+
let decoded;
|
|
177
|
+
try {
|
|
178
|
+
decoded = codec.decode(bytes.subarray(headerBytes));
|
|
179
|
+
}
|
|
180
|
+
catch {
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
if (decoded === undefined)
|
|
184
|
+
return;
|
|
185
|
+
lastSeqByPeer.set(from, seq);
|
|
186
|
+
const prev = peersState.get(from);
|
|
187
|
+
peersState.set(from, decoded);
|
|
188
|
+
changes.fire(from, decoded, prev);
|
|
189
|
+
}
|
|
190
|
+
else if (op === opClear) {
|
|
191
|
+
if (bytes.byteLength !== headerBytes)
|
|
192
|
+
return;
|
|
193
|
+
lastSeqByPeer.set(from, seq);
|
|
194
|
+
if (peersState.has(from)) {
|
|
195
|
+
const prev = peersState.get(from);
|
|
196
|
+
peersState.delete(from);
|
|
197
|
+
changes.fire(from, undefined, prev);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
};
|
|
201
|
+
const shutdown = () => {
|
|
202
|
+
if (closed)
|
|
203
|
+
return;
|
|
204
|
+
closed = true;
|
|
205
|
+
internalAbort.abort();
|
|
206
|
+
offRoomClose();
|
|
207
|
+
changes.clear();
|
|
208
|
+
peersState.clear();
|
|
209
|
+
lastSeqByPeer.clear();
|
|
210
|
+
dirtyLive.clear();
|
|
211
|
+
dirtyReliable.clear();
|
|
212
|
+
currentFrame = undefined;
|
|
213
|
+
};
|
|
214
|
+
const offRoomClose = closed ? () => { } : onRoomClose(room, shutdown);
|
|
215
|
+
if (!closed) {
|
|
216
|
+
const internalListen = { signal: internalAbort.signal };
|
|
217
|
+
reliableChannel.onPacket(handleFrame, internalListen);
|
|
218
|
+
if (liveChannel !== reliableChannel) {
|
|
219
|
+
liveChannel.onPacket(handleFrame, internalListen);
|
|
220
|
+
}
|
|
221
|
+
room.onPeerJoin((peerId) => {
|
|
222
|
+
lastSeqByPeer.delete(peerId);
|
|
223
|
+
if (hasSelfState && currentFrame) {
|
|
224
|
+
recordReliableResults(reliableChannel.send(currentFrame, { to: peerId }));
|
|
225
|
+
}
|
|
226
|
+
}, internalListen);
|
|
227
|
+
room.onPeerLeave((peerId) => {
|
|
228
|
+
lastSeqByPeer.delete(peerId);
|
|
229
|
+
dirtyLive.delete(peerId);
|
|
230
|
+
dirtyReliable.delete(peerId);
|
|
231
|
+
if (peersState.has(peerId)) {
|
|
232
|
+
const prev = peersState.get(peerId);
|
|
233
|
+
peersState.delete(peerId);
|
|
234
|
+
changes.fire(peerId, undefined, prev);
|
|
235
|
+
}
|
|
236
|
+
}, internalListen);
|
|
237
|
+
if (coalesce) {
|
|
238
|
+
room.onDrain((peerId, mode) => {
|
|
239
|
+
if (closed || !currentFrame || !room.peers.includes(peerId)) {
|
|
240
|
+
dirtyLive.delete(peerId);
|
|
241
|
+
dirtyReliable.delete(peerId);
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
if (mode === 'reliable' && dirtyReliable.has(peerId)) {
|
|
245
|
+
recordReliableResults(reliableChannel.send(currentFrame, { to: peerId }));
|
|
246
|
+
}
|
|
247
|
+
else if (mode === 'unreliable' &&
|
|
248
|
+
delivery === 'unreliable' &&
|
|
249
|
+
dirtyLive.has(peerId) &&
|
|
250
|
+
hasSelfState) {
|
|
251
|
+
recordUnreliableResults(liveChannel.send(currentFrame, { to: peerId }));
|
|
252
|
+
}
|
|
253
|
+
}, internalListen);
|
|
254
|
+
}
|
|
255
|
+
if (hasSelfState && currentFrame && room.peers.length > 0) {
|
|
256
|
+
recordReliableResults(reliableChannel.send(currentFrame));
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
return {
|
|
260
|
+
name: reliableChannel.name,
|
|
261
|
+
delivery,
|
|
262
|
+
getSelf() {
|
|
263
|
+
return selfState;
|
|
264
|
+
},
|
|
265
|
+
get(peerId) {
|
|
266
|
+
return peersState.get(peerId);
|
|
267
|
+
},
|
|
268
|
+
getAll() {
|
|
269
|
+
return new Map(peersState);
|
|
270
|
+
},
|
|
271
|
+
set(value) {
|
|
272
|
+
if (closed || isRoomClosed(room)) {
|
|
273
|
+
shutdown();
|
|
274
|
+
throw new Error('PeerState is closed');
|
|
275
|
+
}
|
|
276
|
+
const encoded = encodeValidated(value);
|
|
277
|
+
const seq = nextSeq();
|
|
278
|
+
selfState = value;
|
|
279
|
+
hasSelfState = true;
|
|
280
|
+
currentFrame = buildSetFrame(seq, encoded);
|
|
281
|
+
const results = liveChannel.send(currentFrame);
|
|
282
|
+
if (delivery === 'reliable')
|
|
283
|
+
recordReliableResults(results);
|
|
284
|
+
else
|
|
285
|
+
recordUnreliableResults(results);
|
|
286
|
+
return results;
|
|
287
|
+
},
|
|
288
|
+
clear() {
|
|
289
|
+
if (closed || isRoomClosed(room)) {
|
|
290
|
+
shutdown();
|
|
291
|
+
throw new Error('PeerState is closed');
|
|
292
|
+
}
|
|
293
|
+
const seq = nextSeq();
|
|
294
|
+
selfState = undefined;
|
|
295
|
+
hasSelfState = false;
|
|
296
|
+
currentFrame = buildClearFrame(seq);
|
|
297
|
+
dirtyLive.clear();
|
|
298
|
+
const results = reliableChannel.send(currentFrame);
|
|
299
|
+
recordReliableResults(results);
|
|
300
|
+
return results;
|
|
301
|
+
},
|
|
302
|
+
onChange: changes.add,
|
|
303
|
+
close: shutdown
|
|
304
|
+
};
|
|
305
|
+
}
|
package/dist/voice.d.ts
CHANGED
|
@@ -12,12 +12,14 @@ export interface MicError {
|
|
|
12
12
|
export interface VoiceSnapshot {
|
|
13
13
|
readonly micStatus: MicStatus;
|
|
14
14
|
readonly micError: MicError | null;
|
|
15
|
+
readonly deviceId: string | null;
|
|
15
16
|
readonly autoplayBlocked: boolean;
|
|
16
17
|
readonly deafened: boolean;
|
|
17
18
|
readonly volume: number;
|
|
18
19
|
readonly selfSpeaking: boolean;
|
|
19
20
|
readonly remotePeers: readonly string[];
|
|
20
21
|
readonly speakingPeers: readonly string[];
|
|
22
|
+
readonly mutedPeers: readonly string[];
|
|
21
23
|
}
|
|
22
24
|
/** Configuration options for `createVoice()`. */
|
|
23
25
|
export interface VoiceOptions {
|
|
@@ -38,8 +40,20 @@ export interface VoiceOptions {
|
|
|
38
40
|
speakingThreshold?: number;
|
|
39
41
|
/** Polling interval in milliseconds (`50` to `60000`) for speaking detection. @default 180 */
|
|
40
42
|
speakingIntervalMs?: number;
|
|
41
|
-
/** Optional target peer ID scoping outgoing microphone audio only (`room.addStream(stream, to)`). Incoming audio from all peers still plays. */
|
|
43
|
+
/** Optional target peer ID scoping outgoing microphone audio only (`room.addStream(stream, { to })`). Incoming audio from all peers still plays. */
|
|
42
44
|
to?: string;
|
|
45
|
+
/**
|
|
46
|
+
* Stream tag attached to outgoing microphone streams and matched on incoming streams.
|
|
47
|
+
* Incoming audio streams whose `meta.tag` equals `streamTag` (or is `undefined` when
|
|
48
|
+
* `strictStreamTag` is `false`) are played; streams tagged with another value (e.g. `'screen'`) are ignored.
|
|
49
|
+
* @default 'voice'
|
|
50
|
+
*/
|
|
51
|
+
streamTag?: string;
|
|
52
|
+
/**
|
|
53
|
+
* When `true`, ignore untagged (`meta.tag === undefined`) incoming audio streams as well.
|
|
54
|
+
* @default false
|
|
55
|
+
*/
|
|
56
|
+
strictStreamTag?: boolean;
|
|
43
57
|
}
|
|
44
58
|
/** Headless P2P voice chat controller built on top of a `Room`. */
|
|
45
59
|
export interface Voice extends VoiceSnapshot {
|
|
@@ -60,10 +74,23 @@ export interface Voice extends VoiceSnapshot {
|
|
|
60
74
|
setMuted(muted: boolean): void;
|
|
61
75
|
/** Detach local stream from the room (`room.removeStream`), cancel any in-flight `getUserMedia`, and stop hardware microphone tracks (`track.stop()`). */
|
|
62
76
|
stopMic(): void;
|
|
77
|
+
/**
|
|
78
|
+
* Select or hot-swap the local microphone input device (`deviceId`, or `null`/`undefined`/`''` for system default).
|
|
79
|
+
* When `'live'` or `'muted'`, swaps the active track via `room.replaceStreamTrack()` without SDP renegotiation.
|
|
80
|
+
*/
|
|
81
|
+
switchDevice(deviceId?: string | null): Promise<MicStatus>;
|
|
63
82
|
/** Set playback volume (`0` to `1`, clamped) on all current and future remote `<audio>` elements. */
|
|
64
83
|
setVolume(volume: number): void;
|
|
84
|
+
/** Set local playback volume (`0` to `1`, clamped, scaled by master `voice.volume`) for a specific peer. */
|
|
85
|
+
setPeerVolume(peerId: string, volume: number): void;
|
|
86
|
+
/** Read local playback volume (`0` to `1`, default `1`) configured for a specific peer. */
|
|
87
|
+
getPeerVolume(peerId: string): number;
|
|
65
88
|
/** Mute (`true`) or unmute (`false`) all incoming remote `<audio>` elements locally. Unmuting also triggers `unlockAudio()`. */
|
|
66
89
|
setDeafened(deafened: boolean): void;
|
|
90
|
+
/** Locally mute (`true`) or unmute (`false`) incoming audio from a specific peer (independent of `deafened`). */
|
|
91
|
+
setPeerMuted(peerId: string, muted: boolean): void;
|
|
92
|
+
/** Check whether a specific peer is locally muted via `setPeerMuted()`. */
|
|
93
|
+
isPeerMuted(peerId: string): boolean;
|
|
67
94
|
/** Manually trigger synchronous `AudioContext.resume()` + `audio.play()` retry. */
|
|
68
95
|
unlockAudio(): void;
|
|
69
96
|
/** Subscribe to any state change in `VoiceSnapshot`. Supports `ListenOptions` (`{ once, signal }`). */
|