resolve-uri.mjs 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. // Matches the scheme of a URL, eg "http://"
  2. const schemeRegex = /^[\w+.-]+:\/\//;
  3. /**
  4. * Matches the parts of a URL:
  5. * 1. Scheme, including ":", guaranteed.
  6. * 2. User/password, including "@", optional.
  7. * 3. Host, guaranteed.
  8. * 4. Port, including ":", optional.
  9. * 5. Path, including "/", optional.
  10. */
  11. const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?/;
  12. function isAbsoluteUrl(input) {
  13. return schemeRegex.test(input);
  14. }
  15. function isSchemeRelativeUrl(input) {
  16. return input.startsWith('//');
  17. }
  18. function isAbsolutePath(input) {
  19. return input.startsWith('/');
  20. }
  21. function parseAbsoluteUrl(input) {
  22. const match = urlRegex.exec(input);
  23. return {
  24. scheme: match[1],
  25. user: match[2] || '',
  26. host: match[3],
  27. port: match[4] || '',
  28. path: match[5] || '/',
  29. relativePath: false,
  30. };
  31. }
  32. function parseUrl(input) {
  33. if (isSchemeRelativeUrl(input)) {
  34. const url = parseAbsoluteUrl('http:' + input);
  35. url.scheme = '';
  36. return url;
  37. }
  38. if (isAbsolutePath(input)) {
  39. const url = parseAbsoluteUrl('http://foo.com' + input);
  40. url.scheme = '';
  41. url.host = '';
  42. return url;
  43. }
  44. if (!isAbsoluteUrl(input)) {
  45. const url = parseAbsoluteUrl('http://foo.com/' + input);
  46. url.scheme = '';
  47. url.host = '';
  48. url.relativePath = true;
  49. return url;
  50. }
  51. return parseAbsoluteUrl(input);
  52. }
  53. function stripPathFilename(path) {
  54. // If a path ends with a parent directory "..", then it's a relative path with excess parent
  55. // paths. It's not a file, so we can't strip it.
  56. if (path.endsWith('/..'))
  57. return path;
  58. const index = path.lastIndexOf('/');
  59. return path.slice(0, index + 1);
  60. }
  61. function mergePaths(url, base) {
  62. // If we're not a relative path, then we're an absolute path, and it doesn't matter what base is.
  63. if (!url.relativePath)
  64. return;
  65. normalizePath(base);
  66. // If the path is just a "/", then it was an empty path to begin with (remember, we're a relative
  67. // path).
  68. if (url.path === '/') {
  69. url.path = base.path;
  70. }
  71. else {
  72. // Resolution happens relative to the base path's directory, not the file.
  73. url.path = stripPathFilename(base.path) + url.path;
  74. }
  75. // If the base path is absolute, then our path is now absolute too.
  76. url.relativePath = base.relativePath;
  77. }
  78. /**
  79. * The path can have empty directories "//", unneeded parents "foo/..", or current directory
  80. * "foo/.". We need to normalize to a standard representation.
  81. */
  82. function normalizePath(url) {
  83. const { relativePath } = url;
  84. const pieces = url.path.split('/');
  85. // We need to preserve the first piece always, so that we output a leading slash. The item at
  86. // pieces[0] is an empty string.
  87. let pointer = 1;
  88. // Positive is the number of real directories we've output, used for popping a parent directory.
  89. // Eg, "foo/bar/.." will have a positive 2, and we can decrement to be left with just "foo".
  90. let positive = 0;
  91. // We need to keep a trailing slash if we encounter an empty directory (eg, splitting "foo/" will
  92. // generate `["foo", ""]` pieces). And, if we pop a parent directory. But once we encounter a
  93. // real directory, we won't need to append, unless the other conditions happen again.
  94. let addTrailingSlash = false;
  95. for (let i = 1; i < pieces.length; i++) {
  96. const piece = pieces[i];
  97. // An empty directory, could be a trailing slash, or just a double "//" in the path.
  98. if (!piece) {
  99. addTrailingSlash = true;
  100. continue;
  101. }
  102. // If we encounter a real directory, then we don't need to append anymore.
  103. addTrailingSlash = false;
  104. // A current directory, which we can always drop.
  105. if (piece === '.')
  106. continue;
  107. // A parent directory, we need to see if there are any real directories we can pop. Else, we
  108. // have an excess of parents, and we'll need to keep the "..".
  109. if (piece === '..') {
  110. if (positive) {
  111. addTrailingSlash = true;
  112. positive--;
  113. pointer--;
  114. }
  115. else if (relativePath) {
  116. // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute
  117. // URL, protocol relative URL, or an absolute path, we don't need to keep excess.
  118. pieces[pointer++] = piece;
  119. }
  120. continue;
  121. }
  122. // We've encountered a real directory. Move it to the next insertion pointer, which accounts for
  123. // any popped or dropped directories.
  124. pieces[pointer++] = piece;
  125. positive++;
  126. }
  127. let path = '';
  128. for (let i = 1; i < pointer; i++) {
  129. path += '/' + pieces[i];
  130. }
  131. if (!path || (addTrailingSlash && !path.endsWith('/..'))) {
  132. path += '/';
  133. }
  134. url.path = path;
  135. }
  136. /**
  137. * Attempts to resolve `input` URL/path relative to `base`.
  138. */
  139. function resolve(input, base) {
  140. if (!input && !base)
  141. return '';
  142. const url = parseUrl(input);
  143. // If we have a base, and the input isn't already an absolute URL, then we need to merge.
  144. if (base && !url.scheme) {
  145. const baseUrl = parseUrl(base);
  146. url.scheme = baseUrl.scheme;
  147. // If there's no host, then we were just a path.
  148. if (!url.host || baseUrl.scheme === 'file:') {
  149. // The host, user, and port are joined, you can't copy one without the others.
  150. url.user = baseUrl.user;
  151. url.host = baseUrl.host;
  152. url.port = baseUrl.port;
  153. }
  154. mergePaths(url, baseUrl);
  155. }
  156. normalizePath(url);
  157. // If the input (and base, if there was one) are both relative, then we need to output a relative.
  158. if (url.relativePath) {
  159. // The first char is always a "/".
  160. const path = url.path.slice(1);
  161. if (!path)
  162. return '.';
  163. // If base started with a leading ".", or there is no base and input started with a ".", then we
  164. // need to ensure that the relative path starts with a ".". We don't know if relative starts
  165. // with a "..", though, so check before prepending.
  166. const keepRelative = (base || input).startsWith('.');
  167. return !keepRelative || path.startsWith('.') ? path : './' + path;
  168. }
  169. // If there's no host (and no scheme/user/port), then we need to output an absolute path.
  170. if (!url.scheme && !url.host)
  171. return url.path;
  172. // We're outputting either an absolute URL, or a protocol relative one.
  173. return `${url.scheme}//${url.user}${url.host}${url.port}${url.path}`;
  174. }
  175. export { resolve as default };
  176. //# sourceMappingURL=resolve-uri.mjs.map