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

Paste-bin is for source code and general debugging text.

Login or Register to edit, delete and keep track of your pastes and more.

Raw Paste

Login or Register to edit or fork this paste. It's free.