UNPKG

@flex-development/pathe

Version:

Universal drop-in replacement for node:path

99 lines (98 loc) 3.13 kB
import { DRIVE_PATH_REGEX, sepWindows } from "#internal/constants"; import normalizeString from "#internal/normalize-string"; import process from "#internal/process"; import validateString from "#internal/validate-string"; import dot from "#lib/dot"; import isSep from "#lib/is-sep"; import sep from "#lib/sep"; import toPosix from "#lib/to-posix"; function resolveWith(paths, options) { let cwd = options?.cwd; let env = options?.env; if (typeof cwd !== "function") cwd = process.cwd; if (typeof env !== "object" || env === null) env = process.env; if (typeof paths === "string") paths = [paths]; let resolvedAbsolute = false; let resolvedDevice = ""; let resolvedTail = ""; for (let i = paths.length - 1; i >= -1; i--) { let path; if (i >= 0) { path = paths[i]; validateString(path, `paths[${i}]`); if (!path.length) continue; } else if (!resolvedDevice.length) { path = cwd(); } else { path = env[`=${resolvedDevice}`] || cwd(); if (!path || path.slice(0, 2).toLowerCase() !== resolvedDevice.toLowerCase() && isSep(path[2])) { path = resolvedDevice + sep; } } let absolute = false; let device = ""; let rootEnd = 0; if (path.length === 1) { if (isSep(path)) { absolute = true; rootEnd = 1; } } else if (isSep(path[0])) { absolute = true; if (!isSep(path[1])) { rootEnd = 1; } else { let j = 2; let last = j; while (j < path.length && !isSep(path[j])) j++; if (j < path.length && j !== last) { const comp = path.slice(last, j); last = j; while (j < path.length && isSep(path[j])) j++; if (j < path.length && j !== last) { last = j; while (j < path.length && !isSep(path[j])) j++; if (j === path.length || j !== last) { device = sepWindows.repeat(2) + comp; if (comp !== dot && comp !== "?") { device += sepWindows + path.slice(last, j); rootEnd = j; } else { rootEnd = 4; } } } } } } else if (DRIVE_PATH_REGEX.test(path)) { rootEnd = 2; device = path.slice(0, rootEnd); if (path.length > rootEnd && isSep(path[rootEnd])) { absolute = true; rootEnd++; } } if (device) { if (resolvedDevice) { if (device.toLowerCase() !== resolvedDevice.toLowerCase()) continue; } else { resolvedDevice = device; } } if (resolvedAbsolute) { if (resolvedDevice.length) break; } else { resolvedTail = `${path.slice(rootEnd)}${sep}${resolvedTail}`; resolvedAbsolute = absolute; if (absolute && resolvedDevice.length) break; } } resolvedTail = normalizeString(resolvedTail, !resolvedAbsolute); return toPosix( resolvedAbsolute ? `${resolvedDevice}${sep}${resolvedTail}` : `${resolvedDevice}${resolvedTail}` || dot ); } var resolve_with_default = resolveWith; export { resolve_with_default as default };