每路入站配一组专属策略组,换线不再改配置文件
原本换一条线要改 config.yaml、跑校验、等内核重载,几秒起步;而换线恰恰是这个工具 最高频的动作,把它放在最重的路径上方向就错了。现在每一路配一个 select 组加 AUTO、 FALLBACK 两个,入站的 proxy 永久指向 select,换线只是调一次内核接口。这样做的前提是 选中不会丢:内核把它写进 cache 文件,重启后由 patchSelectGroup 恢复,而 profile.store-selected 默认为真。 链式代理靠给来源订阅复制一份声明、挂上 override.dialer-proxy 实现,因为这个字段写在 策略组上内核只会打条日志然后忽略。副本是 type: file 读原订阅已经落盘的缓存,而不是 自己再拉一次:自己拉的话订阅地址一不可达副本就是空的,那一路入站会一条线都不剩, 表现是端口还在监听却没有任何出口。 顺带把 shared/outbound-chain.ts 里「只有 Selector 接受手动选择」那条断言删了,它是 错的(内核检查的是 SelectAble 接口,URLTest 和 Fallback 也实现了)。界面仍然只让 Selector 可点,但理由换成了另外两种的手动指定会被它们自己撤销。 完整取舍见工作区决策记录 0007。
This commit is contained in:
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* 验证「每路一个专属代理组」和链式代理生成的配置内核真的接受。
|
||||
*
|
||||
* 单元测试只能证明字符串拼对了,证明不了内核认。这里走一遍真实的写回路径,
|
||||
* 产物交给 mihomo -t 校验。特别要看的是订阅副本上的 dialer-proxy 引用能不能过
|
||||
* `validateDialerProxies`(内核源码 config/utils.go:148-176)。
|
||||
*
|
||||
* 用法:bun run scripts/verify-chain.ts <源配置> <输出路径>
|
||||
*/
|
||||
import { readFileSync, writeFileSync } from 'node:fs'
|
||||
import { openDocument } from '../vendor/config-editor/index.ts'
|
||||
import type { ConfigObject } from '../vendor/config-editor/index.ts'
|
||||
import { rewriteYaml } from '../server/config-store.ts'
|
||||
import { applySetup, pruneGenerated } from '../shared/inbound-groups.ts'
|
||||
|
||||
const [src, out] = process.argv.slice(2)
|
||||
if (!src || !out) {
|
||||
console.error('用法:bun run scripts/verify-chain.ts <源配置> <输出路径>')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const source = readFileSync(src, 'utf8')
|
||||
const data = JSON.parse(JSON.stringify(openDocument(source).data)) as ConfigObject
|
||||
|
||||
// 模拟界面上的三个动作:新增两路入站,一路直连,一路开链式代理并把入口筛到某一条线
|
||||
data.listeners = [
|
||||
{ name: '容器A', type: 'mixed', port: 17895 },
|
||||
{ name: '容器B', type: 'mixed', port: 17896 },
|
||||
]
|
||||
|
||||
let next = applySetup(data, '容器A', {
|
||||
proxy: { sources: ['subs'], filter: null },
|
||||
chain: null,
|
||||
})
|
||||
next = applySetup(next, '容器B', {
|
||||
proxy: { sources: ['subs'], filter: null },
|
||||
chain: { sources: ['subs'], filter: '(?i)DMIT' },
|
||||
})
|
||||
|
||||
writeFileSync(out, rewriteYaml(source, pruneGenerated(next)), 'utf8')
|
||||
|
||||
console.log('生成的策略组:')
|
||||
console.log(JSON.stringify(next['proxy-groups'], null, 2))
|
||||
console.log('\n生成的订阅副本(只看结构,url 不回显):')
|
||||
for (const [name, entry] of Object.entries(next['proxy-providers'] as ConfigObject)) {
|
||||
if (!name.startsWith('patchbay:')) continue
|
||||
const { url, ...rest } = entry as ConfigObject
|
||||
console.log(name, JSON.stringify({ ...rest, url: '<同源订阅>' }))
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
/**
|
||||
* 验证「把入站固定到某条订阅线路」生成的配置内核真的接受。
|
||||
*
|
||||
* 这个功能会往用户的配置里塞一个自动生成的策略组,光靠单元测试只能证明字符串拼对了,
|
||||
* 证明不了内核认。所以这里走一遍真实的写回路径,再交给 mihomo -t 校验。
|
||||
*
|
||||
* 用法:bun run scripts/verify-pin.ts <源配置> <输出路径> <线路名>
|
||||
*/
|
||||
import { readFileSync, writeFileSync } from 'node:fs'
|
||||
import { openDocument } from '../vendor/config-editor/index.ts'
|
||||
import type { ConfigObject } from '../vendor/config-editor/index.ts'
|
||||
import { rewriteYaml } from '../server/config-store.ts'
|
||||
import { generatedGroupName, makeFilterGroup, pruneGeneratedGroups } from '../shared/filter-groups.ts'
|
||||
|
||||
const [src, out, line] = process.argv.slice(2)
|
||||
if (!src || !out || !line) {
|
||||
console.error('用法:bun run scripts/verify-pin.ts <源配置> <输出路径> <线路名>')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const source = readFileSync(src, 'utf8')
|
||||
const data = JSON.parse(JSON.stringify(openDocument(source).data)) as ConfigObject
|
||||
|
||||
// 模拟界面上的两个动作:新增一路入站,把它固定到某条订阅线路
|
||||
data.listeners = [{ name: '容器A', type: 'mixed', port: 17895 }]
|
||||
const group = makeFilterGroup(line, 'subs')
|
||||
if (!group) {
|
||||
console.error(`${line} 的名字里含反引号,无法生成筛选条件`)
|
||||
process.exit(1)
|
||||
}
|
||||
data['proxy-groups'] = [...(data['proxy-groups'] as ConfigObject[]), group]
|
||||
;(data.listeners as ConfigObject[])[0]!.proxy = generatedGroupName(line)
|
||||
|
||||
writeFileSync(out, rewriteYaml(source, pruneGeneratedGroups(data)), 'utf8')
|
||||
console.log('生成的组:')
|
||||
console.log(JSON.stringify(group, null, 2))
|
||||
@@ -117,6 +117,16 @@ export async function applyConfig(
|
||||
}
|
||||
}
|
||||
|
||||
// 落盘链路有五步各自可能变慢(校验要起一个内核进程、重载要等内核跑完、备份和写盘是磁盘
|
||||
// IO)。出问题时不靠猜,日志里直接给出每步耗时。
|
||||
const clock = { start: Date.now(), mark: Date.now() }
|
||||
const lap = (stage: string) => {
|
||||
const now = Date.now()
|
||||
const ms = now - clock.mark
|
||||
clock.mark = now
|
||||
return `${stage} ${String(ms)}ms`
|
||||
}
|
||||
|
||||
const nextYaml = rewriteYaml(current.yaml, nextData)
|
||||
|
||||
// 内容没变就不要走后面那一串——不必要的备份和重载只会制造噪音。
|
||||
@@ -138,9 +148,11 @@ export async function applyConfig(
|
||||
|
||||
// 先写到临时文件交给内核校验,别碰真文件。
|
||||
const tempPath = join(dirname(env.configPath), `.patchbay-check-${String(Date.now())}.yaml`)
|
||||
let checkTiming = ''
|
||||
try {
|
||||
await writeFile(tempPath, nextYaml, 'utf8')
|
||||
const checked = await validateConfigFile(env, tempPath)
|
||||
checkTiming = lap('内核校验')
|
||||
if (!checked.ok) {
|
||||
return {
|
||||
ok: false,
|
||||
@@ -156,6 +168,7 @@ export async function applyConfig(
|
||||
|
||||
// 校验过了才动真文件。备份放在写入之前。
|
||||
const backupPath = await createBackup(env)
|
||||
const backupTiming = lap('备份')
|
||||
try {
|
||||
await writeFile(env.configPath, nextYaml, 'utf8')
|
||||
} catch (error) {
|
||||
@@ -168,7 +181,9 @@ export async function applyConfig(
|
||||
}
|
||||
}
|
||||
|
||||
const writeTiming = lap('写盘')
|
||||
const reloaded = await reloadConfig(env, env.configPath)
|
||||
const reloadTiming = lap('重载')
|
||||
if (!reloaded.ok) {
|
||||
// 文件已经写进去了但内核没接受。把文件还原,再让内核载回原样,
|
||||
// 避免留下「文件是新的、内核跑的是旧的」这种最难排查的状态。
|
||||
@@ -192,6 +207,9 @@ export async function applyConfig(
|
||||
}
|
||||
|
||||
await pruneBackups(env)
|
||||
console.log(
|
||||
`[apply] 共 ${String(Date.now() - clock.start)}ms(${checkTiming},${backupTiming},${writeTiming},${reloadTiming})`,
|
||||
)
|
||||
return {
|
||||
ok: true,
|
||||
snapshot: await readConfig(env),
|
||||
|
||||
+3
-1
@@ -8,7 +8,7 @@ import { readEnv } from './env.ts'
|
||||
import { resolveToken } from './auth.ts'
|
||||
import { createRouter } from './routes.ts'
|
||||
import { readConfig } from './config-store.ts'
|
||||
import { kernelVersion } from './kernel.ts'
|
||||
import { kernelVersion, warmUpKernelBinary } from './kernel.ts'
|
||||
|
||||
const env = readEnv()
|
||||
const { token, source } = await resolveToken(env)
|
||||
@@ -29,6 +29,8 @@ try {
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
warmUpKernelBinary(env)
|
||||
|
||||
const kernel = await kernelVersion(env)
|
||||
console.log(
|
||||
kernel.online
|
||||
|
||||
@@ -50,6 +50,24 @@ export async function validateConfigFile(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 启动时先把内核二进制跑一次,什么都不做。
|
||||
*
|
||||
* `mihomo -t` 的第一次调用要 4 秒,之后 55 毫秒(在目标机器那种规格上实测差距只会更大)。
|
||||
* 差的是把这个几十兆的可执行文件读进系统文件缓存的时间,跟配置内容无关。不预热的话,
|
||||
* 这 4 秒会落在用户按下的第一次保存上,而那正是他最容易以为「这个工具很慢」的时刻。
|
||||
*
|
||||
* 失败不用管:内核二进制不可用这件事,第一次真正校验时会带着完整错误信息报出来。
|
||||
*/
|
||||
export function warmUpKernelBinary(env: Env): void {
|
||||
try {
|
||||
const proc = Bun.spawn([env.mihomoBin, '-v'], { stdout: 'ignore', stderr: 'ignore' })
|
||||
void proc.exited
|
||||
} catch {
|
||||
// 同上
|
||||
}
|
||||
}
|
||||
|
||||
/** 带上认证头访问管理接口。 */
|
||||
async function callApi(env: Env, path: string, init?: RequestInit): Promise<Response> {
|
||||
return fetch(`${env.mihomoApi}${path}`, {
|
||||
|
||||
@@ -1,110 +0,0 @@
|
||||
import { describe, expect, it } from 'bun:test'
|
||||
import {
|
||||
generatedGroupName,
|
||||
isGeneratedGroup,
|
||||
lineFilter,
|
||||
makeFilterGroup,
|
||||
pinnedLineOf,
|
||||
pruneGeneratedGroups,
|
||||
} from './filter-groups.ts'
|
||||
import type { ConfigObject } from '../vendor/config-editor/index.ts'
|
||||
|
||||
const LINE = '[vless]Gomami.SIN Secret'
|
||||
|
||||
describe('筛选条件', () => {
|
||||
it('转义正则元字符', () => {
|
||||
// 线路名里的 [ ] . 不转义会当成正则语法,匹配到别的线路上去
|
||||
expect(lineFilter(LINE)).toBe('^\\[vless\\]Gomami\\.SIN Secret$')
|
||||
})
|
||||
|
||||
it('前后加锚点,避免匹配到名字更长的线路', () => {
|
||||
// 内核的筛选是部分匹配:不加锚点时「香港01」会把「香港011」也捞进来
|
||||
expect(lineFilter('香港01')).toBe('^香港01$')
|
||||
})
|
||||
|
||||
it('线路名含反引号时表达不了,返回空让调用方说明原因', () => {
|
||||
// 反引号在内核里是多个筛选条件的分隔符,塞进一条正则会被切成两半
|
||||
expect(lineFilter('怪`名字')).toBeNull()
|
||||
})
|
||||
|
||||
it('转义后的正则确实只匹配它自己', () => {
|
||||
const re = new RegExp(lineFilter(LINE)!)
|
||||
expect(re.test(LINE)).toBe(true)
|
||||
expect(re.test('[vless]GomamiXSIN Secret')).toBe(false)
|
||||
expect(re.test(`${LINE} 备用`)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('生成的组', () => {
|
||||
it('名字带前缀,这是识别它的唯一可靠标记', () => {
|
||||
// 注释靠不住——被碰到的段落重写时会丢,见决策记录 0002
|
||||
const name = generatedGroupName(LINE)
|
||||
expect(isGeneratedGroup(name)).toBe(true)
|
||||
expect(pinnedLineOf(name)).toBe(LINE)
|
||||
})
|
||||
|
||||
it('用户自己建的组不会被认成生成的', () => {
|
||||
expect(isGeneratedGroup('PROXY')).toBe(false)
|
||||
expect(pinnedLineOf('PROXY')).toBeNull()
|
||||
})
|
||||
|
||||
it('组里只有那一条线路,类型是手动选', () => {
|
||||
expect(makeFilterGroup(LINE, 'subs')).toEqual({
|
||||
name: `patchbay:${LINE}`,
|
||||
type: 'select',
|
||||
use: ['subs'],
|
||||
filter: '^\\[vless\\]Gomami\\.SIN Secret$',
|
||||
})
|
||||
})
|
||||
|
||||
it('表达不了的线路名不生成组', () => {
|
||||
expect(makeFilterGroup('怪`名字', 'subs')).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('清理没人用的生成组', () => {
|
||||
const generated = (line: string) => ({ name: generatedGroupName(line), type: 'select' })
|
||||
|
||||
it('入站还指着它就留着', () => {
|
||||
const data: ConfigObject = {
|
||||
listeners: [{ name: 'A', type: 'mixed', port: 1, proxy: generatedGroupName(LINE) }],
|
||||
'proxy-groups': [generated(LINE)],
|
||||
}
|
||||
expect(pruneGeneratedGroups(data)['proxy-groups']).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('没人再指它就删掉', () => {
|
||||
const data: ConfigObject = {
|
||||
listeners: [{ name: 'A', type: 'mixed', port: 1 }],
|
||||
'proxy-groups': [generated(LINE)],
|
||||
}
|
||||
// 不清理的话,改几次出站文件里就攒下一堆用户从没主动建过的组
|
||||
expect(pruneGeneratedGroups(data)['proxy-groups']).toBeUndefined()
|
||||
})
|
||||
|
||||
it('被别的策略组当成员引用也算在用', () => {
|
||||
const data: ConfigObject = {
|
||||
'proxy-groups': [generated(LINE), { name: 'PROXY', proxies: [generatedGroupName(LINE)] }],
|
||||
}
|
||||
expect(pruneGeneratedGroups(data)['proxy-groups']).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('被规则引用也算在用', () => {
|
||||
const data: ConfigObject = {
|
||||
'proxy-groups': [generated(LINE)],
|
||||
rules: [`MATCH,${generatedGroupName(LINE)}`],
|
||||
}
|
||||
expect(pruneGeneratedGroups(data)['proxy-groups']).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('用户自己建的组一律不碰,哪怕真的没人引用', () => {
|
||||
const data: ConfigObject = { 'proxy-groups': [{ name: '我建的组', type: 'select' }] }
|
||||
expect(pruneGeneratedGroups(data)['proxy-groups']).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('没有可删的时候原样返回,不制造无谓的改动', () => {
|
||||
// 返回同一个对象,落盘链路才看得出「内容没变」而跳过备份和重载
|
||||
const data: ConfigObject = { 'proxy-groups': [{ name: 'PROXY' }] }
|
||||
expect(pruneGeneratedGroups(data)).toBe(data)
|
||||
})
|
||||
})
|
||||
@@ -1,118 +0,0 @@
|
||||
/**
|
||||
* 把一路入站固定到某一条订阅线路。
|
||||
*
|
||||
* 内核不允许直接这么写:入站的 `proxy:` 只认全局名字表里的名字,而订阅线路不在表上
|
||||
* (见决策记录 0005)。绕法是给那条线路单独建一个只装它的策略组,入站指向这个组。
|
||||
*
|
||||
* 这些组是 Patchbay 自己造的,用户不该看到也不该管。名字带前缀是唯一可靠的标记——
|
||||
* 注释靠不住,被碰到的段落重写时会丢。
|
||||
*/
|
||||
import type { ConfigObject } from '../vendor/config-editor/index.ts'
|
||||
|
||||
/** 自动生成的筛选组的名字前缀。改它会让已有配置里的组失去标记,别改。 */
|
||||
export const GENERATED_PREFIX = 'patchbay:'
|
||||
|
||||
export function isGeneratedGroup(name: string): boolean {
|
||||
return name.startsWith(GENERATED_PREFIX)
|
||||
}
|
||||
|
||||
/** 固定到某条线路时,生成的组叫什么。名字里带上线路名,翻文件时一眼看得懂。 */
|
||||
export function generatedGroupName(line: string): string {
|
||||
return `${GENERATED_PREFIX}${line}`
|
||||
}
|
||||
|
||||
/** 这个组固定的是哪条线路。不是生成的组返回 null。 */
|
||||
export function pinnedLineOf(groupName: string): string | null {
|
||||
return isGeneratedGroup(groupName) ? groupName.slice(GENERATED_PREFIX.length) : null
|
||||
}
|
||||
|
||||
/**
|
||||
* 出站在界面上怎么念。
|
||||
*
|
||||
* 生成的组显示成它固定的那条线路——用户从没建过这个组,让他在界面上读到
|
||||
* `patchbay:[vless]Gomami` 只会莫名其妙。
|
||||
*/
|
||||
export function displayOutboundName(name: string): string {
|
||||
return pinnedLineOf(name) ?? name
|
||||
}
|
||||
|
||||
/**
|
||||
* 把线路名转成只匹配它自己的筛选条件。
|
||||
*
|
||||
* 两件事必须做对:
|
||||
* 转义正则元字符——线路名形如 `[vmess]DMIT.LAX.Pro.MTYQ`,`[`、`]`、`.` 不转义会匹配错
|
||||
* 前后加锚点——内核的筛选是部分匹配,不加锚点时 `香港01` 会把 `香港011` 也匹配进来
|
||||
*
|
||||
* 反引号在内核里是多个筛选条件的分隔符(adapter/outboundgroup/groupbase.go:72-76),
|
||||
* 线路名里含它就没法用一条正则表达,这种情况返回 null,调用方据此告诉用户做不到。
|
||||
*/
|
||||
export function lineFilter(line: string): string | null {
|
||||
if (line.includes('`')) return null
|
||||
const escaped = line.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
||||
return `^${escaped}$`
|
||||
}
|
||||
|
||||
/**
|
||||
* 造一个只装指定线路的策略组。
|
||||
*
|
||||
* 用 `select` 而不是 `url-test`:组里只有一条线路,没什么可测的,而 `select` 的语义
|
||||
* 就是「用这一个」。
|
||||
*/
|
||||
export function makeFilterGroup(line: string, provider: string): ConfigObject | null {
|
||||
const filter = lineFilter(line)
|
||||
if (filter === null) return null
|
||||
return {
|
||||
name: generatedGroupName(line),
|
||||
type: 'select',
|
||||
use: [provider],
|
||||
filter,
|
||||
}
|
||||
}
|
||||
|
||||
/** 配置里所有指向某个名字的位置。用来判断一个生成的组还有没有人在用。 */
|
||||
function referencesTo(data: ConfigObject, name: string): number {
|
||||
let count = 0
|
||||
|
||||
for (const entry of Array.isArray(data.listeners) ? data.listeners : []) {
|
||||
if (typeof entry === 'object' && entry !== null) {
|
||||
if ((entry as Record<string, unknown>).proxy === name) count += 1
|
||||
}
|
||||
}
|
||||
|
||||
for (const group of Array.isArray(data['proxy-groups']) ? data['proxy-groups'] : []) {
|
||||
if (typeof group !== 'object' || group === null) continue
|
||||
const members = (group as Record<string, unknown>).proxies
|
||||
if (Array.isArray(members) && members.includes(name)) count += 1
|
||||
}
|
||||
|
||||
for (const rule of Array.isArray(data.rules) ? data.rules : []) {
|
||||
// 规则的目标是逗号分隔的最后一段之前那个位置,形如 MATCH,目标 或 DOMAIN,x,目标
|
||||
if (typeof rule === 'string' && rule.split(',').some((part) => part.trim() === name)) count += 1
|
||||
}
|
||||
|
||||
return count
|
||||
}
|
||||
|
||||
/**
|
||||
* 删掉没人再引用的生成组。
|
||||
*
|
||||
* 每次改完配置都跑一遍。不清理的话,改几次出站文件里就攒下一堆没用的组,而用户
|
||||
* 并不知道它们是干嘛的——他从来没主动建过它们。
|
||||
*
|
||||
* 只动带前缀的组,用户自己建的一律不碰,哪怕它确实没人引用。
|
||||
*/
|
||||
export function pruneGeneratedGroups(data: ConfigObject): ConfigObject {
|
||||
const groups = Array.isArray(data['proxy-groups']) ? data['proxy-groups'] : []
|
||||
const kept = groups.filter((group) => {
|
||||
if (typeof group !== 'object' || group === null) return true
|
||||
const name = (group as Record<string, unknown>).name
|
||||
if (typeof name !== 'string' || !isGeneratedGroup(name)) return true
|
||||
return referencesTo(data, name) > 0
|
||||
})
|
||||
|
||||
if (kept.length === groups.length) return data
|
||||
const next = { ...data }
|
||||
if (kept.length === 0) delete next['proxy-groups']
|
||||
else next['proxy-groups'] = kept
|
||||
return next
|
||||
}
|
||||
@@ -0,0 +1,321 @@
|
||||
import { describe, expect, it } from 'bun:test'
|
||||
import {
|
||||
applySetup,
|
||||
chainGroupName,
|
||||
chainProviderName,
|
||||
panelGroups,
|
||||
syncGenerated,
|
||||
isGenerated,
|
||||
linesMatching,
|
||||
proxyGroupName,
|
||||
pruneGenerated,
|
||||
readSetup,
|
||||
} from './inbound-groups.ts'
|
||||
import type { OutboundSetup } from './inbound-groups.ts'
|
||||
import { collectInbounds } from './inbounds.ts'
|
||||
import type { ConfigObject } from '../vendor/config-editor/index.ts'
|
||||
|
||||
const URL = 'http://127.0.0.1:3001/token/download/V2House'
|
||||
|
||||
/** 一份最小但完整的配置:一个订阅、一路入站,还没被 Patchbay 接管过。 */
|
||||
function base(): ConfigObject {
|
||||
return {
|
||||
'proxy-providers': {
|
||||
subs: { type: 'http', url: URL, path: './providers/subs.yaml', interval: 86400 },
|
||||
},
|
||||
listeners: [{ name: 'test1', type: 'mixed', port: 7778 }],
|
||||
}
|
||||
}
|
||||
|
||||
const plain: OutboundSetup = { proxy: { sources: ['subs'], filter: null }, chain: null }
|
||||
const chained: OutboundSetup = {
|
||||
proxy: { sources: ['subs'], filter: null },
|
||||
chain: { sources: ['subs'], filter: '(?i)DMIT' },
|
||||
}
|
||||
|
||||
describe('名字', () => {
|
||||
it('三种生成物都带前缀', () => {
|
||||
// 前缀是识别它们的唯一可靠标记,注释会被配置改写引擎丢掉(决策记录 0002)
|
||||
expect(isGenerated(proxyGroupName('test1'))).toBe(true)
|
||||
expect(isGenerated(chainGroupName('test1'))).toBe(true)
|
||||
expect(isGenerated(chainProviderName('test1', 'subs'))).toBe(true)
|
||||
})
|
||||
|
||||
it('用户自己建的组不会被认成生成的', () => {
|
||||
expect(isGenerated('PROXY')).toBe(false)
|
||||
})
|
||||
|
||||
it('不同的「入站 × 来源」组合不撞名', () => {
|
||||
// proxy-providers 是个映射,撞名会让其中一份被静默丢掉,
|
||||
// 表现是链式代理挂到了别的入站上
|
||||
const names = new Set([
|
||||
chainProviderName('a', 'b c'),
|
||||
chainProviderName('a b', 'c'),
|
||||
chainProviderName('a', 'b'),
|
||||
])
|
||||
expect(names.size).toBe(3)
|
||||
})
|
||||
|
||||
|
||||
})
|
||||
|
||||
describe('筛选预览', () => {
|
||||
const lines = ['[vmess]DMIT.LAX.Pro.MTYQ', '[vless]Gomami.SIN Secret', '香港01', '香港011']
|
||||
|
||||
it('没写筛选条件就是全要', () => {
|
||||
expect(linesMatching(null, lines)).toEqual(lines)
|
||||
})
|
||||
|
||||
it('部分匹配,不自动加锚点', () => {
|
||||
// 内核的筛选就是部分匹配,界面预览必须跟它一致,否则预览的数字骗人
|
||||
expect(linesMatching('香港01', lines)).toEqual(['香港01', '香港011'])
|
||||
})
|
||||
|
||||
it('反引号切成多条正则,取并集', () => {
|
||||
expect(linesMatching('DMIT`Gomami', lines)).toEqual([
|
||||
'[vmess]DMIT.LAX.Pro.MTYQ',
|
||||
'[vless]Gomami.SIN Secret',
|
||||
])
|
||||
})
|
||||
|
||||
it('写法有误时返回空,让界面提示而不是显示一个错的数字', () => {
|
||||
expect(linesMatching('[未闭合', lines)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('一路入站的三个组', () => {
|
||||
it('SELECT 的成员是 DIRECT 加另外两个组,加上订阅', () => {
|
||||
// 这三种挑法是所有 clash 配置里固定的那几种,让用户从零拼一遍没有意义
|
||||
const groups = applySetup(base(), 'test1', plain)['proxy-groups'] as ConfigObject[]
|
||||
expect(groups[0]).toEqual({
|
||||
name: 'patchbay:test1',
|
||||
type: 'select',
|
||||
proxies: ['DIRECT', 'patchbay:test1 AUTO', 'patchbay:test1 FALLBACK'],
|
||||
use: ['subs'],
|
||||
})
|
||||
})
|
||||
|
||||
it('AUTO 是 url-test,FALLBACK 是 fallback,都带测速地址', () => {
|
||||
// 不写测速地址时内核会去借来源订阅的健康检查配置,那依赖订阅写了它,不能指望
|
||||
const groups = applySetup(base(), 'test1', plain)['proxy-groups'] as ConfigObject[]
|
||||
expect(groups[1]).toEqual({
|
||||
name: 'patchbay:test1 AUTO',
|
||||
type: 'url-test',
|
||||
use: ['subs'],
|
||||
url: 'https://www.gstatic.com/generate_204',
|
||||
interval: 300,
|
||||
})
|
||||
expect((groups[2] as ConfigObject).type).toBe('fallback')
|
||||
})
|
||||
|
||||
it('tab 的顺序是 SELECT、AUTO、FALLBACK,只有 SELECT 能点', () => {
|
||||
// 另外两个自己决定用哪条,手动指定会被它们自己撤销,见 outbound-chain.ts
|
||||
const data = applySetup(base(), 'test1', plain)
|
||||
const runtime = {
|
||||
'patchbay:test1': { type: 'Selector' },
|
||||
'patchbay:test1 AUTO': { type: 'URLTest' },
|
||||
'patchbay:test1 FALLBACK': { type: 'Fallback' },
|
||||
}
|
||||
const inbound = collectInbounds(data)[0]!
|
||||
const panel = panelGroups(data, runtime, inbound)
|
||||
|
||||
expect(panel.shared).toBe(false)
|
||||
expect(panel.groups.map((g) => g.label)).toEqual(['SELECT', 'AUTO', 'FALLBACK'])
|
||||
expect(panel.groups.map((g) => g.pickable)).toEqual([true, false, false])
|
||||
expect(panel.groups[0]!.uses).toEqual(['subs'])
|
||||
})
|
||||
|
||||
it('内核里还没有的组不出现在 tab 上', () => {
|
||||
// 保存完到内核重载完之间会有这么一小段,画一个点不出东西的 tab 只会让人以为坏了
|
||||
const data = applySetup(base(), 'test1', plain)
|
||||
const inbound = collectInbounds(data)[0]!
|
||||
expect(panelGroups(data, {}, inbound).groups).toEqual([])
|
||||
})
|
||||
|
||||
it('没接管的入站落到它顺着规则表走到的那个手动选择组,并标为共用', () => {
|
||||
const data: ConfigObject = {
|
||||
...base(),
|
||||
rules: ['MATCH,PROXY'],
|
||||
'proxy-groups': [{ name: 'PROXY', type: 'select', use: ['subs'] }],
|
||||
}
|
||||
const runtime = { PROXY: { type: 'Selector', now: 'A', all: ['A'] } }
|
||||
const panel = panelGroups(data, runtime, collectInbounds(data)[0]!)
|
||||
|
||||
expect(panel.shared).toBe(true)
|
||||
expect(panel.groups).toEqual([
|
||||
{ name: 'PROXY', label: 'PROXY', uses: ['subs'], pickable: true },
|
||||
])
|
||||
})
|
||||
|
||||
it('筛选条件三个组共用一份', () => {
|
||||
const groups = applySetup(base(), 'test1', {
|
||||
proxy: { sources: ['subs'], filter: '(?i)hk' },
|
||||
chain: null,
|
||||
})['proxy-groups'] as ConfigObject[]
|
||||
for (const g of groups) expect((g as ConfigObject).filter).toBe('(?i)hk')
|
||||
})
|
||||
})
|
||||
|
||||
describe('重建成当前形状', () => {
|
||||
it('旧形状的生成组会被补齐成三个', () => {
|
||||
// 改过生成规则之后,早先建的那些停在旧形状上,界面按新形状去找就静默少一块
|
||||
const stale: ConfigObject = {
|
||||
...base(),
|
||||
'proxy-groups': [{ name: 'patchbay:test1', type: 'select', use: ['subs'] }],
|
||||
listeners: [{ name: 'test1', type: 'mixed', port: 7778, proxy: 'patchbay:test1' }],
|
||||
}
|
||||
const fixed = syncGenerated(stale, collectInbounds(stale))
|
||||
const names = (fixed['proxy-groups'] as ConfigObject[]).map((g) => (g as ConfigObject).name)
|
||||
|
||||
expect(names).toEqual(['patchbay:test1', 'patchbay:test1 AUTO', 'patchbay:test1 FALLBACK'])
|
||||
})
|
||||
|
||||
it('没接管的入站不碰', () => {
|
||||
const data = base()
|
||||
expect(syncGenerated(data, collectInbounds(data))).toBe(data)
|
||||
})
|
||||
})
|
||||
|
||||
describe('读取设置', () => {
|
||||
it('没有代理组时返回空,表示这一路由别的方式决定去向', () => {
|
||||
expect(readSetup(base(), 'test1')).toBeNull()
|
||||
})
|
||||
|
||||
it('没开链式代理时,来源就是代理组的 use', () => {
|
||||
const setup: OutboundSetup = { proxy: { sources: ['subs'], filter: '(?i)hk' }, chain: null }
|
||||
expect(readSetup(applySetup(base(), 'test1', setup), 'test1')).toEqual(setup)
|
||||
})
|
||||
|
||||
it('开了链式代理时,来源从副本的 url 还原', () => {
|
||||
// 代理组的 use 这时指向副本,用户选的订阅只能靠 url 相同认回来
|
||||
const data = applySetup(base(), 'test1', chained)
|
||||
expect(readSetup(data, 'test1')).toEqual(chained)
|
||||
})
|
||||
})
|
||||
|
||||
describe('写回设置', () => {
|
||||
it('开链式代理时建入口组,三个组一起改用副本', () => {
|
||||
const groups = applySetup(base(), 'test1', chained)['proxy-groups'] as ConfigObject[]
|
||||
const copyName = chainProviderName('test1', 'subs')
|
||||
|
||||
// 只有副本挂着 dialer-proxy,自动测速和故障转移也得走副本,否则那两条路绕过了中转
|
||||
for (const g of groups.slice(0, 3)) expect((g as ConfigObject).use).toEqual([copyName])
|
||||
expect(groups[3]).toEqual({
|
||||
name: 'patchbay:test1 链式',
|
||||
type: 'select',
|
||||
use: ['subs'],
|
||||
filter: '(?i)DMIT',
|
||||
})
|
||||
})
|
||||
|
||||
it('副本读原订阅的缓存文件,自己不联网', () => {
|
||||
// 副本要是自己去拉,订阅地址一不可达它就是空的,那一路入站的线路会全部消失,
|
||||
// 表现是端口还在监听却一条线都没有
|
||||
const data = applySetup(base(), 'test1', chained)
|
||||
const copy = (data['proxy-providers'] as ConfigObject)[
|
||||
chainProviderName('test1', 'subs')
|
||||
] as ConfigObject
|
||||
|
||||
expect(copy.type).toBe('file')
|
||||
expect(copy.path).toBe('./providers/subs.yaml')
|
||||
expect(copy.url).toBeUndefined()
|
||||
expect(copy.interval).toBeUndefined()
|
||||
expect(copy.override).toEqual({ 'dialer-proxy': 'patchbay:test1 链式' })
|
||||
})
|
||||
|
||||
it('原订阅没写 path 时给它补一个,否则副本认不到该读哪个文件', () => {
|
||||
// 内核会按 url 哈希自己生成缓存路径,那个路径 Patchbay 算不出来
|
||||
const data = base()
|
||||
delete ((data['proxy-providers'] as ConfigObject).subs as ConfigObject).path
|
||||
const next = applySetup(data, 'test1', chained)
|
||||
const providers = next['proxy-providers'] as ConfigObject
|
||||
|
||||
expect((providers.subs as ConfigObject).path).toBe('./providers/subs.yaml')
|
||||
expect(readSetup(next, 'test1')).toEqual(chained)
|
||||
})
|
||||
|
||||
it('源订阅原有的 override 保留,不被覆盖', () => {
|
||||
const data = base()
|
||||
;((data['proxy-providers'] as ConfigObject).subs as ConfigObject).override = { udp: true }
|
||||
const next = applySetup(data, 'test1', chained)
|
||||
const copy = (next['proxy-providers'] as ConfigObject)[
|
||||
chainProviderName('test1', 'subs')
|
||||
] as ConfigObject
|
||||
|
||||
expect(copy.override).toEqual({ udp: true, 'dialer-proxy': 'patchbay:test1 链式' })
|
||||
})
|
||||
|
||||
it('关掉链式代理时,入口组和副本一起消失', () => {
|
||||
const off = applySetup(applySetup(base(), 'test1', chained), 'test1', plain)
|
||||
const names = (off['proxy-groups'] as ConfigObject[]).map((g) => (g as ConfigObject).name)
|
||||
|
||||
expect(names).not.toContain('patchbay:test1 链式')
|
||||
expect(Object.keys(off['proxy-providers'] as ConfigObject)).toEqual(['subs'])
|
||||
})
|
||||
|
||||
it('换来源时旧副本立刻消失', () => {
|
||||
// 留着的话就是一份没人引用、却还在按 interval 定时联网的订阅
|
||||
const data = base()
|
||||
const providers = data['proxy-providers'] as ConfigObject
|
||||
providers.other = { type: 'http', url: 'http://other.example/x', path: './providers/o.yaml' }
|
||||
|
||||
const first = applySetup(data, 'test1', chained)
|
||||
const second = applySetup(first, 'test1', {
|
||||
proxy: { sources: ['other'], filter: null },
|
||||
chain: { sources: ['subs'], filter: null },
|
||||
})
|
||||
|
||||
const names = Object.keys(second['proxy-providers'] as ConfigObject)
|
||||
expect(names).toContain(chainProviderName('test1', 'other'))
|
||||
expect(names).not.toContain(chainProviderName('test1', 'subs'))
|
||||
})
|
||||
|
||||
it('两路入站各自的副本互不干扰', () => {
|
||||
const data = base()
|
||||
;(data.listeners as ConfigObject[]).push({ name: 'test2', type: 'mixed', port: 7779 })
|
||||
|
||||
const next = applySetup(applySetup(data, 'test1', chained), 'test2', chained)
|
||||
const providers = next['proxy-providers'] as ConfigObject
|
||||
|
||||
expect(Object.keys(providers)).toHaveLength(3)
|
||||
expect(readSetup(next, 'test1')).toEqual(chained)
|
||||
expect(readSetup(next, 'test2')).toEqual(chained)
|
||||
})
|
||||
})
|
||||
|
||||
describe('清理', () => {
|
||||
it('删掉入站之后,几个组和副本连锁消失', () => {
|
||||
// 链式引用:SELECT 引 AUTO 和 FALLBACK,三者引副本,副本引入口组,要反复扫才清得干净
|
||||
const withInbound = applySetup(base(), 'test1', chained)
|
||||
const removed: ConfigObject = { ...withInbound, listeners: [] }
|
||||
|
||||
const cleaned = pruneGenerated(removed)
|
||||
expect(cleaned['proxy-groups']).toBeUndefined()
|
||||
expect(Object.keys(cleaned['proxy-providers'] as ConfigObject)).toEqual(['subs'])
|
||||
})
|
||||
|
||||
it('入站还在就一个都不删', () => {
|
||||
const data = applySetup(base(), 'test1', chained)
|
||||
expect(pruneGenerated(data)).toBe(data)
|
||||
})
|
||||
|
||||
it('用户自己建的组和订阅一律不碰,哪怕真的没人引用', () => {
|
||||
const data: ConfigObject = {
|
||||
'proxy-groups': [{ name: '我建的组', type: 'select', use: ['subs'] }],
|
||||
'proxy-providers': { subs: { type: 'http', url: URL } },
|
||||
}
|
||||
expect(pruneGenerated(data)).toBe(data)
|
||||
})
|
||||
|
||||
it('没有可删的时候原样返回,不制造无谓的改动', () => {
|
||||
// 返回同一个对象,落盘链路才看得出「内容没变」而跳过备份和重载
|
||||
const data: ConfigObject = { 'proxy-groups': [{ name: 'PROXY' }] }
|
||||
expect(pruneGenerated(data)).toBe(data)
|
||||
})
|
||||
|
||||
it('被规则引用的生成组不删,连它引用的两个组一起留下', () => {
|
||||
const data = applySetup(base(), 'test1', plain)
|
||||
const orphaned: ConfigObject = { ...data, listeners: [], rules: ['MATCH,patchbay:test1'] }
|
||||
expect((pruneGenerated(orphaned)['proxy-groups'] as ConfigObject[]).length).toBe(3)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,501 @@
|
||||
/**
|
||||
* 每一路入站的专属策略组。
|
||||
*
|
||||
* 一路入站配三个组,入站的 `proxy:` 指向其中的 SELECT,换线是换那个组的当前选中,
|
||||
* 不改配置文件(决策记录 0007):
|
||||
* SELECT 手动选。它的成员是 DIRECT、下面两个组,加上订阅里的线路
|
||||
* AUTO url-test,自动挑延迟最低的
|
||||
* FALLBACK fallback,按顺序挑第一个测得通的
|
||||
* 界面上这三个是并排的 tab。做成三个而不是让用户自己配,是因为它们就是所有 clash 配置
|
||||
* 里那三种固定的挑法,让人从零拼一遍没有意义。
|
||||
*
|
||||
* 开了链式代理时再多一个入口组,以及若干份订阅声明的副本——`dialer-proxy` 写不到策略组
|
||||
* 上,只能挂在整个订阅上(内核源码 adapter/outboundgroup/parser.go:68-70)。
|
||||
*
|
||||
* 配置里的东西属于谁全靠三条线索还原,不靠解析名字:
|
||||
* 四个组 名字由入站名推出来
|
||||
* 订阅副本 override.dialer-proxy 指向哪一路的入口组
|
||||
* 副本的来源 url 和哪个用户订阅相同
|
||||
*/
|
||||
import type { ConfigObject } from '../vendor/config-editor/index.ts'
|
||||
import { resolveDestination } from './inbounds.ts'
|
||||
import type { Inbound } from './inbounds.ts'
|
||||
import { lastSwitchableGroup, resolveChain } from './outbound-chain.ts'
|
||||
import type { RuntimeNode } from './outbound-chain.ts'
|
||||
|
||||
/**
|
||||
* Patchbay 自动创建的策略组和订阅的名字前缀。
|
||||
*
|
||||
* 名字是识别它们的唯一可靠标记。注释靠不住——配置改写引擎重建整个被碰到的顶层段落,
|
||||
* 段落内的注释会丢(决策记录 0002)。改这个前缀会让已有配置里的组失去标记,别改。
|
||||
*/
|
||||
export const GENERATED_PREFIX = 'patchbay:'
|
||||
|
||||
export function isGenerated(name: string): boolean {
|
||||
return name.startsWith(GENERATED_PREFIX)
|
||||
}
|
||||
|
||||
/** 手动选的那个组。入站的 `proxy:` 指向它,它的当前选中决定这一路走哪。 */
|
||||
export function proxyGroupName(inbound: string): string {
|
||||
return `${GENERATED_PREFIX}${inbound}`
|
||||
}
|
||||
|
||||
/** 自动测速组,作为 SELECT 的一个成员出现。 */
|
||||
export function autoGroupName(inbound: string): string {
|
||||
return `${GENERATED_PREFIX}${inbound} AUTO`
|
||||
}
|
||||
|
||||
/** 故障转移组,同上。 */
|
||||
export function fallbackGroupName(inbound: string): string {
|
||||
return `${GENERATED_PREFIX}${inbound} FALLBACK`
|
||||
}
|
||||
|
||||
/** 链式代理的入口组。订阅副本的 `dialer-proxy` 指向它。 */
|
||||
export function chainGroupName(inbound: string): string {
|
||||
return `${GENERATED_PREFIX}${inbound} 链式`
|
||||
}
|
||||
|
||||
/**
|
||||
* 一个出站在界面上叫什么。
|
||||
*
|
||||
* 生成的组要去掉 `patchbay:` 前缀和入站名。用户从没建过这些组,让他在卡片和链条上读到
|
||||
* `patchbay:test1 FALLBACK` 只是噪音——那一屏本来就是这一路入站的详情,名字里再重复
|
||||
* 一遍入站名不增加任何信息。
|
||||
*/
|
||||
export function displayName(name: string): string {
|
||||
if (!isGenerated(name)) return name
|
||||
const rest = name.slice(GENERATED_PREFIX.length)
|
||||
for (const [suffix, label] of [
|
||||
[' AUTO', 'AUTO'],
|
||||
[' FALLBACK', 'FALLBACK'],
|
||||
[' 链式', '链式代理'],
|
||||
] as const) {
|
||||
if (rest.endsWith(suffix)) return label
|
||||
}
|
||||
return rest
|
||||
}
|
||||
|
||||
/** 这一路的三个组,按界面上的显示顺序。 */
|
||||
function ownGroups(inbound: string): Array<{ name: string; label: string }> {
|
||||
return [
|
||||
{ name: proxyGroupName(inbound), label: 'SELECT' },
|
||||
{ name: autoGroupName(inbound), label: 'AUTO' },
|
||||
{ name: fallbackGroupName(inbound), label: 'FALLBACK' },
|
||||
]
|
||||
}
|
||||
|
||||
/** FNV-1a。只用来给名字和文件名去重,不是安全用途,所以不引哈希库,浏览器端也要能算。 */
|
||||
function shortHash(text: string): string {
|
||||
let h = 0x811c9dc5
|
||||
for (let i = 0; i < text.length; i += 1) {
|
||||
h ^= text.charCodeAt(i)
|
||||
h = Math.imul(h, 0x01000193) >>> 0
|
||||
}
|
||||
return h.toString(16).padStart(8, '0')
|
||||
}
|
||||
|
||||
const pairKey = (inbound: string, source: string) => `${inbound} ${source}`
|
||||
|
||||
/**
|
||||
* 「某一路入站 × 某个来源订阅」这个组合对应的订阅副本叫什么。
|
||||
*
|
||||
* 名字里带哈希是因为 `proxy-providers` 是个映射,两个组合撞名会让其中一个被静默丢掉,
|
||||
* 表现是链式代理挂到了别的入站上。带上入站名只是为了翻配置文件时读得懂。
|
||||
*/
|
||||
export function chainProviderName(inbound: string, source: string): string {
|
||||
return `${GENERATED_PREFIX}chain ${inbound} ${shortHash(pairKey(inbound, source))}`
|
||||
}
|
||||
|
||||
/**
|
||||
* 一个订阅的缓存文件落在哪。
|
||||
*
|
||||
* 内核把拉回来的内容写在这里(内核源码 component/resource/vehicle.go:42-47)。没写
|
||||
* `path:` 时它按 url 哈希自己生成一个(adapter/provider/parser.go:87),那个路径 Patchbay
|
||||
* 算不出来,所以缺的时候补一个确定的进去。
|
||||
*/
|
||||
export function providerCachePath(name: string): string {
|
||||
const safe = name.replace(/[^\p{L}\p{N}_-]+/gu, '-').replace(/^-+|-+$/g, '')
|
||||
return `./providers/${safe || shortHash(name)}.yaml`
|
||||
}
|
||||
|
||||
/** 一组线路从哪来、要哪些。三个组共用同一份,它们只是挑法不同。 */
|
||||
export interface GroupSpec {
|
||||
/** 成员来自哪几个订阅,写进组的 `use:` */
|
||||
sources: string[]
|
||||
/** 只要名字匹配这个正则的线路。null 表示全要 */
|
||||
filter: string | null
|
||||
}
|
||||
|
||||
/** 一路入站的出站设置。 */
|
||||
export interface OutboundSetup {
|
||||
proxy: GroupSpec
|
||||
/** 链式代理的入口。null 表示没开 */
|
||||
chain: GroupSpec | null
|
||||
}
|
||||
|
||||
function isPlainObject(value: unknown): value is ConfigObject {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||
}
|
||||
|
||||
function groupsOf(data: ConfigObject): ConfigObject[] {
|
||||
return (Array.isArray(data['proxy-groups']) ? data['proxy-groups'] : []).filter(isPlainObject)
|
||||
}
|
||||
|
||||
function providersOf(data: ConfigObject): ConfigObject {
|
||||
return isPlainObject(data['proxy-providers']) ? data['proxy-providers'] : {}
|
||||
}
|
||||
|
||||
function findGroup(data: ConfigObject, name: string): ConfigObject | null {
|
||||
return groupsOf(data).find((g) => g.name === name) ?? null
|
||||
}
|
||||
|
||||
function stringList(value: unknown): string[] {
|
||||
return Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : []
|
||||
}
|
||||
|
||||
function specOf(group: ConfigObject): GroupSpec {
|
||||
return {
|
||||
sources: stringList(group.use),
|
||||
filter: typeof group.filter === 'string' && group.filter ? group.filter : null,
|
||||
}
|
||||
}
|
||||
|
||||
/** 用户自己配的订阅,不含 Patchbay 生成的副本。界面上「来源」能选的就是这些。 */
|
||||
export function userProviders(data: ConfigObject): string[] {
|
||||
return Object.keys(providersOf(data)).filter((name) => !isGenerated(name))
|
||||
}
|
||||
|
||||
/** 某个策略组从哪几个订阅取成员。组不存在时返回 null。 */
|
||||
export function groupUses(data: ConfigObject, name: string): string[] | null {
|
||||
const group = findGroup(data, name)
|
||||
return group ? stringList(group.use) : null
|
||||
}
|
||||
|
||||
/** 这个订阅副本是哪一路入站的。不是副本、或者认不出归属时返回 null。 */
|
||||
function chainOwnerOf(provider: unknown): string | null {
|
||||
if (!isPlainObject(provider)) return null
|
||||
const override = provider.override
|
||||
if (!isPlainObject(override)) return null
|
||||
const target = override['dialer-proxy']
|
||||
if (typeof target !== 'string' || !isGenerated(target)) return null
|
||||
const suffix = ' 链式'
|
||||
if (!target.endsWith(suffix)) return null
|
||||
return target.slice(GENERATED_PREFIX.length, target.length - suffix.length)
|
||||
}
|
||||
|
||||
/** 副本的来源订阅叫什么。靠读同一个缓存文件来认,因为名字不可靠解析。 */
|
||||
function sourceOfCopy(data: ConfigObject, copy: ConfigObject): string | null {
|
||||
if (typeof copy.path !== 'string') return null
|
||||
for (const [name, entry] of Object.entries(providersOf(data))) {
|
||||
if (isGenerated(name) || !isPlainObject(entry)) continue
|
||||
if (entry.path === copy.path) return name
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* 读出这一路入站当前的出站设置。
|
||||
*
|
||||
* 返回 null 表示它还没在专属组模式下,可能是走规则表、直连,或者指向用户自己建的组。
|
||||
*/
|
||||
export function readSetup(data: ConfigObject, inbound: string): OutboundSetup | null {
|
||||
const proxyGroup = findGroup(data, proxyGroupName(inbound))
|
||||
if (!proxyGroup) return null
|
||||
|
||||
const spec = specOf(proxyGroup)
|
||||
const providers = providersOf(data)
|
||||
const copies = spec.sources.filter((name) => chainOwnerOf(providers[name]) === inbound)
|
||||
|
||||
if (copies.length === 0) return { proxy: spec, chain: null }
|
||||
|
||||
const chainGroup = findGroup(data, chainGroupName(inbound))
|
||||
const sources = copies
|
||||
.map((name) => sourceOfCopy(data, providers[name] as ConfigObject))
|
||||
.filter((name): name is string => name !== null)
|
||||
|
||||
return {
|
||||
proxy: { sources, filter: spec.filter },
|
||||
chain: chainGroup ? specOf(chainGroup) : { sources: [], filter: null },
|
||||
}
|
||||
}
|
||||
|
||||
function makeGroup(
|
||||
name: string,
|
||||
type: string,
|
||||
use: string[],
|
||||
filter: string | null,
|
||||
members: string[] = [],
|
||||
): ConfigObject {
|
||||
const group: ConfigObject = { name, type }
|
||||
if (members.length > 0) group.proxies = members
|
||||
if (use.length > 0) group.use = use
|
||||
if (filter) group.filter = filter
|
||||
// url-test 和 fallback 要有测速地址才知道谁快谁通。不写的话内核会借用来源订阅自己的
|
||||
// 健康检查地址(adapter/outboundgroup/parser.go:139-148),但那依赖订阅写了它,
|
||||
// 不能指望;写死一个和内核默认一致的更稳。
|
||||
if (type !== 'select') {
|
||||
group.url = 'https://www.gstatic.com/generate_204'
|
||||
group.interval = 300
|
||||
}
|
||||
return group
|
||||
}
|
||||
|
||||
function upsert(list: ConfigObject[], entry: ConfigObject): ConfigObject[] {
|
||||
const at = list.findIndex((item) => item.name === entry.name)
|
||||
if (at < 0) return [...list, entry]
|
||||
const next = [...list]
|
||||
next[at] = entry
|
||||
return next
|
||||
}
|
||||
|
||||
/**
|
||||
* 照着一个用户订阅做出带 `dialer-proxy` 的那一份。
|
||||
*
|
||||
* 副本是 `type: file`,读的正是原订阅那个缓存文件,自己不联网。这一点是硬性的:副本要是
|
||||
* 自己去拉,订阅地址一不可达它就是空的,而这一路入站的线路全部来自它,结果是端口还在
|
||||
* 监听却一条线都没有。派生自原订阅已经落盘的内容,原订阅有什么副本就有什么。
|
||||
*
|
||||
* 内核对 file 类型的 provider 自带文件监视(component/resource/fetcher.go:212-228),
|
||||
* 原订阅刷新写盘之后副本自动跟着更新,不需要 Patchbay 做任何事。
|
||||
*
|
||||
* `filter` 这些影响「这个订阅里有哪些线路」的字段照抄,`url` 和 `interval` 去掉,
|
||||
* 它们只对 http 类型有意义。
|
||||
*/
|
||||
function makeChainProvider(source: ConfigObject, inbound: string, cachePath: string): ConfigObject {
|
||||
const override = isPlainObject(source.override) ? { ...source.override } : {}
|
||||
override['dialer-proxy'] = chainGroupName(inbound)
|
||||
const { url: _url, interval: _interval, ...rest } = source
|
||||
return { ...rest, type: 'file', path: cachePath, override }
|
||||
}
|
||||
|
||||
/**
|
||||
* 把一路入站的出站设置写回配置。
|
||||
*
|
||||
* 开了链式代理时,三个组的成员都改从订阅副本里取,因为只有副本挂着 `dialer-proxy`。
|
||||
* 用户选的来源订阅仍然可以从副本的 `url` 还原出来,所以配置文件之外不需要另存状态。
|
||||
*/
|
||||
export function applySetup(data: ConfigObject, inbound: string, setup: OutboundSetup): ConfigObject {
|
||||
const next = { ...data }
|
||||
const chained = setup.chain !== null
|
||||
const providers = { ...providersOf(next) }
|
||||
|
||||
// 先清掉这一路原有的副本,再按新的来源重建。改来源时旧的副本必须消失,
|
||||
// 否则代理组不再引用它,它就成了一份没人用却还在定时拉取的订阅。
|
||||
for (const [name, entry] of Object.entries(providers)) {
|
||||
if (chainOwnerOf(entry) === inbound) delete providers[name]
|
||||
}
|
||||
|
||||
const use: string[] = []
|
||||
if (chained) {
|
||||
for (const sourceName of setup.proxy.sources) {
|
||||
const source = providers[sourceName]
|
||||
if (!isPlainObject(source)) continue
|
||||
// 副本靠「读同一个缓存文件」认亲。原订阅没写 path 时内核按 url 哈希自己生成一个,
|
||||
// 那个路径这边算不出来,所以先给原订阅补一个确定的。
|
||||
const cachePath =
|
||||
typeof source.path === 'string' && source.path ? source.path : providerCachePath(sourceName)
|
||||
providers[sourceName] = { ...source, path: cachePath }
|
||||
const copyName = chainProviderName(inbound, sourceName)
|
||||
providers[copyName] = makeChainProvider(providers[sourceName], inbound, cachePath)
|
||||
use.push(copyName)
|
||||
}
|
||||
} else {
|
||||
use.push(...setup.proxy.sources)
|
||||
}
|
||||
|
||||
const { filter } = setup.proxy
|
||||
let groups = groupsOf(next)
|
||||
groups = upsert(
|
||||
groups,
|
||||
makeGroup(proxyGroupName(inbound), 'select', use, filter, [
|
||||
'DIRECT',
|
||||
autoGroupName(inbound),
|
||||
fallbackGroupName(inbound),
|
||||
]),
|
||||
)
|
||||
groups = upsert(groups, makeGroup(autoGroupName(inbound), 'url-test', use, filter))
|
||||
groups = upsert(groups, makeGroup(fallbackGroupName(inbound), 'fallback', use, filter))
|
||||
|
||||
if (chained) {
|
||||
groups = upsert(
|
||||
groups,
|
||||
makeGroup(chainGroupName(inbound), 'select', setup.chain!.sources, setup.chain!.filter),
|
||||
)
|
||||
} else {
|
||||
groups = groups.filter((g) => g.name !== chainGroupName(inbound))
|
||||
}
|
||||
next['proxy-groups'] = groups
|
||||
|
||||
if (Object.keys(providers).length === 0) delete next['proxy-providers']
|
||||
else next['proxy-providers'] = providers
|
||||
|
||||
const listeners = (Array.isArray(next.listeners) ? next.listeners : []).map((entry) =>
|
||||
isPlainObject(entry) && entry.name === inbound
|
||||
? { ...entry, proxy: proxyGroupName(inbound) }
|
||||
: entry,
|
||||
)
|
||||
if (listeners.length > 0) next.listeners = listeners
|
||||
|
||||
return next
|
||||
}
|
||||
|
||||
/** 配置里指向某个名字的地方有几处。用来判断生成的东西还有没有人在用。 */
|
||||
function referencesTo(data: ConfigObject, name: string): number {
|
||||
let count = 0
|
||||
|
||||
for (const entry of Array.isArray(data.listeners) ? data.listeners : []) {
|
||||
if (isPlainObject(entry) && entry.proxy === name) count += 1
|
||||
}
|
||||
|
||||
for (const group of groupsOf(data)) {
|
||||
if (stringList(group.proxies).includes(name)) count += 1
|
||||
if (stringList(group.use).includes(name)) count += 1
|
||||
}
|
||||
|
||||
for (const entry of Object.values(providersOf(data))) {
|
||||
if (!isPlainObject(entry) || !isPlainObject(entry.override)) continue
|
||||
if (entry.override['dialer-proxy'] === name) count += 1
|
||||
}
|
||||
|
||||
for (const rule of Array.isArray(data.rules) ? data.rules : []) {
|
||||
// 规则是逗号分隔的,目标出站是其中一段,形如 MATCH,目标 或 DOMAIN,x,目标
|
||||
if (typeof rule === 'string' && rule.split(',').some((part) => part.trim() === name)) count += 1
|
||||
}
|
||||
|
||||
return count
|
||||
}
|
||||
|
||||
/**
|
||||
* 删掉没人再引用的生成组和订阅副本。
|
||||
*
|
||||
* 每次改完配置都跑一遍。删一路入站之后,它的几个组和几份副本会先后变成孤儿,不清理的话
|
||||
* 文件里就攒下一堆用户从没主动建过的东西,而副本还在按 interval 定时联网。
|
||||
*
|
||||
* 要反复扫:AUTO 和 FALLBACK 被 SELECT 引用,入口组被副本引用,副本被那三个组引用,
|
||||
* 所以删掉 SELECT 之后下一轮才轮到它们。只动带前缀的,用户自己建的一律不碰。
|
||||
*/
|
||||
export function pruneGenerated(data: ConfigObject): ConfigObject {
|
||||
const groups = Array.isArray(data['proxy-groups']) ? data['proxy-groups'] : []
|
||||
const keptGroups = groups.filter((group) => {
|
||||
if (!isPlainObject(group)) return true
|
||||
const name = group.name
|
||||
if (typeof name !== 'string' || !isGenerated(name)) return true
|
||||
return referencesTo(data, name) > 0
|
||||
})
|
||||
|
||||
const providers = providersOf(data)
|
||||
const keptProviders = Object.entries(providers).filter(
|
||||
([name]) => !isGenerated(name) || referencesTo(data, name) > 0,
|
||||
)
|
||||
const providersChanged = keptProviders.length !== Object.keys(providers).length
|
||||
|
||||
if (keptGroups.length === groups.length && !providersChanged) return data
|
||||
|
||||
const next = { ...data }
|
||||
if (keptGroups.length === 0) delete next['proxy-groups']
|
||||
else next['proxy-groups'] = keptGroups
|
||||
|
||||
if (providersChanged) {
|
||||
if (keptProviders.length === 0) delete next['proxy-providers']
|
||||
else next['proxy-providers'] = Object.fromEntries(keptProviders)
|
||||
}
|
||||
|
||||
return pruneGenerated(next)
|
||||
}
|
||||
|
||||
/**
|
||||
* 把所有已接管入站的生成组按当前的生成规则重建一遍。
|
||||
*
|
||||
* 每次写配置前跑。生成的东西必须永远和生成它的代码一致,否则改过生成规则之后,早先建的
|
||||
* 那些就停在旧形状上,界面按新形状去找,找不到就静默少一块——tab 少了两个正是这么来的。
|
||||
* `applySetup` 幂等,形状没变时返回的内容一样,落盘链路会看出内容没变而跳过重载。
|
||||
*/
|
||||
export function syncGenerated(data: ConfigObject, inbounds: Inbound[]): ConfigObject {
|
||||
let next = data
|
||||
for (const inbound of inbounds) {
|
||||
const setup = readSetup(next, inbound.name)
|
||||
const mode = inbound.outbound
|
||||
if (!setup || mode.kind !== 'named' || mode.name !== proxyGroupName(inbound.name)) continue
|
||||
next = applySetup(next, inbound.name, setup)
|
||||
}
|
||||
return next
|
||||
}
|
||||
|
||||
/** 面板上一个 tab 对应的策略组。 */
|
||||
export interface PanelGroup {
|
||||
name: string
|
||||
/** tab 上显示什么。自己的组显示挑法,共用的组显示它自己的名字 */
|
||||
label: string
|
||||
/** 它从哪几个订阅取成员。测延迟要顺着来源找,见 web/runtime.ts 的 membersOf */
|
||||
uses: string[]
|
||||
/** 能不能点成员换选中 */
|
||||
pickable: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* 这一路入站的面板上能操作哪些策略组。
|
||||
*
|
||||
* 只此一处回答这个问题。之前它散在四个地方(页面算一次能不能点、组件再算一次、
|
||||
* 共用与否又各算一次),加一种情况就要同时改四处,漏一处就是界面和实际操作对不上。
|
||||
*
|
||||
* 两种情况:接管过的入站是它自己那三个组;没接管的(比如 `mixed-port`,配置顶层的端口
|
||||
* 字段没有 `proxy` 可写)落到它顺着规则表走到的那个手动选择组上,那个组是共用的。
|
||||
*/
|
||||
export function panelGroups(
|
||||
data: ConfigObject,
|
||||
runtime: Record<string, RuntimeNode>,
|
||||
inbound: Inbound,
|
||||
): { groups: PanelGroup[]; shared: boolean } {
|
||||
const mode = inbound.outbound
|
||||
const managed = mode.kind === 'named' && mode.name === proxyGroupName(inbound.name)
|
||||
|
||||
if (managed) {
|
||||
return {
|
||||
shared: false,
|
||||
groups: ownGroups(inbound.name)
|
||||
// 保存完到内核重载完之间,组已经在配置里但运行时还没有,这时先不显示那个 tab
|
||||
.filter((g) => runtime[g.name])
|
||||
.map((g) => ({
|
||||
...g,
|
||||
uses: groupUses(data, g.name) ?? [],
|
||||
// 只有手动选的那个能点。另外两个自己决定用哪条,理由见 outbound-chain.ts
|
||||
pickable: runtime[g.name]?.type === 'Selector',
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
const chain = resolveChain(runtime, resolveDestination(data, inbound))
|
||||
const fallback = lastSwitchableGroup(runtime, chain)
|
||||
if (!fallback) return { groups: [], shared: false }
|
||||
return {
|
||||
shared: true,
|
||||
groups: [
|
||||
{
|
||||
name: fallback.group,
|
||||
label: fallback.group,
|
||||
uses: groupUses(data, fallback.group) ?? [],
|
||||
pickable: true,
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 筛选条件会留下哪些线路。界面上用来在保存前当场告诉用户「匹配到几条」。
|
||||
*
|
||||
* 照着内核的规则算(`adapter/outboundgroup/groupbase.go:72-76, 168-195`):反引号把
|
||||
* 条件切成多条独立正则,取并集;每条都是部分匹配,不自动加锚点。
|
||||
*
|
||||
* 内核用的是支持前后向查找的 .NET 风味引擎,浏览器只有 JS 的,所以复杂写法这里算出来的
|
||||
* 数字可能和内核不一致。写法有误时返回 null,界面据此提示而不是显示一个错的数字。
|
||||
*/
|
||||
export function linesMatching(filter: string | null, lines: string[]): string[] | null {
|
||||
if (!filter) return lines
|
||||
let regexps: RegExp[]
|
||||
try {
|
||||
regexps = filter.split('`').map((part) => new RegExp(part))
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
return lines.filter((line) => regexps.some((re) => re.test(line)))
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from 'bun:test'
|
||||
import { acceptsManualChoice, lastSwitchableGroup, resolveChain } from './outbound-chain.ts'
|
||||
import { lastSwitchableGroup, resolveChain } from './outbound-chain.ts'
|
||||
import type { RuntimeNode } from './outbound-chain.ts'
|
||||
|
||||
/**
|
||||
@@ -41,25 +41,11 @@ describe('解析流量最终走到哪条线', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('哪种策略组接受手动选择', () => {
|
||||
it('只有 Selector', () => {
|
||||
expect(acceptsManualChoice('Selector')).toBe(true)
|
||||
})
|
||||
|
||||
it('自动决定的那几种都不接受', () => {
|
||||
// 内核里 URLTest 按延迟挑、Fallback 挑第一个可用、LoadBalance 分摊,
|
||||
// 它们的选中结果是算出来的,点了会被算回去
|
||||
for (const type of ['URLTest', 'Fallback', 'LoadBalance', 'Relay']) {
|
||||
expect(acceptsManualChoice(type)).toBe(false)
|
||||
}
|
||||
expect(acceptsManualChoice(undefined)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('找出用户能换选中的那一层', () => {
|
||||
it('跳过自动决定的组,落在最后一个 Selector 上', () => {
|
||||
// 链条是 PROXY(Selector) → AUTO(URLTest) → 线路。
|
||||
// 能点的是 PROXY,不是 AUTO——让人去点 URLTest 的成员,点完会被延迟测试算回去。
|
||||
// 链条是 PROXY(Selector) → AUTO(URLTest) → 线路。能点的是 PROXY 不是 AUTO:
|
||||
// 内核对 URLTest 也接受手动指定,但那条线测不通时指定会临时让位,
|
||||
// 和「选了就一直是它」不是一回事,摆成同一个控件会骗人。
|
||||
const chain = resolveChain(runtime, 'PROXY')
|
||||
expect(lastSwitchableGroup(runtime, chain)).toEqual({
|
||||
group: 'PROXY',
|
||||
@@ -78,7 +64,7 @@ describe('找出用户能换选中的那一层', () => {
|
||||
expect(lastSwitchableGroup(nested, resolveChain(nested, '外层'))?.group).toBe('内层')
|
||||
})
|
||||
|
||||
it('整条链都是自动决定时返回空', () => {
|
||||
it('整条链都不是 Selector 时返回空', () => {
|
||||
const auto: Record<string, RuntimeNode> = {
|
||||
AUTO: { type: 'URLTest', now: '线路A', all: ['线路A'] },
|
||||
线路A: { type: 'Vmess' },
|
||||
|
||||
@@ -19,18 +19,6 @@ export interface RuntimeNode {
|
||||
all?: string[]
|
||||
}
|
||||
|
||||
/**
|
||||
* 这个类型的策略组接不接受手动选择。
|
||||
*
|
||||
* 内核里只有 `Selector` 是「由人来选」的(内核源码 constant/adapters.go:240-248 列出
|
||||
* 全部类型)。`URLTest` 按延迟挑最快的、`Fallback` 挑第一个可用的、`LoadBalance` 在成员
|
||||
* 之间分摊——它们的选中结果是算出来的,界面上给一个能点的列表只会让人困惑:点完可能
|
||||
* 立刻被算回去。`Relay` 已经被内核移除。
|
||||
*/
|
||||
export function acceptsManualChoice(type: string | undefined): boolean {
|
||||
return type === 'Selector'
|
||||
}
|
||||
|
||||
/**
|
||||
* 从落脚的出站一路跟着「当前选中」往下走。
|
||||
*
|
||||
@@ -58,13 +46,16 @@ export interface SwitchableGroup {
|
||||
}
|
||||
|
||||
/**
|
||||
* 链条上最后一个能由人来选的策略组。
|
||||
* 链条上最后一个 `Selector` 组。这一路入站没被 Patchbay 接管时,界面上能点的就是它。
|
||||
*
|
||||
* 取最后一个而不是第一个,是因为越靠近线路的那一层越接近「换线路」这个意图;
|
||||
* 前面的层换的是「走哪套策略」,那是另一回事。
|
||||
*
|
||||
* 跳过自动决定的组:让人去点一个 URLTest 组的成员,点完会被延迟测试算回去,
|
||||
* 那不是选择,是错觉。
|
||||
* 只认 `Selector`,尽管内核对 `URLTest` 和 `Fallback` 也接受手动指定
|
||||
* (hub/route/proxies.go:85-90 检查的是 `SelectAble` 接口,不是类型)。原因是那两种的
|
||||
* 手动指定会自己失效:`URLTest` 选中的线路测不通时临时让位给最快的
|
||||
* (adapter/outboundgroup/urltest.go:103-116),`Fallback` 更狠,测不通一次就把手动指定
|
||||
* 永久清掉(fallback.go:117)。把它们和「选了就一直是它」摆成同一个控件会骗人。
|
||||
*/
|
||||
export function lastSwitchableGroup(
|
||||
runtime: Record<string, RuntimeNode>,
|
||||
@@ -73,7 +64,7 @@ export function lastSwitchableGroup(
|
||||
for (let i = chain.length - 1; i >= 0; i -= 1) {
|
||||
const name = chain[i]!
|
||||
const node = runtime[name]
|
||||
if (!node?.all?.length || !acceptsManualChoice(node.type)) continue
|
||||
if (!node?.all?.length || node.type !== 'Selector') continue
|
||||
return { group: name, members: node.all, now: node.now ?? '' }
|
||||
}
|
||||
return null
|
||||
|
||||
@@ -146,7 +146,15 @@ const current = computed(() => NAV.find((n) => n.key === active.value))
|
||||
}
|
||||
|
||||
/* ── 侧栏 ───────────────────────────────────── */
|
||||
/*
|
||||
* 钉在视口里。不加 sticky 的话它会被网格行撑到和主区一样高,页面一长,
|
||||
* 导航就跟着滚出屏幕外,而它是全局导航,任何时候都该够得着。
|
||||
*/
|
||||
.side {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
align-self: start;
|
||||
height: 100vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--s-5);
|
||||
|
||||
@@ -5,11 +5,24 @@
|
||||
* 只管显示和选中,不碰任何数据。
|
||||
*/
|
||||
import { inboundTypeLabel, isUnsetOutbound, outboundLabel } from '@shared/inbounds.ts'
|
||||
import { displayOutboundName } from '@shared/filter-groups.ts'
|
||||
import { displayName, isGenerated } from '@shared/inbound-groups.ts'
|
||||
import type { Inbound } from '@shared/inbounds.ts'
|
||||
import { runtime } from '../runtime'
|
||||
|
||||
defineProps<{ inbounds: Inbound[] }>()
|
||||
const selected = defineModel<string | null>('selected', { required: true })
|
||||
|
||||
/**
|
||||
* 这一行右侧显示什么。
|
||||
*
|
||||
* 指向 Patchbay 自动创建的代理组时显示那个组当前选中的线路,而不是组名——组名是
|
||||
* 「patchbay:」加入站名,和左边的名字列完全重复,等于一列没有信息。
|
||||
*/
|
||||
function outboundOf(inbound: Inbound): string {
|
||||
const mode = inbound.outbound
|
||||
if (mode.kind !== 'named' || !isGenerated(mode.name)) return outboundLabel(mode)
|
||||
return displayName(runtime.value[mode.name]?.now ?? '') || '未选择'
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -27,7 +40,7 @@ const selected = defineModel<string | null>('selected', { required: true })
|
||||
<span v-if="inbound.isDefault" class="tag">默认</span>
|
||||
</span>
|
||||
<span :class="['out mono', isUnsetOutbound(inbound.outbound) && 'is-muted']">
|
||||
{{ displayOutboundName(outboundLabel(inbound.outbound)) }}
|
||||
{{ outboundOf(inbound) }}
|
||||
</span>
|
||||
</button>
|
||||
</li>
|
||||
|
||||
@@ -23,6 +23,11 @@ defineProps<{
|
||||
testing?: boolean
|
||||
/** 能不能测延迟。内置出站没得测 */
|
||||
testable?: boolean
|
||||
/**
|
||||
* 选中态用哪一组颜色。同一屏上有两种「当前选中」,一种是流量最后从哪出去,
|
||||
* 一种是流量先经过哪,不区分颜色就分不清哪张卡属于哪一件事。
|
||||
*/
|
||||
tone?: 'proxy' | 'chain'
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{ pick: []; test: [] }>()
|
||||
@@ -36,7 +41,15 @@ function delayClass(ms: number | null): string {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div :class="['card', selected && 'is-on', disabledReason && 'is-off', pending && 'is-pending']">
|
||||
<div
|
||||
:class="[
|
||||
'card',
|
||||
tone === 'chain' && 'tone-chain',
|
||||
selected && 'is-on',
|
||||
disabledReason && 'is-off',
|
||||
pending && 'is-pending',
|
||||
]"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="hit"
|
||||
@@ -70,6 +83,9 @@ function delayClass(ms: number | null): string {
|
||||
|
||||
<style scoped>
|
||||
.card {
|
||||
--tone: var(--c-accent);
|
||||
--tone-soft: var(--c-accent-soft);
|
||||
--tone-text: var(--c-accent-text);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
@@ -78,13 +94,19 @@ function delayClass(ms: number | null): string {
|
||||
background: var(--c-surface-sunken);
|
||||
}
|
||||
|
||||
.card.tone-chain {
|
||||
--tone: var(--c-chain);
|
||||
--tone-soft: var(--c-chain-soft);
|
||||
--tone-text: var(--c-chain-text);
|
||||
}
|
||||
|
||||
.card.is-on {
|
||||
border-color: var(--c-accent);
|
||||
background: var(--c-accent-soft);
|
||||
border-color: var(--tone);
|
||||
background: var(--tone-soft);
|
||||
}
|
||||
|
||||
.card:not(.is-off):hover {
|
||||
border-color: var(--c-accent);
|
||||
border-color: var(--tone);
|
||||
}
|
||||
|
||||
.card.is-off {
|
||||
@@ -120,7 +142,7 @@ function delayClass(ms: number | null): string {
|
||||
}
|
||||
|
||||
.card.is-on .name {
|
||||
color: var(--c-accent-text);
|
||||
color: var(--tone-text);
|
||||
}
|
||||
|
||||
.sub {
|
||||
@@ -157,7 +179,7 @@ function delayClass(ms: number | null): string {
|
||||
|
||||
.delay:hover:not(:disabled) {
|
||||
background: var(--c-surface);
|
||||
color: var(--c-accent-text);
|
||||
color: var(--tone-text);
|
||||
}
|
||||
|
||||
.delay:disabled {
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 挑几个订阅。已选的是一排 tag,末尾一个加号,点开是还没选的那些。
|
||||
*
|
||||
* 不用原生 select:它在已选项旁边显示的是「当前值」,而这里要表达的是「已经选了这几个」,
|
||||
* 两种语义。之前用 select 拼出来的那版,加号和 tag 的对齐、宽度、选中后的复位都得单独调,
|
||||
* 全是在跟控件本身的默认行为较劲。
|
||||
*/
|
||||
import { ref } from 'vue'
|
||||
import IconAdd from '~icons/ri/add-line'
|
||||
import IconRemove from '~icons/ri/close-line'
|
||||
|
||||
defineProps<{ options: string[] }>()
|
||||
const chosen = defineModel<string[]>({ required: true })
|
||||
|
||||
const open = ref(false)
|
||||
const root = ref<HTMLElement | null>(null)
|
||||
|
||||
function add(name: string) {
|
||||
chosen.value = [...chosen.value, name]
|
||||
open.value = false
|
||||
}
|
||||
|
||||
function remove(name: string) {
|
||||
chosen.value = chosen.value.filter((item) => item !== name)
|
||||
}
|
||||
|
||||
/** 焦点离开整块时收起。判断新焦点还在不在里面,否则点列表里的按钮会先把自己关掉。 */
|
||||
function onFocusOut(event: FocusEvent) {
|
||||
const next = event.relatedTarget
|
||||
if (next instanceof Node && root.value?.contains(next)) return
|
||||
open.value = false
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div ref="root" class="picker" @focusout="onFocusOut">
|
||||
<span v-for="name in chosen" :key="name" class="tag">
|
||||
{{ name }}
|
||||
<button type="button" :title="`移除 ${name}`" @click="remove(name)">
|
||||
<IconRemove />
|
||||
</button>
|
||||
</span>
|
||||
|
||||
<div v-if="options.some((o) => !chosen.includes(o))" class="add">
|
||||
<button type="button" class="plus" title="添加订阅" @click="open = !open">
|
||||
<IconAdd />
|
||||
</button>
|
||||
|
||||
<ul v-if="open" class="menu">
|
||||
<template v-for="name in options" :key="name">
|
||||
<li v-if="!chosen.includes(name)">
|
||||
<button type="button" @click="add(name)">{{ name }}</button>
|
||||
</li>
|
||||
</template>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<span v-else-if="chosen.length === 0" class="empty">没有可选的订阅</span>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.picker {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: var(--s-2);
|
||||
}
|
||||
|
||||
.tag {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--s-1);
|
||||
height: 34px;
|
||||
padding: 0 var(--s-1) 0 var(--s-3);
|
||||
border: 1px solid var(--c-border-strong);
|
||||
border-radius: var(--r-sm);
|
||||
background: var(--c-surface-sunken);
|
||||
font-size: var(--t-sm);
|
||||
}
|
||||
|
||||
.tag button {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
border: none;
|
||||
border-radius: var(--r-sm);
|
||||
background: none;
|
||||
color: var(--c-text-faint);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.tag button:hover {
|
||||
background: var(--c-surface);
|
||||
color: var(--c-danger);
|
||||
}
|
||||
|
||||
.add {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.plus {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 34px;
|
||||
height: 34px;
|
||||
border: 1px dashed var(--c-border-strong);
|
||||
border-radius: var(--r-sm);
|
||||
background: none;
|
||||
color: var(--c-text-faint);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.plus:hover {
|
||||
border-style: solid;
|
||||
border-color: var(--c-accent);
|
||||
color: var(--c-accent-text);
|
||||
}
|
||||
|
||||
/* 浮在上面,不能把下面几行顶下去 */
|
||||
.menu {
|
||||
position: absolute;
|
||||
z-index: 1;
|
||||
top: calc(34px + var(--s-1));
|
||||
left: 0;
|
||||
min-width: 10em;
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: var(--s-1);
|
||||
border: 1px solid var(--c-border-strong);
|
||||
border-radius: var(--r-md);
|
||||
background: var(--c-surface);
|
||||
}
|
||||
|
||||
.menu button {
|
||||
width: 100%;
|
||||
padding: var(--s-2) var(--s-3);
|
||||
border: none;
|
||||
border-radius: var(--r-sm);
|
||||
background: none;
|
||||
text-align: left;
|
||||
font-size: var(--t-sm);
|
||||
white-space: nowrap;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.menu button:hover {
|
||||
background: var(--c-surface-sunken);
|
||||
}
|
||||
|
||||
.empty {
|
||||
color: var(--c-text-faint);
|
||||
font-size: var(--t-sm);
|
||||
}
|
||||
</style>
|
||||
+87
-6
@@ -10,11 +10,21 @@
|
||||
import { ref } from 'vue'
|
||||
import { api } from './api'
|
||||
import type { ProxyInfo } from './api'
|
||||
import { isGenerated } from '@shared/inbound-groups.ts'
|
||||
|
||||
/** 出站名字 → 运行时信息。内核没连接时是空的。 */
|
||||
/**
|
||||
* 出站名字 → 运行时信息。内核没连接时是空的。
|
||||
*
|
||||
* 合并了内核全局名字表和用户订阅里的线路。Patchbay 自己生成的订阅副本**不并进来**:
|
||||
* 副本里的线路和原版同名(决策记录 0007 里那套复制订阅声明的做法),并进来只会互相
|
||||
* 覆盖。要看副本里那一份,用下面的 `providers`。
|
||||
*/
|
||||
export const runtime = ref<Record<string, ProxyInfo>>({})
|
||||
|
||||
/** 订阅带来的线路,按订阅返回的顺序。 */
|
||||
/** 订阅名 → 它当前提供的线路。含 Patchbay 生成的副本,按订阅隔开所以不会撞。 */
|
||||
export const providers = ref<Record<string, ProxyInfo[]>>({})
|
||||
|
||||
/** 用户自己的订阅带来的线路,按订阅返回的顺序。不含生成的副本。 */
|
||||
export const providerLines = ref<string[]>([])
|
||||
|
||||
/** 订阅线路 → 它所属的订阅名。测它的延迟必须从所属订阅进去。 */
|
||||
@@ -26,8 +36,7 @@ export const kernel = ref<{ online: boolean; version?: string }>({ online: false
|
||||
* 重新读一遍运行时状态。
|
||||
*
|
||||
* 要读两处:`/proxies` 只包含内核全局名字表里的东西(内置出站、自有线路、策略组),
|
||||
* 订阅线路不在那张表上,它们的协议和延迟只能从 `/providers/proxies` 拿。合成一张表
|
||||
* 之后,界面就不用关心某个名字是从哪来的了。
|
||||
* 订阅线路不在那张表上,它们的协议和延迟只能从 `/providers/proxies` 拿。
|
||||
*
|
||||
* 任何一处取不到都不算错误——界面照常显示,只是少了延迟数字。内核没起来的时候正是
|
||||
* 最需要这个界面的时候。
|
||||
@@ -36,6 +45,7 @@ export async function reloadRuntime(): Promise<void> {
|
||||
kernel.value = await api.kernel().catch(() => ({ online: false }))
|
||||
if (!kernel.value.online) {
|
||||
runtime.value = {}
|
||||
providers.value = {}
|
||||
providerLines.value = []
|
||||
lineProvider.value = {}
|
||||
return
|
||||
@@ -48,13 +58,16 @@ export async function reloadRuntime(): Promise<void> {
|
||||
// 拿不到就当没有
|
||||
}
|
||||
|
||||
const byProvider: Record<string, ProxyInfo[]> = {}
|
||||
const lines: string[] = []
|
||||
const owner: Record<string, string> = {}
|
||||
try {
|
||||
const { providers } = await api.providers()
|
||||
for (const [name, provider] of Object.entries(providers)) {
|
||||
const result = await api.providers()
|
||||
for (const [name, provider] of Object.entries(result.providers)) {
|
||||
// 内核会给每个用了 proxies 的策略组造一个内部 provider,那些不是订阅
|
||||
if (provider.vehicleType === 'Compatible') continue
|
||||
byProvider[name] = provider.proxies
|
||||
if (isGenerated(name)) continue
|
||||
for (const line of provider.proxies) {
|
||||
merged[line.name] = line
|
||||
lines.push(line.name)
|
||||
@@ -66,10 +79,78 @@ export async function reloadRuntime(): Promise<void> {
|
||||
}
|
||||
|
||||
runtime.value = merged
|
||||
providers.value = byProvider
|
||||
providerLines.value = lines
|
||||
lineProvider.value = owner
|
||||
}
|
||||
|
||||
/**
|
||||
* 界面渲染一个策略组需要知道的最少信息。
|
||||
*
|
||||
* `uses` 来自配置文件,`now` 来自内核,两边缺一不可:光有名字查不到它从哪取成员,
|
||||
* 而开了链式代理之后同名线路有两份,不知道来源就分不清该显示哪一份。
|
||||
*/
|
||||
export interface GroupView {
|
||||
name: string
|
||||
uses: string[]
|
||||
}
|
||||
|
||||
/** 一条线路在界面上要显示的样子,外加测它的延迟该从哪个订阅进去。 */
|
||||
export interface LineEntry {
|
||||
name: string
|
||||
/** 它来自哪个订阅。测延迟必须带上 */
|
||||
provider: string
|
||||
info: ProxyInfo | undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* 这条线路是不是来自 Patchbay 生成的订阅副本。
|
||||
*
|
||||
* 副本整份挂着 `dialer-proxy`,所以来自副本就一定经过入口。点名加进组里的成员
|
||||
* (`DIRECT`、AUTO 和 FALLBACK 那两个组)不属于任何订阅,不在副本里。
|
||||
*/
|
||||
export function isChainedLine(name: string): boolean {
|
||||
return Object.entries(providers.value).some(
|
||||
([provider, lines]) => isGenerated(provider) && lines.some((line) => line.name === name),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 这几个订阅里一共有哪些线路。
|
||||
*
|
||||
* 只给高级配置里那个「匹配到几条」的预览用:那时用户选的来源还没保存,内核也还不知道
|
||||
* 有这么个组,只能自己按来源算一遍。已经存在的组要用下面的 `membersOf`。
|
||||
*/
|
||||
export function linesFrom(uses: string[]): string[] {
|
||||
const seen = new Set<string>()
|
||||
for (const provider of uses) {
|
||||
for (const line of providers.value[provider] ?? []) seen.add(line.name)
|
||||
}
|
||||
return [...seen]
|
||||
}
|
||||
|
||||
/**
|
||||
* 一个策略组的成员,按内核给的顺序。
|
||||
*
|
||||
* 成员名单直接用内核算好的(`/proxies` 里那个 `all`),不自己从来源订阅里推——组上的
|
||||
* `filter` 已经在内核那边生效过了,重推一遍就是把同一条规则实现两次,两边一旦不一致
|
||||
* 界面显示的就是假的。
|
||||
*
|
||||
* 每个成员还要标出它来自哪个订阅,因为测延迟得从所属订阅进去。顺着组自己的 `use:` 找而
|
||||
* 不是全局按名字查:开了链式代理之后同一个线路名在原订阅和副本里各有一份,只有顺着来源
|
||||
* 才知道该用哪一份。副本那份挂着 `dialer-proxy`,测出来是走完两跳的延迟,这正是这一路
|
||||
* 真实的延迟。点名加进来的成员(DIRECT、别的策略组)不属于任何订阅,`provider` 是空串。
|
||||
*/
|
||||
export function membersOf(view: GroupView): LineEntry[] {
|
||||
return (runtime.value[view.name]?.all ?? []).map((name) => {
|
||||
for (const provider of view.uses) {
|
||||
const line = (providers.value[provider] ?? []).find((item) => item.name === name)
|
||||
if (line) return { name, provider, info: line }
|
||||
}
|
||||
return { name, provider: '', info: runtime.value[name] }
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 切换策略组选中谁时先在本地改掉,不等内核回话。
|
||||
*
|
||||
|
||||
@@ -8,6 +8,10 @@
|
||||
*
|
||||
* 颜色只留一个强调色,用在「当前选中」和「主要操作」上。状态色(成功/警告/危险)
|
||||
* 只在真的表示状态时用,不拿来装饰。
|
||||
*
|
||||
* 唯一的例外是链式代理那一组色(--c-chain-*)。同一屏上有两种「当前选中」——流量最后
|
||||
* 从哪出去,和流量先经过哪——它们必须一眼分得开,这是含义不是装饰。挑靛蓝是因为它在
|
||||
* 这套色板里不表示任何状态,红绿琥珀都被状态占了。别把它当成通用的第二强调色。
|
||||
*/
|
||||
|
||||
:root {
|
||||
@@ -27,6 +31,11 @@
|
||||
--c-accent-soft: #e6f2f1;
|
||||
--c-accent-text: #1f5c5a;
|
||||
|
||||
/* 链式代理的「当前选中」。靛蓝,和强调色的青绿色相拉得够开 */
|
||||
--c-chain: #5145cd;
|
||||
--c-chain-soft: #eeedfb;
|
||||
--c-chain-text: #4038a8;
|
||||
|
||||
--c-danger: #b3261e;
|
||||
--c-danger-soft: #fdedec;
|
||||
--c-warn: #8a6100;
|
||||
@@ -78,6 +87,10 @@
|
||||
--c-accent-soft: #1b3330;
|
||||
--c-accent-text: #7fd4cb;
|
||||
|
||||
--c-chain: #8b83f0;
|
||||
--c-chain-soft: #241f4a;
|
||||
--c-chain-text: #a9a2f7;
|
||||
|
||||
--c-danger: #f2b8b5;
|
||||
--c-danger-soft: #3a1f1e;
|
||||
--c-warn: #e8c37a;
|
||||
|
||||
+510
-166
@@ -2,79 +2,145 @@
|
||||
/**
|
||||
* 选中那一路入站的详情。
|
||||
*
|
||||
* 分两块,因为它们是两种不同性质的动作,不该长得一样也不该给一样的反馈:
|
||||
* 流量去向 —— 换策略组当前选中谁。不写配置文件,点了立刻变。日常点的就是这个。
|
||||
* 出站 —— 换这路入站指向哪个出站。要改配置文件,走校验和重载,要等几秒。
|
||||
* 上下两半,界限就是高级配置上面那条分割线:
|
||||
* 上半 点卡片立刻生效。换的是策略组当前选中谁,不写配置文件(决策记录 0007)
|
||||
* 下半 高级配置。改的是组从哪些订阅取成员,写配置文件,要校验和重载
|
||||
*
|
||||
* 两半的反馈方式必须不一样。它们长得一样的时候,用户分不清哪个动作要等、哪个不用。
|
||||
*/
|
||||
import { computed } from 'vue'
|
||||
import type { Inbound, OutboundMode } from '@shared/inbounds.ts'
|
||||
import { lastSwitchableGroup, resolveChain } from '@shared/outbound-chain.ts'
|
||||
import { generatedGroupName } from '@shared/filter-groups.ts'
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import type { Inbound } from '@shared/inbounds.ts'
|
||||
import { displayName, linesMatching } from '@shared/inbound-groups.ts'
|
||||
import type { OutboundSetup, PanelGroup } from '@shared/inbound-groups.ts'
|
||||
import { resolveChain } from '@shared/outbound-chain.ts'
|
||||
import { latestDelay } from '../api'
|
||||
import { kernel, providerLines, runtime } from '../runtime'
|
||||
import type { GroupView } from '../runtime'
|
||||
import { isChainedLine, kernel, linesFrom, membersOf, runtime } from '../runtime'
|
||||
import OutboundCard from '../components/OutboundCard.vue'
|
||||
import IconOffline from '~icons/ri/cloud-off-line'
|
||||
import SourcePicker from '../components/SourcePicker.vue'
|
||||
import IconEdit from '~icons/ri/edit-line'
|
||||
import IconDelete from '~icons/ri/delete-bin-line'
|
||||
import IconDown from '~icons/ri/arrow-down-s-line'
|
||||
import IconUp from '~icons/ri/arrow-up-s-line'
|
||||
import IconOffline from '~icons/ri/cloud-off-line'
|
||||
|
||||
const props = defineProps<{
|
||||
inbound: Inbound
|
||||
groups: string[]
|
||||
ownProxies: string[]
|
||||
/** 流量最终交给哪个出站。走规则的入站要查到规则表末尾的 MATCH */
|
||||
destination: string | null
|
||||
/** 正在提交的那个出站的名字。只有它显示忙碌,其余照常能点 */
|
||||
pendingOutbound: string | null
|
||||
/** 能操作哪些策略组、各自能不能点。groups 为空表示这一路没有能点的组 */
|
||||
panel: { groups: PanelGroup[]; shared: boolean }
|
||||
/** 链式代理的入口组。null 表示没开 */
|
||||
chain: GroupView | null
|
||||
/** 配置里定义过的订阅,高级配置里从这里挑来源 */
|
||||
subscriptions: string[]
|
||||
/** 当前的来源和筛选,高级配置的表单初值 */
|
||||
setup: OutboundSetup | null
|
||||
/** 正在测延迟的线路 */
|
||||
testing: string[]
|
||||
/** 高级配置正在保存 */
|
||||
saving: boolean
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
pick: [mode: OutboundMode]
|
||||
edit: []
|
||||
remove: []
|
||||
/** 切换某个策略组当前选中谁 */
|
||||
select: [group: string, member: string]
|
||||
test: [name: string]
|
||||
/** 把这一路入站固定到某条订阅线路 */
|
||||
pin: [line: string]
|
||||
test: [name: string, provider: string]
|
||||
/** 保存高级配置 */
|
||||
save: [setup: OutboundSetup]
|
||||
/** 把这一路改成专属代理组模式 */
|
||||
adopt: []
|
||||
}>()
|
||||
|
||||
/**
|
||||
* 默认入站由配置顶层的端口字段声明,没有 proxy 字段可写,也不能删。
|
||||
* 它的「出站」和编辑删除按钮都不显示。
|
||||
*/
|
||||
/** 默认入站由配置顶层的端口字段声明,没有 proxy 字段可写,也不能删。 */
|
||||
const locked = computed(() => props.inbound.isDefault)
|
||||
|
||||
function describe(name: string): string {
|
||||
const info = runtime.value[name]
|
||||
if (!info) return ''
|
||||
return info.now ? `${info.type}(${info.now})` : info.type
|
||||
}
|
||||
const activeTab = ref('')
|
||||
watch(
|
||||
() => props.panel.groups,
|
||||
(list) => {
|
||||
if (!list.some((t) => t.name === activeTab.value)) activeTab.value = list[0]?.name ?? ''
|
||||
},
|
||||
{ immediate: true },
|
||||
)
|
||||
|
||||
const delayOf = (name: string) => latestDelay(runtime.value[name])
|
||||
const activeGroup = computed(
|
||||
() => props.panel.groups.find((g) => g.name === activeTab.value) ?? null,
|
||||
)
|
||||
|
||||
/**
|
||||
* 表单里开了链式代理但还没保存。
|
||||
*
|
||||
* 这时内核里还没有入口组,卡片点不了,但候选线路是知道的,先按只读画出来。开关拨完
|
||||
* 一片空白、要按了保存才看得见东西,会让人以为开关没生效。
|
||||
*/
|
||||
const chainPreview = computed(() =>
|
||||
props.chain === null && form.value.chain ? linesFrom(form.value.chain.sources) : [],
|
||||
)
|
||||
const proxyLines = computed(() => (activeGroup.value ? membersOf(activeGroup.value) : []))
|
||||
const chainLines = computed(() => (props.chain ? membersOf(props.chain) : []))
|
||||
|
||||
const nowOf = (group: { name: string } | null) =>
|
||||
group ? (runtime.value[group.name]?.now ?? '') : ''
|
||||
const isTesting = (name: string) => props.testing.includes(name)
|
||||
|
||||
const chain = computed(() => resolveChain(runtime.value, props.destination))
|
||||
const switchable = computed(() => lastSwitchableGroup(runtime.value, chain.value))
|
||||
/**
|
||||
* 流量最终走到哪。
|
||||
*
|
||||
* 从代理组当前选中的那个开始一路跟着「当前选中」查下去。选中的是一条线路就到此为止,
|
||||
* 选中的是 `AUTO` 这种自动测速组就还要再查一层,否则只显示一个组名等于没回答。
|
||||
*/
|
||||
const exitChain = computed(() =>
|
||||
resolveChain(runtime.value, nowOf(props.panel.groups[0] ?? null) || null),
|
||||
)
|
||||
|
||||
/**
|
||||
* 这一路当前这条出口是不是真的经过入口。
|
||||
*
|
||||
* 开了链式代理不等于每条出口都走中转:`DIRECT` 是点名加进代理组的成员,不属于任何订阅,
|
||||
* 身上没有 `dialer-proxy`,选中它就是直连。这时画一跳入口是在骗人。
|
||||
*/
|
||||
const throughChain = computed(() => {
|
||||
const exit = exitChain.value.at(-1)
|
||||
return exit !== undefined && props.chain !== null && isChainedLine(exit)
|
||||
})
|
||||
|
||||
function isCurrentOutbound(mode: OutboundMode): boolean {
|
||||
const now = props.inbound.outbound
|
||||
if (now.kind !== mode.kind) return false
|
||||
return now.kind !== 'named' || now.name === (mode as { name: string }).name
|
||||
// ── 高级配置 ────────────────────────────────────────────────
|
||||
const open = ref(false)
|
||||
const form = ref<OutboundSetup>({ proxy: { sources: [], filter: null }, chain: null })
|
||||
|
||||
function reset() {
|
||||
form.value = props.setup
|
||||
? (JSON.parse(JSON.stringify(props.setup)) as OutboundSetup)
|
||||
: { proxy: { sources: [...props.subscriptions], filter: null }, chain: null }
|
||||
}
|
||||
|
||||
const BUILTINS: Array<{ mode: OutboundMode; label: string; sub: string }> = [
|
||||
{ mode: { kind: 'rules' }, label: 'RULE', sub: '由规则决定' },
|
||||
{ mode: { kind: 'direct' }, label: 'DIRECT', sub: '直接连接' },
|
||||
{ mode: { kind: 'global' }, label: 'GLOBAL', sub: '跟随 GLOBAL 组' },
|
||||
]
|
||||
// 切到别的入站时表单要跟着换,否则会把上一路的设置保存到这一路上
|
||||
watch(() => [props.inbound.id, props.setup], reset, { immediate: true, deep: true })
|
||||
|
||||
/** 这一路入站是不是已经固定在某条订阅线路上。 */
|
||||
function isPinnedTo(line: string): boolean {
|
||||
const mode = props.inbound.outbound
|
||||
return mode.kind === 'named' && mode.name === generatedGroupName(line)
|
||||
const chainOn = computed({
|
||||
get: () => form.value.chain !== null,
|
||||
set: (on: boolean) => {
|
||||
form.value.chain = on ? { sources: [...props.subscriptions], filter: null } : null
|
||||
},
|
||||
})
|
||||
|
||||
/** 当前筛选条件会留下几条线路。写错了 kept 是 null,界面据此提示而不是显示错的数字。 */
|
||||
function preview(spec: { sources: string[]; filter: string | null }) {
|
||||
const names = linesFrom(spec.sources)
|
||||
return { total: names.length, kept: linesMatching(spec.filter, names)?.length ?? null }
|
||||
}
|
||||
|
||||
const dirty = computed(() => JSON.stringify(form.value) !== JSON.stringify(props.setup))
|
||||
/**
|
||||
* 至少要选一个订阅。AUTO 和 FALLBACK 只有 `use:` 没有点名成员,一个订阅都不选就是空组,
|
||||
* 内核会直接拒绝整份配置(内核源码 adapter/outboundgroup/parser.go:117-119)。
|
||||
* 在这里拦住,比让用户按下保存再读一段内核报错好。
|
||||
*/
|
||||
const filled = (spec: { sources: string[] }) => spec.sources.length > 0
|
||||
const complete = computed(
|
||||
() => filled(form.value.proxy) && (form.value.chain === null || filled(form.value.chain)),
|
||||
)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -83,11 +149,12 @@ function isPinnedTo(line: string): boolean {
|
||||
<div class="title">
|
||||
<span class="port mono">{{ inbound.port }}</span>
|
||||
<span class="name">{{ inbound.name }}</span>
|
||||
</div>
|
||||
|
||||
<div v-if="!locked" class="acts">
|
||||
<button type="button" @click="emit('edit')"><IconEdit /> 编辑</button>
|
||||
<button type="button" class="danger" @click="emit('remove')"><IconDelete /> 删除</button>
|
||||
<button type="button" class="danger" @click="emit('remove')">
|
||||
<IconDelete /> 删除
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<dl class="facts">
|
||||
@@ -99,115 +166,198 @@ function isPinnedTo(line: string): boolean {
|
||||
<dt>附加规则</dt>
|
||||
<dd class="mono">{{ inbound.ruleSet }}</dd>
|
||||
</template>
|
||||
|
||||
<template v-if="exitChain.length">
|
||||
<dt>流量去向</dt>
|
||||
<dd class="flow mono">
|
||||
<template v-if="throughChain">
|
||||
<span class="hop is-chain">{{ displayName(nowOf(chain)) || '未选择' }}</span>
|
||||
<span class="arrow">→</span>
|
||||
</template>
|
||||
<template v-for="(hop, i) in exitChain" :key="hop">
|
||||
<span v-if="i" class="arrow">→</span>
|
||||
<span :class="['hop', i === exitChain.length - 1 && 'is-proxy']">{{
|
||||
displayName(hop)
|
||||
}}</span>
|
||||
</template>
|
||||
</dd>
|
||||
</template>
|
||||
</dl>
|
||||
</header>
|
||||
|
||||
<!-- 运行时:换线路。不写文件,点了立刻变 -->
|
||||
<section v-if="chain.length" class="block">
|
||||
<h3>流量去向</h3>
|
||||
<p class="chain mono">
|
||||
<template v-for="(hop, i) in chain" :key="hop">
|
||||
<span v-if="i" class="arrow">→</span>
|
||||
<span :class="i === chain.length - 1 && 'tail'">{{ hop }}</span>
|
||||
</template>
|
||||
</p>
|
||||
|
||||
<template v-if="switchable">
|
||||
<h4>{{ switchable.group }} 的当前选中</h4>
|
||||
<div class="grid">
|
||||
<OutboundCard
|
||||
v-for="m in switchable.members"
|
||||
:key="m"
|
||||
:name="m"
|
||||
:sub="describe(m)"
|
||||
:delay="delayOf(m)"
|
||||
:selected="m === switchable.now"
|
||||
:testing="isTesting(m)"
|
||||
testable
|
||||
@pick="emit('select', switchable.group, m)"
|
||||
@test="emit('test', m)"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
<!-- 链条上一个能点的组都没有:只能说明现状 -->
|
||||
<section v-if="panel.groups.length === 0" class="block">
|
||||
<p class="hint">没有可切换的策略组。</p>
|
||||
<button v-if="!locked" type="button" class="adopt" :disabled="saving" @click="emit('adopt')">
|
||||
改成逐条选线路
|
||||
</button>
|
||||
</section>
|
||||
|
||||
<!--
|
||||
配置:换这路入站指向谁。要写文件、要校验。
|
||||
默认入站没有 proxy 字段可写,整块不显示——画一排点不了的卡片只会让人以为是坏了。
|
||||
-->
|
||||
<section v-if="!locked" class="block">
|
||||
<h3>出站</h3>
|
||||
<template v-else>
|
||||
<section class="block">
|
||||
<h3>
|
||||
代理
|
||||
<span
|
||||
v-if="panel.shared"
|
||||
class="tag"
|
||||
:title="`换的是 ${panel.groups[0]?.name},所有走分流规则的入站共用它`"
|
||||
>共用</span
|
||||
>
|
||||
</h3>
|
||||
|
||||
<div class="grid">
|
||||
<OutboundCard
|
||||
v-for="b in BUILTINS"
|
||||
:key="b.label"
|
||||
:name="b.label"
|
||||
:sub="b.sub"
|
||||
:delay="null"
|
||||
:selected="isCurrentOutbound(b.mode)"
|
||||
:pending="pendingOutbound === b.label"
|
||||
@pick="emit('pick', b.mode)"
|
||||
/>
|
||||
<div v-if="panel.groups.length > 1" class="tabs">
|
||||
<button
|
||||
v-for="t in panel.groups"
|
||||
:key="t.name"
|
||||
type="button"
|
||||
:class="['tab', activeTab === t.name && 'is-on']"
|
||||
@click="activeTab = t.name"
|
||||
>
|
||||
{{ t.label }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<template v-if="groups.length">
|
||||
<h4>策略组</h4>
|
||||
<div class="grid">
|
||||
<OutboundCard
|
||||
v-for="g in groups"
|
||||
:key="g"
|
||||
:name="g"
|
||||
:sub="describe(g)"
|
||||
:delay="delayOf(g)"
|
||||
:selected="isCurrentOutbound({ kind: 'named', name: g })"
|
||||
:pending="pendingOutbound === g"
|
||||
:testing="isTesting(g)"
|
||||
testable
|
||||
@pick="emit('pick', { kind: 'named', name: g })"
|
||||
@test="emit('test', g)"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<template v-if="ownProxies.length">
|
||||
<h4>自有线路</h4>
|
||||
<div class="grid">
|
||||
<OutboundCard
|
||||
v-for="p in ownProxies"
|
||||
:key="p"
|
||||
:name="p"
|
||||
:sub="describe(p)"
|
||||
:delay="delayOf(p)"
|
||||
:selected="isCurrentOutbound({ kind: 'named', name: p })"
|
||||
:pending="pendingOutbound === p"
|
||||
:testing="isTesting(p)"
|
||||
testable
|
||||
@pick="emit('pick', { kind: 'named', name: p })"
|
||||
@test="emit('test', p)"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<h4>订阅线路</h4>
|
||||
<p v-if="!kernel.online" class="hint"><IconOffline /> 内核未连接</p>
|
||||
<p v-else-if="providerLines.length === 0" class="hint">订阅中没有线路</p>
|
||||
<p v-else-if="proxyLines.length === 0" class="hint">这个策略组现在没有成员</p>
|
||||
<div v-else class="grid">
|
||||
<OutboundCard
|
||||
v-for="line in providerLines"
|
||||
:key="line"
|
||||
:name="line"
|
||||
:sub="describe(line)"
|
||||
:delay="delayOf(line)"
|
||||
:selected="isPinnedTo(line)"
|
||||
:pending="pendingOutbound === generatedGroupName(line)"
|
||||
:testing="isTesting(line)"
|
||||
v-for="line in proxyLines"
|
||||
:key="line.name"
|
||||
:name="displayName(line.name)"
|
||||
:sub="line.info?.type ?? ''"
|
||||
:delay="latestDelay(line.info)"
|
||||
:selected="line.name === nowOf(activeGroup)"
|
||||
:disabled-reason="activeGroup?.pickable ? undefined : '这个组自己决定用哪条'"
|
||||
:testing="isTesting(line.name)"
|
||||
testable
|
||||
@pick="emit('pin', line)"
|
||||
@test="emit('test', line)"
|
||||
tone="proxy"
|
||||
@pick="emit('select', activeTab, line.name)"
|
||||
@test="emit('test', line.name, line.provider)"
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section v-if="chain || chainPreview.length" class="block">
|
||||
<h3>
|
||||
链式代理
|
||||
<span v-if="!chain" class="tag">未保存</span>
|
||||
</h3>
|
||||
|
||||
<div v-if="!chain" class="grid">
|
||||
<OutboundCard
|
||||
v-for="name in chainPreview"
|
||||
:key="name"
|
||||
:name="name"
|
||||
sub=""
|
||||
:delay="null"
|
||||
:selected="false"
|
||||
disabled-reason="保存之后才能选"
|
||||
tone="chain"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div v-else class="grid">
|
||||
<OutboundCard
|
||||
v-for="line in chainLines"
|
||||
:key="line.name"
|
||||
:name="line.name"
|
||||
:sub="line.info?.type ?? ''"
|
||||
:delay="latestDelay(line.info)"
|
||||
:selected="line.name === nowOf(chain)"
|
||||
:testing="isTesting(line.name)"
|
||||
testable
|
||||
tone="chain"
|
||||
@pick="emit('select', chain.name, line.name)"
|
||||
@test="emit('test', line.name, line.provider)"
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 共用的组只能换选中,改不了它的成员来源:那是别人的组 -->
|
||||
<section v-if="panel.shared && !locked" class="block">
|
||||
<button type="button" class="adopt" :disabled="saving" @click="emit('adopt')">
|
||||
改成逐条选线路
|
||||
</button>
|
||||
</section>
|
||||
|
||||
<section v-if="!panel.shared" class="block advanced">
|
||||
<button type="button" class="toggle" @click="open = !open">
|
||||
<span>高级配置</span>
|
||||
<component :is="open ? IconUp : IconDown" />
|
||||
</button>
|
||||
|
||||
<div v-if="open" class="form">
|
||||
<h4>代理</h4>
|
||||
|
||||
<div class="row">
|
||||
<span class="label">订阅</span>
|
||||
<SourcePicker v-model="form.proxy.sources" :options="subscriptions" />
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<span class="label">筛选</span>
|
||||
<div class="field">
|
||||
<input v-model="form.proxy.filter" placeholder="正则,留空表示全部保留" />
|
||||
<p class="count">
|
||||
<template v-if="preview(form.proxy).kept === null">筛选条件写法有误</template>
|
||||
<template v-else>
|
||||
{{ preview(form.proxy).total }} 条线路里匹配到 {{ preview(form.proxy).kept }} 条
|
||||
</template>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<span class="label">链式代理</span>
|
||||
<div class="field">
|
||||
<button
|
||||
type="button"
|
||||
role="switch"
|
||||
:aria-checked="chainOn"
|
||||
:class="['switch', chainOn && 'is-on']"
|
||||
@click="chainOn = !chainOn"
|
||||
>
|
||||
<span class="knob"></span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<template v-if="form.chain">
|
||||
<h4>链式代理</h4>
|
||||
|
||||
<div class="row">
|
||||
<span class="label">订阅</span>
|
||||
<SourcePicker v-model="form.chain!.sources" :options="subscriptions" />
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<span class="label">筛选</span>
|
||||
<div class="field">
|
||||
<input v-model="form.chain.filter" placeholder="正则,建议筛到作为中转的那一条" />
|
||||
<p class="count">
|
||||
<template v-if="preview(form.chain).kept === null">筛选条件写法有误</template>
|
||||
<template v-else>
|
||||
{{ preview(form.chain).total }} 条线路里匹配到
|
||||
{{ preview(form.chain).kept }} 条
|
||||
</template>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<div class="form-acts">
|
||||
<button type="button" :disabled="!dirty || saving" @click="reset">取消</button>
|
||||
<button
|
||||
type="button"
|
||||
class="primary"
|
||||
:disabled="!dirty || !complete || saving"
|
||||
@click="emit('save', form)"
|
||||
>
|
||||
{{ saving ? '保存中' : '保存' }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
</aside>
|
||||
</template>
|
||||
|
||||
@@ -250,7 +400,7 @@ function isPinnedTo(line: string): boolean {
|
||||
.acts {
|
||||
display: flex;
|
||||
gap: var(--s-2);
|
||||
margin-bottom: var(--s-3);
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
.acts button {
|
||||
@@ -289,6 +439,33 @@ function isPinnedTo(line: string): boolean {
|
||||
|
||||
.facts dd {
|
||||
margin: 0;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.flow {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: var(--s-2);
|
||||
}
|
||||
|
||||
.arrow {
|
||||
color: var(--c-text-faint);
|
||||
}
|
||||
|
||||
.hop {
|
||||
color: var(--c-text-soft);
|
||||
}
|
||||
|
||||
/* 两跳用两种颜色,和下面卡片的选中态对得上 */
|
||||
.hop.is-proxy {
|
||||
color: var(--c-accent-text);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.hop.is-chain {
|
||||
color: var(--c-chain-text);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.block {
|
||||
@@ -301,37 +478,50 @@ function isPinnedTo(line: string): boolean {
|
||||
}
|
||||
|
||||
h3 {
|
||||
font-size: var(--t-sm);
|
||||
font-weight: 600;
|
||||
color: var(--c-text-soft);
|
||||
margin-bottom: var(--s-3);
|
||||
}
|
||||
|
||||
h4 {
|
||||
font-size: var(--t-xs);
|
||||
font-weight: 500;
|
||||
color: var(--c-text-faint);
|
||||
margin: var(--s-5) 0 var(--s-2);
|
||||
}
|
||||
|
||||
.chain {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: var(--s-2);
|
||||
font-size: var(--t-sm);
|
||||
color: var(--c-text-soft);
|
||||
margin-bottom: var(--s-2);
|
||||
font-weight: 600;
|
||||
color: var(--c-text);
|
||||
letter-spacing: 0.02em;
|
||||
margin-bottom: var(--s-4);
|
||||
}
|
||||
|
||||
.chain .arrow {
|
||||
.tag {
|
||||
padding: 0 var(--s-2);
|
||||
border: 1px solid var(--c-border-strong);
|
||||
border-radius: 999px;
|
||||
font-size: var(--t-xs);
|
||||
font-weight: 400;
|
||||
color: var(--c-text-faint);
|
||||
cursor: help;
|
||||
}
|
||||
|
||||
.tabs {
|
||||
display: flex;
|
||||
gap: var(--s-4);
|
||||
margin-bottom: var(--s-4);
|
||||
}
|
||||
|
||||
.chain .tail {
|
||||
color: var(--c-accent-text);
|
||||
font-weight: 500;
|
||||
/* 选中态是一条离文字有距离的下划线,不画边框 */
|
||||
.tab {
|
||||
padding: 0 0 var(--s-2);
|
||||
border: none;
|
||||
border-bottom: 2px solid transparent;
|
||||
background: none;
|
||||
color: var(--c-text-faint);
|
||||
font-size: var(--t-sm);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.tab:hover {
|
||||
color: var(--c-text-soft);
|
||||
}
|
||||
|
||||
.tab.is-on {
|
||||
border-bottom-color: var(--c-accent);
|
||||
color: var(--c-text);
|
||||
}
|
||||
|
||||
.grid {
|
||||
@@ -349,8 +539,162 @@ h4 {
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.hint code {
|
||||
color: var(--c-text-soft);
|
||||
.adopt {
|
||||
padding: var(--s-1) var(--s-4);
|
||||
border: 1px solid var(--c-border-strong);
|
||||
border-radius: var(--r-sm);
|
||||
background: var(--c-surface);
|
||||
font-size: var(--t-sm);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.adopt:hover:not(:disabled) {
|
||||
border-color: var(--c-accent);
|
||||
color: var(--c-accent-text);
|
||||
}
|
||||
|
||||
.adopt:disabled {
|
||||
color: var(--c-text-faint);
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
/* ── 高级配置 ───────────────────────────────── */
|
||||
.toggle {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--s-2);
|
||||
padding: 0;
|
||||
border: none;
|
||||
background: none;
|
||||
color: var(--c-text-soft);
|
||||
font-size: var(--t-sm);
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.toggle:hover {
|
||||
color: var(--c-text);
|
||||
}
|
||||
|
||||
/* 表单不套盒子,靠小标题和一条分割线分段(设计基调第 2 条:不要卡片套卡片) */
|
||||
.form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--s-3);
|
||||
margin-top: var(--s-4);
|
||||
}
|
||||
|
||||
.form h4 {
|
||||
font-size: var(--t-xs);
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.04em;
|
||||
color: var(--c-text-faint);
|
||||
}
|
||||
|
||||
.form h4:not(:first-child) {
|
||||
margin-top: var(--s-4);
|
||||
}
|
||||
|
||||
.row {
|
||||
display: grid;
|
||||
grid-template-columns: 4.5em minmax(0, 1fr);
|
||||
align-items: start;
|
||||
gap: var(--s-3);
|
||||
}
|
||||
|
||||
/* 标签和第一行控件对齐。控件本身高 34px,所以标签也按 34px 居中 */
|
||||
.label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
min-height: 34px;
|
||||
color: var(--c-text-faint);
|
||||
font-size: var(--t-sm);
|
||||
}
|
||||
|
||||
.field {
|
||||
display: flex;
|
||||
min-height: 34px;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
select,
|
||||
input {
|
||||
height: 34px;
|
||||
padding: 0 var(--s-3);
|
||||
border: 1px solid var(--c-border-strong);
|
||||
border-radius: var(--r-sm);
|
||||
background: var(--c-surface);
|
||||
font-size: var(--t-base);
|
||||
}
|
||||
|
||||
input {
|
||||
width: 100%;
|
||||
font-family: var(--f-mono);
|
||||
}
|
||||
|
||||
.count {
|
||||
margin-top: var(--s-1);
|
||||
color: var(--c-text-faint);
|
||||
font-size: var(--t-xs);
|
||||
}
|
||||
|
||||
.switch {
|
||||
flex: none;
|
||||
align-self: flex-start;
|
||||
width: 38px;
|
||||
height: 22px;
|
||||
padding: 2px;
|
||||
border: 1px solid var(--c-border-strong);
|
||||
border-radius: 999px;
|
||||
background: var(--c-surface-sunken);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.switch .knob {
|
||||
display: block;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
border-radius: 50%;
|
||||
background: var(--c-text-faint);
|
||||
transition:
|
||||
transform 0.15s ease,
|
||||
background 0.15s ease;
|
||||
}
|
||||
|
||||
.switch.is-on {
|
||||
border-color: var(--c-chain);
|
||||
background: var(--c-chain-soft);
|
||||
}
|
||||
|
||||
.switch.is-on .knob {
|
||||
background: var(--c-chain);
|
||||
transform: translateX(16px);
|
||||
}
|
||||
|
||||
.form-acts {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: var(--s-2);
|
||||
}
|
||||
|
||||
.form-acts button {
|
||||
padding: var(--s-1) var(--s-4);
|
||||
border: 1px solid var(--c-border-strong);
|
||||
border-radius: var(--r-sm);
|
||||
background: var(--c-surface);
|
||||
font-size: var(--t-sm);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.form-acts button:disabled {
|
||||
color: var(--c-text-faint);
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.form-acts .primary:not(:disabled) {
|
||||
border-color: var(--c-accent);
|
||||
background: var(--c-accent-soft);
|
||||
color: var(--c-accent-text);
|
||||
}
|
||||
</style>
|
||||
|
||||
+66
-86
@@ -7,24 +7,24 @@
|
||||
* 运行时动作(切换选中、测延迟)不经过它,因为它们不写文件也不需要校验。
|
||||
*/
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { collectInbounds } from '@shared/inbounds.ts'
|
||||
import type { Inbound } from '@shared/inbounds.ts'
|
||||
import {
|
||||
collectInbounds,
|
||||
collectOutboundNames,
|
||||
outboundLabel,
|
||||
outboundToProxyField,
|
||||
resolveDestination,
|
||||
} from '@shared/inbounds.ts'
|
||||
import type { Inbound, OutboundMode } from '@shared/inbounds.ts'
|
||||
applySetup,
|
||||
chainGroupName,
|
||||
groupUses,
|
||||
panelGroups,
|
||||
pruneGenerated,
|
||||
syncGenerated,
|
||||
readSetup,
|
||||
userProviders,
|
||||
} from '@shared/inbound-groups.ts'
|
||||
import type { OutboundSetup } from '@shared/inbound-groups.ts'
|
||||
import type { ConfigObject } from '../../vendor/config-editor/index.ts'
|
||||
import { ApiError, api } from '../api'
|
||||
import type { ListenerFields } from '../api'
|
||||
import {
|
||||
generatedGroupName,
|
||||
isGeneratedGroup,
|
||||
makeFilterGroup,
|
||||
pruneGeneratedGroups,
|
||||
} from '@shared/filter-groups.ts'
|
||||
import { lineProvider, optimisticSelect, providerLines, reloadRuntime } from '../runtime'
|
||||
import type { GroupView } from '../runtime'
|
||||
import { optimisticSelect, providerLines, reloadRuntime, runtime } from '../runtime'
|
||||
import { useDelayTest } from '../delay-test'
|
||||
import { density } from '../prefs'
|
||||
import InboundList from '../components/InboundList.vue'
|
||||
@@ -38,11 +38,12 @@ const props = defineProps<{ data: ConfigObject; revision: string }>()
|
||||
const emit = defineEmits<{ saved: [] }>()
|
||||
|
||||
const inbounds = computed(() => collectInbounds(props.data))
|
||||
const outbounds = computed(() => {
|
||||
const names = collectOutboundNames(props.data)
|
||||
// 生成的筛选组不出现在可选列表里:它们是「固定到某条线路」的实现细节,
|
||||
// 用户从没建过,让他在策略组那一栏看到只会莫名其妙。
|
||||
return { ...names, groups: names.groups.filter((g) => !isGeneratedGroup(g)) }
|
||||
const subscriptions = computed(() => userProviders(props.data))
|
||||
|
||||
/** 刚接管一路入站时给它什么:订阅全给上,不筛。三个组由 applySetup 一并建出来。 */
|
||||
const defaultSetup = (): OutboundSetup => ({
|
||||
proxy: { sources: [...subscriptions.value], filter: null },
|
||||
chain: null,
|
||||
})
|
||||
|
||||
const selectedId = ref<string | null>(null)
|
||||
@@ -55,8 +56,6 @@ const notice = ref('')
|
||||
const fields = ref<ListenerFields | null>(null)
|
||||
const formOpen = ref(false)
|
||||
const formEditing = ref<Inbound | null>(null)
|
||||
/** 正在提交的那个出站的名字。只有它显示忙碌,其余卡片照常能点 */
|
||||
const pendingOutbound = ref<string | null>(null)
|
||||
|
||||
const { testing, test } = useDelayTest(
|
||||
() => void reloadRuntime(),
|
||||
@@ -85,13 +84,32 @@ watch(
|
||||
const selected = computed(() => inbounds.value.find((i) => i.id === selectedId.value) ?? null)
|
||||
const takenNames = computed(() => inbounds.value.map((i) => i.name))
|
||||
|
||||
/** 面板上能操作哪些策略组、各自能不能点。这个问题只在 panelGroups 里回答一次。 */
|
||||
const panel = computed(() =>
|
||||
selected.value
|
||||
? panelGroups(props.data, runtime.value, selected.value)
|
||||
: { groups: [], shared: false },
|
||||
)
|
||||
|
||||
/** 共用的组是别人的,改不了它的来源,所以高级配置也不给。 */
|
||||
const setup = computed<OutboundSetup | null>(() =>
|
||||
selected.value && !panel.value.shared ? readSetup(props.data, selected.value.name) : null,
|
||||
)
|
||||
|
||||
const chainView = computed<GroupView | null>(() => {
|
||||
const target = selected.value
|
||||
if (!target || !setup.value?.chain) return null
|
||||
const name = chainGroupName(target.name)
|
||||
return { name, uses: groupUses(props.data, name) ?? [] }
|
||||
})
|
||||
|
||||
const clone = () => JSON.parse(JSON.stringify(props.data)) as ConfigObject
|
||||
|
||||
/** 所有改配置文件的动作都从这里走。 */
|
||||
async function commit(raw: ConfigObject, success: string) {
|
||||
// 顺手清掉没人再引用的生成组。不清理的话,改几次出站文件里就攒下一堆
|
||||
// 用户从没主动建过、也不知道是干嘛的组。
|
||||
const next = pruneGeneratedGroups(raw)
|
||||
// 先把生成的东西按当前规则重建一遍,再清掉没人再引用的。不清理的话,改几次文件里就
|
||||
// 攒下一堆用户从没主动建过的东西,而没人用的订阅副本还会按 interval 继续联网。
|
||||
const next = pruneGenerated(syncGenerated(raw, collectInbounds(raw)))
|
||||
saving.value = true
|
||||
failure.value = null
|
||||
done.value = ''
|
||||
@@ -110,62 +128,18 @@ async function commit(raw: ConfigObject, success: string) {
|
||||
}
|
||||
}
|
||||
|
||||
async function pickOutbound(mode: OutboundMode) {
|
||||
/** 保存高级配置:改的是这一路的组从哪些订阅取成员、筛掉哪些。 */
|
||||
async function saveSetup(next: OutboundSetup) {
|
||||
const target = selected.value
|
||||
if (!target || target.listenerIndex === null || pendingOutbound.value) return
|
||||
pendingOutbound.value = outboundLabel(mode)
|
||||
|
||||
const next = clone()
|
||||
const entry = (next.listeners as ConfigObject[])[target.listenerIndex]!
|
||||
const proxy = outboundToProxyField(mode)
|
||||
// RULE 是「没有这个字段」而不是「字段为空」,所以是删掉而不是置空。
|
||||
if (proxy === undefined) delete entry.proxy
|
||||
else entry.proxy = proxy
|
||||
|
||||
try {
|
||||
await commit(next, `${target.name} 的出站已设为 ${outboundLabel(mode)}`)
|
||||
} finally {
|
||||
pendingOutbound.value = null
|
||||
}
|
||||
if (!target || saving.value) return
|
||||
await commit(applySetup(clone(), target.name, next), `${target.name} 的代理配置已保存`)
|
||||
}
|
||||
|
||||
/**
|
||||
* 把当前这一路入站固定到某条订阅线路。
|
||||
*
|
||||
* 订阅线路不能被入站直接引用,所以要先建一个只装它的策略组再指过去(决策记录 0005)。
|
||||
* 这一步对用户是透明的:他看到的只是「这个口固定走这条线」。
|
||||
*/
|
||||
async function pinLine(line: string) {
|
||||
/** 把一路还没接管的入站改成专属代理组模式。 */
|
||||
async function adopt() {
|
||||
const target = selected.value
|
||||
if (!target || target.listenerIndex === null || pendingOutbound.value) return
|
||||
|
||||
const provider = lineProvider.value[line]
|
||||
if (!provider) {
|
||||
notice.value = `找不到 ${line} 属于哪个订阅,无法固定`
|
||||
return
|
||||
}
|
||||
|
||||
const group = makeFilterGroup(line, provider)
|
||||
if (!group) {
|
||||
notice.value = `${line} 的名字里含反引号,内核会把它当成筛选条件的分隔符,无法固定`
|
||||
return
|
||||
}
|
||||
|
||||
const groupName = generatedGroupName(line)
|
||||
pendingOutbound.value = groupName
|
||||
|
||||
const next = clone()
|
||||
const groups = Array.isArray(next['proxy-groups']) ? (next['proxy-groups'] as ConfigObject[]) : []
|
||||
// 同一条线路被两路入站固定时共用一个组,不重复建
|
||||
if (!groups.some((g) => g.name === groupName)) groups.push(group)
|
||||
next['proxy-groups'] = groups
|
||||
;(next.listeners as ConfigObject[])[target.listenerIndex]!.proxy = groupName
|
||||
|
||||
try {
|
||||
await commit(next, `${target.name} 已固定走 ${line}`)
|
||||
} finally {
|
||||
pendingOutbound.value = null
|
||||
}
|
||||
if (!target || saving.value) return
|
||||
await commit(applySetup(clone(), target.name, defaultSetup()), `${target.name} 已改为逐条选线路`)
|
||||
}
|
||||
|
||||
function openAdd() {
|
||||
@@ -188,7 +162,12 @@ async function submitForm(entry: ConfigObject) {
|
||||
else listeners[editingIndex] = entry
|
||||
next.listeners = listeners
|
||||
|
||||
await commit(next, editingIndex === null ? `已新增 ${String(entry.name)}` : '已保存')
|
||||
// 新增的入站直接进专属组模式。否则新建完看到的是一块「这一路不由 Patchbay 管理」
|
||||
// 的提示,还得再点一次才能用。
|
||||
const name = String(entry.name)
|
||||
const withGroup = editingIndex === null ? applySetup(next, name, defaultSetup()) : next
|
||||
|
||||
await commit(withGroup, editingIndex === null ? `已新增 ${name}` : '已保存')
|
||||
// 失败时不能关对话框——关了再打开就是空表单,用户填的名称、端口、类型全没了
|
||||
if (failure.value) return
|
||||
formOpen.value = false
|
||||
@@ -238,8 +217,8 @@ async function removeSelected() {
|
||||
<span class="sum-k">入站</span>
|
||||
</div>
|
||||
<div class="sum">
|
||||
<span class="sum-n">{{ outbounds.groups.length }}</span>
|
||||
<span class="sum-k">策略组</span>
|
||||
<span class="sum-n">{{ subscriptions.length }}</span>
|
||||
<span class="sum-k">订阅</span>
|
||||
</div>
|
||||
<div class="sum">
|
||||
<span class="sum-n">{{ providerLines.length }}</span>
|
||||
@@ -266,17 +245,18 @@ async function removeSelected() {
|
||||
<InboundDetail
|
||||
v-if="selected"
|
||||
:inbound="selected"
|
||||
:groups="outbounds.groups"
|
||||
:own-proxies="outbounds.ownProxies"
|
||||
:destination="resolveDestination(data, selected)"
|
||||
:pending-outbound="pendingOutbound"
|
||||
:panel="panel"
|
||||
:chain="chainView"
|
||||
:subscriptions="subscriptions"
|
||||
:setup="setup"
|
||||
:testing="testing"
|
||||
@pick="pickOutbound"
|
||||
:saving="saving"
|
||||
@edit="openEdit"
|
||||
@remove="removeSelected"
|
||||
@select="selectMember"
|
||||
@test="(name: string) => test(name, lineProvider[name])"
|
||||
@pin="pinLine"
|
||||
@test="test"
|
||||
@save="saveSetup"
|
||||
@adopt="adopt"
|
||||
/>
|
||||
</div>
|
||||
|
||||
|
||||
Reference in New Issue
Block a user