27 lines
862 B
TypeScript
27 lines
862 B
TypeScript
import type { IpRule } from './api';
|
||
|
||
const MAX_IPS = 200;
|
||
|
||
/** 从表单生成 IpRule,未选模式或内容为空时返回 null */
|
||
export function buildIpRule(mode: '' | 'allow' | 'block', text: string): IpRule | null {
|
||
if (mode !== 'allow' && mode !== 'block') return null;
|
||
const ips = text
|
||
.split(/[\n,;,]+/u)
|
||
.map(s => s.trim())
|
||
.filter(Boolean)
|
||
.slice(0, MAX_IPS);
|
||
if (ips.length === 0) return null;
|
||
return { mode, ips };
|
||
}
|
||
|
||
export function parseIpRuleText(json: string | null | undefined): { mode: '' | 'allow' | 'block'; text: string } {
|
||
if (!json) return { mode: '', text: '' };
|
||
try {
|
||
const r = JSON.parse(json) as IpRule;
|
||
if (r.mode !== 'allow' && r.mode !== 'block') return { mode: '', text: '' };
|
||
return { mode: r.mode, text: (r.ips ?? []).join('\n') };
|
||
} catch {
|
||
return { mode: '', text: '' };
|
||
}
|
||
}
|