export type QuickLinkMap = Record; export type NekoBrowserLink = { id: number; key: string; label: string; url: string; port: string; accessKind: string; accessLabel: string; host: string; }; const NEKO_KEY_RE = /^neko_browser(?:(?:_(lan|wireguard|nat1to1|public))?(?:_(\d+))?)?$/i; const ACCESS_PRIORITY: Record = { wireguard: 80, public: 70, nat1to1: 60, lan: 50, direct: 40, }; function accessLabel(kind: string): string { if (kind === "wireguard") return "WireGuard"; if (kind === "public") return "Public"; if (kind === "nat1to1") return "NAT1TO1"; if (kind === "lan") return "LAN"; return "Direct"; } function parsePort(url: string): string { try { return new URL(url, "http://127.0.0.1").port || ""; } catch { return ""; } } function parseHost(url: string): string { try { return new URL(url, "http://127.0.0.1").hostname || ""; } catch { return ""; } } export function extractNekoBrowserLinks(quickLinks?: QuickLinkMap | null): NekoBrowserLink[] { const picked = new Map(); for (const [key, rawUrl] of Object.entries(quickLinks ?? {})) { const match = key.match(NEKO_KEY_RE); const url = rawUrl.trim(); if (!match || !url) continue; const kind = (match[1] || (key === "neko_browser" || /^neko_browser_\d+$/i.test(key) ? "direct" : "lan")).toLowerCase(); const id = key === "neko_browser" ? 1 : Number(match[2] || 1); const next: NekoBrowserLink = { id, key, label: `Neko ${id}`, url, port: parsePort(url), accessKind: kind, accessLabel: accessLabel(kind), host: parseHost(url), }; const current = picked.get(id); const currentPriority = current ? (ACCESS_PRIORITY[current.accessKind] ?? 0) : -1; const nextPriority = ACCESS_PRIORITY[kind] ?? 0; const preferNext = !current || nextPriority > currentPriority || (nextPriority === currentPriority && key !== "neko_browser"); if (!current || preferNext) picked.set(id, next); } return Array.from(picked.values()).sort((a, b) => a.id - b.id); } export function resolveNekoBrowserLink( links: NekoBrowserLink[], preferredIndex: number, ): { link: NekoBrowserLink | null; fallback: boolean } { if (!links.length) return { link: null, fallback: false }; if (!Number.isInteger(preferredIndex) || preferredIndex < 0) { return { link: links[0], fallback: false }; } if (preferredIndex < links.length) { return { link: links[preferredIndex], fallback: false }; } return { link: links[0], fallback: true }; } export function formatNekoPorts(links: NekoBrowserLink[]): string { const ports = Array.from(new Set(links.map((item) => item.port).filter(Boolean))); return ports.length ? ports.map((port) => `:${port}`).join(" / ") : ""; }