decodePacket.browser.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.decodePacket = void 0;
  4. const commons_js_1 = require("./commons.js");
  5. const base64_arraybuffer_js_1 = require("./contrib/base64-arraybuffer.js");
  6. const withNativeArrayBuffer = typeof ArrayBuffer === "function";
  7. const decodePacket = (encodedPacket, binaryType) => {
  8. if (typeof encodedPacket !== "string") {
  9. return {
  10. type: "message",
  11. data: mapBinary(encodedPacket, binaryType),
  12. };
  13. }
  14. const type = encodedPacket.charAt(0);
  15. if (type === "b") {
  16. return {
  17. type: "message",
  18. data: decodeBase64Packet(encodedPacket.substring(1), binaryType),
  19. };
  20. }
  21. const packetType = commons_js_1.PACKET_TYPES_REVERSE[type];
  22. if (!packetType) {
  23. return commons_js_1.ERROR_PACKET;
  24. }
  25. return encodedPacket.length > 1
  26. ? {
  27. type: commons_js_1.PACKET_TYPES_REVERSE[type],
  28. data: encodedPacket.substring(1),
  29. }
  30. : {
  31. type: commons_js_1.PACKET_TYPES_REVERSE[type],
  32. };
  33. };
  34. exports.decodePacket = decodePacket;
  35. const decodeBase64Packet = (data, binaryType) => {
  36. if (withNativeArrayBuffer) {
  37. const decoded = (0, base64_arraybuffer_js_1.decode)(data);
  38. return mapBinary(decoded, binaryType);
  39. }
  40. else {
  41. return { base64: true, data }; // fallback for old browsers
  42. }
  43. };
  44. const mapBinary = (data, binaryType) => {
  45. switch (binaryType) {
  46. case "blob":
  47. if (data instanceof Blob) {
  48. // from WebSocket + binaryType "blob"
  49. return data;
  50. }
  51. else {
  52. // from HTTP long-polling or WebTransport
  53. return new Blob([data]);
  54. }
  55. case "arraybuffer":
  56. default:
  57. if (data instanceof ArrayBuffer) {
  58. // from HTTP long-polling (base64) or WebSocket + binaryType "arraybuffer"
  59. return data;
  60. }
  61. else {
  62. // from WebTransport (Uint8Array)
  63. return data.buffer;
  64. }
  65. }
  66. };