index.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. "use strict";
  2. var protocols = require("protocols");
  3. /**
  4. * parsePath
  5. * Parses the input url.
  6. *
  7. * @name parsePath
  8. * @function
  9. * @param {String} url The input url.
  10. * @return {Object} An object containing the following fields:
  11. *
  12. * - `protocols` (Array): An array with the url protocols (usually it has one element).
  13. * - `protocol` (String): The first protocol or `"file"`.
  14. * - `port` (String): The domain port (default: `""`).
  15. * - `resource` (String): The url domain/hostname.
  16. * - `host` (String): The url domain (including subdomain and port).
  17. * - `user` (String): The authentication user (default: `""`).
  18. * - `password` (String): The authentication password (default: `""`).
  19. * - `pathname` (String): The url pathname.
  20. * - `hash` (String): The url hash.
  21. * - `search` (String): The url querystring value (excluding `?`).
  22. * - `href` (String): The normalized input url.
  23. * - `query` (Object): The url querystring, parsed as object.
  24. * - `parse_failed` (Boolean): Whether the parsing failed or not.
  25. */
  26. function parsePath(url) {
  27. var output = {
  28. protocols: [],
  29. protocol: null,
  30. port: null,
  31. resource: "",
  32. host: "",
  33. user: "",
  34. password: "",
  35. pathname: "",
  36. hash: "",
  37. search: "",
  38. href: url,
  39. query: {},
  40. parse_failed: false
  41. };
  42. try {
  43. var parsed = new URL(url);
  44. output.protocols = protocols(parsed);
  45. output.protocol = output.protocols[0];
  46. output.port = parsed.port;
  47. output.resource = parsed.hostname;
  48. output.host = parsed.host;
  49. output.user = parsed.username || "";
  50. output.password = parsed.password || "";
  51. output.pathname = parsed.pathname;
  52. output.hash = parsed.hash.slice(1);
  53. output.search = parsed.search.slice(1);
  54. output.href = parsed.href;
  55. output.query = Object.fromEntries(parsed.searchParams);
  56. } catch (e) {
  57. // TODO Maybe check if it is a valid local file path
  58. // In any case, these will be parsed by higher
  59. // level parsers such as parse-url, git-url-parse, git-up
  60. output.protocols = ["file"];
  61. output.protocol = output.protocols[0];
  62. output.port = "";
  63. output.resource = "";
  64. output.user = "";
  65. output.pathname = "";
  66. output.hash = "";
  67. output.search = "";
  68. output.href = url;
  69. output.query = {};
  70. output.parse_failed = true;
  71. }
  72. return output;
  73. }
  74. module.exports = parsePath;