@dimchansky/meshpost 0.4.1 → 0.5.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/dist/identity.js CHANGED
@@ -262,3 +262,195 @@ export async function sha256Base64Url(input) {
262
262
  return null;
263
263
  }
264
264
  }
265
+ const maxStoredIdentityChars = 1024;
266
+ function isValidIdentityStorage(value) {
267
+ return (Boolean(value) &&
268
+ typeof value === 'object' &&
269
+ typeof value.getItem === 'function' &&
270
+ typeof value.setItem === 'function' &&
271
+ typeof value.removeItem === 'function');
272
+ }
273
+ /**
274
+ * Create a race-safe persistent `PeerIdentity` store backed by `localStorage` (by default) or a custom `IdentityStorage`.
275
+ *
276
+ * - Coalesces concurrent `load()` calls and uses a monotonic `epoch` guard so `rotate()` or `clear()`
277
+ * cannot be overwritten by an earlier in-flight operation.
278
+ * - Caps stored JSON reads at `1,024` chars, cryptographically verifies imported keys, and silently
279
+ * regenerates corrupt entries (preserving stored entries untouched if `crypto.subtle` is unavailable).
280
+ * - Degrades cleanly to in-memory caching when `localStorage` throws `SecurityError` or is unavailable.
281
+ */
282
+ export function createIdentityStore(options) {
283
+ if (!options || typeof options !== 'object' || Array.isArray(options)) {
284
+ throw new TypeError('Invalid identity store options');
285
+ }
286
+ const { key, storage: customStorage } = options;
287
+ if (typeof key !== 'string' || key.length === 0 || key.length > 256) {
288
+ throw new TypeError('Expected identity store key to be a non-empty string (1..256 chars)');
289
+ }
290
+ if (customStorage !== undefined &&
291
+ customStorage !== null &&
292
+ !isValidIdentityStorage(customStorage)) {
293
+ throw new TypeError('Invalid identity storage backend');
294
+ }
295
+ let cached = null;
296
+ let inFlightLoad = null;
297
+ let inFlightRotate = null;
298
+ let epoch = 0;
299
+ const resolveStorage = () => {
300
+ if (customStorage === null)
301
+ return null;
302
+ if (customStorage !== undefined)
303
+ return customStorage;
304
+ try {
305
+ const candidate = globalThis.localStorage;
306
+ return isValidIdentityStorage(candidate) ? candidate : null;
307
+ }
308
+ catch {
309
+ return null;
310
+ }
311
+ };
312
+ const safeRead = (storage) => {
313
+ if (!storage)
314
+ return null;
315
+ try {
316
+ const raw = storage.getItem(key);
317
+ return typeof raw === 'string' ? raw : null;
318
+ }
319
+ catch {
320
+ return null;
321
+ }
322
+ };
323
+ const safeWrite = (storage, serialized) => {
324
+ if (!storage)
325
+ return;
326
+ try {
327
+ storage.setItem(key, JSON.stringify(serialized));
328
+ }
329
+ catch {
330
+ // Ignore quota or restricted-storage errors; keep identity cached in memory.
331
+ }
332
+ };
333
+ const safeRemove = (storage) => {
334
+ if (!storage)
335
+ return;
336
+ try {
337
+ storage.removeItem(key);
338
+ }
339
+ catch {
340
+ // Ignore restricted-storage errors.
341
+ }
342
+ };
343
+ return {
344
+ load() {
345
+ if (cached)
346
+ return Promise.resolve(cached);
347
+ if (inFlightRotate)
348
+ return inFlightRotate;
349
+ if (inFlightLoad)
350
+ return inFlightLoad;
351
+ const myEpoch = epoch;
352
+ const promise = (async () => {
353
+ // Verify WebCrypto availability before touching storage so non-secure contexts
354
+ // never misclassify a missing SubtleCrypto error as corrupt storage and delete the key.
355
+ requireSubtleCrypto();
356
+ const storage = resolveStorage();
357
+ const raw = safeRead(storage);
358
+ if (raw !== null) {
359
+ let loaded = null;
360
+ if (raw.length > 0 && raw.length <= maxStoredIdentityChars) {
361
+ try {
362
+ const parsed = JSON.parse(raw);
363
+ if (isSerializedIdentity(parsed)) {
364
+ loaded = await importIdentity(parsed);
365
+ }
366
+ }
367
+ catch {
368
+ loaded = null;
369
+ }
370
+ }
371
+ if (myEpoch !== epoch) {
372
+ if (cached)
373
+ return cached;
374
+ if (inFlightRotate)
375
+ return inFlightRotate;
376
+ return loaded ?? createIdentity();
377
+ }
378
+ if (loaded) {
379
+ cached = loaded;
380
+ return loaded;
381
+ }
382
+ safeRemove(storage);
383
+ }
384
+ const fresh = await createIdentity();
385
+ if (myEpoch !== epoch) {
386
+ if (cached)
387
+ return cached;
388
+ if (inFlightRotate)
389
+ return inFlightRotate;
390
+ return fresh;
391
+ }
392
+ if (storage) {
393
+ const exported = await exportIdentity(fresh);
394
+ if (myEpoch !== epoch) {
395
+ if (cached)
396
+ return cached;
397
+ if (inFlightRotate)
398
+ return inFlightRotate;
399
+ return fresh;
400
+ }
401
+ safeWrite(storage, exported);
402
+ }
403
+ cached = fresh;
404
+ return fresh;
405
+ })().finally(() => {
406
+ if (inFlightLoad === promise)
407
+ inFlightLoad = null;
408
+ });
409
+ inFlightLoad = promise;
410
+ return promise;
411
+ },
412
+ rotate() {
413
+ const myEpoch = ++epoch;
414
+ cached = null;
415
+ inFlightLoad = null;
416
+ let promise = null;
417
+ promise = (async () => {
418
+ requireSubtleCrypto();
419
+ const storage = resolveStorage();
420
+ const fresh = await createIdentity();
421
+ if (myEpoch !== epoch) {
422
+ if (cached)
423
+ return cached;
424
+ if (inFlightRotate && inFlightRotate !== promise)
425
+ return inFlightRotate;
426
+ return fresh;
427
+ }
428
+ if (storage) {
429
+ const exported = await exportIdentity(fresh);
430
+ if (myEpoch !== epoch) {
431
+ if (cached)
432
+ return cached;
433
+ if (inFlightRotate && inFlightRotate !== promise)
434
+ return inFlightRotate;
435
+ return fresh;
436
+ }
437
+ safeWrite(storage, exported);
438
+ }
439
+ cached = fresh;
440
+ return fresh;
441
+ })().finally(() => {
442
+ if (inFlightRotate === promise)
443
+ inFlightRotate = null;
444
+ });
445
+ inFlightRotate = promise;
446
+ return promise;
447
+ },
448
+ clear() {
449
+ epoch++;
450
+ cached = null;
451
+ inFlightLoad = null;
452
+ inFlightRotate = null;
453
+ safeRemove(resolveStorage());
454
+ }
455
+ };
456
+ }
package/dist/index.d.ts CHANGED
@@ -1,17 +1,17 @@
1
1
  export { defaultIceServers, joinRoom } from './room.js';
