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