format-url.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.formatUrl = formatUrl;
  6. exports.formatWithValidation = formatWithValidation;
  7. exports.urlObjectKeys = void 0;
  8. var _interop_require_wildcard = require("@swc/helpers/lib/_interop_require_wildcard.js").default;
  9. var querystring = _interop_require_wildcard(require("./querystring"));
  10. const slashedProtocols = /https?|ftp|gopher|file/;
  11. function formatUrl(urlObj) {
  12. let { auth , hostname } = urlObj;
  13. let protocol = urlObj.protocol || '';
  14. let pathname = urlObj.pathname || '';
  15. let hash = urlObj.hash || '';
  16. let query = urlObj.query || '';
  17. let host = false;
  18. auth = auth ? encodeURIComponent(auth).replace(/%3A/i, ':') + '@' : '';
  19. if (urlObj.host) {
  20. host = auth + urlObj.host;
  21. } else if (hostname) {
  22. host = auth + (~hostname.indexOf(':') ? `[${hostname}]` : hostname);
  23. if (urlObj.port) {
  24. host += ':' + urlObj.port;
  25. }
  26. }
  27. if (query && typeof query === 'object') {
  28. query = String(querystring.urlQueryToSearchParams(query));
  29. }
  30. let search = urlObj.search || query && `?${query}` || '';
  31. if (protocol && !protocol.endsWith(':')) protocol += ':';
  32. if (urlObj.slashes || (!protocol || slashedProtocols.test(protocol)) && host !== false) {
  33. host = '//' + (host || '');
  34. if (pathname && pathname[0] !== '/') pathname = '/' + pathname;
  35. } else if (!host) {
  36. host = '';
  37. }
  38. if (hash && hash[0] !== '#') hash = '#' + hash;
  39. if (search && search[0] !== '?') search = '?' + search;
  40. pathname = pathname.replace(/[?#]/g, encodeURIComponent);
  41. search = search.replace('#', '%23');
  42. return `${protocol}${host}${pathname}${search}${hash}`;
  43. }
  44. const urlObjectKeys = [
  45. 'auth',
  46. 'hash',
  47. 'host',
  48. 'hostname',
  49. 'href',
  50. 'path',
  51. 'pathname',
  52. 'port',
  53. 'protocol',
  54. 'query',
  55. 'search',
  56. 'slashes',
  57. ];
  58. exports.urlObjectKeys = urlObjectKeys;
  59. function formatWithValidation(url) {
  60. if (process.env.NODE_ENV === 'development') {
  61. if (url !== null && typeof url === 'object') {
  62. Object.keys(url).forEach((key)=>{
  63. if (urlObjectKeys.indexOf(key) === -1) {
  64. console.warn(`Unknown key passed via urlObject into url.format: ${key}`);
  65. }
  66. });
  67. }
  68. }
  69. return formatUrl(url);
  70. }
  71. //# sourceMappingURL=format-url.js.map