browser-geturl.ts 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. "use strict";
  2. import { arrayify } from "@ethersproject/bytes";
  3. import type { GetUrlResponse, Options } from "./types";
  4. export { GetUrlResponse, Options };
  5. export async function getUrl(href: string, options?: Options): Promise<GetUrlResponse> {
  6. if (options == null) { options = { }; }
  7. const request: RequestInit = {
  8. method: (options.method || "GET"),
  9. headers: (options.headers || { }),
  10. body: (options.body || undefined),
  11. };
  12. if (options.skipFetchSetup !== true) {
  13. request.mode = <RequestMode>"cors"; // no-cors, cors, *same-origin
  14. request.cache = <RequestCache>"no-cache"; // *default, no-cache, reload, force-cache, only-if-cached
  15. request.credentials = <RequestCredentials>"same-origin"; // include, *same-origin, omit
  16. request.redirect = <RequestRedirect>"follow"; // manual, *follow, error
  17. request.referrer = "client"; // no-referrer, *client
  18. };
  19. const response = await fetch(href, request);
  20. const body = await response.arrayBuffer();
  21. const headers: { [ name: string ]: string } = { };
  22. if (response.headers.forEach) {
  23. response.headers.forEach((value, key) => {
  24. headers[key.toLowerCase()] = value;
  25. });
  26. } else {
  27. (<() => Array<string>>((<any>(response.headers)).keys))().forEach((key) => {
  28. headers[key.toLowerCase()] = response.headers.get(key);
  29. });
  30. }
  31. return {
  32. headers: headers,
  33. statusCode: response.status,
  34. statusMessage: response.statusText,
  35. body: arrayify(new Uint8Array(body)),
  36. }
  37. }