UNPKG

2.26 kBJavaScriptView Raw
1import { PACKET_TYPES } from "./commons.js";
2const withNativeBlob = typeof Blob === "function" ||
3 (typeof Blob !== "undefined" &&
4 Object.prototype.toString.call(Blob) === "[object BlobConstructor]");
5const withNativeArrayBuffer = typeof ArrayBuffer === "function";
6// ArrayBuffer.isView method is not defined in IE10
7const isView = (obj) => {
8 return typeof ArrayBuffer.isView === "function"
9 ? ArrayBuffer.isView(obj)
10 : obj && obj.buffer instanceof ArrayBuffer;
11};
12const encodePacket = ({ type, data }, supportsBinary, callback) => {
13 if (withNativeBlob && data instanceof Blob) {
14 if (supportsBinary) {
15 return callback(data);
16 }
17 else {
18 return encodeBlobAsBase64(data, callback);
19 }
20 }
21 else if (withNativeArrayBuffer &&
22 (data instanceof ArrayBuffer || isView(data))) {
23 if (supportsBinary) {
24 return callback(data);
25 }
26 else {
27 return encodeBlobAsBase64(new Blob([data]), callback);
28 }
29 }
30 // plain string
31 return callback(PACKET_TYPES[type] + (data || ""));
32};
33const encodeBlobAsBase64 = (data, callback) => {
34 const fileReader = new FileReader();
35 fileReader.onload = function () {
36 const content = fileReader.result.split(",")[1];
37 callback("b" + (content || ""));
38 };
39 return fileReader.readAsDataURL(data);
40};
41function toArray(data) {
42 if (data instanceof Uint8Array) {
43 return data;
44 }
45 else if (data instanceof ArrayBuffer) {
46 return new Uint8Array(data);
47 }
48 else {
49 return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
50 }
51}
52let TEXT_ENCODER;
53export function encodePacketToBinary(packet, callback) {
54 if (withNativeBlob && packet.data instanceof Blob) {
55 return packet.data.arrayBuffer().then(toArray).then(callback);
56 }
57 else if (withNativeArrayBuffer &&
58 (packet.data instanceof ArrayBuffer || isView(packet.data))) {
59 return callback(toArray(packet.data));
60 }
61 encodePacket(packet, false, (encoded) => {
62 if (!TEXT_ENCODER) {
63 TEXT_ENCODER = new TextEncoder();
64 }
65 callback(TEXT_ENCODER.encode(encoded));
66 });
67}
68export { encodePacket };