2
- export { createIdentity, exportIdentity, importIdentity, isSerializedIdentity } from './identity.js';
3
- export type { CreateIdentityOptions, PeerIdentity, SerializedIdentity } from './identity.js';
2
+ export { createIdentity, createIdentityStore, exportIdentity, importIdentity, isSerializedIdentity } from './identity.js';
3
+ export type { CreateIdentityOptions, IdentityStorage, IdentityStore, IdentityStoreOptions, PeerIdentity, SerializedIdentity } from './identity.js';
4
4
  export type { AddStreamOptions, Delivery, ListenOptions, PeerRoute, PeerStats, PeerStreamMeta, RemoveStreamOptions, Room, RoomError, RoomErrorCode, RoomOptions, RTCPeerConnectionConstructor, SendOptions, SendResult } from './room.js';
5
5
  export { binaryCodec, createChannel, createCodecChannel, jsonCodec, textCodec } from './channel.js';
6
6
  export type { Channel, ChannelOptions, ChannelSendOptions, Codec, CodecChannel } from './channel.js';
7
7
  export { createRpc, RpcError } from './rpc.js';
8
8
  export type { RpcCallOptions, RpcEndpoint, RpcErrorCode, RpcOptions } from './rpc.js';
9
9
  export { createPeerState } from './state.js';
10
- export type { PeerState, PeerStateOptions } from './state.js';
10
+ export type { PeerState, PeerStateChangeReason, PeerStateOptions } from './state.js';
11
11
  export { createBlobChannel } from './blob.js';
