path-browser.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. */
  4. "use strict";
  5. // A browser shim for the Node `path` builtin, exposing only the subset used by
  6. // `lib/util/path.js`: `posix.normalize`, `posix.dirname`, `win32.normalize`,
  7. // `win32.dirname` and a (posix) `basename`. It is a faithful port of Node's
  8. // `path` implementation and is wired in through the package `browser` field, so
  9. // Node, Deno and Bun keep using their native `path` and only browser bundles
  10. // use this. Inputs are always strings here, so Node's `validateString` guards
  11. // are omitted.
  12. const CHAR_UPPERCASE_A = 65;
  13. const CHAR_UPPERCASE_Z = 90;
  14. const CHAR_LOWERCASE_A = 97;
  15. const CHAR_LOWERCASE_Z = 122;
  16. const CHAR_DOT = 46;
  17. const CHAR_FORWARD_SLASH = 47;
  18. const CHAR_BACKWARD_SLASH = 92;
  19. const CHAR_COLON = 58;
  20. /**
  21. * @param {number} code char code
  22. * @returns {boolean} true for `/`
  23. */
  24. const isPosixPathSeparator = (code) => code === CHAR_FORWARD_SLASH;
  25. /**
  26. * @param {number} code char code
  27. * @returns {boolean} true for `/` or `\`
  28. */
  29. const isPathSeparator = (code) =>
  30. code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
  31. /**
  32. * @param {number} code char code
  33. * @returns {boolean} true for an ASCII letter (a windows device root)
  34. */
  35. const isWindowsDeviceRoot = (code) =>
  36. (code >= CHAR_UPPERCASE_A && code <= CHAR_UPPERCASE_Z) ||
  37. (code >= CHAR_LOWERCASE_A && code <= CHAR_LOWERCASE_Z);
  38. /**
  39. * Resolve `.` and `..` segments in a path. Ported from Node's internal
  40. * `normalizeString`.
  41. * @param {string} path path
  42. * @param {boolean} allowAboveRoot whether leading `..` may be kept
  43. * @param {string} separator path separator to emit
  44. * @param {(code: number) => boolean} isSeparator separator predicate
  45. * @returns {string} normalized path string (without root)
  46. */
  47. function normalizeString(path, allowAboveRoot, separator, isSeparator) {
  48. let res = "";
  49. let lastSegmentLength = 0;
  50. let lastSlash = -1;
  51. let dots = 0;
  52. let code = 0;
  53. for (let i = 0; i <= path.length; ++i) {
  54. if (i < path.length) {
  55. code = path.charCodeAt(i);
  56. } else if (isSeparator(code)) {
  57. break;
  58. } else {
  59. code = CHAR_FORWARD_SLASH;
  60. }
  61. if (isSeparator(code)) {
  62. if (lastSlash === i - 1 || dots === 1) {
  63. // NOOP
  64. } else if (dots === 2) {
  65. if (
  66. res.length < 2 ||
  67. lastSegmentLength !== 2 ||
  68. res.charCodeAt(res.length - 1) !== CHAR_DOT ||
  69. res.charCodeAt(res.length - 2) !== CHAR_DOT
  70. ) {
  71. if (res.length > 2) {
  72. const lastSlashIndex = res.lastIndexOf(separator);
  73. if (lastSlashIndex === -1) {
  74. res = "";
  75. lastSegmentLength = 0;
  76. } else {
  77. res = res.slice(0, lastSlashIndex);
  78. lastSegmentLength = res.length - 1 - res.lastIndexOf(separator);
  79. }
  80. lastSlash = i;
  81. dots = 0;
  82. continue;
  83. } else if (res.length !== 0) {
  84. res = "";
  85. lastSegmentLength = 0;
  86. lastSlash = i;
  87. dots = 0;
  88. continue;
  89. }
  90. }
  91. if (allowAboveRoot) {
  92. res += res.length > 0 ? `${separator}..` : "..";
  93. lastSegmentLength = 2;
  94. }
  95. } else {
  96. if (res.length > 0) {
  97. res += `${separator}${path.slice(lastSlash + 1, i)}`;
  98. } else {
  99. res = path.slice(lastSlash + 1, i);
  100. }
  101. lastSegmentLength = i - lastSlash - 1;
  102. }
  103. lastSlash = i;
  104. dots = 0;
  105. } else if (code === CHAR_DOT && dots !== -1) {
  106. ++dots;
  107. } else {
  108. dots = -1;
  109. }
  110. }
  111. return res;
  112. }
  113. /**
  114. * @param {string} path path
  115. * @returns {string} normalized posix path
  116. */
  117. function posixNormalize(path) {
  118. if (path.length === 0) return ".";
  119. const isAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH;
  120. const trailingSeparator =
  121. path.charCodeAt(path.length - 1) === CHAR_FORWARD_SLASH;
  122. path = normalizeString(path, !isAbsolute, "/", isPosixPathSeparator);
  123. if (path.length === 0) {
  124. if (isAbsolute) return "/";
  125. return trailingSeparator ? "./" : ".";
  126. }
  127. if (trailingSeparator) path += "/";
  128. return isAbsolute ? `/${path}` : path;
  129. }
  130. /**
  131. * @param {string} path path
  132. * @returns {string} posix dirname
  133. */
  134. function posixDirname(path) {
  135. if (path.length === 0) return ".";
  136. const hasRoot = path.charCodeAt(0) === CHAR_FORWARD_SLASH;
  137. let end = -1;
  138. let matchedSlash = true;
  139. for (let i = path.length - 1; i >= 1; --i) {
  140. if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) {
  141. if (!matchedSlash) {
  142. end = i;
  143. break;
  144. }
  145. } else {
  146. matchedSlash = false;
  147. }
  148. }
  149. if (end === -1) return hasRoot ? "/" : ".";
  150. if (hasRoot && end === 1) return "//";
  151. return path.slice(0, end);
  152. }
  153. /**
  154. * Normalizes drive paths (`C:\…`), UNC paths (`\\server\share\…`), DOS device
  155. * paths (`\\.\…`, `\\?\…`) and relative/normal segments like Node's
  156. * `path.win32.normalize`, including the CVE-2024-36139 colon-segment guard.
  157. *
  158. * Scope note: reserved Windows device names (`CON`, `COM1`, `LPT1`, …) are not
  159. * special-cased, so e.g. `\\.\COM1:` differs from Node. Such names cannot occur
  160. * in a browser (the only place this shim is used) and the resolver never routes
  161. * them to `win32.normalize`, so this does not affect resolution.
  162. * @param {string} path path
  163. * @returns {string} normalized win32 path
  164. */
  165. function win32Normalize(path) {
  166. const len = path.length;
  167. if (len === 0) return ".";
  168. let rootEnd = 0;
  169. /** @type {string | undefined} */
  170. let device;
  171. let isAbsolute = false;
  172. const code = path.charCodeAt(0);
  173. if (len === 1) {
  174. return isPosixPathSeparator(code) ? "\\" : path;
  175. }
  176. if (isPathSeparator(code)) {
  177. // Possible UNC root; an initial separator means an absolute path.
  178. isAbsolute = true;
  179. if (isPathSeparator(path.charCodeAt(1))) {
  180. // Matched double path separator at beginning
  181. let j = 2;
  182. let last = j;
  183. while (j < len && !isPathSeparator(path.charCodeAt(j))) j++;
  184. if (j < len && j !== last) {
  185. const firstPart = path.slice(last, j);
  186. last = j;
  187. while (j < len && isPathSeparator(path.charCodeAt(j))) j++;
  188. if (j < len && j !== last) {
  189. last = j;
  190. while (j < len && !isPathSeparator(path.charCodeAt(j))) j++;
  191. if (j === len || j !== last) {
  192. if (firstPart === "." || firstPart === "?") {
  193. // Device root, e.g. `\\.\pipe\…` or `\\?\C:\…`
  194. device = `\\\\${firstPart}`;
  195. rootEnd = 4;
  196. } else if (j === len) {
  197. // Matched a UNC root only
  198. return `\\\\${firstPart}\\${path.slice(last)}\\`;
  199. } else {
  200. // Matched a UNC root with leftovers
  201. device = `\\\\${firstPart}\\${path.slice(last, j)}`;
  202. rootEnd = j;
  203. }
  204. }
  205. }
  206. }
  207. } else {
  208. rootEnd = 1;
  209. }
  210. } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
  211. // Possible device root
  212. device = path.slice(0, 2);
  213. rootEnd = 2;
  214. if (len > 2 && isPathSeparator(path.charCodeAt(2))) {
  215. isAbsolute = true;
  216. rootEnd = 3;
  217. }
  218. }
  219. let tail =
  220. rootEnd < len
  221. ? normalizeString(path.slice(rootEnd), !isAbsolute, "\\", isPathSeparator)
  222. : "";
  223. if (tail.length === 0 && !isAbsolute) tail = ".";
  224. if (tail.length > 0 && isPathSeparator(path.charCodeAt(len - 1))) {
  225. tail += "\\";
  226. }
  227. if (!isAbsolute && device === undefined && path.includes(":")) {
  228. // A relative path that wasn't resolved to a device must not turn into
  229. // something Windows could read as an absolute/drive path (CVE-2024-36139).
  230. if (
  231. tail.length >= 2 &&
  232. isWindowsDeviceRoot(tail.charCodeAt(0)) &&
  233. tail.charCodeAt(1) === CHAR_COLON
  234. ) {
  235. return `.\\${tail}`;
  236. }
  237. let index = path.indexOf(":");
  238. do {
  239. if (index === len - 1 || isPathSeparator(path.charCodeAt(index + 1))) {
  240. return `.\\${tail}`;
  241. }
  242. } while ((index = path.indexOf(":", index + 1)) !== -1);
  243. }
  244. if (device === undefined) {
  245. return isAbsolute ? `\\${tail}` : tail;
  246. }
  247. return isAbsolute ? `${device}\\${tail}` : `${device}${tail}`;
  248. }
  249. /**
  250. * @param {string} path path
  251. * @returns {string} win32 dirname
  252. */
  253. function win32Dirname(path) {
  254. const len = path.length;
  255. if (len === 0) return ".";
  256. let rootEnd = -1;
  257. let offset = 0;
  258. const code = path.charCodeAt(0);
  259. if (len === 1) {
  260. return isPathSeparator(code) ? path : ".";
  261. }
  262. if (isPathSeparator(code)) {
  263. // Possible UNC root
  264. rootEnd = offset = 1;
  265. if (isPathSeparator(path.charCodeAt(1))) {
  266. let j = 2;
  267. let last = j;
  268. while (j < len && !isPathSeparator(path.charCodeAt(j))) j++;
  269. if (j < len && j !== last) {
  270. last = j;
  271. while (j < len && isPathSeparator(path.charCodeAt(j))) j++;
  272. if (j < len && j !== last) {
  273. last = j;
  274. while (j < len && !isPathSeparator(path.charCodeAt(j))) j++;
  275. if (j === len) {
  276. // Matched a UNC root only
  277. return path;
  278. }
  279. if (j !== last) {
  280. // Matched a UNC root with leftovers
  281. rootEnd = offset = j + 1;
  282. }
  283. }
  284. }
  285. }
  286. } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
  287. rootEnd = len > 2 && isPathSeparator(path.charCodeAt(2)) ? 3 : 2;
  288. offset = rootEnd;
  289. }
  290. let end = -1;
  291. let matchedSlash = true;
  292. for (let i = len - 1; i >= offset; --i) {
  293. if (isPathSeparator(path.charCodeAt(i))) {
  294. if (!matchedSlash) {
  295. end = i;
  296. break;
  297. }
  298. } else {
  299. matchedSlash = false;
  300. }
  301. }
  302. if (end === -1) {
  303. if (rootEnd === -1) return ".";
  304. end = rootEnd;
  305. }
  306. return path.slice(0, end);
  307. }
  308. /**
  309. * Posix `basename` — the browser is treated as a posix platform, matching how
  310. * Node picks the posix variant for `path.basename` on non-Windows systems.
  311. * @param {string} path path
  312. * @param {string=} suffix optional suffix to strip
  313. * @returns {string} basename
  314. */
  315. function basename(path, suffix) {
  316. let start = 0;
  317. let end = -1;
  318. let matchedSlash = true;
  319. if (
  320. suffix !== undefined &&
  321. suffix.length > 0 &&
  322. suffix.length <= path.length
  323. ) {
  324. if (suffix === path) return "";
  325. let extIdx = suffix.length - 1;
  326. let firstNonSlashEnd = -1;
  327. for (let i = path.length - 1; i >= 0; --i) {
  328. const code = path.charCodeAt(i);
  329. if (code === CHAR_FORWARD_SLASH) {
  330. if (!matchedSlash) {
  331. start = i + 1;
  332. break;
  333. }
  334. } else {
  335. if (firstNonSlashEnd === -1) {
  336. matchedSlash = false;
  337. firstNonSlashEnd = i + 1;
  338. }
  339. if (extIdx >= 0) {
  340. if (code === suffix.charCodeAt(extIdx)) {
  341. if (--extIdx === -1) {
  342. end = i;
  343. }
  344. } else {
  345. extIdx = -1;
  346. end = firstNonSlashEnd;
  347. }
  348. }
  349. }
  350. }
  351. if (start === end) {
  352. end = firstNonSlashEnd;
  353. } else if (end === -1) {
  354. end = path.length;
  355. }
  356. return path.slice(start, end);
  357. }
  358. for (let i = path.length - 1; i >= 0; --i) {
  359. if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) {
  360. if (!matchedSlash) {
  361. start = i + 1;
  362. break;
  363. }
  364. } else if (end === -1) {
  365. matchedSlash = false;
  366. end = i + 1;
  367. }
  368. }
  369. if (end === -1) return "";
  370. return path.slice(start, end);
  371. }
  372. module.exports = {
  373. basename,
  374. posix: { normalize: posixNormalize, dirname: posixDirname },
  375. win32: { normalize: win32Normalize, dirname: win32Dirname },
  376. };