url.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /**
  2. * Parses string form of URL into an object
  3. * // borrowed from https://tools.ietf.org/html/rfc3986#appendix-B
  4. * // intentionally using regex and not <a/> href parsing trick because React Native and other
  5. * // environments where DOM might not be available
  6. * @returns parsed URL object
  7. */
  8. function parseUrl(url) {
  9. if (!url) {
  10. return {};
  11. }
  12. const match = url.match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);
  13. if (!match) {
  14. return {};
  15. }
  16. // coerce to undefined values to empty string so we don't get 'undefined'
  17. const query = match[6] || '';
  18. const fragment = match[8] || '';
  19. return {
  20. host: match[4],
  21. path: match[5],
  22. protocol: match[2],
  23. search: query,
  24. hash: fragment,
  25. relative: match[5] + query + fragment, // everything minus origin
  26. };
  27. }
  28. /**
  29. * Strip the query string and fragment off of a given URL or path (if present)
  30. *
  31. * @param urlPath Full URL or path, including possible query string and/or fragment
  32. * @returns URL or path without query string or fragment
  33. */
  34. function stripUrlQueryAndFragment(urlPath) {
  35. // eslint-disable-next-line no-useless-escape
  36. return urlPath.split(/[\?#]/, 1)[0];
  37. }
  38. /**
  39. * Returns number of URL segments of a passed string URL.
  40. */
  41. function getNumberOfUrlSegments(url) {
  42. // split at '/' or at '\/' to split regex urls correctly
  43. return url.split(/\\?\//).filter(s => s.length > 0 && s !== ',').length;
  44. }
  45. /**
  46. * Takes a URL object and returns a sanitized string which is safe to use as span description
  47. * see: https://develop.sentry.dev/sdk/data-handling/#structuring-data
  48. */
  49. function getSanitizedUrlString(url) {
  50. const { protocol, host, path } = url;
  51. const filteredHost =
  52. (host &&
  53. host
  54. // Always filter out authority
  55. .replace(/^.*@/, '[filtered]:[filtered]@')
  56. // Don't show standard :80 (http) and :443 (https) ports to reduce the noise
  57. // TODO: Use new URL global if it exists
  58. .replace(/(:80)$/, '')
  59. .replace(/(:443)$/, '')) ||
  60. '';
  61. return `${protocol ? `${protocol}://` : ''}${filteredHost}${path}`;
  62. }
  63. export { getNumberOfUrlSegments, getSanitizedUrlString, parseUrl, stripUrlQueryAndFragment };
  64. //# sourceMappingURL=url.js.map