@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/README.md +330 -96
- package/dist/channel.d.ts +37 -2
- package/dist/channel.js +226 -12
- package/dist/combine.d.ts +12 -1
- package/dist/combine.js +304 -213
- 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 +17 -5
- package/dist/index.js +8 -2
- 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 -7
- package/dist/room.js +656 -65
- package/dist/rpc.d.ts +48 -0
- package/dist/rpc.js +382 -0
- package/dist/signaling.d.ts +9 -8
- package/dist/signaling.js +10 -2
- package/dist/state.d.ts +56 -0
- package/dist/state.js +305 -0
- package/dist/tabs.js +8 -1
- package/dist/turn.d.ts +13 -0
- package/dist/turn.js +213 -0
- package/dist/voice.d.ts +108 -0
- package/dist/voice.js +1160 -0
- package/dist/ws.d.ts +17 -2
- package/dist/ws.js +248 -33
- package/docs/behavior.md +107 -54
- package/package.json +67 -2
package/dist/rpc.d.ts
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { type Codec } from './channel.js';
|
|
2
|
+
import { type ListenOptions, type Room } from './room.js';
|
|
3
|
+
/** Structured failure reason on an `RpcError` rejected by `rpc.call()`. */
|
|
4
|
+
export type RpcErrorCode = 'timeout' | 'aborted' | 'disconnected' | 'unavailable' | 'busy' | 'too-large' | 'unhandled' | 'remote-error' | 'closed';
|
|
5
|
+
/** Error rejected by `rpc.call()` with a structured `code` and target `peerId`. */
|
|
6
|
+
export declare class RpcError extends Error {
|
|
7
|
+
readonly code: RpcErrorCode;
|
|
8
|
+
readonly peerId: string;
|
|
9
|
+
constructor(code: RpcErrorCode, peerId: string, message: string);
|
|
10
|
+
}
|
|
11
|
+
export interface RpcOptions<Req = unknown, Res = unknown> {
|
|
12
|
+
/** Default timeout in milliseconds per outgoing `call()`. @default 10000 */
|
|
13
|
+
timeoutMs?: number;
|
|
14
|
+
/** Codec used to encode/decode request payloads. @default jsonCodec() */
|
|
15
|
+
requestCodec?: Codec<Req>;
|
|
16
|
+
/** Codec used to encode/decode response payloads. @default jsonCodec() */
|
|
17
|
+
responseCodec?: Codec<Res>;
|
|
18
|
+
/** Maximum simultaneous pending outgoing calls across peers (`1..4096`). @default 256 */
|
|
19
|
+
maxPendingCalls?: number;
|
|
20
|
+
/** Maximum simultaneous in-flight incoming handler executions per peer (`1..256`). @default 16 */
|
|
21
|
+
maxConcurrentPerPeer?: number;
|
|
22
|
+
}
|
|
23
|
+
export interface RpcCallOptions {
|
|
24
|
+
/** Per-call timeout override in milliseconds (`1..2147483647`). */
|
|
25
|
+
timeoutMs?: number;
|
|
26
|
+
/** Optional AbortSignal to cancel waiting for the response. */
|
|
27
|
+
signal?: AbortSignal;
|
|
28
|
+
}
|
|
29
|
+
/** Typed request-response RPC endpoint multiplexed over a reliable named `Channel`. */
|
|
30
|
+
export interface RpcEndpoint<Req = unknown, Res = unknown> {
|
|
31
|
+
/** Logical channel name used by this RPC endpoint. */
|
|
32
|
+
readonly name: string;
|
|
33
|
+
/** Send a typed request to `peerId` and await its typed response. */
|
|
34
|
+
call(peerId: string, request: Req, options?: RpcCallOptions): Promise<Res>;
|
|
35
|
+
/**
|
|
36
|
+
* Register the request handler for this RPC endpoint (at most one active handler at a time).
|
|
37
|
+
* Returns an idempotent unsubscribe function that removes this handler.
|
|
38
|
+
*/
|
|
39
|
+
handle(fn: (from: string, request: Req) => Res | Promise<Res>, options?: ListenOptions): () => void;
|
|
40
|
+
/** Reject all pending outgoing calls with `'closed'` and detach internal room listeners. */
|
|
41
|
+
close(): void;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Create a lightweight reliable request-response RPC endpoint over a named `Channel`.
|
|
45
|
+
* Automatically handles correlation IDs, `timeoutMs`, `AbortSignal`, `onPeerLeave` cancellation,
|
|
46
|
+
* peer-scoped anti-spoofing, and immediate error propagation (`'unhandled'`, `'busy'`, `'too-large'`, `'remote-error'`).
|
|
47
|
+
*/
|
|
48
|
+
export declare function createRpc<Req = unknown, Res = unknown>(room: Room, name: string, options?: RpcOptions<Req, Res>): RpcEndpoint<Req, Res>;
|
package/dist/rpc.js
ADDED
|
@@ -0,0 +1,382 @@
|
|
|
1
|
+
import { createChannel, isValidCodec, jsonCodec } from './channel.js';
|
|
2
|
+
import { isRoomClosed, onRoomClose } from './room.js';
|
|
3
|
+
/** Error rejected by `rpc.call()` with a structured `code` and target `peerId`. */
|
|
4
|
+
export class RpcError extends Error {
|
|
5
|
+
code;
|
|
6
|
+
peerId;
|
|
7
|
+
constructor(code, peerId, message) {
|
|
8
|
+
super(message);
|
|
9
|
+
this.name = 'RpcError';
|
|
10
|
+
this.code = code;
|
|
11
|
+
this.peerId = peerId;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
const opReq = 0x01;
|
|
15
|
+
const opResOk = 0x02;
|
|
16
|
+
const opResErr = 0x03;
|
|
17
|
+
const errUnhandled = 1;
|
|
18
|
+
const errRemote = 2;
|
|
19
|
+
const errTooLarge = 3;
|
|
20
|
+
const errBusy = 4;
|
|
21
|
+
const headerBytes = 5;
|
|
22
|
+
const errHeaderBytes = 6;
|
|
23
|
+
const maxRpcErrorBytes = 256;
|
|
24
|
+
const maxTimeoutMs = 2_147_483_647;
|
|
25
|
+
const defaultTimeoutMs = 10_000;
|
|
26
|
+
const defaultMaxPendingCalls = 256;
|
|
27
|
+
const defaultMaxConcurrentPerPeer = 16;
|
|
28
|
+
const encoder = new TextEncoder();
|
|
29
|
+
const strictDecoder = new TextDecoder('utf-8', { fatal: true });
|
|
30
|
+
const controlCharsPattern = /[\x00-\x1f\x7f]/g;
|
|
31
|
+
function sanitizeErrorText(raw, fallback) {
|
|
32
|
+
const cleaned = raw.replace(controlCharsPattern, ' ').trim();
|
|
33
|
+
return cleaned.length > 0 ? cleaned : fallback;
|
|
34
|
+
}
|
|
35
|
+
function encodeTruncatedUtf8(text, maxBytes) {
|
|
36
|
+
const buf = new Uint8Array(maxBytes);
|
|
37
|
+
const { written } = encoder.encodeInto(text, buf);
|
|
38
|
+
return buf.subarray(0, written);
|
|
39
|
+
}
|
|
40
|
+
function buildPayloadFrame(opcode, reqId, body) {
|
|
41
|
+
const frame = new Uint8Array(headerBytes + body.byteLength);
|
|
42
|
+
frame[0] = opcode;
|
|
43
|
+
new DataView(frame.buffer).setUint32(1, reqId >>> 0);
|
|
44
|
+
frame.set(body, headerBytes);
|
|
45
|
+
return frame;
|
|
46
|
+
}
|
|
47
|
+
function buildErrorFrame(reqId, errKind, message) {
|
|
48
|
+
const safeText = sanitizeErrorText(message, 'Remote RPC error');
|
|
49
|
+
const msgBytes = encodeTruncatedUtf8(safeText, maxRpcErrorBytes);
|
|
50
|
+
const frame = new Uint8Array(errHeaderBytes + msgBytes.byteLength);
|
|
51
|
+
frame[0] = opResErr;
|
|
52
|
+
new DataView(frame.buffer).setUint32(1, reqId >>> 0);
|
|
53
|
+
frame[5] = errKind;
|
|
54
|
+
frame.set(msgBytes, errHeaderBytes);
|
|
55
|
+
return frame;
|
|
56
|
+
}
|
|
57
|
+
function decodeErrorMessage(bytes, fallback) {
|
|
58
|
+
const slice = bytes.subarray(errHeaderBytes, Math.min(bytes.byteLength, errHeaderBytes + maxRpcErrorBytes));
|
|
59
|
+
if (slice.byteLength === 0)
|
|
60
|
+
return fallback;
|
|
61
|
+
try {
|
|
62
|
+
return sanitizeErrorText(strictDecoder.decode(slice), fallback);
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
return fallback;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
function mapErrKind(errKind) {
|
|
69
|
+
switch (errKind) {
|
|
70
|
+
case errUnhandled:
|
|
71
|
+
return { code: 'unhandled', fallback: 'No RPC handler registered on remote peer' };
|
|
72
|
+
case errTooLarge:
|
|
73
|
+
return { code: 'too-large', fallback: 'RPC response exceeded 16 KiB packet limit' };
|
|
74
|
+
case errBusy:
|
|
75
|
+
return { code: 'busy', fallback: 'Remote peer RPC concurrency limit exceeded' };
|
|
76
|
+
default:
|
|
77
|
+
return { code: 'remote-error', fallback: 'Remote RPC handler failed' };
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Create a lightweight reliable request-response RPC endpoint over a named `Channel`.
|
|
82
|
+
* Automatically handles correlation IDs, `timeoutMs`, `AbortSignal`, `onPeerLeave` cancellation,
|
|
83
|
+
* peer-scoped anti-spoofing, and immediate error propagation (`'unhandled'`, `'busy'`, `'too-large'`, `'remote-error'`).
|
|
84
|
+
*/
|
|
85
|
+
export function createRpc(room, name, options = {}) {
|
|
86
|
+
if (!room ||
|
|
87
|
+
typeof room !== 'object' ||
|
|
88
|
+
typeof room.onPeerLeave !== 'function' ||
|
|
89
|
+
!Array.isArray(room.peers)) {
|
|
90
|
+
throw new TypeError('Invalid room');
|
|
91
|
+
}
|
|
92
|
+
const defaultTimeout = options.timeoutMs ?? defaultTimeoutMs;
|
|
93
|
+
if (!Number.isSafeInteger(defaultTimeout) ||
|
|
94
|
+
defaultTimeout <= 0 ||
|
|
95
|
+
defaultTimeout > maxTimeoutMs) {
|
|
96
|
+
throw new RangeError('Invalid RPC timeoutMs');
|
|
97
|
+
}
|
|
98
|
+
const maxPendingCalls = options.maxPendingCalls ?? defaultMaxPendingCalls;
|
|
99
|
+
if (!Number.isSafeInteger(maxPendingCalls) || maxPendingCalls < 1 || maxPendingCalls > 4096) {
|
|
100
|
+
throw new RangeError('maxPendingCalls must be an integer between 1 and 4096');
|
|
101
|
+
}
|
|
102
|
+
const maxConcurrentPerPeer = options.maxConcurrentPerPeer ?? defaultMaxConcurrentPerPeer;
|
|
103
|
+
if (!Number.isSafeInteger(maxConcurrentPerPeer) ||
|
|
104
|
+
maxConcurrentPerPeer < 1 ||
|
|
105
|
+
maxConcurrentPerPeer > 256) {
|
|
106
|
+
throw new RangeError('maxConcurrentPerPeer must be an integer between 1 and 256');
|
|
107
|
+
}
|
|
108
|
+
const requestCodec = options.requestCodec !== undefined ? options.requestCodec : jsonCodec();
|
|
109
|
+
const responseCodec = options.responseCodec !== undefined ? options.responseCodec : jsonCodec();
|
|
110
|
+
if (!isValidCodec(requestCodec))
|
|
111
|
+
throw new TypeError('Invalid requestCodec');
|
|
112
|
+
if (!isValidCodec(responseCodec))
|
|
113
|
+
throw new TypeError('Invalid responseCodec');
|
|
114
|
+
const channel = createChannel(room, name, { delivery: 'reliable' });
|
|
115
|
+
const pending = new Map();
|
|
116
|
+
const inFlightByPeer = new Map();
|
|
117
|
+
let activeHandler;
|
|
118
|
+
let nextReqId = (Math.random() * 0xffff_ffff) >>> 0;
|
|
119
|
+
let closed = isRoomClosed(room);
|
|
120
|
+
const internalAbort = new AbortController();
|
|
121
|
+
const allocateReqId = () => {
|
|
122
|
+
for (let i = 0; i <= maxPendingCalls; i++) {
|
|
123
|
+
nextReqId = (nextReqId + 1) >>> 0;
|
|
124
|
+
if (nextReqId === 0)
|
|
125
|
+
nextReqId = 1;
|
|
126
|
+
if (!pending.has(nextReqId))
|
|
127
|
+
return nextReqId;
|
|
128
|
+
}
|
|
129
|
+
return 1;
|
|
130
|
+
};
|
|
131
|
+
const sendErrorBestEffort = (to, reqId, errKind, message) => {
|
|
132
|
+
if (closed || isRoomClosed(room))
|
|
133
|
+
return;
|
|
134
|
+
try {
|
|
135
|
+
channel.send(buildErrorFrame(reqId, errKind, message), { to });
|
|
136
|
+
}
|
|
137
|
+
catch {
|
|
138
|
+
// Room closed concurrently; ignore.
|
|
139
|
+
}
|
|
140
|
+
};
|
|
141
|
+
const settlePending = (reqId, fn) => {
|
|
142
|
+
const entry = pending.get(reqId);
|
|
143
|
+
if (!entry)
|
|
144
|
+
return;
|
|
145
|
+
pending.delete(reqId);
|
|
146
|
+
entry.cleanup();
|
|
147
|
+
fn(entry);
|
|
148
|
+
};
|
|
149
|
+
const shutdown = () => {
|
|
150
|
+
if (closed)
|
|
151
|
+
return;
|
|
152
|
+
closed = true;
|
|
153
|
+
internalAbort.abort();
|
|
154
|
+
offRoomClose();
|
|
155
|
+
if (activeHandler) {
|
|
156
|
+
const h = activeHandler;
|
|
157
|
+
activeHandler = undefined;
|
|
158
|
+
h.off();
|
|
159
|
+
}
|
|
160
|
+
for (const [reqId] of [...pending]) {
|
|
161
|
+
settlePending(reqId, (entry) => {
|
|
162
|
+
entry.reject(new RpcError('closed', entry.peerId, 'RPC endpoint is closed'));
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
};
|
|
166
|
+
const offRoomClose = closed ? () => { } : onRoomClose(room, shutdown);
|
|
167
|
+
if (!closed) {
|
|
168
|
+
const internalListen = { signal: internalAbort.signal };
|
|
169
|
+
room.onPeerLeave((peerId) => {
|
|
170
|
+
for (const [reqId, entry] of [...pending]) {
|
|
171
|
+
if (entry.peerId === peerId) {
|
|
172
|
+
settlePending(reqId, (item) => {
|
|
173
|
+
item.reject(new RpcError('disconnected', peerId, 'Peer disconnected before RPC completed'));
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
}, internalListen);
|
|
178
|
+
channel.onPacket((from, bytes) => {
|
|
179
|
+
if (closed || bytes.byteLength < headerBytes)
|
|
180
|
+
return;
|
|
181
|
+
const opcode = bytes[0];
|
|
182
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
183
|
+
const reqId = view.getUint32(1);
|
|
184
|
+
if (reqId === 0)
|
|
185
|
+
return;
|
|
186
|
+
if (opcode === opReq) {
|
|
187
|
+
const handler = activeHandler;
|
|
188
|
+
if (!handler) {
|
|
189
|
+
sendErrorBestEffort(from, reqId, errUnhandled, 'No RPC handler registered');
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
const currentInFlight = inFlightByPeer.get(from) ?? 0;
|
|
193
|
+
if (currentInFlight >= maxConcurrentPerPeer) {
|
|
194
|
+
sendErrorBestEffort(from, reqId, errBusy, 'Peer RPC concurrency limit exceeded');
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
let decodedReq;
|
|
198
|
+
try {
|
|
199
|
+
decodedReq = requestCodec.decode(bytes.subarray(headerBytes));
|
|
200
|
+
}
|
|
201
|
+
catch {
|
|
202
|
+
sendErrorBestEffort(from, reqId, errRemote, 'Invalid RPC request');
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
if (handler.once)
|
|
206
|
+
handler.off();
|
|
207
|
+
inFlightByPeer.set(from, currentInFlight + 1);
|
|
208
|
+
void (async () => {
|
|
209
|
+
try {
|
|
210
|
+
const result = await handler.fn(from, decodedReq);
|
|
211
|
+
if (closed || isRoomClosed(room) || !room.peers.includes(from))
|
|
212
|
+
return;
|
|
213
|
+
let encodedRes;
|
|
214
|
+
try {
|
|
215
|
+
encodedRes = responseCodec.encode(result);
|
|
216
|
+
if (!(encodedRes instanceof Uint8Array)) {
|
|
217
|
+
throw new TypeError('responseCodec.encode() must return a Uint8Array');
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
catch {
|
|
221
|
+
sendErrorBestEffort(from, reqId, errRemote, 'Failed to encode RPC response');
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
const status = channel
|
|
225
|
+
.send(buildPayloadFrame(opResOk, reqId, encodedRes), { to: from })
|
|
226
|
+
.get(from);
|
|
227
|
+
if (status === 'too-large') {
|
|
228
|
+
sendErrorBestEffort(from, reqId, errTooLarge, 'RPC response exceeded 16 KiB packet limit');
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
catch (error) {
|
|
232
|
+
if (closed || isRoomClosed(room) || !room.peers.includes(from))
|
|
233
|
+
return;
|
|
234
|
+
const rawMsg = error instanceof Error && error.message ? error.message : 'Remote RPC handler failed';
|
|
235
|
+
sendErrorBestEffort(from, reqId, errRemote, rawMsg);
|
|
236
|
+
}
|
|
237
|
+
finally {
|
|
238
|
+
const next = (inFlightByPeer.get(from) ?? 1) - 1;
|
|
239
|
+
if (next <= 0)
|
|
240
|
+
inFlightByPeer.delete(from);
|
|
241
|
+
else
|
|
242
|
+
inFlightByPeer.set(from, next);
|
|
243
|
+
}
|
|
244
|
+
})();
|
|
245
|
+
}
|
|
246
|
+
else if (opcode === opResOk) {
|
|
247
|
+
const entry = pending.get(reqId);
|
|
248
|
+
if (!entry || entry.peerId !== from)
|
|
249
|
+
return;
|
|
250
|
+
let decodedRes;
|
|
251
|
+
try {
|
|
252
|
+
decodedRes = responseCodec.decode(bytes.subarray(headerBytes));
|
|
253
|
+
}
|
|
254
|
+
catch {
|
|
255
|
+
settlePending(reqId, (item) => {
|
|
256
|
+
item.reject(new RpcError('remote-error', from, 'Invalid RPC response'));
|
|
257
|
+
});
|
|
258
|
+
return;
|
|
259
|
+
}
|
|
260
|
+
settlePending(reqId, (item) => item.resolve(decodedRes));
|
|
261
|
+
}
|
|
262
|
+
else if (opcode === opResErr) {
|
|
263
|
+
if (bytes.byteLength < errHeaderBytes)
|
|
264
|
+
return;
|
|
265
|
+
const entry = pending.get(reqId);
|
|
266
|
+
if (!entry || entry.peerId !== from)
|
|
267
|
+
return;
|
|
268
|
+
const { code, fallback } = mapErrKind(bytes[5]);
|
|
269
|
+
const message = decodeErrorMessage(bytes, fallback);
|
|
270
|
+
settlePending(reqId, (item) => item.reject(new RpcError(code, from, message)));
|
|
271
|
+
}
|
|
272
|
+
}, internalListen);
|
|
273
|
+
}
|
|
274
|
+
return {
|
|
275
|
+
name: channel.name,
|
|
276
|
+
call(peerId, request, callOptions = {}) {
|
|
277
|
+
if (typeof peerId !== 'string' || peerId.length === 0) {
|
|
278
|
+
return Promise.reject(new TypeError('Invalid target peerId'));
|
|
279
|
+
}
|
|
280
|
+
const timeoutMs = callOptions.timeoutMs ?? defaultTimeout;
|
|
281
|
+
if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > maxTimeoutMs) {
|
|
282
|
+
return Promise.reject(new RangeError('Invalid RPC timeoutMs'));
|
|
283
|
+
}
|
|
284
|
+
if (closed || isRoomClosed(room)) {
|
|
285
|
+
return Promise.reject(new RpcError('closed', peerId, 'RPC endpoint is closed'));
|
|
286
|
+
}
|
|
287
|
+
const signal = callOptions.signal;
|
|
288
|
+
if (signal?.aborted) {
|
|
289
|
+
return Promise.reject(new RpcError('aborted', peerId, 'RPC call was aborted'));
|
|
290
|
+
}
|
|
291
|
+
if (pending.size >= maxPendingCalls) {
|
|
292
|
+
return Promise.reject(new RpcError('busy', peerId, 'Too many pending RPC calls'));
|
|
293
|
+
}
|
|
294
|
+
let reqBytes;
|
|
295
|
+
try {
|
|
296
|
+
reqBytes = requestCodec.encode(request);
|
|
297
|
+
if (!(reqBytes instanceof Uint8Array)) {
|
|
298
|
+
throw new TypeError('requestCodec.encode() must return a Uint8Array');
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
catch (error) {
|
|
302
|
+
return Promise.reject(error);
|
|
303
|
+
}
|
|
304
|
+
const reqId = allocateReqId();
|
|
305
|
+
const frame = buildPayloadFrame(opReq, reqId, reqBytes);
|
|
306
|
+
return new Promise((resolve, reject) => {
|
|
307
|
+
const onAbort = () => {
|
|
308
|
+
settlePending(reqId, (item) => {
|
|
309
|
+
item.reject(new RpcError('aborted', peerId, 'RPC call was aborted'));
|
|
310
|
+
});
|
|
311
|
+
};
|
|
312
|
+
const timer = setTimeout(() => {
|
|
313
|
+
settlePending(reqId, (item) => {
|
|
314
|
+
item.reject(new RpcError('timeout', peerId, `RPC call timed out after ${timeoutMs}ms`));
|
|
315
|
+
});
|
|
316
|
+
}, timeoutMs);
|
|
317
|
+
pending.set(reqId, {
|
|
318
|
+
peerId,
|
|
319
|
+
resolve,
|
|
320
|
+
reject,
|
|
321
|
+
cleanup() {
|
|
322
|
+
clearTimeout(timer);
|
|
323
|
+
signal?.removeEventListener('abort', onAbort);
|
|
324
|
+
}
|
|
325
|
+
});
|
|
326
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
327
|
+
let sendStatus;
|
|
328
|
+
try {
|
|
329
|
+
sendStatus = channel.send(frame, { to: peerId }).get(peerId);
|
|
330
|
+
}
|
|
331
|
+
catch {
|
|
332
|
+
sendStatus = 'closed';
|
|
333
|
+
}
|
|
334
|
+
if (sendStatus === 'closed') {
|
|
335
|
+
settlePending(reqId, (item) => {
|
|
336
|
+
item.reject(new RpcError('closed', peerId, 'RPC endpoint is closed'));
|
|
337
|
+
});
|
|
338
|
+
}
|
|
339
|
+
else if (sendStatus === 'unavailable' ||
|
|
340
|
+
sendStatus === 'busy' ||
|
|
341
|
+
sendStatus === 'too-large') {
|
|
342
|
+
const status = sendStatus;
|
|
343
|
+
settlePending(reqId, (item) => {
|
|
344
|
+
item.reject(new RpcError(status, peerId, `RPC request send failed (${status})`));
|
|
345
|
+
});
|
|
346
|
+
}
|
|
347
|
+
else if (sendStatus !== 'accepted') {
|
|
348
|
+
settlePending(reqId, (item) => {
|
|
349
|
+
item.reject(new RpcError('unavailable', peerId, 'Peer is unavailable'));
|
|
350
|
+
});
|
|
351
|
+
}
|
|
352
|
+
});
|
|
353
|
+
},
|
|
354
|
+
handle(fn, listenOptions) {
|
|
355
|
+
if (typeof fn !== 'function')
|
|
356
|
+
throw new TypeError('Expected an RPC handler function');
|
|
357
|
+
const signal = listenOptions?.signal;
|
|
358
|
+
if (closed || isRoomClosed(room) || signal?.aborted)
|
|
359
|
+
return () => { };
|
|
360
|
+
if (activeHandler) {
|
|
361
|
+
throw new Error(`RPC handler already registered for channel "${channel.name}"`);
|
|
362
|
+
}
|
|
363
|
+
let removed = false;
|
|
364
|
+
const entry = {
|
|
365
|
+
fn,
|
|
366
|
+
once: Boolean(listenOptions?.once),
|
|
367
|
+
off() {
|
|
368
|
+
if (removed)
|
|
369
|
+
return;
|
|
370
|
+
removed = true;
|
|
371
|
+
signal?.removeEventListener('abort', entry.off);
|
|
372
|
+
if (activeHandler === entry)
|
|
373
|
+
activeHandler = undefined;
|
|
374
|
+
}
|
|
375
|
+
};
|
|
376
|
+
activeHandler = entry;
|
|
377
|
+
signal?.addEventListener('abort', entry.off, { once: true });
|
|
378
|
+
return entry.off;
|
|
379
|
+
},
|
|
380
|
+
close: shutdown
|
|
381
|
+
};
|
|
382
|
+
}
|
package/dist/signaling.d.ts
CHANGED
|
@@ -23,7 +23,7 @@ export type Signal = {
|
|
|
23
23
|
/** Connection state reported by a signaling adapter. */
|
|
24
24
|
export type SignalingState = 'connecting' | 'online' | 'offline' | 'closed';
|
|
25
25
|
/** Structured error codes that a signaling adapter may report via `Discovery.error`. */
|
|
26
|
-
export type SignalingErrorCode = 'decrypt-failed' | 'signaling-error';
|
|
26
|
+
export type SignalingErrorCode = 'decrypt-failed' | 'clock-skew' | 'signaling-error';
|
|
27
27
|
/** Callbacks and room metadata passed by `joinRoom()` into a `Signaling` adapter factory. */
|
|
28
28
|
export interface Discovery {
|
|
29
29
|
/** Application namespace isolating rooms across apps. */
|
|
@@ -40,13 +40,18 @@ export interface Discovery {
|
|
|
40
40
|
receive(from: string, signal: Signal): void;
|
|
41
41
|
/** Report a signaling state transition (with an optional human-readable reason). */
|
|
42
42
|
status(state: SignalingState, reason?: string): void;
|
|
43
|
-
/** Optional: report a structured signaling error (e.g. `'decrypt-failed'` or `'signaling-error'`). */
|
|
43
|
+
/** Optional: report a structured signaling error (e.g. `'decrypt-failed'`, `'clock-skew'`, or `'signaling-error'`). */
|
|
44
44
|
error?(code: SignalingErrorCode, message?: string): void;
|
|
45
45
|
}
|
|
46
46
|
/** Active signaling handle returned by a `Signaling` adapter factory. */
|
|
47
47
|
export interface SignalingSession {
|
|
48
48
|
/** Set `true` if this adapter supports incremental Trickle ICE (`{ kind: 'ice' }`) messages. */
|
|
49
49
|
readonly trickle?: boolean;
|
|
50
|
+
/**
|
|
51
|
+
* Optional per-peer reachability check for composite adapters (such as `withLocalTabs`) whose
|
|
52
|
+
* outer `SignalingState` reflects a primary transport while secondary local transports remain online.
|
|
53
|
+
*/
|
|
54
|
+
canReach?(peerId: string): boolean;
|
|
50
55
|
/** Send a signal to a peer. Return `true` if accepted, or `false` if signaling is unavailable. */
|
|
51
56
|
send(to: string, signal: Signal): boolean;
|
|
52
57
|
/** Shut down the signaling adapter and release all sockets/timers. */
|
|
@@ -54,14 +59,10 @@ export interface SignalingSession {
|
|
|
54
59
|
}
|
|
55
60
|
/** Factory function that connects a room to a discovery and SDP exchange transport. */
|
|
56
61
|
export type Signaling = (discovery: Discovery) => SignalingSession;
|
|
57
|
-
|
|
58
|
-
export
|
|
62
|
+
/** Constructor signature for custom or headless `WebSocket` implementations. */
|
|
63
|
+
export type WebSocketConstructor = new (url: string, protocols?: string | string[]) => WebSocket;
|
|
59
64
|
/** Check whether a value is a lowercase hyphenated UUID string. */
|
|
60
65
|
export declare function isUuid(value: unknown): value is string;
|
|
61
|
-
/** Generate an RFC 4122 v4 UUID even in non-secure contexts (e.g. plain HTTP LAN) where crypto.randomUUID is absent. */
|
|
62
|
-
export declare function randomUuid(): string;
|
|
63
|
-
/** Deterministic 64-bit hex hash (works even in non-secure contexts such as file://). */
|
|
64
|
-
export declare function namespaceHash(input: string): string;
|
|
65
66
|
/** Type guard validating a parsed signaling payload (`need`, `offer`, `answer`, or `ice`). */
|
|
66
67
|
export declare function isSignal(value: unknown): value is Signal;
|
|
67
68
|
/** Add a fallback for co-located endpoints when multicast DNS is unavailable.
|
package/dist/signaling.js
CHANGED
|
@@ -1,10 +1,15 @@
|
|
|
1
|
+
/** @internal */
|
|
1
2
|
export const uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
3
|
+
/** @internal */
|
|
2
4
|
export const maxAttemptNumber = 0x7fffffff;
|
|
3
5
|
/** Check whether a value is a lowercase hyphenated UUID string. */
|
|
4
6
|
export function isUuid(value) {
|
|
5
7
|
return typeof value === 'string' && uuidPattern.test(value);
|
|
6
8
|
}
|
|
7
|
-
/**
|
|
9
|
+
/**
|
|
10
|
+
* Generate an RFC 4122 v4 UUID even in non-secure contexts (e.g. plain HTTP LAN) where crypto.randomUUID is absent.
|
|
11
|
+
* @internal
|
|
12
|
+
*/
|
|
8
13
|
export function randomUuid() {
|
|
9
14
|
if (typeof crypto.randomUUID === 'function')
|
|
10
15
|
return crypto.randomUUID();
|
|
@@ -14,7 +19,10 @@ export function randomUuid() {
|
|
|
14
19
|
const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
|
|
15
20
|
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
16
21
|
}
|
|
17
|
-
/**
|
|
22
|
+
/**
|
|
23
|
+
* Deterministic 64-bit hex hash (works even in non-secure contexts such as file://).
|
|
24
|
+
* @internal
|
|
25
|
+
*/
|
|
18
26
|
export function namespaceHash(input) {
|
|
19
27
|
let h1 = 0xdeadbeef ^ input.length;
|
|
20
28
|
let h2 = 0x41c6ce57 ^ input.length;
|
package/dist/state.d.ts
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { type Codec } from './channel.js';
|
|
2
|
+
import { type Delivery, type ListenOptions, type Room, type SendResult } from './room.js';
|
|
3
|
+
export interface PeerStateOptions<T> {
|
|
4
|
+
/**
|
|
5
|
+
* Delivery mode for live `set()` updates (`initial`, `onPeerJoin` hydration, and `clear()` always use `'reliable'`).
|
|
6
|
+
* @default 'reliable'
|
|
7
|
+
*/
|
|
8
|
+
delivery?: Delivery;
|
|
9
|
+
/** Codec used to encode/decode state values. @default jsonCodec() */
|
|
10
|
+
codec?: Codec<T>;
|
|
11
|
+
/**
|
|
12
|
+
* Optional initial local state. Validated synchronously (throws `RangeError` if encoded payload exceeds
|
|
13
|
+
* the 16 KiB packet limit, or `TypeError` if `codec.encode` fails) and broadcast reliably to currently
|
|
14
|
+
* connected and future peers.
|
|
15
|
+
*/
|
|
16
|
+
initial?: T;
|
|
17
|
+
/** Automatically retry sending the latest state on `room.onDrain` when `send()` returns `'busy'`. @default true */
|
|
18
|
+
coalesce?: boolean;
|
|
19
|
+
}
|
|
20
|
+
/** Single-writer per-peer replicated state store with `u32` ordering, auto-hydration, and `onDrain` coalescing. */
|
|
21
|
+
export interface PeerState<T> {
|
|
22
|
+
/** Logical channel name used by this state store. */
|
|
23
|
+
readonly name: string;
|
|
24
|
+
/** Delivery mode configured for live `set()` updates. */
|
|
25
|
+
readonly delivery: Delivery;
|
|
26
|
+
/** Return your own current local state (`undefined` if never set or cleared). */
|
|
27
|
+
getSelf(): T | undefined;
|
|
28
|
+
/** Return a connected remote peer's latest state (`undefined` if unknown, cleared, or disconnected). */
|
|
29
|
+
get(peerId: string): T | undefined;
|
|
30
|
+
/** Return a fresh `ReadonlyMap<string, T>` snapshot of all remote peers with active state. */
|
|
31
|
+
getAll(): ReadonlyMap<string, T>;
|
|
32
|
+
/**
|
|
33
|
+
* Update your own state and broadcast it synchronously. Returns per-peer `SendResult`.
|
|
34
|
+
* Throws `Error` if closed, `TypeError` if `value === undefined` (use `clear()`),
|
|
35
|
+
* or `RangeError` if the encoded payload exceeds the 16 KiB packet limit.
|
|
36
|
+
*/
|
|
37
|
+
set(value: T): ReadonlyMap<string, SendResult>;
|
|
38
|
+
/**
|
|
39
|
+
* Clear your own state (`undefined`) and broadcast the removal reliably to connected peers.
|
|
40
|
+
* Throws `Error` if closed.
|
|
41
|
+
*/
|
|
42
|
+
clear(): ReadonlyMap<string, SendResult>;
|
|
43
|
+
/**
|
|
44
|
+
* Subscribe to remote peer state updates and removals (`next` is `undefined` when cleared or when the peer leaves).
|
|
45
|
+
* Returns an idempotent unsubscribe function.
|
|
46
|
+
*/
|
|
47
|
+
onChange(fn: (peerId: string, next: T | undefined, prev: T | undefined) => void, options?: ListenOptions): () => void;
|
|
48
|
+
/** Detach internal room listeners without broadcasting a clear frame (also runs automatically on `room.leave()`). */
|
|
49
|
+
close(): void;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Create a single-writer per-peer state synchronization store over a named logical channel.
|
|
53
|
+
* Filters out-of-order updates via RFC 1982 `u32` sequence numbers, hydrates state reliably
|
|
54
|
+
* on `room.onPeerJoin`, cleans up on `room.onPeerLeave`, and optionally coalesces `'busy'` updates on `room.onDrain`.
|
|
55
|
+
*/
|
|
56
|
+
export declare function createPeerState<T = unknown>(room: Room, name: string, options?: PeerStateOptions<T>): PeerState<T>;
|