@dimchansky/meshpost 0.5.0 → 0.7.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.
Files changed (49) hide show
  1. package/README.md +66 -544
  2. package/dist/bip340.d.ts +1 -0
  3. package/dist/bip340.js +346 -0
  4. package/dist/blob.d.ts +1 -1
  5. package/dist/blob.js +44 -45
  6. package/dist/channel.d.ts +4 -0
  7. package/dist/channel.js +19 -44
  8. package/dist/combine.d.ts +9 -2
  9. package/dist/combine.js +40 -57
  10. package/dist/crypto.js +10 -9
  11. package/dist/identity.d.ts +2 -0
  12. package/dist/identity.js +39 -71
  13. package/dist/index.d.ts +3 -2
  14. package/dist/index.js +1 -1
  15. package/dist/listeners.js +18 -3
  16. package/dist/mqtt.js +211 -476
  17. package/dist/nostr.js +194 -836
  18. package/dist/peer-link.d.ts +1 -0
  19. package/dist/peer-link.js +983 -0
  20. package/dist/presence.d.ts +1 -0
  21. package/dist/presence.js +74 -0
  22. package/dist/public.d.ts +1 -1
  23. package/dist/public.js +25 -77
  24. package/dist/relay-core.d.ts +1 -0
  25. package/dist/relay-core.js +399 -0
  26. package/dist/room-reclaim.d.ts +1 -0
  27. package/dist/room-reclaim.js +115 -0
  28. package/dist/room-stats.d.ts +1 -0
  29. package/dist/room-stats.js +75 -0
  30. package/dist/room.js +245 -1218
  31. package/dist/rpc.js +25 -28
  32. package/dist/signaling.d.ts +8 -0
  33. package/dist/signaling.js +55 -0
  34. package/dist/state.js +23 -33
  35. package/dist/tabs.js +6 -50
  36. package/dist/voice-mic.d.ts +1 -0
  37. package/dist/voice-mic.js +496 -0
  38. package/dist/voice-remote.d.ts +1 -0
  39. package/dist/voice-remote.js +568 -0
  40. package/dist/voice.d.ts +19 -1
  41. package/dist/voice.js +95 -1036
  42. package/dist/ws.js +56 -197
  43. package/docs/adr/0001-room-internals-and-channel-budget.md +31 -0
  44. package/docs/api.md +219 -0
  45. package/docs/behavior.md +14 -8
  46. package/docs/guide.md +404 -0
  47. package/docs/signaling-and-production.md +312 -0
  48. package/docs/voice-and-media.md +193 -0
  49. package/package.json +6 -3
package/dist/rpc.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { createChannel, isValidCodec, jsonCodec } from './channel.js';
2
2
  import { bindAbort } from './listeners.js';
3
- import { isRoomClosed, onRoomClose } from './room.js';
3
+ import { bindRoomLifecycle, isRoomClosed } from './room.js';
4
4
  /** Error rejected by `rpc.call()` with a structured `code` and target `peerId`. */
