getSchemeFromUrl.mjs 916 B

123456789101112131415161718192021222324252627282930313233343536
  1. /**
  2. * Get unit from value node
  3. *
  4. * Returns `null` if the unit is not found.
  5. *
  6. * @param {string} urlString
  7. * @returns {string | null}
  8. */
  9. export default function getSchemeFromUrl(urlString) {
  10. let protocol = null;
  11. try {
  12. protocol = new URL(urlString).protocol;
  13. } catch {
  14. return null;
  15. }
  16. if (protocol === null || typeof protocol === 'undefined') {
  17. return null;
  18. }
  19. const scheme = protocol.slice(0, -1); // strip trailing `:`
  20. // The URL spec does not require a scheme to be followed by `//`, but checking
  21. // for it allows this rule to differentiate <scheme>:<hostname> urls from
  22. // <hostname>:<port> urls. `data:` scheme urls are an exception to this rule.
  23. const slashIndex = protocol.length;
  24. const expectedSlashes = urlString.slice(slashIndex, slashIndex + 2);
  25. const isSchemeLessUrl = expectedSlashes !== '//' && scheme !== 'data';
  26. if (isSchemeLessUrl) {
  27. return null;
  28. }
  29. return scheme;
  30. }