1. /**
  2. * Streams request headers with a timeout for hypothesis validation.
  3. * @param {XMLHttpRequest} xhr - The XMLHttpRequest object.
  4. * @param {object} expectedHeaders - An object containing the expected headers and their values.
  5. * @param {number} timeout - The timeout in milliseconds.
  6. * @returns {Promise<object>} - A promise that resolves with the expected headers if all match, or rejects with an error if the timeout is reached.
  7. */
  8. async function streamRequestHeaders(xhr, expectedHeaders, timeout) {
  9. return new Promise((resolve, reject) => {
  10. const startTime = Date.now();
  11. const headersToValidate = Object.keys(expectedHeaders);
  12. let headersReceived = {};
  13. xhr.onheaders = function(e) {
  14. //Handle header events.
  15. for (const headerName in e) {
  16. if (headersToValidate.includes(headerName)) {
  17. headersReceived[headerName] = e[headerName];
  18. }
  19. }
  20. };
  21. xhr.timeout = timeout; //Set timeout on the request
  22. xhr.onload = function() {
  23. if (Date.now() - startTime < timeout) {
  24. // Check if all expected headers are present and match.
  25. let allHeadersMatch = true;
  26. for (const headerName of headersToValidate) {
  27. if (headersReceived[headerName] !== expectedHeaders[headerName]) {
  28. allHeadersMatch = false;
  29. break;
  30. }
  31. }
  32. if (allHeadersMatch) {
  33. resolve(headersReceived);
  34. } else {
  35. reject(new Error("Request headers do not match expected headers."));
  36. }
  37. } else {
  38. reject(new Error("Request timed out."));
  39. }
  40. };
  41. xhr.onerror = function() {
  42. reject(new Error("Request failed."));
  43. };
  44. xhr.ontimeout = function() {
  45. reject(new Error("Request timed out."));
  46. };
  47. });
  48. }

Add your comment