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
|
import { trimTrailingSlash } from '~/misc/utils';
import { ClashAPIConfig, LogsAPIConfig } from '~/types';
const headersCommon = { 'Content-Type': 'application/json' };
function genCommonHeaders({ secret }: { secret?: string }) {
const h = { ...headersCommon };
if (secret) {
h['Authorization'] = `Bearer ${secret}`;
}
return h;
}
function buildWebSocketURLBase(baseURL: string, params: URLSearchParams, endpoint: string) {
const qs = '?' + params.toString();
const url = new URL(baseURL);
url.protocol === 'https:' ? (url.protocol = 'wss:') : (url.protocol = 'ws:');
return `${trimTrailingSlash(url.href)}${endpoint}${qs}`;
}
export function getURLAndInit({ baseURL, secret }: ClashAPIConfig) {
const headers = genCommonHeaders({ secret });
return {
url: baseURL,
init: { headers },
};
}
export function buildWebSocketURL(apiConfig: ClashAPIConfig, endpoint: string) {
const { baseURL, secret } = apiConfig;
const params = new URLSearchParams({
token: secret,
});
return buildWebSocketURLBase(baseURL, params, endpoint);
}
export function buildLogsWebSocketURL(apiConfig: LogsAPIConfig, endpoint: string) {
const { baseURL, secret, logLevel } = apiConfig;
const params = new URLSearchParams({
token: secret,
level: logLevel,
});
return buildWebSocketURLBase(baseURL, params, endpoint);
}
|