// 只写凭证字段(API Key、密码、Cookie、令牌)的表单值约定,前后端一致: // "" → 保持原值(请求里省略该字段) // SECRET_CLEAR → 清除(请求里传 null) // 其它字符串 → 替换为新值 // 服务端从不回传明文;"已设置"只来自 secretRef / hasCredential 之类的布尔,掩码只用服务端给的 hint。 /** 表单里"清除"的哨兵值;不会是用户能输入的内容 */ export const SECRET_CLEAR = "\u0000clear"; export const MASK_DOTS = "••••••••"; /** 表单值 → 请求值:undefined = 不改,null = 清除,字符串 = 替换(去掉首尾空白) */ export function secretPatch(v: unknown): string | null | undefined { if (v === SECRET_CLEAR) return null; if (typeof v !== "string") return undefined; const s = v.trim(); return s ? s : undefined; } /** * 服务端给的掩码(如 "sk-a…wxyz")只取末 4 位;没有或太短只显示圆点。 * 不在前端拼任何可还原的内容。 */ export function maskTail(mask: string | null | undefined): string | null { if (!mask) return null; const tail = mask.includes("…") ? mask.split("…").pop() : null; return tail && /^[^•*]{4}$/.test(tail) ? tail : null; } /** 掩码显示:圆点 + 末 4 位(有的话) */ export function maskedDisplay(mask?: string | null): string { return `${MASK_DOTS}${maskTail(mask) ?? ""}`; } /** 已设置时输入框里的占位 */ export function secretPlaceholder(mask?: string | null): string { return `已设置 ${maskedDisplay(mask)}`; } export type SecretView = | { state: "empty" } | { state: "set"; placeholder: string; canClear: boolean } | { state: "typing"; replacing: boolean } | { state: "cleared" }; /** SecretInput 的显示状态(纯函数,便于测试) */ export function secretView( value: string, opts: { isSet: boolean; mask?: string | null; clearable?: boolean }, ): SecretView { if (value === SECRET_CLEAR) return { state: "cleared" }; if (value !== "") return { state: "typing", replacing: opts.isSet }; if (opts.isSet) return { state: "set", placeholder: secretPlaceholder(opts.mask), canClear: !!opts.clearable }; return { state: "empty" }; } /** 字段说明:已设置时补一句"留空不修改";待清除时框里已写明,说明保持原样 */ export function secretHint(hint: string | undefined, value: unknown, isSet: boolean): string | undefined { if (value === SECRET_CLEAR) return hint; if (!isSet) return hint; return hint ? `${hint};留空不修改` : "留空不修改"; }