path-key.ts 824 B

123456789101112131415161718192021222324
  1. export type PathKey = string & { _brand: "PathKey" }
  2. const isDrive = (value: string) => {
  3. if (value.length !== 2) return false
  4. const code = value.charCodeAt(0)
  5. return value[1] === ":" && ((code >= 65 && code <= 90) || (code >= 97 && code <= 122))
  6. }
  7. const trimTrailingSlashes = (value: string) => {
  8. for (let i = value.length - 1; i >= 0; i--) {
  9. if (value[i] !== "/") return value.slice(0, i + 1)
  10. }
  11. return ""
  12. }
  13. const isWindowsPath = (value: string) => value[1] === ":" || value.startsWith("\\\\")
  14. export const pathKey = (path: string) => {
  15. const value = isWindowsPath(path) ? path.replaceAll("\\", "/") : path
  16. const trimmed = trimTrailingSlashes(value)
  17. if (!trimmed && value.startsWith("/")) return "/" as PathKey
  18. if (isDrive(trimmed)) return `${trimmed}/` as PathKey
  19. return trimmed as PathKey
  20. }