UNPKG

1.2 kBJavaScriptView Raw
1import { PACKET_TYPES } from "./commons.js";
2export 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 // plain string
7 return callback(PACKET_TYPES[type] + (data || ""));
8};
9const 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};
21let TEXT_ENCODER;
22export 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 // lazily created for compatibility with Node.js 10
29 TEXT_ENCODER = new TextEncoder();
30 }
31 callback(TEXT_ENCODER.encode(encoded));
32 });
33}