mirror of
https://github.com/farion1231/cc-switch.git
synced 2026-06-16 13:34:04 +08:00
208987107e
- 修复inferWebsiteUrl函数,支持无协议URL的推测 - 在API地址失焦时自动补全https://协议 - 同时更新API地址和网站地址字段 - 保持URL输入验证,确保API地址有效性 - 提升用户体验:用户可输入api.example.com等简化格式
42 lines
1.1 KiB
TypeScript
42 lines
1.1 KiB
TypeScript
/**
|
|
* 从API地址推测对应的网站地址
|
|
* @param apiUrl API地址
|
|
* @returns 推测的网站地址,如果无法推测则返回空字符串
|
|
*/
|
|
export function inferWebsiteUrl(apiUrl: string): string {
|
|
if (!apiUrl || !apiUrl.trim()) {
|
|
return ''
|
|
}
|
|
|
|
let urlString = apiUrl.trim()
|
|
|
|
// 如果没有协议,默认添加 https://
|
|
if (!urlString.match(/^https?:\/\//)) {
|
|
urlString = 'https://' + urlString
|
|
}
|
|
|
|
try {
|
|
const url = new URL(urlString)
|
|
|
|
// 如果是localhost或IP地址,去掉路径部分
|
|
if (url.hostname === 'localhost' || /^\d+\.\d+\.\d+\.\d+$/.test(url.hostname)) {
|
|
return `${url.protocol}//${url.host}`
|
|
}
|
|
|
|
// 处理域名,去掉api前缀
|
|
let hostname = url.hostname
|
|
|
|
// 去掉 api. 前缀
|
|
if (hostname.startsWith('api.')) {
|
|
hostname = hostname.substring(4)
|
|
}
|
|
|
|
// 构建推测的网站地址
|
|
const port = url.port ? `:${url.port}` : ''
|
|
return `${url.protocol}//${hostname}${port}`
|
|
|
|
} catch (error) {
|
|
// URL解析失败,返回空字符串
|
|
return ''
|
|
}
|
|
} |