5
5
  export class RpcError extends Error {
6
6
  code;
@@ -117,8 +117,6 @@ export function createRpc(room, name, options = {}) {
117
117
  const inFlightByPeer = new Map();
118
118
  let activeHandler;
119
119
  let nextReqId = (Math.random() * 0xffff_ffff) >>> 0;
120
- let closed = isRoomClosed(room);
121
- const internalAbort = new AbortController();
122
120
  const allocateReqId = () => {
123
121
  for (let i = 0; i <= maxPendingCalls; i++) {
124
122
  nextReqId = (nextReqId + 1) >>> 0;
@@ -129,16 +127,6 @@ export function createRpc(room, name, options = {}) {
129
127
  }
130
128
  return 1;
131
129
  };
132
- const sendErrorBestEffort = (to, reqId, errKind, message) => {
133
- if (closed || isRoomClosed(room))
134
- return;
135
- try {
136
- channel.send(buildErrorFrame(reqId, errKind, message), { to });
137
- }
138
- catch {
139
- // Room closed concurrently; ignore.
140
- }
141
- };
142
130
  const settlePending = (reqId, fn) => {
143
131
  const entry = pending.get(reqId);
144
132
  if (!entry)
@@ -147,12 +135,7 @@ export function createRpc(room, name, options = {}) {
147
135
  entry.cleanup();
148
136
  fn(entry);
149
137
  };
150
- const shutdown = () => {
151
- if (closed)
152
- return;
153
- closed = true;
154
- internalAbort.abort();
155
- offRoomClose();
138
+ const lifecycle = bindRoomLifecycle(room, () => {
156
139
  if (activeHandler) {
157
140
  const h = activeHandler;
158
141
  activeHandler = undefined;
@@ -163,11 +146,24 @@ export function createRpc(room, name, options = {}) {
163
146
  entry.reject(new RpcError('closed', entry.peerId, 'RPC endpoint is closed'));
164
147
  });
165
148
  }
149
+ });
150
+ const sendErrorBestEffort = (to, reqId, errKind, message) => {
151
+ if (lifecycle.isClosed() || isRoomClosed(room))
152
+ return;
153
+ try {
154
+ channel.send(buildErrorFrame(reqId, errKind, message), { to });
155
+ }
156
+ catch {
157
+ // Room closed concurrently; ignore.
158
+ }
166
159
  };
167
- const offRoomClose = closed ? () => { } : onRoomClose(room, shutdown);
168
- if (!closed) {
169
- const internalListen = { signal: internalAbort.signal };
160
+ if (!lifecycle.isClosed()) {
161
+ const internalListen = { signal: lifecycle.signal };
170
162
  room.onPeerLeave((peerId) => {
163
+ if (isRoomClosed(room)) {
164
+ lifecycle.close();
165
+ return;
166
+ }
171
167
  for (const [reqId, entry] of [...pending]) {
172
168
  if (entry.peerId === peerId) {
173
169
  settlePending(reqId, (item) => {
@@ -177,7 +173,7 @@ export function createRpc(room, name, options = {}) {
177
173
  }
178
174
  }, internalListen);
179
175
  channel.onPacket((from, bytes) => {
180
- if (closed || bytes.byteLength < headerBytes)
176
+ if (lifecycle.isClosed() || bytes.byteLength < headerBytes)
181
177
  return;
182
178
  const opcode = bytes[0];
183
179
  const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
@@ -209,7 +205,7 @@ export function createRpc(room, name, options = {}) {
209
205
  void (async () => {
210
206
  try {
211
207
  const result = await handler.fn(from, decodedReq);
212
- if (closed || isRoomClosed(room) || !room.peers.includes(from))
208
+ if (lifecycle.isClosed() || isRoomClosed(room) || !room.peers.includes(from))
213
209
  return;
214
210
  let encodedRes;
215
211
  try {
@@ -230,7 +226,7 @@ export function createRpc(room, name, options = {}) {
230
226
  }
231
227
  }
232
228
  catch (error) {
233
- if (closed || isRoomClosed(room) || !room.peers.includes(from))
229
+ if (lifecycle.isClosed() || isRoomClosed(room) || !room.peers.includes(from))
234
230
  return;
235
231
  const rawMsg = error instanceof Error && error.message ? error.message : 'Remote RPC handler failed';
236
232
  sendErrorBestEffort(from, reqId, errRemote, rawMsg);
@@ -282,7 +278,8 @@ export function createRpc(room, name, options = {}) {
282
278
  if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > maxTimeoutMs) {
283
279
  return Promise.reject(new RangeError('Invalid RPC timeoutMs'));
284
280
  }
285
- if (closed || isRoomClosed(room)) {
281
+ if (lifecycle.isClosed() || isRoomClosed(room)) {
282
+ lifecycle.close();
286
283
  return Promise.reject(new RpcError('closed', peerId, 'RPC endpoint is closed'));
287
284
  }
288
285
  const signal = callOptions.signal;
@@ -357,7 +354,7 @@ export function createRpc(room, name, options = {}) {
357
354
  if (typeof fn !== 'function')
358
355
  throw new TypeError('Expected an RPC handler function');
359
356
  const signal = listenOptions?.signal;
360
- if (closed || isRoomClosed(room) || signal?.aborted)
357
+ if (lifecycle.isClosed() || isRoomClosed(room) || signal?.aborted)
361
358
  return () => { };
362
359
  if (activeHandler) {
363
360
  throw new Error(`RPC handler already registered for channel "${channel.name}"`);
@@ -380,6 +377,6 @@ export function createRpc(room, name, options = {}) {
380
377
  unbindAbort = bindAbort(signal, entry.off);
381
378
  return entry.off;
382
379
  },
383
- close: shutdown
380
+ close: lifecycle.close
384
381
  };
385
382
  }
@@ -69,3 +69,11 @@ export declare function isSignal(value: unknown): value is Signal;
69
69
  * Preserve the original candidate and its priority. Never transmit this local hint.
70
70
  */
71
71
  export declare function withLoopbackFallback<T extends Signal>(signal: T): T;
72
+ /**
73
+ * Decorate any `Signaling` adapter to observe per-session `SignalingState` transitions
74
+ * (`'connecting'`, `'online'`, `'offline'`, `'closed'`) without altering `Room` or `Discovery`.
75
+ *
76
+ * - Deduplicates repeated consecutive states and isolates callback errors via `reportError`.
77
+ * - Preserves `trickle` and `canReach` on the underlying `SignalingSession`.
78
+ */
79
+ export declare function observeSignaling(adapter: Signaling, onChange: (state: SignalingState, reason?: string) => void): Signaling;
package/dist/signaling.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { reportAsyncError } from './listeners.js';
1
2
  /** @internal */
2
3
  export const uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
3
4
  /** @internal */
@@ -124,3 +125,57 @@ export function withLoopbackFallback(signal) {
124
125
  }
125
126
  return index ? { ...signal, sdp: lines.join(eol) } : signal;
126
127
  }
128
+ /**
129
+ * Decorate any `Signaling` adapter to observe per-session `SignalingState` transitions
130
+ * (`'connecting'`, `'online'`, `'offline'`, `'closed'`) without altering `Room` or `Discovery`.
131
+ *
132
+ * - Deduplicates repeated consecutive states and isolates callback errors via `reportError`.
133
+ * - Preserves `trickle` and `canReach` on the underlying `SignalingSession`.
134
+ */
135
+ export function observeSignaling(adapter, onChange) {
136
+ if (typeof adapter !== 'function') {
137
+ throw new TypeError('Expected a signaling adapter function');
138
+ }
139
+ if (typeof onChange !== 'function') {
140
+ throw new TypeError('Expected an onChange callback function');
141
+ }
142
+ return (discovery) => {
143
+ let lastState;
144
+ let closed = false;
145
+ const emit = (state, reason) => {
146
+ if (state === lastState)
147
+ return;
148
+ lastState = state;
149
+ try {
150
+ onChange(state, reason);
151
+ }
152
+ catch (error) {
153
+ reportAsyncError(error);
154
+ }
155
+ };
156
+ const session = adapter({
157
+ ...discovery,
158
+ status(state, reason) {
159
+ if (closed)
160
+ return;
161
+ emit(state, reason);
162
+ discovery.status(state, reason);
163
+ }
164
+ });
165
+ if (!closed && lastState === undefined) {
166
+ emit('connecting');
167
+ }
168
+ return {
169
+ ...(session.trickle !== undefined ? { trickle: session.trickle } : {}),
170
+ ...(session.canReach ? { canReach: (peerId) => session.canReach(peerId) } : {}),
171
+ send: (to, signal) => session.send(to, signal),
172
+ close() {
173
+ if (closed)
174
+ return;
175
+ closed = true;
176
+ session.close();
177
+ emit('closed');
178
+ }
179
+ };
180
+ };
181
+ }
package/dist/state.js CHANGED
@@ -1,11 +1,9 @@
1
1
  import { createChannel, isValidCodec, jsonCodec } from './channel.js';
2
2
  import { createListeners } from './listeners.js';
3
- import { isRoomClosed, onRoomClose } from './room.js';
3
+ import { bindRoomLifecycle, isRoomClosed } from './room.js';
4
4
  const opSet = 0x01;
5
5
  const opClear = 0x02;
6
6
  const headerBytes = 5;
7
- const maxPacketBytes = 16 * 1024;
8
- const encoder = new TextEncoder();
9
7
  function isNewerSeq(incoming, prev) {
10
8
  if (prev === undefined)
11
9
  return true;
@@ -26,7 +24,6 @@ function buildClearFrame(seq) {
26
24
  new DataView(frame.buffer).setUint32(1, seq >>> 0);
27
25
  return frame;
28
26
  }
29
- const listeners = createListeners;
30
27
  /**
31
28
  * Create a single-writer per-peer state synchronization store over a named logical channel.
32
29
  * Filters out-of-order updates via RFC 1982 `u32` sequence numbers, hydrates state reliably
@@ -56,8 +53,7 @@ export function createPeerState(room, name, options = {}) {
56
53
  const liveChannel = delivery === 'unreliable'
57
54
  ? createChannel(room, name, { delivery: 'unreliable' })
58
55
  : reliableChannel;
59
- const nameBytesLen = encoder.encode(name).length;
60
- const maxPayloadBytes = maxPacketBytes - (1 + nameBytesLen) - headerBytes;
56
+ const maxPayloadBytes = reliableChannel.maxPayloadBytes - headerBytes;
61
57
  const encodeValidated = (value) => {
62
58
  if (value === undefined) {
63
59
  throw new TypeError('PeerState value cannot be undefined; call clear() instead');
@@ -86,11 +82,15 @@ export function createPeerState(room, name, options = {}) {
86
82
  const lastSeqByPeer = new Map();
87
83
  const dirtyLive = new Set();
88
84
  const dirtyReliable = new Set();
89
- const changes = listeners();
90
- let closed = isRoomClosed(room);
91
- if (closed)
85
+ const changes = createListeners();
86
+ const lifecycle = bindRoomLifecycle(room, () => {
92
87
  changes.clear();
93
- const internalAbort = new AbortController();
88
+ peersState.clear();
89
+ lastSeqByPeer.clear();
90
+ dirtyLive.clear();
91
+ dirtyReliable.clear();
92
+ currentFrame = undefined;
93
+ });
94
94
  const nextSeq = () => {
95
95
  localSeq = (localSeq + 1) >>> 0;
96
96
  return localSeq;
@@ -121,7 +121,7 @@ export function createPeerState(room, name, options = {}) {
121
121
  }
122
122
  };
123
123
  const handleFrame = (from, bytes) => {
124
- if (closed || bytes.byteLength < headerBytes || !room.peers.includes(from))
124
+ if (lifecycle.isClosed() || bytes.byteLength < headerBytes || !room.peers.includes(from))
125
125
  return;
126
126
  const op = bytes[0];
127
127
  const seq = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(1);
@@ -153,22 +153,8 @@ export function createPeerState(room, name, options = {}) {
153
153
  }
154
154
  }
155
155
  };
156
- const shutdown = () => {
157
- if (closed)
158
- return;
159
- closed = true;
160
- internalAbort.abort();
161
- offRoomClose();
162
- changes.clear();
163
- peersState.clear();
164
- lastSeqByPeer.clear();
165
- dirtyLive.clear();
166
- dirtyReliable.clear();
167
- currentFrame = undefined;
168
- };
169
- const offRoomClose = closed ? () => { } : onRoomClose(room, shutdown);
170
- if (!closed) {
171
- const internalListen = { signal: internalAbort.signal };
156
+ if (!lifecycle.isClosed()) {
157
+ const internalListen = { signal: lifecycle.signal };
172
158
  reliableChannel.onPacket(handleFrame, internalListen);
173
159
  if (liveChannel !== reliableChannel) {
174
160
  liveChannel.onPacket(handleFrame, internalListen);
@@ -180,6 +166,10 @@ export function createPeerState(room, name, options = {}) {
180
166
  }
181
167
  }, internalListen);
182
168
  room.onPeerLeave((peerId) => {
169
+ if (isRoomClosed(room)) {
170
+ lifecycle.close();
171
+ return;
172
+ }
183
173
  lastSeqByPeer.delete(peerId);
184
174
  dirtyLive.delete(peerId);
185
175
  dirtyReliable.delete(peerId);
@@ -191,7 +181,7 @@ export function createPeerState(room, name, options = {}) {
191
181
  }, internalListen);
192
182
  if (coalesce) {
193
183
  room.onDrain((peerId, mode) => {
194
- if (closed || !currentFrame || !room.peers.includes(peerId)) {
184
+ if (lifecycle.isClosed() || !currentFrame || !room.peers.includes(peerId)) {
195
185
  dirtyLive.delete(peerId);
196
186
  dirtyReliable.delete(peerId);
197
187
  return;
@@ -224,8 +214,8 @@ export function createPeerState(room, name, options = {}) {
224
214
  return new Map(peersState);
225
215
  },
226
216
  set(value) {
227
- if (closed || isRoomClosed(room)) {
228
- shutdown();
217
+ if (lifecycle.isClosed() || isRoomClosed(room)) {
218
+ lifecycle.close();
229
219
  throw new Error('PeerState is closed');
230
220
  }
231
221
  const encoded = encodeValidated(value);
@@ -241,8 +231,8 @@ export function createPeerState(room, name, options = {}) {
241
231
  return results;
242
232
  },
243
233
  clear() {
244
- if (closed || isRoomClosed(room)) {
245
- shutdown();
234
+ if (lifecycle.isClosed() || isRoomClosed(room)) {
235
+ lifecycle.close();
246
236
  throw new Error('PeerState is closed');
247
237
  }
248
238
  const seq = nextSeq();
@@ -255,6 +245,6 @@ export function createPeerState(room, name, options = {}) {
255
245
  return results;
256
246
  },
257
247
  onChange: changes.add,
258
- close: shutdown
248
+ close: lifecycle.close
259
249
  };
260
250
  }
package/dist/tabs.js CHANGED
@@ -1,5 +1,5 @@
1
- import { isSignal, isUuid, namespaceHash } from './signaling.js';
2
- const maxSeenPeers = 256;
1
+ import { createPresenceTracker } from './presence.js';
2
+ import { isUuid, namespaceHash } from './signaling.js';
3
3
  /** Discover tabs in the same origin and storage partition. Carries signaling only. */
4
4
  export function tabSignaling() {
5
5
  return (discovery) => {
@@ -8,7 +8,6 @@ export function tabSignaling() {
8
8
  discovery.room +
9
9
  (discovery.password !== undefined ? ':' + discovery.password : '');
10
10
  const channel = new BroadcastChannel('meshpost/1/' + namespaceHash(scope));
11
- const seen = new Map();
12
11
  let closed = false;
13
12
  const post = (body) => {
14
13
  try {
@@ -18,62 +17,19 @@ export function tabSignaling() {
18
17
  // Ignore asynchronous partition or bfcache restrictions.
19
18
  }
20
19
  };
21
- const roster = () => discovery.roster([...seen.keys()]);
22
- const touch = (id) => {
23
- const known = seen.has(id);
24
- if (!known && seen.size >= maxSeenPeers) {
25
- const oldest = seen.keys().next().value;
26
- if (oldest !== undefined)
27
- seen.delete(oldest);
28
- }
29
- seen.delete(id);
30
- seen.set(id, Date.now());
31
- if (!known)
32
- roster();
33
- return known;
34
- };
20
+ const presence = createPresenceTracker(discovery, (to) => post({ type: 'present', to }));
35
21
  channel.onmessage = ({ data }) => {
36
22
  if (closed || !data || !isUuid(data.from) || data.from === discovery.self)
37
23
  return;
38
24
  if (data.to !== undefined && data.to !== discovery.self)
39
25
  return;
40
- switch (data.type) {
41
- case 'hello':
42
- touch(data.from);
43
- post({ type: 'present', to: data.from });
44
- break;
45
- case 'heartbeat':
46
- if (!touch(data.from))
47
- post({ type: 'present', to: data.from });
48
- break;
49
- case 'present':
50
- touch(data.from);
51
- break;
52
- case 'bye':
53
- if (seen.delete(data.from))
54
- roster();
55
- break;
56
- case 'signal':
57
- if (isSignal(data.signal)) {
58
- touch(data.from);
59
- discovery.receive(data.from, data.signal);
60
- }
61
- break;
62
- }
26
+ presence.dispatch(data);
63
27
  };
64
28
  const timer = setInterval(() => {
65
- let changed = false;
66
- for (const [id, last] of seen) {
67
- if (Date.now() - last > 30_000) {
68
- seen.delete(id);
69
- changed = true;
70
- }
71
- }
72
- if (changed)
73
- roster();
29
+ presence.prune();
74
30
  if (!closed)
75
31
  post({ type: 'heartbeat' });
76
- }, 5000);
32
+ }, 5_000);
77
33
  queueMicrotask(() => {
78
34
  if (closed)
79
35
  return;
@@ -0,0 +1 @@
1
+ export {};