Source: util/url-path.ts

  1. /**
  2. * @fileoverview URL Path Builder
  3. */
  4. // ------------------------------------------------------------------------------
  5. // Private
  6. // ------------------------------------------------------------------------------
  7. // Pattern to check for relative paths
  8. const PATTERN = /\/\.+/;
  9. /**
  10. * remove leading & trailing slashes from some string. This is useful for
  11. * removing slashes from the path segments that are actually a part of the
  12. * path itself. Without this step, these slashes would be uri-encoded.
  13. *
  14. * @param {string} segment The path segment (ex: '/users')
  15. * @returns {string} The path segment with slashes trimmed (ex: 'users')
  16. * @private
  17. */
  18. function trimSlashes(segment: string) {
  19. return segment.replace(/^\/|\/$/g, '');
  20. }
  21. // ------------------------------------------------------------------------------
  22. // Public
  23. // ------------------------------------------------------------------------------
  24. /**
  25. * URLPath will create a full URL path from the given array of segments.
  26. *
  27. * It also provides the following features:
  28. * - convert all segments to strings
  29. * - add/remove slashes between segments, where appropriate
  30. * - encode each path segment to prevent path manipulation
  31. *
  32. * @name URLPath
  33. * @returns {string} Return a valid URL path comprised of the given path segments
  34. */
  35. export = function urlPath(...args: any[]) {
  36. const path = args
  37. .map((x) => String(x))
  38. .map((x) => {
  39. var trimmedX = trimSlashes(x);
  40. if (PATTERN.test(trimmedX)) {
  41. throw new Error(
  42. `An invalid path parameter exists in ${trimmedX}. Relative path parameters cannot be passed.`
  43. );
  44. }
  45. return trimmedX;
  46. })
  47. .map((x) => encodeURIComponent(x))
  48. .join('/');
  49. return `/${path}`;
  50. };