geturl-browser.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.getUrl = exports.createGetUrl = void 0;
  4. const errors_js_1 = require("./errors.js");
  5. function createGetUrl(options) {
  6. async function getUrl(req, _signal) {
  7. (0, errors_js_1.assert)(_signal == null || !_signal.cancelled, "request cancelled before sending", "CANCELLED");
  8. const protocol = req.url.split(":")[0].toLowerCase();
  9. (0, errors_js_1.assert)(protocol === "http" || protocol === "https", `unsupported protocol ${protocol}`, "UNSUPPORTED_OPERATION", {
  10. info: { protocol },
  11. operation: "request"
  12. });
  13. (0, errors_js_1.assert)(protocol === "https" || !req.credentials || req.allowInsecureAuthentication, "insecure authorized connections unsupported", "UNSUPPORTED_OPERATION", {
  14. operation: "request"
  15. });
  16. let error = null;
  17. const controller = new AbortController();
  18. const timer = setTimeout(() => {
  19. error = (0, errors_js_1.makeError)("request timeout", "TIMEOUT");
  20. controller.abort();
  21. }, req.timeout);
  22. if (_signal) {
  23. _signal.addListener(() => {
  24. error = (0, errors_js_1.makeError)("request cancelled", "CANCELLED");
  25. controller.abort();
  26. });
  27. }
  28. const init = {
  29. method: req.method,
  30. headers: new Headers(Array.from(req)),
  31. body: req.body || undefined,
  32. signal: controller.signal
  33. };
  34. let resp;
  35. try {
  36. resp = await fetch(req.url, init);
  37. }
  38. catch (_error) {
  39. clearTimeout(timer);
  40. if (error) {
  41. throw error;
  42. }
  43. throw _error;
  44. }
  45. clearTimeout(timer);
  46. const headers = {};
  47. resp.headers.forEach((value, key) => {
  48. headers[key.toLowerCase()] = value;
  49. });
  50. const respBody = await resp.arrayBuffer();
  51. const body = (respBody == null) ? null : new Uint8Array(respBody);
  52. return {
  53. statusCode: resp.status,
  54. statusMessage: resp.statusText,
  55. headers, body
  56. };
  57. }
  58. return getUrl;
  59. }
  60. exports.createGetUrl = createGetUrl;
  61. // @TODO: remove in v7; provided for backwards compat
  62. const defaultGetUrl = createGetUrl({});
  63. async function getUrl(req, _signal) {
  64. return defaultGetUrl(req, _signal);
  65. }
  66. exports.getUrl = getUrl;
  67. //# sourceMappingURL=geturl-browser.js.map