UNPKG

1.93 kBJavaScriptView Raw
1import { ERROR_PACKET, PACKET_TYPES_REVERSE, } from "./commons.js";
2import { decode } from "./contrib/base64-arraybuffer.js";
3const withNativeArrayBuffer = typeof ArrayBuffer === "function";
4export 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};
31const 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};
40const mapBinary = (data, binaryType) => {
41 switch (binaryType) {
42 case "blob":
43 if (data instanceof Blob) {
44 // from WebSocket + binaryType "blob"
45 return data;
46 }
47 else {
48 // from HTTP long-polling or WebTransport
49 return new Blob([data]);
50 }
51 case "arraybuffer":
52 default:
53 if (data instanceof ArrayBuffer) {
54 // from HTTP long-polling (base64) or WebSocket + binaryType "arraybuffer"
55 return data;
56 }
57 else {
58 // from WebTransport (Uint8Array)
59 return data.buffer;
60 }
61 }
62};