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