utils.ts•2.2 kB
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
/**
* Converts a URL to a likely valid filename based on the backend logic.
* NOTE: This frontend version omits the hashing/truncation for simplicity,
* as the definitive filename is generated by the backend. This is primarily
* for predicting the filename to fetch associated metadata.
* @param url The URL to convert
* @returns A predicted filename string
*/
export function url_to_filename(url: string): string {
try {
const parsedUrl = new URL(url);
let domain = parsedUrl.hostname;
let path = parsedUrl.pathname;
// Remove www. prefix if present
if (domain.startsWith('www.')) {
domain = domain.substring(4);
}
// Replace dots with underscores in domain
domain = domain.replace(/\./g, '_');
let filename: string;
// Clean up the path
if (path === '/' || !path) {
// If path is empty or just '/', use only the domain
filename = domain;
} else {
// Remove leading and trailing slashes
path = path.replace(/^\/|\/$/g, ''); // Remove leading/trailing slashes
// Replace slashes and other invalid characters with underscores
// Invalid chars in Windows filenames: <>:"/\|?*
// Also replacing slashes for consistency with backend.
path = path.replace(/[\/\?<>\\:\*\|":]/g, '_');
// Combine domain and path
filename = `${domain}_${path}`;
}
// Convert to lowercase for consistency
filename = filename.toLowerCase();
// Basic length check (optional, as backend handles definitive truncation)
// if (filename.length > 200) { // Arbitrary limit for frontend prediction
// filename = filename.substring(0, 200);
// }
// console.log(`Predicted filename for ${url}: ${filename}`);
return filename;
} catch (error) {
console.error(`Error converting URL to filename: ${url}`, error);
// Fallback: Replace common invalid chars in the original URL
return url
.replace(/^https?:\/\//, '')
.replace(/[\/\?<>\\:\*\|":\.]/g, '_')
.toLowerCase();
}
}