DechunkHTTP.mjs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. /**
  2. * @author sevzero [sevzero@protonmail.com]
  3. * @copyright Crown Copyright 2016
  4. * @license Apache-2.0
  5. */
  6. import Operation from "../Operation";
  7. /**
  8. * Dechunk HTTP response operation
  9. */
  10. class DechunkHTTP extends Operation {
  11. /**
  12. * DechunkHTTP constructor
  13. */
  14. constructor() {
  15. super();
  16. this.name = "Dechunk HTTP response";
  17. this.module = "Default";
  18. this.description = "Parses a HTTP response transferred using transfer-encoding:chunked";
  19. this.inputType = "string";
  20. this.outputType = "string";
  21. this.args = [];
  22. }
  23. /**
  24. * @param {string} input
  25. * @param {Object[]} args
  26. * @returns {string}
  27. */
  28. run(input, args) {
  29. let chunks = [];
  30. let chunkSizeEnd = input.indexOf("\n") + 1;
  31. let lineEndings = input.charAt(chunkSizeEnd - 2) === "\r" ? "\r\n" : "\n";
  32. let lineEndingsLength = lineEndings.length;
  33. let chunkSize = parseInt(input.slice(0, chunkSizeEnd), 16);
  34. while (!isNaN(chunkSize)) {
  35. chunks.push(input.slice(chunkSizeEnd, chunkSize + chunkSizeEnd));
  36. input = input.slice(chunkSizeEnd + chunkSize + lineEndingsLength);
  37. chunkSizeEnd = input.indexOf(lineEndings) + lineEndingsLength;
  38. chunkSize = parseInt(input.slice(0, chunkSizeEnd), 16);
  39. }
  40. return chunks.join("") + input;
  41. }
  42. }
  43. export default DechunkHTTP;