forked from openclaw/mcporter
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp-utils.ts
More file actions
89 lines (84 loc) · 2.5 KB
/
Copy pathhttp-utils.ts
File metadata and controls
89 lines (84 loc) · 2.5 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
const DOMAIN_WITH_PATH_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9.-]*)(?::\d+)?\//;
export function normalizeHttpUrlCandidate(value?: string): string | undefined {
if (!value) {
return undefined;
}
const trimmed = value.trim();
if (!trimmed) {
return undefined;
}
const hasScheme = /^https?:\/\//i.test(trimmed);
const candidate = hasScheme ? trimmed : DOMAIN_WITH_PATH_PATTERN.test(trimmed) ? `https://${trimmed}` : null;
if (!candidate) {
return undefined;
}
try {
const url = new URL(candidate);
return url.href;
} catch {
return undefined;
}
}
export function looksLikeHttpUrl(value?: string): boolean {
return Boolean(normalizeHttpUrlCandidate(value));
}
export function splitHttpToolSelector(input: string): { baseUrl: string; tool: string } | null {
const trimmed = input.trim();
const candidate = (() => {
const openParen = trimmed.indexOf('(');
if (openParen === -1) {
return trimmed;
}
return trimmed.slice(0, openParen);
})();
const normalized = normalizeHttpUrlCandidate(candidate);
if (!normalized) {
return null;
}
let url: URL;
try {
url = new URL(normalized);
} catch {
return null;
}
const pathname = url.pathname || '/';
const lastSlash = pathname.lastIndexOf('/');
const segment = pathname.slice(lastSlash + 1);
const dotIndex = segment.lastIndexOf('.');
if (dotIndex <= 0) {
return null;
}
const tool = segment.slice(dotIndex + 1);
if (!tool || !/^[A-Za-z0-9_-]+$/.test(tool)) {
return null;
}
const baseSegment = segment.slice(0, dotIndex);
if (!baseSegment) {
return null;
}
const basePath = `${pathname.slice(0, Math.max(0, lastSlash + 1))}${baseSegment}`;
const normalizedPath = basePath.startsWith('/') ? basePath : `/${basePath}`;
const baseUrl = `${url.origin}${normalizedPath}`;
return { baseUrl, tool };
}
export function normalizeHttpUrl(value: string | URL): string | undefined {
try {
const url = value instanceof URL ? new URL(value.href) : new URL(value);
url.protocol = url.protocol.toLowerCase();
url.hostname = url.hostname.replace(/^www\./i, '').toLowerCase();
if (!url.pathname) {
url.pathname = '/';
}
return url.href.replace(/\/$/, '/');
} catch {
return undefined;
}
}
export function extractHttpServerTarget(value: string): string | undefined {
const split = splitHttpToolSelector(value);
if (split) {
return split.baseUrl;
}
const normalized = normalizeHttpUrlCandidate(value);
return normalized ?? undefined;
}