12
12
  export type { BlobChannel, BlobChannelOptions, BlobProgress, BlobSendOptions, BlobSendStatus } from './blob.js';
13
- export { createVoice } from './voice.js';
14
- export type { MicError, MicErrorCode, MicStatus, Voice, VoiceOptions, VoiceSnapshot } from './voice.js';
13
+ export { createVoice, listAudioInputs, onAudioInputsChange } from './voice.js';
14
+ export type { AudioInputDevice, MicError, MicErrorCode, MicStatus, Voice, VoiceOptions, VoiceSnapshot } from './voice.js';
15
15
  export { fetchTurnCredentials } from './turn.js';
16
16
  export type { FetchTurnOptions } from './turn.js';
17
17
  export { tabSignaling } from './tabs.js';
@@ -24,7 +24,7 @@ export type { NostrSignalingOptions } from './nostr.js';
24
24
  export { optionalWsSignaling, wsSignaling } from './ws.js';
25
25
  export type { OptionalWsSignalingOptions, WsSignalingOptions } from './ws.js';
26
26
  export { publicSignaling } from './public.js';
27
- export type { PublicSignalingOptions } from './public.js';
27
+ export type { PublicSignalingOptions, PublicTransportEvent, PublicTransportKind } from './public.js';
28
28
  export { combineSignaling, withLocalTabs } from './combine.js';
29
29
  export { isSignal, isUuid, withLoopbackFallback } from './signaling.js';
30
30
  export type { Discovery, IceCandidatePayload, Signal, Signaling, SignalingErrorCode, SignalingSession, SignalingState, WebSocketConstructor } from './signaling.js';
package/dist/index.js CHANGED
@@ -1,10 +1,10 @@
1
1
  export { defaultIceServers, joinRoom } from './room.js';
2
- export { createIdentity, exportIdentity, importIdentity, isSerializedIdentity } from './identity.js';
2
+ export { createIdentity, createIdentityStore, exportIdentity, importIdentity, isSerializedIdentity } from './identity.js';
3
3
  export { binaryCodec, createChannel, createCodecChannel, jsonCodec, textCodec } from './channel.js';
4
4
  export { createRpc, RpcError } from './rpc.js';
5
5
  export { createPeerState } from './state.js';
6
6
  export { createBlobChannel } from './blob.js';
7
- export { createVoice } from './voice.js';
7
+ export { createVoice, listAudioInputs, onAudioInputsChange } from './voice.js';
8
8
  export { fetchTurnCredentials } from './turn.js';
9
9
  export { tabSignaling } from './tabs.js';
10
10
  export { manualSignaling } from './manual.js';
