@dimchansky/meshpost 0.2.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/dist/channel.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { Delivery, ListenOptions, Room, SendResult } from './room.js';
1
+ import { type Delivery, type ListenOptions, type Room, type SendResult } from './room.js';
2
2
  export interface ChannelOptions {
3
3
  /** Delivery mode for this logical channel. @default 'unreliable' */
4
4
  delivery?: Delivery;
@@ -18,9 +18,44 @@ export interface Channel {
18
18
  /** Subscribe to packets sent to this channel name. Returns an unsubscribe function. */
19
19
  onPacket(fn: (from: string, bytes: Uint8Array) => void, options?: ListenOptions): () => void;
20
20
  }
21
+ /** Synchronous serializer/deserializer pair for `createCodecChannel()` and `createRpc()`. */
22
+ export interface Codec<T> {
23
+ /** Encode a value into a binary `Uint8Array`. */
24
+ encode(value: T): Uint8Array;
25
+ /** Decode (and optionally validate) a binary `Uint8Array` into `T`. Throw on malformed input. */
26
+ decode(bytes: Uint8Array): T;
27
+ }
28
+ /** Named logical message stream with typed synchronous `send()` and validated `onMessage()`. */
29
+ export interface CodecChannel<T> {
30
+ /** Logical channel name (1-64 UTF-8 bytes). */
31
+ readonly name: string;
32
+ /** Delivery mode configured for this channel. */
33
+ readonly delivery: Delivery;
34
+ /** Encode and send a typed value synchronously. Returns a per-recipient result map. */
35
+ send(value: T, options?: ChannelSendOptions): ReadonlyMap<string, SendResult>;
36
+ /** Subscribe to decoded, validated values on this channel. Malformed incoming frames are ignored. */
37
+ onMessage(fn: (from: string, value: T) => void, options?: ListenOptions): () => void;
38
+ }
39
+ /** Zero-copy identity codec for raw `Uint8Array` payloads. */
40
+ export declare const binaryCodec: Codec<Uint8Array>;
41
+ /** Strict UTF-8 string codec (rejects invalid UTF-8 byte sequences on `decode`). */
42
+ export declare const textCodec: Codec<string>;
43
+ /**
44
+ * Create a UTF-8 JSON codec with optional runtime schema validation.
45
+ * Pass a TypeScript type guard (`(v): v is MyType => ...`) to infer `Codec<MyType>` automatically.
46
+ */
47
+ export declare function jsonCodec<T>(validate: (value: unknown) => value is T): Codec<T>;
48
+ export declare function jsonCodec<T = unknown>(validate?: (value: unknown) => boolean): Codec<T>;
21
49
  /**
22
50
  * Create a named logical channel multiplexed over a Room's existing data channels.
23
51
  * Adds a compact length-prefixed UTF-8 header (`[len, ...nameBytes, ...payload]`)
24
- * without opening additional WebRTC RTCDataChannels.
52
+ * without opening additional WebRTC RTCDataChannels, and dispatches incoming packets
53
+ * in `O(1)` time via a per-Room shared router.
25
54
  */
26
55
  export declare function createChannel(room: Room, name: string, options?: ChannelOptions): Channel;
56
+ /**
57
+ * Create a typed logical channel using a synchronous `Codec<T>` (such as `jsonCodec` or `textCodec`).
58
+ * Preserves synchronous `ReadonlyMap<string, SendResult>` backpressure on `send()`, and drops
59
+ * malformed incoming frames without consuming `{ once: true }` subscriptions.
60
+ */
61
+ export declare function createCodecChannel<T>(room: Room, name: string, codec: Codec<T>, options?: ChannelOptions): CodecChannel<T>;
package/dist/channel.js CHANGED
@@ -1,11 +1,197 @@
1
+ import { isRoomClosed, onRoomClose } from './room.js';
1
2
  const encoder = new TextEncoder();
3
+ const strictDecoder = new TextDecoder('utf-8', { fatal: true });
2
4
  const maxNameBytes = 64;
5
+ const routers = new WeakMap();
6
+ function createModeTable() {
7
+ return {
8
+ byName: new Map(),
9
+ lengthCounts: new Uint32Array(maxNameBytes + 1)
10
+ };
11
+ }
12
+ function getRouter(room) {
13
+ let router = routers.get(room);
14
+ if (router)
15
+ return router;
16
+ const unreliable = createModeTable();
17
+ const reliable = createModeTable();
18
+ let activeSubs = 0;
19
+ let offRoomPacket;
20
+ let offRoomClose;
21
+ const detachIfIdle = () => {
22
+ if (activeSubs === 0 && offRoomPacket) {
23
+ const stopPacket = offRoomPacket;
24
+ const stopClose = offRoomClose;
25
+ offRoomPacket = undefined;
26
+ offRoomClose = undefined;
27
+ stopPacket();
28
+ stopClose?.();
29
+ }
30
+ };
31
+ const dispatch = (from, bytes, mode) => {
32
+ const table = mode === 'reliable' ? reliable : unreliable;
33
+ if (table.byName.size === 0 || bytes.byteLength < 2)
34
+ return;
35
+ const len = bytes[0];
36
+ if (len === 0 ||
37
+ len > maxNameBytes ||
38
+ bytes.byteLength < 1 + len ||
39
+ table.lengthCounts[len] === 0) {
40
+ return;
41
+ }
42
+ let channelName;
43
+ try {
44
+ channelName = strictDecoder.decode(bytes.subarray(1, 1 + len));
45
+ }
46
+ catch {
47
+ return;
48
+ }
49
+ const subs = table.byName.get(channelName);
50
+ if (!subs || subs.size === 0)
51
+ return;
52
+ const payload = bytes.subarray(1 + len);
53
+ for (const entry of [...subs]) {
54
+ if (!subs.has(entry))
55
+ continue;
56
+ if (entry.once)
57
+ entry.off();
58
+ try {
59
+ entry.fn(from, payload);
60
+ }
61
+ catch (error) {
62
+ globalThis.reportError?.(error);
63
+ }
64
+ }
65
+ };
66
+ const clearAll = () => {
67
+ for (const table of [unreliable, reliable]) {
68
+ for (const subs of [...table.byName.values()]) {
69
+ for (const entry of [...subs])
70
+ entry.off();
71
+ }
72
+ table.byName.clear();
73
+ table.lengthCounts.fill(0);
74
+ }
75
+ activeSubs = 0;
76
+ detachIfIdle();
77
+ };
78
+ const ensureAttached = () => {
79
+ if (offRoomPacket)
80
+ return;
81
+ offRoomPacket = room.onPacket(dispatch);
82
+ offRoomClose = onRoomClose(room, clearAll);
83
+ };
84
+ router = {
85
+ subscribe(delivery, name, nameLen, fn, options) {
86
+ if (typeof fn !== 'function')
87
+ throw new TypeError('Expected a listener function');
88
+ const signal = options?.signal;
89
+ if (signal?.aborted || isRoomClosed(room))
90
+ return () => { };
91
+ ensureAttached();
92
+ if (isRoomClosed(room)) {
93
+ clearAll();
94
+ return () => { };
95
+ }
96
+ const table = delivery === 'reliable' ? reliable : unreliable;
97
+ let subs = table.byName.get(name);
98
+ if (!subs) {
99
+ subs = new Set();
100
+ table.byName.set(name, subs);
101
+ table.lengthCounts[nameLen] = (table.lengthCounts[nameLen] ?? 0) + 1;
102
+ }
103
+ let removed = false;
104
+ const entry = {
105
+ fn,
106
+ once: Boolean(options?.once),
107
+ off() {
108
+ if (removed)
109
+ return;
110
+ removed = true;
111
+ signal?.removeEventListener('abort', entry.off);
112
+ const current = table.byName.get(name);
113
+ if (current?.delete(entry)) {
114
+ activeSubs = Math.max(0, activeSubs - 1);
115
+ if (current.size === 0) {
116
+ table.byName.delete(name);
117
+ const prevLenCount = table.lengthCounts[nameLen] ?? 0;
118
+ table.lengthCounts[nameLen] = prevLenCount > 0 ? prevLenCount - 1 : 0;
119
+ }
120
+ }
121
+ detachIfIdle();
122
+ }
123
+ };
124
+ subs.add(entry);
125
+ activeSubs++;
126
+ signal?.addEventListener('abort', entry.off, { once: true });
127
+ return entry.off;
128
+ }
129
+ };
130
+ routers.set(room, router);
131
+ return router;
132
+ }
133
+ /** @internal */
134
+ export function isValidCodec(value) {
135
+ return (Boolean(value) &&
136
+ typeof value === 'object' &&
137
+ typeof value.encode === 'function' &&
138
+ typeof value.decode === 'function');
139
+ }
140
+ /** Zero-copy identity codec for raw `Uint8Array` payloads. */
141
+ export const binaryCodec = Object.freeze({
142
+ encode(value) {
143
+ if (!(value instanceof Uint8Array))
144
+ throw new TypeError('Expected a Uint8Array');
145
+ return value;
146
+ },
147
+ decode(bytes) {
148
+ return bytes;
149
+ }
150
+ });
151
+ /** Strict UTF-8 string codec (rejects invalid UTF-8 byte sequences on `decode`). */
152
+ export const textCodec = Object.freeze({
153
+ encode(value) {
154
+ if (typeof value !== 'string')
155
+ throw new TypeError('Expected a string');
156
+ return encoder.encode(value);
157
+ },
158
+ decode(bytes) {
159
+ return strictDecoder.decode(bytes);
160
+ }
161
+ });
162
+ export function jsonCodec(validate) {
163
+ if (validate !== undefined && typeof validate !== 'function') {
164
+ throw new TypeError('Invalid validator function');
165
+ }
166
+ return Object.freeze({
167
+ encode(value) {
168
+ const json = JSON.stringify(value);
169
+ if (json === undefined)
170
+ throw new TypeError('Value is not JSON-serializable');
171
+ return encoder.encode(json);
172
+ },
173
+ decode(bytes) {
174
+ const parsed = JSON.parse(strictDecoder.decode(bytes));
175
+ if (validate && !validate(parsed)) {
176
+ throw new Error('Invalid JSON payload');
177
+ }
178
+ return parsed;
179
+ }
180
+ });
181
+ }
3
182
  /**
4
183
  * Create a named logical channel multiplexed over a Room's existing data channels.
5
184
  * Adds a compact length-prefixed UTF-8 header (`[len, ...nameBytes, ...payload]`)
6
- * without opening additional WebRTC RTCDataChannels.
185
+ * without opening additional WebRTC RTCDataChannels, and dispatches incoming packets
186
+ * in `O(1)` time via a per-Room shared router.
7
187
  */
8
188
  export function createChannel(room, name, options = {}) {
189
+ if (!room ||
190
+ typeof room !== 'object' ||
191
+ typeof room.send !== 'function' ||
192
+ typeof room.onPacket !== 'function') {
193
+ throw new TypeError('Invalid room');
194
+ }
9
195
  if (typeof name !== 'string' || name.length === 0)
10
196
  throw new TypeError('Invalid channel name');
11
197
  const nameBytes = encoder.encode(name);
@@ -17,6 +203,7 @@ export function createChannel(room, name, options = {}) {
17
203
  const prefix = new Uint8Array(1 + nameBytes.length);
18
204
  prefix[0] = nameBytes.length;
19
205
  prefix.set(nameBytes, 1);
206
+ const router = getRouter(room);
20
207
  return {
21
208
  name,
22
209
  delivery,
@@ -28,23 +215,50 @@ export function createChannel(room, name, options = {}) {
28
215
  framed.set(bytes, prefix.length);
29
216
  return room.send(framed, sendOptions.to === undefined ? { delivery } : { to: sendOptions.to, delivery });
30
217
  },
31
- onPacket(fn, options) {
32
- if (options?.signal?.aborted)
218
+ onPacket(fn, listenOptions) {
219
+ return router.subscribe(delivery, name, nameBytes.length, fn, listenOptions);
220
+ }
221
+ };
222
+ }
223
+ /**
224
+ * Create a typed logical channel using a synchronous `Codec<T>` (such as `jsonCodec` or `textCodec`).
225
+ * Preserves synchronous `ReadonlyMap<string, SendResult>` backpressure on `send()`, and drops
226
+ * malformed incoming frames without consuming `{ once: true }` subscriptions.
227
+ */
228
+ export function createCodecChannel(room, name, codec, options = {}) {
229
+ if (!isValidCodec(codec))
230
+ throw new TypeError('Invalid codec');
231
+ const channel = createChannel(room, name, options);
232
+ return {
233
+ name: channel.name,
234
+ delivery: channel.delivery,
235
+ send(value, sendOptions = {}) {
236
+ const bytes = codec.encode(value);
237
+ if (!(bytes instanceof Uint8Array)) {
238
+ throw new TypeError('Codec encode() must return a Uint8Array');
239
+ }
240
+ return channel.send(bytes, sendOptions);
241
+ },
242
+ onMessage(fn, listenOptions) {
243
+ if (typeof fn !== 'function')
244
+ throw new TypeError('Expected a listener function');
245
+ if (listenOptions?.signal?.aborted || isRoomClosed(room))
33
246
  return () => { };
34
- const once = Boolean(options?.once);
35
- const roomOptions = options?.signal ? { signal: options.signal } : undefined;
247
+ const once = Boolean(listenOptions?.once);
248
+ const subOptions = listenOptions?.signal ? { signal: listenOptions.signal } : undefined;
36
249
  let off = () => { };
37
- off = room.onPacket((from, bytes, mode) => {
38
- if (mode !== delivery || bytes.byteLength < prefix.length)
250
+ off = channel.onPacket((from, bytes) => {
251
+ let decoded;
252
+ try {
253
+ decoded = codec.decode(bytes);
254
+ }
255
+ catch {
39
256
  return;
40
- for (let i = 0; i < prefix.length; i++) {
41
- if (bytes[i] !== prefix[i])
42
- return;
43
257
  }
44
258
  if (once)
45
259
  off();
46
- fn(from, bytes.subarray(prefix.length));
47
- }, roomOptions);
260
+ fn(from, decoded);
261
+ }, subOptions);
48
262
  return off;
49
263
  }
50
264
  };
package/dist/combine.d.ts CHANGED
@@ -1,7 +1,18 @@
1
1
  import type { Signaling } from './signaling.js';
2
2
  /**
3
3
  * Combine multiple signaling adapters into one composite adapter.
4
- * Merges peer rosters across all children, routes signals to online children that advertise the target peer,
4
+ * Merges peer rosters across all children, routes signals to reachable children that advertise the target peer,
5
5
  * and stays `'online'` as long as at least one child adapter is `'online'`.
6
6
  */
7
7
  export declare function combineSignaling(...adapters: readonly Signaling[]): Signaling;
8
+ /**
9
+ * Decorate a network signaling adapter (`mqttSignaling()`, `wsSignaling()`, etc.) with instant
10
+ * same-browser `BroadcastChannel` discovery (`tabSignaling()`).
11
+ *
12
+ * - Exposes `primary`'s `SignalingState` and errors for `room.signalingState` / `room.onSignalingChange`
13
+ * (avoiding a permanently `'online'` indicator when network connectivity is lost).
14
+ * - Still connects same-browser tabs locally even while `primary` is `'connecting'` or `'offline'`.
15
+ * - Safely falls back to `primary` alone when `BroadcastChannel` is unavailable, on `file:` / opaque
16
+ * origins, or if `new BroadcastChannel(...)` throws `SecurityError`.
17
+ */
18
+ export declare function withLocalTabs(primary: Signaling): Signaling;