(path: string, baseDir?: string)
| 30 | * expandPath('/absolute/path') // '/absolute/path' |
| 31 | */ |
| 32 | export function expandPath(path: string, baseDir?: string): string { |
| 33 | // Set default baseDir to getCwd() if not provided |
| 34 | const actualBaseDir = baseDir ?? getCwd() ?? getFsImplementation().cwd() |
| 35 | |
| 36 | // Input validation |
| 37 | if (typeof path !== 'string') { |
| 38 | throw new TypeError(`Path must be a string, received ${typeof path}`) |
| 39 | } |
| 40 | |
| 41 | if (typeof actualBaseDir !== 'string') { |
| 42 | throw new TypeError( |
| 43 | `Base directory must be a string, received ${typeof actualBaseDir}`, |
| 44 | ) |
| 45 | } |
| 46 | |
| 47 | // Security: Check for null bytes |
| 48 | if (path.includes('\0') || actualBaseDir.includes('\0')) { |
| 49 | throw new Error('Path contains null bytes') |
| 50 | } |
| 51 | |
| 52 | // Handle empty or whitespace-only paths |
| 53 | const trimmedPath = path.trim() |
| 54 | if (!trimmedPath) { |
| 55 | return normalize(actualBaseDir).normalize('NFC') |
| 56 | } |
| 57 | |
| 58 | // Handle home directory notation |
| 59 | if (trimmedPath === '~') { |
| 60 | return homedir().normalize('NFC') |
| 61 | } |
| 62 | |
| 63 | if (trimmedPath.startsWith('~/')) { |
| 64 | return join(homedir(), trimmedPath.slice(2)).normalize('NFC') |
| 65 | } |
| 66 | |
| 67 | // On Windows, convert POSIX-style paths (e.g., /c/Users/...) to Windows format |
| 68 | let processedPath = trimmedPath |
| 69 | if (getPlatform() === 'windows' && trimmedPath.match(/^\/[a-z]\//i)) { |
| 70 | try { |
| 71 | processedPath = posixPathToWindowsPath(trimmedPath) |
| 72 | } catch { |
| 73 | // If conversion fails, use original path |
| 74 | processedPath = trimmedPath |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | // Handle absolute paths |
| 79 | if (isAbsolute(processedPath)) { |
| 80 | return normalize(processedPath).normalize('NFC') |
| 81 | } |
| 82 | |
| 83 | // Handle relative paths |
| 84 | return resolve(actualBaseDir, processedPath).normalize('NFC') |
| 85 | } |
| 86 | |
| 87 | /** |
| 88 | * Converts an absolute path to a relative path from cwd, to save tokens in |
no test coverage detected