13 lines
605 B
TypeScript
13 lines
605 B
TypeScript
import { isAbsolute, normalize, sep } from "node:path";
|
|
|
|
/** Normalised relative path, or throws. Rejects absolute paths, `..`, `.git` and NUL. */
|
|
export function checkRelPath(p: string): string {
|
|
if (typeof p !== "string" || p === "" || p.includes("\0") || isAbsolute(p) || p.includes("\\")) throw new Error(`invalid path: ${JSON.stringify(p)}`);
|
|
const n = normalize(p);
|
|
const parts = n.split(sep);
|
|
if (n === "." || parts[0] === ".." || parts.some((x) => x === ".." || x.toLowerCase() === ".git") || n.endsWith(sep)) {
|
|
throw new Error(`invalid path: ${JSON.stringify(p)}`);
|
|
}
|
|
return n;
|
|
}
|