binary.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.reconstructPacket = exports.deconstructPacket = void 0;
  4. const is_binary_1 = require("./is-binary");
  5. /**
  6. * Replaces every Buffer | ArrayBuffer | Blob | File in packet with a numbered placeholder.
  7. *
  8. * @param {Object} packet - socket.io event packet
  9. * @return {Object} with deconstructed packet and list of buffers
  10. * @public
  11. */
  12. function deconstructPacket(packet) {
  13. const buffers = [];
  14. const packetData = packet.data;
  15. const pack = packet;
  16. pack.data = _deconstructPacket(packetData, buffers);
  17. pack.attachments = buffers.length; // number of binary 'attachments'
  18. return { packet: pack, buffers: buffers };
  19. }
  20. exports.deconstructPacket = deconstructPacket;
  21. function _deconstructPacket(data, buffers) {
  22. if (!data)
  23. return data;
  24. if (is_binary_1.isBinary(data)) {
  25. const placeholder = { _placeholder: true, num: buffers.length };
  26. buffers.push(data);
  27. return placeholder;
  28. }
  29. else if (Array.isArray(data)) {
  30. const newData = new Array(data.length);
  31. for (let i = 0; i < data.length; i++) {
  32. newData[i] = _deconstructPacket(data[i], buffers);
  33. }
  34. return newData;
  35. }
  36. else if (typeof data === "object" && !(data instanceof Date)) {
  37. const newData = {};
  38. for (const key in data) {
  39. if (data.hasOwnProperty(key)) {
  40. newData[key] = _deconstructPacket(data[key], buffers);
  41. }
  42. }
  43. return newData;
  44. }
  45. return data;
  46. }
  47. /**
  48. * Reconstructs a binary packet from its placeholder packet and buffers
  49. *
  50. * @param {Object} packet - event packet with placeholders
  51. * @param {Array} buffers - binary buffers to put in placeholder positions
  52. * @return {Object} reconstructed packet
  53. * @public
  54. */
  55. function reconstructPacket(packet, buffers) {
  56. packet.data = _reconstructPacket(packet.data, buffers);
  57. packet.attachments = undefined; // no longer useful
  58. return packet;
  59. }
  60. exports.reconstructPacket = reconstructPacket;
  61. function _reconstructPacket(data, buffers) {
  62. if (!data)
  63. return data;
  64. if (data && data._placeholder) {
  65. return buffers[data.num]; // appropriate buffer (should be natural order anyway)
  66. }
  67. else if (Array.isArray(data)) {
  68. for (let i = 0; i < data.length; i++) {
  69. data[i] = _reconstructPacket(data[i], buffers);
  70. }
  71. }
  72. else if (typeof data === "object") {
  73. for (const key in data) {
  74. if (data.hasOwnProperty(key)) {
  75. data[key] = _reconstructPacket(data[key], buffers);
  76. }
  77. }
  78. }
  79. return data;
  80. }