resolve-url.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. "use strict";
  2. var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
  3. Object.defineProperty(exports, "__esModule", {
  4. value: true
  5. });
  6. exports.default = void 0;
  7. var _urlToolkit = _interopRequireDefault(require("url-toolkit"));
  8. var _window = _interopRequireDefault(require("global/window"));
  9. var DEFAULT_LOCATION = 'http://example.com';
  10. var resolveUrl = function resolveUrl(baseUrl, relativeUrl) {
  11. // return early if we don't need to resolve
  12. if (/^[a-z]+:/i.test(relativeUrl)) {
  13. return relativeUrl;
  14. } // if baseUrl is a data URI, ignore it and resolve everything relative to window.location
  15. if (/^data:/.test(baseUrl)) {
  16. baseUrl = _window.default.location && _window.default.location.href || '';
  17. } // IE11 supports URL but not the URL constructor
  18. // feature detect the behavior we want
  19. var nativeURL = typeof _window.default.URL === 'function';
  20. var protocolLess = /^\/\//.test(baseUrl); // remove location if window.location isn't available (i.e. we're in node)
  21. // and if baseUrl isn't an absolute url
  22. var removeLocation = !_window.default.location && !/\/\//i.test(baseUrl); // if the base URL is relative then combine with the current location
  23. if (nativeURL) {
  24. baseUrl = new _window.default.URL(baseUrl, _window.default.location || DEFAULT_LOCATION);
  25. } else if (!/\/\//i.test(baseUrl)) {
  26. baseUrl = _urlToolkit.default.buildAbsoluteURL(_window.default.location && _window.default.location.href || '', baseUrl);
  27. }
  28. if (nativeURL) {
  29. var newUrl = new URL(relativeUrl, baseUrl); // if we're a protocol-less url, remove the protocol
  30. // and if we're location-less, remove the location
  31. // otherwise, return the url unmodified
  32. if (removeLocation) {
  33. return newUrl.href.slice(DEFAULT_LOCATION.length);
  34. } else if (protocolLess) {
  35. return newUrl.href.slice(newUrl.protocol.length);
  36. }
  37. return newUrl.href;
  38. }
  39. return _urlToolkit.default.buildAbsoluteURL(baseUrl, relativeUrl);
  40. };
  41. var _default = resolveUrl;
  42. exports.default = _default;
  43. module.exports = exports.default;