decodePacket.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. const commons_js_1 = require("./commons.js");
  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. const buffer = Buffer.from(encodedPacket.substring(1), "base64");
  14. return {
  15. type: "message",
  16. data: mapBinary(buffer, binaryType)
  17. };
  18. }
  19. if (!commons_js_1.PACKET_TYPES_REVERSE[type]) {
  20. return commons_js_1.ERROR_PACKET;
  21. }
  22. return encodedPacket.length > 1
  23. ? {
  24. type: commons_js_1.PACKET_TYPES_REVERSE[type],
  25. data: encodedPacket.substring(1)
  26. }
  27. : {
  28. type: commons_js_1.PACKET_TYPES_REVERSE[type]
  29. };
  30. };
  31. const mapBinary = (data, binaryType) => {
  32. const isBuffer = Buffer.isBuffer(data);
  33. switch (binaryType) {
  34. case "arraybuffer":
  35. return isBuffer ? toArrayBuffer(data) : data;
  36. case "nodebuffer":
  37. default:
  38. return data; // assuming the data is already a Buffer
  39. }
  40. };
  41. const toArrayBuffer = (buffer) => {
  42. const arrayBuffer = new ArrayBuffer(buffer.length);
  43. const view = new Uint8Array(arrayBuffer);
  44. for (let i = 0; i < buffer.length; i++) {
  45. view[i] = buffer[i];
  46. }
  47. return arrayBuffer;
  48. };
  49. exports.default = decodePacket;