File size: 1,158 Bytes
28faefd
 
 
 
 
 
 
 
52c6f5c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
export function isValidURL(url: string): boolean {
	try {
		new URL(url);
		return true;
	} catch {
		return false;
	}
}

export const extractDomain = (value: unknown) => {
	const url = toURL(value);

	if (!url) {
		return null;
	}

	const hostnameParts = url.hostname.split(".");

	// Determine typical hostnames like "domain.com" or "domain.org"
	if (hostnameParts.length <= 2) {
		return url.hostname;
	}

	// Determine two-part TLD if second last part of the hostname matches one of the prefixes
	const prefixes = ["com", "co", "org", "net", "gov", "edu"];
	const potentialTwoPartTLD = `${hostnameParts[hostnameParts.length - 2]}.${hostnameParts[hostnameParts.length - 1]}`;

	return prefixes.includes(hostnameParts[hostnameParts.length - 2]!)
		? `${hostnameParts[hostnameParts.length - 3]}.${potentialTwoPartTLD}`
		: hostnameParts.slice(-2).join("."); // Fallback to last two parts of hostname
};

const toURL = (value: unknown) => {
	if (value instanceof URL) {
		return value;
	}

	if (typeof value !== "string" || !value) {
		return null;
	}

	try {
		const url = new URL(value);
		return url.hostname ? url : null;
	} catch {
		return null;
	}
};