minurl.browser.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import {isUrl} from './minurl.shared.js'
  2. export {isUrl} from './minurl.shared.js'
  3. // See: <https://github.com/nodejs/node/blob/6a3403c/lib/internal/url.js>
  4. /**
  5. * @param {URL | string} path
  6. * File URL.
  7. * @returns {string}
  8. * File URL.
  9. */
  10. export function urlToPath(path) {
  11. if (typeof path === 'string') {
  12. path = new URL(path)
  13. } else if (!isUrl(path)) {
  14. /** @type {NodeJS.ErrnoException} */
  15. const error = new TypeError(
  16. 'The "path" argument must be of type string or an instance of URL. Received `' +
  17. path +
  18. '`'
  19. )
  20. error.code = 'ERR_INVALID_ARG_TYPE'
  21. throw error
  22. }
  23. if (path.protocol !== 'file:') {
  24. /** @type {NodeJS.ErrnoException} */
  25. const error = new TypeError('The URL must be of scheme file')
  26. error.code = 'ERR_INVALID_URL_SCHEME'
  27. throw error
  28. }
  29. return getPathFromURLPosix(path)
  30. }
  31. /**
  32. * Get a path from a POSIX URL.
  33. *
  34. * @param {URL} url
  35. * URL.
  36. * @returns {string}
  37. * File path.
  38. */
  39. function getPathFromURLPosix(url) {
  40. if (url.hostname !== '') {
  41. /** @type {NodeJS.ErrnoException} */
  42. const error = new TypeError(
  43. 'File URL host must be "localhost" or empty on darwin'
  44. )
  45. error.code = 'ERR_INVALID_FILE_URL_HOST'
  46. throw error
  47. }
  48. const pathname = url.pathname
  49. let index = -1
  50. while (++index < pathname.length) {
  51. if (
  52. pathname.codePointAt(index) === 37 /* `%` */ &&
  53. pathname.codePointAt(index + 1) === 50 /* `2` */
  54. ) {
  55. const third = pathname.codePointAt(index + 2)
  56. if (third === 70 /* `F` */ || third === 102 /* `f` */) {
  57. /** @type {NodeJS.ErrnoException} */
  58. const error = new TypeError(
  59. 'File URL path must not include encoded / characters'
  60. )
  61. error.code = 'ERR_INVALID_FILE_URL_PATH'
  62. throw error
  63. }
  64. }
  65. }
  66. return decodeURIComponent(pathname)
  67. }