index.js 1.2 KB

1234567891011121314151617181920212223242526272829303132
  1. import encodePacket from "./encodePacket.js";
  2. import decodePacket from "./decodePacket.js";
  3. const SEPARATOR = String.fromCharCode(30); // see https://en.wikipedia.org/wiki/Delimiter#ASCII_delimited_text
  4. const encodePayload = (packets, callback) => {
  5. // some packets may be added to the array while encoding, so the initial length must be saved
  6. const length = packets.length;
  7. const encodedPackets = new Array(length);
  8. let count = 0;
  9. packets.forEach((packet, i) => {
  10. // force base64 encoding for binary packets
  11. encodePacket(packet, false, encodedPacket => {
  12. encodedPackets[i] = encodedPacket;
  13. if (++count === length) {
  14. callback(encodedPackets.join(SEPARATOR));
  15. }
  16. });
  17. });
  18. };
  19. const decodePayload = (encodedPayload, binaryType) => {
  20. const encodedPackets = encodedPayload.split(SEPARATOR);
  21. const packets = [];
  22. for (let i = 0; i < encodedPackets.length; i++) {
  23. const decodedPacket = decodePacket(encodedPackets[i], binaryType);
  24. packets.push(decodedPacket);
  25. if (decodedPacket.type === "error") {
  26. break;
  27. }
  28. }
  29. return packets;
  30. };
  31. export const protocol = 4;
  32. export { encodePacket, encodePayload, decodePacket, decodePayload };