@tianacloud/dsh-remote 0.0.0-stage → 0.2.1

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.
@@ -0,0 +1,496 @@
1
+ import { createHash, randomBytes } from 'node:crypto';
2
+ import { request as httpRequest } from 'node:http';
3
+ import { request as httpsRequest } from 'node:https';
4
+ import { isIP } from 'node:net';
5
+ import { networkInterfaces } from 'node:os';
6
+ import { Readable } from 'node:stream';
7
+
8
+ const WS_GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
9
+ const MAX_LOCAL_WS_MESSAGE = 32 * 1024 * 1024;
10
+
11
+ export function isOwnedLocalAddress(host) {
12
+ if (!host || typeof host !== 'string') return false;
13
+ const bare = host.startsWith('[') && host.endsWith(']') ? host.slice(1, -1) : host;
14
+ if (bare === '127.0.0.1' || bare === '::1' || bare === 'localhost') return true;
15
+ if (!isIP(bare)) return false;
16
+ return Object.values(networkInterfaces()).flat().some((entry) => entry?.address === bare);
17
+ }
18
+
19
+ function defaultPort(protocol) {
20
+ return protocol === 'https:' ? 443 : 80;
21
+ }
22
+
23
+ function normalizeConnectHost(hostname) {
24
+ const bare = hostname.startsWith('[') && hostname.endsWith(']') ? hostname.slice(1, -1) : hostname;
25
+ return bare === 'localhost' ? '127.0.0.1' : bare;
26
+ }
27
+
28
+ export function resolvePinnedEndpoint(origin, inProcess = null) {
29
+ if (inProcess) {
30
+ const { listenOrigin, boundHost, advertisedOrigin } = inProcess;
31
+ if (!isOwnedLocalAddress(boundHost)) {
32
+ throw new Error('DSH listener address is not owned by this host');
33
+ }
34
+ const listenUrl = new URL(listenOrigin);
35
+ if (!['http:', 'https:'].includes(listenUrl.protocol) || listenUrl.username || listenUrl.password) {
36
+ throw new Error('Invalid local DSH listener origin');
37
+ }
38
+ const connectHost = normalizeConnectHost(boundHost);
39
+ if (!isIP(connectHost)) throw new Error('Pinned DSH listener host must be an IP literal');
40
+ const connectPort = Number(listenUrl.port) || defaultPort(listenUrl.protocol);
41
+
42
+ let authorityUrl = listenUrl;
43
+ if (advertisedOrigin) {
44
+ try {
45
+ const adv = new URL(advertisedOrigin);
46
+ const advPort = Number(adv.port) || defaultPort(adv.protocol);
47
+ if (adv.protocol === listenUrl.protocol && advPort === connectPort &&
48
+ !adv.username && !adv.password && adv.pathname === '/' && !adv.search && !adv.hash) {
49
+ authorityUrl = adv;
50
+ }
51
+ } catch {
52
+ // Ignore malformed advertised URL and stay on the bound listener origin.
53
+ }
54
+ }
55
+ const advHostBare = normalizeConnectHost(authorityUrl.hostname);
56
+ return {
57
+ protocol: listenUrl.protocol,
58
+ connectHost,
59
+ connectPort,
60
+ authorityOrigin: authorityUrl.origin,
61
+ hostHeader: authorityUrl.host,
62
+ servername: isIP(advHostBare) ? '' : advHostBare,
63
+ };
64
+ }
65
+
66
+ const base = new URL(origin);
67
+ if (!['http:', 'https:'].includes(base.protocol) || base.username || base.password ||
68
+ !['127.0.0.1', '[::1]', 'localhost'].includes(base.hostname)) {
69
+ throw new Error('DSH must use a loopback HTTP origin');
70
+ }
71
+ const connectHost = normalizeConnectHost(base.hostname);
72
+ const connectPort = Number(base.port) || defaultPort(base.protocol);
73
+ return {
74
+ protocol: base.protocol,
75
+ connectHost,
76
+ connectPort,
77
+ authorityOrigin: base.origin,
78
+ hostHeader: base.host,
79
+ servername: base.hostname === 'localhost' ? 'localhost' : '',
80
+ };
81
+ }
82
+
83
+ export function resolvePinnedTarget(endpoint, pathAndQuery) {
84
+ if (typeof pathAndQuery !== 'string' || !pathAndQuery.startsWith('/') ||
85
+ pathAndQuery.startsWith('//') || /[\\#\u0000-\u0020\u007f]/u.test(pathAndQuery)) {
86
+ throw new Error('Invalid DSH request path');
87
+ }
88
+ const target = new URL(pathAndQuery, endpoint.authorityOrigin);
89
+ if (target.origin !== endpoint.authorityOrigin || target.username || target.password) {
90
+ throw new Error('DSH request must stay on the local origin');
91
+ }
92
+ return target;
93
+ }
94
+
95
+ function pinnedLookup(connectHost) {
96
+ const family = isIP(connectHost) || 4;
97
+ return (_hostname, options, callback) => {
98
+ if (typeof options === 'function') {
99
+ options(null, connectHost, family);
100
+ return;
101
+ }
102
+ if (options?.all) {
103
+ callback(null, [{ address: connectHost, family }]);
104
+ return;
105
+ }
106
+ callback(null, connectHost, family);
107
+ };
108
+ }
109
+
110
+ export function pinnedFetch(endpoint, pathAndQuery, { method = 'GET', headers = {}, body, signal } = {}) {
111
+ const target = resolvePinnedTarget(endpoint, pathAndQuery);
112
+ const reqFn = endpoint.protocol === 'https:' ? httpsRequest : httpRequest;
113
+ const outHeaders = {};
114
+ if (headers instanceof Headers) {
115
+ headers.forEach((value, key) => { outHeaders[key] = value; });
116
+ } else {
117
+ Object.assign(outHeaders, headers);
118
+ }
119
+ outHeaders.host = endpoint.hostHeader;
120
+ if (body !== undefined && outHeaders['content-length'] === undefined) {
121
+ outHeaders['content-length'] = String(Buffer.byteLength(body));
122
+ }
123
+
124
+ return new Promise((resolve, reject) => {
125
+ const abortReason = () => (signal?.reason instanceof Error ? signal.reason : new Error('Aborted'));
126
+ if (signal?.aborted) {
127
+ reject(abortReason());
128
+ return;
129
+ }
130
+ const req = reqFn({
131
+ protocol: endpoint.protocol,
132
+ host: endpoint.connectHost,
133
+ port: endpoint.connectPort,
134
+ servername: endpoint.servername || undefined,
135
+ lookup: pinnedLookup(endpoint.connectHost),
136
+ agent: false,
137
+ method,
138
+ path: target.pathname + target.search,
139
+ headers: outHeaders,
140
+ });
141
+ let currentRes = null;
142
+ let settled = false;
143
+ const cleanupAbort = () => {
144
+ signal?.removeEventListener('abort', onAbort);
145
+ };
146
+ const onAbort = () => {
147
+ const err = abortReason();
148
+ req.destroy(err);
149
+ if (currentRes && !currentRes.destroyed) {
150
+ currentRes.destroy(err);
151
+ }
152
+ };
153
+ signal?.addEventListener('abort', onAbort, { once: true });
154
+
155
+ req.on('error', (err) => {
156
+ cleanupAbort();
157
+ if (!settled) {
158
+ settled = true;
159
+ reject(err);
160
+ }
161
+ });
162
+ req.once('response', (res) => {
163
+ currentRes = res;
164
+ if (signal?.aborted) {
165
+ cleanupAbort();
166
+ const err = abortReason();
167
+ req.destroy(err);
168
+ res.destroy(err);
169
+ if (!settled) {
170
+ settled = true;
171
+ reject(err);
172
+ }
173
+ return;
174
+ }
175
+ const resHeaders = new Headers();
176
+ for (const [key, value] of Object.entries(res.headers)) {
177
+ if (value === undefined) continue;
178
+ if (Array.isArray(value)) {
179
+ for (const item of value) resHeaders.append(key, item);
180
+ } else {
181
+ resHeaders.set(key, value);
182
+ }
183
+ }
184
+ const status = res.statusCode || 502;
185
+ const noBody = method === 'HEAD' || status === 204 || status === 205 || status === 304;
186
+ if (noBody) {
187
+ cleanupAbort();
188
+ res.resume();
189
+ settled = true;
190
+ resolve({
191
+ ok: status >= 200 && status < 300,
192
+ status,
193
+ statusText: res.statusMessage || '',
194
+ headers: resHeaders,
195
+ body: null,
196
+ text: async () => '',
197
+ });
198
+ return;
199
+ }
200
+ res.once('end', cleanupAbort);
201
+ res.once('close', cleanupAbort);
202
+ res.once('error', cleanupAbort);
203
+ const webBody = Readable.toWeb(res);
204
+ settled = true;
205
+ resolve({
206
+ ok: status >= 200 && status < 300,
207
+ status,
208
+ statusText: res.statusMessage || '',
209
+ headers: resHeaders,
210
+ body: webBody,
211
+ async text() {
212
+ const chunks = [];
213
+ for await (const chunk of res) chunks.push(Buffer.from(chunk));
214
+ return Buffer.concat(chunks).toString('utf8');
215
+ },
216
+ });
217
+ });
218
+
219
+ if (body !== undefined && method !== 'GET' && method !== 'HEAD') {
220
+ req.end(body);
221
+ } else {
222
+ req.end();
223
+ }
224
+ });
225
+ }
226
+
227
+ function encodeMaskedWsFrame(opcode, payload) {
228
+ const body = Buffer.isBuffer(payload) ? payload : Buffer.from(payload);
229
+ const len = body.length;
230
+ let headerLen = 2;
231
+ if (len >= 126 && len <= 65535) headerLen = 4;
232
+ else if (len > 65535) headerLen = 10;
233
+ const out = Buffer.allocUnsafe(headerLen + 4 + len);
234
+ out[0] = 0x80 | (opcode & 0x0f);
235
+ if (len < 126) {
236
+ out[1] = 0x80 | len;
237
+ } else if (len <= 65535) {
238
+ out[1] = 0x80 | 126;
239
+ out.writeUInt16BE(len, 2);
240
+ } else {
241
+ out[1] = 0x80 | 127;
242
+ out.writeBigUInt64BE(BigInt(len), 2);
243
+ }
244
+ const mask = randomBytes(4);
245
+ mask.copy(out, headerLen);
246
+ const dataOffset = headerLen + 4;
247
+ for (let i = 0; i < len; i++) {
248
+ out[dataOffset + i] = body[i] ^ mask[i & 3];
249
+ }
250
+ return out;
251
+ }
252
+
253
+ export function openPinnedWebSocket(endpoint, pathAndQuery, { headers = {} } = {}) {
254
+ const target = resolvePinnedTarget(endpoint, pathAndQuery);
255
+ const reqFn = endpoint.protocol === 'https:' ? httpsRequest : httpRequest;
256
+ const wsKey = randomBytes(16).toString('base64');
257
+ const expectedAccept = createHash('sha1').update(wsKey + WS_GUID).digest('base64');
258
+
259
+ const events = new EventTarget();
260
+ let readyState = 0; // CONNECTING
261
+ let netSocket = null;
262
+ let protocol = '';
263
+ let closeEmitted = false;
264
+
265
+ const emitClose = (code = 1006, reason = '', wasClean = false) => {
266
+ if (closeEmitted) return;
267
+ closeEmitted = true;
268
+ readyState = 3;
269
+ const ev = new Event('close');
270
+ Object.assign(ev, { code, reason, wasClean });
271
+ events.dispatchEvent(ev);
272
+ };
273
+
274
+ let failed = false;
275
+ const fail = () => {
276
+ if (failed) return;
277
+ failed = true;
278
+ events.dispatchEvent(new Event('error'));
279
+ netSocket?.destroy();
280
+ req.destroy();
281
+ emitClose(1006, '', false);
282
+ };
283
+
284
+ const req = reqFn({
285
+ protocol: endpoint.protocol,
286
+ host: endpoint.connectHost,
287
+ port: endpoint.connectPort,
288
+ servername: endpoint.servername || undefined,
289
+ lookup: pinnedLookup(endpoint.connectHost),
290
+ agent: false,
291
+ method: 'GET',
292
+ path: target.pathname + target.search,
293
+ headers: {
294
+ ...headers,
295
+ Host: endpoint.hostHeader,
296
+ Connection: 'Upgrade',
297
+ Upgrade: 'websocket',
298
+ 'Sec-WebSocket-Version': '13',
299
+ 'Sec-WebSocket-Key': wsKey,
300
+ },
301
+ });
302
+
303
+ req.once('response', (res) => {
304
+ res.resume();
305
+ fail();
306
+ });
307
+ req.on('error', fail);
308
+
309
+ req.once('upgrade', (res, socket, head) => {
310
+ const accept = String(res.headers['sec-websocket-accept'] || '').trim();
311
+ if (res.statusCode !== 101 || accept !== expectedAccept) {
312
+ socket.destroy();
313
+ fail(new Error('Invalid WebSocket upgrade'));
314
+ return;
315
+ }
316
+ netSocket = socket;
317
+ socket.setNoDelay(true);
318
+ protocol = String(res.headers['sec-websocket-protocol'] || '').trim();
319
+ readyState = 1; // OPEN
320
+
321
+ let buffer = head?.length ? Buffer.from(head) : Buffer.alloc(0);
322
+ let fragOpcode = 0;
323
+ let fragChunks = [];
324
+ let fragBytes = 0;
325
+
326
+ const parseLoop = () => {
327
+ while (buffer.length >= 2 && readyState <= 2) {
328
+ const b0 = buffer[0];
329
+ const b1 = buffer[1];
330
+ const fin = (b0 & 0x80) !== 0;
331
+ const opcode = b0 & 0x0f;
332
+ const masked = (b1 & 0x80) !== 0;
333
+ if ((b0 & 0x70) !== 0) {
334
+ fail(new Error('Invalid WS RSV bits'));
335
+ return;
336
+ }
337
+ let offset = 2;
338
+ let len = b1 & 0x7f;
339
+ if (len === 126) {
340
+ if (buffer.length < 4) return;
341
+ len = buffer.readUInt16BE(2);
342
+ offset = 4;
343
+ } else if (len === 127) {
344
+ if (buffer.length < 10) return;
345
+ const big = buffer.readBigUInt64BE(2);
346
+ if (big > BigInt(MAX_LOCAL_WS_MESSAGE)) {
347
+ fail(new Error('WS frame exceeds limit'));
348
+ return;
349
+ }
350
+ len = Number(big);
351
+ offset = 10;
352
+ }
353
+ if (len > MAX_LOCAL_WS_MESSAGE) {
354
+ fail(new Error('WS frame exceeds limit'));
355
+ return;
356
+ }
357
+ if (masked) {
358
+ if (buffer.length < offset + 4 + len) return;
359
+ } else if (buffer.length < offset + len) {
360
+ return;
361
+ }
362
+ let payload;
363
+ if (masked) {
364
+ const mask = buffer.subarray(offset, offset + 4);
365
+ offset += 4;
366
+ payload = Buffer.from(buffer.subarray(offset, offset + len));
367
+ for (let i = 0; i < len; i++) payload[i] ^= mask[i & 3];
368
+ } else {
369
+ payload = buffer.subarray(offset, offset + len);
370
+ }
371
+ buffer = buffer.subarray(offset + len);
372
+
373
+ if (opcode >= 0x08) {
374
+ if (!fin || len > 125) {
375
+ fail(new Error('Invalid WS control frame'));
376
+ return;
377
+ }
378
+ if (opcode === 0x08) {
379
+ let code = 1000;
380
+ let reason = '';
381
+ if (payload.length >= 2) {
382
+ code = payload.readUInt16BE(0);
383
+ reason = payload.subarray(2).toString('utf8');
384
+ }
385
+ if (readyState === 1) {
386
+ readyState = 2;
387
+ const reply = Buffer.allocUnsafe(2);
388
+ reply.writeUInt16BE(code, 0);
389
+ socket.write(encodeMaskedWsFrame(0x08, reply));
390
+ }
391
+ socket.end();
392
+ emitClose(code, reason, true);
393
+ return;
394
+ }
395
+ if (opcode === 0x09 && readyState === 1) {
396
+ socket.write(encodeMaskedWsFrame(0x0a, payload));
397
+ }
398
+ continue;
399
+ }
400
+
401
+ if (opcode === 0x00) {
402
+ if (!fragOpcode) {
403
+ fail(new Error('Unexpected WS continuation'));
404
+ return;
405
+ }
406
+ } else if (opcode === 0x01 || opcode === 0x02) {
407
+ if (fragOpcode) {
408
+ fail(new Error('Interleaved WS data frame'));
409
+ return;
410
+ }
411
+ fragOpcode = opcode;
412
+ } else {
413
+ fail(new Error('Unsupported WS opcode'));
414
+ return;
415
+ }
416
+
417
+ fragBytes += payload.length;
418
+ if (fragBytes > MAX_LOCAL_WS_MESSAGE) {
419
+ fail(new Error('WS message exceeds limit'));
420
+ return;
421
+ }
422
+ fragChunks.push(Buffer.from(payload));
423
+
424
+ if (fin) {
425
+ const full = fragChunks.length === 1 ? fragChunks[0] : Buffer.concat(fragChunks, fragBytes);
426
+ const msgOp = fragOpcode;
427
+ fragOpcode = 0;
428
+ fragChunks = [];
429
+ fragBytes = 0;
430
+ const ev = new Event('message');
431
+ if (msgOp === 0x01) {
432
+ ev.data = full.toString('utf8');
433
+ } else {
434
+ ev.data = full.buffer.slice(full.byteOffset, full.byteOffset + full.byteLength);
435
+ }
436
+ events.dispatchEvent(ev);
437
+ }
438
+ }
439
+ };
440
+
441
+ socket.on('data', (chunk) => {
442
+ buffer = buffer.length === 0 ? chunk : Buffer.concat([buffer, chunk]);
443
+ parseLoop();
444
+ });
445
+ socket.on('error', () => {
446
+ events.dispatchEvent(new Event('error'));
447
+ });
448
+ socket.on('close', () => {
449
+ emitClose(1006, '', false);
450
+ });
451
+
452
+ events.dispatchEvent(new Event('open'));
453
+ if (buffer.length > 0) parseLoop();
454
+ });
455
+
456
+ req.end();
457
+
458
+ return {
459
+ binaryType: 'arraybuffer',
460
+ get readyState() { return readyState; },
461
+ get protocol() { return protocol; },
462
+ get bufferedAmount() { return netSocket?.writableLength ?? 0; },
463
+ addEventListener: events.addEventListener.bind(events),
464
+ removeEventListener: events.removeEventListener.bind(events),
465
+ send(data) {
466
+ if (readyState !== 1 || !netSocket) throw new Error('WebSocket is not open');
467
+ if (typeof data === 'string') {
468
+ netSocket.write(encodeMaskedWsFrame(0x01, Buffer.from(data, 'utf8')));
469
+ } else if (data instanceof ArrayBuffer) {
470
+ netSocket.write(encodeMaskedWsFrame(0x02, Buffer.from(data)));
471
+ } else if (ArrayBuffer.isView(data)) {
472
+ netSocket.write(encodeMaskedWsFrame(0x02, Buffer.from(data.buffer, data.byteOffset, data.byteLength)));
473
+ } else {
474
+ throw new TypeError('Unsupported WebSocket payload');
475
+ }
476
+ },
477
+ close(code = 1000, reason = '') {
478
+ if (readyState === 3) return;
479
+ if (readyState === 0) {
480
+ readyState = 3;
481
+ req.destroy();
482
+ emitClose(code, reason, false);
483
+ return;
484
+ }
485
+ if (readyState === 1 && netSocket) {
486
+ readyState = 2;
487
+ const validCode = (code === 1000 || (code >= 3000 && code <= 4999)) ? code : 1000;
488
+ const reasonBytes = Buffer.from(String(reason || '').slice(0, 100), 'utf8');
489
+ const payload = Buffer.allocUnsafe(2 + reasonBytes.length);
490
+ payload.writeUInt16BE(validCode, 0);
491
+ reasonBytes.copy(payload, 2);
492
+ netSocket.write(encodeMaskedWsFrame(0x08, payload), () => netSocket?.end());
493
+ }
494
+ },
495
+ };
496
+ }
@@ -0,0 +1,124 @@
1
+ /**
2
+ * Shared binary frame codec for dsh-remote.
3
+ *
4
+ * Host <-> Relay WebSocket frames:
5
+ * [4B uint32BE sessionId][4B uint32BE streamId][1B uint8 msgType][payload]
6
+ *
7
+ * Client <-> Relay WebSocket frames:
8
+ * [4B uint32BE streamId][1B uint8 msgType][payload]
9
+ */
10
+
11
+ export const MSG_CONTROL_JSON = 0x01;
12
+
13
+ export const MSG_HTTP_REQ_HEAD = 0x10;
14
+ export const MSG_HTTP_REQ_BODY = 0x11;
15
+ export const MSG_HTTP_REQ_END = 0x12;
16
+ export const MSG_HTTP_RES_HEAD = 0x13;
17
+ export const MSG_HTTP_RES_BODY = 0x14;
18
+ export const MSG_HTTP_RES_END = 0x15;
19
+ export const MSG_HTTP_ABORT = 0x16;
20
+ export const MSG_HTTP_RES_WINDOW = 0x17;
21
+
22
+ export const MSG_WS_OPEN = 0x20;
23
+ export const MSG_WS_OPENED = 0x21;
24
+ export const MSG_WS_DATA_TEXT = 0x22;
25
+ export const MSG_WS_DATA_BIN = 0x23;
26
+ export const MSG_WS_CLOSE = 0x24;
27
+
28
+ export {
29
+ MSG_E2EE_BOX,
30
+ MSG_E2EE_CLIENT_HELLO,
31
+ MSG_E2EE_ERROR,
32
+ MSG_E2EE_HOST_HELLO,
33
+ } from '../web-src/e2ee.js';
34
+
35
+ const textEncoder = new TextEncoder();
36
+ const textDecoder = new TextDecoder();
37
+
38
+ export function encodeWindowUpdate(creditBytes) {
39
+ if (!Number.isSafeInteger(creditBytes) || creditBytes <= 0 || creditBytes > 0xffffffff) {
40
+ throw new RangeError(`Invalid window credit bytes: ${creditBytes}`);
41
+ }
42
+ const out = new Uint8Array(4);
43
+ new DataView(out.buffer).setUint32(0, creditBytes >>> 0, false);
44
+ return out;
45
+ }
46
+
47
+ export function decodeWindowUpdate(data) {
48
+ const bytes = toBytes(data);
49
+ if (bytes.byteLength !== 4) {
50
+ throw new Error(`Invalid window update frame length: ${bytes.byteLength}`);
51
+ }
52
+ return new DataView(bytes.buffer, bytes.byteOffset, 4).getUint32(0, false);
53
+ }
54
+
55
+ export function encodeHostFrame(sessionId, streamId, msgType, payload) {
56
+ const body = toBytes(payload);
57
+ const out = new Uint8Array(9 + body.byteLength);
58
+ const view = new DataView(out.buffer);
59
+ view.setUint32(0, sessionId >>> 0, false);
60
+ view.setUint32(4, streamId >>> 0, false);
61
+ out[8] = msgType & 0xff;
62
+ if (body.byteLength > 0) {
63
+ out.set(body, 9);
64
+ }
65
+ return out;
66
+ }
67
+
68
+ export function decodeHostFrame(data) {
69
+ const bytes = toBytes(data);
70
+ if (bytes.byteLength < 9) {
71
+ throw new Error(`Invalid host frame length: ${bytes.byteLength}`);
72
+ }
73
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
74
+ return {
75
+ sessionId: view.getUint32(0, false),
76
+ streamId: view.getUint32(4, false),
77
+ msgType: bytes[8],
78
+ payload: bytes.subarray(9),
79
+ };
80
+ }
81
+
82
+ export function encodeClientFrame(streamId, msgType, payload) {
83
+ const body = toBytes(payload);
84
+ const out = new Uint8Array(5 + body.byteLength);
85
+ const view = new DataView(out.buffer);
86
+ view.setUint32(0, streamId >>> 0, false);
87
+ out[4] = msgType & 0xff;
88
+ if (body.byteLength > 0) {
89
+ out.set(body, 5);
90
+ }
91
+ return out;
92
+ }
93
+
94
+ export function decodeClientFrame(data) {
95
+ const bytes = toBytes(data);
96
+ if (bytes.byteLength < 5) {
97
+ throw new Error(`Invalid client frame length: ${bytes.byteLength}`);
98
+ }
99
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
100
+ return {
101
+ streamId: view.getUint32(0, false),
102
+ msgType: bytes[4],
103
+ payload: bytes.subarray(5),
104
+ };
105
+ }
106
+
107
+ export function encodeJSON(value) {
108
+ return textEncoder.encode(JSON.stringify(value));
109
+ }
110
+
111
+ export function decodeJSON(bytes) {
112
+ return JSON.parse(textDecoder.decode(bytes));
113
+ }
114
+
115
+ export function toBytes(value) {
116
+ if (value === undefined || value === null) return new Uint8Array(0);
117
+ if (value instanceof Uint8Array) return value;
118
+ if (value instanceof ArrayBuffer) return new Uint8Array(value);
119
+ if (ArrayBuffer.isView(value)) {
120
+ return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
121
+ }
122
+ if (typeof value === 'string') return textEncoder.encode(value);
123
+ throw new TypeError(`Unsupported payload type: ${typeof value}`);
124
+ }