index.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. const encodePacket = require("./encodePacket");
  2. const decodePacket = require("./decodePacket");
  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. module.exports = {
  32. protocol: 4,
  33. encodePacket,
  34. encodePayload,
  35. decodePacket,
  36. decodePayload
  37. };