Skip to content

armgit / rea

Public Imported from GitHub
0

Reverse engineer anything with agents, from app behavior down to native binaries.

1.3 KB
Raw Blame
import { posix, win32 } from "node:path";

/**
 * Make a caller-selected local path absolute without changing which file it
 * names. POSIX resolves `..` after following the preceding symlink, so lexical
 * normalization of `link/../file` can select a different file. On POSIX, only
 * interior `.` segments and repeated separators are removed, which never
 * change the named file; every `..` is kept for the filesystem to resolve, and
 * a trailing `/` or `/.` keeps its directory requirement as one trailing `/`.
 * A relative `cwd` is made absolute the same way. Win32 resolves `..`
 * lexically, so normalizing there is exact.
 */
export const absoluteCallerPath = (
  path: string,
  {
    cwd = process.cwd(),
    platform = process.platform,
  }: { readonly cwd?: string; readonly platform?: NodeJS.Platform } = {},
): string => {
  if (platform === "win32") return win32.resolve(cwd, path);
  if (!posix.isAbsolute(path)) {
    const base = posix.isAbsolute(cwd)
      ? cwd
      : absoluteCallerPath(cwd, { platform });
    return absoluteCallerPath(`${base}/${path}`, { platform });
  }
  const segments = path
    .split("/")
    .filter((segment) => segment !== "" && segment !== ".");
  const directory = /\/\.?$/u.test(path) && segments.length > 0;
  return `/${segments.join("/")}${directory ? "/" : ""}`;
};