url.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import parseuri from "parseuri";
  2. import debugModule from "debug"; // debug()
  3. const debug = debugModule("socket.io-client:url"); // debug()
  4. /**
  5. * URL parser.
  6. *
  7. * @param uri - url
  8. * @param path - the request path of the connection
  9. * @param loc - An object meant to mimic window.location.
  10. * Defaults to window.location.
  11. * @public
  12. */
  13. export function url(uri, path = "", loc) {
  14. let obj = uri;
  15. // default to window.location
  16. loc = loc || (typeof location !== "undefined" && location);
  17. if (null == uri)
  18. uri = loc.protocol + "//" + loc.host;
  19. // relative path support
  20. if (typeof uri === "string") {
  21. if ("/" === uri.charAt(0)) {
  22. if ("/" === uri.charAt(1)) {
  23. uri = loc.protocol + uri;
  24. }
  25. else {
  26. uri = loc.host + uri;
  27. }
  28. }
  29. if (!/^(https?|wss?):\/\//.test(uri)) {
  30. debug("protocol-less url %s", uri);
  31. if ("undefined" !== typeof loc) {
  32. uri = loc.protocol + "//" + uri;
  33. }
  34. else {
  35. uri = "https://" + uri;
  36. }
  37. }
  38. // parse
  39. debug("parse %s", uri);
  40. obj = parseuri(uri);
  41. }
  42. // make sure we treat `localhost:80` and `localhost` equally
  43. if (!obj.port) {
  44. if (/^(http|ws)$/.test(obj.protocol)) {
  45. obj.port = "80";
  46. }
  47. else if (/^(http|ws)s$/.test(obj.protocol)) {
  48. obj.port = "443";
  49. }
  50. }
  51. obj.path = obj.path || "/";
  52. const ipv6 = obj.host.indexOf(":") !== -1;
  53. const host = ipv6 ? "[" + obj.host + "]" : obj.host;
  54. // define unique id
  55. obj.id = obj.protocol + "://" + host + ":" + obj.port + path;
  56. // define href
  57. obj.href =
  58. obj.protocol +
  59. "://" +
  60. host +
  61. (loc && loc.port === obj.port ? "" : ":" + obj.port);
  62. return obj;
  63. }