/** 工作台客户端包列表加载模型:解析 snake/camel、格式化大小与版本号校验;纯逻辑。 */ import { unwrap } from '../../api/envelope.ts' import { type WorkbenchClientPackageItem, type WorkbenchClientPackageList } from './workbench-client-dto.ts' /** 与后端 biz_workbench_client_package.version VARCHAR(64) 对齐。 */ export const WORKBENCH_CLIENT_VERSION_MAX_LENGTH = 64 function text(value: unknown): string { return typeof value === 'string' ? value.trim() : '' } function numberOrNull(value: unknown): number | null { return typeof value === 'number' && Number.isFinite(value) ? Math.floor(value) : null } /** 解析单条客户端包行;缺 id 视为无效。 */ export function toWorkbenchClientPackageItem(raw: unknown): WorkbenchClientPackageItem | null { if (!raw || typeof raw !== 'object') return null const r = raw as Record const id = numberOrNull(r.id) if (id === null) return null return { id, version: text(r.version), fileName: text(r.file_name ?? r.fileName), objectKey: text(r.object_key ?? r.objectKey), fileSize: numberOrNull(r.file_size ?? r.fileSize) ?? 0, sha256: text(r.sha256), fileUrl: text(r.file_url ?? r.fileUrl), createdAt: text(r.created_at ?? r.createdAt), } } /** 归一化客户端包列表负载为前端结果;缺省回空列表。 */ export function parseWorkbenchClientPackageList(payload: unknown): WorkbenchClientPackageList { const data = unwrap(payload) const record = data && typeof data === 'object' ? (data as Record) : {} const items = Array.isArray(record.items) ? record.items .map((raw) => toWorkbenchClientPackageItem(raw)) .filter((item): item is WorkbenchClientPackageItem => item !== null) : [] return { items } } /** 上传成功后返回的新记录行(data.item);无 item 回 null。 */ export function parseWorkbenchClientPackageUpload(payload: unknown): WorkbenchClientPackageItem | null { const data = unwrap(payload) if (!data || typeof data !== 'object') return null const item = (data as Record).item return item ? toWorkbenchClientPackageItem(item) : null } /** * 版本号必填、纯数字 x.y.z、且不超过后端列宽。 * 客户端按数字逐段比较,v 前缀/两段/后缀会让严格解析器判非法 ⇒ 检查更新永远回「已是最新」。 */ export function isValidWorkbenchClientVersion(value: string): boolean { const normalized = typeof value === 'string' ? value.trim() : '' return normalized.length > 0 && normalized.length <= WORKBENCH_CLIENT_VERSION_MAX_LENGTH && /^\d+\.\d+\.\d+$/.test(normalized) } /** 字节数展示:0=未知展示为 -,其余按 KB/MB/GB 人性化。 */ export function formatFileSize(bytes: number): string { if (!Number.isFinite(bytes) || bytes <= 0) return '—' if (bytes < 1024) return `${bytes} B` const units = ['KB', 'MB', 'GB'] let value = bytes / 1024 let unitIndex = 0 while (value >= 1024 && unitIndex < units.length - 1) { value /= 1024 unitIndex += 1 } return `${value >= 100 ? value.toFixed(0) : value.toFixed(1)} ${units[unitIndex]}` }