@flex-development/pathe
Version:
Universal drop-in replacement for node:path
66 lines (65 loc) • 1.85 kB
JavaScript
import validateString from "#internal/validate-string";
import dot from "#lib/dot";
import isSep from "#lib/is-sep";
import sep from "#lib/sep";
function normalizeString(path, allowAboveRoot) {
validateString(path, "path");
let char;
let dots = 0;
let res = "";
let lastSegmentLength = 0;
let lastSlash = -1;
for (let i = 0; i <= path.length; ++i) {
if (i < path.length) char = path[i];
else if (isSep(char)) break;
else char = sep;
if (isSep(char)) {
if (lastSlash === i - 1 || dots === 1) {
} else if (dots === 2) {
if (res.length < 2 || lastSegmentLength !== 2 || !/(?:\..$)|(?:\.$)/.test(res)) {
if (res.length > 2) {
const sepIdxRet = res.lastIndexOf(sep);
if (sepIdxRet === -1) {
res = "";
lastSegmentLength = 0;
} else {
res = res.slice(0, sepIdxRet);
lastSegmentLength = res.length - 1 - res.lastIndexOf(sep);
}
lastSlash = i;
dots = 0;
continue;
} else if (res.length > 0) {
res = "";
lastSlash = i;
lastSegmentLength = 0;
dots = 0;
continue;
}
}
if (allowAboveRoot) {
res += `${!res ? "" : sep}${dot.repeat(2)}`;
lastSegmentLength = 2;
}
} else {
if (res.length > 0) {
res += `${sep}${path.slice(lastSlash + 1, i)}`;
} else {
res = path.slice(lastSlash + 1, i);
}
lastSegmentLength = i - lastSlash - 1;
}
lastSlash = i;
dots = 0;
} else if (char === dot && dots !== -1) {
++dots;
} else {
dots = -1;
}
}
return res;
}
var normalize_string_default = normalizeString;
export {
normalize_string_default as default
};