@@ -0,0 +1,4 @@
1
+ export interface ListenerOptionsLike {
2
+ once?: boolean;
3
+ signal?: AbortSignal;
4
+ }
@@ -0,0 +1,97 @@
1
+ const abortHub = new WeakMap();
2
+ /**
3
+ * Subscribe `fn` to an `AbortSignal` while attaching at most ONE native `'abort'`
4
+ * listener per `AbortSignal` across all Meshpost primitives (preventing Node.js
5
+ * `MaxListenersExceededWarning` when many subscriptions share one `AbortController`).
6
+ *
7
+ * Callers should check `signal?.aborted` before calling `bindAbort`.
8
+ * @internal
9
+ */
10
+ export function bindAbort(signal, fn) {
11
+ if (!signal || signal.aborted)
12
+ return () => { };
13
+ let entry = abortHub.get(signal);
14
+ if (!entry) {
15
+ const callbacks = new Set();
16
+ const onAbort = () => {
17
+ if (abortHub.get(signal) === hubEntry) {
18
+ abortHub.delete(signal);
19
+ }
20
+ for (const cb of [...callbacks]) {
21
+ if (!callbacks.has(cb))
22
+ continue;
23
+ callbacks.delete(cb);
24
+ try {
25
+ cb();
26
+ }
27
+ catch (error) {
28
+ globalThis.reportError?.(error);
29
+ }
30
+ }
31
+ };
32
+ const hubEntry = { callbacks, onAbort };
33
+ entry = hubEntry;
34
+ abortHub.set(signal, hubEntry);
35
+ signal.addEventListener('abort', onAbort, { once: true });
36
+ }
37
+ const currentEntry = entry;
38
+ currentEntry.callbacks.add(fn);
39
+ let bound = true;
40
+ return () => {
41
+ if (!bound)
42
+ return;
43
+ bound = false;
44
+ if (!currentEntry.callbacks.delete(fn))
45
+ return;
46
+ if (currentEntry.callbacks.size === 0 && abortHub.get(signal) === currentEntry) {
47
+ abortHub.delete(signal);
48
+ signal.removeEventListener('abort', currentEntry.onAbort);
49
+ }
50
+ };
51
+ }
52
+ /** @internal */
53
+ export function createListeners() {
54
+ const entries = new Set();
55
+ let closed = false;
56
+ return {
57
+ add(fn, options) {
58
+ if (typeof fn !== 'function')
59
+ throw new TypeError('Expected a listener function');
60
+ const signal = options?.signal;
61
+ if (closed || signal?.aborted)
62
+ return () => { };
63
+ let unbindAbort;
64
+ const entry = {
65
+ fn,
66
+ once: Boolean(options?.once),
67
+ off() {
68
+ if (!entries.delete(entry))
69
+ return;
70
+ unbindAbort?.();
71
+ }
72
+ };
73
+ entries.add(entry);
74
+ unbindAbort = bindAbort(signal, entry.off);
75
+ return entry.off;
76
+ },
77
+ fire(...args) {
78
+ for (const entry of [...entries]) {
79
+ if (!entries.has(entry))
80
+ continue;
81
+ if (entry.once)
82
+ entry.off();
83
+ try {
84
+ entry.fn(...args);
85
+ }
86
+ catch (error) {
87
+ globalThis.reportError?.(error);
88
+ }
89
+ }
90
+ },
91
+ clear() {
92
+ closed = true;
93
+ for (const entry of [...entries])
94
+ entry.off();
95
+ }
96
+ };
97
+ }
package/dist/public.d.ts CHANGED
@@ -1,4 +1,12 @@
1
- import type { Signaling, WebSocketConstructor } from './signaling.js';
1
+ import type { Signaling, SignalingState, WebSocketConstructor } from './signaling.js';
2
+ export type PublicTransportKind = 'ws' | 'mqtt' | 'nostr' | 'tabs';
3
+ export interface PublicTransportEvent {
4
+ readonly transport: PublicTransportKind;
5
+ /** Normalized WebSocket relay URL when `transport === 'ws'`. */
6
+ readonly url?: string;
7
+ readonly state: SignalingState;
8
+ readonly reason?: string;
9
+ }
2
10
  export interface PublicSignalingOptions {
3
11
  /**
4
12
  * Optional opportunistic WebSocket signaling URL(s) (`ws://` or `wss://`, max 8 unique URLs)
@@ -43,6 +51,16 @@ export interface PublicSignalingOptions {
43
51
  handshakeTimeoutMs?: number;
44
52
  /** Optional custom `WebSocket` constructor forwarded to WS, MQTT, and Nostr transports. */
45
53
  WebSocket?: WebSocketConstructor;
54
+ /**
55
+ * Optional per-transport lifecycle observer (`'ws'`, `'mqtt'`, `'nostr'`, and `'tabs'` when
56
+ * `localTabs: true` and `BroadcastChannel` is available). Fires on each child transport's state
57
+ * transitions (`'connecting'`, `'online'`, `'offline'`, `'closed'`).
58
+ *
59
+ * Note: Per the WHATWG WebSocket specification, browsers intentionally hide HTTP status codes
60
+ * (such as `403` origin rejections) and TLS handshake details behind opaque close code `1006`;
61
+ * client-side handshake timeouts and non-`1006` close codes are reported in `reason`.
62
+ */
63
+ onTransportChange?: (event: PublicTransportEvent) => void;
46
64
  }
