decodePacket.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import { ERROR_PACKET, PACKET_TYPES_REVERSE, } from "./commons.js";
  2. export const decodePacket = (encodedPacket, binaryType) => {
  3. if (typeof encodedPacket !== "string") {
  4. return {
  5. type: "message",
  6. data: mapBinary(encodedPacket, binaryType),
  7. };
  8. }
  9. const type = encodedPacket.charAt(0);
  10. if (type === "b") {
  11. const buffer = Buffer.from(encodedPacket.substring(1), "base64");
  12. return {
  13. type: "message",
  14. data: mapBinary(buffer, binaryType),
  15. };
  16. }
  17. if (!PACKET_TYPES_REVERSE[type]) {
  18. return ERROR_PACKET;
  19. }
  20. return encodedPacket.length > 1
  21. ? {
  22. type: PACKET_TYPES_REVERSE[type],
  23. data: encodedPacket.substring(1),
  24. }
  25. : {
  26. type: PACKET_TYPES_REVERSE[type],
  27. };
  28. };
  29. const mapBinary = (data, binaryType) => {
  30. switch (binaryType) {
  31. case "arraybuffer":
  32. if (data instanceof ArrayBuffer) {
  33. // from WebSocket & binaryType "arraybuffer"
  34. return data;
  35. }
  36. else if (Buffer.isBuffer(data)) {
  37. // from HTTP long-polling
  38. return data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);
  39. }
  40. else {
  41. // from WebTransport (Uint8Array)
  42. return data.buffer;
  43. }
  44. case "nodebuffer":
  45. default:
  46. if (Buffer.isBuffer(data)) {
  47. // from HTTP long-polling or WebSocket & binaryType "nodebuffer" (default)
  48. return data;
  49. }
  50. else {
  51. // from WebTransport (Uint8Array)
  52. return Buffer.from(data);
  53. }
  54. }
  55. };