openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
44 lines (43 loc) • 1.85 kB
JavaScript
import { fileURLToPath } from "node:url";
import path from "node:path";
import { hasEncodedFileUrlSeparator } from "@openclaw/fs-safe/advanced";
//#region src/media/media-reference-comparison.ts
const PATH_PARENT_SEGMENT_RE = /(?:^|[\\/])\.\.(?:[\\/]|$)/u;
const FORWARD_NETWORK_PATH_PREFIX_RE = /^\/\//u;
const FILE_URL_PREFIX_RE = /^file:(?:\/\/)?/iu;
const FILE_URL_LOCAL_NETWORK_KEY_PREFIX = "\0file-url-local-network:";
function normalizeAbsoluteLocalPath(e) {
if (!path.isAbsolute(e) || PATH_PARENT_SEGMENT_RE.test(e) || FORWARD_NETWORK_PATH_PREFIX_RE.test(e)) return e;
return path.normalize(e);
}
function normalizeFileUrlLocalPath(e) {
if (!e.startsWith("//")) return normalizeAbsoluteLocalPath(e);
const t = PATH_PARENT_SEGMENT_RE.test(e) ? e : `//${path.normalize(e.slice(2))}`;
return `${FILE_URL_LOCAL_NETWORK_KEY_PREFIX}${t}`;
}
function normalizeMalformedLocalFileUrl(e) {
const t = e.replace(FILE_URL_PREFIX_RE, "");
let n;
if (t.startsWith("/")) n = t;
else if (/^localhost(?:\/|$)/iu.test(t)) n = t.slice(9);
else return;
if (process.platform === "win32" && /^\/[a-z]:[\\/]/iu.test(n)) n = n.slice(1);
return normalizeFileUrlLocalPath(n);
}
/** Canonicalizes equivalent local media references without resolving the filesystem. */
function normalizeMediaReferenceForComparison(e) {
const t = e.trim();
if (!t) return "";
if (!FILE_URL_PREFIX_RE.test(t)) return normalizeAbsoluteLocalPath(t);
try {
const e = new URL(t);
if (e.protocol === "file:") {
if (hasEncodedFileUrlSeparator(e.pathname)) return t;
const n = process.platform === "win32" && (e.hostname !== "" || /^\/[a-z]:[\\/]/iu.test(e.pathname));
return normalizeFileUrlLocalPath(fileURLToPath(e, { windows: n }));
}
} catch {}
return normalizeMalformedLocalFileUrl(t) ?? t;
}
//#endregion
export { normalizeMediaReferenceForComparison as t };