Node-Red configuration
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

decodePacket.browser.js 1.9KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import { ERROR_PACKET, PACKET_TYPES_REVERSE, } from "./commons.js";
  2. import { decode } from "./contrib/base64-arraybuffer.js";
  3. const withNativeArrayBuffer = typeof ArrayBuffer === "function";
  4. export 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. 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. };