index.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. "use strict";
  2. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  3. var parsePath = require("parse-path"),
  4. normalizeUrl = require("normalize-url");
  5. /**
  6. * parseUrl
  7. * Parses the input url.
  8. *
  9. * **Note**: This *throws* if invalid urls are provided.
  10. *
  11. * @name parseUrl
  12. * @function
  13. * @param {String} url The input url.
  14. * @param {Boolean|Object} normalize Wheter to normalize the url or not.
  15. * Default is `false`. If `true`, the url will
  16. * be normalized. If an object, it will be the
  17. * options object sent to [`normalize-url`](https://github.com/sindresorhus/normalize-url).
  18. *
  19. * For SSH urls, normalize won't work.
  20. *
  21. * @return {Object} An object containing the following fields:
  22. *
  23. * - `protocols` (Array): An array with the url protocols (usually it has one element).
  24. * - `protocol` (String): The first protocol, `"ssh"` (if the url is a ssh url) or `"file"`.
  25. * - `port` (null|Number): The domain port.
  26. * - `resource` (String): The url domain (including subdomains).
  27. * - `user` (String): The authentication user (usually for ssh urls).
  28. * - `pathname` (String): The url pathname.
  29. * - `hash` (String): The url hash.
  30. * - `search` (String): The url querystring value.
  31. * - `href` (String): The input url.
  32. * - `query` (Object): The url querystring, parsed as object.
  33. */
  34. function parseUrl(url) {
  35. var normalize = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
  36. if (typeof url !== "string" || !url.trim()) {
  37. throw new Error("Invalid url.");
  38. }
  39. if (normalize) {
  40. if ((typeof normalize === "undefined" ? "undefined" : _typeof(normalize)) !== "object") {
  41. normalize = {
  42. stripHash: false
  43. };
  44. }
  45. url = normalizeUrl(url, normalize);
  46. }
  47. var parsed = parsePath(url);
  48. return parsed;
  49. }
  50. module.exports = parseUrl;