47
65
  /**
48
66
  * Out-of-the-box composite signaling combining public MQTT + port-443 Nostr relays,
package/dist/public.js CHANGED
@@ -1,4 +1,4 @@
1
- import { combineSignaling, withLocalTabs } from './combine.js';
1
+ import { combineSignaling, withLocalTabsInternal } from './combine.js';
2
2
  import { mqttSignaling } from './mqtt.js';
3
3
  import { nostrSignaling } from './nostr.js';
4
4
  import { optionalWsSignaling } from './ws.js';
@@ -11,6 +11,62 @@ function validateTimeoutMs(value, label) {
11
11
  throw new RangeError(`Invalid ${label}`);
12
12
  }
13
13
  }
14
+ function notifyTransport(callback, event) {
15
+ try {
16
+ callback(event);
17
+ }
18
+ catch (error) {
19
+ if (typeof globalThis.reportError === 'function') {
20
+ globalThis.reportError(error);
21
+ }
22
+ else {
23
+ queueMicrotask(() => {
24
+ throw error;
25
+ });
26
+ }
27
+ }
28
+ }
29
+ function observeTransport(adapter, transport, onTransportChange, url) {
30
+ return (discovery) => {
31
+ let lastState;
32
+ let closed = false;
33
+ const emit = (state, reason) => {
34
+ if (state === lastState)
35
+ return;
36
+ lastState = state;
37
+ notifyTransport(onTransportChange, Object.freeze({
38
+ transport,
39
+ ...(url !== undefined ? { url } : {}),
40
+ state,
41
+ ...(reason !== undefined ? { reason } : {})
42
+ }));
43
+ };
44
+ const session = adapter({
45
+ ...discovery,
46
+ status(state, reason) {
47
+ if (closed)
48
+ return;
49
+ emit(state, reason);
50
+ discovery.status(state, reason);
51
+ }
52
+ });
53
+ if (!closed && lastState === undefined) {
54
+ emit('connecting');
55
+ }
56
+ return {
57
+ ...(session.trickle !== undefined ? { trickle: session.trickle } : {}),
58
+ ...(session.canReach ? { canReach: (peerId) => session.canReach(peerId) } : {}),
59
+ send: (to, signal) => session.send(to, signal),
60
+ close() {
61
+ if (closed)
62
+ return;
63
+ closed = true;
64
+ session.close();
65
+ emit('closed');
66
+ }
67
+ };
68
+ };
69
+ }
14
70
  function normalizeWsUrls(raw) {
15
71
  if (raw === undefined)
16
72
  return [];
@@ -56,7 +112,7 @@ export function publicSignaling(options = {}) {
56
112
  if (!options || typeof options !== 'object' || Array.isArray(options)) {
57
113
  throw new TypeError('Invalid publicSignaling options');
58
114
  }
59
- const { wsUrls, mqtt = true, nostr = true, localTabs = true, wsEncrypt = true, privateTopic = false, appId, wsHandshakeTimeoutMs = defaultWsHandshakeTimeoutMs, handshakeTimeoutMs = defaultPublicHandshakeTimeoutMs, WebSocket: WsCtor } = options;
115
+ const { wsUrls, mqtt = true, nostr = true, localTabs = true, wsEncrypt = true, privateTopic = false, appId, wsHandshakeTimeoutMs = defaultWsHandshakeTimeoutMs, handshakeTimeoutMs = defaultPublicHandshakeTimeoutMs, WebSocket: WsCtor, onTransportChange } = options;
60
116
  if (typeof localTabs !== 'boolean')
61
117
  throw new TypeError('Invalid localTabs option');
62
118
  if (typeof wsEncrypt !== 'boolean')
@@ -69,6 +125,9 @@ export function publicSignaling(options = {}) {
69
125
  if (WsCtor !== undefined && typeof WsCtor !== 'function') {
70
126
  throw new TypeError('Invalid WebSocket constructor');
71
127
  }
128
+ if (onTransportChange !== undefined && typeof onTransportChange !== 'function') {
129
+ throw new TypeError('Invalid onTransportChange callback');
130
+ }
72
131
  if (mqtt !== true && mqtt !== false && !Array.isArray(mqtt)) {
73
132
  throw new TypeError('mqtt option must be a boolean or an array of broker URLs');
74
133
  }
@@ -82,31 +141,32 @@ export function publicSignaling(options = {}) {
82
141
  validateTimeoutMs(handshakeTimeoutMs, 'handshakeTimeoutMs');
83
142
  const normalizedWsUrls = normalizeWsUrls(wsUrls);
84
143
  const adapters = [];
144
+ const maybeObserve = (adapter, kind, url) => onTransportChange ? observeTransport(adapter, kind, onTransportChange, url) : adapter;
85
145
  for (const url of normalizedWsUrls) {
86
- adapters.push(optionalWsSignaling(url, {
146
+ adapters.push(maybeObserve(optionalWsSignaling(url, {
87
147
  handshakeTimeoutMs: wsHandshakeTimeoutMs,
88
148
  encrypt: wsEncrypt,
89
149
  privateTopic,
90
150
  ...(WsCtor !== undefined ? { WebSocket: WsCtor } : {})
91
- }));
151
+ }), 'ws', url));
92
152
  }
93
153
  if (mqtt !== false) {
94
- adapters.push(mqttSignaling({
154
+ adapters.push(maybeObserve(mqttSignaling({
95
155
  ...(Array.isArray(mqtt) ? { urls: mqtt } : {}),
96
156
  ...(appId !== undefined ? { appId } : {}),
97
157
  privateTopic,
98
158
  handshakeTimeoutMs,
99
159
  ...(WsCtor !== undefined ? { WebSocket: WsCtor } : {})
100
- }));
160
+ }), 'mqtt'));
101
161
  }
102
162
  if (nostr !== false) {
103
- adapters.push(nostrSignaling({
163
+ adapters.push(maybeObserve(nostrSignaling({
104
164
  ...(Array.isArray(nostr) ? { urls: nostr } : {}),
105
165
  ...(appId !== undefined ? { appId } : {}),
106
166
  privateTopic,
107
167
  handshakeTimeoutMs,
108
168
  ...(WsCtor !== undefined ? { WebSocket: WsCtor } : {})
109
- }));
169
+ }), 'nostr'));
110
170
  }
111
171
  const network = combineSignaling(...adapters);
112
172
  const pooledNetwork = (discovery) => {
@@ -129,5 +189,7 @@ export function publicSignaling(options = {}) {
129
189
  }
130
190
  });
131
191
  };
132
- return localTabs ? withLocalTabs(pooledNetwork) : pooledNetwork;
192
+ return localTabs
193
+ ? withLocalTabsInternal(pooledNetwork, onTransportChange ? (tabs) => observeTransport(tabs, 'tabs', onTransportChange) : undefined)
194
+ : pooledNetwork;
133
195
  }
package/dist/room.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { toBase64Url } from './crypto.js';
2
+ import { createListeners } from './listeners.js';
2
3
  import { decodeCanonicalBase64Url, extractUniqueDtlsFingerprint, isValidPeerIdentity, sha256Base64Url, signIdentityProof, verifyIdentityProof } from './identity.js';
3
4
  import { isSignal, isUuid, randomUuid, withLoopbackFallback } from './signaling.js';
4
5
  const roomInternals = new WeakMap();
@@ -11,9 +12,30 @@ export function isRoomClosed(room) {
11
12
  export function onRoomClose(room, fn) {
12
13
  const internal = roomInternals.get(room);
13
14
  if (!internal) {
14
- if (room.signalingState === 'closed')
15
+ if (room.signalingState === 'closed') {
15
16
  fn();
16
- return () => { };
17
+ return () => { };
18
+ }
19
+ if (typeof room.onSignalingChange !== 'function')
20
+ return () => { };
21
+ let active = true;
22
+ let off;
23
+ const unsubscribe = () => {
24
+ if (!active)
25
+ return;
26
+ active = false;
27
+ if (typeof off === 'function')
28
+ off();
29
+ };
30
+ off = room.onSignalingChange((state) => {
31
+ if (state === 'closed' && active) {
32
+ unsubscribe();
33
+ fn();
34
+ }
35
+ });
36
+ if (!active && typeof off === 'function')
37
+ off();
38
+ return unsubscribe;
17
39
  }
18
40
  return internal.onClose(fn);
19
41
  }
@@ -27,48 +49,7 @@ export const defaultIceServers = Object.freeze([
27
49
  Object.freeze({ urls: 'stun:stun.l.google.com:19302' }),
28
50
  Object.freeze({ urls: 'stun:stun1.l.google.com:19302' })
29
51
  ]);
30
- function listeners() {
31
- const entries = new Set();
32
- let closed = false;
33
- return {
34
- add(fn, options) {
35
- const signal = options?.signal;
36
- if (closed || signal?.aborted)
37
- return () => { };
38
- const entry = {
39
- fn,
40
- once: Boolean(options?.once),
41
- off() {
42
- if (!entries.delete(entry))
43
- return;
44
- signal?.removeEventListener('abort', entry.off);
45
- }
46
- };
47
- entries.add(entry);
48
- signal?.addEventListener('abort', entry.off, { once: true });
49
- return entry.off;
50
- },
51
- fire(...args) {
52
- for (const entry of [...entries]) {
53
- if (!entries.has(entry))
54
- continue;
55
- if (entry.once)
56
- entry.off();
57
- try {
58
- entry.fn(...args);
59
- }
60
- catch (error) {
61
- globalThis.reportError?.(error);
62
- }
63
- }
64
- },
65
- clear() {
66
- closed = true;
67
- for (const entry of [...entries])
68
- entry.off();
69
- }
70
- };
71
- }
52
+ const listeners = createListeners;
72
53
  const maxPacket = 16 * 1024;
73
54
  function asStat(value) {
74
55
  return value && typeof value === 'object' ? value : undefined;
package/dist/rpc.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { createChannel, isValidCodec, jsonCodec } from './channel.js';
2
+ import { bindAbort } from './listeners.js';
2
3
  import { isRoomClosed, onRoomClose } from './room.js';
3
4
  /** Error rejected by `rpc.call()` with a structured `code` and target `peerId`. */
