validate-this-path
Version:
A lightweight TypeScript utility package for validating, sanitizing, and manipulating file paths across different operating systems
173 lines (170 loc) • 5.45 kB
JavaScript
;
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var index_exports = {};
__export(index_exports, {
getCurrentOS: () => getCurrentOS,
getRelativePath: () => getRelativePath,
isPathTraversal: () => isPathTraversal,
joinPaths: () => joinPaths,
normalizePath: () => normalizePath,
sanitizePath: () => sanitizePath,
validatePath: () => validatePath
});
module.exports = __toCommonJS(index_exports);
// src/lib/pathUtils.ts
var path = __toESM(require("path"));
var import_os = require("os");
var WINDOWS_MAX_PATH = 260;
var POSIX_MAX_PATH = 4096;
var WINDOWS_ILLEGAL_CHARS = /[<>:"|?*\x00-\x1F]/g;
var POSIX_ILLEGAL_CHARS = /\x00/g;
function getCurrentOS() {
return (0, import_os.platform)() === "win32" ? "windows" : "posix";
}
function getMaxPathLength(os) {
return os === "windows" ? WINDOWS_MAX_PATH : POSIX_MAX_PATH;
}
function validatePath(pathStr, options = {}) {
const errors = [];
const os = options.os === "auto" || !options.os ? getCurrentOS() : options.os;
const maxLength = options.maxLength || getMaxPathLength(os);
const allowTraversal = options.allowTraversal ?? false;
const allowAbsolute = options.allowAbsolute ?? true;
const allowRelative = options.allowRelative ?? true;
if (!pathStr) {
return {
isValid: false,
errors: [
{
code: "EMPTY_PATH",
message: "Path cannot be empty"
}
]
};
}
if (pathStr.length > maxLength) {
errors.push({
code: "TOO_LONG",
message: `Path exceeds maximum length of ${maxLength} characters`
});
}
const illegalChars = os === "windows" ? WINDOWS_ILLEGAL_CHARS : POSIX_ILLEGAL_CHARS;
const illegalMatch = pathStr.match(illegalChars);
if (illegalMatch) {
errors.push({
code: "ILLEGAL_CHAR",
message: `Path contains illegal character: ${illegalMatch[0]}`,
position: illegalMatch.index
});
}
if (!allowTraversal && pathStr.includes("..")) {
errors.push({
code: "TRAVERSAL",
message: "Path traversal (..) is not allowed"
});
}
const isAbsolute2 = path.isAbsolute(pathStr);
if (isAbsolute2 && !allowAbsolute) {
errors.push({
code: "ABSOLUTE_NOT_ALLOWED",
message: "Absolute paths are not allowed"
});
}
if (!isAbsolute2 && !allowRelative) {
errors.push({
code: "RELATIVE_NOT_ALLOWED",
message: "Relative paths are not allowed"
});
}
if (errors.length === 0) {
return {
isValid: true,
normalizedPath: normalizePath(pathStr, { os })
};
}
return {
isValid: false,
errors
};
}
function normalizePath(pathStr, options = {}) {
if (!pathStr) {
return "";
}
const os = options.os === "auto" || !options.os ? getCurrentOS() : options.os;
const forceForwardSlash = options.forceForwardSlash ?? true;
const removeTrailingSlash = options.removeTrailingSlash ?? true;
const toLowerCase = options.toLowerCase ?? os === "windows";
let normalized = path.normalize(pathStr);
if (normalized === ".") {
return pathStr;
}
if (forceForwardSlash) {
normalized = normalized.replace(/\\/g, "/");
}
if (removeTrailingSlash && normalized.length > 1) {
normalized = normalized.replace(/[/\\]$/, "");
}
if (toLowerCase) {
normalized = normalized.toLowerCase();
}
return normalized;
}
function joinPaths(...paths) {
return path.join(...paths);
}
function getRelativePath(from, to) {
return path.relative(from, to);
}
function isPathTraversal(pathStr) {
if (!pathStr) {
return false;
}
const normalized = normalizePath(pathStr);
return normalized.includes("..");
}
function sanitizePath(pathStr, os = getCurrentOS()) {
if (!pathStr) {
return "";
}
const illegalChars = os === "windows" ? WINDOWS_ILLEGAL_CHARS : POSIX_ILLEGAL_CHARS;
const sanitized = pathStr.replace(illegalChars, "");
return normalizePath(sanitized, { os });
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
getCurrentOS,
getRelativePath,
isPathTraversal,
joinPaths,
normalizePath,
sanitizePath,
validatePath
});