url.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. 'use strict';
  2. var URL = require('url-parse');
  3. var debug = function() {};
  4. if (process.env.NODE_ENV !== 'production') {
  5. debug = require('debug')('sockjs-client:utils:url');
  6. }
  7. module.exports = {
  8. getOrigin: function(url) {
  9. if (!url) {
  10. return null;
  11. }
  12. var p = new URL(url);
  13. if (p.protocol === 'file:') {
  14. return null;
  15. }
  16. var port = p.port;
  17. if (!port) {
  18. port = (p.protocol === 'https:') ? '443' : '80';
  19. }
  20. return p.protocol + '//' + p.hostname + ':' + port;
  21. }
  22. , isOriginEqual: function(a, b) {
  23. var res = this.getOrigin(a) === this.getOrigin(b);
  24. debug('same', a, b, res);
  25. return res;
  26. }
  27. , isSchemeEqual: function(a, b) {
  28. return (a.split(':')[0] === b.split(':')[0]);
  29. }
  30. , addPath: function (url, path) {
  31. var qs = url.split('?');
  32. return qs[0] + path + (qs[1] ? '?' + qs[1] : '');
  33. }
  34. , addQuery: function (url, q) {
  35. return url + (url.indexOf('?') === -1 ? ('?' + q) : ('&' + q));
  36. }
  37. , isLoopbackAddr: function (addr) {
  38. return /^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(addr) || /^\[::1\]$/.test(addr);
  39. }
  40. };