4
5
  export class RpcError extends Error {
@@ -314,16 +315,17 @@ export function createRpc(room, name, options = {}) {
314
315
  item.reject(new RpcError('timeout', peerId, `RPC call timed out after ${timeoutMs}ms`));
315
316
  });
316
317
  }, timeoutMs);
318
+ let unbindAbort;
317
319
  pending.set(reqId, {
318
320
  peerId,
319
321
  resolve,
320
322
  reject,
321
323
  cleanup() {
322
324
  clearTimeout(timer);
323
- signal?.removeEventListener('abort', onAbort);
325
+ unbindAbort?.();
324
326
  }
325
327
  });
326
- signal?.addEventListener('abort', onAbort, { once: true });
328
+ unbindAbort = bindAbort(signal, onAbort);
327
329
  let sendStatus;
328
330
  try {
329
331
  sendStatus = channel.send(frame, { to: peerId }).get(peerId);
@@ -361,6 +363,7 @@ export function createRpc(room, name, options = {}) {
361
363
  throw new Error(`RPC handler already registered for channel "${channel.name}"`);
362
364
  }
363
365
  let removed = false;
366
+ let unbindAbort;
364
367
  const entry = {
365
368
  fn,
366
369
  once: Boolean(listenOptions?.once),
@@ -368,13 +371,13 @@ export function createRpc(room, name, options = {}) {
368
371
  if (removed)
369
372
  return;
370
373
  removed = true;
371
- signal?.removeEventListener('abort', entry.off);
374
+ unbindAbort?.();
372
375
  if (activeHandler === entry)
373
376
  activeHandler = undefined;
374
377
  }
375
378
  };
376
379
  activeHandler = entry;
377
- signal?.addEventListener('abort', entry.off, { once: true });
380
+ unbindAbort = bindAbort(signal, entry.off);
378
381
  return entry.off;
379
382
  },
