1 | import { PACKET_TYPES } from "./commons.js";
|
2 | export const encodePacket = ({ type, data }, supportsBinary, callback) => {
|
3 | if (data instanceof ArrayBuffer || ArrayBuffer.isView(data)) {
|
4 | return callback(supportsBinary ? data : "b" + toBuffer(data, true).toString("base64"));
|
5 | }
|
6 |
|
7 | return callback(PACKET_TYPES[type] + (data || ""));
|
8 | };
|
9 | const toBuffer = (data, forceBufferConversion) => {
|
10 | if (Buffer.isBuffer(data) ||
|
11 | (data instanceof Uint8Array && !forceBufferConversion)) {
|
12 | return data;
|
13 | }
|
14 | else if (data instanceof ArrayBuffer) {
|
15 | return Buffer.from(data);
|
16 | }
|
17 | else {
|
18 | return Buffer.from(data.buffer, data.byteOffset, data.byteLength);
|
19 | }
|
20 | };
|
21 | let TEXT_ENCODER;
|
22 | export function encodePacketToBinary(packet, callback) {
|
23 | if (packet.data instanceof ArrayBuffer || ArrayBuffer.isView(packet.data)) {
|
24 | return callback(toBuffer(packet.data, false));
|
25 | }
|
26 | encodePacket(packet, true, (encoded) => {
|
27 | if (!TEXT_ENCODER) {
|
28 |
|
29 | TEXT_ENCODER = new TextEncoder();
|
30 | }
|
31 | callback(TEXT_ENCODER.encode(encoded));
|
32 | });
|
33 | }
|