1 | const { PACKET_TYPES_REVERSE, ERROR_PACKET } = require("./commons");
|
---|
2 |
|
---|
3 | const withNativeArrayBuffer = typeof ArrayBuffer === "function";
|
---|
4 |
|
---|
5 | let base64decoder;
|
---|
6 | if (withNativeArrayBuffer) {
|
---|
7 | base64decoder = require("base64-arraybuffer");
|
---|
8 | }
|
---|
9 |
|
---|
10 | const decodePacket = (encodedPacket, binaryType) => {
|
---|
11 | if (typeof encodedPacket !== "string") {
|
---|
12 | return {
|
---|
13 | type: "message",
|
---|
14 | data: mapBinary(encodedPacket, binaryType)
|
---|
15 | };
|
---|
16 | }
|
---|
17 | const type = encodedPacket.charAt(0);
|
---|
18 | if (type === "b") {
|
---|
19 | return {
|
---|
20 | type: "message",
|
---|
21 | data: decodeBase64Packet(encodedPacket.substring(1), binaryType)
|
---|
22 | };
|
---|
23 | }
|
---|
24 | const packetType = PACKET_TYPES_REVERSE[type];
|
---|
25 | if (!packetType) {
|
---|
26 | return ERROR_PACKET;
|
---|
27 | }
|
---|
28 | return encodedPacket.length > 1
|
---|
29 | ? {
|
---|
30 | type: PACKET_TYPES_REVERSE[type],
|
---|
31 | data: encodedPacket.substring(1)
|
---|
32 | }
|
---|
33 | : {
|
---|
34 | type: PACKET_TYPES_REVERSE[type]
|
---|
35 | };
|
---|
36 | };
|
---|
37 |
|
---|
38 | const decodeBase64Packet = (data, binaryType) => {
|
---|
39 | if (base64decoder) {
|
---|
40 | const decoded = base64decoder.decode(data);
|
---|
41 | return mapBinary(decoded, binaryType);
|
---|
42 | } else {
|
---|
43 | return { base64: true, data }; // fallback for old browsers
|
---|
44 | }
|
---|
45 | };
|
---|
46 |
|
---|
47 | const mapBinary = (data, binaryType) => {
|
---|
48 | switch (binaryType) {
|
---|
49 | case "blob":
|
---|
50 | return data instanceof ArrayBuffer ? new Blob([data]) : data;
|
---|
51 | case "arraybuffer":
|
---|
52 | default:
|
---|
53 | return data; // assuming the data is already an ArrayBuffer
|
---|
54 | }
|
---|
55 | };
|
---|
56 |
|
---|
57 | module.exports = decodePacket;
|
---|