380
383
  close: shutdown
package/dist/state.d.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  import { type Codec } from './channel.js';
2
2
  import { type Delivery, type ListenOptions, type Room, type SendResult } from './room.js';
3
+ /** Reason why a remote peer's `PeerState` changed in `onChange()`. */
4
+ export type PeerStateChangeReason = 'set' | 'clear' | 'leave';
3
5
  export interface PeerStateOptions<T> {
4
6
  /**
5
7
  * Delivery mode for live `set()` updates (`initial`, `onPeerJoin` hydration, and `clear()` always use `'reliable'`).
@@ -41,10 +43,11 @@ export interface PeerState<T> {
41
43
  */
42
44
  clear(): ReadonlyMap<string, SendResult>;
43
45
  /**
44
- * Subscribe to remote peer state updates and removals (`next` is `undefined` when cleared or when the peer leaves).
46
+ * Subscribe to remote peer state updates and removals (`next` is `undefined` when cleared or when the peer leaves;
47
+ * inspect `reason` (`'set' | 'clear' | 'leave'`) to distinguish explicit `clear()` from `onPeerLeave`).
45
48
  * Returns an idempotent unsubscribe function.
46
49
  */
47
- onChange(fn: (peerId: string, next: T | undefined, prev: T | undefined) => void, options?: ListenOptions): () => void;
50
+ onChange(fn: (peerId: string, next: T | undefined, prev: T | undefined, reason: PeerStateChangeReason) => void, options?: ListenOptions): () => void;
48
51
  /** Detach internal room listeners without broadcasting a clear frame (also runs automatically on `room.leave()`). */
49
52
  close(): void;
50
53
  }