You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

73 lines
1.5 KiB

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