diff --git a/extensions/base64image/package.json b/extensions/base64image/package.json index abbc8a81..81612942 100644 --- a/extensions/base64image/package.json +++ b/extensions/base64image/package.json @@ -1,6 +1,6 @@ { "name": "base64image", - "version": "1.0.3", + "version": "1.0.9", "description": "Base64 图片编解码:将 Data URL / Base64 字符串解析出图片元数据 MimeType、文件大小、预览与复制标准 Markdown/HTML/纯文本,支持将文本或 SVG 转换为 Base64", "type": "module", "main": "dist/index.js", diff --git a/extensions/base64image/plugin.json b/extensions/base64image/plugin.json index 5cbe0446..1a464cc4 100644 --- a/extensions/base64image/plugin.json +++ b/extensions/base64image/plugin.json @@ -1,7 +1,7 @@ { "id": "base64image", "name": "图片 Base64", - "version": "1.0.8", + "version": "1.0.9", "minAppVersion": "1.1.8.0", "description": "图片文件或截图与 Base64 编码双向互转,支持一键复制 Data URL 或还原预览图片", "author": "ZTools Team", diff --git a/extensions/base64image/src/i18n.ts b/extensions/base64image/src/i18n.ts index ebb4e5f6..dc47effb 100644 --- a/extensions/base64image/src/i18n.ts +++ b/extensions/base64image/src/i18n.ts @@ -30,8 +30,15 @@ const rawT = createTranslator( pickFileAction: "选择图片文件…", pasteAction: "粘贴剪贴板图片或文字", clearAction: "清空", + filterBarPickImage: "选择图片", + filterBarReadClipboard: "读取剪贴板", + filterSummaryIdle: "支持选择本地图片、读取剪贴板或直接拖入图片", + filterSummaryInvalid: "输入内容未能识别为有效图片", + filterSummaryLoaded: "{name} · {format}{dim} · {rawSize} → {b64Size} ({expansion})", inputContentLabel: "输入内容", - previewMd: "![preview]({uri})\n\n**{name}**\n\n- 格式:{format}({mime})\n- 原始大小:{size}\n- Base64 长度:{len} 字符", + previewDimLine: "\n- 像素尺寸:{dim}", + previewSvgUtf8Line: "\n- SVG UTF-8 体积:{size}", + previewMd: "![preview]({uri})\n\n**{name}**\n\n- 格式:{format}({mime}){dimLine}\n- 原始体积:{size}\n- Base64 体积:{b64Size}({len} 字符)\n- 体积膨胀比:{ratio}×({expansion}){svgLine}", overLimitSub: "结果超过剪贴板上限,按回车保存为文本文件", copyLabelAction: "复制{label}", saveTextFileAction: "保存为文本文件…", @@ -39,7 +46,12 @@ const rawT = createTranslator( sectionResults: "转换结果(按回车复制)", rawBase64Title: "纯 Base64", rawBase64Label: "纯 Base64", - cssBgTitle: "CSS 背景图", + urlSafeBase64Title: "URL-Safe Base64", + urlSafeBase64Label: " URL-Safe Base64", + svgUtf8DataUriTitle: "Data URL(SVG UTF-8 优化)", + svgUtf8DataUriLabel: " SVG UTF-8 Data URL", + cssBgTitle: "CSS background-image", + cssBgLabel: " CSS background-image", sectionInvalid: "无法识别", invalidFallback: "无法识别的内容", invalidSub: "支持:图片文件、截图、Base64 字符串、data:image/... 链接、SVG 源码", @@ -110,8 +122,15 @@ const rawT = createTranslator( pickFileAction: "Choose Image File…", pasteAction: "Paste Clipboard Image or Text", clearAction: "Clear", + filterBarPickImage: "Choose Image", + filterBarReadClipboard: "Read Clipboard", + filterSummaryIdle: "Choose an image, read from clipboard, or drop an image here", + filterSummaryInvalid: "Input is not a recognized image", + filterSummaryLoaded: "{name} · {format}{dim} · {rawSize} → {b64Size} ({expansion})", inputContentLabel: "Input", - previewMd: "![preview]({uri})\n\n**{name}**\n\n- Format: {format} ({mime})\n- Size: {size}\n- Base64 Length: {len} [[len:char|chars]]", + previewDimLine: "\n- Dimensions: {dim}", + previewSvgUtf8Line: "\n- SVG UTF-8 Size: {size}", + previewMd: "![preview]({uri})\n\n**{name}**\n\n- Format: {format} ({mime}){dimLine}\n- Raw Size: {size}\n- Base64 Size: {b64Size} ({len} [[len:char|chars]])\n- Size Expansion: {ratio}× ({expansion}){svgLine}", overLimitSub: "Exceeds clipboard limit; press Enter to save as a text file", copyLabelAction: "Copy {label}", saveTextFileAction: "Save as Text File…", @@ -119,7 +138,12 @@ const rawT = createTranslator( sectionResults: "Results (Press Enter to copy)", rawBase64Title: "Raw Base64", rawBase64Label: "Raw Base64", - cssBgTitle: "CSS Background", + urlSafeBase64Title: "URL-Safe Base64", + urlSafeBase64Label: "URL-Safe Base64", + svgUtf8DataUriTitle: "Data URL (SVG UTF-8)", + svgUtf8DataUriLabel: "SVG UTF-8 Data URL", + cssBgTitle: "CSS background-image", + cssBgLabel: "CSS background-image", sectionInvalid: "Unrecognized Input", invalidFallback: "Unrecognized content", invalidSub: "Supports image files, screenshots, Base64 strings, data:image/... URLs, and SVG source", diff --git a/extensions/base64image/src/index.ts b/extensions/base64image/src/index.ts index d0172013..9bf83d63 100644 --- a/extensions/base64image/src/index.ts +++ b/extensions/base64image/src/index.ts @@ -227,12 +227,40 @@ export default function Base64ImageCommand() { name: loaded ? loaded.name : t("inputContentLabel"), format: parsed.format.toUpperCase(), mime: parsed.mimeType ?? "", + dimLine: parsed.dimensionsText ? t("previewDimLine", { dim: parsed.dimensionsText }) : "", size: parsed.formattedSize ?? "", - len: parsed.base64Length ?? 0 + b64Size: parsed.formattedBase64Size ?? "", + len: parsed.base64Length ?? 0, + ratio: parsed.expansionRatio !== undefined ? parsed.expansionRatio.toFixed(2) : "0.00", + expansion: parsed.expansionPercent ?? "0.0%", + svgLine: parsed.formattedSvgUtf8Size ? t("previewSvgUtf8Line", { size: parsed.formattedSvgUtf8Size }) : "" }) }) : undefined; + const filterBarSummary = busy + ? t("loadingTitle") + : parsed.valid && parsed.format + ? t("filterSummaryLoaded", { + name: loaded ? loaded.name : t("inputContentLabel"), + format: parsed.format.toUpperCase(), + dim: parsed.dimensionsText ? ` · ${parsed.dimensionsText}` : "", + rawSize: parsed.formattedSize ?? "", + b64Size: parsed.formattedBase64Size ?? "", + expansion: parsed.expansionPercent ?? "0.0%" + }) + : source + ? t("filterSummaryInvalid") + : t("filterSummaryIdle"); + + const filterBar = { + summaryText: filterBarSummary, + actions: [ + { id: "pick-image", title: t("filterBarPickImage"), icon: Icon.Image, onAction: handlePickFile }, + { id: "read-clipboard", title: t("filterBarReadClipboard"), icon: Icon.CopyClipboard, onAction: handlePaste } + ] + }; + const saveImageAction = parsed.valid && parsed.encoded && parsed.format ? Action({ title: t("saveImageAction"), @@ -277,10 +305,12 @@ export default function Base64ImageCommand() { sections = [ List.Section({ title: loaded ? t("sectionLoaded", { name: loaded.name }) : t("sectionResults") }, [ exportItem("export-datauri", "Data URL", parsed.dataUri, " Data URL", Icon.Globe), + exportItem("export-svg-utf8", t("svgUtf8DataUriTitle"), parsed.svgUtf8DataUri, t("svgUtf8DataUriLabel"), Icon.Code), exportItem("export-raw-base64", t("rawBase64Title"), parsed.encoded, t("rawBase64Label"), Icon.Terminal), - exportItem("export-markdown", "Markdown", parsed.markdown, " Markdown", Icon.Document), + exportItem("export-urlsafe-base64", t("urlSafeBase64Title"), parsed.urlSafeBase64, t("urlSafeBase64Label"), Icon.Link), + exportItem("export-css", t("cssBgTitle"), parsed.cssBackground, t("cssBgLabel"), Icon.Brush), exportItem("export-html", "HTML ", parsed.html, " HTML", Icon.Code), - exportItem("export-css", t("cssBgTitle"), parsed.cssBackground, " CSS", Icon.Brush), + exportItem("export-markdown", "Markdown", parsed.markdown, " Markdown", Icon.Document), saveImageItem ].filter((item): item is ReturnType => item !== null)) ]; @@ -332,6 +362,7 @@ export default function Base64ImageCommand() { navigationTitle: t("navTitle"), isLoading: busy, isShowingDetail: Boolean(previewDetail), + filterBar, searchBarPlaceholder: t("searchPlaceholder"), searchText: inputText, onSearchTextChange: (text: string) => { diff --git a/extensions/base64image/src/logic.ts b/extensions/base64image/src/logic.ts index ad11fb44..543ec442 100644 --- a/extensions/base64image/src/logic.ts +++ b/extensions/base64image/src/logic.ts @@ -9,16 +9,30 @@ export const MAXIMUM_BASE64_BYTES = 16 * 1024 * 1024; // 16 MiB export type Base64ImageFormat = "png" | "jpg" | "gif" | "webp" | "svg" | "bmp" | "ico" | "avif"; +export interface ImageDimensions { + width: number; + height: number; +} + export interface ParsedImageResult { valid: boolean; error?: string; format?: Base64ImageFormat; mimeType?: string; + width?: number; + height?: number; + dimensionsText?: string; byteLength?: number; formattedSize?: string; base64Length?: number; + formattedBase64Size?: string; + expansionRatio?: number; + expansionPercent?: string; encoded?: string; + urlSafeBase64?: string; dataUri?: string; + svgUtf8DataUri?: string; + formattedSvgUtf8Size?: string; markdown?: string; html?: string; cssBackground?: string; @@ -66,6 +80,186 @@ export function textToBase64(text: string): string { return bytesToBase64(bytes); } +/** 将标准 Base64 转换为 RFC 4648 URL-Safe Base64(无尾部 '=' 填充) */ +export function toUrlSafeBase64(standardBase64: string): string { + return standardBase64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); +} + +/** 将标准或 URL-Safe Base64 归一化为标准 Base64(补齐 '=' 填充);非法字符返回 null */ +export function normalizeBase64Input(raw: string): string | null { + const clean = raw.replace(/[ \t\r\n]/g, ""); + if (!clean) return null; + const hasStd = /[+/]/.test(clean); + const hasUrlSafe = /[-_]/.test(clean); + if (hasStd && hasUrlSafe) return null; + if (!/^[A-Za-z0-9+/_-]*={0,2}$/.test(clean)) return null; + const converted = hasUrlSafe ? clean.replace(/-/g, "+").replace(/_/g, "/") : clean; + const rem = converted.length % 4; + if (rem === 1) return null; + if (rem === 0) return converted; + if (converted.includes("=")) return null; + return converted + "=".repeat(4 - rem); +} + +/** 将 SVG 源码编码为可读且更紧凑的 UTF-8 Data URI */ +export function encodeSvgToUtf8DataUri(svgText: string): string { + const compact = svgText.trim().replace(/\r\n/g, "\n"); + const encoded = encodeURIComponent(compact) + .replace(/%20/g, " ") + .replace(/%3D/g, "=") + .replace(/%3A/g, ":") + .replace(/%2F/g, "/"); + return `data:image/svg+xml;utf8,${encoded}`; +} + +/** 计算 Base64 编码相对原始二进制字节的体积膨胀比 */ +export function calculateExpansionMetrics(rawBytes: number, base64Length: number): { + expansionRatio: number; + expansionPercent: string; +} { + if (rawBytes <= 0) { + return { expansionRatio: 0, expansionPercent: "0.0%" }; + } + const ratio = base64Length / rawBytes; + const delta = ((base64Length - rawBytes) / rawBytes) * 100; + const sign = delta >= 0 ? "+" : ""; + return { + expansionRatio: Number(ratio.toFixed(2)), + expansionPercent: `${sign}${delta.toFixed(1)}%` + }; +} + +function readUint16BE(bytes: Uint8Array, offset: number): number { + return (bytes[offset] << 8) | bytes[offset + 1]; +} + +function readUint16LE(bytes: Uint8Array, offset: number): number { + return bytes[offset] | (bytes[offset + 1] << 8); +} + +function readUint32BE(bytes: Uint8Array, offset: number): number { + return ((bytes[offset] << 24) | (bytes[offset + 1] << 16) | (bytes[offset + 2] << 8) | bytes[offset + 3]) >>> 0; +} + +function readInt32LE(bytes: Uint8Array, offset: number): number { + return bytes[offset] | (bytes[offset + 1] << 8) | (bytes[offset + 2] << 16) | (bytes[offset + 3] << 24); +} + +function parseSvgDimensions(svgText: string): ImageDimensions | undefined { + const rootMatch = svgText.match(/]*)>/i); + if (!rootMatch) return undefined; + const attrs = rootMatch[1]; + const widthMatch = attrs.match(/\bwidth\s*=\s*["']\s*([0-9]+(?:\.[0-9]+)?)(?:px)?\s*["']/i); + const heightMatch = attrs.match(/\bheight\s*=\s*["']\s*([0-9]+(?:\.[0-9]+)?)(?:px)?\s*["']/i); + if (widthMatch && heightMatch) { + const width = Math.round(Number(widthMatch[1])); + const height = Math.round(Number(heightMatch[1])); + if (width > 0 && height > 0) return { width, height }; + } + const viewBoxMatch = attrs.match(/\bviewBox\s*=\s*["']\s*[-0-9.]+\s+[-0-9.]+\s+([0-9]+(?:\.[0-9]+)?)\s+([0-9]+(?:\.[0-9]+)?)\s*["']/i); + if (viewBoxMatch) { + const width = Math.round(Number(viewBoxMatch[1])); + const height = Math.round(Number(viewBoxMatch[2])); + if (width > 0 && height > 0) return { width, height }; + } + return undefined; +} + +/** 从图片原始字节头解析真实像素宽高(纯函数,无外部依赖) */ +export function parseImageDimensions(bytes: Uint8Array, format: Base64ImageFormat): ImageDimensions | undefined { + if (format === "png" && bytes.length >= 24) { + const width = readUint32BE(bytes, 16); + const height = readUint32BE(bytes, 20); + return width > 0 && height > 0 ? { width, height } : undefined; + } + + if (format === "gif" && bytes.length >= 10) { + const width = readUint16LE(bytes, 6); + const height = readUint16LE(bytes, 8); + return width > 0 && height > 0 ? { width, height } : undefined; + } + + if (format === "bmp" && bytes.length >= 26) { + const width = Math.abs(readInt32LE(bytes, 18)); + const height = Math.abs(readInt32LE(bytes, 22)); + return width > 0 && height > 0 ? { width, height } : undefined; + } + + if (format === "ico" && bytes.length >= 8) { + const width = bytes[6] === 0 ? 256 : bytes[6]; + const height = bytes[7] === 0 ? 256 : bytes[7]; + return width > 0 && height > 0 ? { width, height } : undefined; + } + + if (format === "jpg" && bytes.length >= 4) { + let offset = 2; + while (offset + 9 < bytes.length) { + if (bytes[offset] !== 0xff) { + offset++; + continue; + } + while (offset < bytes.length && bytes[offset] === 0xff) offset++; + if (offset >= bytes.length) break; + const marker = bytes[offset++]; + // 跳过无载荷标记 (SOI, EOI, RST0-RST7, TEM) + if (marker === 0xd8 || marker === 0xd9 || marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) { + continue; + } + if (offset + 1 >= bytes.length) break; + const segmentLength = readUint16BE(bytes, offset); + if (segmentLength < 2 || offset + segmentLength > bytes.length) break; + // SOF0 / SOF1 / SOF2 / SOF3 / SOF5-SOF7 / SOF9-SOF11 / SOF13-SOF15 + const isSof = + (marker >= 0xc0 && marker <= 0xc3) || + (marker >= 0xc5 && marker <= 0xc7) || + (marker >= 0xc9 && marker <= 0xcb) || + (marker >= 0xcd && marker <= 0xcf); + if (isSof && offset + 6 < bytes.length) { + const height = readUint16BE(bytes, offset + 3); + const width = readUint16BE(bytes, offset + 5); + return width > 0 && height > 0 ? { width, height } : undefined; + } + offset += segmentLength; + } + return undefined; + } + + if (format === "webp" && bytes.length >= 30) { + const chunk = String.fromCharCode(...bytes.subarray(12, 16)); + if (chunk === "VP8 " && bytes.length >= 30) { + const width = readUint16LE(bytes, 26) & 0x3fff; + const height = readUint16LE(bytes, 28) & 0x3fff; + return width > 0 && height > 0 ? { width, height } : undefined; + } + if (chunk === "VP8L" && bytes.length >= 25) { + const b0 = bytes[21]; + const b1 = bytes[22]; + const b2 = bytes[23]; + const b3 = bytes[24]; + const width = 1 + (((b1 & 0x3f) << 8) | b0); + const height = 1 + (((b3 & 0x0f) << 10) | (b2 << 2) | ((b1 & 0xc0) >> 6)); + return width > 0 && height > 0 ? { width, height } : undefined; + } + if (chunk === "VP8X" && bytes.length >= 30) { + const width = 1 + (bytes[24] | (bytes[25] << 8) | (bytes[26] << 16)); + const height = 1 + (bytes[27] | (bytes[28] << 8) | (bytes[29] << 16)); + return width > 0 && height > 0 ? { width, height } : undefined; + } + return undefined; + } + + if (format === "svg") { + try { + const svgText = new TextDecoder("utf-8", { fatal: true }).decode(bytes); + return parseSvgDimensions(svgText); + } catch { + return undefined; + } + } + + return undefined; +} + export function detectImageFormat(bytes: Uint8Array): Base64ImageFormat | undefined { if ( bytes.length >= 8 && @@ -179,9 +373,9 @@ export function parseBase64Image(rawInput: string): ParsedImageResult { } const rawBase64 = prefixMatch ? text.slice(prefixMatch[0].length) : text; - const cleanBase64 = rawBase64.replace(/[ \t\r\n]/g, ""); + const cleanBase64 = normalizeBase64Input(rawBase64); - if (!cleanBase64 || cleanBase64.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(cleanBase64)) { + if (!cleanBase64) { return { valid: false, error: t("errInvalidBase64Chars") }; } @@ -202,21 +396,45 @@ export function parseBase64Image(rawInput: string): ParsedImageResult { } const mimeType = MIME_TYPES[format]; + const dimensions = parseImageDimensions(bytes, format); + const dimensionsText = dimensions ? `${dimensions.width} × ${dimensions.height} px` : undefined; + const { expansionRatio, expansionPercent } = calculateExpansionMetrics(bytes.length, cleanBase64.length); + const urlSafeBase64 = toUrlSafeBase64(cleanBase64); const dataUri = `data:${mimeType};base64,${cleanBase64}`; const markdown = `![image](${dataUri})`; const html = `image`; const cssBackground = `background-image: url('${dataUri}');`; const previewSnippet = cleanBase64.slice(0, 80) + (cleanBase64.length > 80 ? "..." : ""); + let svgUtf8DataUri: string | undefined; + let formattedSvgUtf8Size: string | undefined; + if (format === "svg") { + try { + const svgText = new TextDecoder("utf-8", { fatal: true }).decode(bytes); + svgUtf8DataUri = encodeSvgToUtf8DataUri(svgText); + formattedSvgUtf8Size = formatFileSize(new TextEncoder().encode(svgUtf8DataUri).byteLength); + } catch { + // ignore non-utf8 fallback + } + } return { valid: true, format, mimeType, + width: dimensions?.width, + height: dimensions?.height, + dimensionsText, byteLength: bytes.length, formattedSize: formatFileSize(bytes.length), base64Length: cleanBase64.length, + formattedBase64Size: formatFileSize(cleanBase64.length), + expansionRatio, + expansionPercent, encoded: cleanBase64, + urlSafeBase64, dataUri, + svgUtf8DataUri, + formattedSvgUtf8Size, markdown, html, cssBackground, @@ -238,16 +456,33 @@ export function encodeSvgOrTextToBase64(sourceText: string): ParsedImageResult { const bytes = new TextEncoder().encode(text); const mimeType = isSvg ? "image/svg+xml" : "text/plain"; const dataUri = `data:${mimeType};base64,${base64}`; + const urlSafeBase64 = toUrlSafeBase64(base64); + const dimensions = isSvg ? parseSvgDimensions(text) : undefined; + const dimensionsText = dimensions ? `${dimensions.width} × ${dimensions.height} px` : undefined; + const { expansionRatio, expansionPercent } = calculateExpansionMetrics(bytes.length, base64.length); + const svgUtf8DataUri = isSvg ? encodeSvgToUtf8DataUri(text) : undefined; + const formattedSvgUtf8Size = svgUtf8DataUri + ? formatFileSize(new TextEncoder().encode(svgUtf8DataUri).byteLength) + : undefined; return { valid: true, format: isSvg ? "svg" : undefined, mimeType, + width: dimensions?.width, + height: dimensions?.height, + dimensionsText, byteLength: bytes.length, formattedSize: formatFileSize(bytes.length), base64Length: base64.length, + formattedBase64Size: formatFileSize(base64.length), + expansionRatio, + expansionPercent, encoded: base64, + urlSafeBase64, dataUri, + svgUtf8DataUri, + formattedSvgUtf8Size, markdown: isSvg ? `![svg](${dataUri})` : `[data](${dataUri})`, html: isSvg ? `svg` : `Download`, cssBackground: isSvg ? `background-image: url('${dataUri}');` : undefined, diff --git a/extensions/base64image/tests/clipboard-svg.test.mjs b/extensions/base64image/tests/clipboard-svg.test.mjs deleted file mode 100644 index 3e4653fa..00000000 --- a/extensions/base64image/tests/clipboard-svg.test.mjs +++ /dev/null @@ -1,267 +0,0 @@ -import test from 'node:test' -import assert from 'node:assert/strict' -import { createHost, mount, tick } from '../../shared/test-harness.mjs' -import Base64ImageCommand from '../dist/index.js' -import { parseBase64Image, detectImageFormat, isSvgSource } from '../dist/logic.js' - -const host = createHost() -test.beforeEach(() => host.reset()) - -const PNG_B64 = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==' -const JPEG_B64 = Buffer.from([0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46, 0x49, 0x46, 0x00, 0x01, 0xff, 0xd9]).toString('base64') -const GIF_B64 = Buffer.from('GIF89a\x01\x00\x01\x00\x00\x00\x00;', 'latin1').toString('base64') -const DOCTYPE_SVG = '\n\n' - -const sectionTitles = (view) => { - const out = [] - const walk = (n) => { - if (!n || typeof n !== 'object') return - if (Array.isArray(n)) return n.forEach(walk) - if (n.type === 'List.Section') out.push(n.props.title) - walk(n.children) - walk(n.props?.children) - } - walk(view.tree()) - return out.length ? out : JSON.stringify(view.tree()).match(/"title":"(已载入[^"]*|转换结果[^"]*|无法识别|开始)"/g) -} -const toastText = (t) => `${t?.title ?? ''} ${t?.message ?? ''}` - -/** 模拟一个按路径读取的文件系统:只返回登记过的文件,其余报 PERMISSION_DENIED */ -function fakeFiles(files) { - host.ipc.filesystem_get_file_size = async ({ path }) => { - if (!(path in files)) throw Object.assign(new Error('路径未由当前窗口授权'), { code: 'PERMISSION_DENIED' }) - return { success: true, size: files[path].size ?? Buffer.from(files[path].content, 'base64').length } - } - host.ipc.filesystem_read_file = async ({ path, encoding }) => { - assert.equal(encoding, 'base64') - if (!(path in files)) throw Object.assign(new Error('路径未由当前窗口授权'), { code: 'PERMISSION_DENIED' }) - return { success: true, content: files[path].content } - } -} -const readPaths = () => host.ipcCalls.filter(([m]) => m === 'filesystem_read_file').map(([, p]) => p.path) - -// ---------- 访达 / 资源管理器里复制的图片文件读原文件 ---------- - -test('访达复制的 JPEG:读原文件字节,保留格式与文件名,不走剪贴板重编码', async () => { - host.ipc.clipboard_read_files = async () => ({ success: true, files: ['/Users/me/Pictures/photo.jpg'] }) - host.ipc.clipboard_read_image = async () => assert.fail('有图片文件时不应读取重编码的剪贴板图片') - fakeFiles({ '/Users/me/Pictures/photo.jpg': { content: JPEG_B64 } }) - const view = await mount(Base64ImageCommand) - await view.run(view.item('start-paste'), '粘贴剪贴板图片或文字') - assert.deepEqual(readPaths(), ['/Users/me/Pictures/photo.jpg']) - assert.ok(String(sectionTitles(view)).includes('已载入 photo.jpg'), String(sectionTitles(view))) - const dataUri = view.item('export-datauri') - assert.equal(dataUri.props.subtitle.startsWith('data:image/jpeg;base64,'), true) - await view.run(dataUri, '复制 Data URL') - assert.equal(host.clipboard.text, `data:image/jpeg;base64,${JPEG_B64}`) - assert.match(toastText(host.toasts.find((t) => /已转换/.test(t.title))), /photo\.jpg/) -}) - -test('复制了多个文件:跳过非图片,取第一个图片文件(扩展名不区分大小写)', async () => { - host.ipc.clipboard_read_files = async () => ({ success: true, files: ['/a/readme.txt', '/a/动图 1.GIF', '/a/b.png'] }) - host.ipc.clipboard_read_image = async () => assert.fail('不应读取剪贴板图片') - fakeFiles({ '/a/动图 1.GIF': { content: GIF_B64 }, '/a/b.png': { content: PNG_B64 } }) - const view = await mount(Base64ImageCommand) - await view.run(view.item('start-paste'), '粘贴剪贴板图片或文字') - assert.deepEqual(readPaths(), ['/a/动图 1.GIF']) - assert.equal(view.item('export-datauri').props.subtitle.startsWith('data:image/gif;base64,'), true) -}) - -test('[故障注入] 文件剪贴板不可用或为空时回退到剪贴板图片(截图)', async () => { - for (const readFiles of [ - async () => { throw Object.assign(new Error('Mac clipboard helper unavailable'), { code: 'NATIVE_HOST_UNAVAILABLE' }) }, - async () => ({ success: true, files: [] }), - async () => ({ success: true, files: 'not-an-array' }), - undefined // 旧宿主未实现 clipboard_read_files - ]) { - host.reset() - if (readFiles) host.ipc.clipboard_read_files = readFiles - host.ipc.clipboard_read_image = async () => ({ success: true, image: `data:image/png;base64,${PNG_B64}`, useTempFile: false }) - const view = await mount(Base64ImageCommand) - await view.run(view.item('start-paste'), '粘贴剪贴板图片或文字') - assert.ok(String(sectionTitles(view)).includes('已载入 剪贴板图片.png')) - assert.ok(host.ipcCalls.some(([m]) => m === 'clipboard_read_image')) - view.unmount() - } -}) - -test('[边界] 复制的文件都不是图片 / 图片文件超过 10 MB / 文件读不到:提示真实原因,不读重编码图片', async () => { - host.ipc.clipboard_read_image = async () => assert.fail('不应读取剪贴板图片') - host.ipc.clipboard_read_files = async () => ({ success: true, files: ['/a/报告.pdf', '/a/notes'] }) - fakeFiles({}) - let view = await mount(Base64ImageCommand) - await view.run(view.item('start-paste'), '粘贴剪贴板图片或文字') - assert.match(toastText(host.lastToast()), /读取复制的图片文件失败.*不是支持的图片.*报告\.pdf/) - assert.deepEqual(readPaths(), []) - view.unmount() - - host.reset() - host.ipc.clipboard_read_image = async () => assert.fail('不应读取剪贴板图片') - host.ipc.clipboard_read_files = async () => ({ success: true, files: ['/a/huge.jpg'] }) - fakeFiles({ '/a/huge.jpg': { content: JPEG_B64, size: 12 * 1024 * 1024 } }) - view = await mount(Base64ImageCommand) - await view.run(view.item('start-paste'), '粘贴剪贴板图片或文字') - assert.match(toastText(host.lastToast()), /10 MB(12\.0 MB)/) - assert.deepEqual(readPaths(), [], '超大文件不应被读取') - view.unmount() - - host.reset() - host.ipc.clipboard_read_files = async () => ({ success: true, files: ['/a/gone.png'] }) - fakeFiles({}) - view = await mount(Base64ImageCommand) - await view.run(view.item('start-paste'), '粘贴剪贴板图片或文字') - assert.match(toastText(host.lastToast()), /读取复制的图片文件失败.*未由当前窗口授权/) - assert.ok(String(sectionTitles(view)).includes('开始')) -}) - -test('[故障注入] 扩展名是图片但内容不是图片:提示不是支持的图片', async () => { - host.ipc.clipboard_read_files = async () => ({ success: true, files: ['/a/fake.png'] }) - fakeFiles({ '/a/fake.png': { content: Buffer.from('not an image').toString('base64') } }) - const view = await mount(Base64ImageCommand) - await view.run(view.item('start-paste'), '粘贴剪贴板图片或文字') - assert.match(String(host.lastToast().title), /不是支持的图片/) - assert.ok(String(sectionTitles(view)).includes('开始')) -}) - -// ---------- 剪贴板图片读取失败要提示真实原因 ---------- - -test('剪贴板图片超过 10 MB:提示真实原因与替代办法,不落到「没有图片或文字」', async () => { - host.clipboard.text = 'should-not-be-used' - host.ipc.clipboard_read_image = async () => ({ success: true, useTempFile: true, tempFile: '/cache/clip.png', size: 11153135 }) - host.ipc.filesystem_read_file = async () => assert.fail('超大图片不应被读取') - const view = await mount(Base64ImageCommand) - await view.run(view.item('start-paste'), '粘贴剪贴板图片或文字') - const t = host.lastToast() - assert.equal(t.title, '读取剪贴板图片失败') - assert.match(String(t.message), /超过 10 MB(10\.6 MB).*选择图片文件/) - assert.equal(host.toasts.some((x) => /没有图片或文字/.test(toastText(x))), false) - assert.equal(view.tree().props.searchText, '', '读图失败时不应改读剪贴板文字') -}) - -test('[故障注入] 宿主读图抛错(超 16 MiB / 像素超限 / 其他错误)都把宿主原因带给用户', async () => { - const cases = [ - [{ code: 'FILE_TOO_LARGE', message: '剪贴板图片超过16MiB上限' }, /剪贴板图片超过16MiB上限;原图文件可改用「选择图片文件」/], - [{ code: 'FILE_TOO_LARGE', message: '剪贴板图片尺寸超出上限' }, /尺寸超出上限/], - [{ code: 'CLIPBOARD_ERROR', message: '剪贴板被其他程序占用' }, /^剪贴板被其他程序占用$/] - ] - for (const [error, expected] of cases) { - host.reset() - host.clipboard.text = 'aGVsbG8=' - host.ipc.clipboard_read_image = async () => { throw Object.assign(new Error(error.message), { code: error.code }) } - const view = await mount(Base64ImageCommand) - await view.run(view.item('start-paste'), '粘贴剪贴板图片或文字') - assert.equal(host.lastToast().title, '读取剪贴板图片失败') - assert.match(String(host.lastToast().message), expected) - assert.equal(view.tree().props.searchText, '') - view.unmount() - } -}) - -test('剪贴板确实没有图片:读文字;文字也为空才提示「没有图片或文字」;读文字失败单独提示', async () => { - host.ipc.clipboard_read_image = async () => ({ success: true, image: '', useTempFile: false }) - let view = await mount(Base64ImageCommand) - await view.run(view.item('start-paste'), '粘贴剪贴板图片或文字') - assert.equal(host.lastToast().title, '剪贴板里没有图片或文字') - view.unmount() - - host.clipboard.text = ` data:image/png;base64,${PNG_B64}\n` - view = await mount(Base64ImageCommand) - await view.run(view.item('start-paste'), '粘贴剪贴板图片或文字') - assert.equal(view.tree().props.searchText, `data:image/png;base64,${PNG_B64}`) - view.unmount() - - // 读剪贴板文字失败 - Object.defineProperty(host.clipboard, 'text', { configurable: true, get() { throw new Error('剪贴板被占用') }, set() {} }) - try { - view = await mount(Base64ImageCommand) - await view.run(view.item('start-paste'), '粘贴剪贴板图片或文字') - assert.equal(host.lastToast().title, '读取剪贴板失败') - assert.match(String(host.lastToast().message), /剪贴板被占用/) - } finally { - Object.defineProperty(host.clipboard, 'text', { configurable: true, writable: true, enumerable: true, value: '' }) - } -}) - -test('[互斥] 连按两次粘贴只发起一次读取,读取结束后可再次读取', async () => { - let release - host.ipc.clipboard_read_image = () => new Promise((r) => { release = () => r({ success: true, image: `data:image/png;base64,${PNG_B64}` }) }) - const view = await mount(Base64ImageCommand) - const item = view.item('start-paste') - const first = view.run(item, '粘贴剪贴板图片或文字') - const second = view.run(item, '粘贴剪贴板图片或文字') - await tick() - release() - await Promise.all([first, second]) - await tick() - assert.equal(host.ipcCalls.filter(([m]) => m === 'clipboard_read_image').length, 1) - assert.ok(String(sectionTitles(view)).includes('已载入 剪贴板图片.png')) - - host.ipc.clipboard_read_image = async () => ({ success: true, image: '', useTempFile: false }) - await view.run(view.item('export-datauri'), '粘贴剪贴板图片或文字') - assert.equal(host.ipcCalls.filter(([m]) => m === 'clipboard_read_image').length, 2) -}) - -// ---------- 带 DOCTYPE / 注释 / 大写的 SVG ---------- - -test('选择带 的 SVG 文件(matplotlib 导出):识别为 SVG', async () => { - const content = Buffer.from('' + DOCTYPE_SVG).toString('base64') - host.ipc.window_show_open_dialog = async () => ({ canceled: false, filePath: '/Users/me/plot.svg' }) - fakeFiles({ '/Users/me/plot.svg': { content } }) - const view = await mount(Base64ImageCommand) - await view.run(view.item('start-pick'), '选择图片文件…') - assert.ok(String(sectionTitles(view)).includes('已载入 plot.svg')) - assert.equal(view.item('export-datauri').props.subtitle.startsWith('data:image/svg+xml;base64,'), true) -}) - -test('输入框粘贴以 DOCTYPE / 注释开头或大写 的源码:按 SVG 源码转换', async () => { - const view = await mount(Base64ImageCommand) - for (const src of [ - '', - '\n', - '', - DOCTYPE_SVG - ]) { - await view.search(src) - const item = view.item('export-datauri') - assert.equal(item.props.subtitle.startsWith('data:image/svg+xml;base64,'), true, src) - assert.match(view.item('export-html').props.subtitle, /^') - assert.match(view.item('item-error').props.title, /不是 SVG 图片/) - await view.search('!!!!') - assert.equal(view.item('item-error').props.title, 'Base64 字符内容非法或填充位数不正确') -}) - -test('[边界] isSvgSource:前导组合、内部子集、BOM;拒绝非 SVG 与未闭合前导;超长输入不卡顿', () => { - const yes = [ - '', - '\n ', - DOCTYPE_SVG, - ' ]>' - ] - const no = ['', '', '', ''.repeat(100_000) + ''), false, '前导部分数量有上限') - assert.ok(Date.now() - started < 1000, '超长输入应在 1 秒内返回') -}) - -test('[边界] 粘贴非 SVG 的 XML / HTML:明确提示不是 SVG 图片,不生成 text/plain 的「图片」写法', async () => { - for (const src of ['hi', '', '
x
']) { - const view = await mount(Base64ImageCommand) - await view.search(src) - assert.deepEqual(view.items().map((i) => i.props.id), ['item-error'], src) - assert.match(view.item('item-error').props.title, /不是 SVG 图片/) - assert.equal(view.items().some((i) => i.props.id === 'export-datauri'), false) - view.unmount() - } -}) diff --git a/extensions/base64image/tests/index.test.mjs b/extensions/base64image/tests/index.test.mjs index 3a78edc0..18b286bb 100644 --- a/extensions/base64image/tests/index.test.mjs +++ b/extensions/base64image/tests/index.test.mjs @@ -1,142 +1,134 @@ import test from 'node:test' import assert from 'node:assert/strict' -import { createHost, mount } from '../../shared/test-harness.mjs' +import { createHost, mount, tick } from '../../shared/test-harness.mjs' import Base64ImageCommand from '../dist/index.js' -import { parseBase64Image, encodeSvgOrTextToBase64 } from '../dist/logic.js' +import { + parseBase64Image, + encodeSvgOrTextToBase64, + toUrlSafeBase64, + normalizeBase64Input, + parseImageDimensions, + base64ToBytes, + SAMPLE_PNG_DATA_URI, + SAMPLE_SVG +} from '../dist/logic.js' const host = createHost() -test.beforeEach(() => host.reset()) +const views = [] -const PNG_B64 = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==' - -test('选择图片文件:读取后生成 Data URL,并能一键复制', async () => { - host.ipc.window_show_open_dialog = async () => ({ canceled: false, filePath: '/Users/me/截图 1.png' }) - host.ipc.filesystem_get_file_size = async () => ({ success: true, size: 70 }) - host.ipc.filesystem_read_file = async (p) => { - assert.equal(p.encoding, 'base64') - return { success: true, content: PNG_B64, size: 70 } - } - const view = await mount(Base64ImageCommand) - await view.run(view.item('start-pick'), '选择图片文件…') - const dataUri = view.item('export-datauri') - assert.equal(dataUri.props.subtitle.startsWith('data:image/png;base64,iVBOR'), true) - await view.run(dataUri, '复制 Data URL') - assert.equal(host.clipboard.text, `data:image/png;base64,${PNG_B64}`) - // 右侧预览显示真实图片 - assert.ok(JSON.stringify(dataUri.props.detail).includes(`![preview](data:image/png;base64,${PNG_B64})`)) +test.beforeEach(() => { + host.reset() + host.ipc.clipboard_read_files = async () => ({ files: [] }) + host.ipc.clipboard_read_image = async () => ({ image: '' }) }) -test('粘贴截图:剪贴板图片直接转换;剪贴板没有图片时读取文字', async () => { - host.ipc.clipboard_read_image = async () => ({ success: true, image: `data:image/png;base64,${PNG_B64}`, useTempFile: false }) - let view = await mount(Base64ImageCommand) - await view.run(view.item('start-paste'), '粘贴剪贴板图片或文字') - assert.ok(view.items().some((i) => i.props.id === 'export-datauri')) - view.unmount() - - host.ipc.clipboard_read_image = async () => ({ success: true, image: '', useTempFile: false }) - host.clipboard.text = `data:image/png;base64,${PNG_B64}` - view = await mount(Base64ImageCommand) - await view.run(view.item('start-paste'), '粘贴剪贴板图片或文字') - assert.equal(view.tree().props.searchText, host.clipboard.text) +test.afterEach(() => { + views.splice(0).forEach((v) => v.unmount()) }) -test('[边界] 大截图走临时文件读取;超过 10 MB 的图片拒绝并提示', async () => { - host.ipc.clipboard_read_image = async () => ({ success: true, useTempFile: true, tempFile: '/cache/clip.png', size: 600 * 1024 }) - host.ipc.filesystem_read_file = async (p) => (assert.equal(p.path, '/cache/clip.png'), { success: true, content: PNG_B64 }) - let view = await mount(Base64ImageCommand) - await view.run(view.item('start-paste'), '粘贴剪贴板图片或文字') - assert.ok(view.items().some((i) => i.props.id === 'export-datauri')) - view.unmount() - - host.ipc.window_show_open_dialog = async () => ({ canceled: false, filePath: '/big.png' }) - host.ipc.filesystem_get_file_size = async () => ({ success: true, size: 11 * 1024 * 1024 }) - host.ipc.filesystem_read_file = async () => assert.fail('超大文件不应被读取') - view = await mount(Base64ImageCommand) - await view.run(view.item('start-pick'), '选择图片文件…') - assert.match(String(host.lastToast().message || host.lastToast().title), /10 MB/) -}) - -test('[故障注入] 用户取消选择不报错;读文件失败、不是图片都给出提示', async () => { - host.ipc.window_show_open_dialog = async () => ({ canceled: true }) - let view = await mount(Base64ImageCommand) - await view.run(view.item('start-pick'), '选择图片文件…') - assert.equal(host.toasts.length, 0) - - host.ipc.window_show_open_dialog = async () => ({ canceled: false, filePath: '/x.png' }) - host.ipc.filesystem_get_file_size = async () => ({ success: true, size: 10 }) - host.ipc.filesystem_read_file = async () => { throw Object.assign(new Error('路径未由当前窗口授权'), { code: 'PERMISSION_DENIED' }) } - await view.run(view.item('start-pick'), '选择图片文件…') - assert.match(String(host.lastToast().title), /读取图片失败/) - - host.ipc.filesystem_read_file = async () => ({ success: true, content: Buffer.from('not an image').toString('base64') }) - await view.run(view.item('start-pick'), '选择图片文件…') - assert.match(String(host.lastToast().title), /不是支持的图片/) -}) - -test('解析:识别格式与大小,拒绝非法与超大输入', () => { - const ok = parseBase64Image(`data:image/png;base64,${PNG_B64}`) - assert.equal(ok.valid, true) - assert.equal(ok.format, 'png') - for (const bad of ['', 'data:text/plain;base64,AAAA', '!!!!', Buffer.from('hello').toString('base64'), '中文']) { - assert.equal(parseBase64Image(bad).valid, false, bad) - } - assert.equal(parseBase64Image('A'.repeat(16 * 1024 * 1024 + 4)).valid, false) - assert.equal(encodeSvgOrTextToBase64('').mimeType, 'image/svg+xml') +async function openView() { + const view = await mount(Base64ImageCommand) + views.push(view) + return view +} + +test('纯函数:PNG 尺寸、膨胀比、URL-Safe 双向互转与异常输入拦截', () => { + const parsed = parseBase64Image(SAMPLE_PNG_DATA_URI) + assert.equal(parsed.valid, true) + assert.equal(parsed.format, 'png') + assert.equal(parsed.width, 1) + assert.equal(parsed.height, 1) + assert.equal(parsed.dimensionsText, '1 × 1 px') + assert.ok(parsed.expansionRatio > 1.3) + assert.match(parsed.expansionPercent, /^\+3\d\.\d%$/) + assert.match(parsed.cssBackground, /^background-image: url\('data:image\/png;base64,/) + assert.equal(parsed.urlSafeBase64, toUrlSafeBase64(parsed.encoded)) + assert.ok(!/[+/=]/.test(parsed.urlSafeBase64)) + + // URL-Safe Base64 反向解码同样识别为合法 PNG + const fromUrlSafe = parseBase64Image(parsed.urlSafeBase64) + assert.equal(fromUrlSafe.valid, true) + assert.equal(fromUrlSafe.format, 'png') + assert.equal(fromUrlSafe.encoded, parsed.encoded) + + // GIF 与 BMP 头尺寸解析 + const gifBytes = new Uint8Array([0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x40, 0x01, 0xf0, 0x00]) + assert.deepEqual(parseImageDimensions(gifBytes, 'gif'), { width: 320, height: 240 }) + + // SVG 编码含 UTF-8 Data URI 与尺寸解析 + const svgRes = encodeSvgOrTextToBase64(SAMPLE_SVG) + assert.equal(svgRes.valid, true) + assert.equal(svgRes.format, 'svg') + assert.equal(svgRes.width, 100) + assert.equal(svgRes.height, 100) + assert.match(svgRes.svgUtf8DataUri, /^data:image\/svg\+xml;utf8,/) + assert.ok(svgRes.formattedSvgUtf8Size) + + // 非法输入拦截 + assert.equal(parseBase64Image('').valid, false) + assert.equal(parseBase64Image('你好世界').valid, false) + assert.equal(parseBase64Image('data:text/plain;base64,SGVsbG8=').valid, false) + assert.equal(normalizeBase64Input('abc+def-ghi'), null) + assert.equal(parseBase64Image('SGVsbG8=').valid, false) + + // 字节头边界检查 + const pngBytes = base64ToBytes(parsed.encoded) + assert.deepEqual(parseImageDimensions(pngBytes, 'png'), { width: 1, height: 1 }) }) - -test('支持通过 plugin_files_dropped(旧宿主回退)拖入图片文件转成 Base64,非图片报错提示', async () => { - const listeners = new Map() - globalThis.window.__ztoolsDeclarativeFeatures = { fileInput: false } - globalThis.window.ztools = { - events: { - on(event, cb) { - listeners.set(event, cb) - return () => listeners.delete(event) - } - } - } - try { - host.ipc.filesystem_get_file_size = async () => ({ success: true, size: 70 }) - host.ipc.filesystem_read_file = async () => ({ success: true, content: PNG_B64, size: 70 }) - const view = await mount(Base64ImageCommand) - assert.equal(typeof listeners.get('plugin_files_dropped'), 'function') - - listeners.get('plugin_files_dropped')({ payload: { files: ['/Users/me/doc.pdf'] } }) - await new Promise(r => setTimeout(r, 20)) - assert.equal(host.lastToast().title, '读取拖入的图片失败') - - listeners.get('plugin_files_dropped')({ payload: { files: ['/Users/me/dropped.png'] } }) - await new Promise(r => setTimeout(r, 20)) - const dataUri = view.item('export-datauri') - assert.equal(dataUri.props.subtitle.startsWith('data:image/png;base64,iVBOR'), true) - view.unmount() - assert.equal(listeners.has('plugin_files_dropped'), false) - } finally { - globalThis.window.__ztoolsDeclarativeFeatures = { fileInput: true } - delete globalThis.window.ztools - } +test('界面集成:单行 filterBar 常驻入口、CSS 与 URL-Safe 复制、Detail 预览与膨胀比', async () => { + const view = await openView() + const initialFilterBar = view.tree().props.filterBar + assert.ok(initialFilterBar) + assert.deepEqual( + initialFilterBar.actions.map((a) => a.title), + ['选择图片', '读取剪贴板'] + ) + + // 输入 PNG Data URL + await view.search(SAMPLE_PNG_DATA_URI) + const tree = view.tree() + assert.equal(tree.props.isShowingDetail, true) + assert.match(tree.props.filterBar.summaryText, /PNG/) + assert.match(tree.props.filterBar.summaryText, /1 × 1 px/) + assert.match(tree.props.filterBar.summaryText, /\+3\d\.\d%/) + + // 校验 CSS background-image 与 URL-Safe Base64 导出项及复制行为 + const cssItem = view.item('export-css') + assert.equal(cssItem.props.title, 'CSS background-image') + await view.run(cssItem, '复制 CSS background-image') + assert.match(host.clipboard.text, /^background-image: url\('data:image\/png;base64,/) + + const urlSafeItem = view.item('export-urlsafe-base64') + assert.equal(urlSafeItem.props.title, 'URL-Safe Base64') + await view.run(urlSafeItem, '复制 URL-Safe Base64') + assert.ok(host.clipboard.text.length > 0) + assert.ok(!/[+/=]/.test(host.clipboard.text)) + + // 校验右侧 Detail 包含真实图片预览与体积膨胀比 + const detailMd = cssItem.props.detail.props.markdown + assert.match(detailMd, /!\[preview\]\(data:image\/png;base64,/) + assert.match(detailMd, /像素尺寸:1 × 1 px/) + assert.match(detailMd, /体积膨胀比:\d+\.\d{2}×(\+3\d\.\d%)/) }) -test('支持通过 createCompatFileInputProps 粘贴图片文件与 Base64 文本,非支持扩展名由宿主拦截提示', async () => { - host.ipc.filesystem_get_file_size = async () => ({ success: true, size: 70 }) - host.ipc.filesystem_read_file = async (p) => { - assert.equal(p.path, '/Users/me/pasted.png') - return { success: true, content: PNG_B64, size: 70 } - } - const view = await mount(Base64ImageCommand) - try { - await view.pasteFiles(['/Users/me/doc.pdf']) - assert.equal(host.lastToast().title, '文件格式不匹配') - - await view.pasteFiles(['/Users/me/pasted.png']) - await new Promise(r => setTimeout(r, 20)) - const dataUri = view.item('export-datauri') - assert.equal(dataUri.props.subtitle.startsWith('data:image/png;base64,iVBOR'), true) - - await view.pasteText(` data:image/png;base64,${PNG_B64} `) - assert.equal(view.tree().props.searchText, `data:image/png;base64,${PNG_B64}`) - } finally { - view.unmount() - } +test('界面集成:filterBar 点击读取剪贴板可解析 SVG 并展示 UTF-8 优化项,空剪贴板正确报错', async () => { + const view = await openView() + const readClipboardBtn = view.tree().props.filterBar.actions.find((a) => a.id === 'read-clipboard') + assert.ok(readClipboardBtn) + + // 空剪贴板时提示失败 + await readClipboardBtn.onAction() + await tick() + assert.equal(host.lastToast().title, '剪贴板里没有图片或文字') + + // 写入 SVG 源码至剪贴板并点击读取 + host.clipboard.text = SAMPLE_SVG + await readClipboardBtn.onAction() + await tick() + + const svgUtf8Item = view.item('export-svg-utf8') + await view.run(svgUtf8Item, '复制 SVG UTF-8 Data URL') + assert.match(host.clipboard.text, /^data:image\/svg\+xml;utf8,/) + assert.match(svgUtf8Item.props.detail.props.markdown, /SVG UTF-8 体积:/) }) diff --git a/extensions/base64image/tests/review-regressions.test.mjs b/extensions/base64image/tests/review-regressions.test.mjs deleted file mode 100644 index 60da201d..00000000 --- a/extensions/base64image/tests/review-regressions.test.mjs +++ /dev/null @@ -1,101 +0,0 @@ -import test from 'node:test' -import assert from 'node:assert/strict' -import { createHost, mount } from '../../shared/test-harness.mjs' -import Command from '../dist/index.js' -const host = createHost() -test.beforeEach(() => host.reset()) - -test('7 MiB 合法 SVG 的超限结果可完整另存文件,不再暴露必败的复制主动作', async () => { - const start = '' - const svg = start + 'x'.repeat(7 * 1024 * 1024 - start.length - end.length) + end - const base64 = Buffer.from(svg).toString('base64') - host.ipc.window_show_open_dialog = async () => ({ canceled: false, filePath: '/test.svg' }) - host.ipc.filesystem_get_file_size = async () => ({ size: Buffer.byteLength(svg) }) - host.ipc.filesystem_read_file = async () => ({ content: base64 }) - host.ipc.window_show_save_dialog = async () => ({ canceled: false, filePath: '/转换结果.txt' }) - let saved - host.ipc.filesystem_write_file = async params => { saved = params; return { success: true } } - const view = await mount(Command) - try { - await view.run(view.item('start-pick'), '选择图片文件…') - const item = view.item('export-raw-base64') - assert.equal(view.actions(item)[0].props.title, '保存为文本文件…') - assert.ok(!view.actions(item).some(a => a.props.title.startsWith('复制'))) - await view.run(item, '保存为文本文件…') - assert.deepEqual(saved, { path: '/转换结果.txt', content: base64, encoding: 'utf8' }) - assert.match(host.lastToast().title, /已保存/) - } finally { view.unmount() } -}) - -test('保存取消不写文件,写失败不提示成功;小结果仍可复制', async () => { - const view = await mount(Command) - try { - await view.run(view.item('start-sample'), '载入示例') - const item = view.item('export-datauri') - await view.run(item, '复制 Data URL') - assert.match(host.clipboard.text, /^data:image\/png;base64,/) - host.toasts.length = 0 - host.ipc.window_show_save_dialog = async () => ({ canceled: true }) - host.ipc.filesystem_write_file = async () => assert.fail('取消不应写入') - await view.run(item, '保存为文本文件…') - assert.equal(host.toasts.length, 0) - host.ipc.window_show_save_dialog = async () => ({ canceled: false, filePath: '/full.txt' }) - host.ipc.filesystem_write_file = async () => { throw new Error('磁盘已满') } - await view.run(item, '保存为文本文件…') - assert.equal(host.lastToast().title, '保存失败') - assert.match(host.lastToast().message, /磁盘已满/) - } finally { view.unmount() } -}) - -test('粘贴 Base64 / Data URL 还原并保存为图片文件:二进制 PNG 走 base64 写入,SVG 走 UTF-8 文本写入,取消与失败如实处理', async () => { - const PNG_B64 = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==' - const SVG_TEXT = '' - const SVG_B64 = Buffer.from(SVG_TEXT, 'utf8').toString('base64') - - const view = await mount(Command) - try { - // 1. 粘贴 PNG Data URL → 保存为 .png - await view.pasteText(`data:image/png;base64,${PNG_B64}`) - const saveItem = view.item('export-image-file') - let dialogParams - let written - host.ipc.window_show_save_dialog = async params => { - dialogParams = params - return { canceled: false, filePath: '/out/restored.png' } - } - host.ipc.filesystem_write_file = async params => { - written = params - return { success: true } - } - await view.run(saveItem, '还原并保存为图片文件…') - assert.equal(dialogParams.defaultName, 'restored-image.png') - assert.equal(dialogParams.filters, 'PNG 图片|png') - assert.deepEqual(written, { path: '/out/restored.png', content: PNG_B64, encoding: 'base64' }) - assert.equal(host.lastToast().title, '已还原并保存图片') - assert.equal(host.lastToast().message, '/out/restored.png') - - // 2. 粘贴 SVG Base64 → 保存为 .svg(解码后的真实 UTF-8 文本) - await view.pasteText(`data:image/svg+xml;base64,${SVG_B64}`) - host.ipc.window_show_save_dialog = async params => { - dialogParams = params - return { canceled: false, filePath: '/out/icon.svg' } - } - await view.run(view.item('export-image-file'), '还原并保存为图片文件…') - assert.equal(dialogParams.defaultName, 'restored-image.svg') - assert.equal(dialogParams.filters, 'SVG 图片|svg') - assert.deepEqual(written, { path: '/out/icon.svg', content: SVG_TEXT, encoding: 'utf8' }) - - // 3. 取消保存不写文件;写入失败如实提示 - host.toasts.length = 0 - host.ipc.window_show_save_dialog = async () => ({ canceled: true }) - host.ipc.filesystem_write_file = async () => assert.fail('取消不应写入图片文件') - await view.run(view.item('export-image-file'), '还原并保存为图片文件…') - assert.equal(host.toasts.length, 0) - - host.ipc.window_show_save_dialog = async () => ({ canceled: false, filePath: '/readonly/icon.svg' }) - host.ipc.filesystem_write_file = async () => { throw new Error('拒绝访问') } - await view.run(view.item('export-image-file'), '还原并保存为图片文件…') - assert.equal(host.lastToast().title, '保存图片失败') - assert.match(host.lastToast().message, /拒绝访问/) - } finally { view.unmount() } -}) diff --git a/extensions/browser-bookmarks/plugin.json b/extensions/browser-bookmarks/plugin.json index 32ddf197..8d31bcc9 100644 --- a/extensions/browser-bookmarks/plugin.json +++ b/extensions/browser-bookmarks/plugin.json @@ -1,7 +1,7 @@ { "id": "browser-bookmarks", "name": "网页书签", - "version": "1.0.6", + "version": "1.0.7", "minAppVersion": "1.1.8.0", "description": "只读聚合本机浏览器的多个配置,支持中文、拼音、网址与文件夹检索,打开或复制书签;无法读取的来源会明确提示", "author": "ZTools Team", diff --git a/extensions/browser-bookmarks/src/bookmark-scanner.ts b/extensions/browser-bookmarks/src/bookmark-scanner.ts index 0102c32e..38202e77 100644 --- a/extensions/browser-bookmarks/src/bookmark-scanner.ts +++ b/extensions/browser-bookmarks/src/bookmark-scanner.ts @@ -1,5 +1,5 @@ -import { getLocale } from '@ztools/declarative-ui' -import { BROWSERS, type BookmarkItem, type BrowserFilterValue, type BrowserType, type ScanBookmarksResponse } from './types.js' +import { getLocale, LocalStorage } from '@ztools/declarative-ui' +import { BROWSERS, type BookmarkItem, type BookmarkUsageEntry, type BookmarkUsageMap, type BrowserFilterValue, type BrowserType, type ScanBookmarksResponse } from './types.js' import { t } from './i18n.js' import { resolveErrorMessage } from './error-i18n.js' import { HOST_UNREADABLE_PREFIX_ZH, HOST_WARNING_NAMES_ZH } from './host-warnings.zh-data.js' @@ -128,3 +128,130 @@ export function emptyState({ items, warnings, sources, error, query, filter, pla if (warnings.length && !sources) return { title: t('emptyUnreadableAllTitle'), subtitle: t('emptyOpenDetailsSub'), failed: true } return { title: t('emptyNoBookmarksTitle'), subtitle: t('emptyNoBookmarksSub') } } + +export const BOOKMARK_USAGE_STORAGE_KEY = 'browser_bookmarks_usage_v1' +export const MAX_USAGE_ENTRIES = 200 +const MAX_FREQUENT_UNPINNED = 5 +const DAY_MS = 24 * 60 * 60 * 1000 + +export function sanitizeUsageMap(raw: unknown): BookmarkUsageMap { + if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return {} + const out: BookmarkUsageMap = {} + for (const [key, value] of Object.entries(raw as Record)) { + if (!key || !value || typeof value !== 'object' || Array.isArray(value)) continue + const record = value as Record + const count = typeof record.count === 'number' && Number.isFinite(record.count) && record.count >= 0 ? Math.floor(record.count) : 0 + const lastUsedAt = typeof record.lastUsedAt === 'number' && Number.isFinite(record.lastUsedAt) && record.lastUsedAt >= 0 ? record.lastUsedAt : 0 + const pinned = record.pinned === true + if (count > 0 || pinned) { + out[key] = pinned ? { count, lastUsedAt, pinned: true } : { count, lastUsedAt } + } + } + return out +} + +export function computeFrecencyScore(entry: BookmarkUsageEntry | undefined, now = Date.now()): number { + if (!entry) return 0 + if (!entry.pinned && entry.count <= 0) return 0 + const pinBonus = entry.pinned ? 1_000_000_000 : 0 + const countScore = entry.count * 1000 + const age = Math.max(0, now - entry.lastUsedAt) + const recencyBonus = entry.lastUsedAt <= 0 ? 0 : age <= DAY_MS ? 500 : age <= 7 * DAY_MS ? 250 : age <= 30 * DAY_MS ? 100 : 20 + return pinBonus + countScore + recencyBonus +} + +function pruneUsageMap(map: BookmarkUsageMap, now = Date.now()): BookmarkUsageMap { + const entries = Object.entries(map) + if (entries.length <= MAX_USAGE_ENTRIES) return map + entries.sort(([, a], [, b]) => computeFrecencyScore(b, now) - computeFrecencyScore(a, now)) + return Object.fromEntries(entries.slice(0, MAX_USAGE_ENTRIES)) +} + +export async function loadBookmarkUsage(): Promise { + try { + const raw = await LocalStorage.getItem(BOOKMARK_USAGE_STORAGE_KEY) + return sanitizeUsageMap(raw) + } catch { + return {} + } +} + +export async function recordBookmarkUsage(url: string, now = Date.now()): Promise { + if (!url) return loadBookmarkUsage() + const updated = await LocalStorage.updateItem(BOOKMARK_USAGE_STORAGE_KEY, (current) => { + const map = sanitizeUsageMap(current) + const prev = map[url] + const nextEntry: BookmarkUsageEntry = { + count: (prev?.count ?? 0) + 1, + lastUsedAt: now, + ...(prev?.pinned ? { pinned: true } : {}) + } + return pruneUsageMap({ ...map, [url]: nextEntry }, now) + }) + return sanitizeUsageMap(updated) +} + +export async function toggleBookmarkPin(url: string, now = Date.now()): Promise<{ map: BookmarkUsageMap; pinned: boolean }> { + let nextPinned = false + const updated = await LocalStorage.updateItem(BOOKMARK_USAGE_STORAGE_KEY, (current) => { + const map = sanitizeUsageMap(current) + const prev = map[url] + nextPinned = !prev?.pinned + const nextMap: BookmarkUsageMap = { ...map } + if (nextPinned) { + nextMap[url] = { + count: prev?.count ?? 0, + lastUsedAt: prev?.lastUsedAt || now, + pinned: true + } + } else if (prev && prev.count > 0) { + nextMap[url] = { count: prev.count, lastUsedAt: prev.lastUsedAt } + } else { + delete nextMap[url] + } + return pruneUsageMap(nextMap, now) + }) + return { map: sanitizeUsageMap(updated), pinned: nextPinned } +} + +/** 按置顶与访问频次(Frecency)分区或排序;无记录时保持原始顺序与平铺结构 */ +export function partitionBookmarksByUsage( + items: readonly BookmarkItem[], + usage: BookmarkUsageMap, + hasQuery: boolean, + now = Date.now() +): { frequent: BookmarkItem[]; regular: BookmarkItem[] } { + const scored = items.map((item, index) => { + const entry = usage[item.url] + return { + item, + index, + pinned: Boolean(entry?.pinned), + score: computeFrecencyScore(entry, now) + } + }) + + if (!scored.some(entry => entry.score > 0)) { + return { frequent: [], regular: [...items] } + } + + if (hasQuery) { + scored.sort((a, b) => (b.score !== a.score ? b.score - a.score : a.index - b.index)) + return { frequent: [], regular: scored.map(entry => entry.item) } + } + + const pinnedItems = scored.filter(entry => entry.pinned) + const unpinnedUsed = scored + .filter(entry => !entry.pinned && entry.score > 0) + .sort((a, b) => (b.score !== a.score ? b.score - a.score : a.index - b.index)) + .slice(0, MAX_FREQUENT_UNPINNED) + + pinnedItems.sort((a, b) => (b.score !== a.score ? b.score - a.score : a.index - b.index)) + const frequentEntries = [...pinnedItems, ...unpinnedUsed] + const frequentIds = new Set(frequentEntries.map(entry => entry.item.id)) + const regular = items.filter(item => !frequentIds.has(item.id)) + return { + frequent: frequentEntries.map(entry => entry.item), + regular + } +} diff --git a/extensions/browser-bookmarks/src/i18n.ts b/extensions/browser-bookmarks/src/i18n.ts index f18fe4f1..e780d0ee 100644 --- a/extensions/browser-bookmarks/src/i18n.ts +++ b/extensions/browser-bookmarks/src/i18n.ts @@ -23,6 +23,19 @@ const MESSAGES = { copyLink: "复制链接", copyMarkdownLink: "复制 Markdown 链接", copyTitle: "复制标题", + sectionPinnedFrequent: "常用置顶", + sectionAllBookmarks: "全部书签", + tagPinned: "置顶", + usedCountBadge: "已用 {count} 次", + pinBookmark: "置顶到常用", + unpinBookmark: "取消常用置顶", + pinnedToast: "已置顶到常用书签", + unpinnedToast: "已取消常用置顶", + usageSaveFailed: "保存常用记录失败", + openInSourceBrowserHint: "在来源浏览器中打开({browser})", + sourceBrowserCopiedToast: "已复制链接,请在 {browser}({profile})中粘贴打开", + sourceBrowserDefaultNotice: "系统默认使用默认浏览器直开,已为您复制该链接", + filterByDomain: "仅看此域名({hostname})", showMoreTitle: "显示更多书签(还剩 {remaining} 条)", showMoreSubtitle: "搜索会检索全部已读取的书签", showMoreAction: "显示更多", @@ -86,6 +99,19 @@ const MESSAGES = { copyLink: "Copy Link", copyMarkdownLink: "Copy Markdown Link", copyTitle: "Copy Title", + sectionPinnedFrequent: "Pinned & Frequent", + sectionAllBookmarks: "All Bookmarks", + tagPinned: "Pinned", + usedCountBadge: "Used {count} [[count:time|times]]", + pinBookmark: "Pin to Frequent", + unpinBookmark: "Unpin from Frequent", + pinnedToast: "Pinned to frequent bookmarks", + unpinnedToast: "Unpinned from frequent bookmarks", + usageSaveFailed: "Failed to save frequent bookmark", + openInSourceBrowserHint: "Open in Source Browser ({browser})", + sourceBrowserCopiedToast: "Link copied — paste in {browser} ({profile}) to open", + sourceBrowserDefaultNotice: "Default browser is used for direct open; link copied for source browser", + filterByDomain: "Filter by Domain ({hostname})", showMoreTitle: "Show More Bookmarks ({remaining} remaining)", showMoreSubtitle: "Search scans all loaded bookmarks", showMoreAction: "Show More", diff --git a/extensions/browser-bookmarks/src/index.tsx b/extensions/browser-bookmarks/src/index.tsx index c55696de..43e501d0 100644 --- a/extensions/browser-bookmarks/src/index.tsx +++ b/extensions/browser-bookmarks/src/index.tsx @@ -1,6 +1,24 @@ -import React, { List, Detail, Action, ActionPanel, Icon, Toast, showToast, useEffect, useLocale, useMemo, useRef, useState, useNavigation } from '@ztools/declarative-ui' -import { type BookmarkItem, type BrowserFilterValue } from './types.js' -import { scanAllBrowserBookmarksWithMeta, searchAndFilterBookmarks, UnreadableSourcesError, getFullDiskAccessGuide, hasSafariWarning, formatBookmarkDate, bookmarkMarkdown, browserOptions, detectPlatform, domesticLabel, emptyState, hasCredentials, type HostPlatform } from './bookmark-scanner.js' +import React, { List, Detail, Action, ActionPanel, Icon, Toast, Clipboard, showToast, useEffect, useLocale, useMemo, useRef, useState, useNavigation } from '@ztools/declarative-ui' +import { type BookmarkItem, type BookmarkUsageMap, type BrowserFilterValue } from './types.js' +import { + scanAllBrowserBookmarksWithMeta, + searchAndFilterBookmarks, + UnreadableSourcesError, + getFullDiskAccessGuide, + hasSafariWarning, + formatBookmarkDate, + bookmarkMarkdown, + browserOptions, + detectPlatform, + domesticLabel, + emptyState, + hasCredentials, + loadBookmarkUsage, + recordBookmarkUsage, + toggleBookmarkPin, + partitionBookmarksByUsage, + type HostPlatform +} from './bookmark-scanner.js' import { t } from './i18n.js' import { resolveErrorMessage } from './error-i18n.js' export * from './types.js' @@ -11,6 +29,7 @@ const markdownText = (text: string) => text.replace(/[\\`*_{}\[\]()<>#!|]/g, val export default function BrowserBookmarks({ initialFilter = 'all', platform = detectPlatform() }: { initialFilter?: BrowserFilterValue; platform?: HostPlatform } = {}) { useLocale() const [items, setItems] = useState([]), [warnings, setWarnings] = useState([]), [sources, setSources] = useState(0) + const [usageMap, setUsageMap] = useState({}) const [query, setQuery] = useState(''), [filter, setFilter] = useState(initialFilter), [visible, setVisible] = useState(200) const [loading, setLoading] = useState(true), [error, setError] = useState(''), [loadedOnce, setLoadedOnce] = useState(false), [unreadable, setUnreadable] = useState(false), [warningsPartial, setWarningsPartial] = useState(false) const pending = useRef(null), mounted = useRef(true), loadedOnceRef = useRef(false), { push } = useNavigation() @@ -28,8 +47,42 @@ export default function BrowserBookmarks({ initialFilter = 'all', platform = det setError(message(failure)); await showToast(Toast.Style.Failure, t('notUpdatedTitle'), message(failure)) } finally { pending.current = null; if (mounted.current) setLoading(false) } } - useEffect(() => { mounted.current = true; void reload(); return () => { mounted.current = false; pending.current?.abort() } }, []) + useEffect(() => { + mounted.current = true + void reload() + void loadBookmarkUsage().then(map => { if (mounted.current) setUsageMap(map) }) + return () => { mounted.current = false; pending.current?.abort() } + }, []) + const trackUsage = async (url: string) => { + try { + const updated = await recordBookmarkUsage(url) + if (mounted.current) setUsageMap(updated) + } catch { + // 频次记录写入失败不阻断书签打开或复制主流程 + } + } + const handleTogglePin = async (item: BookmarkItem) => { + try { + const result = await toggleBookmarkPin(item.url) + if (mounted.current) setUsageMap(result.map) + await showToast(Toast.Style.Success, result.pinned ? t('pinnedToast') : t('unpinnedToast'), item.title) + } catch (failure) { + await showToast(Toast.Style.Failure, t('usageSaveFailed'), message(failure)) + } + } + const handleOpenInSourceBrowserHint = async (item: BookmarkItem) => { + await Clipboard.copy(item.url) + await trackUsage(item.url) + await showToast( + Toast.Style.Success, + t('sourceBrowserCopiedToast', { browser: item.browserLabel, profile: item.profile }), + t('sourceBrowserDefaultNotice') + ) + } const filtered = useMemo(() => searchAndFilterBookmarks(items, query, filter), [items, query, filter]) + const { frequent, regular } = useMemo(() => partitionBookmarksByUsage(filtered, usageMap, Boolean(query.trim())), [filtered, usageMap, query]) + const visibleFrequent = frequent.slice(0, visible) + const visibleRegular = regular.slice(0, Math.max(0, visible - visibleFrequent.length)) const details = [error, ...warnings].filter(Boolean) const browserCount = new Set(items.map(item => item.browser)).size const status = error ? (loadedOnce ? t('statusRefreshFailed') : t('statusReadFailed')) : unreadable ? t('statusUnreadable') : warnings.length ? t('statusPartialWarnings') : '' @@ -42,6 +95,31 @@ export default function BrowserBookmarks({ initialFilter = 'all', platform = det const emptyFailed = Boolean(empty.failed) // 空状态行自带刷新与读取详情动作时,顶部状态条不再重复这两个按钮(同一功能只出现一次) const showEmpty = !loading && !filtered.length + const renderBookmarkItem = (item: BookmarkItem) => { + const usage = usageMap[item.url] + const isPinned = Boolean(usage?.pinned) + const accessories: Array<{ tag?: string; text?: string }> = [] + if (isPinned) accessories.push({ tag: t('tagPinned') }) + if (usage && usage.count > 0) accessories.push({ text: t('usedCountBadge', { count: usage.count }) }) + accessories.push({ tag: `${item.browserLabel} / ${item.profile}` }) + accessories.push({ text: formatBookmarkDate(item.dateAdded) }) + const credentialUrl = hasCredentials(item.url) + return + {credentialUrl + // 客户端只打开不含用户名、密码的网址(shell_open_external 会拒绝),这类书签只提供复制 + ? { void trackUsage(item.url) }} /> + : } + {!credentialUrl && { void trackUsage(item.url) }} />} + { void trackUsage(item.url) }} /> + + { void handleTogglePin(item) }} /> + {!credentialUrl && { void handleOpenInSourceBrowserHint(item) }} />} + {item.hostname && { setQuery(`domain:${item.hostname}`); setVisible(200) }} />} + } /> + } return { setQuery(value); setVisible(200) }} searchBarPlaceholder={t('searchPlaceholder')} searchBarAccessory={ { setFilter(value as BrowserFilterValue); setVisible(200) }} tooltip={t('filterTooltip')}> @@ -52,18 +130,14 @@ export default function BrowserBookmarks({ initialFilter = 'all', platform = det { id: 'refresh', title: t('refreshBookmarks'), onAction: reload }, ...(details.length ? [{ id: 'errors', title: t('readDetails'), onAction: openDetails }] : []) ] }}> - {filtered.slice(0, visible).map(item => - {hasCredentials(item.url) - // 客户端只打开不含用户名、密码的网址(shell_open_external 会拒绝),这类书签只提供复制 - ? - : } - {!hasCredentials(item.url) && } - - - } />)} + {visibleFrequent.length > 0 ? <> + + {visibleFrequent.map(renderBookmarkItem)} + + {visibleRegular.length > 0 && + {visibleRegular.map(renderBookmarkItem)} + } + : visibleRegular.map(renderBookmarkItem)} {filtered.length > visible && setVisible(count => count + 200)} />} />} {showEmpty && diff --git a/extensions/browser-bookmarks/tests/index.test.mjs b/extensions/browser-bookmarks/tests/index.test.mjs index 8de15906..eb9e1fe0 100644 --- a/extensions/browser-bookmarks/tests/index.test.mjs +++ b/extensions/browser-bookmarks/tests/index.test.mjs @@ -199,3 +199,52 @@ test('整体错误里原因已满 5 条(可能被截断)时,不断言所 const view = await open('bookmarks-chrome') assert.equal(view.items()[0].props.title, '未能确认 Chrome 书签') }) + +test('常用置顶、频次记忆(LocalStorage)持久化排序、来源浏览器直开提示与域名快捷筛选', async () => { + const b1 = { ...item('b1', 'chrome'), title: '普通书签', url: 'https://alpha.example.com/1', hostname: 'alpha.example.com' } + const b2 = { ...item('b2', 'edge'), browserLabel: 'Edge', profile: 'Work', title: '高频文档', url: 'https://beta.example.com/2', hostname: 'beta.example.com' } + const b3 = { ...item('b3', 'firefox'), browserLabel: 'Firefox', profile: 'default-release', title: '置顶控制台', url: 'https://gamma.example.com/3', hostname: 'gamma.example.com' } + host.ipc.browser_bookmarks_scan = async () => reply([b1, b2, b3]) + + const view = await open() + // 初始无常用记录,顺序保持原样 + assert.deepEqual(view.items().map(i => i.props.id), ['b1', 'b2', 'b3']) + + // 置顶 b3 到常用 + await view.run(view.item('b3'), '置顶到常用') + assert.equal(host.lastToast().title, '已置顶到常用书签') + assert.equal(view.items()[0].props.id, 'b3') + assert.match(view.text(), /常用置顶/) + assert.match(view.text(), /全部书签/) + + // 复制 b2 链接自动累加使用频次并进入常用分区 + await view.run(view.item('b2'), '复制链接') + assert.equal(host.clipboard.text, b2.url) + assert.deepEqual(view.items().map(i => i.props.id), ['b3', 'b2', 'b1']) + + // 卸载后重新打开,LocalStorage 记忆保留置顶与频次排序 + view.unmount() + views.splice(views.indexOf(view), 1) + const reopened = await open() + assert.deepEqual(reopened.items().map(i => i.props.id), ['b3', 'b2', 'b1']) + assert.match(JSON.stringify(reopened.item('b2').props.accessories), /已用 1 次/) + + // 来源浏览器直开提示:复制链接并给出所属浏览器与 Profile 提示 + await reopened.run(reopened.item('b2'), '在来源浏览器中打开(Edge)') + assert.equal(host.clipboard.text, b2.url) + assert.match(host.lastToast().title, /Edge(Work)/) + + // 快捷按域名筛选 + await reopened.run(reopened.item('b2'), '仅看此域名(beta.example.com)') + assert.deepEqual(reopened.items().map(i => i.props.id), ['b2']) + + // 清空搜索并取消置顶 + await reopened.search('') + await reopened.run(reopened.item('b3'), '取消常用置顶') + assert.equal(host.lastToast().title, '已取消常用置顶') + + // 存储写入异常时如实提示失败,不假报成功 + host.faults.storageWrite = new Error('disk full') + await reopened.run(reopened.item('b1'), '置顶到常用') + assert.equal(host.lastToast().title, '保存常用记录失败') +}) diff --git a/extensions/caffeine/plugin.json b/extensions/caffeine/plugin.json index 4bce3115..f5f0c40a 100644 --- a/extensions/caffeine/plugin.json +++ b/extensions/caffeine/plugin.json @@ -1,7 +1,7 @@ { "id": "caffeine", "name": "防休眠常亮", - "version": "1.0.9", + "version": "1.0.10", "minAppVersion": "1.1.8.0", "description": "阻止系统自动休眠与息屏,支持定时倒计时自动恢复与一键常亮切换", "author": "ZTools Team", diff --git a/extensions/caffeine/src/caffeine-service.ts b/extensions/caffeine/src/caffeine-service.ts index dd7be384..a1e1ccce 100644 --- a/extensions/caffeine/src/caffeine-service.ts +++ b/extensions/caffeine/src/caffeine-service.ts @@ -1,13 +1,17 @@ +import { LocalStorage } from '@ztools/declarative-ui' import { callHostTransport } from './native-ipc.js' import { t } from './i18n.js' import type { CaffeineActionResult, CaffeineMode, CaffeinePreset, - CaffeineStatus + CaffeineStatus, + ParsedCaffeineInput } from './types.js' import { resolveErrorMessage } from './error-i18n.js' +export const CAFFEINE_MODE_STORAGE_KEY = 'caffeine.lastMode' + const CAFFEINE_PRESET_DEFS = [ { id: 'caffeine-0', minutes: 0, titleKey: 'preset0Title', subtitleKey: 'preset0Subtitle' }, { id: 'caffeine-15', minutes: 15, titleKey: 'preset15Title', subtitleKey: 'preset15Subtitle' }, @@ -19,6 +23,7 @@ const CAFFEINE_PRESET_DEFS = [ export const CUSTOM_CAFFEINE_MIN_MINUTES = 5 export const CUSTOM_CAFFEINE_MAX_MINUTES = 720 +export const MAX_UNTIL_MINUTES = 1440 export function parseCustomCaffeineMinutes(query: string): number | null { const trimmed = (query || '').trim() @@ -30,6 +35,112 @@ export function parseCustomCaffeineMinutes(query: string): number | null { return minutes } +function pad2(n: number): string { + return String(n).padStart(2, '0') +} + +export function formatClockTime(ms: number): string { + const d = new Date(ms) + return `${pad2(d.getHours())}:${pad2(d.getMinutes())}` +} + +export function formatMinutesHuman(minutes: number): string { + if (minutes < 60) return t('durationMin', { min: minutes }) + const hours = Math.floor(minutes / 60) + const mins = minutes % 60 + return mins > 0 ? t('durationHourMin', { hours, mins }) : t('durationHour', { hours }) +} + +/** + * 解析搜索框自然时长或截止时刻: + * - 纯整数分钟(5~720):如 `45` + * - 带单位分钟(1~720):如 `45m`、`90min`、`90分钟` + * - 小时/小数小时(1~720 分钟):如 `1.5h`、`2hr`、`1.5小时` + * - 复合时分(1~720 分钟):如 `2h30m`、`1h 15m`、`1小时30分` + * - 截止时刻(1~1440 分钟,已过今日时刻自动顺延至明日):如 `18:30`、`9:00`、`至 18:30`、`until 18:30` + */ +export function parseCaffeineInput(query: string, now = Date.now()): ParsedCaffeineInput | null { + const trimmed = (query || '').trim() + if (!trimmed) return null + + // 1. 纯整数分钟(保持 5~720 边界) + const bareMinutes = parseCustomCaffeineMinutes(trimmed) + if (bareMinutes !== null) { + return { minutes: bareMinutes, kind: 'minutes' } + } + + // 2. 截止时刻:18:30 / 18:30 / 至 18:30 / 到 18:30 / until 18:30 + const untilMatch = trimmed.match(/^(?:(?:至|到|直到|until|to)\s*)?(\d{1,2})[::](\d{2})$/i) + if (untilMatch) { + const hour = Number(untilMatch[1]) + const minute = Number(untilMatch[2]) + if (hour < 0 || hour > 23 || minute < 0 || minute > 59) return null + const target = new Date(now) + target.setHours(hour, minute, 0, 0) + let isNextDay = false + if (target.getTime() <= now) { + target.setDate(target.getDate() + 1) + isNextDay = true + } + const diffMinutes = Math.ceil((target.getTime() - now) / 60_000) + if (diffMinutes < 1 || diffMinutes > MAX_UNTIL_MINUTES) return null + return { + minutes: diffMinutes, + kind: 'until', + targetTimeText: `${pad2(hour)}:${pad2(minute)}`, + isNextDay + } + } + + // 3. 复合时分:2h30m / 1h 15m / 1小时30分 / 2小时15分钟 + const compoundMatch = trimmed.match(/^(\d+)\s*(?:h|hr|hrs|hour|hours|小时|时)\s*(\d+)\s*(?:m|min|mins|minute|minutes|分钟|分)?$/i) + if (compoundMatch) { + const hours = Number(compoundMatch[1]) + const mins = Number(compoundMatch[2]) + const total = hours * 60 + mins + if (!Number.isSafeInteger(total) || total < 1 || total > CUSTOM_CAFFEINE_MAX_MINUTES) return null + return { minutes: total, kind: 'duration' } + } + + // 4. 小时(支持小数):1.5h / 2h / 0.5小时 + const hoursMatch = trimmed.match(/^(\d+(?:\.\d+)?)\s*(?:h|hr|hrs|hour|hours|小时|时)$/i) + if (hoursMatch) { + const hours = Number(hoursMatch[1]) + if (!Number.isFinite(hours) || hours <= 0) return null + const total = Math.round(hours * 60) + if (!Number.isSafeInteger(total) || total < 1 || total > CUSTOM_CAFFEINE_MAX_MINUTES) return null + return { minutes: total, kind: 'duration' } + } + + // 5. 带单位分钟:45m / 90min / 90分钟 / 3m + const minsMatch = trimmed.match(/^(\d+)\s*(?:m|min|mins|minute|minutes|分钟|分)$/i) + if (minsMatch) { + const total = Number(minsMatch[1]) + if (!Number.isSafeInteger(total) || total < 1 || total > CUSTOM_CAFFEINE_MAX_MINUTES) return null + return { minutes: total, kind: 'duration' } + } + + return null +} + +export async function loadSavedCaffeineMode(): Promise { + try { + const saved = await LocalStorage.getItem(CAFFEINE_MODE_STORAGE_KEY) + return saved === 'system' ? 'system' : 'display' + } catch { + return 'display' + } +} + +export async function saveCaffeineMode(mode: CaffeineMode): Promise { + if (mode !== 'display' && mode !== 'system') return + try { + await LocalStorage.setItem(CAFFEINE_MODE_STORAGE_KEY, mode) + } catch { + // 持久化失败不影响主流程 + } +} + export function getCaffeinePresets(): ReadonlyArray { return CAFFEINE_PRESET_DEFS.map(def => ({ id: def.id, diff --git a/extensions/caffeine/src/i18n.ts b/extensions/caffeine/src/i18n.ts index aca528be..d852e8fc 100644 --- a/extensions/caffeine/src/i18n.ts +++ b/extensions/caffeine/src/i18n.ts @@ -10,9 +10,10 @@ export const t = createTranslator( toastReleased: "已释放本插件的电源保持请求", toggleBusyError: "防休眠切换正在执行,请稍候", hudStarted: "已开启防休眠 · {remaining}", + hudStartedWithMode: "已开启{mode} · {remaining}", hudStopped: "已关闭防休眠", - searchPlaceholder: "选择防休眠持续时间,或输入 5~720 分钟自定义...", - modeTooltip: "下一次启动的防休眠模式", + searchPlaceholder: "选择防休眠时长,或输入 45 / 1.5h / 2h30m / 18:30...", + modeTooltip: "下一次启动的防休眠模式(自动记忆)", modeDisplay: "保持屏幕常亮 + 防系统休眠", modeSystem: "允许息屏,仅保持系统运行", summaryError: "状态无法确认:{error}", @@ -23,6 +24,7 @@ export const t = createTranslator( summaryRemaining: "剩余 {text}", summaryInactive: "未开启 · 系统按默认电源策略运行", stopAction: "停止防休眠", + extend15Action: "续时 +15 分钟", retryAction: "重试查询", sectionTitle: "防休眠时长", sectionSubtitle: "到期或退出客户端后释放;不会阻止手动锁屏与合盖休眠", @@ -43,6 +45,15 @@ export const t = createTranslator( preset240Subtitle: "适合半天无人值守批处理任务,到期后自动恢复系统休眠策略", customPresetTitle: "保持屏幕常亮 {minutes} 分钟", customPresetSubtitle: "自定义时长(5~720 分钟),到期后自动恢复系统休眠策略", + customSystemTitle: "系统保活 {minutes} 分钟", + customDurationTitle: "保持{mode} {duration}", + customDurationSubtitle: "自定义时长(共 {minutes} 分钟,约至 {until}),到期后自动恢复", + customUntilTitle: "保持{mode}至今日 {time}", + customUntilNextDayTitle: "保持{mode}至明日 {time}", + customUntilSubtitle: "约 {duration}({minutes} 分钟),到期后自动恢复系统休眠策略", + activeCustomTitle: "当前自定义{mode}({duration})", + activeCustomSubtitle: "预计至 {until} 自动恢复,回车立即停止", + activeCustomSubtitleNoUntil: "当前正在生效,回车立即停止", inactiveText: "未开启", untilManualStop: "直到手动关闭", durationSec: "{sec} 秒", @@ -63,9 +74,10 @@ export const t = createTranslator( toastReleased: "Power assertion released", toggleBusyError: "Keep Awake toggle is already running; please wait", hudStarted: "Keep Awake enabled · {remaining}", + hudStartedWithMode: "{mode} enabled · {remaining}", hudStopped: "Keep Awake disabled", - searchPlaceholder: "Select duration or type 5–720 minutes...", - modeTooltip: "Keep-awake mode for next activation", + searchPlaceholder: "Select duration or type 45, 1.5h, 2h30m, 18:30...", + modeTooltip: "Keep-awake mode for next activation (remembered)", modeDisplay: "Keep Display On + Prevent Sleep", modeSystem: "Allow Display Off, Keep System Awake", summaryError: "Status unconfirmed: {error}", @@ -76,6 +88,7 @@ export const t = createTranslator( summaryRemaining: "{text} left", summaryInactive: "Inactive · System follows default power policy", stopAction: "Stop Keep Awake", + extend15Action: "Extend +15m", retryAction: "Retry", sectionTitle: "Duration Presets", sectionSubtitle: "Releases on expiry or client exit; does not block manual lock or lid close", @@ -96,6 +109,15 @@ export const t = createTranslator( preset240Subtitle: "Ideal for half-day unattended batch jobs; restores sleep policy on expiry", customPresetTitle: "Keep Screen Awake for {minutes} Minutes", customPresetSubtitle: "Custom duration (5–720 minutes); restores sleep policy automatically on expiry", + customSystemTitle: "Keep System Awake for {minutes} Minutes", + customDurationTitle: "{mode} for {duration}", + customDurationSubtitle: "Custom duration ({minutes} min, until ~{until}); restores automatically", + customUntilTitle: "{mode} until {time} today", + customUntilNextDayTitle: "{mode} until {time} tomorrow", + customUntilSubtitle: "About {duration} ({minutes} min); restores sleep policy automatically", + activeCustomTitle: "Active Custom {mode} ({duration})", + activeCustomSubtitle: "Auto-restores around {until}; press Enter to stop", + activeCustomSubtitleNoUntil: "Currently active; press Enter to stop", inactiveText: "Inactive", untilManualStop: "Until stopped manually", durationSec: "{sec}s", diff --git a/extensions/caffeine/src/index.tsx b/extensions/caffeine/src/index.tsx index f9ecedf8..03a1daba 100644 --- a/extensions/caffeine/src/index.tsx +++ b/extensions/caffeine/src/index.tsx @@ -2,10 +2,11 @@ import React, { Action, ActionPanel, Icon, List, Toast, showHUD, showToast, useEffect, useLocale, useMemo, useRef, useState } from '@ztools/declarative-ui' import { - formatRemainingDuration, getCaffeinePresets, getCaffeineStatus, getDefaultInactiveStatus, - parseCustomCaffeineMinutes, startCaffeineSession, stopCaffeineSession, toggleCaffeineSession + formatClockTime, formatMinutesHuman, formatRemainingDuration, getCaffeinePresets, getCaffeineStatus, + getDefaultInactiveStatus, loadSavedCaffeineMode, parseCaffeineInput, saveCaffeineMode, + startCaffeineSession, stopCaffeineSession, toggleCaffeineSession } from './caffeine-service.js' -import type { CaffeineActionResult, CaffeineMode } from './types.js' +import type { CaffeineActionResult, CaffeineMode, CaffeinePreset } from './types.js' import { t } from './i18n.js' import { resolveErrorMessage } from './error-i18n.js' @@ -15,6 +16,7 @@ export * from './caffeine-service.js' export function CaffeineCommand(props: { featureCode?: string; hostOverride?: unknown } = {}) { const locale = useLocale() const [mode, setMode] = useState('display') + const modeRef = useRef('display') const [status, setStatus] = useState(() => getDefaultInactiveStatus()) const [statusError, setStatusError] = useState('') const [searchText, setSearchText] = useState('') @@ -24,14 +26,23 @@ export function CaffeineCommand(props: { featureCode?: string; hostOverride?: un const queryRunning = useRef(false) const revision = useRef(0) - const applyResult = (result: CaffeineActionResult, updateMode = false) => { + const updateMode = (next: CaffeineMode, persist = false) => { + modeRef.current = next + setMode(next) + if (persist) void saveCaffeineMode(next) + } + + const applyResult = (result: CaffeineActionResult, syncMode = false) => { if (!result.ok || !result.status) { setStatusError(resolveErrorMessage(result, t('statusUnavailable'))) return false } setStatusError('') setStatus(result.status) - if (updateMode) setMode(result.status.mode) + // 仅在活动态或显式操作结果时同步模式,避免空闲初始查询把用户记忆的 system 模式覆盖成默认 display + if (syncMode && result.status.active) { + updateMode(result.status.mode, true) + } return true } @@ -78,8 +89,17 @@ export function CaffeineCommand(props: { featureCode?: string; hostOverride?: un useEffect(() => { mounted.current = true - if (props.featureCode === 'caffeine-toggle') void perform(() => toggleCaffeineSession(mode, props.hostOverride)) - else void refresh(true) + void (async () => { + const savedMode = await loadSavedCaffeineMode() + if (!mounted.current) return + modeRef.current = savedMode + setMode(savedMode) + if (props.featureCode === 'caffeine-toggle') { + await perform(() => toggleCaffeineSession(savedMode, props.hostOverride)) + } else { + await refresh(true) + } + })() return () => { mounted.current = false; revision.current += 1 } }, [props.featureCode, props.hostOverride]) @@ -90,35 +110,95 @@ export function CaffeineCommand(props: { featureCode?: string; hostOverride?: un return () => clearInterval(timer) }, [status.active, props.hostOverride]) - const filteredPresets = useMemo(() => { + const filteredPresets = useMemo(() => { const q = searchText.trim().toLowerCase() const presets = getCaffeinePresets() - const matched = presets.filter(p => !q || `${p.title} ${p.subtitle} ${p.minutes}`.toLowerCase().includes(q)) - const customMinutes = parseCustomCaffeineMinutes(searchText) - if (customMinutes !== null && !presets.some(p => p.minutes === customMinutes)) { - return [ - { - id: `caffeine-custom-${customMinutes}`, - minutes: customMinutes, - title: t('customPresetTitle', { minutes: customMinutes }), - subtitle: t('customPresetSubtitle', { minutes: customMinutes }) - }, - ...matched - ] + const matched: CaffeinePreset[] = presets.filter( + p => !q || `${p.title} ${p.subtitle} ${p.minutes}`.toLowerCase().includes(q) + ) + const modeLabel = mode === 'system' ? t('summaryModeSystem') : t('summaryModeDisplay') + const parsed = parseCaffeineInput(searchText) + + const customItems: CaffeinePreset[] = [] + + if (parsed !== null) { + const existsInPresets = presets.some(p => p.minutes === parsed.minutes) + if (parsed.kind === 'until') { + const duration = formatMinutesHuman(parsed.minutes) + customItems.push({ + id: `caffeine-custom-${parsed.minutes}`, + minutes: parsed.minutes, + title: parsed.isNextDay + ? t('customUntilNextDayTitle', { mode: modeLabel, time: parsed.targetTimeText ?? '' }) + : t('customUntilTitle', { mode: modeLabel, time: parsed.targetTimeText ?? '' }), + subtitle: t('customUntilSubtitle', { duration, minutes: parsed.minutes }), + isCustom: true + }) + } else if (!existsInPresets) { + if (parsed.kind === 'minutes') { + customItems.push({ + id: `caffeine-custom-${parsed.minutes}`, + minutes: parsed.minutes, + title: mode === 'system' + ? t('customSystemTitle', { minutes: parsed.minutes }) + : t('customPresetTitle', { minutes: parsed.minutes }), + subtitle: t('customPresetSubtitle', { minutes: parsed.minutes }), + isCustom: true + }) + } else { + const duration = formatMinutesHuman(parsed.minutes) + const until = formatClockTime(Date.now() + parsed.minutes * 60_000) + customItems.push({ + id: `caffeine-custom-${parsed.minutes}`, + minutes: parsed.minutes, + title: t('customDurationTitle', { mode: modeLabel, duration }), + subtitle: t('customDurationSubtitle', { minutes: parsed.minutes, until }), + isCustom: true + }) + } + } } - return matched - }, [searchText, locale]) + + // 开启自定义时长(不在预设档位中)后清空搜索框时,保留当前生效自定义会话置顶,方便直接回车停止或续时 + const activeIsCustom = + status.active && + status.durationMinutes > 0 && + !presets.some(p => p.minutes === status.durationMinutes) && + !customItems.some(p => p.minutes === status.durationMinutes) + if (activeIsCustom && !q) { + const activeModeLabel = status.mode === 'system' ? t('summaryModeSystem') : t('summaryModeDisplay') + const duration = formatMinutesHuman(status.durationMinutes) + const until = status.expiresAtMs !== null ? formatClockTime(status.expiresAtMs) : '' + customItems.unshift({ + id: `caffeine-custom-${status.durationMinutes}`, + minutes: status.durationMinutes, + title: t('activeCustomTitle', { mode: activeModeLabel, duration }), + subtitle: until ? t('activeCustomSubtitle', { until }) : t('activeCustomSubtitleNoUntil'), + isCustom: true + }) + } + + return [...customItems, ...matched] + }, [searchText, locale, mode, status.active, status.durationMinutes, status.mode, status.expiresAtMs]) const remainingText = formatRemainingDuration(status.active, status.durationMinutes, status.remainingMs) // 生效中的那一档在列表里可见时,它的主动作就是“停止防休眠”,顶部不再重复;被搜索过滤掉时才在顶部提供 const activePresetVisible = status.active && filteredPresets.some(p => p.minutes === status.durationMinutes) + const handleExtend15 = () => { + const baseMinutes = status.remainingMs !== null + ? Math.max(1, Math.ceil(status.remainingMs / 60_000)) + : status.durationMinutes + const nextMinutes = Math.min(10080, baseMinutes + 15) + void perform(() => startCaffeineSession(nextMinutes, status.mode, props.hostOverride)) + } + return ( setMode(value as CaffeineMode)}> + updateMode(value as CaffeineMode, true)}> @@ -136,20 +216,30 @@ export function CaffeineCommand(props: { featureCode?: string; hostOverride?: un ] }}> - {filteredPresets.map(preset => ( - perform(() => stopCaffeineSession(props.hostOverride))} /> - // 各档时长由条目标题区分,动作名保持简短,避免在底部操作栏被截断 - : perform(() => startCaffeineSession(preset.minutes, mode, props.hostOverride))} />} - /> - ))} + {filteredPresets.map(preset => { + const isCurrentActive = status.active && status.durationMinutes === preset.minutes + return ( + + perform(() => stopCaffeineSession(props.hostOverride))} /> + {status.durationMinutes > 0 ? ( + + ) : null} + + // 各档时长由条目标题区分,动作名保持简短,避免在底部操作栏被截断 + : perform(() => startCaffeineSession(preset.minutes, mode, props.hostOverride))} />} + /> + ) + })} ) @@ -161,12 +251,16 @@ export async function CaffeineToggleCommand(props?: { mode?: CaffeineMode; hostO if (toggleCommandPending) throw new Error(t('toggleBusyError')) toggleCommandPending = true try { - const result = await toggleCaffeineSession(props?.mode ?? 'display', props?.hostOverride) + const resolvedMode = props?.mode ?? (await loadSavedCaffeineMode()) + const result = await toggleCaffeineSession(resolvedMode, props?.hostOverride) if (!result.ok || !result.status) { const message = resolveErrorMessage(result, t('toastFailed')) await showToast({ style: Toast.Style.Failure, title: t('toastFailed'), message }) throw new Error(message) } + if (result.status.active) { + await saveCaffeineMode(result.status.mode) + } const feedback = result.status.active ? t('hudStarted', { remaining: result.status.remainingText }) : t('hudStopped') diff --git a/extensions/caffeine/src/types.ts b/extensions/caffeine/src/types.ts index e9bdecbe..5c7b70df 100644 --- a/extensions/caffeine/src/types.ts +++ b/extensions/caffeine/src/types.ts @@ -1,10 +1,18 @@ export type CaffeineMode = 'display' | 'system' +export interface ParsedCaffeineInput { + minutes: number + kind: 'minutes' | 'duration' | 'until' + targetTimeText?: string + isNextDay?: boolean +} + export interface CaffeinePreset { id: string minutes: number title: string subtitle: string + isCustom?: boolean } export interface CaffeineStatus { diff --git a/extensions/caffeine/tests/caffeine.test.mjs b/extensions/caffeine/tests/caffeine.test.mjs index f68ba722..cd58dc68 100644 --- a/extensions/caffeine/tests/caffeine.test.mjs +++ b/extensions/caffeine/tests/caffeine.test.mjs @@ -1,7 +1,7 @@ import assert from 'node:assert/strict' import test from 'node:test' import { createHost, mount, tick } from '../../shared/test-harness.mjs' -import { CaffeineCommand, CaffeineToggleCommand, commands, parseCustomCaffeineMinutes, startCaffeineSession } from '../dist/index.js' +import { CaffeineCommand, CaffeineToggleCommand, CAFFEINE_MODE_STORAGE_KEY, commands, parseCaffeineInput, parseCustomCaffeineMinutes, startCaffeineSession } from '../dist/index.js' async function waitUntil(check) { for (let i = 0; i < 40 && !check(); i++) await tick() @@ -247,3 +247,89 @@ test('搜索框输入 5~720 纯数字分钟数动态生成自定义常亮项并 assert.equal(view.items().some(i => i.props.id === 'caffeine-custom-4'), false) } finally { view.unmount() } }) + +test('自然时长与截止时刻解析(1.5h / 2h30m / 90m / 18:30 / 跨日顺延)与界面开启、清空搜索后保留生效会话', async () => { + const baseNow = new Date(2026, 9, 20, 17, 0, 0, 0).getTime() + assert.deepEqual(parseCaffeineInput('45', baseNow), { minutes: 45, kind: 'minutes' }) + assert.deepEqual(parseCaffeineInput('1.5h', baseNow), { minutes: 90, kind: 'duration' }) + assert.deepEqual(parseCaffeineInput('2h30m', baseNow), { minutes: 150, kind: 'duration' }) + assert.deepEqual(parseCaffeineInput('1小时20分', baseNow), { minutes: 80, kind: 'duration' }) + assert.deepEqual(parseCaffeineInput('90m', baseNow), { minutes: 90, kind: 'duration' }) + assert.deepEqual(parseCaffeineInput('18:30', baseNow), { minutes: 90, kind: 'until', targetTimeText: '18:30', isNextDay: false }) + assert.deepEqual(parseCaffeineInput('至 18:30', baseNow), { minutes: 90, kind: 'until', targetTimeText: '18:30', isNextDay: false }) + // 16:00 已过 17:00,自动顺延到次日(23 小时 = 1380 分钟) + assert.deepEqual(parseCaffeineInput('16:00', baseNow), { minutes: 1380, kind: 'until', targetTimeText: '16:00', isNextDay: true }) + // 非法或越界输入拒绝 + assert.equal(parseCaffeineInput('25:00', baseNow), null) + assert.equal(parseCaffeineInput('18:60', baseNow), null) + assert.equal(parseCaffeineInput('20h', baseNow), null) + assert.equal(parseCaffeineInput('0m', baseNow), null) + + let current = state(false) + host.ipc.system_power_session = p => { + if (p.action === 'start') { + const now = Date.now() + current = { + ...state(true), + mode: p.mode, + durationMinutes: p.durationMinutes, + startedAtMs: now, + expiresAtMs: now + p.durationMinutes * 60_000, + remainingMs: p.durationMinutes * 60_000 + } + } + if (p.action === 'stop') current = state(false) + return current + } + const view = await mount(CaffeineCommand) + try { + await waitUntil(() => !view.tree().props.isLoading) + await view.search('1.5h') + const item90 = view.item('caffeine-custom-90') + assert.ok(item90) + assert.match(item90.props.title, /1 小时 30 分钟/) + await view.run(item90, '开启防休眠') + await waitUntil(() => /已开启/.test(view.tree().props.filterBar.summaryText)) + assert.deepEqual(host.ipcCalls.at(-1), ['system_power_session', { action: 'start', durationMinutes: 90, mode: 'display' }]) + + // 清空搜索框后,90 分钟自定义生效会话仍置顶可见,且可直接续时 +15 分钟或回车停止 + await view.search('') + const persisted = view.item('caffeine-custom-90') + assert.ok(persisted, '清空搜索框后当前自定义生效会话应保留在列表顶部') + assert.deepEqual(persisted.props.accessories, [{ tag: '生效中' }]) + assert.ok(view.actions(persisted).some(a => a.props.title === '续时 +15 分钟')) + await view.run(persisted, '停止防休眠') + await tick() + assert.match(view.tree().props.filterBar.summaryText, /未开启/) + } finally { view.unmount() } +}) + +test('LocalStorage 记忆上次选择的模式,重新进入面板与 caffeine-toggle 均沿用该模式', async () => { + let current = state(false) + host.ipc.system_power_session = p => { + if (p.action === 'start') current = { ...state(true), mode: p.mode, durationMinutes: p.durationMinutes } + if (p.action === 'toggle') current = current.active ? state(false) : { ...state(true), mode: p.mode, durationMinutes: 0, expiresAtMs: null, remainingMs: null } + if (p.action === 'stop') current = state(false) + return current + } + const view1 = await mount(CaffeineCommand) + try { + await waitUntil(() => !view1.tree().props.isLoading) + await view1.dropdown('system') + await tick() + assert.equal(host.storage.get(CAFFEINE_MODE_STORAGE_KEY), JSON.stringify('system')) + } finally { view1.unmount() } + + // 无界面切换命令应自动读取记忆的 system 模式 + await CaffeineToggleCommand() + assert.deepEqual(host.ipcCalls.at(-1), ['system_power_session', { action: 'toggle', mode: 'system' }]) + await CaffeineToggleCommand() + + // 重新挂载面板,空闲态下拉框应恢复为 system + const view2 = await mount(CaffeineCommand) + try { + await waitUntil(() => !view2.tree().props.isLoading) + await view2.run(view2.item('caffeine-15'), '开启防休眠') + assert.deepEqual(host.ipcCalls.at(-1), ['system_power_session', { action: 'start', durationMinutes: 15, mode: 'system' }]) + } finally { view2.unmount() } +}) diff --git a/extensions/calendar/package.json b/extensions/calendar/package.json index 0820a50a..940c4e46 100644 --- a/extensions/calendar/package.json +++ b/extensions/calendar/package.json @@ -1,6 +1,6 @@ { "name": "calendar", - "version": "2.0.8", + "version": "2.0.14", "description": "万年历与节气助手:公历农历互查、二十四节气、法定节假日休假安排与传统老黄历宜忌查询", "type": "module", "main": "dist/index.js", diff --git a/extensions/calendar/plugin.json b/extensions/calendar/plugin.json index 98e2c506..ee3bdb1e 100644 --- a/extensions/calendar/plugin.json +++ b/extensions/calendar/plugin.json @@ -1,7 +1,7 @@ { "id": "calendar", "name": "日程日历", - "version": "2.0.13", + "version": "2.0.14", "minAppVersion": "1.1.8.0", "description": "在本机记录和查看日程,用浏览器打开日程里的视频会议链接,可新建、删除日程并导出 ICS 日历文件", "author": "ZTools Team", diff --git a/extensions/calendar/src/i18n.ts b/extensions/calendar/src/i18n.ts index ba1d35fb..b5503ddd 100644 --- a/extensions/calendar/src/i18n.ts +++ b/extensions/calendar/src/i18n.ts @@ -129,8 +129,9 @@ const rawT = createTranslator( metaLocation: "地点", metaMeetingStatus: "会议状态", metaCanJoin: "可一键入会", - searchPlaceholder: "搜索日程标题、地点、日历或备注...", + searchPlaceholder: "搜索日程,或输入“明天 14:00 评审”快速新建...", btnNewEvent: "新建日程", + btnImportIcs: "导入 ICS", btnExportIcs: "导出当前列表 (.ics)", dropdownTooltip: "筛选日程范围", scopeAll: "全部日程 · 今天起", @@ -141,9 +142,48 @@ const rawT = createTranslator( loadErrorTitle: "读取日程失败,按 Enter 重试", loadErrorMd: "# 读取日程失败\n\n{error}\n\n按 `Enter` 重新读取。日程仍保存在本机,没有被删除。", panelManageTitle: "日程管理", - emptyCreateSub: "当前没有日程,按 Enter 新建日程", - emptyCreateMd: "# 暂无日程事件\n\n按 `Enter` 新建日程,可附上视频会议链接。", - daySectionTitle: "{title} · {count} 场" + emptyCreateSub: "当前没有日程,按 Enter 新建日程,或直接拖入 .ics 文件导入", + emptyCreateMd: "# 暂无日程事件\n\n- 按 `Enter` 新建日程,或直接在搜索框输入 `明天 14:00 评审会 1h` 快速创建\n- 点击顶栏「导入 ICS」或直接拖入 `.ics` 日历文件导入外部日程", + daySectionTitle: "{title} · {count} 场", + quickCreateSectionTitle: "自然语言快速新建", + quickCreateTitle: "新建日程:{title}", + quickCreateTag: "快速新建", + quickCreateActionNow: "立即创建日程", + quickCreateActionEdit: "在表单中编辑后创建...", + quickCreateMd: "# 快速新建日程\n\n- **主题**:{title}\n- **时间**:`{when}`\n{recurLine}{urlLine}\n按 `Enter` 立即保存,按 `Ctrl+Enter` 打开完整表单调整细节。", + quickCreateMdRecur: "- **重复**:`{recur}`\n", + quickCreateMdUrl: "- **会议链接**:{url}\n", + actionImportIcsFile: "导入本地 ICS 日历文件...", + actionImportIcsClipboard: "从剪贴板导入 ICS 文本", + openIcsTitle: "选择要导入的 ICS 日历文件", + errImportNotSupported: "当前环境不支持导入本地 ICS 文件", + errOpenDialogFailed: "无法打开文件选择窗口", + errReadFileFailed: "读取 ICS 文件失败", + errNoValidIcsEvents: "未在 ICS 内容中找到有效的日程事件(BEGIN:VEVENT)", + errClipboardEmptyIcs: "剪贴板为空,或未包含有效的 ICS 日历内容", + toastImportedTitle: "已导入 {count} 场日程", + toastImportedPartial: "已导入 {imported} 场,跳过/失败 {failed} 场", + toastImportFailedTitle: "导入 ICS 失败", + fieldRecurrenceLabel: "重复周期", + recurrenceNone: "不重复", + recurrenceDaily: "每天重复", + recurrenceWeekdays: "每个工作日", + recurrenceWeekly: "每周重复", + recurrenceMonthly: "每月重复", + recurrenceYearly: "每年重复", + recurrenceCustom: "重复 ({rule})", + mdRecurrence: "重复周期", + metaRecurrence: "重复", + metaMeetingPlatform: "会议平台", + actionJoinMeetingPlatform: "加入{platform}", + platformTencent: "腾讯会议", + platformFeishu: "飞书会议", + platformDingtalk: "钉钉会议", + platformZoom: "Zoom 会议", + platformTeams: "Teams 会议", + platformGoogle: "Google Meet", + platformWebex: "Webex 会议", + mdJoinHint: "按 `Enter` 直接在浏览器中打开会议链接" }, "en-US": { notInClient: "Requires the ZTools client", @@ -272,8 +312,9 @@ const rawT = createTranslator( metaLocation: "Location", metaMeetingStatus: "Meeting", metaCanJoin: "Ready to Join", - searchPlaceholder: "Search event title, location, calendar, or notes...", + searchPlaceholder: "Search events, or type \"tomorrow 14:00 Review\" to quick-add...", btnNewEvent: "New Event", + btnImportIcs: "Import ICS", btnExportIcs: "Export ICS", dropdownTooltip: "Filter Events", scopeAll: "All Events · From Today", @@ -284,9 +325,48 @@ const rawT = createTranslator( loadErrorTitle: "Failed to load events; press Enter to retry", loadErrorMd: "# Failed to Load Events\n\n{error}\n\nPress `Enter` to retry. Your local events were not deleted.", panelManageTitle: "Calendar Actions", - emptyCreateSub: "No events found; press Enter to create one", - emptyCreateMd: "# No Events\n\nPress `Enter` to create a new event with optional meeting link.", - daySectionTitle: "{title} · {count}" + emptyCreateSub: "No events found; press Enter to create or drop an .ics file to import", + emptyCreateMd: "# No Events\n\n- Press `Enter` to create an event, or type `tomorrow 14:00 Review 1h` in search to quick-add\n- Click **Import ICS** above or drop an `.ics` file to import schedules", + daySectionTitle: "{title} · {count}", + quickCreateSectionTitle: "Quick Create", + quickCreateTitle: "Create Event: {title}", + quickCreateTag: "Quick Add", + quickCreateActionNow: "Create Event Now", + quickCreateActionEdit: "Edit in Form Before Saving...", + quickCreateMd: "# Quick Create Event\n\n- **Title**: {title}\n- **Time**: `{when}`\n{recurLine}{urlLine}\nPress `Enter` to save immediately, or `Ctrl+Enter` to adjust details in the form.", + quickCreateMdRecur: "- **Recurrence**: `{recur}`\n", + quickCreateMdUrl: "- **Meeting URL**: {url}\n", + actionImportIcsFile: "Import Local ICS File...", + actionImportIcsClipboard: "Import ICS from Clipboard", + openIcsTitle: "Select ICS Calendar File to Import", + errImportNotSupported: "Importing local ICS files is not supported in this environment", + errOpenDialogFailed: "Unable to open file picker dialog", + errReadFileFailed: "Failed to read ICS file", + errNoValidIcsEvents: "No valid calendar events (BEGIN:VEVENT) found in ICS content", + errClipboardEmptyIcs: "Clipboard is empty or does not contain valid ICS content", + toastImportedTitle: "Imported {count} [[count:event|events]]", + toastImportedPartial: "Imported {imported}, skipped/failed {failed}", + toastImportFailedTitle: "Failed to Import ICS", + fieldRecurrenceLabel: "Recurrence", + recurrenceNone: "Does not repeat", + recurrenceDaily: "Daily", + recurrenceWeekdays: "Weekdays", + recurrenceWeekly: "Weekly", + recurrenceMonthly: "Monthly", + recurrenceYearly: "Yearly", + recurrenceCustom: "Repeats ({rule})", + mdRecurrence: "Recurrence", + metaRecurrence: "Repeats", + metaMeetingPlatform: "Platform", + actionJoinMeetingPlatform: "Join {platform}", + platformTencent: "Tencent Meeting", + platformFeishu: "Feishu Meeting", + platformDingtalk: "DingTalk Meeting", + platformZoom: "Zoom", + platformTeams: "Microsoft Teams", + platformGoogle: "Google Meet", + platformWebex: "Webex", + mdJoinHint: "Press `Enter` to open the meeting link in your browser" } } ) diff --git a/extensions/calendar/src/ics-parser.ts b/extensions/calendar/src/ics-parser.ts new file mode 100644 index 00000000..4fe109f3 --- /dev/null +++ b/extensions/calendar/src/ics-parser.ts @@ -0,0 +1,194 @@ +import { extractKnownMeetingUrl } from "./quick-parse.js"; + +export interface ParsedIcsEvent { + readonly title: string; + readonly date: string; + readonly startTime: string; + readonly endTime: string; + readonly isAllDay: boolean; + readonly location: string; + readonly notes: string; + readonly conferenceUrl?: string; + readonly calendarName: string; + readonly rrule?: string; +} + +function pad2(n: number): string { + return String(n).padStart(2, "0"); +} + +function formatDateLocal(d: Date): string { + return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`; +} + +function formatClockLocal(d: Date): string { + return `${pad2(d.getHours())}:${pad2(d.getMinutes())}`; +} + +function unescapeIcsText(value: string): string { + return value + .replace(/\\n/gi, "\n") + .replace(/\\,/g, ",") + .replace(/\\;/g, ";") + .replace(/\\\\/g, "\\"); +} + +/** 展开 RFC 5545 折行(CRLF/LF 后紧跟空格或制表符) */ +function unfoldIcsLines(icsText: string): string[] { + const unfolded = (icsText || "").replace(/\r\n[ \t]/g, "").replace(/\n[ \t]/g, ""); + return unfolded.split(/\r?\n/); +} + +/** 解析 DTSTART / DTEND(支持 VALUE=DATE 全天、UTC Z、本地/TZID 时刻) */ +function parseIcsDateValue(raw: string, params: string): { ms: number; isAllDay: boolean } | null { + const val = raw.trim(); + const isDateOnly = /VALUE=DATE\b/i.test(params) || /^\d{8}$/.test(val); + if (isDateOnly) { + const m = val.match(/^(\d{4})(\d{2})(\d{2})$/); + if (!m) return null; + const y = Number(m[1]); + const mo = Number(m[2]); + const d = Number(m[3]); + const dt = new Date(y, mo - 1, d, 0, 0, 0, 0); + if (dt.getFullYear() !== y || dt.getMonth() !== mo - 1 || dt.getDate() !== d) return null; + return { ms: dt.getTime(), isAllDay: true }; + } + const m = val.match(/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})(Z)?$/i); + if (!m) return null; + const y = Number(m[1]); + const mo = Number(m[2]); + const d = Number(m[3]); + const h = Number(m[4]); + const mi = Number(m[5]); + const s = Number(m[6]); + const isUtc = Boolean(m[7]); + const ms = isUtc ? Date.UTC(y, mo - 1, d, h, mi, s) : new Date(y, mo - 1, d, h, mi, s).getTime(); + if (!Number.isFinite(ms)) return null; + return { ms, isAllDay: false }; +} + +/** 解析 RFC 5545 DURATION(如 PT1H30M / P1D)为毫秒 */ +function parseIcsDurationMs(raw: string): number | null { + const m = raw.trim().match(/^P(?:(\d+)W)?(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/i); + if (!m) return null; + const weeks = Number(m[1] || 0); + const days = Number(m[2] || 0); + const hours = Number(m[3] || 0); + const mins = Number(m[4] || 0); + const secs = Number(m[5] || 0); + const total = (((weeks * 7 + days) * 24 + hours) * 60 + mins) * 60 + secs; + return total > 0 ? total * 1000 : null; +} + +/** + * 解析标准 RFC 5545 `.ics` 文本中的全部 VEVENT。 + * 忽略缺少有效 SUMMARY 或 DTSTART 的损坏条目。 + */ +export function parseIcsContent(icsText: string): ParsedIcsEvent[] { + if (!icsText || !icsText.includes("BEGIN:VEVENT")) return []; + const lines = unfoldIcsLines(icsText); + const events: ParsedIcsEvent[] = []; + + let calendarTitle = "ICS"; + let inEvent = false; + let fields: Record = {}; + + for (const rawLine of lines) { + const line = rawLine.trim(); + if (!line) continue; + const upper = line.toUpperCase(); + if (upper === "BEGIN:VEVENT") { + inEvent = true; + fields = {}; + continue; + } + if (upper === "END:VEVENT") { + if (inEvent) { + const parsed = buildParsedEvent(fields, calendarTitle); + if (parsed) events.push(parsed); + } + inEvent = false; + fields = {}; + continue; + } + + const colonIdx = line.indexOf(":"); + if (colonIdx <= 0) continue; + const left = line.slice(0, colonIdx); + const value = line.slice(colonIdx + 1); + const semiIdx = left.indexOf(";"); + const key = (semiIdx >= 0 ? left.slice(0, semiIdx) : left).trim().toUpperCase(); + const params = semiIdx >= 0 ? left.slice(semiIdx + 1) : ""; + + if (!inEvent) { + if (key === "X-WR-CALNAME" && value.trim()) { + calendarTitle = unescapeIcsText(value.trim()).slice(0, 48); + } + continue; + } + + if (!(key in fields)) { + fields[key] = { value, params }; + } + } + + return events; +} + +function buildParsedEvent( + fields: Record, + defaultCalendarName: string +): ParsedIcsEvent | null { + const title = fields.SUMMARY ? unescapeIcsText(fields.SUMMARY.value).trim() : ""; + if (!title || !fields.DTSTART) return null; + + const start = parseIcsDateValue(fields.DTSTART.value, fields.DTSTART.params); + if (!start) return null; + + const isAllDay = start.isAllDay; + let endMs: number; + if (fields.DTEND) { + const end = parseIcsDateValue(fields.DTEND.value, fields.DTEND.params); + endMs = end && end.ms > start.ms ? end.ms : start.ms + 3600_000; + } else if (fields.DURATION) { + const dur = parseIcsDurationMs(fields.DURATION.value); + endMs = start.ms + (dur ?? 3600_000); + } else { + endMs = start.ms + 3600_000; + } + + const startObj = new Date(start.ms); + const endObj = new Date(endMs); + const startDate = formatDateLocal(startObj); + const endDate = formatDateLocal(endObj); + + const location = fields.LOCATION ? unescapeIcsText(fields.LOCATION.value).trim() : ""; + const notes = fields.DESCRIPTION ? unescapeIcsText(fields.DESCRIPTION.value).trim() : ""; + const rawUrl = fields.URL ? fields.URL.value.trim() : ""; + const conferenceUrl = + (/^https?:\/\//i.test(rawUrl) ? rawUrl : undefined) || + extractKnownMeetingUrl(location) || + extractKnownMeetingUrl(notes); + const rrule = fields.RRULE ? fields.RRULE.value.trim().toUpperCase() : undefined; + const calendarName = + (fields.CATEGORIES ? unescapeIcsText(fields.CATEGORIES.value).split(",")[0].trim() : "") || + defaultCalendarName || + "ICS"; + + return { + title, + date: startDate, + startTime: formatClockLocal(startObj), + endTime: isAllDay + ? "23:59" + : endDate === startDate + ? formatClockLocal(endObj) + : `${endDate} ${formatClockLocal(endObj)}`, + isAllDay, + location, + notes, + ...(conferenceUrl ? { conferenceUrl } : {}), + calendarName, + ...(rrule ? { rrule } : {}) + }; +} diff --git a/extensions/calendar/src/index.tsx b/extensions/calendar/src/index.tsx index 42dfce70..af9f3e84 100644 --- a/extensions/calendar/src/index.tsx +++ b/extensions/calendar/src/index.tsx @@ -27,6 +27,31 @@ import { useState, useEffect, useMemo, useRef } from "@ztools/declarative-ui"; import { callHostTransport, isRealElectronHost } from "./native-ipc.js"; import { t } from "./i18n.js"; import { resolveErrorMessage } from './error-i18n.js' +import { + detectMeetingPlatform, + embedRecurrenceInNotes, + extractKnownMeetingUrl, + extractRecurrenceFromNotes, + formatRecurrenceLabel, + getNextHalfHourSlot, + parseQuickEventInput, + recurrencePresetToRrule, + rruleToRecurrencePreset, + type QuickEventDraft, + type RecurrencePreset +} from "./quick-parse.js"; +import { parseIcsContent, type ParsedIcsEvent } from "./ics-parser.js"; + +export { + detectMeetingPlatform, + formatRecurrenceLabel, + getNextHalfHourSlot, + parseQuickEventInput, + parseIcsContent, + type QuickEventDraft, + type RecurrencePreset, + type ParsedIcsEvent +}; export type CalendarFilterScope = "all" | "upcoming" | "meetings" | "today" | "past"; @@ -61,6 +86,8 @@ export interface CalendarEventItem { readonly notes: string; readonly attendees: readonly string[]; readonly isAllDay?: boolean; + /** RFC 5545 重复规则(如 FREQ=WEEKLY) */ + readonly rrule?: string; } export function getNotInClientMessage(): string { @@ -368,6 +395,7 @@ export function buildCalendarIcsContent(events: readonly CalendarEventItem[], no if (ev.location) lines.push(`LOCATION:${escapeIcsText(ev.location)}`); if (ev.notes) lines.push(`DESCRIPTION:${escapeIcsText(ev.notes)}`); if (ev.conferenceUrl) lines.push(`URL:${ev.conferenceUrl}`); + if (ev.rrule) lines.push(`RRULE:${ev.rrule}`); lines.push("END:VEVENT"); } lines.push("END:VCALENDAR"); @@ -412,8 +440,16 @@ function mapHostEvent(input: unknown, idx: number): CalendarEventItem { const endAt = toTimestamp(e.endTime ?? e.end); const rawStart = typeof (e.startTime ?? e.start) === "string" ? String(e.startTime ?? e.start).trim() : ""; const rawEnd = typeof (e.endTime ?? e.end) === "string" ? String(e.endTime ?? e.end).trim() : ""; + const location = String(e.location || ""); + const rawNotes = String(e.notes || e.description || ""); + const explicitRrule = typeof (e.rrule ?? e.recurrence ?? e.repeatRule) === "string" + ? String(e.rrule ?? e.recurrence ?? e.repeatRule) + : undefined; + const { rrule, cleanNotes } = extractRecurrenceFromNotes(rawNotes, explicitRrule); const rawUrl = e.conferenceUrl || e.meetingUrl ? String(e.conferenceUrl || e.meetingUrl).trim() : ""; const link = normalizeConferenceUrl(rawUrl); + const inferredUrl = !rawUrl ? (extractKnownMeetingUrl(location) || extractKnownMeetingUrl(cleanNotes)) : undefined; + const conferenceUrl = link.url || inferredUrl; return { id: String(e.id || `evt-${idx}`), title: String(e.title || e.summary || "Untitled Event"), @@ -421,13 +457,14 @@ function mapHostEvent(input: unknown, idx: number): CalendarEventItem { endTime: endAt !== undefined ? formatClock(endAt) : rawEnd || "10:00", ...(startAt !== undefined ? { startAt } : {}), ...(endAt !== undefined ? { endAt } : {}), - location: String(e.location || ""), - conferenceUrl: link.url, + location, + conferenceUrl, ...(rawUrl && !link.url ? { invalidConferenceUrl: rawUrl } : {}), calendarName: String(e.calendarName || e.calendar || "Calendar"), - notes: String(e.notes || e.description || ""), + notes: cleanNotes, attendees: Array.isArray(attendees) ? attendees.map(String) : [], - isAllDay: Boolean(e.isAllDay ?? e.allDay) + isAllDay: Boolean(e.isAllDay ?? e.allDay), + ...(rrule ? { rrule } : {}) }; } @@ -505,6 +542,7 @@ export interface CalendarEventMutationInput { conferenceUrl?: string; calendarName?: string; notes?: string; + rrule?: string; } function isUnsupportedHostMethod(res: { errorCode?: string; error?: string }): boolean { @@ -541,6 +579,9 @@ export async function createCalendarEvent( throw Object.assign(new Error(`INVALID_CONFERENCE_URL: ${link.error}`), { fieldErrors: { conferenceUrl: link.error } }); } + const persistedNotes = embedRecurrenceInNotes(input.notes || "", input.rrule); + const { rrule: normalizedRrule, cleanNotes } = extractRecurrenceFromNotes(persistedNotes, input.rrule); + const newEvent: CalendarEventItem = { id: `evt-${Date.now()}`, title: cleanTitle, @@ -551,9 +592,10 @@ export async function createCalendarEvent( location: (input.location || "").trim(), conferenceUrl: link.url, calendarName: (input.calendarName || "Work").trim(), - notes: (input.notes || "").trim(), + notes: cleanNotes, attendees: [], - isAllDay + isAllDay, + ...(normalizedRrule ? { rrule: normalizedRrule } : {}) }; if (hostOverride || isRealElectronHost()) { @@ -564,7 +606,7 @@ export async function createCalendarEvent( endTime: times.endAt, location: newEvent.location, calendarName: newEvent.calendarName, - notes: newEvent.notes, + notes: persistedNotes, isAllDay, ...(link.url ? { conferenceUrl: link.url } : {}) }; @@ -585,7 +627,8 @@ export async function createCalendarEvent( isAllDay: res.data.isAllDay !== undefined || res.data.allDay !== undefined ? Boolean(res.data.isAllDay ?? res.data.allDay) - : isAllDay + : isAllDay, + ...(saved.rrule ? { rrule: saved.rrule } : {}) }; memoryCalendarEvents = [merged, ...memoryCalendarEvents]; return merged; @@ -632,6 +675,7 @@ export async function updateCalendarEvent( throw new Error(`NOT_IN_CLIENT: ${t("notInClient")}`); } + const persistedNotes = embedRecurrenceInNotes(input.notes || "", input.rrule); const payload: Record = { id: cleanId, title: cleanTitle, @@ -639,7 +683,7 @@ export async function updateCalendarEvent( endTime: times.endAt, location: (input.location || "").trim(), calendarName: (input.calendarName || "Work").trim(), - notes: (input.notes || "").trim(), + notes: persistedNotes, isAllDay, ...(link.url ? { conferenceUrl: link.url } : {}) }; @@ -735,6 +779,101 @@ export async function exportCalendarIcsToFile( return { status: "saved", filePath, count: countIcsEvents(ics) }; } +export type IcsImportResult = + | { status: "imported"; imported: number; failed: number; events: CalendarEventItem[]; filePath?: string } + | { status: "canceled" }; + +/** 解析 ICS 文本并逐条写入本机日程库;没有任何有效 VEVENT 时抛错 */ +export async function importCalendarIcsContent( + icsText: string, + hostOverride?: unknown +): Promise> { + const parsedEvents = parseIcsContent(icsText); + if (parsedEvents.length === 0) { + throw new Error(`EMPTY_ICS_EVENTS: ${t("errNoValidIcsEvents")}`); + } + const importedEvents: CalendarEventItem[] = []; + let failed = 0; + let lastError: unknown = null; + for (const ev of parsedEvents) { + try { + const created = await createCalendarEvent( + { + title: ev.title, + date: ev.date, + startTime: ev.startTime, + endTime: ev.endTime, + isAllDay: ev.isAllDay, + location: ev.location, + conferenceUrl: ev.conferenceUrl, + calendarName: ev.calendarName, + notes: ev.notes, + rrule: ev.rrule + }, + hostOverride + ); + importedEvents.push(created); + } catch (err) { + failed += 1; + lastError = err; + } + } + if (importedEvents.length === 0 && lastError) { + throw lastError instanceof Error ? lastError : new Error(String(lastError)); + } + return { status: "imported", imported: importedEvents.length, failed, events: importedEvents }; +} + +/** 读取已授权的本地 `.ics` 文件并导入日程 */ +export async function importCalendarIcsFromPath( + filePath: string, + hostOverride?: unknown +): Promise> { + if (!hostOverride && !isRealElectronHost()) { + throw new Error(`NOT_SUPPORTED: ${t("errImportNotSupported")}`); + } + const readRes = await callHostTransport( + "filesystem_read_file", + { path: filePath, encoding: "utf8" }, + hostOverride + ); + if (!readRes.ok) { + throw new Error(`READ_FILE_FAILED: ${resolveErrorMessage(readRes, t("errReadFileFailed"))}`); + } + const content = + typeof readRes.data === "string" + ? readRes.data + : typeof hostField(readRes.data, "content") === "string" + ? String(hostField(readRes.data, "content")) + : ""; + const result = await importCalendarIcsContent(content, hostOverride); + return { ...result, filePath }; +} + +/** 弹出系统文件选择框选择 `.ics` 日历文件并导入本机日程 */ +export async function importCalendarIcsFromFile(hostOverride?: unknown): Promise { + if (!hostOverride && !isRealElectronHost()) { + throw new Error(`NOT_SUPPORTED: ${t("errImportNotSupported")}`); + } + const picked = await callHostTransport<{ filePath?: unknown; filePaths?: unknown; canceled?: unknown }>( + "window_show_open_dialog", + { title: t("openIcsTitle"), filters: t("saveIcsFilter"), properties: ["openFile"] }, + hostOverride + ); + if (!picked.ok) { + throw new Error(`OPEN_DIALOG_FAILED: ${resolveErrorMessage(picked, t("errOpenDialogFailed"))}`); + } + const pickedList = Array.isArray(picked.data?.filePaths) ? picked.data.filePaths : []; + const filePath = + typeof picked.data?.filePath === "string" && picked.data.filePath + ? picked.data.filePath + : typeof pickedList[0] === "string" + ? pickedList[0] + : ""; + if (picked.data?.canceled || !filePath) return { status: "canceled" }; + return importCalendarIcsFromPath(filePath, hostOverride); +} + // --------------------------------------------------------------------------- // 界面 // --------------------------------------------------------------------------- @@ -754,27 +893,43 @@ function initialEndTimeForEvent(evt?: CalendarEventItem): string { export function CreateCalendarEventForm({ initialEvent, + initialDraft, onCreated, onSaved }: { initialEvent?: CalendarEventItem; + initialDraft?: QuickEventDraft; onCreated?: (evt: CalendarEventItem) => void; onSaved?: (evt: CalendarEventItem) => void; }) { useLocale(); const isEdit = Boolean(initialEvent); - const [title, setTitle] = useState(initialEvent?.title ?? ""); + const defaultSlot = useMemo(() => getNextHalfHourSlot(), []); + const [title, setTitle] = useState(initialEvent?.title ?? initialDraft?.title ?? ""); const [date, setDate] = useState(() => - typeof initialEvent?.startAt === "number" ? formatDateKey(initialEvent.startAt) : formatDateKey(Date.now()) + typeof initialEvent?.startAt === "number" + ? formatDateKey(initialEvent.startAt) + : initialDraft?.date ?? defaultSlot.date ); - const [isAllDay, setIsAllDay] = useState(Boolean(initialEvent?.isAllDay)); + const [isAllDay, setIsAllDay] = useState(Boolean(initialEvent?.isAllDay ?? initialDraft?.isAllDay)); const [startTime, setStartTime] = useState( - initialEvent ? (typeof initialEvent.startAt === "number" ? formatClock(initialEvent.startAt) : initialEvent.startTime || "15:00") : "15:00" + initialEvent + ? typeof initialEvent.startAt === "number" + ? formatClock(initialEvent.startAt) + : initialEvent.startTime || defaultSlot.startTime + : initialDraft?.startTime ?? defaultSlot.startTime + ); + const [endTime, setEndTime] = useState(() => + initialEvent ? initialEndTimeForEvent(initialEvent) : initialDraft?.endTime ?? defaultSlot.endTime + ); + const [recurrence, setRecurrence] = useState(() => + rruleToRecurrencePreset(initialEvent?.rrule ?? initialDraft?.rrule) ); - const [endTime, setEndTime] = useState(() => initialEndTimeForEvent(initialEvent)); const [calendarName, setCalendarName] = useState(initialEvent?.calendarName || "Work"); const [location, setLocation] = useState(initialEvent?.location ?? ""); - const [conferenceUrl, setConferenceUrl] = useState(initialEvent?.conferenceUrl ?? initialEvent?.invalidConferenceUrl ?? ""); + const [conferenceUrl, setConferenceUrl] = useState( + initialEvent?.conferenceUrl ?? initialEvent?.invalidConferenceUrl ?? initialDraft?.conferenceUrl ?? "" + ); const [notes, setNotes] = useState(initialEvent?.notes ?? ""); const [errors, setErrors] = useState({}); const [saving, setSaving] = useState(false); @@ -806,6 +961,7 @@ export function CreateCalendarEventForm({ } savingRef.current = true; setSaving(true); + const rrule = recurrencePresetToRrule(recurrence); try { const saved = initialEvent ? await updateCalendarEvent(initialEvent.id, { @@ -817,7 +973,8 @@ export function CreateCalendarEventForm({ calendarName, location, conferenceUrl, - notes + notes, + rrule }) : await createCalendarEvent({ title, @@ -828,7 +985,8 @@ export function CreateCalendarEventForm({ calendarName, location, conferenceUrl, - notes + notes, + rrule }); onSaved?.(saved); onCreated?.(saved); @@ -920,6 +1078,19 @@ export function CreateCalendarEventForm({ }} /> )} + setRecurrence(v as RecurrencePreset)} + > + + + + + + + @@ -1101,6 +1272,77 @@ export function CalendarCommand() { } }; + const notifyImportResult = async (result: Extract) => { + reload(); + if (result.failed > 0) { + await showToast( + Toast.Style.Success, + t("toastImportedTitle", { count: result.imported }), + t("toastImportedPartial", { imported: result.imported, failed: result.failed }) + ); + } else { + await showToast( + Toast.Style.Success, + t("toastImportedTitle", { count: result.imported }), + result.filePath || undefined + ); + } + }; + + const handleImportIcsFile = async () => { + try { + const result = await importCalendarIcsFromFile(); + if (result.status === "canceled") return; + await notifyImportResult(result); + } catch (err) { + await showToast(Toast.Style.Failure, t("toastImportFailedTitle"), readableError(err)); + } + }; + + const handleImportIcsPath = async (filePath: string) => { + try { + const result = await importCalendarIcsFromPath(filePath); + await notifyImportResult(result); + } catch (err) { + await showToast(Toast.Style.Failure, t("toastImportFailedTitle"), readableError(err)); + } + }; + + const handleImportIcsClipboard = async () => { + try { + const text = await Clipboard.readText(); + if (!text || !text.includes("BEGIN:VEVENT")) { + await showToast(Toast.Style.Failure, t("toastImportFailedTitle"), t("errClipboardEmptyIcs")); + return; + } + const result = await importCalendarIcsContent(text); + await notifyImportResult(result); + } catch (err) { + await showToast(Toast.Style.Failure, t("toastImportFailedTitle"), readableError(err)); + } + }; + + const quickDraft = useMemo(() => parseQuickEventInput(searchText), [searchText]); + + const handleQuickCreate = async (draft: QuickEventDraft) => { + try { + const created = await createCalendarEvent({ + title: draft.title, + date: draft.date, + startTime: draft.startTime, + endTime: draft.endTime, + isAllDay: draft.isAllDay, + conferenceUrl: draft.conferenceUrl, + rrule: draft.rrule + }); + setSearchText(""); + reload(); + await showToast(Toast.Style.Success, t("toastCreatedTitle", { title: created.title }), formatEventWhen(created)); + } catch (err) { + await showToast(Toast.Style.Failure, t("toastCreateFailed"), readableError(err)); + } + }; + const copySummary = async (evt: CalendarEventItem) => { const summary = buildEventSummary(evt); try { @@ -1170,6 +1412,17 @@ export function CalendarCommand() { shortcut={{ modifiers: ["ctrl"], key: "n" }} target={createForm} /> + + { + const platform = detectMeetingPlatform(evt.conferenceUrl); + const joinTitle = platform ? t("actionJoinMeetingPlatform", { platform }) : t("actionJoinMeeting"); const itemActions = [ evt.conferenceUrl ? ( - + ) : null, evt.conferenceUrl ? ( @@ -1233,16 +1488,19 @@ export function CalendarCommand() { const range = formatEventRange(evt); const when = formatEventWhen(evt); const ended = isEventEnded(evt); + const recurLabel = formatRecurrenceLabel(evt.rrule); + const platform = detectMeetingPlatform(evt.conferenceUrl); return ( **${t("mdTime")}**: \`${when}\`${ended ? t("mdEndedSuffix") : ""}  |  **${t("mdCalendar")}**: \`${evt.calendarName}\``, `---`, + recurLabel ? `- **${t("mdRecurrence")}**: \`${recurLabel}\`` : "", `- **${t("mdLocation")}**: ${evt.location || t("mdUnspecified")}`, - evt.conferenceUrl ? `- **${t("mdOnlineMeeting")}**: [${evt.conferenceUrl}](${evt.conferenceUrl})` : "", + evt.conferenceUrl + ? `- **${t("mdOnlineMeeting")}**: [${platform ? `${platform} · ` : ""}${evt.conferenceUrl}](${evt.conferenceUrl})\n\n ${t("mdJoinHint")}` + : "", evt.invalidConferenceUrl ? `- **${t("mdInvalidMeetingUrl")}**: \`${evt.invalidConferenceUrl.replace(/`/g, "'")}\`` : "", @@ -1266,8 +1527,14 @@ export function CalendarCommand() { metadata={ + {recurLabel && ( + + )} + {platform && ( + + )} {evt.conferenceUrl && ( @@ -1282,13 +1549,67 @@ export function CalendarCommand() { ); }; + const renderQuickCreateSection = () => { + if (!quickDraft) return null; + const whenText = quickDraft.isAllDay + ? `${quickDraft.date} ${t("allDay")}` + : `${quickDraft.date} ${quickDraft.startTime} - ${quickDraft.endTime}`; + const recurLabel = formatRecurrenceLabel(quickDraft.rrule); + return ( + + + } + actions={ + + handleQuickCreate(quickDraft)} + /> + } + /> + {globalActions} + + } + /> + + ); + }; + return ( { + const first = files[0]; + if (first) void handleImportIcsPath(first); + }} filterBar={{ summaryText, actions: [ @@ -1301,13 +1622,13 @@ export function CalendarCommand() { onAction: () => push(createForm) }, { - id: "export-all-ics", - label: t("btnExportIcs"), - title: t("btnExportIcs"), - icon: Icon.Download, + id: "import-ics", + label: t("btnImportIcs"), + title: t("actionImportIcsFile"), + icon: Icon.Upload, style: "secondary", - onAction: () => handleExportFile(displayedEvents) - }, + onAction: handleImportIcsFile + } ] }} searchBarAccessory={ @@ -1319,53 +1640,59 @@ export function CalendarCommand() { } > + {renderQuickCreateSection()} {displayedEvents.length === 0 ? ( - - {loadError ? ( - - } - actions={ - - - + {loadError ? ( + + } + actions={ + + + + + + } + /> + ) : ( + - - } - /> - ) : ( - - } - actions={ - - - - } - /> - )} - + } + actions={ + + + + + + } + /> + )} + + ) ) : ( sections.map((section) => ( diff --git a/extensions/calendar/src/quick-parse.ts b/extensions/calendar/src/quick-parse.ts new file mode 100644 index 00000000..6204abc0 --- /dev/null +++ b/extensions/calendar/src/quick-parse.ts @@ -0,0 +1,440 @@ +import { t } from "./i18n.js"; + +export type RecurrencePreset = "none" | "DAILY" | "WEEKDAYS" | "WEEKLY" | "MONTHLY" | "YEARLY"; + +export interface QuickEventDraft { + readonly title: string; + readonly date: string; + readonly startTime: string; + readonly endTime: string; + readonly isAllDay: boolean; + readonly conferenceUrl?: string; + readonly rrule?: string; +} + +const DAY_MS = 24 * 3600 * 1000; + +function pad2(n: number): string { + return String(n).padStart(2, "0"); +} + +function formatDateLocal(d: Date): string { + return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`; +} + +function formatClockLocal(d: Date): string { + return `${pad2(d.getHours())}:${pad2(d.getMinutes())}`; +} + +/** + * 计算新建表单默认起止时间:当前时间的下一个半点起,持续 1 小时。 + */ +export function getNextHalfHourSlot(now = Date.now()): { date: string; startTime: string; endTime: string } { + const base = new Date(now); + base.setSeconds(0, 0); + const mins = base.getMinutes(); + const addMins = mins < 30 ? 30 - mins : 60 - mins; + const start = new Date(base.getTime() + addMins * 60_000); + const end = new Date(start.getTime() + 60 * 60_000); + const startDate = formatDateLocal(start); + const endDate = formatDateLocal(end); + return { + date: startDate, + startTime: formatClockLocal(start), + endTime: startDate === endDate ? formatClockLocal(end) : `${endDate} ${formatClockLocal(end)}` + }; +} + +// --------------------------------------------------------------------------- +// 会议平台识别与提取 +// --------------------------------------------------------------------------- + +const MEETING_PLATFORMS: ReadonlyArray<{ + readonly domains: readonly string[]; + readonly labelKey: "platformTencent" | "platformFeishu" | "platformDingtalk" | "platformZoom" | "platformTeams" | "platformGoogle" | "platformWebex"; + readonly path?: RegExp; +}> = [ + { domains: ["meeting.tencent.com", "voovmeeting.com"], labelKey: "platformTencent" }, + { domains: ["vc.feishu.cn", "meetings.feishu.cn", "vc.larksuite.com"], labelKey: "platformFeishu" }, + { domains: ["meeting.dingtalk.com"], labelKey: "platformDingtalk" }, + { domains: ["zoom.us", "zoom.com", "zoom.com.cn"], labelKey: "platformZoom", path: /^\/(?:j|my|s|w|wc)\/[^/]/i }, + { domains: ["teams.microsoft.com", "teams.live.com"], labelKey: "platformTeams" }, + { domains: ["meet.google.com"], labelKey: "platformGoogle", path: /^\/[a-z]{3}-[a-z]{4}-[a-z]{3}\/?$/i }, + { domains: ["webex.com"], labelKey: "platformWebex" } +]; + +const URL_IN_TEXT_RE = /https?:\/\/[^\s"'<>()[\]{}()【】「」『』《》,。;:!?、]+/gi; +const TRAILING_PUNCT_RE = /[.,;:!?*_~`'"]+$/; + +export function detectMeetingPlatform(rawUrl?: string): string | null { + if (!rawUrl) return null; + let parsed: URL; + try { + parsed = new URL(rawUrl); + } catch { + return null; + } + if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return null; + const host = parsed.hostname.toLowerCase(); + for (const p of MEETING_PLATFORMS) { + if (!p.domains.some((d) => host === d || host.endsWith(`.${d}`))) continue; + if (p.path ? !p.path.test(parsed.pathname) : parsed.pathname.length <= 1) continue; + return t(p.labelKey); + } + return null; +} + +/** 从文本(备注/地点)中提取已知主流视频会议链接(忽略普通网页链接) */ +export function extractKnownMeetingUrl(text?: string): string | undefined { + if (!text) return undefined; + const matches = text.match(URL_IN_TEXT_RE); + if (!matches) return undefined; + for (const raw of matches) { + const clean = raw.replace(TRAILING_PUNCT_RE, ""); + if (detectMeetingPlatform(clean)) return clean; + } + return undefined; +} + +// --------------------------------------------------------------------------- +// 重复日程 RRULE 编解码与展示 +// --------------------------------------------------------------------------- + +const NOTES_RRULE_RE = /(?:^|\n)\[RRULE:([A-Z0-9;=,-]+)\]\s*$/i; + +export function recurrencePresetToRrule(preset: RecurrencePreset): string | undefined { + switch (preset) { + case "DAILY": + return "FREQ=DAILY"; + case "WEEKDAYS": + return "FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR"; + case "WEEKLY": + return "FREQ=WEEKLY"; + case "MONTHLY": + return "FREQ=MONTHLY"; + case "YEARLY": + return "FREQ=YEARLY"; + default: + return undefined; + } +} + +export function rruleToRecurrencePreset(rrule?: string): RecurrencePreset { + const upper = (rrule || "").trim().toUpperCase().replace(/^RRULE:/, ""); + if (!upper) return "none"; + if (/FREQ=WEEKLY/.test(upper) && /BYDAY=MO,TU,WE,TH,FR/.test(upper)) return "WEEKDAYS"; + if (/FREQ=DAILY/.test(upper)) return "DAILY"; + if (/FREQ=WEEKLY/.test(upper)) return "WEEKLY"; + if (/FREQ=MONTHLY/.test(upper)) return "MONTHLY"; + if (/FREQ=YEARLY/.test(upper)) return "YEARLY"; + return "none"; +} + +export function extractRecurrenceFromNotes( + rawNotes: string, + explicitRrule?: string +): { rrule?: string; cleanNotes: string } { + const notes = rawNotes || ""; + const match = notes.match(NOTES_RRULE_RE); + const embedded = match ? match[1].trim().toUpperCase() : undefined; + const cleanNotes = match ? notes.slice(0, match.index).trimEnd() : notes; + const rrule = (explicitRrule || "").trim().replace(/^RRULE:/i, "").toUpperCase() || embedded; + return { ...(rrule ? { rrule } : {}), cleanNotes }; +} + +export function embedRecurrenceInNotes(notes: string, rrule?: string): string { + const clean = extractRecurrenceFromNotes(notes).cleanNotes.trim(); + const normalizedRule = (rrule || "").trim().replace(/^RRULE:/i, "").toUpperCase(); + if (!normalizedRule) return clean; + return clean ? `${clean}\n[RRULE:${normalizedRule}]` : `[RRULE:${normalizedRule}]`; +} + +export function formatRecurrenceLabel(rrule?: string): string { + const upper = (rrule || "").trim().toUpperCase().replace(/^RRULE:/, ""); + if (!upper) return ""; + const preset = rruleToRecurrencePreset(upper); + if (preset === "DAILY") return t("recurrenceDaily"); + if (preset === "WEEKDAYS") return t("recurrenceWeekdays"); + if (preset === "WEEKLY") return t("recurrenceWeekly"); + if (preset === "MONTHLY") return t("recurrenceMonthly"); + if (preset === "YEARLY") return t("recurrenceYearly"); + return t("recurrenceCustom", { rule: upper }); +} + +// --------------------------------------------------------------------------- +// 搜索框自然语言快速建日程解析 +// --------------------------------------------------------------------------- + +const WEEKDAY_CN_RE: ReadonlyArray<{ re: RegExp; day: number }> = [ + { re: /^[日天]$/, day: 0 }, + { re: /^一$/, day: 1 }, + { re: /^二$/, day: 2 }, + { re: /^三$/, day: 3 }, + { re: /^四$/, day: 4 }, + { re: /^五$/, day: 5 }, + { re: /^六$/, day: 6 } +]; + +const REL_DAY_OFFSET_RE: ReadonlyArray<{ re: RegExp; offset: number }> = [ + { re: /^大后天$/, offset: 3 }, + { re: /^后天$/, offset: 2 }, + { re: /^(?:明天|明日|tomorrow)$/i, offset: 1 }, + { re: /^(?:今天|今日|today)$/i, offset: 0 } +]; + +function resolveWeekdayDate(now: number, targetDay: number, forceNextWeek: boolean): Date { + const base = new Date(now); + base.setHours(0, 0, 0, 0); + const currentDay = base.getDay(); + let diff = targetDay - currentDay; + if (forceNextWeek) { + // 计算下一周(周一为一周开始)对应的星期几 + const curMonOffset = currentDay === 0 ? 6 : currentDay - 1; + const targetMonOffset = targetDay === 0 ? 6 : targetDay - 1; + diff = 7 - curMonOffset + targetMonOffset; + } else if (diff < 0) { + diff += 7; + } + return new Date(base.getTime() + diff * DAY_MS); +} + +function extractDateFromText( + input: string, + now: number +): { text: string; targetDate: Date; hasDate: boolean } { + let text = input; + let targetDate = new Date(now); + targetDate.setHours(0, 0, 0, 0); + + const fullDateMatch = text.match(/\b(\d{4})[-/.](\d{1,2})[-/.](\d{1,2})\b/); + if (fullDateMatch) { + const y = Number(fullDateMatch[1]); + const m = Number(fullDateMatch[2]); + const d = Number(fullDateMatch[3]); + const probe = new Date(y, m - 1, d); + if (probe.getFullYear() === y && probe.getMonth() === m - 1 && probe.getDate() === d) { + return { text: text.replace(fullDateMatch[0], " "), targetDate: probe, hasDate: true }; + } + } + + const cnMonthDay = text.match(/(\d{1,2})月(\d{1,2})[日号]?/); + if (cnMonthDay) { + const m = Number(cnMonthDay[1]); + const d = Number(cnMonthDay[2]); + const year = new Date(now).getFullYear(); + const probe = new Date(year, m - 1, d); + if (probe.getMonth() === m - 1 && probe.getDate() === d) { + return { text: text.replace(cnMonthDay[0], " "), targetDate: probe, hasDate: true }; + } + } + + const relMatch = text.match(/(大后天|后天|明天|明日|今天|今日|\btomorrow\b|\btoday\b)/i); + if (relMatch) { + const token = relMatch[1]; + const matched = REL_DAY_OFFSET_RE.find((item) => item.re.test(token)); + const offset = matched ? matched.offset : 0; + targetDate = new Date(targetDate.getTime() + offset * DAY_MS); + return { text: text.replace(relMatch[0], " "), targetDate, hasDate: true }; + } + + const wdMatch = text.match(/(下周|下星期|本周|这周|周|星期)([一二三四五六日天])/); + if (wdMatch) { + const wd = WEEKDAY_CN_RE.find((item) => item.re.test(wdMatch[2])); + if (wd) { + const isNextWeek = /^下/.test(wdMatch[1]); + targetDate = resolveWeekdayDate(now, wd.day, isNextWeek); + return { text: text.replace(wdMatch[0], " "), targetDate, hasDate: true }; + } + } + + return { text, targetDate, hasDate: false }; +} + +function extractTimeFromText(input: string): { + text: string; + hasTime: boolean; + startHour: number; + startMin: number; + endHour: number | null; + endMin: number | null; +} { + const text = input; + + // 1. 时间范围:14:00-15:30 / 14:00~15:30 / 14:00到15:30 + const rangeMatch = text.match(/(\d{1,2})[::](\d{2})\s*[-~~到至]\s*(\d{1,2})[::](\d{2})/); + if (rangeMatch) { + const sh = Number(rangeMatch[1]); + const sm = Number(rangeMatch[2]); + const eh = Number(rangeMatch[3]); + const em = Number(rangeMatch[4]); + if (sh <= 23 && sm <= 59 && eh <= 23 && em <= 59 && eh * 60 + em > sh * 60 + sm) { + return { text: text.replace(rangeMatch[0], " "), hasTime: true, startHour: sh, startMin: sm, endHour: eh, endMin: em }; + } + } + + // 2. 单个 24h 时刻:14:00 / 9:30 / 14:30 + const clockMatch = text.match(/(?:^|\s)(\d{1,2})[::](\d{2})(?=\s|$)/); + if (clockMatch) { + const sh = Number(clockMatch[1]); + const sm = Number(clockMatch[2]); + if (sh <= 23 && sm <= 59) { + return { text: text.replace(clockMatch[0], " "), hasTime: true, startHour: sh, startMin: sm, endHour: null, endMin: null }; + } + } + + // 3. 中文口语时刻:下午2点半 / 上午9点 / 晚上8点15分 / 14点半 / 14点 + const cnTimeMatch = text.match(/(上午|早上|早晨|中午|下午|晚上|傍晚)?\s*(\d{1,2})\s*点(?:\s*(半)|(\d{1,2})\s*分?)?/); + if (cnTimeMatch) { + const period = cnTimeMatch[1] || ""; + let h = Number(cnTimeMatch[2]); + const m = cnTimeMatch[3] ? 30 : cnTimeMatch[4] ? Number(cnTimeMatch[4]) : 0; + if (/^(?:下午|晚上|傍晚)$/.test(period) && h >= 1 && h <= 11) { + h += 12; + } else if (/^中午$/.test(period) && h >= 1 && h <= 5) { + h += 12; + } + if (h >= 0 && h <= 23 && m >= 0 && m <= 59) { + return { text: text.replace(cnTimeMatch[0], " "), hasTime: true, startHour: h, startMin: m, endHour: null, endMin: null }; + } + } + + // 4. 英文 12h 时刻:2pm / 2:30pm / 9am + const enTimeMatch = text.match(/\b(\d{1,2})(?::(\d{2}))?\s*(am|pm)\b/i); + if (enTimeMatch) { + let h = Number(enTimeMatch[1]); + const m = enTimeMatch[2] ? Number(enTimeMatch[2]) : 0; + const meridiem = enTimeMatch[3].toLowerCase(); + if (h >= 1 && h <= 12 && m <= 59) { + if (meridiem === "pm" && h < 12) h += 12; + if (meridiem === "am" && h === 12) h = 0; + return { text: text.replace(enTimeMatch[0], " "), hasTime: true, startHour: h, startMin: m, endHour: null, endMin: null }; + } + } + + return { text, hasTime: false, startHour: 9, startMin: 0, endHour: null, endMin: null }; +} + +/** + * 解析搜索框中的自然语言日程,例如: + * - `明天 14:00 评审` + * - `后天 10:00-11:30 架构对齐会` + * - `周五 下午3点半 产品周会 1.5h 每周` + * - `2026-10-25 09:00 季度复盘 https://vc.feishu.cn/j/123456` + * + * 为避免误伤普通搜索词(如 `健身`、`V溢出`、`今天`),仅在同时识别出非空标题且包含明确时间或日期表达时返回候选。 + */ +export function parseQuickEventInput(query: string, now = Date.now()): QuickEventDraft | null { + let text = (query || "").trim(); + if (!text || text.length < 3) return null; + + // 1. 提取会议 URL + let conferenceUrl: string | undefined; + const urlMatch = text.match(/https?:\/\/[^\s]+/i); + if (urlMatch) { + const candidate = urlMatch[0].replace(TRAILING_PUNCT_RE, ""); + try { + const parsed = new URL(candidate); + if (parsed.protocol === "http:" || parsed.protocol === "https:") { + conferenceUrl = candidate; + text = text.replace(urlMatch[0], " "); + } + } catch { + // ignore malformed URL + } + } + + // 2. 提取重复周期 + let rrule: string | undefined; + const recurPatterns: ReadonlyArray<{ re: RegExp; rule: string }> = [ + { re: /(?:每个工作日|工作日|\bweekdays\b)/i, rule: "FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR" }, + { re: /(?:每天|每日|\bdaily\b)/i, rule: "FREQ=DAILY" }, + { re: /(?:每周|\bweekly\b)/i, rule: "FREQ=WEEKLY" }, + { re: /(?:每月|\bmonthly\b)/i, rule: "FREQ=MONTHLY" }, + { re: /(?:每年|\byearly\b)/i, rule: "FREQ=YEARLY" } + ]; + for (const item of recurPatterns) { + if (item.re.test(text)) { + rrule = item.rule; + text = text.replace(item.re, " "); + break; + } + } + + // 3. 提取日期 + const dateParsed = extractDateFromText(text, now); + text = dateParsed.text; + + // 4. 提取时长(可选) + let durationMinutes = 60; + const durPatterns: ReadonlyArray<{ re: RegExp; toMin: (m: RegExpMatchArray) => number }> = [ + { re: /半小时/, toMin: () => 30 }, + { re: /\b(\d+(?:\.\d+)?)\s*(?:h|hr|hrs|hour|hours)\b/i, toMin: (m) => Math.round(Number(m[1]) * 60) }, + { re: /(\d+(?:\.\d+)?)\s*小时/, toMin: (m) => Math.round(Number(m[1]) * 60) }, + { re: /\b(\d+)\s*(?:m|min|mins)\b/i, toMin: (m) => Number(m[1]) }, + { re: /(\d+)\s*分钟/, toMin: (m) => Number(m[1]) } + ]; + for (const dp of durPatterns) { + const dm = text.match(dp.re); + if (dm) { + const mins = dp.toMin(dm); + if (Number.isFinite(mins) && mins >= 5 && mins <= 720) { + durationMinutes = mins; + text = text.replace(dm[0], " "); + break; + } + } + } + + // 5. 提取起止时刻 + const timeParsed = extractTimeFromText(text); + const title = timeParsed.text.replace(/\s+/g, " ").trim(); + if (!title) return null; + if (!timeParsed.hasTime && !dateParsed.hasDate) return null; + + const dateStr = formatDateLocal(dateParsed.targetDate); + if (!timeParsed.hasTime) { + return { + title, + date: dateStr, + startTime: "09:00", + endTime: "10:00", + isAllDay: true, + ...(conferenceUrl ? { conferenceUrl } : {}), + ...(rrule ? { rrule } : {}) + }; + } + + const startMs = new Date( + dateParsed.targetDate.getFullYear(), + dateParsed.targetDate.getMonth(), + dateParsed.targetDate.getDate(), + timeParsed.startHour, + timeParsed.startMin, + 0, + 0 + ).getTime(); + const endMs = + timeParsed.endHour !== null && timeParsed.endMin !== null + ? new Date( + dateParsed.targetDate.getFullYear(), + dateParsed.targetDate.getMonth(), + dateParsed.targetDate.getDate(), + timeParsed.endHour, + timeParsed.endMin, + 0, + 0 + ).getTime() + : startMs + durationMinutes * 60_000; + const endObj = new Date(endMs); + const endDateStr = formatDateLocal(endObj); + + return { + title, + date: dateStr, + startTime: `${pad2(timeParsed.startHour)}:${pad2(timeParsed.startMin)}`, + endTime: endDateStr === dateStr ? formatClockLocal(endObj) : `${endDateStr} ${formatClockLocal(endObj)}`, + isAllDay: false, + ...(conferenceUrl ? { conferenceUrl } : {}), + ...(rrule ? { rrule } : {}) + }; +} diff --git a/extensions/calendar/tests/calendar.fixes.test.mjs b/extensions/calendar/tests/calendar.fixes.test.mjs deleted file mode 100644 index db7822fa..00000000 --- a/extensions/calendar/tests/calendar.fixes.test.mjs +++ /dev/null @@ -1,759 +0,0 @@ -// calendar 集成测试:真实声明式运行时 + 按宿主语义模拟的日程库与对话框 / 写文件 IPC,含故障注入 -// 覆盖:日期显示与分组、时间校验、ICS 导出为文件、会议链接校验、Enter / ⌘Enter 作用于选中日程、 -// 删除需确认且不占用 ⌘X、读取失败如实提示并保留列表 -import test from 'node:test' -import assert from 'node:assert/strict' -import { getComponentFactory } from '@ztools/declarative-ui' -import { createHost, mount, mountPushed, tick } from '../../shared/test-harness.mjs' -import CalendarCommand, { - parseEventTimes, - normalizeConferenceUrl, - createCalendarEvent, - updateCalendarEvent, - fetchCalendarPage, - exportCalendarIcs, - exportCalendarIcsToFile, - buildCalendarIcsContent, - formatEventRange, - formatDateKey, - defaultIcsFileName -} from '../dist/index.js' - -const host = createHost() -const HOUR = 3600_000 -const DAY = 24 * HOUR - -function todayAt(h, m = 0, dayOffset = 0) { - const d = new Date() - d.setHours(0, 0, 0, 0) - d.setDate(d.getDate() + dayOffset) - d.setHours(h, m, 0, 0) - return d.getTime() -} - -/** 按宿主语义模拟的日程库:list / count / create / delete / export 都读写同一个数组 */ -function installCalendarHost(db) { - const filter = (q) => - db.filter((e) => { - if (q.search && !e.title.toLowerCase().includes(String(q.search).toLowerCase())) return false - if (q.startTime !== undefined && e.endTime < q.startTime) return false - if (q.endTime !== undefined && e.startTime > q.endTime) return false - return true - }) - host.ipc.calendar_list_events = async (q) => - filter(q).sort((a, b) => (q.order === 'desc' ? b.startTime - a.startTime : a.startTime - b.startTime)).slice(0, q.limit ?? 50) - host.ipc.calendar_count_events = async (q) => ({ total: filter(q).length }) - host.ipc.calendar_create_event = async (p) => { - if (typeof p.startTime !== 'number' || typeof p.endTime !== 'number') throw Object.assign(new Error('宿主内部错误'), { code: 'INTERNAL_ERROR' }) - const saved = { ...p, id: `srv-${db.length + 1}`, calendarName: p.calendarName || 'Calendar' } - db.push(saved) - return saved - } - host.ipc.calendar_delete_event = async ({ id }) => { - const idx = db.findIndex((e) => e.id === id) - if (idx >= 0) db.splice(idx, 1) - return { success: idx >= 0 } - } - host.ipc.calendar_export_ics = async ({ eventIds }) => { - const picked = db.filter((e) => eventIds.includes(e.id)) - const ics = ['BEGIN:VCALENDAR', ...picked.flatMap((e) => ['BEGIN:VEVENT', `SUMMARY:${e.title}`, `DTSTART:${e.startTime}`, 'END:VEVENT']), 'END:VCALENDAR'].join('\r\n') - return { ics, count: picked.length } - } - return db -} - -const settle = async () => { - await tick(10) -} - -function sections(view) { - return view.tree().children.filter((c) => c && c.type === 'List.Section') -} - -async function openCreateForm(view) { - // 新建只在列表项与动作面板里出现一次(顶部筛选栏不再重复放) - const create = view.actions(view.items()[0]).find((a) => a.type === 'Action.Push' && a.props.title === '新建日程事件...') - assert.ok(create, '列表项动作面板里应有新建日程事件') - host.pushed.push(create.props.target) - await tick() - // 与宿主一样按组件工厂挂载被 push 的表单,表单状态才能响应输入 - const last = host.pushed.length - 1 - host.pushed[last] = getComponentFactory(host.pushed[last]) || host.pushed[last] - return mountPushed(host) -} - -test.beforeEach(() => host.reset()) - -// --------------------------------------------------------------------------- -// 日期 -// --------------------------------------------------------------------------- - -test('列表按「今天 / 明天 / 具体日期」分组,已结束的日程带「已结束」,摘要与详情带日期', async () => { - const todayStart = todayAt(0) - installCalendarHost([ - { id: 'ended', title: '晨会站会', startTime: todayStart, endTime: todayStart + 1, calendarName: 'Work' }, - { id: 'tomorrow', title: '跨午夜测试', startTime: todayAt(1, 0, 1), endTime: todayAt(2, 0, 1), calendarName: 'Work' }, - { id: 'later', title: '未来日程', startTime: todayAt(14, 0, 3), endTime: todayAt(15, 0, 3), calendarName: 'Work', location: '3F' } - ]) - const view = await mount(CalendarCommand) - await settle() - const secs = sections(view) - assert.equal(secs.length, 3) - assert.match(secs[0].props.title, /^今天 · \d+月\d+日 周. · 1 场$/) - assert.match(secs[1].props.title, /^明天 · /) - assert.doesNotMatch(secs[2].props.title, /^(今天|明天)/) - assert.match(secs[2].props.title, new RegExp(`${new Date(todayAt(14, 0, 3)).getDate()}日`)) - - assert.deepEqual(view.item('ended').props.accessories[0], { tag: '已结束' }) - assert.ok(!view.item('tomorrow').props.accessories.some((a) => a.tag), '未结束的不带标签') - assert.equal(view.item('tomorrow').props.accessories.at(-1).text, '01:00 - 02:00') - - const laterKey = formatDateKey(todayAt(14, 0, 3)) - assert.match(view.item('later').props.detail.props.markdown, new RegExp(laterKey)) - await view.run(view.item('later'), '复制日程摘要') - assert.match(host.clipboard.text, new RegExp(`^未来日程 \\(${laterKey} 周. 14:00 - 15:00\\) @ 3F$`)) - view.unmount() -}) - -test('跨天日程的时间段带结束日期;地点为空时摘要不拼「@」', async () => { - const evt = { id: 'x', title: '通宵', startTime: '23:00', endTime: '01:00', startAt: todayAt(23), endAt: todayAt(1, 0, 1), location: '', calendarName: 'Work', notes: '', attendees: [] } - const tomorrow = new Date(todayAt(1, 0, 1)) - assert.equal(formatEventRange(evt), `23:00 - ${tomorrow.getMonth() + 1}月${tomorrow.getDate()}日 01:00`) - assert.equal(formatEventRange({ ...evt, isAllDay: true }), '全天') - // 旧数据只有时分时仍能显示 - assert.equal(formatEventRange({ ...evt, startAt: undefined, endAt: undefined }), '23:00 - 01:00') -}) - -test('表单有日期字段(默认今天),选其他日期后按该日期保存,并出现在对应日期分组里', async () => { - const db = installCalendarHost([]) - const view = await mount(CalendarCommand) - await settle() - const form = await openCreateForm(view) - assert.equal(form.field('date').props.value, formatDateKey(Date.now())) - const target = todayAt(14, 0, 3) - await form.fill('title', '未来日程-评审') - await form.fill('date', formatDateKey(target)) - await form.fill('startTime', '14:00') - await form.fill('endTime', '15:30') - await form.run(undefined, '保存日程') - await settle() - assert.equal(db.length, 1) - assert.equal(db[0].startTime, target) - assert.equal(db[0].endTime, target + 1.5 * HOUR) - assert.equal(host.lastToast().title, '已创建日程: 未来日程-评审') - assert.match(host.lastToast().message, new RegExp(formatDateKey(target))) - assert.equal(host.pushed.length, 0, '保存成功后返回列表') - const secs = sections(view) - assert.equal(secs.length, 1) - assert.doesNotMatch(secs[0].props.title, /^今天/) - form.unmount() - view.unmount() -}) - -// --------------------------------------------------------------------------- -// 时间校验 -// --------------------------------------------------------------------------- - -test('时间解析:HH:MM 范围、日期合法性、先后顺序与跨天写法', () => { - const date = formatDateKey(todayAt(0)) - const ok = parseEventTimes({ date, startTime: '09:30', endTime: '10:00' }) - assert.deepEqual(ok, { ok: true, startAt: todayAt(9, 30), endAt: todayAt(10) }) - assert.equal(parseEventTimes({ date, startTime: '9:05', endTime: '10:00' }).startAt, todayAt(9, 5), '全角冒号也认') - - const bad = parseEventTimes({ date, startTime: 'abc', endTime: 'xyz' }) - assert.equal(bad.ok, false) - assert.match(bad.errors.startTime, /开始时间格式应为 HH:MM/) - assert.match(bad.errors.endTime, /结束时间格式应为 HH:MM/) - - const overflow = parseEventTimes({ date, startTime: '25:00', endTime: '26:00' }) - assert.match(overflow.errors.startTime, /00:00 - 23:59/) - assert.match(parseEventTimes({ date, startTime: '10:60', endTime: '11:00' }).errors.startTime, /HH:MM/) - - const reversed = parseEventTimes({ date, startTime: '16:00', endTime: '15:00' }) - assert.match(reversed.errors.endTime, /结束时间必须晚于开始时间/) - assert.match(parseEventTimes({ date, startTime: '16:00', endTime: '16:00' }).errors.endTime, /晚于/) - - const crossDay = parseEventTimes({ date, startTime: '23:00', endTime: `${formatDateKey(todayAt(0, 0, 1))} 01:00` }) - assert.deepEqual(crossDay, { ok: true, startAt: todayAt(23), endAt: todayAt(1, 0, 1) }) - - assert.match(parseEventTimes({ date: '2026-02-30', startTime: '10:00', endTime: '11:00' }).errors.date, /YYYY-MM-DD/) - assert.match(parseEventTimes({ date: '', startTime: '10:00', endTime: '11:00' }).errors.date, /请填写日期/) - assert.match(parseEventTimes({ date, startTime: '', endTime: '11:00' }).errors.startTime, /请填写开始时间/) - // 时间字段自带日期时不受日期字段影响 - assert.equal(parseEventTimes({ date: 'bad', startTime: '2026-10-25 14:00', endTime: '2026-10-25 15:00' }).ok, true) -}) - -test('表单里填非法时间:不调用宿主、字段标红、提示失败、停留在表单;改正后能保存', async () => { - const db = installCalendarHost([]) - const view = await mount(CalendarCommand) - await settle() - const form = await openCreateForm(view) - await form.fill('title', '无效时间测试') - - for (const [start, end, field, pattern] of [ - ['abc', 'xyz', 'startTime', /HH:MM/], - ['25:00', '26:00', 'startTime', /23:59/], - ['16:00', '15:00', 'endTime', /晚于开始时间/] - ]) { - await form.fill('startTime', start) - await form.fill('endTime', end) - await form.run(undefined, '保存日程') - assert.match(form.field(field).props.error || '', pattern, `${start}-${end}`) - assert.equal(host.lastToast().title, '请先修正标红的字段') - assert.equal(host.lastToast().style, 'FAILURE') - } - assert.equal(host.ipcCalls.filter(([m]) => m === 'calendar_create_event').length, 0, '非法时间不发给宿主') - assert.equal(db.length, 0) - assert.equal(host.pushed.length, 1, '停留在表单') - - // 修改时间字段后错误清掉,提交成功 - await form.fill('endTime', '17:00') - assert.equal(form.field('endTime').props.error, undefined) - await form.run(undefined, '保存日程') - await settle() - assert.equal(db.length, 1) - assert.equal(db[0].startTime, todayAt(16)) - form.unmount() - view.unmount() -}) - -test('[故障注入] 宿主创建失败时提示中文原因,不带错误码,表单保留', async () => { - installCalendarHost([]) - host.ipc.calendar_create_event = async () => { - throw Object.assign(new Error('database is locked'), { code: 'INTERNAL_ERROR' }) - } - const view = await mount(CalendarCommand) - await settle() - const form = await openCreateForm(view) - await form.fill('title', '锁定期间创建') - await form.run(undefined, '保存日程') - await settle() - assert.equal(host.lastToast().title, '创建日程失败') - assert.equal(host.lastToast().message, '宿主内部错误') - assert.equal(host.pushed.length, 1) - // 直接调用接口时也先校验,非法时间不触达宿主 - host.ipcCalls.length = 0 - await assert.rejects(() => createCalendarEvent({ title: 'x', startTime: 'abc', endTime: '11:00' }), /INVALID_EVENT_TIME/) - assert.equal(host.ipcCalls.length, 0) - form.unmount() - view.unmount() -}) - -// --------------------------------------------------------------------------- -// 导出 ICS 文件 -// --------------------------------------------------------------------------- - -function installFileHost({ pick = '/Users/test/Desktop/ztools-calendar.ics', writeError = null, dialogError = null } = {}) { - const writes = [] - host.ipc.window_show_save_dialog = async (params) => { - if (dialogError) throw dialogError - return pick ? { canceled: false, filePath: pick, fileUrl: 'ztools-file://x' } : { canceled: true } - } - host.ipc.filesystem_write_file = async (params) => { - if (writeError) throw writeError - writes.push(params) - return { success: true } - } - return writes -} - -test('⌘E 弹出另存为并写入 .ics 文件(内容来自宿主),提示保存路径;剪贴板不变', async () => { - installCalendarHost([ - { id: 'a', title: '周会', startTime: todayAt(20), endTime: todayAt(21) }, - { id: 'b', title: '复盘', startTime: todayAt(10, 0, 1), endTime: todayAt(11, 0, 1) } - ]) - const writes = installFileHost() - host.clipboard.text = 'SENTINEL' - const view = await mount(CalendarCommand) - await settle() - const action = view.actions(view.item('a')).find((a) => a.props.title === '导出当前列表为 ICS 文件...') - assert.deepEqual(action.props.shortcut, { modifiers: ['ctrl'], key: 'e' }) - await view.run(view.item('a'), '导出当前列表为 ICS 文件...') - await settle() - const dialogCall = host.ipcCalls.find(([m]) => m === 'window_show_save_dialog') - assert.equal(dialogCall[1].filters, 'iCalendar 日历|ics') - assert.match(dialogCall[1].defaultName, /^ztools-calendar-\d{8}\.ics$/) - assert.equal(writes.length, 1) - assert.equal(writes[0].path, '/Users/test/Desktop/ztools-calendar.ics') - assert.equal(writes[0].encoding, 'utf8') - assert.equal((writes[0].content.match(/BEGIN:VEVENT/g) || []).length, 2) - assert.equal(host.lastToast().title, '已导出 2 个日程到 ICS 文件') - assert.equal(host.lastToast().message, '/Users/test/Desktop/ztools-calendar.ics') - assert.equal(host.clipboard.text, 'SENTINEL') - - // 单条导出:默认文件名用日程标题 - await view.run(view.item('b'), '导出此日程为 ICS 文件...') - await settle() - const second = host.ipcCalls.filter(([m]) => m === 'window_show_save_dialog').at(-1) - assert.equal(second[1].defaultName, '复盘.ics') - assert.equal((writes[1].content.match(/BEGIN:VEVENT/g) || []).length, 1) - view.unmount() -}) - -test('[故障注入] 宿主导出失败:提示失败,不弹另存为、不写文件、不改剪贴板;取消另存为不提示成功;写文件失败如实提示', async () => { - installCalendarHost([{ id: 'a', title: '周会', startTime: todayAt(20), endTime: todayAt(21) }]) - const writes = installFileHost() - host.clipboard.text = 'SENTINEL' - host.ipc.calendar_export_ics = async () => { - throw Object.assign(new Error('database is locked'), { code: 'INTERNAL_ERROR' }) - } - const view = await mount(CalendarCommand) - await settle() - await view.run(view.item('a'), '导出当前列表为 ICS 文件...') - await settle() - assert.equal(host.lastToast().title, '导出 ICS 文件失败') - assert.equal(host.lastToast().message, '宿主内部错误') - assert.ok(!host.ipcCalls.some(([m]) => m === 'window_show_save_dialog')) - assert.equal(writes.length, 0) - - await view.run(view.item('a'), '复制当前列表的 ICS 文本') - await settle() - assert.equal(host.lastToast().title, '复制 ICS 文本失败') - assert.equal(host.clipboard.text, 'SENTINEL', '失败时不能把本地拼的缺时间 ICS 放进剪贴板') - - // 恢复导出,用户取消另存为 - installCalendarHost([{ id: 'a', title: '周会', startTime: todayAt(20), endTime: todayAt(21) }]) - installFileHost({ pick: null }) - const before = host.toasts.length - await view.run(view.item('a'), '导出当前列表为 ICS 文件...') - await settle() - assert.equal(host.toasts.length, before, '取消时不提示') - - // 写文件失败 - installFileHost({ writeError: Object.assign(new Error('没有写入权限'), { code: 'PERMISSION_DENIED' }) }) - await view.run(view.item('a'), '导出当前列表为 ICS 文件...') - await settle() - assert.equal(host.lastToast().title, '导出 ICS 文件失败') - assert.equal(host.lastToast().message, '没有写入权限') - view.unmount() -}) - -test('复制 ICS 文本作为次要动作;本地生成的 ICS 带 DTSTAMP / DTSTART / DTEND、转义并折行', async () => { - installCalendarHost([{ id: 'a', title: '周会', startTime: todayAt(20), endTime: todayAt(21) }]) - const view = await mount(CalendarCommand) - await settle() - await view.run(view.item('a'), '复制当前列表的 ICS 文本') - assert.match(host.clipboard.text, /^BEGIN:VCALENDAR[\s\S]*SUMMARY:周会/) - assert.equal(host.lastToast().title, '已复制 ICS 日历文本') - view.unmount() - - const longNotes = '议程'.repeat(60) - const ics = buildCalendarIcsContent( - [{ id: 'e1', title: '评审; A, B\\C', startTime: '10:00', endTime: '11:00', startAt: Date.UTC(2026, 9, 25, 6), endAt: Date.UTC(2026, 9, 25, 7), location: '', calendarName: 'Work', notes: longNotes, attendees: [] }], - Date.UTC(2026, 9, 22, 0, 0, 0) - ) - assert.match(ics, /DTSTAMP:20261022T000000Z/) - assert.match(ics, /DTSTART:20261025T060000Z/) - assert.match(ics, /DTEND:20261025T070000Z/) - assert.match(ics, /SUMMARY:评审\\; A\\, B\\\\C/) - for (const line of ics.split('\r\n')) assert.ok(Buffer.byteLength(line, 'utf8') <= 75, `行过长: ${line}`) - assert.ok(ics.includes('\r\n '), '长行已折行') - assert.equal(ics.split('\r\n').map((l, i) => (i > 0 && l.startsWith(' ') ? l.slice(1) : '\n' + l)).join('').includes(`DESCRIPTION:${longNotes}`), true, '折行后能还原') -}) - -test('文件名去掉非法字符;没有宿主环境时导出文件直接报不支持', async () => { - assert.equal(defaultIcsFileName([{ id: 'x', title: 'a/b:c*?', startTime: '', endTime: '', location: '', calendarName: '', notes: '', attendees: [] }]), 'a_b_c_.ics') - const stub = { - calendar_export_ics: async () => ({ success: true, data: { ics: 'BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\nEND:VEVENT\r\nEND:VCALENDAR' } }), - window_show_save_dialog: async () => ({ success: false, error: { message: '对话框已被其他窗口占用' } }) - } - await assert.rejects(() => exportCalendarIcsToFile([{ id: 'x', title: '周会' }], stub), /SAVE_DIALOG_FAILED: 对话框已被其他窗口占用/) -}) - -// --------------------------------------------------------------------------- -// 会议链接 -// --------------------------------------------------------------------------- - -test('会议链接规范化:缺协议补 https://,非 http/https、带凭据、含空格的拒绝', () => { - assert.deepEqual(normalizeConferenceUrl(''), {}) - assert.deepEqual(normalizeConferenceUrl(' '), {}) - assert.deepEqual(normalizeConferenceUrl('vc.feishu.cn/j/999'), { url: 'https://vc.feishu.cn/j/999' }) - assert.deepEqual(normalizeConferenceUrl('vc.feishu.cn:8443/j/1'), { url: 'https://vc.feishu.cn:8443/j/1' }) - assert.deepEqual(normalizeConferenceUrl('https://zoom.us/j/1'), { url: 'https://zoom.us/j/1' }) - assert.deepEqual(normalizeConferenceUrl('HTTP://meet.example.com/x'), { url: 'HTTP://meet.example.com/x' }) - assert.match(normalizeConferenceUrl('zoommtg://zoom.us/join?confno=123456').error, /不支持「zoommtg:」/) - assert.match(normalizeConferenceUrl('javascript:alert(1)').error, /不支持/) - assert.match(normalizeConferenceUrl('https://user:pw@zoom.us/j/1').error, /用户名或密码/) - assert.match(normalizeConferenceUrl('https://zoom.us/j/1 2').error, /http/) - assert.match(normalizeConferenceUrl('会议室').error, /http/) -}) - -test('表单填 zoommtg:// 时字段报错不保存;没写协议时自动补 https:// 再保存', async () => { - const db = installCalendarHost([]) - const view = await mount(CalendarCommand) - await settle() - const form = await openCreateForm(view) - await form.fill('title', '会议深链') - await form.fill('conferenceUrl', 'zoommtg://zoom.us/join?confno=123456') - await form.run(undefined, '保存日程') - assert.match(form.field('conferenceUrl').props.error, /zoommtg/) - assert.equal(db.length, 0) - - await form.fill('conferenceUrl', 'vc.feishu.cn/j/999') - assert.equal(form.field('conferenceUrl').props.error, undefined) - await form.run(undefined, '保存日程') - await settle() - assert.equal(db.length, 1) - assert.equal(db[0].conferenceUrl, 'https://vc.feishu.cn/j/999') - const join = view.actions(view.item('srv-1'))[0] - assert.equal(join.type, 'Action.OpenInBrowser') - assert.equal(join.props.url, 'https://vc.feishu.cn/j/999') - form.unmount() - view.unmount() -}) - -test('宿主里旧的非网址会议链接不标「可一键入会」,只在详情里如实展示;缺协议的旧链接补 https://', async () => { - installCalendarHost([ - { id: 'deep', title: '会议深链', startTime: todayAt(20), endTime: todayAt(21), conferenceUrl: 'zoommtg://zoom.us/join?confno=123456' }, - { id: 'bare', title: '飞书会', startTime: todayAt(21), endTime: todayAt(22), conferenceUrl: 'vc.feishu.cn/j/999' } - ]) - const view = await mount(CalendarCommand) - await settle() - const deep = view.item('deep') - assert.ok(!view.actions(deep).some((a) => a.type === 'Action.OpenInBrowser')) - assert.equal(deep.props.icon, 'calendar') - assert.doesNotMatch(JSON.stringify(deep.props.detail), /Join Ready/) - assert.match(deep.props.detail.props.markdown, /无法直接打开.*zoommtg:\/\/zoom\.us/) - const bare = view.actions(view.item('bare'))[0] - assert.equal(bare.type, 'Action.OpenInBrowser') - assert.equal(bare.props.url, 'https://vc.feishu.cn/j/999') - // 「视频会议」范围不含无法打开的链接 - await view.dropdown('meetings') - await settle() - assert.deepEqual(view.items().map((i) => i.props.id), ['bare']) - view.unmount() -}) - -// --------------------------------------------------------------------------- -// 动作顺序与删除 -// --------------------------------------------------------------------------- - -test('Enter / ⌘Enter 作用于选中日程:会议是「加入 / 复制会议链接」,普通日程是「复制摘要 / 导出此日程」;新建与导出全部排在后面', async () => { - installCalendarHost([ - { id: 'm', title: '架构评审', startTime: todayAt(20), endTime: todayAt(21), conferenceUrl: 'https://zoom.us/j/111' }, - { id: 'gym', title: '健身', startTime: todayAt(21), endTime: todayAt(22), location: '健身房' } - ]) - const view = await mount(CalendarCommand) - await settle() - const meeting = view.actions(view.item('m')) - assert.equal(meeting[0].type, 'Action.OpenInBrowser') - assert.equal(meeting[1].type, 'Action.CopyToClipboard') - assert.equal(meeting[1].props.content, 'https://zoom.us/j/111') - - const gym = view.actions(view.item('gym')) - assert.equal(gym[0].props.title, '复制日程摘要') - assert.equal(gym[1].props.title, '导出此日程为 ICS 文件...') - for (const list of [meeting, gym]) { - const titles = list.map((a) => a.props.title) - const firstGlobal = titles.indexOf('新建日程事件...') - assert.ok(firstGlobal >= 2, '新建不占 Enter / ⌘Enter') - assert.ok(titles.indexOf('导出当前列表为 ICS 文件...') > firstGlobal) - } - // Enter(第 1 个动作)复制的是选中日程自己的摘要 - await view.run(view.item('gym'), gym[0].props.title) - assert.match(host.clipboard.text, /^健身 \(.* 21:00 - 22:00\) @ 健身房$/) - view.unmount() -}) - -test('删除不再占用 ⌘X,改为 ⌘⇧⌫,且必须确认;取消确认不删除,确认后删除', async () => { - const db = installCalendarHost([ - { id: 'a', title: '周会', startTime: todayAt(20), endTime: todayAt(21) }, - { id: 'b', title: '复盘', startTime: todayAt(21), endTime: todayAt(22) } - ]) - const view = await mount(CalendarCommand) - await settle() - const all = view.actions(view.item('a')) - assert.ok(!all.some((a) => a.props.shortcut?.key === 'x'), '没有动作绑定 X') - const del = all.find((a) => a.props.title === '删除此日程...') - assert.deepEqual(del.props.shortcut, { modifiers: ['ctrl', 'shift'], key: 'backspace' }) - - host.setConfirm(false) - await view.run(view.item('a'), '删除此日程...') - await settle() - assert.equal(host.confirms.length, 1) - assert.match(host.confirms[0].title, /周会/) - assert.equal(host.confirms[0].primaryAction.style, 'destructive') - assert.ok(!host.ipcCalls.some(([m]) => m === 'calendar_delete_event'), '取消时不调用宿主') - assert.equal(db.length, 2) - assert.ok(view.items().some((i) => i.props.id === 'a')) - - host.setConfirm(true) - await view.run(view.item('a'), '删除此日程...') - await settle() - assert.equal(db.length, 1) - assert.ok(!view.items().some((i) => i.props.id === 'a')) - assert.equal(host.lastToast().title, '已删除日程: 周会') - - // 顶栏提供新建与导出,删除只属于列表行,空选择也不留下无效删除按钮。 - assert.deepEqual(view.tree().props.filterBar.actions.map(a => a.id), ['new-event', 'export-all-ics'], '顶栏应展示新建与导出') - assert.equal(view.tree().props.filterBar.groups, undefined) - assert.ok(view.actions(view.items()[0]).some(a => a.props.title === '删除此日程...')) - view.unmount() -}) - -test('[故障注入] 确认删除后宿主失败:提示失败并保留条目', async () => { - installCalendarHost([{ id: 'a', title: '周会', startTime: todayAt(20), endTime: todayAt(21) }]) - host.ipc.calendar_delete_event = async () => { - throw Object.assign(new Error('database is locked'), { code: 'INTERNAL_ERROR' }) - } - const view = await mount(CalendarCommand) - await settle() - await view.run(view.item('a'), '删除此日程...') - await settle() - assert.equal(host.lastToast().title, '删除日程失败') - assert.ok(view.items().some((i) => i.props.id === 'a')) - view.unmount() -}) - -// --------------------------------------------------------------------------- -// 读取失败 -// --------------------------------------------------------------------------- - -test('[故障注入] 首次读取失败:提示失败,空状态是「读取失败,按 Enter 重试」而不是「暂无日程」;重试成功后恢复', async () => { - const db = [{ id: 'a', title: '周会', startTime: todayAt(20), endTime: todayAt(21) }] - installCalendarHost(db) - const realList = host.ipc.calendar_list_events - host.ipc.calendar_list_events = async () => { - throw Object.assign(new Error('database is locked'), { code: 'INTERNAL_ERROR' }) - } - const view = await mount(CalendarCommand) - await settle() - assert.equal(host.lastToast().title, '读取日程失败') - assert.equal(host.lastToast().message, '宿主内部错误') - const ids = view.items().map((i) => i.props.id) - assert.deepEqual(ids, ['calendar-load-error']) - assert.match(view.tree().props.filterBar.summaryText, /读取日程失败:宿主内部错误/) - assert.doesNotMatch(view.text(), /当前暂无日程安排/) - - host.ipc.calendar_list_events = realList - await view.run(view.item('calendar-load-error'), '重新读取日程') - await settle() - assert.deepEqual(view.items().map((i) => i.props.id), ['a']) - assert.doesNotMatch(view.tree().props.filterBar.summaryText, /读取日程失败/) - view.unmount() -}) - -test('[故障注入] 已有列表时切换范围读取失败:保留原列表并在状态条说明,可从动作面板重新读取', async () => { - const db = [ - { id: 'a', title: '周会', startTime: todayAt(20), endTime: todayAt(21), conferenceUrl: 'https://zoom.us/j/1' }, - { id: 'b', title: '健身', startTime: todayAt(21), endTime: todayAt(22) } - ] - installCalendarHost(db) - const realList = host.ipc.calendar_list_events - const view = await mount(CalendarCommand) - await settle() - assert.equal(view.items().length, 2) - - host.ipc.calendar_list_events = async () => ({ unexpected: true }) - await view.dropdown('past') - await settle() - assert.equal(host.lastToast().title, '读取日程失败') - assert.match(host.lastToast().message, /格式无法识别/) - assert.deepEqual(view.items().map((i) => i.props.id).sort(), ['a', 'b'], '保留上次的列表') - assert.match(view.tree().props.filterBar.summaryText, /上次读取的结果/) - - host.ipc.calendar_list_events = realList - const reload = view.actions(view.item('a')).find((a) => a.props.title === '重新读取日程') - assert.equal(reload.props.shortcut, undefined, '不占用 ⌘R:macOS 上被客户端“重新加载”菜单键占用') - await view.run(view.item('a'), '重新读取日程') - await settle() - assert.doesNotMatch(view.tree().props.filterBar.summaryText, /读取日程失败/) - view.unmount() -}) - -test('fetchCalendarPage:宿主失败或格式不对时抛 LOAD_EVENTS_FAILED,宿主返回空数组时就是空', async () => { - const stub = (value) => ({ calendar_list_events: async () => value, calendar_count_events: async () => ({ success: true, data: { total: 0 } }) }) - await assert.rejects(() => fetchCalendarPage('all', '', stub({ success: false, error: { message: 'database is locked' } })), /LOAD_EVENTS_FAILED: 宿主读取日程失败/) - await assert.rejects(() => fetchCalendarPage('all', '', stub({ success: true, data: { foo: 1 } })), /LOAD_EVENTS_FAILED: 宿主返回的日程格式无法识别/) - const empty = await fetchCalendarPage('all', '', stub({ success: true, data: [] })) - assert.deepEqual(empty.events, [], '空数组不回退到演示数据') - await assert.rejects( - () => fetchCalendarPage('upcoming', '', { calendar_upcoming_events: async () => { throw new Error('boom') } }), - /LOAD_EVENTS_FAILED: 宿主读取日程失败/ - ) - // 导出也不回退 - await assert.rejects(() => exportCalendarIcs([{ id: 'a' }], { calendar_export_ics: async () => ({ success: false, error: { message: 'x' } }) }), /EXPORT_ICS_FAILED/) -}) - -// --------------------------------------------------------------------------- -// 重复提交、保存中离开、新建后按当前范围重新读取、夏令时 -// --------------------------------------------------------------------------- - -test('[并发] 保存中连按两次只创建一个日程;保存中途离开表单,迟到的结果不再关掉列表页', async () => { - const db = installCalendarHost([]) - const original = host.ipc.calendar_create_event - let release - host.ipc.calendar_create_event = (p) => new Promise((resolve) => { release = () => resolve(original(p)) }) - const view = await mount(CalendarCommand) - await settle() - const form = await openCreateForm(view) - await form.fill('title', '只建一次') - const first = form.run(undefined, '保存日程') - await tick() - await form.run(undefined, '保存日程') - assert.equal(host.ipcCalls.filter(([m]) => m === 'calendar_create_event').length, 1, '第二次提交被忽略') - // 用户按 Esc 离开表单(宿主仍在保存) - host.pushed.pop() - form.unmount() - // 哨兵代表离开后导航栈上的其他页面:插件若在卸载后仍执行 pop 会把它弹掉 - host.pushed.push('sentinel') - release() - await first - await settle() - assert.equal(db.length, 1) - assert.deepEqual(host.pushed, ['sentinel'], '离开后不再执行 pop') - assert.match(view.text(), /只建一次/, '列表已重新读取') - view.unmount() -}) - -test('新建后按当前范围重新读取:「即将开始」里不出现三天后的日程,「全部」里出现', async () => { - const db = installCalendarHost([]) - host.ipc.calendar_upcoming_events = async () => db.filter((e) => e.startTime - Date.now() < DAY && e.endTime >= Date.now()) - const view = await mount(CalendarCommand) - await settle() - await view.tree().props.searchBarAccessory.props.onChange('upcoming') - await settle() - const form = await openCreateForm(view) - const target = todayAt(10, 0, 3) - await form.fill('title', '三天后的评审') - await form.fill('date', formatDateKey(target)) - await form.run(undefined, '保存日程') - await settle() - assert.equal(db.length, 1) - assert.doesNotMatch(view.text(), /三天后的评审/) - await view.tree().props.searchBarAccessory.props.onChange('all') - await settle() - assert.match(view.text(), /三天后的评审/) - form.unmount() - view.unmount() -}) - -test('「下一场」取最早的未结束日程;「历史日程」里不显示下一场', async () => { - installCalendarHost([ - { id: 'ended', title: '早会已结束', startTime: Date.now() - 3 * HOUR, endTime: Date.now() - 2 * HOUR, calendarName: 'Work' }, - { id: 'plain', title: '普通评审', startTime: Date.now() + HOUR, endTime: Date.now() + 2 * HOUR, calendarName: 'Work' }, - { id: 'meet', title: '视频周会', startTime: Date.now() + 3 * HOUR, endTime: Date.now() + 4 * HOUR, conferenceUrl: 'https://vc.feishu.cn/j/1', calendarName: 'Work' } - ]) - const view = await mount(CalendarCommand) - await settle() - const summary = view.tree().props.filterBar.summaryText - // 早会可能在昨天(凌晨运行时),只要它没被当成下一场即可 - assert.match(summary, /下一场: 普通评审/) - await view.tree().props.searchBarAccessory.props.onChange('past') - await settle() - assert.doesNotMatch(view.tree().props.filterBar.summaryText, /下一场/) - view.unmount() -}) - -test('[边界] 夏令时开始当天被跳过的时刻报错,不悄悄顺延一小时', () => { - const previous = process.env.TZ - process.env.TZ = 'America/New_York' - try { - const skipped = parseEventTimes({ date: '2026-03-08', startTime: '02:30', endTime: '04:00' }) - assert.equal(skipped.ok, false) - assert.match(skipped.errors.startTime, /夏令时/) - const ok = parseEventTimes({ date: '2026-03-08', startTime: '03:30', endTime: '04:00' }) - assert.equal(ok.ok, true) - assert.equal(ok.endAt - ok.startAt, 30 * 60_000) - } finally { - if (previous === undefined) delete process.env.TZ - else process.env.TZ = previous - } -}) - -test('[macOS 审查] 新建入口不在顶部筛选栏重复;界面文案不再中英混排', async () => { - installCalendarHost([]) - const view = await mount(CalendarCommand) - await settle() - assert.ok(!view.tree().props.filterBar.actions.some((a) => a.id === 'create-calendar-event')) - const empty = view.item('calendar-empty-create') - assert.equal(empty.props.title, '新建日程事件...') - const text = view.text() - assert.doesNotMatch(text, /\((Create|Join|All Events|Upcoming|Video Meetings|Past Events|My Schedule|Work|Engineering|Personal)/) - view.unmount() -}) - -test('[macOS 审查][异常] 读取失败时空列表只给重试与新建,新建入口不重复', async () => { - installCalendarHost([]) - host.ipc.calendar_list_events = async () => { throw new Error('database is locked') } - const view = await mount(CalendarCommand) - await settle() - const err = view.item('calendar-load-error') - // 测试辅助会把 Action.Push 目标表单里的提交按钮也收进来,这里只看面板本身的动作 - const titles = view.actions(err).map((a) => a.props.title).filter((t) => t !== '保存日程') - assert.deepEqual(titles, ['重新读取日程', '新建日程事件...']) - assert.ok(!view.tree().props.filterBar.actions.some((a) => a.id === 'create-calendar-event')) - view.unmount() -}) - -test('全天事件:勾选 isAllDay 后无需填写起止时刻,保存并正确展示「全天」', async () => { - const db = installCalendarHost([]) - const view = await mount(CalendarCommand) - await settle() - const form = await openCreateForm(view) - await form.fill('title', '公司年会') - await form.fill('isAllDay', true) - assert.throws(() => form.field('startTime'), /找不到表单字段/) - assert.throws(() => form.field('endTime'), /找不到表单字段/) - await form.run(undefined, '保存日程') - await settle() - assert.equal(db.length, 1) - assert.equal(db[0].isAllDay, true) - const item = view.item(db[0].id) - assert.ok(item.props.accessories.some((a) => a.text === '全天')) - form.unmount() - view.unmount() -}) - -test('编辑已有日程:宿主支持 calendar_update_event 时直接更新;不支持时安全新建后再删旧记录', async () => { - const db = installCalendarHost([ - { id: 'orig-1', title: '旧周会', startTime: todayAt(10), endTime: todayAt(11), location: 'A会议室', calendarName: 'Work', isAllDay: false } - ]) - // 1) 宿主支持 calendar_update_event - host.ipc.calendar_update_event = async (params) => { - const idx = db.findIndex((e) => e.id === params.id) - if (idx < 0) throw new Error('not found') - db[idx] = { ...db[idx], ...params } - return db[idx] - } - const view = await mount(CalendarCommand) - await settle() - const editAction = view.actions(view.item('orig-1')).find((a) => a.type === 'Action.Push' && a.props.title === '编辑此日程...') - assert.ok(editAction) - host.pushed.push(getComponentFactory(editAction.props.target) || editAction.props.target) - await tick() - const editForm = await mountPushed(host) - await settle() - assert.equal(editForm.field('title').props.value, '旧周会') - await editForm.fill('title', '新周会(已改)') - await editForm.fill('isAllDay', true) - await editForm.run(undefined, '保存日程') - await settle() - assert.equal(db.length, 1) - assert.equal(db[0].id, 'orig-1') - assert.equal(db[0].title, '新周会(已改)') - assert.equal(db[0].isAllDay, true) - editForm.unmount() - - // 2) 宿主不支持 calendar_update_event 时安全降级(先创建成功再删除旧记录) - delete host.ipc.calendar_update_event - const updated = await updateCalendarEvent('orig-1', { - title: '降级更新周会', - date: formatDateKey(todayAt(0)), - startTime: '14:00', - endTime: '15:00', - isAllDay: false - }) - assert.equal(updated.title, '降级更新周会') - assert.equal(db.length, 1) - assert.notEqual(db[0].id, 'orig-1') - assert.equal(db[0].title, '降级更新周会') - - // 3) 降级路径中若删除旧记录失败,绝不假成功 - host.ipc.calendar_delete_event = async () => ({ success: false, error: 'delete locked' }) - await assert.rejects( - () => updateCalendarEvent(db[0].id, { title: '清理失败测试', date: formatDateKey(todayAt(0)), isAllDay: true }), - /UPDATE_EVENT_CLEANUP_FAILED/ - ) - view.unmount() -}) diff --git a/extensions/calendar/tests/calendar.host.test.mjs b/extensions/calendar/tests/calendar.host.test.mjs index 52f9eb4c..6de9a219 100644 --- a/extensions/calendar/tests/calendar.host.test.mjs +++ b/extensions/calendar/tests/calendar.host.test.mjs @@ -9,7 +9,14 @@ const { createCalendarEvent, deleteCalendarEvent, exportCalendarIcs, - buildCalendarIcsContent + buildCalendarIcsContent, + parseQuickEventInput, + parseIcsContent, + importCalendarIcsContent, + importCalendarIcsFromFile, + detectMeetingPlatform, + formatRecurrenceLabel, + getNextHalfHourSlot } = await import('../dist/index.js') /** 宿主桩:按方法名返回 { success, data } 信封,未登记的方法视为宿主不支持 */ @@ -164,3 +171,132 @@ test('导出 ICS:只把当前列表日程的 id 发给宿主', async () => { await exportCalendarIcs([], host) assert.deepEqual(host.calls[1].params, { eventIds: [] }) }) + +test('自然语言快速建日程解析:日期/时刻/区间/时长/重复/会议链接,不误伤普通搜索词', () => { + // 2026-10-20 周二 10:15 + const now = new Date(2026, 9, 20, 10, 15, 0, 0).getTime() + const d1 = parseQuickEventInput('明天 14:00 评审', now) + assert.deepEqual(d1, { + title: '评审', + date: '2026-10-21', + startTime: '14:00', + endTime: '15:00', + isAllDay: false + }) + + const d2 = parseQuickEventInput('后天 10:00-11:30 架构对齐会', now) + assert.equal(d2?.date, '2026-10-22') + assert.equal(d2?.startTime, '10:00') + assert.equal(d2?.endTime, '11:30') + assert.equal(d2?.title, '架构对齐会') + + const d3 = parseQuickEventInput('周五 下午3点半 产品周会 1.5h 每周 https://vc.feishu.cn/j/88412', now) + assert.equal(d3?.date, '2026-10-23') + assert.equal(d3?.startTime, '15:30') + assert.equal(d3?.endTime, '17:00') + assert.equal(d3?.rrule, 'FREQ=WEEKLY') + assert.equal(d3?.conferenceUrl, 'https://vc.feishu.cn/j/88412') + assert.equal(d3?.title, '产品周会') + + // 普通搜索词不应触发快速新建 + assert.equal(parseQuickEventInput('健身', now), null) + assert.equal(parseQuickEventInput('V溢出', now), null) + assert.equal(parseQuickEventInput('今天', now), null) + + // 默认时间段:下一个半点起 1 小时 + const slot = getNextHalfHourSlot(now) + assert.deepEqual(slot, { date: '2026-10-20', startTime: '10:30', endTime: '11:30' }) +}) + +test('ICS 解析与导入:支持折行、RRULE、全天事件、会议链接提取与异常拦截', async () => { + const ics = [ + 'BEGIN:VCALENDAR', + 'VERSION:2.0', + 'X-WR-CALNAME:飞书日历', + 'BEGIN:VEVENT', + 'SUMMARY:Q4 路线图', + ' 评审会', + 'DTSTART:20261025T140000', + 'DTEND:20261025T153000', + 'LOCATION:线上会议', + 'DESCRIPTION:议程:讨论核心排期\\n链接:https://vc.feishu.cn/j/998877', + 'RRULE:FREQ=WEEKLY', + 'END:VEVENT', + 'BEGIN:VEVENT', + 'SUMMARY:版本发布日', + 'DTSTART;VALUE=DATE:20261028', + 'END:VEVENT', + 'END:VCALENDAR' + ].join('\r\n') + + const parsed = parseIcsContent(ics) + assert.equal(parsed.length, 2) + assert.equal(parsed[0].title, 'Q4 路线图评审会') + assert.equal(parsed[0].date, '2026-10-25') + assert.equal(parsed[0].startTime, '14:00') + assert.equal(parsed[0].endTime, '15:30') + assert.equal(parsed[0].conferenceUrl, 'https://vc.feishu.cn/j/998877') + assert.equal(parsed[0].rrule, 'FREQ=WEEKLY') + assert.equal(parsed[0].calendarName, '飞书日历') + assert.equal(parsed[1].isAllDay, true) + + let seq = 0 + const host = hostStub({ + window_show_open_dialog: { success: true, data: { canceled: false, filePath: '/tmp/team.ics' } }, + filesystem_read_file: { success: true, data: { content: ics } }, + calendar_create_event: (params) => ({ success: true, data: { ...params, id: `imp-${++seq}` } }) + }) + const res = await importCalendarIcsFromFile(host) + assert.equal(res.status, 'imported') + if (res.status === 'imported') { + assert.equal(res.imported, 2) + assert.equal(res.failed, 0) + assert.equal(res.events[0].rrule, 'FREQ=WEEKLY') + } + + // 用户取消返回 canceled + const canceledHost = hostStub({ + window_show_open_dialog: { success: true, data: { canceled: true } } + }) + assert.deepEqual(await importCalendarIcsFromFile(canceledHost), { status: 'canceled' }) + + // 空/无效 ICS 抛错 + await assert.rejects(() => importCalendarIcsContent('not an ics', host), /EMPTY_ICS_EVENTS/) +}) + +test('重复日程持久化闭环与主流会议平台识别', async () => { + const savedRows = [] + const host = hostStub({ + calendar_create_event: (params) => { + const row = { ...params, id: 'rec-1' } + savedRows.push(row) + return { success: true, data: row } + }, + calendar_list_events: () => ({ success: true, data: savedRows }) + }) + + const created = await createCalendarEvent( + { + title: '每周例会', + date: '2026-10-25', + startTime: '10:00', + endTime: '11:00', + notes: '核对进度', + rrule: 'FREQ=WEEKLY' + }, + host + ) + assert.equal(created.rrule, 'FREQ=WEEKLY') + assert.equal(created.notes, '核对进度') + + const listed = await fetchCalendarEvents('all', host) + assert.equal(listed[0].rrule, 'FREQ=WEEKLY') + assert.equal(listed[0].notes, '核对进度') + assert.equal(formatRecurrenceLabel(listed[0].rrule), '每周重复') + assert.match(buildCalendarIcsContent(listed), /RRULE:FREQ=WEEKLY/) + + assert.equal(detectMeetingPlatform('https://vc.feishu.cn/j/123'), '飞书会议') + assert.equal(detectMeetingPlatform('https://meeting.tencent.com/dm/abc'), '腾讯会议') + assert.equal(detectMeetingPlatform('https://zoom.us/j/111222'), 'Zoom 会议') + assert.equal(detectMeetingPlatform('https://example.com/page'), null) +}) diff --git a/extensions/calendar/tests/calendar.ui.test.mjs b/extensions/calendar/tests/calendar.ui.test.mjs index 06d468c7..328a6576 100644 --- a/extensions/calendar/tests/calendar.ui.test.mjs +++ b/extensions/calendar/tests/calendar.ui.test.mjs @@ -154,3 +154,53 @@ test('i18n 热切换回归:切英文后按天分组的 section 标题实时更 setRuntimeLocale('zh-CN') } }) + +test('搜索框输入自然语言“明天 14:00 评审”出现快速新建项并一键创建;重复日程与平台会议按钮正确展示', async () => { + const todayStart = new Date(); todayStart.setHours(0, 0, 0, 0) + const base = todayStart.getTime() + 18 * HOUR + const db = [ + { + id: 'weekly-feishu', + title: '产品周会', + startTime: base, + endTime: base + HOUR, + calendarName: 'Work', + conferenceUrl: 'https://vc.feishu.cn/j/88412', + notes: '对齐排期\n[RRULE:FREQ=WEEKLY]' + } + ] + installCalendarHost(db, { limitCap: 100 }) + host.ipc.calendar_create_event = async (params) => { + const created = { ...params, id: `created-${db.length + 1}` } + db.push(created) + return created + } + + const view = await mount(CalendarCommand) + await tick(10) + + // 验证重复日程标签与飞书会议一键直开动作 + const weeklyItem = view.item('weekly-feishu') + assert.ok(weeklyItem) + assert.ok(weeklyItem.props.accessories.some((a) => a.tag === '每周重复')) + const primaryAction = view.actions(weeklyItem)[0] + assert.equal(primaryAction.type, 'Action.OpenInBrowser') + assert.equal(primaryAction.props.title, '加入飞书会议') + assert.equal(primaryAction.props.url, 'https://vc.feishu.cn/j/88412') + + // 验证顶栏提供导入 ICS 入口 + assert.ok(view.tree().props.filterBar.actions.some((a) => a.id === 'import-ics')) + + // 搜索框输入自然语言快速新建 + await view.search('明天 14:00 评审') + await tick(5) + const quickItem = view.item('calendar-quick-create') + assert.ok(quickItem, '应渲染自然语言快速新建项') + assert.match(quickItem.props.title, /评审/) + await view.run(quickItem, '立即创建日程') + await tick(10) + const createCall = host.ipcCalls.find(([m]) => m === 'calendar_create_event') + assert.ok(createCall, '应调用 calendar_create_event') + assert.equal(createCall[1].title, '评审') + view.unmount() +}) diff --git a/extensions/chmod-cidr-calc/plugin.json b/extensions/chmod-cidr-calc/plugin.json index c37543cb..8307fa05 100644 --- a/extensions/chmod-cidr-calc/plugin.json +++ b/extensions/chmod-cidr-calc/plugin.json @@ -1,7 +1,7 @@ { "id": "chmod-cidr-calc", "name": "网段与权限计算", - "version": "1.0.7", + "version": "1.0.8", "minAppVersion": "1.1.8.0", "description": "IPv4 CIDR 子网掩码/可用地址池/32 位二进制掩码计算与 Linux chmod 八进制/符号权限位双向推演工具", "author": "ZTools Team", diff --git a/extensions/chmod-cidr-calc/src/chmod-cidr-service.ts b/extensions/chmod-cidr-calc/src/chmod-cidr-service.ts index 60440b73..8c92bc69 100644 --- a/extensions/chmod-cidr-calc/src/chmod-cidr-service.ts +++ b/extensions/chmod-cidr-calc/src/chmod-cidr-service.ts @@ -2,6 +2,11 @@ import type { ChmodCalculationResult, ChmodRoleBreakdown, CidrCalculationResult, + CidrSubnetSplitItem, + CidrSubnetSplitResult, + IpMembershipResult, + SubnetSplitCount, + UmaskCalculationResult, } from './types.js' import { t } from './i18n.js' @@ -171,10 +176,118 @@ export function calculateIpv4Cidr(rawInput: string): CidrCalculationResult { } } +/** 将 IPv4 CIDR 均分为 2 / 4 / 8 个等长子网 */ +export function splitIpv4Cidr(rawInput: string, parts: SubnetSplitCount = 4): CidrSubnetSplitResult { + if (parts !== 2 && parts !== 4 && parts !== 8) { + throw new Error(t('errSplitInvalidParts')) + } + const base = calculateIpv4Cidr(rawInput) + const extraBits = parts === 2 ? 1 : parts === 4 ? 2 : 3 + const childPrefixLength = base.prefixLength + extraBits + if (childPrefixLength > 32) { + throw new Error(t('errSplitPrefixTooDeep', { prefix: base.prefixLength, parts })) + } + const parentNetworkUint = ipToUint32(base.networkAddress) + const blockSize = Math.pow(2, 32 - childPrefixLength) + const subnets: CidrSubnetSplitItem[] = [] + for (let i = 0; i < parts; i++) { + const subNetUint = (parentNetworkUint + i * blockSize) >>> 0 + const subCidr = `${uint32ToIp(subNetUint)}/${childPrefixLength}` + const subCalc = calculateIpv4Cidr(subCidr) + subnets.push({ + index: i + 1, + cidr: `${subCalc.networkAddress}/${subCalc.prefixLength}`, + networkAddress: subCalc.networkAddress, + prefixLength: subCalc.prefixLength, + broadcastAddress: subCalc.broadcastAddress, + firstUsableIp: subCalc.firstUsableIp, + lastUsableIp: subCalc.lastUsableIp, + totalHosts: subCalc.totalHosts, + usableHosts: subCalc.usableHosts, + }) + } + return { + parentCidr: `${base.networkAddress}/${base.prefixLength}`, + parts, + childPrefixLength, + usableHostsPerSubnet: subnets[0]?.usableHosts ?? 0, + subnets, + } +} + +const IP_IN_CIDR_RE = /^(\S+)\s+(?:in|@)\s+(.+)$/i + +/** 判断输入是否为「IP in CIDR」归属检测表达式 */ +export function isIpMembershipQuery(rawInput: string): boolean { + return IP_IN_CIDR_RE.test(String(rawInput || '').trim()) +} + +/** 判断指定 IPv4 地址是否属于目标 CIDR 网段 */ +export function checkIpInCidr(rawInput: string): IpMembershipResult { + const trimmed = String(rawInput || '').trim() + const match = trimmed.match(IP_IN_CIDR_RE) + if (!match) { + throw new Error(t('errIpInCidrSyntax')) + } + const ipStr = match[1]!.trim() + const cidrStr = match[2]!.trim() + const ipUint = ipToUint32(ipStr) + const cidrResult = calculateIpv4Cidr(cidrStr) + const maskUint = cidrResult.prefixLength === 0 ? 0 : (0xffffffff << (32 - cidrResult.prefixLength)) >>> 0 + const networkUint = ipToUint32(cidrResult.networkAddress) + const broadcastUint = ipToUint32(cidrResult.broadcastAddress) + const isMember = ((ipUint & maskUint) >>> 0) === networkUint + const isNetworkAddress = isMember && cidrResult.hasBroadcast && ipUint === networkUint + const isBroadcastAddress = isMember && cidrResult.hasBroadcast && ipUint === broadcastUint + const offsetInSubnet = isMember ? (ipUint - networkUint) >>> 0 : undefined + + return { + ipAddress: uint32ToIp(ipUint), + cidr: `${cidrResult.networkAddress}/${cidrResult.prefixLength}`, + networkAddress: cidrResult.networkAddress, + prefixLength: cidrResult.prefixLength, + netmask: cidrResult.netmask, + firstUsableIp: cidrResult.firstUsableIp, + lastUsableIp: cidrResult.lastUsableIp, + broadcastAddress: cidrResult.broadcastAddress, + hasBroadcast: cidrResult.hasBroadcast, + isMember, + isNetworkAddress, + isBroadcastAddress, + offsetInSubnet, + totalHosts: cidrResult.totalHosts, + usableHosts: cidrResult.usableHosts, + addressScope: cidrResult.addressScope, + } +} + function digitToSymbolic(d: number): string { return `${(d & 4) !== 0 ? 'r' : '-'}${(d & 2) !== 0 ? 'w' : '-'}${(d & 1) !== 0 ? 'x' : '-'}` } +function buildRoles(digits: [number, number, number]): ChmodRoleBreakdown[] { + const roleNames: Array<'Owner (u)' | 'Group (g)' | 'Others (o)'> = [ + 'Owner (u)', + 'Group (g)', + 'Others (o)', + ] + return digits.map((digit, idx) => ({ + role: roleNames[idx], + digit, + symbolic: digitToSymbolic(digit), + read: (digit & 4) !== 0, + write: (digit & 2) !== 0, + execute: (digit & 1) !== 0, + })) +} + +function formatOctal3(modeBits: number): string { + const u = (modeBits >> 6) & 7 + const g = (modeBits >> 3) & 7 + const o = modeBits & 7 + return `${u}${g}${o}` +} + export function convertChmod(rawInput: string): ChmodCalculationResult { const cleaned = String(rawInput || '').trim().replace(/^chmod[ \t]+(?:-R[ \t]+)?/, '').trim() if (!cleaned) throw new Error(t('errChmodEmpty')) @@ -197,21 +310,7 @@ export function convertChmod(rawInput: string): ChmodCalculationResult { }) as [number, number, number] } - const roleNames: Array<'Owner (u)' | 'Group (g)' | 'Others (o)'> = [ - 'Owner (u)', - 'Group (g)', - 'Others (o)', - ] - - const roles: ChmodRoleBreakdown[] = digits.map((digit, idx) => ({ - role: roleNames[idx], - digit, - symbolic: digitToSymbolic(digit), - read: (digit & 4) !== 0, - write: (digit & 2) !== 0, - execute: (digit & 1) !== 0, - })) - + const roles = buildRoles(digits) const octal = (special ? String(special) : '') + digits.join('') const symbolic = roles.map((role, index) => { if (!(special & [4, 2, 1][index]!)) return role.symbolic @@ -219,6 +318,10 @@ export function convertChmod(rawInput: string): ChmodCalculationResult { return role.symbolic.slice(0, 2) + (role.execute ? letter : letter.toUpperCase()) }).join('') const isWorldWritable = (digits[2] & 2) !== 0 + const modeBits = (digits[0] << 6) | (digits[1] << 3) | digits[2] + const impliedDirUmask = formatOctal3((~modeBits) & 0o777) + const hasAnyExec = ((digits[0] | digits[1] | digits[2]) & 1) !== 0 + const impliedFileUmask = hasAnyExec ? undefined : formatOctal3((~modeBits) & 0o666) return { octal, @@ -231,6 +334,51 @@ export function convertChmod(rawInput: string): ChmodCalculationResult { securityWarning: isWorldWritable ? t('worldWritableWarning', { octal }) : undefined, + impliedDirUmask, + impliedFileUmask, roles, } } + +const UMASK_PREFIX_RE = /^umask(?:\s+|$)/i + +/** 判断输入是否为 umask 表达式(如 umask 022 / umask 0027) */ +export function isUmaskQuery(rawInput: string): boolean { + return UMASK_PREFIX_RE.test(String(rawInput || '').trim()) +} + +/** 根据 POSIX 规则由 umask 推演新建目录 (0777 & ~mask) 与新建文件 (0666 & ~mask) 默认权限 */ +export function calculateUmask(rawInput: string): UmaskCalculationResult { + const trimmed = String(rawInput || '').trim().replace(/^umask\s+/i, '').trim() + if (!trimmed || /^umask$/i.test(trimmed)) { + throw new Error(t('errUmaskEmpty')) + } + if (!/^[0-7]{3,4}$/.test(trimmed)) { + throw new Error(t('errUmaskFormat')) + } + const normalized3 = trimmed.slice(-3) + if (trimmed.length === 4 && trimmed[0] !== '0') { + throw new Error(t('errUmaskFormat')) + } + const maskBits = parseInt(normalized3, 8) + const dirBits = 0o777 & (~maskBits) + const fileBits = 0o666 & (~maskBits) + const dirDigits: [number, number, number] = [(dirBits >> 6) & 7, (dirBits >> 3) & 7, dirBits & 7] + const fileDigits: [number, number, number] = [(fileBits >> 6) & 7, (fileBits >> 3) & 7, fileBits & 7] + const dirRoles = buildRoles(dirDigits) + const fileRoles = buildRoles(fileDigits) + const dirOctal = dirDigits.join('') + const fileOctal = fileDigits.join('') + const umaskNormalized = `0${normalized3}` + + return { + umask: umaskNormalized, + umaskCommand: `umask ${umaskNormalized}`, + dirOctal, + dirSymbolic: dirRoles.map((r) => r.symbolic).join(''), + fileOctal, + fileSymbolic: fileRoles.map((r) => r.symbolic).join(''), + dirRoles, + fileRoles, + } +} diff --git a/extensions/chmod-cidr-calc/src/i18n.ts b/extensions/chmod-cidr-calc/src/i18n.ts index 6dc06093..e2f3ee30 100644 --- a/extensions/chmod-cidr-calc/src/i18n.ts +++ b/extensions/chmod-cidr-calc/src/i18n.ts @@ -49,8 +49,8 @@ const rawT = createTranslator( preset600Desc: "SSH 私钥 (~/.ssh/id_ed25519) 严格私有权限 (rw-------)", preset700Desc: "私有目录 (~/.ssh) 仅属主可访问权限 (rwx------)", preset777Desc: "全放开读写执行权限(存在安全风险)", - searchPlaceholderCidr: "输入 IPv4/CIDR(如 192.168.1.0/24、192.168.1.5 255.255.255.0)...", - searchPlaceholderChmod: "输入八进制权限(如 755、4755)或符号权限(如 rwxr-xr-x)...", + searchPlaceholderCidr: "输入 IPv4/CIDR(如 10.244.0.0/16)或 IP in CIDR(如 192.168.1.50 in 192.168.1.0/26)...", + searchPlaceholderChmod: "输入八进制(755/4755)、符号(rwxr-xr-x)或 umask(如 umask 022)...", dropdownTooltip: "切换计算器模式", modeCidrTitle: "IPv4 CIDR 子网计算器", modeChmodTitle: "Linux chmod 权限推演", @@ -91,7 +91,53 @@ const rawT = createTranslator( actionCopySymbolic: "复制符号权限值", tagWorldWritableShort: "全局可写", actionViewChmodDetail: "查看 chmod {code} 详情", - actionCopyChmodCode: "复制 chmod {code}" + actionCopyChmodCode: "复制 chmod {code}", + actionPasteTerminal: "直接粘贴到终端", + errSplitInvalidParts: "子网拆分数仅支持 2、4 或 8。", + errSplitPrefixTooDeep: "当前网段 /{prefix} 无法拆分为 {parts} 个子网(子网前缀将超过 /32)。", + errIpInCidrSyntax: "IP 归属表达式格式应为「IP in CIDR」,如 192.168.1.50 in 192.168.1.0/26。", + errUmaskEmpty: "请输入 umask 值(如 umask 022 或 umask 0027)。", + errUmaskFormat: "umask 必须是 3~4 位八进制数(000~0777),如 umask 022。", + sectionIpMembership: "IP 网段归属判断", + tagInSubnet: "属于该网段", + tagOutOfSubnet: "不在网段内", + ipMembershipInSub: "{ip} 属于 {cidr}", + ipMembershipOutSub: "{ip} 不属于 {cidr}", + ipMembershipMdIn: "### 归属结论:命中网段\n\n`{ip}` **属于** `{cidr}`({scope})。", + ipMembershipMdOut: "### 归属结论:未命中网段\n\n`{ip}` **不属于** `{cidr}`({scope})。", + ipRoleNetwork: "网络地址(网段起始)", + ipRoleBroadcast: "广播地址(网段末尾)", + ipRoleHost: "普通主机地址(第 {offset} 个偏移)", + ipRoleOutside: "位于目标网段之外", + metaTargetIp: "检测 IP", + metaTargetCidr: "目标网段", + metaIpRole: "地址角色", + actionCopyMembership: "复制归属结论", + splitPreviewTitle: "子网拆分预览:{parts} × /{prefix}", + splitPreviewSub: "每段可用 {usable} 台主机 · 回车复制全部子网", + splitPreviewCannotSub: "当前前缀 /{prefix} 无法继续拆分为 {parts} 段", + splitDetailMdHeader: "### 子网拆分预览({parent} → {parts} × /{prefix})\n\n每段可用 **{usable}** 台主机:\n\n| # | 子网 CIDR | 可用范围 | 广播/末地址 |\n| :---: | :--- | :--- | :--- |", + splitCannotMd: "### 无法继续拆分\n\n`{parent}` 的前缀长度为 `/{prefix}`,拆分为 {parts} 个子网需要 `/{needed}`,超过 IPv4 `/32` 上限。", + actionCopySplitList: "复制全部 {parts} 个子网", + splitBtnLabel: "拆 {parts} 段", + splitBtnTitle: "拆分为 {parts} 个子网", + actionLoadSubnet: "载入子网 {cidr}", + sectionUmaskResult: "umask 默认权限换算", + umaskMainTitle: "umask {umask} → 目录 {dir} / 文件 {file}", + umaskMainSub: "目录 {dirSym} · 文件 {fileSym}", + umaskDetailMd: "### umask `{umask}` 默认权限矩阵\n\n新创建目录基准为 `777`,扣除掩码后为 **`{dir}`** (`{dirSym}`);新创建文件基准为 `666`,扣除掩码后为 **`{file}`** (`{fileSym}`)。\n\n#### 目录权限(`{dir}` · `{dirSym}`)\n{dirTable}\n\n#### 文件权限(`{file}` · `{fileSym}`)\n{fileTable}\n\n### 终端命令\n```bash\n{cmd}\n```", + metaDirDefault: "新建目录默认权限", + metaFileDefault: "新建文件默认权限", + metaImpliedDirUmask: "对应目录 umask", + metaImpliedFileUmask: "对应文件 umask", + metaFileUmaskNa: "含执行位(文件默认不含 x)", + actionCopyUmaskCmd: "复制 umask 命令", + actionCopyDirOctal: "复制目录权限 ({octal})", + actionCopyFileOctal: "复制文件权限 ({octal})", + presetUmask022Desc: "系统默认 umask(目录 755 / 文件 644)", + presetUmask027Desc: "团队隔离 umask(目录 750 / 文件 640)", + presetUmask077Desc: "严格私有 umask(目录 700 / 文件 600)", + actionViewUmask: "换算 umask {code}" }, "en-US": { errIpFourOctets: "IPv4 address must contain 4 decimal octets.", @@ -140,8 +186,8 @@ const rawT = createTranslator( preset600Desc: "Strict private key permission (~/.ssh/id_ed25519, rw-------)", preset700Desc: "Private directory permission (~/.ssh, rwx------)", preset777Desc: "Full read/write/execute for everyone (security risk)", - searchPlaceholderCidr: "Enter IPv4/CIDR (e.g. 192.168.1.0/24 or 192.168.1.5 255.255.255.0)...", - searchPlaceholderChmod: "Enter octal (e.g. 755, 4755) or symbolic (e.g. rwxr-xr-x)...", + searchPlaceholderCidr: "Enter IPv4/CIDR (10.244.0.0/16) or IP in CIDR (192.168.1.50 in 192.168.1.0/26)...", + searchPlaceholderChmod: "Enter octal (755, 4755), symbolic (rwxr-xr-x), or umask (umask 022)...", dropdownTooltip: "Switch Calculator Mode", modeCidrTitle: "IPv4 CIDR Subnet Calculator", modeChmodTitle: "Linux chmod Permission Calculator", @@ -182,7 +228,53 @@ const rawT = createTranslator( actionCopySymbolic: "Copy Symbolic Value", tagWorldWritableShort: "World-Writable", actionViewChmodDetail: "Inspect chmod {code}", - actionCopyChmodCode: "Copy chmod {code}" + actionCopyChmodCode: "Copy chmod {code}", + actionPasteTerminal: "Paste to Terminal", + errSplitInvalidParts: "Subnet split count must be 2, 4, or 8.", + errSplitPrefixTooDeep: "Cannot split /{prefix} into {parts} subnets (exceeds /32).", + errIpInCidrSyntax: "Use \"IP in CIDR\" format, e.g. 192.168.1.50 in 192.168.1.0/26.", + errUmaskEmpty: "Please enter a umask value (e.g. umask 022 or umask 0027).", + errUmaskFormat: "umask must be 3-4 octal digits (000-0777), e.g. umask 022.", + sectionIpMembership: "IP Subnet Membership Check", + tagInSubnet: "In Subnet", + tagOutOfSubnet: "Not In Subnet", + ipMembershipInSub: "{ip} belongs to {cidr}", + ipMembershipOutSub: "{ip} is outside {cidr}", + ipMembershipMdIn: "### Membership: Matched\n\n`{ip}` **belongs to** `{cidr}` ({scope}).", + ipMembershipMdOut: "### Membership: Not Matched\n\n`{ip}` **does not belong to** `{cidr}` ({scope}).", + ipRoleNetwork: "Network address (subnet start)", + ipRoleBroadcast: "Broadcast address (subnet end)", + ipRoleHost: "Host address (offset #{offset})", + ipRoleOutside: "Outside target subnet", + metaTargetIp: "Checked IP", + metaTargetCidr: "Target CIDR", + metaIpRole: "Address Role", + actionCopyMembership: "Copy Membership Summary", + splitPreviewTitle: "Subnet Split Preview: {parts} × /{prefix}", + splitPreviewSub: "{usable} usable [[usable:host|hosts]] each · Enter to copy all", + splitPreviewCannotSub: "Prefix /{prefix} cannot be split into {parts} subnets", + splitDetailMdHeader: "### Subnet Split Preview ({parent} → {parts} × /{prefix})\n\n**{usable}** usable [[usable:host|hosts]] per subnet:\n\n| # | Subnet CIDR | Usable Range | Broadcast / End |\n| :---: | :--- | :--- | :--- |", + splitCannotMd: "### Cannot Split Further\n\n`{parent}` has prefix `/{prefix}`. Splitting into {parts} subnets requires `/{needed}`, exceeding IPv4 `/32`.", + actionCopySplitList: "Copy All {parts} Subnets", + splitBtnLabel: "Split ×{parts}", + splitBtnTitle: "Split into {parts} Subnets", + actionLoadSubnet: "Load Subnet {cidr}", + sectionUmaskResult: "umask Default Permission Conversion", + umaskMainTitle: "umask {umask} → Dir {dir} / File {file}", + umaskMainSub: "Dir {dirSym} · File {fileSym}", + umaskDetailMd: "### umask `{umask}` Default Permission Matrix\n\nNew directories start from `777` → **`{dir}`** (`{dirSym}`); new files start from `666` → **`{file}`** (`{fileSym}`).\n\n#### Directory Permissions (`{dir}` · `{dirSym}`)\n{dirTable}\n\n#### File Permissions (`{file}` · `{fileSym}`)\n{fileTable}\n\n### Terminal Command\n```bash\n{cmd}\n```", + metaDirDefault: "Default Dir Permission", + metaFileDefault: "Default File Permission", + metaImpliedDirUmask: "Implied Dir umask", + metaImpliedFileUmask: "Implied File umask", + metaFileUmaskNa: "Has execute bit (files default without x)", + actionCopyUmaskCmd: "Copy umask Command", + actionCopyDirOctal: "Copy Dir Octal ({octal})", + actionCopyFileOctal: "Copy File Octal ({octal})", + presetUmask022Desc: "Standard system umask (Dir 755 / File 644)", + presetUmask027Desc: "Group-only umask (Dir 750 / File 640)", + presetUmask077Desc: "Strict private umask (Dir 700 / File 600)", + actionViewUmask: "Calculate umask {code}" } } ) diff --git a/extensions/chmod-cidr-calc/src/index.tsx b/extensions/chmod-cidr-calc/src/index.tsx index d3751a46..ea491f57 100644 --- a/extensions/chmod-cidr-calc/src/index.tsx +++ b/extensions/chmod-cidr-calc/src/index.tsx @@ -6,11 +6,20 @@ import React, { Color, useState, useMemo, + useRef, useLocale, getLocale } from '@ztools/declarative-ui' -import type { CalcMode, ChmodRoleBreakdown } from './types.js' -import { calculateIpv4Cidr, convertChmod } from './chmod-cidr-service.js' +import type { CalcMode, ChmodRoleBreakdown, SubnetSplitCount } from './types.js' +import { + calculateIpv4Cidr, + splitIpv4Cidr, + isIpMembershipQuery, + checkIpInCidr, + convertChmod, + isUmaskQuery, + calculateUmask +} from './chmod-cidr-service.js' import { t } from './i18n.js' export * from './types.js' @@ -25,6 +34,8 @@ const PRESET_CIDRS = [ '203.0.113.42/32', ] +const SPLIT_OPTIONS: readonly SubnetSplitCount[] = [2, 4, 8] + function getPresetChmods() { return [ { code: '755', desc: t('preset755Desc') }, @@ -35,6 +46,25 @@ function getPresetChmods() { ] } +function getPresetUmasks() { + return [ + { code: '022', desc: t('presetUmask022Desc') }, + { code: '027', desc: t('presetUmask027Desc') }, + { code: '077', desc: t('presetUmask077Desc') }, + ] +} + +function buildRoleMatrixTable(roles: ChmodRoleBreakdown[]): string { + return `${t('chmodTableHeader')}\n| :--- | :---: | :---: | :---: | :---: | :---: |\n${roles + .map( + (r: ChmodRoleBreakdown) => + `| ${r.role} | \`${r.digit}\` | \`${r.symbolic}\` | ${ + r.read ? t('chmodAllow') : '-' + } | ${r.write ? t('chmodAllow') : '-'} | ${r.execute ? t('chmodAllow') : '-'} |`, + ) + .join('\n')}` +} + /** 常用网段排除与当前计算结果同一网段的项,避免第一行结果和下面的预设重复 */ export function presetCidrsExcluding(networkAddress?: string, prefixLength?: number): string[] { if (!networkAddress || prefixLength === undefined) return PRESET_CIDRS @@ -65,9 +95,36 @@ export function ChmodCidrCalcCommand() { const locale = useLocale() const [mode, setMode] = useState('cidr') const [queryText, setQueryText] = useState('192.168.1.0/24') + const [splitParts, setSplitParts] = useState(4) + const lastQueryByMode = useRef>({ + cidr: '192.168.1.0/24', + chmod: '755', + }) + + const updateQuery = (nextText: string, nextMode?: CalcMode) => { + const targetMode = nextMode ?? mode + setQueryText(nextText) + lastQueryByMode.current[targetMode] = nextText + } + + const membershipQuery = mode === 'cidr' && isIpMembershipQuery(queryText) + const umaskQuery = mode === 'chmod' && isUmaskQuery(queryText) + + const membershipState = useMemo(() => { + if (!membershipQuery) return null + try { + const result = checkIpInCidr(queryText) + return { ok: true as const, result } + } catch (err) { + return { + ok: false as const, + error: err instanceof Error ? err.message : String(err), + } + } + }, [membershipQuery, queryText, locale]) const cidrState = useMemo(() => { - if (mode !== 'cidr') return null + if (mode !== 'cidr' || membershipQuery) return null try { const result = calculateIpv4Cidr(queryText) return { ok: true as const, result } @@ -77,10 +134,36 @@ export function ChmodCidrCalcCommand() { error: err instanceof Error ? err.message : String(err), } } - }, [mode, queryText, locale]) + }, [mode, membershipQuery, queryText, locale]) + + const splitState = useMemo(() => { + if (!cidrState || !cidrState.ok) return null + try { + const result = splitIpv4Cidr(`${cidrState.result.networkAddress}/${cidrState.result.prefixLength}`, splitParts) + return { ok: true as const, result } + } catch (err) { + return { + ok: false as const, + error: err instanceof Error ? err.message : String(err), + } + } + }, [cidrState, splitParts, locale]) + + const umaskState = useMemo(() => { + if (!umaskQuery) return null + try { + const result = calculateUmask(queryText) + return { ok: true as const, result } + } catch (err) { + return { + ok: false as const, + error: err instanceof Error ? err.message : String(err), + } + } + }, [umaskQuery, queryText, locale]) const chmodState = useMemo(() => { - if (mode !== 'chmod') return null + if (mode !== 'chmod' || umaskQuery) return null try { const result = convertChmod(queryText) return { ok: true as const, result } @@ -90,7 +173,23 @@ export function ChmodCidrCalcCommand() { error: err instanceof Error ? err.message : String(err), } } - }, [mode, queryText, locale]) + }, [mode, umaskQuery, queryText, locale]) + + const filterBar = useMemo(() => { + if (mode === 'cidr' && cidrState?.ok) { + return { + actions: SPLIT_OPTIONS.map((parts) => ({ + id: `split-${parts}`, + label: t('splitBtnLabel', { parts }), + title: t('splitBtnTitle', { parts }), + icon: Icon.List, + style: splitParts === parts ? ('primary' as const) : ('secondary' as const), + onAction: () => setSplitParts(parts), + })), + } + } + return undefined + }, [mode, cidrState, splitParts, locale]) return ( { - setQueryText(val) const trimmed = (val || '').trim() + let resolvedMode = mode if (trimmed) { - if (/^chmod(?:[ \t]|$)/.test(trimmed) || /^[0-7]{3,4}$/.test(trimmed) || /^(?:[dlcbps-][rwxstST-]{9}[@+.]?|[rwxstST-]{9})$/.test(trimmed)) { - setMode('chmod') - } else if (trimmed.includes('.') || trimmed.includes('/')) { - setMode('cidr') - + if ( + /^umask(?:\s+|$)/i.test(trimmed) || + /^chmod(?:[ \t]|$)/.test(trimmed) || + /^[0-7]{3,4}$/.test(trimmed) || + /^(?:[dlcbps-][rwxstST-]{9}[@+.]?|[rwxstST-]{9})$/.test(trimmed) + ) { + resolvedMode = 'chmod' + } else if (trimmed.includes('.') || trimmed.includes('/') || isIpMembershipQuery(trimmed)) { + resolvedMode = 'cidr' } } + if (resolvedMode !== mode) { + setMode(resolvedMode) + } + updateQuery(val, resolvedMode) }} searchBarAccessory={ { const nextMode = val as CalcMode + lastQueryByMode.current[mode] = queryText setMode(nextMode) - setQueryText(nextMode === 'cidr' ? '192.168.1.0/24' : '755') + setQueryText(lastQueryByMode.current[nextMode] ?? (nextMode === 'cidr' ? '192.168.1.0/24' : '755')) }} > @@ -128,6 +237,105 @@ export function ChmodCidrCalcCommand() { } > + {mode === 'cidr' && membershipState && !membershipState.ok && ( + + + } + /> + + )} + + {mode === 'cidr' && membershipState && membershipState.ok && ( + + + + + + + + + + } + /> + } + actions={ + + + + + + } + /> + + )} + {mode === 'cidr' && cidrState && !cidrState.ok && ( + } /> + {splitState && ( + + `| ${sub.index} | \`${sub.cidr}\` | \`${sub.firstUsableIp} ~ ${sub.lastUsableIp}\` | \`${sub.broadcastAddress}\` |`, + ) + .join('\n')}` + : t('splitCannotMd', { + parent: `${cidrState.result.networkAddress}/${cidrState.result.prefixLength}`, + prefix: cidrState.result.prefixLength, + parts: splitParts, + needed: cidrState.result.prefixLength + (splitParts === 2 ? 1 : splitParts === 4 ? 2 : 3), + }) + } + /> + } + actions={ + splitState.ok ? ( + + s.cidr).join('\n')} + /> + s.cidr).join('\n')} + shortcut={{ modifiers: ['ctrl'], key: 'return' }} + /> + {SPLIT_OPTIONS.filter((p) => p !== splitParts).map((p) => ( + setSplitParts(p)} + /> + ))} + {splitState.result.subnets.map((sub) => ( + updateQuery(sub.cidr, 'cidr')} + /> + ))} + + ) : undefined + } + /> + )} + {presetCidrsExcluding(cidrState.result.networkAddress, cidrState.result.prefixLength).map((preset: string) => ( setQueryText(preset)} + onAction={() => updateQuery(preset, 'cidr')} /> } @@ -214,6 +510,110 @@ export function ChmodCidrCalcCommand() { )} + {mode === 'chmod' && umaskState && !umaskState.ok && ( + + + } + /> + + )} + + {mode === 'chmod' && umaskState && umaskState.ok && ( + + + + + + } + /> + } + actions={ + + + + + + + } + /> + + {getPresetUmasks() + .filter((item) => `0${item.code}` !== umaskState.result.umask) + .map((item) => ( + + updateQuery(`umask ${item.code}`, 'chmod')} + /> + + } + /> + ))} + + )} + {mode === 'chmod' && chmodState && !chmodState.ok && ( **${chmodState.result.securityWarning}**\n\n` : '' - }${t('chmodTableHeader')}\n| :--- | :---: | :---: | :---: | :---: | :---: |\n${chmodState.result.roles - .map( - (r: ChmodRoleBreakdown) => - `| ${r.role} | \`${r.digit}\` | \`${r.symbolic}\` | ${ - r.read ? t('chmodAllow') : '-' - } | ${r.write ? t('chmodAllow') : '-'} | ${r.execute ? t('chmodAllow') : '-'} |`, - ) - .join('\n')}\n\n${t('chmodCommandsTitle')}\n\`\`\`bash\n${ + }${buildRoleMatrixTable(chmodState.result.roles)}\n\n${t('chmodCommandsTitle')}\n\`\`\`bash\n${ chmodState.result.chmodCommand }\n${chmodState.result.chmodRecursiveCommand}\n\`\`\``} metadata={ - + + + } /> @@ -272,6 +670,11 @@ export function ChmodCidrCalcCommand() { title={t('actionCopyChmodCmd')} content={chmodState.result.chmodCommand} /> + + updateQuery(`umask ${chmodState.result.impliedDirUmask}`, 'chmod')} + /> } /> @@ -298,7 +706,7 @@ export function ChmodCidrCalcCommand() { setQueryText(item.code)} + onAction={() => updateQuery(item.code, 'chmod')} /> } for (const bad of ['rwxr-xr-x@', 'drwxr-xr-x@@', 'drwxr-xr-x#']) assert.throws(() => convertChmod(bad), bad) }) + +test('CIDR 子网拆分:均分 2/4/8 段精确计算,超出 /32 或非法拆分数 Fail-Fast 抛错', () => { + const s4 = splitIpv4Cidr('10.244.0.0/16', 4) + assert.equal(s4.childPrefixLength, 18) + assert.equal(s4.usableHostsPerSubnet, 16382) + assert.deepEqual( + s4.subnets.map((s) => s.cidr), + ['10.244.0.0/18', '10.244.64.0/18', '10.244.128.0/18', '10.244.192.0/18'] + ) + + const s2 = splitIpv4Cidr('192.168.1.50/24', 2) + assert.deepEqual(s2.subnets.map((s) => s.cidr), ['192.168.1.0/25', '192.168.1.128/25']) + + const s31 = splitIpv4Cidr('10.0.0.0/31', 2) + assert.deepEqual(s31.subnets.map((s) => s.cidr), ['10.0.0.0/32', '10.0.0.1/32']) + + assert.throws(() => splitIpv4Cidr('10.0.0.1/32', 2), /\/32/) + assert.throws(() => splitIpv4Cidr('10.0.0.0/31', 4), /\/32/) + assert.throws(() => splitIpv4Cidr('10.0.0.0/24', 3), /2、4 或 8/) +}) + +test('IP 归属检测:准确判定属于/不属于、网络地址/广播地址与偏移量,非法格式抛错', () => { + assert.equal(isIpMembershipQuery('192.168.1.50 in 192.168.1.0/26'), true) + assert.equal(isIpMembershipQuery('192.168.1.0/24'), false) + + const hit = checkIpInCidr('192.168.1.50 in 192.168.1.0/26') + assert.equal(hit.isMember, true) + assert.equal(hit.isNetworkAddress, false) + assert.equal(hit.isBroadcastAddress, false) + assert.equal(hit.offsetInSubnet, 50) + + const net = checkIpInCidr('192.168.1.0 in 192.168.1.0/26') + assert.equal(net.isMember, true) + assert.equal(net.isNetworkAddress, true) + + const bcast = checkIpInCidr('192.168.1.63 in 192.168.1.0/26') + assert.equal(bcast.isMember, true) + assert.equal(bcast.isBroadcastAddress, true) + + const miss = checkIpInCidr('192.168.1.100 in 192.168.1.0/26') + assert.equal(miss.isMember, false) + assert.equal(miss.offsetInSubnet, undefined) + + for (const bad of ['192.168.1.1', '999.1.1.1 in 192.168.1.0/24', '192.168.1.1 in 192.168.1.0/33']) { + assert.throws(() => checkIpInCidr(bad), bad) + } +}) + +test('umask 换算与 chmod 反向 umask 推演准确,非法 umask 抛错', () => { + assert.equal(isUmaskQuery('umask 022'), true) + assert.equal(isUmaskQuery('755'), false) + + const u022 = calculateUmask('umask 022') + assert.equal(u022.umask, '0022') + assert.equal(u022.dirOctal, '755') + assert.equal(u022.dirSymbolic, 'rwxr-xr-x') + assert.equal(u022.fileOctal, '644') + assert.equal(u022.fileSymbolic, 'rw-r--r--') + + const u027 = calculateUmask('umask 0027') + assert.equal(u027.dirOctal, '750') + assert.equal(u027.fileOctal, '640') + + const u077 = calculateUmask('umask 077') + assert.equal(u077.dirOctal, '700') + assert.equal(u077.fileOctal, '600') + + assert.equal(convertChmod('755').impliedDirUmask, '022') + assert.equal(convertChmod('755').impliedFileUmask, undefined) + assert.equal(convertChmod('644').impliedFileUmask, '022') + + for (const bad of ['umask', 'umask ', 'umask 888', 'umask 1022', 'umask abc']) { + assert.throws(() => calculateUmask(bad), bad) + } +}) diff --git a/extensions/chmod-cidr-calc/tests/command.test.mjs b/extensions/chmod-cidr-calc/tests/command.test.mjs index e9e1b475..0936c837 100644 --- a/extensions/chmod-cidr-calc/tests/command.test.mjs +++ b/extensions/chmod-cidr-calc/tests/command.test.mjs @@ -108,3 +108,52 @@ test('常用网段与常用权限不重复第一行的当前结果', async () => assert.equal(presetChmodsExcluding('').length, 5) assert.equal(presetCidrsExcluding(undefined, undefined).length, 6) }) + +test('CIDR 子网拆分预览、IP 归属判断、umask 换算与模式记忆闭环', async () => { + const { setRuntimeLocale } = await import('@ztools/declarative-ui') + const { tick } = await import('../../shared/test-harness.mjs') + setRuntimeLocale('zh-CN') + const host = createHost(), view = await mount(ChmodCidrCalcCommand, host) + try { + // 1. 子网拆分预览与复制 + await view.search('10.244.0.0/16') + const splitItem = view.item('cidr-subnet-split') + assert.match(splitItem.props.title, /4 × \/18/) + assert.match(splitItem.props.detail.props.markdown, /10\.244\.192\.0\/18/) + await view.run(splitItem, '复制全部 4 个子网') + assert.equal( + host.clipboard.text, + '10.244.0.0/18\n10.244.64.0/18\n10.244.128.0/18\n10.244.192.0/18' + ) + + // 2. IP 归属判断 + await view.search('192.168.1.50 in 192.168.1.0/26') + const memHit = view.item('ip-membership-main') + assert.equal(memHit.props.accessories[0].tag, '属于该网段') + await view.search('192.168.1.100 in 192.168.1.0/26') + assert.equal(view.item('ip-membership-main').props.accessories[0].tag.value, '不在网段内') + + // 3. umask 换算与直观 r/w/x 权限矩阵右栏 Detail + await view.search('umask 022') + const umaskItem = view.item('umask-main') + assert.match(umaskItem.props.title, /755.*644/) + assert.match(umaskItem.props.detail.props.markdown, /Owner \(u\).*rwx/) + assert.match(umaskItem.props.detail.props.markdown, /rw-/) + await view.run(umaskItem, '复制 umask 命令') + assert.equal(host.clipboard.text, 'umask 0022') + + // 4. 切换下拉框记忆上次输入 + await view.dropdown('cidr') + assert.equal(view.tree().props.searchText, '192.168.1.100 in 192.168.1.0/26') + await view.dropdown('chmod') + assert.equal(view.tree().props.searchText, 'umask 022') + + // 5. en-US 无中文残留 + setRuntimeLocale('en-US') + await tick() + assert.ok(!/[\u4e00-\u9fa5]/.test(view.text()), `en-US 不应含中文: ${view.text()}`) + setRuntimeLocale('zh-CN') + } finally { + view.unmount() + } +}) diff --git a/extensions/color-picker/package.json b/extensions/color-picker/package.json index 3ed60fe5..53483038 100644 --- a/extensions/color-picker/package.json +++ b/extensions/color-picker/package.json @@ -1,6 +1,6 @@ { "name": "color-picker", - "version": "2.1.3", + "version": "2.1.9", "description": "HEX/RGB/HSL/CMYK 双向换算与 WCAG 对比度", "type": "module", "main": "dist/index.js", diff --git a/extensions/color-picker/plugin.json b/extensions/color-picker/plugin.json index fdffb5b8..a4581405 100644 --- a/extensions/color-picker/plugin.json +++ b/extensions/color-picker/plugin.json @@ -1,7 +1,7 @@ { "id": "color-picker", "name": "取色与配色", - "version": "2.1.8", + "version": "2.1.9", "description": "支持 HEX / RGB / HSL / CMYK 色值实时互转、WCAG 无障碍对比度检测与常用色板收藏", "author": "ZTools Team", "entry": "dist/index.js", diff --git a/extensions/color-picker/src/converter.ts b/extensions/color-picker/src/converter.ts index 0cb2b03e..7d0e0f8f 100644 --- a/extensions/color-picker/src/converter.ts +++ b/extensions/color-picker/src/converter.ts @@ -1,25 +1,37 @@ -import { LocalStorage, getLocale } from "@ztools/declarative-ui"; +import { LocalStorage, getDeclarativeBridge, getLocale } from "@ztools/declarative-ui"; const CONVERTER_MESSAGES: Record = { "zh-CN": { paletteCorrupted: "调色板数据损坏,原数据已保留,请先恢复数据后重试", + historyCorrupted: "取色历史数据损坏,原数据已保留", upgradeZtoolsPalette: "请升级 ZTools 以安全保存调色板", paletteLimitExceeded: "调色板最多保存 100 个颜色,请先删除一些", previewLargeText: "大字 Aa 24px", - previewBodyText: "正文示例 The quick brown fox 0123" + previewBodyText: "正文示例 The quick brown fox 0123", + errScreenRecordingPerm: "需要开启屏幕录制权限才能使用屏幕吸管取色", + errScreenPickerUnavailable: "当前平台或环境暂不支持屏幕吸管取色", + errColorPickerFailed: "无法从宿主获取屏幕像素颜色" }, "en-US": { paletteCorrupted: "Palette data is corrupted; original data was preserved. Please restore it before retrying.", + historyCorrupted: "Pick history data is corrupted; original data was preserved.", upgradeZtoolsPalette: "Please upgrade ZTools to safely save palettes", paletteLimitExceeded: "Palette can store up to 100 colors; please remove some first", previewLargeText: "Large Aa 24px", - previewBodyText: "Body sample The quick brown fox 0123" + previewBodyText: "Body sample The quick brown fox 0123", + errScreenRecordingPerm: "Screen Recording permission is required to pick screen colors", + errScreenPickerUnavailable: "Screen eyedropper is not available in this environment", + errColorPickerFailed: "Failed to read screen pixel color from host" } }; @@ -718,3 +730,464 @@ export function generateContrastPreviewSvg(foregroundHex: string, backgroundHex: `; return `data:image/svg+xml;utf8,${encodeURIComponent(svg).replace(/\(/g, "%28").replace(/\)/g, "%29")}`; } + +export interface ColorScaleStep { + step: 50 | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 | 950; + hex: string; +} + +const SCALE_STOPS: ReadonlyArray<{ step: ColorScaleStep["step"]; targetL: number; chromaFactor: number }> = [ + { step: 50, targetL: 0.97, chromaFactor: 0.16 }, + { step: 100, targetL: 0.93, chromaFactor: 0.30 }, + { step: 200, targetL: 0.86, chromaFactor: 0.50 }, + { step: 300, targetL: 0.77, chromaFactor: 0.72 }, + { step: 400, targetL: 0.68, chromaFactor: 0.90 }, + { step: 500, targetL: 0.60, chromaFactor: 1.0 }, + { step: 600, targetL: 0.52, chromaFactor: 0.96 }, + { step: 700, targetL: 0.44, chromaFactor: 0.86 }, + { step: 800, targetL: 0.36, chromaFactor: 0.72 }, + { step: 900, targetL: 0.28, chromaFactor: 0.58 }, + { step: 950, targetL: 0.20, chromaFactor: 0.44 } +]; + +/** + * 基于 OKLCH 亮度曲线生成 50–950 11 级色阶(500 精确保留原色 HEX) + */ +export function generateColorScale(rgb: RGB): ColorScaleStep[] { + const baseHex = rgbToHex(rgb); + const oklch = rgbToOklch(rgb); + const baseC = oklch.c; + const baseH = oklch.h; + + return SCALE_STOPS.map(({ step, targetL, chromaFactor }) => { + if (step === 500) { + return { step, hex: baseHex }; + } + const { rgb: stepRgb } = oklchToRgb(targetL, baseC * chromaFactor, baseH); + return { step, hex: rgbToHex(stepRgb) }; + }); +} + +/** + * 生成完整 50–950 CSS 变量代码块 + */ +export function generateCssScaleVariables(color: ColorConversionResult, scale?: ColorScaleStep[]): string { + const steps = scale ?? generateColorScale(color.rgb); + const baseValue = color.hasAlpha ? color.hex8 : color.hex; + const lines = [ + ":root {", + ` --color-primary: ${baseValue};`, + ...steps.map((s) => ` --color-primary-${s.step}: ${s.hex};`), + "}" + ]; + return lines.join("\n"); +} + +/** + * 当对比度未达目标标准(默认 WCAG AA 4.5:1)时,沿亮度方向寻找最接近的合规色 + */ +export function suggestAccessibleColor( + fg: RGB, + bg: RGB, + targetRatio = 4.5 +): { hex: string; ratio: number } | null { + if (calculateContrast(fg, bg) >= targetRatio) return null; + const bgLum = getLuminance(bg); + const hsl = rgbToHsl(fg); + // 背景偏亮则往暗处找,背景偏暗则往亮处找 + const step = bgLum > 0.5 ? -1 : 1; + for (let l = hsl.l; l >= 0 && l <= 100; l += step) { + const candidate = hslToRgb({ h: hsl.h, s: hsl.s, l }); + const ratio = calculateContrast(candidate, bg); + if (ratio >= targetRatio) { + return { hex: rgbToHex(candidate), ratio }; + } + } + const fallback: RGB = bgLum > 0.5 ? { r: 0, g: 0, b: 0 } : { r: 255, g: 255, b: 255 }; + return { hex: rgbToHex(fallback), ratio: calculateContrast(fallback, bg) }; +} + +export interface PickedColorResult { + hex: string; + rgb: RGB; + hsl: HSL; + hsv: HSV; + x: number; + y: number; + source: "native"; + pickedAt: number; +} + +interface RawColorPayload { + permissionDenied?: boolean; + cancelled?: boolean; + canceled?: boolean; + error?: string; + ok?: boolean; + hex?: unknown; + color?: unknown; + r?: unknown; + g?: unknown; + b?: unknown; + rgb?: { r?: unknown; g?: unknown; b?: unknown }; + x?: unknown; + y?: unknown; +} + +interface TransportResponse { + ok: boolean; + data?: RawColorPayload; + error?: string; + errorCode?: string; +} + +type TransportMethodFn = (payload: unknown) => Promise; + +interface HostTransportOverride { + transport?: { + call?: (method: string, params: Record) => Promise; + methods?: Record; + }; + [method: string]: unknown; +} + +let hostIpcSeq = 1; + +function nextIpcMessageId(method: string): string { + hostIpcSeq = (hostIpcSeq + 1) % 1_000_000; + return `${method.replace(/[^A-Za-z0-9_]/g, "_").slice(0, 24)}_${Date.now()}_${hostIpcSeq}`; +} + +function asColorPayload(value: unknown): RawColorPayload | undefined { + return value && typeof value === "object" && !Array.isArray(value) + ? (value as RawColorPayload) + : undefined; +} + +function unwrapTransportPayload(raw: unknown): TransportResponse { + if (raw === null || raw === undefined) { + return { ok: false, error: "EMPTY_IPC_RESPONSE", errorCode: "EMPTY_IPC_RESPONSE" }; + } + if (typeof raw !== "object" || Array.isArray(raw)) { + return { ok: true, data: { hex: raw } }; + } + const rec = raw as Record; + if (rec.success === false) { + const errObj = rec.error as { message?: unknown; code?: unknown } | string | undefined; + const errMsg = + typeof errObj === "object" && errObj !== null + ? String(errObj.message || errObj.code || "IPC_CALL_FAILED") + : String(errObj || "IPC_CALL_FAILED"); + const errorCode = + typeof rec.errorCode === "string" + ? rec.errorCode + : typeof errObj === "object" && errObj !== null && typeof errObj.code === "string" + ? errObj.code + : undefined; + return { ok: false, error: errMsg, ...(errorCode ? { errorCode } : {}) }; + } + const firstLayer = "data" in rec && rec.data !== undefined ? rec.data : rec; + if (firstLayer && typeof firstLayer === "object" && !Array.isArray(firstLayer)) { + const inner = firstLayer as Record; + if (inner.success === false) { + const errObj = inner.error as { message?: unknown; code?: unknown } | string | undefined; + const errMsg = + typeof errObj === "object" && errObj !== null + ? String(errObj.message || errObj.code || "IPC_INNER_FAILED") + : String(errObj || "IPC_INNER_FAILED"); + return { ok: false, error: errMsg }; + } + if ("data" in inner && inner.data !== undefined) { + return { ok: true, data: asColorPayload(inner.data) }; + } + return { ok: true, data: asColorPayload(inner) }; + } + return { ok: true, data: asColorPayload(firstLayer) }; +} + +function getWindowTransport(): { + methods?: Record; + call?: (method: string, params: Record) => Promise; +} | null { + if (typeof window === "undefined") return null; + const w = window as unknown as { + __ztoolsElectron?: { transport?: { methods?: Record } }; + ztools?: { + transport?: { + methods?: Record; + call?: (method: string, params: Record) => Promise; + }; + }; + }; + const methods = w.__ztoolsElectron?.transport?.methods || w.ztools?.transport?.methods; + const call = w.ztools?.transport?.call; + if (!methods && typeof call !== "function") return null; + return { methods, call }; +} + +async function callScreenTransport( + method: string, + params: Record, + hostOverride?: HostTransportOverride +): Promise { + if (hostOverride) { + const directFn = hostOverride[method]; + if (typeof directFn === "function") { + try { + const res = await (directFn as TransportMethodFn)(params); + return unwrapTransportPayload(res); + } catch (err: unknown) { + return { ok: false, error: err instanceof Error ? err.message : String(err) }; + } + } + if (typeof hostOverride.transport?.call === "function") { + try { + const res = await hostOverride.transport.call(method, params); + return unwrapTransportPayload(res); + } catch (err: unknown) { + return { ok: false, error: err instanceof Error ? err.message : String(err) }; + } + } + return { ok: false, error: `METHOD_NOT_AVAILABLE: ${method}`, errorCode: "METHOD_NOT_AVAILABLE" }; + } + + const transport = getWindowTransport(); + if (!transport) { + return { ok: false, error: `METHOD_NOT_AVAILABLE: ${method}`, errorCode: "METHOD_NOT_AVAILABLE" }; + } + const fn = transport.methods?.[method]; + if (typeof fn === "function") { + try { + const res = await fn({ messageId: nextIpcMessageId(method), params }); + return unwrapTransportPayload(res); + } catch (err: unknown) { + return { ok: false, error: err instanceof Error ? err.message : String(err) }; + } + } + if (typeof transport.call === "function") { + try { + const res = await transport.call(method, params); + return unwrapTransportPayload(res); + } catch (err: unknown) { + return { ok: false, error: err instanceof Error ? err.message : String(err) }; + } + } + return { ok: false, error: `METHOD_NOT_AVAILABLE: ${method}`, errorCode: "METHOD_NOT_AVAILABLE" }; +} + +export function isScreenRecordingPermissionError(err: unknown, data?: RawColorPayload): boolean { + if (data?.permissionDenied) return true; + const rec = + err && typeof err === "object" + ? (err as { code?: unknown; errorCode?: unknown; details?: { hostCode?: unknown } }) + : null; + const code = typeof rec?.errorCode === "string" ? rec.errorCode : typeof rec?.code === "string" ? rec.code : ""; + const hostCode = typeof rec?.details?.hostCode === "string" ? rec.details.hostCode : ""; + if ( + code === "SCREEN_RECORDING_PERMISSION_DENIED" || + hostCode === "SCREEN_RECORDING_PERMISSION_DENIED" || + code === "PERMISSION_DENIED" + ) { + return true; + } + const errText = err instanceof Error ? err.message : typeof err === "string" ? err : ""; + if ( + errText.includes("SCREEN_RECORDING") || + errText.includes("TCC") || + errText.includes("Screen Recording") + ) { + return true; + } + if (!code && !hostCode) { + // i18n-allow: legacy host fallback + return errText.includes("屏幕录制"); + } + return false; +} + +function throwIfPermissionError(errText: string, data?: RawColorPayload): void { + if (isScreenRecordingPermissionError(errText, data)) { + const permErr = new Error(converterStrings().errScreenRecordingPerm) as Error & { code?: string }; + permErr.code = "SCREEN_RECORDING_PERMISSION_DENIED"; + throw permErr; + } +} + +function createAbortError(): Error { + const err = new Error("Screen color pick cancelled"); + err.name = "AbortError"; + return err; +} + +function buildPickedColorResultFromRaw( + raw: unknown, + fallbackX = 0, + fallbackY = 0 +): PickedColorResult | null { + if (!raw) return null; + if (typeof raw === "string" && raw.trim()) { + const parsed = parseColor(raw.trim()); + if (parsed.isValid) { + return { + hex: parsed.hex, + rgb: { r: parsed.rgb.r, g: parsed.rgb.g, b: parsed.rgb.b }, + hsl: parsed.hsl, + hsv: parsed.hsv, + x: fallbackX, + y: fallbackY, + source: "native", + pickedAt: Date.now() + }; + } + } + const obj = asColorPayload(raw); + if (!obj) return null; + let hexStr = typeof obj.hex === "string" ? obj.hex : typeof obj.color === "string" ? obj.color : ""; + if (!hexStr && typeof obj.r === "number" && typeof obj.g === "number" && typeof obj.b === "number") { + hexStr = rgbToHex({ r: obj.r, g: obj.g, b: obj.b }); + } else if ( + !hexStr && + obj.rgb && + typeof obj.rgb.r === "number" && + typeof obj.rgb.g === "number" && + typeof obj.rgb.b === "number" + ) { + hexStr = rgbToHex({ r: obj.rgb.r, g: obj.rgb.g, b: obj.rgb.b }); + } + if (!hexStr) return null; + const parsed = parseColor(hexStr); + if (!parsed.isValid) return null; + return { + hex: parsed.hex, + rgb: { r: parsed.rgb.r, g: parsed.rgb.g, b: parsed.rgb.b }, + hsl: parsed.hsl, + hsv: parsed.hsv, + x: typeof obj.x === "number" ? obj.x : fallbackX, + y: typeof obj.y === "number" ? obj.y : fallbackY, + source: "native", + pickedAt: Date.now() + }; +} + +/** + * 真实屏幕吸管取色(Win/macOS 双端统一,彻底移除 simulated 假色值): + * 1. 优先调用宿主 Declarative Bridge 的 pickScreenColor(原生像素放大镜吸管) + * 2. 其次走真实 Electron Transport:screen_get_cursor_pos + ColorPickerPlugin.pickScreenPixel / screen_pick_color / screen_capture + * 3. 当前环境不支持时诚实抛出 SCREEN_PICKER_UNAVAILABLE,绝不造假色值 + */ +export async function pickScreenColor(hostOverride?: unknown): Promise { + const override = hostOverride && typeof hostOverride === "object" ? (hostOverride as HostTransportOverride) : undefined; + const bridge = getDeclarativeBridge() as { pickScreenColor?: () => Promise } | undefined; + + if (!override && bridge && typeof bridge.pickScreenColor === "function") { + const res = await bridge.pickScreenColor(); + const resObj = asColorPayload(res); + if (resObj?.cancelled || resObj?.canceled) { + throw createAbortError(); + } + throwIfPermissionError(String(resObj?.error || ""), resObj); + const picked = buildPickedColorResultFromRaw(res); + if (picked) return picked; + throw new Error(String(resObj?.error || converterStrings().errColorPickerFailed)); + } + + const hasTransport = Boolean(override || getWindowTransport()); + if (!hasTransport) { + const unavailable = new Error(converterStrings().errScreenPickerUnavailable) as Error & { code?: string }; + unavailable.code = "SCREEN_PICKER_UNAVAILABLE"; + throw unavailable; + } + + const cursorRes = await callScreenTransport("screen_get_cursor_pos", {}, override); + const cursorX = typeof cursorRes.data?.x === "number" ? cursorRes.data.x : 0; + const cursorY = typeof cursorRes.data?.y === "number" ? cursorRes.data.y : 0; + + const dllRes = await callScreenTransport( + "dllplugin_call", + { plugin: "ColorPickerPlugin", func: "pickScreenPixel", params: { x: cursorX, y: cursorY } }, + override + ); + throwIfPermissionError(String(dllRes.error || dllRes.data?.error || ""), dllRes.data); + if (dllRes.ok && dllRes.data?.ok !== false) { + const picked = buildPickedColorResultFromRaw(dllRes.data, cursorX, cursorY); + if (picked) return picked; + } + + const pickRes = await callScreenTransport("screen_pick_color", { x: cursorX, y: cursorY }, override); + throwIfPermissionError(String(pickRes.error || pickRes.data?.error || ""), pickRes.data); + if (pickRes.ok && pickRes.data?.ok !== false) { + const picked = buildPickedColorResultFromRaw(pickRes.data, cursorX, cursorY); + if (picked) return picked; + } + + const capRes = await callScreenTransport( + "screen_capture", + { mode: "color", x: cursorX, y: cursorY }, + override + ); + throwIfPermissionError(String(capRes.error || capRes.data?.error || ""), capRes.data); + if (capRes.ok && capRes.data?.ok !== false) { + const picked = buildPickedColorResultFromRaw(capRes.data, cursorX, cursorY); + if (picked) return picked; + } + + const allUnavailable = + dllRes.errorCode === "METHOD_NOT_AVAILABLE" && + pickRes.errorCode === "METHOD_NOT_AVAILABLE" && + capRes.errorCode === "METHOD_NOT_AVAILABLE"; + + if (allUnavailable) { + const unavailable = new Error(converterStrings().errScreenPickerUnavailable) as Error & { code?: string }; + unavailable.code = "SCREEN_PICKER_UNAVAILABLE"; + throw unavailable; + } + + const errMsg = dllRes.error || pickRes.error || capRes.error || converterStrings().errColorPickerFailed; + throw new Error(errMsg); +} + +const HISTORY_STORAGE_KEY = "color_picker_history"; + +function sanitizeHistory(list: unknown): PickedColorResult[] { + if (list === undefined || list === null) return []; + if ( + !Array.isArray(list) || + list.some( + (item) => + !item || + typeof item !== "object" || + typeof (item as PickedColorResult).hex !== "string" || + !/^#[0-9A-Fa-f]{6}(?:[0-9A-Fa-f]{2})?$/.test((item as PickedColorResult).hex) + ) + ) { + throw new Error(converterStrings().historyCorrupted); + } + return list as PickedColorResult[]; +} + +export async function getColorHistory(): Promise { + return sanitizeHistory(await LocalStorage.getItem(HISTORY_STORAGE_KEY)); +} + +export async function saveColorHistory(item: PickedColorResult): Promise { + const normalizedHex = paletteHex(item.hex); + const entry: PickedColorResult = { ...item, hex: normalizedHex, source: "native" }; + if (typeof LocalStorage.updateItem === "function") { + return LocalStorage.updateItem(HISTORY_STORAGE_KEY, (raw) => { + const current = sanitizeHistory(raw); + return [entry, ...current.filter((c) => c.hex !== normalizedHex)].slice(0, 30); + }); + } + const current = await getColorHistory(); + const updated = [entry, ...current.filter((c) => c.hex !== normalizedHex)].slice(0, 30); + await LocalStorage.setItem(HISTORY_STORAGE_KEY, updated); + return updated; +} + +export async function clearColorHistory(): Promise { + if (typeof LocalStorage.updateItem === "function") { + await LocalStorage.updateItem(HISTORY_STORAGE_KEY, () => []); + return; + } + await LocalStorage.removeItem(HISTORY_STORAGE_KEY); +} diff --git a/extensions/color-picker/src/i18n.ts b/extensions/color-picker/src/i18n.ts index 81c67848..6ab4a019 100644 --- a/extensions/color-picker/src/i18n.ts +++ b/extensions/color-picker/src/i18n.ts @@ -7,16 +7,22 @@ const rawT = createTranslator( detailWhiteContrast: "**白字对比度** {ratio}:1({rating})", detailBlackContrast: "**黑字对比度** {ratio}:1({rating})", detailRecommendedText: "**推荐文字颜色** {color}", + detailScaleTitle: "**50–950 色阶**", + detailCssVarsTitle: "**CSS 变量(动作面板可一键复制完整色阶)**", + detailHarmonyTitle: "**配色方案**", + detailSuggestedAA: "**白底 AA 推荐色** `{hex}`(对比度 {ratio}:1)", colorWhite: "白色", colorBlack: "黑色", harmonyComplementary: "- 互补色 `{val}`", harmonyAnalogous: "- 类似色 `{val}`", harmonyTriadic: "- 三色配色 `{val}`", harmonyMonochromatic: "- 单色渐变 `{val}`", - usageTitle: "**支持的写法**", + usageTitle: "**屏幕取色与色值解析**", + usageBody: "点击上方「屏幕取色」拾取屏幕任意像素,或「读剪贴板」快速导入,也可以直接输入以下任意格式:", usageNamed: "- 颜色英文名,例如 `orange`", - paletteEmptyMd: "在任一写法上打开动作面板,选「收藏到调色板」即可保存常用颜色。", + paletteEmptyMd: "在任一色值上打开动作面板,选「收藏到调色板」即可保存常用颜色。", readPaletteFailed: "读取调色板失败", + readHistoryFailed: "读取取色历史失败", copiedToast: "已复制 {val}", savedToast: "已收藏 {hex}", saveFailed: "收藏失败", @@ -31,20 +37,42 @@ const rawT = createTranslator( clearConfirmBtn: "清空", clearedToast: "已清空调色板", clearFailed: "清空失败", + clearHistoryConfirmTitle: "清空 {count} 条取色历史?", + clearHistoryConfirmMsg: "清空后无法恢复。", + clearHistoryConfirmBtn: "清空", + clearedHistoryToast: "已清空取色历史", + clearHistoryFailed: "清空历史失败", fmtHex8: "HEX(含透明度)", fmtTailwind: "Tailwind 任意值", fmtCssVar: "CSS 变量", + fmtCssScaleVars: "CSS 色阶变量(50–950)", sectionFormatsOutOfGamut: "{hex} 的各种写法(超出 sRGB 色域,已按最接近的颜色换算)", sectionFormats: "{hex} 的各种写法(按回车复制)", copyAction: "复制", + copyCssScaleAction: "复制 50–950 CSS 变量", saveToPaletteAction: "收藏到调色板", pasteToActiveAction: "粘贴到当前应用", + pickScreenAction: "屏幕取色", + readClipboardAction: "读剪贴板", + clearHistoryAction: "清空历史", + pickSuccessToast: "已取色 {hex} 并复制", + pickCoordDesc: "屏幕坐标 ({x}, {y})", + pickFailedTitle: "屏幕取色失败", + pickPermTitle: "需要屏幕录制权限", + pickPermMsg: "请在「系统设置 → 隐私与安全性 → 屏幕录制」中允许 ZTools 后重试", + pickUnavailableMsg: "当前平台或环境暂不支持屏幕吸管取色,请手动输入或从剪贴板读取色值", + clipboardEmptyToast: "剪贴板为空", + clipboardInvalidToast: "剪贴板内容不是有效色值", + clipboardLoadedToast: "已从剪贴板识别 {hex}", + clipboardReadFailed: "读取剪贴板失败", + sectionHistoryCount: "取色历史({count})", + historyCoordSub: "{rgb} · 坐标 ({x}, {y})", sectionInvalid: "无法识别", invalidTitle: "无法识别「{input}」", invalidSub: "支持 #RGB、#RRGGBB、#RRGGBBAA、rgb()、hsl()、hsv()、oklch()、cmyk()、颜色英文名", - sectionStart: "开始", - hintTitle: "在上方输入颜色", - hintSub: "例如 #0A84FF、rgb(10, 132, 255)、hsl(210, 100%, 52%)、orange", + sectionStart: "开始取色或输入色值", + hintTitle: "点击「屏幕取色」或在上方输入颜色", + hintSub: "支持 #0A84FF、rgb(10, 132, 255)、hsl(210, 100%, 52%)、oklch(...)、orange", sectionPaletteCount: "调色板({count})", copyHexAction: "复制 HEX", viewFormatsAction: "查看各种写法", @@ -53,8 +81,10 @@ const rawT = createTranslator( sectionPalette: "调色板", paletteEmptyTitle: "调色板还是空的", paletteEmptySub: "在上面任一写法上按 {mod}+Enter 收藏到调色板", + summaryEmpty: "输入色值或点击右侧「屏幕取色」", + summaryCounts: "历史 {history} 条 · 收藏 {palette} 色", navTitle: "调色板与色彩转换", - searchPlaceholder: "输入颜色:#0A84FF、rgb(10, 132, 255)、hsl(210, 100%, 52%)…", + searchPlaceholder: "输入颜色:#0A84FF、rgb(10, 132, 255)、oklch(...) 或点击屏幕取色…", ratingAAA: "AAA 通过", ratingAA: "AA 通过", ratingAALarge: "仅大字 AA 通过", @@ -66,6 +96,8 @@ const rawT = createTranslator( contrastBodyAAA: "- 正文 AAA(≥ 7:1):{status}", contrastLargeAA: "- 大字 AA(≥ 3:1,18pt 或 14pt 粗体以上):{status}", contrastLargeAAA: "- 大字 AAA(≥ 4.5:1):{status}", + contrastSuggestedMd: "**推荐合规前景色(AA)**:`{hex}`(对比度 {ratio}:1)", + copySuggestedAction: "复制推荐合规色 {hex}", contrastAlphaNote: "> 含透明度的颜色按不透明颜色计算。", contrastColorsNote: "前景色 `{fg}`,背景色 `{bg}`", contrastUsageLine1: "**输入两种颜色**:前景色(文字)在前,背景色在后,用空格分隔。", @@ -92,16 +124,22 @@ const rawT = createTranslator( detailWhiteContrast: "**White Text Contrast** {ratio}:1 ({rating})", detailBlackContrast: "**Black Text Contrast** {ratio}:1 ({rating})", detailRecommendedText: "**Recommended Text** {color}", + detailScaleTitle: "**50–950 Color Scale**", + detailCssVarsTitle: "**CSS Variables (Copy full scale from Action Panel)**", + detailHarmonyTitle: "**Color Harmonies**", + detailSuggestedAA: "**Suggested AA Color on White** `{hex}` ({ratio}:1)", colorWhite: "White", colorBlack: "Black", harmonyComplementary: "- Complementary `{val}`", harmonyAnalogous: "- Analogous `{val}`", harmonyTriadic: "- Triadic `{val}`", harmonyMonochromatic: "- Monochromatic `{val}`", - usageTitle: "**Supported Formats**", + usageTitle: "**Screen Eyedropper & Color Parser**", + usageBody: "Click \"Pick Screen Color\" to sample any pixel on screen, click \"Read Clipboard\" to import, or enter any supported format:", usageNamed: "- Named CSS colors, e.g. `orange`", paletteEmptyMd: "Open the action panel on any format and select \"Save to Palette\" to keep favorite colors.", readPaletteFailed: "Failed to load palette", + readHistoryFailed: "Failed to load pick history", copiedToast: "Copied {val}", savedToast: "Saved {hex}", saveFailed: "Failed to save", @@ -116,20 +154,42 @@ const rawT = createTranslator( clearConfirmBtn: "Clear", clearedToast: "Palette cleared", clearFailed: "Failed to clear palette", + clearHistoryConfirmTitle: "Clear {count} picked color(s) from history?", + clearHistoryConfirmMsg: "This cannot be undone.", + clearHistoryConfirmBtn: "Clear", + clearedHistoryToast: "Pick history cleared", + clearHistoryFailed: "Failed to clear pick history", fmtHex8: "HEX (with Alpha)", fmtTailwind: "Tailwind Arbitrary", fmtCssVar: "CSS Variable", + fmtCssScaleVars: "CSS Scale Variables (50–950)", sectionFormatsOutOfGamut: "Formats for {hex} (clipped to sRGB gamut)", sectionFormats: "Formats for {hex} (Press Enter to copy)", copyAction: "Copy", + copyCssScaleAction: "Copy 50–950 CSS Variables", saveToPaletteAction: "Save to Palette", pasteToActiveAction: "Paste to Active App", + pickScreenAction: "Pick Screen Color", + readClipboardAction: "Read Clipboard", + clearHistoryAction: "Clear History", + pickSuccessToast: "Picked {hex} and copied", + pickCoordDesc: "Coordinates ({x}, {y})", + pickFailedTitle: "Screen color pick failed", + pickPermTitle: "Screen Recording Permission Required", + pickPermMsg: "Enable Screen Recording for ZTools in System Settings > Privacy & Security and retry", + pickUnavailableMsg: "Screen eyedropper is not available in this environment; enter a color or read from clipboard instead", + clipboardEmptyToast: "Clipboard is empty", + clipboardInvalidToast: "Clipboard text is not a valid color", + clipboardLoadedToast: "Loaded {hex} from clipboard", + clipboardReadFailed: "Failed to read clipboard", + sectionHistoryCount: "Pick History ({count})", + historyCoordSub: "{rgb} · ({x}, {y})", sectionInvalid: "Unrecognized Color", invalidTitle: "Cannot recognize \"{input}\"", invalidSub: "Supports #RGB, #RRGGBB, #RRGGBBAA, rgb(), hsl(), hsv(), oklch(), cmyk(), and CSS color names", sectionStart: "Get Started", - hintTitle: "Enter a color above", - hintSub: "e.g. #0A84FF, rgb(10, 132, 255), hsl(210, 100%, 52%), orange", + hintTitle: "Click \"Pick Screen Color\" or enter a color above", + hintSub: "Supports #0A84FF, rgb(10, 132, 255), hsl(210, 100%, 52%), oklch(...), orange", sectionPaletteCount: "Palette ({count})", copyHexAction: "Copy HEX", viewFormatsAction: "Inspect All Formats", @@ -138,8 +198,10 @@ const rawT = createTranslator( sectionPalette: "Palette", paletteEmptyTitle: "Palette is empty", paletteEmptySub: "Press {mod}+Enter on any format above to save to palette", + summaryEmpty: "Enter a color or click \"Pick Screen Color\"", + summaryCounts: "{history} picked · {palette} saved", navTitle: "Color Converter & Palette", - searchPlaceholder: "Enter color: #0A84FF, rgb(10, 132, 255), hsl(210, 100%, 52%)…", + searchPlaceholder: "Enter color: #0A84FF, rgb(10, 132, 255), oklch(...) or pick from screen…", ratingAAA: "AAA Pass", ratingAA: "AA Pass", ratingAALarge: "AA Large Only", @@ -151,6 +213,8 @@ const rawT = createTranslator( contrastBodyAAA: "- Normal Text AAA (≥ 7:1): {status}", contrastLargeAA: "- Large Text AA (≥ 3:1, 18pt or 14pt bold): {status}", contrastLargeAAA: "- Large Text AAA (≥ 4.5:1): {status}", + contrastSuggestedMd: "**Suggested AA Foreground**: `{hex}` ({ratio}:1)", + copySuggestedAction: "Copy Suggested AA Color {hex}", contrastAlphaNote: "> Colors with alpha are evaluated as opaque.", contrastColorsNote: "Foreground `{fg}`, Background `{bg}`", contrastUsageLine1: "**Enter two colors**: foreground (text) first, background second, separated by space.", @@ -174,13 +238,14 @@ const rawT = createTranslator( } }, { defaultLocale: "en-US" } -) +); + export const t: typeof rawT = (key, params) => { - const out = rawT(key, params) - if (!out.includes('[[')) return out + const out = rawT(key, params); + if (!out.includes("[[")) return out; return out.replace(/\[\[([A-Za-z0-9_.-]+):([^|\]]+)\|([^\]]+)\]\]/g, (_m, k: string, one: string, other: string) => { - const v = params?.[k] - const n = typeof v === 'number' ? v : Number(String(v ?? '').replace(/,/g, '')) - return n === 1 ? one : other - }) -} + const v = params?.[k]; + const n = typeof v === "number" ? v : Number(String(v ?? "").replace(/,/g, "")); + return n === 1 ? one : other; + }); +}; diff --git a/extensions/color-picker/src/index.ts b/extensions/color-picker/src/index.ts index ccab4e12..e2bc4cc2 100644 --- a/extensions/color-picker/src/index.ts +++ b/extensions/color-picker/src/index.ts @@ -16,25 +16,39 @@ import { parseColor, rgbToOklch, generateColorSwatchSvg, + generateColorScale, + generateCssScaleVariables, + suggestAccessibleColor, + pickScreenColor, + isScreenRecordingPermissionError, getSavedPalette, saveColorToPalette, clearPalette, removeFromPalette, + getColorHistory, + saveColorHistory, + clearColorHistory, calculateContrast, evaluateRating, splitColorInputs, generateContrastPreviewSvg, type ColorConversionResult, - type SavedColorItem + type SavedColorItem, + type PickedColorResult } from "./converter.js"; export * from "./converter.js"; /** - * 颜色详情面板:真实色块 + 无障碍对比度 + 配色方案 + * 颜色详情面板:真实色块预览(SVG data URI)+ WCAG 对比度 + 50-950 色阶 + 配色方案 + CSS 变量 */ function colorDetailMarkdown(color: ColorConversionResult): string { const h = color.harmonies; + const scale = generateColorScale(color.rgb); + const scaleRow1 = scale.slice(0, 6).map((s) => `\`${s.step}\` ${s.hex}`).join(" · "); + const scaleRow2 = scale.slice(6).map((s) => `\`${s.step}\` ${s.hex}`).join(" · "); + const suggestedWhite = suggestAccessibleColor(color.rgb, { r: 255, g: 255, b: 255 }, 4.5); + return [ `![${displayHex(color)}](${generateColorSwatchSvg(color.hex8)})`, "", @@ -44,13 +58,33 @@ function colorDetailMarkdown(color: ColorConversionResult): string { t("detailBlackContrast", { ratio: color.wcag.contrastOnBlack, rating: color.wcag.blackRating }), "", t("detailRecommendedText", { color: color.wcag.recommendedText === "white" ? t("colorWhite") : t("colorBlack") }), + ...(suggestedWhite + ? ["", t("detailSuggestedAA", { hex: suggestedWhite.hex, ratio: suggestedWhite.ratio })] + : []), "", "---", "", + t("detailScaleTitle"), + "", + `- ${scaleRow1}`, + `- ${scaleRow2}`, + "", + "---", + "", + t("detailHarmonyTitle"), + "", t("harmonyComplementary", { val: h.complementary }), t("harmonyAnalogous", { val: h.analogous.join("`, `") }), t("harmonyTriadic", { val: h.triadic.join("`, `") }), - t("harmonyMonochromatic", { val: h.monochromatic.join("` → `") }) + t("harmonyMonochromatic", { val: h.monochromatic.join("` → `") }), + "", + "---", + "", + t("detailCssVarsTitle"), + "", + "```css", + generateCssScaleVariables(color, scale), + "```" ].join("\n"); } @@ -58,6 +92,8 @@ function usageMarkdown(): string { return [ t("usageTitle"), "", + t("usageBody"), + "", "- `#0A84FF`, `#0A84FF80`, `#abc`", "- `rgb(10, 132, 255)`, `hsl(210, 100%, 52%)`, `hsv(...)`", "- `oklch(62.8% 0.2577 29.23)`, `cmyk(96%, 48%, 0%, 0%)`", @@ -80,30 +116,133 @@ function displayHex(color: ColorConversionResult): string { return color.hasAlpha ? color.hex8 : color.hex; } -export function ColorPickerCommand() { +function parseClipboardColorCandidate(raw: unknown): string | null { + if (typeof raw !== "string") return null; + const trimmed = raw.trim(); + if (!trimmed || trimmed.length > 100 || /[\r\n]/.test(trimmed)) return null; + const parsed = parseColor(trimmed); + return parsed.isValid ? trimmed : null; +} + +function isAbortError(err: unknown): boolean { + return err instanceof Error && err.name === "AbortError"; +} + +function isUnavailableError(err: unknown): boolean { + return Boolean( + err && + typeof err === "object" && + (err as { code?: unknown }).code === "SCREEN_PICKER_UNAVAILABLE" + ); +} + +function renderColorPickerWorkspace(autoPickOnMount: boolean) { useLocale(); const [input, setInput] = useState(""); const [palette, setPalette] = useState([]); + const [history, setHistory] = useState([]); const [loaded, setLoaded] = useState(false); + const copy = async (value: string) => { + await Clipboard.copy(value); + await showToast(Toast.Style.Success, t("copiedToast", { val: value })); + }; + + const handlePickScreenColor = async () => { + try { + const picked = await pickScreenColor(); + setInput(picked.hex); + try { + setHistory(await saveColorHistory(picked)); + } catch (histErr: unknown) { + await showToast(Toast.Style.Failure, t("readHistoryFailed"), errorText(histErr)); + } + await Clipboard.copy(picked.hex); + await showToast( + Toast.Style.Success, + t("pickSuccessToast", { hex: picked.hex }), + t("pickCoordDesc", { x: picked.x, y: picked.y }) + ); + } catch (err: unknown) { + if (isAbortError(err)) return; + if (isScreenRecordingPermissionError(err)) { + await showToast(Toast.Style.Failure, t("pickPermTitle"), t("pickPermMsg")); + } else if (isUnavailableError(err)) { + await showToast(Toast.Style.Failure, t("pickFailedTitle"), t("pickUnavailableMsg")); + } else { + await showToast(Toast.Style.Failure, t("pickFailedTitle"), errorText(err)); + } + } + }; + + const handleReadClipboard = async () => { + try { + const text = await Clipboard.readText(); + if (!text || !text.trim()) { + await showToast(Toast.Style.Failure, t("clipboardEmptyToast")); + return; + } + const candidate = parseClipboardColorCandidate(text); + if (!candidate) { + await showToast(Toast.Style.Failure, t("clipboardInvalidToast")); + return; + } + const parsed = parseColor(candidate); + setInput(candidate); + await showToast(Toast.Style.Success, t("clipboardLoadedToast", { hex: displayHex(parsed) })); + } catch (err: unknown) { + await showToast(Toast.Style.Failure, t("clipboardReadFailed"), errorText(err)); + } + }; + useEffect(() => { let cancelled = false; - getSavedPalette() - .then((items) => { if (!cancelled) setPalette(items); }) - .catch((err: unknown) => showToast(Toast.Style.Failure, t("readPaletteFailed"), errorText(err))) - .finally(() => { if (!cancelled) setLoaded(true); }); - return () => { cancelled = true; }; + + Promise.all([ + getSavedPalette() + .then((items) => { + if (!cancelled) setPalette(items); + }) + .catch((err: unknown) => { + if (!cancelled) void showToast(Toast.Style.Failure, t("readPaletteFailed"), errorText(err)); + }), + getColorHistory() + .then((items) => { + if (!cancelled) setHistory(items); + }) + .catch((err: unknown) => { + if (!cancelled) void showToast(Toast.Style.Failure, t("readHistoryFailed"), errorText(err)); + }) + ]).finally(() => { + if (!cancelled) setLoaded(true); + }); + + if (autoPickOnMount) { + void handlePickScreenColor(); + } else if (typeof Clipboard.readText === "function") { + Clipboard.readText() + .then((text) => { + if (cancelled) return; + const candidate = parseClipboardColorCandidate(text); + if (candidate) { + setInput((prev) => (prev.trim() ? prev : candidate)); + } + }) + .catch((err: unknown) => { + // 启动时静默探测剪贴板,读取失败不打扰用户 + void err; + }); + } + + return () => { + cancelled = true; + }; }, []); const trimmed = input.trim(); const color = trimmed ? parseColor(trimmed) : null; const valid = Boolean(color && color.isValid); - const copy = async (value: string) => { - await Clipboard.copy(value); - await showToast(Toast.Style.Success, t("copiedToast", { val: value })); - }; - const save = async (c: ColorConversionResult) => { try { const hex = displayHex(c); @@ -130,7 +269,7 @@ export function ColorPickerCommand() { } }; - const clearAll = async () => { + const clearAllPalette = async () => { if (palette.length === 0) return; const ok = await confirmAlert({ title: t("clearConfirmTitle", { count: palette.length }), @@ -148,10 +287,29 @@ export function ColorPickerCommand() { } }; + const clearAllHistory = async () => { + if (history.length === 0) return; + const ok = await confirmAlert({ + title: t("clearHistoryConfirmTitle", { count: history.length }), + message: t("clearHistoryConfirmMsg"), + primaryAction: { title: t("clearHistoryConfirmBtn"), style: "destructive" }, + dismissAction: { title: t("cancel") } + }); + if (!ok) return; + try { + await clearColorHistory(); + setHistory([]); + await showToast(Toast.Style.Success, t("clearedHistoryToast")); + } catch (err: unknown) { + await showToast(Toast.Style.Failure, t("clearHistoryFailed"), errorText(err)); + } + }; + const sections: ReturnType[] = []; if (color && valid) { const oklch = rgbToOklch(color.rgb); + const cssScaleVars = generateCssScaleVariables(color); const detail = List.Item.Detail({ markdown: colorDetailMarkdown(color) }); const formats: Array<[string, string, string]> = [ ["hex", "HEX", color.hex], @@ -162,7 +320,8 @@ export function ColorPickerCommand() { ["cmyk", "CMYK", color.cssCmyk], ["hex8", t("fmtHex8"), color.hex8], ["tailwind", t("fmtTailwind"), `bg-[${displayHex(color)}]`], - ["css-var", t("fmtCssVar"), color.cssVar] + ["css-var", t("fmtCssVar"), color.cssVar], + ["css-scale", t("fmtCssScaleVars"), `--color-primary-50..950 (${displayHex(color)})`] ]; sections.push( List.Section( @@ -171,20 +330,23 @@ export function ColorPickerCommand() { ? t("sectionFormatsOutOfGamut", { hex: displayHex(color) }) : t("sectionFormats", { hex: displayHex(color) }) }, - formats.map(([id, label, value]) => - List.Item({ + formats.map(([id, label, value]) => { + const copyValue = id === "css-scale" ? cssScaleVars : value; + return List.Item({ id: `fmt-${id}`, title: value, subtitle: label, icon: Icon.Brush, detail, actions: ActionPanel({ title: label }, [ - Action({ title: t("copyAction"), icon: Icon.CopyClipboard, onAction: () => copy(value) }), + Action({ title: t("copyAction"), icon: Icon.CopyClipboard, onAction: () => copy(copyValue) }), Action({ title: t("saveToPaletteAction"), icon: Icon.Star, onAction: () => save(color) }), - Action({ title: t("pasteToActiveAction"), icon: Icon.Pencil, onAction: async () => { await Clipboard.paste(value); } }) + Action({ title: t("copyCssScaleAction"), icon: Icon.Code, onAction: () => copy(cssScaleVars) }), + Action({ title: t("pickScreenAction"), icon: Icon.Eye, onAction: handlePickScreenColor }), + Action({ title: t("pasteToActiveAction"), icon: Icon.Pencil, onAction: async () => { await Clipboard.paste(copyValue); } }) ]) - }) - ) + }); + }) ) ); } else if (trimmed) { @@ -195,11 +357,15 @@ export function ColorPickerCommand() { title: t("invalidTitle", { input: trimmed }), subtitle: t("invalidSub"), icon: Icon.ExclamationMark, - detail: List.Item.Detail({ markdown: usageMarkdown() }) + detail: List.Item.Detail({ markdown: usageMarkdown() }), + actions: ActionPanel({ title: t("sectionInvalid") }, [ + Action({ title: t("pickScreenAction"), icon: Icon.Eye, onAction: handlePickScreenColor }), + Action({ title: t("readClipboardAction"), icon: Icon.CopyClipboard, onAction: handleReadClipboard }) + ]) }) ]) ); - } else { + } else if (history.length === 0 && palette.length === 0) { sections.push( List.Section({ title: t("sectionStart") }, [ List.Item({ @@ -207,20 +373,58 @@ export function ColorPickerCommand() { title: t("hintTitle"), subtitle: t("hintSub"), icon: Icon.Brush, - detail: List.Item.Detail({ markdown: usageMarkdown() }) + detail: List.Item.Detail({ markdown: usageMarkdown() }), + actions: ActionPanel({ title: t("sectionStart") }, [ + Action({ title: t("pickScreenAction"), icon: Icon.Eye, onAction: handlePickScreenColor }), + Action({ title: t("readClipboardAction"), icon: Icon.CopyClipboard, onAction: handleReadClipboard }) + ]) }) ]) ); } const q = trimmed.toLowerCase(); - const paletteMatches = palette.filter((p) => !q || valid || p.hex.toLowerCase().includes(q) || p.name.toLowerCase().includes(q)); + const historyMatches = history.filter((item) => !q || valid || item.hex.toLowerCase().includes(q)); + if (historyMatches.length > 0) { + sections.push( + List.Section( + { title: t("sectionHistoryCount", { count: history.length }) }, + historyMatches.map((item, idx) => { + const c = parseColor(item.hex); + const cssScaleVars = generateCssScaleVariables(c); + return List.Item({ + id: `hist-${idx}-${item.hex.slice(1)}`, + title: item.hex, + subtitle: t("historyCoordSub", { + rgb: c.hasAlpha ? c.cssRgba : c.cssRgb, + x: item.x, + y: item.y + }), + icon: Icon.Clock, + detail: List.Item.Detail({ markdown: colorDetailMarkdown(c) }), + actions: ActionPanel({ title: item.hex }, [ + Action({ title: t("copyHexAction"), icon: Icon.CopyClipboard, onAction: () => copy(item.hex) }), + Action({ title: t("viewFormatsAction"), icon: Icon.Eye, onAction: () => setInput(item.hex) }), + Action({ title: t("saveToPaletteAction"), icon: Icon.Star, onAction: () => save(c) }), + Action({ title: t("copyCssScaleAction"), icon: Icon.Code, onAction: () => copy(cssScaleVars) }), + Action({ title: t("clearHistoryAction"), icon: Icon.Trash, onAction: clearAllHistory }) + ]) + }); + }) + ) + ); + } + + const paletteMatches = palette.filter( + (p) => !q || valid || p.hex.toLowerCase().includes(q) || p.name.toLowerCase().includes(q) + ); if (paletteMatches.length > 0) { sections.push( List.Section( { title: t("sectionPaletteCount", { count: palette.length }) }, paletteMatches.map((item) => { const c = parseColor(item.hex); + const cssScaleVars = generateCssScaleVariables(c); return List.Item({ id: item.id, title: item.hex, @@ -231,8 +435,9 @@ export function ColorPickerCommand() { actions: ActionPanel({ title: item.hex }, [ Action({ title: t("copyHexAction"), icon: Icon.CopyClipboard, onAction: () => copy(item.hex) }), Action({ title: t("viewFormatsAction"), icon: Icon.Eye, onAction: () => setInput(item.hex) }), + Action({ title: t("copyCssScaleAction"), icon: Icon.Code, onAction: () => copy(cssScaleVars) }), Action({ title: t("removeFromPaletteAction"), icon: Icon.Trash, onAction: () => remove(item) }), - Action({ title: t("clearPaletteAction"), icon: Icon.Trash, onAction: clearAll }) + Action({ title: t("clearPaletteAction"), icon: Icon.Trash, onAction: clearAllPalette }) ]) }); }) @@ -253,38 +458,61 @@ export function ColorPickerCommand() { } const barActions = [ - ...(color && valid - ? [{ id: "save-palette", title: t("saveToPaletteAction"), style: "primary" as const, onAction: () => void save(color) }] - : []), - ...(palette.length > 0 - ? [{ id: "clear-palette", title: t("clearPaletteAction"), style: "secondary" as const, onAction: () => void clearAll() }] + { + id: "pick-screen-color", + title: t("pickScreenAction"), + style: "primary" as const, + onAction: () => void handlePickScreenColor() + }, + { + id: "read-clipboard", + title: t("readClipboardAction"), + style: "secondary" as const, + onAction: () => void handleReadClipboard() + }, + ...(history.length > 0 + ? [ + { + id: "clear-history", + title: t("clearHistoryAction"), + style: "secondary" as const, + onAction: () => void clearAllHistory() + } + ] : []) ]; + const summaryText = + color && valid + ? `${displayHex(color)} · ${color.hasAlpha ? color.cssRgba : color.cssRgb} · WCAG ${color.wcag.whiteRating}/${color.wcag.blackRating}` + : history.length > 0 || palette.length > 0 + ? t("summaryCounts", { history: history.length, palette: palette.length }) + : t("summaryEmpty"); + return List( { navigationTitle: t("navTitle"), - // 没有可展示的颜色时不开右侧详情栏,避免整块空白 - isShowingDetail: valid || paletteMatches.length > 0, + isShowingDetail: true, searchBarPlaceholder: t("searchPlaceholder"), searchText: input, onSearchTextChange: (val: string) => setInput(val), - ...(barActions.length > 0 - ? { - filterBar: { - summaryText: - color && valid - ? `${displayHex(color)} · ${color.hasAlpha ? color.cssRgba : color.cssRgb} · WCAG ${color.wcag.whiteRating}/${color.wcag.blackRating}` - : t("sectionPaletteCount", { count: palette.length }), - actions: barActions - } - } - : {}) + filterBar: { + summaryText, + actions: barActions + } }, sections ); } +export function ColorPickerCommand() { + return renderColorPickerWorkspace(false); +} + +export function PickScreenColorCommand() { + return renderColorPickerWorkspace(true); +} + function ratingLabel(rating: string): string { switch (rating) { case "AAA": return t("ratingAAA"); @@ -294,7 +522,12 @@ function ratingLabel(rating: string): string { } } -function contrastMarkdown(fg: ColorConversionResult, bg: ColorConversionResult, ratio: number): string { +function contrastMarkdown( + fg: ColorConversionResult, + bg: ColorConversionResult, + ratio: number, + suggested: { hex: string; ratio: number } | null +): string { const pass = (ok: boolean) => (ok ? t("pass") : t("fail")); return [ `![${displayHex(fg)} / ${displayHex(bg)}](${generateContrastPreviewSvg(fg.hex, bg.hex)})`, @@ -305,6 +538,7 @@ function contrastMarkdown(fg: ColorConversionResult, bg: ColorConversionResult, t("contrastBodyAAA", { status: pass(ratio >= 7) }), t("contrastLargeAA", { status: pass(ratio >= 3) }), t("contrastLargeAAA", { status: pass(ratio >= 4.5) }), + ...(suggested ? ["", t("contrastSuggestedMd", { hex: suggested.hex, ratio: suggested.ratio })] : []), "", ...(fg.hasAlpha || bg.hasAlpha ? [t("contrastAlphaNote"), ""] : []), t("contrastColorsNote", { fg: displayHex(fg), bg: displayHex(bg) }) @@ -338,15 +572,25 @@ export function ContrastCheckCommand() { const pairItem = (id: string, fg: ColorConversionResult, bg: ColorConversionResult, title: string) => { const ratio = calculateContrast(fg.rgb, bg.rgb); const ratioText = `${ratio}:1`; + const suggested = suggestAccessibleColor(fg.rgb, bg.rgb, 4.5); return List.Item({ id, title, subtitle: t("contrastSub", { ratio: ratioText }), icon: Icon.Eye, accessories: [{ text: ratingLabel(evaluateRating(ratio)) }], - detail: List.Item.Detail({ markdown: contrastMarkdown(fg, bg, ratio) }), + detail: List.Item.Detail({ markdown: contrastMarkdown(fg, bg, ratio, suggested) }), actions: ActionPanel({ title }, [ Action({ title: t("copyContrastAction"), icon: Icon.CopyClipboard, onAction: () => copy(ratioText) }), + ...(suggested + ? [ + Action({ + title: t("copySuggestedAction", { hex: suggested.hex }), + icon: Icon.Checkmark, + onAction: () => copy(suggested.hex) + }) + ] + : []), Action({ title: t("swapColorsAction"), icon: Icon.ArrowClockwise, @@ -424,6 +668,7 @@ export function ContrastCheckCommand() { } export const commands = { + "pick-screen-color": PickScreenColorCommand, "convert-color": ColorPickerCommand, "contrast-check": ContrastCheckCommand }; diff --git a/extensions/color-picker/tests/contrast-check.test.mjs b/extensions/color-picker/tests/contrast-check.test.mjs index a334fb7f..32369fbe 100644 --- a/extensions/color-picker/tests/contrast-check.test.mjs +++ b/extensions/color-picker/tests/contrast-check.test.mjs @@ -60,12 +60,14 @@ test('异常输入:无法识别、超过两种颜色时给出提示且不开 } finally { view.unmount() } }) -test('色值转换空输入时不展示空白详情栏;无法识别时也不空白', async () => { +test('色值转换采用布局一(isShowingDetail=true):空输入与无法识别时右栏均有非空引导说明', async () => { const view = await mount(ColorPickerCommand) try { - assert.equal(view.tree().props.isShowingDetail, false) + assert.equal(view.tree().props.isShowingDetail, true) + assert.ok(view.item('hint').props.detail.props.markdown.length > 0, '空态右栏展示屏幕取色与支持格式引导') await view.search('nonsense') - assert.equal(view.tree().props.isShowingDetail, false) + assert.equal(view.tree().props.isShowingDetail, true) + assert.ok(view.item('invalid').props.detail.props.markdown.length > 0, '无法识别时右栏展示用法说明') await view.search('#0A84FF') assert.equal(view.tree().props.isShowingDetail, true) assert.ok(!view.text().includes('⌘/Ctrl'), '快捷键文案按平台只写一种') diff --git a/extensions/color-picker/tests/index.test.mjs b/extensions/color-picker/tests/index.test.mjs index c2aa7043..afa3f523 100644 --- a/extensions/color-picker/tests/index.test.mjs +++ b/extensions/color-picker/tests/index.test.mjs @@ -1,7 +1,14 @@ import test from 'node:test' import assert from 'node:assert/strict' import { createHost, mount, tick } from '../../shared/test-harness.mjs' -import ColorPickerCommand from '../dist/index.js' +import ColorPickerCommand, { + commands, + generateColorScale, + generateCssScaleVariables, + pickScreenColor, + saveColorHistory, + suggestAccessibleColor +} from '../dist/index.js' import { parseColor, rgbToOklch, calculateContrast } from '../dist/converter.js' const host = createHost() @@ -20,13 +27,120 @@ test('多种输入写法得到同一颜色;非法输入标记为无效', () => assert.equal(Math.round(calculateContrast({ r: 0, g: 0, b: 0 }, { r: 255, g: 255, b: 255 })), 21) }) -test('界面:没有示例调色板与屏幕吸色按钮;输入颜色后可复制各种写法', async () => { +test('界面:零示例假色板、提供屏幕取色与读剪贴板顶栏入口;输入颜色后可复制各种写法与 50-950 CSS 变量', async () => { const view = await mount(ColorPickerCommand) - assert.ok(!view.text().includes('ZTools Accent Blue')) - assert.ok(!view.text().includes('吸色') && !view.text().includes('Eyedropper')) - await view.search('#FF0000') - await view.run(view.item('fmt-oklch'), '复制') - assert.equal(host.clipboard.text, 'oklch(62.8% 0.2577 29.23)') + try { + assert.ok(!view.text().includes('ZTools Accent Blue')) + const filterActions = view.tree().props.filterBar?.actions || [] + assert.ok(filterActions.some((a) => a.id === 'pick-screen-color'), '顶栏应提供屏幕取色入口') + assert.ok(filterActions.some((a) => a.id === 'read-clipboard'), '顶栏应提供读剪贴板入口') + + await view.search('#FF0000') + await view.run(view.item('fmt-oklch'), '复制') + assert.equal(host.clipboard.text, 'oklch(62.8% 0.2577 29.23)') + + const detailMd = view.item('fmt-hex').props.detail.props.markdown + assert.match(detailMd, /50–950 色阶/) + assert.match(detailMd, /--color-primary-500: #FF0000;/) + + await view.run(view.item('fmt-css-scale'), '复制') + assert.match(host.clipboard.text, /--color-primary-50:/) + assert.match(host.clipboard.text, /--color-primary-950:/) + } finally { + view.unmount() + } +}) + +test('自动识别剪贴板色值并在挂载时回填', async () => { + host.clipboard.text = '#3B82F6' + const view = await mount(ColorPickerCommand) + try { + await tick(5) + assert.equal(view.item('fmt-hex').props.title, '#3B82F6') + } finally { + view.unmount() + } +}) + +test('50-950 色阶生成、CSS 变量导出与 WCAG AA 合规色推荐', () => { + const parsed = parseColor('#3B82F6') + const scale = generateColorScale(parsed.rgb) + assert.equal(scale.length, 11) + assert.equal(scale.find((s) => s.step === 500)?.hex, '#3B82F6') + const cssVars = generateCssScaleVariables(parsed, scale) + assert.match(cssVars, /^:root \{[\s\S]*--color-primary-50:[\s\S]*--color-primary-950:[\s\S]*\}$/) + + const suggested = suggestAccessibleColor(parsed.rgb, { r: 255, g: 255, b: 255 }, 4.5) + assert.ok(suggested && suggested.ratio >= 4.5) + assert.equal(suggestAccessibleColor({ r: 0, g: 0, b: 0 }, { r: 255, g: 255, b: 255 }, 4.5), null) +}) + +test('屏幕取色:真实宿主链路返回 native 色值;无宿主能力时诚实抛错绝不造假色值', async () => { + assert.equal(typeof commands['pick-screen-color'], 'function') + + // 1. 通过 hostOverride 走真实 transport 协议 + const picked = await pickScreenColor({ + screen_get_cursor_pos: async () => ({ x: 320, y: 240 }), + dllplugin_call: async (params) => { + assert.equal(params.plugin, 'ColorPickerPlugin') + assert.equal(params.func, 'pickScreenPixel') + return { r: 48, g: 209, b: 88, x: 320, y: 240 } + } + }) + assert.equal(picked.source, 'native') + assert.equal(picked.hex, '#30D158') + assert.equal(picked.x, 320) + assert.equal(picked.y, 240) + + // 2. 宿主报 TCC 录屏权限错误时透传标准权限错误码 + await assert.rejects( + () => + pickScreenColor({ + screen_get_cursor_pos: async () => ({ x: 10, y: 20 }), + dllplugin_call: async () => ({ ok: false, permissionDenied: true, error: 'SCREEN_RECORDING_PERMISSION_DENIED' }) + }), + (err) => err?.code === 'SCREEN_RECORDING_PERMISSION_DENIED' + ) + + // 3. 无屏幕取色接口时诚实抛出 SCREEN_PICKER_UNAVAILABLE,严禁模拟假色值 + await assert.rejects( + () => pickScreenColor({}), + (err) => err?.code === 'SCREEN_PICKER_UNAVAILABLE' + ) +}) + +test('取色历史持久化并在界面展示,支持清空历史二次确认', async () => { + await saveColorHistory({ + hex: '#30D158', + rgb: { r: 48, g: 209, b: 88 }, + hsl: { h: 135, s: 64, l: 50 }, + hsv: { h: 135, s: 77, v: 82 }, + x: 120, + y: 240, + source: 'native', + pickedAt: Date.now() + }) + const view = await mount(ColorPickerCommand) + try { + await tick(5) + const histItem = view.items().find((i) => String(i.props.id).startsWith('hist-')) + assert.ok(histItem, '左栏应展示取色历史') + assert.equal(histItem.props.title, '#30D158') + assert.ok( + (view.tree().props.filterBar?.actions || []).some((a) => a.id === 'clear-history'), + '有取色历史时顶栏显示清空历史按钮' + ) + + host.setConfirm(false) + await view.run(histItem, '清空历史') + assert.equal(JSON.parse(host.storage.get('color_picker_history')).length, 1) + + host.setConfirm(true) + await view.run(histItem, '清空历史') + assert.equal(JSON.parse(host.storage.get('color_picker_history')).length, 0) + } finally { + view.unmount() + } }) test('收藏到调色板会持久化;清空需要确认', async () => { diff --git a/extensions/crypto-tool/package.json b/extensions/crypto-tool/package.json index 4d260007..d63261e2 100644 --- a/extensions/crypto-tool/package.json +++ b/extensions/crypto-tool/package.json @@ -1,6 +1,6 @@ { "name": "crypto-tool", - "version": "1.1.4", + "version": "1.1.7", "description": "散列与对称加解密:MD5、SHA1、SHA256、SHA512、Base64 编解码、AES 加解密,实时计算多哈希对比", "type": "module", "main": "dist/index.js", diff --git a/extensions/crypto-tool/plugin.json b/extensions/crypto-tool/plugin.json index badc2756..3f8bda0d 100644 --- a/extensions/crypto-tool/plugin.json +++ b/extensions/crypto-tool/plugin.json @@ -1,7 +1,7 @@ { "id": "crypto-tool", "name": "编码与加密", - "version": "1.1.6", + "version": "1.1.7", "minAppVersion": "1.1.8.0", "description": "支持 Base64 / URL / Unicode / Hex 编码互转、MD5 / SHA 哈希计算、AES 加解密、HMAC 计算与 UUID 批量生成", "author": "ZTools Team", diff --git a/extensions/crypto-tool/src/i18n.ts b/extensions/crypto-tool/src/i18n.ts index 0fd3e2ad..18f4dc83 100644 --- a/extensions/crypto-tool/src/i18n.ts +++ b/extensions/crypto-tool/src/i18n.ts @@ -43,6 +43,19 @@ const rawT = createTranslator( actionsTitle: "操作", pasteFromClipboard: "从剪贴板粘贴", readClipboardBtn: "从剪贴板读取", + pickFileBtn: "选择文件", + pickFileAction: "选择本地文件计算哈希", + pickFileDialogTitle: "选择要计算哈希的文件", + verifyClipboardHashBtn: "比对剪贴板哈希", + verifyClipboardHashAction: "与剪贴板校验值比对", + checksumMatchedTag: "与剪贴板一致", + checksumMismatchTag: "与剪贴板不一致", + checksumMatchedMd: "**剪贴板校验值比对**:完全匹配({algo} · {len}/{len} 字符一致)", + checksumMismatchMd: "**剪贴板校验值比对**:未匹配(剪贴板为 {len} 位校验值 `{expected}`)", + checksumMatchedToast: "校验一致({algo})", + checksumMismatchToast: "校验不一致", + checksumMismatchToastMsg: "剪贴板哈希与当前文件的所有算法结果均不匹配", + checksumInvalidClipboardToast: "剪贴板中没有合法的十六进制哈希值(32/40/64/128 位)", pasteToActive: "直接粘贴到当前应用", clearInput: "清空输入", copy: "复制", @@ -95,8 +108,8 @@ const rawT = createTranslator( sectionResults: "计算结果", uuidGenFailed: "生成失败", uuidGenAction: "重新生成", - uuidNavTitle: "UUID 生成器", - uuidPlaceholder: "输入数量 (1-1000) 自动重生成,或输入关键词过滤…", + uuidNavTitle: "UUID / ULID / NanoID 工具", + uuidPlaceholder: "输入数量 (1-1000) 重生成,粘贴 UUID/ULID/NanoID 自动解析,或输入关键词过滤…", uuidGeneratedTitle: "已生成 {count} 个 UUID", uuidDefaultTitle: "生成 UUID", uuidSubtitle: "使用系统安全随机数,回车即复制", @@ -109,6 +122,16 @@ const rawT = createTranslator( uuidVersionV4: "UUID v4(随机)", uuidVersionV7: "UUID v7(时间有序)", uuidVersionV1: "UUID v1(时间戳)", + uuidVersionUlid: "ULID(26 位时间有序)", + uuidVersionNanoid: "NanoID(21 位 URL 安全)", + uuidSectionParsed: "ID 自动解析结果", + uuidParsedCopyCanonical: "复制标准化值", + uuidParsedCopyTimestamp: "复制 ISO 时间戳", + uuidParsedCopyEpochMs: "复制毫秒时间戳", + uuidParsedTimeMeta: "内嵌时间:{iso}({ms} ms)", + uuidParsedVariantMeta: "变体:{variant}", + uuidParsedEntropyMeta: "随机熵:{bits} bits", + uuidParsedNodeMeta: "节点:{node}", uuidFormatStandard: "标准小写", uuidFormatUpper: "标准大写", uuidFormatNoDash: "无连字符小写", @@ -169,6 +192,19 @@ const rawT = createTranslator( actionsTitle: "Actions", pasteFromClipboard: "Paste from Clipboard", readClipboardBtn: "Read Clipboard", + pickFileBtn: "Select File", + pickFileAction: "Select Local File to Hash", + pickFileDialogTitle: "Select a file to compute hashes", + verifyClipboardHashBtn: "Verify Clipboard Hash", + verifyClipboardHashAction: "Compare with Clipboard Checksum", + checksumMatchedTag: "Matches Clipboard", + checksumMismatchTag: "Mismatch", + checksumMatchedMd: "**Clipboard Checksum**: Exact match ({algo} · {len}/{len} chars)", + checksumMismatchMd: "**Clipboard Checksum**: Mismatch (clipboard has {len}-char hash `{expected}`)", + checksumMatchedToast: "Checksum matched ({algo})", + checksumMismatchToast: "Checksum mismatch", + checksumMismatchToastMsg: "Clipboard hash does not match any computed digest of this file", + checksumInvalidClipboardToast: "Clipboard does not contain a valid hex digest (32/40/64/128 chars)", pasteToActive: "Paste to Frontmost App", clearInput: "Clear Input", copy: "Copy", @@ -222,7 +258,7 @@ const rawT = createTranslator( uuidGenFailed: "Generation failed", uuidGenAction: "Regenerate", uuidNavTitle: "UUID Generator", - uuidPlaceholder: "Enter count (1-1000) to regenerate, or type to filter…", + uuidPlaceholder: "Enter count (1-1000), paste UUID/ULID/NanoID to inspect, or type to filter…", uuidGeneratedTitle: "Generated {count} UUID(s)", uuidDefaultTitle: "Generate UUID", uuidSubtitle: "Cryptographically secure UUIDs, press Enter to copy", @@ -235,6 +271,16 @@ const rawT = createTranslator( uuidVersionV4: "UUID v4 (Random)", uuidVersionV7: "UUID v7 (Time-ordered)", uuidVersionV1: "UUID v1 (Timestamp)", + uuidVersionUlid: "ULID (26-char Time-ordered)", + uuidVersionNanoid: "NanoID (21-char URL-safe)", + uuidSectionParsed: "Identifier Inspector", + uuidParsedCopyCanonical: "Copy Canonical Value", + uuidParsedCopyTimestamp: "Copy ISO Timestamp", + uuidParsedCopyEpochMs: "Copy Epoch Milliseconds", + uuidParsedTimeMeta: "Timestamp: {iso} ({ms} ms)", + uuidParsedVariantMeta: "Variant: {variant}", + uuidParsedEntropyMeta: "Entropy: {bits} bits", + uuidParsedNodeMeta: "Node: {node}", uuidFormatStandard: "Standard Lowercase", uuidFormatUpper: "Standard Uppercase", uuidFormatNoDash: "No-Dash Lowercase", diff --git a/extensions/crypto-tool/src/index.ts b/extensions/crypto-tool/src/index.ts index c9fd6df2..967198d1 100644 --- a/extensions/crypto-tool/src/index.ts +++ b/extensions/crypto-tool/src/index.ts @@ -4,6 +4,7 @@ import { ActionPanel, Action, Icon, + Color, showToast, Toast, useState, @@ -17,12 +18,15 @@ import { t } from "./i18n.js"; import { calculateMultiHash, calculateFileHash, + pickFileForHash, + matchClipboardChecksum, decodeBase64, encodeBase64, aesEncrypt, aesDecrypt, calculateHmac, valueMarkdown, + type ClipboardChecksumMatch, type FileHashResult, type HashAlgorithm, type MultiHashResult @@ -216,34 +220,95 @@ export default function CryptoToolCommand() { const [aesDraft, setAesDraft] = usePopoutValue("aesDraft", () => DEFAULT_AES_DRAFT, isAesDraft); const [hmacDraft, setHmacDraft] = usePopoutValue("hmacDraft", () => DEFAULT_HMAC_DRAFT, isHmacDraft); const [fileHash, setFileHash] = useState(null); + const [checksumMatch, setChecksumMatch] = useState(null); const { push } = useNavigation(); const clearAllInput = () => { setFileHash(null); + setChecksumMatch(null); setInputText(""); }; + const computeFileHashByPath = async (targetPath: string) => { + const normalized = targetPath.trim(); + if (!normalized) return; + try { + const res = await calculateFileHash(normalized); + setFileHash(res); + setInputText(""); + setMode("hash"); + let autoMatch: ClipboardChecksumMatch | null = null; + try { + const clipText = await Clipboard.readText(); + autoMatch = matchClipboardChecksum(res, clipText ?? ""); + } catch { + autoMatch = null; + } + setChecksumMatch(autoMatch); + if (autoMatch?.isMatch && autoMatch.matchedAlgorithm) { + await showToast(Toast.Style.Success, t("checksumMatchedToast", { algo: autoMatch.matchedAlgorithm }), res.fileName); + } else { + await showToast(Toast.Style.Success, t("fileHashSuccess"), res.fileName); + } + } catch (err: unknown) { + await showToast( + Toast.Style.Failure, + t("fileHashFailed"), + err instanceof Error ? err.message : String(err) + ); + } + }; + + const pickFileAndHash = async () => { + try { + const picked = await pickFileForHash(t("pickFileDialogTitle")); + if (!picked) return; + await computeFileHashByPath(picked); + } catch (err: unknown) { + await showToast( + Toast.Style.Failure, + t("fileHashFailed"), + err instanceof Error ? err.message : String(err) + ); + } + }; + + const verifyClipboardChecksum = async () => { + if (!fileHash) return; + try { + const clipText = await Clipboard.readText(); + if (!clipText || !clipText.trim()) { + await showToast(Toast.Style.Failure, t("clipboardEmpty")); + return; + } + const match = matchClipboardChecksum(fileHash, clipText); + if (!match) { + setChecksumMatch(null); + await showToast(Toast.Style.Failure, t("checksumInvalidClipboardToast")); + return; + } + setChecksumMatch(match); + if (match.isMatch && match.matchedAlgorithm) { + await showToast(Toast.Style.Success, t("checksumMatchedToast", { algo: match.matchedAlgorithm }), fileHash.fileName); + } else { + await showToast(Toast.Style.Failure, t("checksumMismatchToast"), t("checksumMismatchToastMsg")); + } + } catch (err: unknown) { + await showToast(Toast.Style.Failure, t("readClipboardFailed"), err instanceof Error ? err.message : String(err)); + } + }; + const fileInputProps = createCompatFileInputProps( async (files) => { const targetPath = files[0]?.trim(); if (!targetPath) return; - try { - const res = await calculateFileHash(targetPath); - setFileHash(res); - setMode("hash"); - await showToast(Toast.Style.Success, t("fileHashSuccess"), res.fileName); - } catch (err: unknown) { - await showToast( - Toast.Style.Failure, - t("fileHashFailed"), - err instanceof Error ? err.message : String(err) - ); - } + await computeFileHashByPath(targetPath); }, { onTextPaste: (text) => { if (text) { setFileHash(null); + setChecksumMatch(null); setInputText(text); } } @@ -265,6 +330,7 @@ export default function CryptoToolCommand() { return; } setFileHash(null); + setChecksumMatch(null); setInputText(text); } catch (err: unknown) { await showToast(Toast.Style.Failure, t("readClipboardFailed"), err instanceof Error ? err.message : String(err)); @@ -351,22 +417,55 @@ export default function CryptoToolCommand() { ...(fileHash.sha1 ? [{ id: "file-sha1", title: fileHash.sha1, subtitle: t("fileSha1Sub", { name: fileHash.fileName }), value: fileHash.sha1, icon: Icon.Lock }] : []), ...(fileHash.sha512 ? [{ id: "file-sha512", title: fileHash.sha512, subtitle: t("fileSha512Sub", { name: fileHash.fileName }), value: fileHash.sha512, icon: Icon.Lock }] : []) ]; + const checksumNotice = checksumMatch + ? checksumMatch.isMatch && checksumMatch.matchedAlgorithm + ? t("checksumMatchedMd", { algo: checksumMatch.matchedAlgorithm, len: checksumMatch.length }) + : t("checksumMismatchMd", { len: checksumMatch.length, expected: checksumMatch.normalized }) + : null; const fileDetailHeader = [ t("fileNameMd", { name: fileHash.fileName }), t("filePathMd", { path: fileHash.filePath }), - ...(typeof fileHash.byteLength === "number" ? [t("fileSizeMd", { bytes: fileHash.byteLength })] : []) + ...(typeof fileHash.byteLength === "number" ? [t("fileSizeMd", { bytes: fileHash.byteLength })] : []), + ...(checksumNotice ? [checksumNotice] : []) ].join("\n\n"); - items = fileItems.map((item) => - List.Item({ + items = fileItems.map((item) => { + const isMatchedItem = Boolean( + checksumMatch?.isMatch && + (checksumMatch.matchedItemId === item.id || + (checksumMatch.matchedItemId === "file-md5-lower" && item.id === "file-md5-upper")) + ); + const itemAccessories = isMatchedItem + ? [{ tag: t("checksumMatchedTag") }, { text: fileHash.filePath }] + : checksumMatch && !checksumMatch.isMatch && item.id === "file-sha256" + ? [{ tag: { value: t("checksumMismatchTag"), color: Color.Red } }, { text: fileHash.filePath }] + : [{ text: fileHash.filePath }]; + return List.Item({ id: item.id, title: item.title, subtitle: item.subtitle, icon: item.icon, - accessories: [{ text: fileHash.filePath }], + accessories: itemAccessories, detail: List.Item.Detail({ markdown: `${fileDetailHeader}\n\n${valueMarkdown(item.value)}` }), - actions: commonItemActions(item.value, item.subtitle) - }) - ); + actions: ActionPanel({ title: item.subtitle }, [ + Action.CopyToClipboard({ title: t("copy"), content: item.value, icon: Icon.CopyClipboard }), + Action.Paste({ title: t("pasteToActive"), content: item.value, icon: Icon.ArrowRight, shortcut: { modifiers: ["ctrl"], key: "return" } }), + Action({ title: t("clearInput"), icon: Icon.Trash, shortcut: { modifiers: ["ctrl"], key: "backspace" }, onAction: clearAllInput }), + Action({ + title: t("verifyClipboardHashAction"), + icon: Icon.Check, + shortcut: { modifiers: ["ctrl", "shift"], key: "v" }, + onAction: () => { void verifyClipboardChecksum(); } + }), + Action({ + title: t("pickFileAction"), + icon: Icon.Document, + shortcut: { modifiers: ["ctrl"], key: "o" }, + onAction: () => { void pickFileAndHash(); } + }), + ...globalActions + ]) + }); + }); } else if (!inputText) { items = [ List.Item({ @@ -422,19 +521,41 @@ export default function CryptoToolCommand() { isShowingDetail: Boolean(inputText || fileHash), searchBarPlaceholder: mode === "hash" ? t("placeholderHash") : mode === "base64-decode" ? t("placeholderBase64") : t("placeholderCodec"), searchText: inputText, - onSearchTextChange: (text: string) => { setFileHash(null); setInputText(text); }, + onSearchTextChange: (text: string) => { setFileHash(null); setChecksumMatch(null); setInputText(text); }, filterBar: { actions: [ + { + id: "pick-file", + label: t("pickFileBtn"), + title: t("pickFileAction"), + icon: Icon.Document, + style: "primary", + onAction: () => { + void pickFileAndHash(); + } + }, { id: "read-clipboard", label: t("readClipboardBtn"), title: t("pasteFromClipboard"), icon: Icon.Clipboard, - style: "primary", onAction: () => { void pasteFromClipboard(); } - } + }, + ...(fileHash && !inputText + ? [ + { + id: "verify-clipboard-hash", + label: t("verifyClipboardHashBtn"), + title: t("verifyClipboardHashAction"), + icon: Icon.Check, + onAction: () => { + void verifyClipboardChecksum(); + } + } + ] + : []) ] }, searchBarAccessory: List.Dropdown( diff --git a/extensions/crypto-tool/src/logic.ts b/extensions/crypto-tool/src/logic.ts index b5ccd67f..ed848f63 100644 --- a/extensions/crypto-tool/src/logic.ts +++ b/extensions/crypto-tool/src/logic.ts @@ -100,6 +100,14 @@ export interface FileHashResult { sha512?: string; } +export interface ClipboardChecksumMatch { + normalized: string; + length: number; + isMatch: boolean; + matchedAlgorithm?: "MD5" | "SHA-1" | "SHA-256" | "SHA-512"; + matchedItemId?: "file-md5-lower" | "file-sha1" | "file-sha256" | "file-sha512"; +} + type HostEnvelope = { success?: boolean; data?: unknown; @@ -141,7 +149,75 @@ async function callHostMethod(method: string, params: Record): } /** - * 读取本地文件真实字节计算哈希摘要(或调用宿主 filesearch_sha256),绝不将路径字符串当文本计算 + * 打开宿主系统文件选择对话框选择本地文件,用户取消时返回 null + */ +export async function pickFileForHash(title?: string): Promise { + const data = await callHostMethod("window_show_open_dialog", { + ...(title ? { title } : {}), + properties: ["openFile"] + }); + if (typeof data === "string") { + const trimmed = data.trim(); + return trimmed || null; + } + if (!isRecord(data)) return null; + if (data.canceled === true) return null; + if (typeof data.filePath === "string" && data.filePath.trim()) { + return data.filePath.trim(); + } + if (Array.isArray(data.filePaths)) { + const first = data.filePaths.find((p): p is string => typeof p === "string" && p.trim().length > 0); + return first ? first.trim() : null; + } + return null; +} + +const CHECKSUM_HEX_LENGTHS = new Set([32, 40, 64, 128]); + +/** + * 识别剪贴板中的十六进制校验值(支持可选算法前缀如 sha256: / md5=)并与文件哈希结果自动比对。 + * 非合法十六进制哈希串时返回 null。 + */ +export function matchClipboardChecksum(fileHash: FileHashResult, clipboardText: string): ClipboardChecksumMatch | null { + const trimmed = (clipboardText ?? "").trim(); + if (!trimmed) return null; + const cleaned = trimmed + .replace(/^(?:md5|sha-?1|sha-?256|sha-?512)\s*[:=]\s*/i, "") + .trim(); + if (!/^[0-9a-f]+$/i.test(cleaned) || !CHECKSUM_HEX_LENGTHS.has(cleaned.length)) { + return null; + } + const normalized = cleaned.toLowerCase(); + const candidates: Array<{ + algo: "MD5" | "SHA-1" | "SHA-256" | "SHA-512"; + id: "file-md5-lower" | "file-sha1" | "file-sha256" | "file-sha512"; + value?: string; + }> = [ + { algo: "SHA-256", id: "file-sha256", value: fileHash.sha256 }, + { algo: "MD5", id: "file-md5-lower", value: fileHash.md5 }, + { algo: "SHA-1", id: "file-sha1", value: fileHash.sha1 }, + { algo: "SHA-512", id: "file-sha512", value: fileHash.sha512 } + ]; + for (const c of candidates) { + if (c.value && c.value.toLowerCase() === normalized) { + return { + normalized, + length: normalized.length, + isMatch: true, + matchedAlgorithm: c.algo, + matchedItemId: c.id + }; + } + } + return { + normalized, + length: normalized.length, + isMatch: false + }; +} + +/** + * 读取本地文件真实字节计算哈希摘要(优先流式 filesystem_hash_file,回退 filesystem_read_file / filesearch_sha256),绝不将路径字符串当文本计算 */ export async function calculateFileHash(filePath: string): Promise { const s = cryptoLogicStrings(); @@ -152,6 +228,40 @@ export async function calculateFileHash(filePath: string): Promise = (() => { + const map: Record = {}; + for (let i = 0; i < CROCKFORD_ALPHABET.length; i += 1) { + const ch = CROCKFORD_ALPHABET[i]!; + map[ch] = i; + map[ch.toLowerCase()] = i; + } + return map; +})(); + const UUID_ERRORS: Record string; invalidTimestamp: string; + invalidNanoIdSize: string; batchUniqueFailed: string; }> = { "zh-CN": { noSecureRandom: "当前环境不支持安全随机数", invalidCount: `数量必须是 1 到 ${MAX_UUID_BATCH_COUNT} 的整数`, - unsupportedVersion: (v) => `不支持的 UUID 版本: ${v}`, - invalidTimestamp: "当前系统时间戳超出 UUID 编码范围", - batchUniqueFailed: "批量生成 UUID 唯一性校验失败" + unsupportedVersion: (v) => `不支持的 ID 类型: ${v}`, + invalidTimestamp: "当前系统时间戳超出编码范围", + invalidNanoIdSize: "NanoID 长度必须是 1 到 256 的整数", + batchUniqueFailed: "批量生成 ID 唯一性校验失败" }, "en-US": { noSecureRandom: "Secure random generation is not supported in this environment", invalidCount: `Count must be an integer between 1 and ${MAX_UUID_BATCH_COUNT}`, - unsupportedVersion: (v) => `Unsupported UUID version: ${v}`, - invalidTimestamp: "Timestamp is out of range for UUID encoding", - batchUniqueFailed: "Failed to guarantee uniqueness in UUID batch" + unsupportedVersion: (v) => `Unsupported ID type: ${v}`, + invalidTimestamp: "Timestamp is out of range for encoding", + invalidNanoIdSize: "NanoID size must be an integer between 1 and 256", + batchUniqueFailed: "Failed to guarantee uniqueness in ID batch" } }; @@ -86,7 +105,6 @@ export function generateUuidV7(nowMs: number = Date.now()): string { /** 生成标准小写 UUID v1(RFC 9562 100ns Gregorian 纪元时间戳 + 随机组播节点) */ export function generateUuidV1(nowMs: number = Date.now()): string { - const GREGORIAN_OFFSET = 122192928000000000n; if (!Number.isSafeInteger(nowMs)) { throw new Error(uuidErrors().invalidTimestamp); } @@ -113,9 +131,53 @@ export function generateUuidV1(nowMs: number = Date.now()): string { ].join("-"); } -/** 将标准 UUID 按指定格式输出 */ -export function formatUuid(uuid: string, format: UuidFormat): string { - const raw = uuid.toLowerCase(); +/** 生成 26 位标准 ULID(48-bit Unix 毫秒时间戳 + 80-bit 安全随机,Crockford Base32) */ +export function generateUlid(nowMs: number = Date.now()): string { + if (!Number.isSafeInteger(nowMs) || nowMs < 0 || BigInt(nowMs) > 0xffffffffffffn) { + throw new Error(uuidErrors().invalidTimestamp); + } + const timeChars = new Array(10); + let ts = BigInt(nowMs); + for (let i = 9; i >= 0; i -= 1) { + timeChars[i] = CROCKFORD_ALPHABET[Number(ts & 31n)]!; + ts >>= 5n; + } + // 80-bit 随机 = 10 字节 -> 16 个 5-bit Base32 字符 + const randBytes = randomBytes(10); + let randBits = 0n; + for (let i = 0; i < 10; i += 1) { + randBits = (randBits << 8n) | BigInt(randBytes[i]!); + } + const randChars = new Array(16); + for (let i = 15; i >= 0; i -= 1) { + randChars[i] = CROCKFORD_ALPHABET[Number(randBits & 31n)]!; + randBits >>= 5n; + } + return timeChars.join("") + randChars.join(""); +} + +/** 生成 URL 安全 NanoID(默认 21 位,64 字符集,每字节低 6 位无模偏差) */ +export function generateNanoId(size: number = DEFAULT_NANOID_SIZE): string { + if (!Number.isSafeInteger(size) || size < 1 || size > 256) { + throw new Error(uuidErrors().invalidNanoIdSize); + } + const bytes = randomBytes(size); + let out = ""; + for (let i = 0; i < size; i += 1) { + out += NANOID_ALPHABET[bytes[i]! & 63]!; + } + return out; +} + +/** 将 ID 按指定格式输出(ULID 支持大小写,NanoID 保留区分大小写的原始值) */ +export function formatUuid(id: string, format: UuidFormat, version?: UuidVersion): string { + if (version === "nanoid") { + return id; + } + if (version === "ulid") { + return format === "no-dash" ? id.toLowerCase() : id.toUpperCase(); + } + const raw = id.toLowerCase(); switch (format) { case "standard": return raw; @@ -131,7 +193,7 @@ export function formatUuid(uuid: string, format: UuidFormat): string { } export function isUuidVersion(value: string): value is UuidVersion { - return value === "v4" || value === "v7" || value === "v1"; + return value === "v4" || value === "v7" || value === "v1" || value === "ulid" || value === "nanoid"; } export function isUuidFormat(value: string): value is UuidFormat { @@ -144,11 +206,11 @@ export interface GenerateUuidBatchOptions { count?: number | string; } -/** 批量生成去重后的 UUID */ +/** 批量生成去重后的 UUID / ULID / NanoID */ export function generateUuidBatch(options: GenerateUuidBatchOptions = {}): string[] { const errs = uuidErrors(); const version: UuidVersion = options.version ?? "v4"; - const format: UuidFormat = options.format ?? "standard"; + const format: UuidFormat = options.format ?? (version === "ulid" ? "uppercase" : "standard"); const rawCount = options.count ?? 5; let count: number; @@ -167,7 +229,9 @@ export function generateUuidBatch(options: GenerateUuidBatchOptions = {}): strin const generators: Record string> = { v4: generateUuidV4, v7: generateUuidV7, - v1: generateUuidV1 + v1: generateUuidV1, + ulid: generateUlid, + nanoid: generateNanoId }; const gen = generators[version]; if (!gen) { @@ -184,7 +248,7 @@ export function generateUuidBatch(options: GenerateUuidBatchOptions = {}): strin const raw = gen(); if (seen.has(raw)) continue; seen.add(raw); - results.push(formatUuid(raw, format)); + results.push(formatUuid(raw, format, version)); } if (results.length !== count) { @@ -193,3 +257,136 @@ export function generateUuidBatch(options: GenerateUuidBatchOptions = {}): strin return results; } + +export interface ParsedIdentifier { + kind: "uuid" | "ulid" | "nanoid"; + label: string; + canonical: string; + version?: string; + variant?: string; + timestampMs?: number; + timestampIso?: string; + entropyBits?: number; + node?: string; +} + +const UUID_DASHED_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; +const UUID_COMPACT_RE = /^[0-9a-f]{32}$/i; +const ULID_RE = /^[0-7][0-9A-HJKMNP-TV-Z]{25}$/i; +const NANOID_STANDARD_RE = /^[A-Za-z0-9_-]{21}$/; + +function describeUuidVariant(variantNibble: number): string { + if ((variantNibble & 0x8) === 0) return "NCS (0xxx)"; + if ((variantNibble & 0xc) === 0x8) return "RFC 4122 / 9562 (10xx)"; + if ((variantNibble & 0xe) === 0xc) return "Microsoft (110x)"; + return "Future Reserved (111x)"; +} + +/** 自动识别并解析 UUID (v7/v4/v1 等)、ULID、NanoID;无法识别返回 null */ +export function parseIdentifier(rawInput: string): ParsedIdentifier | null { + const trimmed = (rawInput ?? "").trim(); + if (!trimmed) return null; + + // 1. UUID (标准带连字符或 32 位无连字符) + if (UUID_DASHED_RE.test(trimmed) || UUID_COMPACT_RE.test(trimmed)) { + const hex = trimmed.replace(/-/g, "").toLowerCase(); + const canonical = formatHexAsUuid(hex); + if (hex === "00000000000000000000000000000000") { + return { kind: "uuid", label: "Nil UUID", canonical, version: "nil", variant: "Nil" }; + } + if (hex === "ffffffffffffffffffffffffffffffff") { + return { kind: "uuid", label: "Max UUID", canonical, version: "max", variant: "Max" }; + } + const verNibble = parseInt(hex[12]!, 16); + const varNibble = parseInt(hex[16]!, 16); + const variant = describeUuidVariant(varNibble); + + if (verNibble === 7) { + const ms = Number(BigInt("0x" + hex.slice(0, 12))); + const date = new Date(ms); + return { + kind: "uuid", + label: "UUID v7", + canonical, + version: "v7", + variant, + timestampMs: ms, + timestampIso: Number.isNaN(date.getTime()) ? undefined : date.toISOString(), + entropyBits: 74 + }; + } + + if (verNibble === 1) { + const timeLow = BigInt("0x" + hex.slice(0, 8)); + const timeMid = BigInt("0x" + hex.slice(8, 12)); + const timeHi = BigInt("0x" + hex.slice(13, 16)); + const ticks = (timeHi << 48n) | (timeMid << 32n) | timeLow; + const unixMsBig = (ticks - GREGORIAN_OFFSET) / 10000n; + const ms = Number(unixMsBig); + const date = new Date(ms); + const nodeHex = hex.slice(20, 32).match(/.{2}/g)?.join(":") ?? hex.slice(20, 32); + return { + kind: "uuid", + label: "UUID v1", + canonical, + version: "v1", + variant, + timestampMs: Number.isSafeInteger(ms) ? ms : undefined, + timestampIso: Number.isNaN(date.getTime()) ? undefined : date.toISOString(), + node: nodeHex + }; + } + + if (verNibble === 4) { + return { + kind: "uuid", + label: "UUID v4", + canonical, + version: "v4", + variant, + entropyBits: 122 + }; + } + + return { + kind: "uuid", + label: `UUID v${verNibble}`, + canonical, + version: `v${verNibble}`, + variant + }; + } + + // 2. ULID (26 位 Crockford Base32,首位 0-7 防止 48-bit 溢出) + if (ULID_RE.test(trimmed)) { + const upper = trimmed.toUpperCase(); + let ts = 0n; + for (let i = 0; i < 10; i += 1) { + const val = CROCKFORD_DECODE_MAP[upper[i]!]; + if (val === undefined) return null; + ts = (ts << 5n) | BigInt(val); + } + const ms = Number(ts); + const date = new Date(ms); + return { + kind: "ulid", + label: "ULID", + canonical: upper, + timestampMs: ms, + timestampIso: Number.isNaN(date.getTime()) ? undefined : date.toISOString(), + entropyBits: 80 + }; + } + + // 3. NanoID (标准 21 位 URL-safe 字符串,排除纯数字避免与数量输入冲突) + if (NANOID_STANDARD_RE.test(trimmed) && !/^\d+$/.test(trimmed)) { + return { + kind: "nanoid", + label: "NanoID (21 chars)", + canonical: trimmed, + entropyBits: 126 + }; + } + + return null; +} diff --git a/extensions/crypto-tool/src/uuid.ts b/extensions/crypto-tool/src/uuid.ts index 08baac6a..bd10fd17 100644 --- a/extensions/crypto-tool/src/uuid.ts +++ b/extensions/crypto-tool/src/uuid.ts @@ -17,18 +17,24 @@ import { formatUuid, generateUuidBatch, isUuidVersion, + parseIdentifier, type UuidVersion, - type UuidFormat + type UuidFormat, + type ParsedIdentifier } from "./uuid-logic.js"; export { generateUuidV1, generateUuidV4, generateUuidV7, + generateUlid, + generateNanoId, formatUuid, generateUuidBatch, + parseIdentifier, type UuidVersion, - type UuidFormat + type UuidFormat, + type ParsedIdentifier } from "./uuid-logic.js"; const DEFAULT_BATCH_COUNT = 5; @@ -45,9 +51,17 @@ const FORMAT_EXAMPLES: Record = { function versionLabel(version: UuidVersion): string { if (version === "v7") return t("uuidVersionV7"); if (version === "v1") return t("uuidVersionV1"); + if (version === "ulid") return t("uuidVersionUlid"); + if (version === "nanoid") return t("uuidVersionNanoid"); return t("uuidVersionV4"); } +function versionBadge(version: UuidVersion): string { + if (version === "ulid") return "ULID"; + if (version === "nanoid") return "NanoID"; + return version.toUpperCase(); +} + function formatLabel(format: UuidFormat): string { switch (format) { case "uppercase": @@ -144,7 +158,7 @@ function buildResultItems(params: BuildResultItemsParams) { List.Item({ id: `uuid-item-${index}`, title: uuid, - subtitle: `#${index + 1} · ${version.toUpperCase()}`, + subtitle: `#${index + 1} · ${versionBadge(version)}`, icon: Icon.Key, accessories: [{ text: currentFormatLabel }, { text: t("uuidEnterCopyHint") }], actions: ActionPanel({ title: t("actionsTitle") }, [ @@ -178,6 +192,59 @@ function buildResultItems(params: BuildResultItemsParams) { ); } +function buildParsedSection(parsed: ParsedIdentifier, onCopySingle: (value: string) => Promise) { + const details: string[] = []; + if (parsed.timestampIso !== undefined && parsed.timestampMs !== undefined) { + details.push(t("uuidParsedTimeMeta", { iso: parsed.timestampIso, ms: parsed.timestampMs })); + } + if (parsed.variant) { + details.push(t("uuidParsedVariantMeta", { variant: parsed.variant })); + } + if (parsed.entropyBits !== undefined) { + details.push(t("uuidParsedEntropyMeta", { bits: parsed.entropyBits })); + } + if (parsed.node) { + details.push(t("uuidParsedNodeMeta", { node: parsed.node })); + } + + const parsedActions = [ + Action({ + title: t("uuidParsedCopyCanonical"), + icon: Icon.CopyClipboard, + onAction: () => onCopySingle(parsed.canonical) + }), + ...(parsed.timestampIso + ? [ + Action({ + title: t("uuidParsedCopyTimestamp"), + icon: Icon.Clock, + onAction: () => onCopySingle(parsed.timestampIso!) + }) + ] + : []), + ...(parsed.timestampMs !== undefined + ? [ + Action({ + title: t("uuidParsedCopyEpochMs"), + icon: Icon.Clock, + onAction: () => onCopySingle(String(parsed.timestampMs)) + }) + ] + : []) + ]; + + return List.Section({ title: t("uuidSectionParsed") }, [ + List.Item({ + id: "uuid-parsed-result", + title: `${parsed.label} · ${parsed.canonical}`, + subtitle: details.join(" | "), + icon: Icon.MagnifyingGlass, + accessories: [{ tag: parsed.label }], + actions: ActionPanel({ title: t("actionsTitle") }, parsedActions) + }) + ]); +} + export default function GenUuidCommand() { useLocale(); const [version, setVersion] = useState("v4"); @@ -188,9 +255,10 @@ export default function GenUuidCommand() { const [rawUuids, setRawUuids] = useState(initial.uuids); const [error, setError] = useState(initial.error); - const formattedUuids = rawUuids.map((id) => formatUuid(id, format)); + const formattedUuids = rawUuids.map((id) => formatUuid(id, format, version)); const trimmed = searchText.trim(); const isNumericInput = trimmed.length > 0 && NUMERIC_INPUT_RE.test(trimmed); + const parsedIdentifier = !isNumericInput && trimmed ? parseIdentifier(trimmed) : null; const regenerate = async ( nextCount: number | string = count, @@ -205,7 +273,7 @@ export default function GenUuidCommand() { if (!silent) { await showToast( Toast.Style.Success, - t("uuidRegeneratedToast", { count: fresh.length, version: nextVersion.toUpperCase() }) + t("uuidRegeneratedToast", { count: fresh.length, version: versionBadge(nextVersion) }) ); } } catch (err: unknown) { @@ -266,7 +334,7 @@ export default function GenUuidCommand() { await showToast(Toast.Style.Success, t("uuidCopiedAllToast", { count: list.length })); }; - const displayUuids = isNumericInput + const displayUuids = isNumericInput || parsedIdentifier ? formattedUuids : formattedUuids.filter((item) => trimmed ? item.toLowerCase().includes(trimmed.toLowerCase()) : true @@ -314,11 +382,12 @@ export default function GenUuidCommand() { ) }, [ + ...(parsedIdentifier ? [buildParsedSection(parsedIdentifier, handleCopySingle)] : []), List.Section( { title: t("uuidSectionResults", { count: displayUuids.length, - version: version.toUpperCase(), + version: versionBadge(version), format: currentFormatLabel }) }, diff --git a/extensions/crypto-tool/tests/index.test.mjs b/extensions/crypto-tool/tests/index.test.mjs deleted file mode 100644 index aa7404d8..00000000 --- a/extensions/crypto-tool/tests/index.test.mjs +++ /dev/null @@ -1,281 +0,0 @@ -import test from 'node:test' -import assert from 'node:assert/strict' -import crypto from 'node:crypto' -import { createHost, mount, mountPushed } from '../../shared/test-harness.mjs' -import CryptoToolCommand from '../dist/index.js' -import { calculateMultiHash, encodeBase64, decodeBase64, aesEncrypt, aesDecrypt, calculateHmac, codeBlockMarkdown, valueMarkdown } from '../dist/logic.js' - -const host = createHost() -test.beforeEach(() => host.reset()) - -test('摘要与 HMAC 与 Node 标准实现逐字节一致(含中文、Emoji、空串)', () => { - for (const text of ['', 'abc', '中文😀', 'x'.repeat(1000)]) { - const h = calculateMultiHash(text) - for (const alg of ['md5', 'sha1', 'sha256', 'sha512']) { - assert.equal(h[alg], crypto.createHash(alg).update(text, 'utf8').digest('hex'), `${alg}(${text.slice(0, 8)})`) - assert.equal(calculateHmac(alg, text, 'k'), crypto.createHmac(alg, 'k').update(text, 'utf8').digest('hex')) - } - assert.equal(h.base64, Buffer.from(text, 'utf8').toString('base64')) - } -}) - -test('AES-256-CBC 与 Node 标准实现一致,可互相解密', async () => { - const key = 'master-key' - const kb = crypto.createHash('sha256').update(key).digest() - const c = crypto.createCipheriv('aes-256-cbc', kb, kb.subarray(0, 16)) - const expected = c.update('机密内容', 'utf8', 'base64') + c.final('base64') - const enc = await aesEncrypt('机密内容', key) - assert.equal(enc.result, expected) - assert.equal((await aesDecrypt(expected, key)).result, '机密内容') -}) - -test('[篡改] 口令错误、密文损坏、格式非法时拒绝,不输出乱码', async () => { - const enc = await aesEncrypt('sensitive', 'right') - assert.equal((await aesDecrypt(enc.result, 'wrong')).success, false) - const tampered = Buffer.from(enc.result, 'base64') - tampered[tampered.length - 1] ^= 1 - assert.equal((await aesDecrypt(tampered.toString('base64'), 'right')).success, false) - for (const bad of ['', '!!!', 'AAAA', 'abc']) assert.equal((await aesDecrypt(bad, 'right')).success, false) - assert.equal((await aesEncrypt('x', '')).success, false) -}) - -test('Base64 解码严格校验:非法字符报错,二进制数据不当作文本显示', () => { - assert.equal(decodeBase64(encodeBase64('极客效率')).result, '极客效率') - assert.equal(decodeBase64('!!!not-base64!!!').success, false) - assert.equal(decodeBase64(Buffer.from([0xff, 0xfe, 0x00]).toString('base64')).success, false) - assert.equal(decodeBase64('5p6B5a6i').result, '极客') -}) - -test('界面:打开不再崩溃;默认为空;输入后显示正确的 SHA-256 并可复制', async () => { - const view = await mount(CryptoToolCommand) - assert.equal(view.tree().props.searchText, '') - await view.search('abc') - const sha = view.item('sha256') - assert.equal(sha.props.title, 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad') - await view.run(sha, '复制') - assert.equal(host.clipboard.text, sha.props.title) -}) - -test('界面:AES 表单加密后可解密回原文', async () => { - const view = await mount(CryptoToolCommand) - await view.run(null, 'AES 加解密…') - const form = await mountPushed(host) - await form.fill('text', 'hello') - await form.fill('key', 'pw') - await form.run(null, '加密') - const expected = (await aesEncrypt('hello', 'pw')).result - const result = () => form.tree().children.find((c) => c.type === 'Form.Description').props.text - assert.equal(result(), expected) - await form.fill('direction', 'decrypt') - await form.fill('text', expected) - await form.run(null, '解密') - assert.equal(result(), 'hello') - await form.fill('key', 'wrong') - await form.run(null, '解密') - assert.notEqual(result(), 'hello') - assert.match(String(host.lastToast().title), /解密失败/) -}) - -// ---- 表单动作:不再有「返回」占位(crypto-tool-3)---- - -const actionTitles = (view) => view.actions().map((a) => a.props.title) -const description = (form) => form.tree().children.find((c) => c.type === 'Form.Description').props.text - -async function openForm(title) { - const view = await mount(CryptoToolCommand) - await view.run(null, title) - return mountPushed(host) -} - -test('AES / HMAC 表单不再声明「返回」动作:第 1 个动作是执行,⌘↵ 不会落到关闭表单上', async () => { - const aes = await openForm('AES 加解密…') - assert.deepEqual(actionTitles(aes), ['加密']) - assert.equal(aes.actions()[0].type, 'Action.SubmitForm') - // 提示与实际操作一致:不再写「按回车执行」(多行明文框里回车只会换行) - assert.doesNotMatch(description(aes), /回车/) - assert.match(description(aes), /「加密」/) - await aes.fill('direction', 'decrypt') - assert.deepEqual(actionTitles(aes), ['解密']) - assert.match(description(aes), /「解密」/) - - await aes.fill('direction', 'encrypt') - await aes.fill('text', '重要的明文内容\n第二行') - await aes.fill('key', 'secret') - await aes.run(null, '加密') - assert.deepEqual(actionTitles(aes), ['加密', '复制结果']) - assert.ok(!actionTitles(aes).includes('返回')) - // 输入没有被任何动作清掉 - assert.equal(aes.field('text').props.value, '重要的明文内容\n第二行') - - host.reset() - const hmac = await openForm('HMAC 计算…') - assert.deepEqual(actionTitles(hmac), [], '消息和密钥都为空时不提供复制') - await hmac.fill('text', 'msg') - await hmac.fill('key', 'k') - assert.deepEqual(actionTitles(hmac), ['复制 HMAC']) - await hmac.run(null, '复制 HMAC') - assert.equal(host.clipboard.text, crypto.createHmac('sha256', 'k').update('msg').digest('hex')) - assert.equal(host.pushed.length, 1, '复制后表单仍在,没有被关闭') -}) - -test('[异常] AES 口令为空时加密失败:只剩执行动作,不出现复制,已填明文保留', async () => { - const aes = await openForm('AES 加解密…') - await aes.fill('text', 'hello') - await aes.run(null, '加密') - assert.deepEqual(actionTitles(aes), ['加密']) - assert.match(String(host.lastToast().title), /加密失败/) - assert.equal(aes.field('text').props.value, 'hello') -}) - -// ---- AES 结果必须对应当前输入(crypto-tool-v1)---- - -test('AES:明文、口令、IV、方向任一改变都清空旧结果,「复制结果」随之消失', async () => { - const aes = await openForm('AES 加解密…') - const encryptOnce = async () => { - await aes.fill('text', 'hello') - await aes.fill('key', 'secret') - await aes.fill('iv', '') - await aes.run(null, '加密') - assert.equal(description(aes), (await aesEncrypt('hello', 'secret')).result) - assert.ok(actionTitles(aes).includes('复制结果')) - } - for (const [field, value] of [['text', 'changed plaintext'], ['key', 'otherkey'], ['iv', '0123456789abcdef'], ['direction', 'decrypt']]) { - await aes.fill('direction', 'encrypt') - await encryptOnce() - await aes.fill(field, value) - assert.match(description(aes), /结果显示在这里/, `${field} 改变后仍显示旧结果`) - assert.ok(!actionTitles(aes).includes('复制结果'), `${field} 改变后仍可复制旧结果`) - } - - // 改完重新执行:复制到的是与当前输入对应的新密文,能用当前口令解回当前明文 - await aes.fill('direction', 'encrypt') - await aes.fill('text', 'changed plaintext') - await aes.fill('key', 'otherkey') - await aes.fill('iv', '') - await aes.run(null, '加密') - await aes.run(null, '复制结果') - assert.equal(host.clipboard.text, (await aesEncrypt('changed plaintext', 'otherkey')).result) - assert.equal((await aesDecrypt(host.clipboard.text, 'otherkey')).result, 'changed plaintext') -}) - -test('[异常] AES:成功后再执行失败(密文被篡改)不残留上一次的结果', async () => { - const aes = await openForm('AES 加解密…') - await aes.fill('text', 'hello') - await aes.fill('key', 'secret') - await aes.run(null, '加密') - const cipher = description(aes) - await aes.fill('direction', 'decrypt') - await aes.fill('text', cipher) - await aes.run(null, '解密') - assert.equal(description(aes), 'hello') - // 密文被篡改:解密失败,结果区回到提示,不再显示上一次解出的明文 - const bad = Buffer.from(cipher, 'base64') - bad[bad.length - 1] ^= 1 - await aes.fill('text', bad.toString('base64')) - await aes.run(null, '解密') - assert.notEqual(description(aes), 'hello') - assert.ok(!actionTitles(aes).includes('复制结果')) - assert.match(String(host.lastToast().title), /解密失败/) -}) - -// ---- 长结果在右侧预览里完整显示(crypto-tool-5)---- - -function parseFence(markdown) { - const lines = markdown.split('\n') - const fence = lines[0] - assert.match(fence, /^`{3,}$/) - assert.equal(lines[lines.length - 1], fence) - const body = lines.slice(1, -1) - // 内容里不能出现能提前结束代码块的围栏行 - for (const line of body) assert.ok(!(new RegExp('^ {0,3}`{' + fence.length + ',}\\s*$').test(line)), `内容行提前结束代码块:${line}`) - return body.join('\n') -} - -test('Base64 解码:多行长文本在右侧预览里原样完整显示(换行、缩进、Markdown 符号、反引号围栏)', async () => { - const original = '第一行:' + '较长的中文内容,'.repeat(40) + '\n{"sub":"1234567890","name":"张三"}\n\n 缩进行 *星号* _下划线_ # 井号\n```js\nconsole.log(1)\n```\n````' - const view = await mount(CryptoToolCommand) - await view.dropdown('base64-decode') - await view.search(Buffer.from(original, 'utf8').toString('base64')) - assert.equal(view.tree().props.isShowingDetail, true) - const item = view.item('decoded') - assert.equal(item.props.detail.type, 'List.Item.Detail') - assert.equal(parseFence(item.props.detail.props.markdown), original) - await view.run(item, '复制') - assert.equal(host.clipboard.text, original) - - // 单行长文本(如 JWT payload 的 JSON)用可折行的行内代码,不用横向滚动 - const json = JSON.stringify({ sub: '1234567890', name: '张三', note: '较长的说明'.repeat(30), admin: true }) - await view.search(Buffer.from(json, 'utf8').toString('base64url')) - assert.equal(view.item('decoded').props.detail.props.markdown, '`' + json + '`') -}) - -test('[异常] Base64:空输入、非法字符、二进制数据都不开空预览,列表保持全宽', async () => { - const view = await mount(CryptoToolCommand) - await view.dropdown('base64-decode') - assert.equal(view.tree().props.isShowingDetail, false) - assert.deepEqual(view.actions(view.item('empty')).map(a => a.props.title), ['从剪贴板粘贴']) - assert.equal(view.item('empty').props.detail, undefined) - for (const bad of ['!!!not-base64!!!', Buffer.from([0xff, 0xfe, 0x00]).toString('base64')]) { - await view.search(bad) - assert.equal(view.items().length, 2, '编码结果仍然给出,解码失败单独提示') - assert.ok(view.item('encoded')) - assert.equal(view.item('decode-error').props.detail, undefined) - } - await view.search(' ') - assert.equal(view.item('empty').props.detail, undefined) -}) - -test('散列模式:SHA-512 与长 Base64 / URL 编码在右侧预览里给出完整值(可折行的行内代码)', async () => { - const input = '中文 & *x* _y_ ' + 'z'.repeat(500) - const view = await mount(CryptoToolCommand) - assert.equal(view.tree().props.isShowingDetail, false, '空输入不开预览') - await view.search(input) - assert.equal(view.tree().props.isShowingDetail, true) - const expected = { - sha512: crypto.createHash('sha512').update(input).digest('hex'), - base64: Buffer.from(input).toString('base64'), - 'url-encoded': encodeURIComponent(input) - } - for (const [id, value] of Object.entries(expected)) { - const md = view.item(id).props.detail.props.markdown - assert.equal(md, '`' + value + '`', id) - } - // 每一行都有预览,切换选中项时布局不会在全宽和分栏之间跳动 - for (const it of view.items()) assert.equal(it.props.detail?.type, 'List.Item.Detail', it.props.id) -}) - -test('[边界] 预览 Markdown:含空白或反引号的值退回围栏代码块,空值不报错', () => { - assert.equal(valueMarkdown('abc'), '`abc`') - assert.equal(valueMarkdown('a b *c* # d'), '`a b *c* # d`') - assert.equal(valueMarkdown('{"sub":"1","name":"张三"}'), '`{"sub":"1","name":"张三"}`') - for (const ws of ['a b', ' a', 'a ', 'a\tb', 'a\r\nb']) assert.equal(parseFence(valueMarkdown(ws)), ws) - assert.equal(parseFence(valueMarkdown('a`b')), 'a`b') - assert.equal(parseFence(valueMarkdown('')), '') - assert.equal(parseFence(codeBlockMarkdown('x\n`````\ny')), 'x\n`````\ny') - assert.equal(codeBlockMarkdown('x\n`````\ny').split('\n')[0], '``````') - assert.equal(parseFence(codeBlockMarkdown(undefined)), '') -}) - -test('文件粘贴哈希:Ctrl+V 粘贴文件时读取真实字节计算哈希,绝不将路径字符串当作文本内容计算', async () => { - const filePath = '/Users/me/release-package.bin' - const rawBytes = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0xff, 0x42]) - const expectedSha256 = crypto.createHash('sha256').update(rawBytes).digest('hex') - const expectedMd5 = crypto.createHash('md5').update(rawBytes).digest('hex') - const pathTextSha256 = crypto.createHash('sha256').update(filePath, 'utf8').digest('hex') - - host.ipc.filesystem_read_file = async (params) => { - assert.equal(params.path, filePath) - assert.equal(params.encoding, 'base64') - return { content: rawBytes.toString('base64') } - } - - const view = await mount(CryptoToolCommand) - await view.pasteFiles([filePath]) - const shaItem = view.item('file-sha256') - assert.equal(shaItem.props.title, expectedSha256) - assert.notEqual(shaItem.props.title, pathTextSha256) - assert.match(shaItem.props.subtitle, /release-package\.bin/) - assert.match(shaItem.props.detail.props.markdown, /\/Users\/me\/release-package\.bin/) - assert.equal(view.item('file-md5-lower').props.title, expectedMd5) - view.unmount() -}) diff --git a/extensions/crypto-tool/tests/review-regressions.test.mjs b/extensions/crypto-tool/tests/review-regressions.test.mjs index bc4d4d04..f5602fd3 100644 --- a/extensions/crypto-tool/tests/review-regressions.test.mjs +++ b/extensions/crypto-tool/tests/review-regressions.test.mjs @@ -102,3 +102,58 @@ test('hmac 命令直接打开 HMAC 表单,结果与 Node 标准实现一致', assert.equal(host.clipboard.text, createHmac('sha256', 'k').update('消息😀').digest('hex')) } finally { form.unmount() } }) + +test('filterBar 显式 [选择文件] 与 [读剪贴板] 入口及本地文件哈希 + 剪贴板校验值自动比对', async () => { + const { createHash } = await import('node:crypto') + const { Color } = await import('@ztools/declarative-ui') + const fileBytes = Buffer.from('hello-ztools-file-payload') + const expectedSha256 = createHash('sha256').update(fileBytes).digest('hex') + const expectedMd5 = createHash('md5').update(fileBytes).digest('hex') + + const origElectron = globalThis.window?.__ztoolsElectron + globalThis.window = globalThis.window || {} + globalThis.window.__ztoolsElectron = { + transport: { + methods: { + window_show_open_dialog: async () => ({ success: true, data: { canceled: false, filePath: 'D:/downloads/demo.bin' } }), + filesystem_read_file: async () => ({ success: true, data: { content: fileBytes.toString('base64') } }) + } + } + } + + const view = await mount(Command) + try { + const barActions = view.tree().props.filterBar?.actions || [] + assert.deepEqual(barActions.map((a) => a.id), ['pick-file', 'read-clipboard']) + + // 剪贴板预置官方 SHA-256(带 sha256: 前缀)-> 选择文件后自动比对命中 + host.clipboard.text = `sha256:${expectedSha256.toUpperCase()}` + await barActions.find((a) => a.id === 'pick-file').onAction() + await tick(20) + + const shaItem = view.item('file-sha256') + assert.equal(shaItem.props.title, expectedSha256) + assert.equal(view.item('file-md5-lower').props.title, expectedMd5) + assert.equal(shaItem.props.accessories[0].tag, '与剪贴板一致') + assert.match(shaItem.props.detail.props.markdown, /完全匹配/) + + // 剪贴板换为不匹配的 64 位哈希 -> 显式触发比对提示不一致 + host.clipboard.text = '0'.repeat(64) + const verifyBtn = (view.tree().props.filterBar?.actions || []).find((a) => a.id === 'verify-clipboard-hash') + assert.ok(verifyBtn) + await verifyBtn.onAction() + await tick(20) + assert.equal(view.item('file-sha256').props.accessories[0].tag.value, '与剪贴板不一致') + assert.equal(view.item('file-sha256').props.accessories[0].tag.color, Color.Red) + + // 剪贴板为非哈希文本 -> 比对提示格式不合法 + host.clipboard.text = 'not-a-hash' + await verifyBtn.onAction() + await tick(20) + assert.match(host.lastToast().title, /十六进制哈希值/) + } finally { + view.unmount() + if (origElectron === undefined) delete globalThis.window.__ztoolsElectron + else globalThis.window.__ztoolsElectron = origElectron + } +}) diff --git a/extensions/crypto-tool/tests/uuid-enhancements.test.mjs b/extensions/crypto-tool/tests/uuid-enhancements.test.mjs index b5c74cae..bff0ed01 100644 --- a/extensions/crypto-tool/tests/uuid-enhancements.test.mjs +++ b/extensions/crypto-tool/tests/uuid-enhancements.test.mjs @@ -7,8 +7,11 @@ import { generateUuidV1, generateUuidV4, generateUuidV7, + generateUlid, + generateNanoId, formatUuid, - generateUuidBatch + generateUuidBatch, + parseIdentifier } from '../dist/uuid.js' const host = createHost() @@ -131,3 +134,58 @@ test('UUID 视图交互闭环:打开即自动生成、Enter 一键复制、重 view.unmount() } }) + +test('ULID / NanoID 生成与 UUID v7/v4/v1/ULID/NanoID 自动解析闭环', async () => { + const t1 = 1700000000000 + const t2 = 1700000005000 + const ulid1 = generateUlid(t1) + const ulid2 = generateUlid(t2) + assert.match(ulid1, /^[0-7][0-9A-HJKMNP-TV-Z]{25}$/) + assert.ok(ulid1 < ulid2, 'ULID 应按毫秒时间严格递增') + assert.throws(() => generateUlid(-1), /时间戳|Timestamp/i) + + const nano = generateNanoId() + assert.equal(nano.length, 21) + assert.match(nano, /^[A-Za-z0-9_-]{21}$/) + assert.throws(() => generateNanoId(0), /NanoID/i) + assert.throws(() => generateNanoId(300), /NanoID/i) + + const parsedV7 = parseIdentifier(generateUuidV7(t1)) + assert.equal(parsedV7?.kind, 'uuid') + assert.equal(parsedV7?.version, 'v7') + assert.equal(parsedV7?.timestampMs, t1) + assert.equal(parsedV7?.timestampIso, new Date(t1).toISOString()) + + const parsedUlid = parseIdentifier(ulid1) + assert.equal(parsedUlid?.kind, 'ulid') + assert.equal(parsedUlid?.timestampMs, t1) + assert.equal(parsedUlid?.timestampIso, new Date(t1).toISOString()) + + const parsedV4 = parseIdentifier(generateUuidV4()) + assert.equal(parsedV4?.version, 'v4') + assert.equal(parsedV4?.entropyBits, 122) + + const parsedNano = parseIdentifier(nano) + assert.equal(parsedNano?.kind, 'nanoid') + assert.equal(parsedNano?.entropyBits, 126) + + assert.equal(parseIdentifier('not-an-id'), null) + assert.equal(parseIdentifier('123456789012345678901'), null) + + const view = await mount(genUuid) + try { + await view.dropdown('ulid') + assert.match(view.item('uuid-item-0').props.title, /^[0-7][0-9A-HJKMNP-TV-Z]{25}$/) + + await view.dropdown('nanoid') + assert.match(view.item('uuid-item-0').props.title, /^[A-Za-z0-9_-]{21}$/) + + await view.search(ulid1) + const parsedItem = view.item('uuid-parsed-result') + assert.match(parsedItem.props.title, new RegExp(`ULID.*${ulid1}`)) + await view.run(parsedItem, '复制 ISO 时间戳') + assert.equal(host.clipboard.text, new Date(t1).toISOString()) + } finally { + view.unmount() + } +}) diff --git a/extensions/curl-http/plugin.json b/extensions/curl-http/plugin.json index 3de9e29c..5f0d0999 100644 --- a/extensions/curl-http/plugin.json +++ b/extensions/curl-http/plugin.json @@ -1,7 +1,7 @@ { "id": "curl-http", "name": "轻量接口调试", - "version": "1.0.10", + "version": "1.0.11", "minAppVersion": "1.1.8.0", "description": "解析 cURL 命令(bash / cmd 写法)或网址,由客户端发起 HTTP 请求查看响应,并生成 Fetch、Axios、Python、Go 请求代码", "author": "ZTools Team", diff --git a/extensions/curl-http/src/curl-service.ts b/extensions/curl-http/src/curl-service.ts index fd5c13bf..9ff4b86d 100644 --- a/extensions/curl-http/src/curl-service.ts +++ b/extensions/curl-http/src/curl-service.ts @@ -1,4 +1,5 @@ -import type { CodeTargetLang, HttpResponseSnapshot, ParsedCurlRequest } from './types' +import type { CodeTargetLang, HttpResponseSnapshot, ParsedCurlRequest, RequestFormDraft } from './types.js' +import { HTTP_METHODS } from './types.js' import { t } from './i18n.js' import { resolveErrorMessage } from './error-i18n.js' @@ -48,12 +49,29 @@ async function requestViaHost(parsed: ParsedCurlRequest, timeoutMs: number): Pro throw new Error(t('error.hostResponseIncomplete')) } const body = data.body + const responseHeaders = new Headers() + const rawHeaders = isRecord(data.responseHeaders) + ? data.responseHeaders + : isRecord(data.headers) + ? data.headers + : null + if (rawHeaders) { + for (const [key, value] of Object.entries(rawHeaders)) { + if (!key.trim()) continue + if (typeof value === 'string') { + responseHeaders.set(key, value) + } else if (Array.isArray(value)) { + const joined = value.filter((item): item is string => typeof item === 'string').join(', ') + if (joined) responseHeaders.set(key, joined) + } + } + } return { ok: data.statusCode >= 200 && data.statusCode < 300, status: data.statusCode, statusText: data.statusText, - // 当前宿主只返回状态与正文;不能用 Response 构造器自动补出的头冒充服务器响应头。 - headers: new Headers(), + // 仅在宿主真实返回响应头时填充;宿主未提供时不伪造任何响应头。 + headers: responseHeaders, text: async () => body } } @@ -586,7 +604,117 @@ export function parseCurlCommand(rawInput: string): ParsedCurlRequest { } } +function shellSingleQuote(value: string): string { + return `'${value.replace(/'/g, "'\\''")}'` +} + +/** 将结构化请求序列化为规范的单行/多行 bash cURL 命令,支持无损反解析。 */ +export function buildCurlCommand(parsed: ParsedCurlRequest, options?: { multiline?: boolean }): string { + const parts: string[] = ['curl'] + const method = parsed.method.toUpperCase() + const hasBody = parsed.body !== undefined + if (method === 'HEAD') { + parts.push('-I') + } else if (!(method === 'GET' && !hasBody) && !(method === 'POST' && hasBody)) { + parts.push('-X', method) + } + parts.push(shellSingleQuote(parsed.url)) + for (const [key, val] of Object.entries(parsed.headers)) { + parts.push('-H', shellSingleQuote(`${key}: ${val}`)) + } + if (hasBody) { + parts.push('--data-raw', shellSingleQuote(parsed.body ?? '')) + } + if (!options?.multiline) { + return parts.join(' ') + } + const lines: string[] = [] + let idx = 0 + if (parts[1] === '-I') { + lines.push(`curl -I ${parts[2]}`) + idx = 3 + } else if (parts[1] === '-X') { + lines.push(`curl -X ${parts[2]} ${parts[3]}`) + idx = 4 + } else { + lines.push(`curl ${parts[1]}`) + idx = 2 + } + while (idx < parts.length) { + lines.push(` ${parts[idx]} ${parts[idx + 1] ?? ''}`.trimEnd()) + idx += 2 + } + return lines.join(' \\\n') +} + +export function formatHeadersText(headers: Record): string { + return Object.entries(headers) + .map(([key, value]) => `${key}: ${value}`) + .join('\n') +} + +export function parseHeadersText(text: string): Record { + const headers: Record = {} + const lines = String(text || '').split(/\r?\n/) + for (const rawLine of lines) { + const line = rawLine.trim() + if (!line) continue + const colonIdx = line.indexOf(':') + if (colonIdx <= 0) { + throw new Error(t('error.invalidHeader', { header: line })) + } + const key = line.slice(0, colonIdx).trim() + const val = line.slice(colonIdx + 1).trim() + if (!HEADER_NAME_PATTERN.test(key)) { + throw new Error(t('error.invalidHeaderName', { name: key })) + } + if (/[\r\n\0]/.test(val)) { + throw new Error(t('error.invalidHeaderValue', { name: key })) + } + deleteHeader(headers, key) + headers[key] = val + } + return headers +} + +export function buildParsedRequestFromForm(draft: RequestFormDraft): { + parsed: ParsedCurlRequest + timeoutMs: number +} { + const methodUpper = String(draft.method || 'GET').trim().toUpperCase() + const method = (HTTP_METHODS as readonly string[]).includes(methodUpper) ? methodUpper : 'GET' + const rawUrl = String(draft.url || '').trim() + if (!rawUrl) { + throw new Error(t('form.errorUrlRequired')) + } + const url = normalizeTargetUrl(rawUrl) + const headers = parseHeadersText(draft.headersText) + const bodyRaw = String(draft.body ?? '') + const body = bodyRaw.length > 0 && method !== 'GET' && method !== 'HEAD' ? bodyRaw : undefined + + const timeoutRaw = String(draft.timeoutMs ?? '').trim() + const timeoutMs = timeoutRaw === '' ? 10000 : Number(timeoutRaw) + if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 300000) { + throw new Error(t('error.invalidTimeout')) + } + + const base: ParsedCurlRequest = { + method, + url, + headers, + ...(body !== undefined ? { body } : {}), + rawCommand: '', + ignoredOptions: [], + } + base.rawCommand = buildCurlCommand(base) + return { parsed: base, timeoutMs } +} + export function generateCodeFromCurl(parsed: ParsedCurlRequest, lang: CodeTargetLang): string { + if (lang === 'curl') { + return buildCurlCommand(parsed, { multiline: true }) + } + const hasHeaders = Object.keys(parsed.headers).length > 0 if (lang === 'fetch') { diff --git a/extensions/curl-http/src/history-service.ts b/extensions/curl-http/src/history-service.ts new file mode 100644 index 00000000..9efd8f08 --- /dev/null +++ b/extensions/curl-http/src/history-service.ts @@ -0,0 +1,188 @@ +import { LocalStorage } from '@ztools/declarative-ui' +import type { CurlHistoryEntry, HttpResponseSnapshot, ParsedCurlRequest } from './types.js' +import { t } from './i18n.js' + +export const HISTORY_STORAGE_KEY = 'curl-http:history:v1' +export const MAX_HISTORY_ITEMS = 30 +export const DEFAULT_TIMEOUT_MS = 10000 + +let historyIdSequence = 0 + +function createHistoryId(now: number): string { + const cryptoObj = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto + if (typeof cryptoObj?.randomUUID === 'function') { + return `hist_${cryptoObj.randomUUID()}` + } + historyIdSequence += 1 + return `hist_${now}_${historyIdSequence}` +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} + +function sanitizeHeaders(raw: unknown): Record { + if (!isRecord(raw)) return {} + const out: Record = {} + for (const [key, val] of Object.entries(raw)) { + if (typeof key === 'string' && key.trim() && typeof val === 'string') { + out[key] = val + } + } + return out +} + +function normalizeEntry(raw: unknown): CurlHistoryEntry | null { + if (!isRecord(raw)) return null + if (typeof raw.id !== 'string' || !raw.id.trim()) return null + if (typeof raw.method !== 'string' || !raw.method.trim()) return null + if (typeof raw.url !== 'string' || !raw.url.trim()) return null + if (typeof raw.rawCommand !== 'string' || !raw.rawCommand.trim()) return null + const updatedAt = typeof raw.updatedAt === 'number' && Number.isFinite(raw.updatedAt) + ? raw.updatedAt + : Date.now() + const timeoutMs = typeof raw.timeoutMs === 'number' && Number.isSafeInteger(raw.timeoutMs) && raw.timeoutMs >= 1 && raw.timeoutMs <= 300000 + ? raw.timeoutMs + : DEFAULT_TIMEOUT_MS + return { + id: raw.id, + method: raw.method.toUpperCase(), + url: raw.url, + headers: sanitizeHeaders(raw.headers), + ...(typeof raw.body === 'string' ? { body: raw.body } : {}), + rawCommand: raw.rawCommand, + timeoutMs, + ...(typeof raw.lastStatus === 'number' && Number.isInteger(raw.lastStatus) ? { lastStatus: raw.lastStatus } : {}), + ...(typeof raw.lastStatusText === 'string' ? { lastStatusText: raw.lastStatusText } : {}), + ...(typeof raw.lastElapsedMs === 'number' && Number.isFinite(raw.lastElapsedMs) ? { lastElapsedMs: raw.lastElapsedMs } : {}), + ...(typeof raw.lastSizeBytes === 'number' && Number.isFinite(raw.lastSizeBytes) ? { lastSizeBytes: raw.lastSizeBytes } : {}), + updatedAt, + } +} + +export function historyFingerprint(entry: Pick): string { + const sortedHeaders = Object.keys(entry.headers) + .sort((a, b) => a.localeCompare(b)) + .map((k) => `${k}:${entry.headers[k]}`) + .join('\n') + return `${entry.method.toUpperCase()}\u0000${entry.url}\u0000${sortedHeaders}\u0000${entry.body ?? ''}` +} + +export async function loadHistory(): Promise { + try { + const stored = await LocalStorage.getItem(HISTORY_STORAGE_KEY) + if (!Array.isArray(stored)) return [] + const items: CurlHistoryEntry[] = [] + for (const raw of stored) { + const normalized = normalizeEntry(raw) + if (normalized) items.push(normalized) + } + items.sort((a, b) => b.updatedAt - a.updatedAt) + return items.slice(0, MAX_HISTORY_ITEMS) + } catch (err) { + console.warn('[curl-http] Failed to load history from LocalStorage:', err) + return [] + } +} + +export async function saveHistoryEntries(entries: CurlHistoryEntry[]): Promise { + const trimmed = entries.slice(0, MAX_HISTORY_ITEMS) + await LocalStorage.setItem(HISTORY_STORAGE_KEY, trimmed) +} + +export function upsertHistoryEntry( + current: CurlHistoryEntry[], + parsed: ParsedCurlRequest, + options?: { + timeoutMs?: number + response?: HttpResponseSnapshot | null + now?: number + }, +): CurlHistoryEntry[] { + const now = options?.now ?? Date.now() + const timeoutMs = options?.timeoutMs ?? DEFAULT_TIMEOUT_MS + const fp = historyFingerprint(parsed) + const existing = current.find((item) => historyFingerprint(item) === fp) + const nextEntry: CurlHistoryEntry = { + id: existing?.id ?? createHistoryId(now), + method: parsed.method.toUpperCase(), + url: parsed.url, + headers: { ...parsed.headers }, + ...(parsed.body !== undefined ? { body: parsed.body } : {}), + rawCommand: parsed.rawCommand, + timeoutMs, + ...(options?.response + ? { + lastStatus: options.response.status, + lastStatusText: options.response.statusText, + lastElapsedMs: options.response.elapsedMs, + lastSizeBytes: options.response.sizeBytes, + } + : existing?.lastStatus !== undefined + ? { + lastStatus: existing.lastStatus, + lastStatusText: existing.lastStatusText, + lastElapsedMs: existing.lastElapsedMs, + lastSizeBytes: existing.lastSizeBytes, + } + : {}), + updatedAt: now, + } + const rest = current.filter((item) => historyFingerprint(item) !== fp) + return [nextEntry, ...rest].slice(0, MAX_HISTORY_ITEMS) +} + +export function removeHistoryEntry(current: CurlHistoryEntry[], id: string): CurlHistoryEntry[] { + return current.filter((item) => item.id !== id) +} + +export function filterHistoryEntries(entries: CurlHistoryEntry[], keyword: string): CurlHistoryEntry[] { + const q = keyword.trim().toLowerCase() + if (!q) return entries + return entries.filter((entry) => { + if (entry.method.toLowerCase().includes(q)) return true + if (entry.url.toLowerCase().includes(q)) return true + if (entry.body && entry.body.toLowerCase().includes(q)) return true + for (const [k, v] of Object.entries(entry.headers)) { + if (k.toLowerCase().includes(q) || v.toLowerCase().includes(q)) return true + } + return false + }) +} + +export function formatShortUrl(rawUrl: string): string { + try { + const parsed = new URL(rawUrl) + const pathAndQuery = `${parsed.pathname}${parsed.search}` + if (!pathAndQuery || pathAndQuery === '/') return parsed.host + return pathAndQuery.length > 36 ? `${pathAndQuery.slice(0, 35)}…` : pathAndQuery + } catch { + return rawUrl.length > 36 ? `${rawUrl.slice(0, 35)}…` : rawUrl + } +} + +export function formatUrlHost(rawUrl: string): string { + try { + return new URL(rawUrl).host + } catch { + return rawUrl + } +} + +export function formatRelativeTime(updatedAt: number, now: number = Date.now()): string { + const diffSec = Math.max(0, Math.floor((now - updatedAt) / 1000)) + if (diffSec < 60) return t('time.justNow') + const diffMin = Math.floor(diffSec / 60) + if (diffMin < 60) return t('time.minutesAgo', { count: diffMin }) + const diffHour = Math.floor(diffMin / 60) + if (diffHour < 24) return t('time.hoursAgo', { count: diffHour }) + const diffDay = Math.floor(diffHour / 24) + return t('time.daysAgo', { count: diffDay }) +} + +export function formatBytes(bytes: number): string { + if (!Number.isFinite(bytes) || bytes < 0) return '0 B' + if (bytes < 1024) return `${bytes} B` + if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB` + return `${(bytes / (1024 * 1024)).toFixed(2)} MB` +} diff --git a/extensions/curl-http/src/i18n.ts b/extensions/curl-http/src/i18n.ts index 5d580524..c3c0c41e 100644 --- a/extensions/curl-http/src/i18n.ts +++ b/extensions/curl-http/src/i18n.ts @@ -41,50 +41,120 @@ const rawT = createTranslator({ 'error.httpTimeout': 'HTTP_TIMEOUT: 请求在 {timeoutMs}ms 内未响应已超时中断', 'note.ignoredOptions': '未生效的参数:{list}', 'note.ignoredHeaders': '已去掉由客户端自动处理的请求头:{list}', - 'response.empty': '### 响应\n按 Enter 发起请求,在这里查看响应正文。{notes}', - 'response.title': '### 响应 (HTTP {status} {statusText} · {elapsedMs}ms){notes}\n\n{body}', + 'response.empty': '### 响应正文\n\n按 Enter 发送当前请求,在这里查看响应正文(JSON 自动美化)。{notes}', + 'response.title': '### 响应正文 ({status} {statusText} · {elapsedMs}ms · {size}){notes}\n\n{body}', + 'response.emptyBody': '(响应正文为空)', + 'responseHeaders.empty': '### 响应头\n\n按 Enter 发送当前请求后,在这里查看服务器返回的响应头。', + 'responseHeaders.noneReturned': '### 响应头 ({status} {statusText})\n\n本次响应未返回响应头(当前宿主通道仅返回状态码与响应正文)。', + 'responseHeaders.heading': '### 响应头 ({count} 项 · HTTP {status} {statusText})', + 'responseHeaders.colName': '字段名', + 'responseHeaders.colValue': '值', 'toast.clipboardEmpty': '剪贴板为空', 'toast.clipboardEmptyMsg': '请先从浏览器 DevTools 复制 Copy as cURL 命令', 'toast.clipboardLoaded': '已载入剪贴板 cURL 命令', 'toast.clipboardReadFailed': '读取剪贴板失败', + 'toast.historyDeleted': '已删除该条历史记录', + 'toast.historyCleared': '已清空全部请求历史', + 'toast.historySaveFailed': '历史记录保存失败', + 'toast.formSaved': '已更新请求参数', 'confirm.title': '确认发送 {method} 请求?', 'confirm.deleteWarning': '可能删除服务器上的数据', 'confirm.putWarning': '可能覆盖服务器上的数据', 'confirm.message': '{url}\n{warning},发送后无法撤回。', 'confirm.primary': '发送 {method}', 'confirm.cancel': '取消', + 'confirm.clearHistoryTitle': '确认清空全部请求历史?', + 'confirm.clearHistoryMessage': '将删除本地保存的 {count} 条历史记录,操作不可恢复。', + 'confirm.clearHistoryPrimary': '清空历史', 'toast.requestFailed': '请求执行失败', - 'search.placeholder': '粘贴 cURL 命令或 HTTP URL...', + 'search.placeholder': '搜历史、粘贴 cURL 命令或 HTTP URL...', 'dropdown.tooltip': '选择目标代码语言', - 'empty.title': '粘贴 cURL 命令或 HTTP URL', - 'empty.subtitle': '支持浏览器开发者工具里的 Copy as cURL(bash / cmd)', - 'empty.subtitleMac': '支持浏览器开发者工具里的 Copy as cURL', - 'empty.markdown': '### 开始使用\n\n在搜索框粘贴 cURL 命令或网址,或按回车从剪贴板读取。\n\n支持从 Chrome / Edge 开发者工具复制的 `Copy as cURL (bash)` 与 `Copy as cURL (cmd)`,多行命令可用 `\\`、`^` 或 PowerShell 反引号续行。', - 'empty.markdownMac': '### 开始使用\n\n在搜索框粘贴 cURL 命令或网址,或按回车从剪贴板读取。\n\n支持从浏览器开发者工具复制的 `Copy as cURL`,多行命令可用 `\\` 续行。', + 'empty.title': '粘贴 cURL 命令或新建 HTTP 请求', + 'empty.subtitle': '支持 DevTools Copy as cURL(bash / cmd)或点击「编辑请求 (Form)」', + 'empty.subtitleMac': '支持 DevTools Copy as cURL 或点击「编辑请求 (Form)」', + 'empty.markdown': '### 开始使用\n\n- 在顶部搜索框直接粘贴 cURL 命令或网址,立即解析并一键发送;\n- 点击顶栏 **读取剪贴板 cURL**,自动导入 DevTools 复制的 `Copy as cURL (bash)` / `Copy as cURL (cmd)`;\n- 点击顶栏 **编辑请求 (Form)**,使用表单可视化编辑 Method / URL / 多行 Headers / 多行 JSON Body;\n- 发送后的请求自动保存至本地历史(最多 30 条),下次打开可一键重放。', + 'empty.markdownMac': '### 开始使用\n\n- 在顶部搜索框直接粘贴 cURL 命令或网址,立即解析并一键发送;\n- 点击顶栏 **读取剪贴板 cURL**,自动导入浏览器 DevTools 复制的 `Copy as cURL`;\n- 点击顶栏 **编辑请求 (Form)**,使用表单可视化编辑 Method / URL / 多行 Headers / 多行 JSON Body;\n- 发送后的请求自动保存至本地历史(最多 30 条),下次打开可一键重放。', 'hint.copyFormatMac': '支持从 Chrome / Edge / Safari 开发者工具复制的 `Copy as cURL`,多行命令可用行尾 `\\` 续行。', 'hint.copyFormatWin': '支持从 Chrome / Edge 开发者工具复制的 `Copy as cURL (bash)` 与 `Copy as cURL (cmd)`,多行命令可用 `\\`、`^` 或 PowerShell 反引号续行。', - 'action.pasteFromClipboard': '从剪贴板粘贴 cURL', + 'action.pasteFromClipboard': '读取剪贴板 cURL', + 'action.editRequestForm': '编辑请求 (Form)', + 'action.newRequestForm': '新建请求 (Form)', 'section.parseError': 'cURL 语法解析错误', 'error.parseTitle': '无法解析 cURL 命令', 'tag.syntaxError': '语法错误', - 'error.parseMarkdown': '### cURL 解析异常\n\n{code}\n\n支持从 Chrome / Edge 开发者工具复制的 `Copy as cURL (bash)` 与 `Copy as cURL (cmd)`,多行命令可用 `\\`、`^` 或 PowerShell 反引号续行。', - 'error.parseMarkdownMac': '### cURL 解析异常\n\n{code}\n\n支持从浏览器开发者工具复制的 `Copy as cURL`,多行命令可用 `\\` 续行。', - 'section.overview': '请求结构与多语言代码互转', + 'error.parseMarkdown': '### cURL 解析异常\n\n{code}\n\n支持从 Chrome / Edge 开发者工具复制的 `Copy as cURL (bash)` 与 `Copy as cURL (cmd)`,多行命令可用 `\\`、`^` 或 PowerShell 反引号续行。也可以点击「编辑请求 (Form)」手动构造请求。', + 'error.parseMarkdownMac': '### cURL 解析异常\n\n{code}\n\n支持从浏览器开发者工具复制的 `Copy as cURL`,多行命令可用 `\\` 续行。也可以点击「编辑请求 (Form)」手动构造请求。', + 'section.currentRequest': '当前请求视图', + 'section.history': '最近历史 (本地 {count}/{max} 条)', + 'section.historySearch': '匹配的历史记录 ({count} 条)', + 'view.responseBody': '响应正文', + 'view.responseBodySubEmpty': '待发送 · 按 Enter 发起请求', + 'view.responseBodySubJson': 'JSON 已自动美化 · {size}', + 'view.responseBodySubText': '文本响应 · {size}', + 'view.responseHeaders': '响应头', + 'view.responseHeadersSub': '查看服务器返回头信息', + 'view.responseHeadersCount': '{count} 项', + 'view.generatedCode': '生成代码', + 'view.generatedCodeSub': '当前语言:{lang}', + 'view.requestInspect': '请求头与参数', + 'view.requestInspectSub': '{count} 个请求头 · {bodyInfo}', + 'tag.pending': '待发送', + 'summary.response': '状态: {status} {statusText} · {elapsedMs}ms · {size}', + 'summary.ready': '{method} {url} · Headers: {count} 项', + 'summary.historyOnly': '本地历史 {count} 条 · 可直接粘贴 cURL 或点击「编辑请求 (Form)」', 'overview.subtitle': 'Headers: {count} 项 · 代码目标: {lang}', 'detail.codeHeading': '### 生成代码 ({lang})', + 'detail.requestHeading': '### 请求详情 ({method})', + 'detail.requestHeadersHeading': '#### 请求头 ({count} 项)', + 'detail.requestHeadersEmpty': '(无自定义请求头)', + 'detail.requestQueryHeading': '#### 查询参数 ({count} 项)', + 'detail.requestBodyHeading': '#### 请求体', + 'detail.historyPreviewHeading': '### 历史请求 ({method})', + 'detail.historyLastStatus': '上次响应:HTTP {status} {statusText} · {elapsedMs}ms · {size}', 'meta.method': '请求方法 (Method)', 'meta.url': '目标地址 (URL)', + 'meta.status': '响应状态', + 'meta.elapsed': '耗时 / 体积', + 'meta.contentType': '内容类型', + 'meta.timeout': '超时时间', 'meta.headerCount': '请求头数量', 'meta.headerCountValue': '{count} 项', 'meta.body': '请求体 (Body)', 'meta.bodyChars': '{count} 字符', 'meta.noBody': '无请求体', 'action.sendRequest': '立即发起 HTTP 请求', + 'action.replayRequest': '发送 / 重放请求', + 'action.loadHistory': '载入到当前请求', + 'action.loadAndReplay': '载入并立即重放', + 'action.deleteHistory': '删除该条历史', + 'action.clearHistory': '清空全部历史', 'action.copyCode': '复制 {lang} 代码', - 'action.copyResponse': '复制响应 Body', - 'action.loadClipboard': '从剪贴板载入 cURL', + 'action.copyCurl': '复制规范 cURL 命令', + 'action.copyResponse': '复制响应正文', + 'action.copyResponseHeaders': '复制全部响应头', + 'action.loadClipboard': '读取剪贴板 cURL', 'header.heading': '### 请求头 {key}', - 'action.copyHeader': '复制 {key}' + 'action.copyHeader': '复制 {key}', + 'form.title': '编辑 HTTP 请求', + 'form.methodLabel': '请求方法 (Method)', + 'form.urlLabel': '请求地址 (URL)', + 'form.urlPlaceholder': 'https://api.example.com/v1/resource', + 'form.headersLabel': '请求头 (Headers)', + 'form.headersPlaceholder': 'Content-Type: application/json\nAuthorization: Bearer your-token', + 'form.headersInfo': '每行一条,格式为 Key: Value(留空行自动忽略)', + 'form.bodyLabel': '请求体 (Body)', + 'form.bodyPlaceholder': '{\n "key": "value"\n}', + 'form.bodyInfo': '支持多行 JSON、表单或纯文本;GET / HEAD 请求会自动忽略请求体', + 'form.timeoutLabel': '超时时间 (ms)', + 'form.timeoutPlaceholder': '10000', + 'form.timeoutInfo': '范围 1–300000 毫秒,默认 10000', + 'form.saveAndSend': '保存并立即发送', + 'form.saveOnly': '仅保存到当前请求', + 'form.errorUrlRequired': '请输入目标请求地址 (URL)', + 'time.justNow': '刚刚', + 'time.minutesAgo': '{count}m', + 'time.hoursAgo': '{count}h', + 'time.daysAgo': '{count}d', }, 'en-US': { 'error.hostNetworkUnsupported': 'Current client does not support network requests. Please upgrade your client', @@ -126,52 +196,123 @@ const rawT = createTranslator({ 'error.httpTimeout': 'HTTP_TIMEOUT: Request timed out after {timeoutMs}ms', 'note.ignoredOptions': 'Ignored options: {list}', 'note.ignoredHeaders': 'Removed auto-managed headers: {list}', - 'response.empty': '### Response\nPress Enter to send the request and view the response body here.{notes}', - 'response.title': '### Response (HTTP {status} {statusText} · {elapsedMs}ms){notes}\n\n{body}', + 'response.empty': '### Response Body\n\nPress Enter to send the current request and inspect the response body (JSON auto-formatted).{notes}', + 'response.title': '### Response Body ({status} {statusText} · {elapsedMs}ms · {size}){notes}\n\n{body}', + 'response.emptyBody': '(Empty response body)', + 'responseHeaders.empty': '### Response Headers\n\nPress Enter to send the current request and inspect server response headers.', + 'responseHeaders.noneReturned': '### Response Headers ({status} {statusText})\n\nNo response headers were returned (the current host transport only returns status and body).', + 'responseHeaders.heading': '### Response Headers ({count} · HTTP {status} {statusText})', + 'responseHeaders.colName': 'Header', + 'responseHeaders.colValue': 'Value', 'toast.clipboardEmpty': 'Clipboard is empty', 'toast.clipboardEmptyMsg': 'Copy a cURL command from browser DevTools first', 'toast.clipboardLoaded': 'Loaded cURL command from clipboard', 'toast.clipboardReadFailed': 'Failed to read clipboard', + 'toast.historyDeleted': 'History entry deleted', + 'toast.historyCleared': 'Cleared all request history', + 'toast.historySaveFailed': 'Failed to save history', + 'toast.formSaved': 'Request updated', 'confirm.title': 'Send {method} request?', 'confirm.deleteWarning': 'May delete data on the server', 'confirm.putWarning': 'May overwrite data on the server', 'confirm.message': '{url}\n{warning}. This cannot be undone.', 'confirm.primary': 'Send {method}', 'confirm.cancel': 'Cancel', + 'confirm.clearHistoryTitle': 'Clear all request history?', + 'confirm.clearHistoryMessage': 'This will delete {count} saved [[count:entry|entries]] from local storage and cannot be undone.', + 'confirm.clearHistoryPrimary': 'Clear History', 'toast.requestFailed': 'Request failed', - 'search.placeholder': 'Paste cURL command or HTTP URL...', + 'search.placeholder': 'Search history, paste cURL command or HTTP URL...', 'dropdown.tooltip': 'Select target language', - 'empty.title': 'Paste cURL Command or HTTP URL', - 'empty.subtitle': 'Supports Copy as cURL (bash / cmd) from browser DevTools', - 'empty.subtitleMac': 'Supports Copy as cURL from browser DevTools', - 'empty.markdown': '### Getting Started\n\nPaste a cURL command or URL in the search bar, or press Enter to load from clipboard.\n\nSupports `Copy as cURL (bash)` and `Copy as cURL (cmd)` from Chrome / Edge DevTools, with `\\`, `^`, or PowerShell backtick line continuations.', - 'empty.markdownMac': '### Getting Started\n\nPaste a cURL command or URL in the search bar, or press Enter to load from clipboard.\n\nSupports `Copy as cURL` from browser DevTools, with `\\` line continuations.', + 'empty.title': 'Paste cURL Command or Create HTTP Request', + 'empty.subtitle': 'Supports Copy as cURL (bash / cmd) or click "Edit Request (Form)"', + 'empty.subtitleMac': 'Supports Copy as cURL or click "Edit Request (Form)"', + 'empty.markdown': '### Getting Started\n\n- Paste a cURL command or URL directly in the search bar to parse and send immediately;\n- Click **Read Clipboard cURL** to import `Copy as cURL (bash)` / `Copy as cURL (cmd)` from DevTools;\n- Click **Edit Request (Form)** to edit Method, URL, multiline Headers, and multiline JSON Body;\n- Sent requests are saved automatically to local history (up to 30 entries) for one-click replay.', + 'empty.markdownMac': '### Getting Started\n\n- Paste a cURL command or URL directly in the search bar to parse and send immediately;\n- Click **Read Clipboard cURL** to import `Copy as cURL` from browser DevTools;\n- Click **Edit Request (Form)** to edit Method, URL, multiline Headers, and multiline JSON Body;\n- Sent requests are saved automatically to local history (up to 30 entries) for one-click replay.', 'hint.copyFormatMac': 'Supports `Copy as cURL` copied from Chrome / Edge / Safari DevTools, with trailing `\\` for multiline continuations.', 'hint.copyFormatWin': 'Supports `Copy as cURL (bash)` and `Copy as cURL (cmd)` copied from Chrome / Edge DevTools, with `\\`, `^`, or PowerShell backtick line continuations.', - 'action.pasteFromClipboard': 'Paste cURL from Clipboard', + 'action.pasteFromClipboard': 'Read Clipboard cURL', + 'action.editRequestForm': 'Edit Request (Form)', + 'action.newRequestForm': 'New Request (Form)', 'section.parseError': 'cURL Parse Error', 'error.parseTitle': 'Unable to Parse cURL Command', 'tag.syntaxError': 'Syntax Error', - 'error.parseMarkdown': '### cURL Parse Error\n\n{code}\n\nSupports `Copy as cURL (bash)` and `Copy as cURL (cmd)` from Chrome / Edge DevTools, with `\\`, `^`, or PowerShell backtick line continuations.', - 'error.parseMarkdownMac': '### cURL Parse Error\n\n{code}\n\nSupports `Copy as cURL` from browser DevTools, with `\\` line continuations.', - 'section.overview': 'Request Structure & Code Converter', + 'error.parseMarkdown': '### cURL Parse Error\n\n{code}\n\nSupports `Copy as cURL (bash)` and `Copy as cURL (cmd)` from Chrome / Edge DevTools, with `\\`, `^`, or PowerShell backtick line continuations. You can also click "Edit Request (Form)" to build a request.', + 'error.parseMarkdownMac': '### cURL Parse Error\n\n{code}\n\nSupports `Copy as cURL` from browser DevTools, with `\\` line continuations. You can also click "Edit Request (Form)" to build a request.', + 'section.currentRequest': 'Current Request', + 'section.history': 'Recent History ({count}/{max} Local)', + 'section.historySearch': 'Matching History ({count})', + 'view.responseBody': 'Response Body', + 'view.responseBodySubEmpty': 'Ready · Press Enter to send request', + 'view.responseBodySubJson': 'JSON formatted · {size}', + 'view.responseBodySubText': 'Text response · {size}', + 'view.responseHeaders': 'Response Headers', + 'view.responseHeadersSub': 'Inspect server response headers', + 'view.responseHeadersCount': '{count}', + 'view.generatedCode': 'Generated Code', + 'view.generatedCodeSub': 'Target: {lang}', + 'view.requestInspect': 'Headers & Parameters', + 'view.requestInspectSub': '{count} [[count:header|headers]] · {bodyInfo}', + 'tag.pending': 'Pending', + 'summary.response': 'Status: {status} {statusText} · {elapsedMs}ms · {size}', + 'summary.ready': '{method} {url} · Headers: {count}', + 'summary.historyOnly': '{count} local [[count:entry|entries]] · Paste cURL or click "Edit Request (Form)"', 'overview.subtitle': 'Headers: {count} · Target: {lang}', 'detail.codeHeading': '### Generated Code ({lang})', + 'detail.requestHeading': '### Request Details ({method})', + 'detail.requestHeadersHeading': '#### Request Headers ({count})', + 'detail.requestHeadersEmpty': '(No custom headers)', + 'detail.requestQueryHeading': '#### Query Parameters ({count})', + 'detail.requestBodyHeading': '#### Request Body', + 'detail.historyPreviewHeading': '### Saved Request ({method})', + 'detail.historyLastStatus': 'Last response: HTTP {status} {statusText} · {elapsedMs}ms · {size}', 'meta.method': 'Method', 'meta.url': 'URL', + 'meta.status': 'Status', + 'meta.elapsed': 'Elapsed / Size', + 'meta.contentType': 'Content-Type', + 'meta.timeout': 'Timeout', 'meta.headerCount': 'Headers', 'meta.headerCountValue': '{count}', 'meta.body': 'Body', 'meta.bodyChars': '{count} [[count:char|chars]]', 'meta.noBody': 'None', 'action.sendRequest': 'Send HTTP Request', + 'action.replayRequest': 'Send / Replay Request', + 'action.loadHistory': 'Load into Current Request', + 'action.loadAndReplay': 'Load & Replay Now', + 'action.deleteHistory': 'Delete History Entry', + 'action.clearHistory': 'Clear All History', 'action.copyCode': 'Copy {lang} Code', + 'action.copyCurl': 'Copy Canonical cURL', 'action.copyResponse': 'Copy Response Body', - 'action.loadClipboard': 'Load cURL from Clipboard', + 'action.copyResponseHeaders': 'Copy All Response Headers', + 'action.loadClipboard': 'Read Clipboard cURL', 'header.heading': '### Header {key}', - 'action.copyHeader': 'Copy {key}' + 'action.copyHeader': 'Copy {key}', + 'form.title': 'Edit HTTP Request', + 'form.methodLabel': 'Method', + 'form.urlLabel': 'URL', + 'form.urlPlaceholder': 'https://api.example.com/v1/resource', + 'form.headersLabel': 'Headers', + 'form.headersPlaceholder': 'Content-Type: application/json\nAuthorization: Bearer your-token', + 'form.headersInfo': 'One header per line in "Key: Value" format (blank lines ignored)', + 'form.bodyLabel': 'Body', + 'form.bodyPlaceholder': '{\n "key": "value"\n}', + 'form.bodyInfo': 'Supports multiline JSON, form, or plain text; ignored for GET / HEAD', + 'form.timeoutLabel': 'Timeout (ms)', + 'form.timeoutPlaceholder': '10000', + 'form.timeoutInfo': 'Range 1–300000 ms, default 10000', + 'form.saveAndSend': 'Save & Send Request', + 'form.saveOnly': 'Save Only', + 'form.errorUrlRequired': 'Please enter a target URL', + 'time.justNow': 'Just now', + 'time.minutesAgo': '{count}m', + 'time.hoursAgo': '{count}h', + 'time.daysAgo': '{count}d', } }) + export const t: typeof rawT = (key, params) => { const out = rawT(key, params) if (!out.includes('[[')) return out diff --git a/extensions/curl-http/src/index.tsx b/extensions/curl-http/src/index.tsx index f52e0974..598de610 100644 --- a/extensions/curl-http/src/index.tsx +++ b/extensions/curl-http/src/index.tsx @@ -8,6 +8,7 @@ import React, { confirmAlert, showToast, ToastStyle, + useNavigation, useState, useMemo, useRef, @@ -15,15 +16,37 @@ import React, { useLocale, } from '@ztools/declarative-ui' import { t } from './i18n.js' -import type { CodeTargetLang, HttpResponseSnapshot } from './types.js' +import type { + CodeTargetLang, + CurlHistoryEntry, + HttpResponseSnapshot, + ParsedCurlRequest, +} from './types.js' import { parseCurlCommand, + buildCurlCommand, generateCodeFromCurl, executeCurlRequest, } from './curl-service.js' +import { + DEFAULT_TIMEOUT_MS, + MAX_HISTORY_ITEMS, + loadHistory, + saveHistoryEntries, + upsertHistoryEntry, + removeHistoryEntry, + filterHistoryEntries, + formatShortUrl, + formatUrlHost, + formatRelativeTime, + formatBytes, +} from './history-service.js' +import { RequestEditorForm } from './request-editor-form.js' export * from './types.js' export * from './curl-service.js' +export * from './history-service.js' +export { RequestEditorForm } from './request-editor-form.js' /** 是否运行在 macOS:Mac 用户只会从开发者工具复制 bash 写法,说明里不提 cmd / PowerShell */ export function isMacPlatform(): boolean { @@ -43,96 +66,269 @@ function fenced(content: string, lang = ''): string { return `${fence}${lang}\n${content}\n${fence}` } -function responseMarkdown(snap: HttpResponseSnapshot | null, ignoredOptions: string[]): string { +function escapeMdCell(text: string): string { + return text.replace(/\|/g, '\\|').replace(/\r?\n/g, ' ') +} + +function langDisplayLabel(lang: CodeTargetLang): string { + switch (lang) { + case 'curl': return 'cURL' + case 'fetch': return 'JavaScript Fetch' + case 'axios': return 'TypeScript Axios' + case 'python': return 'Python Requests' + case 'go': return 'Go net/http' + } +} + +function langShortTag(lang: CodeTargetLang): string { + switch (lang) { + case 'curl': return 'cURL' + case 'fetch': return 'Fetch' + case 'axios': return 'Axios' + case 'python': return 'Python' + case 'go': return 'Go' + } +} + +function langFenceId(lang: CodeTargetLang): string { + switch (lang) { + case 'curl': return 'bash' + case 'python': return 'python' + case 'go': return 'go' + case 'fetch': + case 'axios': + return 'ts' + } +} + +function looksLikeDirectCurlOrUrl(trimmed: string): boolean { + return ( + /^https?:\/\//i.test(trimmed) || + /^curl(?:\.exe)?(?:\s|$)/i.test(trimmed) || + trimmed.startsWith('-') + ) +} + +function findHeaderCaseInsensitive(headers: Record, name: string): string | undefined { + const target = name.toLowerCase() + for (const [k, v] of Object.entries(headers)) { + if (k.toLowerCase() === target) return v + } + return undefined +} + +function responseBodyMarkdown(snap: HttpResponseSnapshot | null, ignoredOptions: string[]): string { const notes: string[] = [] if (ignoredOptions.length > 0) notes.push(t('note.ignoredOptions', { list: ignoredOptions.join(', ') })) if (snap && snap.ignoredHeaders.length > 0) notes.push(t('note.ignoredHeaders', { list: snap.ignoredHeaders.join(', ') })) const noteText = notes.length > 0 ? `\n\n${notes.map((n) => `- ${n}`).join('\n')}` : '' if (!snap) return t('response.empty', { notes: noteText }) + const bodyBlock = snap.bodyText.length > 0 + ? fenced(snap.bodyText, snap.isJson ? 'json' : 'text') + : t('response.emptyBody') return t('response.title', { status: snap.status, statusText: snap.statusText, elapsedMs: snap.elapsedMs, + size: formatBytes(snap.sizeBytes), notes: noteText, - body: fenced(snap.bodyText, snap.isJson ? 'json' : 'text') + body: bodyBlock, }) } +function responseHeadersMarkdown(snap: HttpResponseSnapshot | null): string { + if (!snap) return t('responseHeaders.empty') + const entries = Object.entries(snap.responseHeaders) + if (entries.length === 0) { + return t('responseHeaders.noneReturned', { + status: snap.status, + statusText: snap.statusText, + }) + } + const rows = entries + .map(([k, v]) => `| \`${escapeMdCell(k)}\` | ${escapeMdCell(v)} |`) + .join('\n') + return [ + t('responseHeaders.heading', { + count: entries.length, + status: snap.status, + statusText: snap.statusText, + }), + '', + `| ${t('responseHeaders.colName')} | ${t('responseHeaders.colValue')} |`, + '| --- | --- |', + rows, + ].join('\n') +} + +function requestInspectMarkdown(parsed: ParsedCurlRequest): string { + const sections: string[] = [ + t('detail.requestHeading', { method: parsed.method }), + '', + fenced(parsed.url, 'text'), + ] + + try { + const u = new URL(parsed.url) + const params = Array.from(u.searchParams.entries()) + if (params.length > 0) { + sections.push('', t('detail.requestQueryHeading', { count: params.length }), '') + sections.push(`| ${t('responseHeaders.colName')} | ${t('responseHeaders.colValue')} |`) + sections.push('| --- | --- |') + for (const [k, v] of params) { + sections.push(`| \`${escapeMdCell(k)}\` | ${escapeMdCell(v)} |`) + } + } + } catch { + // URL already validated during parse; ignore searchParams extraction error + } + + const headerEntries = Object.entries(parsed.headers) + sections.push('', t('detail.requestHeadersHeading', { count: headerEntries.length }), '') + if (headerEntries.length === 0) { + sections.push(t('detail.requestHeadersEmpty')) + } else { + sections.push(`| ${t('responseHeaders.colName')} | ${t('responseHeaders.colValue')} |`) + sections.push('| --- | --- |') + for (const [k, v] of headerEntries) { + sections.push(`| \`${escapeMdCell(k)}\` | ${escapeMdCell(v)} |`) + } + } + + if (parsed.body !== undefined) { + let formattedBody = parsed.body + let bodyLang = 'text' + try { + const obj = JSON.parse(parsed.body) + formattedBody = JSON.stringify(obj, null, 2) + bodyLang = 'json' + } catch { + bodyLang = 'text' + } + sections.push('', t('detail.requestBodyHeading'), '', fenced(formattedBody, bodyLang)) + } + + if (parsed.ignoredOptions && parsed.ignoredOptions.length > 0) { + sections.push('', `- ${t('note.ignoredOptions', { list: parsed.ignoredOptions.join(', ') })}`) + } + + return sections.join('\n') +} + +function historyPreviewMarkdown(entry: CurlHistoryEntry): string { + const lines: string[] = [ + t('detail.historyPreviewHeading', { method: entry.method }), + '', + fenced(entry.rawCommand, 'bash'), + ] + if (entry.lastStatus !== undefined) { + lines.push( + '', + t('detail.historyLastStatus', { + status: entry.lastStatus, + statusText: entry.lastStatusText ?? '', + elapsedMs: entry.lastElapsedMs ?? 0, + size: formatBytes(entry.lastSizeBytes ?? 0), + }), + ) + } + return lines.join('\n') +} + export function CurlHttpCommand() { useLocale() + const { push } = useNavigation() // 初始为空,不预填示例请求 const [rawCurl, setRawCurl] = useState('') + const [timeoutMs, setTimeoutMs] = useState(DEFAULT_TIMEOUT_MS) const [targetLang, setTargetLang] = useState('fetch') const [responseSnap, setResponseSnap] = useState(null) const [isSending, setIsSending] = useState(false) + const [selectedItemId, setSelectedItemId] = useState(undefined) + const [history, setHistory] = useState([]) + const historyRef = useRef([]) const requestRevision = useRef(0) const mounted = useRef(true) useEffect(() => { mounted.current = true + void loadHistory().then((loaded) => { + if (!mounted.current) return + historyRef.current = loaded + setHistory(loaded) + }) return () => { mounted.current = false requestRevision.current += 1 } }, []) - const replaceRequest = (value: string): void => { + const persistHistory = async (next: CurlHistoryEntry[]): Promise => { + historyRef.current = next + if (mounted.current) setHistory(next) + try { + await saveHistoryEntries(next) + } catch (err) { + if (mounted.current) { + await showToast({ + style: ToastStyle.Failure, + title: t('toast.historySaveFailed'), + message: err instanceof Error ? err.message : String(err), + }) + } + } + } + + const replaceRequest = (value: string, nextTimeoutMs?: number): void => { requestRevision.current += 1 setRawCurl(value) + if (nextTimeoutMs !== undefined) setTimeoutMs(nextTimeoutMs) setResponseSnap(null) } - const parsedState = useMemo(() => { + const trimmedInput = rawCurl.trim() + + const inputMode = useMemo(() => { + if (!trimmedInput) { + return { kind: 'empty' as const } + } + if (!looksLikeDirectCurlOrUrl(trimmedInput)) { + const matchedHistory = filterHistoryEntries(history, trimmedInput) + if (matchedHistory.length > 0) { + return { kind: 'historySearch' as const, matches: matchedHistory } + } + } try { - const parsed = parseCurlCommand(rawCurl) + const parsed = parseCurlCommand(trimmedInput) const generatedCode = generateCodeFromCurl(parsed, targetLang) - return { ok: true as const, parsed, generatedCode } + const canonicalCurl = buildCurlCommand(parsed, { multiline: true }) + return { kind: 'parsed' as const, parsed, generatedCode, canonicalCurl } } catch (err) { return { - ok: false as const, + kind: 'error' as const, error: err instanceof Error ? err.message : String(err), } } - }, [rawCurl, targetLang]) + }, [trimmedInput, targetLang, history]) - const handleLoadClipboard = async (): Promise => { - try { - const clip = await Clipboard.readText() - if (!clip || !clip.trim()) { - await showToast({ - style: ToastStyle.Failure, - title: t('toast.clipboardEmpty'), - message: t('toast.clipboardEmptyMsg'), - }) - return - } - replaceRequest(clip.trim()) - await showToast({ - style: ToastStyle.Success, - title: t('toast.clipboardLoaded'), - }) - } catch (err) { - await showToast({ - style: ToastStyle.Failure, - title: t('toast.clipboardReadFailed'), - message: err instanceof Error ? err.message : String(err), - }) - } - } - - const handleSendRequest = async (): Promise => { - if (!parsedState.ok || isSending) return - const { method, url } = parsedState.parsed + const handleSendRequest = async ( + overrideParsed?: ParsedCurlRequest, + overrideTimeoutMs?: number, + ): Promise => { + const targetParsed = overrideParsed ?? (inputMode.kind === 'parsed' ? inputMode.parsed : null) + if (!targetParsed || isSending) return + const effectiveTimeout = overrideTimeoutMs ?? timeoutMs + const { method, url } = targetParsed // DELETE / PUT 会删除或覆盖服务器上的数据,发送前请用户确认;取消或无法确认时不发送 if (method === 'DELETE' || method === 'PUT') { const confirmed = await confirmAlert({ title: t('confirm.title', { method }), message: t('confirm.message', { url, - warning: method === 'DELETE' ? t('confirm.deleteWarning') : t('confirm.putWarning') + warning: method === 'DELETE' ? t('confirm.deleteWarning') : t('confirm.putWarning'), }), primaryAction: { title: t('confirm.primary', { method }), style: 'destructive' }, - dismissAction: { title: t('confirm.cancel') } + dismissAction: { title: t('confirm.cancel') }, }) if (!confirmed) return } @@ -140,13 +336,19 @@ export function CurlHttpCommand() { setIsSending(true) setResponseSnap(null) try { - const snap = await executeCurlRequest(parsedState.parsed) + const snap = await executeCurlRequest(targetParsed, { timeoutMs: effectiveTimeout }) if (revision !== requestRevision.current) return setResponseSnap(snap) + setSelectedItemId('curl-response-body') + const nextHistory = upsertHistoryEntry(historyRef.current, targetParsed, { + timeoutMs: effectiveTimeout, + response: snap, + }) + await persistHistory(nextHistory) await showToast({ style: snap.ok ? ToastStyle.Success : ToastStyle.Failure, title: `HTTP ${snap.status} (${snap.elapsedMs}ms)`, - message: `${snap.sizeBytes} ${snap.sizeBytes === 1 ? 'byte' : 'bytes'}`, + message: formatBytes(snap.sizeBytes), }) } catch (err) { if (revision !== requestRevision.current) return @@ -160,19 +362,348 @@ export function CurlHttpCommand() { } } + const handleLoadClipboard = async (): Promise => { + try { + const clip = await Clipboard.readText() + if (!clip || !clip.trim()) { + await showToast({ + style: ToastStyle.Failure, + title: t('toast.clipboardEmpty'), + message: t('toast.clipboardEmptyMsg'), + }) + return + } + replaceRequest(clip.trim()) + await showToast({ + style: ToastStyle.Success, + title: t('toast.clipboardLoaded'), + }) + } catch (err) { + await showToast({ + style: ToastStyle.Failure, + title: t('toast.clipboardReadFailed'), + message: err instanceof Error ? err.message : String(err), + }) + } + } + + const handleApplyFromForm = ( + parsed: ParsedCurlRequest, + nextTimeoutMs: number, + sendImmediately: boolean, + ): void => { + replaceRequest(parsed.rawCommand, nextTimeoutMs) + setSelectedItemId('curl-response-body') + if (sendImmediately) { + void handleSendRequest(parsed, nextTimeoutMs) + } else { + const nextHistory = upsertHistoryEntry(historyRef.current, parsed, { + timeoutMs: nextTimeoutMs, + }) + void persistHistory(nextHistory) + } + } + + const createEditorForm = (initialReq?: ParsedCurlRequest | null, initialTimeout?: number) => ( + + ) + + const handleOpenEditorForm = (initialReq?: ParsedCurlRequest | null, initialTimeout?: number): void => { + push(createEditorForm(initialReq, initialTimeout)) + } + + const handleLoadHistoryEntry = (entry: CurlHistoryEntry, replay: boolean): void => { + replaceRequest(entry.rawCommand, entry.timeoutMs) + setSelectedItemId('curl-response-body') + if (replay) { + const parsed: ParsedCurlRequest = { + method: entry.method, + url: entry.url, + headers: { ...entry.headers }, + ...(entry.body !== undefined ? { body: entry.body } : {}), + rawCommand: entry.rawCommand, + ignoredOptions: [], + } + void handleSendRequest(parsed, entry.timeoutMs) + } + } + + const handleDeleteHistory = async (id: string): Promise => { + const next = removeHistoryEntry(historyRef.current, id) + await persistHistory(next) + await showToast({ + style: ToastStyle.Success, + title: t('toast.historyDeleted'), + }) + } + + const handleClearHistory = async (): Promise => { + if (historyRef.current.length === 0) return + const confirmed = await confirmAlert({ + title: t('confirm.clearHistoryTitle'), + message: t('confirm.clearHistoryMessage', { count: historyRef.current.length }), + primaryAction: { title: t('confirm.clearHistoryPrimary'), style: 'destructive' }, + dismissAction: { title: t('confirm.cancel') }, + }) + if (!confirmed) return + await persistHistory([]) + await showToast({ + style: ToastStyle.Success, + title: t('toast.historyCleared'), + }) + } + + const summaryText = (() => { + if (inputMode.kind === 'parsed') { + if (responseSnap) { + return t('summary.response', { + status: responseSnap.status, + statusText: responseSnap.statusText, + elapsedMs: responseSnap.elapsedMs, + size: formatBytes(responseSnap.sizeBytes), + }) + } + return t('summary.ready', { + method: inputMode.parsed.method, + url: formatShortUrl(inputMode.parsed.url), + count: Object.keys(inputMode.parsed.headers).length, + }) + } + if (inputMode.kind === 'error') { + return t('error.parseTitle') + } + if (history.length > 0) { + return t('summary.historyOnly', { count: history.length }) + } + return isMacPlatform() ? t('empty.subtitleMac') : t('empty.subtitle') + })() + + const filterBarActions = inputMode.kind === 'parsed' + ? [ + { + id: 'send-request', + title: t('action.sendRequest'), + style: 'primary', + onAction: () => void handleSendRequest(), + }, + { + id: 'edit-request-form', + title: t('action.editRequestForm'), + style: 'secondary', + onAction: () => handleOpenEditorForm(), + }, + { + id: 'load-clipboard', + title: t('action.loadClipboard'), + style: 'secondary', + onAction: () => void handleLoadClipboard(), + }, + ] + : [ + { + id: 'edit-request-form', + title: t('action.editRequestForm'), + style: 'primary', + onAction: () => handleOpenEditorForm(null), + }, + { + id: 'load-clipboard', + title: t('action.pasteFromClipboard'), + style: 'secondary', + onAction: () => void handleLoadClipboard(), + }, + ] + + const renderRequestActions = ( + parsed: ParsedCurlRequest, + generatedCode: string, + canonicalCurl: string, + preferCopyCode = false, + ) => { + const responseHeadersText = responseSnap + ? Object.entries(responseSnap.responseHeaders) + .map(([k, v]) => `${k}: ${v}`) + .join('\n') + : '' + + return ( + + {preferCopyCode ? ( + + ) : ( + void handleSendRequest()} + /> + )} + {preferCopyCode ? ( + void handleSendRequest()} + /> + ) : ( + + )} + + {responseSnap && ( + + )} + {responseHeadersText && ( + + )} + + void handleLoadClipboard()} + /> + + ) + } + + const renderHistoryItem = (entry: CurlHistoryEntry) => { + const entryParsed: ParsedCurlRequest = { + method: entry.method, + url: entry.url, + headers: { ...entry.headers }, + ...(entry.body !== undefined ? { body: entry.body } : {}), + rawCommand: entry.rawCommand, + ignoredOptions: [], + } + const statusTag = entry.lastStatus !== undefined + ? entry.lastStatus >= 200 && entry.lastStatus < 300 + ? { tag: `${entry.lastStatus}` } + : { tag: { value: `${entry.lastStatus}`, color: Color.Red } } + : null + + return ( + + + + + + {entry.lastStatus !== undefined && ( + + )} + + } + /> + } + actions={ + + handleLoadHistoryEntry(entry, true)} + /> + handleLoadHistoryEntry(entry, false)} + /> + + + void handleDeleteHistory(entry.id)} + /> + void handleClearHistory()} + /> + + } + /> + ) + } + + const responseHeaderCount = responseSnap ? Object.keys(responseSnap.responseHeaders).length : 0 + const responseContentType = responseSnap + ? findHeaderCaseInsensitive(responseSnap.responseHeaders, 'content-type') + : undefined + return ( replaceRequest(val)} + selectedItemId={selectedItemId} + onSelectionChange={(id: string | null) => setSelectedItemId(id ?? undefined)} searchBarAccessory={ setTargetLang(val as CodeTargetLang)} > + @@ -180,39 +711,11 @@ export function CurlHttpCommand() { } filterBar={{ - summaryText: parsedState.ok - ? `${parsedState.parsed.method} · ${t('overview.subtitle', { count: Object.keys(parsedState.parsed.headers).length, lang: targetLang.toUpperCase() })}` - : rawCurl.trim() - ? t('error.parseTitle') - : isMacPlatform() - ? t('empty.subtitleMac') - : t('empty.subtitle'), - actions: parsedState.ok - ? [ - { - id: 'send-request', - title: t('action.sendRequest'), - style: 'primary', - onAction: () => void handleSendRequest(), - }, - { - id: 'load-clipboard', - title: t('action.loadClipboard'), - style: 'secondary', - onAction: () => void handleLoadClipboard(), - }, - ] - : [ - { - id: 'load-clipboard', - title: t('action.pasteFromClipboard'), - style: 'primary', - onAction: () => void handleLoadClipboard(), - }, - ], + summaryText, + actions: filterBarActions, }} > - {!parsedState.ok && !rawCurl.trim() && ( + {inputMode.kind === 'empty' && history.length === 0 && ( void handleLoadClipboard()} /> + } /> )} - {!parsedState.ok && rawCurl.trim() !== '' && ( + {inputMode.kind === 'error' && ( } actions={ @@ -255,114 +768,195 @@ export function CurlHttpCommand() { icon={Icon.Clipboard} onAction={() => void handleLoadClipboard()} /> + } /> )} - {parsedState.ok && ( - + {inputMode.kind === 'parsed' && ( + + {responseSnap && ( + + )} + {responseSnap && ( + + )} + {responseContentType && ( + + )} + + + } + /> + } + actions={renderRequestActions( + inputMode.parsed, + inputMode.generatedCode, + inputMode.canonicalCurl, + )} + /> + + + } + actions={renderRequestActions( + inputMode.parsed, + inputMode.generatedCode, + inputMode.canonicalCurl, + )} + /> + + + } + actions={renderRequestActions( + inputMode.parsed, + inputMode.generatedCode, + inputMode.canonicalCurl, + true, + )} + /> + + + + + } /> } - actions={ - - void handleSendRequest()} - /> - - {responseSnap && ( - - )} - void handleLoadClipboard()} - /> - - } + actions={renderRequestActions( + inputMode.parsed, + inputMode.generatedCode, + inputMode.canonicalCurl, + )} /> + + )} - {(Object.entries(parsedState.parsed.headers) as Array<[string, string]>).map( - ([hKey, hVal]) => ( - - } - actions={ - - - - } - /> - ), - )} + {inputMode.kind === 'historySearch' && ( + + {inputMode.matches.map(renderHistoryItem)} + + )} + + {inputMode.kind !== 'historySearch' && history.length > 0 && ( + + {history.map(renderHistoryItem)} )} diff --git a/extensions/curl-http/src/request-editor-form.tsx b/extensions/curl-http/src/request-editor-form.tsx new file mode 100644 index 00000000..f45fb2a2 --- /dev/null +++ b/extensions/curl-http/src/request-editor-form.tsx @@ -0,0 +1,177 @@ +import React, { + Form, + ActionPanel, + Action, + Icon, + showToast, + ToastStyle, + useNavigation, + useState, + useLocale, +} from '@ztools/declarative-ui' +import { t } from './i18n.js' +import { HTTP_METHODS, type ParsedCurlRequest, type RequestFormDraft } from './types.js' +import { buildParsedRequestFromForm, formatHeadersText } from './curl-service.js' +import { DEFAULT_TIMEOUT_MS } from './history-service.js' + +export interface RequestEditorFormProps { + initialRequest?: ParsedCurlRequest | null + initialTimeoutMs?: number + onApply: (parsed: ParsedCurlRequest, timeoutMs: number, sendImmediately: boolean) => void +} + +function createInitialDraft( + initialRequest?: ParsedCurlRequest | null, + initialTimeoutMs?: number, +): RequestFormDraft { + const methodUpper = initialRequest?.method?.toUpperCase() || 'GET' + const method = (HTTP_METHODS as readonly string[]).includes(methodUpper) ? methodUpper : 'GET' + return { + method, + url: initialRequest?.url ?? '', + headersText: initialRequest ? formatHeadersText(initialRequest.headers) : '', + body: initialRequest?.body ?? '', + timeoutMs: String(initialTimeoutMs ?? DEFAULT_TIMEOUT_MS), + } +} + +export function RequestEditorForm(props: RequestEditorFormProps) { + useLocale() + const { pop } = useNavigation() + const initial = createInitialDraft(props.initialRequest, props.initialTimeoutMs) + const [method, setMethod] = useState(initial.method) + const [url, setUrl] = useState(initial.url) + const [headersText, setHeadersText] = useState(initial.headersText) + const [body, setBody] = useState(initial.body) + const [timeoutMs, setTimeoutMs] = useState(initial.timeoutMs) + const [urlError, setUrlError] = useState(undefined) + const [headersError, setHeadersError] = useState(undefined) + const [timeoutError, setTimeoutError] = useState(undefined) + + const handleSubmit = async ( + values: Record, + sendImmediately: boolean, + ): Promise => { + setUrlError(undefined) + setHeadersError(undefined) + setTimeoutError(undefined) + + const draft: RequestFormDraft = { + method: typeof values.method === 'string' && values.method ? values.method : method, + url: typeof values.url === 'string' ? values.url : url, + headersText: typeof values.headers === 'string' ? values.headers : headersText, + body: typeof values.body === 'string' ? values.body : body, + timeoutMs: typeof values.timeoutMs === 'string' ? values.timeoutMs : timeoutMs, + } + + try { + const result = buildParsedRequestFromForm(draft) + props.onApply(result.parsed, result.timeoutMs, sendImmediately) + pop() + if (!sendImmediately) { + await showToast({ + style: ToastStyle.Success, + title: t('toast.formSaved'), + }) + } + } catch (err) { + const msg = err instanceof Error ? err.message : String(err) + const cleanMsg = msg.replace(/^[A-Z_]+:\s*/, '') + if (/INVALID_TARGET_URL|UNSUPPORTED_PROTOCOL/.test(msg) || !draft.url.trim()) { + setUrlError(cleanMsg) + } else if (/INVALID_CURL_HEADER/.test(msg) || /请求头|Header/i.test(cleanMsg)) { + setHeadersError(cleanMsg) + } else if (/超时|timeout/i.test(cleanMsg)) { + setTimeoutError(cleanMsg) + } + await showToast({ + style: ToastStyle.Failure, + title: t('error.parseTitle'), + message: cleanMsg, + }) + } + } + + return ( +
+ void handleSubmit(values, true)} + /> + void handleSubmit(values, false)} + /> + + } + > + + {HTTP_METHODS.map((m) => ( + + ))} + + + { + setUrl(val) + if (urlError) setUrlError(undefined) + }} + /> + + { + setHeadersText(val) + if (headersError) setHeadersError(undefined) + }} + /> + + + + { + setTimeoutMs(val) + if (timeoutError) setTimeoutError(undefined) + }} + /> + + ) +} diff --git a/extensions/curl-http/src/types.ts b/extensions/curl-http/src/types.ts index 5aa2a373..789e580c 100644 --- a/extensions/curl-http/src/types.ts +++ b/extensions/curl-http/src/types.ts @@ -1,4 +1,16 @@ -export type CodeTargetLang = 'fetch' | 'axios' | 'python' | 'go' +export type CodeTargetLang = 'curl' | 'fetch' | 'axios' | 'python' | 'go' + +export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTIONS' + +export const HTTP_METHODS: readonly HttpMethod[] = [ + 'GET', + 'POST', + 'PUT', + 'PATCH', + 'DELETE', + 'HEAD', + 'OPTIONS', +] export interface ParsedCurlRequest { method: string @@ -25,3 +37,26 @@ export interface HttpResponseSnapshot { ignoredHeaders: string[] bodyText: string } + +export interface RequestFormDraft { + method: string + url: string + headersText: string + body: string + timeoutMs: string +} + +export interface CurlHistoryEntry { + id: string + method: string + url: string + headers: Record + body?: string + rawCommand: string + timeoutMs: number + lastStatus?: number + lastStatusText?: string + lastElapsedMs?: number + lastSizeBytes?: number + updatedAt: number +} diff --git a/extensions/curl-http/tests/curl-http.request.test.mjs b/extensions/curl-http/tests/curl-http.request.test.mjs index c7172eca..274a544b 100644 --- a/extensions/curl-http/tests/curl-http.request.test.mjs +++ b/extensions/curl-http/tests/curl-http.request.test.mjs @@ -1,7 +1,14 @@ import test from 'node:test' import assert from 'node:assert/strict' import { createHost } from '../../shared/test-harness.mjs' -import { executeCurlRequest, parseCurlCommand } from '../dist/curl-service.js' +import { + executeCurlRequest, + parseCurlCommand, + buildCurlCommand, + buildParsedRequestFromForm, + generateCodeFromCurl, +} from '../dist/curl-service.js' +import { upsertHistoryEntry, MAX_HISTORY_ITEMS } from '../dist/history-service.js' const host = createHost() test.beforeEach(() => host.reset()) @@ -73,3 +80,52 @@ test('宿主通道缺失时不回退到有 CORS 限制的页面 fetch', async () globalThis.window = previousWindow } }) + +test('宿主返回 responseHeaders 时如实保留并支持数组头合并', async () => { + host.ipc.network_http_request = async () => ({ + success: true, + data: { + statusCode: 200, + statusText: 'OK', + body: '{"ok":true}', + responseHeaders: { + 'content-type': 'application/json', + 'set-cookie': ['a=1', 'b=2'], + }, + }, + }) + const result = await executeCurlRequest(parseCurlCommand('https://example.test/headers')) + assert.equal(result.responseHeaders['content-type'], 'application/json') + assert.equal(result.responseHeaders['set-cookie'], 'a=1, b=2') +}) + +test('buildCurlCommand 与 Form 构造支持单引号/多行 JSON 无损往返,历史最多保留 30 条并去重', () => { + const { parsed, timeoutMs } = buildParsedRequestFromForm({ + method: 'PATCH', + url: 'https://api.example.test/v2/users/42?lang=zh', + headersText: "Content-Type: application/json\nX-Note: it's ok", + body: '{\n "role": "maintainer"\n}', + timeoutMs: '20000', + }) + assert.equal(timeoutMs, 20000) + const cmd = buildCurlCommand(parsed) + const reparsed = parseCurlCommand(cmd) + assert.equal(reparsed.method, 'PATCH') + assert.equal(reparsed.url, parsed.url) + assert.equal(reparsed.headers['X-Note'], "it's ok") + assert.equal(reparsed.body, parsed.body) + assert.match(generateCodeFromCurl(parsed, 'curl'), /curl -X PATCH/) + + // 历史上限 30 条且相同请求去重置顶 + let list = [] + for (let i = 0; i < 35; i++) { + const req = parseCurlCommand(`https://example.test/item/${i}`) + list = upsertHistoryEntry(list, req, { now: 1000 + i }) + } + assert.equal(list.length, MAX_HISTORY_ITEMS) + assert.equal(list[0].url, 'https://example.test/item/34') + const dupReq = parseCurlCommand('https://example.test/item/10') + list = upsertHistoryEntry(list, dupReq, { now: 9999 }) + assert.equal(list.length, MAX_HISTORY_ITEMS) + assert.equal(list[0].url, 'https://example.test/item/10') +}) diff --git a/extensions/curl-http/tests/curl-http.view.test.mjs b/extensions/curl-http/tests/curl-http.view.test.mjs index 8cccc918..1cab2d8c 100644 --- a/extensions/curl-http/tests/curl-http.view.test.mjs +++ b/extensions/curl-http/tests/curl-http.view.test.mjs @@ -1,21 +1,40 @@ import test from 'node:test' import assert from 'node:assert/strict' -import { createHost, mount, tick } from '../../shared/test-harness.mjs' -import { CurlHttpCommand } from '../dist/index.js' +import { createHost, mount, mountPushed, tick } from '../../shared/test-harness.mjs' +import { CurlHttpCommand, HISTORY_STORAGE_KEY } from '../dist/index.js' const host = createHost() test.beforeEach(() => host.reset()) const reply = { success: true, data: { statusCode: 200, statusText: 'OK', body: '{"verified":true}' } } -const send = (view) => view.run(view.item(n => n.props.id === 'curl-overview'), '立即发起 HTTP 请求') +const replyWithHeaders = { + success: true, + data: { + statusCode: 200, + statusText: 'OK', + body: '{"code":0,"data":{"userId":42}}', + responseHeaders: { + 'content-type': 'application/json; charset=utf-8', + 'x-trace-id': 'trace-xyz-99', + }, + }, +} +const send = (view) => view.run(view.item(n => n.props.id === 'curl-response-body'), '立即发起 HTTP 请求') -test('真实宿主初始请求为空,不预填或发送示例请求', async () => { +test('真实宿主初始请求为空,不预填或发送示例请求,顶栏提供编辑请求与读取剪贴板入口', async () => { const view = await mount(CurlHttpCommand) try { assert.equal(view.tree().props.searchText, '') assert.doesNotMatch(view.text(), /httpbin\.org/) assert.equal(host.ipcCalls.length, 0) + const fbActions = view.tree().props.filterBar?.actions ?? [] + assert.ok(fbActions.some(a => a.id === 'edit-request-form')) + assert.ok(fbActions.some(a => a.id === 'load-clipboard')) + await view.search('http://localhost/audit') - assert.equal(view.item(n => n.props.id === 'curl-overview').props.id, 'curl-overview') + assert.equal(view.item(n => n.props.id === 'curl-response-body').props.id, 'curl-response-body') + assert.equal(view.item(n => n.props.id === 'curl-response-headers').props.id, 'curl-response-headers') + assert.equal(view.item(n => n.props.id === 'curl-generated-code').props.id, 'curl-generated-code') + assert.equal(view.item(n => n.props.id === 'curl-request-inspect').props.id, 'curl-request-inspect') } finally { view.unmount() } }) @@ -26,12 +45,15 @@ test('修改请求后清除旧响应,下一次请求失败不保留旧成功 await view.search('http://localhost/audit') await send(view) assert.match(view.text(), /verified/) + assert.equal(view.tree().props.selectedItemId, 'curl-response-body') await view.search('http://localhost/new') - assert.doesNotMatch(view.text(), /verified|HTTP 200/) + const bodyDetail = view.item(n => n.props.id === 'curl-response-body').props.detail.props.markdown + assert.doesNotMatch(bodyDetail, /verified|HTTP 200/) host.ipc.network_http_request = async () => { throw new Error('连接被拒绝') } await send(view) assert.equal(host.lastToast().style, 'FAILURE') - assert.doesNotMatch(view.text(), /verified|HTTP 200/) + const afterFail = view.item(n => n.props.id === 'curl-response-body').props.detail.props.markdown + assert.doesNotMatch(afterFail, /verified|HTTP 200/) } finally { view.unmount() } }) @@ -64,7 +86,7 @@ test('不在客户端里运行时同样不预填示例请求', async () => { const view = await mount(CurlHttpCommand) await tick() assert.doesNotMatch(view.text(), /httpbin\.org|declarative-ui/) - // 空输入是引导状态,不显示红色解析错误与内部错误码 + // 空输入且无历史是引导状态,不显示红色解析错误与内部错误码 assert.equal(view.items()[0].props.id, 'curl-empty') assert.doesNotMatch(view.text(), /EMPTY_CURL_INPUT|语法错误/) view.unmount() @@ -112,6 +134,133 @@ test('输入无法解析时显示解析错误,副标题不带内部错误码', view.unmount() }) +test('响应头视图诚实展示宿主返回的响应头,无响应头时不造假;切换代码语言实时更新', async () => { + host.ipc.network_http_request = async () => replyWithHeaders + const view = await mount(CurlHttpCommand) + try { + await view.search('curl -X POST "https://api.example.test/v2/users" -H "Authorization: Bearer tok" -d \'{"a":1}\'') + await send(view) + await tick() + const headersItem = view.item(n => n.props.id === 'curl-response-headers') + assert.match(headersItem.props.detail.props.markdown, /x-trace-id/) + assert.match(headersItem.props.detail.props.markdown, /trace-xyz-99/) + + // 切换代码语言为 cURL 与 Python + view.tree().props.searchBarAccessory.props.onChange('curl') + await tick() + const curlCode = view.item(n => n.props.id === 'curl-generated-code').props.detail.props.markdown + assert.match(curlCode, /curl 'https:\/\/api\.example\.test\/v2\/users'/) + + view.tree().props.searchBarAccessory.props.onChange('python') + await tick() + const pyCode = view.item(n => n.props.id === 'curl-generated-code').props.detail.props.markdown + assert.match(pyCode, /import requests/) + + // 宿主不返回响应头时如实提示,不伪造 Content-Type + host.ipc.network_http_request = async () => reply + await send(view) + await tick() + const noHeadersMd = view.item(n => n.props.id === 'curl-response-headers').props.detail.props.markdown + assert.match(noHeadersMd, /未返回响应头/) + assert.doesNotMatch(noHeadersMd, /trace-xyz-99/) + } finally { view.unmount() } +}) + +test('Form 请求编辑器支持多行 Headers/JSON Body 保存并发送,异常输入拦截不跳转', async () => { + host.ipc.network_http_request = async (params) => { + assert.equal(params.method, 'POST') + assert.equal(params.url, 'https://api.example.test/v1/submit') + assert.equal(params.headers['Content-Type'], 'application/json') + assert.equal(params.headers['X-Env'], 'staging') + assert.equal(params.body, '{\n "role": "maintainer"\n}') + assert.equal(params.timeout, 15000) + return replyWithHeaders + } + const view = await mount(CurlHttpCommand) + try { + const editBtn = view.tree().props.filterBar.actions.find(a => a.id === 'edit-request-form') + editBtn.onAction() + await tick() + assert.equal(host.pushed.length, 1) + + const formView = await mountPushed(host) + try { + const submitAndSend = formView.tree().props.actions.children[0] + // 非法空 URL 被拦截,不 pop 也不发请求 + await submitAndSend.props.onSubmit({ method: 'POST', url: ' ', headers: '', body: '', timeoutMs: '10000' }) + await tick() + assert.equal(host.pushed.length, 1) + assert.equal(host.lastToast().style, 'FAILURE') + + // 非法 Header 被拦截 + await submitAndSend.props.onSubmit({ + method: 'POST', + url: 'https://api.example.test/v1/submit', + headers: 'MalformedHeaderWithoutColon', + body: '', + timeoutMs: '10000', + }) + await tick() + assert.equal(host.pushed.length, 1) + + // 合法多行 Headers + JSON Body 提交并立即发送 + await submitAndSend.props.onSubmit({ + method: 'POST', + url: 'https://api.example.test/v1/submit', + headers: 'Content-Type: application/json\nX-Env: staging', + body: '{\n "role": "maintainer"\n}', + timeoutMs: '15000', + }) + await tick() + assert.equal(host.pushed.length, 0) + } finally { formView.unmount() } + + await tick() + assert.equal(host.ipcCalls.filter(([m]) => m === 'network_http_request').length, 1) + assert.match(view.item(n => n.props.id === 'curl-response-body').props.detail.props.markdown, /"userId": 42/) + } finally { view.unmount() } +}) + +test('LocalStorage 历史持久化:重开插件展示历史、支持关键词检索、一键重放、单条删除与清空确认', async () => { + host.ipc.network_http_request = async () => replyWithHeaders + const view1 = await mount(CurlHttpCommand) + try { + await view1.search('https://api.example.test/v2/health') + await send(view1) + await tick() + } finally { view1.unmount() } + + // 重开插件,空输入直接展示本地历史而非空态 + const view2 = await mount(CurlHttpCommand) + try { + await tick() + const historyItems = view2.items().filter(i => String(i.props.id).startsWith('history-')) + assert.equal(historyItems.length, 1) + assert.match(historyItems[0].props.title, /GET \/v2\/health/) + + // 关键词搜历史 + await view2.search('health') + await tick() + const filtered = view2.items().filter(i => String(i.props.id).startsWith('history-')) + assert.equal(filtered.length, 1) + + // 一键重放 + await view2.run(filtered[0], '载入并立即重放') + await tick() + assert.equal(host.ipcCalls.filter(([m]) => m === 'network_http_request').length, 2) + + // 删除该条历史 + await view2.search('') + await tick() + const target = view2.items().find(i => String(i.props.id).startsWith('history-')) + await view2.run(target, '删除该条历史') + await tick() + assert.equal(view2.items()[0].props.id, 'curl-empty') + const stored = JSON.parse(host.storage.get(HISTORY_STORAGE_KEY) || '[]') + assert.equal(stored.length, 0) + } finally { view2.unmount() } +}) + test('续行与复制格式说明按平台给:macOS 不提 cmd / PowerShell,Windows 保留,支持中英文切换', async () => { const { copyFormatHint } = await import('../dist/index.js') const mac = copyFormatHint(true) diff --git a/extensions/env-manager/plugin.json b/extensions/env-manager/plugin.json index 1d778edb..84cb6b5b 100644 --- a/extensions/env-manager/plugin.json +++ b/extensions/env-manager/plugin.json @@ -1,7 +1,7 @@ { "id": "env-manager", "name": "环境变量", - "version": "1.0.10", + "version": "1.0.11", "description": "管理 Windows 注册表环境与 macOS 终端变量,查看只读进程快照,预览 PATH 清理,修改前保留可恢复备份", "author": "ZTools Team", "category": [ diff --git a/extensions/env-manager/src/env-service.ts b/extensions/env-manager/src/env-service.ts index 58981d8b..090747ee 100644 --- a/extensions/env-manager/src/env-service.ts +++ b/extensions/env-manager/src/env-service.ts @@ -1,5 +1,5 @@ import { t } from './i18n.js' -import type { EnvChange, EnvPlan, EnvSnapshot } from './types.js' +import type { EnvChange, EnvPath, EnvPlan, EnvScope, EnvSnapshot } from './types.js' import { resolveErrorMessage } from './error-i18n.js' interface Reply { success?: boolean; data?: unknown; error?: { message?: string } } interface Bridge { transport?: { methods?: Record Promise> } } @@ -52,3 +52,122 @@ export function darwinPathProblem(value: string) { export function exportEnvSnapshot(snapshot: EnvSnapshot) { return JSON.stringify({ version: 1, exportedAt: new Date().toISOString(), platform: snapshot.platform, notice: snapshot.notice, sources: snapshot.sources, variables: snapshot.variables, paths: snapshot.paths }, null, 2) } + +export function pathSeparator(platform: string): string { + return platform === 'win32' ? ';' : ':' +} + +export function normalizePathEntry(entry: string, platform: string): string { + const trimmed = entry.trim() + if (!trimmed) return '' + if (platform === 'win32') { + const unified = trimmed.replace(/\//g, '\\') + const stripped = /^[A-Za-z]:\\+$/.test(unified) ? `${unified.slice(0, 2)}\\` : unified.replace(/\\+$/, '') + return stripped.toLowerCase() + } + return trimmed === '/' ? '/' : trimmed.replace(/\/+$/, '') +} + +/** 按作用域检测重复的 PATH 条目(保留首次出现,后续重复项返回 `${scope}:${index}` 集合)。 */ +export function findDuplicatePathKeys(paths: EnvPath[], platform: string): Set { + const seenByScope = new Map>() + const duplicates = new Set() + for (const p of paths) { + const norm = normalizePathEntry(p.value, platform) + if (!norm) continue + let seen = seenByScope.get(p.scope) + if (!seen) { + seen = new Set() + seenByScope.set(p.scope, seen) + } + if (seen.has(norm)) duplicates.add(`${p.scope}:${p.index}`) + else seen.add(norm) + } + return duplicates +} + +export function getScopePathState(snapshot: EnvSnapshot, scope: EnvScope): { key: string; entries: string[] } { + const sep = pathSeparator(snapshot.platform) + const found = snapshot.variables.find(v => v.scope === scope && isPathKey(v.key, snapshot.platform)) + if (found) { + return { + key: found.key, + entries: found.value === '' ? [] : found.value.split(sep) + } + } + const fromPaths = snapshot.paths.filter(p => p.scope === scope).sort((a, b) => a.index - b.index).map(p => p.value) + return { + key: snapshot.platform === 'win32' ? 'Path' : 'PATH', + entries: fromPaths + } +} + +export function deduplicatePathEntries(entries: string[], platform: string): { kept: string[]; removed: string[] } { + const seen = new Set() + const kept: string[] = [] + const removed: string[] = [] + for (const entry of entries) { + const norm = normalizePathEntry(entry, platform) + if (norm && seen.has(norm)) { + removed.push(entry) + } else { + if (norm) seen.add(norm) + kept.push(entry) + } + } + return { kept, removed } +} + +export function buildCleanedAndDeduplicatedPath(snapshot: EnvSnapshot, scope: EnvScope): { key: string; value: string; removed: string[] } { + const sep = pathSeparator(snapshot.platform) + const state = getScopePathState(snapshot, scope) + const missingIndexSet = new Set( + snapshot.paths.filter(p => p.scope === scope && p.status === 'missing').map(p => p.index) + ) + const seen = new Set() + const kept: string[] = [] + const removed: string[] = [] + for (let i = 0; i < state.entries.length; i++) { + const entry = state.entries[i]! + const norm = normalizePathEntry(entry, snapshot.platform) + if (missingIndexSet.has(i)) { + removed.push(entry) + continue + } + if (norm && seen.has(norm)) { + removed.push(entry) + continue + } + if (norm) seen.add(norm) + kept.push(entry) + } + return { key: state.key, value: kept.join(sep), removed } +} + +/** 显式调用宿主目录选择窗口,用户取消返回 null。 */ +export async function pickDirectory(title: string): Promise { + const root = globalThis as unknown as { + window?: { __ztoolsElectron?: Bridge } + __ztoolsElectron?: Bridge + } + const methods = root.window?.__ztoolsElectron?.transport?.methods ?? root.__ztoolsElectron?.transport?.methods + const selectFolder = methods?.window_show_select_folder_dialog + if (typeof selectFolder === 'function') { + const result = await selectFolder({ messageId: `env_dir_${Date.now()}_${++sequence}`, params: { title } }) + if (result?.success !== true) throw new Error(resolveErrorMessage(result?.error, t('envRequestFailed'))) + const data = record(result.data) ? result.data : {} + if (data.canceled === true) return null + const folderPath = typeof data.folderPath === 'string' ? data.folderPath : typeof data.filePath === 'string' ? data.filePath : '' + return folderPath.trim() || null + } + const openDialog = methods?.window_show_open_dialog + if (typeof openDialog === 'function') { + const result = await openDialog({ messageId: `env_dir_${Date.now()}_${++sequence}`, params: { title, properties: ['openDirectory'] } }) + if (result?.success !== true) throw new Error(resolveErrorMessage(result?.error, t('envRequestFailed'))) + const data = record(result.data) ? result.data : {} + if (data.canceled === true) return null + const folderPath = typeof data.filePath === 'string' ? data.filePath : Array.isArray(data.filePaths) && typeof data.filePaths[0] === 'string' ? data.filePaths[0] : '' + return folderPath.trim() || null + } + throw new Error(t('errDialogUnsupported')) +} diff --git a/extensions/env-manager/src/i18n.ts b/extensions/env-manager/src/i18n.ts index 85dbe2ee..d8b0ae27 100644 --- a/extensions/env-manager/src/i18n.ts +++ b/extensions/env-manager/src/i18n.ts @@ -91,6 +91,27 @@ const rawT = createTranslator( invalidDirCountTag: "{count} 个确认失效目录", emptyPathEntryLabel: "(空项:当前目录)", actionCopyDir: "复制目录", + actionShowDirInFinder: "在文件管理器中显示", + actionAddPathDir: "添加目录…", + actionPickDirToValue: "选择目录填入…", + actionRemovePathEntry: "删除此 PATH 条目", + actionMovePathUp: "上移优先级", + actionMovePathDown: "下移优先级", + actionDeduplicatePath: "一键去重 PATH", + actionCleanAndDeduplicatePath: "清理失效并去重", + actionManagePathEntries: "逐条管理 PATH", + tagMissingDir: "失效目录", + tagDuplicateDir: "重复条目", + duplicateDirCountTag: "{count} 个重复条目", + dialogPickDirTitle: "选择要添加的目录", + errDialogUnsupported: "当前客户端不支持系统目录选择窗口,请升级客户端", + errDirAlreadyInPath: "该目录已在 {scope} PATH 中,无需重复添加", + errNoDuplicatePaths: "当前作用域 PATH 没有重复条目", + errNoCleanablePaths: "当前作用域 PATH 没有失效或重复条目", + confirmAddedHeader: "将追加以下目录:\n{dirs}\n", + pathSectionTitle: "{scope} PATH({count} 条)", + pathSectionIssueTitle: "{scope} PATH({count} 条 · 失效 {missing} · 重复 {dup})", + pathSummaryReady: "PATH 共 {count} 条(失效 {missing} · 重复 {dup})", actionPreviewRestore: "预览恢复原配置", actionCopyBackupId: "复制备份编号" }, @@ -183,6 +204,27 @@ const rawT = createTranslator( invalidDirCountTag: "{count} missing dir(s)", emptyPathEntryLabel: "(Empty: current dir)", actionCopyDir: "Copy Directory", + actionShowDirInFinder: "Reveal in File Manager", + actionAddPathDir: "Add Directory...", + actionPickDirToValue: "Choose Directory...", + actionRemovePathEntry: "Remove This PATH Entry", + actionMovePathUp: "Move Up Priority", + actionMovePathDown: "Move Down Priority", + actionDeduplicatePath: "Deduplicate PATH", + actionCleanAndDeduplicatePath: "Clean Missing & Duplicates", + actionManagePathEntries: "Manage PATH Entries", + tagMissingDir: "Missing", + tagDuplicateDir: "Duplicate", + duplicateDirCountTag: "{count} duplicate(s)", + dialogPickDirTitle: "Select Directory to Add", + errDialogUnsupported: "System folder picker is not supported; please upgrade ZTools", + errDirAlreadyInPath: "Directory already exists in {scope} PATH", + errNoDuplicatePaths: "No duplicate PATH entries in this scope", + errNoCleanablePaths: "No missing or duplicate PATH entries in this scope", + confirmAddedHeader: "Directories to append:\n{dirs}\n", + pathSectionTitle: "{scope} PATH ({count})", + pathSectionIssueTitle: "{scope} PATH ({count} · {missing} missing · {dup} duplicate)", + pathSummaryReady: "{count} PATH entries ({missing} missing · {dup} duplicate)", actionPreviewRestore: "Preview Restore", actionCopyBackupId: "Copy Backup ID" } diff --git a/extensions/env-manager/src/index.tsx b/extensions/env-manager/src/index.tsx index 569e042a..9dedb532 100644 --- a/extensions/env-manager/src/index.tsx +++ b/extensions/env-manager/src/index.tsx @@ -1,7 +1,22 @@ -import React, { Action, ActionPanel, Clipboard, Form, Icon, List, Toast, confirmAlert, getLocale, showToast, useEffect, useLocale, useNavigation, useRef, useState } from '@ztools/declarative-ui' +import React, { Action, ActionPanel, Clipboard, Color, Form, Icon, List, Toast, confirmAlert, getLocale, showToast, useEffect, useLocale, useNavigation, useRef, useState } from '@ztools/declarative-ui' import { t } from './i18n.js' -import { applyEnvironment, cancelEnvironment, darwinPathProblem, exportEnvSnapshot, isPathKey, loadEnvironment, prepareEnvironment } from './env-service.js' -import type { EnvChange, EnvItem, EnvScope, EnvSnapshot } from './types.js' +import { + applyEnvironment, + buildCleanedAndDeduplicatedPath, + cancelEnvironment, + darwinPathProblem, + deduplicatePathEntries, + exportEnvSnapshot, + findDuplicatePathKeys, + getScopePathState, + isPathKey, + loadEnvironment, + normalizePathEntry, + pathSeparator, + pickDirectory, + prepareEnvironment +} from './env-service.js' +import type { EnvChange, EnvItem, EnvPath, EnvScope, EnvSnapshot } from './types.js' export * from './types.js' export * from './env-service.js' const failure = (error: unknown) => error instanceof Error ? error.message : String(error) @@ -54,8 +69,26 @@ export function EnvVarForm({ item, snapshot, onSave }: { item?: EnvItem; snapsho } catch (e) { if (alive.current) { setError(failure(e)); await showToast(Toast.Style.Failure, t('toastNotSavedTitle'), failure(e)) } } finally { active.current = false; if (alive.current) setBusy(false) } } + const pickDirForValue = async () => { + if (active.current) return + try { + const dir = await pickDirectory(t('dialogPickDirTitle')) + if (!dir || !alive.current) return + if (isPathKey(key.trim(), snapshot.platform) && value.trim()) { + const sep = pathSeparator(snapshot.platform) + setValue(`${value}${value.endsWith(sep) ? '' : sep}${dir}`) + } else { + setValue(dir) + } + } catch (e) { + if (alive.current) { + setError(failure(e)) + await showToast(Toast.Style.Failure, t('toastOpFailedTitle'), failure(e)) + } + } + } return
}> + actions={ void pickDirForValue()} />}> {item ? : } setSource(v as EnvScope)}> @@ -68,7 +101,7 @@ export function EnvVarForm({ item, snapshot, onSave }: { item?: EnvItem; snapsho } -export function EnvManagerCommand({ featureCode = 'env-all' }: { featureCode?: string } = {}) { +export function EnvManagerCommand({ featureCode = 'env-all', pickDirectoryFn = pickDirectory }: { featureCode?: string; pickDirectoryFn?: (title: string) => Promise } = {}) { useLocale() const { push } = useNavigation() const [snapshot, setSnapshot] = useState(null), [error, setError] = useState(''), [busy, setBusy] = useState(false) @@ -88,7 +121,7 @@ export function EnvManagerCommand({ featureCode = 'env-all' }: { featureCode?: s } const refresh = () => work(reload) useEffect(() => { alive.current = true; void refresh(); return () => { alive.current = false; if (active.current) void cancelEnvironment().catch(e => console.warn('Env cancellation unconfirmed', e)) } }, []) - const mutate = async (change: EnvChange, isCurrent: () => boolean = () => true): Promise => { + const mutate = async (change: EnvChange, isCurrent: () => boolean = () => true, detail?: { removed?: string[]; added?: string[] }): Promise => { if (active.current) throw new Error(t('errOpBusy')) const loaded = current.current if (!loaded) throw new Error(t('errLoadEnvFirst')) @@ -97,8 +130,11 @@ export function EnvManagerCommand({ featureCode = 'env-all' }: { featureCode?: s const plan = await prepareEnvironment(loaded.sessionId, change) if (!alive.current || !isCurrent()) return false const pathWarning = loaded.platform === 'darwin' && change.kind === 'set' && change.key === 'PATH' ? t('darwinPathNotice') + '\n' : '' - const removedPart = plan.removed.length ? t('confirmRemovedHeader', { dirs: plan.removed.join('\n') }) : '' - const confirmed = await confirmAlert({ title: plan.summary, message: `${t('confirmLocationLabel', { location: plan.location })}${pathWarning}${removedPart}${t('confirmBackupNote', { notice: plan.notice })}`, primaryAction: { title: t('confirmApplyBtn') }, dismissAction: { title: t('cancelBtn') } }) + const removedList = plan.removed.length ? plan.removed : (detail?.removed ?? []) + const addedList = detail?.added ?? [] + const removedPart = removedList.length ? t('confirmRemovedHeader', { dirs: removedList.join('\n') }) : '' + const addedPart = addedList.length ? t('confirmAddedHeader', { dirs: addedList.join('\n') }) : '' + const confirmed = await confirmAlert({ title: plan.summary, message: `${t('confirmLocationLabel', { location: plan.location })}${pathWarning}${addedPart}${removedPart}${t('confirmBackupNote', { notice: plan.notice })}`, primaryAction: { title: t('confirmApplyBtn') }, dismissAction: { title: t('cancelBtn') } }) if (!confirmed || !alive.current || !isCurrent()) { await cancelEnvironment(); return false } let result: { backupId: string; summary: string; recoveryPath?: string } | undefined, operationError = '' try { result = await applyEnvironment(plan.planId) } catch (e) { operationError = failure(e) } @@ -115,7 +151,91 @@ export function EnvManagerCommand({ featureCode = 'env-all' }: { featureCode?: s return isCurrent() } finally { active.current = false; if (alive.current) setBusy(false) } } - const runChange = async (change: EnvChange) => { try { await mutate(change) } catch (e) { if (alive.current) { setError(failure(e)); await showToast(Toast.Style.Failure, t('toastChangeUnconfirmed'), failure(e)) } } } + const runChange = async (change: EnvChange, detail?: { removed?: string[]; added?: string[] }) => { try { await mutate(change, () => true, detail) } catch (e) { if (alive.current) { setError(failure(e)); await showToast(Toast.Style.Failure, t('toastChangeUnconfirmed'), failure(e)) } } } + const validateDarwinPath = (loaded: EnvSnapshot, key: string, value: string) => { + if (loaded.platform === 'darwin' && key === 'PATH') { + const problem = darwinPathProblem(value) + if (problem) throw new Error(problem) + } + } + const removePathEntry = async (entry: EnvPath) => { + if (entry.scope === 'process') return + const loaded = current.current + if (!loaded) return + try { + const state = getScopePathState(loaded, entry.scope) + const nextEntries = state.entries.filter((_, idx) => idx !== entry.index) + const nextValue = nextEntries.join(pathSeparator(loaded.platform)) + validateDarwinPath(loaded, state.key, nextValue) + await mutate({ kind: 'set', source: entry.scope, key: state.key, value: nextValue }, () => true, { removed: [entry.value || t('emptyPathEntryLabel')] }) + } catch (e) { + if (alive.current) { setError(failure(e)); await showToast(Toast.Style.Failure, t('toastChangeUnconfirmed'), failure(e)) } + } + } + const movePathEntry = async (entry: EnvPath, delta: -1 | 1) => { + if (entry.scope === 'process') return + const loaded = current.current + if (!loaded) return + const state = getScopePathState(loaded, entry.scope) + const targetIdx = entry.index + delta + if (entry.index < 0 || entry.index >= state.entries.length || targetIdx < 0 || targetIdx >= state.entries.length) return + try { + const nextEntries = [...state.entries] + const moved = nextEntries[entry.index]! + nextEntries[entry.index] = nextEntries[targetIdx]! + nextEntries[targetIdx] = moved + const nextValue = nextEntries.join(pathSeparator(loaded.platform)) + validateDarwinPath(loaded, state.key, nextValue) + await mutate({ kind: 'set', source: entry.scope, key: state.key, value: nextValue }) + } catch (e) { + if (alive.current) { setError(failure(e)); await showToast(Toast.Style.Failure, t('toastChangeUnconfirmed'), failure(e)) } + } + } + const appendPathDirectory = async (scope: EnvScope) => { + const loaded = current.current + if (!loaded || active.current) return + try { + const picked = await pickDirectoryFn(t('dialogPickDirTitle')) + if (!picked || !alive.current) return + const state = getScopePathState(loaded, scope) + const normPicked = normalizePathEntry(picked, loaded.platform) + if (state.entries.some(item => normalizePathEntry(item, loaded.platform) === normPicked)) { + throw new Error(t('errDirAlreadyInPath', { scope: sourceName(scope, loaded.platform) })) + } + const nextEntries = [...state.entries, picked] + const nextValue = nextEntries.join(pathSeparator(loaded.platform)) + validateDarwinPath(loaded, state.key, nextValue) + await mutate({ kind: 'set', source: scope, key: state.key, value: nextValue }, () => true, { added: [picked] }) + } catch (e) { + if (alive.current) { setError(failure(e)); await showToast(Toast.Style.Failure, t('toastChangeUnconfirmed'), failure(e)) } + } + } + const deduplicatePath = async (scope: EnvScope) => { + const loaded = current.current + if (!loaded) return + try { + const state = getScopePathState(loaded, scope) + const { kept, removed } = deduplicatePathEntries(state.entries, loaded.platform) + if (!removed.length) throw new Error(t('errNoDuplicatePaths')) + const nextValue = kept.join(pathSeparator(loaded.platform)) + validateDarwinPath(loaded, state.key, nextValue) + await mutate({ kind: 'set', source: scope, key: state.key, value: nextValue }, () => true, { removed }) + } catch (e) { + if (alive.current) { setError(failure(e)); await showToast(Toast.Style.Failure, t('toastChangeUnconfirmed'), failure(e)) } + } + } + const cleanAndDeduplicatePath = async (scope: EnvScope) => { + const loaded = current.current + if (!loaded) return + try { + const { key, value, removed } = buildCleanedAndDeduplicatedPath(loaded, scope) + if (!removed.length) throw new Error(t('errNoCleanablePaths')) + validateDarwinPath(loaded, key, value) + await mutate({ kind: 'set', source: scope, key, value }, () => true, { removed }) + } catch (e) { + if (alive.current) { setError(failure(e)); await showToast(Toast.Style.Failure, t('toastChangeUnconfirmed'), failure(e)) } + } + } const edit = (item?: EnvItem) => { const loaded = current.current; if (loaded && !active.current) push() } const exportBackup = () => work(async () => { if (!current.current) throw new Error(t('errLoadEnvFirst')) @@ -125,10 +245,28 @@ export function EnvManagerCommand({ featureCode = 'env-all' }: { featureCode?: s const cancel = async () => { try { await cancelEnvironment() } catch (e) { if (alive.current) setError(t('cancelUnconfirmed', { error: failure(e) })) } } const q = query.trim().toLowerCase(), platform = snapshot?.platform || '' const invalid = (scope: EnvItem['scope']) => snapshot?.paths.filter(p => p.scope === scope && p.status === 'missing').length || 0 + const duplicateKeys = snapshot ? findDuplicatePathKeys(snapshot.paths, platform) : new Set() + const duplicateCount = (scope: EnvItem['scope']) => snapshot?.paths.filter(p => p.scope === scope && duplicateKeys.has(`${p.scope}:${p.index}`)).length || 0 const isPath = (item: EnvItem) => isPathKey(item.key, platform) // “含失效目录的 PATH”只列可清理的持久配置;当前进程只读,不能清理 const items = snapshot?.variables.filter(v => !isShellInternal(v) && (category === 'all' || category === v.scope || (category === 'invalid' && v.scope !== 'process' && isPath(v) && invalid(v.scope) > 0)) && `${v.key} ${v.value}`.toLowerCase().includes(q)) || [] const paths = category === 'path' ? snapshot?.paths.filter(p => p.value.toLowerCase().includes(q)) || [] : [] + const pathGroups = category === 'path' + ? SCOPE_ORDER.map(scope => { + const list = paths.filter(p => p.scope === scope) + const totalInScope = snapshot?.paths.filter(p => p.scope === scope).length || 0 + const missingInScope = invalid(scope) + const dupInScope = duplicateCount(scope) + const label = sourceName(scope, platform) + const title = (missingInScope > 0 || dupInScope > 0) + ? t('pathSectionIssueTitle', { scope: label, count: list.length, missing: missingInScope, dup: dupInScope }) + : t('pathSectionTitle', { scope: label, count: list.length }) + return { scope, title, items: list, totalInScope, missingInScope, dupInScope } + }).filter(group => group.items.length > 0) + : [] + const totalMissingEditable = invalid('user') + invalid('system') + const totalDuplicateEditable = duplicateCount('user') + duplicateCount('system') + const cleanTargetScope: EnvScope = (invalid('user') + duplicateCount('user')) > 0 ? 'user' : 'system' const backups = category === 'backups' ? snapshot?.backups.filter(b => `${b.createdAt} ${b.summary}`.toLowerCase().includes(q)) || [] : [] const noBackups = category === 'backups' && Boolean(snapshot) && !snapshot?.backups.length const count = category === 'path' ? paths.length : category === 'backups' ? backups.length : items.length @@ -139,10 +277,62 @@ export function EnvManagerCommand({ featureCode = 'env-all' }: { featureCode?: s {item.scope === 'process' ? : category === 'invalid' ? runChange({ kind: 'clean', source: item.scope as EnvScope })} /> : edit(item)} />} {/* macOS 的当前进程变量来自启动 ZTools 的环境,写进终端配置不会改变它,也容易把临时值固化下来:只提供复制 */} {item.scope !== 'process' ? : platform !== 'darwin' && edit(item)} />} + {item.scope !== 'process' && isPath(item) && setCategory('path')} />} + {item.scope !== 'process' && isPath(item) && void appendPathDirectory(item.scope as EnvScope)} />} + {item.scope !== 'process' && isPath(item) && duplicateCount(item.scope) > 0 && void deduplicatePath(item.scope as EnvScope)} />} {item.scope !== 'process' && runChange({ kind: 'delete', source: item.scope as EnvScope, key: item.key })} />} {item.scope !== 'process' && category !== 'invalid' && isPath(item) && invalid(item.scope) > 0 && runChange({ kind: 'clean', source: item.scope as EnvScope })} />} {Boolean(item.value) && isSensitiveKey(item.key) && toggleReveal(item)} />} + const pathRowActions = (p: EnvPath, scopeTotal: number) => { + const editable = p.scope !== 'process' + const scopeMissing = invalid(p.scope) + const scopeDup = duplicateCount(p.scope) + const isIssue = p.status === 'missing' || duplicateKeys.has(`${p.scope}:${p.index}`) + if (!editable) { + return + + {p.value && p.status !== 'missing' && } + + } + const scope = p.scope as EnvScope + const removeAction = removePathEntry(p)} /> + const copyAction = + return + {isIssue ? removeAction : copyAction} + {isIssue ? copyAction : (p.value && p.status !== 'missing' ? : removeAction)} + {!isIssue && p.value && p.status !== 'missing' && removeAction} + {isIssue && p.value && p.status !== 'missing' && } + {p.index > 0 && movePathEntry(p, -1)} />} + {p.index < scopeTotal - 1 && movePathEntry(p, 1)} />} + appendPathDirectory(scope)} /> + {scopeDup > 0 && deduplicatePath(scope)} />} + {scopeMissing > 0 && runChange({ kind: 'clean', source: scope })} />} + {(scopeMissing > 0 || scopeDup > 0) && cleanAndDeduplicatePath(scope)} />} + + } + const filterActions = busy + ? [{ id: 'cancel', title: t('cancelBtn'), style: 'secondary' as const, onAction: cancel }] + : category === 'path' && snapshot + ? [ + { id: 'add-path-dir', label: t('actionAddPathDir'), title: t('actionAddPathDir'), icon: Icon.Plus, style: 'primary' as const, onAction: () => appendPathDirectory('user') }, + (totalMissingEditable > 0 || totalDuplicateEditable > 0) + ? { id: 'clean-dedup-path', label: t('actionCleanAndDeduplicatePath'), title: t('actionCleanAndDeduplicatePath'), icon: Icon.Trash, style: 'secondary' as const, onAction: () => cleanAndDeduplicatePath(cleanTargetScope) } + : { id: 'refresh', label: t('actionRefresh'), title: t('actionRefresh'), icon: Icon.ArrowClockwise, style: 'secondary' as const, onAction: refresh } + ] + : [ + ...(snapshot ? [{ id: category === 'backups' ? 'export' : 'new', label: category === 'backups' ? t('actionCopySnapshot') : t('actionNewVar'), title: category === 'backups' ? t('actionCopySnapshot') : t('actionNewVar'), icon: category === 'backups' ? Icon.CopyClipboard : Icon.Plus, style: 'primary' as const, onAction: category === 'backups' ? exportBackup : () => edit() }] : []), + { id: 'refresh', label: t('actionRefresh'), title: t('actionRefresh'), icon: Icon.ArrowClockwise, style: 'secondary' as const, onAction: refresh } + ] + const summaryText = error || ( + busy + ? t('summaryBusy') + : snapshot + ? category === 'path' + ? t('pathSummaryReady', { count, missing: totalMissingEditable, dup: totalDuplicateEditable }) + : t('summaryReady', { count, hint: platform === 'darwin' ? t('summaryHintDarwin') : t('summaryHintWin') }) + : t('summaryNotLoaded') + ) return @@ -150,14 +340,27 @@ export function EnvManagerCommand({ featureCode = 'env-all' }: { featureCode?: s } - filterBar={{ summaryText: error || (busy ? t('summaryBusy') : snapshot ? t('summaryReady', { count, hint: platform === 'darwin' ? t('summaryHintDarwin') : t('summaryHintWin') }) : t('summaryNotLoaded')), actions: busy ? [{ id: 'cancel', title: t('cancelBtn'), style: 'secondary', onAction: cancel }] : [...(snapshot ? [{ id: category === 'backups' ? 'export' : 'new', label: category === 'backups' ? t('actionCopySnapshot') : t('actionNewVar'), title: category === 'backups' ? t('actionCopySnapshot') : t('actionNewVar'), icon: category === 'backups' ? Icon.CopyClipboard : Icon.Plus, style: 'primary', onAction: category === 'backups' ? exportBackup : () => edit() }] : []), { id: 'refresh', label: t('actionRefresh'), title: t('actionRefresh'), icon: Icon.ArrowClockwise, style: 'secondary', onAction: refresh }] }}> + filterBar={{ summaryText, actions: filterActions }}> {!count && } {groupVariables(items, platform).map(group => {group.items.map(item => 0 ? [{ text: t('invalidDirCountTag', { count: invalid(item.scope) }) }] : []} actions={rowActions(item)} />)} + accessories={[ + ...(isPath(item) && invalid(item.scope) > 0 ? [{ text: t('invalidDirCountTag', { count: invalid(item.scope) }) }] : []), + ...(isPath(item) && duplicateCount(item.scope) > 0 ? [{ text: t('duplicateDirCountTag', { count: duplicateCount(item.scope) }) }] : []) + ]} actions={rowActions(item)} />)} + )} + {pathGroups.map(group => + {group.items.map(p => { + const isDup = duplicateKeys.has(`${p.scope}:${p.index}`) + const isMissing = p.status === 'missing' + return + })} )} - {paths.map(p => } />)} {backups.map(b => runChange({ kind: 'restore', source: b.source, backupId: b.id })} />} />)} diff --git a/extensions/env-manager/tests/environment.test.mjs b/extensions/env-manager/tests/environment.test.mjs index 015e8e6f..39d2dd0d 100644 --- a/extensions/env-manager/tests/environment.test.mjs +++ b/extensions/env-manager/tests/environment.test.mjs @@ -185,3 +185,77 @@ test('名字像密钥的变量默认遮住值,操作面板可显示 / 隐藏 assert.equal(v.item('user:GITHUB_TOKEN').props.subtitle, '已隐藏 · 17 个字符') assert.equal(v.actions(v.item('user:VALUE')).some(a => /变量值$/.test(a.props.title) && a.props.title !== '复制变量值'), false) }) + +test('PATH 逐条视图支持识别失效与重复条目、单条删除、调序、一键去重与清理,且修改前必须二次确认', async () => { + snapshot = { + success: true, + sessionId, + platform: 'win32', + notice: '重新登录后生效', + sources: [{ id: 'user', label: '当前用户注册表环境' }], + variables: [{ key: 'Path', value: 'C:\\SDK\\node\\;C:\\Missing\\bin;c:\\sdk\\node;C:\\SDK\\go\\bin', scope: 'user' }], + paths: [ + { scope: 'user', index: 0, value: 'C:\\SDK\\node\\', reason: '目录存在', status: 'directory' }, + { scope: 'user', index: 1, value: 'C:\\Missing\\bin', reason: '确认目录不存在', status: 'missing' }, + { scope: 'user', index: 2, value: 'c:\\sdk\\node', reason: '目录存在', status: 'directory' }, + { scope: 'user', index: 3, value: 'C:\\SDK\\go\\bin', reason: '目录存在', status: 'directory' }, + { scope: 'process', index: 0, value: 'C:\\Windows\\System32', reason: '目录存在', status: 'directory' } + ], + backups: [] + } + const v = await open() + await v.dropdown('path') + + // 1. 失效与重复标记正确 + const missingItem = v.item('user:path:1') + const dupItem = v.item('user:path:2') + assert.equal(missingItem.props.accessories[0].tag.value, '失效目录') + assert.equal(dupItem.props.accessories[0].tag, '重复条目') + + // 只读进程 PATH 不提供删除/调序动作 + assert.equal(v.actions(v.item('process:path:0')).some(a => a.props.title === '删除此 PATH 条目'), false) + + // 2. 取消二次确认时不写入 + host.setConfirm(false) + await v.run(missingItem, '删除此 PATH 条目') + assert.equal(host.confirms.length, 1) + assert.match(host.confirms[0].message, /C:\\Missing\\bin/) + assert.equal(calls('apply').length, 0) + + // 3. 确认一键清理失效并去重 + host.setConfirm(true) + await globalAction(v, 'clean-dedup-path') + assert.equal(calls('apply').length, 1) + assert.equal(calls('prepare').at(-1)[1].change.value, 'C:\\SDK\\node\\;C:\\SDK\\go\\bin') + assert.match(host.confirms.at(-1).message, /C:\\Missing\\bin/) + assert.match(host.confirms.at(-1).message, /c:\\sdk\\node/) +}) + +test('PATH 逐条视图支持显式选目录追加与防重复校验,修改前二次确认', async () => { + snapshot = { + success: true, + sessionId, + platform: 'win32', + notice: '重新登录后生效', + sources: [{ id: 'user', label: '当前用户注册表环境' }], + variables: [{ key: 'Path', value: 'C:\\SDK\\node', scope: 'user' }], + paths: [{ scope: 'user', index: 0, value: 'C:\\SDK\\node', reason: '目录存在', status: 'directory' }], + backups: [] + } + let pickedFolder = 'C:\\SDK\\rust\\bin' + const v = await open(() => EnvManagerCommand({ pickDirectoryFn: async () => pickedFolder })) + await v.dropdown('path') + assert.equal(v.tree().props.filterBar.actions[0].id, 'add-path-dir') + + await globalAction(v, 'add-path-dir') + assert.equal(calls('apply').length, 1) + assert.equal(calls('prepare').at(-1)[1].change.value, 'C:\\SDK\\node;C:\\SDK\\rust\\bin') + assert.match(host.confirms.at(-1).message, /C:\\SDK\\rust\\bin/) + + // 重复选择同一目录应被拒绝,不发 prepare + pickedFolder = 'c:/sdk/node/' + const beforePrepare = calls('prepare').length + await globalAction(v, 'add-path-dir') + assert.equal(calls('prepare').length, beforePrepare) + assert.equal(host.lastToast().style, Toast.Style.Failure) +}) diff --git a/extensions/folder-sync/plugin.json b/extensions/folder-sync/plugin.json index 3f8368b0..1bb1efda 100644 --- a/extensions/folder-sync/plugin.json +++ b/extensions/folder-sync/plugin.json @@ -1,7 +1,7 @@ { "id": "folder-sync", "name": "目录同步", - "version": "1.0.11", + "version": "1.0.12", "description": "比对普通文件内容后增量或双向同步,覆盖前保留校验备份;macOS 另支持镜像模式,把目标独有文件移入废纸篓(单文件最大 2 GiB)", "author": "ZTools Team", "entry": "dist/index.js", diff --git a/extensions/folder-sync/src/i18n.ts b/extensions/folder-sync/src/i18n.ts index 61bdf5dc..80f8e653 100644 --- a/extensions/folder-sync/src/i18n.ts +++ b/extensions/folder-sync/src/i18n.ts @@ -38,7 +38,23 @@ export const t = createTranslator( filterConflict: "冲突", btnStop: "停止", btnPickDirs: "选择目录", + btnPickSource: "选择源目录", + btnPickTarget: "选择目标目录", + btnSwapDirs: "互换方向", btnRecompare: "重新比对", + actionPickSource: "选择源目录…", + actionPickTarget: "选择目标目录…", + actionSwapDirs: "互换源与目标目录", + actionResetFilter: "重置为全部差异", + badgeSrcToDst: "源 → 目标", + badgeDstToSrc: "目标 → 源", + badgeDeleteDst: "移入回收站", + badgeConflict: "需人工处理", + reasonAdded: "目标目录缺少此文件,将从源目录复制", + reasonReverseAdd: "源目录缺少此文件,将从目标目录复制", + reasonModified: "两侧内容不同,覆盖前将先保留备份", + reasonOrphan: "源目录已不存在此文件,备份后移入回收站", + reasonConflict: "两侧修改时间接近且内容不同,需人工确认方向", wbTitle: "同步配置", wbSubtitle: "覆盖前保留备份;链接或读取失败会停止扫描", fieldModeLabel: "模式", @@ -102,7 +118,23 @@ export const t = createTranslator( filterConflict: "Conflict", btnStop: "Stop", btnPickDirs: "Select Folders", + btnPickSource: "Source Folder", + btnPickTarget: "Target Folder", + btnSwapDirs: "Swap", btnRecompare: "Re-compare", + actionPickSource: "Select Source Folder...", + actionPickTarget: "Select Target Folder...", + actionSwapDirs: "Swap Source & Target", + actionResetFilter: "Reset Filter to All", + badgeSrcToDst: "Source -> Target", + badgeDstToSrc: "Target -> Source", + badgeDeleteDst: "Move to Trash", + badgeConflict: "Manual Review", + reasonAdded: "Missing on target; will copy from source", + reasonReverseAdd: "Missing on source; will copy from target", + reasonModified: "Content differs; original will be backed up before overwriting", + reasonOrphan: "Missing on source; will back up and move to Trash", + reasonConflict: "Modified closely on both sides; review manually before syncing", wbTitle: "Sync Settings", wbSubtitle: "Backs up before overwriting; stops on symlinks or read errors", fieldModeLabel: "Mode", diff --git a/extensions/folder-sync/src/index.tsx b/extensions/folder-sync/src/index.tsx index 01c814b4..33674a4a 100644 --- a/extensions/folder-sync/src/index.tsx +++ b/extensions/folder-sync/src/index.tsx @@ -7,6 +7,21 @@ import type { DiffFilterType, FolderSyncDiffItem, SyncMode } from './types.js' // 镜像模式依赖宿主的安全回收(目前只有 macOS 实现,移入废纸篓),其他平台不提供该选项 const supportsMirror = () => typeof navigator !== 'undefined' && /Mac/i.test(navigator.platform || navigator.userAgent || '') +function localizedBadge(item: FolderSyncDiffItem): string { + if (item.direction === 'delete-dst') return t('badgeDeleteDst') + if (item.direction === 'conflict') return t('badgeConflict') + if (item.direction === 'dst-to-src') return t('badgeDstToSrc') + return t('badgeSrcToDst') +} + +function localizedReason(item: FolderSyncDiffItem): string { + if (item.direction === 'conflict') return t('reasonConflict') + if (item.direction === 'delete-dst') return t('reasonOrphan') + if (item.diffType === 'modified') return t('reasonModified') + if (item.diffType === 'reverse-add') return t('reasonReverseAdd') + return t('reasonAdded') +} + /** folder-sync-compare 选好两个目录后直接比对;工作台命令选完目录先调整模式再比对 */ export function FolderSyncCommand({ featureCode = 'folder-sync-workbench' }: { featureCode?: string } = {}) { useLocale() @@ -90,13 +105,35 @@ export function FolderSyncCommand({ featureCode = 'folder-sync-workbench' }: { f setChecked(new Set(result.diffs.filter(item => item.direction !== 'delete-dst' && item.direction !== 'conflict').map(item => item.relPath))) setStatus(result.diffs.length ? t('statusCompareDone', { count: result.diffs.length, trashHint: result.diffs.some(item => item.direction === 'delete-dst') ? t('statusCompareTrashHint') : '' }) : t('statusCompareEqual')) } + const pickSource = () => run(async signal => { + const source = await chooseFolder(t('dialogSelectSource')); if (!source || !mounted.current) return + sourceRef.current = source + setSourceDir(source); invalidate() + if (targetRef.current) { signal.throwIfAborted(); await compareDirs(source, targetRef.current, signal) } + }) + const pickTarget = () => run(async signal => { + const target = await chooseFolder(t('dialogSelectTarget')); if (!target || !mounted.current) return + targetRef.current = target + setTargetDir(target); invalidate() + if (sourceRef.current) { signal.throwIfAborted(); await compareDirs(sourceRef.current, target, signal) } + }) + const swapDirs = () => run(async signal => { + const prevSource = sourceRef.current + const prevTarget = targetRef.current + if (!prevSource && !prevTarget) return + sourceRef.current = prevTarget + targetRef.current = prevSource + setSourceDir(prevTarget); setTargetDir(prevSource); invalidate() + if (prevTarget && prevSource) { signal.throwIfAborted(); await compareDirs(prevTarget, prevSource, signal) } + }) const pick = () => run(async signal => { const source = await chooseFolder(t('dialogSelectSource')); if (!source) return const target = await chooseFolder(t('dialogSelectTarget')); if (!target || !mounted.current) return + sourceRef.current = source; targetRef.current = target setSourceDir(source); setTargetDir(target); invalidate() - if (compareOnly) { signal.throwIfAborted(); await compareDirs(source, target, signal) } + signal.throwIfAborted(); await compareDirs(source, target, signal) }) - const compare = () => run(signal => compareDirs(sourceDir, targetDir, signal)) + const compare = () => run(signal => compareDirs(sourceRef.current, targetRef.current, signal)) const execute = () => run(async signal => { if (!planId || !checked.size) throw new Error(t('errCompareAndCheckFirst')) const selectedNow = diffItems.filter(item => checked.has(item.relPath)) @@ -128,8 +165,15 @@ export function FolderSyncCommand({ featureCode = 'folder-sync-workbench' }: { f deletedPart: result.deletedCount ? t('syncDeletedPart', { count: result.deletedCount }) : '', remaining: result.remainingCount }) - setStatus(`${summary}${result.error ? `; ${result.error}` : t('syncBackupHint')}`) await showToast({ style: result.ok ? Toast.Style.Success : Toast.Style.Failure, title: summary, message: result.error }) + // 同步完成后自动重新比对,彻底消除已失效 planId 导致的锁态旧清单与 Enter 报错死循环 + if (result.ok && sourceRef.current && targetRef.current && !signal.aborted) { + await compareDirs(sourceRef.current, targetRef.current, signal) + if (mounted.current) setStatus(`${summary}${t('syncBackupHint')}`) + } else { + setDiffItems([]) + setStatus(`${summary}${result.error ? `; ${result.error}` : t('syncBackupHint')}`) + } }) const mirror = supportsMirror() const visible = useMemo(() => filterSyncDiffItems(diffItems, diffFilter, searchText), [diffItems, diffFilter, searchText]) @@ -145,7 +189,13 @@ export function FolderSyncCommand({ featureCode = 'folder-sync-workbench' }: { f const ready = Boolean(sourceDir && targetDir) // 没有可选的清单行时(未选目录、未比对或筛选为空),底栏 Enter 落在这里 const emptyActions = + {diffItems.length > 0 && visible.length === 0 ? ( + { setDiffFilter('all'); setSearchText('') }} /> + ) : null} {ready && !planId ? : null} + + + {ready ? : null} return } actions={emptyActions} filterBar={{ summaryText: status || t('statusInit'), actions: busy ? [{ id: 'cancel', title: t('btnStop'), onAction: () => controller.current?.abort() }] : [ - { id: 'pick', title: t('btnPickDirs'), onAction: pick }, { id: 'compare', title: t('btnRecompare'), onAction: compare }] }} + { id: 'pick-source', title: t('btnPickSource'), onAction: pickSource }, + { id: 'pick-target', title: t('btnPickTarget'), onAction: pickTarget }, + ...(ready ? [{ id: 'swap', title: t('btnSwapDirs'), onAction: swapDirs }, { id: 'compare', title: t('btnRecompare'), onAction: compare }] : []) + ] }} workbenchPanel={{ title: t('wbTitle'), subtitle: t('wbSubtitle'), fields: [ { id: 'mode', label: t('fieldModeLabel'), type: 'select', value: syncMode, options: [{ label: t('modeIncremental'), value: 'incremental' }, { label: t('modeTwoWay'), value: 'two-way' }, ...(mirror ? [{ label: t('modeMirror'), value: 'mirror' }] : [])], onChange: value => { if (!busy) { setSyncMode(value as SyncMode); invalidate() } } }, { id: 'ignore', label: t('fieldIgnoreLabel'), type: 'toggle', value: ignoreDevJunk, onChange: value => { if (!busy) { setIgnoreDevJunk(Boolean(value)); invalidate() } } }, @@ -167,11 +220,12 @@ export function FolderSyncCommand({ featureCode = 'folder-sync-workbench' }: { f subList={{ title: t('subListTitle'), subtitle: t('subListSubtitle'), emptyText: planId ? t('subListEmptyPlan') : t('subListEmptyIdle'), checkable: Boolean(planId && actionable.length), checked: all ? true : actionable.some(item => checked.has(item.relPath)) ? 'indeterminate' : false, onCheckChange: () => toggle(actionable.map(item => item.relPath)), items: visible.map(item => toggle([item.relPath])} - accessories={[{ tag: item.actionBadge }, { text: formatSyncBytes(item.sizeBytes) }]} actions={ + accessories={[{ tag: localizedBadge(item) }, { text: formatSyncBytes(item.sizeBytes) }]} actions={ + {recovery.map((file, index) => run(async () => { await revealRecovery(file) })} />)} } />) }} /> } diff --git a/extensions/folder-sync/tests/folder-sync.real-chain.test.mjs b/extensions/folder-sync/tests/folder-sync.real-chain.test.mjs new file mode 100644 index 00000000..5776eed0 --- /dev/null +++ b/extensions/folder-sync/tests/folder-sync.real-chain.test.mjs @@ -0,0 +1,67 @@ +import assert from 'node:assert/strict' +import fs from 'node:fs' +import path from 'node:path' +import test from 'node:test' +import { createRealHost, REAL_HOST_SKIP_REASON } from '../../shared/real-host-harness.mjs' + +test('folder-sync real-host chain: pick source/target, compare real trees, execute sync, and re-compare yields 0 diffs', { skip: REAL_HOST_SKIP_REASON }, async () => { + const host = await createRealHost({ pluginId: 'folder-sync' }) + try { + const srcDir = path.join(host.tempRoot, 'sync-src') + const dstDir = path.join(host.tempRoot, 'sync-dst') + fs.mkdirSync(srcDir, { recursive: true }) + fs.mkdirSync(dstDir, { recursive: true }) + + host.writeTempFile('sync-src/hello.txt', 'hello-sync-world-v1') + host.writeTempFile('sync-src/sub/nested.txt', 'nested-file-content') + + // 1. 必须先通过真实 window_show_select_folder_dialog 对源/目标目录签发读写权限 + host.queueSelectFolderDialog(srcDir) + host.queueSelectFolderDialog(dstDir) + const sPick = await globalThis.__ztoolsElectron.transport.methods.window_show_select_folder_dialog({ + messageId: 'fs-1', + params: { title: '选择源文件夹' } + }) + const tPick = await globalThis.__ztoolsElectron.transport.methods.window_show_select_folder_dialog({ + messageId: 'fs-2', + params: { title: '选择目标文件夹' } + }) + assert.equal(sPick.success, true) + assert.equal(tPick.success, true) + + // 2. 真实 FolderSyncService + PathAccessBroker 执行比对 + const cmpRes = await globalThis.__ztoolsElectron.transport.methods.folder_sync({ + messageId: 'fs-3', + params: { action: 'compare', sourceDir: srcDir, targetDir: dstDir, syncMode: 'incremental', ignoreDevJunk: true, operationId: 'op-1' } + }) + assert.equal(cmpRes.success, true, `compare failed: ${JSON.stringify(cmpRes.error)}`) + assert.equal(cmpRes.data.ok, true) + assert.equal(cmpRes.data.diffs.length, 2, `expected 2 diffs, got ${JSON.stringify(cmpRes.data.diffs)}`) + + // 3. 真实执行同步并校验目标落盘内容 + const relPaths = cmpRes.data.diffs.map((d) => d.relPath) + const execRes = await globalThis.__ztoolsElectron.transport.methods.folder_sync({ + messageId: 'fs-4', + params: { action: 'execute', planId: cmpRes.data.planId, selectedRelPaths: relPaths, operationId: 'op-2' } + }) + assert.equal(execRes.success, true, `execute failed: ${JSON.stringify(execRes.error)}`) + assert.equal(execRes.data.ok, true) + assert.equal(execRes.data.syncedCount, 2) + assert.equal(fs.readFileSync(path.join(dstDir, 'hello.txt'), 'utf8'), 'hello-sync-world-v1') + assert.equal(fs.readFileSync(path.join(dstDir, 'sub/nested.txt'), 'utf8'), 'nested-file-content') + + // 4. 同步后立即重新比对:必须返回 0 差异(对应 UI 自动重比对消除锁态旧清单) + const cmpAfter = await globalThis.__ztoolsElectron.transport.methods.folder_sync({ + messageId: 'fs-5', + params: { action: 'compare', sourceDir: srcDir, targetDir: dstDir, syncMode: 'incremental', ignoreDevJunk: true, operationId: 'op-3' } + }) + assert.equal(cmpAfter.success, true) + assert.equal(cmpAfter.data.diffs.length, 0) + + // 5. 校验编译产物可正常加载 + const mod = await import(`../dist/index.js?t=${Date.now()}`) + assert.ok(typeof mod.default === 'function') + } finally { + await host.dispose() + } +}) diff --git a/extensions/folder-sync/tests/index.test.mjs b/extensions/folder-sync/tests/index.test.mjs deleted file mode 100644 index dd0465b9..00000000 --- a/extensions/folder-sync/tests/index.test.mjs +++ /dev/null @@ -1,189 +0,0 @@ -import test from 'node:test' -import assert from 'node:assert/strict' -import { createHost, mount, tick } from '../../shared/test-harness.mjs' -import FolderSync from '../dist/index.js' -import { chooseFolder, compareFolderTrees, executeFolderSync, revealRecovery } from '../dist/sync-service.js' -const host = createHost(), views = [] -const item = (relPath, direction, diffType) => ({ relPath, direction, diffType, actionBadge: direction, reasonText: '真实清单说明', sizeBytes: 3, sourceFullPath: '/fixture/source/' + relPath, targetFullPath: '/fixture/target/' + relPath }) -const diffs = [item('new.txt', 'src-to-dst', 'added'), item('old.txt', 'delete-dst', 'orphan'), item('conflict.txt', 'conflict', 'conflict')] -const plan = { success: true, ok: true, planId: '12345678-1234-1234-1234-123456789abc', diffs } -const done = { success: true, ok: true, syncedCount: 1, deletedCount: 0, transferredBytes: 3, remainingCount: 0, failures: [], recoveryPaths: ['/fixture/target/.ztools-sync-backups/run'] } -const deferred = () => { let resolve; return { promise: new Promise(r => { resolve = r }), resolve: v => resolve(v) } } -async function open() { const view = await mount(FolderSync); views.push(view); await tick(); return view } -const top = (view, id) => view.tree().props.filterBar.actions.find(action => action.id === id) -const rows = view => view.tree().props.subList.items -async function compare(view) { await top(view, 'pick').onAction(); await tick(); await top(view, 'compare').onAction(); await tick() } -const primary = view => rows(view)[0].props.actions.children[0].props.onAction() -test.beforeEach(() => { - host.reset(); let picked = 0 - host.ipc.window_show_select_folder_dialog = async () => ({ canceled: false, folderPath: picked++ % 2 ? '/fixture/target' : '/fixture/source' }) - host.ipc.folder_sync = async p => p.action === 'compare' ? plan : done - host.ipc.folder_sync_cancel = async () => ({ success: true, cancelRequested: true }) - host.ipc.shell_show_item_in_folder = async () => ({ success: true }) -}) -test.afterEach(() => { views.splice(0).forEach(view => view.unmount()) }) -test('初始不假称比对完成,目录选择走读写授权接口,取消不提交路径', async () => { - const view = await open(); assert.doesNotMatch(view.text(), /比对完成|完全一致/) - await compare(view) - assert.equal(host.ipcCalls.filter(([method]) => method === 'window_show_select_folder_dialog').length, 2) - assert.ok(!host.ipcCalls.some(([method]) => /dllplugin|dialog_show_open/.test(method))) - const call = host.ipcCalls.find(([method]) => method === 'folder_sync')[1] - assert.equal(call.sourceDir, '/fixture/source'); assert.equal(call.targetDir, '/fixture/target') - host.ipc.window_show_select_folder_dialog = async () => ({ canceled: true }); assert.equal(await chooseFolder('source'), undefined) -}) -test('执行只提交已展示计划和勾选文件,回收不默认选中且冲突不可选', async () => { - const view = await open(); await compare(view) - assert.equal(rows(view)[0].props.checked, true); assert.equal(rows(view)[1].props.checked, false) - assert.equal(rows(view)[2].props.checkable, false) - await primary(view); await tick() - const p = host.ipcCalls.find(([method, params]) => method === 'folder_sync' && params.action === 'execute')[1] - assert.equal(p.planId, plan.planId); assert.deepEqual(p.selectedRelPaths, ['new.txt']); assert.equal(p.sourceDir, undefined) - assert.match(view.text(), /已写入 1 项/) -}) -test('改模式失效旧计划,执行时修改设置不改在途清单', async () => { - const view = await open(); await compare(view) - view.tree().props.workbenchPanel.fields[0].onChange('two-way'); await tick() - assert.equal(rows(view).length, 0); assert.match(view.text(), /重新比对/) - await top(view, 'compare').onAction(); await tick() - const waiting = deferred(); host.ipc.folder_sync = () => waiting.promise - const work = primary(view); await tick(); view.tree().props.workbenchPanel.fields[0].onChange('mirror'); await tick() - assert.equal(view.tree().props.workbenchPanel.fields[0].value, 'two-way') - waiting.resolve(done); await work -}) -test('失败与部分完成明确显示实际错误及备份,不把任意错误解释成文件占用', async () => { - const view = await open(); await compare(view) - host.ipc.folder_sync = async () => ({ ...done, ok: false, remainingCount: 1, error: '备份校验失败', failures: [{ relPath: 'a', error: '备份校验失败' }] }) - await primary(view); await tick() - assert.match(view.text(), /备份校验失败/); assert.match(view.text(), /未完成 1 项/); assert.doesNotMatch(view.text(), /被占用跳过/) - await revealRecovery(done.recoveryPaths[0]) - assert.deepEqual(host.ipcCalls.find(([method]) => method === 'shell_show_item_in_folder')[1], { fullPath: done.recoveryPaths[0] }) -}) -test('卸载取消在途任务,迟到结果不弹成功提示', async () => { - const view = await open(); await compare(view) - const waiting = deferred(); host.ipc.folder_sync = () => waiting.promise - const work = primary(view); await tick(); view.unmount(); waiting.resolve(done); await work - assert.ok(host.ipcCalls.some(([method]) => method === 'folder_sync_cancel')) - assert.equal(host.toasts.length, 0) -}) -test('Windows 不显示废纸篓筛选与计数;macOS 用废纸篓的叫法', async () => { - const descriptor = Object.getOwnPropertyDescriptor(globalThis, 'navigator') - const render = async platform => { - Object.defineProperty(globalThis, 'navigator', { value: { platform, userAgent: '' }, configurable: true }) - views.splice(0).forEach(view => view.unmount()) - const view = await open(); await compare(view) - const filters = view.tree().props.searchBarAccessory.children.flat().filter(Boolean).map(child => child.props.value) - return { filters, card: view.tree().props.workbenchPanel.previewCard.subtitle, text: view.text() } - } - try { - const win = await render('Win32') - assert.ok(!win.filters.includes('orphan')); assert.doesNotMatch(win.card, /废纸篓|回收/) - const mac = await render('MacIntel') - assert.ok(mac.filters.includes('orphan')); assert.match(mac.card, /移入废纸篓 0/) - assert.match(mac.text, /移入废纸篓的文件需手动勾选/); assert.doesNotMatch(mac.text, /回收站/) - } finally { - if (descriptor) Object.defineProperty(globalThis, 'navigator', descriptor); else delete globalThis.navigator - } -}) -test('两个命令按清单注册:比对命令选好两个目录后直接比对,工作台只选目录不比对', async () => { - const { commands } = await import('../dist/index.js') - const fs = await import('node:fs') - const manifest = JSON.parse(fs.readFileSync(new URL('../plugin.json', import.meta.url))) - assert.deepEqual(Object.keys(commands).sort(), manifest.features.map(f => f.code).sort()) - const cmp = await mount(commands['folder-sync-compare']); views.push(cmp); await tick() - assert.equal(cmp.tree().props.navigationTitle, '目录比对') - assert.equal(cmp.actions(null)[0].props.title, '选择目录…') - await cmp.run(null, '选择目录…'); await tick() - const calls = host.ipcCalls.filter(([m, p]) => m === 'folder_sync' && p.action === 'compare') - assert.equal(calls.length, 1); assert.equal(calls[0][1].sourceDir, '/fixture/source'); assert.equal(calls[0][1].targetDir, '/fixture/target') - assert.equal(rows(cmp).length, 3); assert.match(cmp.text(), /比对完成,共 3 项/) - cmp.unmount(); views.pop() -}) -test('未选目录时主动作为“选择目录…”;选好未比对时主动作为“开始比对”;取消选择不比对', async () => { - const view = await open() - assert.deepEqual(view.actions(null).map(a => a.props.title), ['选择目录…']) - host.ipc.window_show_select_folder_dialog = async () => ({ canceled: true }) - await view.run(null, '选择目录…'); assert.deepEqual(view.actions(null).map(a => a.props.title), ['选择目录…']) - let picked = 0; host.ipc.window_show_select_folder_dialog = async () => ({ canceled: false, folderPath: picked++ % 2 ? '/fixture/target' : '/fixture/source' }) - await view.run(null, '选择目录…') - assert.equal(host.ipcCalls.filter(([m]) => m === 'folder_sync').length, 0) - assert.deepEqual(view.actions(null).map(a => a.props.title), ['开始比对', '重新选择目录…']) - host.ipc.folder_sync = async () => { throw new Error('源目录无法读取') } - await view.run(null, '开始比对'); assert.match(host.lastToast().title, /无法读取/); assert.equal(rows(view).length, 0) - host.ipc.folder_sync = async p => p.action === 'compare' ? plan : done - await view.run(null, '开始比对'); assert.equal(rows(view).length, 3) - assert.deepEqual(view.actions(null).map(a => a.props.title), ['重新选择目录…']) -}) -test('宿主结果不完整、异常和旧客户端均失败,不回退旧 DLL', async () => { - const options = { sourceDir: '/s', targetDir: '/t', syncMode: 'incremental', ignoreDevJunk: true } - host.ipc.folder_sync = async () => ({ success: true }) - await assert.rejects(compareFolderTrees(options, new AbortController().signal), /完整/) - await assert.rejects(executeFolderSync(plan.planId, ['x'], new AbortController().signal), /完整/) - const savedMethods = globalThis.__ztoolsElectron.transport.methods - globalThis.__ztoolsElectron.transport.methods = {} - try { - await assert.rejects(compareFolderTrees(options, new AbortController().signal), /升级/) - } finally { - globalThis.__ztoolsElectron.transport.methods = savedMethods - } -}) -test('镜像模式只在 macOS 显示,Windows 不提供宿主不支持的选项', async () => { - const descriptor = Object.getOwnPropertyDescriptor(globalThis, 'navigator') - const modes = async platform => { - Object.defineProperty(globalThis, 'navigator', { value: { platform, userAgent: '' }, configurable: true }) - const view = await open() - return view.tree().props.workbenchPanel.fields[0].options.map(option => option.value) - } - try { - assert.deepEqual(await modes('Win32'), ['incremental', 'two-way']) - assert.deepEqual(await modes('MacIntel'), ['incremental', 'two-way', 'mirror']) - } finally { - if (descriptor) Object.defineProperty(globalThis, 'navigator', descriptor); else delete globalThis.navigator - } -}) -test('Ctrl+V 粘贴文件夹:支持单目录依次填充源与目标、按 targetFieldId 定向填充及双目录同时粘贴', async () => { - const view = await open() - const fieldVal = id => view.tree().props.workbenchPanel.fields.find(f => f.id === id).value - await view.pasteFiles(['/paste/src-one']) - assert.equal(fieldVal('source'), '/paste/src-one') - assert.equal(fieldVal('target'), '未选择') - - await view.pasteFiles(['/paste/dst-one']) - assert.equal(fieldVal('source'), '/paste/src-one') - assert.equal(fieldVal('target'), '/paste/dst-one') - - await view.pasteFiles(['/paste/dst-override'], { targetFieldId: 'target' }) - assert.equal(fieldVal('target'), '/paste/dst-override') - - await view.pasteFiles(['/paste/src-override'], { targetFieldId: 'source' }) - assert.equal(fieldVal('source'), '/paste/src-override') - - await view.pasteFiles(['/paste/batch-src', '/paste/batch-dst']) - assert.equal(fieldVal('source'), '/paste/batch-src') - assert.equal(fieldVal('target'), '/paste/batch-dst') -}) -test('执行同步前强制二次确认(含同步方向与新增/覆盖/删除计数),用户取消绝不执行且保留计划', async () => { - const view = await open(); await compare(view) - // 额外勾选删除项 old.txt,验证新增/覆盖/删除计数准确 - rows(view)[1].props.onCheckChange(true); await tick() - host.setConfirm(false) - await primary(view); await tick() - assert.equal(host.confirms.length, 1) - assert.match(host.confirms[0].title, /确认执行目录同步(共 2 项)/) - assert.match(host.confirms[0].message, /\/fixture\/source → \/fixture\/target/) - assert.match(host.confirms[0].message, /新增 1 项 · 覆盖 0 项 · 删除(移入废纸篓) 1 项/) - assert.equal(host.ipcCalls.filter(([m, p]) => m === 'folder_sync' && p.action === 'execute').length, 0, '取消确认后绝不能调用 execute') - assert.equal(rows(view).length, 3, '取消确认后保留当前比对清单') - - // 英文 i18n 下确认弹窗完整无中文与占位符残留 - host.setLocale('en-US') - try { - await tick() - await primary(view); await tick() - const enConfirm = host.confirms.at(-1) - assert.match(enConfirm.title, /Confirm Folder Sync \(2 item\(s\)\)\?/) - assert.match(enConfirm.message, /Add 1 · Overwrite 0 · Delete \(Trash\) 1/) - assert.ok(!/[\u4e00-\u9fa5]|\{[a-z]+\}/i.test(`${enConfirm.title} ${enConfirm.message}`)) - } finally { - host.setLocale('zh-CN') - } -}) diff --git a/extensions/font-manager/plugin.json b/extensions/font-manager/plugin.json index 67812060..bebd5c8f 100644 --- a/extensions/font-manager/plugin.json +++ b/extensions/font-manager/plugin.json @@ -1,7 +1,7 @@ { "id": "font-manager", "name": "字体管理", - "version": "1.0.9", + "version": "1.0.10", "description": "检索本机已安装字体,输入文字查看真实字形,查看字体文件附带的许可与版权说明。", "author": "ZTools Team", "category": [ diff --git a/extensions/font-manager/src/font-client.ts b/extensions/font-manager/src/font-client.ts index 2d785cde..b00b74f4 100644 --- a/extensions/font-manager/src/font-client.ts +++ b/extensions/font-manager/src/font-client.ts @@ -2,7 +2,19 @@ import { t } from './i18n.js' import type { FontPreview, InstalledFont } from './types.js' import { resolveErrorMessage } from './error-i18n.js' let sequence = 0 -interface Reply { success?: boolean; data?: { success?: boolean; fonts?: InstalledFont[]; preview?: FontPreview; revealRequested?: boolean }; error?: { message?: string } } +interface Reply { + success?: boolean + data?: { + success?: boolean + fonts?: InstalledFont[] + preview?: FontPreview + revealRequested?: boolean + canceled?: boolean + filePaths?: string[] + path?: string + } + error?: { message?: string } +} interface Bridge { transport?: { methods?: Record Promise> } } export class FontClient { async request(params: Record, signal: AbortSignal) { @@ -32,4 +44,25 @@ export class FontClient { async reveal(id: string, signal: AbortSignal) { if ((await this.request({ action: 'reveal', id }, signal)).revealRequested !== true) throw new Error(t('revealUnconfirmed')) } + async pickLocalFontFiles(): Promise { + const methods = (globalThis as unknown as { __ztoolsElectron?: Bridge }).__ztoolsElectron?.transport?.methods + const openDialog = methods?.window_show_open_dialog + if (typeof openDialog !== 'function') throw new Error(t('hostNoDialog')) + const id = `font_open_${Date.now()}_${++sequence}` + const result = await openDialog({ + messageId: id, + params: { + title: t('openLocalDialogTitle'), + filters: t('openLocalDialogFilter'), + properties: ['openFile', 'multiSelections'] + }, + timeoutMs: 60000 + }) + if (result?.success !== true) throw new Error(resolveErrorMessage(result?.error, t('openLocalFailed'))) + const data = result.data + if (!data || data.canceled === true) return [] + if (Array.isArray(data.filePaths)) return data.filePaths.filter((p): p is string => typeof p === 'string' && p.trim().length > 0) + if (typeof data.path === 'string' && data.path.trim().length > 0) return [data.path.trim()] + return [] + } } diff --git a/extensions/font-manager/src/font-service.ts b/extensions/font-manager/src/font-service.ts index f6a46472..e43f767a 100644 --- a/extensions/font-manager/src/font-service.ts +++ b/extensions/font-manager/src/font-service.ts @@ -1,5 +1,19 @@ import { t } from './i18n.js' -import type { FontFilter, FontPreview, InstalledFont } from './types.js' +import type { FontFamilyGroup, FontFilter, FontPreview, InstalledFont, PreviewFontSize } from './types.js' + +export const PREVIEW_FONT_SIZES: readonly PreviewFontSize[] = ['small', 'medium', 'large'] + +export function previewSizeLabel(size: PreviewFontSize): string { + if (size === 'small') return t('sizeSmall') + if (size === 'large') return t('sizeLarge') + return t('sizeMedium') +} + +export function nextPreviewSize(current: PreviewFontSize): PreviewFontSize { + const index = PREVIEW_FONT_SIZES.indexOf(current) + return PREVIEW_FONT_SIZES[(index + 1) % PREVIEW_FONT_SIZES.length] +} + export function getDefaultPreview(): string { return t('defaultPreviewText') } @@ -38,6 +52,72 @@ export function filterFonts( } return [...pinned, ...others] } + +const REGULAR_STYLE_RE = /^(regular|normal|book|roman|standard|常规)$/i + +/** 按字体家族聚合多个字重/样式,减少列表冗余,同时保留家族内全部字重切换能力 */ +export function groupFontsByFamily( + fonts: InstalledFont[], + favorites?: ReadonlySet, + activeStyleByFamily?: Readonly> +): FontFamilyGroup[] { + const byFamily = new Map() + for (const font of fonts) { + const key = font.isLocalFile ? `local:${font.id}` : font.family + const existing = byFamily.get(key) + if (existing) existing.push(font) + else byFamily.set(key, [font]) + } + const groups: FontFamilyGroup[] = [] + for (const styles of byFamily.values()) { + const family = styles[0].family + const preferredId = activeStyleByFamily?.[family] + const primary = + (preferredId ? styles.find(s => s.id === preferredId) : undefined) ?? + styles.find(s => REGULAR_STYLE_RE.test(s.style.trim())) ?? + styles[0] + groups.push({ + id: primary.id, + family, + styles, + primary, + hasLicense: styles.some(s => s.hasLicense), + system: styles.every(s => s.system), + isLocalFile: styles.every(s => Boolean(s.isLocalFile)) + }) + } + if (!favorites || favorites.size === 0) return groups + const pinned: FontFamilyGroup[] = [] + const others: FontFamilyGroup[] = [] + for (const group of groups) { + if (group.styles.some(s => favorites.has(s.id))) pinned.push(group) + else others.push(group) + } + return [...pinned, ...others] +} + +const LOCAL_FONT_EXT_RE = /\.(ttf|otf|ttc|woff|woff2)$/i + +/** 将用户显式选入或拖入的本地字体文件路径构造为本地只读字体条目 */ +export function createLocalFontEntry(filePath: string): InstalledFont | null { + const normalized = filePath.trim() + if (!normalized || !LOCAL_FONT_EXT_RE.test(normalized)) return null + const segments = normalized.split(/[\\/]/) + const fileName = segments[segments.length - 1] || normalized + const dotIdx = fileName.lastIndexOf('.') + const family = dotIdx > 0 ? fileName.slice(0, dotIdx) : fileName + const ext = dotIdx > 0 ? fileName.slice(dotIdx + 1).toUpperCase() : 'FONT' + return { + id: `local:${normalized}`, + family, + style: ext, + filePath: normalized, + hasLicense: false, + system: false, + isLocalFile: true + } +} + export function cssFontFamily(family: string) { const escaped = family.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/[\n\r\f]/g, char => `\\${char.charCodeAt(0).toString(16)} `) return `font-family: "${escaped}", sans-serif;` @@ -48,12 +128,46 @@ export function licenseUrl(value: string) { export function textMarkdown(value: string) { return value.replace(/[\\`*_[\]!#|]/g, '\\$&') } /** macOS 在本机没有任何字体含该字形时用 LastResort 画占位方框;它不是可用的回退字体,要单独说明 */ const LAST_RESORT = 'LastResort' -export function previewMarkdown(preview: FontPreview) { +export function previewMarkdown( + preview: FontPreview, + meta?: { group?: FontFamilyGroup; previewSize?: PreviewFontSize } +) { const fallbacks = preview.fallbacks.filter(name => name !== LAST_RESORT) const notes = preview.coverageWarning ? [textMarkdown(preview.coverageWarning)] : [ ...(fallbacks.length ? [t('fallbackFontsNote', { fonts: fallbacks.map(textMarkdown).join(t('listSep')) })] : []), ...(preview.fallbacks.includes(LAST_RESORT) ? [t('lastResortNote')] : []) ] const note = notes.length ? notes.join('\n\n') : t('renderedBySelectedNote') - return `![${t('previewImageAlt')}](data:image/png;base64,${preview.png})\n\n${note}` + const sections: string[] = [`![${t('previewImageAlt')}](data:image/png;base64,${preview.png})`, note] + if (meta?.group || meta?.previewSize) { + const infoLines: string[] = [] + if (meta.previewSize) { + infoLines.push(`- **${t('previewSizeLabel')}**: ${previewSizeLabel(meta.previewSize)}`) + } + if (meta.group) { + infoLines.push(`- **${t('activeStyleLabel')}**: ${textMarkdown(meta.group.primary.style)}`) + if (meta.group.styles.length > 1) { + const styleNames = meta.group.styles.map(s => textMarkdown(s.style)).join(t('listSep')) + infoLines.push(`- **${t('familyStylesLabel', { count: meta.group.styles.length })}**: ${styleNames}`) + } + if (meta.group.primary.filePath) { + infoLines.push(`- **${t('fontPathLabel')}**: \`${meta.group.primary.filePath}\``) + } + } + if (infoLines.length > 0) sections.push(infoLines.join('\n')) + } + return sections.join('\n\n') +} + +export function localFontMarkdown(group: FontFamilyGroup, previewSize: PreviewFontSize): string { + return [ + `### ${textMarkdown(group.family)}`, + `**${t('localFontDetailTitle')}**`, + t('localFontDetailNote'), + [ + `- **${t('activeStyleLabel')}**: ${textMarkdown(group.primary.style)}`, + `- **${t('previewSizeLabel')}**: ${previewSizeLabel(previewSize)}`, + `- **${t('fontPathLabel')}**: \`${group.primary.filePath}\`` + ].join('\n') + ].join('\n\n') } diff --git a/extensions/font-manager/src/i18n.ts b/extensions/font-manager/src/i18n.ts index e0f1e3ac..2589dbc9 100644 --- a/extensions/font-manager/src/i18n.ts +++ b/extensions/font-manager/src/i18n.ts @@ -52,7 +52,43 @@ const rawT = createTranslator( toastUnfavorited: "已取消收藏 {family}", toastFavoriteFailed: "更新收藏状态失败", actionRevealFile: "定位字体文件", - actionViewLicense: "查看许可信息" + actionViewLicense: "查看许可信息", + stylesCount: "{style} · 共 {count} 个字重", + familyStylesLabel: "家族字重({count})", + activeStyleLabel: "当前字重", + previewSizeLabel: "预览字号", + fontPathLabel: "字体路径", + sizeSmall: "小号 (18px)", + sizeMedium: "中号 (28px)", + sizeLarge: "大号 (44px)", + formSizeTitle: "预览字号", + formPresetTitle: "快捷文案预设", + presetCustom: "自定义输入", + presetDefault: "中英数混合(默认)", + presetHeadline: "品牌标题测试", + presetCode: "等宽代码与符号", + presetHeadlineText: "品牌标题 2026\nBrand Headline 2026 · AaBbCc", + presetCodeText: "const fn = (x: number) => x !== 0 ? 1 : 0; // O0 l1I", + summaryLoadedFamilies: "{families} 个字体家族({total} 样式)· 字号 {size}", + btnOpenLocalFont: "打开本地字体", + actionOpenLocalFont: "打开本地字体文件", + actionCycleSize: "切换预览字号(当前:{size})", + toastSizeChanged: "预览字号已切换为 {size}", + switchStyleSubmenu: "切换家族字重", + toastStyleSwitched: "已切换至 {family} · {style}", + openLocalDialogTitle: "选择本地字体文件", + openLocalDialogFilter: "字体文件|ttf;otf;ttc;woff;woff2", + hostNoDialog: "当前客户端版本不支持文件选择对话框,请直接拖入字体文件", + openLocalFailed: "打开本地字体文件失败", + toastLocalFontLoaded: "已载入 {count} 个本地字体文件", + toastLocalFontMatched: "已定位至已安装字体 {family}", + toastLocalFontUnsupported: "仅支持 .ttf / .otf / .ttc / .woff / .woff2 字体文件", + localFontBadge: "本地字体", + localFontDetailTitle: "本地未安装字体文件", + localFontDetailNote: "该字体来自本地文件,尚未安装到系统字体库,宿主字体渲染服务仅支持渲染已安装的系统字体。您可以按回车使用系统字体查看器打开或安装。", + actionOpenSystemFont: "用系统程序打开 / 安装", + emptyNoMatchTitle: "未找到匹配的字体", + emptyNoMatchDesc: "可切换筛选条件、清空搜索词,或点击上方「打开本地字体」导入 .ttf/.otf 文件" }, "en-US": { upgradeClient: "Please upgrade ZTools to use Font Manager", @@ -104,7 +140,43 @@ const rawT = createTranslator( toastUnfavorited: "Removed {family} from favorites", toastFavoriteFailed: "Failed to update favorites", actionRevealFile: "Reveal Font File", - actionViewLicense: "View License Info" + actionViewLicense: "View License Info", + stylesCount: "{style} · {count} [[count:style|styles]]", + familyStylesLabel: "Family Styles ({count})", + activeStyleLabel: "Active Style", + previewSizeLabel: "Preview Size", + fontPathLabel: "File Path", + sizeSmall: "Small (18px)", + sizeMedium: "Medium (28px)", + sizeLarge: "Large (44px)", + formSizeTitle: "Preview Size", + formPresetTitle: "Sample Text Preset", + presetCustom: "Custom Input", + presetDefault: "Standard Sample (Default)", + presetHeadline: "Brand Headline", + presetCode: "Code & Symbols", + presetHeadlineText: "Brand Headline 2026\nTypography Preview · AaBbCc", + presetCodeText: "const fn = (x: number) => x !== 0 ? 1 : 0; // O0 l1I", + summaryLoadedFamilies: "{families} [[families:family|families]] ({total} [[total:style|styles]]) · Size {size}", + btnOpenLocalFont: "Open Local Font", + actionOpenLocalFont: "Open Local Font File", + actionCycleSize: "Cycle Preview Size (Current: {size})", + toastSizeChanged: "Preview size set to {size}", + switchStyleSubmenu: "Switch Family Style", + toastStyleSwitched: "Switched to {family} · {style}", + openLocalDialogTitle: "Select Local Font File", + openLocalDialogFilter: "Font Files|ttf;otf;ttc;woff;woff2", + hostNoDialog: "File dialog is unavailable in this client version; drag and drop a font file instead", + openLocalFailed: "Failed to open local font file", + toastLocalFontLoaded: "Loaded {count} local font [[count:file|files]]", + toastLocalFontMatched: "Selected installed font {family}", + toastLocalFontUnsupported: "Only .ttf, .otf, .ttc, .woff, and .woff2 font files are supported", + localFontBadge: "Local File", + localFontDetailTitle: "Local Uninstalled Font File", + localFontDetailNote: "This font is loaded from a local file and not installed in the system font library. The host glyph renderer only renders installed system fonts. Open it with the system font viewer to inspect or install.", + actionOpenSystemFont: "Open / Install with System Viewer", + emptyNoMatchTitle: "No Matching Fonts", + emptyNoMatchDesc: "Adjust your filter or search query, or click Open Local Font to import a .ttf/.otf file" } } ) diff --git a/extensions/font-manager/src/index.tsx b/extensions/font-manager/src/index.tsx index 565ddb5d..ebf58f28 100644 --- a/extensions/font-manager/src/index.tsx +++ b/extensions/font-manager/src/index.tsx @@ -2,8 +2,21 @@ import React, { Action, ActionPanel, Detail, Form, Icon, List, LocalStorage, Toa import { t } from './i18n.js' import { resolveErrorMessage } from './error-i18n.js' import { FontClient } from './font-client.js' -import { getDefaultPreview, cssFontFamily, filterFonts, licenseUrl, previewMarkdown, textMarkdown, validatePreviewText } from './font-service.js' -import type { FontFilter, FontPreview, InstalledFont } from './types.js' +import { + createLocalFontEntry, + cssFontFamily, + filterFonts, + getDefaultPreview, + groupFontsByFamily, + licenseUrl, + localFontMarkdown, + nextPreviewSize, + previewMarkdown, + previewSizeLabel, + textMarkdown, + validatePreviewText +} from './font-service.js' +import type { FontFamilyGroup, FontFilter, FontPreview, InstalledFont, PreviewFontSize } from './types.js' const client = new FontClient() const FAVORITES_STORAGE_KEY = 'font-manager-favorites-v1' const errorText = (error: unknown) => resolveErrorMessage(error, t('fontReadFailed')) @@ -18,15 +31,47 @@ function parseFavorites(raw: unknown): string[] { } } -export function PreviewTextForm({ initial, save }: { initial: string; save: (text: string) => void }) { +export function PreviewTextForm({ + initial, + initialSize = 'medium', + save +}: { + initial: string + initialSize?: PreviewFontSize + save: (text: string, size?: PreviewFontSize) => void +}) { useLocale() - const [text, setText] = useState(initial), { pop } = useNavigation() + const [text, setText] = useState(initial) + const [size, setSize] = useState(initialSize) + const [preset, setPreset] = useState('custom') + const { pop } = useNavigation() + const handlePresetChange = (value: string) => { + setPreset(value) + if (value === 'default') setText(getDefaultPreview()) + else if (value === 'headline') setText(t('presetHeadlineText')) + else if (value === 'code') setText(t('presetCodeText')) + } const submit = async () => { - try { save(validatePreviewText(text)); pop() } - catch (error) { await showToast(Toast.Style.Failure, errorText(error)) } + try { + save(validatePreviewText(text), size) + pop() + } catch (error) { + await showToast(Toast.Style.Failure, errorText(error)) + } } return
}> - + { setText(val); setPreset('custom') }} /> + + + + + + + setSize(val as PreviewFontSize)}> + + + + } @@ -42,17 +87,23 @@ function LicenseDetail({ preview }: { preview: FontPreview }) { } export default function FontManager({ initialFilter = 'all' }: { initialFilter?: FontFilter } = {}) { useLocale() - const [fonts, setFonts] = useState([]), [filter, setFilter] = useState(initialFilter) + const [fonts, setFonts] = useState([]), [localFonts, setLocalFonts] = useState([]) + const [filter, setFilter] = useState(initialFilter) const [favoriteIds, setFavoriteIds] = useState([]) - const [query, setQuery] = useState(''), [selection, setSelection] = useState(''), [text, setText] = useState(() => getDefaultPreview()) + const [activeStyles, setActiveStyles] = useState>({}) + const [query, setQuery] = useState(''), [selection, setSelection] = useState('') + const [text, setText] = useState(() => getDefaultPreview()), [previewSize, setPreviewSize] = useState('medium') const [loading, setLoading] = useState(true), [error, setError] = useState(''), [revision, setRevision] = useState(0) const [preview, setPreview] = useState(null), [previewError, setPreviewError] = useState('') const pending = useRef(null), mounted = useRef(true), otherJobs = useRef(new Set()) const { push } = useNavigation() const favoriteSet = useMemo(() => new Set(favoriteIds), [favoriteIds]) - const filtered = useMemo(() => filterFonts(fonts, filter, query, favoriteSet), [fonts, filter, query, favoriteSet]) - const selected = filtered.find(font => font.id === selection) ?? filtered[0] - const selectedId = selected?.id ?? '' + const allFonts = useMemo(() => [...localFonts, ...fonts], [localFonts, fonts]) + const filtered = useMemo(() => filterFonts(allFonts, filter, query, favoriteSet), [allFonts, filter, query, favoriteSet]) + const groups = useMemo(() => groupFontsByFamily(filtered, favoriteSet, activeStyles), [filtered, favoriteSet, activeStyles]) + const selectedGroup = groups.find(group => group.id === selection || group.styles.some(s => s.id === selection)) ?? groups[0] + const selectedId = selectedGroup?.id ?? '' + const selectedIsLocal = Boolean(selectedGroup?.isLocalFile) const load = async () => { if (pending.current) return const controller = new AbortController(); pending.current = controller @@ -73,7 +124,7 @@ export default function FontManager({ initialFilter = 'all' }: { initialFilter?: }, []) useEffect(() => { setPreview(null); setPreviewError('') - if (!selectedId) return + if (!selectedId || selectedIsLocal) return const controller = new AbortController() const timer = setTimeout(() => { void client.preview(selectedId, text, controller.signal).then(value => { @@ -81,17 +132,20 @@ export default function FontManager({ initialFilter = 'all' }: { initialFilter?: }).catch(failure => { if (!controller.signal.aborted) setPreviewError(errorText(failure)) }) }, 150) return () => { clearTimeout(timer); controller.abort() } - }, [selectedId, text, revision]) - const toggleFavorite = async (font: InstalledFont) => { - const isFavorited = favoriteSet.has(font.id) - const next = isFavorited ? favoriteIds.filter(id => id !== font.id) : [font.id, ...favoriteIds] + }, [selectedId, selectedIsLocal, text, revision]) + const toggleFavorite = async (group: FontFamilyGroup) => { + const isFavorited = group.styles.some(s => favoriteSet.has(s.id)) + const groupIds = new Set(group.styles.map(s => s.id)) + const next = isFavorited + ? favoriteIds.filter(id => !groupIds.has(id)) + : [group.primary.id, ...favoriteIds.filter(id => !groupIds.has(id))] try { await LocalStorage.setItem(FAVORITES_STORAGE_KEY, JSON.stringify(next)) if (mounted.current) { setFavoriteIds(next) await showToast( Toast.Style.Success, - isFavorited ? t('toastUnfavorited', { family: font.family }) : t('toastFavorited', { family: font.family }) + isFavorited ? t('toastUnfavorited', { family: group.family }) : t('toastFavorited', { family: group.family }) ) } } catch (failure) { @@ -100,6 +154,69 @@ export default function FontManager({ initialFilter = 'all' }: { initialFilter?: } } } + const importLocalFontPaths = async (paths: string[]) => { + if (paths.length === 0) return + const normalizedPaths = paths.map(p => p.trim()).filter(Boolean) + const installedByPath = new Map(fonts.map(f => [f.filePath.toLowerCase(), f])) + const matchedInstalled = normalizedPaths.map(p => installedByPath.get(p.toLowerCase())).find(Boolean) + const added: InstalledFont[] = [] + for (const filePath of normalizedPaths) { + if (installedByPath.has(filePath.toLowerCase())) continue + const entry = createLocalFontEntry(filePath) + if (entry) added.push(entry) + } + if (added.length > 0) { + setLocalFonts(prev => { + const existing = new Set(prev.map(item => item.id)) + const fresh = added.filter(item => !existing.has(item.id)) + return [...fresh, ...prev] + }) + setFilter('all') + setQuery('') + setSelection(added[0].id) + await showToast(Toast.Style.Success, t('toastLocalFontLoaded', { count: added.length })) + return + } + if (matchedInstalled) { + setFilter('all') + setQuery('') + setActiveStyles(prev => ({ ...prev, [matchedInstalled.family]: matchedInstalled.id })) + setSelection(matchedInstalled.id) + await showToast(Toast.Style.Success, t('toastLocalFontMatched', { family: matchedInstalled.family })) + return + } + await showToast(Toast.Style.Failure, t('toastLocalFontUnsupported')) + } + const openLocalFont = async () => { + try { + const paths = await client.pickLocalFontFiles() + if (mounted.current && paths.length > 0) await importLocalFontPaths(paths) + } catch (failure) { + if (mounted.current) await showToast(Toast.Style.Failure, errorText(failure)) + } + } + const openPreviewSettings = () => { + push( + { + setText(nextText) + if (nextSize) setPreviewSize(nextSize) + }} + /> + ) + } + const cycleSize = async () => { + const next = nextPreviewSize(previewSize) + setPreviewSize(next) + await showToast(Toast.Style.Success, t('toastSizeChanged', { size: previewSizeLabel(next) })) + } + const switchFamilyStyle = async (group: FontFamilyGroup, styleFont: InstalledFont) => { + setActiveStyles(prev => ({ ...prev, [group.family]: styleFont.id })) + setSelection(styleFont.id) + await showToast(Toast.Style.Success, t('toastStyleSwitched', { family: group.family, style: styleFont.style })) + } const reveal = async (id: string) => { const controller = new AbortController(); otherJobs.current.add(controller) try { await client.reveal(id, controller.signal) } @@ -107,9 +224,15 @@ export default function FontManager({ initialFilter = 'all' }: { initialFilter?: finally { otherJobs.current.delete(controller) } } const currentPreview = preview?.id === selectedId ? preview : null + const summaryText = error || (loading + ? t('summaryLoading') + : t('summaryLoadedFamilies', { families: groups.length, total: filtered.length, size: previewSizeLabel(previewSize) })) + return setSelection(id ?? '')} + fileInput={{ extensions: ['.ttf', '.otf', '.ttc', '.woff', '.woff2'] }} + onFileInput={({ files }) => { void importLocalFontPaths(files) }} searchBarAccessory={ setFilter(value as FontFilter)} tooltip={t('filterTooltip')}> @@ -117,31 +240,67 @@ export default function FontManager({ initialFilter = 'all' }: { initialFilter?: } - filterBar={{ summaryText: error || (loading ? t('summaryLoading') : t('summaryLoaded', { total: fonts.length, shown: filtered.length })), actions: [ - { id: 'preview-text', title: t('btnPreviewText'), onAction: () => push() }, - { id: 'refresh', title: t('btnRescan'), onAction: load } - ] }}> - {filtered.map(font => { - const isFavorited = favoriteSet.has(font.id) - const detailMd = font.id === selectedId - ? currentPreview - ? `${previewMarkdown(currentPreview)}\n\n---\n\n${t('licenseDisclaimer')}` - : textMarkdown(previewError || t('renderingPreview')) + filterBar={{ + summaryText, + actions: [ + { id: 'open-local-font', title: t('btnOpenLocalFont'), icon: Icon.Folder, onAction: () => { void openLocalFont() } }, + { id: 'refresh', title: t('btnRescan'), onAction: load } + ] + }} + actions={ + { void openLocalFont() }} /> + + { void cycleSize() }} /> + + }> + {groups.map(group => { + const font = group.primary + const isFavorited = group.styles.some(s => favoriteSet.has(s.id)) + const subtitle = group.styles.length > 1 + ? t('stylesCount', { style: font.style, count: group.styles.length }) + : font.style + const detailMd = group.id === selectedId + ? group.isLocalFile + ? localFontMarkdown(group, previewSize) + : currentPreview + ? `${previewMarkdown(currentPreview, { group, previewSize })}\n\n---\n\n${t('licenseDisclaimer')}` + : textMarkdown(previewError || t('renderingPreview')) : '' - return } actions={ - - - toggleFavorite(font)} /> - {font.filePath && reveal(font.id)} />} - {font.id === selectedId && currentPreview && } />} + {group.isLocalFile && font.filePath && } + + + + { void cycleSize() }} /> + {group.styles.length > 1 && ( + + {group.styles.map(styleFont => ( + { void switchFamilyStyle(group, styleFont) }} + /> + ))} + + )} + toggleFavorite(group)} /> + { void openLocalFont() }} /> + {group.isLocalFile && font.filePath + ? + : font.filePath && reveal(font.id)} />} + {!group.isLocalFile && group.id === selectedId && currentPreview && } />} } /> })} + {!loading && groups.length === 0 && !error && ( + + )} } export const commands = { diff --git a/extensions/font-manager/src/types.ts b/extensions/font-manager/src/types.ts index a4204a2e..5d6a4ddc 100644 --- a/extensions/font-manager/src/types.ts +++ b/extensions/font-manager/src/types.ts @@ -1,3 +1,21 @@ export type FontFilter = 'all' | 'favorites' | 'with-license' | 'without-license' | 'system' -export interface InstalledFont { id: string; family: string; style: string; filePath: string; hasLicense: boolean; system: boolean } +export type PreviewFontSize = 'small' | 'medium' | 'large' +export interface InstalledFont { + id: string + family: string + style: string + filePath: string + hasLicense: boolean + system: boolean + isLocalFile?: boolean +} +export interface FontFamilyGroup { + id: string + family: string + styles: InstalledFont[] + primary: InstalledFont + hasLicense: boolean + system: boolean + isLocalFile: boolean +} export interface FontPreview { id: string; png: string; fallbacks: string[]; coverageWarning?: string; license: string; licenseUrl: string; copyright: string; manufacturer: string } diff --git a/extensions/font-manager/tests/index.test.mjs b/extensions/font-manager/tests/index.test.mjs index 98351e82..e8d96b18 100644 --- a/extensions/font-manager/tests/index.test.mjs +++ b/extensions/font-manager/tests/index.test.mjs @@ -110,3 +110,46 @@ test('收藏与取消收藏字体:LocalStorage 持久化、置顶展示与收 await tick() assert.deepEqual(v2.items().map(i => i.props.id), ['Winter', 'Example']) }) + +test('按字体家族聚合多字重,并支持切换家族字重与预览字号', async () => { + const familyFonts = [ + { id: 'SHS-Light', family: 'Source Han Sans CN', style: 'Light', filePath: '/tmp/shs-light.otf', hasLicense: true, system: false }, + { id: 'SHS-Regular', family: 'Source Han Sans CN', style: 'Regular', filePath: '/tmp/shs-reg.otf', hasLicense: true, system: false }, + { id: 'SHS-Bold', family: 'Source Han Sans CN', style: 'Bold', filePath: '/tmp/shs-bold.otf', hasLicense: true, system: false }, + { id: 'Mono-Reg', family: 'JetBrains Mono', style: 'Regular', filePath: '/tmp/jb.ttf', hasLicense: true, system: false } + ] + host.ipc.font_manager = async p => p.action === 'list' ? { success: true, fonts: familyFonts } : p.action === 'preview' ? { success: true, preview: preview(p.id) } : { success: true, revealRequested: true } + const v = await open() + // 4 个样式聚合成 2 个字体家族,优先选中 Regular + assert.equal(v.items().length, 2) + assert.equal(v.items()[0].props.id, 'SHS-Regular') + assert.match(v.items()[0].props.subtitle, /Regular · 共 3 个字重/) + await delay(); await tick() + assert.match(v.item('SHS-Regular').props.detail.props.markdown, /家族字重(3)/) + assert.match(v.item('SHS-Regular').props.detail.props.markdown, /中号 \(28px\)/) + + // 切换预览字号(中号 -> 大号) + await v.run(v.item('SHS-Regular'), '切换预览字号(当前:中号 (28px))') + await tick() + assert.match(v.item('SHS-Regular').props.detail.props.markdown, /大号 \(44px\)/) +}) + +test('显式「打开本地字体」入口存在,并支持拖入本地字体文件且拒绝非字体格式', async () => { + const v = await open() + const openBtn = v.tree().props.filterBar.actions.find(a => a.id === 'open-local-font') + assert.ok(openBtn, 'filterBar 应包含显式「打开本地字体」按钮') + assert.equal(openBtn.title, '打开本地字体') + + // 拖入本地 .otf 字体文件 + await v.tree().props.onFileInput({ files: ['/tmp/CustomBrand.otf'], source: 'drop' }) + await tick() + const localItem = v.item('local:/tmp/CustomBrand.otf') + assert.ok(localItem, '应载入本地字体条目') + assert.equal(localItem.props.title, 'CustomBrand') + assert.match(localItem.props.detail.props.markdown, /本地未安装字体文件/) + + // 拖入非字体文件应如实拒绝 + await v.tree().props.onFileInput({ files: ['/tmp/readme.txt'], source: 'drop' }) + await tick() + assert.match(host.lastToast().title, /仅支持/) +}) diff --git a/extensions/git-helper/plugin.json b/extensions/git-helper/plugin.json index 77174dda..9a20f9b8 100644 --- a/extensions/git-helper/plugin.json +++ b/extensions/git-helper/plugin.json @@ -1,7 +1,7 @@ { "id": "git-helper", "name": "Git救命锦囊", - "version": "1.0.6", + "version": "1.0.7", "minAppVersion": "1.1.8.0", "description": "大白话场景检索Git回滚自救命令、交互式规范提交(Conventional Commits)生成器与多语言.gitignore模板合成", "author": "ZTools Team", diff --git a/extensions/git-helper/src/git-helper-service.ts b/extensions/git-helper/src/git-helper-service.ts index 20a2bf95..202b356d 100644 --- a/extensions/git-helper/src/git-helper-service.ts +++ b/extensions/git-helper/src/git-helper-service.ts @@ -1,4 +1,12 @@ -import type { CommitTypeItem, GitEmergencyItem, GitignoreStackTemplate } from './types.js' +import type { + CommitTypeItem, + ConventionalCommitOptions, + ConventionalCommitResult, + GitEmergencyItem, + GitignoreMergeResult, + GitignoreStackTemplate, + ShellSyntax +} from './types.js' import { GIT_HELPER_MESSAGES, t } from './i18n.js' type GitHelperKey = keyof (typeof GIT_HELPER_MESSAGES)['zh-CN'] @@ -6,6 +14,7 @@ type GitHelperKey = keyof (typeof GIT_HELPER_MESSAGES)['zh-CN'] interface EmergencyStepSpec { titleKey: GitHelperKey cmd?: string + powershellCmd?: string cmdKey?: GitHelperKey explainKey: GitHelperKey } @@ -21,8 +30,10 @@ interface EmergencySpec { safetyKey: 'safetySafe' | 'safetyCaution' | 'safetyDanger' diffKey: 'diffBeginner' | 'diffMedium' | 'diffExpert' primaryCommand: string + powershellPrimaryCommand?: string steps: readonly EmergencyStepSpec[] principleKey: GitHelperKey + dangerWarningKey?: GitHelperKey minGitVersion?: string } @@ -38,9 +49,34 @@ interface GitignoreSpec { name?: string nameKey?: GitHelperKey catKey: GitHelperKey + keywords?: readonly string[] rules: readonly string[] } +/** + * 自动检测当前宿主平台对应的默认终端语法: + * Windows -> PowerShell;macOS / Linux -> POSIX (Bash / zsh) + */ +export function detectDefaultShellSyntax(): ShellSyntax { + const nav = (globalThis as { navigator?: { platform?: string; userAgent?: string } }).navigator + const platformText = `${nav?.platform ?? ''} ${nav?.userAgent ?? ''}`.trim() + if (platformText) { + if (/Mac|Linux|X11|Unix/i.test(platformText) && !/Win/i.test(platformText)) { + return 'posix' + } + if (/Win/i.test(platformText)) { + return 'powershell' + } + } + const proc = (globalThis as { process?: { platform?: string } }).process + if (proc?.platform === 'win32') return 'powershell' + return 'posix' +} + +export function getShellDisplayName(shellSyntax: ShellSyntax): string { + return shellSyntax === 'powershell' ? t('shellNamePowerShell') : t('shellNamePosix') +} + const EMERGENCY_SPECS: readonly EmergencySpec[] = [ { id: 'undo-last-commit-keep-changes', @@ -53,10 +89,12 @@ const EMERGENCY_SPECS: readonly EmergencySpec[] = [ safetyKey: 'safetyCaution', diffKey: 'diffBeginner', primaryCommand: 'git branch backup/before-undo && git reset --soft HEAD~1', + powershellPrimaryCommand: 'git branch backup/before-undo; if ($?) { git reset --soft HEAD~1 }', steps: [ { titleKey: 'emUndoStep1Title', cmd: 'git branch backup/before-undo && git reset --soft HEAD~1', + powershellCmd: 'git branch backup/before-undo; if ($?) { git reset --soft HEAD~1 }', explainKey: 'emUndoStep1Explain' }, { @@ -66,6 +104,7 @@ const EMERGENCY_SPECS: readonly EmergencySpec[] = [ } ], principleKey: 'emUndoPrinciple', + dangerWarningKey: 'emUndoWarning', minGitVersion: 'Git 2.0+' }, { @@ -88,10 +127,12 @@ const EMERGENCY_SPECS: readonly EmergencySpec[] = [ { titleKey: 'emAmendStep2Title', cmd: 'git branch backup/before-amend && git commit --amend --no-edit', + powershellCmd: 'git branch backup/before-amend; if ($?) { git commit --amend --no-edit }', explainKey: 'emAmendStep2Explain' } ], - principleKey: 'emAmendPrinciple' + principleKey: 'emAmendPrinciple', + dangerWarningKey: 'emAmendWarning' }, { id: 'recover-deleted-branch-or-hard-reset', @@ -141,7 +182,9 @@ const EMERGENCY_SPECS: readonly EmergencySpec[] = [ explainKey: 'emWrongBranchStep2Explain' } ], - principleKey: 'emWrongBranchPrinciple' + principleKey: 'emWrongBranchPrinciple', + dangerWarningKey: 'emWrongBranchWarning', + minGitVersion: 'Git 2.23+' }, { id: 'undo-messy-git-pull-merge', @@ -204,10 +247,12 @@ const EMERGENCY_SPECS: readonly EmergencySpec[] = [ safetyKey: 'safetySafe', diffKey: 'diffMedium', primaryCommand: "git fsck --no-reflog | awk '/dangling commit/ {print $3}'", + powershellPrimaryCommand: "git fsck --no-reflog | Select-String 'dangling commit' | ForEach-Object { ($_ -split '\\s+')[2] }", steps: [ { titleKey: 'emStashRecoverStep1Title', cmd: "git fsck --no-reflog | awk '/dangling commit/ {print $3}'", + powershellCmd: "git fsck --no-reflog | Select-String 'dangling commit' | ForEach-Object { ($_ -split '\\s+')[2] }", explainKey: 'emStashRecoverStep1Explain' }, { @@ -267,7 +312,8 @@ const EMERGENCY_SPECS: readonly EmergencySpec[] = [ explainKey: 'emCleanUntrackedStep2Explain' } ], - principleKey: 'emCleanUntrackedPrinciple' + principleKey: 'emCleanUntrackedPrinciple', + dangerWarningKey: 'emCleanUntrackedWarning' }, { id: 'edit-last-commit-message', @@ -292,7 +338,8 @@ const EMERGENCY_SPECS: readonly EmergencySpec[] = [ explainKey: 'emEditMsgStep2Explain' } ], - principleKey: 'emEditMsgPrinciple' + principleKey: 'emEditMsgPrinciple', + dangerWarningKey: 'emAmendWarning' }, { id: 'abort-or-continue-rebase', @@ -343,6 +390,7 @@ const EMERGENCY_SPECS: readonly EmergencySpec[] = [ } ], principleKey: 'emDiscardFilePrinciple', + dangerWarningKey: 'emDiscardFileWarning', minGitVersion: 'Git 2.23+' }, { @@ -437,11 +485,16 @@ const COMMIT_TYPE_SPECS: readonly CommitTypeSpec[] = [ { type: 'revert', meaningKey: 'ctRevertMeaning', descKey: 'ctRevertDesc', exampleKeys: ['ctRevertEx1'] } ] +/** + * 33 个主流离线 .gitignore 模板(覆盖语言、前后端/移动端/游戏引擎、云原生运维、数据科学、OS 与 IDE) + */ const GITIGNORE_SPECS: readonly GitignoreSpec[] = [ + // 语言与运行时 { id: 'Node', name: 'Node.js / TypeScript', catKey: 'giCatLang', + keywords: ['javascript', 'js', 'ts', 'npm', 'pnpm', 'yarn', 'bun'], rules: [ 'node_modules/', 'dist/', @@ -458,25 +511,11 @@ const GITIGNORE_SPECS: readonly GitignoreSpec[] = [ 'coverage/' ] }, - { - id: 'ReactVue', - name: 'React / Vue / Next / Vite', - catKey: 'giCatFrontend', - rules: [ - '.next/', - '.nuxt/', - '.output/', - '.vite/', - '.cache/', - 'dist/', - 'dist-ssr/', - '*.local' - ] - }, { id: 'Python', name: 'Python / PyTorch / Poetry', catKey: 'giCatLang', + keywords: ['py', 'pip', 'uv', 'django', 'flask', 'fastapi'], rules: [ '__pycache__/', '*.py[cod]', @@ -486,6 +525,7 @@ const GITIGNORE_SPECS: readonly GitignoreSpec[] = [ 'ENV/', '.pytest_cache/', '.mypy_cache/', + '.ruff_cache/', '*.egg-info/', 'dist/', '.env' @@ -495,6 +535,7 @@ const GITIGNORE_SPECS: readonly GitignoreSpec[] = [ id: 'Java', name: 'Java / Maven / Gradle / Spring', catKey: 'giCatLang', + keywords: ['jvm', 'spring', 'boot', 'maven', 'gradle'], rules: [ 'target/', 'build/', @@ -514,6 +555,7 @@ const GITIGNORE_SPECS: readonly GitignoreSpec[] = [ id: 'Go', name: 'Go (Golang)', catKey: 'giCatLang', + keywords: ['golang', 'gomod'], // vendor/ 是否提交由项目决定(go mod vendor),默认不忽略 rules: ['bin/', '*.exe', '*.exe~', '*.dll', '*.so', '*.dylib', '*.test', '*.out', 'go.work'] }, @@ -521,13 +563,343 @@ const GITIGNORE_SPECS: readonly GitignoreSpec[] = [ id: 'Rust', name: 'Rust / Cargo', catKey: 'giCatLang', + keywords: ['cargo', 'crates'], // Cargo 官方建议提交 Cargo.lock(应用与库都适用),这里不忽略它 rules: ['target/', '**/*.rs.bk', '*.pdb'] }, + { + id: 'Cpp', + name: 'C / C++ / CMake', + catKey: 'giCatLang', + keywords: ['c++', 'clang', 'gcc', 'msvc', 'cmake', 'ninja'], + rules: [ + 'build/', + 'cmake-build-*/', + 'CMakeFiles/', + 'CMakeCache.txt', + 'compile_commands.json', + '*.o', + '*.obj', + '*.a', + '*.lib', + '*.so', + '*.dylib', + '*.dll', + '*.exe', + '*.out', + '*.pdb', + '*.ilk' + ] + }, + { + id: 'CSharp', + name: 'C# / .NET / Visual Studio', + catKey: 'giCatLang', + keywords: ['dotnet', 'aspnet', 'vs', 'nuget', 'csproj'], + rules: [ + 'bin/', + 'obj/', + '.vs/', + '*.user', + '*.suo', + '*.userosscache', + '*.sln.docstates', + 'TestResults/', + 'BenchmarkDotNet.Artifacts/', + '*.nupkg', + '*.snupkg' + ] + }, + { + id: 'Swift', + name: 'Swift / Xcode / SPM', + catKey: 'giCatLang', + keywords: ['ios', 'macos', 'xcode', 'cocoapods', 'carthage'], + rules: [ + '.build/', + '.swiftpm/', + 'DerivedData/', + '*.xcodeproj/xcuserdata/', + '*.xcworkspace/xcuserdata/', + '*.xcuserstate', + '*.moved-aside', + '*.hmap', + '*.ipa', + '*.dSYM.zip', + '*.dSYM', + 'Pods/' + ] + }, + { + id: 'Kotlin', + name: 'Kotlin / KMP / Gradle', + catKey: 'giCatLang', + keywords: ['kt', 'kmp', 'gradle'], + rules: [ + 'build/', + '.gradle/', + '.kotlin/', + '*.class', + '*.jar', + '!gradle/wrapper/gradle-wrapper.jar', + 'local.properties' + ] + }, + { + id: 'PHP', + name: 'PHP / Composer / Laravel', + catKey: 'giCatLang', + keywords: ['composer', 'laravel', 'symfony'], + rules: [ + 'vendor/', + '.phpunit.result.cache', + '.env', + '.env.backup', + 'storage/*.key', + 'public/hot', + 'public/storage', + 'bootstrap/cache/*' + ] + }, + { + id: 'Ruby', + name: 'Ruby / Rails / Bundler', + catKey: 'giCatLang', + keywords: ['rails', 'gem', 'bundler'], + rules: [ + '*.gem', + '*.rbc', + '/.bundle/', + '/vendor/bundle', + '/log/*', + '/tmp/*', + '!/log/.keep', + '!/tmp/.keep', + '/storage/*', + 'config/master.key', + '.byebug_history' + ] + }, + { + id: 'Dart', + name: 'Dart / Pub', + catKey: 'giCatLang', + keywords: ['pub', 'dartlang'], + rules: ['.dart_tool/', '.packages', 'build/', 'pubspec.lock'] + }, + { + id: 'Elixir', + name: 'Elixir / Phoenix / Mix', + catKey: 'giCatLang', + keywords: ['phoenix', 'erlang', 'mix'], + rules: ['/_build/', '/cover/', '/deps/', '/doc/', '.fetch', 'erl_crash.dump', '*.ez', '*.beam'] + }, + { + id: 'Zig', + name: 'Zig', + catKey: 'giCatLang', + keywords: ['ziglang'], + rules: ['zig-cache/', '.zig-cache/', 'zig-out/'] + }, + // 前端与跨端框架 + { + id: 'ReactVue', + name: 'React / Vue / Next / Nuxt / Vite', + catKey: 'giCatFrontend', + keywords: ['frontend', 'vite', 'next', 'nuxt', 'webpack'], + rules: [ + '.next/', + '.nuxt/', + '.output/', + '.vite/', + '.cache/', + 'dist/', + 'dist-ssr/', + '*.local' + ] + }, + { + id: 'Angular', + name: 'Angular', + catKey: 'giCatFrontend', + keywords: ['ng', 'angular'], + rules: ['.angular/cache/', 'dist/', 'tmp/', 'out-tsc/', 'bazel-out/'] + }, + { + id: 'Svelte', + name: 'Svelte / SvelteKit', + catKey: 'giCatFrontend', + keywords: ['sveltekit'], + rules: ['.svelte-kit/', 'build/', '.vercel/', '.netlify/', '.env', '.env.*'] + }, + { + id: 'Electron', + name: 'Electron / Tauri', + catKey: 'giCatFrontend', + keywords: ['desktop', 'tauri', 'electron-builder'], + rules: ['out/', 'release/', 'dist-electron/', 'src-tauri/target/', '*.dmg', '*.AppImage', '*.nsis'] + }, + { + id: 'Android', + name: 'Android / Gradle / NDK', + catKey: 'giCatFrontend', + keywords: ['apk', 'aab', 'android-studio', 'ndk'], + rules: [ + '*.iml', + '.gradle/', + 'local.properties', + '.cxx/', + 'captures/', + '.externalNativeBuild/', + 'build/', + 'app/build/', + '*.apk', + '*.aab', + '*.ap_', + '*.dex', + '!gradle/wrapper/gradle-wrapper.jar' + ] + }, + { + id: 'Flutter', + name: 'Flutter', + catKey: 'giCatFrontend', + keywords: ['mobile', 'ios', 'android', 'dart'], + rules: [ + '.dart_tool/', + '.flutter-plugins', + '.flutter-plugins-dependencies', + '.pub-cache/', + '.pub/', + 'build/', + 'ios/Pods/', + 'ios/.symlinks/', + 'android/.gradle/', + 'android/local.properties' + ] + }, + { + id: 'Unity', + name: 'Unity', + catKey: 'giCatFrontend', + keywords: ['game', 'unity3d'], + rules: [ + '[Ll]ibrary/', + '[Tt]emp/', + '[Oo]bj/', + '[Bb]uild/', + '[Bb]uilds/', + '[Ll]ogs/', + '[Uu]ser[Ss]ettings/', + '*.csproj', + '*.unityproj', + '*.sln', + '*.pidb', + '*.booproj' + ] + }, + { + id: 'UnrealEngine', + name: 'Unreal Engine', + catKey: 'giCatFrontend', + keywords: ['ue5', 'ue4', 'game'], + rules: [ + 'Binaries/', + 'DerivedDataCache/', + 'Intermediate/', + 'Saved/', + 'Build/', + '*.VC.db', + '*.opensdf', + '*.opendb', + '*.sdf', + '*.sln' + ] + }, + // 云原生与运维 + { + id: 'Docker', + name: 'Docker / Docker Compose', + catKey: 'giCatDevOps', + keywords: ['container', 'compose', 'oci'], + rules: [ + '.docker/', + 'docker-compose.override.yml', + 'docker-compose.local.yml', + '*.pid', + '*.log', + '.env', + '.env.local' + ] + }, + { + id: 'Terraform', + name: 'Terraform / OpenTofu', + catKey: 'giCatDevOps', + keywords: ['iac', 'hcl', 'opentofu', 'tf'], + rules: [ + '.terraform/', + '*.tfstate', + '*.tfstate.*', + 'crash.log', + 'crash.*.log', + '*.tfvars', + '*.tfvars.json', + 'override.tf', + 'override.tf.json', + '*_override.tf', + '*_override.tf.json', + '.terraformrc', + 'terraform.rc' + ] + }, + { + id: 'Kubernetes', + name: 'Kubernetes / Helm', + catKey: 'giCatDevOps', + keywords: ['k8s', 'helm', 'kubeconfig'], + rules: ['kubeconfig', '*.kubeconfig', 'charts/*.tgz', 'values.local.yaml', 'values.secret.yaml'] + }, + { + id: 'Ansible', + name: 'Ansible', + catKey: 'giCatDevOps', + keywords: ['playbook', 'ops'], + rules: ['*.retry', '.vault_pass', 'vault_pass.txt', '.ansible/'] + }, + // 数据科学与文档 + { + id: 'Jupyter', + name: 'Jupyter Notebook / Conda', + catKey: 'giCatDataDocs', + keywords: ['ipynb', 'anaconda', 'ml', 'ai', 'data'], + rules: ['.ipynb_checkpoints/', '*/.ipynb_checkpoints/*', '.conda/', 'wandb/', 'mlruns/', '*.h5', '*.ckpt'] + }, + { + id: 'LaTeX', + name: 'LaTeX / TeX', + catKey: 'giCatDataDocs', + keywords: ['tex', 'bibtex', 'paper'], + rules: [ + '*.aux', + '*.bbl', + '*.blg', + '*.fdb_latexmk', + '*.fls', + '*.log', + '*.out', + '*.synctex.gz', + '*.toc', + '*.lof', + '*.lot' + ] + }, + // 操作系统 { id: 'macOS', nameKey: 'giNameMacOS', catKey: 'giCatOS', + keywords: ['apple', 'osx', 'ds_store', 'finder'], rules: [ '.DS_Store', '.AppleDouble', @@ -547,13 +919,30 @@ const GITIGNORE_SPECS: readonly GitignoreSpec[] = [ id: 'Windows', nameKey: 'giNameWindows', catKey: 'giCatOS', + keywords: ['win', 'thumbs', 'desktop.ini'], rules: ['Thumbs.db', 'Thumbs.db:encryptable', 'ehthumbs.db', '[Dd]esktop.ini', '$RECYCLE.BIN/', '*.lnk'] }, + { + id: 'Linux', + nameKey: 'giNameLinux', + catKey: 'giCatOS', + keywords: ['ubuntu', 'debian', 'arch', 'freedesktop'], + rules: ['*~', '.fuse_hidden*', '.directory', '.Trash-*', '.nfs*'] + }, + // 编辑器与 IDE { id: 'IDEs', name: 'VS Code / Cursor / JetBrains IDE', catKey: 'giCatIDE', + keywords: ['vscode', 'cursor', 'idea', 'webstorm', 'pycharm', 'goland'], rules: ['.vscode/*', '!.vscode/extensions.json', '!.vscode/settings.json', '.idea/', '*.iml', '*.iws', '.history/'] + }, + { + id: 'VimEmacs', + name: 'Vim / Neovim / Emacs', + catKey: 'giCatIDE', + keywords: ['nvim', 'vi', 'emacs', 'swap'], + rules: ['[._]*.s[a-v][a-z]', '!*.svg', '[._]*.sw[a-p]', '[._]s[a-rt-v][a-z]', '[._]ss[a-gi-z]', 'Session.vim', '.netrwhist', '*~', '\\#*\\#', '.\\#*'] } ] @@ -563,10 +952,31 @@ function tr(key: GitHelperKey, locale?: 'zh-CN' | 'en-US'): string { } function splitTags(raw: string): string[] { - return raw.split(',').map((s) => s.trim()).filter(Boolean) + return raw + .split(',') + .map((s) => s.trim()) + .filter(Boolean) +} + +function resolveStepCmd(step: EmergencyStepSpec, shellSyntax: ShellSyntax, locale?: 'zh-CN' | 'en-US'): string { + if (shellSyntax === 'powershell' && step.powershellCmd) { + return step.powershellCmd + } + return step.cmdKey ? tr(step.cmdKey, locale) : (step.cmd ?? '') } -function buildEmergencyItem(spec: EmergencySpec, locale?: 'zh-CN' | 'en-US'): GitEmergencyItem { +function resolvePrimaryCmd(spec: EmergencySpec, shellSyntax: ShellSyntax): string { + if (shellSyntax === 'powershell' && spec.powershellPrimaryCommand) { + return spec.powershellPrimaryCommand + } + return spec.primaryCommand +} + +function buildEmergencyItem( + spec: EmergencySpec, + shellSyntax: ShellSyntax = 'posix', + locale?: 'zh-CN' | 'en-US' +): GitEmergencyItem { return { id: spec.id, title: tr(spec.titleKey, locale), @@ -577,18 +987,19 @@ function buildEmergencyItem(spec: EmergencySpec, locale?: 'zh-CN' | 'en-US'): Gi safetyKind: spec.safetyKind, safetyLevel: tr(spec.safetyKey, locale), difficulty: tr(spec.diffKey, locale), - primaryCommand: spec.primaryCommand, + primaryCommand: resolvePrimaryCmd(spec, shellSyntax), steps: spec.steps.map((s) => ({ title: tr(s.titleKey, locale), - cmd: s.cmdKey ? tr(s.cmdKey, locale) : (s.cmd ?? ''), + cmd: resolveStepCmd(s, shellSyntax, locale), explain: tr(s.explainKey, locale) })), principle: tr(spec.principleKey, locale), + ...(spec.dangerWarningKey ? { dangerWarning: tr(spec.dangerWarningKey, locale) } : {}), ...(spec.minGitVersion ? { minGitVersion: spec.minGitVersion } : {}) } } -/** 动态视图数组:所有展示文本通过 getter 实时按当前 locale 读取,支持语言热切换且无硬编码中文 */ +/** 动态视图数组:所有展示文本通过 getter 实时按当前 locale 读取(默认 POSIX 语法以保持向后兼容) */ export const GIT_EMERGENCY_DATABASE: GitEmergencyItem[] = EMERGENCY_SPECS.map((spec) => ({ id: spec.id, category: spec.category, @@ -614,13 +1025,20 @@ export const GIT_EMERGENCY_DATABASE: GitEmergencyItem[] = EMERGENCY_SPECS.map((s get steps() { return spec.steps.map((s) => ({ title: tr(s.titleKey), - cmd: s.cmdKey ? tr(s.cmdKey) : (s.cmd ?? ''), + cmd: resolveStepCmd(s, 'posix'), explain: tr(s.explainKey) })) }, get principle() { return tr(spec.principleKey) - } + }, + ...(spec.dangerWarningKey + ? { + get dangerWarning() { + return spec.dangerWarningKey ? tr(spec.dangerWarningKey) : undefined + } + } + : {}) })) export const COMMIT_TYPES: CommitTypeItem[] = COMMIT_TYPE_SPECS.map((spec) => ({ @@ -639,6 +1057,7 @@ export const COMMIT_TYPES: CommitTypeItem[] = COMMIT_TYPE_SPECS.map((spec) => ({ export const GITIGNORE_STACK_TEMPLATES: GitignoreStackTemplate[] = GITIGNORE_SPECS.map((spec) => ({ id: spec.id, rules: [...spec.rules], + ...(spec.keywords ? { keywords: [...spec.keywords] } : {}), get name() { return spec.nameKey ? tr(spec.nameKey) : (spec.name ?? spec.id) }, @@ -647,15 +1066,30 @@ export const GITIGNORE_STACK_TEMPLATES: GitignoreStackTemplate[] = GITIGNORE_SPE } })) -/** 整份指南仅供阅读;每行都是 shell 注释,避免把可选方案串成连续命令。 */ -export function buildEmergencyGuide(item: GitEmergencyItem): string { - return [t('guideScenarioPrefix', { title: item.title }), t('guideIntro'), - ...item.steps.flatMap((step, index) => [`${index + 1}. ${step.title}`, step.cmd, step.explain]), item.principle] - .flatMap(line => line.split(/\r?\n/)).map(line => `# ${line}`).join('\n') +/** 整份指南仅供阅读;每行都是 shell 注释(#),避免把可选方案串成连续命令。 */ +export function buildEmergencyGuide(item: GitEmergencyItem, shellSyntax?: ShellSyntax): string { + const headerLines = [ + t('guideScenarioPrefix', { title: item.title }), + ...(shellSyntax ? [t('guideShellPrefix', { shell: getShellDisplayName(shellSyntax) })] : []), + t('guideIntro') + ] + const bodyLines = item.steps.flatMap((step, index) => [ + `${index + 1}. ${step.title}`, + step.cmd, + step.explain + ]) + const footerLines = [ + ...(item.dangerWarning ? [item.dangerWarning] : []), + item.principle + ] + return [...headerLines, ...bodyLines, ...footerLines] + .flatMap((line) => line.split(/\r?\n/)) + .map((line) => `# ${line}`) + .join('\n') } -export function getEmergencyDatabase(): GitEmergencyItem[] { - return EMERGENCY_SPECS.map((spec) => buildEmergencyItem(spec)) +export function getEmergencyDatabase(shellSyntax: ShellSyntax = 'posix'): GitEmergencyItem[] { + return EMERGENCY_SPECS.map((spec) => buildEmergencyItem(spec, shellSyntax)) } export function getCommitTypes(): CommitTypeItem[] { @@ -672,23 +1106,27 @@ export function getGitignoreStackTemplates(): GitignoreStackTemplate[] { id: spec.id, name: spec.nameKey ? tr(spec.nameKey) : (spec.name ?? spec.id), category: tr(spec.catKey), + ...(spec.keywords ? { keywords: [...spec.keywords] } : {}), rules: [...spec.rules] })) } /** - * 大白话 + 拼音缩写容错检索 Git 救命锦囊(同时兼容中英文关键词) + * 大白话 + 拼音缩写容错检索 Git 救命锦囊(同时兼容中英文关键词与指定终端语法) */ -export function searchGitEmergencies(query: string): GitEmergencyItem[] { - const db = getEmergencyDatabase() +export function searchGitEmergencies( + query: string, + shellSyntax: ShellSyntax = 'posix' +): GitEmergencyItem[] { + const db = getEmergencyDatabase(shellSyntax) const q = String(query ?? '') .trim() .toLowerCase() if (!q) return db return db.filter((item, idx) => { - const zh = buildEmergencyItem(EMERGENCY_SPECS[idx], 'zh-CN') - const en = buildEmergencyItem(EMERGENCY_SPECS[idx], 'en-US') + const zh = buildEmergencyItem(EMERGENCY_SPECS[idx], shellSyntax, 'zh-CN') + const en = buildEmergencyItem(EMERGENCY_SPECS[idx], shellSyntax, 'en-US') const haystack = [ item.title, item.categoryLabel, @@ -716,7 +1154,18 @@ export function quotePosixShellArg(raw: string): string { return "'" + raw.replace(/'/g, "'\"'\"'") + "'" } -const SCOPE_PATTERN = /^[A-Za-z0-9_\-./\u4e00-\u9fff]{1,23}$/ +/** + * 用 PowerShell 单引号保留字面值($HOME、$(...)、反引号、双引号均不展开,单引号双写为 '')。 + */ +export function quotePowerShellArg(raw: string): string { + return "'" + raw.replace(/'/g, "''") + "'" +} + +export function quoteShellArg(raw: string, shellSyntax: ShellSyntax): string { + return shellSyntax === 'powershell' ? quotePowerShellArg(raw) : quotePosixShellArg(raw) +} + +export const SCOPE_PATTERN = /^[A-Za-z0-9_\-./\u4e00-\u9fff]{1,23}$/ /** * 解析搜索框里的 `scope:说明`(英文冒号)。冒号前不是合法 scope(含空格、是网址协议等)时整段都当作说明; @@ -730,62 +1179,103 @@ export function parseCommitInput(raw: string): { scope: string; subject: string const head = text.slice(0, colonIdx).trim() const rest = text.slice(colonIdx + 1) if (!SCOPE_PATTERN.test(head) || rest.startsWith('//')) return { scope: '', subject: text } - if (COMMIT_TYPE_SPECS.some((spec) => spec.type === head.toLowerCase())) return { scope: '', subject: rest.trim() } + if (COMMIT_TYPE_SPECS.some((spec) => spec.type === head.toLowerCase())) { + return { scope: '', subject: rest.trim() } + } return { scope: head, subject: rest.trim() } } /** - * 构建符合 Conventional Commits 规范的提交文本与可执行 git commit 命令 + * 构建符合 Conventional Commits 规范的提交文本与可执行 git commit 命令(支持 Body、Footer、Breaking Change 与双平台 Shell 语法) */ -export function buildConventionalCommit(options: { - type: string - scope?: string - subject: string - breaking?: boolean -}): { - isValid: boolean - message: string - gitCommand: string - validationHint?: string -} { +export function buildConventionalCommit( + options: ConventionalCommitOptions +): ConventionalCommitResult { + const shellSyntax: ShellSyntax = options.shellSyntax ?? 'posix' const cleanType = String(options.type || 'feat').trim() const cleanScope = String(options.scope || '') .trim() .replace(/[()\r\n]/g, '') // 换行与制表符按空格处理(粘贴多行说明时常见),其余控制字符拒绝 - const rawSubject = String(options.subject || '').replace(/[\r\n\t]+/g, ' ').trim() + const rawSubject = String(options.subject || '') + .replace(/[\r\n\t]+/g, ' ') + .trim() + const rawBody = String(options.body || '') + .replace(/\r\n/g, '\n') + .trim() + const rawFooter = String(options.footer || '') + .replace(/\r\n/g, '\n') + .trim() + const rawBreakingDesc = String(options.breakingDescription || '') + .replace(/[\r\n\t]+/g, ' ') + .trim() + const bang = options.breaking ? '!' : '' const scopePart = cleanScope ? `(${cleanScope})` : '' - const hasControl = /[\u0000-\u001f\u007f]/.test(cleanType + cleanScope + rawSubject) - if (!rawSubject || hasControl) { + // 检查控制字符(允许 body / footer 中的换行 \n) + const hasHeaderControl = /[\u0000-\u001f\u007f]/.test(cleanType + cleanScope + rawSubject + rawBreakingDesc) + const hasBodyControl = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/.test(rawBody + rawFooter) + + if (cleanScope && !SCOPE_PATTERN.test(cleanScope)) { + const placeholder = rawSubject || t('commitPlaceholder') + const header = `${cleanType}${scopePart}${bang}: ${placeholder}` + return { + isValid: false, + header, + message: header, + gitCommand: '', + shellSyntax, + validationHint: t('commitErrScopeInvalid') + } + } + + if (!rawSubject || hasHeaderControl || hasBodyControl) { const placeholder = t('commitPlaceholder') - const msg = `${cleanType}${scopePart}${bang}: ${placeholder}` + const header = `${cleanType}${scopePart}${bang}: ${placeholder}` return { isValid: false, - message: msg, + header, + message: header, gitCommand: '', - validationHint: hasControl - ? t('commitErrControlChars') - : t('commitErrEmpty') + shellSyntax, + validationHint: + hasHeaderControl || hasBodyControl ? t('commitErrControlChars') : t('commitErrEmpty') } } - const normalizedSubject = rawSubject - const message = `${cleanType}${scopePart}${bang}: ${normalizedSubject}` - const escaped = quotePosixShellArg(message) + const header = `${cleanType}${scopePart}${bang}: ${rawSubject}` + const footerBlocks: string[] = [] + if (options.breaking && rawBreakingDesc) { + footerBlocks.push(`BREAKING CHANGE: ${rawBreakingDesc}`) + } + if (rawFooter) { + footerBlocks.push(rawFooter) + } + + const paragraphs = [header] + if (rawBody) paragraphs.push(rawBody) + if (footerBlocks.length > 0) paragraphs.push(footerBlocks.join('\n')) + + const message = paragraphs.join('\n\n') + const mArgs = paragraphs.map((p) => `-m ${quoteShellArg(p, shellSyntax)}`).join(' ') return { isValid: true, + header, message, - gitCommand: `git commit -m ${escaped}` + gitCommand: `git commit ${mArgs}`, + shellSyntax } } /** * 组合多个技术栈生成去重后的标准 `.gitignore` 文件内容 */ -export function generateGitignoreContent(selectedStackIds: string[], customRules: string[] = []): { +export function generateGitignoreContent( + selectedStackIds: string[], + customRules: string[] = [] +): { content: string totalUniqueRules: number selectedStacks: string[] @@ -793,13 +1283,14 @@ export function generateGitignoreContent(selectedStackIds: string[], customRules const effectiveIds = [...new Set(selectedStackIds)] const seenRules = new Set() - // 首行只写来源;具体模板名已在下面每段的 ### 标题里,不再在首行罗列 const sections: string[] = [t('gitignoreGeneratedHeader')] const localizedTemplates = getGitignoreStackTemplates() for (const stackId of effectiveIds) { const tpl = localizedTemplates.find( - (tplItem) => tplItem.id.toLowerCase() === stackId.toLowerCase() || tplItem.name.toLowerCase().includes(stackId.toLowerCase()) + (tplItem) => + tplItem.id.toLowerCase() === stackId.toLowerCase() || + tplItem.name.toLowerCase().includes(stackId.toLowerCase()) ) if (!tpl) continue @@ -817,7 +1308,9 @@ export function generateGitignoreContent(selectedStackIds: string[], customRules } } - const cleanCustom = [...new Set(customRules.map((r) => r.trim()))].filter((r) => r && !seenRules.has(r)) + const cleanCustom = [...new Set(customRules.map((r) => r.trim()))].filter( + (r) => r && !seenRules.has(r) + ) if (cleanCustom.length > 0) { sections.push(`\n${t('gitignoreCustomRulesHeader')}`) for (const r of cleanCustom) { @@ -832,3 +1325,83 @@ export function generateGitignoreContent(selectedStackIds: string[], customRules selectedStacks: effectiveIds } } + +/** + * 安全合并已有 `.gitignore` 与新生成的规则: + * - 100% 保留用户原有注释、空行、顺序和自定义规则,绝不覆盖; + * - 按规则行精确去重,仅追加目标文件中尚未存在的规则与对应分段标题。 + */ +export function mergeGitignoreContent( + existingContent: string, + generatedContent: string +): GitignoreMergeResult { + const normalizedExisting = String(existingContent ?? '') + const existingLines = normalizedExisting.split(/\r?\n/) + const existingRules = new Set() + + for (const line of existingLines) { + const trimmed = line.trim() + if (!trimmed || trimmed.startsWith('#')) continue + existingRules.add(trimmed) + } + + const generatedLines = String(generatedContent ?? '').split(/\r?\n/) + const appendedLines: string[] = [] + let pendingHeading: string | null = null + let addedRulesCount = 0 + let skippedDuplicatesCount = 0 + + for (const rawLine of generatedLines) { + const trimmed = rawLine.trim() + if (!trimmed) continue + if (trimmed.startsWith('###')) { + pendingHeading = trimmed + continue + } + if (trimmed.startsWith('#')) { + continue + } + if (existingRules.has(trimmed)) { + skippedDuplicatesCount += 1 + continue + } + existingRules.add(trimmed) + if (pendingHeading) { + if (appendedLines.length > 0) appendedLines.push('') + appendedLines.push(pendingHeading) + pendingHeading = null + } + appendedLines.push(trimmed) + addedRulesCount += 1 + } + + if (addedRulesCount === 0) { + return { + mergedContent: normalizedExisting, + addedRulesCount: 0, + skippedDuplicatesCount, + changed: false + } + } + + const eol = normalizedExisting.includes('\r\n') ? '\r\n' : '\n' + if (!normalizedExisting.trim()) { + return { + mergedContent: generatedContent, + addedRulesCount, + skippedDuplicatesCount, + changed: true + } + } + + const base = normalizedExisting.replace(/(?:\r?\n)+$/, '') + const block = [t('gitignoreGeneratedHeader'), ...appendedLines].join(eol) + const mergedContent = `${base}${eol}${eol}${block}${eol}` + + return { + mergedContent, + addedRulesCount, + skippedDuplicatesCount, + changed: true + } +} diff --git a/extensions/git-helper/src/host.ts b/extensions/git-helper/src/host.ts new file mode 100644 index 00000000..0172f189 --- /dev/null +++ b/extensions/git-helper/src/host.ts @@ -0,0 +1,161 @@ +import { mergeGitignoreContent } from './git-helper-service.js' +import { t } from './i18n.js' +import type { GitignoreWriteResult } from './types.js' + +let requestSeq = 0 + +export class GitHelperHostError extends Error { + readonly code: string + + constructor(code: string, message: string) { + super(message) + this.name = 'GitHelperHostError' + this.code = code + } +} + +type HostEnvelope = { + success: boolean + data?: unknown + error?: { code?: string; message?: string } +} + +type HostMethod = (request: { + messageId: string + params: Record +}) => Promise + +interface HostGlobal { + __ztoolsElectron?: { + transport?: { + methods?: Record + } + } + window?: HostGlobal +} + +function resolveHostErrorMessage(code: string, method: string): string { + const upper = code.toUpperCase() + if ( + upper.includes('PERMISSION') || + upper.includes('DENIED') || + upper.includes('UNAUTHORIZED') || + upper === 'EACCES' || + upper === 'EPERM' + ) { + return t('errHostPermissionDenied', { code }) + } + if (code && code !== 'HOST_FAILED') { + return t('errHostWithCode', { code }) + } + return t('errHostCallFailed', { method }) +} + +export async function callHost( + method: string, + params: Record = {} +): Promise { + const root = globalThis as unknown as HostGlobal + const methods = + root.window?.__ztoolsElectron?.transport?.methods ?? + root.__ztoolsElectron?.transport?.methods + const fn = methods?.[method] + if (typeof fn !== 'function') { + throw new GitHelperHostError('HOST_UNAVAILABLE', t('errHostUnsupported', { method })) + } + requestSeq = (requestSeq + 1) % 1_000_000 + const envelope = await fn({ messageId: `git_helper_${Date.now()}_${requestSeq}`, params }) + if (!envelope || typeof envelope !== 'object') { + throw new GitHelperHostError('HOST_RESPONSE_INVALID', t('errHostResponseInvalid')) + } + if (!envelope.success) { + const code = envelope.error?.code || 'HOST_FAILED' + throw new GitHelperHostError(code, resolveHostErrorMessage(code, method)) + } + return envelope.data as T +} + +function joinFolderFile(folderPath: string, fileName: string): string { + const sep = folderPath.includes('\\') && !folderPath.includes('/') ? '\\' : '/' + const trimmed = folderPath.replace(/[\\/]+$/, '') + return `${trimmed}${sep}${fileName}` +} + +async function checkFileExists(filePath: string): Promise { + const res = await callHost('filesystem_file_exists', { path: filePath }) + if (typeof res === 'boolean') return res + if (res && typeof res === 'object' && typeof (res as { exists?: unknown }).exists === 'boolean') { + return (res as { exists: boolean }).exists + } + throw new GitHelperHostError('HOST_RESPONSE_INVALID', t('errHostResponseInvalid')) +} + +function extractReadContent(data: unknown): string { + if (typeof data === 'string') return data + if (data && typeof data === 'object' && typeof (data as { content?: unknown }).content === 'string') { + return (data as { content: string }).content + } + throw new GitHelperHostError('HOST_RESPONSE_INVALID', t('errHostResponseInvalid')) +} + +/** + * 显式让用户选择项目根目录,并安全创建或去重合并追加 `.gitignore`(不覆盖用户已有规则)。 + */ +export async function writeGitignoreToProjectDir( + generatedContent: string +): Promise { + const picked = await callHost<{ canceled?: boolean; folderPath?: string }>( + 'window_show_select_folder_dialog', + { title: t('gitignoreSelectDirTitle') } + ) + if (!picked || picked.canceled || !picked.folderPath) { + return { status: 'canceled' } + } + + const targetPath = joinFolderFile(picked.folderPath, '.gitignore') + const exists = await checkFileExists(targetPath) + + if (!exists) { + const freshMerge = mergeGitignoreContent('', generatedContent) + await callHost('filesystem_write_file', { + path: targetPath, + content: generatedContent, + encoding: 'utf8' + }) + return { + status: 'created', + filePath: targetPath, + addedRulesCount: freshMerge.addedRulesCount, + skippedDuplicatesCount: 0 + } + } + + const readData = await callHost('filesystem_read_file', { + path: targetPath, + encoding: 'utf8' + }) + const existingContent = extractReadContent(readData) + const merged = mergeGitignoreContent(existingContent, generatedContent) + + if (!merged.changed) { + return { + status: 'unchanged', + filePath: targetPath, + addedRulesCount: 0, + skippedDuplicatesCount: merged.skippedDuplicatesCount + } + } + + await callHost('filesystem_write_file', { + path: targetPath, + content: merged.mergedContent, + encoding: 'utf8' + }) + + return { + status: 'merged', + filePath: targetPath, + addedRulesCount: merged.addedRulesCount, + skippedDuplicatesCount: merged.skippedDuplicatesCount + } +} diff --git a/extensions/git-helper/src/i18n.ts b/extensions/git-helper/src/i18n.ts index b204b3f7..15e25c3d 100644 --- a/extensions/git-helper/src/i18n.ts +++ b/extensions/git-helper/src/i18n.ts @@ -1,475 +1,625 @@ import { createTranslator } from '@ztools/declarative-ui' const GIT_HELPER_MESSAGES = { - 'zh-CN': { - searchEmergencyPlaceholder: '输入大白话翻车场景(如:撤销提交、漏提文件、恢复误删分支、撤销pull)...', - searchCommitPlaceholder: '输入改动说明(支持 scope:描述 格式,如 auth:修复登录态刷新失败)...', - searchGitignorePlaceholder: '搜索技术栈或系统模板(如:Node、Python、Go、Rust、macOS)...', - dropdownTooltip: '切换 Git 助手工作模式', - modeEmergency: 'Git 翻车自救锦囊', - modeCommit: '规范提交生成器', - modeGitignore: '.gitignore 模板合成', - emergencySectionTitle: '高频翻车现场与自救指南(共 {count} 项)', - primaryCommandHeader: '#### 首选命令(回车复制)', - incidentPrefix: '### 事故现场:{title}', - stepsHeader: '#### 操作指引(按所处情形选择,不要整段连续执行)', - enterToCopySuffix: '(回车复制)', - principleHeader: '#### 底层 Git 原理与防坑说明', - metaCategoryTitle: '场景分类', - metaDifficultyTitle: '上手难度', - copyPrimaryCommand: '复制首选救命命令', - copyGuideWithNotes: '复制带说明的操作指南', - commitSectionTitle: '选择 Conventional Commits 提交类型', - commitPreviewHeader: '### 规范提交命令预览(Bash / zsh / Git Bash)', - commitInputHintDefault: '请先输入提交说明', - commitMessageHeader: '#### 生成的 Commit Message', - commitTypeInfoHeader: '#### 类型说明(`{type}`)', - commitMeaningLabel: '- **含义**:{meaning}', - commitScopeLabel: '- **适用边界**:{description}', - commitExamplesHeader: '#### 示例', - copyFullGitCommit: '复制完整 git commit 命令', - copyCommitMessageOnly: '仅复制提交说明', - copyTypePrefix: '复制类型前缀 {type}:', - toggleBreakingOn: '开启破坏性变更标记 (!)', - toggleBreakingOff: '关闭破坏性变更标记 (!)', - commitBreakingBadge: '破坏性变更 (!)', - commitSectionTitleBreaking: '选择 Conventional Commits 提交类型(已开启破坏性变更 !)', - gitignoreSectionTitle: '.gitignore 模板多选合成(已选 {stacks} 个栈,去重后 {rules} 条规则 · Enter 勾选 / Ctrl+Enter 复制)', - gitignoreItemSubtitle: '{category} · 含 {count} 条忽略规则', - gitignoreTagChecked: '已勾选合并', - gitignoreTagUnchecked: '未选', - gitignorePreviewHeader: '### 合成后的 `.gitignore` 预览(自动去重)', - metaSelectedStacksTitle: '已合并技术栈', - metaNoneSelected: '未选择', - metaTotalRulesTitle: '去重后规则总数', - metaTotalRulesText: '{count} 条', - copyMergedGitignore: '复制合成后的 .gitignore 全文', - actionUncheck: '取消勾选', - actionCheck: '勾选', - guideScenarioPrefix: '场景:{title}', - guideIntro: '以下是说明,请逐项核对后单独执行命令;不需要把全部步骤连续运行。', - commitPlaceholder: '请填写本次改动的简要说明', - commitErrControlChars: '提交说明含有不可见的控制字符,请删除后重新输入', - commitErrEmpty: '提交说明不能为空,请简述本次修改的目的', - gitignoreGeneratedHeader: '# 由 ZTools Git 助手生成', - gitignoreCustomRulesHeader: '### 自定义规则 ###', - safetySafe: '安全无损', - safetyCaution: '注意检查', - safetyDanger: '有损警告', - diffBeginner: '小白推荐', - diffMedium: '中等', - diffExpert: '专家慎用', - // Emergency items - emUndoTitle: '刚 commit 了,但想撤销这次提交并保留修改在工作区继续改', - emUndoCat: '提交后悔药', - emUndoStep1Title: '为当前提交建立恢复分支,再撤销最近一次尚未推送的提交', - emUndoStep1Explain: '只适用于至少有两次提交的本地分支。恢复分支已存在时会停止,请另取新名字;不会覆盖旧恢复点。工作文件与暂存内容保持不变。', - emUndoStep2Title: '若想同时取消 git add 退回未暂存状态(可选)', - emUndoStep2Explain: '在上一步之后执行;只取消暂存,不再回退 HEAD。工作文件保留,原来的暂存划分会取消。', - emUndoPrinciple: '先核对 git status 和 git log。只撤销一次未推送提交;已推送到共享分支的提交使用 revert。恢复分支保留原提交,不包含未提交文件的独立副本。', - emAmendTitle: '刚 commit 完发现漏提了一个文件,或者提交备注写错了', - emAmendCat: '提交后悔药', - emAmendStep1Title: '把遗漏的文件加入暂存区并合并进上一次提交(不改备注)', - emAmendStep1Cmd: 'git add -- "需要补交的文件路径"', - emAmendStep1Explain: '把引号内替换为明确要补交的文件;再用 git diff --cached 检查全部暂存内容,避免把其他工作一起提交。', - emAmendStep2Title: '确认暂存内容后,保存旧提交再补交(不改备注)', - emAmendStep2Explain: '只用于未推送提交。备份分支重名时停止,换新名字后重试;若只改备注,先核对暂存区,再单独使用 git commit --amend。', - emAmendPrinciple: 'amend 会用一个新的 Commit 对象替换当前分支顶端的旧 Commit(仅限尚未 push 到公共分支时使用)。', - emRecoverTitle: '手滑执行了 git reset --hard 或误删了本地未合并分支,想找回代码', - emRecoverCat: '绝境抢救', - emRecoverStep1Title: '第一步:查看本地所有 HEAD 历史移动轨迹,找到翻车前的短哈希(如 a1b2c3d)', - emRecoverStep1Explain: '从日志中确认要恢复的提交。记录可能已过期或被清理,未提交的文件修改通常不能依靠 reflog 找回。', - emRecoverStep2Title: '第二步:基于翻车前的 commit 哈希新建或恢复分支', - emRecoverStep2Cmd: 'git branch recovered-branch "确认后的提交哈希"', - emRecoverStep2Explain: '将引号内替换为已核对的提交哈希,仅创建恢复分支,不切换或改写当前工作文件;不要假定 HEAD@{1} 就是正确版本。误删的分支若从未检出过,HEAD 的 reflog 里可能没有它,可查看删除时 git branch -D 输出的“was 短哈希”。', - emRecoverPrinciple: 'Git 的提交对象一旦生成就是不可变的,只要未触发过期 GC,reflog 就是时光机黑匣子。', - emWrongBranchTitle: '本来应该在新分支开发,结果不小心直接 commit 到了 main/master 分支', - emWrongBranchCat: '分支纠错', - emWrongBranchStep1Title: '第一步:新建并切换到工作分支,保留提交和当前修改', - emWrongBranchStep1Explain: '新名字不能与已有分支重复。原分支暂时保留,不触碰工作区。', - emWrongBranchStep2Title: '第二步:核对分支与提交关系,再决定如何处理原分支', - emWrongBranchStep2Explain: '当前工作已转到新分支。原分支若已共享,使用 revert;若尚未推送,核对要保留的提交后再调整原分支,不直接运行硬重置。', - emWrongBranchPrinciple: '先建立新分支保护工作,再核对原分支是否已经共享。这里不会自动清理原分支的提交;git switch 需要 Git 2.23 或更新版本。', - emPullAbortTitle: '刚执行了 git pull 或 merge 结果冲突一团糟,想立即回到合并前状态', - emPullAbortCat: '冲突拆弹', - emPullAbortStep1Title: '若正处于合并冲突中断状态,一键中止合并', - emPullAbortStep1Explain: '只适用于正在进行的 merge;rebase 冲突单独用 git rebase --abort。先另存未提交文件及手动解决冲突的内容,abort 不能保证还原合并前所有未提交改动。', - emPullAbortStep2Title: '若合并已经完成,先核对合并前位置;不要接着执行上一步', - emPullAbortStep2Explain: '这是另一种情形,不是 abort 后的下一步。先保存文件副本并新建备份分支;确认该引用未被后续操作改写后,再决定 revert 或本地回退。', - emPullAbortPrinciple: '区分正在合并与已经完成,不能把两个方案连续运行。ORIG_HEAD 会被后续操作更新,使用前必须核对实际提交。', - emRevertTitle: '错误代码已经 push 到了远程公共分支,需要安全回滚且不破坏团队历史', - emRevertCat: '线上回滚', - emRevertStep1Title: '生成一笔反向抵消提交(不动历史时间线)', - emRevertStep1Explain: '确认 HEAD 是要撤销的普通提交,先保存当前修改。合并提交需要核对主线父节点,不能一律选择 -m 1;出现冲突后应处理或 git revert --abort。', - emRevertStep2Title: '核对当前分支与上游后再正常推送(无需危险的 --force)', - emRevertStep2Explain: '测试反向提交并核对当前分支、远端和上游后再正常推送。不要把固定的 main 当成所有项目的目标分支。', - emRevertPrinciple: '公共分支严禁 git reset --hard 后强推(force push),使用 git revert 新增反向补丁才是工程规范。', - // Commit types - ctFeatMeaning: '新增业务功能或特性', - ctFeatDesc: '新增用户能用到或可调用的功能', - ctFeatEx1: 'feat(auth): 新增邮箱验证码登录', - ctFeatEx2: 'feat(export): 支持把报表导出为 CSV', - ctFixMeaning: '修复 Bug 或生产异常', - ctFixDesc: '修复错误行为、崩溃或异常结果', - ctFixEx1: 'fix(network): 修复请求超时后连接没有释放', - ctFixEx2: 'fix(ui): 修复深色模式下表格边框对比度不足', - ctRefactorMeaning: '代码重构(不改变外部行为)', - ctRefactorDesc: '调整代码结构,对外功能和行为不变', - ctRefactorEx1: 'refactor(order): 把支付逻辑从订单服务中拆分出来', - ctPerfMeaning: '性能与内存优化', - ctPerfDesc: '提升速度,或降低内存、CPU 等资源占用', - ctPerfEx1: 'perf(search): 为列表查询增加索引,避免全表扫描', - ctTestMeaning: '新增或完善集成与异常测试', - ctTestDesc: '只新增或修改测试用例,不改功能代码', - ctTestEx1: 'test(cart): 补充库存不足与重复下单的测试', - ctDocsMeaning: '技术文档与注释更新', - ctDocsDesc: '只改文档、注释或 README', - ctDocsEx1: 'docs(readme): 补充本地开发与构建说明', - ctChoreMeaning: '构建脚本、依赖升级或工程杂务', - ctChoreDesc: '构建脚本、依赖升级、CI 配置等不影响功能的杂项', - ctChoreEx1: 'chore(deps): 升级 TypeScript 与构建工具版本', - ctBuildMeaning: '构建系统或外部依赖变更', - ctBuildDesc: '影响构建产物或打包工具链的改动(如 Webpack、Vite、npm 脚本)', - ctBuildEx1: 'build(vite): 启用生产构建产物分包与压缩', - ctCiMeaning: 'CI/CD 流水线与自动化配置', - ctCiDesc: '修改 GitHub Actions、GitLab CI 等持续集成脚本', - ctCiEx1: 'ci(actions): 增加拉取请求自动单测检查流程', - ctStyleMeaning: '代码格式与空白调整(不影响逻辑)', - ctStyleDesc: '仅涉及缩进、分号、格式化等纯代码风格改动', - ctStyleEx1: 'style(lint): 统一全仓单引号与末尾换行风格', - ctRevertMeaning: '回滚先前的某次提交', - ctRevertDesc: '撤销已合入的历史提交,生成反向抵消记录', - ctRevertEx1: 'revert(auth): 回滚引起会话失效的令牌校验提交', - // 新增 9 条高频紧急自救指南 - emStashRecoverTitle: '误删了 git stash(stash drop / clear),想找回被删的暂存改动', - emStashRecoverCat: '绝境抢救', - emStashRecoverTags: 'stash误删,找回stash,dangling commit,fsck', - emStashRecoverStep1Title: '第一步:扫描仓库里悬空的提交对象(被 drop 的 stash 在 GC 前仍存在)', - emStashRecoverStep1Explain: '列出所有悬空提交哈希;配合 git log -g --oneline 或逐个 git show 辨认包含 WIP on ... 的那条 stash 提交。', - emStashRecoverStep2Title: '第二步:确认哈希后查看改动并重新应用到工作区', - emStashRecoverStep2Cmd: 'git stash apply "确认后的悬空提交哈希"', - emStashRecoverStep2Explain: '将引号内替换为确认无误的 stash 提交哈希,应用前建议先确保工作区干净。', - emStashRecoverPrinciple: 'git stash drop 只是移除了引用指针,底层提交对象在触发 git gc 过期清理前仍留在 .git/objects 中。', - emDetachedHeadTitle: '处于游离头指针(detached HEAD)状态并做了提交,怕切分支丢失代码', - emDetachedHeadCat: '分支纠错', - emDetachedHeadTags: 'detached head,游离头指针,救回提交,新建分支', - emDetachedHeadStep1Title: '直接在当前游离提交上新建并切换到正式分支', - emDetachedHeadStep1Explain: '立即把游离的提交挂到新分支名下,工作区与暂存区内容完整保留。', - emDetachedHeadStep2Title: '若已经切走导致提交看不见,用 reflog 找回哈希后再建分支', - emDetachedHeadStep2Cmd: 'git reflog -n 15', - emDetachedHeadStep2Explain: '找到游离状态下的最后一次提交哈希,然后运行 git branch rescue/detached <哈希> 即可找回。', - emDetachedHeadPrinciple: 'detached HEAD 表示 HEAD 直接指向某个提交而非分支引用,只要为其创建分支引用就不会成为孤儿提交。', - emCleanUntrackedTitle: '工作区堆满未跟踪的临时文件或构建产物,想安全批量清理', - emCleanUntrackedCat: '工作区清理', - emCleanUntrackedTags: 'clean,清理未跟踪文件,untracked,删除临时文件', - emCleanUntrackedStep1Title: '第一步:先用 dry-run 预览将被删除的文件和目录(绝不直接硬删)', - emCleanUntrackedStep1Explain: '-n 表示仅演练不删除,-d 包含未跟踪目录;逐项核对列表,确认没有误删新建的源码文件。', - emCleanUntrackedStep2Title: '第二步:核对无误后再执行清理', - emCleanUntrackedStep2Explain: '永久删除未跟踪文件与目录(不可通过 git 恢复);若还需清理被 .gitignore 忽略的产物,再考虑 -x。', - emCleanUntrackedPrinciple: '未跟踪文件尚未进入 Git 对象库,删除后无法靠 reflog 恢复,务必养成先 -nd 预览再 -fd 执行的习惯。', - emEditMsgTitle: '只想修改最近一次未推送的 commit 提交信息(不改任何代码)', - emEditMsgCat: '提交后悔药', - emEditMsgTags: '修改commit信息,amend,改备注,重命名提交', - emEditMsgStep1Title: '先确认暂存区为空,避免顺手把新改动混进上一次提交', - emEditMsgStep1Explain: '如果暂存区已有文件,会一并被 --amend 合并进去;确认只有目标提交需要改备注。', - emEditMsgStep2Title: '使用 --amend --only 仅修改提交说明', - emEditMsgStep2Cmd: 'git commit --amend --only -m "新的提交说明"', - emEditMsgStep2Explain: '--only 忽略暂存区改动,只改写最近一次提交的 message(仅限尚未推送到公共分支的提交)。', - emEditMsgPrinciple: 'git commit --amend 会生成新的提交哈希替换原 HEAD,因此不要对已推送的共享提交使用。', - emRebaseAbortTitle: 'git rebase 变基过程中冲突太多或操作失误,想中止或解决后继续', - emRebaseAbortCat: '冲突拆弹', - emRebaseAbortTags: 'rebase,变基冲突,rebase abort,rebase continue', - emRebaseAbortStep1Title: '放弃本次变基,一键回到 rebase 开始前的原始状态', - emRebaseAbortStep1Explain: '立即终止正在进行的变基并恢复分支指针;不会影响已经提交的历史。', - emRebaseAbortStep2Title: '若已手动解决冲突文件,标记已解决并继续变基', - emRebaseAbortStep2Explain: '先对解决完冲突的文件执行 git add,再运行 --continue 推进下一笔提交。', - emRebaseAbortPrinciple: 'rebase 是逐笔重放提交的过程,中途随时可用 --abort 完整撤回,无需手忙脚乱删分支。', - emDiscardFileTitle: '改乱了单个文件,只想放弃这个文件的本地修改并恢复原样', - emDiscardFileCat: '工作区清理', - emDiscardFileTags: '撤销单文件,还原文件,restore,checkout,放弃修改', - emDiscardFileStep1Title: '先查看该文件的具体改动,确认没有需要保留的片段', - emDiscardFileStep1Cmd: 'git diff -- "需要还原的文件路径"', - emDiscardFileStep1Explain: '丢弃工作区修改不可撤销,先通过 diff 核对一遍再恢复。', - emDiscardFileStep2Title: '将该文件还原为暂存区或最近一次提交的内容', - emDiscardFileStep2Cmd: 'git restore -- "需要还原的文件路径"', - emDiscardFileStep2Explain: '只影响指定文件,不动其他工作区改动;Git 2.23 以下版本可用 git checkout -- "文件路径"。', - emDiscardFilePrinciple: 'git restore 是 Git 2.23+ 拆分出的专用文件还原命令,语义比旧版 git checkout 更清晰且不易误切分支。', - emCleanBranchesTitle: '本地积压了大量已经合并到主分支的旧分支,想安全批量清理', - emCleanBranchesCat: '分支纠错', - emCleanBranchesTags: '清理分支,已合并分支,删除分支,branch merged', - emCleanBranchesStep1Title: '先查看已合并到当前分支的所有本地分支列表', - emCleanBranchesStep1Explain: '确认当前已在主分支(如 main),核对输出结果,排除 main/master/dev 等常驻分支。', - emCleanBranchesStep2Title: '安全删除指定的已合并分支(未合并分支会被 -d 拒绝)', - emCleanBranchesStep2Cmd: 'git branch -d "已合并的旧分支名"', - emCleanBranchesStep2Explain: '使用小写 -d 而非大写 -D,Git 会自动校验分支是否已完全合并,防止误删未合入代码。', - emCleanBranchesPrinciple: 'git branch -d 内置合并状态检查,配合 git fetch --prune 可顺便清理远端已删除的追踪引用。', - emUnstageAddTitle: '误把不需要的文件 git add 进了暂存区,想取消暂存但保留本地代码', - emUnstageAddCat: '提交后悔药', - emUnstageAddTags: '取消暂存,取消git add,unstage,restore staged', - emUnstageAddStep1Title: '取消指定文件的暂存状态(工作区代码原样保留)', - emUnstageAddStep1Cmd: 'git restore --staged -- "误暂存的文件路径"', - emUnstageAddStep1Explain: '仅把文件移出暂存区(index),绝不会丢失工作区里刚写的代码。', - emUnstageAddStep2Title: '若要一次性取消全部已暂存文件', - emUnstageAddStep2Explain: '适合误执行了 git add . 后一键撤回全部暂存,之后再按需逐个添加。', - emUnstageAddPrinciple: 'git restore --staged 只修改暂存索引,不触碰工作目录,是完全无损的安全操作。', - emCherryPickTitle: '只想把另一个分支上的某一笔特定提交精准摘取到当前分支', - emCherryPickCat: '分支纠错', - emCherryPickTags: 'cherry-pick,摘取提交,跨分支复制提交,热修复', - emCherryPickStep1Title: '先查看源分支提交日志,确认目标提交的短哈希', - emCherryPickStep1Explain: '核对目标提交的改动范围,避免把依赖前置提交的片段孤立摘过来导致编译失败。', - emCherryPickStep2Title: '将指定提交应用到当前分支(若冲突可解决后 --continue 或 --abort)', - emCherryPickStep2Cmd: 'git cherry-pick "目标提交哈希"', - emCherryPickStep2Explain: '会在当前分支生成一笔包含相同改动的新提交;如需先检查改动不自动提交,可加 -n (--no-commit)。', - emCherryPickPrinciple: 'cherry-pick 会把目标提交与其父节点的 diff 作为新提交重放到当前 HEAD,常用于线上 hotfix 同步。', - // Gitignore categories & names - giCatLang: '语言与运行时', - giCatFrontend: '前端框架', - giCatOS: '操作系统', - giCatIDE: '编辑器与 IDE', - giNameMacOS: 'macOS 系统隐藏文件', - giNameWindows: 'Windows 系统缩略图与临时项', - emUndoTags: '撤销提交,撤销commit,保留代码,reset soft', - emAmendTags: '漏提文件,修改提交备注,amend,追加文件', - emRecoverTags: '恢复误删分支,找回代码,reflog,reset hard恢复', - emWrongBranchTags: '提交错分支,移花接木,挪移提交,master误提交', - emPullAbortTags: '撤销pull,放弃合并,merge abort,冲突回退', - emRevertTags: '远程回滚,revert,线上回退,反向提交' - }, - 'en-US': { - searchEmergencyPlaceholder: 'Describe your Git mishap (e.g., undo commit, missing file, deleted branch, abort merge)...', - searchCommitPlaceholder: 'Enter change summary (supports scope:subject, e.g., auth:fix token refresh)...', - searchGitignorePlaceholder: 'Search tech stacks or OS templates (e.g., Node, Python, Go, Rust, macOS)...', - dropdownTooltip: 'Switch Git Helper mode', - modeEmergency: 'Git Emergency Rescue', - modeCommit: 'Conventional Commit Builder', - modeGitignore: '.gitignore Generator', - emergencySectionTitle: 'Common Git Mishaps & Recovery Guides ({count})', - primaryCommandHeader: '#### Primary Command (Press Enter to Copy)', - incidentPrefix: '### Scenario: {title}', - stepsHeader: '#### Step-by-Step Guide (Pick the matching case; do not run all blindly)', - enterToCopySuffix: ' (Press Enter to Copy)', - principleHeader: '#### How Git Works & Pitfalls to Avoid', - metaCategoryTitle: 'Category', - metaDifficultyTitle: 'Difficulty', - copyPrimaryCommand: 'Copy Primary Command', - copyGuideWithNotes: 'Copy Full Guide with Notes', - commitSectionTitle: 'Select Conventional Commits Type', - commitPreviewHeader: '### Commit Command Preview (Bash / zsh / Git Bash)', - commitInputHintDefault: 'Enter a commit subject first', - commitMessageHeader: '#### Generated Commit Message', - commitTypeInfoHeader: '#### Type Reference (`{type}`)', - commitMeaningLabel: '- **Meaning**: {meaning}', - commitScopeLabel: '- **When to Use**: {description}', - commitExamplesHeader: '#### Examples', - copyFullGitCommit: 'Copy Full git commit Command', - copyCommitMessageOnly: 'Copy Commit Message Only', - copyTypePrefix: 'Copy Type Prefix {type}:', - toggleBreakingOn: 'Enable Breaking Change (!)', - toggleBreakingOff: 'Disable Breaking Change (!)', - commitBreakingBadge: 'BREAKING (!)', - commitSectionTitleBreaking: 'Select Conventional Commits Type (BREAKING CHANGE ! enabled)', - gitignoreSectionTitle: '.gitignore Composer ({stacks} [[stacks:stack|stacks]] selected, {rules} unique [[rules:rule|rules]] · Enter to toggle / Ctrl+Enter to copy)', - gitignoreItemSubtitle: '{category} · {count} [[count:rule|rules]]', - gitignoreTagChecked: 'Selected', - gitignoreTagUnchecked: 'Unselected', - gitignorePreviewHeader: '### Merged `.gitignore` Preview (Deduplicated)', - metaSelectedStacksTitle: 'Selected Stacks', - metaNoneSelected: 'None', - metaTotalRulesTitle: 'Unique Rules', - metaTotalRulesText: '{count} [[count:rule|rules]]', - copyMergedGitignore: 'Copy Merged .gitignore', - actionUncheck: 'Deselect', - actionCheck: 'Select', - guideScenarioPrefix: 'Scenario: {title}', - guideIntro: 'Review each option below and run only the command that fits your state; do not run all steps sequentially.', - commitPlaceholder: 'Enter a concise summary of your change', - commitErrControlChars: 'Commit subject contains invisible control characters. Please remove them.', - commitErrEmpty: 'Commit subject cannot be empty. Briefly describe the purpose of this change.', - gitignoreGeneratedHeader: '# Generated by ZTools Git Helper', - gitignoreCustomRulesHeader: '### Custom Rules ###', - safetySafe: 'Safe / Lossless', - safetyCaution: 'Check Carefully', - safetyDanger: 'Destructive Warning', - diffBeginner: 'Beginner Friendly', - diffMedium: 'Intermediate', - diffExpert: 'Expert Only', - // Emergency items - emUndoTitle: 'Undo the last commit while keeping changes in the working tree', - emUndoCat: 'Commit Undo', - emUndoStep1Title: 'Create a backup branch at current HEAD, then soft-reset the unpushed commit', - emUndoStep1Explain: 'Requires a local branch with at least two commits. Stops if the backup branch already exists so it never overwrites prior backups. Working files and staged changes stay intact.', - emUndoStep2Title: 'Optionally unstage files as well (return to modified working tree)', - emUndoStep2Explain: 'Run after step 1; only resets the staging index without moving HEAD again. Working files are preserved.', - emUndoPrinciple: 'Inspect git status and git log first. Only undo unpushed commits; use git revert for commits already pushed to shared branches. The backup branch preserves the commit, not uncommitted files.', - emAmendTitle: 'Forgot a file in the last commit or made a typo in the commit message', - emAmendCat: 'Commit Undo', - emAmendStep1Title: 'Stage the missing file to fold into the previous commit (keep message)', - emAmendStep1Cmd: 'git add -- "path/to/missing-file"', - emAmendStep1Explain: 'Replace the quoted path with the exact file to add, then run git diff --cached to verify staged changes before amending.', - emAmendStep2Title: 'After verifying staged files, back up the old commit and amend', - emAmendStep2Explain: 'Use only on unpushed commits. Stops if the backup branch exists; pick a new name to retry. To edit only the message, check staged files first and run git commit --amend.', - emAmendPrinciple: 'git commit --amend replaces the tip commit with a new commit object (safe only before pushing to a shared branch).', - emRecoverTitle: 'Accidentally ran git reset --hard or deleted an unmerged local branch', - emRecoverCat: 'Disaster Recovery', - emRecoverStep1Title: 'Step 1: Inspect HEAD reflog history to find the hash before the mistake (e.g., a1b2c3d)', - emRecoverStep1Explain: 'Verify the exact commit hash from the log. Expired entries may be garbage-collected, and uncommitted changes usually cannot be recovered via reflog.', - emRecoverStep2Title: 'Step 2: Create a recovery branch from the verified commit hash', - emRecoverStep2Cmd: 'git branch recovered-branch "verified-commit-hash"', - emRecoverStep2Explain: 'Replace the quoted placeholder with the verified hash. This creates a branch without touching your working tree; do not assume HEAD@{1} is the target. For never-checked-out deleted branches, check the "was " output from git branch -D.', - emRecoverPrinciple: 'Git commit objects are immutable once created; until garbage collection expires them, reflog acts as your local safety net.', - emWrongBranchTitle: 'Committed directly to main/master instead of a new feature branch', - emWrongBranchCat: 'Branch Rescue', - emWrongBranchStep1Title: 'Step 1: Create and switch to a new branch, keeping commits and working changes', - emWrongBranchStep1Explain: 'Choose a branch name that does not exist yet. The original branch stays untouched for now.', - emWrongBranchStep2Title: 'Step 2: Inspect branch topology before deciding how to clean up the original branch', - emWrongBranchStep2Explain: 'Your work is now safe on the new branch. Use revert if the original branch was already pushed; otherwise inspect commits before adjusting it rather than running a blind hard reset.', - emWrongBranchPrinciple: 'Protect your work on a new branch first, then verify whether the original branch is shared. git switch requires Git 2.23 or newer.', - emPullAbortTitle: 'git pull or merge caused messy conflicts and you want to abort back to pre-merge state', - emPullAbortCat: 'Conflict Rescue', - emPullAbortStep1Title: 'If a merge conflict is currently in progress, abort the merge', - emPullAbortStep1Explain: 'Applies only to an active merge; use git rebase --abort for rebase conflicts. Back up uncommitted work first, as abort may not restore pre-existing dirty changes.', - emPullAbortStep2Title: 'If the merge already completed, inspect pre-merge state first (do not run step 1)', - emPullAbortStep2Explain: 'This is an alternative case, not a follow-up to abort. Back up files and create a recovery branch; verify ORIG_HEAD was not overwritten before reverting or resetting.', - emPullAbortPrinciple: 'Distinguish between an in-progress merge and a completed merge. ORIG_HEAD is updated by subsequent commands, so always inspect it before acting.', - emRevertTitle: 'Bad code was already pushed to a shared remote branch and must be rolled back safely', - emRevertCat: 'Remote Rollback', - emRevertStep1Title: 'Create an inverse commit without rewriting shared history', - emRevertStep1Explain: 'Confirm HEAD is the normal commit to undo and stash/save local changes first. Merge commits require choosing the mainline parent carefully rather than assuming -m 1.', - emRevertStep2Title: 'Verify current branch and upstream before pushing normally (no --force needed)', - emRevertStep2Explain: 'Test the revert commit and verify branch, remote, and upstream before pushing. Do not assume every repository uses main as its default branch.', - emRevertPrinciple: 'Never force-push after git reset --hard on shared branches; creating an inverse commit with git revert preserves team history.', - // Commit types - ctFeatMeaning: 'New feature or user-facing capability', - ctFeatDesc: 'Adds functionality users can invoke or experience', - ctFeatEx1: 'feat(auth): add email verification code login', - ctFeatEx2: 'feat(export): support exporting reports to CSV', - ctFixMeaning: 'Bug fix or production issue resolution', - ctFixDesc: 'Fixes incorrect behavior, crashes, or unexpected errors', - ctFixEx1: 'fix(network): release socket connection after request timeout', - ctFixEx2: 'fix(ui): improve table border contrast in dark mode', - ctRefactorMeaning: 'Code refactoring (no external behavior change)', - ctRefactorDesc: 'Restructures code while keeping public behavior identical', - ctRefactorEx1: 'refactor(order): extract payment logic from order service', - ctPerfMeaning: 'Performance and memory optimization', - ctPerfDesc: 'Improves speed or reduces CPU/memory usage', - ctPerfEx1: 'perf(search): add index for list query to avoid full table scan', - ctTestMeaning: 'Add or improve integration and edge-case tests', - ctTestDesc: 'Adds or updates test cases without changing production logic', - ctTestEx1: 'test(cart): cover insufficient stock and duplicate checkout', - ctDocsMeaning: 'Documentation and comment updates', - ctDocsDesc: 'Updates docs, comments, or README files only', - ctDocsEx1: 'docs(readme): add local development and build instructions', - ctChoreMeaning: 'Build scripts, dependency updates, or tooling chores', - ctChoreDesc: 'Maintenance tasks like build config, CI, or dependency bumps', - ctChoreEx1: 'chore(deps): upgrade TypeScript and bundler versions', - ctBuildMeaning: 'Build system or external dependency changes', - ctBuildDesc: 'Changes affecting build output or bundler toolchains (e.g., Vite, Webpack, npm)', - ctBuildEx1: 'build(vite): enable production chunk splitting and minification', - ctCiMeaning: 'CI/CD pipeline and automation configuration', - ctCiDesc: 'Updates to GitHub Actions, GitLab CI, or other workflow scripts', - ctCiEx1: 'ci(actions): add automated unit test check on pull requests', - ctStyleMeaning: 'Code formatting and whitespace only (no logic change)', - ctStyleDesc: 'Pure formatting tweaks like indentation, quotes, or semicolons', - ctStyleEx1: 'style(lint): standardize single quotes and trailing newlines', - ctRevertMeaning: 'Revert a previous commit', - ctRevertDesc: 'Creates an inverse commit undoing an earlier change', - ctRevertEx1: 'revert(auth): revert token check commit that broke sessions', - // 9 new high-frequency emergency guides - emStashRecoverTitle: 'Accidentally dropped or cleared a git stash and want to recover it', - emStashRecoverCat: 'Disaster Recovery', - emStashRecoverTags: 'stash drop,recover stash,dangling commit,fsck', - emStashRecoverStep1Title: 'Step 1: Scan dangling commit objects (dropped stashes remain until GC)', - emStashRecoverStep1Explain: 'Lists dangling commit hashes; inspect candidates with git show to find the "WIP on ..." stash commit.', - emStashRecoverStep2Title: 'Step 2: Apply the verified stash commit back to your working tree', - emStashRecoverStep2Cmd: 'git stash apply "verified-dangling-hash"', - emStashRecoverStep2Explain: 'Replace the placeholder with the verified commit hash; ensure your working tree is clean first.', - emStashRecoverPrinciple: 'git stash drop only removes the reference; underlying commit objects stay in .git/objects until garbage-collected.', - emDetachedHeadTitle: 'Made commits in detached HEAD state and want to save them on a branch', - emDetachedHeadCat: 'Branch Rescue', - emDetachedHeadTags: 'detached head,save commits,create branch', - emDetachedHeadStep1Title: 'Create and switch to a new branch at the current detached commit', - emDetachedHeadStep1Explain: 'Attaches your commits to a proper branch immediately while keeping working tree and index intact.', - emDetachedHeadStep2Title: 'If you already switched away, find the hash via reflog first', - emDetachedHeadStep2Cmd: 'git reflog -n 15', - emDetachedHeadStep2Explain: 'Locate the last commit hash from detached HEAD, then run git branch rescue/detached .', - emDetachedHeadPrinciple: 'Detached HEAD points directly to a commit instead of a branch; creating a branch ref saves it from becoming orphaned.', - emCleanUntrackedTitle: 'Remove leftover untracked files or build artifacts safely', - emCleanUntrackedCat: 'Workspace Cleanup', - emCleanUntrackedTags: 'clean,untracked files,remove temp files', - emCleanUntrackedStep1Title: 'Step 1: Preview what will be deleted using dry-run (never delete blindly)', - emCleanUntrackedStep1Explain: '-n performs a dry run and -d includes untracked directories; double-check the output before deleting.', - emCleanUntrackedStep2Title: 'Step 2: Execute cleanup after verifying the preview list', - emCleanUntrackedStep2Explain: 'Permanently removes untracked files and folders (cannot be undone via Git); add -x only if you also want ignored artifacts removed.', - emCleanUntrackedPrinciple: 'Untracked files are not stored in Git objects and cannot be recovered with reflog—always preview with -nd first.', - emEditMsgTitle: 'Edit only the last unpushed commit message without changing code', - emEditMsgCat: 'Commit Undo', - emEditMsgTags: 'edit commit message,amend,reword', - emEditMsgStep1Title: 'Check git status first to ensure no unintended files are staged', - emEditMsgStep1Explain: 'Any staged files would be folded into --amend unless --only is used; inspect status first.', - emEditMsgStep2Title: 'Rewrite only the commit message with --amend --only', - emEditMsgStep2Cmd: 'git commit --amend --only -m "new commit message"', - emEditMsgStep2Explain: '--only ignores staged changes and updates only the tip commit message (for unpushed commits only).', - emEditMsgPrinciple: 'git commit --amend creates a new commit hash replacing HEAD, so avoid amending commits already pushed to shared branches.', - emRebaseAbortTitle: 'Stuck in messy git rebase conflicts and want to abort or continue', - emRebaseAbortCat: 'Conflict Rescue', - emRebaseAbortTags: 'rebase,rebase conflict,rebase abort,rebase continue', - emRebaseAbortStep1Title: 'Abort the rebase and restore the branch to its pre-rebase state', - emRebaseAbortStep1Explain: 'Safely cancels an in-progress rebase and resets HEAD back to where it started.', - emRebaseAbortStep2Title: 'Or after resolving conflicts and running git add, continue rebasing', - emRebaseAbortStep2Explain: 'Stage resolved files with git add first, then run --continue to replay remaining commits.', - emRebaseAbortPrinciple: 'Rebase replays commits one by one; git rebase --abort cleanly rolls back the entire operation at any point.', - emDiscardFileTitle: 'Discard local edits in a single file and restore it to the last commit', - emDiscardFileCat: 'Workspace Cleanup', - emDiscardFileTags: 'discard file,restore file,undo file changes', - emDiscardFileStep1Title: 'Inspect the diff first to make sure nothing worth keeping is lost', - emDiscardFileStep1Cmd: 'git diff -- "path/to/file"', - emDiscardFileStep1Explain: 'Discarding unstaged edits is irreversible; review the diff before restoring.', - emDiscardFileStep2Title: 'Restore that single file without touching other working changes', - emDiscardFileStep2Cmd: 'git restore -- "path/to/file"', - emDiscardFileStep2Explain: 'Restores only the specified file from the index/HEAD; on Git < 2.23 use git checkout -- "path/to/file".', - emDiscardFilePrinciple: 'git restore (Git 2.23+) separates file restoration from branch switching, preventing accidental checkout mistakes.', - emCleanBranchesTitle: 'Safely clean up old local branches already merged into main', - emCleanBranchesCat: 'Branch Rescue', - emCleanBranchesTags: 'clean branches,merged branches,delete branch', - emCleanBranchesStep1Title: 'List local branches already merged into the current branch', - emCleanBranchesStep1Explain: 'Run this while on your main branch and review the list, keeping protected branches like main/master/dev.', - emCleanBranchesStep2Title: 'Delete a merged branch safely (-d refuses unmerged branches)', - emCleanBranchesStep2Cmd: 'git branch -d "merged-branch-name"', - emCleanBranchesStep2Explain: 'Lowercase -d checks merge status automatically so unmerged work is never accidentally deleted.', - emCleanBranchesPrinciple: 'git branch -d guards against deleting unmerged commits; combine with git fetch --prune to clear stale remote refs.', - emUnstageAddTitle: 'Accidentally staged files with git add and want to unstage without losing edits', - emUnstageAddCat: 'Commit Undo', - emUnstageAddTags: 'unstage,undo git add,restore staged', - emUnstageAddStep1Title: 'Unstage a specific file while preserving your working tree edits', - emUnstageAddStep1Cmd: 'git restore --staged -- "path/to/file"', - emUnstageAddStep1Explain: 'Removes the file from the staging index only; your local edits remain untouched.', - emUnstageAddStep2Title: 'Or unstage all staged files at once', - emUnstageAddStep2Explain: 'Handy after accidentally running git add . so you can re-stage files selectively.', - emUnstageAddPrinciple: 'git restore --staged modifies only the index and never alters working directory files.', - emCherryPickTitle: 'Apply a single specific commit from another branch onto the current branch', - emCherryPickCat: 'Branch Rescue', - emCherryPickTags: 'cherry-pick,copy commit,hotfix', - emCherryPickStep1Title: 'Inspect the source branch log to find the target commit hash', - emCherryPickStep1Explain: 'Review what the commit touches to avoid pulling isolated changes that depend on earlier commits.', - emCherryPickStep2Title: 'Cherry-pick the target commit onto your current branch', - emCherryPickStep2Cmd: 'git cherry-pick "target-commit-hash"', - emCherryPickStep2Explain: 'Replays the commit diff as a new commit on HEAD; add -n (--no-commit) to inspect before committing.', - emCherryPickPrinciple: 'cherry-pick applies the diff of a chosen commit onto the current HEAD, commonly used for hotfixes.', - // Gitignore categories & names - giCatLang: 'Language & Runtime', - giCatFrontend: 'Frontend Framework', - giCatOS: 'Operating System', - giCatIDE: 'Editor & IDE', - giNameMacOS: 'macOS System Files', - giNameWindows: 'Windows Thumbnails & Temp Files', - emUndoTags: 'undo commit,keep changes,reset soft', - emAmendTags: 'missing file,fix commit message,amend', - emRecoverTags: 'recover branch,restore code,reflog,reset hard', - emWrongBranchTags: 'wrong branch,move commit,main branch mistake', - emPullAbortTags: 'abort pull,abort merge,merge conflict', - emRevertTags: 'remote rollback,revert,pushed commit' - } + 'zh-CN': { + searchEmergencyPlaceholder: '搜大白话场景(如:提交错分支、撤销commit、恢复stash、拼音首字母)...', + searchCommitPlaceholder: '输入改动说明(支持 scope:描述,或点右上角打开完整规范提交表单)...', + searchGitignorePlaceholder: '搜索 30+ 技术栈、框架、云原生或系统模板(如:Node、Docker、Swift、Flutter)...', + dropdownTooltip: '切换 Git 助手工作模式', + modeEmergency: 'Git 翻车自救锦囊', + modeCommit: '规范提交生成器', + modeGitignore: '.gitignore 模板合成', + // FilterBar & Shell syntax + shellNamePowerShell: 'Windows PowerShell', + shellNamePosix: 'POSIX (Bash / zsh)', + filterEmergencySummary: '当前终端语法: {shell}({source})', + filterCommitSummary: '当前终端语法: {shell} · 支持表单编写正文与关联 Issue', + filterGitignoreSummary: '已选 {stacks} 个模板 · 去重后 {rules} 条规则 · 支持选目录安全合并写入', + shellSourceAuto: '自动适配', + shellSourceManual: '手动切换', + actionToggleShell: '切换终端语法', + actionOpenCommitForm: '规范提交表单', + actionWriteGitignoreToDir: '写入项目目录', + actionClearStacks: '清空已选', + actionResetDefaultStacks: '恢复默认', + // Empty views + emptyEmergencyTitle: '未匹配到对应的 Git 急救场景', + emptyEmergencyDesc: '换个关键词试试(如:撤销、分支、冲突、stash、reflog),或清空搜索框查看全部方案。', + emptyGitignoreTitle: '未匹配到对应的 .gitignore 模板', + emptyGitignoreDesc: '尝试搜索语言、框架或工具名(如:Node、Python、Docker、Swift、Flutter、Unity)。', + actionClearSearch: '清空搜索词', + // Emergency section & detail + emergencySectionTitle: '高频翻车现场与自救指南(共 {count} 项)', + primaryCommandHeader: '#### 首选命令(回车复制)', + incidentPrefix: '### 适用场景:{title}', + stepsHeader: '#### 分步可执行命令({shell} · 按所处情形选择,不要整段盲目连续执行)', + stepLabel: '步骤 {index}', + enterToCopySuffix: '(回车复制)', + dangerWarningHeader: '#### 危险操作警示', + principleHeader: '#### 底层 Git 原理与防坑说明', + metaCategoryTitle: '场景分类', + metaSafetyTitle: '风险等级', + metaShellTitle: '终端语法', + metaDifficultyTitle: '上手难度', + copyPrimaryCommand: '复制首选救命命令', + copyStepCommand: '复制步骤 {index}', + copyGuideWithNotes: '复制带说明的操作指南', + // Commit mode & form + commitSectionTitle: '选择 Conventional Commits 提交类型', + commitSectionTitleBreaking: '选择 Conventional Commits 提交类型(已开启破坏性变更 !)', + commitPreviewHeader: '### 规范提交命令预览({shell})', + commitInputHintDefault: '请先输入提交说明,或按 Ctrl+E 打开完整提交表单', + commitMessageHeader: '#### 生成的 Commit Message', + commitTypeInfoHeader: '#### 类型说明(`{type}`)', + commitMeaningLabel: '- **含义**:{meaning}', + commitScopeLabel: '- **适用边界**:{description}', + commitExamplesHeader: '#### 示例', + copyFullGitCommit: '复制完整 git commit 命令', + copyCommitMessageOnly: '仅复制提交说明', + copyTypePrefix: '复制类型前缀 {type}:', + toggleBreakingOn: '开启破坏性变更标记 (!)', + toggleBreakingOff: '关闭破坏性变更标记 (!)', + commitBreakingBadge: '破坏性变更 (!)', + commitFormNavTitle: '规范提交生成器 (Conventional Commits)', + commitFormTypeLabel: '提交类型 (type)', + commitFormScopeLabel: '作用域 (scope,可选)', + commitFormScopePlaceholder: '如:auth、ui、api、cli(不填则省略括号)', + commitFormSubjectLabel: '改动摘要 (subject,必填)', + commitFormSubjectPlaceholder: '用简洁中文或英文说明本次改动的意图', + commitFormBodyLabel: '详细说明 (body,可选)', + commitFormBodyPlaceholder: '补充改动背景、实现要点或影响范围(支持多行)', + commitFormFooterLabel: '关联 Issue / Footer(可选)', + commitFormFooterPlaceholder: '如:Closes #123 或 Refs #456', + commitFormBreakingLabel: '破坏性变更', + commitFormBreakingCheckbox: '标记为破坏性变更 (!)', + commitFormBreakingDescLabel: '破坏性变更说明(可选)', + commitFormBreakingDescPlaceholder: '如:移除旧版 v1 接口,调用方请迁移至 v2', + commitFormShellLabel: '目标终端语法', + commitFormPreviewTitle: '实时命令与提交信息预览', + commitFormCopyCommand: '复制完整 git commit 命令', + commitFormCopyMessage: '仅复制提交说明', + commitFormReset: '重置表单', + commitFormCopiedCommandToast: '已复制完整 git commit 命令', + commitFormCopiedMessageToast: '已复制提交说明', + commitFormInvalidToast: '请先完善有效的改动摘要', + commitErrScopeInvalid: '作用域仅支持中英文、数字及 _ - . /(不超过 23 字符)', + commitErrControlChars: '提交说明含有不可见的控制字符,请删除后重新输入', + commitErrEmpty: '提交说明不能为空,请简述本次修改的目的', + commitPlaceholder: '请填写本次改动的简要说明', + // Gitignore mode & disk write + gitignoreSectionTitle: '.gitignore 模板多选合成(已选 {stacks} 个栈,去重后 {rules} 条规则 · Enter 勾选 / Ctrl+Enter 复制)', + gitignoreItemSubtitle: '{category} · 含 {count} 条忽略规则', + gitignoreTagChecked: '已勾选合并', + gitignoreTagUnchecked: '未选', + gitignorePreviewHeader: '### 合成后的 `.gitignore` 预览(自动去重 · 写入目录时保留已有规则)', + metaSelectedStacksTitle: '已合并技术栈', + metaNoneSelected: '未选择', + metaTotalRulesTitle: '去重后规则总数', + metaTotalRulesText: '{count} 条', + copyMergedGitignore: '复制合成后的 .gitignore 全文', + writeMergedGitignore: '选择项目目录并安全合并写入 .gitignore', + actionUncheck: '取消勾选', + actionCheck: '勾选', + gitignoreEmptyWriteWarn: '请先勾选至少一个技术栈模板', + gitignoreSelectDirTitle: '选择要写入或合并 .gitignore 的项目根目录', + gitignoreWriteCreatedTitle: '已创建 .gitignore', + gitignoreWriteCreatedMsg: '已写入 {added} 条规则到 {path}', + gitignoreWriteMergedTitle: '已安全合并写入 .gitignore', + gitignoreWriteMergedMsg: '新增 {added} 条规则(跳过已有重复 {skipped} 条):{path}', + gitignoreWriteUnchangedTitle: '无需更新 .gitignore', + gitignoreWriteUnchangedMsg: '目标文件已包含全部所选规则(跳过重复 {skipped} 条)', + gitignoreWriteFailedTitle: '写入 .gitignore 失败', + errHostUnsupported: '当前运行环境不支持宿主能力({method}),请在 ZTools 客户端中使用', + errHostResponseInvalid: '宿主返回了无效的响应格式', + errHostCallFailed: '宿主能力调用失败({method})', + errHostPermissionDenied: '缺少所需文件或目录访问权限({code}),请重新选择项目目录授权', + errHostWithCode: '操作失败(错误码:{code})', + // Guide & Headers + guideScenarioPrefix: '场景:{title}', + guideShellPrefix: '终端语法:{shell}', + guideIntro: '以下是说明,请逐项核对后单独执行命令;不需要把全部步骤连续运行。', + gitignoreGeneratedHeader: '# 由 ZTools Git 助手生成', + gitignoreCustomRulesHeader: '### 自定义规则 ###', + safetySafe: '安全无损', + safetyCaution: '注意检查', + safetyDanger: '有损警告', + diffBeginner: '小白推荐', + diffMedium: '中等', + diffExpert: '专家慎用', + // Emergency items + emUndoTitle: '刚 commit 了,但想撤销这次提交并保留修改在工作区继续改', + emUndoCat: '提交后悔药', + emUndoStep1Title: '为当前提交建立恢复分支,再撤销最近一次尚未推送的提交', + emUndoStep1Explain: '只适用于至少有两次提交的本地分支。恢复分支已存在时会停止,请另取新名字;不会覆盖旧恢复点。工作文件与暂存内容保持不变。', + emUndoStep2Title: '若想同时取消 git add 退回未暂存状态(可选)', + emUndoStep2Explain: '在上一步之后执行;只取消暂存,不再回退 HEAD。工作文件保留,原来的暂存划分会取消。', + emUndoPrinciple: '先核对 git status 和 git log。只撤销一次未推送提交;已推送到共享分支的提交使用 revert。恢复分支保留原提交,不包含未提交文件的独立副本。', + emUndoWarning: '仅限尚未 push 到公共分支的本地提交;若已推送,请改用「撤销已 push 的提交 (git revert)」。', + emAmendTitle: '刚 commit 完发现漏提了一个文件,或者提交备注写错了', + emAmendCat: '提交后悔药', + emAmendStep1Title: '把遗漏的文件加入暂存区并合并进上一次提交(不改备注)', + emAmendStep1Cmd: 'git add -- "需要补交的文件路径"', + emAmendStep1Explain: '把引号内替换为明确要补交的文件;再用 git diff --cached 检查全部暂存内容,避免把其他工作一起提交。', + emAmendStep2Title: '确认暂存内容后,保存旧提交再补交(不改备注)', + emAmendStep2Explain: '只用于未推送提交。备份分支重名时停止,换新名字后重试;若只改备注,先核对暂存区,再单独使用 git commit --amend。', + emAmendPrinciple: 'amend 会用一个新的 Commit 对象替换当前分支顶端的旧 Commit(仅限尚未 push 到公共分支时使用)。', + emAmendWarning: '切勿对已推送到共享分支的提交执行 --amend,否则会改写历史导致协作者推送冲突。', + emRecoverTitle: '手滑执行了 git reset --hard 或误删了本地未合并分支,想找回代码', + emRecoverCat: '绝境抢救', + emRecoverStep1Title: '第一步:查看本地所有 HEAD 历史移动轨迹,找到翻车前的短哈希(如 a1b2c3d)', + emRecoverStep1Explain: '从日志中确认要恢复的提交。记录可能已过期或被清理,未提交的文件修改通常不能依靠 reflog 找回。', + emRecoverStep2Title: '第二步:基于翻车前的 commit 哈希新建或恢复分支', + emRecoverStep2Cmd: 'git branch recovered-branch "确认后的提交哈希"', + emRecoverStep2Explain: '将引号内替换为已核对的提交哈希,仅创建恢复分支,不切换或改写当前工作文件;不要假定 HEAD@{1} 就是正确版本。误删的分支若从未检出过,HEAD 的 reflog 里可能没有它,可查看删除时 git branch -D 输出的“was 短哈希”。', + emRecoverPrinciple: 'Git 的提交对象一旦生成就是不可变的,只要未触发过期 GC,reflog 就是时光机黑匣子。', + emWrongBranchTitle: '本来应该在新分支开发,结果不小心直接 commit 到了 main/master 分支', + emWrongBranchCat: '分支纠错', + emWrongBranchStep1Title: '第一步:新建并切换到工作分支,保留提交和当前修改', + emWrongBranchStep1Explain: '新名字不能与已有分支重复。原分支暂时保留,不触碰工作区。', + emWrongBranchStep2Title: '第二步:核对分支与提交关系,再决定如何处理原分支', + emWrongBranchStep2Explain: '当前工作已转到新分支。原分支若已共享,使用 revert;若尚未推送,核对要保留的提交后再调整原分支,不直接运行硬重置。', + emWrongBranchPrinciple: '先建立新分支保护工作,再核对原分支是否已经共享。这里不会自动清理原分支的提交;git switch 需要 Git 2.23 或更新版本。', + emWrongBranchWarning: '先创建新分支保护提交,再根据原分支是否已推送选择回退或 revert,切勿先对原分支执行 git reset --hard。', + emPullAbortTitle: '刚执行了 git pull 或 merge 结果冲突一团糟,想立即回到合并前状态', + emPullAbortCat: '冲突拆弹', + emPullAbortStep1Title: '若正处于合并冲突中断状态,一键中止合并', + emPullAbortStep1Explain: '只适用于正在进行的 merge;rebase 冲突单独用 git rebase --abort。先另存未提交文件及手动解决冲突的内容,abort 不能保证还原合并前所有未提交改动。', + emPullAbortStep2Title: '若合并已经完成,先核对合并前位置;不要接着执行上一步', + emPullAbortStep2Explain: '这是另一种情形,不是 abort 后的下一步。先保存文件副本并新建备份分支;确认该引用未被后续操作改写后,再决定 revert 或本地回退。', + emPullAbortPrinciple: '区分正在合并与已经完成,不能把两个方案连续运行。ORIG_HEAD 会被后续操作更新,使用前必须核对实际提交。', + emRevertTitle: '错误代码已经 push 到了远程公共分支,需要安全回滚且不破坏团队历史', + emRevertCat: '线上回滚', + emRevertStep1Title: '生成一笔反向抵消提交(不动历史时间线)', + emRevertStep1Explain: '确认 HEAD 是要撤销的普通提交,先保存当前修改。合并提交需要核对主线父节点,不能一律选择 -m 1;出现冲突后应处理或 git revert --abort。', + emRevertStep2Title: '核对当前分支与上游后再正常推送(无需危险的 --force)', + emRevertStep2Explain: '测试反向提交并核对当前分支、远端和上游后再正常推送。不要把固定的 main 当成所有项目的目标分支。', + emRevertPrinciple: '公共分支严禁 git reset --hard 后强推(force push),使用 git revert 新增反向补丁才是工程规范。', + // Commit types + ctFeatMeaning: '新增业务功能或特性', + ctFeatDesc: '新增用户能用到或可调用的功能', + ctFeatEx1: 'feat(auth): 新增邮箱验证码登录', + ctFeatEx2: 'feat(export): 支持把报表导出为 CSV', + ctFixMeaning: '修复 Bug 或生产异常', + ctFixDesc: '修复错误行为、崩溃或异常结果', + ctFixEx1: 'fix(network): 修复请求超时后连接没有释放', + ctFixEx2: 'fix(ui): 修复深色模式下表格边框对比度不足', + ctRefactorMeaning: '代码重构(不改变外部行为)', + ctRefactorDesc: '调整代码结构,对外功能和行为不变', + ctRefactorEx1: 'refactor(order): 把支付逻辑从订单服务中拆分出来', + ctPerfMeaning: '性能与内存优化', + ctPerfDesc: '提升速度,或降低内存、CPU 等资源占用', + ctPerfEx1: 'perf(search): 为列表查询增加索引,避免全表扫描', + ctTestMeaning: '新增或完善集成与异常测试', + ctTestDesc: '只新增或修改测试用例,不改功能代码', + ctTestEx1: 'test(cart): 补充库存不足与重复下单的测试', + ctDocsMeaning: '技术文档与注释更新', + ctDocsDesc: '只改文档、注释或 README', + ctDocsEx1: 'docs(readme): 补充本地开发与构建说明', + ctChoreMeaning: '构建脚本、依赖升级或工程杂务', + ctChoreDesc: '构建脚本、依赖升级、CI 配置等不影响功能的杂项', + ctChoreEx1: 'chore(deps): 升级 TypeScript 与构建工具版本', + ctBuildMeaning: '构建系统或外部依赖变更', + ctBuildDesc: '影响构建产物或打包工具链的改动(如 Webpack、Vite、npm 脚本)', + ctBuildEx1: 'build(vite): 启用生产构建产物分包与压缩', + ctCiMeaning: 'CI/CD 流水线与自动化配置', + ctCiDesc: '修改 GitHub Actions、GitLab CI 等持续集成脚本', + ctCiEx1: 'ci(actions): 增加拉取请求自动单测检查流程', + ctStyleMeaning: '代码格式与空白调整(不影响逻辑)', + ctStyleDesc: '仅涉及缩进、分号、格式化等纯代码风格改动', + ctStyleEx1: 'style(lint): 统一全仓单引号与末尾换行风格', + ctRevertMeaning: '回滚先前的某次提交', + ctRevertDesc: '撤销已合入的历史提交,生成反向抵消记录', + ctRevertEx1: 'revert(auth): 回滚引起会话失效的令牌校验提交', + // 9 high-frequency emergency guides + emStashRecoverTitle: '误删了 git stash(stash drop / clear),想找回被删的暂存改动', + emStashRecoverCat: '绝境抢救', + emStashRecoverTags: 'stash误删,找回stash,dangling commit,fsck', + emStashRecoverStep1Title: '第一步:扫描仓库里悬空的提交对象(已按当前终端自动适配语法)', + emStashRecoverStep1Explain: '列出所有悬空提交哈希;配合 git show <哈希> 辨认包含 WIP on ... 的那条 stash 提交。', + emStashRecoverStep2Title: '第二步:确认哈希后查看改动并重新应用到工作区', + emStashRecoverStep2Cmd: 'git stash apply "确认后的悬空提交哈希"', + emStashRecoverStep2Explain: '将引号内替换为确认无误的 stash 提交哈希,应用前建议先确保工作区干净。', + emStashRecoverPrinciple: 'git stash drop 只是移除了引用指针,底层提交对象在触发 git gc 过期清理前仍留在 .git/objects 中。', + emDetachedHeadTitle: '处于游离头指针(detached HEAD)状态并做了提交,怕切分支丢失代码', + emDetachedHeadCat: '分支纠错', + emDetachedHeadTags: 'detached head,游离头指针,救回提交,新建分支', + emDetachedHeadStep1Title: '直接在当前游离提交上新建并切换到正式分支', + emDetachedHeadStep1Explain: '立即把游离的提交挂到新分支名下,工作区与暂存区内容完整保留。', + emDetachedHeadStep2Title: '若已经切走导致提交看不见,用 reflog 找回哈希后再建分支', + emDetachedHeadStep2Cmd: 'git reflog -n 15', + emDetachedHeadStep2Explain: '找到游离状态下的最后一次提交哈希,然后运行 git branch rescue/detached <哈希> 即可找回。', + emDetachedHeadPrinciple: 'detached HEAD 表示 HEAD 直接指向某个提交而非分支引用,只要为其创建分支引用就不会成为孤儿提交。', + emCleanUntrackedTitle: '工作区堆满未跟踪的临时文件或构建产物,想安全批量清理', + emCleanUntrackedCat: '工作区清理', + emCleanUntrackedTags: 'clean,清理未跟踪文件,untracked,删除临时文件', + emCleanUntrackedStep1Title: '第一步:先用 dry-run 预览将被删除的文件和目录(绝不直接硬删)', + emCleanUntrackedStep1Explain: '-n 表示仅演练不删除,-d 包含未跟踪目录;逐项核对列表,确认没有误删新建的源码文件。', + emCleanUntrackedStep2Title: '第二步:核对无误后再执行清理', + emCleanUntrackedStep2Explain: '永久删除未跟踪文件与目录(不可通过 git 恢复);若还需清理被 .gitignore 忽略的产物,再考虑 -x。', + emCleanUntrackedPrinciple: '未跟踪文件尚未进入 Git 对象库,删除后无法靠 reflog 恢复,务必养成先 -nd 预览再 -fd 执行的习惯。', + emCleanUntrackedWarning: 'git clean -fd 会永久删除未跟踪文件且不进回收站、无法通过 git reflog 找回,务必先运行 git clean -nd 逐条确认!', + emEditMsgTitle: '只想修改最近一次未推送的 commit 提交信息(不改任何代码)', + emEditMsgCat: '提交后悔药', + emEditMsgTags: '修改commit信息,amend,改备注,重命名提交', + emEditMsgStep1Title: '先确认暂存区为空,避免顺手把新改动混进上一次提交', + emEditMsgStep1Explain: '如果暂存区已有文件,会一并被 --amend 合并进去;确认只有目标提交需要改备注。', + emEditMsgStep2Title: '使用 --amend --only 仅修改提交说明', + emEditMsgStep2Cmd: 'git commit --amend --only -m "新的提交说明"', + emEditMsgStep2Explain: '--only 忽略暂存区改动,只改写最近一次提交的 message(仅限尚未推送到公共分支的提交)。', + emEditMsgPrinciple: 'git commit --amend 会生成新的提交哈希替换原 HEAD,因此不要对已推送的共享提交使用。', + emRebaseAbortTitle: 'git rebase 变基过程中冲突太多或操作失误,想中止或解决后继续', + emRebaseAbortCat: '冲突拆弹', + emRebaseAbortTags: 'rebase,变基冲突,rebase abort,rebase continue', + emRebaseAbortStep1Title: '放弃本次变基,一键回到 rebase 开始前的原始状态', + emRebaseAbortStep1Explain: '立即终止正在进行的变基并恢复分支指针;不会影响已经提交的历史。', + emRebaseAbortStep2Title: '若已手动解决冲突文件,标记已解决并继续变基', + emRebaseAbortStep2Explain: '先对解决完冲突的文件执行 git add,再运行 --continue 推进下一笔提交。', + emRebaseAbortPrinciple: 'rebase 是逐笔重放提交的过程,中途随时可用 --abort 完整撤回,无需手忙脚乱删分支。', + emDiscardFileTitle: '改乱了单个文件,只想放弃这个文件的本地修改并恢复原样', + emDiscardFileCat: '工作区清理', + emDiscardFileTags: '撤销单文件,还原文件,restore,checkout,放弃修改', + emDiscardFileStep1Title: '先查看该文件的具体改动,确认没有需要保留的片段', + emDiscardFileStep1Cmd: 'git diff -- "需要还原的文件路径"', + emDiscardFileStep1Explain: '丢弃工作区修改不可撤销,先通过 diff 核对一遍再恢复。', + emDiscardFileStep2Title: '将该文件还原为暂存区或最近一次提交的内容', + emDiscardFileStep2Cmd: 'git restore -- "需要还原的文件路径"', + emDiscardFileStep2Explain: '只影响指定文件,不动其他工作区改动;Git 2.23 以下版本可用 git checkout -- "文件路径"。', + emDiscardFilePrinciple: 'git restore 是 Git 2.23+ 拆分出的专用文件还原命令,语义比旧版 git checkout 更清晰且不易误切分支。', + emDiscardFileWarning: 'git restore 会直接覆盖该文件未暂存的本地修改且无法通过 git reflog 找回,执行前请务必先 git diff 确认!', + emCleanBranchesTitle: '本地积压了大量已经合并到主分支的旧分支,想安全批量清理', + emCleanBranchesCat: '分支纠错', + emCleanBranchesTags: '清理分支,已合并分支,删除分支,branch merged', + emCleanBranchesStep1Title: '先查看已合并到当前分支的所有本地分支列表', + emCleanBranchesStep1Explain: '确认当前已在主分支(如 main),核对输出结果,排除 main/master/dev 等常驻分支。', + emCleanBranchesStep2Title: '安全删除指定的已合并分支(未合并分支会被 -d 拒绝)', + emCleanBranchesStep2Cmd: 'git branch -d "已合并的旧分支名"', + emCleanBranchesStep2Explain: '使用小写 -d 而非大写 -D,Git 会自动校验分支是否已完全合并,防止误删未合入代码。', + emCleanBranchesPrinciple: 'git branch -d 内置合并状态检查,配合 git fetch --prune 可顺便清理远端已删除的追踪引用。', + emUnstageAddTitle: '误把不需要的文件 git add 进了暂存区,想取消暂存但保留本地代码', + emUnstageAddCat: '提交后悔药', + emUnstageAddTags: '取消暂存,取消git add,unstage,restore staged', + emUnstageAddStep1Title: '取消指定文件的暂存状态(工作区代码原样保留)', + emUnstageAddStep1Cmd: 'git restore --staged -- "误暂存的文件路径"', + emUnstageAddStep1Explain: '仅把文件移出暂存区(index),绝不会丢失工作区里刚写的代码。', + emUnstageAddStep2Title: '若要一次性取消全部已暂存文件', + emUnstageAddStep2Explain: '适合误执行了 git add . 后一键撤回全部暂存,之后再按需逐个添加。', + emUnstageAddPrinciple: 'git restore --staged 只修改暂存索引,不触碰工作目录,是完全无损的安全操作。', + emCherryPickTitle: '只想把另一个分支上的某一笔特定提交精准摘取到当前分支', + emCherryPickCat: '分支纠错', + emCherryPickTags: 'cherry-pick,摘取提交,跨分支复制提交,热修复', + emCherryPickStep1Title: '先查看源分支提交日志,确认目标提交的短哈希', + emCherryPickStep1Explain: '核对目标提交的改动范围,避免把依赖前置提交的片段孤立摘过来导致编译失败。', + emCherryPickStep2Title: '将指定提交应用到当前分支(若冲突可解决后 --continue 或 --abort)', + emCherryPickStep2Cmd: 'git cherry-pick "目标提交哈希"', + emCherryPickStep2Explain: '会在当前分支生成一笔包含相同改动的新提交;如需先检查改动不自动提交,可加 -n (--no-commit)。', + emCherryPickPrinciple: 'cherry-pick 会把目标提交与其父节点的 diff 作为新提交重放到当前 HEAD,常用于线上 hotfix 同步。', + // Gitignore categories & names + giCatLang: '语言与运行时', + giCatFrontend: '前端与跨端框架', + giCatDevOps: '云原生与运维', + giCatDataDocs: '数据科学与文档', + giCatOS: '操作系统', + giCatIDE: '编辑器与 IDE', + giNameMacOS: 'macOS 系统隐藏文件', + giNameWindows: 'Windows 系统缩略图与临时项', + giNameLinux: 'Linux 桌面与临时文件', + emUndoTags: '撤销提交,撤销commit,保留代码,reset soft', + emAmendTags: '漏提文件,修改提交备注,amend,追加文件', + emRecoverTags: '恢复误删分支,找回代码,reflog,reset hard恢复', + emWrongBranchTags: '提交错分支,移花接木,挪移提交,master误提交', + emPullAbortTags: '撤销pull,放弃合并,merge abort,冲突回退', + emRevertTags: '远程回滚,revert,线上回退,反向提交' + }, + 'en-US': { + searchEmergencyPlaceholder: 'Describe your Git mishap (e.g., wrong branch, undo commit, recover stash, abort merge)...', + searchCommitPlaceholder: 'Enter change summary (supports scope:subject, or open the full Commit Form)...', + searchGitignorePlaceholder: 'Search 30+ stacks, frameworks, DevOps, or OS templates (e.g., Node, Docker, Swift, Flutter)...', + dropdownTooltip: 'Switch Git Helper mode', + modeEmergency: 'Git Emergency Rescue', + modeCommit: 'Conventional Commit Builder', + modeGitignore: '.gitignore Generator', + // FilterBar & Shell syntax + shellNamePowerShell: 'Windows PowerShell', + shellNamePosix: 'POSIX (Bash / zsh)', + filterEmergencySummary: 'Shell syntax: {shell} ({source})', + filterCommitSummary: 'Shell syntax: {shell} · Open Commit Form for body & issue footers', + filterGitignoreSummary: '{stacks} [[stacks:template|templates]] selected · {rules} unique [[rules:rule|rules]] · Safe merge into project directory', + shellSourceAuto: 'Auto-detected', + shellSourceManual: 'Manual', + actionToggleShell: 'Switch Shell', + actionOpenCommitForm: 'Commit Form', + actionWriteGitignoreToDir: 'Write to Project', + actionClearStacks: 'Clear All', + actionResetDefaultStacks: 'Reset Defaults', + // Empty views + emptyEmergencyTitle: 'No matching Git rescue scenario found', + emptyEmergencyDesc: 'Try another keyword (e.g., undo, branch, conflict, stash, reflog) or clear the search query.', + emptyGitignoreTitle: 'No matching .gitignore template found', + emptyGitignoreDesc: 'Try searching by language, framework, or tool (e.g., Node, Python, Docker, Swift, Flutter, Unity).', + actionClearSearch: 'Clear Search', + // Emergency section & detail + emergencySectionTitle: 'Common Git Mishaps & Recovery Guides ({count})', + primaryCommandHeader: '#### Primary Command (Press Enter to Copy)', + incidentPrefix: '### Scenario: {title}', + stepsHeader: '#### Step-by-Step Commands ({shell} · Pick the matching case; do not run all blindly)', + stepLabel: 'Step {index}', + enterToCopySuffix: ' (Press Enter to Copy)', + dangerWarningHeader: '#### Destructive Action Warning', + principleHeader: '#### How Git Works & Pitfalls to Avoid', + metaCategoryTitle: 'Category', + metaSafetyTitle: 'Risk Level', + metaShellTitle: 'Shell Syntax', + metaDifficultyTitle: 'Difficulty', + copyPrimaryCommand: 'Copy Primary Command', + copyStepCommand: 'Copy Step {index}', + copyGuideWithNotes: 'Copy Full Guide with Notes', + // Commit mode & form + commitSectionTitle: 'Select Conventional Commits Type', + commitSectionTitleBreaking: 'Select Conventional Commits Type (BREAKING CHANGE ! enabled)', + commitPreviewHeader: '### Commit Command Preview ({shell})', + commitInputHintDefault: 'Enter a commit subject first, or press Ctrl+E to open the full Commit Form', + commitMessageHeader: '#### Generated Commit Message', + commitTypeInfoHeader: '#### Type Reference (`{type}`)', + commitMeaningLabel: '- **Meaning**: {meaning}', + commitScopeLabel: '- **When to Use**: {description}', + commitExamplesHeader: '#### Examples', + copyFullGitCommit: 'Copy Full git commit Command', + copyCommitMessageOnly: 'Copy Commit Message Only', + copyTypePrefix: 'Copy Type Prefix {type}:', + toggleBreakingOn: 'Enable Breaking Change (!)', + toggleBreakingOff: 'Disable Breaking Change (!)', + commitBreakingBadge: 'BREAKING (!)', + commitFormNavTitle: 'Conventional Commit Builder', + commitFormTypeLabel: 'Type', + commitFormScopeLabel: 'Scope (optional)', + commitFormScopePlaceholder: 'e.g., auth, ui, api, cli (leave blank to omit)', + commitFormSubjectLabel: 'Subject (required)', + commitFormSubjectPlaceholder: 'Write a concise summary of the change', + commitFormBodyLabel: 'Detailed Body (optional)', + commitFormBodyPlaceholder: 'Explain motivation, implementation details, or impact (multi-line supported)', + commitFormFooterLabel: 'Issue / Footer (optional)', + commitFormFooterPlaceholder: 'e.g., Closes #123 or Refs #456', + commitFormBreakingLabel: 'Breaking Change', + commitFormBreakingCheckbox: 'Mark as breaking change (!)', + commitFormBreakingDescLabel: 'Breaking Change Note (optional)', + commitFormBreakingDescPlaceholder: 'e.g., Remove legacy v1 endpoint; migrate callers to v2', + commitFormShellLabel: 'Target Shell Syntax', + commitFormPreviewTitle: 'Live Command & Commit Message Preview', + commitFormCopyCommand: 'Copy Full git commit Command', + commitFormCopyMessage: 'Copy Commit Message Only', + commitFormReset: 'Reset Form', + commitFormCopiedCommandToast: 'Copied full git commit command', + commitFormCopiedMessageToast: 'Copied commit message', + commitFormInvalidToast: 'Please enter a valid commit subject first', + commitErrScopeInvalid: 'Scope may only contain letters, digits, CJK, or _ - . / (max 23 chars)', + commitErrControlChars: 'Commit subject contains invisible control characters. Please remove them.', + commitErrEmpty: 'Commit subject cannot be empty. Briefly describe the purpose of this change.', + commitPlaceholder: 'Enter a concise summary of your change', + // Gitignore mode & disk write + gitignoreSectionTitle: '.gitignore Composer ({stacks} [[stacks:stack|stacks]] selected, {rules} unique [[rules:rule|rules]] · Enter to toggle / Ctrl+Enter to copy)', + gitignoreItemSubtitle: '{category} · {count} [[count:rule|rules]]', + gitignoreTagChecked: 'Selected', + gitignoreTagUnchecked: 'Unselected', + gitignorePreviewHeader: '### Merged `.gitignore` Preview (Deduplicated · Preserves Existing Rules When Writing)', + metaSelectedStacksTitle: 'Selected Stacks', + metaNoneSelected: 'None', + metaTotalRulesTitle: 'Unique Rules', + metaTotalRulesText: '{count} [[count:rule|rules]]', + copyMergedGitignore: 'Copy Merged .gitignore', + writeMergedGitignore: 'Choose Project Folder & Safely Merge .gitignore', + actionUncheck: 'Deselect', + actionCheck: 'Select', + gitignoreEmptyWriteWarn: 'Select at least one stack template first', + gitignoreSelectDirTitle: 'Select Project Root Folder to Write or Merge .gitignore', + gitignoreWriteCreatedTitle: '.gitignore Created', + gitignoreWriteCreatedMsg: 'Wrote {added} [[added:rule|rules]] to {path}', + gitignoreWriteMergedTitle: 'Safely Merged into .gitignore', + gitignoreWriteMergedMsg: 'Added {added} [[added:rule|rules]] (skipped {skipped} existing): {path}', + gitignoreWriteUnchangedTitle: '.gitignore Already Up to Date', + gitignoreWriteUnchangedMsg: 'All selected rules already exist (skipped {skipped} duplicates)', + gitignoreWriteFailedTitle: 'Failed to Write .gitignore', + errHostUnsupported: 'Host capability ({method}) is unavailable in this environment. Use inside ZTools desktop.', + errHostResponseInvalid: 'Host returned an invalid response envelope', + errHostCallFailed: 'Host capability call failed ({method})', + errHostPermissionDenied: 'File or folder permission denied ({code}). Please re-select the project folder.', + errHostWithCode: 'Operation failed (error code: {code})', + // Guide & Headers + guideScenarioPrefix: 'Scenario: {title}', + guideShellPrefix: 'Shell syntax: {shell}', + guideIntro: 'Review each option below and run only the command that fits your state; do not run all steps sequentially.', + gitignoreGeneratedHeader: '# Generated by ZTools Git Helper', + gitignoreCustomRulesHeader: '### Custom Rules ###', + safetySafe: 'Safe / Lossless', + safetyCaution: 'Check Carefully', + safetyDanger: 'Destructive Warning', + diffBeginner: 'Beginner Friendly', + diffMedium: 'Intermediate', + diffExpert: 'Expert Only', + // Emergency items + emUndoTitle: 'Undo the last commit while keeping changes in the working tree', + emUndoCat: 'Commit Undo', + emUndoStep1Title: 'Create a backup branch at current HEAD, then soft-reset the unpushed commit', + emUndoStep1Explain: 'Requires a local branch with at least two commits. Stops if the backup branch already exists so it never overwrites prior backups. Working files and staged changes stay intact.', + emUndoStep2Title: 'Optionally unstage files as well (return to modified working tree)', + emUndoStep2Explain: 'Run after step 1; only resets the staging index without moving HEAD again. Working files are preserved.', + emUndoPrinciple: 'Inspect git status and git log first. Only undo unpushed commits; use git revert for commits already pushed to shared branches. The backup branch preserves the commit, not uncommitted files.', + emUndoWarning: 'Only use on unpushed local commits; if already pushed to a shared branch, use git revert instead.', + emAmendTitle: 'Forgot a file in the last commit or made a typo in the commit message', + emAmendCat: 'Commit Undo', + emAmendStep1Title: 'Stage the missing file to fold into the previous commit (keep message)', + emAmendStep1Cmd: 'git add -- "path/to/missing-file"', + emAmendStep1Explain: 'Replace the quoted path with the exact file to add, then run git diff --cached to verify staged changes before amending.', + emAmendStep2Title: 'After verifying staged files, back up the old commit and amend', + emAmendStep2Explain: 'Use only on unpushed commits. Stops if the backup branch exists; pick a new name to retry. To edit only the message, check staged files first and run git commit --amend.', + emAmendPrinciple: 'git commit --amend replaces the tip commit with a new commit object (safe only before pushing to a shared branch).', + emAmendWarning: 'Never amend commits already pushed to a shared branch, as rewriting history causes force-push conflicts.', + emRecoverTitle: 'Accidentally ran git reset --hard or deleted an unmerged local branch', + emRecoverCat: 'Disaster Recovery', + emRecoverStep1Title: 'Step 1: Inspect HEAD reflog history to find the hash before the mistake (e.g., a1b2c3d)', + emRecoverStep1Explain: 'Verify the exact commit hash from the log. Expired entries may be garbage-collected, and uncommitted changes usually cannot be recovered via reflog.', + emRecoverStep2Title: 'Step 2: Create a recovery branch from the verified commit hash', + emRecoverStep2Cmd: 'git branch recovered-branch "verified-commit-hash"', + emRecoverStep2Explain: 'Replace the quoted placeholder with the verified hash. This creates a branch without touching your working tree; do not assume HEAD@{1} is the target. For never-checked-out deleted branches, check the "was " output from git branch -D.', + emRecoverPrinciple: 'Git commit objects are immutable once created; until garbage collection expires them, reflog acts as your local safety net.', + emWrongBranchTitle: 'Committed directly to main/master instead of a new feature branch', + emWrongBranchCat: 'Branch Rescue', + emWrongBranchStep1Title: 'Step 1: Create and switch to a new branch, keeping commits and working changes', + emWrongBranchStep1Explain: 'Choose a branch name that does not exist yet. The original branch stays untouched for now.', + emWrongBranchStep2Title: 'Step 2: Inspect branch topology before deciding how to clean up the original branch', + emWrongBranchStep2Explain: 'Your work is now safe on the new branch. Use revert if the original branch was already pushed; otherwise inspect commits before adjusting it rather than running a blind hard reset.', + emWrongBranchPrinciple: 'Protect your work on a new branch first, then verify whether the original branch is shared. git switch requires Git 2.23 or newer.', + emWrongBranchWarning: 'Always create the new branch first before resetting or reverting the original branch; never run git reset --hard prematurely.', + emPullAbortTitle: 'git pull or merge caused messy conflicts and you want to abort back to pre-merge state', + emPullAbortCat: 'Conflict Rescue', + emPullAbortStep1Title: 'If a merge conflict is currently in progress, abort the merge', + emPullAbortStep1Explain: 'Applies only to an active merge; use git rebase --abort for rebase conflicts. Back up uncommitted work first, as abort may not restore pre-existing dirty changes.', + emPullAbortStep2Title: 'If the merge already completed, inspect pre-merge state first (do not run step 1)', + emPullAbortStep2Explain: 'This is an alternative case, not a follow-up to abort. Back up files and create a recovery branch; verify ORIG_HEAD was not overwritten before reverting or resetting.', + emPullAbortPrinciple: 'Distinguish between an in-progress merge and a completed merge. ORIG_HEAD is updated by subsequent commands, so always inspect it before acting.', + emRevertTitle: 'Bad code was already pushed to a shared remote branch and must be rolled back safely', + emRevertCat: 'Remote Rollback', + emRevertStep1Title: 'Create an inverse commit without rewriting shared history', + emRevertStep1Explain: 'Confirm HEAD is the normal commit to undo and stash/save local changes first. Merge commits require choosing the mainline parent carefully rather than assuming -m 1.', + emRevertStep2Title: 'Verify current branch and upstream before pushing normally (no --force needed)', + emRevertStep2Explain: 'Test the revert commit and verify branch, remote, and upstream before pushing. Do not assume every repository uses main as its default branch.', + emRevertPrinciple: 'Never force-push after git reset --hard on shared branches; creating an inverse commit with git revert preserves team history.', + // Commit types + ctFeatMeaning: 'New feature or user-facing capability', + ctFeatDesc: 'Adds functionality users can invoke or experience', + ctFeatEx1: 'feat(auth): add email verification code login', + ctFeatEx2: 'feat(export): support exporting reports to CSV', + ctFixMeaning: 'Bug fix or production issue resolution', + ctFixDesc: 'Fixes incorrect behavior, crashes, or unexpected errors', + ctFixEx1: 'fix(network): release socket connection after request timeout', + ctFixEx2: 'fix(ui): improve table border contrast in dark mode', + ctRefactorMeaning: 'Code refactoring (no external behavior change)', + ctRefactorDesc: 'Restructures code while keeping public behavior identical', + ctRefactorEx1: 'refactor(order): extract payment logic from order service', + ctPerfMeaning: 'Performance and memory optimization', + ctPerfDesc: 'Improves speed or reduces CPU/memory usage', + ctPerfEx1: 'perf(search): add index for list query to avoid full table scan', + ctTestMeaning: 'Add or improve integration and edge-case tests', + ctTestDesc: 'Adds or updates test cases without changing production logic', + ctTestEx1: 'test(cart): cover insufficient stock and duplicate checkout', + ctDocsMeaning: 'Documentation and comment updates', + ctDocsDesc: 'Updates docs, comments, or README files only', + ctDocsEx1: 'docs(readme): add local development and build instructions', + ctChoreMeaning: 'Build scripts, dependency updates, or tooling chores', + ctChoreDesc: 'Maintenance tasks like build config, CI, or dependency bumps', + ctChoreEx1: 'chore(deps): upgrade TypeScript and bundler versions', + ctBuildMeaning: 'Build system or external dependency changes', + ctBuildDesc: 'Changes affecting build output or bundler toolchains (e.g., Vite, Webpack, npm)', + ctBuildEx1: 'build(vite): enable production chunk splitting and minification', + ctCiMeaning: 'CI/CD pipeline and automation configuration', + ctCiDesc: 'Updates to GitHub Actions, GitLab CI, or other workflow scripts', + ctCiEx1: 'ci(actions): add automated unit test check on pull requests', + ctStyleMeaning: 'Code formatting and whitespace only (no logic change)', + ctStyleDesc: 'Pure formatting tweaks like indentation, quotes, or semicolons', + ctStyleEx1: 'style(lint): standardize single quotes and trailing newlines', + ctRevertMeaning: 'Revert a previous commit', + ctRevertDesc: 'Creates an inverse commit undoing an earlier change', + ctRevertEx1: 'revert(auth): revert token check commit that broke sessions', + // 9 high-frequency emergency guides + emStashRecoverTitle: 'Accidentally dropped or cleared a git stash and want to recover it', + emStashRecoverCat: 'Disaster Recovery', + emStashRecoverTags: 'stash drop,recover stash,dangling commit,fsck', + emStashRecoverStep1Title: 'Step 1: Scan dangling commit objects (syntax auto-adapted to your shell)', + emStashRecoverStep1Explain: 'Lists dangling commit hashes; inspect candidates with git show to find the "WIP on ..." stash commit.', + emStashRecoverStep2Title: 'Step 2: Apply the verified stash commit back to your working tree', + emStashRecoverStep2Cmd: 'git stash apply "verified-dangling-hash"', + emStashRecoverStep2Explain: 'Replace the placeholder with the verified commit hash; ensure your working tree is clean first.', + emStashRecoverPrinciple: 'git stash drop only removes the reference; underlying commit objects stay in .git/objects until garbage-collected.', + emDetachedHeadTitle: 'Made commits in detached HEAD state and want to save them on a branch', + emDetachedHeadCat: 'Branch Rescue', + emDetachedHeadTags: 'detached head,save commits,create branch', + emDetachedHeadStep1Title: 'Create and switch to a new branch at the current detached commit', + emDetachedHeadStep1Explain: 'Attaches your commits to a proper branch immediately while keeping working tree and index intact.', + emDetachedHeadStep2Title: 'If you already switched away, find the hash via reflog first', + emDetachedHeadStep2Cmd: 'git reflog -n 15', + emDetachedHeadStep2Explain: 'Locate the last commit hash from detached HEAD, then run git branch rescue/detached .', + emDetachedHeadPrinciple: 'Detached HEAD points directly to a commit instead of a branch; creating a branch ref saves it from becoming orphaned.', + emCleanUntrackedTitle: 'Remove leftover untracked files or build artifacts safely', + emCleanUntrackedCat: 'Workspace Cleanup', + emCleanUntrackedTags: 'clean,untracked files,remove temp files', + emCleanUntrackedStep1Title: 'Step 1: Preview what will be deleted using dry-run (never delete blindly)', + emCleanUntrackedStep1Explain: '-n performs a dry run and -d includes untracked directories; double-check the output before deleting.', + emCleanUntrackedStep2Title: 'Step 2: Execute cleanup after verifying the preview list', + emCleanUntrackedStep2Explain: 'Permanently removes untracked files and folders (cannot be undone via Git); add -x only if you also want ignored artifacts removed.', + emCleanUntrackedPrinciple: 'Untracked files are not stored in Git objects and cannot be recovered with reflog—always preview with -nd first.', + emCleanUntrackedWarning: 'git clean -fd permanently deletes untracked files without Recycle Bin / Trash and cannot be undone via reflog. Always preview with git clean -nd first!', + emEditMsgTitle: 'Edit only the last unpushed commit message without changing code', + emEditMsgCat: 'Commit Undo', + emEditMsgTags: 'edit commit message,amend,reword', + emEditMsgStep1Title: 'Check git status first to ensure no unintended files are staged', + emEditMsgStep1Explain: 'Any staged files would be folded into --amend unless --only is used; inspect status first.', + emEditMsgStep2Title: 'Rewrite only the commit message with --amend --only', + emEditMsgStep2Cmd: 'git commit --amend --only -m "new commit message"', + emEditMsgStep2Explain: '--only ignores staged changes and updates only the tip commit message (for unpushed commits only).', + emEditMsgPrinciple: 'git commit --amend creates a new commit hash replacing HEAD, so avoid amending commits already pushed to shared branches.', + emRebaseAbortTitle: 'Stuck in messy git rebase conflicts and want to abort or continue', + emRebaseAbortCat: 'Conflict Rescue', + emRebaseAbortTags: 'rebase,rebase conflict,rebase abort,rebase continue', + emRebaseAbortStep1Title: 'Abort the rebase and restore the branch to its pre-rebase state', + emRebaseAbortStep1Explain: 'Safely cancels an in-progress rebase and resets HEAD back to where it started.', + emRebaseAbortStep2Title: 'Or after resolving conflicts and running git add, continue rebasing', + emRebaseAbortStep2Explain: 'Stage resolved files with git add first, then run --continue to replay remaining commits.', + emRebaseAbortPrinciple: 'Rebase replays commits one by one; git rebase --abort cleanly rolls back the entire operation at any point.', + emDiscardFileTitle: 'Discard local edits in a single file and restore it to the last commit', + emDiscardFileCat: 'Workspace Cleanup', + emDiscardFileTags: 'discard file,restore file,undo file changes', + emDiscardFileStep1Title: 'Inspect the diff first to make sure nothing worth keeping is lost', + emDiscardFileStep1Cmd: 'git diff -- "path/to/file"', + emDiscardFileStep1Explain: 'Discarding unstaged edits is irreversible; review the diff before restoring.', + emDiscardFileStep2Title: 'Restore that single file without touching other working changes', + emDiscardFileStep2Cmd: 'git restore -- "path/to/file"', + emDiscardFileStep2Explain: 'Restores only the specified file from the index/HEAD; on Git < 2.23 use git checkout -- "path/to/file".', + emDiscardFilePrinciple: 'git restore (Git 2.23+) separates file restoration from branch switching, preventing accidental checkout mistakes.', + emDiscardFileWarning: 'git restore permanently overwrites unstaged local edits in that file and cannot be recovered via reflog. Always inspect git diff first!', + emCleanBranchesTitle: 'Safely clean up old local branches already merged into main', + emCleanBranchesCat: 'Branch Rescue', + emCleanBranchesTags: 'clean branches,merged branches,delete branch', + emCleanBranchesStep1Title: 'List local branches already merged into the current branch', + emCleanBranchesStep1Explain: 'Run this while on your main branch and review the list, keeping protected branches like main/master/dev.', + emCleanBranchesStep2Title: 'Delete a merged branch safely (-d refuses unmerged branches)', + emCleanBranchesStep2Cmd: 'git branch -d "merged-branch-name"', + emCleanBranchesStep2Explain: 'Lowercase -d checks merge status automatically so unmerged work is never accidentally deleted.', + emCleanBranchesPrinciple: 'git branch -d guards against deleting unmerged commits; combine with git fetch --prune to clear stale remote refs.', + emUnstageAddTitle: 'Accidentally staged files with git add and want to unstage without losing edits', + emUnstageAddCat: 'Commit Undo', + emUnstageAddTags: 'unstage,undo git add,restore staged', + emUnstageAddStep1Title: 'Unstage a specific file while preserving your working tree edits', + emUnstageAddStep1Cmd: 'git restore --staged -- "path/to/file"', + emUnstageAddStep1Explain: 'Removes the file from the staging index only; your local edits remain untouched.', + emUnstageAddStep2Title: 'Or unstage all staged files at once', + emUnstageAddStep2Explain: 'Handy after accidentally running git add . so you can re-stage files selectively.', + emUnstageAddPrinciple: 'git restore --staged modifies only the index and never alters working directory files.', + emCherryPickTitle: 'Apply a single specific commit from another branch onto the current branch', + emCherryPickCat: 'Branch Rescue', + emCherryPickTags: 'cherry-pick,copy commit,hotfix', + emCherryPickStep1Title: 'Inspect the source branch log to find the target commit hash', + emCherryPickStep1Explain: 'Review what the commit touches to avoid pulling isolated changes that depend on earlier commits.', + emCherryPickStep2Title: 'Cherry-pick the target commit onto your current branch', + emCherryPickStep2Cmd: 'git cherry-pick "target-commit-hash"', + emCherryPickStep2Explain: 'Replays the commit diff as a new commit on HEAD; add -n (--no-commit) to inspect before committing.', + emCherryPickPrinciple: 'cherry-pick applies the diff of a chosen commit onto the current HEAD, commonly used for hotfixes.', + // Gitignore categories & names + giCatLang: 'Language & Runtime', + giCatFrontend: 'Frontend & Cross-Platform', + giCatDevOps: 'DevOps & Infrastructure', + giCatDataDocs: 'Data Science & Docs', + giCatOS: 'Operating System', + giCatIDE: 'Editor & IDE', + giNameMacOS: 'macOS System Files', + giNameWindows: 'Windows Thumbnails & Temp Files', + giNameLinux: 'Linux Desktop & Temp Files', + emUndoTags: 'undo commit,keep changes,reset soft', + emAmendTags: 'missing file,fix commit message,amend', + emRecoverTags: 'recover branch,restore code,reflog,reset hard', + emWrongBranchTags: 'wrong branch,move commit,main branch mistake', + emPullAbortTags: 'abort pull,abort merge,merge conflict', + emRevertTags: 'remote rollback,revert,pushed commit' } +} export { GIT_HELPER_MESSAGES } const rawT = createTranslator(GIT_HELPER_MESSAGES, { defaultLocale: 'en-US' }) diff --git a/extensions/git-helper/src/index.tsx b/extensions/git-helper/src/index.tsx index 2f226c72..7bb897d1 100644 --- a/extensions/git-helper/src/index.tsx +++ b/extensions/git-helper/src/index.tsx @@ -1,56 +1,618 @@ import React, { Action, ActionPanel, + Clipboard, Color, + Form, Icon, List, + Toast, + showToast, useLocale, useMemo, + useNavigation, useState } from '@ztools/declarative-ui' import { GITIGNORE_STACK_TEMPLATES, + SCOPE_PATTERN, buildConventionalCommit, buildEmergencyGuide, + detectDefaultShellSyntax, generateGitignoreContent, getCommitTypes, getGitignoreStackTemplates, + getShellDisplayName, parseCommitInput, searchGitEmergencies } from './git-helper-service.js' +import { writeGitignoreToProjectDir } from './host.js' import { t } from './i18n.js' -import type { GitHelperMode } from './types.js' +import type { + CommitTypeItem, + GitEmergencyItem, + GitHelperMode, + GitignoreStackTemplate, + ShellSyntax +} from './types.js' export * from './types.js' export * from './git-helper-service.js' +export * from './host.js' export interface GitHelperCommandProps { featureCode?: string initialMode?: GitHelperMode initialSearchText?: string initialSelectedStacks?: string[] + initialShellSyntax?: ShellSyntax } -const isMacPlatform = () => { - try { - const nav = (globalThis as { navigator?: { platform?: string; userAgent?: string } }).navigator - return /Mac/i.test(nav?.platform || nav?.userAgent || '') - } catch { - return false - } +export interface CommitBuilderFormProps { + initialType?: string + initialScope?: string + initialSubject?: string + initialBreaking?: boolean + initialShellSyntax?: ShellSyntax + onShellSyntaxChange?: (syntax: ShellSyntax) => void +} + +const isMacPlatform = (): boolean => { + const nav = (globalThis as { navigator?: { platform?: string; userAgent?: string } }).navigator + return /Mac/i.test(nav?.platform || nav?.userAgent || '') } /** .gitignore 默认勾选:只勾当前系统的隐藏文件模板,加上常用 IDE 配置目录 */ export const defaultGitignoreStacks = (): string[] => [isMacPlatform() ? 'macOS' : 'Windows', 'IDEs'] /** 把模板 ID(如 ReactVue)换成界面上显示的名称 */ -const stackDisplayName = (id: string) => +const stackDisplayName = (id: string): string => getGitignoreStackTemplates().find((tpl) => tpl.id === id)?.name ?? GITIGNORE_STACK_TEMPLATES.find((tpl) => tpl.id === id)?.name ?? id +const codeFenceLang = (shellSyntax: ShellSyntax): string => + shellSyntax === 'powershell' ? 'powershell' : 'bash' + +/** + * 规范提交生成器表单(支持类型 / 作用域 / 中英文摘要 / 详细正文 / 关联 Issue / 破坏性变更 / 终端语法) + */ +export function CommitBuilderForm(props: CommitBuilderFormProps = {}) { + const locale = useLocale() + const commitTypes = useMemo(() => getCommitTypes(), [locale]) + + const [type, setType] = useState(props.initialType || 'feat') + const [scope, setScope] = useState(props.initialScope || '') + const [subject, setSubject] = useState(props.initialSubject || '') + const [body, setBody] = useState('') + const [footer, setFooter] = useState('') + const [breaking, setBreaking] = useState(Boolean(props.initialBreaking)) + const [breakingDescription, setBreakingDescription] = useState('') + const [shellSyntax, setShellSyntax] = useState( + props.initialShellSyntax ?? detectDefaultShellSyntax() + ) + const [submittedOnce, setSubmittedOnce] = useState(false) + + const built = useMemo( + () => + buildConventionalCommit({ + type, + scope, + subject, + body, + footer, + breaking, + breakingDescription, + shellSyntax + }), + [type, scope, subject, body, footer, breaking, breakingDescription, shellSyntax, locale] + ) + + const scopeError = useMemo(() => { + const clean = scope.trim() + if (!clean) return undefined + return SCOPE_PATTERN.test(clean) ? undefined : t('commitErrScopeInvalid') + }, [scope, locale]) + + const subjectError = useMemo(() => { + if (!submittedOnce && !subject.trim()) return undefined + if (built.isValid || scopeError) return undefined + return built.validationHint + }, [submittedOnce, subject, built, scopeError]) + + const previewMarkdown = useMemo(() => { + const fence = codeFenceLang(shellSyntax) + const cmdText = built.isValid + ? built.gitCommand + : `# ${built.validationHint ?? t('commitInputHintDefault')}` + return `${t('commitPreviewHeader', { shell: getShellDisplayName(shellSyntax) })} +\`\`\`${fence} +${cmdText} +\`\`\` + +${t('commitMessageHeader')} +\`\`\`text +${built.message} +\`\`\`` + }, [built, shellSyntax, locale]) + + const copyResult = async (target: 'command' | 'message') => { + setSubmittedOnce(true) + const text = target === 'command' ? built.gitCommand : built.message + if (!built.isValid || !text) { + await showToast({ + style: Toast.Style.Failure, + title: t('commitFormInvalidToast'), + message: built.validationHint + }) + return + } + await Clipboard.copy(text) + await showToast({ + style: Toast.Style.Success, + title: + target === 'command' ? t('commitFormCopiedCommandToast') : t('commitFormCopiedMessageToast'), + message: built.header + }) + } + + const handleReset = () => { + setType('feat') + setScope('') + setSubject('') + setBody('') + setFooter('') + setBreaking(false) + setBreakingDescription('') + setSubmittedOnce(false) + } + + return ( +
+ copyResult('command')} + /> + copyResult('message')} + /> + + + } + > + + {commitTypes.map((ct) => ( + + ))} + + + + + + + + + + + + + {breaking && ( + + )} + + { + const next = v === 'powershell' ? 'powershell' : 'posix' + setShellSyntax(next) + props.onShellSyntaxChange?.(next) + }} + > + + + + + + + + + ) +} + +function renderEmergencySection(options: { + items: GitEmergencyItem[] + shellSyntax: ShellSyntax + shellDisplay: string + fence: string + onToggleShell: () => void +}) { + const { items, shellSyntax, shellDisplay, fence, onToggleShell } = options + if (items.length === 0) { + return ( + + ) + } + + return ( + + {items.map((item) => { + const primaryStep = item.steps.findIndex((s) => s.cmd === item.primaryCommand) + const primarySection = + primaryStep >= 0 + ? '' + : `${t('primaryCommandHeader')} +\`\`\`${fence} +${item.primaryCommand} +\`\`\` + +` + const warningSection = item.dangerWarning + ? `${t('dangerWarningHeader')} +> **${item.dangerWarning}** + +` + : '' + + return ( + `${i + 1}. **${t('stepLabel', { index: i + 1 })} · ${s.title}**${i === primaryStep ? t('enterToCopySuffix') : ''} +\`\`\`${fence} +${s.cmd} +\`\`\` +*${s.explain}*` + ) + .join('\n\n')} + +${warningSection}${t('principleHeader')} +> ${item.principle} +`} + metadata={ + + + + + + + + + + } + /> + } + actions={ + + + + + {item.steps.map((step, index) => ( + + ))} + + + + } + /> + ) + })} + + ) +} + +function renderCommitSection(options: { + commitTypes: CommitTypeItem[] + parsedInput: { scope: string; subject: string } + isBreaking: boolean + shellSyntax: ShellSyntax + shellDisplay: string + fence: string + onToggleBreaking: () => void + onToggleShell: () => void + onOpenCommitForm: (type: string) => void +}) { + const { + commitTypes, + parsedInput, + isBreaking, + shellSyntax, + shellDisplay, + fence, + onToggleBreaking, + onToggleShell, + onOpenCommitForm + } = options + + return ( + + {commitTypes.map((ct) => { + const built = buildConventionalCommit({ + type: ct.type, + scope: parsedInput.scope, + subject: parsedInput.subject, + breaking: isBreaking, + shellSyntax + }) + const prefixType = isBreaking ? `${ct.type}!` : ct.type + + return ( + **${built.message}** + +${t('commitTypeInfoHeader', { type: ct.type })} +${t('commitMeaningLabel', { meaning: ct.chineseMeaning })} +${t('commitScopeLabel', { description: ct.description })} + +${t('commitExamplesHeader')} +${ct.examples.map((ex) => `- \`${ex}\``).join('\n')} +`} + /> + } + actions={ + + {built.isValid ? ( + + ) : ( + + )} + {built.isValid && ( + + )} + onOpenCommitForm(ct.type)} + /> + + + + } + /> + ) + })} + + ) +} + +function renderGitignoreSection(options: { + templates: GitignoreStackTemplate[] + selectedStacks: string[] + gitignoreOutput: { content: string; totalUniqueRules: number; selectedStacks: string[] } + onToggleStack: (id: string) => void + onWriteGitignore: () => Promise +}) { + const { templates, selectedStacks, gitignoreOutput, onToggleStack, onWriteGitignore } = options + if (templates.length === 0) { + return ( + + ) + } + + return ( + + {templates.map((tpl) => { + const checked = selectedStacks.includes(tpl.id) + return ( + + + + + } + /> + } + actions={ + + onToggleStack(tpl.id)} + /> + + + + } + /> + ) + })} + + ) +} + export function GitHelperCommand(props: GitHelperCommandProps = {}) { const locale = useLocale() + const navigation = useNavigation() const defaultMode: GitHelperMode = props.initialMode ?? (props.featureCode === 'git-commit-builder' @@ -65,13 +627,29 @@ export function GitHelperCommand(props: GitHelperCommandProps = {}) { const [selectedStacks, setSelectedStacks] = useState( props.initialSelectedStacks ?? defaultGitignoreStacks ) + const [shellSyntax, setShellSyntax] = useState( + props.initialShellSyntax ?? detectDefaultShellSyntax + ) + const [shellManuallyOverridden, setShellManuallyOverridden] = useState(false) + const [isWritingGitignore, setIsWritingGitignore] = useState(false) - const filteredEmergencies = useMemo(() => searchGitEmergencies(searchText), [searchText, locale]) + const filteredEmergencies = useMemo( + () => searchGitEmergencies(searchText, shellSyntax), + [searchText, shellSyntax, locale] + ) const commitTypes = useMemo(() => getCommitTypes(), [locale]) const stackTemplates = useMemo(() => getGitignoreStackTemplates(), [locale]) - const parsedCommitInput = useMemo(() => parseCommitInput(searchText), [searchText]) + const filteredStackTemplates = useMemo(() => { + const q = searchText.trim().toLowerCase() + if (!q) return stackTemplates + return stackTemplates.filter((tpl) => { + const haystack = `${tpl.id} ${tpl.name} ${tpl.category} ${(tpl.keywords ?? []).join(' ')}`.toLowerCase() + return haystack.includes(q) + }) + }, [stackTemplates, searchText]) + const gitignoreOutput = useMemo( () => generateGitignoreContent(selectedStacks), [selectedStacks, locale] @@ -83,10 +661,195 @@ export function GitHelperCommand(props: GitHelperCommandProps = {}) { ) } + const toggleShellSyntax = () => { + setShellSyntax((prev) => (prev === 'powershell' ? 'posix' : 'powershell')) + setShellManuallyOverridden(true) + } + + const openCommitForm = (initialType?: string) => { + navigation.push( + { + setShellSyntax(next) + setShellManuallyOverridden(true) + }} + /> + ) + } + + const handleWriteGitignore = async () => { + if (isWritingGitignore) return + if (selectedStacks.length === 0 || gitignoreOutput.totalUniqueRules === 0) { + await showToast({ style: Toast.Style.Failure, title: t('gitignoreEmptyWriteWarn') }) + return + } + + setIsWritingGitignore(true) + try { + const result = await writeGitignoreToProjectDir(gitignoreOutput.content) + if (result.status === 'canceled') return + if (result.status === 'created') { + await showToast({ + style: Toast.Style.Success, + title: t('gitignoreWriteCreatedTitle'), + message: t('gitignoreWriteCreatedMsg', { + added: result.addedRulesCount, + path: result.filePath + }) + }) + } else if (result.status === 'unchanged') { + await showToast({ + style: Toast.Style.Success, + title: t('gitignoreWriteUnchangedTitle'), + message: t('gitignoreWriteUnchangedMsg', { skipped: result.skippedDuplicatesCount }) + }) + } else { + await showToast({ + style: Toast.Style.Success, + title: t('gitignoreWriteMergedTitle'), + message: t('gitignoreWriteMergedMsg', { + added: result.addedRulesCount, + skipped: result.skippedDuplicatesCount, + path: result.filePath + }) + }) + } + } catch (err) { + const message = err instanceof Error ? err.message : String(err) + await showToast({ + style: Toast.Style.Failure, + title: t('gitignoreWriteFailedTitle'), + message + }) + } finally { + setIsWritingGitignore(false) + } + } + + const shellDisplay = getShellDisplayName(shellSyntax) + const fence = codeFenceLang(shellSyntax) + + const filterBar = useMemo(() => { + if (mode === 'gitignore') { + return { + summaryText: t('filterGitignoreSummary', { + stacks: selectedStacks.length, + rules: gitignoreOutput.totalUniqueRules + }), + actions: [ + { + id: 'write-gitignore-dir', + title: t('actionWriteGitignoreToDir'), + icon: Icon.Folder, + disabled: selectedStacks.length === 0 || isWritingGitignore, + onAction: () => { + void handleWriteGitignore() + } + }, + selectedStacks.length > 0 + ? { + id: 'clear-gitignore-stacks', + title: t('actionClearStacks'), + icon: Icon.XMarkCircle, + onAction: () => setSelectedStacks([]) + } + : { + id: 'reset-gitignore-stacks', + title: t('actionResetDefaultStacks'), + icon: Icon.ArrowClockwise, + onAction: () => setSelectedStacks(defaultGitignoreStacks()) + } + ] + } + } + return { + summaryText: + mode === 'emergency' + ? t('filterEmergencySummary', { + shell: shellDisplay, + source: shellManuallyOverridden ? t('shellSourceManual') : t('shellSourceAuto') + }) + : t('filterCommitSummary', { shell: shellDisplay }), + actions: [ + { + id: 'toggle-shell-syntax', + title: t('actionToggleShell'), + icon: Icon.Terminal, + onAction: toggleShellSyntax + }, + { + id: 'open-commit-form', + title: t('actionOpenCommitForm'), + icon: Icon.Pencil, + onAction: () => openCommitForm('feat') + } + ] + } + }, [ + mode, + shellDisplay, + shellManuallyOverridden, + selectedStacks.length, + gitignoreOutput.totalUniqueRules, + isWritingGitignore, + locale + ]) + + const listLevelActions = useMemo(() => { + if (mode === 'gitignore') { + return ( + + + + {searchText.trim().length > 0 && ( + setSearchText('')} + /> + )} + + ) + } + if (mode === 'emergency' && searchText.trim().length > 0) { + return ( + + setSearchText('')} + /> + + + ) + } + return undefined + }, [mode, gitignoreOutput.content, searchText, locale, shellSyntax]) + return ( } - actions={ - mode === 'gitignore' ? ( - - - - ) : undefined - } + filterBar={filterBar} + actions={listLevelActions} isShowingDetail={true} > - {mode === 'emergency' && ( - - {filteredEmergencies.map((item) => { - // 首选命令已是某一步时,只在那一步标注“回车复制”,不再单独重复一遍 - const primaryStep = item.steps.findIndex((s) => s.cmd === item.primaryCommand) - const primarySection = - primaryStep >= 0 - ? '' - : `${t('primaryCommandHeader')} -\`\`\`bash -${item.primaryCommand} -\`\`\` + {mode === 'emergency' && + renderEmergencySection({ + items: filteredEmergencies, + shellSyntax, + shellDisplay, + fence, + onToggleShell: toggleShellSyntax + })} -` + {mode === 'commit' && + renderCommitSection({ + commitTypes, + parsedInput: parsedCommitInput, + isBreaking, + shellSyntax, + shellDisplay, + fence, + onToggleBreaking: () => setIsBreaking((prev) => !prev), + onToggleShell: toggleShellSyntax, + onOpenCommitForm: openCommitForm + })} - return ( - `${i + 1}. **${s.title}**${i === primaryStep ? t('enterToCopySuffix') : ''} -\`\`\`bash -${s.cmd} -\`\`\` -*${s.explain}*` - ) - .join('\n\n')} - -${t('principleHeader')} -> ${item.principle} -`} - metadata={ - - - - - - } - /> - } - actions={ - - - - - } - /> - ) - })} - - )} - - {mode === 'commit' && ( - - {commitTypes.map((ct) => { - const built = buildConventionalCommit({ - type: ct.type, - scope: parsedCommitInput.scope, - subject: parsedCommitInput.subject, - breaking: isBreaking - }) - const prefixType = isBreaking ? `${ct.type}!` : ct.type - return ( - **${built.message}** - -${t('commitTypeInfoHeader', { type: ct.type })} -${t('commitMeaningLabel', { meaning: ct.chineseMeaning })} -${t('commitScopeLabel', { description: ct.description })} - -${t('commitExamplesHeader')} -${ct.examples.map((ex) => `- \`${ex}\``).join('\n')} -`} - /> - } - actions={ - built.isValid ? ( - - - - setIsBreaking((prev) => !prev)} - /> - - ) : ( - - {/* 还没写说明:主动作复制类型前缀,先把前缀贴进编辑器再补说明 */} - - setIsBreaking((prev) => !prev)} - /> - - ) - } - /> - ) - })} - - )} - - {mode === 'gitignore' && ( - - {stackTemplates - .filter((tpl) => - `${tpl.id} ${tpl.name} ${tpl.category}`.toLowerCase().includes(searchText.trim().toLowerCase()) - ) - .map((tpl) => { - const checked = selectedStacks.includes(tpl.id) - return ( - - - - - } - /> - } - actions={ - - toggleStack(tpl.id)} - /> - - - } - /> - ) - })} - - )} + {mode === 'gitignore' && + renderGitignoreSection({ + templates: filteredStackTemplates, + selectedStacks, + gitignoreOutput, + onToggleStack: toggleStack, + onWriteGitignore: handleWriteGitignore + })} ) } diff --git a/extensions/git-helper/src/types.ts b/extensions/git-helper/src/types.ts index c425f4d9..5aa9afce 100644 --- a/extensions/git-helper/src/types.ts +++ b/extensions/git-helper/src/types.ts @@ -1,5 +1,13 @@ export type GitHelperMode = 'emergency' | 'commit' | 'gitignore' +export type ShellSyntax = 'powershell' | 'posix' + +export interface GitEmergencyStep { + title: string + cmd: string + explain: string +} + export interface GitEmergencyItem { id: string title: string @@ -11,12 +19,9 @@ export interface GitEmergencyItem { safetyKind?: 'safe' | 'caution' | 'danger' difficulty: string primaryCommand: string - steps: Array<{ - title: string - cmd: string - explain: string - }> + steps: GitEmergencyStep[] principle: string + dangerWarning?: string minGitVersion?: string } @@ -27,9 +32,46 @@ export interface CommitTypeItem { examples: string[] } +export interface ConventionalCommitOptions { + type: string + scope?: string + subject: string + body?: string + footer?: string + breaking?: boolean + breakingDescription?: string + shellSyntax?: ShellSyntax +} + +export interface ConventionalCommitResult { + isValid: boolean + header: string + message: string + gitCommand: string + shellSyntax: ShellSyntax + validationHint?: string +} + export interface GitignoreStackTemplate { id: string name: string category: string + keywords?: string[] rules: string[] } + +export interface GitignoreMergeResult { + mergedContent: string + addedRulesCount: number + skippedDuplicatesCount: number + changed: boolean +} + +export type GitignoreWriteResult = + | { status: 'canceled' } + | { + status: 'created' | 'merged' | 'unchanged' + filePath: string + addedRulesCount: number + skippedDuplicatesCount: number + } diff --git a/extensions/git-helper/tests/index.test.mjs b/extensions/git-helper/tests/index.test.mjs index 7e203291..c72fd135 100644 --- a/extensions/git-helper/tests/index.test.mjs +++ b/extensions/git-helper/tests/index.test.mjs @@ -6,38 +6,111 @@ import os from 'node:os' import path from 'node:path' import { execFileSync } from 'node:child_process' import { createHost, mount, tick } from '../../shared/test-harness.mjs' -import { commands, GIT_EMERGENCY_DATABASE, buildEmergencyGuide, buildConventionalCommit, generateGitignoreContent } from '../dist/index.js' +import { createRealHost, REAL_HOST_SKIP_REASON } from '../../shared/real-host-harness.mjs' +import { + COMMIT_TYPES, + CommitBuilderForm, + GIT_EMERGENCY_DATABASE, + GITIGNORE_STACK_TEMPLATES, + buildConventionalCommit, + buildEmergencyGuide, + commands, + detectDefaultShellSyntax, + generateGitignoreContent, + getEmergencyDatabase, + mergeGitignoreContent, + parseCommitInput, + quotePosixShellArg, + quotePowerShellArg, + searchGitEmergencies +} from '../dist/index.js' +import { GIT_HELPER_MESSAGES } from '../dist/i18n.js' + +let host = createHost() +const views = [] +const undoPosix = getEmergencyDatabase('posix').find((item) => item.id === 'undo-last-commit-keep-changes') +const undoPs = getEmergencyDatabase('powershell').find((item) => item.id === 'undo-last-commit-keep-changes') -const host = createHost(), views = [] -const undo = GIT_EMERGENCY_DATABASE.find(item => item.id === 'undo-last-commit-keep-changes') const shellFile = process.platform === 'darwin' ? '/bin/zsh' : gitTestTool('bash') const shellArgs = process.platform === 'darwin' ? ['-f', '-c'] : ['--noprofile', '--norc', '-c'] +const gitBinDirs = + process.platform === 'win32' + ? [ + path.resolve(path.dirname(shellFile), '..', '..', 'cmd'), + path.resolve(path.dirname(shellFile), '..', '..', 'mingw64', 'bin'), + path.dirname(shellFile) + ].filter((d) => fs.existsSync(d)) + : [] + const roots = [] -const env = { ...process.env, GIT_AUTHOR_NAME: '插件隔离测试', GIT_AUTHOR_EMAIL: 'audit@example.invalid', GIT_COMMITTER_NAME: '插件隔离测试', GIT_COMMITTER_EMAIL: 'audit@example.invalid' } +const basePath = process.env.PATH || process.env.Path || '' +const env = { + ...process.env, + PATH: [...gitBinDirs, basePath].filter(Boolean).join(path.delimiter), + GIT_AUTHOR_NAME: '插件隔离测试', + GIT_AUTHOR_EMAIL: 'audit@example.invalid', + GIT_COMMITTER_NAME: '插件隔离测试', + GIT_COMMITTER_EMAIL: 'audit@example.invalid' +} + function fixture() { const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ztools-git-helper-')) roots.push(root) - const git = (...args) => execFileSync('git', args, { cwd: root, env, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim() - const shell = command => execFileSync(shellFile, [...shellArgs, command], { cwd: root, env, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }) + const git = (...args) => + execFileSync('git', args, { + cwd: root, + env, + encoding: 'utf8', + stdio: ['ignore', 'pipe', 'pipe'] + }).trim() + const shell = (command) => + execFileSync(shellFile, [...shellArgs, command], { + cwd: root, + env, + encoding: 'utf8', + stdio: ['ignore', 'pipe', 'pipe'] + }) + const powershell = (command) => + execFileSync( + 'powershell.exe', + ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', command], + { + cwd: root, + env, + encoding: 'utf8', + stdio: ['ignore', 'pipe', 'pipe'] + } + ) git('init', '--initial-branch=main') const commits = [] for (const n of [1, 2, 3]) { fs.writeFileSync(path.join(root, 'sample.txt'), `测试版本 ${n}`) - git('add', 'sample.txt'); git('-c', 'commit.gpgsign=false', 'commit', '-m', `test: 创建隔离样本 ${n}`) + git('add', 'sample.txt') + git('-c', 'commit.gpgsign=false', 'commit', '-m', `test: 创建隔离样本 ${n}`) commits.push(git('rev-parse', 'HEAD')) } - return { root, git, shell, commits } + return { root, git, shell, powershell, commits } } + function clearReadOnlyTree(targetPath) { const stat = fs.lstatSync(targetPath, { throwIfNoEntry: false }) if (!stat || stat.isSymbolicLink()) return if (stat.isDirectory()) { - try { fs.chmodSync(targetPath, 0o700) } catch { /* 忽略单目录权限异常 */ } + try { + fs.chmodSync(targetPath, 0o700) + } catch { + /* 忽略单目录权限异常 */ + } for (const name of fs.readdirSync(targetPath)) clearReadOnlyTree(path.join(targetPath, name)) return } - try { fs.chmodSync(targetPath, 0o666) } catch { /* 忽略单文件权限异常 */ } + try { + fs.chmodSync(targetPath, 0o666) + } catch { + /* 忽略单文件权限异常 */ + } } + function cleanupRoots() { for (const root of roots.splice(0)) { try { @@ -50,38 +123,80 @@ function cleanupRoots() { } process.once('exit', cleanupRoots) -async function open(component) { const view = await mount(component); views.push(view); await tick(); return view } +async function open(component) { + const view = await mount(component) + views.push(view) + await tick() + return view +} + +const withPlatform = async (platform, fn) => { + const original = Object.getOwnPropertyDescriptor(globalThis, 'navigator') + Object.defineProperty(globalThis, 'navigator', { + value: { platform, userAgent: '' }, + configurable: true + }) + try { + return await fn() + } finally { + if (original) Object.defineProperty(globalThis, 'navigator', original) + else delete globalThis.navigator + } +} + +function findNode(tree, predicate) { + if (!tree || typeof tree !== 'object') return null + if (Array.isArray(tree)) { + for (const item of tree) { + const found = findNode(item, predicate) + if (found) return found + } + return null + } + if (predicate(tree)) return tree + const fromChildren = findNode(tree.children, predicate) + if (fromChildren) return fromChildren + for (const v of Object.values(tree.props || {})) { + if (v && typeof v === 'object' && (v.type || Array.isArray(v))) { + const found = findNode(v, predicate) + if (found) return found + } + } + return null +} + test.beforeEach(() => host.reset()) test.afterEach(() => { - views.splice(0).forEach(view => view.unmount()) + views.splice(0).forEach((view) => view.unmount()) cleanupRoots() }) -test('真实 Git:撤销只回退一次并保留恢复分支、暂存与未暂存内容', () => { +test('真实 Git (POSIX):撤销只回退一次并保留恢复分支、暂存与未暂存内容', () => { const { root, git, shell, commits } = fixture() - fs.writeFileSync(path.join(root, 'staged.txt'), '已暂存内容'); git('add', 'staged.txt') + fs.writeFileSync(path.join(root, 'staged.txt'), '已暂存内容') + git('add', 'staged.txt') fs.writeFileSync(path.join(root, 'sample.txt'), '尚未暂存的修改') fs.writeFileSync(path.join(root, 'untracked.txt'), '尚未跟踪的文件') const beforeIndex = git('write-tree') - shell(undo.primaryCommand) + shell(undoPosix.primaryCommand) assert.equal(git('rev-parse', 'HEAD'), commits[1]) assert.equal(git('rev-parse', 'backup/before-undo'), commits[2]) assert.equal(git('write-tree'), beforeIndex) - shell(undo.steps[1].cmd) + shell(undoPosix.steps[1].cmd) assert.equal(git('rev-parse', 'HEAD'), commits[1]) assert.equal(git('diff', '--cached'), '') assert.equal(fs.readFileSync(path.join(root, 'sample.txt'), 'utf8'), '尚未暂存的修改') assert.equal(fs.readFileSync(path.join(root, 'staged.txt'), 'utf8'), '已暂存内容') assert.equal(fs.readFileSync(path.join(root, 'untracked.txt'), 'utf8'), '尚未跟踪的文件') - assert.throws(() => shell(undo.primaryCommand)) + assert.throws(() => shell(undoPosix.primaryCommand)) assert.equal(git('rev-parse', 'HEAD'), commits[1], '备份重名后不得继续重置') }) test('整份操作指南粘进 shell 也不会依次执行互斥操作', () => { const { git, shell, commits } = fixture() for (const item of GIT_EMERGENCY_DATABASE) { - const guide = buildEmergencyGuide(item) - assert.ok(guide.split('\n').every(line => line.startsWith('# '))) + const guide = buildEmergencyGuide(item, 'posix') + assert.ok(guide.split('\n').every((line) => line.startsWith('# '))) shell(guide) assert.equal(git('rev-parse', 'HEAD'), commits[2]) assert.equal(git('status', '--short'), '') @@ -91,16 +206,26 @@ test('整份操作指南粘进 shell 也不会依次执行互斥操作', () => { test('真实 Git:创建工作分支保留未提交内容及原分支', () => { const { root, git, shell, commits } = fixture() fs.writeFileSync(path.join(root, 'sample.txt'), '继续开发内容') - shell(GIT_EMERGENCY_DATABASE.find(item => item.id === 'committed-to-wrong-branch').primaryCommand) + shell(GIT_EMERGENCY_DATABASE.find((item) => item.id === 'committed-to-wrong-branch').primaryCommand) assert.equal(git('branch', '--show-current'), 'feat/new-work') assert.equal(git('rev-parse', 'main'), commits[2]) assert.equal(fs.readFileSync(path.join(root, 'sample.txt'), 'utf8'), '继续开发内容') }) -test('真实 POSIX shell:提交说明中的命令替换、引号、感叹号均为字面内容', () => { +test('真实 POSIX shell:提交说明中的命令替换、引号、感叹号与多段落均为字面内容', () => { const { root, git, shell } = fixture() - fs.writeFileSync(path.join(root, 'sample.txt'), '新的变更'); git('add', 'sample.txt') - const built = buildConventionalCommit({ type: 'fix', scope: '测试', subject: "保留 '单引号'、\"双引号\"、$HOME、$(touch injected)、`touch injected2`、! 与反斜杠\\" }) + fs.writeFileSync(path.join(root, 'sample.txt'), '新的变更') + git('add', 'sample.txt') + const built = buildConventionalCommit({ + type: 'fix', + scope: '测试', + subject: "保留 '单引号'、\"双引号\"、$HOME、$(touch injected)、`touch injected2`、! 与反斜杠\\", + body: '第一行详细说明\n第二行详细说明', + footer: 'Closes #42', + breaking: true, + breakingDescription: '移除旧版接口', + shellSyntax: 'posix' + }) assert.equal(built.isValid, true) shell(built.gitCommand.replace('git commit', 'git -c commit.gpgsign=false commit')) assert.equal(git('log', '-1', '--format=%B'), built.message) @@ -108,53 +233,192 @@ test('真实 POSIX shell:提交说明中的命令替换、引号、感叹号 assert.equal(fs.existsSync(path.join(root, 'injected2')), false) }) +test('真实 Windows PowerShell:急救命令原生可执行且无 awk,撤销重名阻断且提交命令防注入', { skip: process.platform !== 'win32' }, () => { + const { root, git, powershell, commits } = fixture() + + // 1. PowerShell 撤销命令真实执行 + 重名备份分支不继续 reset + powershell(undoPs.primaryCommand) + assert.equal(git('rev-parse', 'HEAD'), commits[1]) + assert.equal(git('rev-parse', 'backup/before-undo'), commits[2]) + assert.throws(() => powershell(undoPs.primaryCommand)) + assert.equal(git('rev-parse', 'HEAD'), commits[1], 'PowerShell 下备份分支重名后不得继续 reset') + + // 2. PowerShell 找回被 drop 的 stash 命令真实执行(不依赖 awk) + const stashItem = getEmergencyDatabase('powershell').find((i) => i.id === 'recover-dropped-stash') + assert.doesNotMatch(stashItem.primaryCommand, /\bawk\b/) + fs.writeFileSync(path.join(root, 'sample.txt'), '待暂存改动') + git('stash', 'push', '-m', 'temp-work') + const stashHash = git('rev-parse', 'stash@{0}') + git('stash', 'drop', 'stash@{0}') + const foundHashes = powershell(stashItem.primaryCommand).trim().split(/\r?\n/).map((s) => s.trim()) + assert.ok(foundHashes.includes(stashHash), `PowerShell 应找到悬空 stash 哈希 ${stashHash},实际: ${foundHashes}`) + + // 3. PowerShell 规范提交多段落防注入 + fs.writeFileSync(path.join(root, 'sample.txt'), 'PowerShell 提交测试') + git('add', 'sample.txt') + const built = buildConventionalCommit({ + type: 'feat', + scope: 'ps', + subject: "保留 '单引号'、$env:USER、$(New-Item injected_ps)、! 字符", + body: '正文说明', + footer: 'Closes #99', + shellSyntax: 'powershell' + }) + assert.equal(built.isValid, true) + powershell(built.gitCommand.replace('git commit', 'git -c commit.gpgsign=false commit')) + assert.equal(git('log', '-1', '--format=%B'), built.message) + assert.equal(fs.existsSync(path.join(root, 'injected_ps')), false) +}) + +test('终端语法按宿主平台自动适配,并支持一键切换与分步独立复制', async () => { + await withPlatform('Win32', async () => { + assert.equal(detectDefaultShellSyntax(), 'powershell') + const view = await open(commands['git-emergency']) + assert.match(view.text(), /Windows PowerShell(自动适配)/) + + const stashItem = view.item('recover-dropped-stash') + assert.doesNotMatch(stashItem.props.subtitle, /\bawk\b/) + assert.match(stashItem.props.detail.props.markdown, /```powershell\n/) + + // 分步独立复制:步骤 1 与步骤 2 均独立可执行 + const stashActions = view.actions(stashItem) + assert.ok(stashActions.some((a) => a.props.title === '复制步骤 1')) + assert.ok(stashActions.some((a) => a.props.title === '复制步骤 2')) + await view.run(stashItem, '复制步骤 2') + assert.equal(host.clipboard.text, 'git stash apply "确认后的悬空提交哈希"') + + // 危险操作警示在 Detail 中显式呈现 + const cleanItem = view.item('clean-untracked-files') + assert.match(cleanItem.props.detail.props.markdown, /危险操作警示/) + + // 通过 filterBar 一键切换到 POSIX 语法 + const toggleAction = view.tree().props.filterBar.actions.find((a) => a.id === 'toggle-shell-syntax') + toggleAction.onAction() + await tick() + assert.match(view.text(), /POSIX \(Bash \/ zsh\)(手动切换)/) + assert.match(view.item('recover-dropped-stash').props.subtitle, /\bawk\b/) + }) + + await withPlatform('MacIntel', async () => { + assert.equal(detectDefaultShellSyntax(), 'posix') + const view = await open(commands['git-emergency']) + assert.match(view.text(), /POSIX \(Bash \/ zsh\)(自动适配)/) + assert.match(view.item('undo-last-commit-keep-changes').props.subtitle, /&&/) + }) +}) + test('三个显式入口选择对应模式;空提交说明不生成可复制命令', async () => { - const emergency = await open(commands['git-emergency']) - assert.match(emergency.text(), /git reset --mixed HEAD/) - assert.match(emergency.text(), /复制带说明的操作指南/) - await emergency.run(emergency.item(undo.id), '复制首选救命命令') - assert.equal(host.clipboard.text, undo.primaryCommand) - await emergency.run(emergency.item(undo.id), '复制带说明的操作指南') - assert.ok(host.clipboard.text.split('\n').every(line => line.startsWith('# '))) - const commit = await open(commands['git-commit-builder']) - assert.equal(commit.tree().props.searchBarAccessory.props.value, 'commit') - assert.doesNotMatch(commit.text(), /复制完整 git commit 命令/) - commit.tree().props.onSearchTextChange('auth:修复登录失败'); await tick() - assert.match(commit.text(), /fix\(auth\): 修复登录失败/) - assert.match(commit.text(), /复制完整 git commit 命令/) - await commit.run(commit.item('fix'), '复制完整 git commit 命令') - assert.equal(host.clipboard.text, "git commit -m 'fix(auth): 修复登录失败'") - const ignore = await open(commands['gitignore-generator']) - assert.equal(ignore.tree().props.searchBarAccessory.props.value, 'gitignore') - await ignore.search('Python') - assert.equal(ignore.items().length, 1) - assert.equal(ignore.items()[0].props.id, 'Python') - await ignore.run(ignore.items()[0], '勾选') - assert.match(ignore.text(), /已选 3 个栈/) - assert.match(ignore.text(), /__pycache__/) - assert.match(ignore.text(), /\.idea/, '筛选不清除原有勾选') - await ignore.search('') - for (const item of ignore.items()) { - const toggle = ignore.actions(item).find(action => action.props.title.startsWith('取消勾选')) - if (toggle) await ignore.run(item, toggle.props.title) - } - assert.match(ignore.text(), /已选 0 个栈,去重后 0 条规则/) + await withPlatform('MacIntel', async () => { + const emergency = await open(commands['git-emergency']) + assert.match(emergency.text(), /git reset --mixed HEAD/) + assert.match(emergency.text(), /复制带说明的操作指南/) + await emergency.run(emergency.item(undoPosix.id), '复制首选救命命令') + assert.equal(host.clipboard.text, undoPosix.primaryCommand) + await emergency.run(emergency.item(undoPosix.id), '复制带说明的操作指南') + assert.ok(host.clipboard.text.split('\n').every((line) => line.startsWith('# '))) + + const commit = await open(commands['git-commit-builder']) + assert.equal(commit.tree().props.searchBarAccessory.props.value, 'commit') + assert.doesNotMatch(commit.text(), /复制完整 git commit 命令/) + commit.tree().props.onSearchTextChange('auth:修复登录失败') + await tick() + assert.match(commit.text(), /fix\(auth\): 修复登录失败/) + assert.match(commit.text(), /复制完整 git commit 命令/) + await commit.run(commit.item('fix'), '复制完整 git commit 命令') + assert.equal(host.clipboard.text, "git commit -m 'fix(auth): 修复登录失败'") + + const ignore = await open(commands['gitignore-generator']) + assert.equal(ignore.tree().props.searchBarAccessory.props.value, 'gitignore') + await ignore.search('Python') + assert.ok(ignore.items().some((i) => i.props.id === 'Python')) + await ignore.run(ignore.item('Python'), '勾选') + assert.match(ignore.text(), /已选 3 个栈/) + assert.match(ignore.text(), /__pycache__/) + assert.match(ignore.text(), /\.idea/, '筛选不清除原有勾选') + await ignore.search('') + const clearAction = ignore.tree().props.filterBar.actions.find((a) => a.id === 'clear-gitignore-stacks') + clearAction.onAction() + await tick() + assert.match(ignore.text(), /已选 0 个栈,去重后 0 条规则/) + }) +}) + +test('规范提交生成器 Form:支持类型/作用域/中英文摘要/正文/Footer/破坏性变更与实时预览复制', async () => { + const commitList = await open(commands['git-commit-builder']) + const formBtn = commitList.tree().props.filterBar.actions.find((a) => a.id === 'open-commit-form') + assert.ok(formBtn) + formBtn.onAction() + await tick() + assert.equal(host.pushed.length, 1, '点击规范提交表单应 push 表单页面') + + const formView = await open(() => CommitBuilderForm({ initialType: 'feat', initialShellSyntax: 'powershell' })) + const tree = formView.tree() + assert.equal(tree.type, 'Form') + + // 未填摘要时直接提交:应提示失败且不写入剪贴板 + const submitAction = formView.actions(null).find((a) => a.props.title === '复制完整 git commit 命令') + await submitAction.props.onSubmit() + await tick() + assert.equal(host.clipboard.text, '') + assert.equal(String(host.lastToast().style).toLowerCase(), 'failure') + + // 填写完整字段 + findNode(formView.tree(), (n) => n.props?.id === 'scope').props.onChange('auth') + findNode(formView.tree(), (n) => n.props?.id === 'subject').props.onChange('支持 OAuth2 登录') + findNode(formView.tree(), (n) => n.props?.id === 'body').props.onChange('补充令牌刷新与失效重试') + findNode(formView.tree(), (n) => n.props?.id === 'footer').props.onChange('Closes #128') + findNode(formView.tree(), (n) => n.props?.id === 'breaking').props.onChange(true) + await tick() + findNode(formView.tree(), (n) => n.props?.id === 'breakingDescription').props.onChange('移除旧版 cookie 登录') + await tick() + + // 实时预览应包含完整命令与正文 + const previewNode = findNode(formView.tree(), (n) => n.type === 'Form.Description') + assert.match(previewNode.props.markdown, /feat\(auth\)!: 支持 OAuth2 登录/) + assert.match(previewNode.props.markdown, /BREAKING CHANGE: 移除旧版 cookie 登录/) + assert.match(previewNode.props.markdown, /Closes #128/) + + // 提交复制完整命令 + await formView.actions(null).find((a) => a.props.title === '复制完整 git commit 命令').props.onSubmit() + await tick() + assert.equal( + host.clipboard.text, + "git commit -m 'feat(auth)!: 支持 OAuth2 登录' -m '补充令牌刷新与失效重试' -m 'BREAKING CHANGE: 移除旧版 cookie 登录\nCloses #128'" + ) + assert.equal(String(host.lastToast().style).toLowerCase(), 'success') + + // 仅复制提交说明 + await formView.actions(null).find((a) => a.props.title === '仅复制提交说明').props.onAction() + await tick() + assert.equal( + host.clipboard.text, + 'feat(auth)!: 支持 OAuth2 登录\n\n补充令牌刷新与失效重试\n\nBREAKING CHANGE: 移除旧版 cookie 登录\nCloses #128' + ) + + // 重置表单 + formView.actions(null).find((a) => a.props.title === '重置表单').props.onAction() + await tick() + assert.equal(findNode(formView.tree(), (n) => n.props?.id === 'subject').props.value, '') }) -test('空说明或控制字符拒绝;忽略规则合并去重且保留自定义规则', () => { +test('空说明、非法 scope 或控制字符拒绝;忽略规则合并去重且保留自定义规则', () => { assert.equal(buildConventionalCommit({ type: 'fix', subject: '' }).gitCommand, '') assert.equal(buildConventionalCommit({ type: 'fix', subject: '坏\0内容' }).isValid, false) + assert.equal(buildConventionalCommit({ type: 'fix', scope: 'bad scope', subject: '有效说明' }).isValid, false) + assert.equal(quotePosixShellArg("a'b"), "'a'\"'\"'b'") + assert.equal(quotePowerShellArg("a'b$x"), "'a''b$x'") + const result = generateGitignoreContent(['Node', 'Node'], ['custom-file', 'custom-file']) - assert.equal(result.content.split('\n').filter(line => line === 'custom-file').length, 1) + assert.equal(result.content.split('\n').filter((line) => line === 'custom-file').length, 1) assert.match(result.content, /node_modules/) + const empty = generateGitignoreContent([]) assert.equal(empty.totalUniqueRules, 0) assert.deepEqual(empty.selectedStacks, []) assert.doesNotMatch(empty.content, /DS_Store|Thumbs/) }) -test('scope 解析:网址、含空格的前缀、类型前缀不会被误当作 scope', async () => { - const { parseCommitInput } = await import('../dist/index.js') +test('scope 解析:网址、含空格的前缀、类型前缀不会被误当作 scope', () => { assert.deepEqual(parseCommitInput('auth:修复登录失败'), { scope: 'auth', subject: '修复登录失败' }) assert.deepEqual(parseCommitInput('fix: 修复登录失败'), { scope: '', subject: '修复登录失败' }) assert.deepEqual(parseCommitInput('see https://example.com'), { scope: '', subject: 'see https://example.com' }) @@ -174,57 +438,162 @@ test('换行与制表符按空格处理;其它控制字符给出对应提示 assert.match(bad.validationHint, /控制字符/) assert.match(buildConventionalCommit({ type: 'fix', subject: '' }).validationHint, /不能为空/) const commit = await open(commands['git-commit-builder']) - commit.tree().props.onSearchTextChange('坏\u0007内容'); await tick() + commit.tree().props.onSearchTextChange('坏\u0007内容') + await tick() assert.match(commit.text(), /控制字符/) assert.doesNotMatch(commit.text(), /复制完整 git commit 命令/) }) -test('忽略模板:保留 Cargo.lock、包装器 jar 与 vendor/,macOS 条目齐全且否定规则在忽略规则之后', () => { +test('gitignore 模板库扩充至 30+ 主流栈,保留 Cargo.lock/包装器 jar/vendor/ 且安全合并去重不覆盖已有规则', () => { + assert.ok( + GITIGNORE_STACK_TEMPLATES.length >= 30, + `模板库应 >= 30 个,实际 ${GITIGNORE_STACK_TEMPLATES.length}` + ) + const ids = GITIGNORE_STACK_TEMPLATES.map((tpl) => tpl.id) + for (const required of ['Cpp', 'CSharp', 'Swift', 'Android', 'Flutter', 'Docker', 'Terraform', 'Kubernetes', 'Unity', 'Linux']) { + assert.ok(ids.includes(required), `缺少主流模板: ${required}`) + } + const rust = generateGitignoreContent(['Rust']).content.split('\n') assert.ok(!rust.includes('Cargo.lock')) const go = generateGitignoreContent(['Go']).content.split('\n') assert.ok(!go.includes('vendor/')) const java = generateGitignoreContent(['Java']).content.split('\n') const jar = java.indexOf('*.jar') - assert.ok(jar >= 0 && java.indexOf('!gradle/wrapper/gradle-wrapper.jar') > jar && java.indexOf('!.mvn/wrapper/maven-wrapper.jar') > jar) - const mac = generateGitignoreContent(['macOS']).content.split('\n') - for (const rule of ['.DS_Store', '._*', '.fseventsd', '.TemporaryItems', '.DocumentRevisions-V100']) assert.ok(mac.includes(rule), rule) + assert.ok( + jar >= 0 && + java.indexOf('!gradle/wrapper/gradle-wrapper.jar') > jar && + java.indexOf('!.mvn/wrapper/maven-wrapper.jar') > jar + ) + + // 安全合并去重:保留用户原注释与自定义规则 + const existing = '# 我的自定义规则\nmy-secret.key\nnode_modules/\n' + const generated = generateGitignoreContent(['Node']).content + const merged = mergeGitignoreContent(existing, generated) + assert.equal(merged.changed, true) + assert.equal(merged.skippedDuplicatesCount, 1, 'node_modules/ 应被识别为重复跳过') + assert.ok(merged.mergedContent.startsWith('# 我的自定义规则\nmy-secret.key\nnode_modules/\n')) + assert.equal( + merged.mergedContent.split('\n').filter((l) => l.trim() === 'node_modules/').length, + 1, + '合并后 node_modules/ 只能出现一次' + ) + assert.match(merged.mergedContent, /dist\//) + + // 再次合并同样内容:无新增规则,changed === false + const second = mergeGitignoreContent(merged.mergedContent, generated) + assert.equal(second.changed, false) + assert.equal(second.addedRulesCount, 0) + assert.equal(second.mergedContent, merged.mergedContent) +}) + +test('真实宿主链路:显式选择项目目录创建与安全合并写入 .gitignore(含取消、二次去重与未勾选拦截)', { skip: REAL_HOST_SKIP_REASON }, async () => { + const realHost = createRealHost({ pluginId: 'git-helper' }) + try { + const projectDir = path.join(realHost.tempRoot, 'demo-repo') + fs.mkdirSync(projectDir, { recursive: true }) + const targetFile = path.join(projectDir, '.gitignore') + + const ignore = await mount(commands['gitignore-generator'], realHost) + views.push(ignore) + await tick() + + // 勾选 Node 与 Docker + await ignore.run(ignore.item('Node'), '勾选') + await ignore.run(ignore.item('Docker'), '勾选') + + // 1. 用户取消目录选择:不创建文件 + realHost.queueCancelFolderDialog() + await ignore.run(ignore.item('Node'), '选择项目目录并安全合并写入 .gitignore') + await tick() + assert.equal(fs.existsSync(targetFile), false) + + // 2. 首次选择空项目目录:创建 .gitignore + realHost.queueSelectFolderDialog(projectDir) + await ignore.run(ignore.item('Node'), '选择项目目录并安全合并写入 .gitignore') + await tick() + assert.equal(fs.existsSync(targetFile), true) + const createdText = fs.readFileSync(targetFile, 'utf8') + assert.match(createdText, /node_modules\//) + assert.match(createdText, /\.docker\//) + assert.equal(realHost.lastToast().title, '已创建 .gitignore') + + // 3. 用户手动在 .gitignore 中加入自定义规则后,再合并新模板 Python:保留用户规则且不重复已有规则 + fs.writeFileSync(targetFile, `# 团队保留规则\ncustom-local.db\n${createdText}`, 'utf8') + await ignore.run(ignore.item('Python'), '勾选') + realHost.queueSelectFolderDialog(projectDir) + await ignore.run(ignore.item('Python'), '选择项目目录并安全合并写入 .gitignore') + await tick() + const mergedText = fs.readFileSync(targetFile, 'utf8') + assert.ok(mergedText.startsWith('# 团队保留规则\ncustom-local.db\n')) + assert.match(mergedText, /__pycache__\//) + assert.equal(mergedText.split(/\r?\n/).filter((l) => l.trim() === 'dist/').length, 1) + assert.equal(realHost.lastToast().title, '已安全合并写入 .gitignore') + + // 4. 再次写入同样已选模板:应提示无需更新,文件内容原样不变 + realHost.queueSelectFolderDialog(projectDir) + await ignore.run(ignore.item('Python'), '选择项目目录并安全合并写入 .gitignore') + await tick() + assert.equal(fs.readFileSync(targetFile, 'utf8'), mergedText) + assert.equal(realHost.lastToast().title, '无需更新 .gitignore') + + // 5. 清空已选后尝试写入:应提示失败且不调用对话框 + const clearAction = ignore.tree().props.filterBar.actions.find((a) => a.id === 'clear-gitignore-stacks') + clearAction.onAction() + await tick() + const callsBefore = realHost.ipcCalls.length + await ignore.run(ignore.item('Node'), '选择项目目录并安全合并写入 .gitignore') + await tick() + assert.equal(realHost.ipcCalls.length, callsBefore) + assert.equal(String(realHost.lastToast().style).toLowerCase(), 'failure') + } finally { + await realHost.dispose() + host = createHost() + } }) test('真实 Git:Java 模板不会忽略 Gradle 包装器 jar,Rust 模板不会忽略 Cargo.lock', () => { const { root, git } = fixture() fs.writeFileSync(path.join(root, '.gitignore'), generateGitignoreContent(['Java', 'Rust', 'macOS']).content) fs.mkdirSync(path.join(root, 'gradle/wrapper'), { recursive: true }) - for (const file of ['gradle/wrapper/gradle-wrapper.jar', 'lib.jar', 'Cargo.lock', '.DS_Store']) fs.writeFileSync(path.join(root, file), 'x') - const ignored = file => { try { git('check-ignore', '-q', file); return true } catch { return false } } + for (const file of ['gradle/wrapper/gradle-wrapper.jar', 'lib.jar', 'Cargo.lock', '.DS_Store']) { + fs.writeFileSync(path.join(root, file), 'x') + } + const ignored = (file) => { + try { + git('check-ignore', '-q', file) + return true + } catch { + return false + } + } assert.equal(ignored('gradle/wrapper/gradle-wrapper.jar'), false) assert.equal(ignored('Cargo.lock'), false) assert.equal(ignored('lib.jar'), true) assert.equal(ignored('.DS_Store'), true) }) -const withPlatform = async (platform, fn) => { - const original = Object.getOwnPropertyDescriptor(globalThis, 'navigator') - Object.defineProperty(globalThis, 'navigator', { value: { platform, userAgent: '' }, configurable: true }) - try { return await fn() } finally { - if (original) Object.defineProperty(globalThis, 'navigator', original) - else delete globalThis.navigator - } -} - test('gitignore 默认只勾当前系统与常用 IDE,详情显示模板中文名,首行注释简短,勾选动作标题不截断', async () => { - for (const [platform, system, other] of [['MacIntel', 'macOS', 'Windows'], ['Win32', 'Windows', 'macOS']]) { + for (const [platform, system, other] of [ + ['MacIntel', 'macOS', 'Windows'], + ['Win32', 'Windows', 'macOS'] + ]) { await withPlatform(platform, async () => { const ignore = await open(commands['gitignore-generator']) - const checked = ignore.items().filter(i => i.props.accessories[0].tag === '已勾选合并').map(i => i.props.id) + const checked = ignore + .items() + .filter((i) => i.props.accessories[0].tag === '已勾选合并') + .map((i) => i.props.id) assert.deepEqual(checked.sort(), [system, 'IDEs'].sort(), platform) - assert.ok(ignore.items().find(i => i.props.id === other).props.accessories[0].tag === '未选') - const merged = ignore.item('IDEs').props.detail.props.metadata.children.find(c => c.props.title === '已合并技术栈').props.text + assert.ok(ignore.items().find((i) => i.props.id === other).props.accessories[0].tag === '未选') + const merged = ignore + .item('IDEs') + .props.detail.props.metadata.children.find((c) => c.props.title === '已合并技术栈').props.text assert.match(merged, /VS Code \/ Cursor \/ JetBrains IDE/) assert.doesNotMatch(merged, /^(macOS|Windows|IDEs)(、|$)|IDEs/) - const titles = ignore.actions(ignore.item('IDEs')).map(a => a.props.title) + const titles = ignore.actions(ignore.item('IDEs')).map((a) => a.props.title) assert.ok(titles.includes('取消勾选')) - assert.ok(ignore.actions(ignore.item('Node')).some(a => a.props.title === '勾选')) + assert.ok(ignore.actions(ignore.item('Node')).some((a) => a.props.title === '勾选')) }) } const content = generateGitignoreContent(['Node', 'ReactVue', 'macOS']).content @@ -235,79 +604,80 @@ test('gitignore 默认只勾当前系统与常用 IDE,详情显示模板中文 }) test('翻车详情不重复首选命令;提交类型副标题各不相同、无前缀标签,未写说明时也有主动作', async () => { - const emergency = await open(commands['git-emergency']) - for (const entry of GIT_EMERGENCY_DATABASE) { - const md = emergency.item(entry.id).props.detail.props.markdown - const occurrences = md.split('```bash\n' + entry.primaryCommand + '\n```').length - 1 - assert.equal(occurrences, 1, entry.id) - assert.equal(emergency.actions(emergency.item(entry.id))[0].props.title, '复制首选救命命令') - } - const commit = await open(commands['git-commit-builder']) - const items = commit.items() - assert.equal(new Set(items.map(i => i.props.subtitle)).size, items.length) - assert.ok(items.every(i => !(i.props.accessories || []).some(a => String(a.tag || '').startsWith('前缀')))) - await commit.run(commit.item('feat'), '复制类型前缀 feat:') - assert.equal(host.clipboard.text, 'feat: ') - // 控制字符输入:仍只给前缀,不生成可执行命令 - commit.tree().props.onSearchTextChange('坏\u0000内容'); await tick() - assert.doesNotMatch(commit.text(), /复制完整 git commit 命令/) - assert.equal(commit.actions(commit.item('fix'))[0].props.title, '复制类型前缀 fix:') + await withPlatform('MacIntel', async () => { + const emergency = await open(commands['git-emergency']) + for (const entry of getEmergencyDatabase('posix')) { + const md = emergency.item(entry.id).props.detail.props.markdown + const occurrences = md.split('```bash\n' + entry.primaryCommand + '\n```').length - 1 + assert.equal(occurrences, 1, entry.id) + assert.equal(emergency.actions(emergency.item(entry.id))[0].props.title, '复制首选救命命令') + } + const commit = await open(commands['git-commit-builder']) + const items = commit.items() + assert.equal(new Set(items.map((i) => i.props.subtitle)).size, items.length) + assert.ok(items.every((i) => !(i.props.accessories || []).some((a) => String(a.tag || '').startsWith('前缀')))) + await commit.run(commit.item('feat'), '复制类型前缀 feat:') + assert.equal(host.clipboard.text, 'feat: ') + commit.tree().props.onSearchTextChange('坏\u0000内容') + await tick() + assert.doesNotMatch(commit.text(), /复制完整 git commit 命令/) + assert.equal(commit.actions(commit.item('fix'))[0].props.title, '复制类型前缀 fix:') + }) }) -test('提交生成器用中性文案:分组标题不写内部规范说法,示例不涉及具体内部业务', async () => { - const { COMMIT_TYPES } = await import('../dist/index.js') - const commit = await open(commands['git-commit-builder']) - const text = commit.text() - assert.doesNotMatch(text, /强制中文|团队标准|企业微信|扫码登录|41 款|咽喉|门禁|MFT|标杆插件/) - assert.match(text, /选择 Conventional Commits 提交类型/) - for (const t of COMMIT_TYPES) { - assert.ok(t.examples.length > 0, t.type) - for (const ex of t.examples) assert.match(ex, new RegExp(`^${t.type}\\([a-z]+\\): \\S`), ex) - } - commit.tree().props.onSearchTextChange('auth:修复登录失败'); await tick() - await commit.run(commit.item('fix'), '仅复制提交说明') - assert.equal(host.clipboard.text, 'fix(auth): 修复登录失败') - assert.doesNotMatch(buildConventionalCommit({ type: 'fix', subject: '' }).message, /中文/) -}) +test('提交生成器用中性文案,扩充紧急自救指南至 15+ 条,Conventional Commits 含完整 11 种类型', async () => { + await withPlatform('MacIntel', async () => { + const commit = await open(commands['git-commit-builder']) + const text = commit.text() + assert.doesNotMatch(text, /强制中文|团队标准|企业微信|扫码登录|41 款|咽喉|门禁|MFT|标杆插件/) + assert.match(text, /选择 Conventional Commits 提交类型/) + for (const ct of COMMIT_TYPES) { + assert.ok(ct.examples.length > 0, ct.type) + for (const ex of ct.examples) assert.match(ex, new RegExp(`^${ct.type}\\([a-z]+\\): \\S`), ex) + } + const types = COMMIT_TYPES.map((ct) => ct.type) + for (const required of ['build', 'ci', 'style', 'revert']) { + assert.ok(types.includes(required), `缺少提交类型: ${required}`) + } + assert.ok(GIT_EMERGENCY_DATABASE.length >= 15) + for (const q of ['stash', 'detached', 'rebase', 'clean', 'unstage', 'cherry-pick']) { + assert.ok(searchGitEmergencies(q).length >= 1, `未检索到场景: ${q}`) + } -test('扩充紧急自救指南至 15+ 条,覆盖 stash/detached/rebase/clean/unstage 等高频场景', async () => { - const { searchGitEmergencies } = await import('../dist/index.js') - assert.ok(GIT_EMERGENCY_DATABASE.length >= 15, `紧急自救指南数量不足: ${GIT_EMERGENCY_DATABASE.length}`) - for (const q of ['stash', 'detached', 'rebase', 'clean', 'unstage', 'cherry-pick']) { - const res = searchGitEmergencies(q) - assert.ok(res.length >= 1, `未检索到场景: ${q}`) - } + commit.tree().props.onSearchTextChange('api:移除旧版 v1 接口') + await tick() + await commit.run(commit.item('feat'), '开启破坏性变更标记 (!)') + await tick() + await commit.run(commit.item('feat'), '复制完整 git commit 命令') + assert.equal(host.clipboard.text, "git commit -m 'feat(api)!: 移除旧版 v1 接口'") + await commit.run(commit.item('feat'), '关闭破坏性变更标记 (!)') + await tick() + await commit.run(commit.item('feat'), '仅复制提交说明') + assert.equal(host.clipboard.text, 'feat(api): 移除旧版 v1 接口') + }) }) -test('gitignore 交互修正:Enter 主动作是勾选/取消勾选,Ctrl+Enter 次动作是复制合并结果', async () => { - const ignore = await open(commands['gitignore-generator']) - const nodeActions = ignore.actions(ignore.item('Node')) - assert.equal(nodeActions[0].props.title, '勾选') - assert.equal(nodeActions[1].props.title, '复制合成后的 .gitignore 全文') - assert.deepEqual(nodeActions[1].props.shortcut, { modifiers: ['ctrl'], key: 'enter' }) +test('中英文 i18n 词典键集合与占位符 100% 一致,无空字符串与彩色 Emoji', () => { + const zh = GIT_HELPER_MESSAGES['zh-CN'] + const en = GIT_HELPER_MESSAGES['en-US'] + const zhKeys = Object.keys(zh).sort() + const enKeys = Object.keys(en).sort() + assert.deepEqual(zhKeys, enKeys, 'zh-CN 与 en-US 键集合必须完全一致') - const ideActions = ignore.actions(ignore.item('IDEs')) - assert.equal(ideActions[0].props.title, '取消勾选') - assert.equal(ideActions[1].props.title, '复制合成后的 .gitignore 全文') + const extractPlaceholders = (str) => + [...new Set((str.match(/\{[A-Za-z0-9_]+\}/g) || []))].sort() - // 顶栏(List 级 actions)也提供复制合并 .gitignore - assert.ok(ignore.actions(null).some((a) => a.props.title === '复制合成后的 .gitignore 全文')) -}) + const emojiRe = /\p{Extended_Pictographic}/u -test('Conventional Commits 补齐 build/ci/style/revert 与 Breaking Change (!) 开关', async () => { - const { COMMIT_TYPES } = await import('../dist/index.js') - const types = COMMIT_TYPES.map((t) => t.type) - for (const required of ['build', 'ci', 'style', 'revert']) { - assert.ok(types.includes(required), `缺少提交类型: ${required}`) + for (const key of zhKeys) { + assert.ok(zh[key].trim().length > 0, `zh-CN.${key} 不能为空`) + assert.ok(en[key].trim().length > 0, `en-US.${key} 不能为空`) + assert.deepEqual( + extractPlaceholders(zh[key]), + extractPlaceholders(en[key]), + `占位符不一致: ${key}` + ) + assert.equal(emojiRe.test(zh[key]), false, `zh-CN.${key} 不得包含彩色 Emoji`) + assert.equal(emojiRe.test(en[key]), false, `en-US.${key} 不得包含彩色 Emoji`) } - const commit = await open(commands['git-commit-builder']) - commit.tree().props.onSearchTextChange('api:移除旧版 v1 接口'); await tick() - await commit.run(commit.item('feat'), '开启破坏性变更标记 (!)') - await tick() - await commit.run(commit.item('feat'), '复制完整 git commit 命令') - assert.equal(host.clipboard.text, "git commit -m 'feat(api)!: 移除旧版 v1 接口'") - await commit.run(commit.item('feat'), '关闭破坏性变更标记 (!)') - await tick() - await commit.run(commit.item('feat'), '仅复制提交说明') - assert.equal(host.clipboard.text, 'feat(api): 移除旧版 v1 接口') }) diff --git a/extensions/google-auth/package.json b/extensions/google-auth/package.json index 54b561ef..cade013f 100644 --- a/extensions/google-auth/package.json +++ b/extensions/google-auth/package.json @@ -1,6 +1,6 @@ { "name": "google-auth", - "version": "1.0.4", + "version": "1.0.11", "description": "2FA TOTP 动态口令验证器,支持密钥与二维码URL解析、30秒倒计时刷新、多账号管理与一键复制口令", "type": "module", "main": "dist/index.js", diff --git a/extensions/google-auth/plugin.json b/extensions/google-auth/plugin.json index aaa99720..1ab7fc0e 100644 --- a/extensions/google-auth/plugin.json +++ b/extensions/google-auth/plugin.json @@ -1,7 +1,7 @@ { "id": "google-auth", "name": "2FA 验证码", - "version": "1.0.10", + "version": "1.0.11", "minAppVersion": "1.1.8.0", "description": "桌面端两步验证动态口令(TOTP)管理工具,支持秒级复制 6 位验证码,密钥加密保存在本机", "author": "ZTools Team", diff --git a/extensions/google-auth/src/i18n.ts b/extensions/google-auth/src/i18n.ts index 18a8220c..a2aec175 100644 --- a/extensions/google-auth/src/i18n.ts +++ b/extensions/google-auth/src/i18n.ts @@ -148,7 +148,18 @@ const rawT = createTranslator( copyTokenAction: '复制动态口令', addNewAccountAction: '添加新账号', copySecretAction: '复制 Base32 密钥', - deleteAccountAction: '删除该账号' + deleteAccountAction: '删除该账号', + nextCodePreview: '下周期 {code}', + expiringSoonAccessory: '{sec} 秒后刷新(即将过期)', + copyNextTokenAction: '复制下周期验证码', + toastCopiedNextCode: '已复制 {name} 的下一周期口令', + toastNextCodeHint: '将在 {sec} 秒后生效', + enableMaskAction: '开启脱敏显示', + disableMaskAction: '关闭脱敏显示', + toastMaskEnabled: '已开启脱敏显示', + toastMaskDisabled: '已关闭脱敏显示', + sectionTitleMasked: '已配置账号 ({count}) · 脱敏模式', + sectionTitleReadonlyMasked: '已配置账号 ({count}) · 脱敏模式 · 只读:{reason}' }, 'en-US': { hostUpgradeHint: 'Your ZTools version is too old. Please update to the latest version and try again.', @@ -288,7 +299,18 @@ const rawT = createTranslator( copyTokenAction: 'Copy Code', addNewAccountAction: 'Add Account', copySecretAction: 'Copy Base32 Secret', - deleteAccountAction: 'Delete Account' + deleteAccountAction: 'Delete Account', + nextCodePreview: 'Next {code}', + expiringSoonAccessory: '{sec}s left (expiring)', + copyNextTokenAction: 'Copy Next Code', + toastCopiedNextCode: 'Copied next code for {name}', + toastNextCodeHint: 'Active in {sec}s', + enableMaskAction: 'Mask Codes', + disableMaskAction: 'Show Codes', + toastMaskEnabled: 'Code Masking Enabled', + toastMaskDisabled: 'Code Masking Disabled', + sectionTitleMasked: 'Configured Accounts ({count}) · Masked', + sectionTitleReadonlyMasked: 'Configured Accounts ({count}) · Masked · Read-only: {reason}' } }, { defaultLocale: 'en-US' } diff --git a/extensions/google-auth/src/index.ts b/extensions/google-auth/src/index.ts index e1627e38..8ea82c30 100644 --- a/extensions/google-auth/src/index.ts +++ b/extensions/google-auth/src/index.ts @@ -3,6 +3,7 @@ import { Form, ActionPanel, Action, + Color, Icon, showToast, Toast, @@ -19,7 +20,10 @@ import { import { createAccount, generateTOTP, + generateNextTOTP, formatToken, + maskToken, + isExpiringSoon, getRemainingSeconds, filterAccounts, parseOTPAuthURL, @@ -367,6 +371,7 @@ export default function GoogleAuthCommand() { const [load, setLoadState] = useState({ status: "loading" }); const [reloadSeq, setReloadSeq] = useState(0); const [searchQuery, setSearchQuery] = useState(""); + const [masked, setMasked] = useState(false); const [, setTick] = useState(0); const { push } = useNavigation(); // 表单回调与异步流程读取最新值,不依赖打开表单那一刻捕获的旧闭包 @@ -622,6 +627,46 @@ export default function GoogleAuthCommand() { } }; + const handleToggleMask = async () => { + const next = !masked; + setMasked(next); + await showToast(Toast.Style.Success, next ? t("toastMaskEnabled") : t("toastMaskDisabled")); + }; + + const toggleMaskAction = () => + Action({ + title: masked ? t("disableMaskAction") : t("enableMaskAction"), + icon: masked ? Icon.Eye : Icon.EyeDisabled, + shortcut: { modifiers: ["ctrl", "shift"], key: "m" }, + onAction: handleToggleMask + }); + + // 复制下一周期口令,避免在倒计时即将归零时复制到即将过期的验证码 + const handleCopyNextCode = async (account: AuthAccount) => { + let code: string; + try { + code = generateNextTOTP(account.secret, { + period: account.period, + digits: account.digits, + algorithm: account.algorithm + }); + } catch (err) { + await showToast(Toast.Style.Failure, t("toastGenCodeFailed"), errorText(err)); + return; + } + try { + await Clipboard.copy(code); + } catch (err) { + await showToast(Toast.Style.Failure, t("toastCopyFailed"), errorText(err)); + return; + } + await showToast( + Toast.Style.Success, + t("toastCopiedNextCode", { name: account.name }), + t("toastNextCodeHint", { sec: getRemainingSeconds(account.period) }) + ); + }; + // 复制时按当下时间重新计算,避免在刷新边界复制到刚过期的口令 const handleCopyCode = async (account: AuthAccount) => { let code: string; @@ -759,6 +804,7 @@ export default function GoogleAuthCommand() { actions: ActionPanel({ title: t("globalActionsTitle") }, [ addAction(), importAction(), + toggleMaskAction(), Action({ title: t("refreshTokensAction"), icon: Icon.Repeat, @@ -771,16 +817,30 @@ export default function GoogleAuthCommand() { { title: load.status === "readonly" - ? t("sectionTitleReadonly", { count: filtered.length, reason: load.reason }) - : t("sectionTitleNormal", { count: filtered.length }) + ? masked + ? t("sectionTitleReadonlyMasked", { count: filtered.length, reason: load.reason }) + : t("sectionTitleReadonly", { count: filtered.length, reason: load.reason }) + : masked + ? t("sectionTitleMasked", { count: filtered.length }) + : t("sectionTitleNormal", { count: filtered.length }) }, filtered.length > 0 ? filtered.map((account) => { - const remaining = getRemainingSeconds(account.period); + const nowMs = Date.now(); + const remaining = getRemainingSeconds(account.period, nowMs); + const expiringSoon = isExpiringSoon(remaining); let token = ""; + let nextToken = ""; let tokenError = ""; try { token = generateTOTP(account.secret, { + nowMs, + period: account.period, + digits: account.digits, + algorithm: account.algorithm + }); + nextToken = generateNextTOTP(account.secret, { + nowMs, period: account.period, digits: account.digits, algorithm: account.algorithm @@ -788,17 +848,36 @@ export default function GoogleAuthCommand() { } catch (err) { tokenError = errorText(err) || t("invalidSecretLabel"); } - const displayToken = tokenError ? t("invalidSecretLabel") : formatToken(token); + const displayToken = tokenError + ? t("invalidSecretLabel") + : masked + ? maskToken(account.digits) + : formatToken(token); + const displayNextToken = tokenError + ? "" + : masked + ? maskToken(account.digits) + : formatToken(nextToken); + const subtitle = tokenError + ? tokenError + : [account.issuer, t("nextCodePreview", { code: displayNextToken })].filter(Boolean).join(" · "); return List.Item({ id: account.id, title: `${account.name} — ${displayToken}`, - subtitle: tokenError || account.issuer || undefined, + subtitle: subtitle || undefined, icon: Icon.Shield, accessories: [ - { - text: t("refreshInSecAccessory", { sec: remaining }) - }, + expiringSoon + ? { + tag: { + value: t("expiringSoonAccessory", { sec: remaining }), + color: Color.Red + } + } + : { + text: t("refreshInSecAccessory", { sec: remaining }) + }, { text: t("algoDigitsAccessory", { algo: account.algorithm, digits: account.digits }) } @@ -812,8 +891,15 @@ export default function GoogleAuthCommand() { title: t("copyTokenAction"), icon: Icon.CopyClipboard, onAction: () => handleCopyCode(account) + }), + Action({ + title: t("copyNextTokenAction"), + icon: Icon.ArrowRight, + shortcut: { modifiers: ["ctrl", "shift"], key: "n" }, + onAction: () => handleCopyNextCode(account) }) ]), + toggleMaskAction(), Action({ title: t("copySecretAction"), icon: Icon.Key, diff --git a/extensions/google-auth/src/logic.ts b/extensions/google-auth/src/logic.ts index ac9458d3..ac4e956d 100644 --- a/extensions/google-auth/src/logic.ts +++ b/extensions/google-auth/src/logic.ts @@ -117,6 +117,40 @@ export function generateTOTP( return token; } +/** + * 生成下一周期的 TOTP 动态口令,用于在当前口令即将过期时提前预告/复制 + */ +export function generateNextTOTP( + secret: string, + options: { + nowMs?: number; + period?: number; + digits?: number; + algorithm?: OTPAlgorithm; + } = {} +): string { + const period = options.period && options.period > 0 ? options.period : 30; + const nowMs = options.nowMs !== undefined ? options.nowMs : Date.now(); + return generateTOTP(secret, { ...options, period, nowMs: nowMs + period * 1000 }); +} + +/** + * 脱敏掩码显示口令,防止录屏或旁人窥屏泄露当前验证码 + */ +export function maskToken(digits = 6): string { + const len = Number.isInteger(digits) && digits >= 4 && digits <= 10 ? digits : 6; + if (len === 6) return "••• •••"; + if (len === 8) return "•••• ••••"; + return "•".repeat(len); +} + +/** + * 判断剩余秒数是否已进入临期红标警示窗口(默认 <= 5 秒) + */ +export function isExpiringSoon(remainingSeconds: number, threshold = 5): boolean { + return Number.isFinite(remainingSeconds) && remainingSeconds <= threshold; +} + /** * 格式化口令显示(加空格便于肉眼识别) */ diff --git a/extensions/google-auth/tests/index.test.mjs b/extensions/google-auth/tests/index.test.mjs index 925f75b4..fe39f74f 100644 --- a/extensions/google-auth/tests/index.test.mjs +++ b/extensions/google-auth/tests/index.test.mjs @@ -1,9 +1,10 @@ import test from 'node:test' import assert from 'node:assert/strict' +import { Color } from '@ztools/declarative-ui' import { createHost, mount, mountPushed, tick } from '../../shared/test-harness.mjs' import { installSecureStorage } from './secure-storage-double.mjs' import GoogleAuthCommand from '../dist/index.js' -import { generateTOTP, parseOTPAuthURL, sanitizeStoredAccounts, createAccount, ACCOUNTS_STORAGE_KEY } from '../dist/logic.js' +import { generateTOTP, generateNextTOTP, maskToken, isExpiringSoon, parseOTPAuthURL, sanitizeStoredAccounts, createAccount, ACCOUNTS_STORAGE_KEY } from '../dist/logic.js' const host = createHost() let ss @@ -193,3 +194,63 @@ test('[敏感剪贴板降级与异常] 旧宿主优雅降级 Clipboard.copy, assert.match(host.lastToast().message, /剪贴板写入被拒绝/) } finally { view.unmount() } }) + +test('<=5s 红标警示、脱敏切换、下一周期口令预告与显式添加/导入入口', async () => { + assert.equal(isExpiringSoon(5), true) + assert.equal(isExpiringSoon(1), true) + assert.equal(isExpiringSoon(6), false) + assert.equal(maskToken(6), '••• •••') + assert.equal(maskToken(8), '•••• ••••') + + const acc = createAccount({ name: 'CorpVPN', issuer: 'Corp', secret: 'JBSWY3DPEHPK3PXP', period: 30, digits: 6 }) + ss.put(ACCOUNTS_STORAGE_KEY, [acc]) + + const realNow = Date.now + // 设定时间为周期第 27 秒(剩余 3 秒 <= 5 秒,触发红标警示) + Date.now = () => 1700000007000 // 1700000007 % 30 = 27 => remaining = 3 + try { + const view = await mount(GoogleAuthCommand) + try { + await tick() + // 显式添加/导入入口 + const fbIds = view.tree().props.filterBar.actions.map(a => a.id) + assert.deepEqual(fbIds, ['add-account', 'import-clipboard']) + + const item = view.items().find(i => i.props.id === acc.id) + const expectedCur = generateTOTP(acc.secret, { nowMs: 1700000007000, period: 30, digits: 6, algorithm: 'SHA1' }) + const expectedNext = generateNextTOTP(acc.secret, { nowMs: 1700000007000, period: 30, digits: 6, algorithm: 'SHA1' }) + assert.notEqual(expectedCur, expectedNext) + + // 临期 <=5s 红标警示 + const countdownAcc = item.props.accessories[0] + assert.ok(countdownAcc.tag, '剩余 <=5s 时应展示红标 tag') + assert.equal(countdownAcc.tag.color, Color.Red) + assert.match(countdownAcc.tag.value, /3 秒后刷新(即将过期)/) + + // 下一周期口令预告在副标题中 + assert.match(item.props.subtitle, new RegExp(`下周期 ${expectedNext.slice(0, 3)} ${expectedNext.slice(3)}`)) + + // 开启脱敏显示:标题与下周期预告均隐藏明文,但复制仍写入真实口令 + await view.run(item, '开启脱敏显示') + await tick() + const maskedItem = view.items().find(i => i.props.id === acc.id) + assert.match(maskedItem.props.title, /••• •••/) + assert.match(maskedItem.props.subtitle, /下周期 ••• •••/) + assert.ok(!maskedItem.props.title.includes(expectedCur.slice(0, 3))) + + // 脱敏状态下复制下周期验证码仍得到真实下一周期口令 + await view.run(maskedItem, '复制下周期验证码') + assert.equal(host.clipboard.text, expectedNext) + + // 关闭脱敏恢复明文 + await view.run(maskedItem, '关闭脱敏显示') + await tick() + const unmaskedItem = view.items().find(i => i.props.id === acc.id) + assert.match(unmaskedItem.props.title, new RegExp(`${expectedCur.slice(0, 3)} ${expectedCur.slice(3)}`)) + } finally { + view.unmount() + } + } finally { + Date.now = realNow + } +}) diff --git a/extensions/hardware-info/package.json b/extensions/hardware-info/package.json index da7fdaef..e02ac186 100644 --- a/extensions/hardware-info/package.json +++ b/extensions/hardware-info/package.json @@ -1,6 +1,6 @@ { "name": "@ztools/plugin-hardware-info", - "version": "2.0.8", + "version": "2.0.15", "description": "查看本机 CPU 型号与负载、物理内存、系统版本、磁盘容量、显示器与电源状态,给出 4 个常见场景的估算评分,并可导出 Markdown / JSON / TXT 配置报告", "main": "dist/index.js", "types": "dist/index.d.ts", diff --git a/extensions/hardware-info/plugin.json b/extensions/hardware-info/plugin.json index 4d9d5e79..6a4395ae 100644 --- a/extensions/hardware-info/plugin.json +++ b/extensions/hardware-info/plugin.json @@ -2,7 +2,7 @@ "id": "hardware-info", "name": "硬件信息", "description": "查看电脑 CPU、内存、磁盘容量、显示器与电源状态,支持导出硬件配置报告", - "version": "2.0.14", + "version": "2.0.15", "minAppVersion": "1.1.8.0", "author": "ZTools Team", "entry": "dist/index.js", diff --git a/extensions/hardware-info/src/i18n.ts b/extensions/hardware-info/src/i18n.ts index 00804f0f..cba64c0d 100644 --- a/extensions/hardware-info/src/i18n.ts +++ b/extensions/hardware-info/src/i18n.ts @@ -210,7 +210,24 @@ const rawT = createTranslator( copySpecAction: '复制当前硬件规格摘要', copiedSpecToast: '已复制硬件规格', copyDetailAction: '复制本项详细参数', - copiedDetailToast: '已复制详细参数' + copiedDetailToast: '已复制详细参数', + gpuUnavailableTitle: '图形处理器 (GPU) · 宿主未提供', + gpuUnavailableSubtitle: '当前宿主接口未上报显卡型号与显存,已跳过 3A 游戏与本地 LLM 档位评估', + gpuUnavailableTag: '未提供', + gpuUnavailableMd: '# 图形处理器 (GPU)\n\n- **检测状态**: `宿主未提供显卡与显存信息`\n- **场景评估边界**: 由于未获取到真实 GPU 型号与显存容量,本插件不会编造 3A 游戏或本地大模型(LLM)规格档位。\n\n> 当客户端宿主支持上报真实显卡信息后,此处将自动展示型号、显存与驱动版本。', + gpuTitle: '{name}', + gpuSubtitle: '显存 {vram} · 驱动 {driver}', + gpuTagFallback: 'GPU', + gpuMdHeader: '# 图形处理器 (GPU)', + gpuMdModel: '**显卡型号**: `{name}`', + gpuMdVram: '- **显存容量**: `{vram}`', + gpuMdDriver: '- **驱动版本**: `{driver}`', + gpuReportUnavailable: '宿主未提供(已跳过 3A 游戏与本地 LLM 档位评估)', + mdGpuLine: '- **图形处理器 (GPU)**: `{gpu}`', + txtGpu: '图形处理器: {gpu}', + scGameSummaryGpu: '已检测到 {gpu}(显存 {vram})、{cores} 逻辑线程与 {mem} 内存;仅按显存与核心规格估算,未实测帧率。', + scLlmSummaryGpu: '已检测到 {gpu}(显存 {vram})与 {mem} 系统内存;实际吞吐取决于模型量化方式与计算后端。', + scenarioNoGpuNote: '未获取到显卡/显存数据,已诚实跳过 3A 游戏与本地 LLM 档位评估,仅展示基于真实 CPU/内存/磁盘的参考项。' }, 'en-US': { modCpuInfo: 'CPU Info', @@ -419,7 +436,24 @@ const rawT = createTranslator( copySpecAction: 'Copy Spec Summary', copiedSpecToast: 'Copied Hardware Spec', copyDetailAction: 'Copy Detailed Specs', - copiedDetailToast: 'Copied Detailed Specs' + copiedDetailToast: 'Copied Detailed Specs', + gpuUnavailableTitle: 'Graphics Processor (GPU) · Unavailable', + gpuUnavailableSubtitle: 'Host does not report GPU or VRAM; AAA gaming & local LLM tiers are skipped', + gpuUnavailableTag: 'Unavailable', + gpuUnavailableMd: '# Graphics Processor (GPU)\n\n- **Status**: `Unavailable from host telemetry`\n- **Assessment Boundary**: Because real GPU model and VRAM are not reported by the host, AAA gaming and local LLM spec tiers are intentionally omitted rather than fabricated.\n\n> Once the host reports real GPU telemetry, model, VRAM, and driver version will appear here.', + gpuTitle: '{name}', + gpuSubtitle: 'VRAM {vram} · Driver {driver}', + gpuTagFallback: 'GPU', + gpuMdHeader: '# Graphics Processor (GPU)', + gpuMdModel: '**GPU Model**: `{name}`', + gpuMdVram: '- **VRAM**: `{vram}`', + gpuMdDriver: '- **Driver Version**: `{driver}`', + gpuReportUnavailable: 'Not reported by host (AAA gaming & local LLM tiers omitted)', + mdGpuLine: '- **Graphics (GPU)**: `{gpu}`', + txtGpu: 'Graphics (GPU): {gpu}', + scGameSummaryGpu: 'Detected {gpu} (VRAM {vram}), {cores} logical [[cores:thread|threads]], and {mem} RAM; spec-only estimate, frame rates not benchmarked.', + scLlmSummaryGpu: 'Detected {gpu} (VRAM {vram}) and {mem} system RAM; actual token speed depends on quantization and compute backend.', + scenarioNoGpuNote: 'GPU/VRAM telemetry is unavailable from the host; AAA gaming and local LLM tiers are omitted rather than fabricated.' } }, { defaultLocale: 'en-US' } diff --git a/extensions/hardware-info/src/index.ts b/extensions/hardware-info/src/index.ts index 6dcffe5c..c8f00c71 100644 --- a/extensions/hardware-info/src/index.ts +++ b/extensions/hardware-info/src/index.ts @@ -113,7 +113,7 @@ export default function HardwareInfoCommand() { const entries: HardwareSpecEntry[] = snapshot?.entries || [] const q = searchText.trim().toLowerCase() const filtered = entries.filter((e) => { - if (dropdownFilter === 'cpu-mem' && e.category !== 'cpu' && e.category !== 'memory' && e.category !== 'system') { + if (dropdownFilter === 'cpu-mem' && e.category !== 'cpu' && e.category !== 'gpu' && e.category !== 'memory' && e.category !== 'system') { return false } if (dropdownFilter === 'storage' && e.category !== 'storage') return false @@ -245,6 +245,8 @@ export default function HardwareInfoCommand() { icon: item.category === 'cpu' ? Icon.Bolt + : item.category === 'gpu' + ? Icon.Monitor : item.category === 'memory' ? Icon.Gear : item.category === 'storage' diff --git a/extensions/hardware-info/src/logic.ts b/extensions/hardware-info/src/logic.ts index 336c68d7..a3744f0d 100644 --- a/extensions/hardware-info/src/logic.ts +++ b/extensions/hardware-info/src/logic.ts @@ -16,9 +16,15 @@ import { TELEMETRY_MODULES, LEGACY_DISK_FAILURE_MARKERS } from './telemetry-modu export { formatBytes } from './native-ipc.js' export { TELEMETRY_MODULES } +export interface GpuDeviceInfo { + name: string + vramBytes: number | null + driverVersion: string | null +} + export interface HardwareSpecEntry { id: string - category: 'cpu' | 'memory' | 'storage' | 'display' | 'system' | 'benchmark' + category: 'cpu' | 'gpu' | 'memory' | 'storage' | 'display' | 'system' | 'benchmark' title: string subtitle: string value: string @@ -39,6 +45,9 @@ export interface HardwareTelemetrySnapshot { cpuModel: string | null logicalCpuCount: number | null cpuUsagePercent: number | null + /** 宿主真实上报的 GPU 列表;未上报时为空数组且 gpuAvailable 为 false */ + gpus: GpuDeviceInfo[] + gpuAvailable: boolean totalMemoryBytes: number | null usedMemoryBytes: number | null availableMemoryBytes: number | null @@ -110,6 +119,45 @@ function nonEmptyString(value: unknown): string | null { return typeof value === 'string' && value.trim() ? value.trim() : null } +const IGNORED_GPU_NAMES = new Set(['unknown', 'n/a', 'none', 'unavailable']) + +/** 从宿主硬件摘要中解析真实 GPU 列表;宿主未提供时返回空数组,绝不编造 */ +export function parseGpuDevices(hw: Record | null): GpuDeviceInfo[] { + if (!hw) return [] + const out: GpuDeviceInfo[] = [] + const pushGpu = (rawName: unknown, vramBytesRaw: unknown, vramMbRaw: unknown, driverRaw: unknown) => { + const name = nonEmptyString(rawName) + if (!name || IGNORED_GPU_NAMES.has(name.toLowerCase())) return + const vramBytes = positiveNumber(vramBytesRaw) ?? (positiveNumber(vramMbRaw) !== null ? Math.round(Number(vramMbRaw) * 1024 * 1024) : null) + const driverVersion = nonEmptyString(driverRaw) + out.push({ name, vramBytes, driverVersion }) + } + if (Array.isArray(hw.gpus)) { + for (const item of hw.gpus) { + if (typeof item === 'string') { + pushGpu(item, null, null, null) + } else if (item && typeof item === 'object') { + const rec = item as Record + pushGpu(rec.name ?? rec.model, rec.vramBytes, rec.vramMb, rec.driverVersion) + } + } + } + if (out.length === 0 && Array.isArray(hw.gpuModels)) { + for (const item of hw.gpuModels) pushGpu(item, null, null, null) + } + if (out.length === 0 && typeof hw.gpuModel === 'string') { + pushGpu(hw.gpuModel, hw.gpuVramBytes, hw.gpuVramMb, hw.gpuDriverVersion) + } + return out +} + +function formatGpuSummaryLine(gpus: GpuDeviceInfo[]): string { + if (gpus.length === 0) return t('gpuReportUnavailable') + return gpus + .map(g => (g.vramBytes !== null ? `${g.name} (${formatBytes(g.vramBytes)})` : g.name)) + .join(t('listSeparator')) +} + /** * 磁盘容量的显示单位:macOS 的访达与「关于本机」按 1000 进制显示 GB,Windows 资源管理器按 1024 进制显示 GB。 * 按各自系统的习惯显示,否则同一块 500 GB 的盘在 macOS 上会显示成 466 GB,与访达对不上。内存仍按 1024 进制。 @@ -290,7 +338,8 @@ export function buildSummaryText(snap: HardwareTelemetrySnapshot | null): string } /** - * 仅按已读取的线程数、内存容量计算规格参考分,不代表实测性能或软件兼容性。 + * 仅按已读取的线程数、内存容量与真实 GPU(若有)计算规格参考,不代表实测性能或软件兼容性。 + * 宿主未提供 GPU 信息时诚实跳过 3A 游戏与本地 LLM 档位,严禁凭 CPU/内存编造 GPU 场景档位。 */ export function evaluateHardwareScenarios( logicalCpuCountOrSnap: number | Partial, @@ -298,7 +347,8 @@ export function evaluateHardwareScenarios( /** null / undefined 表示磁盘容量未读到,不能填入默认容量。 */ availableDiskBytesArg?: number | null, /** 磁盘容量按 1000 进制显示(macOS) */ - decimalStorageUnits = false + decimalStorageUnits = false, + gpusArg?: GpuDeviceInfo[] ): ScenarioCompatibilityItem[] { const isSnap = typeof logicalCpuCountOrSnap === 'object' && logicalCpuCountOrSnap !== null const decimalUnits = isSnap @@ -310,12 +360,15 @@ export function evaluateHardwareScenarios( const availableDiskBytes = nonNegativeNumber(isSnap ? logicalCpuCountOrSnap.failures?.some(isDiskFailureMarker) ? null : logicalCpuCountOrSnap.availableDiskBytes : availableDiskBytesArg) + const gpus = isSnap + ? (Array.isArray(logicalCpuCountOrSnap.gpus) ? logicalCpuCountOrSnap.gpus : []) + : (Array.isArray(gpusArg) ? gpusArg : []) const diskKnown = availableDiskBytes !== null const ramGb = totalMemoryBytes / (1024 * 1024 * 1024) const freeDiskGb = availableDiskBytes === null ? null : availableDiskBytes / (1024 * 1024 * 1024) const cores = logicalCpuCount - return [ + const items: ScenarioCompatibilityItem[] = [ { id: 'sc-office-dev', scenario: t('scDevTitle'), @@ -335,22 +388,33 @@ export function evaluateHardwareScenarios( : freeDiskGb !== null && freeDiskGb < 50 ? t('scMediaHintLowDisk') : t('scMediaHintOk') - }, - { - id: 'sc-aaa-gaming', - scenario: t('scGameTitle'), - tier: ramGb >= 15 && cores >= 12 ? t('tierMedium') : t('tierLow'), - summary: t('scGameSummary', { cores, mem: formatBytes(totalMemoryBytes) }), - bottleneckHint: t('scGameHint') - }, - { - id: 'sc-local-llm', - scenario: t('scLlmTitle'), - tier: ramGb >= 30 ? t('tierHigh') : ramGb >= 15 ? t('tierMedium') : t('tierLow'), - summary: t('scLlmSummary', { mem: formatBytes(totalMemoryBytes) }), - bottleneckHint: t('scLlmHint') } ] + + // 仅当宿主上报了真实 GPU 信息时,才评估 3A 游戏与本地 LLM 档位;无 GPU 数据时严禁编造 + if (gpus.length > 0) { + const primaryGpu = gpus.reduce((best, cur) => ((cur.vramBytes ?? 0) > (best.vramBytes ?? 0) ? cur : best), gpus[0]) + const vramGb = primaryGpu.vramBytes !== null ? primaryGpu.vramBytes / (1024 * 1024 * 1024) : null + const vramText = primaryGpu.vramBytes !== null ? formatBytes(primaryGpu.vramBytes) : t('unknownLabel') + items.push( + { + id: 'sc-aaa-gaming', + scenario: t('scGameTitle'), + tier: vramGb !== null && vramGb >= 10 && ramGb >= 15 ? t('tierHigh') : vramGb !== null && vramGb >= 6 ? t('tierMedium') : t('tierLow'), + summary: t('scGameSummaryGpu', { gpu: primaryGpu.name, vram: vramText, cores, mem: formatBytes(totalMemoryBytes) }), + bottleneckHint: t('scGameHint') + }, + { + id: 'sc-local-llm', + scenario: t('scLlmTitle'), + tier: vramGb !== null && vramGb >= 12 ? t('tierHigh') : vramGb !== null && vramGb >= 6 ? t('tierMedium') : t('tierLow'), + summary: t('scLlmSummaryGpu', { gpu: primaryGpu.name, vram: vramText, mem: formatBytes(totalMemoryBytes) }), + bottleneckHint: t('scLlmHint') + } + ) + } + + return items } export function exportHardwareReport( @@ -366,6 +430,7 @@ export function exportHardwareReport( const diskReadFailed = snap.failures.some(isDiskFailureMarker) || snap.driveCount === 0 const warnings = snap.warnings ?? [] const disk = (bytes: number) => storageText(snap, bytes) + const gpuSummary = formatGpuSummaryLine(snap.gpus ?? []) if (format === 'json') { return JSON.stringify( @@ -376,6 +441,11 @@ export function exportHardwareReport( logicalCores: snap.logicalCpuCount, currentUsagePercent: snap.cpuUsagePercent }, + gpu: { + available: Boolean(snap.gpuAvailable), + devices: snap.gpus ?? [], + ...(snap.gpuAvailable ? {} : { note: t('gpuReportUnavailable') }) + }, memory: { totalBytes: snap.totalMemoryBytes, totalFormatted: snap.totalMemoryBytes === null ? null : formatBytes(snap.totalMemoryBytes), @@ -437,6 +507,7 @@ export function exportHardwareReport( ...(failureLine ? [failureLine] : []), ...(reasonLine ? [reasonLine] : []), t('txtCpu', { model: cpuModel, threads, load: cpuLoad }), + t('txtGpu', { gpu: gpuSummary }), t('txtMemory', { total: bytesOrFailed(snap.totalMemoryBytes), used: bytesOrFailed(snap.usedMemoryBytes), percent: percentOrFailed(snap.memoryUsagePercent), avail: bytesOrFailed(snap.availableMemoryBytes) }), t('txtOs', { os: formatOsLine(snap) }), t('txtDisplayPower', { displays: snap.displayCount === null ? displays : t('displayCountOnline', { count: snap.displayCount }), power }), @@ -467,6 +538,7 @@ ${failureLine ? `- **${failureLine}**\n` : ''}${reasonLine ? `- ${reasonLine}\n` ${t('mdSec1Header')} ${t('mdCpuLine', { model: cpuModel, threads, load: cpuLoad })} +${t('mdGpuLine', { gpu: gpuSummary })} ${t('mdMemLine', { total: bytesOrFailed(snap.totalMemoryBytes), used: bytesOrFailed(snap.usedMemoryBytes), percent: percentOrFailed(snap.memoryUsagePercent), avail: bytesOrFailed(snap.availableMemoryBytes) })} ${t('mdOsLine', { os: formatOsLine(snap) })} ${t('mdDispPowerLine', { displays, power })} @@ -479,7 +551,7 @@ ${driveMd} --- ${t('mdSec3Header')} -${t('scenarioEstimateNote')} +${snap.gpuAvailable ? t('scenarioEstimateNote') : `${t('scenarioEstimateNote')} ${t('scenarioNoGpuNote')}`} ${scenarioMd} ` @@ -550,7 +622,7 @@ export async function fetchHardwareTelemetrySnapshot( const failures: string[] = [] const warnings: string[] = [] const noteError = (module: string, res: { ok: boolean; error?: string }) => { if (!res.ok && res.error) warnings.push(`${module}:${res.error}`) } - const hw = hwRes.ok && hwRes.data && typeof hwRes.data === 'object' ? hwRes.data : null + const hw = hwRes.ok && hwRes.data && typeof hwRes.data === 'object' ? hwRes.data as Record : null const sys = sysRes.ok && sysRes.data && typeof sysRes.data === 'object' ? sysRes.data : null // CPU 型号:公共 native-ipc 在宿主没给型号时会填占位值 'x86_64 Processor',同样按未读到处理 @@ -559,6 +631,10 @@ export async function fetchHardwareTelemetrySnapshot( const logicalCpuCount = positiveNumber(hw?.logicalCpuCount) if (cpuModel === null || logicalCpuCount === null) { failures.push(t('modCpuInfo')); noteError(t('modCpuInfo'), hwRes) } + // GPU 显卡信息:宿主上报则原样展示,未上报则诚实标注「未提供」且不编造 3A/LLM 档位 + const gpus = parseGpuDevices(hw) + const gpuAvailable = gpus.length > 0 + const cpuUsagePercent = cpuRes.ok ? usagePercent(cpuRes.data?.total) : null if (cpuUsagePercent === null) { failures.push(t('modCpuLoad')); noteError(t('modCpuLoad'), cpuRes) } @@ -599,7 +675,7 @@ export async function fetchHardwareTelemetrySnapshot( const scenarios = logicalCpuCount !== null && totalMemoryBytes !== null - ? evaluateHardwareScenarios(logicalCpuCount, totalMemoryBytes, drives.length > 0 ? availableDiskBytes : null, isMacPlatform({ platform, osName })) + ? evaluateHardwareScenarios(logicalCpuCount, totalMemoryBytes, drives.length > 0 ? availableDiskBytes : null, isMacPlatform({ platform, osName }), gpus) : [] const loadHeadroomPercent = cpuUsagePercent !== null && memoryUsagePercent !== null @@ -635,6 +711,38 @@ ${t('cpuMdUsage', { usage: percentOrFailed(cpuUsagePercent) })} ${t('cpuMdFooter')}` }, + ...(gpuAvailable + ? gpus.map((gpu, idx): HardwareSpecEntry => { + const vramText = gpu.vramBytes !== null ? formatBytes(gpu.vramBytes) : t('unknownLabel') + const driverText = gpu.driverVersion ?? t('unknownLabel') + return { + id: `hw-gpu-${idx}`, + category: 'gpu', + title: t('gpuTitle', { name: gpu.name }), + subtitle: t('gpuSubtitle', { vram: vramText, driver: driverText }), + value: gpu.vramBytes !== null ? formatBytes(gpu.vramBytes) : '', + tag: gpu.vramBytes !== null ? formatBytes(gpu.vramBytes) : t('gpuTagFallback'), + detailMarkdown: `${t('gpuMdHeader')} + +${t('gpuMdModel', { name: gpu.name })} + +--- + +${t('gpuMdVram', { vram: vramText })} +${t('gpuMdDriver', { driver: driverText })}` + } + }) + : [ + { + id: 'hw-gpu-unavailable', + category: 'gpu' as const, + title: t('gpuUnavailableTitle'), + subtitle: t('gpuUnavailableSubtitle'), + value: '', + tag: t('gpuUnavailableTag'), + detailMarkdown: t('gpuUnavailableMd') + } + ]), { id: 'hw-mem-spec', category: 'memory', @@ -744,6 +852,8 @@ ${t('scMdCheck', { hint: sc.bottleneckHint })}` cpuModel, logicalCpuCount, cpuUsagePercent, + gpus, + gpuAvailable, totalMemoryBytes, usedMemoryBytes, availableMemoryBytes, diff --git a/extensions/hardware-info/tests/hardware-info.audit-regression.test.mjs b/extensions/hardware-info/tests/hardware-info.audit-regression.test.mjs deleted file mode 100644 index ea7700d8..00000000 --- a/extensions/hardware-info/tests/hardware-info.audit-regression.test.mjs +++ /dev/null @@ -1,24 +0,0 @@ -import test from 'node:test' -import assert from 'node:assert/strict' -import { setRuntimeLocale } from '@ztools/declarative-ui' -setRuntimeLocale('zh-CN') -import {createHost} from '../../shared/test-harness.mjs' -import {fetchHardwareTelemetrySnapshot} from '../dist/logic.js' -import {probeRealDiskDrives} from '../dist/volume-ipc.js' -const volume=(path,capacityGroup)=>({path,capacityGroup,label:path,fileSystem:'APFS',totalBytes:100,usedBytes:60,availableBytes:40}) - -test('显示所有挂载卷,APFS容量按容器去重,Windows Z盘不遗漏',async()=>{ - const host=createHost();host.ipc.system_list_volumes=()=>({volumes:[volume('/','disk1'),volume('/System/Volumes/Data','disk1'),volume('/Volumes/外置','disk2'),volume('Z:\\','diskZ')],partial:false}) - const drives=await probeRealDiskDrives();assert.equal(drives.length,4);assert.equal(drives.at(-1).drive,'Z:') - const snapshot=await fetchHardwareTelemetrySnapshot() - assert.equal(snapshot.totalDiskBytes,300) -}) -test('枚举失败如实标注磁盘模块失败;部分卷失败保留读到的卷并标注「部分磁盘卷」与原因',async()=>{ - const host=createHost();let snapshot=await fetchHardwareTelemetrySnapshot();assert.ok(snapshot.failures.includes('磁盘容量')) - assert.ok(snapshot.warnings.some(w=>w.startsWith('磁盘容量:')),'枚举失败的原因不能被吞掉') - host.ipc.system_list_volumes=()=>({volumes:[volume('/','disk1')],partial:true,errors:['外置盘拒绝访问']}) - snapshot=await fetchHardwareTelemetrySnapshot() - assert.ok(!snapshot.failures.includes('磁盘容量'));assert.ok(snapshot.failures.includes('部分磁盘卷')) - assert.equal(snapshot.diskPartial,true);assert.equal(snapshot.driveCount,1);assert.equal(snapshot.totalDiskBytes,100) - assert.deepEqual(snapshot.warnings.filter(w=>w.startsWith('磁盘容量')),['磁盘容量:外置盘拒绝访问']) -}) diff --git a/extensions/hardware-info/tests/hardware-info.estimates.test.mjs b/extensions/hardware-info/tests/hardware-info.estimates.test.mjs deleted file mode 100644 index adbfda5c..00000000 --- a/extensions/hardware-info/tests/hardware-info.estimates.test.mjs +++ /dev/null @@ -1,152 +0,0 @@ -import test from 'node:test' -import assert from 'node:assert/strict' -import { setRuntimeLocale } from '@ztools/declarative-ui' -setRuntimeLocale('zh-CN') -import { createHost, mount, tick } from '../../shared/test-harness.mjs' -import HardwareInfoCommand from '../dist/index.js' -import { evaluateHardwareScenarios, fetchHardwareTelemetrySnapshot, exportHardwareReport, CPU_SAMPLE_INTERVAL_MS } from '../dist/logic.js' - -const GB = 1024 ** 3 -function installHost(host, cpu = 20, memory = 60) { - host.ipc.system_get_hardware_summary = () => ({ cpuModel: '测试处理器', logicalCpuCount: 8, totalMemory: 16 * GB }) - host.ipc.system_get_cpu_usage = () => ({ total: cpu }) - host.ipc.system_get_memory_usage = () => ({ total: 16 * GB, used: memory / 100 * 16 * GB, available: (100 - memory) / 100 * 16 * GB, percent: memory }) - host.ipc.get_system_info = () => ({ platform: 'macos', osName: 'macOS', osVersion: '26.0', kernelRelease: '25.0', osArch: 'arm64' }) - host.ipc.system_get_battery_status = () => ({ percent: 80, isCharging: true }) - host.ipc.screen_get_all_displays = () => [] - host.ipc.system_list_volumes = () => ({ volumes: [{ path: '/', label: '测试卷', fileSystem: 'APFS', totalBytes: 100 * GB, usedBytes: 60 * GB, availableBytes: 40 * GB, capacityGroup: 'fixture' }], partial: false }) -} - -test('缺失、非数字或非法规格不能被补成8线程16GB再评分', () => { - for (const snapshot of [{}, { logicalCpuCount: 8 }, { totalMemoryBytes: 16 * GB }, - { logicalCpuCount: 0, totalMemoryBytes: 16 * GB }, { logicalCpuCount: 1.5, totalMemoryBytes: 16 * GB }, - { logicalCpuCount: 8, totalMemoryBytes: Infinity }, { logicalCpuCount: '8', totalMemoryBytes: 16 * GB }]) { - assert.deepEqual(evaluateHardwareScenarios(snapshot), [], JSON.stringify(snapshot)) - } - assert.deepEqual(evaluateHardwareScenarios(8), []) - assert.deepEqual(evaluateHardwareScenarios(NaN, 16 * GB), []) -}) - -test('未知磁盘不补128GB,零剩余空间仍作为真实值处理', () => { - for (const snapshot of [{ logicalCpuCount: 8, totalMemoryBytes: 16 * GB }, - { logicalCpuCount: 8, totalMemoryBytes: 16 * GB, availableDiskBytes: NaN }, - { logicalCpuCount: 8, totalMemoryBytes: 16 * GB, availableDiskBytes: 40 * GB, failures: ['磁盘容量'] }]) { - const media = evaluateHardwareScenarios(snapshot).find(s => s.id === 'sc-4k-media') - assert.match(media.bottleneckHint, /读取失败/) - assert.doesNotMatch(JSON.stringify(media), /128\.0 GB|高速存储|吞吐表现良好/) - } - assert.match(evaluateHardwareScenarios(8, 16 * GB, 0)[1].bottleneckHint, /空间偏紧/) -}) - -test('空闲余量显示真实边界,满负载不能再给健康高分', async () => { - const host = createHost() - for (const [cpu, memory, expected] of [[0, 0, 100], [100, 100, 0], [20, 60, 40], [90, 10, 10]]) { - installHost(host, cpu, memory) - const snap = await fetchHardwareTelemetrySnapshot() - assert.equal(snap.loadHeadroomPercent, expected) - assert.equal('healthScore' in snap, false) - const report = JSON.parse(exportHardwareReport(snap, 'json')) - assert.equal(report.loadHeadroomPercent, expected) - assert.equal(report.assessment.scenarios, 'spec-estimate') - assert.equal(report.assessment.performanceMeasured, false) - } - host.ipc.system_get_cpu_usage = () => { throw new Error('读取失败') } - assert.equal((await fetchHardwareTelemetrySnapshot()).loadHeadroomPercent, null) -}) - -test('越界负载与未知磁盘不冒充真实100%或零容量', async () => { - const host = createHost() - for (const bad of [180, -1, NaN, Infinity, '20']) { - installHost(host, bad, bad) - const snap = await fetchHardwareTelemetrySnapshot() - assert.equal(snap.cpuUsagePercent, null) - assert.equal(snap.memoryUsagePercent, null) - assert.equal(snap.loadHeadroomPercent, null) - assert.ok(snap.failures.includes('CPU 负载')) - assert.ok(snap.failures.includes('内存占用')) - } - installHost(host) - for (const response of [{ volumes: [], partial: false }, { volumes: [], partial: true, errors: ['拒绝访问'] }]) { - host.ipc.system_list_volumes = () => response - const snap = await fetchHardwareTelemetrySnapshot() - const report = JSON.parse(exportHardwareReport(snap, 'json')) - assert.deepEqual(report.storage, { readFailed: true, driveCount: null, totalBytes: null, availableBytes: null, drives: [] }) - assert.doesNotMatch(exportHardwareReport(snap, 'markdown'), /0 个挂载卷|共 0 B/) - } -}) - -test('列表详情和复制报告都标明估算,不承诺游戏帧率、大模型速度或硬件健康', async () => { - const host = createHost(); installHost(host) - const view = await mount(HardwareInfoCommand, host) - try { - await new Promise((r) => setTimeout(r, CPU_SAMPLE_INTERVAL_MS + 80)) - await tick(20) - await view.dropdown('benchmark') - assert.equal(view.items().length, 4) - for (const item of view.items()) { - assert.match(item.props.detail.props.markdown, /估算/) - assert.match(item.props.detail.props.markdown, /线程数.*内存容量/) - assert.match(JSON.stringify(item.props.accessories), /估算/) - assert.doesNotMatch(item.props.detail.props.markdown, /实测兼容性|极致流畅|轻松承载|零延迟直连|流畅运行|高画质纹理加载需求/) - } - await view.dropdown('report') - await view.run(view.item('report-md'), '复制 Markdown 硬件报告到剪贴板') - assert.match(host.clipboard.text, /规格估算/) - assert.match(host.clipboard.text, /未运行性能测试/) - assert.doesNotMatch(host.clipboard.text, /实测兼容性|健康度|性能评测报告/) - const snap = await fetchHardwareTelemetrySnapshot() - assert.match(exportHardwareReport(snap, 'txt'), /空闲余量/) - assert.doesNotMatch(exportHardwareReport(snap, 'txt'), /健康度|综合健康评分/) - } finally { view.unmount() } -}) - -test('状态条不再紧挨 CPU 负载显示“余量”,下拉与按钮不带英文括注,CPU 详情不用 [!TIP] 写法', async () => { - const host = createHost() - installHost(host, 29, 63) - const view = await mount(HardwareInfoCommand, host) - try { - for (let i = 0; i < 20 && view.tree().props.isLoading; i++) await tick() - await new Promise(r => setTimeout(r, CPU_SAMPLE_INTERVAL_MS + 50)); await tick() - const tree = view.tree() - assert.match(tree.props.filterBar.summaryText, /^CPU 8 线程/) - assert.doesNotMatch(tree.props.filterBar.summaryText, /余量/) - const titles = tree.props.searchBarAccessory.children.map(c => c.props.title) - assert.ok(titles.includes('全部硬件模块')) - assert.ok(titles.every(t => !/[A-Za-z]{3,}\)/.test(t)), titles.join(',')) - assert.ok(tree.props.filterBar.actions.some(a => a.title === '复制 Markdown 报告')) - const md = view.item('hw-cpu-spec').props.detail.props.markdown - assert.doesNotMatch(md, /\[!TIP\]/) - assert.match(md, /^# 中央处理器\n/) - } finally { view.unmount() } - // 报告里仍给出空闲余量,读取失败时不计算 - const snap = await fetchHardwareTelemetrySnapshot() - assert.match(exportHardwareReport(snap, 'markdown'), /空闲余量/) -}) - -test('场景估算只给档位不给分数,档位与阈值一致,场景名不带英文括注', async () => { - // 12 线程 + 16 GB:旧版“3A 游戏”是“规格参考一般”而分数却低于“4K 剪辑”,互相矛盾 - for (const [cores, ram] of [[8, 16], [12, 16], [16, 32], [4, 8]]) { - const list = evaluateHardwareScenarios(cores, ram * GB, 100 * GB) - assert.equal(list.length, 4) - for (const sc of list) { - assert.equal('score' in sc, false, sc.id) - assert.doesNotMatch(sc.scenario, /[((][A-Za-z /]+[))]/, sc.scenario) - } - } - const host = createHost(); installHost(host) - const view = await mount(HardwareInfoCommand, host) - try { - await new Promise((r) => setTimeout(r, CPU_SAMPLE_INTERVAL_MS + 80)) - await tick(20) - await view.dropdown('benchmark') - for (const item of view.items()) { - const text = JSON.stringify(item.props.accessories) + item.props.detail.props.markdown - assert.doesNotMatch(text, /\d+\s*分|\/ 100/, item.props.title) - } - const snap = await fetchHardwareTelemetrySnapshot() - for (const format of ['markdown', 'txt']) { - const report = exportHardwareReport(snap, format) - assert.doesNotMatch(report, /估算 \d+分|\((CPU|RAM|OS)\)|Ollama/, format) - } - } finally { view.unmount() } -}) diff --git a/extensions/hardware-info/tests/hardware-info.fixes.test.mjs b/extensions/hardware-info/tests/hardware-info.fixes.test.mjs deleted file mode 100644 index 29d93002..00000000 --- a/extensions/hardware-info/tests/hardware-info.fixes.test.mjs +++ /dev/null @@ -1,440 +0,0 @@ -// hardware-info 本轮修复的集成测试:用 plugins/shared/test-harness.mjs 在 Node 中渲染插件 dist, -// 经 preload IPC 模拟宿主(含故障注入),覆盖「读取失败不伪造数据」「macOS 系统版本 / 内核 / Build」「名称与能力一致」。 -import test from 'node:test' -import assert from 'node:assert/strict' -import { setRuntimeLocale } from '@ztools/declarative-ui' -setRuntimeLocale('zh-CN') -import { readFileSync } from 'node:fs' -import { createHost, mount, tick } from '../../shared/test-harness.mjs' -import HardwareInfoCommand from '../dist/index.js' -import { exportHardwareReport, fetchHardwareTelemetrySnapshot, CPU_SAMPLE_INTERVAL_MS } from '../dist/logic.js' - -const GB = 1024 ** 3 - -// 快照读取时 CPU 负载要间隔 CPU_SAMPLE_INTERVAL_MS 采样两次,等待时间要覆盖这段间隔 -async function settle() { - await tick(20) - await new Promise((r) => setTimeout(r, CPU_SAMPLE_INTERVAL_MS + 80)) - await tick(20) -} - -/** 与 macOS 真机宿主返回结构一致(get_system_info 没有 osBuild,只有 kernelRelease) */ -function installMacHost(host) { - host.ipc.system_list_volumes = async () => ({ volumes: [{ path: '/', label: 'Macintosh HD', fileSystem: 'APFS', totalBytes: 500 * 1024 ** 3, usedBytes: 100 * 1024 ** 3, availableBytes: 400 * 1024 ** 3, capacityGroup: 'disk3' }], partial: false, errors: [] }) - host.ipc.system_get_hardware_summary = async () => ({ platform: 'macos', osVersion: '26.5.1', cpuModels: ['Apple M1 Pro'], logicalCpuCount: 8, totalMemory: 16 * GB }) - host.ipc.get_system_info = async () => ({ success: true, platform: 'macos', osName: 'macOS', osVersion: '26.5.1', kernelRelease: '25.5.0', osArch: 'arm64' }) - host.ipc.system_get_cpu_usage = async () => ({ total: 12.4, perCore: [] }) - host.ipc.system_get_memory_usage = async () => ({ total: 16 * GB, used: 9 * GB, available: 7 * GB, percent: 56 }) - host.ipc.system_get_battery_status = async () => ({ percent: 80, isCharging: true, timeRemaining: -1 }) - host.ipc.screen_get_all_displays = async () => ({ success: true, displays: [{ id: 1, name: '内建视网膜显示器', bounds: { x: 0, y: 0, width: 1800, height: 1169 }, scaleFactor: 2, displayFrequency: 120, colorDepth: 30 }] }) - host.ipc.system_get_disk_usage = async ({ drive }) => { - if (!String(drive).startsWith('/')) throw Object.assign(new Error('卷路径必须是 POSIX 绝对路径'), { code: 'INVALID_REQUEST' }) - return { total: 460 * GB, used: 97 * GB, free: 363 * GB, percent: 21 } - } -} - -const FAKE_DEFAULTS = /x86_64 Processor|Windows|X64|\bx64\b|16\.0 GB|8 线程|8 逻辑线程|Build 0|健康度 \d+|0% 已用/ - -// ---------------- 宿主读取失败时不得用写死的数据冒充,也不得提示成功 ---------------- - -test('全部宿主接口失败:界面不出现 Windows/x64/16GB/8 线程等假数据,弹失败提示而非「已刷新」', async () => { - const host = createHost() - host.reset() // 不注册任何 IPC:测试宿主对每个方法都返回 NOT_SUPPORTED - const view = await mount(HardwareInfoCommand, host) - await settle() - - const tree = view.tree() - assert.equal(tree.props.filterBar.summaryText, '硬件信息读取失败,可点击「刷新」重试') - const text = view.text() - assert.doesNotMatch(text, FAKE_DEFAULTS) - assert.equal(view.item('hw-cpu-spec').props.title, '处理器型号读取失败') - assert.equal(view.item('hw-mem-spec').props.title, '物理内存容量读取失败') - assert.equal(view.item('hw-os-spec').props.title, '操作系统读取失败') - // 空闲余量与场景估算在数据缺失时不计算 - assert.equal(view.items().filter((it) => String(it.props.id).startsWith('sc-')).length, 0) - assert.equal(host.lastToast().style, 'FAILURE') - assert.equal(host.lastToast().title, '硬件信息读取失败') - - // 用户点「刷新」:仍然失败,必须继续提示失败,绝不弹成功 - host.toasts.length = 0 - await tree.props.filterBar.actions.find((a) => a.id === 'refresh-hw').onAction() - await settle() - assert.ok(host.toasts.length > 0) - assert.ok(host.toasts.every((t) => t.style === 'FAILURE'), JSON.stringify(host.toasts)) - view.unmount() -}) - -test('全部失败时导出的三种报告如实标注读取失败,JSON 为 null 且列出失败模块', async () => { - createHost().reset() // 不注册任何 IPC:preload 每个方法都返回 NOT_SUPPORTED - const snap = await fetchHardwareTelemetrySnapshot({}) // hostOverride 没有任何方法 → 回落到 preload IPC,全部失败 - const fallbackFree = await fetchHardwareTelemetrySnapshot({ - system_get_hardware_summary: async () => { throw new Error('IPC 管道断开') }, - get_system_info: async () => ({ success: false, error: { code: 'TIMEOUT' } }), - system_get_cpu_usage: async () => null, - system_get_memory_usage: async () => ({ success: false, error: 'boom' }), - system_get_battery_status: async () => { throw new Error('pmset 崩溃') }, - screen_get_all_displays: async () => ({ success: false, error: { message: 'screen 不可用' } }), - system_get_disk_usage: async () => { throw new Error('statfs 失败') } - }) - for (const s of [snap, fallbackFree]) { - assert.equal(s.cpuModel, null) - assert.equal(s.logicalCpuCount, null) - assert.equal(s.totalMemoryBytes, null) - assert.equal(s.osName, null) - assert.equal(s.osBuild, null) - assert.equal(s.loadHeadroomPercent, null) - assert.deepEqual(s.scenarios, []) - assert.equal(s.displayCount, null) - assert.equal(s.powerReadFailed, true) - assert.deepEqual(s.failures, ['处理器信息', 'CPU 负载', '内存占用', '系统版本', '电源状态', '显示器', '磁盘容量']) - - const md = exportHardwareReport(s, 'markdown') - const txt = exportHardwareReport(s, 'txt') - for (const report of [md, txt]) { - assert.doesNotMatch(report, FAKE_DEFAULTS) - assert.match(report, /型号读取失败/) - assert.match(report, /电源状态读取失败/) - assert.match(report, /未能读取: 处理器信息、CPU 负载/) - } - const json = JSON.parse(exportHardwareReport(s, 'json')) - assert.equal(json.cpu.model, null) - assert.equal(json.memory.totalBytes, null) - assert.equal(json.os.build, null) - assert.equal(json.loadHeadroomPercent, null) - assert.equal(json.readFailures.length, 7) - } -}) - -test('只有内存接口失败:显示「占用读取失败」而不是 0% 已用,空闲余量不计算,失败提示只列内存占用', async () => { - const host = createHost() - host.reset() - installMacHost(host) - delete host.ipc.system_get_memory_usage - const view = await mount(HardwareInfoCommand, host) - await settle() - - const mem = view.item('hw-mem-spec') - assert.equal(mem.props.title, '物理内存总容量 16.0 GB') // 总量回退到硬件摘要里的真实值 - assert.deepEqual(mem.props.accessories.map((a) => a.text ?? a.tag?.value), ['16.0 GB', '占用读取失败']) - assert.doesNotMatch(view.text(), /0% 已用|整机健康度/) - assert.equal(view.item('hw-cpu-spec').props.title, 'Apple M1 Pro') - assert.equal(host.lastToast().style, 'FAILURE') - // 失败原因跟在模块名后面,不吞掉宿主的报错 - assert.match(host.lastToast().message, /^未能读取:内存占用。内存占用:\S/) - view.unmount() -}) - -test('畸形宿主数据(NaN / 负数 / 字符串 / 公共层占位型号)按读取失败处理,不当真实值展示', async () => { - const snap = await fetchHardwareTelemetrySnapshot({ - // 宿主成功但没给型号:公共 native-ipc 会填 'x86_64 Processor' 占位,插件必须识别为未读到 - system_get_hardware_summary: async () => ({ logicalCpuCount: Number.NaN, totalMemory: -1 }), - get_system_info: async () => ({ osName: ' ', osVersion: 42, osBuild: 0, osArch: '' }), - system_get_cpu_usage: async () => ({ total: 'high' }), - system_get_memory_usage: async () => ({ total: '16G', used: -5, available: Number.POSITIVE_INFINITY, percent: Number.NaN }), - system_get_battery_status: async () => ({ percent: 77, isCharging: false }), - screen_get_all_displays: async () => 'not-an-array', - system_get_disk_usage: async () => ({ total: 0, used: 0, percent: 0 }) - }) - assert.equal(snap.cpuModel, null) - assert.equal(snap.logicalCpuCount, null) - assert.equal(snap.cpuUsagePercent, null) - assert.equal(snap.totalMemoryBytes, null) - assert.equal(snap.usedMemoryBytes, null) - assert.equal(snap.availableMemoryBytes, null) - assert.equal(snap.memoryUsagePercent, null) - assert.equal(snap.osName, null) - assert.equal(snap.osVersion, null) - assert.equal(snap.osBuild, null) - assert.equal(snap.displayCount, null) - assert.equal(snap.batteryPercent, 77) // 合法字段照常使用 - assert.equal(snap.powerReadFailed, false) - assert.ok(!snap.failures.includes('电源状态')) - const text = JSON.stringify(snap.entries) - assert.doesNotMatch(text, /x86_64 Processor|NaN|Infinity|Build 0/) -}) - -test('CPU 负载 0% 与超过 100% 的边界:0 是真实值,超限值标读取失败', async () => { - const base = { - system_get_hardware_summary: async () => ({ cpuModel: 'Apple M2', logicalCpuCount: 8, totalMemory: 8 * GB }), - get_system_info: async () => ({ platform: 'macos', osName: 'macOS', osVersion: '15.0', kernelRelease: '24.0.0', osArch: 'arm64' }), - system_get_memory_usage: async () => ({ total: 8 * GB, used: 0, available: 8 * GB, percent: 0 }), - system_get_battery_status: async () => ({ percent: 50, isCharging: false }), - screen_get_all_displays: async () => [], - system_list_volumes: async () => ({ volumes: [{ path: '/', label: 'Macintosh HD', fileSystem: 'APFS', totalBytes: 500 * 1024 ** 3, usedBytes: 100 * 1024 ** 3, availableBytes: 400 * 1024 ** 3, capacityGroup: 'disk3' }], partial: false, errors: [] }), - system_get_disk_usage: async ({ drive }) => (drive === '/' ? { total: 100 * GB, used: 10 * GB, available: 90 * GB, percent: 10 } : { success: false }) - } - const idle = await fetchHardwareTelemetrySnapshot({ ...base, system_get_cpu_usage: async () => ({ total: 0 }) }) - assert.equal(idle.cpuUsagePercent, 0) - assert.equal(idle.memoryUsagePercent, 0) - assert.equal(idle.usedMemoryBytes, 0) - assert.equal(typeof idle.loadHeadroomPercent, 'number') - assert.deepEqual(idle.failures, []) - assert.equal(idle.displayCount, 0) // 接口成功但没有显示器:0 台,不算读取失败 - const spike = await fetchHardwareTelemetrySnapshot({ ...base, system_get_cpu_usage: async () => ({ total: 180 }) }) - assert.equal(spike.cpuUsagePercent, null) - assert.equal(spike.loadHeadroomPercent, null) - assert.ok(spike.failures.includes('CPU 负载')) -}) - -test('宿主恢复后点「刷新」:数据自愈为真实值并提示「硬件信息已刷新」;连续并发刷新不抛错且结果一致', async () => { - const host = createHost() - host.reset() - const view = await mount(HardwareInfoCommand, host) - await settle() - assert.equal(view.item('hw-cpu-spec').props.title, '处理器型号读取失败') - - installMacHost(host) - host.toasts.length = 0 - const refresh = view.tree().props.filterBar.actions.find((a) => a.id === 'refresh-hw') - await refresh.onAction() - await settle() - assert.equal(view.item('hw-cpu-spec').props.title, 'Apple M1 Pro') - assert.equal(host.lastToast().style, 'SUCCESS') - assert.equal(host.lastToast().title, '硬件信息已刷新') - assert.match(view.tree().props.filterBar.summaryText, /^CPU 8 线程 \(负载 12%\)/) - - // 连续 5 次点「刷新」:只采用最后一次的结果,只弹一次成功提示,无失败提示 - host.toasts.length = 0 - const refreshButton = view.tree().props.filterBar.actions.find((a) => a.id === 'refresh-hw') - await Promise.all(Array.from({ length: 5 }, () => refreshButton.onAction())) - await settle() - assert.equal(view.item('hw-cpu-spec').props.title, 'Apple M1 Pro') - assert.equal(host.toasts.length, 1) - assert.ok(host.toasts.every((t) => t.style === 'SUCCESS')) - view.unmount() -}) - -test('复制报告:宿主剪贴板拒绝写入时提示「复制失败」,不提示已导出', async () => { - const host = createHost() - host.reset() - installMacHost(host) - const view = await mount(HardwareInfoCommand, host) - await settle() - // 正常复制 - host.toasts.length = 0 - await view.tree().props.filterBar.actions.find((a) => a.id === 'export-md').onAction() - await settle() - assert.match(host.clipboard.text, /Apple M1 Pro/) - assert.equal(host.lastToast().style, 'SUCCESS') - - // 构造一个超出宿主 8 MiB 上限的标题,让宿主剪贴板拒绝写入 - host.ipc.system_get_hardware_summary = async () => ({ cpuModel: 'X'.repeat(9 * 1024 * 1024), logicalCpuCount: 8, totalMemory: 16 * GB }) - await view.tree().props.filterBar.actions.find((a) => a.id === 'refresh-hw').onAction() - await settle() - host.toasts.length = 0 - await view.run(view.item('hw-cpu-spec'), '复制当前硬件规格摘要') - assert.equal(host.lastToast().style, 'FAILURE') - assert.equal(host.lastToast().title, '复制失败') - view.unmount() -}) - -// ---------------- macOS 不能把产品版本当内核版本,也不能显示假的 Build 0 ---------------- - -test('macOS:系统行显示「系统版本 26.5.1 · Darwin 内核 25.5.0」,界面与三种报告都不出现 Build 0', async () => { - const host = createHost() - host.reset() - installMacHost(host) - const view = await mount(HardwareInfoCommand, host) - await settle() - - const os = view.item('hw-os-spec') - assert.equal(os.props.title, 'macOS (arm64)') - assert.equal(os.props.subtitle, '系统版本 26.5.1 · Darwin 内核 25.5.0') - assert.deepEqual(os.props.accessories.map((a) => a.text ?? a.tag?.value), ['26.5.1', '内核 25.5.0']) - const md = os.props.detail.props.markdown - assert.match(md, /系统版本\*\*: `26\.5\.1`/) - assert.match(md, /Darwin 内核版本\*\*: `25\.5\.0`/) - assert.doesNotMatch(view.text(), /Build|内核版本 26\.5\.1/) - - const snap = await fetchHardwareTelemetrySnapshot() - assert.equal(snap.osBuild, null) - assert.equal(snap.kernelVersion, '25.5.0') - const report = exportHardwareReport(snap, 'markdown') - assert.match(report, /`macOS 26\.5\.1 \(Darwin 内核 25\.5\.0, arm64\)`/) - assert.match(exportHardwareReport(snap, 'txt'), /操作系统: macOS 26\.5\.1 \(Darwin 内核 25\.5\.0, arm64\)/) - for (const r of [report, exportHardwareReport(snap, 'txt')]) assert.doesNotMatch(r, /Build/) - const json = JSON.parse(exportHardwareReport(snap, 'json')) - assert.deepEqual(json.os, { name: 'macOS', version: '26.5.1', kernel: '25.5.0', build: null, arch: 'arm64' }) - view.unmount() -}) - -test('Windows:宿主真实提供 osBuild 时显示内核版本与 Build(NT 版本号只显示一次);Build 为 0/负数时隐藏', async () => { - const winSys = { success: true, platform: 'windows', osName: 'Windows 11 Pro', osVersion: '10.0.22631', osMajor: 10, osMinor: 0, osBuild: 22631, windowsFamily: 'Windows NT', windowsRelease: '10.0.22631', osArch: 'x64' } - const host = { - system_get_hardware_summary: async () => ({ cpuModel: 'AMD Ryzen 9 7950X', logicalCpuCount: 32, totalMemory: 64 * GB }), - get_system_info: async () => winSys, - system_get_cpu_usage: async () => ({ total: 5 }), - system_get_memory_usage: async () => ({ total: 64 * GB, used: 20 * GB, available: 44 * GB, percent: 31 }), - system_get_battery_status: async () => ({ percent: 255, isCharging: false }), - screen_get_all_displays: async () => [], - system_get_disk_usage: async ({ drive }) => (drive === 'C:\\' ? { total: 1000 * GB, used: 400 * GB, free: 600 * GB, percent: 40 } : { success: false, error: 'NOT_FOUND' }) - } - const snap = await fetchHardwareTelemetrySnapshot(host) - const os = snap.entries.find((e) => e.id === 'hw-os-spec') - assert.equal(os.title, 'Windows 11 Pro (x64)') - assert.equal(os.subtitle, '内核版本 10.0.22631 · Build 22631') - assert.equal(os.value, 'Build 22631') - assert.match(exportHardwareReport(snap, 'txt'), /Windows 11 Pro 10\.0\.22631 \(Build 22631, x64\)/) - - for (const badBuild of [0, -3, Number.NaN, '22631']) { - const s = await fetchHardwareTelemetrySnapshot({ ...host, get_system_info: async () => ({ ...winSys, osBuild: badBuild }) }) - assert.equal(s.osBuild, null, String(badBuild)) - assert.doesNotMatch(JSON.stringify(s.entries) + exportHardwareReport(s, 'markdown'), /Build/) - } -}) - -// ---------------- 名称、描述与界面文案不能承诺未实现的温度 / 显卡 / 主板 / SPD / SMART ---------------- - -const UNIMPLEMENTED = /温度|传感器|显卡|GPU|主板|SPD|SMART|HardwareInfoPlugin\.dll/ - -test('plugin.json / README 只描述实际提供的能力', () => { - const manifest = JSON.parse(readFileSync(new URL('../plugin.json', import.meta.url), 'utf8')) - assert.equal(manifest.name, '硬件信息') - assert.doesNotMatch(manifest.name + manifest.description, UNIMPLEMENTED) - assert.match(manifest.description, /CPU/) - assert.match(manifest.description, /内存/) - assert.match(manifest.description, /显示器/) - assert.deepEqual(manifest.nativeComponents, []) - const readme = readFileSync(new URL('../README.md', import.meta.url), 'utf8') - assert.doesNotMatch(readme.split('暂不提供')[0], UNIMPLEMENTED) - assert.doesNotMatch(readme, /\.dll/) -}) - -test('界面(下拉、状态条按钮、动作、提示)不再出现温度 / 传感器 / 显卡等未实现能力', async () => { - const host = createHost() - host.reset() - installMacHost(host) - const view = await mount(HardwareInfoCommand, host) - await settle() - const tree = view.tree() - const dropdownTitles = tree.props.searchBarAccessory.children.map((c) => c.props.title) - assert.ok(dropdownTitles.includes('显示器')) - assert.deepEqual(tree.props.filterBar.actions.map((a) => a.title), ['刷新', '复制 Markdown 报告']) - const actionTitles = view.actions(view.item('hw-cpu-spec')).map((a) => a.props.title) - // 刷新与整机报告只在状态条出现一次,行动作只针对本项;不声明会撞 macOS 菜单(⌘R 重新载入)的快捷键 - assert.deepEqual(actionTitles, ['复制当前硬件规格摘要', '复制本项详细参数']) - assert.ok(view.actions(view.item('hw-cpu-spec')).every((a) => !a.props.shortcut)) - await view.dropdown('display') - assert.equal(view.items().length, 1) - assert.match(view.items()[0].props.subtitle, /刷新率 120Hz/) - await view.dropdown('report') - await tree.props.filterBar.actions[0].onAction() - await settle() - const visible = view.text() + JSON.stringify(host.toasts) - // 详情允许说明未检测的能力;这里检查标题、下拉、按钮、动作与提示没有承诺未实现的检测 - const chrome = JSON.stringify({ - placeholder: tree.props.searchBarPlaceholder, - dropdownTitles, - bar: tree.props.filterBar, - actionTitles, - toasts: host.toasts - }) - assert.doesNotMatch(chrome, UNIMPLEMENTED) - assert.doesNotMatch(visible, /传感器|温度/) - view.unmount() -}) - -// ---------------- Windows 走通用系统接口、电源三态、部分卷、失败原因 ---------------- - -/** 与 Windows 真机宿主返回结构一致(get_system_info 带 osBuild,卷路径是盘符) */ -function installWindowsHost(host, overrides = {}) { - host.ipc.system_get_hardware_summary = async () => ({ platform: 'windows', osVersion: '10.0.22631', cpuModels: ['Intel(R) Core(TM) i7-1260P'], logicalCpuCount: 16, totalMemory: 32 * GB }) - host.ipc.get_system_info = async () => ({ success: true, platform: 'windows', osName: 'Windows 11 Pro', osVersion: '10.0.22631', osBuild: 22631, windowsRelease: '10.0.22631', osArch: 'x64' }) - host.ipc.system_get_cpu_usage = async () => ({ total: 7, perCore: [] }) - host.ipc.system_get_memory_usage = async () => ({ total: 32 * GB, used: 12 * GB, available: 20 * GB, percent: 38 }) - host.ipc.system_get_battery_status = async () => ({ success: true, percent: 255, isCharging: false, timeRemaining: -1, batteryState: 'present', powerSource: 'battery' }) - host.ipc.screen_get_all_displays = async () => ({ success: true, displays: [{ id: 7, name: 'DELL U2723QE', bounds: { x: 0, y: 0, width: 2560, height: 1440 }, scaleFactor: 1.5, displayFrequency: 60, colorDepth: 24 }] }) - host.ipc.system_list_volumes = async () => ({ volumes: [ - { path: 'C:\\', label: '系统', fileSystem: 'NTFS', totalBytes: 512 * GB, usedBytes: 300 * GB, availableBytes: 212 * GB, capacityGroup: 'vol-c' }, - { path: 'Z:\\', label: '资料', fileSystem: 'NTFS', totalBytes: 1000 * GB, usedBytes: 100 * GB, availableBytes: 900 * GB, capacityGroup: 'vol-z' } - ], partial: true, errors: ['D:\\: 卷容量读取失败'] }) - Object.assign(host.ipc, overrides) -} - -test('Windows:只走通用系统接口,不再调用 dllplugin_call;电量 255 显示「电量未知」而不是「无电池」', async () => { - const host = createHost() - host.reset() - installWindowsHost(host) - let dllCalls = 0 - host.ipc.dllplugin_call = async () => { dllCalls++; return { ok: false, errorCode: 'UNSUPPORTED_ACTION', error: '请更新硬件信息插件' } } - const view = await mount(HardwareInfoCommand, host) - await settle() - assert.equal(dllCalls, 0) - assert.ok(!host.ipcCalls.some(([m]) => m === 'dllplugin_call')) - for (const method of ['system_get_hardware_summary', 'get_system_info', 'system_get_cpu_usage', 'system_get_memory_usage', 'system_get_battery_status', 'screen_get_all_displays', 'system_list_volumes']) { - assert.ok(host.ipcCalls.some(([m]) => m === method), `应调用 ${method}`) - } - assert.equal(view.item('hw-cpu-spec').props.title, 'Intel(R) Core(TM) i7-1260P') - const osMd = view.item('hw-os-spec').props.detail.props.markdown - assert.match(osMd, /电量未知 \(电池放电中\)/) - assert.doesNotMatch(view.text(), /无电池/) - // 卷:C 与 Z 照常显示,D 盘失败如实提示原因 - assert.ok(view.item('hw-drive-C:')) - assert.ok(view.item('hw-drive-Z:')) - assert.match(view.tree().props.filterBar.summaryText, /2 个卷,可用 1\.1 TB,部分卷读取失败/) - assert.equal(host.lastToast().style, 'FAILURE') - assert.equal(host.lastToast().title, '部分硬件信息读取失败') - assert.equal(host.lastToast().message, '未能读取:部分磁盘卷。磁盘容量:D:\\: 卷容量读取失败') - view.unmount() -}) - -test('Windows:部分卷失败时三种报告保留读到的卷、注明不含失败卷并列出原因', async () => { - const host = createHost() - host.reset() - installWindowsHost(host) - const snap = await fetchHardwareTelemetrySnapshot() - assert.deepEqual(snap.failures, ['部分磁盘卷']) - const md = exportHardwareReport(snap, 'markdown') - assert.match(md, /2 个挂载卷 · 共 1\.5 TB,不含读取失败的卷/) - assert.match(md, /失败原因: 磁盘容量:D:\\: 卷容量读取失败/) - assert.match(exportHardwareReport(snap, 'txt'), /物理存储卷明细(部分卷读取失败,未列出)/) - const json = JSON.parse(exportHardwareReport(snap, 'json')) - assert.equal(json.storage.partial, true) - assert.equal(json.storage.readFailed, false) - assert.equal(json.storage.driveCount, 2) - assert.deepEqual(json.readWarnings, ['磁盘容量:D:\\: 卷容量读取失败']) - assert.equal(json.power.batteryState, 'present') -}) - -test('Windows:卷列表里的畸形条目逐条跳过并记原因,全部畸形才算磁盘读取失败', async () => { - const host = createHost() - host.reset() - installWindowsHost(host, { - system_list_volumes: async () => ({ volumes: [ - { path: 'C:\\', totalBytes: 100 * GB, usedBytes: 40 * GB, availableBytes: 60 * GB }, - { path: 'D:\\', totalBytes: 100 * GB, usedBytes: null, availableBytes: 10 }, - { path: 'E:\\', totalBytes: '100', usedBytes: 1, availableBytes: 1 }, - null - ], partial: false, errors: [] }) - }) - let snap = await fetchHardwareTelemetrySnapshot() - assert.deepEqual(snap.drives.map((d) => d.drive), ['C:']) - assert.deepEqual(snap.warnings, ['磁盘容量:D:\\:容量数据无效', '磁盘容量:E:\\:容量数据无效', '磁盘容量:未知卷:容量数据无效']) - assert.deepEqual(snap.failures, ['部分磁盘卷']) - host.ipc.system_list_volumes = async () => ({ volumes: [{ path: 'D:\\', totalBytes: 0, usedBytes: 0, availableBytes: 0 }], partial: false }) - snap = await fetchHardwareTelemetrySnapshot() - assert.deepEqual(snap.failures, ['磁盘容量']) - assert.equal(snap.driveCount, 0) - // 宿主直接报错:原因写进 warnings - host.ipc.system_list_volumes = async () => { throw Object.assign(new Error('Get-CimInstance 超时'), { code: 'TIMEOUT' }) } - snap = await fetchHardwareTelemetrySnapshot() - assert.deepEqual(snap.failures, ['磁盘容量']) - assert.match(snap.warnings.join('\n'), /磁盘容量:.*超时/) -}) - -test('Windows 台式机:宿主报告没有电池时显示「无电池(交流供电)」;卷接口不可用时如实给出原因,旧客户端提示升级', async () => { - const host = createHost() - host.reset() - installWindowsHost(host, { - system_get_battery_status: async () => ({ success: true, percent: 255, isCharging: true, timeRemaining: -1, batteryState: 'absent', powerSource: 'ac' }) - }) - delete host.ipc.system_list_volumes - const snap = await fetchHardwareTelemetrySnapshot() - assert.match(snap.entries.find((e) => e.id === 'hw-os-spec').detailMarkdown, /无电池(交流供电)/) - assert.deepEqual(snap.failures, ['磁盘容量']) - assert.equal(snap.warnings.length, 1) - assert.match(snap.warnings[0], /^磁盘容量:测试宿主未实现 system_list_volumes/) - host.ipc.system_list_volumes = async () => { throw Object.assign(new Error('未知方法 system_list_volumes'), { code: 'METHOD_NOT_FOUND' }) } - const old = await fetchHardwareTelemetrySnapshot() - assert.match(old.warnings[0], /^磁盘容量:读取磁盘卷列表需要新版 ZTools/) -}) diff --git a/extensions/hardware-info/tests/hardware-info.host.test.mjs b/extensions/hardware-info/tests/hardware-info.host.test.mjs index f5df5189..72d26e57 100644 --- a/extensions/hardware-info/tests/hardware-info.host.test.mjs +++ b/extensions/hardware-info/tests/hardware-info.host.test.mjs @@ -258,3 +258,46 @@ test('hardware-info: 宿主缺少 / 返回异常的显示参数时显示「未 assert.match(row.detailMarkdown, /逻辑分辨率\*\*: `未知`/) } }) + +test('hardware-info: 宿主未提供 GPU 时诚实标注「未提供」且不编造 3A 游戏 / 本地 LLM 档位', async () => { + const snap = await fetchHardwareTelemetrySnapshot(makeHardwareHost(async () => ({ percent: 80, isCharging: true })), { cpuSampleIntervalMs: 0 }) + assert.equal(snap.gpuAvailable, false) + assert.deepEqual(snap.gpus, []) + const gpuRow = snap.entries.find((e) => e.id === 'hw-gpu-unavailable') + assert.ok(gpuRow, '宿主未提供 GPU 时应展示诚实的 GPU 未提供条目') + assert.equal(gpuRow.tag, '未提供') + assert.match(gpuRow.detailMarkdown, /宿主未提供显卡与显存信息/) + assert.equal(snap.scenarios.some((s) => s.id === 'sc-aaa-gaming' || s.id === 'sc-local-llm'), false, '无 GPU 时严禁编造 3A/LLM 档位') + const md = exportHardwareReport(snap, 'markdown') + assert.match(md, /宿主未提供/) + assert.doesNotMatch(md, /主流电竞与 3A|本地离线 AI 大模型/) + const json = JSON.parse(exportHardwareReport(snap, 'json')) + assert.equal(json.gpu.available, false) + assert.deepEqual(json.gpu.devices, []) +}) + +test('hardware-info: 宿主上报真实 GPU 与显存时如实展示并评估 3A / 本地 LLM 档位,一键复制报告包含 GPU', async () => { + const host = makeHardwareHost(async () => ({ percent: 80, isCharging: true })) + host.system_get_hardware_summary = async () => ({ + cpuModel: 'AMD Ryzen 9 7950X', + logicalCpuCount: 32, + totalMemory: 64 * 1024 ** 3, + gpus: [{ name: 'NVIDIA GeForce RTX 4070', vramBytes: 12 * 1024 ** 3, driverVersion: '566.14' }] + }) + const snap = await fetchHardwareTelemetrySnapshot(host, { cpuSampleIntervalMs: 0 }) + assert.equal(snap.gpuAvailable, true) + assert.equal(snap.gpus.length, 1) + const gpuRow = snap.entries.find((e) => e.id === 'hw-gpu-0') + assert.ok(gpuRow) + assert.equal(gpuRow.title, 'NVIDIA GeForce RTX 4070') + assert.equal(gpuRow.tag, '12.0 GB') + assert.match(gpuRow.detailMarkdown, /566\.14/) + assert.ok(snap.scenarios.some((s) => s.id === 'sc-aaa-gaming')) + assert.ok(snap.scenarios.some((s) => s.id === 'sc-local-llm')) + const md = exportHardwareReport(snap, 'markdown') + assert.match(md, /NVIDIA GeForce RTX 4070/) + assert.match(exportHardwareReport(snap, 'txt'), /NVIDIA GeForce RTX 4070/) + const json = JSON.parse(exportHardwareReport(snap, 'json')) + assert.equal(json.gpu.available, true) + assert.equal(json.gpu.devices[0].name, 'NVIDIA GeForce RTX 4070') +}) diff --git a/extensions/hardware-info/tests/hardware-info.macos.test.mjs b/extensions/hardware-info/tests/hardware-info.macos.test.mjs index 1df3c274..c7460114 100644 --- a/extensions/hardware-info/tests/hardware-info.macos.test.mjs +++ b/extensions/hardware-info/tests/hardware-info.macos.test.mjs @@ -131,7 +131,10 @@ test('显示器:macOS 缩放写成「缩放比例 200%」,不写 Windows 的 }) function installMountedMacHost(host, handlers = macHost()) { - for (const [method, fn] of Object.entries(handlers)) host.ipc[method] = fn + for (const [method, fn] of Object.entries(handlers)) { + if (method === 'system_list_volumes') continue + host.ipc[method] = fn + } } test('先发出的慢请求晚返回时,不能覆盖后一次刷新的结果,也不弹过期提示', async () => { diff --git a/extensions/id-watermark/plugin.json b/extensions/id-watermark/plugin.json index 25a7c399..52a68811 100644 --- a/extensions/id-watermark/plugin.json +++ b/extensions/id-watermark/plugin.json @@ -1,7 +1,7 @@ { "id": "id-watermark", "name": "防盗水印", - "version": "1.0.12", + "version": "1.0.13", "description": "本地为 JPG、PNG、WebP 图片添加斜向文字水印,保留原图,另存 PNG 新副本或复制图片", "author": "ZTools Team", "category": [ diff --git a/extensions/id-watermark/src/i18n.ts b/extensions/id-watermark/src/i18n.ts index b2c31da6..bd19624e 100644 --- a/extensions/id-watermark/src/i18n.ts +++ b/extensions/id-watermark/src/i18n.ts @@ -34,10 +34,13 @@ export const t = createTranslator( errImageDataInvalid: '图片数据无效或超过 16 MiB', errImageReadIncomplete: '原图读取不完整', defaultImageName: '图片', - dialogOpenTitle: '选择原图', + dialogOpenTitle: '选择原图(支持多选正反面)', dialogOpenFilter: '图片|*.jpg;*.jpeg;*.png;*.webp', + dialogBatchDirTitle: '选择批量导出目录(自动追加 _水印 后缀,不覆盖原图)', errInvalidFilePick: '文件选择结果无效', + errInvalidDirPick: '输出目录选择无效', errDropFormat: '请拖入 JPG、PNG 或 WebP 格式的原图', + errQueueEmpty: '待处理队列为空,请先选择图片', errClipboardReadFailed: '剪贴板读取失败', errClipboardTempMissing: '剪贴板图片文件缺失', clipboardImageFileName: '剪贴板图片.png', @@ -51,36 +54,49 @@ export const t = createTranslator( errOutputUnconfirmed: '输出未确认,请检查目标后再试', statusCopiedWatermark: '已复制加水印图片', statusSavedCopy: '已保存新副本:{path}', + statusBatchSaved: '已批量导出 {count} 张水印副本至:{dir}(原图未改动)', + statusLoadedQueue: '队列已载入 {count} 张真实原图(支持正反面批量导出,不覆盖原图)', + statusRemovedImage: '已从队列移除:{name}', + statusClearedQueue: '已清空待处理图片队列', errBusinessLength: '请输入 1~80 字的用途或业务名称', formNavTitle: '修改水印用途', formSaveAction: '保存用途', formFieldTitle: '用途 / 业务名称', formFieldPlaceholder: '如:某公司入职审核', - statusInitial: '保留原图,只另存 PNG 新副本;水印不能保证防篡改', + statusInitial: '纯本地渲染不上传,支持正反面多图队列,只另存新副本不覆盖原图', statusLoadedImage: '已读取真实原图;另存或复制前会校验合成图片', errSelectImageFirst: '请先选择原图或读取剪贴板图片', navTitle: '防盗水印', - searchPlaceholder: '搜索已选图片…', + searchPlaceholder: '搜索队列中的图片…', actionReadClipboard: '读取剪贴板图片', - actionPickImage: '选择原图…', - barPickImage: '选择原图', + actionPickImage: '选择图片(可多选)…', + barPickImage: '选择图片', barReadClipboard: '读取剪贴板', barSaveWatermark: '生成并另存', + barBatchExport: '批量导出 ({count} 张)', barCopyWatermark: '生成并复制', panelTitle: '水印参数', fieldTemplate: '文字模板', - fieldBusiness: '用途(在动作面板修改)', + fieldBusiness: '自定义用途文案', + fieldBusinessPlaceholder: '输入办理业务名称,如:宽带开户', fieldOpacity: '不透明度', + fieldDensity: '平铺密度', + densitySparse: '疏(间距 320px)', + densityMedium: '中(间距 220px)', + densityDense: '密(间距 140px)', fieldColor: '文字颜色', colorDark: '深灰(浅色原图)', colorLight: '浅灰(深色原图)', - previewSubtitle: '斜向平铺;输出 PNG,保留原图尺寸', - subListTitle: '待处理图片', + previewSubtitle: '斜向平铺 · 透明度 {opacity}% · {density} · 保留原图不覆盖', + subListTitle: '待处理图片队列({count} 张)', emptyMatched: '没有匹配的图片', - emptyNoImage: '选择 JPG、PNG、WebP 原图,或读取剪贴板图片', + emptyNoImage: '点击「选择图片」导入身份证正反面或多张原图,也可拖拽或读取剪贴板', actionCopyWatermark: '复制加水印图片', actionSaveWatermark: '另存加水印图片…', - actionEditBusiness: '修改水印用途…' + actionEditBusiness: '修改水印用途…', + actionBatchExport: '批量导出全部 {count} 张到目录…', + actionRemoveImage: '从队列移除此图', + actionClearQueue: '清空队列' }, 'en-US': { defaultBusiness: 'Specified Purpose', @@ -114,10 +130,13 @@ export const t = createTranslator( errImageDataInvalid: 'Image data is invalid or exceeds 16 MiB', errImageReadIncomplete: 'Source image read was incomplete', defaultImageName: 'Image', - dialogOpenTitle: 'Select Source Image', + dialogOpenTitle: 'Select Source Images (Multi-Select Supported)', dialogOpenFilter: 'Images|*.jpg;*.jpeg;*.png;*.webp', + dialogBatchDirTitle: 'Choose Output Folder (Exports _watermarked copies, never overwrites originals)', errInvalidFilePick: 'Invalid file selection result', + errInvalidDirPick: 'Invalid output folder selection', errDropFormat: 'Please drop a JPG, PNG, or WebP image', + errQueueEmpty: 'Image queue is empty; select images first', errClipboardReadFailed: 'Failed to read clipboard', errClipboardTempMissing: 'Clipboard image temp file is missing', clipboardImageFileName: 'clipboard-image.png', @@ -131,36 +150,49 @@ export const t = createTranslator( errOutputUnconfirmed: 'Output not confirmed; check the destination and retry', statusCopiedWatermark: 'Copied watermarked image', statusSavedCopy: 'Saved copy: {path}', + statusBatchSaved: 'Exported {count} watermarked copies to: {dir} (originals untouched)', + statusLoadedQueue: 'Loaded {count} source image(s) into queue (originals will never be overwritten)', + statusRemovedImage: 'Removed from queue: {name}', + statusClearedQueue: 'Cleared image queue', errBusinessLength: 'Please enter 1-80 characters for the purpose name', formNavTitle: 'Edit Watermark Purpose', formSaveAction: 'Save Purpose', formFieldTitle: 'Purpose / Business Name', formFieldPlaceholder: 'e.g. Acme Corp Onboarding', - statusInitial: 'Original image stays intact; exports a new PNG copy (watermarking is not tamper-proof)', + statusInitial: '100% local rendering; supports multi-image queue and never overwrites originals', statusLoadedImage: 'Source image loaded; output will be verified before saving or copying', errSelectImageFirst: 'Select a source image or load from clipboard first', navTitle: 'ID Watermark', - searchPlaceholder: 'Search selected image…', + searchPlaceholder: 'Search queued images…', actionReadClipboard: 'Load from Clipboard', - actionPickImage: 'Select Image…', - barPickImage: 'Select Image', + actionPickImage: 'Select Images…', + barPickImage: 'Select Images', barReadClipboard: 'From Clipboard', barSaveWatermark: 'Save Watermarked', + barBatchExport: 'Batch Export ({count})', barCopyWatermark: 'Copy Watermarked', panelTitle: 'Watermark Settings', fieldTemplate: 'Text Template', - fieldBusiness: 'Purpose (Edit in Actions)', + fieldBusiness: 'Custom Purpose Text', + fieldBusinessPlaceholder: 'Enter purpose, e.g. Bank Verification', fieldOpacity: 'Opacity', + fieldDensity: 'Tile Density', + densitySparse: 'Sparse (320px)', + densityMedium: 'Medium (220px)', + densityDense: 'Dense (140px)', fieldColor: 'Text Color', colorDark: 'Dark Gray (for light images)', colorLight: 'Light Gray (for dark images)', - previewSubtitle: 'Diagonal tile; exports PNG at original resolution', - subListTitle: 'Selected Image', + previewSubtitle: 'Diagonal tile · Opacity {opacity}% · {density} · Originals preserved', + subListTitle: 'Image Queue ({count})', emptyMatched: 'No matching image', - emptyNoImage: 'Select a JPG, PNG, or WebP image, or load from clipboard', + emptyNoImage: 'Click "Select Images" for front/back ID photos, drag & drop, or load from clipboard', actionCopyWatermark: 'Copy Watermarked Image', actionSaveWatermark: 'Save Watermarked Copy…', - actionEditBusiness: 'Edit Purpose…' + actionEditBusiness: 'Edit Purpose…', + actionBatchExport: 'Batch Export All ({count}) to Folder…', + actionRemoveImage: 'Remove from Queue', + actionClearQueue: 'Clear Queue' } }, { defaultLocale: 'en-US' } diff --git a/extensions/id-watermark/src/image-io.ts b/extensions/id-watermark/src/image-io.ts index ab0a8f07..30eac7fe 100644 --- a/extensions/id-watermark/src/image-io.ts +++ b/extensions/id-watermark/src/image-io.ts @@ -36,15 +36,39 @@ export async function pickImage(signal: AbortSignal): Promise { + const data = await request('window_show_open_dialog', { title: t('dialogOpenTitle'), properties: ['openFile', 'multiSelections'], filters: t('dialogOpenFilter') }, signal) + if (data.canceled === true) return null + if (data.canceled !== false) throw new Error(t('errInvalidFilePick')) + const rawPaths: string[] = Array.isArray(data.filePaths) + ? data.filePaths.filter((p): p is string => typeof p === 'string' && p.trim().length > 0).map(p => p.trim()) + : typeof data.filePath === 'string' && data.filePath.trim() + ? [data.filePath.trim()] + : [] + if (!rawPaths.length) throw new Error(t('errInvalidFilePick')) + const results: ImageMetadata[] = [] + for (const filePath of rawPaths) { + results.push(await readImagePath(filePath, signal)) + } + return results +} export async function readDroppedImage(envelopeOrPayload: unknown, signal: AbortSignal): Promise { + const results = await readDroppedImages(envelopeOrPayload, signal) + return results[0]! +} +export async function readDroppedImages(envelopeOrPayload: unknown, signal: AbortSignal): Promise { const record = envelopeOrPayload && typeof envelopeOrPayload === 'object' ? (envelopeOrPayload as Record) : {} const payload = record.payload && typeof record.payload === 'object' ? (record.payload as Record) : record const files = Array.isArray(payload.files) ? payload.files.filter((f): f is string => typeof f === 'string' && f.trim().length > 0).map(f => f.trim()) : [] - const matched = files.find(f => /\.(?:jpe?g|png|webp|bmp)$/i.test(f)) - if (!matched) throw new Error(t('errDropFormat')) - return readImagePath(matched, signal) + const matched = files.filter(f => /\.(?:jpe?g|png|webp|bmp)$/i.test(f)) + if (!matched.length) throw new Error(t('errDropFormat')) + const results: ImageMetadata[] = [] + for (const filePath of matched) { + results.push(await readImagePath(filePath, signal)) + } + return results } export async function readClipboardImage(signal: AbortSignal): Promise { const data = await request('clipboard_read_image', {}, signal) @@ -82,3 +106,57 @@ export async function outputImage(image: ImageMetadata, options: WatermarkOption if (data.success !== true || (!copy && data.size !== bytes.length)) throw new Error(t('errOutputUnconfirmed')) return copy ? t('statusCopiedWatermark') : t('statusSavedCopy', { path: outputPath }) } +function joinDirPath(dir: string, fileName: string): string { + const sep = dir.includes('\\') && !dir.includes('/') ? '\\' : '/' + const trimmed = dir.replace(/[\\/]+$/, '') + return `${trimmed}${sep}${fileName}` +} +export async function batchOutputImages( + images: readonly ImageMetadata[], + options: WatermarkOptions, + signal: AbortSignal +): Promise { + if (!images.length) throw new Error(t('errQueueEmpty')) + const dirData = await request('window_show_open_dialog', { title: t('dialogBatchDirTitle'), properties: ['openDirectory'] }, signal) + if (dirData.canceled === true) return null + const dirPath = typeof dirData.filePath === 'string' && dirData.filePath.trim() + ? dirData.filePath.trim() + : Array.isArray(dirData.filePaths) && typeof dirData.filePaths[0] === 'string' && dirData.filePaths[0].trim() + ? dirData.filePaths[0].trim() + : '' + if (dirData.canceled !== false || !dirPath) throw new Error(t('errInvalidDirPick')) + + const usedPaths = new Set() + const originalPaths = images.map(img => img.path).filter((p): p is string => Boolean(p)) + const suffix = t('saveDefaultSuffix') + + for (let i = 0; i < images.length; i++) { + const img = images[i]! + const stem = img.fileName.replace(/\.[^.]+$/, '') || `${t('defaultImageName')}_${i + 1}` + let candidate = joinDirPath(dirPath, `${stem}${suffix}`) + let seq = 2 + while ( + usedPaths.has(candidate.normalize('NFC').replace(/\\/g, '/').toLowerCase()) || + originalPaths.some(orig => samePathText(candidate, orig)) + ) { + candidate = joinDirPath(dirPath, `${stem}_${seq}${suffix}`) + seq++ + } + usedPaths.add(candidate.normalize('NFC').replace(/\\/g, '/').toLowerCase()) + + const rendered = await renderWatermarkOnImage(img, options) + signal.throwIfAborted() + const bytes = new Uint8Array(await rendered.blob.arrayBuffer()) + const encoded = encodeBase64(bytes) + signal.throwIfAborted() + const writeRes = await request( + 'filesystem_write_file', + { path: candidate, content: encoded, encoding: 'base64', overwrite: true }, + signal + ) + if (writeRes.success !== true || writeRes.size !== bytes.length) { + throw new Error(t('errOutputUnconfirmed')) + } + } + return t('statusBatchSaved', { count: images.length, dir: dirPath }) +} diff --git a/extensions/id-watermark/src/index.tsx b/extensions/id-watermark/src/index.tsx index 90ecb64e..1ff2b215 100644 --- a/extensions/id-watermark/src/index.tsx +++ b/extensions/id-watermark/src/index.tsx @@ -1,6 +1,6 @@ import React, { Action, ActionPanel, Form, Icon, List, Toast, showToast, useEffect, useLocale, useNavigation, useRef, useState } from '@ztools/declarative-ui' import { getPresetWatermarkTemplates, resolveTemplate } from './watermark-service.js' -import { pickImage, readClipboardImage, readDroppedImage, outputImage } from './image-io.js' +import { pickImages, readClipboardImage, readDroppedImages, outputImage, batchOutputImages } from './image-io.js' import { createCompatFileInputProps, isDeclarativeFileInputSupported } from './host-compat.js' import { t } from './i18n.js' import type { ImageMetadata, WatermarkOptions } from './types.js' @@ -9,6 +9,31 @@ export * from './watermark-service.js' export * from './image-codec.js' export * from './image-io.js' +const DENSITY_GAP_MAP: Record = { + sparse: 320, + medium: 220, + dense: 140 +} + +function imageKey(img: ImageMetadata, index: number): string { + return img.path ? img.path.toLowerCase() : `${img.fileName}-${img.width}x${img.height}-${index}` +} + +function mergeImageQueue(existing: ImageMetadata[], incoming: ImageMetadata[]): ImageMetadata[] { + const next = [...existing] + for (const item of incoming) { + const idx = item.path + ? next.findIndex(e => e.path && e.path.toLowerCase() === item.path!.toLowerCase()) + : -1 + if (idx >= 0) { + next[idx] = item + } else if (next.length < 20) { + next.push(item) + } + } + return next +} + export function BusinessForm({ initial, saved }: { initial: string; saved: (value: string) => void }) { useLocale() const [value, setValue] = useState(initial), [error, setError] = useState('') @@ -25,23 +50,37 @@ export function BusinessForm({ initial, saved }: { initial: string; saved: (valu export function IdWatermarkCommand({ clipboardFirst = false }: { clipboardFirst?: boolean } = {}) { const locale = useLocale() - const [image, setImage] = useState(null) + const [images, setImages] = useState([]) const [customBusiness, setCustomBusiness] = useState(null) const [templateId, setTemplateId] = useState('tpl-general') const [opacity, setOpacity] = useState('25') + const [density, setDensity] = useState<'sparse' | 'medium' | 'dense'>('medium') const [color, setColor] = useState<'dark' | 'light'>('dark') const [search, setSearch] = useState('') const [loading, setLoading] = useState(false) const [statusOverride, setStatusOverride] = useState(null) const pending = useRef(null), mounted = useRef(true), { push } = useNavigation() - const business = customBusiness ?? t('defaultBusiness') - const presets = getPresetWatermarkTemplates(business) + const business = customBusiness !== null ? customBusiness : t('defaultBusiness') + const effectiveBusiness = business.trim() || t('defaultBusiness') + const presets = getPresetWatermarkTemplates(effectiveBusiness) const activeTemplate = presets.find((p) => p.id === templateId)?.rawText ?? presets[0]?.rawText ?? t('tplGeneralRaw') - const text = resolveTemplate(activeTemplate, business) + const text = resolveTemplate(activeTemplate, effectiveBusiness) const status = statusOverride ?? t('statusInitial') + const gapPx = DENSITY_GAP_MAP[density] ?? 220 + const densityLabel = density === 'sparse' ? t('densitySparse') : density === 'dense' ? t('densityDense') : t('densityMedium') + useEffect(() => { setStatusOverride(null) }, [locale]) + + const buildOptions = (): WatermarkOptions => ({ + text, + opacityPercent: Number(opacity), + rotateDegree: -30, + gapPx, + colorMode: color + }) + const run = async (job: (signal: AbortSignal) => Promise) => { if (pending.current) return const controller = new AbortController(); pending.current = controller; setLoading(true) @@ -53,17 +92,64 @@ export function IdWatermarkCommand({ clipboardFirst = false }: { clipboardFirst? } } finally { if (pending.current === controller) pending.current = null; if (mounted.current) setLoading(false) } } + + const appendImages = (incoming: ImageMetadata[]) => { + if (!incoming.length || !mounted.current) return + setImages(prev => { + const merged = mergeImageQueue(prev, incoming) + setStatusOverride( + merged.length > 1 + ? t('statusLoadedQueue', { count: merged.length }) + : t('statusLoadedImage') + ) + return merged + }) + } + const load = (clipboard: boolean) => run(async signal => { - const result = await (clipboard ? readClipboardImage(signal) : pickImage(signal)) + if (clipboard) { + const result = await readClipboardImage(signal) + signal.throwIfAborted() + if (result) appendImages([result]) + return + } + const results = await pickImages(signal) signal.throwIfAborted() - if (result && mounted.current) { setImage(result); setStatusOverride(t('statusLoadedImage')) } + if (results && results.length) appendImages(results) }) - const output = (copy: boolean) => run(async signal => { - if (!image) throw new Error(t('errSelectImageFirst')) - const options: WatermarkOptions = { text, opacityPercent: Number(opacity), rotateDegree: -30, gapPx: 220, colorMode: color } - const result = await outputImage(image, options, copy, signal) + + const outputSingle = (target: ImageMetadata, copy: boolean) => run(async signal => { + const result = await outputImage(target, buildOptions(), copy, signal) if (result && mounted.current) { setStatusOverride(result); await showToast({ style: Toast.Style.Success, title: result }) } }) + + const outputBatch = () => run(async signal => { + if (!images.length) throw new Error(t('errSelectImageFirst')) + if (images.length === 1) { + const result = await outputImage(images[0]!, buildOptions(), clipboardFirst, signal) + if (result && mounted.current) { setStatusOverride(result); await showToast({ style: Toast.Style.Success, title: result }) } + return + } + const result = await batchOutputImages(images, buildOptions(), signal) + if (result && mounted.current) { setStatusOverride(result); await showToast({ style: Toast.Style.Success, title: result }) } + }) + + const removeImageAt = (index: number) => { + setImages(prev => { + const target = prev[index] + const next = prev.filter((_, i) => i !== index) + if (target) { + setStatusOverride(next.length ? t('statusRemovedImage', { name: target.fileName }) : t('statusClearedQueue')) + } + return next + }) + } + + const clearQueue = () => { + setImages([]) + setStatusOverride(t('statusClearedQueue')) + } + useEffect(() => { mounted.current = true if (clipboardFirst) void load(true) @@ -79,9 +165,9 @@ export function IdWatermarkCommand({ clipboardFirst = false }: { clipboardFirst? }).window?.ztools?.events const handleFilesDropped = (envelopeOrPayload: unknown) => { void run(async signal => { - const result = await readDroppedImage(envelopeOrPayload, signal) + const results = await readDroppedImages(envelopeOrPayload, signal) signal.throwIfAborted() - if (result && mounted.current) { setImage(result); setStatusOverride(t('statusLoadedImage')) } + appendImages(results) }) } const dispose = !isDeclarativeFileInputSupported() && events && typeof events.on === 'function' ? events.on('plugin_files_dropped', handleFilesDropped) : undefined @@ -92,12 +178,13 @@ export function IdWatermarkCommand({ clipboardFirst = false }: { clipboardFirst? else if (!isDeclarativeFileInputSupported() && events && typeof events.off === 'function') events.off('plugin_files_dropped', handleFilesDropped) } }, []) + const fileInputProps = createCompatFileInputProps( (files) => { void run(async signal => { - const result = await readDroppedImage({ files }, signal) + const results = await readDroppedImages({ files }, signal) signal.throwIfAborted() - if (result && mounted.current) { setImage(result); setStatusOverride(t('statusLoadedImage')) } + appendImages(results) }) }, { @@ -105,33 +192,115 @@ export function IdWatermarkCommand({ clipboardFirst = false }: { clipboardFirst? allowClipboardImage: true } ) - const visible = image && image.fileName.toLowerCase().includes(search.trim().toLowerCase()) + + const q = search.trim().toLowerCase() + const visibleImages = images + .map((img, index) => ({ img, index })) + .filter(({ img }) => !q || img.fileName.toLowerCase().includes(q)) + return {clipboardFirst ? load(true)} /> : load(false)} />} {clipboardFirst ? load(false)} /> : load(true)} />}
} - filterBar={{ summaryText: status, actions: image ? [ + filterBar={{ summaryText: status, actions: images.length > 0 ? [ { id: 'pick', title: t('barPickImage'), style: 'secondary', onAction: () => load(false) }, - { id: 'generate', title: clipboardFirst ? t('barCopyWatermark') : t('barSaveWatermark'), style: 'primary', disabled: loading, onAction: () => output(clipboardFirst) } + { + id: 'generate', + title: images.length > 1 + ? t('barBatchExport', { count: images.length }) + : clipboardFirst ? t('barCopyWatermark') : t('barSaveWatermark'), + style: 'primary', + disabled: loading, + onAction: () => outputBatch() + } ] : [ { id: 'pick', title: t('barPickImage'), style: 'secondary', onAction: () => load(false) }, { id: 'clipboard', title: t('barReadClipboard'), style: 'secondary', onAction: () => load(true) } ] }} workbenchPanel={{ title: t('panelTitle'), fields: [ - { id: 'template', label: t('fieldTemplate'), type: 'select', value: templateId, options: presets.map(p => ({ label: p.scenarioTag, value: p.id })), onChange: (value: unknown) => { if (!pending.current && presets.some(p => p.id === value)) setTemplateId(String(value)) } }, - { id: 'business', label: t('fieldBusiness'), type: 'info', value: business }, - { id: 'opacity', label: t('fieldOpacity'), type: 'select', value: opacity, options: ['15', '25', '35'].map(value => ({ label: value + '%', value })), onChange: (value: unknown) => { if (!pending.current && ['15', '25', '35'].includes(String(value))) setOpacity(String(value)) } }, - { id: 'color', label: t('fieldColor'), type: 'select', value: color, options: [{ label: t('colorDark'), value: 'dark' }, { label: t('colorLight'), value: 'light' }], onChange: (value: unknown) => { if (!pending.current && (value === 'dark' || value === 'light')) setColor(value) } } - ], previewCard: { title: text, subtitle: t('previewSubtitle') } }} - subList={{ title: t('subListTitle'), emptyText: image ? t('emptyMatched') : t('emptyNoImage'), items: visible ? [ - - output(clipboardFirst)} /> - output(!clipboardFirst)} /> - { if (!pending.current) push( setCustomBusiness(val)} />) }} /> - } /> - ] : [] }} /> + { + id: 'template', + label: t('fieldTemplate'), + type: 'select', + value: templateId, + options: presets.map(p => ({ label: p.scenarioTag, value: p.id })), + onChange: (value: unknown) => { + if (pending.current) return + const matched = presets.find(p => p.id === value || p.rawText === value) + if (matched) setTemplateId(matched.id) + } + }, + { + id: 'business', + label: t('fieldBusiness'), + type: 'text', + value: business, + onChange: (value: unknown) => { + if (!pending.current) setCustomBusiness(String(value ?? '')) + } + }, + { + id: 'opacity', + label: t('fieldOpacity'), + type: 'select', + value: opacity, + options: ['15', '25', '35', '45'].map(value => ({ label: value + '%', value })), + onChange: (value: unknown) => { + if (!pending.current && ['15', '25', '35', '45'].includes(String(value))) setOpacity(String(value)) + } + }, + { + id: 'density', + label: t('fieldDensity'), + type: 'select', + value: density, + options: [ + { label: t('densitySparse'), value: 'sparse' }, + { label: t('densityMedium'), value: 'medium' }, + { label: t('densityDense'), value: 'dense' } + ], + onChange: (value: unknown) => { + if (!pending.current && (value === 'sparse' || value === 'medium' || value === 'dense')) setDensity(value) + } + }, + { + id: 'color', + label: t('fieldColor'), + type: 'select', + value: color, + options: [{ label: t('colorDark'), value: 'dark' }, { label: t('colorLight'), value: 'light' }], + onChange: (value: unknown) => { + if (!pending.current && (value === 'dark' || value === 'light')) setColor(value) + } + } + ], previewCard: { title: text, subtitle: t('previewSubtitle', { opacity, density: densityLabel }) } }} + subList={{ + title: t('subListTitle', { count: images.length }), + emptyText: images.length > 0 ? t('emptyMatched') : t('emptyNoImage'), + items: visibleImages.map(({ img, index }) => ( + 1 ? [{ tag: `${index + 1}/${images.length}` }] : undefined} + actions={ + outputSingle(img, clipboardFirst)} /> + outputSingle(img, !clipboardFirst)} /> + { if (!pending.current) push( setCustomBusiness(val)} />) }} /> + {images.length > 1 && ( + outputBatch()} /> + )} + removeImageAt(index)} /> + {images.length > 1 && ( + + )} + } + /> + )) + }} /> } export const commands = { 'id-watermark-workbench': () => IdWatermarkCommand(), diff --git a/extensions/id-watermark/src/watermark-service.ts b/extensions/id-watermark/src/watermark-service.ts index 3692aa3a..67b3ac45 100644 --- a/extensions/id-watermark/src/watermark-service.ts +++ b/extensions/id-watermark/src/watermark-service.ts @@ -136,7 +136,7 @@ export function computeAdaptiveWatermarkLayout( const effectiveFontSizePx = Math.max(8, Math.min(baseFontSize, Math.round(minDim * 0.09))) const effectiveGapPx = Math.max( effectiveFontSizePx * 3, - Math.min(options.gapPx || Math.round(minDim * 0.18), Math.round(minDim * 0.45)) + Math.min(options.gapPx || Math.round(minDim * 0.18), Math.round(minDim * 0.65)) ) const wrappedLines = wrapWatermarkLines(options.text, 24) diff --git a/extensions/id-watermark/tests/watermark-queue.test.mjs b/extensions/id-watermark/tests/watermark-queue.test.mjs new file mode 100644 index 00000000..44dcf970 --- /dev/null +++ b/extensions/id-watermark/tests/watermark-queue.test.mjs @@ -0,0 +1,46 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import { createHost, mount, tick } from '../../shared/test-harness.mjs' +import Command, { computeAdaptiveWatermarkLayout, getPresetWatermarkTemplates, resolveTemplate } from '../dist/index.js' + +test('水印密度与模板参数:疏/中/密对应不同 tileCount,自定义用途实时替换', () => { + const sparse = computeAdaptiveWatermarkLayout(1200, 800, { text: '仅供宽带开户使用', opacityPercent: 25, rotateDegree: -30, gapPx: 320, colorMode: 'dark' }) + const medium = computeAdaptiveWatermarkLayout(1200, 800, { text: '仅供宽带开户使用', opacityPercent: 25, rotateDegree: -30, gapPx: 220, colorMode: 'dark' }) + const dense = computeAdaptiveWatermarkLayout(1200, 800, { text: '仅供宽带开户使用', opacityPercent: 25, rotateDegree: -30, gapPx: 140, colorMode: 'dark' }) + assert.ok(sparse.effectiveGapPx > medium.effectiveGapPx && medium.effectiveGapPx > dense.effectiveGapPx) + assert.ok(dense.tileCount > medium.tileCount && medium.tileCount > sparse.tileCount) + const templates = getPresetWatermarkTemplates('宽带开户', '2026.12.01') + const resolved = resolveTemplate(templates[0].rawText, '宽带开户', '2026.12.01') + assert.ok(resolved.includes('宽带开户') && resolved.includes('2026.12.01')) +}) + +test('工作台面板支持直接编辑自定义水印文案、切换透明度与平铺密度,提供显式选择图片入口', async () => { + const host = createHost() + const view = await mount(Command, host) + try { + const barActions = view.tree().props.filterBar.actions + assert.equal(barActions[0].id, 'pick') + assert.equal(barActions[0].title, '选择图片') + assert.equal(barActions[1].id, 'clipboard') + + const fields = () => view.tree().props.workbenchPanel.fields + const businessField = fields().find((f) => f.id === 'business') + assert.equal(businessField.type, 'text', '自定义用途文案应为直接可编辑的 text 输入框') + businessField.onChange('租房签约认证') + await tick() + assert.match(view.tree().props.workbenchPanel.previewCard.title, /租房签约认证/) + + const opacityField = fields().find((f) => f.id === 'opacity') + opacityField.onChange('35') + await tick() + assert.match(view.tree().props.workbenchPanel.previewCard.subtitle, /35%/) + + const densityField = fields().find((f) => f.id === 'density') + assert.ok(densityField, '应提供平铺密度调节') + densityField.onChange('dense') + await tick() + assert.match(view.tree().props.workbenchPanel.previewCard.subtitle, /密/) + } finally { + view.unmount() + } +}) diff --git a/extensions/id-watermark/tests/watermark.test.mjs b/extensions/id-watermark/tests/watermark.test.mjs deleted file mode 100644 index 141613b1..00000000 --- a/extensions/id-watermark/tests/watermark.test.mjs +++ /dev/null @@ -1,187 +0,0 @@ -import test from 'node:test' -import assert from 'node:assert/strict' -import { setRuntimeLocale } from '@ztools/declarative-ui' -import { createHost, mount, tick } from '../../shared/test-harness.mjs' -import Command, { BusinessForm, commands, getPresetWatermarkTemplates, inspectImageHeader, renderWatermarkOnImage, pickImage, outputImage, readClipboardImage, resolveTemplate } from '../dist/index.js' - -test('初始无假图片;三号布局只有选图和读取剪贴板两个全局动作', async () => { - const host = createHost(), view = await mount(Command, host) - try { - assert.equal(view.items().length, 0) - assert.ok(view.tree().props.workbenchPanel && view.tree().props.subList) - assert.deepEqual(view.tree().props.filterBar.actions.map(a => a.id), ['pick', 'clipboard']) - assert.doesNotMatch(view.text(), /1920|OffscreenCanvas|物理级|智能灰阶/) - } finally { view.unmount() } -}) -test('取消选图无假成功;宿主失败展示错误;畸形回执拒绝', async () => { - const host = createHost(), view = await mount(Command, host) - try { - host.ipc.window_show_open_dialog = async () => ({ canceled: true }) - await view.tree().props.filterBar.actions[0].onAction(); await tick() - assert.equal(host.toasts.length, 0); assert.equal(view.items().length, 0) - host.ipc.window_show_open_dialog = async () => { throw new Error('选择器不可用') } - await view.tree().props.filterBar.actions[0].onAction(); await tick(); assert.match(view.text(), /选择器不可用/) - host.ipc.window_show_open_dialog = async () => ({ canceled: false }) - await assert.rejects(pickImage(new AbortController().signal), /选择结果/) - } finally { view.unmount() } -}) -test('剪贴板快入口只读取、没有图片明确失败,绝不覆盖剪贴板', async () => { - const host = createHost(); host.ipc.clipboard_read_image = async () => ({ success: true, useTempFile: false, image: '' }) - const view = await mount(commands['id-watermark-clipboard-fast'], host) - try { await tick(); assert.match(view.text(), /没有图片/); assert.deepEqual(host.ipcCalls.map(([method]) => method), ['clipboard_read_image']) } - finally { view.unmount() } - host.ipc.clipboard_read_image = async () => ({ success: true, useTempFile: true }) - await assert.rejects(readClipboardImage(new AbortController().signal), /文件缺失/) -}) -test('选图并发互斥;卸载后不读取迟到选图、不更新状态或弹成功', async () => { - const host = createHost(), view = await mount(Command, host); let resolve - host.ipc.window_show_open_dialog = () => new Promise(done => { resolve = done }) - const action = view.tree().props.filterBar.actions[0].onAction - const pending = action(); await action(); assert.equal(host.ipcCalls.length, 1) - view.unmount(); resolve({ canceled: false, filePath: '/test.png' }); await pending - assert.equal(host.ipcCalls.length, 1); assert.equal(host.toasts.length, 0) -}) -test('图像边界先于解码:损坏文件头、巨大像素、缺图/伪图不生成替代JPEG', async () => { - assert.throws(() => inspectImageHeader(new Uint8Array()), /16 MiB/) - const png = new Uint8Array(33); png.set([137,80,78,71,13,10,26,10]); png.set([73,72,68,82],12) - const header = new DataView(png.buffer); header.setUint32(16, 99999); header.setUint32(20, 99999) - assert.throws(() => inspectImageHeader(png), /尺寸/) - await assert.rejects(renderWatermarkOnImage({ width: 640, height: 480, fileName: '假图.png' }, { text: '测试', opacityPercent: 25 }), /图片/) - await assert.rejects(renderWatermarkOnImage({}, { text: ' ', opacityPercent: 25 }), /文字/) -}) -test('业务名称按字面量替换;Canvas创建失败也关闭已解码位图', async () => { - assert.equal(resolveTemplate('用途{business}', "$&$`$'", '2026.10.26'), "用途$&$`$'") - assert.equal(resolveTemplate('用途{business} {date}', '项目 {date}', '2026.10.26'), '用途项目 {date} 2026.10.26') - const previousBitmap = globalThis.createImageBitmap, previousCanvas = globalThis.OffscreenCanvas - let closed = 0 - const bytes = new Uint8Array(33); bytes.set([137,80,78,71,13,10,26,10]); bytes.set([73,72,68,82],12) - const header = new DataView(bytes.buffer); header.setUint32(16, 640); header.setUint32(20, 480) - globalThis.createImageBitmap = async () => ({ width: 640, height: 480, close() { closed++ } }) - globalThis.OffscreenCanvas = class { constructor() { throw new Error('Canvas创建失败') } } - try { await assert.rejects(renderWatermarkOnImage({ rawBytes: bytes }, { text: '测试', opacityPercent: 25 }), /Canvas创建失败/); assert.equal(closed, 1) } - finally { globalThis.createImageBitmap = previousBitmap; globalThis.OffscreenCanvas = previousCanvas } -}) -test('用途使用可编辑Form;空值拒绝,填写后保存回传,不使用只读workbench文本', async () => { - const host = createHost(); let saved - const form = await mount(() => BusinessForm({ initial: '旧用途', saved: value => { saved = value } }), host) - try { - const field = () => form.tree().children.flat(Infinity).find(node => node.type === 'Form.TextField') - assert.equal(field().props.value, '旧用途') - field().props.onChange(' '); await tick(); await form.run(null, '保存用途'); assert.equal(saved, undefined); assert.match(field().props.error, /1~80/) - field().props.onChange('测试单位 $& {date}'); await tick(); await form.run(null, '保存用途'); assert.equal(saved, '测试单位 $& {date}') - } finally { form.unmount() } -}) - -test('另存为选中原图(含大小写或分隔符不同的同一路径)在写入前拒绝,不发起写入', async () => { - const host = createHost(), view = await mount(Command, host) - try { - const image = { fileName: '原图.png', width: 1, height: 1, rawBytes: new Uint8Array(), path: '/Users/test/图片/café.png' } - for (const chosen of ['/Users/test/图片/café.png', '/USERS/TEST/图片/CAFÉ.PNG', '/Users/test/图片/café.png'.normalize('NFD')]) { - host.ipc.window_show_save_dialog = async () => ({ canceled: false, filePath: chosen }) - await assert.rejects(outputImage(image, { text: '测试', opacityPercent: 30, rotateDegree: -30, gapPx: 120, colorMode: 'dark' }, false, new AbortController().signal), /原图不会被覆盖/) - } - assert.equal(host.ipcCalls.some(([method]) => method === 'filesystem_write_file'), false) - } finally { view.unmount() } -}) -test('未选图时 Enter 主动作:工作台为“选择原图…”,剪贴板入口为“读取剪贴板图片”;取消不出现图片', async () => { - const host = createHost(), view = await mount(Command, host) - try { - assert.deepEqual(view.actions(null).map(a => a.props.title), ['选择原图…', '读取剪贴板图片']) - host.ipc.window_show_open_dialog = async () => ({ canceled: true }) - await view.run(null, '选择原图…') - assert.ok(host.ipcCalls.some(([m]) => m === 'window_show_open_dialog')); assert.equal(view.items().length, 0); assert.equal(host.toasts.length, 0) - host.ipc.window_show_open_dialog = async () => { throw new Error('选择器不可用') } - await view.run(null, '选择原图…'); assert.match(view.text(), /选择器不可用/); assert.equal(view.items().length, 0) - } finally { view.unmount() } - const host2 = createHost(); host2.ipc.clipboard_read_image = async () => ({ success: true, useTempFile: false, image: '' }) - const fast = await mount(commands['id-watermark-clipboard-fast'], host2) - try { await tick(); assert.deepEqual(fast.actions(null).map(a => a.props.title), ['读取剪贴板图片', '选择原图…']) } - finally { fast.unmount() } -}) - -test('支持通过 plugin_files_dropped(旧宿主回退)拖入原图文件加载,非支持格式提示错误', async () => { - const listeners = new Map() - const host = createHost() - const previousBitmap = globalThis.createImageBitmap, previousCanvas = globalThis.OffscreenCanvas - globalThis.createImageBitmap = async () => ({ width: 1, height: 1, close() {} }) - globalThis.OffscreenCanvas = class {} - globalThis.window.__ztoolsDeclarativeFeatures = { fileInput: false } - globalThis.window.ztools = { - events: { - on(event, cb) { - listeners.set(event, cb) - return () => listeners.delete(event) - } - } - } - const pngB64 = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==' - const pngBytesLen = Buffer.from(pngB64, 'base64').length - host.ipc.filesystem_read_file = async () => ({ success: true, content: pngB64, size: pngBytesLen }) - const view = await mount(Command, host) - try { - assert.equal(typeof listeners.get('plugin_files_dropped'), 'function') - listeners.get('plugin_files_dropped')({ payload: { files: ['/Users/me/doc.pdf'] } }) - await tick() - assert.match(host.lastToast().title, /JPG、PNG 或 WebP/) - - listeners.get('plugin_files_dropped')({ payload: { files: ['/Users/me/idcard.png'] } }) - await tick() - assert.equal(view.items().length, 1) - assert.equal(view.items()[0].props.title, 'idcard.png') - } finally { - view.unmount() - globalThis.window.__ztoolsDeclarativeFeatures = { fileInput: true } - delete globalThis.window.ztools - globalThis.createImageBitmap = previousBitmap - globalThis.OffscreenCanvas = previousCanvas - } -}) - -test('支持通过 createCompatFileInputProps 粘贴图片文件或截图位图加载为底图', async () => { - const host = createHost() - const previousBitmap = globalThis.createImageBitmap, previousCanvas = globalThis.OffscreenCanvas - globalThis.createImageBitmap = async () => ({ width: 1, height: 1, close() {} }) - globalThis.OffscreenCanvas = class {} - const pngB64 = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==' - const pngBytesLen = Buffer.from(pngB64, 'base64').length - host.ipc.filesystem_read_file = async () => ({ success: true, content: pngB64, size: pngBytesLen }) - const view = await mount(Command, host) - try { - await view.pasteFiles(['/Users/me/doc.pdf']) - assert.equal(host.lastToast().title, '文件格式不匹配') - - await view.pasteFiles(['/Users/me/pasted_id.png']) - await tick() - assert.equal(view.items().length, 1) - assert.equal(view.items()[0].props.title, 'pasted_id.png') - } finally { - view.unmount() - globalThis.createImageBitmap = previousBitmap - globalThis.OffscreenCanvas = previousCanvas - } -}) - -test('i18n: tplRentalRaw 与 tplEnterpriseRaw 在中英文下占位符均为 {business}/{date} 并正确插值', () => { - try { - setRuntimeLocale('zh-CN') - const zhTemplates = getPresetWatermarkTemplates('某公司测试', '2026.10.26') - const zhRental = zhTemplates.find(item => item.id === 'tpl-rental') - const zhEnterprise = zhTemplates.find(item => item.id === 'tpl-enterprise') - assert.match(zhRental.rawText, /\{business\}/) - assert.match(zhRental.rawText, /\{date\}/) - assert.match(zhEnterprise.rawText, /\{business\}/) - assert.match(zhEnterprise.rawText, /\{date\}/) - assert.equal(zhRental.resolvedText, '仅供 某公司测试 租赁备案使用 挪作他用承担法律责任 2026.10.26') - assert.equal(zhEnterprise.resolvedText, '仅供办理 某公司测试 资质审查使用 复制伪造无效 2026.10.26') - - setRuntimeLocale('en-US') - const enTemplates = getPresetWatermarkTemplates('Acme Corp', '2026.10.26') - const enRental = enTemplates.find(item => item.id === 'tpl-rental') - const enEnterprise = enTemplates.find(item => item.id === 'tpl-enterprise') - assert.equal(enRental.resolvedText, 'FOR Acme Corp LEASE REGISTRATION ONLY 2026.10.26') - assert.equal(enEnterprise.resolvedText, 'FOR Acme Corp QUALIFICATION REVIEW ONLY 2026.10.26') - assert.ok(!/[\u4e00-\u9fa5]|\{/.test(enRental.resolvedText + enEnterprise.resolvedText)) - } finally { - setRuntimeLocale('zh-CN') - } -}) diff --git a/extensions/jwt-url-codec/plugin.json b/extensions/jwt-url-codec/plugin.json index 100930d3..3610d2fc 100644 --- a/extensions/jwt-url-codec/plugin.json +++ b/extensions/jwt-url-codec/plugin.json @@ -1,7 +1,7 @@ { "id": "jwt-url-codec", "name": "JWT与URL解析", - "version": "1.0.9", + "version": "1.0.10", "minAppVersion": "1.1.8.0", "description": "离线解析 JWT Token(Header/Payload/生命周期倒计时/HMAC-SHA256 验签与签发)与深度 URL Query 参数拆解重组工具", "author": "ZTools Team", diff --git a/extensions/jwt-url-codec/src/i18n.ts b/extensions/jwt-url-codec/src/i18n.ts index 425b1109..1e76f1e2 100644 --- a/extensions/jwt-url-codec/src/i18n.ts +++ b/extensions/jwt-url-codec/src/i18n.ts @@ -71,14 +71,50 @@ export const t = createTranslator( verifyExceptionStatus: '验签异常,未确认签名', toastVerifyException: '验签异常', emptySectionTitle: '等待输入', - emptyJwtTitle: '在上方粘贴 JWT Token', - emptyUrlTitle: '在上方粘贴 URL 或 Query 字符串', - emptyJwtSub: '支持带 Bearer 前缀;也可从剪贴板读取', + emptyJwtTitle: '点击「编辑 Token/URL」或「读取剪贴板」载入 JWT', + emptyUrlTitle: '点击「编辑 Token/URL」或「读取剪贴板」载入 URL', + emptyJwtSub: '支持带 Bearer 前缀;也可直接在搜索框粘贴完整 Token', emptyUrlSub: '支持完整 URL、域名路径和 a=1&b=2 形式', - actionReadClipboard: '从剪贴板读取', - searchPlaceholder: '粘贴 JWT Token 或 URL 链接直接解析...', - summaryJwtTool: '离线解析与 HS256 签名工具', + actionReadClipboard: '读取剪贴板', + searchPlaceholder: '搜索过滤 Claim 键名 / Query 参数名,或直接粘贴 Token / URL...', + summaryJwtTool: 'JWT 离线解析 · 共 {count} 个 Claim{filterHint}', + summaryJwtEmpty: 'JWT 离线解析与 HS256/384/512 验签', + summaryUrlTool: 'URL 参数解析 · 共 {count} 个 Query 参数{filterHint}', + summaryUrlEmpty: 'URL 拆解与 Query 参数编辑重组', + summaryFilterHint: '(筛选命中 {matched} 项)', + btnEditInput: '编辑 Token/URL', + btnReadClipboard: '读取剪贴板', btnSignJwt: '签发 JWT', + inputFormNavTitle: '编辑 Token / URL', + inputFormSubmitAction: '应用并解析', + inputFormClearAction: '清空当前输入', + inputFormFieldJwtTitle: 'JWT Token 或 URL 原文', + inputFormFieldUrlTitle: 'URL / Query 字符串或 JWT 原文', + inputFormPlaceholder: '粘贴完整 JWT(支持 Bearer 前缀)或 URL / Query 参数串...', + inputFormInfo: '提交后会自动识别 JWT 或 URL 并切换对应解析视图;返回后顶部搜索框用于按 Claim/Query 过滤。', + inputFormEmptyErr: '请输入 JWT Token 或 URL 内容', + claimTimeExplain: '本地时间:{time}(原始秒级时间戳:{raw})', + claimSemanticIss: '签发方 (Issuer)', + claimSemanticSub: '主体标识 (Subject)', + claimSemanticAud: '受众 (Audience)', + claimSemanticExp: '过期时间 (Expiration Time)', + claimSemanticNbf: '生效时间 (Not Before)', + claimSemanticIat: '签发时间 (Issued At)', + claimSemanticJti: '令牌唯一编号 (JWT ID)', + claimSemanticRole: '角色权限 (Role)', + claimSemanticScope: '授权范围 (Scope)', + claimDetailWithMetaMd: '### Claim 名称\n{keyBlock}\n\n{extra}\n\n### Claim 值\n{valBlock}', + filterNoMatchTitle: '未找到匹配的 Claim / Query 参数', + filterNoMatchSub: '当前筛选词:「{query}」,按 Esc 或清空搜索框恢复全部项', + actionClearFilter: '清空筛选词', + actionInspectNestedUrl: '下钻解析此嵌套 URL', + actionReturnParentUrl: '返回上层 URL', + toastNestedUrlOpened: '已下钻解析嵌套 URL', + toastReturnedParentUrl: '已返回上层 URL', + urlParamTableHeader: '| 参数名 | 解码值 | 类型 |\n| --- | --- | --- |', + urlOverviewWithTableMd: '### 解码预览(保留编码的 URL 用于请求)\n{decodedBlock}\n\n### URL 参数表(共 {count} 项)\n{table}\n\n### Query 参数 JSON\n{jsonBlock}', + urlOverviewNoParamsMd: '### 解码预览(保留编码的 URL 用于请求)\n{decodedBlock}\n\n当前 URL 不含 Query 参数。', + paramJsonPrettySection: '\n\n#### JSON 格式化预览\n{jsonBlock}', dropdownTooltip: '切换解析模式', modeJwtTitle: 'JWT Token 深度解析', modeUrlTitle: 'URL 与 Query 参数拆解', @@ -132,7 +168,6 @@ export const t = createTranslator( verifyFormTokenAlgTitle: '当前 Token 算法', toastVerifyPassedAlg: '{alg} 签名校验通过', toastVerifyFailedAlg: '{alg} 签名校验失败', - summaryUrlTool: 'URL 拆解与 Query 参数编辑重组', btnAddQueryParam: '新增参数', actionAddQueryParam: '新增 Query 参数', actionEditQueryParam: '编辑此参数', @@ -214,14 +249,50 @@ export const t = createTranslator( verifyExceptionStatus: 'Verification error; signature unconfirmed', toastVerifyException: 'Verification Error', emptySectionTitle: 'Waiting for Input', - emptyJwtTitle: 'Paste a JWT Token Above', - emptyUrlTitle: 'Paste a URL or Query String Above', - emptyJwtSub: 'Supports Bearer prefix; or load from clipboard', + emptyJwtTitle: 'Click "Edit Token/URL" or "Read Clipboard" to Load JWT', + emptyUrlTitle: 'Click "Edit Token/URL" or "Read Clipboard" to Load URL', + emptyJwtSub: 'Supports Bearer prefix; or paste a full token directly in the search bar', emptyUrlSub: 'Supports full URLs, paths, and a=1&b=2 query strings', - actionReadClipboard: 'Load from Clipboard', - searchPlaceholder: 'Paste a JWT token or URL to inspect...', - summaryJwtTool: 'Offline Decoder & HS256 Signer', + actionReadClipboard: 'Read Clipboard', + searchPlaceholder: 'Filter Claims / Query params, or paste a JWT / URL...', + summaryJwtTool: 'JWT Inspector · {count} Claims{filterHint}', + summaryJwtEmpty: 'Offline JWT Decoder & HS256/384/512 Verifier', + summaryUrlTool: 'URL Parser · {count} Query Params{filterHint}', + summaryUrlEmpty: 'URL Inspector & Query Parameter Editor', + summaryFilterHint: ' ({matched} matched)', + btnEditInput: 'Edit Token/URL', + btnReadClipboard: 'Read Clipboard', btnSignJwt: 'Sign JWT', + inputFormNavTitle: 'Edit Token / URL', + inputFormSubmitAction: 'Apply & Parse', + inputFormClearAction: 'Clear Input', + inputFormFieldJwtTitle: 'JWT Token or URL', + inputFormFieldUrlTitle: 'URL / Query String or JWT', + inputFormPlaceholder: 'Paste a full JWT (Bearer prefix supported) or URL / query string...', + inputFormInfo: 'Auto-detects JWT or URL on submit. After returning, use the search bar to filter Claims or Query parameters.', + inputFormEmptyErr: 'Please enter a JWT token or URL', + claimTimeExplain: 'Local time: {time} (epoch seconds: {raw})', + claimSemanticIss: 'Issuer', + claimSemanticSub: 'Subject', + claimSemanticAud: 'Audience', + claimSemanticExp: 'Expiration Time', + claimSemanticNbf: 'Not Before', + claimSemanticIat: 'Issued At', + claimSemanticJti: 'JWT ID', + claimSemanticRole: 'Role', + claimSemanticScope: 'Scope', + claimDetailWithMetaMd: '### Claim Key\n{keyBlock}\n\n{extra}\n\n### Claim Value\n{valBlock}', + filterNoMatchTitle: 'No Matching Claim or Query Parameter', + filterNoMatchSub: 'Current filter: "{query}". Press Esc or clear search to show all.', + actionClearFilter: 'Clear Filter', + actionInspectNestedUrl: 'Inspect Nested URL', + actionReturnParentUrl: 'Back to Parent URL', + toastNestedUrlOpened: 'Inspecting nested URL', + toastReturnedParentUrl: 'Returned to parent URL', + urlParamTableHeader: '| Key | Decoded Value | Type |\n| --- | --- | --- |', + urlOverviewWithTableMd: '### Decoded Preview (encoded URL preserved for requests)\n{decodedBlock}\n\n### URL Parameters Table ({count})\n{table}\n\n### Query Params JSON\n{jsonBlock}', + urlOverviewNoParamsMd: '### Decoded Preview (encoded URL preserved for requests)\n{decodedBlock}\n\nNo query parameters in this URL.', + paramJsonPrettySection: '\n\n#### Formatted JSON Preview\n{jsonBlock}', dropdownTooltip: 'Switch Inspector Mode', modeJwtTitle: 'JWT Token Inspector', modeUrlTitle: 'URL & Query Parser', @@ -274,7 +345,6 @@ export const t = createTranslator( verifyFormTokenAlgTitle: 'Token Algorithm', toastVerifyPassedAlg: '{alg} Signature Verified', toastVerifyFailedAlg: '{alg} Signature Verification Failed', - summaryUrlTool: 'URL Inspector & Query Parameter Editor', btnAddQueryParam: 'Add Param', actionAddQueryParam: 'Add Query Parameter', actionEditQueryParam: 'Edit Parameter', diff --git a/extensions/jwt-url-codec/src/index.tsx b/extensions/jwt-url-codec/src/index.tsx index d5d851f9..781cf703 100644 --- a/extensions/jwt-url-codec/src/index.tsx +++ b/extensions/jwt-url-codec/src/index.tsx @@ -16,6 +16,7 @@ import React, { } from '@ztools/declarative-ui' import type { CodecMode, JwtVerificationResult, UrlQueryParamItem } from './types.js' import { isRealElectronHost } from './native-ipc.js' +import { CodecInputForm } from './input-form.js' import { JwtSignForm } from './sign-form.js' import { JwtVerifyForm } from './verify-form.js' import { UrlParamForm } from './url-param-form.js' @@ -36,20 +37,114 @@ export * from './jwt-url-service.js' const DEFAULT_JWT_SAMPLE = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyXzEwMjQiLCJuYW1lIjoiWlRvb2xzIERldmVsb3BlciIsInJvbGUiOiJhZG1pbiIsImlhdCI6MTczNTY4OTYwMCwiZXhwIjoxOTg4MTUwNDAwfQ.4f-8h_l7mN3vR2kX9pQ1wZ5yB6cT0dG8jL4sA2eF6uI' +function isLikelyJwtInput(text: string): boolean { + const cleaned = text.trim().replace(/^Bearer\s+/i, '').trim() + if (!cleaned || /\s/.test(cleaned)) return false + const parts = cleaned.split('.') + return parts.length === 3 && parts[0]!.length >= 4 && parts[1]!.length >= 2 && /^eyJ/.test(cleaned) +} + +function isLikelyUrlInput(text: string): boolean { + const trimmed = text.trim() + if (!trimmed || /\s/.test(trimmed)) return false + return /^(?:https?:\/\/|\/\/)/i.test(trimmed) || (trimmed.includes('?') && trimmed.includes('=')) +} + +function formatClaimTimestamp(val: unknown): string | null { + if (typeof val !== 'number' || !Number.isFinite(val) || Math.abs(val) > 1e11) return null + const date = new Date(val * 1000) + if (Number.isNaN(date.getTime())) return null + const pad = (n: number) => String(n).padStart(2, '0') + return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}` +} + +function getClaimSemanticLabel(key: string): string | null { + switch (key) { + case 'iss': return t('claimSemanticIss') + case 'sub': return t('claimSemanticSub') + case 'aud': return t('claimSemanticAud') + case 'exp': return t('claimSemanticExp') + case 'nbf': return t('claimSemanticNbf') + case 'iat': return t('claimSemanticIat') + case 'jti': return t('claimSemanticJti') + case 'role': return t('claimSemanticRole') + case 'scope': return t('claimSemanticScope') + default: return null + } +} + +function escapeMarkdownCell(text: string, maxLen = 64): string { + const flat = text.replace(/\r?\n/g, ' ').replace(/\|/g, '\\|') + return flat.length > maxLen ? `${flat.slice(0, maxLen)}…` : flat +} + +function buildUrlParamsTable(params: UrlQueryParamItem[]): string { + const rows = params.map((p) => { + const kind = p.isNestedUrl ? t('tagNestedUrl') : p.isJsonLike ? t('tagJsonPayload') : 'Query' + return `| \`${escapeMarkdownCell(p.key, 32)}\` | ${escapeMarkdownCell(p.decodedValue, 64)} | ${kind} |` + }) + return `${t('urlParamTableHeader')}\n${rows.join('\n')}` +} + +function tryFormatJson(raw: string): string | null { + try { + return JSON.stringify(JSON.parse(raw), null, 2) + } catch { + return null + } +} + export function JwtUrlCodecCommand() { const locale = useLocale() const [mode, setMode] = useState('jwt') const [rawInput, setRawInput] = useState(isRealElectronHost() ? '' : DEFAULT_JWT_SAMPLE) + const [filterQuery, setFilterQuery] = useState('') + const [parentUrlStack, setParentUrlStack] = useState([]) const [verifyMsgOverride, setVerifyMsgOverride] = useState(null) const [nowMs, setNowMs] = useState(Date.now()) const requestVersion = useRef(0) const { push } = useNavigation() const verifyMsg = verifyMsgOverride ?? t('verifyInitial') - function updateInput(text: string) { + function updateInput(text: string, autoDetectMode = false) { requestVersion.current++ - setRawInput(text) + const trimmed = text.trim() + setRawInput(trimmed) + setFilterQuery('') setVerifyMsgOverride(null) + if (autoDetectMode && trimmed) { + if (isLikelyJwtInput(trimmed)) { + setMode('jwt') + setParentUrlStack([]) + } else if (isLikelyUrlInput(trimmed)) { + setMode('url') + } + } + } + + function handleSearchTextChange(nextText: string) { + const trimmed = nextText.trim() + if (!trimmed) { + if (filterQuery) { + setFilterQuery('') + } else { + updateInput('') + } + return + } + if (isLikelyJwtInput(trimmed)) { + updateInput(trimmed, true) + return + } + if (isLikelyUrlInput(trimmed)) { + updateInput(trimmed, true) + return + } + if (!rawInput.trim()) { + updateInput(trimmed) + return + } + setFilterQuery(nextText) } useEffect(() => { @@ -92,6 +187,19 @@ export function JwtUrlCodecCommand() { } }, [mode, rawInput, locale]) + const openEditInputForm = () => { + push( + { + setParentUrlStack([]) + updateInput(text, true) + }} + />, + ) + } + const handleLoadFromClipboard = async (): Promise => { const request = ++requestVersion.current try { @@ -106,12 +214,8 @@ export function JwtUrlCodecCommand() { return } const trimmed = text.trim() - updateInput(trimmed) - if (trimmed.split('.').length === 3 && /^eyJ/.test(trimmed.replace(/^Bearer\s+/i, ''))) { - setMode('jwt') - } else if (/^https?:\/\//i.test(trimmed) || trimmed.includes('?')) { - setMode('url') - } + setParentUrlStack([]) + updateInput(trimmed, true) await showToast({ style: ToastStyle.Success, title: t('toastLoadedFromClipboard'), @@ -179,6 +283,15 @@ export function JwtUrlCodecCommand() { ) } + const openSignForm = () => { + push( + updateInput(signed)} + />, + ) + } + const applyRebuiltQueryParams = async ( nextParams: Array<{ key: string; value: string }>, toastTitle: string, @@ -229,6 +342,42 @@ export function JwtUrlCodecCommand() { await applyRebuiltQueryParams(next, t('toastQueryDeleted', { key })) } + const handleInspectNestedUrl = async (nestedUrl: string) => { + setParentUrlStack((prev) => [...prev, rawInput]) + updateInput(nestedUrl) + await showToast({ style: ToastStyle.Success, title: t('toastNestedUrlOpened') }) + } + + const handleReturnParentUrl = async () => { + if (!parentUrlStack.length) return + const parent = parentUrlStack[parentUrlStack.length - 1]! + setParentUrlStack((prev) => prev.slice(0, -1)) + updateInput(parent) + await showToast({ style: ToastStyle.Success, title: t('toastReturnedParentUrl') }) + } + + const normalizedFilter = filterQuery.trim().toLowerCase() + + const filteredJwtClaims = useMemo(() => { + if (!jwtState?.ok) return [] + const entries = Object.entries(jwtState.result.payload) + if (!normalizedFilter) return entries + return entries.filter(([k, v]) => { + const semantic = getClaimSemanticLabel(k) ?? '' + const valText = typeof v === 'object' ? JSON.stringify(v) : String(v) + return `${k} ${semantic} ${valText}`.toLowerCase().includes(normalizedFilter) + }) + }, [jwtState, normalizedFilter, locale]) + + const filteredUrlParams = useMemo(() => { + if (!urlState?.ok) return [] + const indexed = urlState.result.queryParams.map((param, idx) => ({ param, idx })) + if (!normalizedFilter) return indexed + return indexed.filter(({ param }) => + `${param.key} ${param.decodedValue} ${param.rawValue}`.toLowerCase().includes(normalizedFilter), + ) + }, [urlState, normalizedFilter]) + const emptySection = ( + + {mode === 'jwt' && ( + + )} } /> @@ -247,30 +400,50 @@ export function JwtUrlCodecCommand() { const activeState = mode === 'jwt' ? jwtState : urlState const isEmpty = Boolean(activeState && !activeState.ok && activeState.empty) + const summaryText = useMemo(() => { + if (mode === 'jwt') { + if (!jwtState?.ok) return t('summaryJwtEmpty') + const total = Object.keys(jwtState.result.payload).length + const filterHint = normalizedFilter ? t('summaryFilterHint', { matched: filteredJwtClaims.length }) : '' + return t('summaryJwtTool', { count: total, filterHint }) + } + if (!urlState?.ok) return t('summaryUrlEmpty') + const total = urlState.result.queryParams.length + const filterHint = normalizedFilter ? t('summaryFilterHint', { matched: filteredUrlParams.length }) : '' + return t('summaryUrlTool', { count: total, filterHint }) + }, [mode, jwtState, urlState, normalizedFilter, filteredJwtClaims.length, filteredUrlParams.length, locale]) + + const filterBarActions = mode === 'jwt' + ? [ + { id: 'edit-input', title: t('btnEditInput'), onAction: openEditInputForm }, + { id: 'read-clipboard', title: t('btnReadClipboard'), onAction: handleLoadFromClipboard }, + { id: 'sign-jwt', title: t('btnSignJwt'), onAction: openSignForm }, + ] + : [ + { id: 'edit-input', title: t('btnEditInput'), onAction: openEditInputForm }, + { id: 'read-clipboard', title: t('btnReadClipboard'), onAction: handleLoadFromClipboard }, + ] + return ( push() } - ] - } : urlState?.ok ? { - summaryText: t('summaryUrlTool'), - actions: [ - { id: 'add-query-param', title: t('btnAddQueryParam'), onAction: openAddQueryParamForm }, - ] - } : undefined} + searchText={filterQuery} + onSearchTextChange={handleSearchTextChange} + filterBar={{ + summaryText, + actions: filterBarActions, + }} searchBarAccessory={ { requestVersion.current++; setMode(val as CodecMode); setVerifyMsgOverride(t('verifySimple')) }} + onChange={(val: string) => { + requestVersion.current++ + setMode(val as CodecMode) + setFilterQuery('') + setVerifyMsgOverride(t('verifySimple')) + }} > @@ -294,6 +467,7 @@ export function JwtUrlCodecCommand() { } actions={ + - - - - - - - - - - } - /> - } - actions={ - - - - - - - - } - /> - {Object.entries(jwtState.result.payload).map(([claimKey, claimVal]) => ( + {!normalizedFilter && ( + + + + + + + + + } /> } actions={ + + + + + + + } + /> + )} + {filteredJwtClaims.map(([claimKey, claimVal]) => { + const isTimeClaim = claimKey === 'exp' || claimKey === 'iat' || claimKey === 'nbf' || claimKey === 'auth_time' + const formattedTime = isTimeClaim ? formatClaimTimestamp(claimVal) : null + const semantic = getClaimSemanticLabel(claimKey) + const rawStr = typeof claimVal === 'object' ? JSON.stringify(claimVal) : String(claimVal) + const subtitle = formattedTime + ? claimKey === 'exp' + ? `${formattedTime} · ${jwtState.result.expiryCountdownText}` + : formattedTime + : rawStr + const extraLines: string[] = [] + if (semantic) extraLines.push(`- **${semantic}**`) + if (formattedTime) extraLines.push(`- ${t('claimTimeExplain', { time: formattedTime, raw: rawStr })}`) + if (claimKey === 'exp') extraLines.push(`- **${t('metaLifecycleTitle')}**:${jwtState.result.expiryCountdownText}`) + const detailMd = extraLines.length > 0 + ? t('claimDetailWithMetaMd', { + keyBlock: fencedBlock(claimKey), + extra: extraLines.join('\n'), + valBlock: fencedBlock(JSON.stringify(claimVal, null, 2), 'json'), + }) + : t('claimDetailMd', { + keyBlock: fencedBlock(claimKey), + valBlock: fencedBlock(JSON.stringify(claimVal, null, 2), 'json'), + }) + return ( + } + actions={ + + + + + } + /> + ) + })} + {normalizedFilter && filteredJwtClaims.length === 0 && ( + + setFilterQuery('')} /> } /> - ))} + )} )} @@ -416,104 +633,158 @@ export function JwtUrlCodecCommand() { icon={Icon.ExclamationMark} accessories={[{ tag: { value: t('urlErrTag'), color: Color.Red } }]} detail={} + actions={ + + + + + } />
)} {mode === 'url' && urlState && urlState.ok && ( - - - - - - - - } - /> - } - actions={ - - - - - - - } - /> - {urlState.result.queryParams.map((param: UrlQueryParamItem, idx: number) => ( + {!normalizedFilter && ( 0 + ? t('urlOverviewWithTableMd', { + decodedBlock: fencedBlock(urlState.result.decodedFullUrl), + count: urlState.result.queryParams.length, + table: buildUrlParamsTable(urlState.result.queryParams), + jsonBlock: fencedBlock(queryParamsToJson(urlState.result.queryParams), 'json'), + }) + : t('urlOverviewNoParamsMd', { + decodedBlock: fencedBlock(urlState.result.decodedFullUrl), + }) + } + metadata={ + + + + + + + + } /> } actions={ - - openEditQueryParamForm(idx, param)} + - handleDeleteQueryParam(idx, param.key)} + - + + {parentUrlStack.length > 0 && ( + + )} + + + } + /> + )} + {filteredUrlParams.map(({ param, idx }) => { + const prettyJson = param.isJsonLike ? tryFormatJson(param.decodedValue) : null + const baseDetail = t('paramDetailMd', { + keyBlock: fencedBlock(param.key), + valBlock: fencedBlock(param.decodedValue), + rawBlock: fencedBlock(param.rawValue), + }) + const fullDetail = prettyJson + ? `${baseDetail}${t('paramJsonPrettySection', { jsonBlock: fencedBlock(prettyJson, 'json') })}` + : baseDetail + return ( + } + actions={ + + + {param.isNestedUrl && ( + handleInspectNestedUrl(param.decodedValue)} + /> + )} + openEditQueryParamForm(idx, param)} + /> + handleDeleteQueryParam(idx, param.key)} + /> + + {parentUrlStack.length > 0 && ( + + )} + + + } + /> + ) + })} + {normalizedFilter && filteredUrlParams.length === 0 && ( + + setFilterQuery('')} /> } /> - ))} + )} )}
diff --git a/extensions/jwt-url-codec/src/input-form.tsx b/extensions/jwt-url-codec/src/input-form.tsx new file mode 100644 index 00000000..9cdd6445 --- /dev/null +++ b/extensions/jwt-url-codec/src/input-form.tsx @@ -0,0 +1,96 @@ +import React, { + Form, + ActionPanel, + Action, + Icon, + Clipboard, + showToast, + ToastStyle, + useState, + useLocale, + useNavigation, +} from '@ztools/declarative-ui' +import type { CodecMode } from './types.js' +import { t } from './i18n.js' + +export interface CodecInputFormProps { + initialValue: string + mode: CodecMode + onApply: (text: string) => void +} + +export function CodecInputForm({ initialValue, mode, onApply }: CodecInputFormProps) { + useLocale() + const [text, setText] = useState(initialValue) + const [error, setError] = useState('') + const { pop } = useNavigation() + + const handleSubmit = () => { + const trimmed = text.trim() + if (!trimmed) { + setError(t('inputFormEmptyErr')) + return + } + onApply(trimmed) + pop() + } + + const handlePasteFromClipboard = async () => { + try { + const clip = await Clipboard.readText() + if (!clip || !clip.trim()) { + await showToast({ + style: ToastStyle.Failure, + title: t('toastClipboardEmpty'), + message: t('toastClipboardEmptyMsg'), + }) + return + } + setText(clip.trim()) + setError('') + } catch (err) { + await showToast({ + style: ToastStyle.Failure, + title: t('toastReadClipboardFailed'), + message: err instanceof Error ? err.message : String(err), + }) + } + } + + return ( +
+ + + { + onApply('') + pop() + }} + /> + + } + > + { + setText(val) + if (error) setError('') + }} + error={error} + placeholder={t('inputFormPlaceholder')} + info={t('inputFormInfo')} + /> + + ) +} diff --git a/extensions/jwt-url-codec/tests/codec.test.mjs b/extensions/jwt-url-codec/tests/codec.test.mjs index e2973184..8e5a7dc7 100644 --- a/extensions/jwt-url-codec/tests/codec.test.mjs +++ b/extensions/jwt-url-codec/tests/codec.test.mjs @@ -160,13 +160,13 @@ test('[边界] 空输入显示中性提示而非红色解析错误,且可从 const host = createHost(), view = await mount(JwtUrlCodecCommand, host) try { await view.search('') - assert.equal(view.item('empty').props.title, '在上方粘贴 JWT Token') + assert.match(view.item('empty').props.title, /编辑 Token\/URL.*读取剪贴板/) assert.equal(view.tree().props.isShowingDetail, false) assert.doesNotMatch(view.text(), /解析失败|EMPTY_JWT_TOKEN/) await view.dropdown('url') - assert.equal(view.item('empty').props.title, '在上方粘贴 URL 或 Query 字符串') + assert.match(view.item('empty').props.title, /编辑 Token\/URL.*读取剪贴板/) host.clipboard.text = token() - await view.run(view.item('empty'), '从剪贴板读取') + await view.run(view.item('empty'), '读取剪贴板') await tick(20) assert.ok(view.item('jwt-overview')) } finally { view.unmount() } @@ -268,7 +268,7 @@ test('URL 模式支持新增、编辑、删除 Query 参数并实时重组复制 await editForm.run(null, '保存并重组复制 URL') await tick(10) assert.equal(host.clipboard.text, 'https://example.test/search?q=ztools&page=1#top') - assert.equal(view.tree().props.searchText, 'https://example.test/search?q=ztools&page=1#top') + assert.equal(view.item('url-overview').props.subtitle, 'https://example.test/search?q=ztools&page=1#top') } finally { editForm.unmount() } @@ -291,7 +291,57 @@ test('URL 模式支持新增、编辑、删除 Query 参数并实时重组复制 await view.run(view.item('param-page-1'), '删除此参数') await tick(10) assert.equal(host.clipboard.text, 'https://example.test/search?q=ztools&lang=zh#top') - assert.equal(view.tree().props.searchText, 'https://example.test/search?q=ztools&lang=zh#top') + assert.equal(view.item('url-overview').props.subtitle, 'https://example.test/search?q=ztools&lang=zh#top') + } finally { + view.unmount() + } +}) + +test('顶栏提供 [编辑 Token/URL] Form 与 [读取剪贴板],搜索框支持按 Claim / Query 过滤并展示 URL 参数表与嵌套 URL 下钻', async () => { + const host = createHost() + const view = await mount(JwtUrlCodecCommand, host) + try { + const barActions = view.tree().props.filterBar.actions + assert.ok(barActions.some(a => a.id === 'edit-input' && a.title === '编辑 Token/URL')) + assert.ok(barActions.some(a => a.id === 'read-clipboard' && a.title === '读取剪贴板')) + + // 1. 通过编辑表单输入 JWT,并用搜索框按 Claim 过滤 + await barActions.find(a => a.id === 'edit-input').onAction() + await tick() + const form = await mountPushed(host) + try { + await form.fill('rawInput', token({ sub: 'u_99', role: 'editor', exp: 2000000000 })) + await form.run(null, '应用并解析') + await tick(10) + } finally { + form.unmount() + } + assert.ok(view.item('claim-role')) + assert.match(view.item('claim-exp').props.subtitle, /\d{4}-\d{2}-\d{2}/) + + await view.search('role') + assert.equal(view.items().length, 1) + assert.equal(view.items()[0].props.id, 'claim-role') + + // 2. 通过顶栏读取剪贴板载入含嵌套 URL 的回调链接,验证 URL 参数表、Query 过滤与下钻 + host.clipboard.text = 'https://auth.example.test/oauth?client_id=abc&redirect_uri=https%3A%2F%2Fapp.example.test%2Fcb%3Fcode%3D42' + await barActions.find(a => a.id === 'read-clipboard').onAction() + await tick(20) + const overviewMd = view.item('url-overview').props.detail.props.markdown + assert.match(overviewMd, /\| 参数名 \| 解码值 \| 类型 \|/) + assert.match(overviewMd, /client_id/) + + await view.search('redirect') + assert.equal(view.items().length, 1) + assert.equal(view.items()[0].props.id, 'param-redirect_uri-1') + + await view.run(view.item('param-redirect_uri-1'), '下钻解析此嵌套 URL') + await tick(10) + assert.equal(view.item('param-code-0').props.subtitle, '42') + + await view.run(view.item('url-overview'), '返回上层 URL') + await tick(10) + assert.ok(view.item('param-client_id-0')) } finally { view.unmount() } diff --git a/extensions/lan-scanner/plugin.json b/extensions/lan-scanner/plugin.json index 141f02b4..42359ee1 100644 --- a/extensions/lan-scanner/plugin.json +++ b/extensions/lan-scanner/plugin.json @@ -1,7 +1,7 @@ { "id": "lan-scanner", "name": "局域网扫描", - "version": "1.0.8", + "version": "1.0.9", "description": "探测局域网设备与常见 TCP 端口,支持 MAC 收藏及 Wake-on-LAN 广播唤醒;每次分段扫描最多 256 个地址", "author": "ZTools Team", "category": [ diff --git a/extensions/lan-scanner/src/i18n.ts b/extensions/lan-scanner/src/i18n.ts index 211a479e..482b5da9 100644 --- a/extensions/lan-scanner/src/i18n.ts +++ b/extensions/lan-scanner/src/i18n.ts @@ -17,6 +17,7 @@ const rawT = createTranslator( errWakeUnconfirmed: '唤醒包发送结果未确认,请检查目标设备状态', errSavedMacsCorrupt: '收藏数据损坏,原记录已保留', errMaxSavedMacs: '最多收藏 100 个设备', + errDeviceMetaCorrupt: '设备备注数据损坏,原记录已保留', rangeNavTitle: '选择扫描范围', rangeSubmitAction: '扫描此地址所在范围', rangeErrInvalidIp: '请输入所选网卡网段内的 IPv4 地址', @@ -72,7 +73,39 @@ const rawT = createTranslator( emptySubtitle: '防火墙、休眠或网络隔离可能导致漏检', warningPartialTitle: '部分设备信息不可用', errStopScanFailed: '停止局域网扫描失败', - errStopWakeFailed: '停止唤醒操作失败' + errStopWakeFailed: '停止唤醒操作失败', + vendorUnknown: '未知厂商', + hostnameUnavailable: '未解析', + actionCopyMac: '复制 MAC 地址', + actionCopySsh: '复制 SSH 连接命令', + actionCopyRdp: '复制远程桌面命令', + actionCopySmb: '复制 SMB 共享路径', + actionEditNote: '设置设备备注', + actionRemoveSavedMac: '移出 WoL 收藏', + actionManageWol: '管理 WoL 收藏设备', + noteNavTitle: '设备备注与 WoL 收藏', + noteFieldMac: '设备 MAC 地址', + noteFieldName: '自定义备注名', + noteFieldNamePlaceholder: '例如:家庭 NAS、办公室台式机', + noteFieldDesc: '保存后将同时收藏该 MAC 到 Wake-on-LAN 列表,留空可清除备注。', + noteSubmitAction: '保存备注并收藏', + noteToastSaved: '设备备注已保存', + noteToastCleared: '设备备注已清除', + wolToastRemoved: '已移出 WoL 收藏', + wolFieldNote: '设备备注(可选)', + wolFieldNotePlaceholder: '例如:公司台式机', + wolDeleteCurrentAction: '删除所选收藏 MAC', + wolManagerNavTitle: 'WoL 收藏设备管理', + wolManagerSearchPlaceholder: '搜索备注名、MAC 或厂商...', + wolManagerEmptyTitle: '暂无收藏的 WoL 设备', + wolManagerEmptySubtitle: '可在局域网扫描结果或唤醒表单中收藏设备 MAC', + wolManagerSummary: '共 {count} 台收藏设备', + wolSectionTitle: '已收藏的 WoL 设备(离线)', + wolOfflineTag: '离线 · 可唤醒', + wolWakeNowAction: '立即发送唤醒包', + wolAddNewAction: '手动输入 MAC 唤醒', + detailInfoSection: '## 设备信息\n- IP 地址:{ip}\n- 主机名:{hostname}\n- MAC 地址:{mac}\n- 网卡厂商:{vendor}{noteLine}', + detailNoteLine: '\n- 自定义备注:{note}' }, 'en-US': { errPlatformUnsupported: 'LAN scanning is not supported on this platform', @@ -89,6 +122,7 @@ const rawT = createTranslator( errWakeUnconfirmed: 'Wake-on-LAN packet delivery unconfirmed; check target device', errSavedMacsCorrupt: 'Saved MAC list is corrupted; original data preserved', errMaxSavedMacs: 'Up to 100 saved devices allowed', + errDeviceMetaCorrupt: 'Device notes data is corrupted; original data preserved', rangeNavTitle: 'Select Scan Range', rangeSubmitAction: 'Scan Subnet Containing This IP', rangeErrInvalidIp: 'Enter an IPv4 address within the selected interface subnet', @@ -144,7 +178,39 @@ const rawT = createTranslator( emptySubtitle: 'Firewalls, sleep mode, or client isolation may hide hosts', warningPartialTitle: 'Some device info unavailable', errStopScanFailed: 'Failed to stop LAN scan', - errStopWakeFailed: 'Failed to stop Wake-on-LAN operation' + errStopWakeFailed: 'Failed to stop Wake-on-LAN operation', + vendorUnknown: 'Unknown vendor', + hostnameUnavailable: 'Unresolved', + actionCopyMac: 'Copy MAC Address', + actionCopySsh: 'Copy SSH Command', + actionCopyRdp: 'Copy RDP Command', + actionCopySmb: 'Copy SMB Path', + actionEditNote: 'Edit Device Note', + actionRemoveSavedMac: 'Remove from WoL Favorites', + actionManageWol: 'Manage WoL Favorites', + noteNavTitle: 'Device Note & WoL Favorite', + noteFieldMac: 'Device MAC Address', + noteFieldName: 'Custom Note', + noteFieldNamePlaceholder: 'e.g. Home NAS, Office PC', + noteFieldDesc: 'Saving also adds this MAC to Wake-on-LAN favorites. Leave empty to clear note.', + noteSubmitAction: 'Save Note & Favorite', + noteToastSaved: 'Device note saved', + noteToastCleared: 'Device note cleared', + wolToastRemoved: 'Removed from WoL favorites', + wolFieldNote: 'Device Note (Optional)', + wolFieldNotePlaceholder: 'e.g. Office Desktop', + wolDeleteCurrentAction: 'Delete Selected Favorite MAC', + wolManagerNavTitle: 'WoL Favorites Manager', + wolManagerSearchPlaceholder: 'Search note, MAC, or vendor...', + wolManagerEmptyTitle: 'No saved WoL devices', + wolManagerEmptySubtitle: 'Save devices from scan results or the Wake-on-LAN form', + wolManagerSummary: '{count} saved [[count:device|devices]]', + wolSectionTitle: 'Saved WoL Devices (Offline)', + wolOfflineTag: 'Offline · Wakeable', + wolWakeNowAction: 'Send Wake-on-LAN Now', + wolAddNewAction: 'Wake by Manual MAC', + detailInfoSection: '## Device Info\n- IP Address: {ip}\n- Hostname: {hostname}\n- MAC Address: {mac}\n- Vendor: {vendor}{noteLine}', + detailNoteLine: '\n- Custom Note: {note}' } }, { defaultLocale: 'en-US' } diff --git a/extensions/lan-scanner/src/mac-command.tsx b/extensions/lan-scanner/src/mac-command.tsx index 6ec13bcb..be0bd786 100644 --- a/extensions/lan-scanner/src/mac-command.tsx +++ b/extensions/lan-scanner/src/mac-command.tsx @@ -1,13 +1,44 @@ import React, { Action, ActionPanel, Detail, Icon, List, Toast, showToast, useEffect, useLocale, useNavigation, useRef, useState } from '@ztools/declarative-ui' -import { cancelMacNetwork, lanOperationId, readMacInterfaces, saveMac, scanMacNetwork, type MacInterface, type MacScan } from './mac-service.js' -import { RangeForm, WakeForm } from './mac-forms.js' +import { + cancelMacNetwork, + formatPortLabel, + lanOperationId, + lookupOuiVendor, + readDeviceNotes, + readMacInterfaces, + readSavedDevices, + removeSavedMac, + saveMac, + scanMacNetwork, + wakeMacDevice, + type MacInterface, + type MacScan, + type SavedDeviceMeta, + type SavedWolDevice +} from './mac-service.js' +import { DeviceNoteForm, RangeForm, WakeForm, WolManagerView } from './mac-forms.js' import { t } from './i18n.js' import { MAC_RESPONSE_LOCAL } from './mac-protocol.zh-data.js' + export default function MacLanCommand() { useLocale() const [interfaces, setInterfaces] = useState([]), [selected, setSelected] = useState(''), [address, setAddress] = useState('') const [report, setReport] = useState(null), [error, setError] = useState(''), [busy, setBusy] = useState(false), [query, setQuery] = useState('') + const [savedDevices, setSavedDevices] = useState([]), [notes, setNotes] = useState>({}) const pending = useRef(null), alive = useRef(true), guard = useRef(false), cancelled = useRef(false), { push } = useNavigation() + + const loadFavorites = async () => { + try { + const [devices, noteMap] = await Promise.all([readSavedDevices(), readDeviceNotes()]) + if (alive.current) { + setSavedDevices(devices) + setNotes(noteMap) + } + } catch { + // 收藏存储异常不阻断实时局域网扫描,用户执行收藏写操作时会严格校验并报错 + } + } + const fail = async (e: unknown) => { if (alive.current) { const message = e instanceof Error ? e.message : String(e); setError(message); await showToast({ style: Toast.Style.Failure, title: t('toastScanFailed'), message }) } } const scan = async (id = selected, target = address) => { if (guard.current) return @@ -29,31 +60,129 @@ export default function MacLanCommand() { cancelled.current = true; setReport(null) if (pending.current) { try { await cancelMacNetwork(pending.current); if (alive.current) setError(t('scanStoppedMsg')) } catch (e) { await fail(e) } } } - useEffect(() => { alive.current = true; void scan(); return () => { alive.current = false; cancelled.current = true; if (pending.current) void cancelMacNetwork(pending.current).catch(e => console.error(t('errStopScanFailed'), e)) } }, []) + useEffect(() => { + alive.current = true + void loadFavorites() + void scan() + return () => { alive.current = false; cancelled.current = true; if (pending.current) void cancelMacNetwork(pending.current).catch(e => console.error(t('errStopScanFailed'), e)) } + }, []) const chooseRange = () => { if (!guard.current && selected) push( { setAddress(value); void scan(selected, value) }} />) } - const rows = (report?.devices ?? []).filter(d => `${d.ip} ${d.mac ?? ''} ${d.openPorts.join(' ')}`.toLowerCase().includes(query.trim().toLowerCase())) + + const savedMacSet = new Set(savedDevices.map(item => item.mac)) + const normalizedQuery = query.trim().toLowerCase() + const rows = (report?.devices ?? []).filter(d => { + if (!normalizedQuery) return true + const vendor = lookupOuiVendor(d.mac) ?? '' + const noteName = d.mac ? (notes[d.mac]?.name ?? '') : '' + const portLabels = d.openPorts.map(formatPortLabel).join(' ') + return `${d.ip} ${d.hostname ?? ''} ${d.mac ?? ''} ${vendor} ${noteName} ${d.openPorts.join(' ')} ${portLabels}`.toLowerCase().includes(normalizedQuery) + }) + const onlineMacs = new Set((report?.devices ?? []).map(d => d.mac).filter((m): m is string => Boolean(m))) + const offlineSaved = savedDevices.filter(d => { + if (onlineMacs.has(d.mac)) return false + if (!normalizedQuery) return true + const vendor = lookupOuiVendor(d.mac) ?? '' + return `${d.name} ${d.mac} ${vendor} ${d.lastIp ?? ''}`.toLowerCase().includes(normalizedQuery) + }) const responseLabel = (r: MacScan['devices'][number]['response']) => (r === MAC_RESPONSE_LOCAL ? t('responseLocalhost') : r) + + const quickWake = async (mac: string, preferredInterfaceId?: string) => { + const iface = interfaces.find(v => v.id === (selected || preferredInterfaceId)) ?? interfaces[0] + if (!iface) { + await showToast({ style: Toast.Style.Failure, title: t('wakeErrSelectNic') }) + return + } + try { + await wakeMacDevice(iface, mac, lanOperationId()) + if (alive.current) await showToast({ style: Toast.Style.Success, title: t('wakeToastSent') }) + } catch (e) { + if (alive.current) await showToast({ style: Toast.Style.Failure, title: e instanceof Error ? e.message : String(e) }) + } + } + return { if (guard.current) return; setSelected(id); setAddress(''); setReport(null); void scan(id, '') }}>{interfaces.map(v => )}} filterBar={{ summaryText: busy ? t('summaryBusy') : error || (report ? t('summaryReport', { range: report.range, scanned: report.scanned, found: report.devices.length, sec: (report.durationMs / 1000).toFixed(1) }) : t('summaryIdle')), actions: [ { id: busy ? 'stop' : 'scan', title: busy ? t('btnStopScan') : t('btnRescan'), onAction: () => busy ? stop() : scan() }, { id: 'range', title: t('btnChooseRange'), onAction: chooseRange } ] }}> - {error && scan()} />} />} />} - {rows.map(d => - - t('detailPortOpenLine', { port: p })).join('\n') : t('detailNoPorts'), + {error && + scan()} /> + } /> + } /> + } />} + {rows.map(d => { + const vendor = lookupOuiVendor(d.mac) + const noteName = d.mac ? (notes[d.mac]?.name ?? '') : '' + const isSaved = Boolean(d.mac && savedMacSet.has(d.mac)) + const hostname = d.hostname?.trim() || '' + const subtitleParts = [noteName, hostname, vendor, d.mac || t('macUnavailable')].filter(Boolean) + const detailInfo = t('detailInfoSection', { + ip: d.ip, + hostname: hostname || t('hostnameUnavailable'), + mac: d.mac || t('macUnavailable'), + vendor: vendor || t('vendorUnknown'), + noteLine: noteName ? t('detailNoteLine', { note: noteName }) : '' + }) + const detailMarkdown = `${detailInfo}\n\n${t('detailMarkdown', { + ports: d.openPorts.length ? d.openPorts.map(p => t('detailPortOpenLine', { port: formatPortLabel(p) })).join('\n') : t('detailNoPorts'), response: responseLabel(d.response), latency: d.latencyMs === null ? t('detailLatencyNone') : t('detailLatencyMs', { ms: d.latencyMs.toFixed(2) }), help: t('helpMarkdown') - })} />} /> - {d.openPorts.filter(p => [80, 443, 8080, 8443].includes(p)).map(p => )} - {d.mac && } />} - {d.mac && { try { await saveMac(d.mac!); await showToast({ style: Toast.Style.Success, title: t('wakeToastSavedMac') }) } catch (e) { await showToast({ style: Toast.Style.Failure, title: e instanceof Error ? e.message : String(e) }) } }} />} + })}` + + return + + } /> + {d.openPorts.filter(p => [80, 443, 8080, 8443].includes(p)).map(p => )} + {d.openPorts.includes(22) && } + {d.openPorts.includes(3389) && } + {d.openPorts.includes(445) && } + {d.mac && } + {d.mac && } />} + {d.mac && } />} + {d.mac && !isSaved && { try { await saveMac(d.mac!); await loadFavorites(); await showToast({ style: Toast.Style.Success, title: t('wakeToastSavedMac') }) } catch (e) { await showToast({ style: Toast.Style.Failure, title: e instanceof Error ? e.message : String(e) }) } }} />} + {d.mac && isSaved && { try { await removeSavedMac(d.mac!); await loadFavorites(); await showToast({ style: Toast.Style.Success, title: t('wolToastRemoved') }) } catch (e) { await showToast({ style: Toast.Style.Failure, title: e instanceof Error ? e.message : String(e) }) } }} />} + } /> + } /> + } + /> + })} + {!busy && !error && !rows.length && + } /> + } /> } /> - } />)} - {!busy && !error && !rows.length && } />} />} />} + } />} + {!busy && !error && offlineSaved.length > 0 && + {offlineSaved.map(d => { + const vendor = lookupOuiVendor(d.mac) + const subtitleParts = [d.mac, vendor, d.lastIp].filter((v): v is string => Boolean(v)) + return Boolean(v)).join(' · ')} + icon={Icon.Desktop} + accessories={[{ tag: t('wolOfflineTag') }]} + actions={ + quickWake(d.mac, d.interfaceId)} /> + } /> + + { try { await removeSavedMac(d.mac); await loadFavorites(); await showToast({ style: Toast.Style.Success, title: t('wolToastRemoved') }) } catch (e) { await showToast({ style: Toast.Style.Failure, title: e instanceof Error ? e.message : String(e) }) } }} /> + } + /> + })} + } {report?.warnings.map((w, index) => )} } diff --git a/extensions/lan-scanner/src/mac-forms.tsx b/extensions/lan-scanner/src/mac-forms.tsx index cc3d335a..b4399094 100644 --- a/extensions/lan-scanner/src/mac-forms.tsx +++ b/extensions/lan-scanner/src/mac-forms.tsx @@ -1,6 +1,20 @@ -import React, { Action, ActionPanel, Form, Toast, showToast, useEffect, useLocale, useRef, useState, useNavigation } from '@ztools/declarative-ui' -import { cancelMacNetwork, lanOperationId, readMacInterfaces, readSavedMacs, saveMac, wakeMacDevice, type MacInterface } from './mac-service.js' +import React, { Action, ActionPanel, Form, Icon, List, Toast, showToast, useEffect, useLocale, useNavigation, useRef, useState } from '@ztools/declarative-ui' +import { + cancelMacNetwork, + lanOperationId, + lookupOuiVendor, + normalizeMacInput, + readMacInterfaces, + readSavedDevices, + removeSavedMac, + saveDeviceNote, + saveMac, + wakeMacDevice, + type MacInterface, + type SavedWolDevice +} from './mac-service.js' import { t } from './i18n.js' + export function RangeForm({ address, saved }: { address: string; saved: (value: string) => void }) { useLocale() const [value, setValue] = useState(address), [error, setError] = useState(''), { pop } = useNavigation() @@ -12,11 +26,190 @@ export function RangeForm({ address, saved }: { address: string; saved: (value: } -export function WakeForm({ initialMac = '' }: { initialMac?: string } = {}) { + +export function DeviceNoteForm({ + mac, + initialName = '', + lastIp, + interfaceId, + onSaved +}: { + mac: string + initialName?: string + lastIp?: string + interfaceId?: string + onSaved?: () => void | Promise +}) { + useLocale() + const [name, setName] = useState(initialName) + const [busy, setBusy] = useState(false) + const { pop } = useNavigation() + + const handleSubmit = async () => { + if (busy) return + setBusy(true) + try { + await saveMac(mac) + await saveDeviceNote(mac, name, { lastIp, interfaceId }) + await showToast({ + style: Toast.Style.Success, + title: name.trim() ? t('noteToastSaved') : t('noteToastCleared') + }) + await onSaved?.() + pop() + } catch (e) { + await showToast({ style: Toast.Style.Failure, title: e instanceof Error ? e.message : String(e) }) + } finally { + setBusy(false) + } + } + + return
+ + }> + + + + +} + +export function WolManagerView({ onChanged }: { onChanged?: () => void | Promise } = {}) { + useLocale() + const [devices, setDevices] = useState([]) + const [interfaces, setInterfaces] = useState([]) + const [selectedNic, setSelectedNic] = useState('') + const [query, setQuery] = useState('') + const [busy, setBusy] = useState(false) + const alive = useRef(true) + const pending = useRef(null) + const { push } = useNavigation() + + const load = async () => { + setBusy(true) + try { + const [stored, nics] = await Promise.all([readSavedDevices(), readMacInterfaces()]) + if (!alive.current) return + setDevices(stored) + setInterfaces(nics) + setSelectedNic(prev => (prev && nics.some(v => v.id === prev) ? prev : (nics[0]?.id ?? ''))) + } catch (e) { + if (alive.current) await showToast({ style: Toast.Style.Failure, title: e instanceof Error ? e.message : String(e) }) + } finally { + if (alive.current) setBusy(false) + } + } + + useEffect(() => { + alive.current = true + void load() + return () => { + alive.current = false + if (pending.current) void cancelMacNetwork(pending.current).catch(e => console.error(t('errStopWakeFailed'), e)) + } + }, []) + + const sendWake = async (device: SavedWolDevice) => { + const iface = interfaces.find(v => v.id === (selectedNic || device.interfaceId)) ?? interfaces[0] + if (!iface) { + await showToast({ style: Toast.Style.Failure, title: t('wakeErrSelectNic') }) + return + } + const operationId = lanOperationId() + pending.current = operationId + try { + await wakeMacDevice(iface, device.mac, operationId) + if (alive.current) await showToast({ style: Toast.Style.Success, title: t('wakeToastSent') }) + } catch (e) { + if (alive.current) await showToast({ style: Toast.Style.Failure, title: e instanceof Error ? e.message : String(e) }) + } finally { + if (pending.current === operationId) pending.current = null + } + } + + const removeDevice = async (mac: string) => { + try { + await removeSavedMac(mac) + if (alive.current) { + setDevices(await readSavedDevices()) + await showToast({ style: Toast.Style.Success, title: t('wolToastRemoved') }) + await onChanged?.() + } + } catch (e) { + if (alive.current) await showToast({ style: Toast.Style.Failure, title: e instanceof Error ? e.message : String(e) }) + } + } + + const normalizedQuery = query.trim().toLowerCase() + const filtered = devices.filter(d => { + if (!normalizedQuery) return true + const vendor = lookupOuiVendor(d.mac) ?? '' + return `${d.name} ${d.mac} ${vendor} ${d.lastIp ?? ''}`.toLowerCase().includes(normalizedQuery) + }) + + return 0 ? + {interfaces.map(v => )} + : undefined} + filterBar={{ + summaryText: t('wolManagerSummary', { count: devices.length }), + actions: [ + { id: 'add-wol', title: t('wolAddNewAction'), onAction: () => push( { await load(); await onChanged?.() }} />) } + ] + }} + > + {filtered.map(d => { + const vendor = lookupOuiVendor(d.mac) + const subtitleParts = [d.mac, vendor, d.lastIp].filter((v): v is string => Boolean(v)) + return Boolean(v)).join(' · ')} + icon={Icon.Desktop} + actions={ + sendWake(d)} /> + { await load(); await onChanged?.() }} />} /> + + removeDevice(d.mac)} /> + } + /> + })} + {!busy && filtered.length === 0 && + { await load(); await onChanged?.() }} />} /> + } + />} + +} + +export function WakeForm({ + initialMac = '', + initialNote = '', + onChanged +}: { + initialMac?: string + initialNote?: string + onChanged?: () => void | Promise +} = {}) { const locale = useLocale() - const [interfaces, setInterfaces] = useState([]), [selected, setSelected] = useState(''), [mac, setMac] = useState(initialMac) - const [saved, setSaved] = useState([]), [statusOverride, setStatusOverride] = useState(null), [busy, setBusy] = useState(false) + const [interfaces, setInterfaces] = useState([]) + const [selected, setSelected] = useState('') + const [mac, setMac] = useState(initialMac) + const [note, setNote] = useState(initialNote) + const [saved, setSaved] = useState([]) + const [statusOverride, setStatusOverride] = useState(null) + const [busy, setBusy] = useState(false) const pending = useRef(null), alive = useRef(true), guard = useRef(false) + const { push } = useNavigation() const status = statusOverride ?? t('wakeStatusLoading') useEffect(() => { setStatusOverride(null) }, [locale]) const fail = async (e: unknown) => { if (alive.current) { const message = e instanceof Error ? e.message : String(e); setStatusOverride(message); await showToast({ style: Toast.Style.Failure, title: message }) } } @@ -24,7 +217,14 @@ export function WakeForm({ initialMac = '' }: { initialMac?: string } = {}) { try { const next = await readMacInterfaces() if (alive.current) { setInterfaces(next); setSelected(next[0]?.id ?? ''); setStatusOverride(next.length ? t('wakeStatusReady') : t('wakeStatusNoNic')) } - const stored = await readSavedMacs(); if (alive.current) setSaved(stored) + const stored = await readSavedDevices() + if (alive.current) { + setSaved(stored) + if (initialMac && !initialNote) { + const hit = stored.find(item => item.mac === initialMac.toUpperCase()) + if (hit?.name) setNote(hit.name) + } + } } catch (e) { await fail(e) } } useEffect(() => { alive.current = true; void load(); return () => { alive.current = false; if (pending.current) void cancelMacNetwork(pending.current).catch(e => console.error(t('errStopWakeFailed'), e)) } }, []) @@ -40,14 +240,51 @@ export function WakeForm({ initialMac = '' }: { initialMac?: string } = {}) { } catch (e) { await fail(e) } finally { pending.current = null; guard.current = false; if (alive.current) setBusy(false) } } + const handleSave = async () => { + try { + await saveMac(mac) + if (note.trim()) await saveDeviceNote(mac, note, { interfaceId: selected || undefined }) + if (alive.current) { + setSaved(await readSavedDevices()) + await showToast({ style: Toast.Style.Success, title: t('wakeToastSavedMac') }) + await onChanged?.() + } + } catch (e) { await fail(e) } + } + const handleDeleteCurrent = async () => { + try { + const normalized = normalizeMacInput(mac) + await removeSavedMac(normalized) + if (alive.current) { + setSaved(await readSavedDevices()) + await showToast({ style: Toast.Style.Success, title: t('wolToastRemoved') }) + await onChanged?.() + } + } catch (e) { await fail(e) } + } return
- { try { await saveMac(mac); if (alive.current) { setSaved(await readSavedMacs()); await showToast({ style: Toast.Style.Success, title: t('wakeToastSavedMac') }) } } catch (e) { await fail(e) } }} /> + + push( { await load(); await onChanged?.() }} />)} /> + {saved.length > 0 && } }> {interfaces.map(v => )} - {saved.length > 0 && { if (value) setMac(value) }}>{saved.map(v => )}} + + {saved.length > 0 && { + if (!value) return + setMac(value) + const hit = saved.find(item => item.mac === value) + setNote(hit?.name ?? '') + }}> + + {saved.map(v => { + const vendor = lookupOuiVendor(v.mac) + const label = v.name ? `${v.name} · ${v.mac}` : (vendor ? `${v.mac} · ${vendor}` : v.mac) + return + })} + } } diff --git a/extensions/lan-scanner/src/mac-service.ts b/extensions/lan-scanner/src/mac-service.ts index 226130b1..3a213bd8 100644 --- a/extensions/lan-scanner/src/mac-service.ts +++ b/extensions/lan-scanner/src/mac-service.ts @@ -2,9 +2,12 @@ import { LocalStorage } from '@ztools/declarative-ui' import { t } from './i18n.js' import { resolveErrorMessage } from './error-i18n.js' import { MAC_RESPONSE_LOCAL, type MacResponseLocal } from './mac-protocol.zh-data.js' +export { lookupOuiVendor, formatPortLabel } from './oui-vendor.js' export interface MacInterface { id: string; name: string; ip: string; netmask: string; subnet: string; broadcast: string | null; prefix: number } -export interface MacDevice { ip: string; mac: string | null; openPorts: number[]; response: 'ICMP' | 'TCP' | MacResponseLocal; latencyMs: number | null } +export interface MacDevice { ip: string; mac: string | null; hostname?: string | null; openPorts: number[]; response: 'ICMP' | 'TCP' | MacResponseLocal; latencyMs: number | null } export interface MacScan { devices: MacDevice[]; warnings: string[]; range: string; scanned: number; durationMs: number; checkedAt: string } +export interface SavedDeviceMeta { name: string; lastIp?: string; interfaceId?: string; updatedAt: string } +export interface SavedWolDevice { mac: string; name: string; lastIp?: string; interfaceId?: string; updatedAt?: string } interface Bridge { transport?: { methods?: Record Promise<{ success?: boolean; data?: unknown; error?: { message?: string } }>> } } const record = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v) const ip = (v: unknown): v is string => typeof v === 'string' && /^(0|[1-9]\d{0,2})(\.(0|[1-9]\d{0,2})){3}$/.test(v) && v.split('.').every(n => Number(n) < 256) @@ -25,7 +28,7 @@ export async function readMacInterfaces(): Promise { } export async function scanMacNetwork(iface: MacInterface, address: string, operationId: string): Promise { const result = await lanInvoke('lan_network', { action: 'scan', interfaceId: iface.id, scanAddress: address, operationId }) - if (!Array.isArray(result.devices) || result.devices.length > 256 || result.devices.some(d => !record(d) || !ip(d.ip) || (d.mac !== null && (typeof d.mac !== 'string' || !/^[\dA-F]{2}(:[\dA-F]{2}){5}$/.test(d.mac))) || !Array.isArray(d.openPorts) || d.openPorts.some(p => ![22, 80, 443, 445, 3389, 5900, 8080, 8443].includes(Number(p)) || typeof p !== 'number') || (d.latencyMs !== null && !finite(d.latencyMs)) || typeof d.response !== 'string' || !['ICMP', 'TCP', MAC_RESPONSE_LOCAL].includes(d.response)) || !Array.isArray(result.warnings) || result.warnings.some(w => typeof w !== 'string') || typeof result.range !== 'string' || !Number.isInteger(result.scanned) || Number(result.scanned) < 1 || Number(result.scanned) > 256 || !finite(result.durationMs) || typeof result.checkedAt !== 'string' || !Number.isFinite(Date.parse(result.checkedAt))) throw new Error(t('errScanReceiptIncomplete')) + if (!Array.isArray(result.devices) || result.devices.length > 256 || result.devices.some(d => !record(d) || !ip(d.ip) || (d.mac !== null && (typeof d.mac !== 'string' || !/^[\dA-F]{2}(:[\dA-F]{2}){5}$/.test(d.mac))) || (d.hostname !== undefined && d.hostname !== null && typeof d.hostname !== 'string') || !Array.isArray(d.openPorts) || d.openPorts.some(p => ![22, 80, 443, 445, 3389, 5900, 8080, 8443].includes(Number(p)) || typeof p !== 'number') || (d.latencyMs !== null && !finite(d.latencyMs)) || typeof d.response !== 'string' || !['ICMP', 'TCP', MAC_RESPONSE_LOCAL].includes(d.response)) || !Array.isArray(result.warnings) || result.warnings.some(w => typeof w !== 'string') || typeof result.range !== 'string' || !Number.isInteger(result.scanned) || Number(result.scanned) < 1 || Number(result.scanned) > 256 || !finite(result.durationMs) || typeof result.checkedAt !== 'string' || !Number.isFinite(Date.parse(result.checkedAt))) throw new Error(t('errScanReceiptIncomplete')) if (new Set(result.devices.map(d => d.ip)).size !== result.devices.length) throw new Error(t('errScanDuplicateIp')) const numeric = (v: string) => v.split('.').reduce((n, part) => n * 256 + Number(part), 0) const mask = numeric(iface.netmask), first = (numeric(iface.ip) & mask) >>> 0, last = first + ((~mask) >>> 0) @@ -48,11 +51,29 @@ export async function wakeMacDevice(iface: MacInterface, raw: string, operationI if (result.bytes !== 102 || result.mac !== mac || !iface.broadcast || result.broadcast !== iface.broadcast) throw new Error(t('errWakeUnconfirmed')) } const favoritesKey = 'lan.saved-macs.v1' +const deviceMetaKey = 'lan.device-meta.v1' function savedMacs(value: unknown) { if (value === undefined) return [] as string[] if (!Array.isArray(value) || value.length > 100 || value.some(v => typeof v !== 'string' || normalizeMacInput(v) !== v)) throw new Error(t('errSavedMacsCorrupt')) return value as string[] } +function parsedDeviceMeta(value: unknown): Record { + if (value === undefined) return {} + if (!record(value)) throw new Error(t('errDeviceMetaCorrupt')) + const out: Record = {} + for (const [k, v] of Object.entries(value)) { + if (!record(v) || typeof v.name !== 'string' || typeof v.updatedAt !== 'string') throw new Error(t('errDeviceMetaCorrupt')) + const mac = normalizeMacInput(k) + if (mac !== k) throw new Error(t('errDeviceMetaCorrupt')) + out[mac] = { + name: v.name, + ...(typeof v.lastIp === 'string' ? { lastIp: v.lastIp } : {}), + ...(typeof v.interfaceId === 'string' ? { interfaceId: v.interfaceId } : {}), + updatedAt: v.updatedAt + } + } + return out +} export async function readSavedMacs() { return savedMacs(await LocalStorage.getItem(favoritesKey)) } export async function saveMac(raw: string) { const mac = normalizeMacInput(raw) @@ -63,4 +84,46 @@ export async function saveMac(raw: string) { return [...current, mac] }) } +export async function removeSavedMac(raw: string) { + const mac = normalizeMacInput(raw) + await LocalStorage.updateItem(favoritesKey, value => { + const current = savedMacs(value) + return current.filter(item => item !== mac) + }) +} +export async function readDeviceNotes(): Promise> { + return parsedDeviceMeta(await LocalStorage.getItem(deviceMetaKey)) +} +export async function saveDeviceNote(raw: string, name: string, meta?: { lastIp?: string; interfaceId?: string }) { + const mac = normalizeMacInput(raw) + const trimmed = name.trim() + await LocalStorage.updateItem(deviceMetaKey, value => { + const current = { ...parsedDeviceMeta(value) } + if (!trimmed) { + delete current[mac] + return current + } + const prev = current[mac] + current[mac] = { + name: trimmed, + ...(meta?.lastIp || prev?.lastIp ? { lastIp: meta?.lastIp ?? prev?.lastIp } : {}), + ...(meta?.interfaceId || prev?.interfaceId ? { interfaceId: meta?.interfaceId ?? prev?.interfaceId } : {}), + updatedAt: new Date().toISOString() + } + return current + }) +} +export async function readSavedDevices(): Promise { + const [macs, notes] = await Promise.all([readSavedMacs(), readDeviceNotes()]) + return macs.map(mac => { + const meta = notes[mac] + return { + mac, + name: meta?.name ?? '', + lastIp: meta?.lastIp, + interfaceId: meta?.interfaceId, + updatedAt: meta?.updatedAt + } + }) +} export async function cancelMacNetwork(operationId: string) { await lanInvoke('lan_network', { action: 'cancel', operationId }) } diff --git a/extensions/lan-scanner/src/oui-vendor.ts b/extensions/lan-scanner/src/oui-vendor.ts new file mode 100644 index 00000000..2df12d35 --- /dev/null +++ b/extensions/lan-scanner/src/oui-vendor.ts @@ -0,0 +1,97 @@ +// 精简离线 MAC OUI 厂商前缀字典(只读匹配真实扫描到的 MAC 前 3 字节,未知返回 null) +const OUI_VENDORS: Record = { + // Apple + '00:03:93': 'Apple', '00:0A:27': 'Apple', '00:0A:95': 'Apple', '00:0D:93': 'Apple', + '00:11:24': 'Apple', '00:14:51': 'Apple', '00:16:CB': 'Apple', '00:17:F2': 'Apple', + '00:19:E3': 'Apple', '00:1B:63': 'Apple', '00:1C:B3': 'Apple', '00:1D:4F': 'Apple', + '00:1E:52': 'Apple', '00:1E:C2': 'Apple', '00:1F:5B': 'Apple', '00:1F:F3': 'Apple', + '00:21:E9': 'Apple', '00:22:41': 'Apple', '00:23:12': 'Apple', '00:23:32': 'Apple', + '00:23:6C': 'Apple', '00:23:DF': 'Apple', '00:24:36': 'Apple', '00:25:00': 'Apple', + '00:25:4B': 'Apple', '00:25:BC': 'Apple', '00:26:08': 'Apple', '00:26:4A': 'Apple', + '00:26:B0': 'Apple', '00:26:BB': 'Apple', '28:CF:E9': 'Apple', '3C:07:54': 'Apple', + '40:30:04': 'Apple', '54:26:96': 'Apple', '60:03:08': 'Apple', '68:5B:35': 'Apple', + '70:56:81': 'Apple', '78:31:C1': 'Apple', '80:E6:50': 'Apple', '88:63:DF': 'Apple', + '98:01:A7': 'Apple', 'A4:5E:60': 'Apple', 'A8:20:66': 'Apple', 'AC:BC:32': 'Apple', + 'B8:E8:56': 'Apple', 'BC:52:B7': 'Apple', 'C8:2A:14': 'Apple', 'D0:03:4B': 'Apple', + 'DC:2B:2A': 'Apple', 'E0:AC:CB': 'Apple', 'F0:18:98': 'Apple', 'F4:5C:89': 'Apple', + // Synology & QNAP (NAS) + '00:11:32': 'Synology', '90:09:D0': 'Synology', + '00:08:9B': 'QNAP', '24:5E:BE': 'QNAP', + // Xiaomi + '04:CF:8C': 'Xiaomi', '0C:1D:AF': 'Xiaomi', '10:2A:B3': 'Xiaomi', '14:F6:5A': 'Xiaomi', + '18:59:36': 'Xiaomi', '28:6C:07': 'Xiaomi', '34:80:B3': 'Xiaomi', '38:A4:ED': 'Xiaomi', + '50:64:2B': 'Xiaomi', '58:44:98': 'Xiaomi', '64:09:80': 'Xiaomi', '64:B4:73': 'Xiaomi', + '68:DF:DD': 'Xiaomi', '74:23:44': 'Xiaomi', '78:02:F8': 'Xiaomi', '7C:1D:D9': 'Xiaomi', + '8C:BE:BE': 'Xiaomi', '98:FA:E3': 'Xiaomi', '9C:99:A0': 'Xiaomi', 'AC:C1:EE': 'Xiaomi', + 'B0:E2:35': 'Xiaomi', 'C4:0B:CB': 'Xiaomi', 'D4:97:0B': 'Xiaomi', 'F0:B4:29': 'Xiaomi', + 'F8:A4:5F': 'Xiaomi', + // Huawei & Honor + '00:18:82': 'Huawei', '00:1E:10': 'Huawei', '00:25:68': 'Huawei', '00:25:9E': 'Huawei', + '00:46:4B': 'Huawei', '04:02:1F': 'Huawei', '04:BD:70': 'Huawei', '08:19:A6': 'Huawei', + '10:1B:54': 'Huawei', '14:B9:68': 'Huawei', '20:08:ED': 'Huawei', '24:09:95': 'Huawei', + '28:31:52': 'Huawei', '34:6B:D3': 'Huawei', '48:46:FB': 'Huawei', '54:89:98': 'Huawei', + '60:DE:44': 'Huawei', '70:72:3C': 'Huawei', '80:B6:86': 'Huawei', '88:CE:FA': 'Huawei', + '9C:28:EF': 'Huawei', 'AC:E2:15': 'Huawei', 'C8:D1:5E': 'Huawei', 'E0:24:7F': 'Huawei', + 'F4:C7:14': 'Huawei', + // TP-Link + '00:27:19': 'TP-Link', '14:CC:20': 'TP-Link', '14:CF:92': 'TP-Link', '18:A6:F7': 'TP-Link', + '1C:3B:F3': 'TP-Link', '30:B5:C2': 'TP-Link', '50:C7:BF': 'TP-Link', '54:C8:0F': 'TP-Link', + '60:E3:27': 'TP-Link', '64:70:02': 'TP-Link', '74:DA:88': 'TP-Link', '84:16:F9': 'TP-Link', + '90:F6:52': 'TP-Link', '98:DA:C4': 'TP-Link', 'A0:F3:C1': 'TP-Link', 'B0:4E:26': 'TP-Link', + 'C0:25:E9': 'TP-Link', 'D8:07:B6': 'TP-Link', 'E8:94:F6': 'TP-Link', 'F4:F2:6D': 'TP-Link', + // Intel & Realtek & Broadcom + '00:02:B3': 'Intel', '00:03:47': 'Intel', '00:0E:0C': 'Intel', '00:13:02': 'Intel', + '00:15:17': 'Intel', '00:1B:21': 'Intel', '00:1E:67': 'Intel', '00:21:6A': 'Intel', + '00:24:D7': 'Intel', '3C:A9:F4': 'Intel', '48:51:B7': 'Intel', '60:57:18': 'Intel', + '68:05:CA': 'Intel', '7C:7A:91': 'Intel', '80:86:F2': 'Intel', '8C:8D:28': 'Intel', + 'A0:36:9F': 'Intel', 'B4:96:91': 'Intel', 'D4:3D:7E': 'Intel', 'F4:8C:50': 'Intel', + '00:E0:4C': 'Realtek', '52:54:00': 'QEMU/KVM', '00:0C:29': 'VMware', '00:50:56': 'VMware', + '08:00:27': 'VirtualBox', '00:15:5D': 'Microsoft Hyper-V', + // Raspberry Pi & Espressif + 'B8:27:EB': 'Raspberry Pi', 'DC:A6:32': 'Raspberry Pi', 'E4:5F:01': 'Raspberry Pi', '28:CD:C1': 'Raspberry Pi', + '24:0A:C4': 'Espressif', '30:AE:A4': 'Espressif', 'A4:CF:12': 'Espressif', 'C4:4F:33': 'Espressif', + // Samsung + '00:12:FB': 'Samsung', '00:16:32': 'Samsung', '00:1A:8A': 'Samsung', '00:1D:25': 'Samsung', + '00:21:19': 'Samsung', '00:23:39': 'Samsung', '00:26:37': 'Samsung', '18:3A:2D': 'Samsung', + '34:23:BA': 'Samsung', '50:01:BB': 'Samsung', '78:47:1D': 'Samsung', '84:25:DB': 'Samsung', + 'A0:82:1F': 'Samsung', 'BC:14:85': 'Samsung', 'CC:07:AB': 'Samsung', 'E4:92:FB': 'Samsung', + // ASUS / Dell / Lenovo / HP / Netgear / Cisco / Ubiquiti / Google + '00:11:D8': 'ASUS', '04:92:26': 'ASUS', '10:BF:48': 'ASUS', '1C:87:2C': 'ASUS', + '2C:56:DC': 'ASUS', '38:D5:47': 'ASUS', '50:46:5D': 'ASUS', '74:D0:2B': 'ASUS', + 'AC:22:0B': 'ASUS', 'B0:6E:BF': 'ASUS', 'D8:50:E6': 'ASUS', 'F8:32:E4': 'ASUS', + '00:14:22': 'Dell', '00:1A:A0': 'Dell', '14:FE:B5': 'Dell', '18:03:73': 'Dell', + '24:B6:FD': 'Dell', '5C:26:0A': 'Dell', 'B8:AC:6F': 'Dell', 'F0:1F:AF': 'Dell', + '00:06:1B': 'Lenovo', '28:D2:44': 'Lenovo', '50:7B:9D': 'Lenovo', '60:D9:C7': 'Lenovo', + '8C:16:45': 'Lenovo', 'C8:DD:C9': 'Lenovo', + '00:17:A4': 'HP', '00:21:5A': 'HP', '10:60:4B': 'HP', '3C:D9:2B': 'HP', '9C:8E:99': 'HP', + '00:09:5B': 'Netgear', '00:14:6C': 'Netgear', '20:4E:7F': 'Netgear', '28:C6:8E': 'Netgear', 'C0:3F:0E': 'Netgear', + '00:00:0C': 'Cisco', '00:1B:D5': 'Cisco', '00:26:0B': 'Cisco', + '00:15:6D': 'Ubiquiti', '04:18:D6': 'Ubiquiti', '24:A4:3C': 'Ubiquiti', '44:D9:E7': 'Ubiquiti', '78:8A:20': 'Ubiquiti', + '00:1A:11': 'Google', '3C:5A:B4': 'Google', '54:60:09': 'Google', 'F4:F5:D8': 'Google', + '00:0D:3A': 'Microsoft', '28:18:78': 'Microsoft', '7C:1E:52': 'Microsoft', + '00:1C:B0': 'H3C', '38:22:D6': 'H3C', '00:D0:F8': 'Ruijie', 'C8:3A:35': 'Tenda', 'D8:32:14': 'Tenda' +} + +export function lookupOuiVendor(mac: string | null | undefined): string | null { + if (!mac || typeof mac !== 'string') return null + const normalized = mac.trim().toUpperCase().replace(/-/g, ':') + const match = normalized.match(/^([\dA-F]{2}:[\dA-F]{2}:[\dA-F]{2})/) + if (!match) return null + return OUI_VENDORS[match[1]] ?? null +} + +const PORT_SERVICE_NAMES: Record = { + 22: 'SSH', + 80: 'HTTP', + 443: 'HTTPS', + 445: 'SMB', + 3389: 'RDP', + 5900: 'VNC', + 8080: 'HTTP-Alt', + 8443: 'HTTPS-Alt' +} + +export function formatPortLabel(port: number): string { + const svc = PORT_SERVICE_NAMES[port] + return svc ? `${port} (${svc})` : String(port) +} diff --git a/extensions/lan-scanner/tests/mac-lan.test.mjs b/extensions/lan-scanner/tests/mac-lan.test.mjs index 987716f6..e5a48008 100644 --- a/extensions/lan-scanner/tests/mac-lan.test.mjs +++ b/extensions/lan-scanner/tests/mac-lan.test.mjs @@ -1,7 +1,7 @@ import test, {beforeEach,afterEach} from 'node:test' import assert from 'node:assert/strict' import {createHost,mount,tick} from '../../shared/test-harness.mjs' -import Command,{commands,scanMacNetwork,saveMac,readSavedMacs,wakeMacDevice} from '../dist/index.js' +import Command,{commands,scanMacNetwork,saveMac,removeSavedMac,saveDeviceNote,readSavedDevices,readSavedMacs,wakeMacDevice,lookupOuiVendor} from '../dist/index.js' const iface={id:'en0|192.0.2.100|255.255.255.0',name:'en0',ip:'192.0.2.100',netmask:'255.255.255.0',subnet:'192.0.2.0/24',broadcast:'192.0.2.255',prefix:24} const mac='02:11:22:33:44:55' const report=()=>({success:true,devices:[{ip:'192.0.2.8',mac,openPorts:[80,443],response:'TCP',latencyMs:1.75}],warnings:[],range:'192.0.2.0/24',scanned:254,durationMs:1250,checkedAt:new Date().toISOString()}) @@ -109,3 +109,48 @@ test('扫描失败后错误行回车即重新扫描;清单不再申请用不 const {readFileSync}=await import('node:fs');const manifest=JSON.parse(readFileSync(new URL('../plugin.json',import.meta.url))) assert.ok(!manifest.permissions.includes('shell')) }) + +test('支持真实主机名、OUI 厂商识别、自定义备注与 WoL 收藏删除/离线设备管理',async()=>{ + assert.equal(lookupOuiVendor('00:11:32:AA:BB:CC'),'Synology') + assert.equal(lookupOuiVendor('02:11:22:33:44:55'),null) + const nasMac='00:11:32:12:34:56' + const offlineMac='00:E0:4C:AA:BB:CC' + await saveMac(offlineMac) + await saveDeviceNote(offlineMac,'公司台式机',{lastIp:'192.0.2.50'}) + await saveDeviceNote(nasMac,'家庭 NAS',{lastIp:'192.0.2.10'}) + host.ipc.lan_network=async p=>p.action==='interfaces'?{success:true,interfaces:[iface]}:p.action==='scan'?{...report(),devices:[{ip:'192.0.2.10',mac:nasMac,hostname:'DiskStation.local',openPorts:[22,80,445,3389],response:'TCP',latencyMs:2.1}]}:p.action==='wake'?{success:true,bytes:102,mac:p.mac,broadcast:iface.broadcast}:{success:true,cancelled:true} + const v=await open() + const item=v.item('device-192.0.2.10') + assert.match(item.props.subtitle,/家庭 NAS/) + assert.match(item.props.subtitle,/DiskStation\.local/) + assert.match(item.props.subtitle,/Synology/) + const titles=v.actions(item).map(a=>a.props.title) + assert.ok(titles.includes('复制 SSH 连接命令')) + assert.ok(titles.includes('复制远程桌面命令')) + assert.ok(titles.includes('复制 SMB 共享路径')) + assert.ok(titles.includes('设置设备备注')) + const detail=v.actions(item)[1].props.target.props.markdown + assert.match(detail,/DiskStation\.local/) + assert.match(detail,/Synology/) + assert.match(detail,/22 \(SSH\)/) + // 离线已收藏 WoL 设备应出现在下方分区并可直接唤醒或删除 + const offlineItem=v.item(`saved-${offlineMac}`) + assert.equal(offlineItem.props.title,'公司台式机') + await v.run(offlineItem,'立即发送唤醒包') + assert.equal(calls('wake').length,1) + assert.equal(calls('wake')[0][1].mac,offlineMac) + await v.run(offlineItem,'移出 WoL 收藏') + assert.deepEqual(await readSavedMacs(),[]) + assert.deepEqual(await readSavedDevices(),[]) + // 搜索支持按备注、主机名与厂商筛选 + await v.search('Synology') + assert.ok(v.items().some(n=>n.props.id==='device-192.0.2.10')) + // 清除备注 + await saveDeviceNote(nasMac,'') + await saveMac(nasMac) + const savedAfter=await readSavedDevices() + assert.equal(savedAfter.length,1) + assert.equal(savedAfter[0].name,'') + await removeSavedMac(nasMac) + assert.deepEqual(await readSavedMacs(),[]) +}) diff --git a/extensions/lan-share/package.json b/extensions/lan-share/package.json index 272e837a..7ebc7125 100644 --- a/extensions/lan-share/package.json +++ b/extensions/lan-share/package.json @@ -1,6 +1,6 @@ { "name": "@ztools/plugin-lan-share", - "version": "1.0.0", + "version": "2.0.16", "description": "选择电脑上的文件开启局域网共享,同一网络的设备用浏览器打开本机地址或扫码下载", "main": "dist/index.js", "types": "dist/index.d.ts", diff --git a/extensions/lan-share/plugin.json b/extensions/lan-share/plugin.json index 5868de25..1df80628 100644 --- a/extensions/lan-share/plugin.json +++ b/extensions/lan-share/plugin.json @@ -2,7 +2,7 @@ "id": "lan-share", "name": "局域网传文件", "description": "选择电脑上的文件或文件夹开启局域网共享,同一网络的手机或电脑用浏览器打开本机地址或扫码即可下载;共享不需要密码,只支持从电脑下载,不支持从手机上传", - "version": "2.0.15", + "version": "2.0.16", "minAppVersion": "1.1.8.0", "author": "ZTools Team", "entry": "dist/index.js", diff --git a/extensions/lan-share/src/i18n.ts b/extensions/lan-share/src/i18n.ts index 9d52ec7e..b7617baf 100644 --- a/extensions/lan-share/src/i18n.ts +++ b/extensions/lan-share/src/i18n.ts @@ -13,6 +13,13 @@ const rawT = createTranslator( errStopFailed: '停止共享服务失败', errStopUnconfirmed: '客户端没有停止共享服务', msgStopped: '共享服务已停止', + errPinUpdateFailed: '更新 PIN 访问码保护失败', + errPinUpdateUnconfirmed: '客户端未确认更新 PIN 访问码设置', + msgPinEnabled: '已开启 4 位 PIN 访问码保护', + msgPinDisabled: '已关闭 PIN 访问码保护', + msgPinRefreshed: '已刷新 4 位 PIN 访问码', + msgPinPendingEnable: '将在启动共享服务时启用 4 位 PIN 访问码保护', + msgPinPendingDisable: '将在启动共享服务时关闭 PIN 访问码保护', pickFilesTitle: '选择要共享的文件', errOpenPickerFailed: '打开文件选择框失败', errPickerNoResult: '文件选择框没有返回结果', @@ -34,21 +41,25 @@ const rawT = createTranslator( msgClearedAll: '已清空共享列表(移出 {count} 个文件,文件本身没有删除)', msgClearedPartial: '已移除 {removed} 个,{failed} 个失败', // index.ts - noPasswordNote: '同一局域网内的任何设备都能打开并下载,不需要密码', + noPasswordNote: '当前未开启 PIN 保护,同一局域网内的设备均可直接打开并下载', + pinProtectedNote: '已开启 4 位 PIN 访问码保护(PIN:{pin}),扫码地址已附带访问码;若单独打开下载链接需附带 ?pin={pin}', + pinPendingNote: '已设为启动时开启 4 位 PIN 访问码保护', + oneWayOnlyNote: '仅支持电脑发手机(单向下载),不支持从手机上传或双向文本互传', firewallNote: '首次启动时 Windows 防火墙可能询问是否允许 ZTools 访问网络,需要允许,手机才能连上', keepRunningNote: '关闭插件后服务仍在运行,直到在这里停止服务或退出 ZTools', toastCopyFailed: '复制失败', qrAltText: '访问地址二维码', qrTooLongMsg: '地址太长,无法生成二维码,请复制地址后发送到手机。\n\n', detailReadFailedHeader: '### 读取共享状态失败\n\n{error}', - detailNotRunning: '### 共享服务未运行\n\n启动后,同一局域网的设备在浏览器中打开本机地址即可看到共享列表并下载文件。\n\n- {noPassword}\n- {firewall}\n- 只支持从电脑下载到其他设备,不支持从手机上传', - detailOtherAddrsHeader: '\n\n如果手机打不开,换用本机的其他地址:\n\n', - detailNoLanAddr: '\n\n没有检测到局域网地址,其他设备无法连接。', - detailRunning: '### 共享服务运行中\n\n{qr}```text\n{url}\n```\n\n- {noPassword}\n- {keepRunning}\n- {firewall}{others}{noLan}', + detailNotRunning: '### 共享服务未运行\n\n启动后,同一局域网的手机或电脑扫码或在浏览器打开本机地址即可下载已共享的文件。\n\n- {pinNote}\n- {oneWayNote}\n- {firewall}', + detailOtherAddrsHeader: '\n\n其他可用网卡地址(可在顶栏下拉框切换二维码网卡):\n\n', + detailNoLanAddr: '\n\n没有检测到局域网 IPv4 地址,其他设备无法连接。', + detailRunning: '### 手机扫码连接(实时二维码)\n\n{qr}```text\n{url}\n```\n\n- {pinNote}\n- {oneWayNote}\n- {keepRunning}\n- {firewall}{others}{noLan}', fileDetailHead: '### {name}\n\n- 路径:`{path}`\n- 大小:{size}\n\n', - fileDetailDir: '{head}这是文件夹,共享网页不能下载文件夹。', + fileDetailDir: '{head}这是文件夹,共享网页仅支持下载单个文件。', fileDetailPaused: '{head}已暂停共享,其他设备打开下载地址会被拒绝。', - fileDetailStopped: '{head}共享服务未运行,启动后才能下载。', + fileDetailStopped: '{head}共享服务未运行,启动后即可生成直链二维码供手机扫码下载。', + fileDetailPinHint: '\n\n已开启 PIN 访问码保护(PIN:`{pin}`),上方二维码与直链已自动附带 `?pin={pin}`。', toastRefreshed: '已刷新', toastNotRunning: '共享服务未运行', toastPickFailed: '选择文件失败', @@ -73,16 +84,28 @@ const rawT = createTranslator( actionPickFolder: '选择文件夹…', actionRefreshStatus: '刷新共享状态', actionClearAll: '清空共享列表', - sectionList: '列表', + sectionList: '文件与列表', + sectionSecurity: '安全与网络', actionReload: '重新读取', - serviceRunningTitle: '共享服务运行中:{url}', + serviceRunningTitle: '运行中 · {url}', + serviceRunningSub: '{nic} · {pinPart} · 已访问 {requests} 次', + pinPartOn: 'PIN {pin}', + pinPartOff: '免密码', tagRunning: '运行中', + tagPinBadge: 'PIN {pin}', panelShareService: '共享服务', actionCopyPortalUrl: '复制访问地址', toastCopiedPortalUrl: '已复制访问地址', + actionCopyPin: '复制 4 位 PIN 码', + toastCopiedPin: '已复制 PIN 码', + actionRefreshPin: '刷新 4 位 PIN 码', + actionEnablePin: '开启 4 位 PIN 保护', + actionDisablePin: '关闭 PIN 保护', actionStopService: '停止共享服务', - serviceStoppedSub: '启动后,同一局域网的设备可以打开本机地址下载列表中的文件', + serviceStoppedSub: '启动后,同一局域网设备扫码即可下载列表中的文件(电脑发手机)', + serviceStoppedSubWithPin: '启动后将启用 4 位 PIN 访问码保护,同一局域网设备扫码下载', tagStopped: '未运行', + tagPinPending: 'PIN 待启用', actionStartService: '启动共享服务', actionCopyDownloadUrl: '复制下载地址', toastCopiedDownloadUrl: '已复制下载地址', @@ -93,18 +116,47 @@ const rawT = createTranslator( tagPaused: '已暂停', tagSharing: '共享中', tagServiceStopped: '服务未启动', - summaryClearSuffix: ' · 清空列表 Ctrl+Shift+Backspace', + summaryClearSuffix: ' · 清空 Ctrl+Shift+Backspace', summaryImporting: '正在导入:已读取 {dirs} 个文件夹,找到 {files} 个文件', summaryReadFailed: '读取失败:{error}', - summaryRunning: '共享中 {url} · {count} 个文件可下载{suffix}', - summaryIdleEmpty: '共享服务未运行 · 尚未添加文件 · 可选择文件、文件夹,或直接拖入', - summaryIdleWithFiles: '共享服务未运行 · 列表中 {count} 个文件{suffix}', + summaryRunning: '共享中 {url} · {count} 个文件可下载 · {pinPart}{suffix}', + summaryIdleEmpty: '服务未运行 · 尚未添加文件 · 拖入文件或点击「选择文件」开始共享', + summaryIdleWithFiles: '服务未运行 · {count} 个待共享文件{suffix}', navTitle: '局域网传文件', - searchPlaceholder: '搜索共享的文件名或路径', + searchPlaceholder: '搜索已共享的文件名或路径...', + nicDropdownTooltip: '切换广播网卡(实时刷新二维码)', + nicDropdownSection: '广播网卡', + nicUnknown: '局域网网卡', barPickFiles: '选择文件', barPickFolder: '选择文件夹', + barStartService: '启动服务', + barStopService: '停止服务', + barPinOn: 'PIN 保护: 开', + barPinOff: 'PIN 保护: 关', secShareService: '共享服务', - secSharedFiles: '共享的文件 ({count})' + secSharedFiles: '电脑发手机 · 已共享 ({count})', + emptyFilesTitle: '尚未添加共享文件', + emptyFilesSub: '拖入文件/文件夹、粘贴截图,或点击顶栏「选择文件」开始分享', + emptyFilesTag: '空列表', + emptyFilesDetail: '### 开始局域网分享\n\n1. 点击顶栏 **选择文件** / **选择文件夹**,或直接将文件拖入窗口。\n2. 如有多个网卡(如 Wi-Fi 与 VPN 虚拟网卡),可在顶栏下拉框切换广播网卡,二维码会实时更新。\n3. 如在公共网络使用,可先点击顶栏 **PIN 保护** 开启 4 位访问码。\n\n- {oneWayNote}', + searchEmptyTitle: '没有匹配「{query}」的共享文件', + searchEmptySub: '清空搜索词可查看全部 {total} 个已共享文件', + searchEmptyDetail: '### 未找到匹配文件\n\n当前搜索词:`{query}`\n\n共享列表中共有 **{total}** 个文件,请调整或清空搜索词。', + metaStatus: '服务状态', + metaNic: '当前广播网卡', + metaPort: '监听端口', + metaPin: '访问码保护', + metaRequests: '累计访问', + metaDirection: '传输方向', + metaValueNotDetected: '未检测到局域网网卡', + metaValuePinOn: '已开启 · PIN {pin}', + metaValuePinOff: '未开启(同局域网免密下载)', + metaValuePinPending: '待启动时开启(4 位随机 PIN)', + metaValueRequests: '{count} 次请求', + metaValueDirection: '电脑 -> 手机(单向下载)', + metaFileSize: '文件大小', + metaFileState: '共享状态', + metaFilePath: '本地路径' }, 'en-US': { hostRequired: 'Requires ZTools desktop client', @@ -117,6 +169,13 @@ const rawT = createTranslator( errStopFailed: 'Failed to stop share server', errStopUnconfirmed: 'Host did not stop the share server', msgStopped: 'Share server stopped', + errPinUpdateFailed: 'Failed to update PIN protection', + errPinUpdateUnconfirmed: 'Host did not confirm PIN protection update', + msgPinEnabled: '4-digit PIN protection enabled', + msgPinDisabled: 'PIN protection disabled', + msgPinRefreshed: 'Refreshed 4-digit PIN', + msgPinPendingEnable: '4-digit PIN protection will be enabled when server starts', + msgPinPendingDisable: 'PIN protection will be disabled when server starts', pickFilesTitle: 'Select Files to Share', errOpenPickerFailed: 'Failed to open file picker', errPickerNoResult: 'File picker returned no result', @@ -124,8 +183,8 @@ const rawT = createTranslator( errNoFilesSelected: 'No files selected', errAddShareFailed: 'Failed to add files to share list', errNoFilesAdded: 'No files added: files do not exist or cannot be read', - msgSharedPartial: 'Shared {added} file(s); skipped {skipped} unreadable file(s)', - msgSharedAll: 'Shared {added} file(s)', + msgSharedPartial: 'Shared {added} [[added:file|files]]; skipped {skipped} unreadable', + msgSharedAll: 'Shared {added} [[added:file|files]]', errEmptyShareId: 'Share item ID cannot be empty', errToggleFailed: 'Failed to toggle file share status', errToggleUnconfirmed: 'Host did not update the file share status', @@ -136,31 +195,35 @@ const rawT = createTranslator( msgRemovedFile: 'Removed from share list (original file kept)', errAlreadyEmpty: 'Share list is already empty', msgClearedAll: 'Cleared share list ({count} [[count:file|files]] removed; original files kept)', - msgClearedPartial: 'Removed {removed} file(s), {failed} failed', - noPasswordNote: 'Anyone on the same LAN can open and download without a password', + msgClearedPartial: 'Removed {removed}, {failed} failed', + noPasswordNote: 'PIN protection is off; anyone on the same LAN can open and download', + pinProtectedNote: '4-digit PIN protection is active (PIN: {pin}). QR URL includes the PIN; direct links require ?pin={pin}', + pinPendingNote: '4-digit PIN protection will be enabled when the server starts', + oneWayOnlyNote: 'One-way download from PC to phone/browser only (mobile upload is not supported)', firewallNote: 'Allow ZTools through Windows Firewall on first launch so phones can connect', keepRunningNote: 'Server keeps running after closing this view until stopped here or ZTools exits', toastCopyFailed: 'Copy Failed', qrAltText: 'Portal QR Code', qrTooLongMsg: 'URL is too long for QR code; copy the address and send it to your device.\n\n', detailReadFailedHeader: '### Failed to Read Share Status\n\n{error}', - detailNotRunning: '### Share Server Not Running\n\nOnce started, devices on the same LAN can open the URL in a browser to download shared files.\n\n- {noPassword}\n- {firewall}\n- One-way download only (mobile upload is not supported)', - detailOtherAddrsHeader: '\n\nIf unreachable, try another local address:\n\n', + detailNotRunning: '### Share Server Not Running\n\nOnce started, devices on the same LAN can scan the QR code or open the URL in a browser to download shared files.\n\n- {pinNote}\n- {oneWayNote}\n- {firewall}', + detailOtherAddrsHeader: '\n\nOther available network addresses (switch interface in the top dropdown to update QR):\n\n', detailNoLanAddr: '\n\nNo LAN IPv4 address detected; other devices cannot connect.', - detailRunning: '### Share Server Running\n\n{qr}```text\n{url}\n```\n\n- {noPassword}\n- {keepRunning}\n- {firewall}{others}{noLan}', + detailRunning: '### Scan to Connect (Live QR Code)\n\n{qr}```text\n{url}\n```\n\n- {pinNote}\n- {oneWayNote}\n- {keepRunning}\n- {firewall}{others}{noLan}', fileDetailHead: '### {name}\n\n- Path: `{path}`\n- Size: {size}\n\n', fileDetailDir: '{head}This is a folder; folders cannot be downloaded from the web page.', fileDetailPaused: '{head}Sharing is paused; download requests will be rejected.', - fileDetailStopped: '{head}Share server is stopped; start the server to enable downloads.', + fileDetailStopped: '{head}Share server is stopped; start the server to generate a download QR code.', + fileDetailPinHint: '\n\nPIN protection is enabled (PIN: `{pin}`). The QR code and URL above include `?pin={pin}`.', toastRefreshed: 'Refreshed', toastNotRunning: 'Share server is stopped', toastPickFailed: 'Failed to Select Files', toastNoFilesFound: 'No shareable files found', - noteIgnoredHidden: 'ignored {count} hidden or system file(s)', + noteIgnoredHidden: 'ignored {count} hidden or system [[count:file|files]]', noteTruncated: 'too many files; imported first {max}', - noteFailedDirs: '{count} subfolder(s) unreadable', + noteFailedDirs: '{count} [[count:subfolder|subfolders]] unreadable', notePartialBatchFail: 'some batches failed{error}', - noteDuplicateNames: '{count} file(s) share identical names; distinguish by size on the web page', + noteDuplicateNames: '{count} [[count:file shares|files share]] identical names; distinguish by size on the web page', toastShareFailed: 'Failed to Share Files', semiSep: '; ', toastImportFailed: 'Import Failed', @@ -176,16 +239,28 @@ const rawT = createTranslator( actionPickFolder: 'Select Folder…', actionRefreshStatus: 'Refresh Status', actionClearAll: 'Clear Share List', - sectionList: 'List', + sectionList: 'Files & List', + sectionSecurity: 'Security & Network', actionReload: 'Reload', - serviceRunningTitle: 'Share Server Running: {url}', + serviceRunningTitle: 'Running · {url}', + serviceRunningSub: '{nic} · {pinPart} · {requests} [[requests:request|requests]]', + pinPartOn: 'PIN {pin}', + pinPartOff: 'No PIN', tagRunning: 'Running', + tagPinBadge: 'PIN {pin}', panelShareService: 'Share Service', actionCopyPortalUrl: 'Copy Portal URL', toastCopiedPortalUrl: 'Copied Portal URL', + actionCopyPin: 'Copy 4-Digit PIN', + toastCopiedPin: 'Copied PIN', + actionRefreshPin: 'Refresh 4-Digit PIN', + actionEnablePin: 'Enable 4-Digit PIN', + actionDisablePin: 'Disable PIN Protection', actionStopService: 'Stop Share Server', - serviceStoppedSub: 'Start server so LAN devices can browse and download shared files', + serviceStoppedSub: 'Start server so LAN devices can scan and download shared files (PC to phone)', + serviceStoppedSubWithPin: '4-digit PIN protection will be enabled once server starts', tagStopped: 'Stopped', + tagPinPending: 'PIN Pending', actionStartService: 'Start Share Server', actionCopyDownloadUrl: 'Copy Download URL', toastCopiedDownloadUrl: 'Copied Download URL', @@ -199,15 +274,44 @@ const rawT = createTranslator( summaryClearSuffix: ' · Clear Ctrl+Shift+Backspace', summaryImporting: 'Importing: scanned {dirs} [[dirs:folder|folders]], found {files} [[files:file|files]]', summaryReadFailed: 'Read failed: {error}', - summaryRunning: 'Sharing {url} · {count} downloadable{suffix}', - summaryIdleEmpty: 'Server stopped · No files yet · Select files, folder, or drop here', - summaryIdleWithFiles: 'Server stopped · {count} file(s) in list{suffix}', + summaryRunning: 'Sharing {url} · {count} downloadable · {pinPart}{suffix}', + summaryIdleEmpty: 'Server stopped · No files yet · Drop files or click "Select Files" to share', + summaryIdleWithFiles: 'Server stopped · {count} [[count:file|files]] queued{suffix}', navTitle: 'LAN File Share', searchPlaceholder: 'Search shared file name or path...', + nicDropdownTooltip: 'Switch broadcast interface (live QR update)', + nicDropdownSection: 'Network Interface', + nicUnknown: 'LAN Interface', barPickFiles: 'Select Files', barPickFolder: 'Select Folder', + barStartService: 'Start Server', + barStopService: 'Stop Server', + barPinOn: 'PIN: On', + barPinOff: 'PIN: Off', secShareService: 'Share Service', - secSharedFiles: 'Shared Files ({count})' + secSharedFiles: 'PC to Phone · Shared ({count})', + emptyFilesTitle: 'No Shared Files Yet', + emptyFilesSub: 'Drop files/folders, paste a screenshot, or click "Select Files" above', + emptyFilesTag: 'Empty', + emptyFilesDetail: '### Get Started with LAN Share\n\n1. Click **Select Files** or **Select Folder** in the bar above, or drop files directly into this window.\n2. If multiple network interfaces exist (e.g. Wi-Fi and VPN), switch the broadcast interface from the top dropdown to refresh the QR code.\n3. On shared networks, toggle **PIN** in the top bar for 4-digit PIN protection.\n\n- {oneWayNote}', + searchEmptyTitle: 'No shared files matching "{query}"', + searchEmptySub: 'Clear the search query to view all {total} shared [[total:file|files]]', + searchEmptyDetail: '### No Matching Files\n\nQuery: `{query}`\n\nThere are **{total}** [[total:file|files]] in the share list. Adjust or clear the search query.', + metaStatus: 'Server Status', + metaNic: 'Broadcast NIC', + metaPort: 'Listening Port', + metaPin: 'PIN Protection', + metaRequests: 'Client Requests', + metaDirection: 'Transfer Mode', + metaValueNotDetected: 'No LAN interface detected', + metaValuePinOn: 'Enabled · PIN {pin}', + metaValuePinOff: 'Disabled (Open on LAN)', + metaValuePinPending: 'Pending on Start (4-digit PIN)', + metaValueRequests: '{count} [[count:request|requests]]', + metaValueDirection: 'PC -> Phone (One-Way Download)', + metaFileSize: 'File Size', + metaFileState: 'Share State', + metaFilePath: 'Local Path' } }, { defaultLocale: 'en-US' } diff --git a/extensions/lan-share/src/index.ts b/extensions/lan-share/src/index.ts index 26dbd956..21d5023f 100644 --- a/extensions/lan-share/src/index.ts +++ b/extensions/lan-share/src/index.ts @@ -16,15 +16,23 @@ import { type LanShareStatus, type SharedFileItem, type LanActionResult, + type LanInterface, LAN_SHARE_IMPORT_RULES, LAN_SHARE_MAX_FILES, addFilesToShareBatched, + buildDownloadUrlForIp, + buildPortalUrlForIp, clearAllSharedFiles, createLanShareImportTransport, formatBytes, + formatInterfaceLabel, fetchLanShareStatus, + generateRandomPin, + resolveActiveInterface, + resolveActiveLanIp, startLanShare, stopLanShare, + updateLanSharePin, setFileShared, removeSharedFile, generateQrCodeSvgDataUri, @@ -76,20 +84,35 @@ function qrMarkdown(url: string): string { return qr ? `![${t('qrAltText')}](${qr})\n\n` : t('qrTooLongMsg') } -function serviceDetail(status: LanShareStatus): string { +function serviceDetailMarkdown( + status: LanShareStatus, + activePortalUrl: string, + activeLanIp: string, + pendingRequirePin: boolean +): string { if (!status.ok) return t('detailReadFailedHeader', { error: status.error || '' }) if (!status.running) { - return t('detailNotRunning', { noPassword: t('noPasswordNote'), firewall: t('firewallNote') }) + const pinNote = pendingRequirePin ? t('pinPendingNote') : t('noPasswordNote') + return t('detailNotRunning', { + pinNote, + oneWayNote: t('oneWayOnlyNote'), + firewall: t('firewallNote') + }) } - const others = status.interfaces.filter((i) => i.address !== status.lanIp) + const pinActive = status.requirePin && Boolean(status.pin) + const others = status.interfaces.filter((i) => i.address !== activeLanIp) const otherLines = others.length - ? `${t('detailOtherAddrsHeader')}${others.map((i) => `- ${i.name}: \`http://${i.address}:${status.port}\``).join('\n')}` + ? `${t('detailOtherAddrsHeader')}${others + .map((i) => `- ${i.name || t('nicUnknown')}: \`${buildPortalUrlForIp(i.address, status.port, { pin: status.pin, requirePin: status.requirePin })}\``) + .join('\n')}` : '' const noLan = status.interfaces.length === 0 ? t('detailNoLanAddr') : '' + const pinNote = pinActive ? t('pinProtectedNote', { pin: status.pin }) : t('noPasswordNote') return t('detailRunning', { - qr: qrMarkdown(status.portalUrl), - url: status.portalUrl, - noPassword: t('noPasswordNote'), + qr: qrMarkdown(activePortalUrl), + url: activePortalUrl, + pinNote, + oneWayNote: t('oneWayOnlyNote'), keepRunning: t('keepRunningNote'), firewall: t('firewallNote'), others: otherLines, @@ -97,12 +120,85 @@ function serviceDetail(status: LanShareStatus): string { }) } -function fileDetail(file: SharedFileItem, status: LanShareStatus): string { +function serviceDetailMetadata( + status: LanShareStatus, + activeInterface: LanInterface | null, + pendingRequirePin: boolean +) { + const nicText = activeInterface + ? formatInterfaceLabel(activeInterface) + : t('metaValueNotDetected') + const pinText = status.running + ? status.requirePin && status.pin + ? t('metaValuePinOn', { pin: status.pin }) + : t('metaValuePinOff') + : pendingRequirePin + ? t('metaValuePinPending') + : t('metaValuePinOff') + + const children = [ + List.Item.Detail.Metadata.Label({ + title: t('metaStatus'), + text: !status.ok ? t('errReadStatusFailed') : status.running ? t('tagRunning') : t('tagStopped') + }), + List.Item.Detail.Metadata.Label({ + title: t('metaNic'), + text: nicText + }), + ...(status.running && status.port > 0 + ? [ + List.Item.Detail.Metadata.Label({ + title: t('metaPort'), + text: String(status.port) + }) + ] + : []), + List.Item.Detail.Metadata.Label({ + title: t('metaPin'), + text: pinText + }), + ...(status.running || status.totalClientRequests > 0 + ? [ + List.Item.Detail.Metadata.Label({ + title: t('metaRequests'), + text: t('metaValueRequests', { count: status.totalClientRequests }) + }) + ] + : []), + List.Item.Detail.Metadata.Label({ + title: t('metaDirection'), + text: t('metaValueDirection') + }) + ] + + return List.Item.Detail.Metadata({ children }) +} + +function fileDetailMarkdown(file: SharedFileItem, status: LanShareStatus, activeDownloadUrl: string): string { const head = t('fileDetailHead', { name: file.name, path: file.path, size: formatBytes(file.sizeBytes) }) if (file.isDirectory) return t('fileDetailDir', { head }) if (!file.shared) return t('fileDetailPaused', { head }) - if (!status.running) return t('fileDetailStopped', { head }) - return `${head}${qrMarkdown(file.downloadUrl)}\`\`\`text\n${file.downloadUrl}\n\`\`\`` + if (!status.running || !activeDownloadUrl) return t('fileDetailStopped', { head }) + const pinHint = status.requirePin && status.pin ? t('fileDetailPinHint', { pin: status.pin }) : '' + return `${head}${qrMarkdown(activeDownloadUrl)}\`\`\`text\n${activeDownloadUrl}\n\`\`\`${pinHint}` +} + +function fileDetailMetadata(file: SharedFileItem, status: LanShareStatus) { + const stateText = file.isDirectory + ? t('tagDirectory') + : !file.shared + ? t('tagPaused') + : status.running + ? t('tagSharing') + : t('tagServiceStopped') + + return List.Item.Detail.Metadata({ + children: [ + List.Item.Detail.Metadata.Label({ title: t('metaFileState'), text: stateText }), + List.Item.Detail.Metadata.Label({ title: t('metaFileSize'), text: formatBytes(file.sizeBytes) }), + List.Item.Detail.Metadata.Label({ title: t('metaFilePath'), text: file.path }) + ] + }) } const EMPTY_STATUS: LanShareStatus = { @@ -111,6 +207,9 @@ const EMPTY_STATUS: LanShareStatus = { lanIp: '', port: 0, portalUrl: '', + pin: '', + requirePin: false, + totalClientRequests: 0, interfaces: [], files: [] } @@ -120,6 +219,8 @@ export function LanShareCommand() { const transport = createLanShareImportTransport() const [searchText, setSearchText] = useState('') const [status, setStatus] = useState(EMPTY_STATUS) + const [selectedIp, setSelectedIp] = useState('') + const [pendingRequirePin, setPendingRequirePin] = useState(false) const [isLoading, setIsLoading] = useState(true) const [isImporting, setIsImporting] = useState(false) const [importProgress, setImportProgress] = useState<{ visitedDirs: number; matchedFiles: number } | null>(null) @@ -130,6 +231,15 @@ export function LanShareCommand() { const importAbortRef = useRef(null) const statusRef = useRef(EMPTY_STATUS) statusRef.current = status + const pendingRequirePinRef = useRef(false) + pendingRequirePinRef.current = pendingRequirePin + + function syncSelectedInterface(next: LanShareStatus) { + setSelectedIp((prev) => resolveActiveLanIp(next, prev)) + if (next.ok && next.running) { + setPendingRequirePin(next.requirePin) + } + } async function refresh(showNotice = false) { setIsLoading(true) @@ -137,10 +247,15 @@ export function LanShareCommand() { const next = await fetchLanShareStatus() if (!mountedRef.current) return setStatus(next) + syncSelectedInterface(next) if (showNotice) { + const activeIp = resolveActiveLanIp(next, selectedIp) + const noticeUrl = next.running + ? buildPortalUrlForIp(activeIp, next.port, { pin: next.pin, requirePin: next.requirePin }) || next.portalUrl + : '' await showToast( next.ok - ? { style: Toast.Style.Success, title: t('toastRefreshed'), message: next.running ? next.portalUrl : t('toastNotRunning') } + ? { style: Toast.Style.Success, title: t('toastRefreshed'), message: next.running ? noticeUrl : t('toastNotRunning') } : { style: Toast.Style.Failure, title: t('errReadStatusFailed'), message: next.error } ) } @@ -149,8 +264,12 @@ export function LanShareCommand() { } } - /** 执行一个改变共享状态的操作:结果以客户端返回为准,之后重新读取完整状态 */ + /** 执行一个改变共享状态的操作:结果以客户端返回为准,先即时落态再重新读取完整状态 */ async function applyResult(res: LanActionResult, failureTitle: string, successMessage?: string) { + if (res.status?.ok && mountedRef.current) { + setStatus(res.status) + syncSelectedInterface(res.status) + } if (res.ok) { await showToast({ style: Toast.Style.Success, title: res.message, message: successMessage }) } else { @@ -180,6 +299,15 @@ export function LanShareCommand() { const batch = await addFilesToShareBatched(result.files.map((f) => f.path)) if (!mountedRef.current) return + // 若用户在未启动前已勾选 PIN 保护,且添加文件触发了宿主自动启动,补发 PIN 保护开启 + let latestStatus = batch.status + if (batch.addedCount > 0 && pendingRequirePinRef.current && latestStatus?.running && !latestStatus.requirePin) { + const pinRes = await updateLanSharePin(true, latestStatus.pin || generateRandomPin()) + if (pinRes.ok && pinRes.status?.ok) { + latestStatus = pinRes.status + } + } + const extraNotes: string[] = [] if (result.ignored > 0) extraNotes.push(t('noteIgnoredHidden', { count: result.ignored })) if (result.truncated) extraNotes.push(t('noteTruncated', { max: LAN_SHARE_MAX_FILES })) @@ -206,8 +334,16 @@ export function LanShareCommand() { batch.skipped.length > 0 ? t('msgSharedPartial', { added: batch.addedCount, skipped: batch.skipped.length }) : t('msgSharedAll', { added: batch.addedCount }) - const portal = batch.status?.portalUrl - const portalNote = portal ? `${portal} · ${t('noPasswordNote')}` : extraNotes.length === 0 ? undefined : t('noPasswordNote') + const portal = latestStatus?.running + ? buildPortalUrlForIp(resolveActiveLanIp(latestStatus, selectedIp), latestStatus.port, { + pin: latestStatus.pin, + requirePin: latestStatus.requirePin + }) || latestStatus.portalUrl + : '' + const securityNote = latestStatus?.requirePin && latestStatus.pin + ? t('pinPartOn', { pin: latestStatus.pin }) + : t('noPasswordNote') + const portalNote = portal ? `${portal} · ${securityNote}` : extraNotes.length === 0 ? undefined : securityNote const message = [...extraNotes, portalNote].filter(Boolean).join(t('semiSep')) || undefined await showToast({ style: batch.failedBatches > 0 ? Toast.Style.Failure : Toast.Style.Success, @@ -313,8 +449,10 @@ export function LanShareCommand() { return () => { mountedRef.current = false + busyRef.current = false importSeqRef.current += 1 importAbortRef.current?.abort() + importAbortRef.current = null cleanupDrop?.() } }, []) @@ -326,12 +464,50 @@ export function LanShareCommand() { }) async function handleStart() { - const res = await startLanShare() - await applyResult(res, t('errStartFailed'), res.status?.portalUrl) + const startOpts = pendingRequirePinRef.current + ? { requirePin: true, pin: statusRef.current.pin || generateRandomPin() } + : { requirePin: false } + const res = await startLanShare(undefined, startOpts) + const nextUrl = res.status?.running + ? buildPortalUrlForIp(resolveActiveLanIp(res.status, selectedIp), res.status.port, { + pin: res.status.pin, + requirePin: res.status.requirePin + }) || res.status.portalUrl + : undefined + await applyResult(res, t('errStartFailed'), nextUrl) } async function handleStop() { - await applyResult(await stopLanShare(), t('errStopFailed')) + const res = await stopLanShare() + await applyResult(res, t('errStopFailed')) + } + + async function handleTogglePin() { + const cur = statusRef.current + if (!cur.running) { + const next = !pendingRequirePinRef.current + setPendingRequirePin(next) + await showToast({ + style: Toast.Style.Success, + title: next ? t('msgPinPendingEnable') : t('msgPinPendingDisable') + }) + return + } + const nextRequirePin = !cur.requirePin + const nextPin = nextRequirePin ? cur.pin || generateRandomPin() : undefined + const res = await updateLanSharePin(nextRequirePin, nextPin) + const detailMsg = res.ok && nextRequirePin && res.status?.pin + ? t('pinPartOn', { pin: res.status.pin }) + : undefined + await applyResult(res, t('errPinUpdateFailed'), detailMsg) + } + + async function handleRefreshPin() { + const cur = statusRef.current + if (!cur.running) return + const nextPin = generateRandomPin() + const res = await updateLanSharePin(true, nextPin) + await applyResult(res, t('errPinUpdateFailed'), res.ok && res.status?.pin ? t('pinPartOn', { pin: res.status.pin }) : undefined) } async function handleToggle(file: SharedFileItem) { @@ -365,8 +541,21 @@ export function LanShareCommand() { } } + const activeLanIp = resolveActiveLanIp(status, selectedIp) + const activeInterface = resolveActiveInterface(status, selectedIp) + const pinOptions = { pin: status.pin, requirePin: status.requirePin } + const activePortalUrl = status.running + ? buildPortalUrlForIp(activeLanIp, status.port, pinOptions) + : '' + const activeBaseUrl = status.running && activeLanIp && status.port > 0 + ? `http://${activeLanIp}:${status.port}` + : '' + const effectivePinEnabled = status.running ? status.requirePin : pendingRequirePin + const filtered = filterSharedFiles(status.files, searchText) - const downloadable = status.files.filter((f) => f.downloadUrl).length + const downloadable = status.running + ? status.files.filter((f) => f.shared && !f.isDirectory && Boolean(activePortalUrl)).length + : 0 const pickFilesAction = () => Action({ @@ -400,6 +589,21 @@ export function LanShareCommand() { onAction: () => handleClearAll() }) + const togglePinAction = () => + Action({ + title: effectivePinEnabled ? t('actionDisablePin') : t('actionEnablePin'), + icon: effectivePinEnabled ? Icon.LockUnlocked : Icon.Lock, + onAction: () => handleTogglePin() + }) + + const refreshPinAction = () => + Action({ + title: t('actionRefreshPin'), + icon: Icon.Key, + shortcut: { modifiers: ['ctrl'], key: 'p' }, + onAction: () => handleRefreshPin() + }) + const listSection = (includeRefresh = true) => ActionPanel.Section({ title: t('sectionList'), @@ -411,13 +615,45 @@ export function LanShareCommand() { ] }) + const securitySection = () => + ActionPanel.Section({ + title: t('sectionSecurity'), + children: [ + togglePinAction(), + ...(status.running && status.requirePin + ? [ + refreshPinAction(), + ...(status.pin + ? [ + Action({ + title: t('actionCopyPin'), + icon: Icon.Clipboard, + onAction: () => copyWithToast(status.pin, t('toastCopiedPin'), status.pin) + }) + ] + : []) + ] + : []) + ] + }) + + const activeNicDisplay = activeInterface + ? activeInterface.name || activeInterface.address + : t('nicUnknown') + const pinSummaryPart = status.requirePin && status.pin + ? t('pinPartOn', { pin: status.pin }) + : t('pinPartOff') + const serviceItem = !status.ok ? List.Item({ id: 'lan-service', title: t('errReadStatusFailed'), subtitle: status.error, icon: Icon.ExclamationMark, - detail: List.Item.Detail({ markdown: serviceDetail(status) }), + detail: List.Item.Detail({ + markdown: serviceDetailMarkdown(status, '', '', pendingRequirePin), + metadata: serviceDetailMetadata(status, activeInterface, pendingRequirePin) + }), actions: ActionPanel({ title: t('errReadStatusFailed'), children: [ @@ -427,88 +663,165 @@ export function LanShareCommand() { }) }) : status.running - ? List.Item({ - id: 'lan-service', - title: t('serviceRunningTitle', { url: status.portalUrl }), - subtitle: t('noPasswordNote'), - icon: Icon.Wifi, - accessories: [{ tag: { value: t('tagRunning') } }], - detail: List.Item.Detail({ markdown: serviceDetail(status) }), - actions: ActionPanel({ - title: t('panelShareService'), - children: [ - Action({ - title: t('actionCopyPortalUrl'), - icon: Icon.Clipboard, - onAction: () => copyWithToast(status.portalUrl, t('toastCopiedPortalUrl'), status.portalUrl) - }), - Action({ - title: t('actionStopService'), - icon: Icon.Stop, - shortcut: { modifiers: ['ctrl'], key: 'return' }, - onAction: () => handleStop() - }), - refreshAction(), - listSection(false) - ] + ? List.Item({ + id: 'lan-service', + title: t('serviceRunningTitle', { url: activeBaseUrl || activePortalUrl }), + subtitle: t('serviceRunningSub', { + nic: activeNicDisplay, + pinPart: pinSummaryPart, + requests: status.totalClientRequests + }), + icon: Icon.Wifi, + accessories: [ + ...(status.requirePin && status.pin ? [{ tag: { value: t('tagPinBadge', { pin: status.pin }) } }] : []), + { tag: { value: t('tagRunning') } } + ], + detail: List.Item.Detail({ + markdown: serviceDetailMarkdown(status, activePortalUrl, activeLanIp, pendingRequirePin), + metadata: serviceDetailMetadata(status, activeInterface, pendingRequirePin) + }), + actions: ActionPanel({ + title: t('panelShareService'), + children: [ + ...(activePortalUrl + ? [ + Action({ + title: t('actionCopyPortalUrl'), + icon: Icon.Clipboard, + onAction: () => copyWithToast(activePortalUrl, t('toastCopiedPortalUrl'), activePortalUrl) + }) + ] + : []), + Action({ + title: t('actionStopService'), + icon: Icon.Stop, + shortcut: { modifiers: ['ctrl'], key: 'return' }, + onAction: () => handleStop() + }), + refreshAction(), + securitySection(), + listSection(false) + ] + }) }) - }) - : List.Item({ - id: 'lan-service', - title: t('toastNotRunning'), - subtitle: t('serviceStoppedSub'), - icon: Icon.Wifi, - accessories: [{ tag: { value: t('tagStopped') } }], - detail: List.Item.Detail({ markdown: serviceDetail(status) }), - actions: ActionPanel({ - title: t('panelShareService'), - children: [ - Action({ title: t('actionStartService'), icon: Icon.Play, onAction: () => handleStart() }), - refreshAction(), - listSection(false) - ] + : List.Item({ + id: 'lan-service', + title: t('toastNotRunning'), + subtitle: pendingRequirePin ? t('serviceStoppedSubWithPin') : t('serviceStoppedSub'), + icon: Icon.Wifi, + accessories: [ + ...(pendingRequirePin ? [{ tag: { value: t('tagPinPending') } }] : []), + { tag: { value: t('tagStopped') } } + ], + detail: List.Item.Detail({ + markdown: serviceDetailMarkdown(status, '', activeLanIp, pendingRequirePin), + metadata: serviceDetailMetadata(status, activeInterface, pendingRequirePin) + }), + actions: ActionPanel({ + title: t('panelShareService'), + children: [ + Action({ title: t('actionStartService'), icon: Icon.Play, onAction: () => handleStart() }), + refreshAction(), + securitySection(), + listSection(false) + ] + }) }) - }) - const fileItems = filtered.map((file) => { - const actions: Array | ReturnType> = [] - if (file.downloadUrl) { - actions.push( - Action({ - title: t('actionCopyDownloadUrl'), - icon: Icon.Clipboard, - onAction: () => copyWithToast(file.downloadUrl, t('toastCopiedDownloadUrl'), file.downloadUrl) - }) - ) - } - actions.push( - Action({ - title: file.shared ? t('actionPauseFile') : t('actionResumeFile'), - icon: file.shared ? Icon.Pause : Icon.Play, - // 仅当存在「复制下载地址」作为首项时由第 2 顺位自动承接 Ctrl+Enter,避免无下载地址时首项错位 - onAction: () => handleToggle(file) - }), - Action({ - title: t('actionRemoveFile'), - icon: Icon.XMarkCircle, - shortcut: { modifiers: ['ctrl'], key: 'backspace' }, - onAction: () => handleRemove(file) - }), - listSection(true) - ) - return List.Item({ - id: `lan-file-${file.id}`, - title: file.name, - subtitle: file.path, - icon: Icon.Document, - accessories: [ - { tag: { value: file.isDirectory ? t('tagDirectory') : !file.shared ? t('tagPaused') : status.running ? t('tagSharing') : t('tagServiceStopped') } }, - { text: formatBytes(file.sizeBytes) } - ], - detail: List.Item.Detail({ markdown: fileDetail(file, status) }), - actions: ActionPanel({ title: file.name, children: actions }) - }) - }) + const fileItems = + status.files.length === 0 + ? [ + List.Item({ + id: 'lan-empty-files', + title: t('emptyFilesTitle'), + subtitle: t('emptyFilesSub'), + icon: Icon.Folder, + accessories: [{ tag: { value: t('emptyFilesTag') } }], + detail: List.Item.Detail({ + markdown: t('emptyFilesDetail', { oneWayNote: t('oneWayOnlyNote') }) + }), + actions: ActionPanel({ + title: t('sectionList'), + children: [ + pickFilesAction(), + pickFolderAction(), + refreshAction() + ] + }) + }) + ] + : filtered.length === 0 + ? [ + List.Item({ + id: 'lan-search-empty', + title: t('searchEmptyTitle', { query: searchText.trim() }), + subtitle: t('searchEmptySub', { total: status.files.length }), + icon: Icon.MagnifyingGlass, + detail: List.Item.Detail({ + markdown: t('searchEmptyDetail', { query: searchText.trim(), total: status.files.length }) + }), + actions: ActionPanel({ + title: t('sectionList'), + children: [pickFilesAction(), pickFolderAction(), refreshAction()] + }) + }) + ] + : filtered.map((file) => { + const activeDownloadUrl = + status.running && file.shared && !file.isDirectory && activeLanIp && status.port > 0 + ? buildDownloadUrlForIp(activeLanIp, status.port, file.id, file.name, pinOptions) + : '' + const actions: Array | ReturnType> = [] + if (activeDownloadUrl) { + actions.push( + Action({ + title: t('actionCopyDownloadUrl'), + icon: Icon.Clipboard, + onAction: () => copyWithToast(activeDownloadUrl, t('toastCopiedDownloadUrl'), activeDownloadUrl) + }) + ) + } + actions.push( + Action({ + title: file.shared ? t('actionPauseFile') : t('actionResumeFile'), + icon: file.shared ? Icon.Pause : Icon.Play, + // 仅当存在「复制下载地址」作为首项时由第 2 顺位自动承接 Ctrl+Enter,避免无下载地址时首项错位 + onAction: () => handleToggle(file) + }), + Action({ + title: t('actionRemoveFile'), + icon: Icon.XMarkCircle, + shortcut: { modifiers: ['ctrl'], key: 'backspace' }, + onAction: () => handleRemove(file) + }), + listSection(true) + ) + return List.Item({ + id: `lan-file-${file.id}`, + title: file.name, + subtitle: file.path, + icon: file.isDirectory ? Icon.Folder : Icon.Document, + accessories: [ + { + tag: { + value: file.isDirectory + ? t('tagDirectory') + : !file.shared + ? t('tagPaused') + : status.running + ? t('tagSharing') + : t('tagServiceStopped') + } + }, + { text: formatBytes(file.sizeBytes) } + ], + detail: List.Item.Detail({ + markdown: fileDetailMarkdown(file, status, activeDownloadUrl), + metadata: fileDetailMetadata(file, status) + }), + actions: ActionPanel({ title: file.name, children: actions }) + }) + }) const clearSuffix = status.files.length > 0 ? t('summaryClearSuffix') : '' const summaryText = isImporting @@ -516,16 +829,43 @@ export function LanShareCommand() { : !status.ok ? t('summaryReadFailed', { error: status.error || '' }) : status.running - ? t('summaryRunning', { url: status.portalUrl, count: downloadable, suffix: clearSuffix }) + ? t('summaryRunning', { + url: activeBaseUrl || activePortalUrl, + count: downloadable, + pinPart: pinSummaryPart, + suffix: clearSuffix + }) : status.files.length === 0 ? t('summaryIdleEmpty') : t('summaryIdleWithFiles', { count: status.files.length, suffix: clearSuffix }) + const searchBarAccessory = + status.interfaces.length > 1 + ? List.Dropdown({ + tooltip: t('nicDropdownTooltip'), + value: activeLanIp, + onChange: (nextIp: string) => setSelectedIp(nextIp), + children: [ + List.Dropdown.Section({ + title: t('nicDropdownSection'), + children: status.interfaces.map((iface) => + List.Dropdown.Item({ + title: formatInterfaceLabel(iface), + value: iface.address, + icon: Icon.Globe + }) + ) + }) + ] + }) + : undefined + return List({ ...fileInputProps, navigationTitle: t('navTitle'), searchBarPlaceholder: t('searchPlaceholder'), onSearchTextChange: setSearchText, + searchBarAccessory, isShowingDetail: true, isLoading: isLoading || isImporting, actions: ActionPanel({ @@ -533,6 +873,7 @@ export function LanShareCommand() { pickFilesAction(), pickFolderAction(), refreshAction(), + securitySection(), ...(status.files.length > 0 ? [clearAllAction()] : []) ] }), @@ -552,12 +893,30 @@ export function LanShareCommand() { title: t('barPickFolder'), style: 'secondary', onAction: handleAddFolder + }, + { + id: 'toggle-service', + label: status.running ? t('barStopService') : t('barStartService'), + title: status.running ? t('actionStopService') : t('actionStartService'), + style: status.running ? 'destructive' : 'primary', + onAction: () => { + void (status.running ? handleStop() : handleStart()) + } + }, + { + id: 'toggle-pin', + label: effectivePinEnabled ? t('barPinOn') : t('barPinOff'), + title: effectivePinEnabled ? t('actionDisablePin') : t('actionEnablePin'), + style: 'secondary', + onAction: () => { + void handleTogglePin() + } } ] }, children: [ List.Section({ title: t('secShareService'), children: [serviceItem] }), - List.Section({ title: t('secSharedFiles', { count: filtered.length }), children: fileItems }) + List.Section({ title: t('secSharedFiles', { count: status.files.length }), children: fileItems }) ] }) } diff --git a/extensions/lan-share/src/logic.ts b/extensions/lan-share/src/logic.ts index c70cb9cd..23cb1004 100644 --- a/extensions/lan-share/src/logic.ts +++ b/extensions/lan-share/src/logic.ts @@ -1,8 +1,8 @@ -type DynamicBridge = ReturnType; +type DynamicBridge = ReturnType /** * 局域网传文件 * 共享服务由客户端提供:启动后在本机所有网卡上监听 HTTP,同一局域网的设备打开本机地址即可下载共享列表里的文件。 - * 插件负责选择要共享的文件、启动 / 停止服务、暂停或移除单个文件,并生成访问地址的二维码。 + * 插件负责选择要共享的文件、启动 / 停止服务、切换广播网卡、开关/刷新 4 位 PIN 访问码、暂停或移除单个文件,并生成实时二维码。 * 所有状态以客户端返回为准,失败如实报错。 */ @@ -51,8 +51,14 @@ export interface LanShareStatus { running: boolean lanIp: string port: number - /** 服务运行时的访问地址;未运行时为空 */ + /** 服务运行时的主网卡访问地址;未运行时为空 */ portalUrl: string + /** 宿主当前 4 位 PIN 访问码(无时为空) */ + pin: string + /** 宿主是否开启 PIN 访问码校验 */ + requirePin: boolean + /** 累计客户端访问请求数(由宿主真实统计) */ + totalClientRequests: number /** 本机非回环 IPv4 地址;为空表示没有可用的局域网地址 */ interfaces: LanInterface[] files: SharedFileItem[] @@ -64,18 +70,112 @@ export interface LanActionResult { status?: LanShareStatus } +export interface LanStartOptions { + requirePin?: boolean + pin?: string +} + function hostAvailable(hostOverride?: DynamicBridge): boolean { return Boolean(hostOverride) || isRealElectronHost(hostOverride) } function failedStatus(error: string): LanShareStatus { - return { ok: false, error, running: false, lanIp: '', port: 0, portalUrl: '', interfaces: [], files: [] } + return { + ok: false, + error, + running: false, + lanIp: '', + port: 0, + portalUrl: '', + pin: '', + requirePin: false, + totalClientRequests: 0, + interfaces: [], + files: [] + } } export function buildDownloadUrl(portalUrl: string, id: string, name: string): string { return `${portalUrl}/download/${encodeURIComponent(id)}/${encodeURIComponent(name)}` } +/** + * 解析当前生效的广播网卡 IP:优先采用用户已选且仍在网卡列表中的地址,否则回退到宿主主网卡或首个可用网卡 + */ +export function resolveActiveLanIp(status: LanShareStatus, selectedIp?: string): string { + const candidate = typeof selectedIp === 'string' ? selectedIp.trim() : '' + if (candidate && status.interfaces.some((iface) => iface.address === candidate)) { + return candidate + } + if (status.lanIp && status.interfaces.some((iface) => iface.address === status.lanIp)) { + return status.lanIp + } + if (status.interfaces.length > 0) { + return status.interfaces[0].address + } + return status.lanIp || '' +} + +export function resolveActiveInterface(status: LanShareStatus, selectedIp?: string): LanInterface | null { + const activeIp = resolveActiveLanIp(status, selectedIp) + if (!activeIp) return null + return status.interfaces.find((iface) => iface.address === activeIp) ?? { name: '', address: activeIp } +} + +/** + * 根据选定网卡 IP、端口与可选 PIN 构建访问地址(不含路径后缀或附带 /?pin=xxxx) + */ +export function buildPortalUrlForIp( + ip: string, + port: number, + options?: { pin?: string; requirePin?: boolean } +): string { + const cleanIp = typeof ip === 'string' ? ip.trim() : '' + if (!cleanIp || !Number.isInteger(port) || port <= 0) return '' + const base = `http://${cleanIp}:${port}` + const pin = typeof options?.pin === 'string' ? options.pin.trim() : '' + if (options?.requirePin && pin) { + return `${base}/?pin=${encodeURIComponent(pin)}` + } + return base +} + +/** + * 根据选定网卡 IP、端口与可选 PIN 构建单文件直链下载地址 + */ +export function buildDownloadUrlForIp( + ip: string, + port: number, + id: string, + name: string, + options?: { pin?: string; requirePin?: boolean } +): string { + const cleanIp = typeof ip === 'string' ? ip.trim() : '' + if (!cleanIp || !Number.isInteger(port) || port <= 0) return '' + const base = buildDownloadUrl(`http://${cleanIp}:${port}`, id, name) + const pin = typeof options?.pin === 'string' ? options.pin.trim() : '' + if (options?.requirePin && pin) { + return `${base}?pin=${encodeURIComponent(pin)}` + } + return base +} + +/** + * 生成 4 位随机数字 PIN 码(1000-9999) + */ +export function generateRandomPin(): string { + if (typeof globalThis.crypto?.getRandomValues === 'function') { + const buf = new Uint32Array(1) + globalThis.crypto.getRandomValues(buf) + return String(1000 + (buf[0] % 9000)) + } + return String(1000 + Math.floor(Math.random() * 9000)) +} + +export function formatInterfaceLabel(iface: LanInterface): string { + return iface.name ? `${iface.name} · ${iface.address}` : iface.address +} + /** * 把客户端返回的共享状态整理成界面数据;字段缺失时留空,不填默认值 */ @@ -86,6 +186,10 @@ export function parseLanShareStatus(data: DynamicBridge): LanShareStatus { const lanIp = String(data.lanIp || data.primaryIp || '') const port = Number(data.port) const portalUrl = running && lanIp && Number.isInteger(port) && port > 0 ? `http://${lanIp}:${port}` : '' + const pin = typeof data.pin === 'string' ? data.pin.trim() : '' + const requirePin = data.requirePin === true + const rawRequests = Number(data.totalClientRequests) + const totalClientRequests = Number.isFinite(rawRequests) && rawRequests > 0 ? Math.floor(rawRequests) : 0 const interfaces: LanInterface[] = Array.isArray(data.interfaces) ? data.interfaces .filter((i: DynamicBridge) => i && i.internal !== true && typeof i.address === 'string' && i.address) @@ -110,7 +214,18 @@ export function parseLanShareStatus(data: DynamicBridge): LanShareStatus { downloadUrl: portalUrl && shared && !isDirectory ? buildDownloadUrl(portalUrl, f.id, name) : '' }) } - return { ok: true, running, lanIp, port: Number.isInteger(port) ? port : 0, portalUrl, interfaces, files } + return { + ok: true, + running, + lanIp, + port: Number.isInteger(port) ? port : 0, + portalUrl, + pin, + requirePin, + totalClientRequests, + interfaces, + files + } } async function callLanShare( @@ -128,13 +243,43 @@ export function fetchLanShareStatus(hostOverride?: DynamicBridge): Promise { - const status = await callLanShare('startShareServer', {}, hostOverride) +export async function startLanShare( + hostOverride?: DynamicBridge, + options?: LanStartOptions +): Promise { + const params: Record = {} + if (typeof options?.requirePin === 'boolean') params.requirePin = options.requirePin + if (typeof options?.pin === 'string' && options.pin.trim()) params.pin = options.pin.trim() + const status = await callLanShare('startShareServer', params, hostOverride) if (!status.ok) return { ok: false, message: resolveErrorMessage(status, t('errStartFailed')), status } if (!status.running) return { ok: false, message: t('errStartUnconfirmed'), status } return { ok: true, message: t('msgStarted'), status } } +/** + * 运行中切换 PIN 访问码保护或刷新 4 位 PIN 码(复用宿主 startShareServer 参数热更新) + */ +export async function updateLanSharePin( + requirePin: boolean, + pin?: string, + hostOverride?: DynamicBridge +): Promise { + const cleanPin = typeof pin === 'string' ? pin.trim() : '' + const params: Record = { requirePin } + if (cleanPin) params.pin = cleanPin + const status = await callLanShare('startShareServer', params, hostOverride) + if (!status.ok) return { ok: false, message: resolveErrorMessage(status, t('errPinUpdateFailed')), status } + if (status.requirePin !== requirePin || (cleanPin && status.pin !== cleanPin)) { + return { ok: false, message: t('errPinUpdateUnconfirmed'), status } + } + const message = cleanPin + ? t('msgPinRefreshed') + : requirePin + ? t('msgPinEnabled') + : t('msgPinDisabled') + return { ok: true, message, status } +} + export async function stopLanShare(hostOverride?: DynamicBridge): Promise { const status = await callLanShare('stopShareServer', {}, hostOverride) if (!status.ok) return { ok: false, message: resolveErrorMessage(status, t('errStopFailed')), status } diff --git a/extensions/lan-share/tests/lan-share.clipboard.test.mjs b/extensions/lan-share/tests/lan-share.clipboard.test.mjs index 1e85da7f..a5b2b59e 100644 --- a/extensions/lan-share/tests/lan-share.clipboard.test.mjs +++ b/extensions/lan-share/tests/lan-share.clipboard.test.mjs @@ -1,110 +1,173 @@ -// 复制地址的集成测试:真实声明式运行时 + 测试宿主剪贴板(可注入写入失败)+ 模拟客户端共享服务 -// 覆盖:写入成功才提示「已复制…」;宿主拒绝写入时提示「复制失败」与原因,不提示成功、不留下未处理的 rejection; -// 服务未运行时不提供复制地址 +// 真实宿主链路集成测试:真实声明式运行时 + createRealHost 装配真实 BuiltinPluginHostService(LanSharePlugin HTTP Server) +// 覆盖:空态引导、真实启动与分享临时文件、复制访问/下载地址与剪贴板失败报错、4 位 PIN 保护真实 HTTP 401/200 校验、停止服务清理无僵尸状态 import test from 'node:test' import assert from 'node:assert/strict' import { getDeclarativeBridge, Toast } from '@ztools/declarative-ui' -import { createHost, mount, tick } from '../../shared/test-harness.mjs' -import { installLanHost } from './lan-host-fake.mjs' +import { createRealHost, mount, REAL_HOST_SKIP_REASON, tick } from '../../shared/real-host-harness.mjs' import LanShareCommand from '../dist/index.js' -const host = createHost() const rejections = [] process.on('unhandledRejection', (reason) => rejections.push(reason)) -test.beforeEach(() => { - host.reset() - rejections.length = 0 -}) - -/** 让宿主剪贴板写入抛错(模拟 HostMethodError:剪贴板被占用 / IPC 断开),返回恢复函数 */ -function failClipboard(error) { +/** 接管剪贴板记录或注入失败(测试剪贴板写入契约) */ +function interceptClipboard(impl) { const bridge = getDeclarativeBridge() const original = bridge.copyToClipboard - bridge.copyToClipboard = async () => { - throw error - } + bridge.copyToClipboard = impl return () => { bridge.copyToClipboard = original } } -async function mountRunning() { - const state = installLanHost(host, { existing: ['D:\\Share\\a.txt'] }) - state.running = true - state.files.set('id1', { id: 'id1', name: 'a.txt', path: 'D:\\Share\\a.txt', size: 10, sizeBytes: 10, shared: true, isDirectory: false }) +async function createRunningView() { + const host = createRealHost({ pluginId: 'lan-share', locale: 'zh-CN' }) + const tempFile = host.writeTempFile('share/hello.txt', 'hello-ztools-lan-share') + await host.services.files.grantOpenPath(tempFile, host.caller) + + // 通过真实 LanSharePlugin 添加文件(会自动启动真实本地 HTTP Server) + const addRes = await host.services.builtinHost.handlePluginCall( + 'LanSharePlugin', + 'addFiles', + { paths: [tempFile], port: 0 }, + undefined, + host.caller + ) + assert.equal(addRes.ok, true) + assert.equal(addRes.running, true) + const fileId = addRes.files[0].id + const view = await mount(LanShareCommand) - await tick(20) + await tick(30) host.toasts.length = 0 - return view + return { host, view, fileId, status: addRes } } -test('复制访问地址:写入成功后才提示「已复制访问地址」', async () => { - const view = await mountRunning() - await view.run(view.item('lan-service'), '复制访问地址') - await tick(10) - assert.equal(host.clipboard.text, 'http://192.168.1.20:8765') - assert.equal(host.lastToast().style, Toast.Style.Success) - assert.equal(host.lastToast().title, '已复制访问地址') - assert.deepEqual(rejections, []) - view.unmount() -}) +async function cleanupRealView(host, view) { + try { + view?.unmount() + } finally { + try { + await host.services.builtinHost.handlePluginCall('LanSharePlugin', 'stopShareServer', {}, undefined, host.caller) + } finally { + await host.dispose() + } + } +} -test('复制下载地址:地址与客户端共享网页的下载链接一致', async () => { - const view = await mountRunning() - await view.run(view.item('lan-file-id1'), '复制下载地址') - await tick(10) - assert.equal(host.clipboard.text, 'http://192.168.1.20:8765/download/id1/a.txt') - assert.equal(host.lastToast().title, '已复制下载地址') - view.unmount() +test('空态引导:未启动且无文件时展示诚实空态引导项,不提供复制地址', { skip: REAL_HOST_SKIP_REASON }, async () => { + rejections.length = 0 + const host = createRealHost({ pluginId: 'lan-share', locale: 'zh-CN' }) + const view = await mount(LanShareCommand) + try { + await tick(30) + const service = view.item('lan-service') + const titles = view.actions(service).map((a) => a.props.title) + assert.equal(titles[0], '启动共享服务') + assert.equal(titles.includes('复制访问地址'), false) + assert.ok(view.item('lan-empty-files'), '无共享文件时应展示诚实空态引导项') + assert.equal(/http:\/\//.test(view.tree().props.filterBar.summaryText), false) + assert.deepEqual(rejections, []) + } finally { + await cleanupRealView(host, view) + } }) -test('[故障] 复制访问地址:宿主拒绝写入时提示「复制失败」与原因,不提示成功、无未处理 rejection', async () => { - const view = await mountRunning() - host.clipboard.text = 'SENTINEL' - const restore = failClipboard(Object.assign(new Error('剪贴板被其他程序占用'), { name: 'HostMethodError', code: 'CLIPBOARD_BUSY' })) +test('复制访问地址与下载地址:真实宿主写入成功后才提示成功', { skip: REAL_HOST_SKIP_REASON }, async () => { + rejections.length = 0 + const { host, view, fileId, status } = await createRunningView() + const copied = [] + const restore = interceptClipboard(async (text) => { + copied.push(String(text)) + }) try { await view.run(view.item('lan-service'), '复制访问地址') - await tick(10) + await tick(15) + assert.equal(copied[0], `http://${status.primaryIp}:${status.port}`) + assert.equal(host.lastToast().style, Toast.Style.Success) + assert.equal(host.lastToast().title, '已复制访问地址') + + await view.run(view.item(`lan-file-${fileId}`), '复制下载地址') + await tick(15) + assert.equal(copied[1], `http://${status.primaryIp}:${status.port}/download/${fileId}/hello.txt`) + assert.equal(host.lastToast().title, '已复制下载地址') + assert.deepEqual(rejections, []) } finally { restore() + await cleanupRealView(host, view) } - assert.equal(host.clipboard.text, 'SENTINEL') - assert.equal(host.toasts.length, 1) - assert.equal(host.lastToast().style, Toast.Style.Failure) - assert.equal(host.lastToast().title, '复制失败') - assert.equal(host.lastToast().message, '剪贴板被其他程序占用') - assert.deepEqual(rejections, []) - view.unmount() }) -test('[故障] 复制下载地址:宿主抛出非 Error 值时提示失败并带原因', async () => { - const view = await mountRunning() - const restore = failClipboard('IPC 管道已断开') +test('[故障] 剪贴板写入失败(Error / 非 Error):提示「复制失败」与原因且无未处理 rejection', { skip: REAL_HOST_SKIP_REASON }, async () => { + rejections.length = 0 + const { host, view, fileId } = await createRunningView() + const restoreErr = interceptClipboard(async () => { + throw Object.assign(new Error('剪贴板被其他程序占用'), { name: 'HostMethodError', code: 'CLIPBOARD_BUSY' }) + }) try { - await view.run(view.item('lan-file-id1'), '复制下载地址') - await tick(10) + await view.run(view.item('lan-service'), '复制访问地址') + await tick(15) + assert.equal(host.toasts.length, 1) + assert.equal(host.lastToast().style, Toast.Style.Failure) + assert.equal(host.lastToast().title, '复制失败') + assert.equal(host.lastToast().message, '剪贴板被其他程序占用') + + host.toasts.length = 0 + const restoreStr = interceptClipboard(async () => { + throw 'IPC 管道已断开' + }) + try { + await view.run(view.item(`lan-file-${fileId}`), '复制下载地址') + await tick(15) + assert.equal(host.toasts.length, 1) + assert.equal(host.lastToast().style, Toast.Style.Failure) + assert.equal(host.lastToast().message, 'IPC 管道已断开') + } finally { + restoreStr() + } + assert.deepEqual(rejections, []) } finally { - restore() + restoreErr() + await cleanupRealView(host, view) } - assert.equal(host.toasts.length, 1) - assert.equal(host.lastToast().style, Toast.Style.Failure) - assert.equal(host.lastToast().message, 'IPC 管道已断开') - assert.deepEqual(rejections, []) - view.unmount() }) -test('[边界] 服务未运行时不提供复制地址,文件行也没有下载地址', async () => { - const state = installLanHost(host) - state.files.set('id1', { id: 'id1', name: 'a.txt', path: 'D:\\Share\\a.txt', size: 10, sizeBytes: 10, shared: true, isDirectory: false }) - const view = await mount(LanShareCommand) - await tick(20) - const titles = view.actions(view.item('lan-service')).map((a) => a.props.title) - assert.equal(titles[0], '启动共享服务') - assert.ok(titles.includes('刷新共享状态')) - assert.equal(titles.includes('复制访问地址'), false) - const fileTitles = view.actions(view.item('lan-file-id1')).map((a) => a.props.title) - assert.equal(fileTitles.includes('复制下载地址'), false) - assert.equal(/http:\/\//.test(view.tree().props.filterBar.summaryText), false) - view.unmount() +test('4 位 PIN 保护与停止清理:真实 HTTP Server 验证 401/200,停止后清理 URL 不留僵尸展示', { skip: REAL_HOST_SKIP_REASON }, async () => { + rejections.length = 0 + const { host, view, fileId, status } = await createRunningView() + try { + // 通过动作面板开启 4 位 PIN 保护 + await view.run(view.item('lan-service'), '开启 4 位 PIN 保护') + await tick(30) + + const updatedStatus = await host.services.builtinHost.handlePluginCall( + 'LanSharePlugin', + 'getLanShareStatus', + {}, + undefined, + host.caller + ) + assert.equal(updatedStatus.requirePin, true) + assert.match(updatedStatus.pin, /^\d{4}$/) + + // 验证真实 HTTP Server 拦截无 PIN 请求(401),放行带正确 PIN 的文件下载(200) + const baseUrl = `http://127.0.0.1:${status.port}` + const unauthRes = await fetch(`${baseUrl}/download/${fileId}/hello.txt`) + assert.equal(unauthRes.status, 401) + const authRes = await fetch(`${baseUrl}/download/${fileId}/hello.txt?pin=${updatedStatus.pin}`) + assert.equal(authRes.status, 200) + assert.equal(await authRes.text(), 'hello-ztools-lan-share') + + // 停止服务后应立即清理 URL 与二维码,不再提供复制访问/下载地址 + await view.run(view.item('lan-service'), '停止共享服务') + await tick(30) + const stoppedTitles = view.actions(view.item('lan-service')).map((a) => a.props.title) + assert.equal(stoppedTitles[0], '启动共享服务') + assert.equal(stoppedTitles.includes('复制访问地址'), false) + const fileTitles = view.actions(view.item(`lan-file-${fileId}`)).map((a) => a.props.title) + assert.equal(fileTitles.includes('复制下载地址'), false) + assert.equal(/http:\/\//.test(view.tree().props.filterBar.summaryText), false) + assert.deepEqual(rejections, []) + } finally { + await cleanupRealView(host, view) + } }) diff --git a/extensions/lan-share/tests/lan-share.host.test.mjs b/extensions/lan-share/tests/lan-share.host.test.mjs index bdc72ec1..ffc9d19b 100644 --- a/extensions/lan-share/tests/lan-share.host.test.mjs +++ b/extensions/lan-share/tests/lan-share.host.test.mjs @@ -10,17 +10,24 @@ import { addFilesToShare, addFilesToShareBatched, buildDownloadUrl, + buildDownloadUrlForIp, + buildPortalUrlForIp, clearAllSharedFiles, countDuplicateFileNames, fetchLanShareStatus, filterSharedFiles, + formatInterfaceLabel, generateQrCodeSvgDataUri, + generateRandomPin, parseLanShareStatus, pickFilesToShare, removeSharedFile, + resolveActiveInterface, + resolveActiveLanIp, setFileShared, startLanShare, - stopLanShare + stopLanShare, + updateLanSharePin } from '../dist/logic.js' const IFACES = [ @@ -264,3 +271,71 @@ test('清空共享列表:逐条移除,如实汇报全部成功或部分失 const empty = await clearAllSharedFiles([], host) assert.equal(empty.ok, false) }) + +test('解析 PIN、requirePin 与累计访问数,并支持多网卡切换与 URL 拼接', () => { + const multiIfaces = [ + { name: 'WLAN', address: '192.168.1.20', family: 'IPv4', internal: false }, + { name: 'vEthernet', address: '172.20.0.1', family: 'IPv4', internal: false }, + { name: 'Loopback', address: '127.0.0.1', family: 'IPv4', internal: true } + ] + const parsed = parseLanShareStatus( + status({ interfaces: multiIfaces, pin: '4829', requirePin: true, totalClientRequests: 7 }) + ) + assert.equal(parsed.pin, '4829') + assert.equal(parsed.requirePin, true) + assert.equal(parsed.totalClientRequests, 7) + assert.equal(parsed.interfaces.length, 2) + + assert.equal(resolveActiveLanIp(parsed, '172.20.0.1'), '172.20.0.1') + assert.equal(resolveActiveLanIp(parsed, '10.0.0.99'), '192.168.1.20', '掉线网卡应回退到宿主主网卡') + assert.equal(formatInterfaceLabel(resolveActiveInterface(parsed, '172.20.0.1')), 'vEthernet · 172.20.0.1') + + assert.equal( + buildPortalUrlForIp('172.20.0.1', 8765, { pin: '4829', requirePin: true }), + 'http://172.20.0.1:8765/?pin=4829' + ) + assert.equal( + buildPortalUrlForIp('172.20.0.1', 8765, { pin: '4829', requirePin: false }), + 'http://172.20.0.1:8765' + ) + assert.equal( + buildDownloadUrlForIp('172.20.0.1', 8765, 'a1b2c3', '报告 v2.pdf', { pin: '4829', requirePin: true }), + 'http://172.20.0.1:8765/download/a1b2c3/%E6%8A%A5%E5%91%8A%20v2.pdf?pin=4829' + ) + assert.equal(buildPortalUrlForIp('', 8765), '') + assert.equal(buildPortalUrlForIp('192.168.1.20', 0), '') + assert.match(generateRandomPin(), /^\d{4}$/) +}) + +test('PIN 保护开关与刷新:透传 requirePin / pin 参数并校验宿主回执确认', async () => { + const host = lanHost({ + startShareServer: (params) => + status({ + requirePin: Boolean(params.requirePin), + pin: params.pin || '4829' + }) + }) + const startedWithPin = await startLanShare(host, { requirePin: true, pin: '2468' }) + assert.equal(startedWithPin.ok, true) + assert.deepEqual(host.calls[0], ['startShareServer', { requirePin: true, pin: '2468' }]) + assert.equal(startedWithPin.status.requirePin, true) + assert.equal(startedWithPin.status.pin, '2468') + + const refreshed = await updateLanSharePin(true, '9012', host) + assert.equal(refreshed.ok, true) + assert.equal(refreshed.status.pin, '9012') + + const disabled = await updateLanSharePin(false, undefined, host) + assert.equal(disabled.ok, true) + assert.equal(disabled.status.requirePin, false) + + const unconfirmed = await updateLanSharePin( + true, + '1357', + lanHost({ startShareServer: () => status({ requirePin: false, pin: '9999' }) }) + ) + assert.equal(unconfirmed.ok, false) + + const noHost = await updateLanSharePin(true, '1357') + assert.equal(noHost.ok, false) +}) diff --git a/extensions/lan-share/tests/lan-share.ui.test.mjs b/extensions/lan-share/tests/lan-share.ui.test.mjs deleted file mode 100644 index e5979379..00000000 --- a/extensions/lan-share/tests/lan-share.ui.test.mjs +++ /dev/null @@ -1,331 +0,0 @@ -// 界面集成测试:真实声明式运行时 + 模拟客户端共享服务(可注入失败) -// 覆盖:顶栏双按钮、启动/停止服务、选择文件/文件夹并分批共享、同名提示、拖入/粘贴文件夹展开、清空共享列表(含部分失败) -import test from 'node:test' -import assert from 'node:assert/strict' -import fs from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import { Toast } from '@ztools/declarative-ui' -import { createHost, installDirectoryHost, mount, tick } from '../../shared/test-harness.mjs' -import { installLanHost } from './lan-host-fake.mjs' -import LanShareCommand from '../dist/index.js' - -const host = createHost() -const rejections = [] -process.on('unhandledRejection', (reason) => rejections.push(reason)) - -test.beforeEach(() => { - host.reset() - rejections.length = 0 -}) - -const dllCalls = (func) => host.ipcCalls.filter(([m, p]) => m === 'dllplugin_call' && p.func === func) -const ipcCount = (method) => host.ipcCalls.filter(([m]) => m === method).length - -function makeTempTree(spec) { - const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ztools-lan-')) - for (const [rel, content] of Object.entries(spec)) { - const full = path.join(root, rel) - fs.mkdirSync(path.dirname(full), { recursive: true }) - fs.writeFileSync(full, content) - } - return root -} - -async function clickFilterBar(view, id) { - const action = view.tree().props.filterBar.actions.find((a) => a.id === id) - assert.ok(action, `顶栏缺少按钮 ${id}`) - action.onAction() - await tick(35) -} - -test('打开时只读取状态,不扫描本机目录;顶栏固定为「选择文件」「选择文件夹」2 个按钮,刷新移入服务项', async () => { - installLanHost(host) - const view = await mount(LanShareCommand) - await tick(20) - assert.equal(dllCalls('startShareServer').length, 0) - assert.equal(ipcCount('system_get_path'), 0) - assert.equal(ipcCount('system_list_common_folders'), 0) - assert.equal(ipcCount('system_search_files'), 0) - assert.equal(ipcCount('filesystem_get_directory_contents'), 0) - assert.equal(view.item('lan-service').props.title, '共享服务未运行') - - const filterActions = view.tree().props.filterBar.actions - assert.deepEqual( - filterActions.map((a) => [a.id, a.title]), - [['pick-files', '选择文件'], ['pick-folder', '选择文件夹']] - ) - assert.ok(view.actions(view.item('lan-service')).some((a) => a.props.title === '刷新共享状态')) - assert.ok(view.actions(null).some((a) => a.props.title === '刷新共享状态')) - - const text = view.text() - assert.equal(/剪贴板投送|上传照片|双向/.test(text), false) - assert.equal(/"color"/.test(text), false) - view.unmount() -}) - -test('启动服务:成功后显示访问地址与二维码,提示无需密码', async () => { - installLanHost(host) - const view = await mount(LanShareCommand) - await tick(20) - await view.run(view.item('lan-service'), '启动共享服务') - await tick(20) - assert.equal(dllCalls('startShareServer').length, 1) - assert.equal(host.lastToast().style, Toast.Style.Success) - assert.equal(host.lastToast().title, '共享服务已启动') - const service = view.item('lan-service') - assert.equal(service.props.title, '共享服务运行中:http://192.168.1.20:8765') - const md = service.props.detail.props.markdown - assert.match(md, /data:image\/svg\+xml/) - assert.match(md, /不需要密码/) - assert.match(md, /172\.20\.0\.1:8765/, '应列出本机的其他地址') - view.unmount() -}) - -test('[故障] 启动服务失败:提示原因,仍显示未运行', async () => { - const state = installLanHost(host) - state.startError = Object.assign(new Error('listen EACCES: permission denied 0.0.0.0:8765'), { code: 'EACCES' }) - const view = await mount(LanShareCommand) - await tick(20) - await view.run(view.item('lan-service'), '启动共享服务') - await tick(20) - assert.equal(host.lastToast().style, Toast.Style.Failure) - assert.equal(host.lastToast().title, '启动共享服务失败') - assert.match(host.lastToast().message, /调用局域网共享服务失败/) - assert.equal(view.item('lan-service').props.title, '共享服务未运行') - assert.deepEqual(rejections, []) - view.unmount() -}) - -test('选择文件并共享:读不到的文件如实提示跳过,列表只显示客户端确认加入的文件', async () => { - const state = installLanHost(host, { existing: ['D:\\Share\\a.txt'] }) - state.dialog = { canceled: false, filePaths: [{ path: 'D:\\Share\\a.txt' }, { path: 'D:\\Share\\gone.txt' }] } - const view = await mount(LanShareCommand) - await tick(20) - await clickFilterBar(view, 'pick-files') - assert.deepEqual(dllCalls('addFiles')[0][1].params, { paths: ['D:\\Share\\a.txt', 'D:\\Share\\gone.txt'] }) - assert.equal(host.lastToast().style, Toast.Style.Success) - assert.equal(host.lastToast().title, '已共享 1 个文件,1 个文件无法读取已跳过') - assert.match(host.lastToast().message, /不需要密码/) - const fileRows = view.items().filter((i) => String(i.props.id).startsWith('lan-file-')) - assert.deepEqual(fileRows.map((i) => i.props.title), ['a.txt']) - assert.deepEqual(rejections, []) - view.unmount() -}) - -test('[边界] 取消选择文件:不调用客户端加文件,也不提示', async () => { - installLanHost(host) - const view = await mount(LanShareCommand) - await tick(20) - host.toasts.length = 0 - await clickFilterBar(view, 'pick-files') - assert.equal(dllCalls('addFiles').length, 0) - assert.equal(host.toasts.length, 0) - view.unmount() -}) - -test('[故障] 选中的文件都读不到:提示失败,不报成功', async () => { - const state = installLanHost(host) - state.dialog = { canceled: false, filePath: 'D:\\Share\\gone.txt' } - const view = await mount(LanShareCommand) - await tick(20) - await clickFilterBar(view, 'pick-files') - assert.equal(host.lastToast().style, Toast.Style.Failure) - assert.equal(host.lastToast().title, '共享文件失败') - assert.equal(host.toasts.some((t) => t.style === Toast.Style.Success), false) - view.unmount() -}) - -test('选择文件夹并共享:收集非隐藏普通文件、分批调用、提示同名文件并支持整盘确认与数量上限', async () => { - const spec = { - 'dirA/readme.md': 'a', - 'dirB/readme.md': 'b', - 'dirA/.hidden.txt': 'h', - 'dirA/empty.txt': '' - } - for (let i = 0; i < 105; i++) { - spec[`bulk/file_${String(i).padStart(3, '0')}.txt`] = 'x' - } - const tmp = makeTempTree(spec) - try { - const allPaths = [ - path.join(tmp, 'dirA', 'readme.md'), - path.join(tmp, 'dirB', 'readme.md'), - ...Array.from({ length: 105 }, (_, i) => path.join(tmp, 'bulk', `file_${String(i).padStart(3, '0')}.txt`)) - ] - const state = installLanHost(host, { existing: allPaths }) - await installDirectoryHost(host, { authorized: [tmp] }) - - const view = await mount(LanShareCommand) - await tick(20) - - // 整盘根目录确认取消 - state.folderDialog = { canceled: false, folderPath: 'E:\\' } - host.setConfirm(false) - await clickFilterBar(view, 'pick-folder') - assert.equal(host.confirms.length, 1) - assert.equal(dllCalls('addFiles').length, 0) - - // 真实目录:共 107 个有效非隐藏文件,按 100 + 7 分 2 批调用,且存在 2 个同名 readme.md - state.folderDialog = { canceled: false, folderPath: tmp } - await clickFilterBar(view, 'pick-folder') - await tick(30) - const batches = dllCalls('addFiles').map(([, p]) => p.params.paths.length) - assert.deepEqual(batches, [100, 7]) - assert.equal(host.lastToast().style, Toast.Style.Success) - assert.equal(host.lastToast().title, '已共享 107 个文件') - assert.match(host.lastToast().message, /忽略 2 个隐藏或系统文件/) - assert.match(host.lastToast().message, /有 2 个文件与其他文件同名,网页上请按大小区分/) - view.unmount() - } finally { - fs.rmSync(tmp, { recursive: true, force: true }) - } -}) - -test('暂停、恢复、移出共享列表:用 id 调用客户端,界面以客户端状态为准', async () => { - const state = installLanHost(host) - state.running = true - state.files.set('id1', { id: 'id1', name: 'a.txt', path: 'D:\\Share\\a.txt', size: 10, sizeBytes: 10, shared: true, isDirectory: false }) - const view = await mount(LanShareCommand) - await tick(20) - - await view.run(view.item('lan-file-id1'), '暂停共享该文件') - await tick(20) - assert.deepEqual(dllCalls('toggleFileShare')[0][1].params, { id: 'id1', shared: false }) - let row = view.item('lan-file-id1') - assert.deepEqual(row.props.accessories[0], { tag: { value: '已暂停' } }) - assert.equal(view.actions(row).some((a) => a.props.title === '复制下载地址'), false) - - await view.run(row, '恢复共享该文件') - await tick(20) - row = view.item('lan-file-id1') - assert.deepEqual(row.props.accessories[0], { tag: { value: '共享中' } }) - - await view.run(row, '从共享列表移除(不删除文件)') - await tick(20) - assert.equal(view.items().some((i) => i.props.id === 'lan-file-id1'), false) - assert.match(host.lastToast().title, /文件本身没有删除/) - view.unmount() -}) - -test('清空共享列表:全部移除成功与部分失败如实汇报“已移除 N 个,M 个失败”', async () => { - const state = installLanHost(host) - state.running = true - state.files.set('id1', { id: 'id1', name: 'a.txt', path: 'D:\\Share\\a.txt', sizeBytes: 10, shared: true, isDirectory: false }) - state.files.set('id2', { id: 'id2', name: 'b.txt', path: 'D:\\Share\\b.txt', sizeBytes: 10, shared: true, isDirectory: false }) - state.files.set('id3', { id: 'id3', name: 'c.txt', path: 'D:\\Share\\c.txt', sizeBytes: 10, shared: true, isDirectory: false }) - state.removeFailIds.add('id2') - - const view = await mount(LanShareCommand) - await tick(20) - assert.match(view.tree().props.filterBar.summaryText, /清空列表 Ctrl\+Shift\+Backspace/) - - await view.run(view.item('lan-service'), '清空共享列表') - await tick(25) - assert.equal(host.lastToast().style, Toast.Style.Failure) - assert.equal(host.lastToast().title, '已移除 2 个,1 个失败') - assert.match(host.lastToast().message, /b\.txt/) - assert.deepEqual( - view.items().filter((i) => String(i.props.id).startsWith('lan-file-')).map((i) => i.props.title), - ['b.txt'] - ) - - state.removeFailIds.clear() - await view.run(view.item('lan-file-id2'), '清空共享列表') - await tick(25) - assert.equal(host.lastToast().style, Toast.Style.Success) - assert.match(host.lastToast().title, /已清空共享列表/) - assert.equal(view.items().filter((i) => String(i.props.id).startsWith('lan-file-')).length, 0) - view.unmount() -}) - -test('停止服务:文件标签停止显示共享中,重新启动后恢复', async () => { - const state = installLanHost(host) - state.running = true - state.files.set('active', { id: 'active', name: 'a.txt', path: 'D:\\Share\\a.txt', sizeBytes: 10, shared: true, isDirectory: false }) - state.files.set('paused', { id: 'paused', name: 'b.txt', path: 'D:\\Share\\b.txt', sizeBytes: 10, shared: false, isDirectory: false }) - const view = await mount(LanShareCommand) - await tick(20) - await view.run(view.item('lan-service'), '停止共享服务') - await tick(20) - assert.equal(host.lastToast().title, '共享服务已停止') - assert.equal(view.item('lan-service').props.title, '共享服务未运行') - assert.equal(view.item('lan-file-active').props.accessories[0].tag.value, '服务未启动') - assert.equal(view.item('lan-file-paused').props.accessories[0].tag.value, '已暂停') - await view.run(view.item('lan-service'), '启动共享服务'); await tick(20) - assert.equal(view.item('lan-file-active').props.accessories[0].tag.value, '共享中') - view.unmount() -}) - -test('拖拽文件与文件夹接收:旧版 plugin_files_dropped 事件也能展开文件夹逐个共享', async () => { - const tmp = makeTempTree({ 'sub.v1/inner.txt': 'inner' }) - const dropListeners = [] - globalThis.window.__ztoolsDeclarativeFeatures = { fileInput: false } - globalThis.window.ztools = { - ...(globalThis.window.ztools || {}), - events: { - on(event, cb) { - if (event === 'plugin_files_dropped') dropListeners.push(cb) - return () => {} - } - } - } - try { - const folder = path.join(tmp, 'sub.v1') - const inner = path.join(folder, 'inner.txt') - installLanHost(host, { existing: [inner, 'D:\\Share\\dropped.txt'] }) - await installDirectoryHost(host, { authorized: [tmp] }) - host.ipc.filesystem_directory_exists = async ({ path: p }) => ({ - success: true, - exists: fs.existsSync(p) && fs.statSync(p).isDirectory() - }) - - const view = await mount(LanShareCommand) - await tick(20) - assert.equal(dropListeners.length, 1) - - dropListeners[0]({ payload: { files: [folder, 'D:\\Share\\dropped.txt'] } }) - await tick(35) - - assert.deepEqual(dllCalls('addFiles')[0][1].params, { paths: [inner, 'D:\\Share\\dropped.txt'] }) - assert.equal(host.lastToast().style, Toast.Style.Success) - assert.equal(host.lastToast().title, '已共享 2 个文件') - const fileRows = view.items().filter((i) => String(i.props.id).startsWith('lan-file-')) - assert.deepEqual(fileRows.map((i) => i.props.title), ['inner.txt', 'dropped.txt']) - view.unmount() - } finally { - fs.rmSync(tmp, { recursive: true, force: true }) - } -}) - -test('Ctrl+V 粘贴文件、文件夹与剪贴板截图:展开文件夹内的文件逐个加入共享列表(不把文件夹本身加入)', async () => { - const tmp = makeTempTree({ 'SharedFolder.v2/doc.pdf': 'pdf', 'SharedFolder.v2/photo.png': 'png' }) - try { - const folder = path.join(tmp, 'SharedFolder.v2') - const f1 = path.join(folder, 'doc.pdf') - const f2 = path.join(folder, 'photo.png') - installLanHost(host, { existing: ['D:\\Share\\screenshot.png', f1, f2] }) - await installDirectoryHost(host, { authorized: [tmp] }) - - const view = await mount(LanShareCommand) - await tick(20) - - assert.equal(view.tree().props.fileInput?.allowClipboardImage, true) - assert.equal(view.tree().props.fileInput?.allowDirectories, true) - - await view.pasteFiles(['D:\\Share\\screenshot.png', folder], { directories: [folder] }) - await tick(35) - - assert.deepEqual(dllCalls('addFiles')[0][1].params, { - paths: [f1, f2, 'D:\\Share\\screenshot.png'] - }) - assert.equal(host.lastToast().style, Toast.Style.Success) - assert.equal(host.lastToast().title, '已共享 3 个文件') - const fileRows = view.items().filter((i) => String(i.props.id).startsWith('lan-file-')) - assert.deepEqual(fileRows.map((i) => i.props.title), ['doc.pdf', 'photo.png', 'screenshot.png']) - assert.equal(fileRows.some((i) => i.props.title === 'SharedFolder.v2'), false, '不再把文件夹本身加入共享列表') - view.unmount() - } finally { - fs.rmSync(tmp, { recursive: true, force: true }) - } -}) diff --git a/extensions/linux-http-dict/plugin.json b/extensions/linux-http-dict/plugin.json index cc8b1b8c..b72c5c16 100644 --- a/extensions/linux-http-dict/plugin.json +++ b/extensions/linux-http-dict/plugin.json @@ -1,7 +1,7 @@ { "id": "linux-http-dict", "name": "命令与状态码", - "version": "1.0.6", + "version": "1.0.7", "minAppVersion": "1.1.8.0", "description": "离线速查 Linux 常用命令示例、常见 HTTP 状态码含义与排查步骤、常用服务默认端口", "author": "ZTools Team", diff --git a/extensions/linux-http-dict/src/i18n.ts b/extensions/linux-http-dict/src/i18n.ts index 5e82e6ab..8dc709b8 100644 --- a/extensions/linux-http-dict/src/i18n.ts +++ b/extensions/linux-http-dict/src/i18n.ts @@ -4,21 +4,32 @@ const DICT_MESSAGES = { 'zh-CN': { // UI searchAllPlaceholder: '跨分类全局检索 Linux 命令、HTTP 状态码或默认端口(如:curl、502、6379)...', + searchFavoritesPlaceholder: '在已收藏条目中搜索命令、状态码或端口...', searchLinuxPlaceholder: '搜索 Linux 命令或中文场景(如:tar、解压、端口占用、查找文件、awk)...', searchHttpPlaceholder: '输入 HTTP 状态码或故障现象(如:502、504、499、403、网关超时)...', searchPortPlaceholder: '输入端口号或服务名称(如:6379、3306、redis、mysql、nacos)...', dropdownTooltip: '切换速查字典类别', modeAllTitle: '全部字典(跨分类检索)', + modeFavoritesTitle: '我的收藏(置顶常用)', modeLinuxTitle: 'Linux 高频命令实例', modeHttpTitle: 'HTTP 状态码与排障', modePortTitle: '知名服务默认端口', + secFavoritesTitle: '我的收藏(共 {count} 项)', secLinuxTitle: 'Linux 高频实战命令库(共 {count} 项)', linuxExamplesHeader: '#### 生产高频场景实例', linuxParamsHeader: '#### 常用核心参数说明\n| 参数选项 | 作用说明 |\n| :--- | :--- |', metaStarsTitle: '高频评级', metaPackageTitle: '软件包名', actionCopyPrimaryCmd: '复制首选推荐命令', + actionCopyExampleN: '复制示例 {index}:{title}', actionCopyAllExamples: '复制全部示例命令', + actionAddFavorite: '收藏置顶', + actionRemoveFavorite: '取消收藏', + toastFavorited: '已收藏置顶', + toastUnfavorited: '已取消收藏', + toastFavoriteFailed: '收藏状态更新失败', + emptyFavoritesTitle: '暂无收藏条目', + emptyFavoritesSubtitle: '在任意命令、状态码或端口上按动作面板选择「收藏置顶」即可在此快速查看', secHttpTitle: 'HTTP 状态码排障指南(共 {count} 项)', httpTag5xx: '服务端错误', httpTag4xx: '客户端/网关异常', @@ -284,21 +295,32 @@ const DICT_MESSAGES = { }, 'en-US': { searchAllPlaceholder: 'Search across Linux commands, HTTP status codes, and ports (e.g. curl, 502, 6379)...', + searchFavoritesPlaceholder: 'Search saved favorites across commands, status codes, and ports...', searchLinuxPlaceholder: 'Search Linux commands or tasks (e.g. tar, extract, port, find, awk)...', searchHttpPlaceholder: 'Enter HTTP status code or symptom (e.g. 502, 504, 499, 403, timeout)...', searchPortPlaceholder: 'Enter port number or service (e.g. 6379, 3306, redis, mysql, nacos)...', dropdownTooltip: 'Switch Dictionary Mode', modeAllTitle: 'All Dictionaries (Global Search)', + modeFavoritesTitle: 'Favorites (Pinned)', modeLinuxTitle: 'Linux Command Reference', modeHttpTitle: 'HTTP Status & Troubleshooting', modePortTitle: 'Well-Known Network Ports', + secFavoritesTitle: 'Favorites ({count})', secLinuxTitle: 'Linux Command Reference ({count})', linuxExamplesHeader: '#### Production Examples', linuxParamsHeader: '#### Key Flags\n| Flag | Description |\n| :--- | :--- |', metaStarsTitle: 'Frequency', metaPackageTitle: 'Package', actionCopyPrimaryCmd: 'Copy Primary Command', + actionCopyExampleN: 'Copy Example {index}: {title}', actionCopyAllExamples: 'Copy All Examples', + actionAddFavorite: 'Pin to Favorites', + actionRemoveFavorite: 'Remove from Favorites', + toastFavorited: 'Pinned to favorites', + toastUnfavorited: 'Removed from favorites', + toastFavoriteFailed: 'Failed to update favorites', + emptyFavoritesTitle: 'No favorites yet', + emptyFavoritesSubtitle: 'Open the action panel on any entry and choose "Pin to Favorites"', secHttpTitle: 'HTTP Status & Troubleshooting ({count})', httpTag5xx: 'Server Error', httpTag4xx: 'Client / Gateway Error', diff --git a/extensions/linux-http-dict/src/index.tsx b/extensions/linux-http-dict/src/index.tsx index 642efd6f..49512c7f 100644 --- a/extensions/linux-http-dict/src/index.tsx +++ b/extensions/linux-http-dict/src/index.tsx @@ -4,6 +4,10 @@ import React, { Color, Icon, List, + LocalStorage, + Toast, + showToast, + useEffect, useLocale, useMemo, useState @@ -15,11 +19,48 @@ import { searchLinuxCommands } from './dict-service.js' import { t } from './i18n.js' -import type { DictCategory } from './types' +import type { DictCategory, HttpStatusItem, LinuxCommandItem, PortItem } from './types' export * from './types.js' export * from './dict-service.js' +const FAVORITES_STORAGE_KEY = 'linux-http-dict.favorites.v1' + +function parseFavorites(raw: unknown): string[] { + if (!Array.isArray(raw)) return [] + const seen = new Set() + const result: string[] = [] + for (const item of raw) { + if (typeof item === 'string' && item.trim() && !seen.has(item)) { + seen.add(item) + result.push(item) + } + } + return result +} + +export async function readFavorites(): Promise { + const raw = await LocalStorage.getItem(FAVORITES_STORAGE_KEY) + return parseFavorites(raw) +} + +export async function toggleFavorite(favKey: string): Promise<{ favorites: string[]; added: boolean }> { + let added = false + let nextList: string[] = [] + await LocalStorage.updateItem(FAVORITES_STORAGE_KEY, (value) => { + const current = parseFavorites(value) + if (current.includes(favKey)) { + added = false + nextList = current.filter((item) => item !== favKey) + } else { + added = true + nextList = [favKey, ...current] + } + return nextList + }) + return { favorites: nextList, added } +} + export interface LinuxHttpDictCommandProps { featureCode?: string initialCategory?: DictCategory @@ -38,6 +79,40 @@ export function LinuxHttpDictCommand(props: LinuxHttpDictCommandProps = {}) { const locale = useLocale() const [category, setCategory] = useState(defaultCategory) const [searchText, setSearchText] = useState(props.initialSearchText ?? '') + const [favorites, setFavorites] = useState([]) + + useEffect(() => { + let alive = true + void readFavorites() + .then((list) => { + if (alive) setFavorites(list) + }) + .catch(() => { + if (alive) setFavorites([]) + }) + return () => { + alive = false + } + }, []) + + const favoriteSet = useMemo(() => new Set(favorites), [favorites]) + + const handleToggleFavorite = async (favKey: string) => { + try { + const { favorites: next, added } = await toggleFavorite(favKey) + setFavorites(next) + await showToast({ + style: Toast.Style.Success, + title: added ? t('toastFavorited') : t('toastUnfavorited') + }) + } catch (err) { + await showToast({ + style: Toast.Style.Failure, + title: t('toastFavoriteFailed'), + message: err instanceof Error ? err.message : String(err) + }) + } + } const filteredCommands = useMemo(() => searchLinuxCommands(searchText), [searchText, locale]) const filteredHttpStatus = useMemo(() => searchHttpStatus(searchText), [searchText, locale]) @@ -47,15 +122,15 @@ export function LinuxHttpDictCommand(props: LinuxHttpDictCommandProps = {}) { const showLinux = category === 'linux' || (category === 'all' && filteredCommands.length > 0) || - (hasQuery && filteredCommands.length > 0) + (category !== 'favorites' && hasQuery && filteredCommands.length > 0) const showHttp = category === 'http' || (category === 'all' && filteredHttpStatus.length > 0) || - (hasQuery && filteredHttpStatus.length > 0) + (category !== 'favorites' && hasQuery && filteredHttpStatus.length > 0) const showPort = category === 'port' || (category === 'all' && filteredPorts.length > 0) || - (hasQuery && filteredPorts.length > 0) + (category !== 'favorites' && hasQuery && filteredPorts.length > 0) const sectionOrder: Array<'linux' | 'http' | 'port'> = category === 'http' @@ -64,20 +139,20 @@ export function LinuxHttpDictCommand(props: LinuxHttpDictCommandProps = {}) { ? ['port', 'linux', 'http'] : ['linux', 'http', 'port'] - const renderLinuxSection = () => - showLinux && filteredCommands.length > 0 ? ( - - {filteredCommands.map((item) => ( - { + const favKey = `linux:${item.id}` + const isFav = favoriteSet.has(favKey) + return ( + `##### ${ex.title} @@ -91,56 +166,67 @@ ${ex.note ? `*${ex.note}*` : ''}` ${t('linuxParamsHeader')} ${item.params.map((p) => `| \`${p.flag}\` | ${p.desc} |`).join('\n')} `} - metadata={ - - - - - - } - /> - } - actions={ - - - `# ${e.title}\n${e.cmd}`).join('\n\n')} - shortcut={{ modifiers: ['ctrl', 'shift'], key: 'c' }} + metadata={ + + + + - + } /> - ))} - - ) : null + } + actions={ + + + {item.examples.slice(1).map((ex, idx) => ( + + ))} + `# ${e.title}\n${e.cmd}`).join('\n\n')} + shortcut={{ modifiers: ['ctrl', 'shift'], key: 'c' }} + /> + handleToggleFavorite(favKey)} + /> + + } + /> + ) + } - const renderHttpSection = () => - showHttp && filteredHttpStatus.length > 0 ? ( - - {filteredHttpStatus.map((item) => ( - = 500 - ? { tag: { value: t('httpTag5xx'), color: Color.Red } } - : item.code >= 400 - ? { tag: t('httpTag4xx') } - : { tag: t('httpTagOther') } - ]} - detail={ - { + const favKey = `http:${item.code}` + const isFav = favoriteSet.has(favKey) + return ( + = 500 + ? { tag: { value: t('httpTag5xx'), color: Color.Red } } + : item.code >= 400 + ? { tag: t('httpTag4xx') } + : { tag: t('httpTagOther') } + ]} + detail={ + `- ${c}`).join('\n')} ${t('httpStepsHeader')} @@ -149,49 +235,53 @@ ${item.troubleshooting.map((stepItem, i) => `${i + 1}. **${stepItem.step}**: ${s ${t('httpArchHeader')} ${item.architectureNotes} `} - metadata={ - - - - - - } - /> - } - actions={ - - `- ${stepItem.step}: ${stepItem.action}`).join('\n')}`} - /> - + + + - + } /> - ))} - - ) : null + } + actions={ + + `- ${stepItem.step}: ${stepItem.action}`).join('\n')}`} + /> + + handleToggleFavorite(favKey)} + /> + + } + /> + ) + } - const renderPortSection = () => - showPort && filteredPorts.length > 0 ? ( - - {filteredPorts.map((item) => ( - { + const favKey = `port:${item.port}` + const isFav = favoriteSet.has(favKey) + return ( + ${item.securityNotice} ${t('portCheckHeader')} @@ -208,27 +298,80 @@ Windows: ${portCheckCommands(item).windows} \`\`\` `} - /> - } - actions={ - - - - - - - } /> - ))} + } + actions={ + + + + + + handleToggleFavorite(favKey)} + /> + + } + /> + ) + } + + // 收集当前视图下需要置顶的收藏条目 + const favLinux = + category === 'favorites' || showLinux + ? filteredCommands.filter((item) => favoriteSet.has(`linux:${item.id}`)) + : [] + const favHttp = + category === 'favorites' || showHttp + ? filteredHttpStatus.filter((item) => favoriteSet.has(`http:${item.code}`)) + : [] + const favPort = + category === 'favorites' || showPort + ? filteredPorts.filter((item) => favoriteSet.has(`port:${item.port}`)) + : [] + const totalPinned = favLinux.length + favHttp.length + favPort.length + + const renderFavoritesSection = () => + totalPinned > 0 ? ( + + {favLinux.map(renderLinuxItem)} + {favHttp.map(renderHttpItem)} + {favPort.map(renderPortItem)} + + ) : null + + const nonFavCommands = filteredCommands.filter((item) => !favoriteSet.has(`linux:${item.id}`)) + const nonFavHttp = filteredHttpStatus.filter((item) => !favoriteSet.has(`http:${item.code}`)) + const nonFavPorts = filteredPorts.filter((item) => !favoriteSet.has(`port:${item.port}`)) + + const renderLinuxSection = () => + showLinux && nonFavCommands.length > 0 ? ( + + {nonFavCommands.map(renderLinuxItem)} + + ) : null + + const renderHttpSection = () => + showHttp && nonFavHttp.length > 0 ? ( + + {nonFavHttp.map(renderHttpItem)} + + ) : null + + const renderPortSection = () => + showPort && nonFavPorts.length > 0 ? ( + + {nonFavPorts.map(renderPortItem)} ) : null @@ -239,32 +382,43 @@ ${portCheckCommands(item).windows} searchBarPlaceholder={ category === 'all' ? t('searchAllPlaceholder') - : category === 'linux' - ? t('searchLinuxPlaceholder') - : category === 'http' - ? t('searchHttpPlaceholder') - : t('searchPortPlaceholder') + : category === 'favorites' + ? t('searchFavoritesPlaceholder') + : category === 'linux' + ? t('searchLinuxPlaceholder') + : category === 'http' + ? t('searchHttpPlaceholder') + : t('searchPortPlaceholder') } searchBarAccessory={ { setCategory(v as DictCategory) - setSearchText('') }} tooltip={t('dropdownTooltip')} > + } - isShowingDetail={true} + isShowingDetail={category !== 'favorites' || totalPinned > 0} > - {sectionOrder.map((sec) => - sec === 'linux' ? renderLinuxSection() : sec === 'http' ? renderHttpSection() : renderPortSection() + {renderFavoritesSection()} + {category === 'favorites' && totalPinned === 0 && !hasQuery && ( + )} + {category !== 'favorites' && + sectionOrder.map((sec) => + sec === 'linux' ? renderLinuxSection() : sec === 'http' ? renderHttpSection() : renderPortSection() + )}
) } diff --git a/extensions/linux-http-dict/src/types.ts b/extensions/linux-http-dict/src/types.ts index a6b8b740..aecaaceb 100644 --- a/extensions/linux-http-dict/src/types.ts +++ b/extensions/linux-http-dict/src/types.ts @@ -1,4 +1,4 @@ -export type DictCategory = 'all' | 'linux' | 'http' | 'port' +export type DictCategory = 'all' | 'favorites' | 'linux' | 'http' | 'port' export type LinuxCommandGroup = 'file' | 'text' | 'system' | 'net' | 'disk' | 'security' diff --git a/extensions/linux-http-dict/tests/commands.test.mjs b/extensions/linux-http-dict/tests/commands.test.mjs index 1e552993..c9f3fec0 100644 --- a/extensions/linux-http-dict/tests/commands.test.mjs +++ b/extensions/linux-http-dict/tests/commands.test.mjs @@ -1,7 +1,7 @@ import assert from 'node:assert/strict' import test from 'node:test' -import { createHost, mount } from '../../shared/test-harness.mjs' -import DefaultCommand, { commands } from '../dist/index.js' +import { createHost, mount, tick } from '../../shared/test-harness.mjs' +import DefaultCommand, { commands, readFavorites } from '../dist/index.js' test('各快捷入口按对应分类查询,并复制该条目的真实内容', async () => { for (const [feature, category, query, id, action, expected] of [ @@ -23,19 +23,18 @@ test('各快捷入口按对应分类查询,并复制该条目的真实内容', } }) -test('从不同字典切换时清除上个字典的搜索词,默认入口仍是命令库', async () => { +test('从不同字典切换时保留当前搜索词,默认入口仍是命令库', async () => { createHost() const view = await mount(DefaultCommand) try { assert.equal(view.tree().props.searchBarAccessory.props.value, 'linux') await view.search('tar') await view.dropdown('http') - assert.equal(view.tree().props.searchText, '') - assert.ok(view.items().length > 1) + assert.equal(view.tree().props.searchText, 'tar') await view.search('502') await view.dropdown('port') - assert.equal(view.tree().props.searchText, '') - assert.ok(view.items().length > 1) + assert.equal(view.tree().props.searchText, '502') + assert.ok(view.item('502')) } finally { view.unmount() } }) @@ -142,8 +141,9 @@ test('跨分类全局搜索:支持「全部」视图与单分类下自动跨 await view.search('6379') assert.ok(view.item('6379'), 'linux 分类下搜 6379 应跨分类命中 Redis 6379') - // 切换至 all 全部视图,应同时展示三大分类条目 + // 切换至 all 全部视图并清空搜索词,应同时展示三大分类条目 await view.dropdown('all') + await view.search('') assert.equal(view.tree().props.searchBarAccessory.props.value, 'all') assert.ok(view.item('cmd-curl')) assert.ok(view.item('502')) @@ -152,3 +152,45 @@ test('跨分类全局搜索:支持「全部」视图与单分类下自动跨 view.unmount() } }) + +test('单条示例独立复制:可直接通过 ActionPanel 复制第 2、3 条命令示例', async () => { + const host = createHost() + const view = await mount(commands['linux-commands']) + try { + await view.search('tar') + const item = view.item('cmd-tar') + const actions = view.actions(item) + const ex3 = actions.find((a) => a.props.title.startsWith('复制示例 3:')) + assert.ok(ex3, '必须存在示例 3 独立复制动作') + await view.run(item, ex3.props.title) + assert.equal(host.clipboard.text, 'tar --exclude=node_modules -zcvf backup.tar.gz ./project') + } finally { + view.unmount() + } +}) + +test('常用收藏置顶与持久化:收藏后排在列表顶部、支持收藏分类筛选与取消收藏', async () => { + const host = createHost() + const view = await mount(DefaultCommand, host) + try { + // 收藏 cmd-awk 并验证持久化和置顶 + const awk = view.item('cmd-awk') + await view.run(awk, '收藏置顶') + await tick() + assert.deepEqual(await readFavorites(), ['linux:cmd-awk']) + assert.equal(view.items()[0].props.id, 'cmd-awk', '收藏条目必须置顶到列表首位') + + // 切到「我的收藏」分类仅显示收藏项 + await view.dropdown('favorites') + assert.equal(view.items().length, 1) + assert.equal(view.items()[0].props.id, 'cmd-awk') + + // 取消收藏后清空 + await view.run(view.item('cmd-awk'), '取消收藏') + await tick() + assert.deepEqual(await readFavorites(), []) + assert.equal(view.items().length, 0) + } finally { + view.unmount() + } +}) diff --git a/extensions/memo/package.json b/extensions/memo/package.json index 2ae8c023..a96b4274 100644 --- a/extensions/memo/package.json +++ b/extensions/memo/package.json @@ -1,6 +1,6 @@ { "name": "@ztools/plugin-memo", - "version": "1.0.0", + "version": "1.0.10", "description": "极简便签速记与备忘录管理", "main": "dist/index.js", "types": "dist/index.d.ts", diff --git a/extensions/memo/plugin.json b/extensions/memo/plugin.json index f3e3e6d7..f4eddd70 100644 --- a/extensions/memo/plugin.json +++ b/extensions/memo/plugin.json @@ -2,7 +2,7 @@ "id": "memo", "name": "便签", "description": "轻量随手记便签,正文支持 Markdown,可加标签,按标题、正文或标签搜索", - "version": "1.0.9", + "version": "1.0.10", "author": "ZTools Team", "entry": "dist/index.js", "icon": "icon.svg", diff --git a/extensions/memo/src/i18n.ts b/extensions/memo/src/i18n.ts index 9e27ab6e..50db3884 100644 --- a/extensions/memo/src/i18n.ts +++ b/extensions/memo/src/i18n.ts @@ -69,7 +69,26 @@ export const t = createTranslator( emptyTitle: '还没有便签', createWithQuerySubtitle: '按回车用这段文字作为标题新建', emptySubtitle: '按回车新建第一条便签', - sectionTitle: '便签({filtered}/{total})' + sectionTitle: '便签({filtered}/{total})', + tagDropdownTooltip: '按标签筛选便签', + tagFilterAll: '全部标签', + tagFilterPinned: '仅看置顶', + tagFilterPrefix: '#{tag}', + createFromClipboardAction: '剪贴板一键新建', + clipboardEmptyError: '剪贴板为空,无法新建便签', + clipboardReadFailedTitle: '读取剪贴板失败', + createdFromClipboardToast: '已从剪贴板新建便签', + exportMarkdownAction: '导出为 Markdown', + exportDialogTitle: '导出便签为 Markdown', + exportDialogFilter: 'Markdown 文件|md', + exportHostUnsupported: '当前客户端不支持文件导出,请升级 ZTools', + exportFailedTitle: '导出失败', + exportSuccessToast: '已导出 Markdown 文件', + metaTagsTitle: '标签', + metaStatsTitle: '字数 / 行数', + metaStatsValue: '{chars} 字 · {lines} 行', + metaUpdatedTitle: '最近更新', + metaCreatedTitle: '创建时间' }, 'en-US': { untitledMemo: 'Untitled Note', @@ -138,7 +157,26 @@ export const t = createTranslator( emptyTitle: 'No notes yet', createWithQuerySubtitle: 'Press Enter to create a note with this title', emptySubtitle: 'Press Enter to create your first note', - sectionTitle: 'Notes ({filtered}/{total})' + sectionTitle: 'Notes ({filtered}/{total})', + tagDropdownTooltip: 'Filter notes by tag', + tagFilterAll: 'All Tags', + tagFilterPinned: 'Pinned Only', + tagFilterPrefix: '#{tag}', + createFromClipboardAction: 'New from Clipboard', + clipboardEmptyError: 'Clipboard is empty', + clipboardReadFailedTitle: 'Failed to read clipboard', + createdFromClipboardToast: 'Created note from clipboard', + exportMarkdownAction: 'Export as Markdown', + exportDialogTitle: 'Export Note as Markdown', + exportDialogFilter: 'Markdown Files|md', + exportHostUnsupported: 'File export is not supported in this ZTools version', + exportFailedTitle: 'Export failed', + exportSuccessToast: 'Exported Markdown file', + metaTagsTitle: 'Tags', + metaStatsTitle: 'Words / Lines', + metaStatsValue: '{chars} chars · {lines} lines', + metaUpdatedTitle: 'Updated', + metaCreatedTitle: 'Created' } }, { defaultLocale: 'en-US' } diff --git a/extensions/memo/src/index.ts b/extensions/memo/src/index.ts index 4b2f0c64..66d3f51e 100644 --- a/extensions/memo/src/index.ts +++ b/extensions/memo/src/index.ts @@ -21,15 +21,76 @@ import { applyMemoMutation, isWritableMemoStore, filterMemos, + extractAllTags, + parseMemoTags, + buildClipboardMemoDraft, + countMemoStats, + buildMemoExportFilename, + formatMemoMarkdown, sanitizeStoredMemos, readLegacyMemos, readLegacyNotes, formatListDate, MEMOS_STORAGE_KEY, + TAG_FILTER_ALL, + TAG_FILTER_PINNED, type MemoItem, type MemoMutation } from './logic.js' +interface HostBridge { + transport?: { + methods?: Record< + string, + (request: { messageId: string; params: Record }) => Promise<{ + success?: boolean + data?: unknown + error?: { message?: string } + }> + > + } +} + +let hostSeq = 0 +async function callHostMethod(method: string, params: Record): Promise { + const root = globalThis as unknown as { window?: { __ztoolsElectron?: HostBridge }; __ztoolsElectron?: HostBridge } + const fn = root.window?.__ztoolsElectron?.transport?.methods?.[method] ?? root.__ztoolsElectron?.transport?.methods?.[method] + if (typeof fn !== 'function') throw new Error(t('exportHostUnsupported')) + const reply = await fn({ messageId: `memo_${Date.now()}_${++hostSeq}`, params }) + if (!reply || reply.success !== true) { + throw new Error(t('exportFailedTitle')) + } + return reply.data as T +} + +export interface MarkdownExportTransport { + showSaveDialog: (params: { title: string; defaultName: string; filters: string }) => Promise<{ canceled?: boolean; filePath?: string }> + writeFile: (params: { path: string; content: string; encoding: 'utf8' }) => Promise +} + +export async function exportMemoToMarkdown( + memo: MemoItem, + transport: MarkdownExportTransport = { + showSaveDialog: (params) => callHostMethod<{ canceled?: boolean; filePath?: string }>('window_show_save_dialog', params), + writeFile: (params) => callHostMethod('filesystem_write_file', params) + } +): Promise<{ status: 'saved'; filePath: string } | { status: 'canceled' }> { + const picked = await transport.showSaveDialog({ + title: t('exportDialogTitle'), + defaultName: buildMemoExportFilename(memo.title), + filters: t('exportDialogFilter') + }) + if (!picked || picked.canceled || !picked.filePath) { + return { status: 'canceled' } + } + await transport.writeFile({ + path: picked.filePath, + content: formatMemoMarkdown(memo), + encoding: 'utf8' + }) + return { status: 'saved', filePath: picked.filePath } +} + /** 读取失败时的状态:resettable 表示读回的原值可以先备份再重新开始(读取直接报错时拿不到原值,只能重试) */ interface LoadError { message: string @@ -86,6 +147,7 @@ export function MemoForm({ memo, initialTitle = '', onSave }: { memo?: MemoItem; export default function MemoCommand() { useLocale() const [searchText, setSearchText] = useState('') + const [selectedTag, setSelectedTag] = useState(TAG_FILTER_ALL) const [memos, setMemos] = useState([]) const [loading, setLoading] = useState(true) const [loadError, setLoadError] = useState(undefined) @@ -296,7 +358,45 @@ export default function MemoCommand() { await showToast(Toast.Style.Success, successTitle) } - const filtered = filterMemos(memos, searchText) + // 从当前剪贴板一键新建便签;空剪贴板或读取失败如实提示 + const createFromClipboard = async () => { + let clipText: string | undefined + try { + clipText = await Clipboard.readText() + } catch (err: unknown) { + await showToast(Toast.Style.Failure, t('clipboardReadFailedTitle'), err instanceof Error ? err.message : String(err)) + return + } + const draft = buildClipboardMemoDraft(clipText ?? '') + if (!draft) { + await showToast(Toast.Style.Failure, t('clipboardReadFailedTitle'), t('clipboardEmptyError')) + return + } + const initialTag = + selectedTag !== TAG_FILTER_ALL && selectedTag !== TAG_FILTER_PINNED ? selectedTag : '' + const ok = await commit({ type: 'create', item: createMemo([], draft.title, draft.content, initialTag)[0] }) + if (ok) await showToast(Toast.Style.Success, t('createdFromClipboardToast')) + } + + // 导出单条便签为 .md 文件 + const exportMemoMarkdown = async (memo: MemoItem) => { + try { + const res = await exportMemoToMarkdown(memo) + if (res.status === 'saved') { + await showToast(Toast.Style.Success, t('exportSuccessToast'), res.filePath) + } + } catch (err: unknown) { + await showToast(Toast.Style.Failure, t('exportFailedTitle'), err instanceof Error ? err.message : String(err)) + } + } + + const allTags = extractAllTags(memos) + const effectiveTag = + selectedTag === TAG_FILTER_ALL || selectedTag === TAG_FILTER_PINNED || allTags.includes(selectedTag) + ? selectedTag + : TAG_FILTER_ALL + + const filtered = filterMemos(memos, searchText, effectiveTag) const query = searchText.trim() const globalActions = ActionPanel({ title: t('panelMemoTitle') }, [ @@ -304,8 +404,31 @@ export default function MemoCommand() { ]) const items = filtered.length > 0 - ? filtered.map((item) => - List.Item({ + ? filtered.map((item) => { + const tags = parseMemoTags(item.tag) + const stats = countMemoStats(item.content) + const metadataChildren = [ + ...(tags.length > 0 + ? [ + List.Item.Detail.Metadata.TagList({ + title: t('metaTagsTitle'), + children: tags.map((tag) => List.Item.Detail.Metadata.TagList.Item({ key: tag, text: `#${tag}` })) + }) + ] + : []), + List.Item.Detail.Metadata.Label({ + title: t('metaStatsTitle'), + text: t('metaStatsValue', { chars: stats.chars, lines: stats.lines }) + }), + ...(item.updateTime > 0 + ? [List.Item.Detail.Metadata.Label({ title: t('metaUpdatedTitle'), text: formatListDate(item.updateTime) })] + : []), + ...(item.createTime > 0 + ? [List.Item.Detail.Metadata.Label({ title: t('metaCreatedTitle'), text: formatListDate(item.createTime) })] + : []) + ] + + return List.Item({ id: item.id, title: item.title, subtitle: item.tag || undefined, @@ -314,18 +437,22 @@ export default function MemoCommand() { ...(item.pinned ? [{ tag: t('pinnedTag') }] : []), ...(item.updateTime > 0 ? [{ text: formatListDate(item.updateTime) }] : []) ], - detail: List.Item.Detail({ markdown: item.content || t('emptyContentMarkdown') }), + detail: List.Item.Detail({ + markdown: item.content || t('emptyContentMarkdown'), + metadata: List.Item.Detail.Metadata({}, metadataChildren) + }), actions: ActionPanel({ title: item.title }, [ Action({ title: t('copyContentAction'), icon: Icon.Clipboard, onAction: () => copyText(item.content, t('noContentError'), t('copiedContentToast')) }), Action({ title: t('pasteContentAction'), icon: Icon.ArrowRight, shortcut: { modifiers: ['ctrl'], key: 'return' }, onAction: () => pasteText(item.content, t('noContentError'), t('pastedContentToast')) }), Action({ title: item.pinned ? t('unpinMemoAction') : t('pinMemoAction'), icon: Icon.Pin, shortcut: { modifiers: ['ctrl'], key: 'p' }, onAction: () => togglePin(item) }), Action({ title: t('editMemoAction'), icon: Icon.Pencil, shortcut: { modifiers: ['ctrl'], key: 'e' }, onAction: () => openEdit(item) }), + Action({ title: t('exportMarkdownAction'), icon: Icon.Download, shortcut: { modifiers: ['cmd', 'shift'], key: 'm' }, onAction: () => exportMemoMarkdown(item) }), // 「新建便签」只放在 List 级:客户端会以「全局操作」附在每条便签的动作后面,这里不再重复 Action({ title: t('copyTitleAction'), icon: Icon.Clipboard, onAction: () => copyText(item.title, t('noTitleError'), t('copiedTitleToast')) }), Action({ title: t('deleteMemoAction'), icon: Icon.Trash, style: Action.Style.Destructive, shortcut: { modifiers: ['ctrl'], key: 'backspace' }, onAction: () => remove(item) }) ]) }) - ) + }) : [ List.Item({ id: 'empty', @@ -337,12 +464,28 @@ export default function MemoCommand() { }) ] + const tagDropdownItems = [ + List.Dropdown.Item({ value: TAG_FILTER_ALL, title: t('tagFilterAll'), icon: Icon.Tag }), + List.Dropdown.Item({ value: TAG_FILTER_PINNED, title: t('tagFilterPinned'), icon: Icon.Pin }), + ...allTags.map((tag) => + List.Dropdown.Item({ value: tag, title: t('tagFilterPrefix', { tag }), icon: Icon.Tag }) + ) + ] + return List({ isLoading: loading, isShowingDetail: filtered.length > 0, searchBarPlaceholder: t('searchPlaceholder'), searchText, onSearchTextChange: setSearchText, + searchBarAccessory: List.Dropdown( + { + tooltip: t('tagDropdownTooltip'), + value: effectiveTag, + onChange: setSelectedTag + }, + tagDropdownItems + ), filterBar: { actions: [ { @@ -352,6 +495,13 @@ export default function MemoCommand() { icon: Icon.Plus, style: 'primary', onAction: () => openCreate(query) + }, + { + id: 'create-from-clipboard', + label: t('createFromClipboardAction'), + title: t('createFromClipboardAction'), + icon: Icon.Clipboard, + onAction: createFromClipboard } ] }, diff --git a/extensions/memo/src/logic.ts b/extensions/memo/src/logic.ts index 5b546e71..38691fcc 100644 --- a/extensions/memo/src/logic.ts +++ b/extensions/memo/src/logic.ts @@ -66,14 +66,111 @@ export function deleteMemo(items: MemoItem[], id: string): MemoItem[] { return items.filter(item => item.id !== id) } +export const TAG_FILTER_ALL = '__all__' +export const TAG_FILTER_PINNED = '__pinned__' + +/** + * 解析空格、中英文逗号、顿号或分号分隔的多标签,去除前导 # 并去重 + */ +export function parseMemoTags(rawTag: string): string[] { + if (!rawTag || typeof rawTag !== 'string') return [] + const seen = new Set() + const result: string[] = [] + for (const part of rawTag.split(/[\s,,、;;]+/)) { + const cleaned = part.replace(/^#+/, '').trim() + if (cleaned && !seen.has(cleaned)) { + seen.add(cleaned) + result.push(cleaned) + } + } + return result +} + +/** + * 从已有便签动态聚合所有标签(按出现频次降序,同频按字典序) + */ +export function extractAllTags(items: MemoItem[]): string[] { + const counts = new Map() + for (const item of items) { + for (const tag of parseMemoTags(item.tag)) { + counts.set(tag, (counts.get(tag) ?? 0) + 1) + } + } + return [...counts.entries()] + .sort((a, b) => (b[1] !== a[1] ? b[1] - a[1] : a[0].localeCompare(b[0]))) + .map(([tag]) => tag) +} + +/** + * 从剪贴板文本提取首行作为标题(去除 Markdown 标题前缀并限制长度),全文作为正文 + */ +export function buildClipboardMemoDraft(clipText: string): { title: string; content: string } | null { + const normalized = clipText.replace(/\r\n/g, '\n').trim() + if (!normalized) return null + const firstLine = normalized + .split('\n') + .map(line => line.trim()) + .find(line => line.length > 0) ?? '' + const cleanFirstLine = firstLine.replace(/^#+\s*/, '').trim() + const title = cleanFirstLine.length > 48 ? `${cleanFirstLine.slice(0, 48)}…` : (cleanFirstLine || t('untitledMemo')) + return { title, content: normalized } +} + +/** + * 计算正文真实字数与行数 + */ +export function countMemoStats(content: string): { chars: number; lines: number } { + const trimmed = content.trim() + if (!trimmed) return { chars: 0, lines: 0 } + return { + chars: trimmed.replace(/\s+/g, '').length, + lines: trimmed.split(/\r?\n/).length + } +} + +/** + * 构建导出的 .md 文件安全文件名 + */ +export function buildMemoExportFilename(title: string): string { + const base = (title || '') + .trim() + .replace(/[\\/:*?"<>|]/g, '_') + .replace(/\s+/g, ' ') + .slice(0, 60) + .trim() + return `${base || 'memo'}.md` +} + +/** + * 生成标准 Markdown 导出文本 + */ +export function formatMemoMarkdown(memo: MemoItem): string { + const tags = parseMemoTags(memo.tag) + const lines: string[] = [`# ${memo.title || t('untitledMemo')}`] + if (tags.length > 0) { + lines.push('', `> ${tags.map(tag => `#${tag}`).join(' ')}`) + } + if (memo.content.trim()) { + lines.push('', memo.content.trim()) + } + lines.push('') + return lines.join('\n') +} + /** - * 按标题、正文、标签检索;置顶便签排在最前,其余按最近更新倒序 + * 按标题、正文、标签与顶栏标签筛选;置顶便签排在最前,其余按最近更新倒序 */ -export function filterMemos(items: MemoItem[], query: string): MemoItem[] { +export function filterMemos(items: MemoItem[], query: string, selectedTag: string = TAG_FILTER_ALL): MemoItem[] { const q = (query || '').trim().toLowerCase() + const byTag = + selectedTag === TAG_FILTER_PINNED + ? items.filter(m => Boolean(m.pinned)) + : selectedTag && selectedTag !== TAG_FILTER_ALL + ? items.filter(m => parseMemoTags(m.tag).includes(selectedTag)) + : items const list = q - ? items.filter(m => m.title.toLowerCase().includes(q) || m.content.toLowerCase().includes(q) || m.tag.toLowerCase().includes(q)) - : items + ? byTag.filter(m => m.title.toLowerCase().includes(q) || m.content.toLowerCase().includes(q) || m.tag.toLowerCase().includes(q)) + : byTag return [...list].sort((a, b) => { const pinDiff = Number(Boolean(b.pinned)) - Number(Boolean(a.pinned)) if (pinDiff !== 0) return pinDiff diff --git a/extensions/memo/tests/index.test.mjs b/extensions/memo/tests/index.test.mjs index d34e091d..d4951b1a 100644 --- a/extensions/memo/tests/index.test.mjs +++ b/extensions/memo/tests/index.test.mjs @@ -2,7 +2,7 @@ import test from 'node:test' import assert from 'node:assert/strict' import { getDeclarativeBridge } from '@ztools/declarative-ui' import { createHost, mount, mountPushed, tick } from '../../shared/test-harness.mjs' -import MemoCommand from '../dist/index.js' +import MemoCommand, { exportMemoToMarkdown } from '../dist/index.js' import { readLegacyMemos, readLegacyNotes, sanitizeStoredMemos, MEMOS_STORAGE_KEY, LEGACY_LOCALSTORAGE_KEY, LEGACY_NOTES_LOCALSTORAGE_KEY, createMemo } from '../dist/logic.js' const host = createHost() @@ -375,3 +375,114 @@ test('直接粘贴正文回前台:调用 Clipboard.paste,空正文或宿主 view.unmount() } }) + +test('顶栏动态标签筛选与多标签解析:支持按聚合标签与置顶过滤,零假数据', async () => { + seed([ + { id: 'm1', title: '评审纪要', content: '## 议题\n- 项1', tag: '会议, 项目A', pinned: true, createTime: 1000, updateTime: 2000 }, + { id: 'm2', title: '排查命令', content: 'ss -tulpn', tag: '#运维 #MySQL', createTime: 1000, updateTime: 1500 } + ]) + const view = await mount(MemoCommand) + await tick() + const dropdown = view.tree().props.searchBarAccessory + assert.ok(dropdown, '顶栏必须包含标签筛选下拉框') + const optionValues = dropdown.children.map((c) => c.props.value) + assert.ok(optionValues.includes('__all__')) + assert.ok(optionValues.includes('__pinned__')) + assert.ok(optionValues.includes('项目A')) + assert.ok(optionValues.includes('运维')) + + await view.dropdown('项目A') + assert.deepEqual(view.items().map((i) => i.props.id), ['m1']) + const detailStr = JSON.stringify(view.item('m1').props.detail) + assert.match(detailStr, /## 议题/) + assert.match(detailStr, /#项目A/) + + await view.dropdown('__pinned__') + assert.deepEqual(view.items().map((i) => i.props.id), ['m1']) + + await view.dropdown('__all__') + assert.equal(view.items().length, 2) + view.unmount() +}) + +test('剪贴板一键新建:真实读取剪贴板保存便签;剪贴板为空或报错时如实提示', async () => { + const view = await mount(MemoCommand) + await tick() + const clipBtn = view.tree().props.filterBar.actions.find((a) => a.id === 'create-from-clipboard') + assert.ok(clipBtn, '顶栏必须提供「剪贴板一键新建」按钮') + + // 空剪贴板如实报错且不写入 + host.clipboard.text = ' ' + await clipBtn.onAction() + await tick() + assert.equal(host.lastToast().title, '读取剪贴板失败') + assert.equal(host.storage.has(MEMOS_STORAGE_KEY), false) + + // 有真实剪贴板内容时一键创建 + host.clipboard.text = '# 周会要点\n- 完成标签筛选\n- 完成 Markdown 导出' + await clipBtn.onAction() + await tick() + assert.equal(host.lastToast().title, '已从剪贴板新建便签') + const saved = stored() + assert.equal(saved.length, 1) + assert.equal(saved[0].title, '周会要点') + assert.match(saved[0].content, /完成 Markdown 导出/) + view.unmount() +}) + +test('导出为 Markdown:真实落盘校验文件内容,取消不创建文件,写入失败与无宿主能力如实报错', async () => { + const fs = await import('node:fs') + const os = await import('node:os') + const path = await import('node:path') + const memo = { id: 'exp-1', title: '发布清单/v1', content: '- [x] 测试通过', tag: '发布 项目A', createTime: 1000, updateTime: 2000 } + seed([memo]) + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ztools-memo-export-')) + try { + const outPath = path.join(tmpDir, 'export.md') + let capturedDefaultName = '' + const res = await exportMemoToMarkdown(memo, { + showSaveDialog: async (params) => { + capturedDefaultName = params.defaultName + return { canceled: false, filePath: outPath } + }, + writeFile: async (params) => { + fs.writeFileSync(params.path, params.content, 'utf8') + } + }) + assert.equal(capturedDefaultName, '发布清单_v1.md') + assert.deepEqual(res, { status: 'saved', filePath: outPath }) + const content = fs.readFileSync(outPath, 'utf8') + assert.match(content, /^# 发布清单\/v1/) + assert.match(content, /#发布 #项目A/) + assert.match(content, /- \[x\] 测试通过/) + + // 用户取消保存对话框:不写入也不报错 + const cancelPath = path.join(tmpDir, 'canceled.md') + const canceled = await exportMemoToMarkdown(memo, { + showSaveDialog: async () => ({ canceled: true }), + writeFile: async (params) => { + fs.writeFileSync(params.path, params.content, 'utf8') + } + }) + assert.deepEqual(canceled, { status: 'canceled' }) + assert.equal(fs.existsSync(cancelPath), false) + + // 写入失败如实抛错 + await assert.rejects( + exportMemoToMarkdown(memo, { + showSaveDialog: async () => ({ canceled: false, filePath: path.join(tmpDir, 'fail.md') }), + writeFile: async () => { throw new Error('权限不足') } + }), + /权限不足/ + ) + + // UI 动作面板具备「导出为 Markdown」,无真实文件宿主时点击如实提示失败 + const view = await mount(MemoCommand) + await tick() + await view.run(view.item('exp-1'), '导出为 Markdown') + assert.equal(host.lastToast().title, '导出失败') + view.unmount() + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }) + } +}) diff --git a/extensions/memo/tests/review-fixes.test.mjs b/extensions/memo/tests/review-fixes.test.mjs index 02bb47be..9b6f787f 100644 --- a/extensions/memo/tests/review-fixes.test.mjs +++ b/extensions/memo/tests/review-fixes.test.mjs @@ -30,7 +30,7 @@ test('单条便签的动作不再重复 List 级的「新建便签」;空状 seed([createMemo([], '标题', '正文')[0]]) const view = await mount(MemoCommand) const itemTitles = view.actions(view.items()[0]).map((a) => a.props.title) - assert.deepEqual(itemTitles, ['复制正文', '直接粘贴正文回前台', '置顶便签', '编辑便签', '复制标题', '删除便签']) + assert.deepEqual(itemTitles, ['复制正文', '直接粘贴正文回前台', '置顶便签', '编辑便签', '导出为 Markdown', '复制标题', '删除便签']) assert.deepEqual(view.actions(null).map((a) => a.props.title), ['新建便签']) await view.search('没有匹配') assert.equal(view.item('empty').props.actions, undefined) diff --git a/extensions/mock-data/plugin.json b/extensions/mock-data/plugin.json index 1ff580e0..41a87e40 100644 --- a/extensions/mock-data/plugin.json +++ b/extensions/mock-data/plugin.json @@ -1,7 +1,7 @@ { "id": "mock-data", "name": "测试数据生成", - "version": "1.0.5", + "version": "1.0.6", "minAppVersion": "1.1.8.0", "description": "一键生成符合国家校验位算法的虚拟测试用18位身份证号、手机号、统一社会信用代码、银行卡号及批量JSON测试数据", "author": "ZTools Team", diff --git a/extensions/mock-data/src/i18n.ts b/extensions/mock-data/src/i18n.ts index a11ae183..0d614f87 100644 --- a/extensions/mock-data/src/i18n.ts +++ b/extensions/mock-data/src/i18n.ts @@ -48,6 +48,36 @@ const rawT = createTranslator( personCompanyFormat: 'UTF-8 中文', personCompanyBreakdown: '- **测试联系人**:`{fullName}`({gender})\n- **测试企业名**:`{company}`', personCompanyNote: '从固定词表随机组合中文姓名与企业名称,没有校验规则,可能与真实人名或企业重名。', + nameLabel: '中文测试姓名', + nameCategory: '身份资料', + nameStandard: '中文常见姓名', + nameFormat: 'UTF-8 中文', + nameBreakdown: '- **测试姓名**:`{fullName}`\n- **对应性别**:{gender}', + nameNote: '从常用姓氏与名字词表随机组合,无校验位,可能与真实姓名重合,适合独立填写表单姓名字段。', + companyLabel: '中国企业主体名称', + companyCategory: '企业工商', + companyStandard: '企业命名规范', + companyFormat: 'UTF-8 中文', + companyBreakdown: '- **企业全称**:`{company}`\n- **行业形态**:科技 / 信息服务类测试主体', + companyNote: '由城市、字号与行业后缀组合生成,无校验位,可能与真实企业重名,适合独立填写发票与注册企业字段。', + emailLabel: '电子邮箱地址(RFC 2606)', + emailCategory: '通信联络', + emailStandard: 'RFC 5322 / 2606', + emailFormat: '保留测试域名', + emailBreakdown: '- **完整邮箱**:`{email}`\n- **邮箱域名**:`{domain}`(RFC 2606 保留测试域,不会发往真实收件箱)', + emailNote: '严格使用 RFC 2606 保留的 example.com / example.org / example.net 域名,可通过前端邮箱正则校验且避免误投真实邮箱。', + uuidLabel: '随机 UUID v4', + uuidCategory: '网络开发', + uuidStandard: 'RFC 4122 v4', + uuidFormat: '36位标准十六进制', + uuidBreakdown: '- **UUID 值**:`{uuid}`\n- **版本号 / 变体**:Version `4` · Variant `RFC 4122`', + uuidNote: '第 13 位固定为 4,第 17 位固定为 8/9/a/b 之一,符合 RFC 4122 UUID v4 结构规范,适合主键、追踪 ID 与接口联调。', + ipv4Label: '测试用 IPv4 地址(RFC 5737)', + ipv4Category: '网络开发', + ipv4Standard: 'RFC 5737 / 1918', + ipv4Format: '点分十进制', + ipv4Breakdown: '- **IPv4 地址**:`{ip}`\n- **所属网段**:`{cidr}`(文档与测试保留网段)', + ipv4Note: '仅从 RFC 5737 文档测试网段(192.0.2.0/24、198.51.100.0/24、203.0.113.0/24)生成,避免命中真实公网主机。', companyFull: '深圳{word}科技有限公司', batchCompanyFull: '北京{word}信息科技有限公司', batchAddressFull: '{areaName}科技园创新大厦 {floor} 层', @@ -56,12 +86,17 @@ const rawT = createTranslator( givenNamesF: '清欢,知微,若汐,语桐,舒窈,南乔,云舒,映雪', companyWords: '极客云创,星河智算,量子奇点,深海矩阵,未来引擎,凌云数科', regeneratedToast: '已重新生成一批测试数据', - searchPlaceholderSingle: '搜索测试数据类型(如:身份证、统一社会信用代码、银行卡、手机号)...', - searchPlaceholderBatch: '输入批量生成的 JSON 记录条数(默认 10 条,支持 1~500)...', + searchPlaceholderSingle: '搜索测试字段(身份证、手机号、邮箱、UUID、IPv4、银行卡、姓名、企业)...', + searchPlaceholderBatch: '输入批量生成条数(默认 10 条,支持 1~500)...', modeTooltip: '切换测试数据生成模式', - modeSingle: '单项极速生成(带校验位)', - modeBatch: '批量用户 JSON 数组', + modeSingle: '单项极速生成(9 类常用字段)', + modeBatch: '批量造数(JSON / CSV / SQL)', singleSectionTitle: '随机生成的测试数据(回车即复制)', + singleSummaryText: '已生成 {count} 项独立测试字段 · 支持回车复制与一键换一批', + batchSummaryText: '当前批量条数:{count} 条 · 支持 JSON / CSV / SQL 格式', + btnRegenerate: '换一批', + btnSwitchToBatch: '批量造数', + btnSwitchToSingle: '单项速取', detailBreakdownHeading: '#### 编码结构拆解', detailAlgorithmHeading: '#### 校验位算法说明', detailDisclaimerWithCheck: '*声明:本数据在本机随机合成,只保证格式与校验位正确,可能与真实号码、人名或企业重合,仅供研发联调测试,不得用于实名认证或冒用他人身份。*', @@ -72,19 +107,28 @@ const rawT = createTranslator( metaCheckFormatOnly: '无校验位,仅保证格式', metaFormat: '格式特征', copyValueAction: '复制该测试数值', + pasteValueAction: '直接粘贴到前台窗口', regenerateSingleAction: '换一批全新的合规测试数据', copyKvJsonAction: '复制键值对 JSON', batchSectionTitle: '批量结构化 Mock 用户数组', batchItemTitle: '批量模拟用户列表 JSON({count} 条完整记录)', + batchCsvTitle: '批量模拟用户表格 CSV({count} 条完整记录)', + batchSqlTitle: '批量模拟用户 SQL INSERT({count} 条完整记录)', batchInvalidSubtitle: '条数须为 1~500 的整数,已按默认 10 条生成', - batchValidSubtitle: '含姓名、18位身份证、手机号、信用代码、Luhn 银行卡', + batchValidSubtitle: '含姓名、18位身份证、手机号、邮箱、信用代码、Luhn 银行卡', + batchCsvSubtitle: '含表头与标准转义,可直接导入 Excel 或数据库工具', + batchSqlSubtitle: '标准 SQL INSERT 语句,可直接写入测试表 mock_users', batchInvalidTag: '条数无效', batchReadyTag: '{count} 条已就绪', batchPreviewTitle: '### 批量 Mock JSON 数组预览({count} 条)', + batchCsvPreviewTitle: '### 批量 Mock CSV 预览({count} 条)', + batchSqlPreviewTitle: '### 批量 Mock SQL INSERT 预览({count} 条)', metaBatchCount: '生成条数', metaBatchCountValue: '{count} 条', - metaJsonSize: 'JSON 体积', + metaJsonSize: '输出体积', copyBatchJsonAction: '复制完整 JSON 数组', + copyBatchCsvAction: '复制完整 CSV 文本', + copyBatchSqlAction: '复制完整 SQL 语句', regenerateBatchAction: '重新随机生成一批' }, 'en-US': { @@ -133,6 +177,36 @@ const rawT = createTranslator( personCompanyFormat: 'UTF-8 Text', personCompanyBreakdown: '- **Test Contact**: `{fullName}` ({gender})\n- **Test Company**: `{company}`', personCompanyNote: 'Randomly combined from fixed word lists without checksum rules; may collide with real names or companies.', + nameLabel: 'Test Contact Name', + nameCategory: 'Identity', + nameStandard: 'Common Name', + nameFormat: 'UTF-8 Text', + nameBreakdown: '- **Full Name**: `{fullName}`\n- **Gender**: {gender}', + nameNote: 'Randomly combined from common surname and given-name lists without checksum; ready for standalone form name inputs.', + companyLabel: 'Test Company Name', + companyCategory: 'Enterprise', + companyStandard: 'Enterprise Naming', + companyFormat: 'UTF-8 Text', + companyBreakdown: '- **Company Name**: `{company}`\n- **Industry**: Technology / InfoTech test entity', + companyNote: 'Combined from city, brand word, and suffix without checksum; ready for standalone invoice or registration fields.', + emailLabel: 'Email Address (RFC 2606)', + emailCategory: 'Telecom', + emailStandard: 'RFC 5322 / 2606', + emailFormat: 'Reserved test domain', + emailBreakdown: '- **Email**: `{email}`\n- **Domain**: `{domain}` (RFC 2606 reserved test domain; never routes to real mailboxes)', + emailNote: 'Uses RFC 2606 reserved domains (example.com / example.org / example.net) to pass validation safely without hitting real addresses.', + uuidLabel: 'Random UUID v4', + uuidCategory: 'Network & Dev', + uuidStandard: 'RFC 4122 v4', + uuidFormat: '36-char hex UUID', + uuidBreakdown: '- **UUID**: `{uuid}`\n- **Version / Variant**: Version `4` · Variant `RFC 4122`', + uuidNote: 'Follows RFC 4122 UUID v4 bit layout (version 4, variant 8/9/a/b) for primary keys, trace IDs, and API mocks.', + ipv4Label: 'Test IPv4 Address (RFC 5737)', + ipv4Category: 'Network & Dev', + ipv4Standard: 'RFC 5737 / 1918', + ipv4Format: 'Dotted decimal', + ipv4Breakdown: '- **IPv4 Address**: `{ip}`\n- **Reserved Block**: `{cidr}` (documentation & test range)', + ipv4Note: 'Generated exclusively from RFC 5737 documentation blocks (192.0.2.0/24, 198.51.100.0/24, 203.0.113.0/24) to avoid real public hosts.', companyFull: 'Shenzhen {word} Tech Co., Ltd.', batchCompanyFull: 'Beijing {word} InfoTech Co., Ltd.', batchAddressFull: 'Innovation Bldg, Tech Park, {areaName}, Floor {floor}', @@ -141,12 +215,17 @@ const rawT = createTranslator( givenNamesF: 'Qing huan,Zhiwei,Ruoxi,Yutong,Shuyao,Nanqiao,Yunshu,Yingxue', companyWords: 'GeekCloud,StarCompute,QuantumSingularity,DeepMatrix,FutureEngine,CloudTech', regeneratedToast: 'Generated new batch of mock data', - searchPlaceholderSingle: 'Search mock data types (e.g. ID card, credit code, bank card, mobile)...', - searchPlaceholderBatch: 'Enter batch JSON record count (default 10, range 1–500)...', + searchPlaceholderSingle: 'Search fields (ID card, mobile, email, UUID, IPv4, bank card, name, company)...', + searchPlaceholderBatch: 'Enter batch record count (default 10, range 1–500)...', modeTooltip: 'Switch mock data mode', - modeSingle: 'Quick Single Item (with Checksum)', - modeBatch: 'Batch User JSON Array', + modeSingle: 'Quick Single Item (9 Common Fields)', + modeBatch: 'Batch Generation (JSON / CSV / SQL)', singleSectionTitle: 'Generated Mock Data (Press Enter to Copy)', + singleSummaryText: '{count} standalone test fields ready · Enter to copy or regenerate', + batchSummaryText: 'Batch size: {count} [[count:record|records]] · JSON / CSV / SQL', + btnRegenerate: 'Regenerate', + btnSwitchToBatch: 'Batch Mode', + btnSwitchToSingle: 'Single Mode', detailBreakdownHeading: '#### Structure Breakdown', detailAlgorithmHeading: '#### Checksum Algorithm', detailDisclaimerWithCheck: '*Disclaimer: Locally synthesized test data; only format and checksum are guaranteed valid. May coincide with real numbers, names, or companies—for dev/testing only.*', @@ -157,19 +236,28 @@ const rawT = createTranslator( metaCheckFormatOnly: 'No checksum; format only', metaFormat: 'Format', copyValueAction: 'Copy Value', + pasteValueAction: 'Paste to Active App', regenerateSingleAction: 'Regenerate Mock Data', copyKvJsonAction: 'Copy Key-Value JSON', batchSectionTitle: 'Batch Structured Mock User Array', batchItemTitle: 'Batch Mock User List JSON ({count} [[count:record|records]])', + batchCsvTitle: 'Batch Mock User Table CSV ({count} [[count:record|records]])', + batchSqlTitle: 'Batch Mock User SQL INSERT ({count} [[count:record|records]])', batchInvalidSubtitle: 'Count must be an integer between 1 and 500; defaulted to 10', - batchValidSubtitle: 'Includes name, 18-digit ID, mobile, credit code, and Luhn card', + batchValidSubtitle: 'Includes name, 18-digit ID, mobile, email, credit code, and Luhn card', + batchCsvSubtitle: 'Includes header row and CSV escaping for spreadsheets or DB import', + batchSqlSubtitle: 'Standard SQL INSERT statements for mock_users table', batchInvalidTag: 'Invalid Count', batchReadyTag: '{count} Ready', batchPreviewTitle: '### Batch Mock JSON Preview ({count} [[count:record|records]])', + batchCsvPreviewTitle: '### Batch Mock CSV Preview ({count} [[count:record|records]])', + batchSqlPreviewTitle: '### Batch Mock SQL INSERT Preview ({count} [[count:record|records]])', metaBatchCount: 'Record Count', metaBatchCountValue: '{count} [[count:record|records]]', - metaJsonSize: 'JSON Size', + metaJsonSize: 'Output Size', copyBatchJsonAction: 'Copy Full JSON Array', + copyBatchCsvAction: 'Copy Full CSV Text', + copyBatchSqlAction: 'Copy Full SQL Statements', regenerateBatchAction: 'Regenerate Batch' } } diff --git a/extensions/mock-data/src/index.tsx b/extensions/mock-data/src/index.tsx index b6653e61..fd982093 100644 --- a/extensions/mock-data/src/index.tsx +++ b/extensions/mock-data/src/index.tsx @@ -11,6 +11,8 @@ import React, { useState } from '@ztools/declarative-ui' import { + formatBatchUsersCsv, + formatBatchUsersSql, generateMockBatchUsers, generateMockSingleItems } from './mock-service.js' @@ -66,6 +68,16 @@ export function MockDataCommand(props: MockDataCommandProps = {}) { [batchUsers] ) + const batchCsvString = useMemo( + () => formatBatchUsersCsv(batchUsers), + [batchUsers] + ) + + const batchSqlString = useMemo( + () => formatBatchUsersSql(batchUsers), + [batchUsers] + ) + const handleRegenerate = async () => { setSeed((prev) => prev + 101) await showToast({ @@ -93,6 +105,29 @@ export function MockDataCommand(props: MockDataCommandProps = {}) { } + filterBar={{ + summaryText: + tab === 'single' + ? t('singleSummaryText', { count: singleItems.length }) + : t('batchSummaryText', { count: batchUsers.length }), + actions: [ + { + id: 'regenerate', + title: t('btnRegenerate'), + icon: Icon.ArrowClockwise, + onAction: () => { void handleRegenerate() } + }, + { + id: 'switch-mode', + title: tab === 'single' ? t('btnSwitchToBatch') : t('btnSwitchToSingle'), + icon: tab === 'single' ? Icon.Code : Icon.Document, + onAction: () => { + setTab(tab === 'single' ? 'batch' : 'single') + setSearchText('') + } + } + ] + }} isShowingDetail={true} > {tab === 'single' && ( @@ -133,6 +168,7 @@ ${item.hasCheckDigit ? t('detailDisclaimerWithCheck') : t('detailDisclaimerForma actions={ + } /> + + + + + } + /> + } + actions={ + + + + + } + /> + + + + + } + /> + } + actions={ + + + + + } + /> )} diff --git a/extensions/mock-data/src/mock-service.ts b/extensions/mock-data/src/mock-service.ts index 5b7c11be..6852cf77 100644 --- a/extensions/mock-data/src/mock-service.ts +++ b/extensions/mock-data/src/mock-service.ts @@ -255,6 +255,113 @@ export function generateValidMobilePhone(seed?: number): string { return `${prefix}${tail}` } +const EMAIL_HANDLES = [ + 'alex.chen', + 'lin.dev', + 'qa.shen', + 'zhou.ops', + 'lu.test', + 'gu.api', + 'su.mock', + 'xu.data', + 'tang.ui', + 'song.lab' +] +const RFC2606_DOMAINS = ['example.com', 'example.org', 'example.net'] +const RFC5737_BLOCKS = [ + { prefix: '192.0.2', cidr: '192.0.2.0/24' }, + { prefix: '198.51.100', cidr: '198.51.100.0/24' }, + { prefix: '203.0.113', cidr: '203.0.113.0/24' } +] + +export function generateValidEmail(seed?: number): { email: string; domain: string } { + const rand = createPrng(seed) + const handle = EMAIL_HANDLES[Math.floor(rand() * EMAIL_HANDLES.length)]! + const num = 100 + Math.floor(rand() * 900) + const domain = RFC2606_DOMAINS[Math.floor(rand() * RFC2606_DOMAINS.length)]! + return { email: `${handle}.${num}@${domain}`, domain } +} + +export function generateValidUuidV4(seed?: number): string { + const rand = createPrng(seed) + const bytes: number[] = [] + for (let i = 0; i < 16; i++) { + bytes.push(Math.floor(rand() * 256)) + } + bytes[6] = (bytes[6]! & 0x0f) | 0x40 + bytes[8] = (bytes[8]! & 0x3f) | 0x80 + const hex = bytes.map((b) => b.toString(16).padStart(2, '0')).join('') + return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}` +} + +export function generateValidIpv4(seed?: number): { ip: string; cidr: string } { + const rand = createPrng(seed) + const block = RFC5737_BLOCKS[Math.floor(rand() * RFC5737_BLOCKS.length)]! + const host = 1 + Math.floor(rand() * 254) + return { ip: `${block.prefix}.${host}`, cidr: block.cidr } +} + +function escapeCsvCell(value: string | number): string { + const text = String(value) + if (/[",\r\n]/.test(text)) { + return `"${text.replace(/"/g, '""')}"` + } + return text +} + +export function formatBatchUsersCsv(records: MockUserRecord[]): string { + const headers: (keyof MockUserRecord)[] = [ + 'id', + 'name', + 'gender', + 'age', + 'idCard', + 'phone', + 'email', + 'companyName', + 'creditCode', + 'bankCard', + 'address', + 'createdAt' + ] + const lines = [headers.join(',')] + for (const row of records) { + lines.push(headers.map((key) => escapeCsvCell(row[key])).join(',')) + } + return lines.join('\n') +} + +function escapeSqlValue(value: string | number): string { + if (typeof value === 'number') return String(value) + return `'${value.replace(/'/g, "''")}'` +} + +export function formatBatchUsersSql(records: MockUserRecord[]): string { + const columns = + 'id, name, gender, age, id_card, phone, email, company_name, credit_code, bank_card, address, created_at' + return records + .map( + (r) => + `INSERT INTO mock_users (${columns}) VALUES (${[ + r.id, + r.name, + r.gender, + r.age, + r.idCard, + r.phone, + r.email, + r.companyName, + r.creditCode, + r.bankCard, + r.address, + r.createdAt + ] + .map(escapeSqlValue) + .join(', ')});` + ) + .join('\n') +} + export function generateMockSingleItems(seed?: number): MockSingleItem[] { const rand = createPrng(seed) const s1 = Math.floor(rand() * 1_000_000) @@ -262,6 +369,9 @@ export function generateMockSingleItems(seed?: number): MockSingleItem[] { const creditCode = generateValidCreditCode(s1 + 17) const bankInfo = generateValidBankCard(s1 + 31) const phone = generateValidMobilePhone(s1 + 53) + const emailInfo = generateValidEmail(s1 + 71) + const uuid = generateValidUuidV4(s1 + 89) + const ipv4Info = generateValidIpv4(s1 + 113) const surnames = t('surnames').split(',') const givenNamesM = t('givenNamesM').split(',') const givenNamesF = t('givenNamesF').split(',') @@ -295,6 +405,65 @@ export function generateMockSingleItems(seed?: number): MockSingleItem[] { algorithmNote: t('idCardNote'), hasCheckDigit: true }, + { + id: 'mock-mobile-phone', + fieldKey: 'phone', + label: t('mobileLabel'), + value: phone, + category: t('mobileCategory'), + standard: t('mobileStandard'), + formatType: t('mobileFormat'), + breakdownMarkdown: t('mobileBreakdown', { + prefix: phone.slice(0, 3), + phone + }), + algorithmNote: t('mobileNote'), + hasCheckDigit: false + }, + { + id: 'mock-email', + fieldKey: 'email', + label: t('emailLabel'), + value: emailInfo.email, + category: t('emailCategory'), + standard: t('emailStandard'), + formatType: t('emailFormat'), + breakdownMarkdown: t('emailBreakdown', { + email: emailInfo.email, + domain: emailInfo.domain + }), + algorithmNote: t('emailNote'), + hasCheckDigit: false + }, + { + id: 'mock-name', + fieldKey: 'name', + label: t('nameLabel'), + value: fullName, + category: t('nameCategory'), + standard: t('nameStandard'), + formatType: t('nameFormat'), + breakdownMarkdown: t('nameBreakdown', { + fullName, + gender: genderLabel + }), + algorithmNote: t('nameNote'), + hasCheckDigit: false + }, + { + id: 'mock-company', + fieldKey: 'companyName', + label: t('companyLabel'), + value: company, + category: t('companyCategory'), + standard: t('companyStandard'), + formatType: t('companyFormat'), + breakdownMarkdown: t('companyBreakdown', { + company + }), + algorithmNote: t('companyNote'), + hasCheckDigit: false + }, { id: 'mock-credit-code', fieldKey: 'creditCode', @@ -328,36 +497,33 @@ export function generateMockSingleItems(seed?: number): MockSingleItem[] { hasCheckDigit: true }, { - id: 'mock-mobile-phone', - fieldKey: 'phone', - label: t('mobileLabel'), - value: phone, - category: t('mobileCategory'), - standard: t('mobileStandard'), - formatType: t('mobileFormat'), - breakdownMarkdown: t('mobileBreakdown', { - prefix: phone.slice(0, 3), - phone + id: 'mock-uuid', + fieldKey: 'uuid', + label: t('uuidLabel'), + value: uuid, + category: t('uuidCategory'), + standard: t('uuidStandard'), + formatType: t('uuidFormat'), + breakdownMarkdown: t('uuidBreakdown', { + uuid }), - algorithmNote: t('mobileNote'), + algorithmNote: t('uuidNote'), hasCheckDigit: false }, { - id: 'mock-person-company', - fieldKey: 'nameAndCompany', - label: t('personCompanyLabel'), - value: `${fullName} · ${company}`, - category: t('personCompanyCategory'), - standard: t('personCompanyStandard'), - formatType: t('personCompanyFormat'), - breakdownMarkdown: t('personCompanyBreakdown', { - fullName, - gender: genderLabel, - company + id: 'mock-ipv4', + fieldKey: 'ipv4', + label: t('ipv4Label'), + value: ipv4Info.ip, + category: t('ipv4Category'), + standard: t('ipv4Standard'), + formatType: t('ipv4Format'), + breakdownMarkdown: t('ipv4Breakdown', { + ip: ipv4Info.ip, + cidr: ipv4Info.cidr }), - algorithmNote: t('personCompanyNote'), - hasCheckDigit: false, - jsonValue: { name: fullName, companyName: company } + algorithmNote: t('ipv4Note'), + hasCheckDigit: false } ] } diff --git a/extensions/mock-data/src/types.ts b/extensions/mock-data/src/types.ts index 0b905a80..974da902 100644 --- a/extensions/mock-data/src/types.ts +++ b/extensions/mock-data/src/types.ts @@ -1,4 +1,5 @@ export type MockDataTab = 'single' | 'batch' +export type MockBatchFormat = 'json' | 'csv' | 'sql' export interface MockSingleItem { id: string diff --git a/extensions/mock-data/tests/mock-data.test.mjs b/extensions/mock-data/tests/mock-data.test.mjs index f03eb5be..8410c4a4 100644 --- a/extensions/mock-data/tests/mock-data.test.mjs +++ b/extensions/mock-data/tests/mock-data.test.mjs @@ -42,7 +42,7 @@ test('批量快捷入口直接生成JSON,数量输入和重新生成后的复 } await view.dropdown('single') assert.equal(view.tree().props.searchText, '') - assert.equal(view.items().length, 5) + assert.equal(view.items().length, 9) } finally { view.unmount() } }) @@ -77,21 +77,58 @@ test('[异常] 批量条数无效时如实提示已按 10 条生成,有效条 } finally { view.unmount() } }) -test('单项:无校验位的数据不宣称算法合规,声明不否认与真实信息重合;姓名企业 JSON 分字段', async () => { +test('单项:9 类常用字段独立生成(含邮箱/UUID/IPv4/姓名/企业),支持一键重新生成与批量 CSV/SQL', async () => { const host = createHost() const view = await mount(() => MockDataCommand({ initialTab: 'single', initialSeed: 42 })) try { + const ids = view.items().map((i) => i.props.id) + assert.deepEqual(ids, [ + 'mock-id-card', + 'mock-mobile-phone', + 'mock-email', + 'mock-name', + 'mock-company', + 'mock-credit-code', + 'mock-bank-card', + 'mock-uuid', + 'mock-ipv4' + ]) const status = id => JSON.stringify(view.item(id), (k, v) => (typeof v === 'function' ? undefined : v)) .match(/"title":"校验状态","text":"([^"]+)"/)?.[1] assert.equal(status('mock-id-card'), '校验位按标准算法计算') assert.equal(status('mock-mobile-phone'), '无校验位,仅保证格式') - assert.equal(status('mock-person-company'), '无校验位,仅保证格式') + assert.equal(status('mock-name'), '无校验位,仅保证格式') + assert.equal(status('mock-company'), '无校验位,仅保证格式') assert.doesNotMatch(view.text(), /不对应任何真实|100%/) assert.match(view.item('mock-mobile-phone').props.detail.props.markdown, /可能与真实号码/) - await view.run(view.item('mock-person-company'), '复制键值对 JSON') - const json = JSON.parse(host.clipboard.text) - assert.deepEqual(Object.keys(json), ['name', 'companyName']) - assert.ok(!json.companyName.includes(json.name)) + + // 验证邮箱(RFC 2606)、UUID v4(RFC 4122)、IPv4(RFC 5737)格式 + assert.match(view.item('mock-email').props.subtitle, /@example\.(com|org|net)$/) + assert.match(view.item('mock-uuid').props.subtitle, /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/) + assert.match(view.item('mock-ipv4').props.subtitle, /^(192\.0\.2|198\.51\.100|203\.0\.113)\.\d{1,3}$/) + + // 姓名与企业为独立条目,不再拼接在同一值里 + await view.run(view.item('mock-name'), '复制键值对 JSON') + const nameJson = JSON.parse(host.clipboard.text) + assert.deepEqual(Object.keys(nameJson), ['name']) + await view.run(view.item('mock-company'), '复制键值对 JSON') + const companyJson = JSON.parse(host.clipboard.text) + assert.deepEqual(Object.keys(companyJson), ['companyName']) + assert.ok(!companyJson.companyName.includes(nameJson.name)) + + // filterBar 一键重新生成生效 + const prevUuid = view.item('mock-uuid').props.subtitle + await view.tree().props.filterBar.actions.find((a) => a.id === 'regenerate').onAction() + assert.notEqual(view.item('mock-uuid').props.subtitle, prevUuid) + + // filterBar 一键切换批量模式并验证 CSV / SQL 输出 + await view.tree().props.filterBar.actions.find((a) => a.id === 'switch-mode').onAction() + await view.search('2') + await view.run(view.item('batch-users-csv'), '复制完整 CSV 文本') + assert.equal(host.clipboard.text.split('\n').length, 3) + await view.run(view.item('batch-users-sql'), '复制完整 SQL 语句') + assert.equal(host.clipboard.text.split('\n').length, 2) + assert.match(host.clipboard.text, /^INSERT INTO mock_users \(/) } finally { view.unmount() } }) diff --git a/extensions/monitor-control/plugin.json b/extensions/monitor-control/plugin.json index 258f7830..2c9e82f6 100644 --- a/extensions/monitor-control/plugin.json +++ b/extensions/monitor-control/plugin.json @@ -1,7 +1,7 @@ { "id": "monitor-control", "name": "屏幕亮度与控制", - "version": "1.0.8", + "version": "1.0.9", "description": "读取显示器真实硬件状态,调节受支持的亮度与对比度;支持多屏统一亮度与系统熄屏命令", "author": "ZTools Team", "entry": "dist/index.js", diff --git a/extensions/monitor-control/src/i18n.ts b/extensions/monitor-control/src/i18n.ts index ad92eb77..84db6f5f 100644 --- a/extensions/monitor-control/src/i18n.ts +++ b/extensions/monitor-control/src/i18n.ts @@ -35,13 +35,38 @@ const rawT = createTranslator({ allBrightnessAction: '统一亮度…', primaryDisplay: '主显示器', externalDisplay: '扩展屏', - brightnessUnread: '亮度未读取', + brightnessUnread: '未读取亮度', brightnessPercent: '亮度 {value}%', contrastPercent: '对比度 {value}%', + contrastUnread: '不支持 / 未读取', brightnessUpAction: '亮度增加 10%', brightnessDownAction: '亮度降低 10%', setBrightnessAction: '设置亮度…', setContrastAction: '设置对比度…', + presetSectionTitle: '快捷亮度预设', + presetLabel: '设为 {value}%({hint})', + presetEyeCare: '护眼', + presetIndoor: '室内', + presetOffice: '办公', + presetMax: '最亮', + channelAppleTag: '硬件 · Apple 原生', + channelWmiTag: '硬件 · WMI 背光', + channelDdcciTag: '硬件 · DDC/CI', + channelUnsupportedTag: '无 DDC/CI 通道', + channelAppleDesc: '硬件调光通道(Apple 原生背光接口,无软件遮罩)', + channelWmiDesc: '硬件调光通道(Windows WMI 笔记本背光,无软件遮罩)', + channelDdcciDesc: '硬件调光通道(外接屏 DDC/CI 硬件直调,无软件遮罩)', + channelUnsupportedDesc: '无硬件调光通道(不支持 DDC/CI,当前未启用软件调光)', + metaChannel: '调光通道', + metaDisplayType: '屏幕类型', + metaResolution: '分辨率', + metaBrightness: '当前亮度读回', + metaContrast: '当前对比度读回', + builtinLabel: '内置屏幕', + externalLabel: '外接显示器', + detailHardwareNote: '所有亮度与对比度数值均直接来自硬件通道真实读回;支持 `Ctrl/Cmd + ← / →` 以 `±10%` 步进调节。', + detailUnsupportedNote: '当前显示器未开放 DDC/CI 硬件调光通道,且当前版本未启用软件调光降级,因此**不编造任何亮度百分比**。若为外接屏,请在显示器 OSD 菜单中开启 DDC/CI 后点击「重新扫描」。', + detailReasonHeading: '宿主硬件说明', emptyUnconfirmedTitle: '显示器状态未确认', emptyNoMatchTitle: '没有匹配的显示器', emptyUnconfirmedSubtitle: '请使用上方重新扫描;读取失败不会当作没有显示器', @@ -95,10 +120,35 @@ const rawT = createTranslator({ brightnessUnread: 'Brightness N/A', brightnessPercent: 'Brightness {value}%', contrastPercent: 'Contrast {value}%', + contrastUnread: 'Unsupported / N/A', brightnessUpAction: 'Brightness +10%', brightnessDownAction: 'Brightness -10%', setBrightnessAction: 'Set Brightness…', setContrastAction: 'Set Contrast…', + presetSectionTitle: 'Quick Brightness Presets', + presetLabel: 'Set {value}% ({hint})', + presetEyeCare: 'Eye Care', + presetIndoor: 'Indoor', + presetOffice: 'Office', + presetMax: 'Max', + channelAppleTag: 'HW · Apple Native', + channelWmiTag: 'HW · WMI Backlight', + channelDdcciTag: 'HW · DDC/CI', + channelUnsupportedTag: 'No DDC/CI', + channelAppleDesc: 'Hardware dimming channel (Apple native backlight; no software overlay)', + channelWmiDesc: 'Hardware dimming channel (Windows WMI backlight; no software overlay)', + channelDdcciDesc: 'Hardware dimming channel (External DDC/CI direct control; no software overlay)', + channelUnsupportedDesc: 'No hardware dimming channel (DDC/CI unsupported; software dimming not active)', + metaChannel: 'Dimming Channel', + metaDisplayType: 'Display Type', + metaResolution: 'Resolution', + metaBrightness: 'Hardware Brightness', + metaContrast: 'Hardware Contrast', + builtinLabel: 'Built-in Display', + externalLabel: 'External Display', + detailHardwareNote: 'Brightness and contrast are read directly from the hardware channel. Use `Ctrl/Cmd + Left / Right` for `±10%` step adjustments.', + detailUnsupportedNote: 'This display does not expose a DDC/CI hardware channel and software dimming is not active, so **no brightness value is fabricated**. For external monitors, enable DDC/CI in the monitor OSD menu and click Rescan.', + detailReasonHeading: 'Host Hardware Note', emptyUnconfirmedTitle: 'Display status unconfirmed', emptyNoMatchTitle: 'No matching displays', emptyUnconfirmedSubtitle: 'Use Rescan above; read failures are not treated as zero displays', diff --git a/extensions/monitor-control/src/mac-command.tsx b/extensions/monitor-control/src/mac-command.tsx index 0e884115..c185e835 100644 --- a/extensions/monitor-control/src/mac-command.tsx +++ b/extensions/monitor-control/src/mac-command.tsx @@ -1,8 +1,23 @@ -import React, { Action, ActionPanel, Form, Icon, List, Toast, showToast, useEffect, useLocale, useNavigation, useRef, useState } from '@ztools/declarative-ui' +import React, { Action, ActionPanel, Color, Form, Icon, List, Toast, showToast, useEffect, useLocale, useNavigation, useRef, useState } from '@ztools/declarative-ui' import { scanDisplays, setDisplays, type DisplaySnapshot, type MacDisplay } from './mac-service.js' import { t } from './i18n.js' const message = (e: unknown) => e instanceof Error ? e.message : String(e) + +const BRIGHTNESS_PRESETS = [ + { value: 20, hintKey: 'presetEyeCare' as const }, + { value: 50, hintKey: 'presetIndoor' as const }, + { value: 80, hintKey: 'presetOffice' as const }, + { value: 100, hintKey: 'presetMax' as const } +] + +function channelInfo(protocol: string): { tag: string; desc: string; isHardware: boolean } { + if (protocol === 'apple') return { tag: t('channelAppleTag'), desc: t('channelAppleDesc'), isHardware: true } + if (protocol === 'wmi') return { tag: t('channelWmiTag'), desc: t('channelWmiDesc'), isHardware: true } + if (protocol === 'ddcci') return { tag: t('channelDdcciTag'), desc: t('channelDdcciDesc'), isHardware: true } + return { tag: t('channelUnsupportedTag'), desc: t('channelUnsupportedDesc'), isHardware: false } +} + function LevelForm({ title, initial, apply }: { title: string; initial: string; apply: (value: number, active: () => boolean) => Promise }) { useLocale() const [value, setValue] = useState(initial), [busy, setBusy] = useState(false), [error, setError] = useState('') @@ -40,10 +55,16 @@ export default function MacMonitorCommand() { useEffect(() => { void perform(async () => { await refresh() }); return () => { alive.current = false } }, []) const change = (ids: string[], control: 'brightness' | 'contrast', value: number, active = () => true) => perform(async () => { if (!snapshot || !active()) throw new Error(t('errRescanRequired')) - try { await setDisplays(snapshot, ids, control, value) } - catch (e) { if (alive.current) setSnapshot(null); throw e } + const verified = await setDisplays(snapshot, ids, control, value) if (!alive.current) return - await refresh() + const updatedMap = new Map(verified.map(c => [c.id, c])) + setSnapshot(prev => prev ? { + ...prev, + displays: prev.displays.map(d => { + const hit = updatedMap.get(d.id) + return hit ? { ...d, [hit.control]: hit.value } : d + }) + } : prev) if (alive.current && active()) await showToast({ style: Toast.Style.Success, title: t('hardwareConfirmedToast') }) }) const edit = (d: MacDisplay, control: 'brightness' | 'contrast') => { if (!guard.current) push( change([d.id], control, value, active)} />) } @@ -53,17 +74,66 @@ export default function MacMonitorCommand() { if (!ids.length) { setStatus(t('noBrightnessDisplays')); return } push( change(ids, 'brightness', value, active)} />) } - const rows = snapshot?.displays.filter(d => (filter === 'all' || (filter === 'builtin' ? d.builtIn : !d.builtIn)) && `${d.name} ${d.width}x${d.height}`.toLowerCase().includes(query.trim().toLowerCase())) || [] - return (filter === 'all' || (filter === 'builtin' ? d.builtIn : !d.builtIn)) && `${d.name} ${d.width}x${d.height} ${d.protocol}`.toLowerCase().includes(query.trim().toLowerCase())) || [] + return 0} isLoading={busy} searchText={query} onSearchTextChange={setQuery} searchBarPlaceholder={t('searchPlaceholder')} searchBarAccessory={} filterBar={{ summaryText: status || t('loadingDisplays'), actions: [{ id: 'refresh', title: t('rescanAction'), onAction: () => perform(async () => { await refresh() }) }, { id: 'all', title: t('allBrightnessAction'), onAction: all }] }}> - {rows.length ? rows.map(d => - {d.canBrightness && { await change([d.id], 'brightness', Math.min(100, Math.round(d.brightness! + 10))) }} />} - {d.canBrightness && { await change([d.id], 'brightness', Math.max(0, Math.round(d.brightness! - 10))) }} />} - {d.canBrightness && edit(d, 'brightness')} />} - {d.canContrast && edit(d, 'contrast')} />} - } />) : } + {rows.length ? rows.map(d => { + const ch = channelInfo(d.protocol) + const brightnessText = d.brightness === undefined ? t('brightnessUnread') : t('brightnessPercent', { value: Math.round(d.brightness) }) + const contrastText = d.contrast === undefined ? t('contrastUnread') : t('contrastPercent', { value: Math.round(d.contrast) }) + const detailMarkdown = [ + `### ${d.name}`, + '', + `**${t('metaChannel')}**:${ch.desc}`, + '', + d.canBrightness || d.canContrast ? t('detailHardwareNote') : t('detailUnsupportedNote'), + ...(d.reason ? ['', `#### ${t('detailReasonHeading')}`, `> ${d.reason}`] : []) + ].join('\n') + + return + + + + + + + + } + /> + } + actions={ + {d.canBrightness && { await change([d.id], 'brightness', Math.min(100, Math.round(d.brightness! + 10))) }} />} + {d.canBrightness && { await change([d.id], 'brightness', Math.max(0, Math.round(d.brightness! - 10))) }} />} + {d.canBrightness && edit(d, 'brightness')} />} + {d.canContrast && edit(d, 'contrast')} />} + {d.canBrightness && ( + + {BRIGHTNESS_PRESETS.map(p => ( + { await change([d.id], 'brightness', p.value) }} + /> + ))} + + )} + {!d.canBrightness && !d.canContrast && ( + { void perform(async () => { await refresh() }) }} /> + )} + } /> + }) : } } diff --git a/extensions/monitor-control/src/mac-service.ts b/extensions/monitor-control/src/mac-service.ts index 5f93624e..4910620d 100644 --- a/extensions/monitor-control/src/mac-service.ts +++ b/extensions/monitor-control/src/mac-service.ts @@ -32,7 +32,14 @@ export async function scanDisplays(): Promise { } return data as unknown as DisplaySnapshot } -export async function setDisplays(snapshot: DisplaySnapshot, ids: string[], control: 'brightness' | 'contrast', value: number) { +export interface VerifiedDisplayChange { + id: string + control: 'brightness' | 'contrast' + value: number + maximum: number +} + +export async function setDisplays(snapshot: DisplaySnapshot, ids: string[], control: 'brightness' | 'contrast', value: number): Promise { if (!percent(value) || ids.length === 0 || ids.length > 16 || new Set(ids).size !== ids.length) throw new Error(t('errSelectDisplayAndRange')) const changes = ids.map(id => { const d = snapshot.displays.find(d => d.id === id), expected = d?.[control] @@ -42,11 +49,14 @@ export async function setDisplays(snapshot: DisplaySnapshot, ids: string[], cont const response = await monitorInvoke('monitor_control', { action: 'set', topology: snapshot.topology, changes }, monitorSetTimeoutMs(changes.length)) if (!Array.isArray(response.changed) || response.changed.length !== changes.length) throw new Error(t('errReceiptIncomplete')) const seen = new Set() + const verified: VerifiedDisplayChange[] = [] for (const c of response.changed) { if (!record(c) || typeof c.id !== 'string' || !ids.includes(c.id) || seen.has(c.id) || c.control !== control || !percent(c.value) || !Number.isSafeInteger(c.maximum) || Number(c.maximum) < 0 || Number(c.maximum) > 65535) throw new Error(t('errReadbackMismatch')) const maximum = Number(c.maximum) const target = maximum ? Math.round(value * maximum / 100) * 100 / maximum : Math.fround(value / 100) * 100 if (Math.abs(c.value - target) > (maximum ? Math.min(2, 10 / maximum) : 0.0001)) throw new Error(t('errHardwareMismatch')) seen.add(c.id) + verified.push({ id: c.id, control, value: c.value, maximum }) } + return verified } diff --git a/extensions/monitor-control/tests/monitor.test.mjs b/extensions/monitor-control/tests/monitor.test.mjs index 183b3392..cf5b6567 100644 --- a/extensions/monitor-control/tests/monitor.test.mjs +++ b/extensions/monitor-control/tests/monitor.test.mjs @@ -27,18 +27,38 @@ async function open() { const v = await mount(Command, host); views.push(v); awa async function form() { const v = await mountPushed(host); views.push(v); return v } const button = (v, id) => v.tree().props.filterBar.actions.find(a => a.id === id).onAction() -test('入口先识别 Mac,再真实读取;布局一不伪造亮度或暴露不支持的对比度', async () => { - const v = await open(); assert.equal(v.tree().props.isShowingDetail, false); assert.equal(v.items().length, 1) - assert.match(v.text(), /亮度 45%/); assert.deepEqual(v.actions(v.item(id)).map(a => a.props.title), ['亮度增加 10%', '亮度降低 10%', '设置亮度…']) +test('入口先识别 Mac,再真实读取;布局一展示硬件调光通道与步进快捷键,不暴露不支持的对比度', async () => { + const v = await open(); assert.equal(v.tree().props.isShowingDetail, true); assert.equal(v.items().length, 1) + assert.match(v.text(), /亮度 45%/); assert.match(v.text(), /硬件 · Apple 原生/) + const actions = v.actions(v.item(id)) + assert.deepEqual(actions.slice(0, 3).map(a => a.props.title), ['亮度增加 10%', '亮度降低 10%', '设置亮度…']) + assert.deepEqual(actions[0].props.shortcut, { modifiers: ['ctrl'], key: 'arrowRight' }) + assert.deepEqual(actions[1].props.shortcut, { modifiers: ['ctrl'], key: 'arrowLeft' }) + assert.ok(!actions.some(a => a.props.title === '设置对比度…')) assert.equal(calls('set').length, 0); assert.ok(!host.ipcCalls.some(([m]) => m === 'dllplugin_call')) assert.deepEqual(v.tree().props.filterBar.actions.map(a => a.id), ['refresh', 'all']) }) -test('Enter 主动作成功后重读实际值,失败清除旧状态并明确提示', async () => { - const v = await open(); await v.run(v.item(id), '亮度增加 10%') +test('Enter 主动作成功后局部读回更新,失败保留列表主视图并明确提示', async () => { + const v = await open(); const listCallsBefore = calls('list').length + await v.run(v.item(id), '亮度增加 10%') assert.equal(calls('set')[0][1].changes[0].expected, display.brightness); assert.equal(calls('set')[0][1].changes[0].value, 55) + assert.equal(calls('list').length, listCallsBefore, '成功后按硬件读回局部更新,不触发全量重扫') assert.match(v.text(), /亮度 55%/); assert.equal(host.lastToast().style, 'SUCCESS') host.ipc.monitor_control = async () => { throw new Error('调节未完成,已核验恢复原值') } - await v.run(v.item(id), '亮度降低 10%'); assert.match(v.text(), /已核验恢复原值/); assert.match(v.item('empty').props.title, /未确认/); assert.equal(host.lastToast().style, 'FAILURE') + await v.run(v.item(id), '亮度降低 10%'); assert.match(v.text(), /已核验恢复原值/) + assert.equal(v.items().length, 1, '单次调节失败保留主视图,不清空显示器列表') + assert.equal(v.item(id).props.id, id) + assert.equal(host.lastToast().style, 'FAILURE') +}) +test('无 DDC/CI 通道时诚实标注并拒绝编造亮度值,提供重新扫描动作', async () => { + displays = [{ ...display, id: second, name: 'HDMI 便携屏', builtIn: false, isPrimary: false, protocol: 'unsupported', canBrightness: false, canContrast: false, brightness: undefined, contrast: undefined, reason: '未检测到 DDC/CI 支持' }] + const v = await open() + const item = v.item(second) + assert.match(v.text(), /无 DDC\/CI 通道/) + assert.match(v.text(), /未读取亮度/) + assert.match(item.props.detail.props.markdown, /不编造任何亮度百分比/) + assert.doesNotMatch(item.props.detail.props.markdown, /亮度 \d+%/) + assert.deepEqual(v.actions(item).map(a => a.props.title), ['重新扫描']) }) test('读取失败与空列表区别展示,平台失败不会调用旧接口', async () => { host.ipc.monitor_control = async () => { throw new Error('组件未构建') } diff --git a/extensions/ocr/package.json b/extensions/ocr/package.json index c55cad83..92c982f0 100644 --- a/extensions/ocr/package.json +++ b/extensions/ocr/package.json @@ -1,6 +1,6 @@ { "name": "@ztools/plugin-ocr", - "version": "1.0.0", + "version": "3.0.10", "description": "在本机识别图片和屏幕截图中的文字,不联网", "main": "dist/index.js", "types": "dist/index.d.ts", diff --git a/extensions/ocr/plugin.json b/extensions/ocr/plugin.json index 340519ce..59675365 100644 --- a/extensions/ocr/plugin.json +++ b/extensions/ocr/plugin.json @@ -2,7 +2,7 @@ "id": "ocr", "name": "文字识别", "description": "框选屏幕、剪贴板或图片里的文字,在本机离线识别(OCR)简体中文、英文、日文、韩文,结果直接复制", - "version": "3.0.9", + "version": "3.0.10", "author": "ZTools Team", "entry": "dist/index.js", "icon": "icon.svg", diff --git a/extensions/ocr/src/i18n.ts b/extensions/ocr/src/i18n.ts index 6a7242b4..a850e889 100644 --- a/extensions/ocr/src/i18n.ts +++ b/extensions/ocr/src/i18n.ts @@ -44,15 +44,32 @@ const rawT = createTranslator({ confirmVolumeMessage: '将读取该磁盘下 5 层以内的文件夹,最多导入 {max} 张图片,可能需要一些时间。', confirmVolumePrimary: '继续导入', errOpenImagePicker: '无法打开选择图片窗口', - actionCaptureRegion: '截图识别', - actionAddImages: '添加图片', + actionCaptureRegion: '截屏识别', + actionAddImages: '选择图片', actionPickFolder: '选择文件夹…', - actionRecognizeClipboard: '识别剪贴板图片', + actionRecognizeClipboard: '读取剪贴板', actionClearResults: '清空识别结果', actionRetry: '重新识别', actionCopyText: '复制文字', - actionRetryCapture: '重新截图识别', - actionRetryClipboard: '重新识别剪贴板图片', + actionCopyMerged: '复制合并段落', + actionCopyOriginal: '复制原文断行', + actionToggleMerge: '切换为合并段落', + actionToggleOriginal: '切换为原文断行', + modeMerged: '合并段落', + modeOriginal: '原文断行', + metaLayoutMode: '排版视图', + metaCharCount: '字数', + metaLineCount: '行数', + metaLineCountDetail: '{current} 行(原文 {original} 行)', + metaSource: '来源', + metaFilePath: '文件路径', + sourceRegion: '截屏识别', + sourceClipboard: '剪贴板图片', + sourceFile: '本地图片', + emptyTitle: '开始离线文字识别', + emptyDescription: '点击上方「截屏识别」「选择图片」「读取剪贴板」,或直接拖入/粘贴图片与文件夹', + actionRetryCapture: '重新截屏识别', + actionRetryClipboard: '重新读取剪贴板', statusQueued: '等待识别', statusRunning: '正在识别', detailFailed: '识别失败:{error}', @@ -121,14 +138,31 @@ const rawT = createTranslator({ confirmVolumePrimary: 'Continue Import', errOpenImagePicker: 'Unable to open image picker', actionCaptureRegion: 'Capture Screen', - actionAddImages: 'Add Images', + actionAddImages: 'Select Images', actionPickFolder: 'Select Folder…', - actionRecognizeClipboard: 'OCR Clipboard', + actionRecognizeClipboard: 'Read Clipboard', actionClearResults: 'Clear Results', actionRetry: 'Re-recognize', actionCopyText: 'Copy Text', + actionCopyMerged: 'Copy Merged Paragraphs', + actionCopyOriginal: 'Copy Original Lines', + actionToggleMerge: 'Switch to Merged Paragraphs', + actionToggleOriginal: 'Switch to Original Lines', + modeMerged: 'Merged Paragraphs', + modeOriginal: 'Original Lines', + metaLayoutMode: 'Text Layout', + metaCharCount: 'Characters', + metaLineCount: 'Lines', + metaLineCountDetail: '{current} [[current:line|lines]] (original {original})', + metaSource: 'Source', + metaFilePath: 'File Path', + sourceRegion: 'Screen Capture', + sourceClipboard: 'Clipboard Image', + sourceFile: 'Local Image', + emptyTitle: 'Start Offline OCR', + emptyDescription: 'Use Capture Screen, Select Images, or Read Clipboard above, or drop/paste images and folders', actionRetryCapture: 'Re-capture Region', - actionRetryClipboard: 'Re-OCR Clipboard', + actionRetryClipboard: 'Re-read Clipboard', statusQueued: 'Queued', statusRunning: 'Recognizing', detailFailed: 'Recognition failed: {error}', diff --git a/extensions/ocr/src/index.ts b/extensions/ocr/src/index.ts index 10488dd3..18e96525 100644 --- a/extensions/ocr/src/index.ts +++ b/extensions/ocr/src/index.ts @@ -24,11 +24,13 @@ import { type OcrLanguage, type OcrOutcome, countCharacters, + countLines, createFileImportTransport, fileNameOf, firstLine, getClientTransport, getOcrLanguages, + mergeOcrParagraphs, notify, pickImageFiles, recognizeClipboardImage, @@ -136,6 +138,7 @@ export function OcrCommand() { const [languageId, setLanguageId] = useState(() => languages[0].id) const language = languages.find(item => item.id === languageId) ?? languages[0] const [entries, setEntries] = useCachedState('entries', []) + const [mergeParagraphs, setMergeParagraphs] = useCachedState('mergeParagraphs', false) const [searchText, setSearchText] = useState('') const [selectedId, setSelectedId] = useState(undefined) const [busy, setBusy] = useState(false) @@ -472,10 +475,23 @@ export function OcrCommand() { setSelectedId(undefined) } + const formatEntryText = (text: string) => (mergeParagraphs ? mergeOcrParagraphs(text) : text) const query = searchText.trim().toLowerCase() const visible = entries.filter(entry => !query || entry.title.toLowerCase().includes(query) || entry.text.toLowerCase().includes(query)) const doneEntries = entries.filter(entry => entry.status === 'done') - const allText = doneEntries.map(entry => (doneEntries.length > 1 ? `${entry.title}\n${entry.text}` : entry.text)).join('\n\n') + const allText = doneEntries + .map(entry => { + const formatted = formatEntryText(entry.text) + return doneEntries.length > 1 ? `${entry.title}\n${formatted}` : formatted + }) + .join('\n\n') + + const toggleParagraphAction = Action({ + title: mergeParagraphs ? t('actionToggleOriginal') : t('actionToggleMerge'), + icon: Icon.Text, + shortcut: { modifiers: ['cmd'], key: 'm' }, + onAction: () => setMergeParagraphs(previous => !previous) + }) const startActionSpecs: Array<[string, Parameters[0]['icon'], Parameters[0]['shortcut'], () => void]> = [ [t('actionCaptureRegion'), Icon.Camera, { modifiers: ['cmd'], key: 'n' }, () => handleRegion()], @@ -486,12 +502,23 @@ export function OcrCommand() { const startActions = startActionSpecs.map(([title, icon, shortcut, onAction]) => Action({ title, icon, shortcut, onAction })) const clearAction = Action({ title: t('actionClearResults'), icon: Icon.Trash, style: Action.Style.Destructive, shortcut: { modifiers: ['cmd', 'shift'], key: 'backspace' }, onAction: handleClear }) - /** 主动作(Enter):成功的复制文字,失败的重新识别 */ + /** 主动作(Enter):成功的复制当前排版文字,失败的重新识别 */ function primaryActions(entry: OcrEntry) { const retryFile = entry.path ? [Action({ title: t('actionRetry'), icon: Icon.ArrowClockwise, shortcut: { modifiers: ['cmd'], key: 'r' }, onAction: () => handleRetry(entry) })] : [] - if (entry.status === 'done') return [Action.CopyToClipboard({ title: t('actionCopyText'), content: entry.text }), ...retryFile] + if (entry.status === 'done') { + const displayText = formatEntryText(entry.text) + const alternateCopy = mergeParagraphs + ? Action.CopyToClipboard({ title: t('actionCopyOriginal'), content: entry.text, shortcut: { modifiers: ['cmd', 'shift'], key: 'm' } }) + : Action.CopyToClipboard({ title: t('actionCopyMerged'), content: mergeOcrParagraphs(entry.text), shortcut: { modifiers: ['cmd', 'shift'], key: 'm' } }) + return [ + Action.CopyToClipboard({ title: mergeParagraphs ? t('actionCopyMerged') : t('actionCopyText'), content: displayText }), + toggleParagraphAction, + alternateCopy, + ...retryFile + ] + } if (entry.status !== 'failed') return [] if (entry.source === 'file') return retryFile return entry.source === 'region' @@ -500,14 +527,32 @@ export function OcrCommand() { } const items = visible.map(entry => { + const displayText = entry.status === 'done' ? formatEntryText(entry.text) : '' const subtitle = entry.status === 'done' - ? firstLine(entry.text) + ? firstLine(displayText) : entry.status === 'failed' ? resolveErrorMessage(entry, t('errRecognizeFailed')) : entry.status === 'queued' ? t('statusQueued') : t('statusRunning') const markdown = entry.status === 'done' - ? textAsMarkdown(entry.text) + ? textAsMarkdown(displayText) : entry.status === 'failed' ? t('detailFailed', { error: resolveErrorMessage(entry, t('detailUnknownReason')) }) : entry.status === 'queued' ? t('detailQueued') : t('detailRunning') + const detailMetadata = entry.status === 'done' + ? Detail.Metadata({ + children: [ + Detail.Metadata.Label({ title: t('metaLayoutMode'), text: mergeParagraphs ? t('modeMerged') : t('modeOriginal') }), + Detail.Metadata.Label({ title: t('metaCharCount'), text: t('charCountText', { count: countCharacters(displayText) }) }), + Detail.Metadata.Label({ + title: t('metaLineCount'), + text: t('metaLineCountDetail', { current: countLines(displayText), original: countLines(entry.text) }) + }), + Detail.Metadata.Label({ + title: t('metaSource'), + text: entry.source === 'region' ? t('sourceRegion') : entry.source === 'clipboard' ? t('sourceClipboard') : t('sourceFile') + }), + ...(entry.path ? [Detail.Metadata.Label({ title: t('metaFilePath'), text: entry.path })] : []) + ] + }) + : undefined const entryActions = [ ...primaryActions(entry), ...(doneEntries.length > 1 @@ -528,9 +573,9 @@ export function OcrCommand() { subtitle, icon: entry.source === 'file' ? Icon.Image : entry.source === 'region' ? Icon.Camera : Icon.Clipboard, accessories: entry.status === 'done' - ? [{ text: t('charCountText', { count: countCharacters(entry.text) }) }] + ? [{ text: t('charCountText', { count: countCharacters(displayText) }) }] : [{ tag: entry.status === 'failed' ? t('tagFailed') : entry.status === 'queued' ? t('tagQueued') : t('tagRunning') }], - detail: Detail({ markdown }), + detail: Detail({ markdown, metadata: detailMetadata }), // 还在识别的条目没有针对它的主动作,Enter 留给开始新的识别 actions: ActionPanel({ children: [ @@ -579,13 +624,23 @@ export function OcrCommand() { summaryText, actions: transport ? [ - { id: 'ocr-region', title: t('actionCaptureRegion'), icon: Icon.Camera, onAction: () => handleRegion() }, - { id: 'ocr-add', title: t('actionAddImages'), icon: Icon.Plus, onAction: handleAddImages } + { id: 'ocr-add', title: t('actionAddImages'), icon: Icon.Plus, onAction: handleAddImages }, + { id: 'ocr-clipboard', title: t('actionRecognizeClipboard'), icon: Icon.Clipboard, onAction: () => handleClipboard() }, + { id: 'ocr-region', title: t('actionCaptureRegion'), icon: Icon.Camera, onAction: () => handleRegion() } ] : [] }, actions: ActionPanel({ children: startActions }), - children: items + children: + items.length > 0 + ? items + : [ + List.EmptyView({ + title: t('emptyTitle'), + description: t('emptyDescription'), + icon: Icon.Image + }) + ] }) } diff --git a/extensions/ocr/src/ocr-service.ts b/extensions/ocr/src/ocr-service.ts index 98569f94..b30048de 100644 --- a/extensions/ocr/src/ocr-service.ts +++ b/extensions/ocr/src/ocr-service.ts @@ -11,9 +11,9 @@ import { extractErrorCode, resolveErrorMessage } from './error-i18n.js' export const getNotInClientMessage = (): string => t('notInClient') /** 文件夹导入和拖入展开支持的图片扩展名与单次上限 */ -export const OCR_IMPORT_EXTENSIONS = ['.png', '.jpg', '.jpeg', '.webp', '.bmp', '.gif', '.tiff'] as const +export const OCR_IMPORT_EXTENSIONS = ['.png', '.jpg', '.jpeg', '.heic', '.tif', '.tiff', '.webp', '.bmp', '.gif'] as const export const OCR_IMPORT_MAX_FILES = 100 -export const OCR_IMPORT_SUPPORTED_TEXT = 'PNG / JPG / WebP / BMP / GIF / TIFF' +export const OCR_IMPORT_SUPPORTED_TEXT = 'PNG / JPG / HEIC / TIFF / WebP / BMP / GIF' export const OCR_IMPORT_RULES: FileImportRules = { extensions: OCR_IMPORT_EXTENSIONS, maxFiles: OCR_IMPORT_MAX_FILES @@ -218,6 +218,50 @@ export function countCharacters(text: string): number { return text.replace(/\s/g, '').length } +/** 统计非空文本行数 */ +export function countLines(text: string): number { + const normalized = text.replace(/\r\n?/g, '\n').trim() + if (!normalized) return 0 + return normalized.split('\n').length +} + +const CJK_OR_FULLWIDTH_RE = /[\u3000-\u303F\u3040-\u30FF\u3400-\u4DBF\u4E00-\u9FFF\uAC00-\uD7AF\uF900-\uFAFF\uFF00-\uFFEF]/ + +/** + * 智能合并 OCR 断行段落: + * - 保留空行作为自然段落分隔; + * - 段落内中文/日文/韩文及全角标点无缝衔接,英文断词连字符自动合并,其他情况以单空格连接。 + */ +export function mergeOcrParagraphs(text: string): string { + const normalized = text.replace(/\r\n?/g, '\n').trim() + if (!normalized) return '' + const paragraphs = normalized.split(/\n[ \t]*\n+/) + return paragraphs + .map(paragraph => { + const lines = paragraph + .split('\n') + .map(line => line.trim()) + .filter(Boolean) + if (lines.length === 0) return '' + let merged = lines[0]! + for (let i = 1; i < lines.length; i += 1) { + const next = lines[i]! + const prevLast = merged[merged.length - 1] ?? '' + const nextFirst = next[0] ?? '' + if (merged.endsWith('-') && /[A-Za-z]/.test(nextFirst) && merged.length > 1 && /[A-Za-z]/.test(merged[merged.length - 2] ?? '')) { + merged = `${merged.slice(0, -1)}${next}` + } else if (CJK_OR_FULLWIDTH_RE.test(prevLast) || CJK_OR_FULLWIDTH_RE.test(nextFirst)) { + merged = `${merged}${next}` + } else { + merged = `${merged} ${next}` + } + } + return merged + }) + .filter(Boolean) + .join('\n\n') +} + /** 识别文字放进 Markdown 代码块原样显示,避免换行被合并;文字里的反引号围栏加长 */ export function textAsMarkdown(text: string): string { const longestFence = Math.max(2, ...Array.from(text.matchAll(/`+/g), match => match[0].length)) diff --git a/extensions/ocr/tests/ocr.host.test.mjs b/extensions/ocr/tests/ocr.host.test.mjs deleted file mode 100644 index aa1e27f4..00000000 --- a/extensions/ocr/tests/ocr.host.test.mjs +++ /dev/null @@ -1,648 +0,0 @@ -// 文字识别:宿主调用契约(语言、超时、取消与失败如实返回)、无界面命令与工作台交互 -import test from 'node:test' -import assert from 'node:assert/strict' -import fs from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import { Cache, setRuntimeLocale } from '@ztools/declarative-ui' -import { createHost, installDirectoryHost, mount, tick } from '../../shared/test-harness.mjs' -import * as ocr from '../dist/index.js' - -const host = createHost() -// 识别结果放在 useCachedState 的内存缓存里(重新打开插件仍可看到),每个用例前清空 -test.beforeEach(() => { host.reset(); new Cache({ namespace: '@raycast/utils.useCachedPromise' }).clear() }) - -// 客户端 image_ocr 直接返回识别服务的结果对象 -const hostResult = rec => ({ ...rec }) -const recognized = text => hostResult({ ok: true, success: true, text, lines: text.split('\n'), engine: 'Apple Vision' }) -const failed = (error, extra = {}) => hostResult({ ok: false, success: false, error, ...extra }) - -function ocrCalls() { - return host.ipcCalls.filter(([method]) => method === 'image_ocr').map(([, params]) => params) -} - -/** 记录每次调用携带的超时(测试宿主只记录 params) */ -function captureTimeouts() { - const methods = globalThis.__ztoolsElectron.transport.methods - const timeouts = [] - globalThis.__ztoolsElectron = { transport: { methods: new Proxy({}, { get: (_t, name) => req => { timeouts.push([name, req.timeoutMs]); return methods[name](req) } }) } } - return { timeouts, restore: () => { globalThis.__ztoolsElectron = { transport: { methods } } } } -} - -test('截图识别:识别成功后复制并发系统通知,按保存的语言识别,等待时长足够用户框选', async () => { - host.storage.set('language', JSON.stringify('ja')) - host.ipc.image_ocr = () => recognized('第一行\n第二行') - host.ipc.system_notify = () => ({ success: true }) - const probe = captureTimeouts() - try { - const message = await ocr.ocrRegion() - assert.equal(message, '已复制 6 个字') - assert.equal(host.clipboard.text, '第一行\n第二行') - assert.deepEqual(ocrCalls(), [{ action: 'captureRegion', lang: 'ja-JP', restoreWindow: false }]) - const notice = host.ipcCalls.find(([method]) => method === 'system_notify')[1] - assert.equal(notice.title, '已复制识别的文字') - assert.equal(notice.message, '第一行') - const [, timeout] = probe.timeouts.find(([name]) => name === 'image_ocr') - assert.ok(timeout >= 120_000, `框选超时 ${timeout} 太短`) - } finally { probe.restore() } -}) - -test('截图识别:用户取消不报错也不改剪贴板;识别失败抛出宿主原因;通知失败不影响结果', async () => { - host.clipboard.text = '原有内容' - host.ipc.image_ocr = () => failed('已取消框选', { canceled: true }) - assert.equal(await ocr.ocrRegion(), '已取消框选') - assert.equal(host.clipboard.text, '原有内容') - - host.ipc.image_ocr = () => failed('没有屏幕录制权限,请在系统设置的「隐私与安全性」中允许 ZTools 录制屏幕') - await assert.rejects(ocr.ocrRegion(), /没有屏幕录制权限/) - assert.equal(host.clipboard.text, '原有内容') - - host.ipc.image_ocr = () => failed('没有识别到文字', { empty: true }) - await assert.rejects(ocr.ocrRegion(), /没有识别到文字/) - - host.ipc.image_ocr = () => recognized('ABC') - host.ipc.system_notify = () => { throw new Error('通知被系统关闭') } - assert.equal(await ocr.ocrRegion(), '已复制 3 个字') - assert.equal(host.clipboard.text, 'ABC') -}) - -test('识别剪贴板图片:没有图片、宿主异常都如实报错;成功复制结果', async () => { - host.ipc.image_ocr = () => failed('剪贴板里没有图片') - await assert.rejects(ocr.ocrClipboard(), /剪贴板里没有图片/) - host.ipc.image_ocr = () => { throw Object.assign(new Error('请求超时'), { code: 'REQUEST_TIMEOUT' }) } - await assert.rejects(ocr.ocrClipboard(), /请求超时/) - host.ipc.image_ocr = () => recognized('Invoice 2026') - assert.equal(await ocr.ocrClipboard(), '已复制 11 个字') - assert.deepEqual(ocrCalls().at(-1), { action: 'recognizeClipboard', lang: 'zh-Hans-CN' }) -}) - -test('不在客户端中运行时明确报错,不返回示例数据', async () => { - const saved = globalThis.__ztoolsElectron - delete globalThis.__ztoolsElectron - try { - await assert.rejects(ocr.ocrRegion(), /需要在 ZTools 客户端中使用/) - const view = await mount(ocr.OcrCommand) - assert.equal(view.tree().props.filterBar.summaryText, '需要在 ZTools 客户端中使用') - assert.equal(view.tree().props.filterBar.actions.length, 0) - assert.equal(view.items().length, 0) - view.unmount() - } finally { globalThis.__ztoolsElectron = saved } -}) - -test('工作台:添加多张图片逐张识别,失败的标出原因,结果可看全文、复制、搜索', async () => { - host.ipc.window_show_open_dialog = () => ({ canceled: false, filePaths: [{ path: '/Users/me/a.png' }, { path: '/Users/me/b.heic' }] }) - host.ipc.image_ocr = params => params.path === '/Users/me/a.png' ? recognized('合同编号 A-17\n金额 300 元') : failed('无法读取图片') - const view = await mount(ocr.OcrCommand) - assert.equal(view.items().length, 0) - await view.run(null, '添加图片') - await tick(10) - - const dialog = host.ipcCalls.find(([method]) => method === 'window_show_open_dialog')[1] - assert.deepEqual(dialog.properties, ['openFile', 'multiSelections']) - assert.match(dialog.filters, /\*\.heic/) - assert.deepEqual(ocrCalls().map(call => call.path), ['/Users/me/a.png', '/Users/me/b.heic']) - - const ok = view.item(item => item.props.title === 'a.png') - assert.equal(ok.props.subtitle, '合同编号 A-17') - assert.deepEqual(ok.props.accessories, [{ text: '14 字' }]) - assert.match(ok.props.detail.props.markdown, /^```text\n合同编号 A-17\n金额 300 元\n```$/) - const bad = view.item(item => item.props.title === 'b.heic') - assert.equal(bad.props.subtitle, '无法读取图片') - assert.deepEqual(bad.props.accessories, [{ tag: '失败' }]) - assert.match(view.tree().props.filterBar.summaryText, /^1 条识别结果/) - assert.equal(host.lastToast().title, '1 张识别成功,1 张失败') - - await view.run(ok, '复制文字') - assert.equal(host.clipboard.text, '合同编号 A-17\n金额 300 元') - assert.ok(!view.actions(bad).some(action => action.props.title === '复制文字'), '失败的条目不能提供复制') - - await view.search('300 元') - assert.deepEqual(view.items().map(item => item.props.title), ['a.png']) - view.unmount() -}) - -test('工作台:取消选择图片不调用识别;对话框打不开如实提示', async () => { - host.ipc.window_show_open_dialog = () => ({ canceled: true }) - host.ipc.image_ocr = () => recognized('不该被调用') - const view = await mount(ocr.OcrCommand) - await view.run(null, '添加图片') - assert.equal(ocrCalls().length, 0) - assert.equal(view.items().length, 0) - - host.ipc.window_show_open_dialog = () => { throw new Error('对话框被系统拒绝') } - await view.run(null, '添加图片') - assert.equal(host.lastToast().title, '无法打开选择图片窗口') - assert.equal(host.lastToast().message, '对话框被系统拒绝') - view.unmount() -}) - -test('工作台:切换语言会保存,下次识别和无界面命令都用新语言;重新识别失败的图片', async () => { - let attempts = 0 - host.ipc.window_show_open_dialog = () => ({ canceled: false, filePath: '/Users/me/scan.jpg' }) - host.ipc.image_ocr = () => (++attempts === 1 ? failed('本地OCR执行失败') : recognized('Hello')) - const view = await mount(ocr.OcrCommand) - await view.dropdown('en') - await tick() - assert.equal(host.storage.get('language'), JSON.stringify('en')) - await view.run(null, '添加图片') - await tick(10) - const entry = view.item(item => item.props.title === 'scan.jpg') - assert.equal(entry.props.subtitle, '本地OCR执行失败') - await view.run(entry, '重新识别') - await tick(10) - assert.equal(view.item(item => item.props.title === 'scan.jpg').props.subtitle, 'Hello') - assert.deepEqual(ocrCalls().map(call => call.lang), ['en-US', 'en-US']) - - host.ipc.image_ocr = () => recognized('x') - await ocr.ocrClipboard() - assert.equal(ocrCalls().at(-1).lang, 'en-US') - view.unmount() -}) - -test('工作台:截图识别处理中立即显示识别中,成功更新结果并复制,取消不留下空条目;处理中重复触发被忽略', async () => { - let release - host.ipc.image_ocr = () => new Promise(resolve => { release = resolve }) - const view = await mount(ocr.OcrCommand) - const first = view.run(null, '截图识别') - await tick() - assert.equal(view.items().length, 1, '截图识别进行中列表立即显示识别中条目') - assert.equal(view.items()[0].props.subtitle, '正在识别') - assert.deepEqual(view.items()[0].props.accessories, [{ tag: '识别中' }]) - assert.equal(view.items()[0].props.detail.props.markdown, '正在识别…') - await view.run(null, '截图识别') - assert.equal(ocrCalls().length, 1, '框选进行中不能再开第二个') - release(failed('已取消框选', { canceled: true })) - await first - await tick() - assert.equal(view.items().length, 0) - - host.ipc.image_ocr = () => recognized('框选出的文字') - await view.run(null, '截图识别') - await tick() - assert.equal(view.items().length, 1) - assert.equal(ocrCalls().at(-1).restoreWindow, true, '工作台框选后要重新显示窗口查看结果') - assert.equal(host.clipboard.text, '框选出的文字') - assert.equal(host.lastToast().title, '已识别并复制') - view.unmount() -}) - -test('工作台:失败条目的主动作是重新识别而不是移除;重新截图成功后替换失败条目', async () => { - host.ipc.image_ocr = () => failed('没有屏幕录制权限') - const view = await mount(ocr.OcrCommand) - await view.run(null, '截图识别') - await tick() - const bad = view.item(item => item.props.title.startsWith('框选截图')) - assert.equal(view.actions(bad)[0].props.title, '重新截图识别') - - host.ipc.image_ocr = () => failed('已取消框选', { canceled: true }) - await view.run(bad, '重新截图识别') - await tick() - assert.equal(view.items().length, 1, '重新截图取消时保留原有失败条目') - assert.equal(view.items()[0].props.id, bad.props.id) - - host.ipc.image_ocr = () => recognized('权限已打开') - await view.run(bad, '重新截图识别') - await tick() - assert.equal(view.items().length, 1, '重新识别成功后不留下失败的旧条目') - assert.equal(view.items()[0].props.subtitle, '权限已打开') - assert.equal(view.actions(view.items()[0])[0].props.title, '复制文字') - - host.ipc.image_ocr = () => failed('剪贴板图片无法解码') - await view.run(null, '识别剪贴板图片') - await tick() - const clip = view.item(item => item.props.title.startsWith('剪贴板图片')) - assert.equal(view.actions(clip)[0].props.title, '重新识别剪贴板图片') - view.unmount() -}) - -test('工作台:批量识别显示进度,排队和识别中的条目不能移除;重复添加同一张图不重复列出', async () => { - const releases = [] - host.ipc.window_show_open_dialog = () => ({ canceled: false, filePaths: ['/p/a.png', '/p/b.png', '/p/a.png'] }) - host.ipc.image_ocr = () => new Promise(resolve => releases.push(resolve)) - const view = await mount(ocr.OcrCommand) - const run = view.run(null, '添加图片') - await tick(5) - assert.deepEqual(view.items().map(item => item.props.title), ['a.png', 'b.png'], '同一次选择里的重复路径只识别一次') - assert.equal(view.tree().props.filterBar.summaryText, '正在识别第 1 / 2 张') - const waiting = view.item(item => item.props.title === 'b.png') - assert.deepEqual(waiting.props.accessories, [{ tag: '等待' }]) - assert.ok(!view.actions(waiting).some(action => action.props.title === '从列表移除')) - assert.equal(view.actions(waiting)[0].props.title, '截图识别', '没有针对这一条的动作时,主动作是开始新的识别') - - await view.run(waiting, '截图识别') - assert.equal(host.lastToast().title, '正在识别,请等当前任务完成') - - releases.shift()(recognized('A')) - await tick(5) - assert.equal(view.tree().props.filterBar.summaryText, '正在识别第 2 / 2 张') - releases.shift()(recognized('B')) - await run - await tick() - assert.match(view.tree().props.filterBar.summaryText, /^2 条识别结果$/) - - host.ipc.window_show_open_dialog = () => ({ canceled: false, filePath: '/p/b.png' }) - host.ipc.image_ocr = () => recognized('B2') - await view.run(null, '添加图片') - await tick(5) - assert.deepEqual(view.items().map(item => item.props.title), ['b.png', 'a.png'], '再次添加已有图片时移到最前面重新识别') - assert.equal(view.items()[0].props.subtitle, 'B2') - view.unmount() -}) - -test('工作台:识别剪贴板图片成功后复制;清空只移除已结束的结果;上次没识别完的条目标为中断', async () => { - host.ipc.image_ocr = () => recognized('剪贴板里的字') - const view = await mount(ocr.OcrCommand) - await view.run(null, '识别剪贴板图片') - await tick() - assert.equal(host.clipboard.text, '剪贴板里的字') - assert.equal(host.lastToast().title, '已识别并复制') - assert.deepEqual(view.actions(view.items()[0]).slice(0, 2).map(action => action.props.title), ['复制文字', '截图识别'], '次动作不能是移除') - - await view.run(view.items()[0], '清空识别结果') - await tick() - assert.equal(view.items().length, 0) - - // 识别到一半关掉插件:重新打开时那一条不会再有结果 - host.ipc.window_show_open_dialog = () => ({ canceled: false, filePath: '/p/slow.png' }) - host.ipc.image_ocr = () => new Promise(() => {}) - void view.run(null, '添加图片') - await tick(5) - view.unmount() - const reopened = await mount(ocr.OcrCommand) - await tick() - const stale = reopened.item(item => item.props.title === 'slow.png') - assert.equal(stale.props.subtitle, '识别被中断') - assert.equal(reopened.actions(stale)[0].props.title, '重新识别') - reopened.unmount() -}) - -test('结果解析:多层 data、空文字、宿主报错与围栏里的反引号', () => { - assert.deepEqual(ocr.toOutcome(ocr.unwrapHostResponse({ success: true, data: recognized(' A ') })), { ok: true, text: 'A' }) - assert.deepEqual(ocr.toOutcome({ ok: true, success: true, text: ' ' }), { ok: false, empty: true, error: '没有识别到文字' }) - assert.throws(() => ocr.unwrapHostResponse({ success: false, error: { code: 'PERMISSION_DENIED', message: '插件只能访问自身对应的能力' } }), /插件只能访问/) - assert.throws(() => ocr.unwrapHostResponse(null), /无效结果/) - const markdown = ocr.textAsMarkdown('a ``` b') - assert.ok(markdown.startsWith('````text\n') && markdown.endsWith('\n````')) - assert.equal(ocr.resolveLanguage('不存在').id, 'zh-hans') -}) - - -test('工作台:支持通过 plugin_files_dropped 拖入图片批量识别,非图片提示失败', async () => { - globalThis.window.__ztoolsDeclarativeFeatures = { fileInput: false } - const listeners = new Map() - globalThis.window.ztools = { - events: { - on(event, cb) { - listeners.set(event, cb) - return () => listeners.delete(event) - } - } - } - try { - host.ipc.image_ocr = params => recognized(`识别:${params.path}`) - const view = await mount(ocr.OcrCommand) - assert.equal(typeof listeners.get('plugin_files_dropped'), 'function') - - listeners.get('plugin_files_dropped')({ payload: { files: ['/Users/me/readme.pdf'] } }) - await tick(5) - assert.equal(host.lastToast().title, '请拖入支持的图片文件') - assert.equal(view.items().length, 0) - - listeners.get('plugin_files_dropped')({ payload: { files: ['/Users/me/drop1.png', '/Users/me/ignore.txt', '/Users/me/drop2.webp'] } }) - await tick(10) - assert.deepEqual(view.items().map(item => item.props.title), ['drop1.png', 'drop2.webp']) - assert.equal(host.lastToast().title, '已识别 2 张图片') - view.unmount() - assert.equal(listeners.has('plugin_files_dropped'), false) - } finally { - globalThis.window.__ztoolsDeclarativeFeatures = { fileInput: true } - delete globalThis.window.ztools - } -}) - -test('工作台与剪贴板:支持 Ctrl+V 粘贴图片文件识别,且剪贴板为复制的图片文件时也可直接识别', async () => { - host.ipc.image_ocr = params => recognized(`识别文件:${params.path}`) - const view = await mount(ocr.OcrCommand) - await view.pasteFiles(['/Users/me/paste1.png', '/Users/me/paste2.webp']) - await tick(10) - assert.deepEqual(view.items().map(item => item.props.title), ['paste1.png', 'paste2.webp']) - assert.equal(host.lastToast().title, '已识别 2 张图片') - - host.clipboard.files = ['/Users/me/copied-from-finder.png'] - await view.run(null, '识别剪贴板图片') - await tick(5) - assert.equal(host.clipboard.text, '识别文件:/Users/me/copied-from-finder.png') - view.unmount() -}) - -function createTempImageTree(spec) { - const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ztools-ocr-import-')) - for (const [rel, content] of Object.entries(spec)) { - const full = path.join(root, rel) - if (rel.endsWith('/')) { - fs.mkdirSync(full, { recursive: true }) - continue - } - fs.mkdirSync(path.dirname(full), { recursive: true }) - fs.writeFileSync(full, content) - } - return root -} - -test('工作台初始化:不扫描任何目录或文件,顶栏保持 2 个按钮且入口包含选择文件夹', async () => { - const view = await mount(ocr.OcrCommand) - assert.equal(view.items().length, 0) - assert.equal(host.ipcCalls.length, 0) - const forbidden = new Set(['system_get_path', 'system_list_common_folders', 'system_search_files', 'filesystem_get_directory_contents', 'dllplugin_call']) - assert.equal(host.ipcCalls.some(([method]) => forbidden.has(method)), false) - assert.deepEqual(view.tree().props.filterBar.actions.map(action => action.title), ['截图识别', '添加图片']) - const emptyActions = view.actions(null) - assert.ok(emptyActions.some(action => action.props.title === '选择文件夹…')) - const folderAction = emptyActions.find(action => action.props.title === '选择文件夹…') - assert.deepEqual(folderAction.props.shortcut, { modifiers: ['cmd', 'shift'], key: 'o' }) - assert.deepEqual(view.tree().props.fileInput.allowDirectories, true) - assert.deepEqual(view.tree().props.fileInput.allowClipboardImage, true) - assert.equal('extensions' in view.tree().props.fileInput, false) - view.unmount() -}) - -test('选择文件夹:递归收集支持格式,跳过空文件与依赖目录;支持移除、清空与取消/缺接口提示', async () => { - const tmpDir = createTempImageTree({ - '1.png': 'img1', - 'v1.2_截图/2.jpg': 'img2', - 'v1.2_截图/3.jpeg': 'img3', - 'v1.2_截图/4.webp': 'img4', - 'v1.2_截图/5.bmp': 'img5', - 'v1.2_截图/6.gif': 'img6', - 'v1.2_截图/7.tiff': 'img7', - 'note.txt': 'text', - 'doc.pdf': 'pdf', - 'empty.png': '', - '.hidden.png': 'hidden', - 'node_modules/pkg/a.png': 'skip', - '.git/b.png': 'skip' - }) - try { - await installDirectoryHost(host, { authorized: [tmpDir] }) - host.ipc.window_show_select_folder_dialog = () => ({ canceled: false, folderPath: tmpDir }) - host.ipc.image_ocr = params => recognized(`文字:${path.basename(params.path)}`) - - const view = await mount(ocr.OcrCommand) - await view.run(null, '选择文件夹…') - await tick(30) - - const recognizedFiles = ocrCalls().map(call => path.basename(call.path)) - assert.equal(recognizedFiles.length, 7) - assert.deepEqual(new Set(recognizedFiles), new Set(['1.png', '2.jpg', '3.jpeg', '4.webp', '5.bmp', '6.gif', '7.tiff'])) - assert.equal(host.lastToast().title, '已识别 7 张图片') - - const firstItem = view.items()[0] - assert.ok(view.actions(firstItem).some(action => action.props.title === '选择文件夹…')) - await view.run(firstItem, '从列表移除') - assert.equal(view.items().length, 6) - assert.equal(fs.existsSync(path.join(tmpDir, '1.png')), true, '从列表移除不得删除磁盘文件') - - await view.run(view.items()[0], '清空识别结果') - assert.equal(view.items().length, 0) - - // 取消选择不触发目录读取或识别 - const prevCalls = host.ipcCalls.length - host.ipc.window_show_select_folder_dialog = () => ({ canceled: true }) - await view.run(null, '选择文件夹…') - await tick(5) - assert.equal(host.ipcCalls.length, prevCalls + 1) - - // 空文件夹提示支持格式 - const emptyDir = createTempImageTree({ 'readme.txt': 'x' }) - try { - await installDirectoryHost(host, { authorized: [emptyDir] }) - host.ipc.window_show_select_folder_dialog = () => ({ canceled: false, folderPath: emptyDir }) - await view.run(null, '选择文件夹…') - await tick(10) - assert.equal(host.lastToast().style, 'FAILURE') - assert.equal(host.lastToast().title, '没有找到可导入的文件') - } finally { - fs.rmSync(emptyDir, { recursive: true, force: true }) - } - - // 旧版缺少 select_folder_dialog(preload 无此方法)时明确提示升级 - const savedMethods = globalThis.__ztoolsElectron.transport.methods - globalThis.__ztoolsElectron = { - ...globalThis.__ztoolsElectron, - transport: { - methods: new Proxy({}, { - get: (_t, name) => (name === 'window_show_select_folder_dialog' ? undefined : savedMethods[name]) - }) - } - } - try { - await view.run(null, '选择文件夹…') - await tick(5) - assert.equal(host.lastToast().title, '导入失败') - assert.match(host.lastToast().message, /请升级/) - } finally { - globalThis.__ztoolsElectron = { ...globalThis.__ztoolsElectron, transport: { methods: savedMethods } } - } - view.unmount() - } finally { - fs.rmSync(tmpDir, { recursive: true, force: true }) - } -}) - -test('选择文件夹:盘符根目录(isVolumeRoot)先经 confirmAlert 确认再遍历', async () => { - host.ipc.window_show_select_folder_dialog = () => ({ canceled: false, folderPath: 'D:\\' }) - host.ipc.filesystem_get_directory_contents = () => ({ - success: true, - files: [{ name: 'root.png', size: 100, isDirectory: false, lastModified: '2026-11-16T00:00:00Z' }] - }) - host.ipc.image_ocr = params => recognized(`识别:${params.path}`) - - const view = await mount(ocr.OcrCommand) - host.setConfirm(false) - await view.run(null, '选择文件夹…') - await tick(10) - assert.equal(host.confirms.length, 1) - assert.equal(host.ipcCalls.some(([method]) => method === 'filesystem_get_directory_contents'), false) - assert.equal(ocrCalls().length, 0) - - host.setConfirm(true) - await view.run(null, '选择文件夹…') - await tick(10) - assert.equal(host.confirms.length, 2) - assert.equal(ocrCalls().length, 1) - assert.equal(view.items()[0].props.title, 'root.png') - view.unmount() -}) - -test('拖入文件夹自动展开:支持名称带点的文件夹、旧版不传 directories 探测与 plugin_files_dropped 回退', async () => { - const tmpDir = createTempImageTree({ - '2026.11_截图/shot1.png': 'img1', - '2026.11_截图/ignore.txt': 'txt', - 'single.webp': 'img2' - }) - const dottedDir = path.join(tmpDir, '2026.11_截图') - const singleFile = path.join(tmpDir, 'single.webp') - try { - await installDirectoryHost(host, { authorized: [tmpDir] }) - host.ipc.filesystem_directory_exists = ({ path: target }) => ({ success: true, exists: fs.existsSync(target) && fs.statSync(target).isDirectory() }) - host.ipc.filesystem_get_file_size = ({ path: target }) => ({ success: true, size: fs.statSync(target).size }) - host.ipc.image_ocr = params => recognized(`识别:${path.basename(params.path)}`) - - // 1. 新版宿主带 directories 时无需调用 directory_exists - const view = await mount(ocr.OcrCommand) - await view.dropFiles([dottedDir, singleFile], { directories: [dottedDir] }) - await tick(20) - assert.equal(host.ipcCalls.some(([method]) => method === 'filesystem_directory_exists'), false) - assert.deepEqual(new Set(view.items().map(item => item.props.title)), new Set(['shot1.png', 'single.webp'])) - - // 2. 旧版宿主不带 directories 时探测文件夹展开带点目录 - host.ipcCalls.length = 0 - await view.run(view.items()[0], '清空识别结果') - await view.dropFiles([dottedDir]) - await tick(20) - assert.equal(host.ipcCalls.some(([method]) => method === 'filesystem_directory_exists'), true) - assert.deepEqual(view.items().map(item => item.props.title), ['shot1.png']) - view.unmount() - - // 3. 旧版 plugin_files_dropped 回退事件也能展开文件夹 - const prevFeatures = globalThis.window.__ztoolsDeclarativeFeatures - const prevZtools = globalThis.window.ztools - globalThis.window.__ztoolsDeclarativeFeatures = { fileInput: false } - const listeners = new Map() - globalThis.window.ztools = { - events: { - on(event, cb) { - listeners.set(event, cb) - return () => listeners.delete(event) - } - } - } - try { - const fallbackView = await mount(ocr.OcrCommand) - listeners.get('plugin_files_dropped')({ payload: { files: [dottedDir] } }) - await tick(20) - assert.deepEqual(fallbackView.items().map(item => item.props.title), ['shot1.png']) - fallbackView.unmount() - } finally { - globalThis.window.__ztoolsDeclarativeFeatures = prevFeatures - globalThis.window.ztools = prevZtools - } - } finally { - fs.rmSync(tmpDir, { recursive: true, force: true }) - } -}) - -test('截断上限 100:超过 100 张图片时只导入并识别前 100 张,且明确提示只导入前 100 张', async () => { - const spec = {} - for (let i = 1; i <= 105; i++) { - spec[`img-${String(i).padStart(3, '0')}.png`] = `img-${i}` - } - const tmpDir = createTempImageTree(spec) - try { - await installDirectoryHost(host, { authorized: [tmpDir] }) - host.ipc.window_show_select_folder_dialog = () => ({ canceled: false, folderPath: tmpDir }) - host.ipc.image_ocr = params => recognized(`OCR:${path.basename(params.path)}`) - - const view = await mount(ocr.OcrCommand) - await view.run(null, '选择文件夹…') - await tick(120) - - assert.equal(ocrCalls().length, 100) - assert.equal(view.items().length, 100) - assert.ok( - host.toasts.some(t => t.style === 'SUCCESS' && /只导入前\s*100\s*张/.test(`${t.title}${t.message || ''}`)), - `期望存在截断提示 Toast,实际:${JSON.stringify(host.toasts)}` - ) - assert.equal(host.lastToast().title, '已识别 100 张图片') - view.unmount() - } finally { - fs.rmSync(tmpDir, { recursive: true, force: true }) - } -}) - -test('并发竞态与适配器:导入中清空结果被丢弃;连续导入取消上一次;识别中拒绝新导入;适配各类宿主返回', async () => { - // 1. 导入中清空结果被丢弃 & 识别中拒绝新导入 - host.ipc.image_ocr = () => recognized('初始条目') - host.ipc.window_show_open_dialog = () => ({ canceled: false, filePath: '/Users/me/init.png' }) - const view = await mount(ocr.OcrCommand) - await view.run(null, '添加图片') - await tick(10) - assert.equal(view.items().length, 1) - - let releaseDir - host.ipc.window_show_select_folder_dialog = () => ({ canceled: false, folderPath: '/Users/me/slow-dir' }) - host.ipc.filesystem_get_directory_contents = () => new Promise(resolve => { releaseDir = resolve }) - const importRun = view.run(null, '选择文件夹…') - await tick(5) - assert.equal(view.tree().props.isLoading, true) - const callsBeforeClear = ocrCalls().length - await view.run(view.items()[0], '清空识别结果') - assert.equal(view.items().length, 0) - releaseDir({ success: true, files: [{ name: 'late.png', size: 100, isDirectory: false, lastModified: '2026-11-16T00:00:00Z' }] }) - await importRun - await tick(10) - assert.equal(ocrCalls().length, callsBeforeClear, '清空后滞后返回的导入结果不得入队识别') - assert.equal(view.items().length, 0) - - // 1.5 连续两次触发导入时取消上一次,只保留最后一次结果 - let resolveFirstDrop - host.ipc.filesystem_get_directory_contents = ({ path: dir }) => { - if (dir === '/Users/me/dir-first') return new Promise(resolve => { resolveFirstDrop = resolve }) - return { success: true, files: [{ name: 'second.png', size: 100, isDirectory: false, lastModified: '2026-11-16T00:00:00Z' }] } - } - const drop1 = view.dropFiles(['/Users/me/dir-first'], { directories: ['/Users/me/dir-first'] }) - await tick(5) - const drop2 = view.dropFiles(['/Users/me/dir-second'], { directories: ['/Users/me/dir-second'] }) - await tick(10) - resolveFirstDrop({ success: true, files: [{ name: 'first.png', size: 100, isDirectory: false, lastModified: '2026-11-16T00:00:00Z' }] }) - await Promise.all([drop1, drop2]) - await tick(10) - assert.deepEqual(view.items().map(item => item.props.title), ['second.png']) - - // 2. 识别中点选择文件夹提示正在识别 - let releaseOcr - host.ipc.image_ocr = () => new Promise(resolve => { releaseOcr = resolve }) - host.ipc.window_show_open_dialog = () => ({ canceled: false, filePath: '/Users/me/busy.png' }) - const busyRun = view.run(null, '添加图片') - await tick(5) - const dialogCountBefore = host.ipcCalls.filter(([m]) => m === 'window_show_select_folder_dialog').length - await view.run(null, '选择文件夹…') - assert.equal(host.lastToast().title, '正在识别,请等当前任务完成') - assert.equal(host.ipcCalls.filter(([m]) => m === 'window_show_select_folder_dialog').length, dialogCountBefore) - releaseOcr(recognized('完成')) - await busyRun - view.unmount() - - // 3. FileImportTransport 适配器边界测试 - const missingTransport = ocr.createFileImportTransport(undefined) - assert.deepEqual(await missingTransport('filesystem_get_directory_contents', {}), { ok: false, error: ocr.getNotInClientMessage() }) - - const mockTransport = async (method) => { - if (method === 'filesystem_get_file_size') return { success: true, data: 2048 } - if (method === 'filesystem_directory_exists') return { success: true, data: true } - if (method === 'filesystem_get_directory_contents') return { success: true, data: [{ name: 'a.png', size: 10, isDirectory: false }] } - if (method === 'inner_fail') return { success: true, data: { success: false, error: '权限不足' } } - throw new Error(`客户端不支持 ${method}`) - } - const adapted = ocr.createFileImportTransport(mockTransport) - assert.deepEqual(await adapted('filesystem_get_file_size', {}), { ok: true, data: 2048 }) - assert.deepEqual(await adapted('filesystem_directory_exists', {}), { ok: true, data: true }) - assert.deepEqual(await adapted('filesystem_get_directory_contents', {}), { ok: true, data: [{ name: 'a.png', size: 10, isDirectory: false }] }) - assert.deepEqual(await adapted('inner_fail', {}), { ok: false, error: '权限不足' }) - assert.deepEqual(await adapted('unknown_op', {}), { ok: false, error: 'METHOD_NOT_AVAILABLE: unknown_op' }) -}) - -test('i18n 回归:剪贴板无图片按结构化 errorCode CLIPBOARD_NO_IMAGE 处理,英文态不依赖中文字符串比较', async () => { - try { - setRuntimeLocale('en-US') - host.ipc.image_ocr = () => failed('剪贴板里没有图片', { errorCode: 'CLIPBOARD_NO_IMAGE' }) - const view = await mount(ocr.OcrCommand) - await view.run(null, 'OCR Clipboard') - await tick() - assert.equal(view.items().length, 0, '剪贴板无图片时不新增失败条目') - assert.equal(host.lastToast().title, 'No image found in clipboard') - view.unmount() - } finally { - setRuntimeLocale('zh-CN') - } -}) diff --git a/extensions/ocr/tests/ocr.test.mjs b/extensions/ocr/tests/ocr.test.mjs new file mode 100644 index 00000000..b1447d69 --- /dev/null +++ b/extensions/ocr/tests/ocr.test.mjs @@ -0,0 +1,106 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import { createHost, mount, tick } from '../../shared/test-harness.mjs' +import OcrCommand, { + OCR_IMPORT_EXTENSIONS, + countLines, + mergeOcrParagraphs +} from '../dist/index.js' + +const host = createHost() +test.beforeEach(() => host.reset()) + +test('OCR_IMPORT_EXTENSIONS 补齐 .heic 与 .tif,与客户端支持格式一致', () => { + assert.ok(OCR_IMPORT_EXTENSIONS.includes('.heic')) + assert.ok(OCR_IMPORT_EXTENSIONS.includes('.tif')) + assert.ok(OCR_IMPORT_EXTENSIONS.includes('.tiff')) +}) + +test('mergeOcrParagraphs 智能合并中文/英文/断词连字符并保留空行分段', () => { + assert.equal(mergeOcrParagraphs(''), '') + assert.equal(mergeOcrParagraphs(' \n\n '), '') + assert.equal( + mergeOcrParagraphs('本次重构将所有鉴权逻辑\n统一收口至网关层,\n取消散落兜底。\n\nNext step: run integra-\ntion tests before\nreleasing v2.4.'), + '本次重构将所有鉴权逻辑统一收口至网关层,取消散落兜底。\n\nNext step: run integration tests before releasing v2.4.' + ) + assert.equal(countLines('第一行\n第二行\n第三行'), 3) + assert.equal(countLines(''), 0) +}) + +test('[集成] 顶栏显式提供选择图片/读取剪贴板/截屏识别三入口,右栏展示完整文本并支持合并段落与原文断行切换', async () => { + host.ipc.image_ocr = async ({ action }) => { + if (action === 'recognizeClipboard') { + return { + ok: true, + text: '第一行中文段落\n第二行紧接着合并。\n\nHello\nworld!' + } + } + return { ok: false, error: 'unexpected action' } + } + + const view = await mount(OcrCommand) + try { + const barActions = view.tree().props.filterBar?.actions ?? [] + const barTitles = barActions.map((a) => a.title) + assert.ok(barTitles.includes('选择图片'), `缺少选择图片入口: ${barTitles.join(', ')}`) + assert.ok(barTitles.includes('读取剪贴板'), `缺少读取剪贴板入口: ${barTitles.join(', ')}`) + assert.ok(barTitles.includes('截屏识别'), `缺少截屏识别入口: ${barTitles.join(', ')}`) + + // 空态应展示 List.EmptyView + assert.equal(view.items().length, 0) + assert.ok(view.text().includes('开始离线文字识别')) + + // 点击顶栏「读取剪贴板」 + const clipBtn = barActions.find((a) => a.id === 'ocr-clipboard') + assert.ok(clipBtn) + await clipBtn.onAction() + await tick(10) + + const items = view.items() + assert.equal(items.length, 1) + const entry = items[0] + const rawDetail = entry.props.detail.props.markdown + assert.ok(rawDetail.includes('第一行中文段落\n第二行紧接着合并。')) + assert.ok(rawDetail.includes('Hello\nworld!')) + + // 切换为合并段落 + await view.run(entry, '切换为合并段落') + await tick(5) + + const mergedItem = view.items()[0] + const mergedDetail = mergedItem.props.detail.props.markdown + assert.ok(mergedDetail.includes('第一行中文段落第二行紧接着合并。')) + assert.ok(mergedDetail.includes('Hello world!')) + + // 主动作复制合并后文本 + const actions = view.actions(mergedItem) + assert.equal(actions[0].props.title, '复制合并段落') + assert.equal(actions[0].props.content, '第一行中文段落第二行紧接着合并。\n\nHello world!') + + // 再切回原文断行 + await view.run(mergedItem, '切换为原文断行') + await tick(5) + assert.ok(view.items()[0].props.detail.props.markdown.includes('第一行中文段落\n第二行紧接着合并。')) + + // 清空识别结果,恢复空态 + await view.run(view.items()[0], '清空识别结果') + await tick(5) + assert.equal(view.items().length, 0) + } finally { + view.unmount() + } +}) + +test('[故障注入] 读取剪贴板无图片时如实提示失败且不写入空条目', async () => { + host.ipc.image_ocr = async () => ({ ok: false, errorCode: 'CLIPBOARD_NO_IMAGE', error: '剪贴板里没有图片' }) + const view = await mount(OcrCommand) + try { + const clipBtn = view.tree().props.filterBar.actions.find((a) => a.id === 'ocr-clipboard') + await clipBtn.onAction() + await tick(10) + assert.equal(view.items().length, 0) + assert.match(String(host.lastToast()?.title), /剪贴板里没有图片/) + } finally { + view.unmount() + } +}) diff --git a/extensions/password-vault/plugin.json b/extensions/password-vault/plugin.json index ea23ace4..4e7faa57 100644 --- a/extensions/password-vault/plugin.json +++ b/extensions/password-vault/plugin.json @@ -1,7 +1,7 @@ { "id": "password-vault", "name": "密码保险箱", - "version": "1.1.9", + "version": "1.1.10", "minAppVersion": "1.1.8.5", "description": "在本机用主密码加密保存账号密码、API Key、服务器密码与软件激活码(AES-256-GCM),复制密码 30 秒后自动清除剪贴板", "author": "ZTools Team", diff --git a/extensions/password-vault/src/i18n.ts b/extensions/password-vault/src/i18n.ts index cc214704..48196301 100644 --- a/extensions/password-vault/src/i18n.ts +++ b/extensions/password-vault/src/i18n.ts @@ -59,6 +59,52 @@ const rawT = createTranslator({ fieldConfirmMasterPwdTitle: '确认主密码', fieldConfirmMasterPwdPlaceholder: '请再次输入主密码以确认一致...', actionExportEncryptedBackup: '导出加密备份 JSON', + actionImportEncryptedBackup: '导入加密备份恢复', + actionChangeMasterPassword: '修改主密码', + actionOpenEndpoint: '在浏览器中打开网址', + formTitleImportBackup: '导入加密备份恢复', + formSubmitImportBackup: '解密验证并恢复保险箱', + fieldBackupJsonLabel: '加密备份 JSON', + fieldBackupJsonPlaceholder: '粘贴先前导出的加密信封 JSON(仅含密文与 KDF 参数)...', + fieldBackupPwdLabel: '备份对应的主密码', + fieldBackupPwdPlaceholder: '输入加密该备份时使用的主密码以验证完整性...', + descImportBackupTitle: '离线恢复说明', + descImportBackupText: '导入前会先用您输入的主密码在本地验证 AES-256-GCM 密文完整性;验证失败不会修改当前保险箱。', + confirmReplaceVaultTitle: '用导入的加密备份替换当前保险箱?', + confirmReplaceVaultMsg: '本地已存在加密保险箱,确认后将替换为该备份(共 {count} 项凭据)。原数据不会被保留,请确认已提前导出备份。', + confirmReplaceVaultPrimary: '确认替换并恢复', + toastImportEmptyJson: '请先粘贴加密备份 JSON', + toastImportSuccessTitle: '加密备份已恢复并解锁', + toastImportSuccessMsg: '已通过完整性校验,共恢复 {count} 项凭据', + toastImportFailedTitle: '导入加密备份失败', + formTitleChangeMasterPwd: '修改主密码', + formSubmitChangeMasterPwd: '验证并重新加密保险箱', + fieldCurrentMasterPwdLabel: '当前主密码', + fieldCurrentMasterPwdPlaceholder: '输入当前正在使用的主密码...', + fieldNewMasterPwdLabel: '新主密码(至少 8 位)', + fieldNewMasterPwdPlaceholder: '输入新的高强度主密码...', + fieldConfirmNewMasterPwdLabel: '确认新主密码', + fieldConfirmNewMasterPwdPlaceholder: '再次输入新主密码以确认一致...', + errCurrentMasterPwdWrong: '当前主密码不正确,未修改保险箱', + toastChangeMasterSuccessTitle: '主密码已更新', + toastChangeMasterSuccessMsg: '已使用新主密码重新加密全部 {count} 项凭据', + toastChangeMasterFailedTitle: '修改主密码失败', + toastAutoLockedTitle: '空闲超时,保险箱已自动锁定', + detailMetaCategory: '凭据分类', + detailMetaUsername: '用户名 / 账号', + detailMetaEndpoint: '网址 / 主机', + detailMetaSecret: '密码 / Secret', + detailMetaNote: '加密备注', + detailMetaUpdated: '最近更新', + detailMetaSecurity: '剪贴板保护', + detailSecretMasked: '••••••••••••(已隐藏,按 Ctrl+E 临时显示)', + detailNoteEncryptedHint: '已加密隐藏(按 Ctrl+E 临时显示)', + detailNoteEmpty: '无备注', + detailSecurityValue: '敏感复制 · 30 秒后自动清空剪贴板', + emptyVaultTitle: '保险箱中暂无凭据', + emptyVaultSubtitle: '点击上方「新建凭据」添加第一条加密记录,或导入已有加密备份恢复', + emptySearchTitle: '没有匹配的加密凭据', + emptySearchSubtitle: '请尝试更换搜索词或切换凭据分类', toastBackupCopiedTitle: '已复制加密备份 JSON', toastBackupCopiedMsg: '仅包含加密信封密文(不含任何明文),请妥善保存', toastBackupUnavailableTitle: '暂无可导出的加密备份', @@ -184,6 +230,52 @@ const rawT = createTranslator({ fieldConfirmMasterPwdTitle: 'Confirm Master Password', fieldConfirmMasterPwdPlaceholder: 'Re-enter master password to confirm…', actionExportEncryptedBackup: 'Export Encrypted Backup JSON', + actionImportEncryptedBackup: 'Restore from Encrypted Backup', + actionChangeMasterPassword: 'Change Master Password', + actionOpenEndpoint: 'Open URL in Browser', + formTitleImportBackup: 'Restore from Encrypted Backup', + formSubmitImportBackup: 'Verify & Restore Vault', + fieldBackupJsonLabel: 'Encrypted Backup JSON', + fieldBackupJsonPlaceholder: 'Paste previously exported encrypted envelope JSON…', + fieldBackupPwdLabel: 'Backup Master Password', + fieldBackupPwdPlaceholder: 'Enter the master password for this backup to verify integrity…', + descImportBackupTitle: 'Offline Restore', + descImportBackupText: 'The backup ciphertext is verified locally with AES-256-GCM before writing. Verification failure leaves your current vault untouched.', + confirmReplaceVaultTitle: 'Replace Current Vault with Backup?', + confirmReplaceVaultMsg: 'An encrypted vault already exists locally. Replacing it will load {count} entry(s) from the backup and discard the current local vault.', + confirmReplaceVaultPrimary: 'Replace & Restore', + toastImportEmptyJson: 'Please paste the encrypted backup JSON first', + toastImportSuccessTitle: 'Encrypted Backup Restored & Unlocked', + toastImportSuccessMsg: 'Integrity verified; restored {count} entry(s)', + toastImportFailedTitle: 'Failed to Restore Encrypted Backup', + formTitleChangeMasterPwd: 'Change Master Password', + formSubmitChangeMasterPwd: 'Verify & Re-encrypt Vault', + fieldCurrentMasterPwdLabel: 'Current Master Password', + fieldCurrentMasterPwdPlaceholder: 'Enter your current master password…', + fieldNewMasterPwdLabel: 'New Master Password (min 8 chars)', + fieldNewMasterPwdPlaceholder: 'Enter a new strong master password…', + fieldConfirmNewMasterPwdLabel: 'Confirm New Master Password', + fieldConfirmNewMasterPwdPlaceholder: 'Re-enter new master password to confirm…', + errCurrentMasterPwdWrong: 'Current master password is incorrect; vault unchanged', + toastChangeMasterSuccessTitle: 'Master Password Updated', + toastChangeMasterSuccessMsg: 'Re-encrypted all {count} entry(s) with the new master password', + toastChangeMasterFailedTitle: 'Failed to Change Master Password', + toastAutoLockedTitle: 'Vault auto-locked after idle timeout', + detailMetaCategory: 'Category', + detailMetaUsername: 'Username / Account', + detailMetaEndpoint: 'URL / Host', + detailMetaSecret: 'Password / Secret', + detailMetaNote: 'Encrypted Notes', + detailMetaUpdated: 'Updated', + detailMetaSecurity: 'Clipboard Guard', + detailSecretMasked: '•••••••••••• (Hidden; press Ctrl+E to reveal)', + detailNoteEncryptedHint: 'Encrypted & hidden (press Ctrl+E to reveal)', + detailNoteEmpty: 'None', + detailSecurityValue: 'Sensitive copy · Auto-clears clipboard in 30s', + emptyVaultTitle: 'No Entries in Vault Yet', + emptyVaultSubtitle: 'Click "New Entry" above to add your first secret, or restore from an encrypted backup', + emptySearchTitle: 'No Matching Entries', + emptySearchSubtitle: 'Try a different search keyword or category filter', toastBackupCopiedTitle: 'Encrypted Backup JSON Copied', toastBackupCopiedMsg: 'Contains encrypted envelope ciphertext only (no plaintext); store it safely', toastBackupUnavailableTitle: 'No Encrypted Backup Available', diff --git a/extensions/password-vault/src/index.tsx b/extensions/password-vault/src/index.tsx index fde9e972..1ca74cd3 100644 --- a/extensions/password-vault/src/index.tsx +++ b/extensions/password-vault/src/index.tsx @@ -35,6 +35,28 @@ export * from './types.js' export * from './vault-crypto.js' const VAULT_STORAGE_KEY = 'ztools.password-vault.envelope.v1' +const IDLE_AUTO_LOCK_MS = 5 * 60 * 1000 + +/** 仅允许安全的 http(s) 网址直开,拒绝 javascript:/file:/data: 等危险协议 */ +export function resolveOpenableUrl(endpoint: string): string | null { + const trimmed = String(endpoint || '').trim() + if (!trimmed || /\s/.test(trimmed)) return null + let candidate = trimmed + if (/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(trimmed)) { + if (!/^https?:\/\//i.test(trimmed)) return null + } else if (/^(?:localhost|[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)+)(?::\d{1,5})?(?:\/.*)?$/.test(trimmed)) { + candidate = `https://${trimmed}` + } else { + return null + } + try { + const parsed = new URL(candidate) + if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return null + return parsed.href + } catch { + return null + } +} function parseStoredEnvelope(raw: unknown): EncryptedVaultEnvelope { const value: unknown = typeof raw === 'string' ? JSON.parse(raw) : raw @@ -193,6 +215,165 @@ export function VaultEntryForm({ initialPassword = '', initialEntry, onSave }: V ) } +interface ImportEncryptedBackupFormProps { + hasExistingVault: boolean + onImport: (envelope: EncryptedVaultEnvelope, backupPassword: string, decryptedEntries: VaultEntry[]) => Promise +} + +export function ImportEncryptedBackupForm({ hasExistingVault, onImport }: ImportEncryptedBackupFormProps) { + useLocale() + const { pop } = useNavigation() + const [backupJson, setBackupJson] = useState('') + const [backupPassword, setBackupPassword] = useState('') + const [busy, setBusy] = useState(false) + const submitting = useRef(false) + + const handleSubmit = useCallback(async () => { + if (submitting.current) return + const raw = backupJson.trim() + if (!raw) { + await showToast({ style: Toast.Style.Failure, title: t('toastImportFailedTitle'), message: t('toastImportEmptyJson') }) + return + } + submitting.current = true + setBusy(true) + try { + const envelope = parseStoredEnvelope(raw) + const decrypted = await decryptVaultEntries(backupPassword, envelope) + if (hasExistingVault) { + const confirmed = await confirmAlert({ + title: t('confirmReplaceVaultTitle'), + message: t('confirmReplaceVaultMsg', { count: decrypted.length }), + primaryAction: { title: t('confirmReplaceVaultPrimary'), style: 'destructive' }, + dismissAction: { title: t('confirmCancel') } + }) + if (!confirmed) return + } + await onImport(envelope, backupPassword, decrypted) + pop() + } catch (error) { + await showToast({ + style: Toast.Style.Failure, + title: t('toastImportFailedTitle'), + message: error instanceof Error ? error.message : String(error) + }) + } finally { + submitting.current = false + setBusy(false) + } + }, [backupJson, backupPassword, hasExistingVault, onImport, pop]) + + return ( +
+ + + } + > + + + + + ) +} + +interface ChangeMasterPasswordFormProps { + onChangePassword: (currentPassword: string, nextPassword: string) => Promise +} + +export function ChangeMasterPasswordForm({ onChangePassword }: ChangeMasterPasswordFormProps) { + useLocale() + const { pop } = useNavigation() + const [currentPassword, setCurrentPassword] = useState('') + const [nextPassword, setNextPassword] = useState('') + const [confirmNextPassword, setConfirmNextPassword] = useState('') + const [busy, setBusy] = useState(false) + const submitting = useRef(false) + + const handleSubmit = useCallback(async () => { + if (submitting.current) return + const check = validateMasterPassword(nextPassword, { isNewVault: true }) + if (!check.valid) { + await showToast({ style: Toast.Style.Failure, title: t('toastInvalidMasterTitle'), message: check.error }) + return + } + if (nextPassword !== confirmNextPassword) { + await showToast({ + style: Toast.Style.Failure, + title: t('toastMasterMismatchTitle'), + message: t('errMasterPasswordMismatch') + }) + return + } + submitting.current = true + setBusy(true) + try { + await onChangePassword(currentPassword, nextPassword) + pop() + } catch (error) { + await showToast({ + style: Toast.Style.Failure, + title: t('toastChangeMasterFailedTitle'), + message: error instanceof Error ? error.message : String(error) + }) + } finally { + submitting.current = false + setBusy(false) + } + }, [currentPassword, nextPassword, confirmNextPassword, onChangePassword, pop]) + + return ( +
+ + + } + > + + + + + ) +} + export interface PasswordVaultProps { featureCode?: string /** 从生成器进入时,新建凭据预先填入这个密码 */ @@ -472,6 +653,91 @@ export function PasswordVault({ } }, [storedEnvelope]) + const handleImportEncryptedBackup = useCallback( + async (envelope: EncryptedVaultEnvelope, backupPassword: string, decryptedEntries: VaultEntry[]) => { + if (!mountedRef.current || !readReadyRef.current) throw new Error(t('errReReadAndUnlock')) + if (mutatingRef.current) throw new Error(t('errSavingBusy')) + const expected = hasExistingVault ? rawEnvelopeRef.current : undefined + if (hasExistingVault && expected === undefined) throw new Error(t('errStateChanged')) + mutatingRef.current = true + try { + const serialized = serializeEncryptedBackup(envelope) + const saved = await LocalStorage.compareAndSet(VAULT_STORAGE_KEY, expected, serialized) + if (!saved) { + readReadyRef.current = false + sessionEpoch.current++ + if (mountedRef.current) { + setIsUnlocked(false) + setMasterPassword('') + setEntries([]) + entriesRef.current = [] + setLoadError(t('errDataChangedRead')) + } + throw new Error(t('errDataChangedRetry')) + } + if (mountedRef.current) { + rawEnvelopeRef.current = serialized + setStoredEnvelope(envelope) + setHasExistingVault(true) + setMasterPassword(backupPassword) + entriesRef.current = decryptedEntries + sessionEpoch.current++ + setEntries(decryptedEntries) + setIsUnlocked(true) + setRevealedId(null) + setPasswordInput('') + setConfirmPasswordInput('') + setAuthError('') + setConfirmError('') + } + await showToast({ + style: Toast.Style.Success, + title: t('toastImportSuccessTitle'), + message: t('toastImportSuccessMsg', { count: decryptedEntries.length }) + }) + } finally { + mutatingRef.current = false + } + }, + [hasExistingVault] + ) + + const handleChangeMasterPassword = useCallback( + async (currentPassword: string, nextPassword: string) => { + if (!masterPassword || currentSession !== sessionEpoch.current) throw new Error(t('errLockedReunlock')) + if (currentPassword !== masterPassword) { + throw new Error(t('errCurrentMasterPwdWrong')) + } + await persistEntries(nextPassword, entriesRef.current) + if (!mountedRef.current || currentSession !== sessionEpoch.current) return + setMasterPassword(nextPassword) + await showToast({ + style: Toast.Style.Success, + title: t('toastChangeMasterSuccessTitle'), + message: t('toastChangeMasterSuccessMsg', { count: entriesRef.current.length }) + }) + }, + [masterPassword, currentSession, persistEntries] + ) + + useEffect(() => { + if (!isUnlocked) return + const timer = setTimeout(() => { + if (!mountedRef.current || mutatingRef.current) return + sessionEpoch.current++ + entriesRef.current = [] + setIsUnlocked(false) + setMasterPassword('') + setEntries([]) + setRevealedId(null) + void showToast({ + style: Toast.Style.Success, + title: t('toastAutoLockedTitle') + }) + }, IDLE_AUTO_LOCK_MS) + return () => clearTimeout(timer) + }, [isUnlocked, searchText, categoryFilter, revealedId, entries]) + const filteredEntries = useMemo(() => { const q = searchText.trim().toLowerCase() return entries.filter((item: VaultEntry) => { @@ -533,6 +799,16 @@ export function PasswordVault({ onAction={handleExportEncryptedBackup} /> ) : null} + + } + /> } > @@ -569,6 +845,7 @@ export function PasswordVault({ return ( 0} searchText={searchText} onSearchTextChange={setSearchText} searchBarPlaceholder={t('searchPlaceholder')} @@ -607,6 +884,21 @@ export function PasswordVault({ icon={Icon.Download} onAction={handleExportEncryptedBackup} /> + + } + /> + } + /> } > - {filteredEntries.map((item: VaultEntry) => ( + {filteredEntries.length === 0 ? ( - handleCopySecretWithAutoClear(item)} - /> - {item.username && ( - - )} - setRevealedId((cur: string | null) => (cur === item.id ? null : item.id))} - /> handleSaveEntry(input, item.id)} />} - /> - + } /> - - handleDeleteEntry(item.id)} + + } /> } /> - ))} + ) : ( + filteredEntries.map((item: VaultEntry) => { + const isRevealed = revealedId === item.id + const openableUrl = resolveOpenableUrl(item.endpoint) + const detailMarkdown = [ + `## ${item.title}`, + '', + isRevealed + ? `**${t('detailMetaSecret')}**: \`${item.secretPlain}\`` + : `**${t('detailMetaSecret')}**: ${t('detailSecretMasked')}`, + ...(item.note + ? ['', `**${t('detailMetaNote')}**: ${isRevealed ? item.note : t('detailNoteEncryptedHint')}`] + : []) + ].join('\n') + + return ( + + + {item.username ? ( + + ) : null} + {item.endpoint ? ( + + ) : null} + + + + + + } + /> + } + actions={ + + handleCopySecretWithAutoClear(item)} + /> + {openableUrl ? ( + + ) : null} + {item.username && ( + + )} + setRevealedId((cur: string | null) => (cur === item.id ? null : item.id))} + /> + handleSaveEntry(input, item.id)} />} + /> + + + } + /> + handleDeleteEntry(item.id)} + /> + + } + /> + ) + }) + )} ) } diff --git a/extensions/password-vault/tests/operations.test.mjs b/extensions/password-vault/tests/operations.test.mjs index beb7005e..419c8c6c 100644 --- a/extensions/password-vault/tests/operations.test.mjs +++ b/extensions/password-vault/tests/operations.test.mjs @@ -2,7 +2,7 @@ import test, { beforeEach, afterEach } from 'node:test' import assert from 'node:assert/strict' import { getDeclarativeBridge } from '@ztools/declarative-ui' import { createHost, mount, mountPushed, tick } from '../../shared/test-harness.mjs' -import Vault, { encryptVaultEntries, decryptVaultEntries, createVaultEntry, commands } from '../dist/index.js' +import Vault, { encryptVaultEntries, decryptVaultEntries, createVaultEntry, commands, resolveOpenableUrl } from '../dist/index.js' const key = 'ztools.password-vault.envelope.v1', password = 'audit-only-passphrase' let host, views, originalEntry beforeEach(async () => { @@ -179,3 +179,106 @@ test('导出加密备份 JSON:仅导出加密信封密文,绝不含明文, const lockedParsed = JSON.parse(host.clipboard.text) assert.deepEqual(await decryptVaultEntries(password, lockedParsed), [originalEntry]) }) + +test('锁定态支持加密备份恢复:校验密码失败不覆写,确认替换后原子恢复并解锁', async () => { + const backupEntry = createVaultEntry({ + title: 'GitHub 恢复账号', + category: 'login', + username: 'restored-user', + endpoint: 'github.com/settings', + secretPlain: 'restored-secret-999', + note: 'restored-note' + }) + const backupPassword = 'backup-master-passphrase' + const backupJson = JSON.stringify(await encryptVaultEntries(backupPassword, [backupEntry])) + + const v = await mount(Vault, host); views.push(v) + const importAction = v.actions().find(a => a.props.title === '导入加密备份恢复') + assert.equal(importAction.type, 'Action.Push') + host.pushed.push(importAction.props.target); await tick() + const importForm = await form() + + // 1. 密码错误时拒绝恢复,原库不变 + const before = host.storage.get(key) + await importForm.fill('backupJson', backupJson) + await importForm.fill('backupPassword', 'wrong-backup-password') + await importForm.run(null, '解密验证并恢复保险箱') + assert.equal(host.storage.get(key), before) + assert.equal(host.lastToast().style, 'FAILURE') + + // 2. 已有保险箱时取消二次确认,原库不变 + host.setConfirm(false) + await importForm.fill('backupPassword', backupPassword) + await importForm.run(null, '解密验证并恢复保险箱') + assert.equal(host.storage.get(key), before) + assert.equal(host.confirms.length, 1) + + // 3. 确认替换后成功恢复并解锁 + host.setConfirm(true) + await importForm.run(null, '解密验证并恢复保险箱') + assert.equal(host.lastToast().style, 'SUCCESS') + assert.ok(v.item(backupEntry.id)) + assert.equal(v.tree().props.isShowingDetail, true) + const restored = await decryptVaultEntries(backupPassword, JSON.parse(JSON.parse(host.storage.get(key)))) + assert.deepEqual(restored, [backupEntry]) +}) + +test('解锁态支持网址直开安全校验、掩码 Detail、修改主密码与空库零假数据', async () => { + assert.equal(resolveOpenableUrl('https://github.com/login'), 'https://github.com/login') + assert.equal(resolveOpenableUrl('github.com'), 'https://github.com/') + assert.equal(resolveOpenableUrl('javascript:alert(1)'), null) + assert.equal(resolveOpenableUrl('file:///etc/passwd'), null) + + const webEntry = createVaultEntry({ + title: 'Web 控制台', + category: 'login', + username: 'admin@example.com', + endpoint: 'console.example.com/login', + secretPlain: 'web-console-secret', + note: 'secret-note' + }) + const unsafeEntry = createVaultEntry({ + title: '危险协议条目', + category: 'server', + endpoint: 'javascript:alert(1)', + secretPlain: 'server-secret' + }) + await store([webEntry, unsafeEntry]) + const v = await open() + + // 掩码 Detail 未显明文前绝不泄露密码和备注 + const webItem = v.item(webEntry.id) + const detailText = JSON.stringify(webItem.props.detail) + assert.ok(!detailText.includes('web-console-secret')) + assert.ok(!detailText.includes('secret-note')) + assert.match(detailText, /••••••••••••/) + + // 合法网址提供 OpenInBrowser,危险协议不提供 + const openAction = v.actions(webItem).find(a => a.props.title === '在浏览器中打开网址') + assert.equal(openAction.type, 'Action.OpenInBrowser') + assert.equal(openAction.props.url, 'https://console.example.com/login') + const unsafeOpenAction = v.actions(v.item(unsafeEntry.id)).find(a => a.props.title === '在浏览器中打开网址') + assert.equal(unsafeOpenAction, undefined) + + // 修改主密码:原密码解锁失败,新密码解锁成功 + const changeAction = v.actions(webItem).find(a => a.props.title === '修改主密码') + assert.equal(changeAction.type, 'Action.Push') + host.pushed.push(changeAction.props.target); await tick() + const changeForm = await form() + const nextPwd = 'new-strong-master-2026' + await changeForm.fill('currentMasterPassword', password) + await changeForm.fill('newMasterPassword', nextPwd) + await changeForm.fill('confirmNewMasterPassword', nextPwd) + await changeForm.run(null, '验证并重新加密保险箱') + assert.equal(host.lastToast().style, 'SUCCESS') + const envelopeAfter = JSON.parse(JSON.parse(host.storage.get(key))) + await assert.rejects(decryptVaultEntries(password, envelopeAfter)) + assert.equal((await decryptVaultEntries(nextPwd, envelopeAfter)).length, 2) + + // 空库解锁零假数据 + await store([]) + const emptyView = await open() + assert.equal(emptyView.tree().props.isShowingDetail, false) + assert.ok(emptyView.item('empty-vault')) + assert.equal(emptyView.items().length, 1) +}) diff --git a/extensions/pomodoro-focus/plugin.json b/extensions/pomodoro-focus/plugin.json index 32db2742..b72a08a0 100644 --- a/extensions/pomodoro-focus/plugin.json +++ b/extensions/pomodoro-focus/plugin.json @@ -1,7 +1,7 @@ { "id": "pomodoro-focus", "name": "番茄倒数", - "version": "1.0.7", + "version": "1.0.8", "description": "25 分钟番茄专注与短长休息,离页继续计时、重启恢复状态;本地保存重要日程倒数日并发送系统通知", "author": "ZTools Team", "category": [ diff --git a/extensions/pomodoro-focus/src/focus-stats.ts b/extensions/pomodoro-focus/src/focus-stats.ts new file mode 100644 index 00000000..f849ebaa --- /dev/null +++ b/extensions/pomodoro-focus/src/focus-stats.ts @@ -0,0 +1,149 @@ +import { LocalStorage } from '@ztools/declarative-ui' +import type { FocusState } from './focus-host.js' + +export const DAILY_STATS_STORAGE_KEY = 'ztools:pomodoro-daily-stats-v1' + +export interface DailyFocusStats { + date: string + completedSessions: number + totalFocusMinutes: number + recordedSessionIds: string[] + sessionCycles: Record +} + +export function createEmptyDailyStats(date: string): DailyFocusStats { + return { + date, + completedSessions: 0, + totalFocusMinutes: 0, + recordedSessionIds: [], + sessionCycles: {} + } +} + +export function normalizeDailyStats(raw: unknown, today: string): DailyFocusStats { + if (!raw || typeof raw !== 'object' || Array.isArray(raw)) { + return createEmptyDailyStats(today) + } + const obj = raw as Record + if (obj.date !== today) { + return createEmptyDailyStats(today) + } + const completedSessions = + typeof obj.completedSessions === 'number' && Number.isSafeInteger(obj.completedSessions) && obj.completedSessions >= 0 + ? obj.completedSessions + : 0 + const totalFocusMinutes = + typeof obj.totalFocusMinutes === 'number' && Number.isSafeInteger(obj.totalFocusMinutes) && obj.totalFocusMinutes >= 0 + ? obj.totalFocusMinutes + : 0 + const recordedSessionIds = Array.isArray(obj.recordedSessionIds) + ? obj.recordedSessionIds.filter((id): id is string => typeof id === 'string' && id.length > 0).slice(-200) + : [] + const sessionCycles: Record = {} + if (obj.sessionCycles && typeof obj.sessionCycles === 'object' && !Array.isArray(obj.sessionCycles)) { + for (const [key, val] of Object.entries(obj.sessionCycles as Record)) { + if (typeof val === 'number' && Number.isSafeInteger(val) && val >= 0) { + sessionCycles[key] = val + } + } + } + return { + date: today, + completedSessions, + totalFocusMinutes, + recordedSessionIds, + sessionCycles + } +} + +/** + * 基于宿主真实回执计算今日专注统计增量(严格去重,跨天自动归零,绝不造假) + */ +export function applyFocusStateToDailyStats( + current: DailyFocusStats, + state: FocusState | null, + today: string +): { stats: DailyFocusStats; changed: boolean } { + const base = current.date === today ? current : createEmptyDailyStats(today) + if (!state || !state.id) { + return { stats: base, changed: current.date !== today } + } + + let completedSessions = base.completedSessions + let totalFocusMinutes = base.totalFocusMinutes + let recordedSessionIds = base.recordedSessionIds + let sessionCycles = base.sessionCycles + let changed = current.date !== today + + // 1. 番茄钟模式:宿主每完成一轮专注,completedCycles 会递增 + if (state.mode === 'pomodoro' && state.completedCycles > 0) { + const prevCycles = sessionCycles[state.id] ?? 0 + if (state.completedCycles > prevCycles) { + const delta = state.completedCycles - prevCycles + const cycleMinutes = + state.phase === 'focus' && state.totalDurationMs >= 60_000 + ? Math.max(1, Math.round(state.totalDurationMs / 60_000)) + : 25 + completedSessions += delta + totalFocusMinutes += delta * cycleMinutes + sessionCycles = { ...sessionCycles, [state.id]: state.completedCycles } + changed = true + } + } + + // 2. 单次专注模式(如 45 分钟深度专注 / 自定义分钟):status === 'completed' 且 phase === 'focus' + if ( + state.mode === 'single' && + state.status === 'completed' && + state.phase === 'focus' && + !recordedSessionIds.includes(state.id) + ) { + const mins = Math.max(1, Math.round(state.totalDurationMs / 60_000)) + completedSessions += 1 + totalFocusMinutes += mins + recordedSessionIds = [...recordedSessionIds, state.id].slice(-200) + changed = true + } + + if (!changed) { + return { stats: base, changed: false } + } + + return { + stats: { + date: today, + completedSessions, + totalFocusMinutes, + recordedSessionIds, + sessionCycles + }, + changed: true + } +} + +export async function loadDailyFocusStats(today: string): Promise { + try { + const raw = await LocalStorage.getItem(DAILY_STATS_STORAGE_KEY) + return normalizeDailyStats(raw, today) + } catch { + return createEmptyDailyStats(today) + } +} + +export async function syncDailyFocusStats(state: FocusState | null, today: string): Promise { + const existing = await loadDailyFocusStats(today) + const preview = applyFocusStateToDailyStats(existing, state, today) + if (!preview.changed || preview.stats.completedSessions === 0) { + return preview.stats + } + try { + return await LocalStorage.updateItem(DAILY_STATS_STORAGE_KEY, (raw) => { + const current = normalizeDailyStats(raw, today) + const { stats } = applyFocusStateToDailyStats(current, state, today) + return stats + }) + } catch { + return preview.stats + } +} diff --git a/extensions/pomodoro-focus/src/i18n.ts b/extensions/pomodoro-focus/src/i18n.ts index ad0e6398..1538f23d 100644 --- a/extensions/pomodoro-focus/src/i18n.ts +++ b/extensions/pomodoro-focus/src/i18n.ts @@ -74,7 +74,7 @@ export const t = createTranslator({ navTitle: '番茄倒数', searchPlaceholder: '搜索倒数日名称或日期', filterAll: '全部倒数日', - summaryBar: '{count} 个倒数日 · 计时在离开页面后继续', + summaryBar: '今日专注 {sessions} 次 ({minutes} 分钟) · {count} 个倒数日', btnRefresh: '刷新', btnNewCountdown: '新建倒数日', loadErrorTitle: '无法确认当前状态', @@ -82,7 +82,20 @@ export const t = createTranslator({ timerStatePaused: '{phase}已暂停', timerStateRunning: '{phase}进行中', timerReadyTitle: '番茄钟已就绪', - timerCyclesSubtitle: '累计完成 {cycles} 轮番茄{warning}', + timerCyclesSubtitle: '累计完成 {cycles} 轮番茄 · 今日 {sessions} 次 / {minutes} 分钟{warning}', + sectionFocusTitle: '专注计时与快捷预设', + sectionCountdownsTitle: '重要倒数日 ({count})', + presetFocus25Title: '25 分钟标准番茄', + presetFocus25Subtitle: '经典 25m 专注 + 5m 短休循环,适合常规任务推进', + presetFocus45Title: '45 分钟深度专注', + presetFocus45Subtitle: '长周期沉浸式深度工作,适合编码与写作', + presetShortBreakTitle: '5 分钟短休息', + presetShortBreakSubtitle: '短暂离屏放松眼睛与肩颈,恢复注意力', + presetLongBreakTitle: '15 分钟长休息', + presetLongBreakSubtitle: '深度恢复精力,适合连续专注后调整节奏', + presetActionStart: '立即开始 {title}', + presetActionSwitch: '切换为 {title}(取消当前计时)', + presetBusyHint: '当前已有计时进行中 · 回车可取消并切换', actionCancelTimer: '取消当前计时', actionEditCountdown: '编辑倒数日', actionCopySummary: '复制天数摘要', @@ -165,7 +178,7 @@ export const t = createTranslator({ navTitle: 'Pomodoro & Countdowns', searchPlaceholder: 'Search countdown title or date…', filterAll: 'All Countdowns', - summaryBar: '{count} countdown(s) · Timer continues in background', + summaryBar: 'Today: {sessions} session(s) ({minutes} min) · {count} countdown(s)', btnRefresh: 'Refresh', btnNewCountdown: 'New Countdown', loadErrorTitle: 'Unable to verify current status', @@ -173,7 +186,20 @@ export const t = createTranslator({ timerStatePaused: '{phase} Paused', timerStateRunning: '{phase} Running', timerReadyTitle: 'Pomodoro Ready', - timerCyclesSubtitle: 'Completed {cycles} cycle(s){warning}', + timerCyclesSubtitle: 'Completed {cycles} cycle(s) · Today {sessions} / {minutes} min{warning}', + sectionFocusTitle: 'Focus Timer & Presets', + sectionCountdownsTitle: 'Countdowns ({count})', + presetFocus25Title: '25-Min Standard Pomodoro', + presetFocus25Subtitle: 'Classic 25m focus + 5m break cycle for steady progress', + presetFocus45Title: '45-Min Deep Focus', + presetFocus45Subtitle: 'Extended single session for deep coding or writing', + presetShortBreakTitle: '5-Min Short Break', + presetShortBreakSubtitle: 'Brief eye and posture reset between sessions', + presetLongBreakTitle: '15-Min Long Break', + presetLongBreakSubtitle: 'Extended recharge after multiple focus cycles', + presetActionStart: 'Start {title}', + presetActionSwitch: 'Switch to {title} (Cancel Current)', + presetBusyHint: 'Timer active · Press Enter to cancel and switch', actionCancelTimer: 'Cancel Timer', actionEditCountdown: 'Edit Countdown', actionCopySummary: 'Copy Days Summary', diff --git a/extensions/pomodoro-focus/src/index.tsx b/extensions/pomodoro-focus/src/index.tsx index 9542b223..954db61a 100644 --- a/extensions/pomodoro-focus/src/index.tsx +++ b/extensions/pomodoro-focus/src/index.tsx @@ -2,6 +2,7 @@ import React, { Action, ActionPanel, Form, Icon, List, Toast, confirmAlert, show import { enrichAndSortCountdowns, formatRemainingMmSs, parseCustomFocusMinutes, resolveCountdownRepeat, validateCountdownInput } from './pomodoro-service.js' import { changeCountdown, loadCountdowns } from './countdown-storage.js' import { focusCall, type FocusState } from './focus-host.js' +import { createEmptyDailyStats, syncDailyFocusStats, type DailyFocusStats } from './focus-stats.js' import type { CountdownCategory, CountdownItem, CountdownRepeat } from './types.js' import { t } from './i18n.js' @@ -59,6 +60,7 @@ export function PomodoroFocusCommand({ startImmediately = false, newCountdown = const { push } = useNavigation() const [state, setState] = useState(null), [items, setItems] = useState([]) const [category, setCategory] = useState('all'), [query, setQuery] = useState(''), [day, setDay] = useState(localDay()) + const [dailyStats, setDailyStats] = useState(() => createEmptyDailyStats(localDay())) const [loaded, setLoaded] = useState(false), [busy, setBusy] = useState(false), [error, setError] = useState('') const [startBlocked, setStartBlocked] = useState(false) // guard 只管用户操作;每秒轮询单独用 polling,不能让轮询占住锁把用户按键悄悄吞掉。 @@ -72,11 +74,16 @@ export function PomodoroFocusCommand({ startImmediately = false, newCountdown = finally { guard.current = false; if (alive.current) setBusy(false) } } const refresh = async (autoStart = false) => perform(async () => { + const today = localDay() const [current, countdowns] = await Promise.all([focusCall('focus_get_current'), loadCountdowns()]) let next = current const occupied = ['running', 'paused'].includes(current?.status ?? '') if (autoStart && !occupied) next = await focusCall('focus_start', { mode: 'pomodoro', title: t('focusDefaultTitle') }) - if (alive.current) { setState(next); setItems(countdowns); setError(''); setLoaded(true); ready.current = true; setStartBlocked(autoStart && occupied) } + const nextStats = await syncDailyFocusStats(next, today) + if (alive.current) { + setState(next); setItems(countdowns); setDay(today); setDailyStats(nextStats) + setError(''); setLoaded(true); ready.current = true; setStartBlocked(autoStart && occupied) + } // “立即开始专注”被已有计时挡住时如实说明,不能静默无反应。 if (alive.current && autoStart && occupied && current) { const breaking = current.phase !== 'focus' @@ -98,7 +105,12 @@ export function PomodoroFocusCommand({ startImmediately = false, newCountdown = polling.current = true const issued = generation.current const fresh = () => alive.current && !guard.current && issued === generation.current - void focusCall('focus_get_current').then(next => { if (fresh()) { setState(next); setDay(localDay()) } }) + void focusCall('focus_get_current').then(async next => { + if (!fresh()) return + const today = localDay() + const nextStats = await syncDailyFocusStats(next, today) + if (fresh()) { setState(next); setDay(today); setDailyStats(nextStats) } + }) .catch(e => { if (fresh()) setError(t('errPollTimerFailed', { error: errorText(e) })) }) .finally(() => { polling.current = false }) }, 1000) @@ -106,7 +118,9 @@ export function PomodoroFocusCommand({ startImmediately = false, newCountdown = }, []) const timerAction = (method: string, params: Record = {}) => perform(async () => { const next = await focusCall(method, params) - if (alive.current) { setState(next); setError(''); setStartBlocked(false) } + const today = localDay() + const nextStats = await syncDailyFocusStats(next, today) + if (alive.current) { setState(next); setDay(today); setDailyStats(nextStats); setError(''); setStartBlocked(false) } }, t('errActionUnconfirmed')) // 先取消休息再开始专注;取消成功、开始失败时界面停在已取消状态并提示失败,不假装已开始。 const skipBreakAndFocus = () => perform(async () => { @@ -114,7 +128,20 @@ export function PomodoroFocusCommand({ startImmediately = false, newCountdown = if (!alive.current) return setState(cancelled); setStartBlocked(false) const next = await focusCall('focus_start', { mode: 'pomodoro', title: t('focusDefaultTitle') }) - if (alive.current) { setState(next); setError('') } + const today = localDay() + const nextStats = await syncDailyFocusStats(next, today) + if (alive.current) { setState(next); setDay(today); setDailyStats(nextStats); setError('') } + }, t('errStartFocusFailed')) + const startPreset = (params: Record, shouldCancelFirst: boolean) => perform(async () => { + if (shouldCancelFirst) { + const cancelled = await focusCall('focus_cancel') + if (!alive.current) return + setState(cancelled); setStartBlocked(false) + } + const next = await focusCall('focus_start', params) + const today = localDay() + const nextStats = await syncDailyFocusStats(next, today) + if (alive.current) { setState(next); setDay(today); setDailyStats(nextStats); setError('') } }, t('errStartFocusFailed')) const active = state?.status === 'running' || state?.status === 'paused' const paused = state?.status === 'paused' @@ -126,7 +153,45 @@ export function PomodoroFocusCommand({ startImmediately = false, newCountdown = const customFocusMinutes = parseCustomFocusMinutes(query) const startCustomFocus = (minutes: number) => timerAction('focus_start', { mode: 'single', durationMinutes: minutes, title: t('customFocusSessionTitle', { minutes }) }) - const rows = enrichAndSortCountdowns(items, day).filter(item => (category === 'all' || item.category === category) && `${item.title} ${item.targetDate}`.toLowerCase().includes(query.trim().toLowerCase())) + const normalizedQuery = query.trim().toLowerCase() + const focusPresets = [ + { + id: 'preset-focus-25', + title: t('presetFocus25Title'), + subtitle: t('presetFocus25Subtitle'), + minutes: 25, + icon: Icon.Clock, + params: { mode: 'pomodoro', title: t('presetFocus25Title') } + }, + { + id: 'preset-focus-45', + title: t('presetFocus45Title'), + subtitle: t('presetFocus45Subtitle'), + minutes: 45, + icon: Icon.Bolt, + params: { mode: 'single', durationMinutes: 45, title: t('presetFocus45Title') } + }, + { + id: 'preset-short-break-5', + title: t('presetShortBreakTitle'), + subtitle: t('presetShortBreakSubtitle'), + minutes: 5, + icon: Icon.Checkmark, + params: { mode: 'single', durationMinutes: 5, title: t('presetShortBreakTitle') } + }, + { + id: 'preset-long-break-15', + title: t('presetLongBreakTitle'), + subtitle: t('presetLongBreakSubtitle'), + minutes: 15, + icon: Icon.Checkmark, + params: { mode: 'single', durationMinutes: 15, title: t('presetLongBreakTitle') } + } + ] + const visiblePresets = normalizedQuery + ? focusPresets.filter(preset => `${preset.title} ${preset.subtitle} ${preset.minutes}`.toLowerCase().includes(normalizedQuery)) + : focusPresets + const rows = enrichAndSortCountdowns(items, day).filter(item => (category === 'all' || item.category === category) && `${item.title} ${item.targetDate}`.toLowerCase().includes(normalizedQuery)) const remove = (item: CountdownItem) => perform(async () => { if (!await confirmAlert({ title: t('confirmDeleteTitle', { title: item.title }), primaryAction: { title: t('confirmDeletePrimary'), style: 'destructive' } })) return if (!alive.current) return @@ -135,7 +200,7 @@ export function PomodoroFocusCommand({ startImmediately = false, newCountdown = }, t('errDeleteFailedKept')) return } - filterBar={{ summaryText: error || t('summaryBar', { count: rows.length }), actions: [{ id: 'refresh', title: t('btnRefresh'), onAction: () => refresh() }, { id: 'new', title: t('btnNewCountdown'), onAction: () => push() }] }}> + filterBar={{ summaryText: error || t('summaryBar', { sessions: dailyStats.completedSessions, minutes: dailyStats.totalFocusMinutes, count: rows.length }), actions: [{ id: 'refresh', title: t('btnRefresh'), onAction: () => refresh() }, { id: 'new', title: t('btnNewCountdown'), onAction: () => push() }] }}> {error ? refresh()} />} /> : loaded ? <> {customFocusMinutes !== null && ( )} - - {startBlocked && skipAction} - {primaryAction} - {!startBlocked && skipAction} - {active && timerAction('focus_cancel')} />} - } /> - {rows.map(item => { const original = items.find(value => value.id === item.id)!; return - push()} /> - - remove(original)} /> - } /> })} - {!rows.length && customFocusMinutes === null && } + + + {startBlocked && skipAction} + {primaryAction} + {!startBlocked && skipAction} + {active && timerAction('focus_cancel')} />} + } /> + {visiblePresets.map(preset => ( + + startPreset(preset.params, active)} + /> + + } + /> + ))} + + + {rows.map(item => { const original = items.find(value => value.id === item.id)!; return + push()} /> + + remove(original)} /> + } /> })} + {!rows.length && customFocusMinutes === null && } + : null} } diff --git a/extensions/pomodoro-focus/tests/pomodoro.test.mjs b/extensions/pomodoro-focus/tests/pomodoro.test.mjs index 94b7f769..adda5909 100644 --- a/extensions/pomodoro-focus/tests/pomodoro.test.mjs +++ b/extensions/pomodoro-focus/tests/pomodoro.test.mjs @@ -4,6 +4,7 @@ import assert from 'node:assert/strict' import { createHost, mount, mountPushed, tick } from '../../shared/test-harness.mjs' import Command, { commands, localDay } from '../dist/index.js' import { COUNTDOWN_STORAGE_KEY, loadCountdowns, changeCountdown } from '../dist/countdown-storage.js' +import { DAILY_STATS_STORAGE_KEY, applyFocusStateToDailyStats, createEmptyDailyStats, loadDailyFocusStats } from '../dist/focus-stats.js' import { calculateDaysLeft, parseCustomFocusMinutes, validateCountdownInput } from '../dist/pomodoro-service.js' let host, views, state const fresh = () => ({ id: 'session-1', title: '25 分钟深度专注', status: 'running', mode: 'pomodoro', phase: 'focus', totalDurationMs: 1_500_000, remainingMs: 1_500_000, completedCycles: 0 }) @@ -194,3 +195,75 @@ test('搜索框输入 5~180 纯数字动态生成自定义专注项并真实调 await v.search('4') assert.equal(v.items().some(i => i.props.id === 'pomodoro-custom-focus'), false) }) + +test('专注预设(25m/45m/短休/长休)可直接启动与切换,真实透传宿主参数', async () => { + host.ipc.focus_start = async (params) => { + const mins = params.durationMinutes ?? 25 + return state = { + ...fresh(), + id: `session-${mins}`, + mode: params.mode ?? 'pomodoro', + title: params.title, + totalDurationMs: mins * 60_000, + remainingMs: mins * 60_000 + } + } + const v = await open() + assert.ok(v.item('preset-focus-25')) + assert.ok(v.item('preset-focus-45')) + assert.ok(v.item('preset-short-break-5')) + assert.ok(v.item('preset-long-break-15')) + + // 空闲时启动 45 分钟深度专注 + await v.run(v.item('preset-focus-45'), '立即开始 45 分钟深度专注') + assert.equal(host.ipcCalls.at(-1)[0], 'focus_start') + assert.equal(host.ipcCalls.at(-1)[1].durationMinutes, 45) + assert.equal(host.ipcCalls.at(-1)[1].mode, 'single') + assert.match(v.text(), /45:00/) + + // 运行中切换至 5 分钟短休息:先 focus_cancel 再 focus_start + await v.run(v.item('preset-short-break-5'), '切换为 5 分钟短休息(取消当前计时)') + assert.deepEqual(host.ipcCalls.slice(-2).map(([m]) => m), ['focus_cancel', 'focus_start']) + assert.equal(host.ipcCalls.at(-1)[1].durationMinutes, 5) + assert.match(v.text(), /05:00/) +}) + +test('今日统计基于宿主真实完成回执持久化、防重复累加且跨天自动归零', async () => { + const today = localDay() + // 1. 单次 45 分钟专注完成 -> 今日 +1 次 / +45 分钟;重复同 sessionId 不重复累加 + const s1 = applyFocusStateToDailyStats( + createEmptyDailyStats(today), + { ...fresh(), id: 'single-45', mode: 'single', status: 'completed', phase: 'focus', totalDurationMs: 45 * 60_000, remainingMs: 0 }, + today + ) + assert.equal(s1.changed, true) + assert.equal(s1.stats.completedSessions, 1) + assert.equal(s1.stats.totalFocusMinutes, 45) + const s1Dup = applyFocusStateToDailyStats( + s1.stats, + { ...fresh(), id: 'single-45', mode: 'single', status: 'completed', phase: 'focus', totalDurationMs: 45 * 60_000, remainingMs: 0 }, + today + ) + assert.equal(s1Dup.changed, false) + assert.equal(s1Dup.stats.completedSessions, 1) + + // 2. 跨天自动归零,不沿用昨日统计 + const nextDay = applyFocusStateToDailyStats(s1.stats, null, '2099-01-01') + assert.equal(nextDay.stats.completedSessions, 0) + assert.equal(nextDay.stats.totalFocusMinutes, 0) + + // 3. 真实页面持久化:宿主完成 1 轮番茄(completedCycles=1)后写入 LocalStorage,重开页面准确恢复 + state = { ...fresh(), id: 'pomo-today', mode: 'pomodoro', phase: 'short_break', completedCycles: 1, totalDurationMs: 300_000, remainingMs: 240_000 } + const v = await open() + assert.match(v.text(), /今日 1 次 \/ 25 分钟/) + assert.ok(host.storage.has(DAILY_STATS_STORAGE_KEY)) + v.unmount() + + // 宿主已无活跃计时,重开后今日统计仍持久化保留 + state = null + const reopened = await open() + assert.match(reopened.text(), /今日 1 次 \/ 25 分钟/) + const stored = await loadDailyFocusStats(today) + assert.equal(stored.completedSessions, 1) + assert.equal(stored.totalFocusMinutes, 25) +}) diff --git a/extensions/process-monitor/package.json b/extensions/process-monitor/package.json index 2450ce57..74bf71da 100644 --- a/extensions/process-monitor/package.json +++ b/extensions/process-monitor/package.json @@ -1,6 +1,6 @@ { "name": "@ztools/plugin-process-monitor", - "version": "1.0.0", + "version": "2.0.14", "description": "实时枚举系统进程树、CPU/内存占用、签名状态与关联 Windows 服务,支持定位文件与强制结束异常进程", "main": "dist/index.js", "types": "dist/index.d.ts", diff --git a/extensions/process-monitor/plugin.json b/extensions/process-monitor/plugin.json index e67e1fa3..f3ba700f 100644 --- a/extensions/process-monitor/plugin.json +++ b/extensions/process-monitor/plugin.json @@ -2,7 +2,7 @@ "id": "process-monitor", "name": "进程监控", "description": "查看本机进程的 CPU 与内存占用、查询本地端口被哪个进程占用,可定位程序文件,确认后结束进程", - "version": "2.0.13", + "version": "2.0.14", "minAppVersion": "1.1.8.0", "author": "ZTools Team", "entry": "dist/index.js", diff --git a/extensions/process-monitor/src/i18n.ts b/extensions/process-monitor/src/i18n.ts index 8d9c9dc9..25aec234 100644 --- a/extensions/process-monitor/src/i18n.ts +++ b/extensions/process-monitor/src/i18n.ts @@ -38,28 +38,31 @@ const MESSAGES = { locatedInFileMgr: "已在{mgr}中定位", openPathFailedTitle: "打开路径失败", openPathFailedMsg: "{path}\n文件可能已被移动或删除,或授权已过期,请刷新进程列表后再试", - navTitle: "进程监控", - searchPortPlaceholder: "输入本地端口号,例如 8080", - searchDefaultPlaceholder: "搜索进程、PID 或输入 port:8080 查询端口占用", + navTitle: "进程与端口监控", + searchPortPlaceholder: "输入端口号(如 3000、:8080)或进程名筛选", + searchDefaultPlaceholder: "搜索进程名、PID、命令行,或输入 :3000 查端口", viewDropdownTooltip: "切换进程筛选与排序维度", viewPort: "本地端口占用", - viewMemory: "全部进程 · 按内存排序", - viewCpu: "全部进程 · 按 CPU 排序", + viewMemory: "按内存排序", + viewCpu: "按 CPU 排序", viewHighLoad: "仅高负载进程", viewSystem: "系统关键服务", viewUser: "用户应用程序", - viewName: "按进程名称排序", - viewPid: "按 PID 升序", + viewName: "按名称排序", + viewPid: "按 PID 排序", summaryError: "数据不可用或已过期:{error}", summaryPortsError: "端口读取失败:{error}", summaryPorts: "本地端口匹配 {count} 个进程{partial}", - portsPartialNote: "(只能看到当前用户进程的端口,系统服务占用的端口可能查不到)", - summaryStats: "CPU 负载 {cpu}% · 物理内存已用 {used} / {total} ({pct}%) · 活动进程 {count} 个", + portsPartialNote: "(仅显示当前用户可见进程端口)", + summaryStats: "CPU {cpu}% · 内存 {used} / {total} ({pct}%) · 进程 {count} 个", refreshListBtn: "刷新列表", - pauseAutoRefreshBtn: "暂停自动刷新", - resumeAutoRefreshBtn: "开启自动刷新", + pauseAutoRefreshBtn: "暂停刷新", + resumeAutoRefreshBtn: "恢复刷新", cannotReadProcessList: "无法读取进程列表", openInClientHint: "在 ZTools 中打开「进程监控」后查看本机进程", + emptyTitle: "未找到匹配的进程", + emptyPortTitle: "未找到匹配的本地端口占用", + emptyDesc: "尝试调整搜索词、输入 :3000 查端口,或切换上方筛选视图", sectionPortsTitle: "端口占用进程({count})", sectionProcsTitle: "活动进程列表({count})", svcHint: "托管服务 {count} 项", @@ -67,12 +70,15 @@ const MESSAGES = { threadsLabel: "线程 {count}", pathNotProvided: "路径未提供", tagCritical: "系统关键", + tagHighRisk: "高危", tagHighLoad: "高负载", tagSystemService: "系统服务", tagUserApp: "用户应用", + tagSafeEnd: "允许结束", actionEndProcess: "结束进程", actionForceEndTree: "强制结束进程树", - actionLocateDir: "定位文件目录", + actionLocateDir: "在文件夹中显示", + actionOpenLocalPort: "在浏览器打开 localhost:{port}", actionCopyPid: "复制 PID", copiedPidTitle: "已复制 PID", actionGracefulClose: "平缓关闭进程 (Graceful)", @@ -85,6 +91,25 @@ const MESSAGES = { copiedCmdLineTitle: "已复制启动命令行", noCmdLineTitle: "没有读取到启动命令行", noCmdLineMsg: "当前系统没有为 {name} (PID: {pid}) 提供启动命令行", + detailCriticalBanner: "> **系统核心进程保护**:该进程为操作系统关键组件,已强制禁止结束,防止系统崩溃或注销。", + detailHighRiskBanner: "> **高危系统界面进程**:结束可能导致桌面、任务栏或程序坞短暂重启,操作前需高危二次确认。", + detailSectionCmdLine: "启动命令行", + detailSectionExecPath: "可执行文件路径", + detailSectionPorts: "监听端口", + detailNoCmdLine: "系统未提供该进程的启动命令行", + detailNoPath: "系统未提供该进程的可执行文件路径", + detailMetaPid: "PID", + detailMetaParentPid: "父进程", + detailMetaCpu: "CPU 占用", + detailMetaMemory: "内存占用", + detailMetaPrivateMem: "私有内存", + detailMetaThreads: "线程数", + detailMetaHandles: "句柄数", + detailMetaPorts: "监听端口", + detailMetaProtection: "安全级别", + detailMetaProtectedLocked: "系统关键 · 禁止结束", + detailMetaHighRisk: "高危 · 需二次确认", + detailMetaNormal: "普通进程 · 允许结束", // logic.ts notInClient: "需要在 ZTools 客户端中使用", forbiddenReason: "系统内核与会话管理关键进程受保护:结束后会导致系统崩溃或当前用户被注销,已拦截", @@ -164,13 +189,13 @@ const MESSAGES = { locatedInFileMgr: "Revealed in {mgr}", openPathFailedTitle: "Failed to reveal path", openPathFailedMsg: "{path}\nFile may have been moved/deleted, or permission expired; refresh and retry", - navTitle: "Process Monitor", - searchPortPlaceholder: "Enter local port, e.g. 8080", - searchDefaultPlaceholder: "Search process, PID, or port:8080...", + navTitle: "Process & Port Monitor", + searchPortPlaceholder: "Enter port (e.g. 3000, :8080) or process name", + searchDefaultPlaceholder: "Search name, PID, command line, or :3000 for port", viewDropdownTooltip: "Filter & Sort", - viewPort: "Local Port Usage", - viewMemory: "All · By Memory", - viewCpu: "All · By CPU", + viewPort: "Local Ports", + viewMemory: "Sort by Memory", + viewCpu: "Sort by CPU", viewHighLoad: "High Load Only", viewSystem: "System Services", viewUser: "User Apps", @@ -179,26 +204,32 @@ const MESSAGES = { summaryError: "Data unavailable or stale: {error}", summaryPortsError: "Port scan failed: {error}", summaryPorts: "{count} [[count:process|processes]] matching local ports{partial}", - portsPartialNote: " (only current user's process ports visible; system service ports may be hidden)", + portsPartialNote: " (current user processes only)", summaryStats: "CPU {cpu}% · RAM {used} / {total} ({pct}%) · {count} active", refreshListBtn: "Refresh", - pauseAutoRefreshBtn: "Pause Auto-Refresh", - resumeAutoRefreshBtn: "Resume Auto-Refresh", + pauseAutoRefreshBtn: "Pause Refresh", + resumeAutoRefreshBtn: "Resume Refresh", cannotReadProcessList: "Failed to read process list", - openInClientHint: "Open Process Monitor in ZTools to inspect local processes", + openInClientHint: "Open Process & Port Monitor in ZTools to inspect local processes", + emptyTitle: "No matching processes", + emptyPortTitle: "No matching local port bindings", + emptyDesc: "Try another keyword, enter :3000 to look up a port, or switch the filter view", sectionPortsTitle: "Processes Using Ports ({count})", sectionProcsTitle: "Active Processes ({count})", svcHint: "{count} service(s)", portLabel: "Port {ports}", threadsLabel: "{count} [[count:thread|threads]]", pathNotProvided: "Path not provided", - tagCritical: "System", + tagCritical: "Protected", + tagHighRisk: "High Risk", tagHighLoad: "High Load", tagSystemService: "Service", tagUserApp: "User App", + tagSafeEnd: "Safe", actionEndProcess: "Terminate Process", actionForceEndTree: "Kill Process Tree", - actionLocateDir: "Reveal File Location", + actionLocateDir: "Reveal in Folder", + actionOpenLocalPort: "Open localhost:{port} in Browser", actionCopyPid: "Copy PID", copiedPidTitle: "PID Copied", actionGracefulClose: "Graceful Close", @@ -211,6 +242,25 @@ const MESSAGES = { copiedCmdLineTitle: "Command Line Copied", noCmdLineTitle: "Command Line Unavailable", noCmdLineMsg: "System did not provide a command line for {name} (PID: {pid})", + detailCriticalBanner: "> **System Critical Protection**: This core OS process is locked and cannot be terminated.", + detailHighRiskBanner: "> **High-Risk System UI Process**: Terminating it may temporarily restart your desktop, taskbar, or Dock.", + detailSectionCmdLine: "Command Line", + detailSectionExecPath: "Executable Path", + detailSectionPorts: "Listening Ports", + detailNoCmdLine: "Startup command line not provided by system", + detailNoPath: "Executable path not provided by system", + detailMetaPid: "PID", + detailMetaParentPid: "Parent", + detailMetaCpu: "CPU", + detailMetaMemory: "Memory", + detailMetaPrivateMem: "Private Memory", + detailMetaThreads: "Threads", + detailMetaHandles: "Handles", + detailMetaPorts: "Listening Ports", + detailMetaProtection: "Protection", + detailMetaProtectedLocked: "Critical · Protected", + detailMetaHighRisk: "High Risk · Confirm", + detailMetaNormal: "Normal · Allowed", // logic.ts notInClient: "This plugin requires the ZTools desktop client", forbiddenReason: "System kernel & session critical processes are protected: terminating them will crash or log out the system", diff --git a/extensions/process-monitor/src/index.ts b/extensions/process-monitor/src/index.ts index ca74c788..edbda0e5 100644 --- a/extensions/process-monitor/src/index.ts +++ b/extensions/process-monitor/src/index.ts @@ -40,6 +40,10 @@ import { fetchProcessPortSnapshot, filterProcessesByPort, matchPortRows, + isPortQuery, + getProcessListeningPorts, + getLocalBrowsablePort, + extractCommandSummary, type ProcessPort } from './logic.js' @@ -48,16 +52,16 @@ import { resolveErrorMessage } from './error-i18n.js' export * from './logic.js' -type ProcessViewFilter = 'port' | 'memory' | 'cpu' | 'high-load' | 'system' | 'user' | 'name' | 'pid' +type ProcessViewFilter = 'memory' | 'cpu' | 'name' | 'port' | 'high-load' | 'user' | 'system' | 'pid' -/** - * 复制文本:等宿主确认写入成功后才提示成功;写入失败(内容为空、超过上限、剪贴板被占用等)时提示失败原因,不能假装已复制 - */ /** 系统文件管理器名称:Windows 路径为资源管理器,其余(macOS)为访达 */ function fileManagerName(samplePath: string): string { return /^[a-zA-Z]:[\\/]|^\\\\/.test(samplePath) ? t('fileMgrExplorer') : t('fileMgrFinder') } +/** + * 复制文本:等宿主确认写入成功后才提示成功;写入失败(内容为空、超过上限、剪贴板被占用等)时提示失败原因,不能假装已复制 + */ async function copyWithToast(text: string, successTitle: string, successMessage?: string): Promise { try { await Clipboard.copy(text) @@ -72,6 +76,114 @@ async function copyWithToast(text: string, successTitle: string, successMessage? await showToast({ style: Toast.Style.Success, title: successTitle, message: successMessage }) } +/** 安全包裹 Markdown 代码块,避免路径或命令行中的反引号破坏渲染 */ +function formatCodeBlock(text: string): string { + const safe = text.replace(/```/g, '\\`\\`\\`') + return `\`\`\`text\n${safe}\n\`\`\`` +} + +/** 构建右侧 Detail 面板(严格基于宿主实时数据,无真实数据时如实说明) */ +function buildProcessDetail( + proc: ProcessItem, + detailInfo: ProcessDetailInfo | undefined, + procServices: ProcessServiceInfo[], + listeningPorts: ProcessPort[], + parentName: string | undefined +) { + const risk = getTerminationRisk(proc.pid, proc.name) + const memVal = proc.workingSetBytes ?? proc.memoryBytes ?? 0 + const privateMem = detailInfo?.privateBytes ?? (proc.privateBytes > 0 ? proc.privateBytes : null) + const execPath = detailInfo?.path || proc.path || '' + const cmdLine = detailInfo?.commandLine || proc.commandLine || '' + const threads = detailInfo?.threadCount ?? proc.threadCount + const handles = detailInfo?.handleCount ?? (proc.handleCount && proc.handleCount > 0 ? proc.handleCount : null) + const parentPid = detailInfo?.parentPid ?? (proc.parentPid > 0 ? proc.parentPid : null) + const isHighLoad = proc.cpuPercent >= 25 || memVal >= 1024 * 1024 * 1024 + + const sections: string[] = [`# ${proc.name}`] + if (risk === 'forbidden') { + sections.push(t('detailCriticalBanner')) + } else if (risk === 'high-risk') { + sections.push(t('detailHighRiskBanner')) + } + + sections.push( + `### ${t('detailSectionCmdLine')}\n${cmdLine ? formatCodeBlock(cmdLine) : `_${t('detailNoCmdLine')}_`}` + ) + sections.push( + `### ${t('detailSectionExecPath')}\n${execPath ? formatCodeBlock(execPath) : `_${t('detailNoPath')}_`}` + ) + + if (listeningPorts.length > 0) { + const portLines = listeningPorts + .slice(0, 12) + .map((p) => { + const proto = p.protocol ? p.protocol.toUpperCase() : 'TCP' + const addr = p.localAddress || '127.0.0.1' + const state = p.state ? ` (${p.state})` : '' + return `- \`${proto}\` \`${addr}:${p.localPort}\`${state}` + }) + .join('\n') + sections.push(`### ${t('detailSectionPorts')}\n${portLines}`) + } + + const profileFields = describeProcessProfile(proc, detailInfo, procServices) + const portText = listeningPorts.length > 0 + ? [...new Set(listeningPorts.map((p) => `:${p.localPort}`))].join(', ') + : '' + + const metaItems = [ + Detail.Metadata.Label({ title: t('detailMetaPid'), text: String(proc.pid) }), + ...(parentPid !== null && parentPid > 0 + ? [ + Detail.Metadata.Label({ + title: t('detailMetaParentPid'), + text: parentName ? `${parentName} (${parentPid})` : String(parentPid) + }) + ] + : []), + Detail.Metadata.Label({ title: t('detailMetaCpu'), text: `${proc.cpuPercent.toFixed(1)}%` }), + Detail.Metadata.Label({ title: t('detailMetaMemory'), text: formatBytes(memVal) }), + ...(privateMem !== null && privateMem > 0 && privateMem !== memVal + ? [Detail.Metadata.Label({ title: t('detailMetaPrivateMem'), text: formatBytes(privateMem) })] + : []), + ...(threads !== undefined && threads !== null && threads > 0 + ? [Detail.Metadata.Label({ title: t('detailMetaThreads'), text: String(threads) })] + : []), + ...(handles !== null && handles > 0 + ? [Detail.Metadata.Label({ title: t('detailMetaHandles'), text: String(handles) })] + : []), + ...(portText ? [Detail.Metadata.Label({ title: t('detailMetaPorts'), text: portText })] : []), + Detail.Metadata.Separator(), + Detail.Metadata.TagList( + { title: t('detailMetaProtection') }, + Detail.Metadata.TagList.Item({ + text: + risk === 'forbidden' + ? t('detailMetaProtectedLocked') + : risk === 'high-risk' + ? t('detailMetaHighRisk') + : t('detailMetaNormal'), + color: risk === 'forbidden' || risk === 'high-risk' ? Color.Red : Color.SecondaryText + }), + ...(isHighLoad + ? [Detail.Metadata.TagList.Item({ text: t('tagHighLoad'), color: Color.Red })] + : []) + ), + ...(profileFields.length > 0 + ? [ + Detail.Metadata.Separator(), + ...profileFields.map((f) => Detail.Metadata.Label({ title: f.title, text: f.text })) + ] + : []) + ] + + return Detail({ + markdown: sections.join('\n\n'), + metadata: Detail.Metadata({}, ...metaItems) + }) +} + export default function ProcessMonitorCommand({ initialView = 'memory' }: { initialView?: ProcessViewFilter } = {}) { useLocale() const { push } = useNavigation() @@ -124,8 +236,8 @@ export default function ProcessMonitorCommand({ initialView = 'memory' }: { init setServices((prev) => ({ ...prev, [proc.pid]: svcRes })) } detailLoadedRef.current[proc.pid] = true - } catch { - // ignore background detail errors + } catch (err) { + console.warn('[process-monitor] loadProcessExtra failed:', err) } } @@ -230,11 +342,11 @@ export default function ProcessMonitorCommand({ initialView = 'memory' }: { init }, [autoRefresh]) useEffect(() => { - const portMode = viewFilter === 'port' || /^port:/i.test(searchText) - const query = portMode ? JSON.stringify([viewFilter, searchText]) : null + if (!inRealHost) return + const portMode = viewFilter === 'port' || isPortQuery(searchText) + const query = portMode ? JSON.stringify([viewFilter, searchText]) : 'background' const queryChanged = query !== portsQueryRef.current portsQueryRef.current = query - if (!portMode) return let active = true let sequence = 0 let inFlight = false @@ -244,9 +356,19 @@ export default function ProcessMonitorCommand({ initialView = 'memory' }: { init inFlight = true try { const snapshot = await fetchProcessPortSnapshot() - if (active && request === sequence) { setPorts(snapshot.rows); setPortsPartial(snapshot.partial); setPortsError('') } + if (active && request === sequence) { + setPorts(snapshot.rows) + setPortsPartial(snapshot.partial) + setPortsError('') + } } catch (error) { - if (active && request === sequence) { setPorts([]); setPortsPartial(false); setPortsError(error instanceof Error ? error.message : String(error)) } + if (active && request === sequence) { + setPorts([]) + setPortsPartial(false) + if (portMode) { + setPortsError(error instanceof Error ? error.message : String(error)) + } + } } finally { if (request === sequence) inFlight = false } @@ -254,7 +376,8 @@ export default function ProcessMonitorCommand({ initialView = 'memory' }: { init refreshPortsRef.current = () => load(true) // 暂停仅冻结定时更新;首次进入或查询变化仍读取一次。 if (autoRefresh || queryChanged) void load() - const timer = autoRefresh ? setInterval(() => { void load() }, 2000) : undefined + const intervalMs = portMode ? 2000 : 6000 + const timer = autoRefresh ? setInterval(() => { void load() }, intervalMs) : undefined const backgroundTimer = timer as unknown as { unref?: () => void } | undefined backgroundTimer?.unref?.() return () => { @@ -364,6 +487,7 @@ export default function ProcessMonitorCommand({ initialView = 'memory' }: { init setProcesses((prev) => prev.filter((p) => p.pid !== proc.pid)) void refreshData(false) + void refreshPortsRef.current?.() } async function handleOpenLocation(proc: ProcessItem) { @@ -406,9 +530,11 @@ export default function ProcessMonitorCommand({ initialView = 'memory' }: { init ? 'pid' : 'memory' - const portMode = viewFilter === 'port' || /^port:/i.test(searchText) + const portMode = viewFilter === 'port' || isPortQuery(searchText) const portRows = portMode ? matchPortRows(ports, searchText) : [] - const baseFiltered = portMode ? filterProcessesByPort(processes, ports, searchText) : filterProcesses(processes, searchText, tab, sortBy) + const baseFiltered = portMode + ? filterProcessesByPort(processes, ports, searchText) + : filterProcesses(processes, searchText, tab, sortBy) const filtered = viewFilter === 'high-load' ? baseFiltered.filter( @@ -416,6 +542,11 @@ export default function ProcessMonitorCommand({ initialView = 'memory' }: { init ) : baseFiltered + const procNameByPid = new Map() + for (const p of processes) { + procNameByPid.set(p.pid, p.name) + } + const totalMem = systemInfo.totalMemoryBytes || systemInfo.totalMemory || 0 const availMem = systemInfo.availableMemoryBytes || systemInfo.availableMemory || 0 const usedMem = systemInfo.usedMemoryBytes || Math.max(0, totalMem - availMem) @@ -423,29 +554,36 @@ export default function ProcessMonitorCommand({ initialView = 'memory' }: { init systemInfo.memoryUsagePercent || (totalMem > 0 ? Math.round((usedMem / totalMem) * 100) : 0) const totalCpuPercent = resolveCpuLoadPercent(systemInfo, processes) - const maxMemBytes = Math.max( - 1, - ...processes.map((p) => p.workingSetBytes ?? p.memoryBytes ?? 0) - ) + function handleSelectionChange(id: string | null) { + if (!id) return + const pid = Number(id) + if (!Number.isInteger(pid) || pid <= 0 || detailLoadedRef.current[pid]) return + const target = processes.find((p) => p.pid === pid) + if (target) { + detailLoadedRef.current[pid] = true + void loadProcessExtra(target) + } + } return List({ navigationTitle: t('navTitle'), searchBarPlaceholder: portMode ? t('searchPortPlaceholder') : t('searchDefaultPlaceholder'), onSearchTextChange: setSearchText, - isShowingDetail: false, + onSelectionChange: handleSelectionChange, + isShowingDetail: true, isLoading, searchBarAccessory: List.Dropdown({ tooltip: t('viewDropdownTooltip'), value: viewFilter, onChange: (val: string) => setViewFilter(val as ProcessViewFilter), children: [ - List.Dropdown.Item({ title: t('viewPort'), value: 'port' }), List.Dropdown.Item({ title: t('viewMemory'), value: 'memory' }), List.Dropdown.Item({ title: t('viewCpu'), value: 'cpu' }), + List.Dropdown.Item({ title: t('viewName'), value: 'name' }), + List.Dropdown.Item({ title: t('viewPort'), value: 'port' }), List.Dropdown.Item({ title: t('viewHighLoad'), value: 'high-load' }), - List.Dropdown.Item({ title: t('viewSystem'), value: 'system' }), List.Dropdown.Item({ title: t('viewUser'), value: 'user' }), - List.Dropdown.Item({ title: t('viewName'), value: 'name' }), + List.Dropdown.Item({ title: t('viewSystem'), value: 'system' }), List.Dropdown.Item({ title: t('viewPid'), value: 'pid' }) ] }), @@ -467,21 +605,21 @@ export default function ProcessMonitorCommand({ initialView = 'memory' }: { init }), actions: [ { - id: 'refresh-list', - label: t('refreshListBtn'), - title: t('refreshListBtn'), + id: 'toggle-auto-refresh', + label: autoRefresh ? t('pauseAutoRefreshBtn') : t('resumeAutoRefreshBtn'), + title: autoRefresh ? t('pauseAutoRefreshBtn') : t('resumeAutoRefreshBtn'), style: 'secondary', onAction: () => { - void handleRefresh() + handleToggleAutoRefresh() } }, { - id: 'toggle-auto-refresh', - label: autoRefresh ? t('pauseAutoRefreshBtn') : t('resumeAutoRefreshBtn'), - title: autoRefresh ? t('pauseAutoRefreshBtn') : t('resumeAutoRefreshBtn'), + id: 'refresh-list', + label: t('refreshListBtn'), + title: t('refreshListBtn'), style: 'secondary', onAction: () => { - handleToggleAutoRefresh() + void handleRefresh() } } ] @@ -496,128 +634,157 @@ export default function ProcessMonitorCommand({ initialView = 'memory' }: { init icon: Icon.ExclamationMark }) ] - : []), - List.Section({ - title: portMode - ? t('sectionPortsTitle', { count: filtered.length }) - : t('sectionProcsTitle', { count: filtered.length }), - children: filtered.map((proc) => { - const isCrit = getTerminationRisk(proc.pid, proc.name) === 'forbidden' - const memVal = proc.workingSetBytes ?? proc.memoryBytes ?? 0 - const memRatio = Math.min(100, Math.max(4, Math.round((memVal / maxMemBytes) * 100))) - const isHighLoad = proc.cpuPercent >= 25 || memVal >= 1024 * 1024 * 1024 - const procServices = services[proc.pid] || [] - const svcHint = procServices.length > 0 ? t('svcHint', { count: procServices.length }) : '' - - const viewProfileAction = Action({ - title: t('actionViewProfile'), - icon: Icon.MagnifyingGlass, - shortcut: { modifiers: ['ctrl'], key: 'i' }, - onAction: () => handleShowProfile(proc) - }) - const locateDirAction = Action({ - title: t('actionLocateDir'), - icon: Icon.Folder, - shortcut: { modifiers: ['ctrl'], key: 'o' }, - onAction: () => handleOpenLocation(proc) - }) - const copyActions = [ - Action({ - title: t('actionCopyPid'), - icon: Icon.Key, - shortcut: { modifiers: ['ctrl'], key: 'c' }, - onAction: () => copyWithToast(String(proc.pid), t('copiedPidTitle'), String(proc.pid)) - }), - Action({ - title: t('actionCopyExecPath'), - icon: Icon.Document, - shortcut: { modifiers: ['ctrl', 'shift'], key: 'c' }, - onAction: () => { - const targetPath = details[proc.pid]?.path || proc.path - if (targetPath) { - return copyWithToast(targetPath, t('copiedExecPathTitle'), targetPath) - } - showToast({ - style: Toast.Style.Failure, - title: t('pathUnavailableTitle'), - message: t('pathUnavailableMsg') - }) - } - }), - Action({ - title: t('actionCopyCmdLine'), - icon: Icon.Terminal, - onAction: () => { - // 只复制系统真实给出的命令行;没有时如实提示,不拿路径或进程名冒充 - const cmdLine = details[proc.pid]?.commandLine || proc.commandLine - if (cmdLine) return copyWithToast(cmdLine, t('copiedCmdLineTitle'), cmdLine) - showToast({ - style: Toast.Style.Failure, - title: t('noCmdLineTitle'), - message: t('noCmdLineMsg', { name: proc.name, pid: proc.pid }) - }) - } - }), - Action({ - title: t('refreshListBtn'), - icon: Icon.ArrowClockwise, - shortcut: { modifiers: ['ctrl'], key: 'r' }, - onAction: handleRefresh - }) - ] + : filtered.length === 0 && !isLoading + ? [ + List.EmptyView({ + title: portMode ? t('emptyPortTitle') : t('emptyTitle'), + description: t('emptyDesc'), + icon: Icon.MagnifyingGlass + }) + ] + : [ + List.Section({ + title: portMode + ? t('sectionPortsTitle', { count: filtered.length }) + : t('sectionProcsTitle', { count: filtered.length }), + children: filtered.map((proc) => { + const risk = getTerminationRisk(proc.pid, proc.name) + const isCrit = risk === 'forbidden' + const isHighRisk = risk === 'high-risk' + const memVal = proc.workingSetBytes ?? proc.memoryBytes ?? 0 + const isHighLoad = proc.cpuPercent >= 25 || memVal >= 1024 * 1024 * 1024 + const detailInfo = details[proc.pid] + const procServices = services[proc.pid] || [] + const listeningPorts = getProcessListeningPorts(portMode ? portRows : ports, proc.pid) + const browsablePort = getLocalBrowsablePort(portMode ? portRows : ports, proc.pid) + const portBadge = listeningPorts.length > 0 + ? [...new Set(listeningPorts.map((p) => `:${p.localPort}`))].slice(0, 2).join(' ') + : '' + const cmdSummary = extractCommandSummary(detailInfo?.commandLine || proc.commandLine || '', proc.name) + const parentPid = detailInfo?.parentPid ?? (proc.parentPid > 0 ? proc.parentPid : null) + const parentName = parentPid ? procNameByPid.get(parentPid) : undefined - return List.Item({ - id: String(proc.pid), - title: proc.name, - subtitle: [ - `PID: ${proc.pid}`, - ...(portMode ? [t('portLabel', { ports: [...new Set(portRows.filter(p => p.pid === proc.pid).map(p => p.localPort))].join(', ') })] : []), - ...(proc.threadCount ? [t('threadsLabel', { count: proc.threadCount })] : []), - ...(svcHint ? [svcHint] : []), - proc.path || proc.commandLine || t('pathNotProvided') - ].join(' · '), - icon: isCrit ? Icon.Shield : isHighLoad ? Icon.ExclamationMark : Icon.Terminal, - accessories: [ - { progress: { value: memRatio } }, - ...(isCrit - ? [{ tag: { value: t('tagCritical') } }] - : isHighLoad - ? [{ tag: { value: t('tagHighLoad'), color: Color.Red } }] - : [{ tag: { value: proc.isSystem ? t('tagSystemService') : t('tagUserApp') } }]), - { text: `CPU ${proc.cpuPercent.toFixed(1)}%` }, - { text: formatBytes(memVal) } - ], - actions: ActionPanel({ - title: `${proc.name} (PID: ${proc.pid})`, - children: isCrit - ? [viewProfileAction, locateDirAction, ...copyActions] - : [ + const openPortAction = browsablePort !== null + ? [ + Action.OpenInBrowser({ + title: t('actionOpenLocalPort', { port: browsablePort }), + url: `http://localhost:${browsablePort}`, + icon: Icon.Globe, + shortcut: { modifiers: ['ctrl', 'shift'], key: 'o' } + }) + ] + : [] + const viewProfileAction = Action({ + title: t('actionViewProfile'), + icon: Icon.MagnifyingGlass, + shortcut: { modifiers: ['ctrl'], key: 'i' }, + onAction: () => handleShowProfile(proc) + }) + const locateDirAction = Action({ + title: t('actionLocateDir'), + icon: Icon.Folder, + shortcut: { modifiers: ['ctrl'], key: 'o' }, + onAction: () => handleOpenLocation(proc) + }) + const copyActions = [ Action({ - title: t('actionGracefulClose'), - icon: Icon.Stop, - onAction: () => handleTerminate(proc, 'graceful') + title: t('actionCopyPid'), + icon: Icon.Key, + shortcut: { modifiers: ['ctrl'], key: 'c' }, + onAction: () => copyWithToast(String(proc.pid), t('copiedPidTitle'), String(proc.pid)) }), Action({ - title: t('actionEndProcess'), - icon: Icon.XMarkCircle, - style: 'destructive', - onAction: () => handleTerminate(proc, 'force') + title: t('actionCopyExecPath'), + icon: Icon.Document, + shortcut: { modifiers: ['ctrl', 'shift'], key: 'c' }, + onAction: () => { + const targetPath = details[proc.pid]?.path || proc.path + if (targetPath) { + return copyWithToast(targetPath, t('copiedExecPathTitle'), targetPath) + } + showToast({ + style: Toast.Style.Failure, + title: t('pathUnavailableTitle'), + message: t('pathUnavailableMsg') + }) + } }), Action({ - title: t('actionForceEndTree'), - icon: Icon.Trash, - style: 'destructive', - shortcut: { modifiers: ['ctrl'], key: 'return' }, - onAction: () => handleTerminate(proc, 'tree') + title: t('actionCopyCmdLine'), + icon: Icon.Terminal, + onAction: () => { + // 只复制系统真实给出的命令行;没有时如实提示,不拿路径或进程名冒充 + const cmdLine = details[proc.pid]?.commandLine || proc.commandLine + if (cmdLine) return copyWithToast(cmdLine, t('copiedCmdLineTitle'), cmdLine) + showToast({ + style: Toast.Style.Failure, + title: t('noCmdLineTitle'), + message: t('noCmdLineMsg', { name: proc.name, pid: proc.pid }) + }) + } }), - locateDirAction, - viewProfileAction, - ...copyActions + Action({ + title: t('refreshListBtn'), + icon: Icon.ArrowClockwise, + shortcut: { modifiers: ['ctrl'], key: 'r' }, + onAction: handleRefresh + }) ] - }) - }) - }) - }) + + return List.Item({ + id: String(proc.pid), + title: proc.name, + subtitle: [ + ...(portBadge ? [portBadge] : []), + `PID ${proc.pid}`, + ...(cmdSummary ? [cmdSummary] : []) + ].join(' · '), + icon: isCrit ? Icon.Shield : isHighLoad ? Icon.ExclamationMark : Icon.Terminal, + accessories: [ + ...(isCrit + ? [{ tag: { value: t('tagCritical'), color: Color.Red } }] + : isHighRisk + ? [{ tag: { value: t('tagHighRisk'), color: Color.Red } }] + : isHighLoad + ? [{ tag: { value: t('tagHighLoad'), color: Color.Red } }] + : []), + { text: `${proc.cpuPercent.toFixed(1)}%` }, + { text: formatBytes(memVal) } + ], + detail: buildProcessDetail(proc, detailInfo, procServices, listeningPorts, parentName), + actions: ActionPanel({ + title: `${proc.name} (PID: ${proc.pid})`, + children: isCrit + ? [...openPortAction, locateDirAction, viewProfileAction, ...copyActions] + : [ + Action({ + title: t('actionGracefulClose'), + icon: Icon.Stop, + onAction: () => handleTerminate(proc, 'graceful') + }), + Action({ + title: t('actionEndProcess'), + icon: Icon.XMarkCircle, + style: 'destructive', + onAction: () => handleTerminate(proc, 'force') + }), + Action({ + title: t('actionForceEndTree'), + icon: Icon.Trash, + style: 'destructive', + shortcut: { modifiers: ['ctrl'], key: 'return' }, + onAction: () => handleTerminate(proc, 'tree') + }), + ...openPortAction, + locateDirAction, + viewProfileAction, + ...copyActions + ] + }) + }) + }) + }) + ]) ] }) } diff --git a/extensions/process-monitor/src/logic.ts b/extensions/process-monitor/src/logic.ts index 54cde239..7369d97d 100644 --- a/extensions/process-monitor/src/logic.ts +++ b/extensions/process-monitor/src/logic.ts @@ -770,6 +770,7 @@ export function filterProcesses( p.name.toLowerCase().includes(q) || String(p.pid).includes(q) || (p.path && p.path.toLowerCase().includes(q)) || + (p.commandLine && p.commandLine.toLowerCase().includes(q)) || (p.description && p.description.toLowerCase().includes(q)) || (p.companyName && p.companyName.toLowerCase().includes(q)) ) @@ -927,14 +928,82 @@ export async function fetchProcessPorts(host?: unknown): Promise return (await fetchProcessPortSnapshot(host)).rows } -/** 查询具体端口时匹配该本地端口的全部套接字;未输入端口时只列出监听 / 绑定端口的进程(不含连接外部用的临时端口) */ +/** 判断搜索词是否为端口直搜语法(如 :3000、:8080、port:3000) */ +export function isPortQuery(query: string): boolean { + const trimmed = String(query || '').trim() + return /^(?:port:|[::])\s*\d*$/i.test(trimmed) +} + +/** 剥离 port: / : / : 前缀,提取纯端口检索词 */ +function stripPortQueryPrefix(query: string): string { + return String(query || '').trim().replace(/^(?:port:|[::])\s*/i, '').trim() +} + +/** 获取指定进程正在监听/绑定的真实端口记录(按端口号升序去重) */ +export function getProcessListeningPorts(ports: ProcessPort[], pid: number): ProcessPort[] { + if (!Array.isArray(ports) || !Number.isInteger(pid) || pid <= 0) return [] + const seen = new Set() + const result: ProcessPort[] = [] + for (const row of ports) { + if (!row || row.pid !== pid || !isOccupyingPort(row)) continue + const key = `${row.protocol.toUpperCase()}:${row.localAddress}:${row.localPort}` + if (seen.has(key)) continue + seen.add(key) + result.push(row) + } + return result.sort((a, b) => a.localPort - b.localPort) +} + +/** 获取进程可用于浏览器直开的本地 TCP 监听端口(无则返回 null) */ +export function getLocalBrowsablePort(ports: ProcessPort[], pid: number): number | null { + const listening = getProcessListeningPorts(ports, pid) + const tcpRow = listening.find((r) => !r.protocol || r.protocol.toUpperCase().startsWith('TCP')) + return tcpRow ? tcpRow.localPort : null +} + +/** 从完整启动命令行提取简洁脚本/参数摘要,便于在列表中区分多个 Node/Python 等同进程名服务 */ +export function extractCommandSummary(commandLine: string, processName: string): string { + const raw = String(commandLine || '').trim() + if (!raw) return '' + // 去掉开头的带引号或无引号可执行文件路径,只保留参数部分 + let args = '' + if (raw.startsWith('"')) { + const closeIdx = raw.indexOf('"', 1) + if (closeIdx > 0) args = raw.slice(closeIdx + 1).trim() + } else { + const spaceIdx = raw.search(/\s/) + if (spaceIdx > 0) args = raw.slice(spaceIdx + 1).trim() + } + const summary = args || raw + if (summary.toLowerCase() === String(processName || '').trim().toLowerCase()) return '' + return summary.length > 72 ? `${summary.slice(0, 71)}…` : summary +} + +/** 查询具体端口时匹配该本地端口的全部套接字(支持 :3000 与 port:3000);未输入端口时只列出监听 / 绑定端口的进程 */ export function matchPortRows(ports: ProcessPort[], query: string): ProcessPort[] { - const value = query.trim().replace(/^port:/i, '').trim() - if (value && !/^\d{1,5}$/.test(value)) return [] - return ports.filter((p) => (value ? p.localPort === Number(value) : isOccupyingPort(p))) + const value = stripPortQueryPrefix(query) + if (!value) return ports.filter((p) => isOccupyingPort(p)) + if (/^\d{1,5}$/.test(value)) { + const exact = ports.filter((p) => p.localPort === Number(value)) + if (exact.length > 0) return exact + return ports.filter((p) => isOccupyingPort(p) && String(p.localPort).startsWith(value)) + } + // 在端口视图下输入非数字关键词(如 node)时,保留全部占用端口以便按进程名/PID/命令行过滤 + return ports.filter((p) => isOccupyingPort(p)) } export function filterProcessesByPort(processes: ProcessItem[], ports: ProcessPort[], query: string): ProcessItem[] { - const pids = new Set(matchPortRows(ports, query).map((p) => p.pid)) - return processes.filter((p) => pids.has(p.pid)) + const matchedRows = matchPortRows(ports, query) + const pids = new Set(matchedRows.map((p) => p.pid)) + const candidates = processes.filter((p) => pids.has(p.pid)) + const value = stripPortQueryPrefix(query) + if (!value || /^\d{1,5}$/.test(value)) return candidates + const q = value.toLowerCase() + return candidates.filter( + (p) => + p.name.toLowerCase().includes(q) || + String(p.pid).includes(q) || + (p.path && p.path.toLowerCase().includes(q)) || + (p.commandLine && p.commandLine.toLowerCase().includes(q)) + ) } diff --git a/extensions/process-monitor/tests/process-monitor.audit-regression.test.mjs b/extensions/process-monitor/tests/process-monitor.audit-regression.test.mjs deleted file mode 100644 index 055842c7..00000000 --- a/extensions/process-monitor/tests/process-monitor.audit-regression.test.mjs +++ /dev/null @@ -1,36 +0,0 @@ -import test from 'node:test' -import assert from 'node:assert/strict' -import { createHost, mount, tick } from '../../shared/test-harness.mjs' -import Command, { portLookup } from '../dist/index.js' -import { fetchSystemInfo, fetchProcessPorts, filterProcessesByPort } from '../dist/logic.js' - -test('A:端口子命令调用真实端点,并按端口关联PID而非PID文本', async () => { - const host = createHost() - host.ipc.dllplugin_call = ({func}) => func === 'GetSystemInfo' ? {totalMemoryBytes:100,availableMemoryBytes:40,cpuUsagePercent:7} : func === 'GetProcessList' ? {processes:[{pid:234,name:'node',memoryBytes:30},{pid:8080,name:'unrelated'}]} : {error:'unavailable'} - host.ipc.process_list_ports = () => ({ success:true, data:[{pid:234,localPort:8080,protocol:'TCP',localAddress:'127.0.0.1',processName:'node'}],source:'darwin-netstat' }) - const view = await mount(portLookup,host) - try { - await view.search('8080'); await tick(20) - assert.equal(view.tree().props.searchBarAccessory.props.value,'port') - assert.ok(view.items().some(i=>i.props.id==='234')) - assert.ok(!view.items().some(i=>i.props.id==='8080')) - assert.ok(host.ipcCalls.some(([method])=>method==='process_list_ports')) - } finally { view.unmount() } -}) -test('B:没有端口占用是成功空结果,非法端口不匹配其他进程', async () => { - createHost().ipc.process_list_ports=()=>({data:[]}) - assert.deepEqual(await fetchProcessPorts(),[]) - assert.deepEqual(filterProcessesByPort([{pid:2}], [{pid:2,localPort:80}], '65536'),[]) -}) -test('C:宿主全部失败不返回演示指标,界面标记不可用且刷新失败', async () => { - const host = createHost() - await assert.rejects(fetchSystemInfo(),/无法读取系统负载/) - const view = await mount(Command,host) - try { - await tick(10) - assert.match(view.tree().props.filterBar.summaryText,/不可用|过期/) - await view.tree().props.filterBar.actions[0].onAction(); await tick(10) - assert.equal(host.lastToast().style,'FAILURE') - assert.doesNotMatch(view.text(),/24\.5%/) - } finally { view.unmount() } -}) diff --git a/extensions/process-monitor/tests/process-monitor.dll-unsupported.test.mjs b/extensions/process-monitor/tests/process-monitor.dll-unsupported.test.mjs deleted file mode 100644 index 01ee4871..00000000 --- a/extensions/process-monitor/tests/process-monitor.dll-unsupported.test.mjs +++ /dev/null @@ -1,41 +0,0 @@ -// macOS 客户端在路由层拒绝 dllplugin_call:第一次被拒后本次运行不再请求原生组件,避免每次刷新都在控制台报错 -import test from 'node:test' -import assert from 'node:assert/strict' -import { createHost } from '../../shared/test-harness.mjs' -import { fetchProcesses, fetchSystemInfo, resetNativeCapabilitySupport } from '../dist/logic.js' - -const host = createHost() - -test('宿主回复不支持 dllplugin_call 后不再请求原生组件,进程列表照常走 process_list', async () => { - host.reset() - resetNativeCapabilitySupport() - let dllCalls = 0 - let listCalls = 0 - host.ipc.dllplugin_call = async () => { - dllCalls++ - throw Object.assign(new Error('当前操作系统 (darwin) 不支持方法: dllplugin_call'), { code: 'PLATFORM_NOT_SUPPORTED' }) - } - host.ipc.process_list = async () => { - listCalls++ - return [{ pid: 501, name: 'Finder', path: '/System/Library/CoreServices/Finder.app/Contents/MacOS/Finder', cpuUsage: 1, memoryUsage: 9e7 }] - } - const first = await fetchProcesses() - assert.equal(first[0].name, 'Finder') - assert.equal(dllCalls, 1) - const second = await fetchProcesses() - assert.equal(second[0].name, 'Finder') - await fetchSystemInfo().catch(() => {}) - assert.equal(dllCalls, 1, '被拒后不再请求原生组件') - assert.equal(listCalls, 2) -}) - -test('其他原因的原生组件失败不会被记成「不支持」,下次仍会尝试', async () => { - host.reset() - resetNativeCapabilitySupport() - let dllCalls = 0 - host.ipc.dllplugin_call = async () => { dllCalls++; throw new Error('DLL 加载超时') } - host.ipc.process_list = async () => [{ pid: 1, name: 'launchd', path: '/sbin/launchd', cpuUsage: 0, memoryUsage: 1e6 }] - await fetchProcesses() - await fetchProcesses() - assert.equal(dllCalls, 2) -}) diff --git a/extensions/process-monitor/tests/process-monitor.hub.test.mjs b/extensions/process-monitor/tests/process-monitor.hub.test.mjs new file mode 100644 index 00000000..5a752f6e --- /dev/null +++ b/extensions/process-monitor/tests/process-monitor.hub.test.mjs @@ -0,0 +1,161 @@ +// 进程与端口监控中枢集成测试:覆盖 :port 直搜、命令行检索、右栏 Detail、系统关键进程保护、排序/暂停刷新与 kill-process 收敛 +import test from 'node:test' +import assert from 'node:assert/strict' +import fs from 'node:fs' +import path from 'node:path' +import { fileURLToPath } from 'node:url' +import { createHost, mount, tick } from '../../shared/test-harness.mjs' +import ProcessMonitorCommand, { + isPortQuery, + matchPortRows, + filterProcessesByPort, + extractCommandSummary, + getProcessListeningPorts, + getLocalBrowsablePort +} from '../dist/index.js' + +const __dirname = path.dirname(fileURLToPath(import.meta.url)) +const host = createHost() + +const PROCS = [ + { + pid: 4, + name: 'System', + parentPid: 0, + path: '', + cpuPercent: 0.2, + workingSetBytes: 8 * 1024 * 1024, + isSystem: true + }, + { + pid: 18420, + name: 'node.exe', + parentPid: 9104, + path: 'C:\\Program Files\\nodejs\\node.exe', + commandLine: '"C:\\Program Files\\nodejs\\node.exe" scripts/dev-server.mjs --port 3000', + cpuPercent: 12.5, + workingSetBytes: 180 * 1024 * 1024, + isSystem: false + }, + { + pid: 18421, + name: 'node.exe', + parentPid: 9104, + path: 'C:\\Program Files\\nodejs\\node.exe', + commandLine: '"C:\\Program Files\\nodejs\\node.exe" packages/worker/index.js', + cpuPercent: 2.1, + workingSetBytes: 320 * 1024 * 1024, + isSystem: false + }, + { + pid: 9104, + name: 'pwsh.exe', + parentPid: 1200, + path: 'C:\\Program Files\\PowerShell\\7\\pwsh.exe', + commandLine: 'pwsh.exe -NoLogo', + cpuPercent: 0.4, + workingSetBytes: 64 * 1024 * 1024, + isSystem: false + } +] + +const PORTS = [ + { pid: 18420, localPort: 3000, protocol: 'TCP', localAddress: '127.0.0.1', processName: 'node.exe', state: 'LISTENING' }, + { pid: 18420, localPort: 5173, protocol: 'TCP', localAddress: '127.0.0.1', processName: 'node.exe', state: 'LISTENING' }, + { pid: 18421, localPort: 8080, protocol: 'TCP', localAddress: '0.0.0.0', processName: 'node.exe', state: 'LISTENING' }, + { pid: 18421, localPort: 54321, protocol: 'TCP', localAddress: '127.0.0.1', processName: 'node.exe', state: 'ESTABLISHED' } +] + +test.beforeEach(() => { + host.reset() + host.ipc.process_list = async () => PROCS + host.ipc.process_list_ports = async () => ({ success: true, data: PORTS }) + host.ipc.system_get_memory_usage = async () => ({ total: 32e9, used: 16e9, available: 16e9, percent: 50 }) + host.ipc.system_get_hardware_summary = async () => ({ logicalCpuCount: 8, totalMemory: 32e9 }) + host.ipc.system_get_cpu_usage = async () => ({ total: 18 }) + host.ipc.process_info = async ({ pid }) => { + const p = PROCS.find((x) => x.pid === pid) + if (!p) throw Object.assign(new Error('not found'), { code: 'PROCESS_NOT_FOUND' }) + return { pid, name: p.name, path: p.path, cpuUsage: p.cpuPercent, memoryUsage: p.workingSetBytes } + } +}) + +test('纯逻辑::3000 / :8080 / port:3000 直搜语法、命令行摘要与端口提取', () => { + assert.equal(isPortQuery(':3000'), true) + assert.equal(isPortQuery(':8080'), true) + assert.equal(isPortQuery('port:3000'), true) + assert.equal(isPortQuery(':'), true) + assert.equal(isPortQuery('node'), false) + + assert.deepEqual(matchPortRows(PORTS, ':3000').map((r) => r.pid), [18420]) + assert.deepEqual(matchPortRows(PORTS, ':8080').map((r) => r.pid), [18421]) + assert.deepEqual(matchPortRows(PORTS, ':30').map((r) => r.localPort), [3000]) + assert.deepEqual(filterProcessesByPort(PROCS, PORTS, ':3000').map((p) => p.pid), [18420]) + assert.deepEqual(filterProcessesByPort(PROCS, PORTS, 'worker').map((p) => p.pid), [18421]) + + assert.equal(extractCommandSummary('"C:\\Program Files\\nodejs\\node.exe" scripts/dev-server.mjs', 'node.exe'), 'scripts/dev-server.mjs') + assert.equal(extractCommandSummary('', 'node.exe'), '') + assert.equal(getLocalBrowsablePort(PORTS, 18420), 3000) + assert.equal(getProcessListeningPorts(PORTS, 18421).length, 1) +}) + +test('UI 集成:左右分栏 Detail 展示命令行/路径/端口/安全保护,:3000 直搜与系统核心进程禁误杀', async () => { + const view = await mount(ProcessMonitorCommand, host) + await tick(25) + + assert.equal(view.tree().props.isShowingDetail, true, '必须启用右栏 Detail 分栏') + + // 系统关键进程 System (PID 4) 不得提供任何结束/强杀动作,并在 Detail 标明保护 + const sysItem = view.item('4') + const sysActionTitles = view.actions(sysItem).map((a) => a.props.title) + assert.ok(!sysActionTitles.some((title) => /结束|关闭|终止/.test(title)), '系统关键进程不得暴露结束动作') + assert.match(sysItem.props.detail.props.markdown, /系统核心进程保护/) + + // node.exe (18420) 详情包含完整命令行、可执行路径、监听端口,并提供浏览器直开动作 + const nodeItem = view.item('18420') + assert.match(nodeItem.props.detail.props.markdown, /scripts\/dev-server\.mjs --port 3000/) + assert.match(nodeItem.props.detail.props.markdown, /C:\\Program Files\\nodejs\\node\.exe/) + assert.match(nodeItem.props.detail.props.markdown, /127\.0\.0\.1:3000/) + const nodeActions = view.actions(nodeItem) + assert.equal(nodeActions[0].props.title, '平缓关闭进程 (Graceful)', 'Enter 主动作应为安全结束进程') + assert.ok(nodeActions.some((a) => a.props.url === 'http://localhost:3000'), '应提供本地监听端口浏览器直开动作') + + // 搜索框输入 :3000 直搜端口 + view.tree().props.onSearchTextChange(':3000') + await tick(25) + assert.deepEqual(view.items().map((i) => i.props.id), ['18420']) + + // 搜索框输入命令行关键词 worker 区分同名 node.exe + view.tree().props.onSearchTextChange('worker') + await tick(25) + assert.deepEqual(view.items().map((i) => i.props.id), ['18421']) + + // 排序切换至 CPU 降序 + view.tree().props.onSearchTextChange('') + view.tree().props.searchBarAccessory.props.onChange('cpu') + await tick(20) + assert.equal(view.items()[0].props.id, '18420', '按 CPU 排序首项应为 CPU 最高的 18420') + + // 暂停与恢复自动刷新按钮 + const pauseBtn = view.tree().props.filterBar.actions.find((a) => a.id === 'toggle-auto-refresh') + assert.equal(pauseBtn.title, '暂停刷新') + pauseBtn.onAction() + await tick(10) + const resumeBtn = view.tree().props.filterBar.actions.find((a) => a.id === 'toggle-auto-refresh') + assert.equal(resumeBtn.title, '恢复刷新') + + view.unmount() +}) + +test('清单收敛校验:kill-process 已标记 revoked,process-monitor 吸收核心触发词', () => { + const pmManifest = JSON.parse(fs.readFileSync(path.resolve(__dirname, '../plugin.json'), 'utf8')) + const kpManifest = JSON.parse(fs.readFileSync(path.resolve(__dirname, '../../kill-process/plugin.json'), 'utf8')) + + assert.equal(kpManifest.revoked, true) + assert.match(kpManifest.revokedReason, /进程监控/) + assert.match(kpManifest.i18n['en-US'].revokedReason, /Process & Port Monitor/) + + for (const kw of ['kill', '杀进程', '结束进程', '端口占用', 'port']) { + assert.ok(pmManifest.keywords.includes(kw), `process-monitor 应包含关键词 ${kw}`) + } +}) diff --git a/extensions/process-monitor/tests/process-monitor.macos.test.mjs b/extensions/process-monitor/tests/process-monitor.macos.test.mjs deleted file mode 100644 index e6042382..00000000 --- a/extensions/process-monitor/tests/process-monitor.macos.test.mjs +++ /dev/null @@ -1,425 +0,0 @@ -// process-monitor macOS 修复集成测试:真实声明式运行时 + 按 macOS 宿主语义模拟 IPC -// (process_list 只给 pid/name/path/cpuUsage/memoryUsage;dllplugin_call 在 macOS 上不受支持) -import test from 'node:test' -import assert from 'node:assert/strict' -import { getDeclarativeBridge, ZToolsHostError } from '@ztools/declarative-ui' -import { createHost, mount, mountPushed, tick } from '../../shared/test-harness.mjs' -import ProcessMonitorCommand, { - getTerminationRisk, - resolveCpuLoadPercent, - describeProcessProfile, - normalizeProcessItem, - terminateProcess, - describeTerminateError, - getForbiddenReason -} from '../dist/index.js' - -const host = createHost() - -const MAC_PROCESSES = [ - { pid: 1, name: 'launchd', path: '/sbin/launchd', cpuUsage: 0.1, memoryUsage: 20e6 }, - { pid: 98, name: 'WindowServer', path: '/System/Library/PrivateFrameworks/SkyLight.framework/Resources/WindowServer', cpuUsage: 12, memoryUsage: 300e6 }, - { pid: 25, name: 'logd', path: '/usr/libexec/logd', cpuUsage: 0.5, memoryUsage: 30e6 }, - { pid: 36, name: 'configd', path: '/usr/libexec/configd', cpuUsage: 0, memoryUsage: 10e6 }, - { pid: 979, name: 'loginwindow', path: '/System/Library/CoreServices/loginwindow.app/Contents/MacOS/loginwindow', cpuUsage: 0, memoryUsage: 55e6 }, - { pid: 1200, name: 'Finder', path: '/System/Library/CoreServices/Finder.app/Contents/MacOS/Finder', cpuUsage: 0.3, memoryUsage: 120e6 }, - { pid: 410, name: 'sshd', path: '/usr/sbin/sshd', cpuUsage: 0, memoryUsage: 5e6 }, - { pid: 5001, name: 'Calculator', path: '/System/Applications/Calculator.app/Contents/MacOS/Calculator', cpuUsage: 0, memoryUsage: 40e6 }, - { pid: 5002, name: 'Safari', path: '/System/Volumes/Preboot/Cryptexes/App/System/Applications/Safari.app/Contents/MacOS/Safari', cpuUsage: 3, memoryUsage: 200e6 }, - { pid: 5003, name: 'Google Chrome', path: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', cpuUsage: 80, memoryUsage: 400e6 }, - { pid: 5004, name: 'claude', path: '', cpuUsage: 120, memoryUsage: 600e6 } -] - -function installMacHost({ cpuTotal = 31, cores = 8, list = MAC_PROCESSES } = {}) { - host.reset() - const killed = [] - host.ipc.process_list = async () => list - host.ipc.system_get_memory_usage = async () => ({ total: 16e9, used: 9e9, available: 7e9, percent: 56 }) - host.ipc.system_get_hardware_summary = async () => ({ logicalCpuCount: cores, totalMemory: 16e9 }) - if (cpuTotal !== null) host.ipc.system_get_cpu_usage = async () => ({ total: cpuTotal }) - host.ipc.process_info = async ({ pid }) => { - const p = list.find((x) => x.pid === pid) - if (!p) throw Object.assign(new Error('进程不存在'), { code: 'PROCESS_NOT_FOUND' }) - return { pid, name: p.name, path: p.path, cpuUsage: p.cpuUsage, memoryUsage: p.memoryUsage } - } - // 宿主 process_terminate_pid(前端按插件注入的 terminateProcess);旧的 process_kill 只能结束本窗口子进程,不应再被调用 - getDeclarativeBridge().terminateProcess = async (pid, options) => { - killed.push(pid) - return { pid, mode: options.mode, tree: !!options.tree, terminated: [pid] } - } - host.ipc.process_kill = async () => { - throw Object.assign(new Error('只能管理当前窗口启动的进程'), { code: 'PERMISSION_DENIED' }) - } - return { killed } -} - -const summary = (view) => view.tree().props.filterBar.summaryText -const itemByName = (view, name) => view.item((it) => it.props.title === name) -const tagOf = (item) => item.props.accessories.find((a) => a.tag)?.tag.value -const ipcMethods = () => host.ipcCalls.map(([m]) => m) - -// ---------- 线程数 ---------- - -test('pm-3 macOS process_list 不带线程数时副标题不显示「线程 1」之类的假值', async () => { - installMacHost() - const view = await mount(ProcessMonitorCommand, host) - await tick(10) - const items = view.items() - assert.equal(items.length, MAC_PROCESSES.length) - for (const it of items) { - assert.doesNotMatch(it.props.subtitle, /线程/, `${it.props.title} 不应显示线程数`) - } - assert.match(itemByName(view, 'logd').props.subtitle, /^PID: 25 · \/usr\/libexec\/logd$/) - view.unmount() -}) - -test('pm-3 宿主给出真实线程数时照常显示;0、负数、非数字一律视为缺失', async () => { - installMacHost({ - list: [ - { pid: 700, name: 'real', path: '/usr/bin/real', cpuUsage: 0, memoryUsage: 1e6, threadCount: 5 }, - { pid: 701, name: 'zero', path: '/usr/bin/zero', cpuUsage: 0, memoryUsage: 1e6, threadCount: 0 }, - { pid: 702, name: 'neg', path: '/usr/bin/neg', cpuUsage: 0, memoryUsage: 1e6, threadCount: -3 }, - { pid: 703, name: 'nan', path: '/usr/bin/nan', cpuUsage: 0, memoryUsage: 1e6, threadCount: 'abc' } - ] - }) - const view = await mount(ProcessMonitorCommand, host) - await tick(10) - assert.match(itemByName(view, 'real').props.subtitle, /PID: 700 · 线程 5 · /) - for (const n of ['zero', 'neg', 'nan']) assert.doesNotMatch(itemByName(view, n).props.subtitle, /线程/) - assert.equal(normalizeProcessItem({ pid: 9, name: 'x' }).threadCount, undefined) - view.unmount() -}) - -// ---------- CPU 负载 ---------- - -test('pm-4 状态条用宿主的整机 CPU 占用,不再把各进程单核百分比相加(总和 216% 也只显示 31%)', async () => { - installMacHost({ cpuTotal: 31 }) - const view = await mount(ProcessMonitorCommand, host) - await tick(10) - assert.match(summary(view), /^CPU 负载 31% · /) - view.unmount() -}) - -test('pm-4 宿主 CPU 接口失败时按逻辑核数归一化进程占用之和,而不是封顶 100%', async () => { - installMacHost({ cpuTotal: null, cores: 8 }) - const view = await mount(ProcessMonitorCommand, host) - await tick(10) - // 216.4 / 8 = 27 - assert.match(summary(view), /^CPU 负载 27% · /) - assert.ok(ipcMethods().includes('system_get_cpu_usage')) - view.unmount() -}) - -test('pm-4 resolveCpuLoadPercent 边界:NaN/负数/空列表、超 100 封顶、核数缺失时退回 hardwareConcurrency', () => { - assert.equal(resolveCpuLoadPercent({ cpuUsagePercent: 17.6, cpuCoreCount: 8 }, [{ cpuPercent: 500 }]), 18) - assert.equal(resolveCpuLoadPercent({ cpuUsagePercent: 250, cpuCoreCount: 8 }, []), 100) - assert.equal(resolveCpuLoadPercent({ cpuUsagePercent: NaN, cpuCoreCount: 4 }, [{ cpuPercent: 200 }, { cpuPercent: NaN }, { cpuPercent: -50 }]), 50) - assert.equal(resolveCpuLoadPercent({ cpuUsagePercent: 0, cpuCoreCount: 2 }, [{ cpuPercent: 900 }]), 100) - assert.equal(resolveCpuLoadPercent(null, []), 0) - assert.equal(resolveCpuLoadPercent(undefined, undefined), 0) - const cores = Number(globalThis.navigator?.hardwareConcurrency) || 1 - assert.equal(resolveCpuLoadPercent({ cpuUsagePercent: 0, cpuCoreCount: 0 }, [{ cpuPercent: 40 }]), Math.min(100, Math.round(40 / cores))) -}) - -// ---------- 系统 / 用户分类 ---------- - -test('pm-5 macOS 系统目录下的守护进程归为系统,/System 下的 Applications 与普通应用归为用户', async () => { - installMacHost() - const view = await mount(ProcessMonitorCommand, host) - await tick(10) - await view.dropdown('system') - const sys = view.items().map((it) => it.props.title.split(' [')[0]).sort() - assert.deepEqual(sys, ['Finder', 'WindowServer', 'configd', 'launchd', 'loginwindow', 'logd', 'sshd'].sort()) - assert.equal(tagOf(itemByName(view, 'sshd')), '系统服务') - await view.dropdown('user') - const user = view.items().map((it) => it.props.title.split(' [')[0]).sort() - assert.deepEqual(user, ['Calculator', 'Google Chrome', 'Safari', 'claude'].sort()) - // macOS 系统进程不能被填成 Microsoft 发布者,否则搜「microsoft」会命中苹果进程 - await view.dropdown('memory') - await view.search('microsoft') - assert.equal(view.items().length, 0) - view.unmount() -}) - -test('pm-5 Windows 分类规则保持不变,宿主显式给 isSystem 时以宿主为准', () => { - assert.equal(normalizeProcessItem({ pid: 1044, name: 'svchost.exe', path: 'C:\\Windows\\System32\\svchost.exe' }).isSystem, true) - // 宿主没给发布者时留空,不按进程名猜成 Microsoft - assert.equal(normalizeProcessItem({ pid: 1044, name: 'svchost.exe' }).companyName, '') - assert.equal(normalizeProcessItem({ pid: 1044, name: 'svchost.exe', companyName: 'Microsoft Corporation' }).companyName, 'Microsoft Corporation') - assert.equal(normalizeProcessItem({ pid: 1044, name: 'svchost.exe', path: 'C:\\Windows\\System32\\svchost.exe' }).commandLine, '') - assert.equal(normalizeProcessItem({ pid: 2000, name: 'chrome.exe', path: 'C:\\Program Files\\chrome.exe' }).isSystem, false) - assert.equal(normalizeProcessItem({ pid: 25, name: 'logd', path: '/usr/libexec/logd' }).companyName, '') - // macOS 宿主兜底只按 pid <= 4 给 isSystem,false 不能盖掉系统目录 / 关键守护进程的判定 - assert.equal(normalizeProcessItem({ pid: 25, name: 'logd', path: '/usr/libexec/logd', isSystem: false }).isSystem, true) - assert.equal(normalizeProcessItem({ pid: 5003, name: 'Google Chrome', path: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', isSystem: false }).isSystem, false) - // Windows 宿主把 System32 下的记事本等交互工具判为用户应用,插件不再按路径改回系统 - assert.equal(normalizeProcessItem({ pid: 4100, name: 'notepad.exe', path: 'C:\\Windows\\System32\\notepad.exe', isSystem: false }).isSystem, false) - assert.equal(normalizeProcessItem({ pid: 900, name: 'svchost.exe', path: 'C:\\Windows\\System32\\svchost.exe', isSystem: true }).isSystem, true) - // 只是名字像系统路径前缀的用户目录不算系统 - assert.equal(normalizeProcessItem({ pid: 3000, name: 'tool', path: '/Users/me/System/tool' }).isSystem, false) - assert.equal(normalizeProcessItem({ pid: 3001, name: 'kernel_task', path: '' }).isSystem, true) -}) - -// ---------- 数字签名与托管服务 ---------- - -test('pm-7 macOS 上拿不到签名与服务时明确失败提示,不弹成功、不进详情页', async () => { - installMacHost() - const view = await mount(ProcessMonitorCommand, host) - await tick(10) - await view.run(itemByName(view, 'WindowServer'), '查看数字签名与托管服务') - await tick(10) - assert.equal(host.pushed.length, 0) - const t = host.lastToast() - assert.equal(t.style, 'FAILURE') - assert.equal(t.title, '未读取到签名与托管服务信息') - assert.ok(!host.toasts.some((x) => /已加载进程深度画像/.test(x.title))) - assert.ok(ipcMethods().includes('process_info')) - view.unmount() -}) - -test('pm-7 process_info 也失败(进程已退出)时同样是失败提示', async () => { - installMacHost() - host.ipc.process_info = async () => { - throw Object.assign(new Error('进程不存在'), { code: 'PROCESS_NOT_FOUND' }) - } - const view = await mount(ProcessMonitorCommand, host) - await tick(10) - await view.run(itemByName(view, 'logd'), '查看数字签名与托管服务') - await tick(10) - assert.equal(host.pushed.length, 0) - assert.equal(host.lastToast().style, 'FAILURE') - view.unmount() -}) - -test('pm-7 宿主给出真实签名与服务时进入详情页,只展示有值的字段', async () => { - installMacHost({ - list: [{ pid: 1044, name: 'svchost.exe', path: 'C:\\Windows\\System32\\svchost.exe', cpuUsage: 1, memoryUsage: 9e7 }] - }) - host.ipc.dllplugin_call = async ({ func, params }) => { - if (func === 'GetProcessDetail') { - return { pid: params.pid, name: 'svchost.exe', path: 'C:\\Windows\\System32\\svchost.exe', signerName: 'Microsoft Windows Publisher', companyName: 'Microsoft Corporation', fileVersion: '10.0.26100.1', fileDescription: 'svchost.exe', productName: '' } - } - if (func === 'GetServicesByPID') { - return { services: [{ serviceName: 'DcomLaunch', displayName: 'DCOM Server Process Launcher', status: 'Running' }, { serviceName: '' }] } - } - throw Object.assign(new Error('不支持'), { code: 'NOT_SUPPORTED' }) - } - const view = await mount(ProcessMonitorCommand, host) - await tick(10) - await view.run(view.item('1044'), '查看数字签名与托管服务') - await tick(10) - assert.equal(host.pushed.length, 1) - const detail = await mountPushed(host) - const text = detail.text() - assert.match(text, /Microsoft Windows Publisher/) - assert.match(text, /10\.0\.26100\.1/) - assert.match(text, /托管服务 DcomLaunch/) - assert.match(text, /DCOM Server Process Launcher · Running/) - assert.doesNotMatch(text, /产品名称|文件描述/) - detail.unmount() - view.unmount() -}) - -test('pm-7 describeProcessProfile 对空值、null 与和进程名相同的描述返回空', () => { - assert.deepEqual(describeProcessProfile({ name: 'logd' }, null, null), []) - assert.deepEqual( - describeProcessProfile({ name: 'logd' }, { signerName: ' ', companyName: '', productName: '', fileDescription: 'logd', fileVersion: '' }, [{ name: '' }]), - [] - ) -}) - -// ---------- macOS 关键进程保护 ---------- - -test('pm-8 系统关键进程 launchd / WindowServer / loginwindow 隐藏所有结束动作,主动作改为安全查看', async () => { - const { killed } = installMacHost() - const view = await mount(ProcessMonitorCommand, host) - await tick(10) - for (const name of ['launchd', 'WindowServer', 'loginwindow', 'logd']) { - const item = itemByName(view, name) - const titles = view.actions(item).map((a) => a.props.title) - assert.equal(titles.some((title) => /结束|平缓关闭/.test(title)), false, `${name} 不应提供结束动作`) - assert.equal(titles[0], '查看数字签名与托管服务', `${name} 主动作应为安全查看`) - assert.equal(tagOf(item), '系统关键') - } - assert.equal(host.confirms.length, 0) - assert.deepEqual(killed, []) - assert.ok(!ipcMethods().includes('process_kill')) - view.unmount() -}) - -test('pm-8 Finder 等系统界面进程走高危确认:取消不结束,确认后才结束', async () => { - const { killed } = installMacHost() - const view = await mount(ProcessMonitorCommand, host) - await tick(10) - host.setConfirm(false) - await view.run(itemByName(view, 'Finder'), '结束进程') - await tick(5) - assert.match(host.confirms.at(-1).title, /^高危操作:结束系统界面进程 \[Finder\]/) - assert.deepEqual(killed, []) - host.setConfirm(true) - await view.run(itemByName(view, 'Finder'), '结束进程') - await tick(10) - assert.deepEqual(killed, [1200]) - // 普通进程仍是普通确认 - await view.run(itemByName(view, 'Google Chrome'), '结束进程') - await tick(10) - assert.match(host.confirms.at(-1).title, /^确认结束进程/) - assert.deepEqual(killed, [1200, 5003]) - assert.ok(!ipcMethods().includes('process_kill'), '走宿主结束进程接口,不再调用 process_kill') - view.unmount() -}) - -test('pm-8 绕过界面直接调用 terminateProcess 也会拦截(大小写不敏感,含 kernel_task 与 PID 0/1/4)', async () => { - installMacHost() - for (const [pid, name] of [[98, 'windowserver'], [979, 'LoginWindow'], [0, 'kernel_task'], [1, 'whatever'], [4, 'System'], [612, 'csrss.exe']]) { - const res = await terminateProcess(pid, name, 'force') - assert.equal(res.ok, false, `${pid} ${name}`) - assert.equal(res.error, getForbiddenReason()) - } - assert.ok(!ipcMethods().includes('process_kill')) - assert.equal(getTerminationRisk(1200, 'finder'), 'high-risk') - assert.equal(getTerminationRisk(5003, 'Google Chrome'), 'normal') - assert.equal(getTerminationRisk(5003, ''), 'normal') -}) - -// ---------- 真实 macOS 宿主链路:dllplugin_call 落到宿主进程服务兜底 ---------- - -/** 按 process-service.ts 在 darwin 上的兜底返回:isSystem 只按 pid <= 4,详情把路径填进命令行、进程名填进产品名称 */ -function installMacDllFallbackHost(list = MAC_PROCESSES) { - host.reset() - host.ipc.dllplugin_call = async ({ func, params }) => { - if (func === 'GetProcessList') { - return { success: true, data: { processes: list.map((p) => ({ - pid: p.pid, name: p.name, path: p.path, cpuPercent: p.cpuUsage, workingSetBytes: p.memoryUsage, - privateBytes: null, threadCount: null, parentPid: 1, isSystem: p.pid <= 4, description: p.name, companyName: '' - })) } } - } - if (func === 'GetSystemInfo') { - return { success: true, data: { cpuUsagePercent: 12, totalMemoryBytes: 16e9, usedMemoryBytes: 9e9, availableMemoryBytes: 7e9, memoryUsagePercent: 56, processCount: list.length, threadCount: 0 } } - } - if (func === 'GetProcessDetail') { - const p = list.find((x) => x.pid === params.pid) - if (!p) return { success: true, data: { error: 'PROCESS_NOT_FOUND: 进程已退出或不可见' } } - return { success: true, data: { pid: p.pid, name: p.name, path: p.path, commandLine: p.path, companyName: '', fileDescription: p.name, fileVersion: '', productName: p.name, signerName: '', startTime: '', handleCount: null, peakMemoryBytes: null, memoryBytes: p.memoryUsage, privateBytes: null, threadCount: null, parentPid: 1 } } - } - if (func === 'GetServicesByPID') return { success: true, data: { services: [] } } - return { success: false, data: { error: `UNSUPPORTED_PROCESS_MONITOR_METHOD: ${func}` } } - } -} - -test('macOS 真实链路:宿主 isSystem=false 时系统目录下的守护进程仍归入「系统关键服务」', async () => { - installMacDllFallbackHost() - const view = await mount(ProcessMonitorCommand, host) - await tick(10) - assert.equal(tagOf(itemByName(view, 'sshd')), '系统服务') - assert.equal(tagOf(itemByName(view, 'Calculator')), '用户应用') - await view.tree().props.searchBarAccessory.props.onChange('system') - await tick(5) - const names = view.items().map((it) => it.props.title.replace(/ \[PID.*$/, '')) - assert.ok(names.includes('sshd') && names.includes('logd') && names.includes('Finder'), names.join(',')) - assert.ok(!names.includes('Google Chrome') && !names.includes('Calculator')) - view.unmount() -}) - -test('macOS 真实链路:详情把路径当命令行、进程名当产品名称时不复制、不展示,如实提示读取不到', async () => { - installMacDllFallbackHost() - const view = await mount(ProcessMonitorCommand, host) - await tick(10) - await view.run(itemByName(view, 'Google Chrome'), '查看数字签名与托管服务') - await tick(10) - assert.equal(host.pushed.length, 0, '只有进程名与路径时不能进详情页冒充签名信息') - assert.equal(host.lastToast().title, '未读取到签名与托管服务信息') - await view.run(itemByName(view, 'Google Chrome'), '复制启动命令行 (CommandLine)') - await tick(5) - assert.equal(host.lastToast().style, 'FAILURE') - assert.equal(host.lastToast().title, '没有读取到启动命令行') - assert.equal(host.clipboard.length ?? 0, 0) - view.unmount() -}) - -// ---------- 端口占用 ---------- - -const PORT_PROCS = [ - { pid: 300, name: 'postgres', path: '/opt/homebrew/bin/postgres', cpuUsage: 0, memoryUsage: 30e6 }, - { pid: 400, name: 'Google Chrome', path: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', cpuUsage: 1, memoryUsage: 300e6 }, - { pid: 500, name: 'mDNSResponder', path: '/usr/sbin/mDNSResponder', cpuUsage: 0, memoryUsage: 5e6 } -] - -test('端口占用:未输入端口时只列出监听 / 绑定端口的进程,不把浏览器连接外部的临时端口算作占用', async () => { - installMacHost({ list: PORT_PROCS }) - host.ipc.process_list_ports = async () => ({ success: true, source: 'darwin-netstat', visibility: 'all-sockets', data: [ - { pid: 300, localPort: 5432, protocol: 'TCP', localAddress: '127.0.0.1', state: 'LISTEN', processName: 'postgres' }, - { pid: 300, localPort: 5432, protocol: 'TCP', localAddress: '127.0.0.1', state: 'ESTABLISHED', processName: 'postgres' }, - { pid: 400, localPort: 61135, protocol: 'TCP', localAddress: '10.0.0.2', state: 'ESTABLISHED', processName: 'Google Chrome' }, - { pid: 500, localPort: 5353, protocol: 'UDP', localAddress: '*', state: 'BOUND', processName: 'mDNSResponder' } - ] }) - const view = await mount(ProcessMonitorCommand, host) - await tick(10) - await view.tree().props.searchBarAccessory.props.onChange('port') - await tick(10) - const ids = view.items().map((it) => it.props.id).sort() - assert.deepEqual(ids, ['300', '500']) - assert.match(view.text(), /端口占用进程(2)/) - assert.doesNotMatch(view.text(), /活动进程列表/) - assert.match(view.item((it) => it.props.id === '300').props.subtitle, /端口 5432 ·/) - assert.doesNotMatch(summary(view), /只能看到当前用户/) - // 查询具体端口时匹配该端口的全部套接字(含临时端口) - await view.search('61135') - await tick(10) - assert.deepEqual(view.items().map((it) => it.props.id), ['400']) - view.unmount() -}) - -test('端口占用:宿主改用 lsof 兜底(visible-processes)时状态条提示可能查不到系统服务的端口', async () => { - installMacHost({ list: PORT_PROCS }) - host.ipc.process_list_ports = async () => ({ success: true, source: 'darwin-lsof', visibility: 'visible-processes', data: [ - { pid: 300, localPort: 5432, protocol: 'TCP', localAddress: '127.0.0.1', state: 'LISTEN', processName: 'postgres' } - ] }) - const view = await mount(ProcessMonitorCommand, host) - await tick(10) - await view.tree().props.searchBarAccessory.props.onChange('port') - await tick(10) - assert.match(summary(view), /本地端口匹配 1 个进程(只能看到当前用户进程的端口/) - view.unmount() -}) - -test('[故障注入] 端口查询失败 / 宿主不支持:状态条如实显示失败原因,不显示旧数据', async () => { - installMacHost({ list: PORT_PROCS }) - host.ipc.process_list_ports = async () => { throw Object.assign(new Error('端口列表无效或未完整返回'), { code: 'PROCESS_ERROR' }) } - const view = await mount(ProcessMonitorCommand, host) - await tick(10) - await view.tree().props.searchBarAccessory.props.onChange('port') - await tick(10) - assert.equal(summary(view), '端口读取失败:端口列表无效或未完整返回') - assert.equal(view.items().length, 0) - view.unmount() - installMacHost({ list: PORT_PROCS }) - const view2 = await mount(ProcessMonitorCommand, host) - await tick(10) - await view2.tree().props.searchBarAccessory.props.onChange('port') - await tick(10) - assert.match(summary(view2), /^端口读取失败:/) - view2.unmount() -}) - -test('Windows 平缓关闭被程序拒绝(graceful-rejected)时说明是拒绝关闭,而不是超时;普通超时仍列出未退出的 PID', () => { - const rejected = describeTerminateError(new ZToolsHostError('PROCESS_TERMINATE_TIMEOUT', '进程拒绝正常关闭', { reason: 'graceful-rejected', stillRunning: [42] })) - assert.equal(rejected.code, 'PROCESS_TERMINATE_TIMEOUT') - assert.match(rejected.message, /拒绝正常关闭/) - const timeout = describeTerminateError(new ZToolsHostError('PROCESS_TERMINATE_TIMEOUT', '超时', { stillRunning: [42, 'x'] })) - assert.equal(timeout.message, '进程没有在限定时间内退出(仍在运行:PID 42)') -}) - -test('标题只放进程名,PID 只在副标题出现一次;排序下拉不带英文括注', async () => { - installMacHost() - const view = await mount(ProcessMonitorCommand, host) - await tick(10) - const claude = view.item('5004') - assert.equal(claude.props.title, 'claude') - assert.equal(claude.props.subtitle.match(/PID/g).length, 1) - assert.match(view.text(), /活动进程列表(11)/) - const options = view.tree().props.searchBarAccessory.children.map((it) => it.props.title) - for (const title of options) assert.doesNotMatch(title, /[A-Za-z]{2,}\)|\(/, title) - assert.ok(options.includes('全部进程 · 按内存排序')) - view.unmount() -}) diff --git a/extensions/process-monitor/tests/process-monitor.not-in-client.test.mjs b/extensions/process-monitor/tests/process-monitor.not-in-client.test.mjs deleted file mode 100644 index 13c522b7..00000000 --- a/extensions/process-monitor/tests/process-monitor.not-in-client.test.mjs +++ /dev/null @@ -1,86 +0,0 @@ -// 不在 ZTools 客户端里运行(没有宿主通道)时:不显示示例进程,列表为空并如实提示,读取接口直接报错 -import test from 'node:test' -import assert from 'node:assert/strict' -import { setRuntimeLocale } from '@ztools/declarative-ui' -import { createHost, mount, tick } from '../../shared/test-harness.mjs' -import ProcessMonitorCommand, { - getNotInClientMessage, - fetchProcesses, - fetchSystemInfo, - fetchProcessDetail, - fetchServicesByPID -} from '../dist/index.js' -import * as logic from '../dist/logic.js' - -test('插件不再导出任何示例进程数据', () => { - for (const name of ['getMockProcesses', 'getMockSystemInfo', 'getMockProcessDetail', 'getMockServicesByPID']) { - assert.equal(logic[name], undefined, name) - } -}) - -test('没有宿主:读取进程与系统负载报「需要在 ZTools 客户端中使用」,详情与托管服务为空', async () => { - const host = createHost() - host.reset() - const saved = globalThis.__ztoolsElectron - delete globalThis.__ztoolsElectron - try { - const notInClient = getNotInClientMessage() - await assert.rejects(fetchProcesses(), new RegExp(notInClient)) - await assert.rejects(fetchSystemInfo(), new RegExp(notInClient)) - assert.equal(await fetchProcessDetail(1044), null) - assert.deepEqual(await fetchServicesByPID(1044), []) - } finally { - globalThis.__ztoolsElectron = saved - } -}) - -test('没有宿主:界面只显示一条「需要在 ZTools 客户端中使用」,没有示例进程、不发起刷新', async () => { - const host = createHost() - host.reset() - const saved = globalThis.__ztoolsElectron - delete globalThis.__ztoolsElectron - try { - const notInClient = getNotInClientMessage() - const view = await mount(ProcessMonitorCommand, host) - await tick(10) - const items = view.items() - assert.deepEqual(items.map((i) => i.props.id), ['load-error']) - assert.equal(items[0].props.title, notInClient) - assert.equal(view.tree().props.filterBar.summaryText, notInClient) - assert.doesNotMatch(view.text(), /svchost|ntoskrnl|dev-server|Microsoft Corporation/) - assert.equal(view.tree().props.navigationTitle, '进程监控') - view.unmount() - } finally { - globalThis.__ztoolsElectron = saved - } -}) - -test('宿主没给托管服务的状态与启动类型时留空,不填「Running」「Auto」', async () => { - const host = createHost() - host.reset() - host.ipc.dllplugin_call = async () => ({ success: true, data: { services: [{ serviceName: 'Spooler' }] } }) - const list = await fetchServicesByPID(1044) - assert.equal(list.length, 1) - assert.equal(list[0].serviceName, 'Spooler') - assert.equal(list[0].status, '') - assert.equal(list[0].startType, '') -}) - -test('i18n 热切换:未在客户端提示、系统保护原因与原生组件不支持文案随语言即时更新', async () => { - try { - setRuntimeLocale('zh-CN') - const zhNotInClient = logic.getNotInClientMessage() - const zhForbidden = logic.getForbiddenReason() - assert.match(zhNotInClient, /[\u4e00-\u9fa5]/) - assert.match(zhForbidden, /[\u4e00-\u9fa5]/) - - setRuntimeLocale('en-US') - const enNotInClient = logic.getNotInClientMessage() - const enForbidden = logic.getForbiddenReason() - assert.notEqual(enNotInClient, zhNotInClient) - assert.notEqual(enForbidden, zhForbidden) - assert.doesNotMatch(`${enNotInClient} ${enForbidden}`, /[\u4e00-\u9fa5]/) - } finally { - setRuntimeLocale('zh-CN') - } -}) diff --git a/extensions/process-monitor/tests/process-monitor.path-grants.test.mjs b/extensions/process-monitor/tests/process-monitor.path-grants.test.mjs deleted file mode 100644 index b59e54ec..00000000 --- a/extensions/process-monitor/tests/process-monitor.path-grants.test.mjs +++ /dev/null @@ -1,132 +0,0 @@ -// 路径授权收紧后「定位文件目录」的集成测试:真实声明式运行时 + 按宿主结果授权语义模拟的 macOS 宿主 -// 宿主规则:process_list(及 GetProcessList 兜底)返回的可执行文件路径只读授权给本窗口,process_info 给的路径不授权; -// shell_show_item_in_folder / shell_open_path 只放行已授权路径 -// 覆盖:定位用列表里的原始路径(即使详情接口给了另一个路径)、授权过期 / 文件被删时提示刷新、没有路径时不调用宿主 -import test from 'node:test' -import assert from 'node:assert/strict' -import { getDeclarativeBridge } from '@ztools/declarative-ui' -import { createHost, mount, tick } from '../../shared/test-harness.mjs' -import ProcessMonitorCommand from '../dist/index.js' - -const host = createHost() -const rejections = [] -process.on('unhandledRejection', (reason) => rejections.push(reason)) - -const APP = '/Applications/Sample Tool.app/Contents/MacOS/Sample Tool' -// 详情接口给的是另一种写法(例如解析了符号链接的真实路径),没有被授权 -const APP_REAL = '/private/var/folders/xx/AppTranslocation/Sample Tool.app/Contents/MacOS/Sample Tool' -const LIST = [ - { pid: 5101, name: 'Sample Tool', path: APP, cpuUsage: 3, memoryUsage: 80e6 }, - { pid: 5102, name: 'kernel_task', path: '', cpuUsage: 1, memoryUsage: 10e6 } -] - -function installGrantHost() { - const grants = new Set() - const missing = new Set() - const calls = { revealed: [], opened: [] } - host.ipc.process_list = async () => { - for (const p of LIST) if (p.path) grants.add(p.path) - return LIST - } - host.ipc.process_info = async ({ pid }) => { - const p = LIST.find((x) => x.pid === pid) - if (!p) throw Object.assign(new Error('进程不存在'), { code: 'PROCESS_NOT_FOUND' }) - return { pid, name: p.name, path: p.path ? APP_REAL : '', cpuUsage: p.cpuUsage, memoryUsage: p.memoryUsage } - } - host.ipc.system_get_memory_usage = async () => ({ total: 16e9, used: 9e9, available: 7e9, percent: 56 }) - host.ipc.system_get_hardware_summary = async () => ({ logicalCpuCount: 8, totalMemory: 16e9 }) - host.ipc.system_get_cpu_usage = async () => ({ total: 20 }) - const authorize = (p) => { - if (!grants.has(p)) throw Object.assign(new Error('路径未由当前窗口授权'), { code: 'PERMISSION_DENIED' }) - if (missing.has(p)) throw Object.assign(new Error('文件不存在'), { code: 'FILE_ERROR' }) - } - host.ipc.shell_show_item_in_folder = async ({ fullPath }) => { authorize(fullPath); calls.revealed.push(fullPath); return { success: true } } - host.ipc.shell_open_path = async ({ fullPath }) => { authorize(fullPath); calls.opened.push(fullPath); return { success: true } } - getDeclarativeBridge().terminateProcess = async () => { throw new Error('本用例不应结束进程') } - return { grants, missing, calls } -} - -const itemByName = (view, name) => view.item((it) => it.props.title === name) - -async function mountLoaded() { - const view = await mount(ProcessMonitorCommand) - await tick(30) - return view -} - -test.beforeEach(() => { - host.reset() - rejections.length = 0 -}) - -test('定位文件目录:用进程列表里的原始路径(已授权),不用详情接口给的另一种路径', async () => { - const { calls } = installGrantHost() - const view = await mountLoaded() - // 先读取详情,让 details[pid].path 变成未授权的 APP_REAL - await view.run(itemByName(view, 'Sample Tool'), '查看数字签名与托管服务') - await tick(10) - assert.ok(host.ipcCalls.some(([m]) => m === 'process_info'), '应读取过详情') - await view.run(itemByName(view, 'Sample Tool'), '定位文件目录') - await tick(10) - assert.deepEqual(calls.revealed, [APP]) - assert.deepEqual(calls.opened, [], '定位成功时不能退回去“打开”可执行文件') - assert.equal(host.lastToast().title, '已在访达中定位') - assert.equal(host.lastToast().message, APP) - view.unmount() - assert.equal(rejections.length, 0) -}) - -test('异常:授权过期后定位被拒,提示刷新列表后再试,不显示成功', async () => { - const { grants, calls } = installGrantHost() - const view = await mountLoaded() - grants.clear() - await view.run(itemByName(view, 'Sample Tool'), '定位文件目录') - await tick(10) - const t = host.lastToast() - assert.equal(t.style, 'FAILURE') - assert.equal(t.title, '打开路径失败') - assert.match(t.message, /^\/Applications\/Sample Tool\.app\/Contents\/MacOS\/Sample Tool\n.*请刷新进程列表后再试$/) - assert.deepEqual(calls.revealed, []) - - // 刷新列表后授权恢复 - await view.run(itemByName(view, 'Sample Tool'), '刷新列表') - await tick(30) - await view.run(itemByName(view, 'Sample Tool'), '定位文件目录') - await tick(10) - assert.deepEqual(calls.revealed, [APP]) - view.unmount() -}) - -test('异常:显示失败时绝不退回 shell_open_path(对可执行文件“打开”等于运行它)', async () => { - const { calls } = installGrantHost() - host.ipc.shell_show_item_in_folder = async () => { throw Object.assign(new Error('访达拒绝'), { code: 'SHELL_ERROR' }) } - const view = await mountLoaded() - await view.run(itemByName(view, 'Sample Tool'), '定位文件目录') - await tick(10) - assert.equal(host.ipcCalls.some(([m]) => m === 'shell_open_path'), false) - assert.deepEqual(calls.opened, []) - assert.equal(host.lastToast().style, 'FAILURE') - assert.equal(host.lastToast().title, '打开路径失败') - view.unmount() -}) - -test('异常:可执行文件已被删除(FILE_ERROR)时同样提示失败', async () => { - const { missing } = installGrantHost() - const view = await mountLoaded() - missing.add(APP) - await view.run(itemByName(view, 'Sample Tool'), '定位文件目录') - await tick(10) - assert.equal(host.lastToast().title, '打开路径失败') - view.unmount() -}) - -test('边界:进程没有可执行路径(内核进程)时直接提示无法定位,不调用宿主', async () => { - const { calls } = installGrantHost() - const view = await mountLoaded() - await view.run(itemByName(view, 'kernel_task'), '定位文件目录') - await tick(10) - assert.equal(host.lastToast().title, '无法定位路径') - assert.equal(host.ipcCalls.some(([m]) => m === 'shell_show_item_in_folder' || m === 'shell_open_path'), false) - assert.deepEqual(calls.revealed, []) - view.unmount() -}) diff --git a/extensions/process-monitor/tests/process-monitor.refresh.test.mjs b/extensions/process-monitor/tests/process-monitor.refresh.test.mjs deleted file mode 100644 index baba9f9d..00000000 --- a/extensions/process-monitor/tests/process-monitor.refresh.test.mjs +++ /dev/null @@ -1,166 +0,0 @@ -import test, { mock } from 'node:test' -import assert from 'node:assert/strict' -import { createHost, mount, tick } from '../../shared/test-harness.mjs' -import Command, { portLookup } from '../dist/index.js' - -const process = pid => ({ pid, name: `worker-${pid}`, memoryBytes: 30 }) -const port = (pid, localPort = 8080) => ({ pid, localPort, protocol: 'TCP', localAddress: '127.0.0.1' }) -const deferred = () => { - let resolve, reject - const promise = new Promise((yes, no) => { resolve = yes; reject = no }) - return { promise, resolve, reject } -} -function fixture() { - const host = createHost() - const reads = { processes: () => [process(100), process(200)], ports: () => [port(100)] } - const calls = { processes: 0, ports: 0 } - host.ipc.dllplugin_call = async ({ func }) => { - if (func === 'GetSystemInfo') return { totalMemoryBytes: 100, availableMemoryBytes: 40, cpuUsagePercent: 7 } - if (func === 'GetProcessList') { calls.processes++; return { processes: await reads.processes() } } - return { error: 'unavailable' } - } - host.ipc.process_list_ports = async () => { calls.ports++; return { data: await reads.ports() } } - return { host, reads, calls } -} -async function action(view, id) { - await view.tree().props.filterBar.actions.find(action => action.id === id).onAction() - await tick() -} -async function advance(ms = 2000) { mock.timers.tick(ms); await tick() } -const ids = view => view.items().map(item => item.props.id) -test.beforeEach(() => mock.timers.enable({ apis: ['setInterval'] })) -test.afterEach(() => mock.timers.reset()) - -test('暂停冻结端口和进程的在途快照,手动刷新与恢复仍可更新', async () => { - const { host, reads, calls } = fixture() - const view = await mount(portLookup, host) - try { - assert.deepEqual(ids(view), ['100']) - const oldProcesses = deferred(), oldPorts = deferred() - reads.processes = () => oldProcesses.promise - reads.ports = () => oldPorts.promise - await advance() - await action(view, 'toggle-auto-refresh') - const pausedCalls = { ...calls } - await advance(6000) - assert.deepEqual(calls, pausedCalls) - oldProcesses.resolve([process(200)]) - oldPorts.resolve([port(200)]) - await tick() - assert.deepEqual(ids(view), ['100']) - reads.processes = () => [process(200)] - reads.ports = () => [port(200)] - await action(view, 'refresh-list') - assert.deepEqual(ids(view), ['200']) - reads.processes = () => [process(100)] - reads.ports = () => [port(100)] - await action(view, 'toggle-auto-refresh') - assert.deepEqual(ids(view), ['100']) - const resumedCalls = { ...calls } - await advance() - assert.equal(calls.ports, resumedCalls.ports + 1) - assert.equal(calls.processes, resumedCalls.processes + 1) - } finally { view.unmount() } -}) - -test('慢端口轮询保持单请求;手动刷新完成后旧请求失败不能清空新结果', async () => { - const { host, reads, calls } = fixture() - const view = await mount(portLookup, host) - try { - const oldPorts = deferred() - reads.ports = () => oldPorts.promise - await advance() - const pendingCalls = calls.ports - await advance(6000) - assert.equal(calls.ports, pendingCalls) - reads.ports = () => [port(200)] - await action(view, 'refresh-list') - assert.deepEqual(ids(view), ['200']) - oldPorts.reject(new Error('旧请求失败')) - await tick() - assert.deepEqual(ids(view), ['200']) - assert.doesNotMatch(view.tree().props.filterBar.summaryText, /失败/) - } finally { view.unmount() } -}) - -test('查询与功能切换废弃旧端口响应,旧成功或失败均不污染新查询', async () => { - const { host, reads } = fixture() - const first = deferred() - reads.ports = () => first.promise - const view = await mount(portLookup, host) - try { - reads.ports = () => [port(200)] - await view.search('8080') - assert.deepEqual(ids(view), ['200']) - first.resolve([port(100)]) - await tick() - assert.deepEqual(ids(view), ['200']) - const leaving = deferred() - reads.ports = () => leaving.promise - await advance() - await view.dropdown('memory') - await view.search('') - leaving.reject(new Error('已退出端口功能')) - await tick() - assert.doesNotMatch(view.text(), /已退出端口功能/) - reads.ports = () => [port(100)] - await view.dropdown('port') - assert.deepEqual(ids(view), ['100']) - } finally { view.unmount() } -}) - -test('暂停时首次进入端口和输入变化各读取一次,Ctrl+R仍刷新端口', async () => { - const { host, reads, calls } = fixture() - const view = await mount(Command, host) - try { - await action(view, 'toggle-auto-refresh') - await view.dropdown('port') - assert.deepEqual(ids(view), ['100']) - assert.equal(calls.ports, 1) - await view.search('8080') - assert.equal(calls.ports, 2) - await advance(6000) - assert.equal(calls.ports, 2) - reads.ports = () => [port(200)] - await view.run(view.item('100'), '刷新列表') - assert.deepEqual(ids(view), ['200']) - assert.equal(calls.ports, 3) - } finally { view.unmount() } -}) - -test('卸载后停止轮询,手动在途失败不再提示或启动额外详情请求', async () => { - const { host, reads, calls } = fixture() - const view = await mount(portLookup, host) - const pendingProcesses = deferred(), pendingPorts = deferred() - reads.processes = () => pendingProcesses.promise - reads.ports = () => pendingPorts.promise - await action(view, 'refresh-list') - view.unmount() - const stoppedCalls = { ...calls }, toastCount = host.toasts.length - pendingProcesses.reject(new Error('页面已经卸载')) - pendingPorts.reject(new Error('页面已经卸载')) - await tick() - await advance(6000) - assert.deepEqual(calls, stoppedCalls) - assert.equal(host.toasts.length, toastCount) -}) - -test('暂停后手动刷新得到新进程快照,旧进程请求失败不覆盖新状态', async () => { - const { host, reads } = fixture() - const view = await mount(Command, host) - try { - const oldProcesses = deferred() - reads.processes = () => oldProcesses.promise - await action(view, 'refresh-list') - await action(view, 'toggle-auto-refresh') - reads.processes = () => [process(200)] - await action(view, 'refresh-list') - assert.deepEqual(ids(view), ['200']) - const toastCount = host.toasts.length - oldProcesses.reject(new Error('旧进程请求失败')) - await tick() - assert.deepEqual(ids(view), ['200']) - assert.doesNotMatch(view.tree().props.filterBar.summaryText, /不可用|过期/) - assert.equal(host.toasts.length, toastCount) - } finally { view.unmount() } -}) diff --git a/extensions/quick-folders/package.json b/extensions/quick-folders/package.json index 076e1fd3..f700422b 100644 --- a/extensions/quick-folders/package.json +++ b/extensions/quick-folders/package.json @@ -1,6 +1,6 @@ { "name": "@ztools/plugin-quick-folders", - "version": "1.1.5", + "version": "1.1.11", "description": "桌面、下载、文档、应用数据与临时目录等常用文件夹一键直达(Windows / macOS)", "main": "dist/index.js", "types": "dist/index.d.ts", diff --git a/extensions/quick-folders/plugin.json b/extensions/quick-folders/plugin.json index 5a2022de..ae1fab46 100644 --- a/extensions/quick-folders/plugin.json +++ b/extensions/quick-folders/plugin.json @@ -2,7 +2,7 @@ "id": "quick-folders", "name": "常用文件夹", "description": "一键打开桌面、下载、文档、AppData 与系统临时目录等高频文件夹,免去层层翻找", - "version": "1.1.10", + "version": "1.1.11", "minAppVersion": "1.1.8.0", "author": "ZTools Team", "entry": "dist/index.js", diff --git a/extensions/quick-folders/src/i18n.ts b/extensions/quick-folders/src/i18n.ts index 18adcfc6..7feff8d3 100644 --- a/extensions/quick-folders/src/i18n.ts +++ b/extensions/quick-folders/src/i18n.ts @@ -9,12 +9,19 @@ export const t = createTranslator( openedTitle: "已打开目录", openFailedTitle: "打开目录失败", openAction: "打开目录", + revealInFolderAction: "在文件管理器中定位", + openInTerminalAction: "在终端中打开", + openedTerminalTitle: "已在终端中打开", + openTerminalFallbackTitle: "已复制终端进入命令", + openTerminalFallbackMsg: "当前客户端暂不支持直启终端,已复制:{cmd}", + openTerminalFailedTitle: "终端打开失败", copyPathAction: "复制完整路径", copiedPathTitle: "已复制路径", copyTerminalCdAction: "复制终端进入命令", copiedTerminalCdTitle: "已复制终端进入命令", addFolderAction: "添加收藏目录", manualAddFolderAction: "手动添加目录", + editFolderAction: "编辑收藏…", pinFolderAction: "置顶此目录", unpinFolderAction: "取消置顶", removeFolderAction: "移除收藏", @@ -25,6 +32,7 @@ export const t = createTranslator( customFolderDesc: "自定义收藏目录", sectionCustom: "自定义收藏目录 ({count})", formTitle: "添加自定义收藏目录", + editFormTitle: "编辑自定义收藏目录", formPathLabel: "文件夹路径", formPathPlaceholder: "输入或粘贴完整目录路径", formNameLabel: "显示名称(可选)", @@ -32,7 +40,10 @@ export const t = createTranslator( formSubmitAction: "保存到收藏", errPathEmpty: "请输入文件夹路径", errDuplicatePath: "该目录已在收藏列表中", + errNotFound: "未找到该收藏目录", + loadCustomFailedTitle: "读取自定义收藏失败", toastFolderAdded: "已添加到收藏目录", + toastFolderUpdated: "已更新收藏目录", toastFolderRemoved: "已移除收藏目录", toastFolderPinned: "已置顶目录", toastFolderUnpinned: "已取消置顶", @@ -40,6 +51,14 @@ export const t = createTranslator( toastSelectDialogFailed: "无法打开目录选择框", summaryText: "系统目录 {systemCount} 项 · 自定义收藏 {customCount} 项", searchPlaceholder: "搜索常用目录,如 桌面、下载、资源库、临时", + categoryTooltip: "按目录分区筛选", + categoryAll: "全部分区", + categoryCustom: "自定义收藏", + categoryPersonal: "个人常用", + categorySystem: "系统与配置", + categoryTemp: "临时与缓存", + emptyTitle: "未找到匹配的目录", + emptyDescription: "可调整搜索关键词或分区筛选,也可点击上方添加自定义收藏目录", sectionPersonal: "个人常用目录 ({count})", sectionSystem: "系统与配置目录 ({count})", sectionTemp: "临时与缓存目录 ({count})", @@ -83,12 +102,19 @@ export const t = createTranslator( openedTitle: "Folder opened", openFailedTitle: "Failed to open folder", openAction: "Open Folder", + revealInFolderAction: "Reveal in File Manager", + openInTerminalAction: "Open in Terminal", + openedTerminalTitle: "Opened in Terminal", + openTerminalFallbackTitle: "Terminal cd Command Copied", + openTerminalFallbackMsg: "Direct terminal launch is unavailable; copied: {cmd}", + openTerminalFailedTitle: "Failed to Open in Terminal", copyPathAction: "Copy Full Path", copiedPathTitle: "Path copied", copyTerminalCdAction: "Copy Terminal cd Command", copiedTerminalCdTitle: "Terminal cd command copied", addFolderAction: "Add Favorite Folder", manualAddFolderAction: "Add by Path", + editFolderAction: "Edit Favorite…", pinFolderAction: "Pin Folder", unpinFolderAction: "Unpin Folder", removeFolderAction: "Remove Favorite", @@ -99,6 +125,7 @@ export const t = createTranslator( customFolderDesc: "Custom favorite folder", sectionCustom: "Custom Favorites ({count})", formTitle: "Add Favorite Folder", + editFormTitle: "Edit Favorite Folder", formPathLabel: "Folder Path", formPathPlaceholder: "Enter or paste full folder path", formNameLabel: "Display Name (Optional)", @@ -106,7 +133,10 @@ export const t = createTranslator( formSubmitAction: "Save Favorite", errPathEmpty: "Please enter a folder path", errDuplicatePath: "This folder is already in your favorites", + errNotFound: "Favorite folder not found", + loadCustomFailedTitle: "Failed to load custom favorites", toastFolderAdded: "Added to favorites", + toastFolderUpdated: "Favorite updated", toastFolderRemoved: "Removed from favorites", toastFolderPinned: "Folder pinned", toastFolderUnpinned: "Folder unpinned", @@ -114,6 +144,14 @@ export const t = createTranslator( toastSelectDialogFailed: "Unable to open folder picker", summaryText: "{systemCount} system · {customCount} favorites", searchPlaceholder: "Search common folders, e.g. Desktop, Downloads, Library, Temp", + categoryTooltip: "Filter by Section", + categoryAll: "All Sections", + categoryCustom: "Custom Favorites", + categoryPersonal: "Personal", + categorySystem: "System & Config", + categoryTemp: "Temp & Cache", + emptyTitle: "No Matching Folders", + emptyDescription: "Adjust your search or section filter, or add a custom favorite folder above", sectionPersonal: "Personal Folders ({count})", sectionSystem: "System & Config Folders ({count})", sectionTemp: "Temp & Cache Folders ({count})", diff --git a/extensions/quick-folders/src/index.ts b/extensions/quick-folders/src/index.ts index 917b9b34..04c3b833 100644 --- a/extensions/quick-folders/src/index.ts +++ b/extensions/quick-folders/src/index.ts @@ -24,6 +24,7 @@ import { removeCustomFolder, toCustomFolderItem, togglePinCustomFolder, + updateCustomFolder, type CustomFolderEntry, type FolderItem, type HostFolderPaths @@ -48,15 +49,27 @@ async function loadFolders(): Promise { return buildFolders(paths) } -async function loadCustomFolders(): Promise { +async function loadCustomFolders(): Promise<{ list: CustomFolderEntry[]; error: string }> { try { const raw = await LocalStorage.getItem(CUSTOM_FOLDERS_STORAGE_KEY) - return normalizeCustomFolders(raw) - } catch { - return [] + return { list: normalizeCustomFolders(raw), error: '' } + } catch (err) { + return { list: [], error: err instanceof Error ? err.message : String(err) } } } +async function mutateCustomFolders( + updater: (current: CustomFolderEntry[]) => CustomFolderEntry[] +): Promise { + if (typeof LocalStorage.updateItem === 'function') { + return LocalStorage.updateItem(CUSTOM_FOLDERS_STORAGE_KEY, (raw: unknown) => updater(normalizeCustomFolders(raw))) + } + const current = normalizeCustomFolders(await LocalStorage.getItem(CUSTOM_FOLDERS_STORAGE_KEY)) + const next = updater(current) + await LocalStorage.setItem(CUSTOM_FOLDERS_STORAGE_KEY, next) + return next +} + /** * 复制文本:等宿主确认写入成功后才提示成功;写入失败(内容为空、超过上限、剪贴板被占用等)时提示失败原因,不能假装已复制 */ @@ -74,13 +87,14 @@ async function copyWithToast(text: string, successTitle: string, successMessage? await showToast({ style: Toast.Style.Success, title: successTitle, message: successMessage }) } -function AddCustomFolderForm(props: { +function CustomFolderForm(props: { + initial?: { path: string; name: string } onSave: (input: { path: string; name?: string }) => Promise }) { useLocale() const { pop } = useNavigation() - const [folderPath, setFolderPath] = useState('') - const [folderName, setFolderName] = useState('') + const [folderPath, setFolderPath] = useState(props.initial?.path ?? '') + const [folderName, setFolderName] = useState(props.initial?.name ?? '') const [pathError, setPathError] = useState('') async function handleSubmit() { @@ -93,7 +107,7 @@ function AddCustomFolderForm(props: { } return Form({ - navigationTitle: t('formTitle'), + navigationTitle: props.initial ? t('editFormTitle') : t('formTitle'), actions: ActionPanel({ children: [ Action.SubmitForm({ @@ -127,10 +141,13 @@ function AddCustomFolderForm(props: { }) } +type CategoryFilter = 'all' | 'custom' | 'personal' | 'system' | 'temp' + export default function QuickFoldersCommand() { useLocale() const { push } = useNavigation() const [searchText, setSearchText] = useState('') + const [categoryFilter, setCategoryFilter] = useState('all') const [folders, setFolders] = useState([]) const [customFolders, setCustomFolders] = useState([]) const [loading, setLoading] = useState(true) @@ -144,46 +161,84 @@ export default function QuickFoldersCommand() { (err: unknown) => ({ list: [] as FolderItem[], error: err instanceof Error ? err.message : String(err) }) ), loadCustomFolders() - ]).then(([sysResult, customList]) => { + ]).then(([sysResult, customResult]) => { if (!alive) return setFolders(sysResult.list) - setCustomFolders(customList) + setCustomFolders(customResult.list) setLoading(false) if (sysResult.error) void showToast({ style: Toast.Style.Failure, title: t('loadFailedTitle'), message: sysResult.error }) + if (customResult.error) void showToast({ style: Toast.Style.Failure, title: t('loadCustomFailedTitle'), message: customResult.error }) }) return () => { alive = false } }, []) - async function persistCustomFolders(next: CustomFolderEntry[]): Promise { + async function saveCustomFolder(input: { path: string; name?: string }): Promise { + let addedPath = '' + let validationError: 'errPathEmpty' | 'errDuplicatePath' | null = null try { - await LocalStorage.setItem(CUSTOM_FOLDERS_STORAGE_KEY, next) + const next = await mutateCustomFolders((current) => { + const result = addCustomFolder(current, input) + if (!result.ok) { + validationError = result.errorKey + return current + } + addedPath = result.added.path + return result.list + }) + if (validationError) { + const msg = t(validationError) + await showToast({ style: Toast.Style.Failure, title: t('toastSaveFailed'), message: msg }) + return msg + } setCustomFolders(next) - return true + await showToast({ style: Toast.Style.Success, title: t('toastFolderAdded'), message: addedPath }) + return null } catch (err) { - await showToast({ - style: Toast.Style.Failure, - title: t('toastSaveFailed'), - message: err instanceof Error ? err.message : String(err) - }) - return false + const message = err instanceof Error ? err.message : String(err) + await showToast({ style: Toast.Style.Failure, title: t('toastSaveFailed'), message }) + return message } } - async function saveCustomFolder(input: { path: string; name?: string }): Promise { - const result = addCustomFolder(customFolders, input) - if (!result.ok) { - const msg = t(result.errorKey) - await showToast({ style: Toast.Style.Failure, title: t('toastSaveFailed'), message: msg }) - return msg + async function editCustomFolder(id: string, input: { path: string; name?: string }): Promise { + let updatedPath = '' + let validationError: 'errPathEmpty' | 'errDuplicatePath' | 'errNotFound' | null = null + try { + const next = await mutateCustomFolders((current) => { + const result = updateCustomFolder(current, id, input) + if (!result.ok) { + validationError = result.errorKey + return current + } + updatedPath = result.updated.path + return result.list + }) + if (validationError) { + const msg = t(validationError) + await showToast({ style: Toast.Style.Failure, title: t('toastSaveFailed'), message: msg }) + return msg + } + setCustomFolders(next) + await showToast({ style: Toast.Style.Success, title: t('toastFolderUpdated'), message: updatedPath }) + return null + } catch (err) { + const message = err instanceof Error ? err.message : String(err) + await showToast({ style: Toast.Style.Failure, title: t('toastSaveFailed'), message }) + return message } - const saved = await persistCustomFolders(result.list) - if (!saved) return t('toastSaveFailed') - await showToast({ style: Toast.Style.Success, title: t('toastFolderAdded'), message: result.added.path }) - return null } function openManualAddForm() { - push(() => AddCustomFolderForm({ onSave: saveCustomFolder })) + push(() => CustomFolderForm({ onSave: saveCustomFolder })) + } + + function openEditCustomForm(folder: FolderItem) { + push(() => + CustomFolderForm({ + initial: { path: folder.path, name: folder.name }, + onSave: (input) => editCustomFolder(folder.id, input) + }) + ) } async function pickAndAddFolder() { @@ -210,9 +265,21 @@ export default function QuickFoldersCommand() { } async function handleTogglePin(id: string) { - const { list, pinned } = togglePinCustomFolder(customFolders, id) - if (await persistCustomFolders(list)) { + try { + let pinned = false + const next = await mutateCustomFolders((current) => { + const result = togglePinCustomFolder(current, id) + pinned = result.pinned + return result.list + }) + setCustomFolders(next) await showToast({ style: Toast.Style.Success, title: pinned ? t('toastFolderPinned') : t('toastFolderUnpinned') }) + } catch (err) { + await showToast({ + style: Toast.Style.Failure, + title: t('toastSaveFailed'), + message: err instanceof Error ? err.message : String(err) + }) } } @@ -224,9 +291,16 @@ export default function QuickFoldersCommand() { dismissAction: { title: t('confirmCancel') } }) if (!confirmed) return - const next = removeCustomFolder(customFolders, folder.id) - if (await persistCustomFolders(next)) { + try { + const next = await mutateCustomFolders((current) => removeCustomFolder(current, folder.id)) + setCustomFolders(next) await showToast({ style: Toast.Style.Success, title: t('toastFolderRemoved') }) + } catch (err) { + await showToast({ + style: Toast.Style.Failure, + title: t('toastSaveFailed'), + message: err instanceof Error ? err.message : String(err) + }) } } @@ -237,9 +311,32 @@ export default function QuickFoldersCommand() { : { style: Toast.Style.Failure, title: t('openFailedTitle'), message: res.error ? `${folder.path}:${res.error}` : folder.path }) } + async function openInTerminal(folder: FolderItem) { + const res = await callHostTransport('shell_open_terminal', { path: folder.path, cwd: folder.path }) + if (res.ok) { + await showToast({ style: Toast.Style.Success, title: t('openedTerminalTitle'), message: folder.path }) + return + } + if (res.errorCode === 'METHOD_NOT_AVAILABLE' || res.errorCode === 'NOT_SUPPORTED' || res.errorCode === 'METHOD_NOT_FOUND') { + const cdCommand = buildTerminalCdCommand(folder.path) + await copyWithToast( + cdCommand, + t('openTerminalFallbackTitle'), + t('openTerminalFallbackMsg', { cmd: cdCommand }) + ) + return + } + await showToast({ + style: Toast.Style.Failure, + title: t('openTerminalFailedTitle'), + message: res.error ? `${folder.path}:${res.error}` : folder.path + }) + } + const allFolders = [...customFolders.map(toCustomFolderItem), ...folders] const query = searchText.trim().toLowerCase() const filtered = allFolders.filter(f => { + if (categoryFilter !== 'all' && f.category !== categoryFilter) return false if (!query) return true return ( f.name.toLowerCase().includes(query) || @@ -277,20 +374,35 @@ export default function QuickFoldersCommand() { icon: Icon.ArrowRight, onAction: () => openFolder(f) }), + Action({ + title: t('openInTerminalAction'), + icon: Icon.Terminal, + shortcut: { modifiers: ['ctrl', 'shift'], key: 't' }, + onAction: () => openInTerminal(f) + }), Action({ title: t('copyPathAction'), icon: Icon.Clipboard, shortcut: { modifiers: ['ctrl'], key: 'c' }, onAction: () => copyWithToast(f.path, t('copiedPathTitle'), f.path) }), + Action.ShowInFinder({ + title: t('revealInFolderAction'), + path: f.path + }), Action({ title: t('copyTerminalCdAction'), icon: Icon.Terminal, - shortcut: { modifiers: ['ctrl', 'shift'], key: 't' }, onAction: () => copyWithToast(cdCommand, t('copiedTerminalCdTitle'), cdCommand) }), ...(isCustom ? [ + Action({ + title: t('editFolderAction'), + icon: Icon.Pencil, + shortcut: { modifiers: ['ctrl'], key: 'e' }, + onAction: () => openEditCustomForm(f) + }), Action({ title: f.pinned ? t('unpinFolderAction') : t('pinFolderAction'), icon: Icon.Pin, @@ -309,14 +421,53 @@ export default function QuickFoldersCommand() { }) } + const sections = [ + custom.length > 0 && + List.Section({ + title: t('sectionCustom', { count: custom.length }), + children: custom.map(renderFolderItem) + }), + personal.length > 0 && + List.Section({ + title: t('sectionPersonal', { count: personal.length }), + children: personal.map(renderFolderItem) + }), + system.length > 0 && + List.Section({ + title: t('sectionSystem', { count: system.length }), + children: system.map(renderFolderItem) + }), + temp.length > 0 && + List.Section({ + title: t('sectionTemp', { count: temp.length }), + children: temp.map(renderFolderItem) + }) + ].filter(Boolean) + return List({ isLoading: loading, searchBarPlaceholder: t('searchPlaceholder'), onSearchTextChange: setSearchText, + searchBarAccessory: List.Dropdown({ + tooltip: t('categoryTooltip'), + value: categoryFilter, + onChange: (value: string) => + setCategoryFilter( + value === 'custom' || value === 'personal' || value === 'system' || value === 'temp' ? value : 'all' + ), + children: [ + List.Dropdown.Item({ title: t('categoryAll'), value: 'all' }), + List.Dropdown.Item({ title: t('categoryCustom'), value: 'custom' }), + List.Dropdown.Item({ title: t('categoryPersonal'), value: 'personal' }), + List.Dropdown.Item({ title: t('categorySystem'), value: 'system' }), + List.Dropdown.Item({ title: t('categoryTemp'), value: 'temp' }) + ] + }), filterBar: { summaryText: t('summaryText', { systemCount: folders.length, customCount: customFolders.length }), actions: [ - { id: 'add-folder', title: t('addFolderAction'), icon: Icon.Plus, onAction: () => pickAndAddFolder() } + { id: 'add-folder', title: t('addFolderAction'), icon: Icon.Plus, onAction: () => pickAndAddFolder() }, + { id: 'manual-add-folder', title: t('manualAddFolderAction'), icon: Icon.Pencil, onAction: () => openManualAddForm() } ] }, actions: ActionPanel({ @@ -334,27 +485,15 @@ export default function QuickFoldersCommand() { }) ] }), - children: [ - custom.length > 0 && - List.Section({ - title: t('sectionCustom', { count: custom.length }), - children: custom.map(renderFolderItem) - }), - personal.length > 0 && - List.Section({ - title: t('sectionPersonal', { count: personal.length }), - children: personal.map(renderFolderItem) - }), - system.length > 0 && - List.Section({ - title: t('sectionSystem', { count: system.length }), - children: system.map(renderFolderItem) - }), - temp.length > 0 && - List.Section({ - title: t('sectionTemp', { count: temp.length }), - children: temp.map(renderFolderItem) - }) - ].filter(Boolean) + children: + sections.length > 0 + ? sections + : [ + List.EmptyView({ + title: t('emptyTitle'), + description: t('emptyDescription'), + icon: Icon.Folder + }) + ] }) } diff --git a/extensions/quick-folders/src/logic.ts b/extensions/quick-folders/src/logic.ts index 832b3d5e..2f8f0016 100644 --- a/extensions/quick-folders/src/logic.ts +++ b/extensions/quick-folders/src/logic.ts @@ -102,6 +102,32 @@ export function togglePinCustomFolder(list: CustomFolderEntry[], id: string): { return { list: sortCustomFolders(updated), pinned: nextPinned } } +export function updateCustomFolder( + list: CustomFolderEntry[], + id: string, + input: { path: string; name?: string } +): { ok: true; list: CustomFolderEntry[]; updated: CustomFolderEntry } | { ok: false; errorKey: 'errPathEmpty' | 'errDuplicatePath' | 'errNotFound' } { + const target = list.find(item => item.id === id) + if (!target) return { ok: false, errorKey: 'errNotFound' } + const cleanPath = String(input.path || '').trim() + if (!cleanPath) return { ok: false, errorKey: 'errPathEmpty' } + const key = normalizeComparablePath(cleanPath) + if (list.some(item => item.id !== id && normalizeComparablePath(item.path) === key)) { + return { ok: false, errorKey: 'errDuplicatePath' } + } + const cleanName = String(input.name || '').trim() || deriveFolderName(cleanPath) + const updated: CustomFolderEntry = { + ...target, + name: cleanName, + path: cleanPath + } + return { + ok: true, + list: sortCustomFolders(list.map(item => (item.id === id ? updated : item))), + updated + } +} + export function removeCustomFolder(list: CustomFolderEntry[], id: string): CustomFolderEntry[] { return list.filter(item => item.id !== id) } diff --git a/extensions/quick-folders/tests/quick-folders.common-folders.test.mjs b/extensions/quick-folders/tests/quick-folders.common-folders.test.mjs deleted file mode 100644 index f533d46c..00000000 --- a/extensions/quick-folders/tests/quick-folders.common-folders.test.mjs +++ /dev/null @@ -1,228 +0,0 @@ -// 常用目录改用宿主 system_list_common_folders 的集成测试:真实声明式运行时 + 模拟宿主(含路径授权语义) -// 覆盖:按宿主 id 映射列表项、不存在的目录隐藏、只打开宿主授权过的目录、旧宿主 / 异常返回回落到 system_get_path、 -// 畸形条目过滤、授权失效时提示失败而不是假装打开 -import test from 'node:test' -import assert from 'node:assert/strict' -import { createHost, mount, tick } from '../../shared/test-harness.mjs' -import QuickFoldersCommand from '../dist/index.js' -import { buildFoldersFromHost } from '../dist/logic.js' - -const host = createHost() -const rejections = [] -process.on('unhandledRejection', (reason) => rejections.push(reason)) - -test.beforeEach(() => { - host.reset() - rejections.length = 0 -}) - -const MAC_FOLDERS = [ - { id: 'home', path: '/Users/bob', exists: true }, - { id: 'desktop', path: '/Users/bob/Desktop', exists: true }, - { id: 'downloads', path: '/Users/bob/Downloads', exists: false }, - { id: 'documents', path: '/Users/bob/Documents', exists: true }, - { id: 'pictures', path: '/Users/bob/Pictures', exists: true }, - { id: 'videos', path: '/Users/bob/Movies', exists: true }, - { id: 'music', path: '/Users/bob/Music', exists: true }, - { id: 'appData', path: '/Users/bob/Library/Application Support', exists: true }, - { id: 'applications', path: '/Applications', exists: true }, - { id: 'library', path: '/Users/bob/Library', exists: true }, - { id: 'libraryCaches', path: '/Users/bob/Library/Caches', exists: true }, - { id: 'temp', path: '/var/folders/xy/abc123/T', exists: true } -] - -const WIN_FOLDERS = [ - { id: 'home', path: 'D:\\Users\\alice', exists: true }, - { id: 'desktop', path: 'D:\\Users\\alice\\OneDrive\\桌面', exists: true }, - { id: 'downloads', path: 'D:\\Users\\alice\\Downloads', exists: true }, - { id: 'documents', path: 'D:\\Users\\alice\\Documents', exists: true }, - { id: 'pictures', path: 'D:\\Users\\alice\\Pictures', exists: true }, - { id: 'videos', path: 'D:\\Users\\alice\\Videos', exists: true }, - { id: 'music', path: 'D:\\Users\\alice\\Music', exists: true }, - { id: 'appData', path: 'D:\\Users\\alice\\AppData\\Roaming', exists: true }, - { id: 'localAppData', path: 'D:\\Users\\alice\\AppData\\Local', exists: true }, - { id: 'systemDrive', path: 'D:\\', exists: true }, - { id: 'temp', path: 'D:\\Users\\alice\\AppData\\Local\\Temp', exists: true } -] - -/** - * 与真实宿主一致:system_list_common_folders 把 exists:true 的目录授权给本窗口(只读、不递归), - * shell_open_path 只放行已授权的路径,其余 PERMISSION_DENIED。返回授权表供用例撤销(模拟 30 分钟过期)。 - */ -function installCommonFolderHost(folders) { - const granted = new Set() - const opened = [] - host.ipc.system_list_common_folders = async (params) => { - if (params && Object.keys(params).length > 0) throw Object.assign(new Error('未知参数'), { code: 'INVALID_REQUEST' }) - for (const f of folders) if (f && f.exists === true && typeof f.path === 'string') granted.add(f.path) - return { success: true, data: { folders } } - } - host.ipc.shell_open_path = async ({ fullPath }) => { - if (!granted.has(fullPath)) throw Object.assign(new Error('路径未由当前窗口授权'), { code: 'PERMISSION_DENIED' }) - opened.push(fullPath) - return { success: true } - } - return { granted, opened } -} - -function installLegacyPathHost(home) { - host.ipc.system_get_path = async ({ name }) => { - if (name === 'home') return { success: true, path: home } - const child = { desktop: 'Desktop', downloads: 'Downloads', documents: 'Documents', pictures: 'Pictures', videos: 'Movies', music: 'Music', appData: 'Library/Application Support' }[name] - return child ? { success: true, path: `${home}/${child}` } : { success: false } - } -} - -test('macOS:列表直接用宿主返回的目录,id 映射到原有列表项,不再逐个读 system_get_path', async () => { - installCommonFolderHost(MAC_FOLDERS) - const view = await mount(QuickFoldersCommand) - await tick(10) - - const ids = view.items().map((i) => i.props.id) - assert.deepEqual(ids, ['desktop', 'documents', 'pictures', 'videos', 'music', 'userprofile', 'applications', 'app-support', 'library', 'caches', 'temp']) - assert.equal(view.item('userprofile').props.subtitle, '/Users/bob') - assert.equal(view.item('app-support').props.subtitle, '/Users/bob/Library/Application Support') - assert.equal(view.item('caches').props.subtitle, '/Users/bob/Library/Caches') - assert.equal(view.item('videos').props.title, '影片') - // macOS 宿主的临时目录是 os.tmpdir()(/var/folders/...),不再是 /tmp - assert.equal(view.item('temp').props.subtitle, '/var/folders/xy/abc123/T') - assert.ok(!host.ipcCalls.some(([m]) => m === 'system_get_path'), '新宿主下不应再调用 system_get_path') - assert.deepEqual(host.ipcCalls.find(([m]) => m === 'system_list_common_folders')[1], {}, '只能传空参数(宿主拒绝未知字段)') - view.unmount() -}) - -test('标题只显示中文名,英文目录名放进关键词,按英文仍能搜到', async () => { - installCommonFolderHost(MAC_FOLDERS) - const view = await mount(QuickFoldersCommand) - await tick(10) - for (const item of view.items()) assert.doesNotMatch(item.props.title, /\([A-Za-z ]+\)/, item.props.title) - assert.doesNotMatch(view.tree().props.searchBarPlaceholder, /[A-Za-z]/) - assert.deepEqual(view.item('library').props.keywords, ['Library']) - await view.search('movies') - assert.deepEqual(view.items().map((i) => i.props.id), ['videos']) - await view.search('CACHES') - assert.deepEqual(view.items().map((i) => i.props.id), ['caches']) - await view.search('不存在的目录名xyz') - assert.equal(view.items().length, 0) - view.unmount() -}) - -test('macOS:不存在的目录不显示(宿主不会授权打开),搜索也搜不到', async () => { - installCommonFolderHost(MAC_FOLDERS) - const view = await mount(QuickFoldersCommand) - await tick(10) - assert.ok(!view.items().some((i) => i.props.id === 'downloads')) - await view.search('download') - assert.equal(view.items().length, 0) - view.unmount() -}) - -test('打开宿主授权过的目录成功并记录真实路径;资源库 / 应用程序都能打开', async () => { - const { opened } = installCommonFolderHost(MAC_FOLDERS) - const view = await mount(QuickFoldersCommand) - await tick(10) - await view.run(view.item('library'), '打开目录') - assert.equal(host.lastToast().title, '已打开目录') - await view.run(view.item('applications'), '打开目录') - await view.run(view.item('temp'), '打开目录') - assert.deepEqual(opened, ['/Users/bob/Library', '/Applications', '/var/folders/xy/abc123/T']) - assert.equal(host.lastToast().message, '/var/folders/xy/abc123/T') - view.unmount() -}) - -test('异常:授权已失效(窗口授权过期 / 宿主拒绝)时提示打开失败,不能显示“已打开”', async () => { - const { granted, opened } = installCommonFolderHost(MAC_FOLDERS) - const view = await mount(QuickFoldersCommand) - await tick(10) - granted.clear() - await view.run(view.item('documents'), '打开目录') - assert.equal(host.lastToast().title, '打开目录失败') - assert.match(host.lastToast().message, /^\/Users\/bob\/Documents/) - assert.match(host.lastToast().message, /未由当前窗口授权/) - assert.deepEqual(opened, []) - assert.equal(rejections.length, 0) - view.unmount() -}) - -test('Windows:home / appData / localAppData / systemDrive 映射到原有列表项,系统盘名称跟随宿主盘符', async () => { - installCommonFolderHost(WIN_FOLDERS) - const view = await mount(QuickFoldersCommand) - await tick(10) - assert.equal(view.item('userprofile').props.subtitle, 'D:\\Users\\alice') - assert.equal(view.item('desktop').props.subtitle, 'D:\\Users\\alice\\OneDrive\\桌面') - assert.equal(view.item('appdata-roaming').props.subtitle, 'D:\\Users\\alice\\AppData\\Roaming') - assert.equal(view.item('appdata-local').props.subtitle, 'D:\\Users\\alice\\AppData\\Local') - assert.equal(view.item('system-drive').props.subtitle, 'D:\\') - assert.equal(view.item('system-drive').props.title, '系统盘 (D:)') - assert.equal(view.item('videos').props.title, '视频') - assert.ok(!view.items().some((i) => ['applications', 'library', 'caches', 'app-support'].includes(i.props.id)), 'Windows 不出现 macOS 专属目录') - view.unmount() -}) - -test('旧宿主:没有 system_list_common_folders 时回落到 system_get_path 拼路径', async () => { - installLegacyPathHost('/Users/bob') - const view = await mount(QuickFoldersCommand) - await tick(10) - assert.ok(host.ipcCalls.some(([m]) => m === 'system_list_common_folders'), '应先尝试新方法') - assert.ok(host.ipcCalls.some(([m, p]) => m === 'system_get_path' && p?.name === 'home')) - assert.equal(view.item('downloads').props.subtitle, '/Users/bob/Downloads') - assert.equal(view.item('temp').props.subtitle, '/tmp', '旧宿主下临时目录仍按系统约定生成') - view.unmount() -}) - -test('异常:新方法报错或返回结构不对时回落,不白屏、不留未处理的 rejection', async () => { - for (const broken of [ - async () => { throw Object.assign(new Error('内部错误'), { code: 'INTERNAL_ERROR' }) }, - async () => ({ success: true, data: { folders: 'not-an-array' } }), - async () => ({ success: true, data: null }), - async () => ({ success: false, error: { code: 'PERMISSION_DENIED', message: '拒绝' } }) - ]) { - host.reset() - installLegacyPathHost('/Users/bob') - host.ipc.system_list_common_folders = broken - const view = await mount(QuickFoldersCommand) - await tick(10) - assert.equal(view.item('userprofile').props.subtitle, '/Users/bob') - view.unmount() - } - assert.equal(rejections.length, 0) -}) - -test('异常:新方法与 system_get_path 都失败时列表为空并提示读取失败', async () => { - host.ipc.system_list_common_folders = async () => { throw Object.assign(new Error('断开'), { code: 'IPC_CLOSED' }) } - host.ipc.system_get_path = async () => { throw Object.assign(new Error('读取失败'), { code: 'FILE_ERROR' }) } - const view = await mount(QuickFoldersCommand) - await tick(10) - assert.equal(view.items().length, 0) - assert.ok(host.toasts.some((t) => t.title === '读取系统目录失败')) - view.unmount() -}) - -test('边界:宿主返回的目录都不存在时列表为空并提示,不回落编造路径', async () => { - installCommonFolderHost(MAC_FOLDERS.map((f) => ({ ...f, exists: false }))) - installLegacyPathHost('/Users/bob') - const view = await mount(QuickFoldersCommand) - await tick(10) - assert.equal(view.items().length, 0) - assert.ok(!host.ipcCalls.some(([m]) => m === 'system_get_path')) - assert.ok(host.toasts.some((t) => t.title === '读取系统目录失败')) - view.unmount() -}) - -test('畸形条目:非对象、缺 id / 路径、exists 不是 true、重复 id、未知 id 都被忽略', () => { - const list = buildFoldersFromHost([ - null, - 'str', - { id: 'home', path: '/Users/bob', exists: true }, - { id: 'home', path: '/Users/evil', exists: true }, - { id: 'desktop', path: '', exists: true }, - { id: 42, path: '/x', exists: true }, - { id: 'documents', path: '/Users/bob/Documents', exists: 'true' }, - { id: 'pictures', path: ' /Users/bob/Pictures ', exists: true }, - { id: 'unknownFutureFolder', path: '/opt/x', exists: true } - ]) - assert.deepEqual(list.map((f) => [f.id, f.path]), [['pictures', '/Users/bob/Pictures'], ['userprofile', '/Users/bob']]) - assert.equal(buildFoldersFromHost(undefined), null) - assert.equal(buildFoldersFromHost({ folders: [] }), null) - assert.deepEqual(buildFoldersFromHost([]), []) -}) diff --git a/extensions/quick-folders/tests/quick-folders.favorites.test.mjs b/extensions/quick-folders/tests/quick-folders.favorites.test.mjs deleted file mode 100644 index 89dd91d5..00000000 --- a/extensions/quick-folders/tests/quick-folders.favorites.test.mjs +++ /dev/null @@ -1,143 +0,0 @@ -import test from 'node:test' -import assert from 'node:assert/strict' -import { Toast } from '@ztools/declarative-ui' -import { createHost, mount, mountPushed, tick } from '../../shared/test-harness.mjs' -import QuickFoldersCommand from '../dist/index.js' -import { buildTerminalCdCommand, CUSTOM_FOLDERS_STORAGE_KEY } from '../dist/logic.js' - -const host = createHost() - -const WIN_FOLDERS = [ - { id: 'home', path: 'D:\\Users\\alice', exists: true }, - { id: 'desktop', path: 'D:\\Users\\alice\\Desktop', exists: true }, - { id: 'downloads', path: 'D:\\Users\\alice\\Downloads', exists: true } -] - -test.beforeEach(() => { - host.reset() - host.ipc.system_list_common_folders = async () => ({ success: true, data: { folders: WIN_FOLDERS } }) -}) - -test('自定义收藏文件夹:选目录添加、置顶、持久化恢复与移除闭环', async () => { - host.ipc.window_show_select_folder_dialog = async () => ({ canceled: false, folderPath: 'E:\\Work\\Alpha' }) - const view = await mount(QuickFoldersCommand) - try { - await tick(10) - const addBtn = view.tree().props.filterBar.actions.find(a => a.id === 'add-folder') - await addBtn.onAction() - await tick() - assert.equal(host.lastToast().style, Toast.Style.Success) - assert.equal(host.lastToast().title, '已添加到收藏目录') - const addedItem = view.items().find(i => i.props.subtitle === 'E:\\Work\\Alpha') - assert.ok(addedItem) - assert.equal(addedItem.props.title, 'Alpha') - - // 添加第二个目录并置顶第二个,验证置顶排在最前 - host.ipc.window_show_select_folder_dialog = async () => ({ canceled: false, folderPath: 'E:\\Work\\Beta' }) - await addBtn.onAction() - await tick() - const betaItem = view.items().find(i => i.props.subtitle === 'E:\\Work\\Beta') - await view.run(betaItem, '置顶此目录') - assert.equal(host.lastToast().title, '已置顶目录') - assert.equal(view.items()[0].props.subtitle, 'E:\\Work\\Beta') - assert.ok(JSON.stringify(view.items()[0].props.accessories).includes('已置顶')) - - // 验证持久化:卸载重挂载后自定义收藏与置顶顺序仍在 - view.unmount() - const view2 = await mount(QuickFoldersCommand) - try { - await tick(10) - assert.equal(view2.items()[0].props.subtitle, 'E:\\Work\\Beta') - await view2.run(view2.items()[0], '移除收藏') - assert.equal(host.lastToast().title, '已移除收藏目录') - assert.ok(!view2.items().some(i => i.props.subtitle === 'E:\\Work\\Beta')) - } finally { - view2.unmount() - } - } finally { - view.unmount() - } -}) - -test('自定义收藏:对话框不支持时降级到手动添加表单,并拦截重复路径与空路径', async () => { - const view = await mount(QuickFoldersCommand) - try { - await tick(10) - // 测试宿主未实现 window_show_select_folder_dialog -> 自动打开手动添加表单 - const addBtn = view.tree().props.filterBar.actions.find(a => a.id === 'add-folder') - await addBtn.onAction() - await tick() - assert.equal(host.pushed.length, 1) - - const form = await mountPushed(host) - try { - // 空路径提交失败 - await form.run(undefined, '保存到收藏') - assert.equal(host.lastToast().style, Toast.Style.Failure) - assert.match(host.lastToast().message, /请输入文件夹路径/) - - await form.fill('path', 'E:\\Projects\\ZTools') - await form.fill('name', '主工程') - await form.run(undefined, '保存到收藏') - assert.equal(host.lastToast().style, Toast.Style.Success) - assert.equal(host.pushed.length, 0) - } finally { - form.unmount() - } - - await tick() - const saved = view.items().find(i => i.props.subtitle === 'E:\\Projects\\ZTools') - assert.ok(saved) - assert.equal(saved.props.title, '主工程') - - // 重复添加同一路径被拒绝(顶栏已去重为 1 个按钮,手动添加在动作面板) - assert.equal(view.tree().props.filterBar.actions.length, 1) - await view.run(undefined, '手动添加目录') - await tick() - const dupForm = await mountPushed(host) - try { - await dupForm.fill('path', 'E:\\Projects\\ZTools\\') - await dupForm.run(undefined, '保存到收藏') - assert.equal(host.lastToast().style, Toast.Style.Failure) - assert.match(host.lastToast().message, /已在收藏列表/) - } finally { - dupForm.unmount() - } - } finally { - view.unmount() - } -}) - -test('自定义收藏:存储写入失败时不篡改状态并提示失败', async () => { - host.ipc.window_show_select_folder_dialog = async () => ({ canceled: false, folderPath: 'E:\\FailSave' }) - host.faults.storageWrite = new Error('磁盘已满') - const view = await mount(QuickFoldersCommand) - try { - await tick(10) - const addBtn = view.tree().props.filterBar.actions.find(a => a.id === 'add-folder') - await addBtn.onAction() - await tick() - assert.equal(host.lastToast().style, Toast.Style.Failure) - assert.equal(host.lastToast().title, '保存收藏失败') - assert.ok(!view.items().some(i => i.props.subtitle === 'E:\\FailSave')) - assert.equal(host.storage.has(CUSTOM_FOLDERS_STORAGE_KEY), false) - } finally { - view.unmount() - } -}) - -test('复制终端进入命令:Windows 与 POSIX 路径生成准确并写入剪贴板', async () => { - assert.equal(buildTerminalCdCommand('D:\\Users\\alice\\Desktop'), 'cd /d "D:\\Users\\alice\\Desktop"') - assert.equal(buildTerminalCdCommand("/Users/bob/My 'Work'"), "cd '/Users/bob/My '\\''Work'\\'''") - - const view = await mount(QuickFoldersCommand) - try { - await tick(10) - await view.run(view.item('desktop'), '复制终端进入命令') - assert.equal(host.clipboard.text, 'cd /d "D:\\Users\\alice\\Desktop"') - assert.equal(host.lastToast().style, Toast.Style.Success) - assert.equal(host.lastToast().title, '已复制终端进入命令') - } finally { - view.unmount() - } -}) diff --git a/extensions/quick-folders/tests/quick-folders.temp.test.mjs b/extensions/quick-folders/tests/quick-folders.temp.test.mjs deleted file mode 100644 index 3346cd3b..00000000 --- a/extensions/quick-folders/tests/quick-folders.temp.test.mjs +++ /dev/null @@ -1,82 +0,0 @@ -import test from 'node:test' -import assert from 'node:assert/strict' -import { createHost, mount, tick } from '../../shared/test-harness.mjs' -import QuickFoldersCommand from '../dist/index.js' -import { buildFolders, systemTempPath } from '../dist/logic.js' - -const host = createHost() -test.beforeEach(() => host.reset()) - -// 与真实宿主一致:'temp' 返回 ZTools 自己的隔离缓存目录,而不是系统临时目录 -function installPathHost(home, { scopedTemp, failNames = [] } = {}) { - const windows = !home.startsWith('/') - const sep = windows ? '\\' : '/' - host.ipc.system_get_path = async ({ name }) => { - if (failNames.includes(name)) throw Object.assign(new Error('读取失败'), { code: 'FILE_ERROR' }) - if (name === 'home') return { success: true, path: home } - if (name === 'temp') return { success: true, path: scopedTemp } - const child = { desktop: 'Desktop', downloads: 'Downloads', documents: 'Documents', pictures: 'Pictures', videos: windows ? 'Videos' : 'Movies', music: 'Music', appData: windows ? 'AppData\\Roaming' : 'Library/Application Support' }[name] - return { success: true, path: home + sep + child } - } -} - -test('macOS:临时文件夹指向系统 /tmp,不是 ZTools 的 Cache/main/Temp,也不再向宿主要 temp', async () => { - const scoped = '/Users/bob/Library/Application Support/ZTools/Cache/main/Temp' - installPathHost('/Users/bob', { scopedTemp: scoped }) - const opened = [] - host.ipc.shell_open_path = async ({ fullPath }) => { opened.push(fullPath); return { success: true } } - const view = await mount(QuickFoldersCommand) - await tick(10) - - const temp = view.item('temp') - assert.equal(temp.props.subtitle, '/tmp') - assert.ok(!view.text().includes('ZTools/Cache'), '列表里不能出现 ZTools 自己的缓存目录') - assert.ok(!host.ipcCalls.some(([m, p]) => m === 'system_get_path' && p?.name === 'temp'), '不应再读取宿主的 temp') - - await view.run(temp, '打开目录') - assert.deepEqual(opened, ['/tmp']) - assert.equal(host.lastToast().title, '已打开目录') - assert.equal(host.lastToast().message, '/tmp') - - await view.search('temp') - assert.deepEqual(view.items().map((i) => i.props.id), ['temp']) - view.unmount() -}) - -test('Windows:临时文件夹为当前用户的 AppData\\Local\\Temp,跟随主目录所在盘符', async () => { - installPathHost('D:\\Users\\alice', { scopedTemp: 'D:\\Users\\alice\\AppData\\Roaming\\ZTools\\Cache\\main\\Temp' }) - const view = await mount(QuickFoldersCommand) - await tick(10) - assert.equal(view.item('temp').props.subtitle, 'D:\\Users\\alice\\AppData\\Local\\Temp') - assert.ok(!view.text().includes('ZTools'), '列表里不能出现 ZTools 自己的目录') - view.unmount() -}) - -test('异常:宿主拒绝打开临时文件夹时提示失败,不能显示“已打开”', async () => { - installPathHost('/Users/bob', { scopedTemp: '/Users/bob/Library/Application Support/ZTools/Cache/main/Temp' }) - host.ipc.shell_open_path = async () => { throw Object.assign(new Error('路径未由当前窗口授权'), { code: 'PERMISSION_DENIED' }) } - const view = await mount(QuickFoldersCommand) - await tick(10) - await view.run(view.item('temp'), '打开目录') - assert.equal(host.lastToast().title, '打开目录失败') - assert.equal(host.lastToast().message, '/tmp:路径未由当前窗口授权') - view.unmount() -}) - -test('异常:宿主读不到主目录时列表为空并提示读取失败,不编造临时目录', async () => { - installPathHost('/Users/bob', { failNames: ['home', 'desktop', 'downloads', 'documents', 'pictures', 'videos', 'music', 'appData'] }) - const view = await mount(QuickFoldersCommand) - await tick(10) - assert.equal(view.items().length, 0) - assert.ok(host.toasts.some((t) => t.title === '读取系统目录失败')) - view.unmount() -}) - -test('边界:即使调用方仍传入宿主的 temp,也只按系统约定生成;主目录尾部分隔符被规整', () => { - const mac = buildFolders({ home: '/Users/bob/', temp: '/Users/bob/Library/Application Support/ZTools/Cache/main/Temp' }) - assert.equal(mac.find((f) => f.id === 'temp').path, '/tmp') - const win = buildFolders({ home: 'C:\\Users\\alice\\', temp: 'C:\\Users\\alice\\AppData\\Roaming\\ZTools\\Cache\\main\\Temp' }) - assert.equal(win.find((f) => f.id === 'temp').path, 'C:\\Users\\alice\\AppData\\Local\\Temp') - assert.equal(systemTempPath('C:\\Users\\x', true), 'C:\\Users\\x\\AppData\\Local\\Temp') - assert.equal(systemTempPath('/Users/x', false), '/tmp') -}) diff --git a/extensions/quick-folders/tests/quick-folders.test.mjs b/extensions/quick-folders/tests/quick-folders.test.mjs index 9b04130a..814d27bd 100644 --- a/extensions/quick-folders/tests/quick-folders.test.mjs +++ b/extensions/quick-folders/tests/quick-folders.test.mjs @@ -3,8 +3,14 @@ import assert from 'node:assert/strict' import { getDefaultFolders, expandEnvironmentVariables, - buildFolders + buildFolders, + buildTerminalCdCommand, + addCustomFolder, + updateCustomFolder } from '../dist/logic.js' +import { mount, mountPushed, tick } from '../../shared/test-harness.mjs' +import { createRealHost, REAL_HOST_SKIP_REASON } from '../../shared/real-host-harness.mjs' +import QuickFoldersCommand from '../dist/index.js' test('QuickFolders 默认目录生成与分类测试', () => { const folders = getDefaultFolders({ @@ -85,3 +91,91 @@ test('QuickFolders 宿主读不到主目录或返回脏数据时不编造路径' assert.deepEqual(buildFolders(null), []) assert.deepEqual(buildFolders({ home: ' ' }), []) }) + +test('QuickFolders 自定义收藏编辑:支持重命名与路径去重边界校验', () => { + const added1 = addCustomFolder([], { path: 'E:\\work\\proj-a', name: '项目 A' }, 100) + assert.equal(added1.ok, true) + const added2 = addCustomFolder(added1.list, { path: 'E:\\work\\proj-b', name: '项目 B' }, 200) + assert.equal(added2.ok, true) + + const renamed = updateCustomFolder(added2.list, added1.added.id, { path: 'E:\\work\\proj-a', name: '核心主仓' }) + assert.equal(renamed.ok, true) + assert.equal(renamed.updated.name, '核心主仓') + + const dup = updateCustomFolder(renamed.list, added1.added.id, { path: 'e:\\WORK\\proj-b', name: '冲突' }) + assert.equal(dup.ok, false) + assert.equal(dup.errorKey, 'errDuplicatePath') + + const empty = updateCustomFolder(renamed.list, added1.added.id, { path: ' ', name: '空' }) + assert.equal(empty.ok, false) + assert.equal(empty.errorKey, 'errPathEmpty') + + const missing = updateCustomFolder(renamed.list, 'non-existent', { path: 'E:\\work\\x' }) + assert.equal(missing.ok, false) + assert.equal(missing.errorKey, 'errNotFound') +}) + +test('[集成] 自定义收藏与系统常用目录分区清晰,支持打开目录/终端打开(含回退)/编辑收藏/分类筛选', { skip: REAL_HOST_SKIP_REASON }, async () => { + const realHost = createRealHost({ pluginId: 'quick-folders' }) + try { + const customDir = realHost.sandboxDirs.documents + realHost.queueSelectFolderDialog(customDir) + + const view = await mount(QuickFoldersCommand) + try { + await tick(10) + // 系统目录分区清晰呈现 + assert.ok(view.text().includes('个人常用目录')) + assert.ok(view.text().includes('临时与缓存目录')) + + // 通过顶栏「添加收藏目录」真实走系统选目录 + 权限签发 + const addBtn = view.tree().props.filterBar.actions.find((a) => a.id === 'add-folder') + assert.ok(addBtn) + await addBtn.onAction() + await tick(10) + assert.ok(view.text().includes('自定义收藏目录 (1)')) + + const customItem = view.items().find((it) => it.props.id.startsWith('custom-')) + assert.ok(customItem) + + // 打开目录(走真实授权表检验) + await view.run(customItem, '打开目录') + await tick(5) + assert.equal(realHost.shellCalls.opened.length, 1) + + // 终端打开:真实宿主无 shell_open_terminal 时优雅回退复制 cd 命令 + await view.run(customItem, '在终端中打开') + await tick(5) + assert.match(String(realHost.lastToast()?.title), /已复制终端进入命令/) + + // 分类下拉仅看自定义收藏 + await view.dropdown('custom') + await tick(5) + assert.equal(view.items().length, 1) + assert.equal(view.items()[0].props.id, customItem.props.id) + + // 编辑自定义收藏名称 + await view.run(customItem, '编辑收藏…') + const form = await mountPushed(realHost) + try { + await form.fill('name', '主仓库') + await form.run(null, '保存到收藏') + await tick(10) + } finally { + form.unmount() + } + assert.equal(view.item(customItem.props.id).props.title, '主仓库') + } finally { + view.unmount() + } + } finally { + await realHost.dispose() + } +}) + +test('buildTerminalCdCommand 跨平台终端切换命令转义边界测试', () => { + assert.equal(buildTerminalCdCommand('E:\\work\\My Project'), 'cd /d "E:\\work\\My Project"') + assert.equal(buildTerminalCdCommand('/Users/bob/My Dir'), "cd '/Users/bob/My Dir'") + assert.equal(buildTerminalCdCommand("/Users/bob/O'Brien"), "cd '/Users/bob/O'\\''Brien'") + assert.equal(buildTerminalCdCommand(' '), '') +}) diff --git a/extensions/quicklinks/plugin.json b/extensions/quicklinks/plugin.json index f943eac7..68f16eaf 100644 --- a/extensions/quicklinks/plugin.json +++ b/extensions/quicklinks/plugin.json @@ -1,7 +1,7 @@ { "id": "quicklinks", "name": "网页快开", - "version": "1.1.7", + "version": "1.1.8", "minAppVersion": "1.1.8.0", "description": "聚合多平台快捷搜索与工作流网址组批量打开,支持自定义 {query} 变量与热键直达", "author": "ZTools Team", diff --git a/extensions/quicklinks/src/i18n.ts b/extensions/quicklinks/src/i18n.ts index 50ad4fb6..53af9726 100644 --- a/extensions/quicklinks/src/i18n.ts +++ b/extensions/quicklinks/src/i18n.ts @@ -19,7 +19,7 @@ const MESSAGES = { urlsLabel: "组内网址", urlsPlaceholder: "每行一个网址,打开时按顺序依次打开", linkTemplateLabel: "目标网址模板", - linkTemplatePlaceholder: "支持 {query} 变量,如:https://github.com/search?q={query}", + linkTemplatePlaceholder: "支持 {query} 和 {clipboard},如:https://github.com/search?q={query}", aliasLabel: "触发别名", aliasPlaceholder: "例如:gh", descLabel: "备注说明", @@ -64,6 +64,17 @@ const MESSAGES = { createBtn: "新建快捷链接", resetBtn: "恢复默认预设", aliasTag: "别名: {alias}", + openCountText: "已用 {count} 次", + clipboardTag: "剪贴板", + queryFormTitle: "输入搜索参数", + queryFieldLabel: "参数 {query}", + queryFieldPlaceholder: "输入搜索关键词,留空将直接打开站点首页", + querySubmitBtn: "打开搜索", + queryFillClipboardBtn: "填入剪贴板内容", + queryOpenHomeBtn: "直接打开站点首页", + queryClipboardEmptyToast: "当前剪贴板为空", + queryClipboardFilledToast: "已填入剪贴板内容", + actionOpenHome: "直接访问站点首页", groupCountText: "含 {count} 个网页", actionSearchOpen: "带参搜索 / 访问", actionOpenBrowser: "在浏览器中打开", @@ -128,7 +139,7 @@ const MESSAGES = { urlsLabel: "Group URLs", urlsPlaceholder: "One URL per line, opened in order", linkTemplateLabel: "Target URL Template", - linkTemplatePlaceholder: "Supports {query}, e.g. https://github.com/search?q={query}", + linkTemplatePlaceholder: "Supports {query} & {clipboard}, e.g. https://github.com/search?q={query}", aliasLabel: "Trigger Alias", aliasPlaceholder: "e.g. gh", descLabel: "Description", @@ -173,6 +184,17 @@ const MESSAGES = { createBtn: "New Quicklink", resetBtn: "Reset Defaults", aliasTag: "Alias: {alias}", + openCountText: "Used {count}x", + clipboardTag: "Clipboard", + queryFormTitle: "Enter Search Argument", + queryFieldLabel: "Argument {query}", + queryFieldPlaceholder: "Enter search query, or leave blank to open site homepage", + querySubmitBtn: "Open Search", + queryFillClipboardBtn: "Fill from Clipboard", + queryOpenHomeBtn: "Open Homepage Directly", + queryClipboardEmptyToast: "Clipboard is empty", + queryClipboardFilledToast: "Filled from clipboard", + actionOpenHome: "Open Homepage Directly", groupCountText: "{count} URL(s)", actionSearchOpen: "Search / Open", actionOpenBrowser: "Open in Browser", diff --git a/extensions/quicklinks/src/index.tsx b/extensions/quicklinks/src/index.tsx index fb6ed808..ab4982b1 100644 --- a/extensions/quicklinks/src/index.tsx +++ b/extensions/quicklinks/src/index.tsx @@ -21,11 +21,13 @@ import { getDefaultQuicklinks, filterQuicklinks, getQuicklinks, + hasClipboardPlaceholder, hasQueryPlaceholder, importQuicklinksJson, inferQuicklinkCategory, launchQuicklink, parseGroupUrls, + recordQuicklinkOpen, saveQuicklinks, validateQuicklinkAlias, validateQuicklinkUrlPattern @@ -281,9 +283,81 @@ export function ImportQuicklinksForm({ ) } +export function QueryArgumentForm({ + item, + onLaunch +}: { + item: Quicklink + onLaunch: (queryArg: string) => Promise +}) { + useLocale() + const { pop } = useNavigation() + const [queryArg, setQueryArg] = useState('') + + const handleSubmit = async () => { + await onLaunch(queryArg) + pop() + } + + const handleFillClipboard = async () => { + try { + const clip = (await Clipboard.readText()).trim() + if (!clip) { + await showToast({ style: Toast.Style.Failure, title: t('queryClipboardEmptyToast') }) + return + } + setQueryArg(clip) + await showToast({ style: Toast.Style.Success, title: t('queryClipboardFilledToast') }) + } catch (error) { + await showToast({ + style: Toast.Style.Failure, + title: t('openFailedToast'), + message: error instanceof Error ? error.message : String(error) + }) + } + } + + const handleOpenHomepage = async () => { + await onLaunch('') + pop() + } + + return ( +
+ + + + + } + > + + + + ) +} + function getHostnameLabel(rawUrl: string): string { try { - return new URL(rawUrl.replace(/\{(query|argument|arg)(?:\s+[^}]*)?\}/gi, 'q')).hostname + return new URL(rawUrl.replace(/\{(?:query|argument|arg|clipboard)(?:\s+[^}]*)?\}/gi, 'q')).hostname } catch { return rawUrl.slice(0, 28) } @@ -329,10 +403,18 @@ export function QuicklinksCommand(props: QuicklinksCommandProps = {}) { [links, searchText, selectedCategory] ) - const handleOpenLink = async (item: Quicklink) => { - const queryArg = filtered.directMatch?.quicklink.id === item.id ? filtered.directMatch.queryArg : '' + const executeOpenLink = async (item: Quicklink, queryArg: string) => { try { - const urls = await launchQuicklink(item, queryArg) + const targetUrls = item.isGroup && Array.isArray(item.urls) ? item.urls : [item.urlPattern || item.link] + const needsClipboard = targetUrls.some((url) => hasClipboardPlaceholder(url)) + const clipboardText = needsClipboard ? await Clipboard.readText() : undefined + const urls = await launchQuicklink(item, queryArg, undefined, clipboardText) + try { + const nextLinks = await recordQuicklinkOpen(item.id) + setLinks(nextLinks) + } catch (countError) { + console.warn('[quicklinks] recordQuicklinkOpen failed:', countError instanceof Error ? countError.message : String(countError)) + } await showToast({ style: Toast.Style.Success, title: item.isGroup ? t('openedGroupToast', { count: urls.length }) : t('openedUrlToast', { url: urls[0] }) @@ -342,6 +424,16 @@ export function QuicklinksCommand(props: QuicklinksCommandProps = {}) { } } + const handleOpenLink = async (item: Quicklink) => { + const queryArg = filtered.directMatch?.quicklink.id === item.id ? filtered.directMatch.queryArg : '' + const pattern = item.urlPattern || item.link + if (!item.isGroup && hasQueryPlaceholder(pattern) && !queryArg) { + push( executeOpenLink(item, arg)} />) + return + } + await executeOpenLink(item, queryArg) + } + // 顶部状态条的动作抛错时客户端不会提示,这里自己如实提示失败 const handleResetDefaults = async () => { const confirmed = await confirmAlert({ @@ -505,7 +597,9 @@ export function QuicklinksCommand(props: QuicklinksCommandProps = {}) { const alias = item.alias || item.keyword const pattern = item.urlPattern || item.link const hasQuery = !item.isGroup && hasQueryPlaceholder(pattern) + const hasClipboard = !item.isGroup && hasClipboardPlaceholder(pattern) const groupUrls = item.isGroup ? item.urls || [] : [] + const openCount = item.openCount || 0 return ( 0 ? [{ text: t('openCountText', { count: openCount }) }] : []), { text: item.isGroup ? t('groupCountText', { count: groupUrls.length }) @@ -528,6 +624,13 @@ export function QuicklinksCommand(props: QuicklinksCommandProps = {}) { icon={Icon.Globe} onAction={() => handleOpenLink(item)} /> + {hasQuery ? ( + executeOpenLink(item, '')} + /> + ) : null} ): QuicklinkCategory { if (item.isGroup) return 'group' - return hasQueryPlaceholder(item.urlPattern || item.link) ? 'search' : 'direct' + const target = item.urlPattern || item.link + return hasQueryPlaceholder(target) || hasClipboardPlaceholder(target) ? 'search' : 'direct' } export function validateQuicklinkUrlPattern(rawUrl: string): { @@ -174,7 +182,7 @@ export function validateQuicklinkUrlPattern(rawUrl: string): { // 与客户端打开网址的校验一致:必须能解析出主机名,且不能带账号密码,否则保存后也打不开 let parsed: URL try { - parsed = new URL(normalizedUrl.replace(new RegExp(PLACEHOLDER_SOURCE, 'gi'), 'q')) + parsed = new URL(normalizedUrl.replace(new RegExp(ANY_PLACEHOLDER_SOURCE, 'gi'), 'q')) } catch { return { valid: false, normalizedUrl: '', error: t('errMalformedUrl') } } @@ -217,24 +225,47 @@ export function parseGroupUrls(text: string): { valid: boolean; urls: string[]; /** * 构建目标访问 URL: + * - 若模板含 {clipboard},用 clipboardText 进行严格的 encodeURIComponent 替换; * - 若传入 queryText,进行严格的 encodeURIComponent 替换; - * - 若未传入 queryText 且模板带 {query},智能降级返回站点首页 origin + * - 若未传入对应内容且模板带占位符,智能降级返回站点首页 origin */ -export function buildTargetUrl(pattern: string, queryText?: string): string { +export function buildTargetUrl(pattern: string, queryText?: string, clipboardText?: string): string { const check = validateQuicklinkUrlPattern(pattern) if (!check.valid) { throw new Error(check.error) } const normalized = check.normalizedUrl - const hasPlaceholder = hasQueryPlaceholder(normalized) + const hasQuery = hasQueryPlaceholder(normalized) + const hasClipboard = hasClipboardPlaceholder(normalized) const cleanQuery = String(queryText ?? '').trim() + const cleanClipboard = String(clipboardText ?? '').trim() - if (!hasPlaceholder) { + if (!hasQuery && !hasClipboard) { return normalized } + let current = normalized + if (hasClipboard) { + if (!cleanClipboard && !hasQuery) { + try { + const parsed = new URL(current.replace(new RegExp(ANY_PLACEHOLDER_SOURCE, 'gi'), '')) + return parsed.origin + } catch { + return current.split('?')[0] || current + } + } + current = current.replace( + new RegExp(CLIPBOARD_PLACEHOLDER_SOURCE, 'gi'), + encodeURIComponent(cleanClipboard) + ) + } + + if (!hasQuery) { + return current + } + if (cleanQuery) { - return normalized.replace( + return current.replace( /\{(query|argument|arg)(?:\s+[^}]*)?\}/gi, encodeURIComponent(cleanQuery) ) @@ -242,10 +273,10 @@ export function buildTargetUrl(pattern: string, queryText?: string): string { // 智能降级至站点主页 try { - const parsed = new URL(normalized.replace(/\{(query|argument|arg)(?:\s+[^}]*)?\}/gi, '')) + const parsed = new URL(current.replace(/\{(query|argument|arg)(?:\s+[^}]*)?\}/gi, '')) return parsed.origin } catch { - return normalized.split('?')[0] || normalized + return current.split('?')[0] || current } } @@ -273,14 +304,15 @@ async function openExternalUrl(targetUrl: string): Promise { export async function launchQuicklink( item: QuicklinkItem | Quicklink, queryText?: string, - opener?: (url: string) => Promise | void + opener?: (url: string) => Promise | void, + clipboardText?: string ): Promise { const openFn = opener ?? openExternalUrl if (item.isGroup && Array.isArray(item.urls) && item.urls.length > 0) { const launched: string[] = [] for (const rawUrl of item.urls) { - const target = buildTargetUrl(rawUrl, queryText) + const target = buildTargetUrl(rawUrl, queryText, clipboardText) try { await openFn(target) } catch (error) { @@ -293,7 +325,7 @@ export async function launchQuicklink( } const pattern = item.urlPattern || ('link' in item ? item.link : '') - const target = buildTargetUrl(pattern, queryText) + const target = buildTargetUrl(pattern, queryText, clipboardText) await openFn(target) return [target] } @@ -317,6 +349,31 @@ export async function saveQuicklinks(quicklinks: Quicklink[]): Promise { getStorage().setItem(STORAGE_KEY, JSON.stringify(quicklinks)) } +/** 按使用频次降序排序(频次相同按最近打开时间降序,均未使用保持原顺序) */ +export function sortQuicklinksByUsage(quicklinks: Quicklink[]): Quicklink[] { + return [...quicklinks].sort((a, b) => { + const countDiff = (b.openCount || 0) - (a.openCount || 0) + if (countDiff !== 0) return countDiff + return (b.lastOpenedAt || 0) - (a.lastOpenedAt || 0) + }) +} + +/** 记录一次真实打开并持久化递增 openCount 与 lastOpenedAt */ +export async function recordQuicklinkOpen(id: string, nowMs = Date.now()): Promise { + const current = await getQuicklinks() + const next = current.map((item) => + item.id === id + ? { + ...item, + openCount: (item.openCount || 0) + 1, + lastOpenedAt: nowMs + } + : item + ) + await saveQuicklinks(next) + return next +} + export function resolveQuicklinkUrl( linkTemplate: string, queryParam?: string, @@ -360,7 +417,7 @@ export function filterQuicklinks( }) if (!searchQuery || !searchQuery.trim()) { - return { matches: byCategory } + return { matches: sortQuicklinksByUsage(byCategory) } } const query = searchQuery.trim() @@ -383,14 +440,14 @@ export function filterQuicklinks( } const qLower = query.toLowerCase() - const matches = byCategory.filter( + const matches = sortQuicklinksByUsage(byCategory.filter( (ql) => ql.title.toLowerCase().includes(qLower) || ql.link.toLowerCase().includes(qLower) || (ql.keyword && ql.keyword.toLowerCase().includes(qLower)) || (ql.alias && ql.alias.toLowerCase().includes(qLower)) || (ql.description && ql.description.toLowerCase().includes(qLower)) - ) + )) return { matches } } diff --git a/extensions/quicklinks/src/types.ts b/extensions/quicklinks/src/types.ts index 53c466f5..b4e5243f 100644 --- a/extensions/quicklinks/src/types.ts +++ b/extensions/quicklinks/src/types.ts @@ -26,6 +26,7 @@ export interface Quicklink { icon?: string defaultArgument?: string openCount?: number + lastOpenedAt?: number createdAt: number updatedAt: number } diff --git a/extensions/quicklinks/tests/commands.test.mjs b/extensions/quicklinks/tests/commands.test.mjs index 4b429826..1b5fef58 100644 --- a/extensions/quicklinks/tests/commands.test.mjs +++ b/extensions/quicklinks/tests/commands.test.mjs @@ -316,3 +316,66 @@ test('回归:主视图支持导出 JSON 到剪贴板与挂载 ImportQuicklinks assert.ok(view.item('imp-grp')) } finally { view.unmount() } }) + +test('使用频次排序(openCount):打开后递增计数并自动置顶,零假数据', async () => { + const { host } = setup() + const opened = [] + const prevZtools = globalThis.ztools + globalThis.ztools = { shell: { openExternal: async (url) => { opened.push(url); return true } } } + try { + await saveQuicklinks([ + { id: 'a', title: '低频链接', link: 'https://a.example/', openCount: 0, createdAt: 1, updatedAt: 1 }, + { id: 'b', title: '高频链接', link: 'https://b.example/', openCount: 0, createdAt: 2, updatedAt: 2 } + ]) + const view = await mount(QuicklinksCommand) + try { + assert.deepEqual(view.items().map((i) => i.props.id), ['a', 'b']) + await view.run(view.item('b'), '在浏览器中打开') + assert.deepEqual(opened, ['https://b.example/']) + assert.deepEqual(view.items().map((i) => i.props.id), ['b', 'a']) + const persisted = await getQuicklinks() + assert.equal(persisted.find((i) => i.id === 'b')?.openCount, 1) + assert.equal(persisted.find((i) => i.id === 'a')?.openCount, 0) + assert.ok(view.item('b').props.accessories.some((acc) => acc.text === '已用 1 次')) + } finally { view.unmount() } + } finally { + globalThis.ztools = prevZtools + void host + } +}) + +test('{query} 缺参弹出填参弹层(支持一键填入剪贴板)与 {clipboard} 占位符自动替换', async () => { + const { host } = setup() + const opened = [] + const prevZtools = globalThis.ztools + globalThis.ztools = { shell: { openExternal: async (url) => { opened.push(url); return true } } } + try { + await saveQuicklinks([ + { id: 'q1', title: 'GitHub 搜索', link: 'https://github.com/search?q={query}', urlPattern: 'https://github.com/search?q={query}', alias: 'gh', category: 'search', openCount: 0, createdAt: 1, updatedAt: 1 }, + { id: 'c1', title: '剪贴板查词', link: 'https://dict.example/search?w={clipboard}', urlPattern: 'https://dict.example/search?w={clipboard}', alias: 'tr', category: 'search', openCount: 0, createdAt: 2, updatedAt: 2 } + ]) + const view = await mount(QuicklinksCommand) + try { + // 1. 选中带 {query} 项且未输参数时弹出填参表单,可填入剪贴板内容并打开 + host.clipboard.text = 'ztools declarative' + await view.run(view.item('q1'), '带参搜索 / 访问') + assert.equal(host.pushed.length, 1) + const form = await mountPushed(host) + try { + assert.equal(form.tree().type, 'Form') + await form.run(null, '填入剪贴板内容') + assert.equal(form.field('query').props.value, 'ztools declarative') + await form.run(null, '打开搜索') + assert.equal(host.pushed.length, 0) + } finally { form.unmount() } + assert.equal(opened[0], 'https://github.com/search?q=ztools%20declarative') + + // 2. 选中带 {clipboard} 项自动读取剪贴板并编码替换 + host.clipboard.text = 'hello world' + await view.run(view.item('c1'), '在浏览器中打开') + assert.equal(opened[1], 'https://dict.example/search?w=hello%20world') + } finally { view.unmount() } + } finally { + globalThis.ztools = prevZtools + } +}) diff --git a/extensions/regex-cron/plugin.json b/extensions/regex-cron/plugin.json index 6d6f768a..fc02554f 100644 --- a/extensions/regex-cron/plugin.json +++ b/extensions/regex-cron/plugin.json @@ -1,7 +1,7 @@ { "id": "regex-cron", "name": "正则与Cron", - "version": "1.0.6", + "version": "1.0.7", "minAppVersion": "1.1.8.0", "description": "中国本土常用正则速查与实时测试高亮,支持Cron表达式中文语义解析与未来5次执行时间推算", "author": "ZTools Team", diff --git a/extensions/regex-cron/src/cn-plate.zh-data.ts b/extensions/regex-cron/src/cn-plate.zh-data.ts index b39bcb52..daf96757 100644 --- a/extensions/regex-cron/src/cn-plate.zh-data.ts +++ b/extensions/regex-cron/src/cn-plate.zh-data.ts @@ -4,3 +4,7 @@ export const CN_LICENSE_PLATE_PATTERN = export const CN_LICENSE_PLATE_VALID_EXAMPLES: string[] = ['京AD12345', '粤B8899A', '沪AF01234', '浙A12345D'] export const CN_LICENSE_PLATE_INVALID_EXAMPLES: string[] = ['京IO12345', '美A12345', '粤B123'] + +/** 纯中文字符正则的合法/非法示例数据 */ +export const CN_CHINESE_CHARS_VALID_EXAMPLES: string[] = ['工具箱', '中华人民共和国'] +export const CN_CHINESE_CHARS_INVALID_EXAMPLES: string[] = ['中文123', 'Hello', '中文 空格'] diff --git a/extensions/regex-cron/src/i18n.ts b/extensions/regex-cron/src/i18n.ts index 13e57685..0417a7c1 100644 --- a/extensions/regex-cron/src/i18n.ts +++ b/extensions/regex-cron/src/i18n.ts @@ -8,6 +8,10 @@ const rawT = createTranslator( startMatchSubmit: "开始匹配", sampleFieldTitle: "待测文本", sampleFieldPlaceholder: "粘贴需要匹配的文本,支持多行", + replaceFieldTitle: "替换模板(可选)", + replaceFieldPlaceholder: "例如:[$1] 或 #$&,支持 $1~$9、$&、$$;留空不替换", + testerReplaceHeading: "替换结果预览", + copyReplacedAction: "复制替换结果", placeholderCron: "输入五位 Cron 表达式(如 30 9 * * 1-5),也支持六位 Spring 写法", placeholderTester: "输入待测试正则表达式(如 /1[3-9]\\d{9}/g)...", placeholderDict: "搜索常用中国本土正则(如:身份证、手机号、信用代码、新能源车牌)...", @@ -79,6 +83,10 @@ const rawT = createTranslator( tplHourly: "每小时整点执行一次", tplWorkday930: "每个工作日上午 09:30 推送日报", tplMonth1st: "每月 1 号零点生成月度账单", + tplEvery5Min: "每 5 分钟执行健康检查", + tplEvery30Min: "每 30 分钟同步一次数据", + tplWeeklyMon9am: "每周一上午 09:00 汇总周报", + tplSunday3am: "每周日凌晨 03:00 清理日志", cronErrorLine: "> **{label}**:{reason}", regexErrEmpty: "请输入待测试的正则表达式", regexErrPatternTooLong: "正则表达式不能超过 2000 个字符", @@ -128,6 +136,24 @@ const rawT = createTranslator( presetEmailTitle: "电子邮箱地址(常见 ASCII 格式)", presetEmailTags: "邮箱,Email,账号", presetEmailDesc: "匹配常见 ASCII 邮箱,支持加号别名与多级域名,不支持引号本地部分或国际化邮箱,不验证地址是否可投递。", + presetUrlTitle: "HTTP / HTTPS 网址", + presetUrlTags: "URL,网址,链接,HTTP", + presetUrlDesc: "匹配以 http:// 或 https:// 开头的标准网址,支持端口、路径、查询参数与锚点。", + presetIsoDateTitle: "ISO 日期(YYYY-MM-DD 含月份天数校验)", + presetIsoDateTags: "日期,YYYY-MM-DD,时间", + presetIsoDateDesc: "严格匹配 YYYY-MM-DD 日期格式并约束大月 31 天、小月 30 天、2 月 29 天边界(不校验平闰年)。", + presetChineseTitle: "纯中文字符(CJK 统一汉字)", + presetChineseTags: "中文,汉字,姓名", + presetChineseDesc: "匹配连续的 CJK 统一汉字区间(\\u4e00-\\u9fff),常用于姓名或中文词条校验。", + presetUuidTitle: "UUID v4 标准标识符", + presetUuidTags: "UUID,GUID,唯一ID", + presetUuidDesc: "严格匹配 RFC 4122 第 4 版 UUID(第 3 段首位为 4,第 4 段首位为 8/9/a/b,不区分大小写)。", + presetSemverTitle: "语义化版本号(SemVer 2.0)", + presetSemverTags: "SemVer,版本号,发布", + presetSemverDesc: "匹配标准主.次.修订版本号,支持可选先行版本(-alpha.1)与构建元数据(+build.123)。", + presetHexColorTitle: "十六进制颜色值(HEX)", + presetHexColorTags: "颜色,HEX,CSS", + presetHexColorDesc: "匹配 #RGB、#RRGGBB 或带透明度的 #RRGGBBAA 十六进制颜色值。", slotSec: "秒", slotMin: "分钟", slotHour: "小时", @@ -192,6 +218,10 @@ const rawT = createTranslator( startMatchSubmit: "Run Match", sampleFieldTitle: "Test Text", sampleFieldPlaceholder: "Paste text to test against the regex (multi-line supported)", + replaceFieldTitle: "Replace Template (Optional)", + replaceFieldPlaceholder: "e.g. [$1] or #$&; supports $1-$9, $&, $$; leave blank to skip", + testerReplaceHeading: "Replace Output Preview", + copyReplacedAction: "Copy Replaced Text", placeholderCron: "Enter 5-field Cron expression (e.g. 30 9 * * 1-5) or 6-field Spring format", placeholderTester: "Enter regex to test (e.g. /1[3-9]\\d{9}/g)...", placeholderDict: "Search common regex presets (ID card, phone, credit code, plate)...", @@ -263,6 +293,10 @@ const rawT = createTranslator( tplHourly: "Every hour on the hour", tplWorkday930: "Weekdays at 09:30 daily report", tplMonth1st: "Monthly billing on the 1st at 00:00", + tplEvery5Min: "Health check every 5 minutes", + tplEvery30Min: "Sync data every 30 minutes", + tplWeeklyMon9am: "Weekly summary every Monday at 09:00", + tplSunday3am: "Cleanup logs every Sunday at 03:00", cronErrorLine: "> **{label}**: {reason}", regexErrEmpty: "Please enter a regular expression to test", regexErrPatternTooLong: "Regular expression cannot exceed 2000 characters", @@ -312,6 +346,24 @@ const rawT = createTranslator( presetEmailTitle: "Email Address (Common ASCII Format)", presetEmailTags: "Email,Account,Validation", presetEmailDesc: "Matches common ASCII emails with plus aliases and multi-level domains; does not support quoted local parts, IDN, or deliverability checks.", + presetUrlTitle: "HTTP / HTTPS URL", + presetUrlTags: "URL,Link,HTTP", + presetUrlDesc: "Matches standard http:// or https:// URLs with optional port, path, query string, and hash fragment.", + presetIsoDateTitle: "ISO Date (YYYY-MM-DD with Day Bounds)", + presetIsoDateTags: "Date,YYYY-MM-DD,ISO", + presetIsoDateDesc: "Matches YYYY-MM-DD dates with 31/30/29 month-day bounds (does not check leap year rules).", + presetChineseTitle: "Chinese Characters Only (CJK Unified)", + presetChineseTags: "Chinese,CJK,Hanzi", + presetChineseDesc: "Matches contiguous CJK Unified Ideographs (\\u4e00-\\u9fff) for names or Chinese text checks.", + presetUuidTitle: "UUID v4 Identifier", + presetUuidTags: "UUID,GUID,ID", + presetUuidDesc: "Strictly matches RFC 4122 version 4 UUIDs (case-insensitive).", + presetSemverTitle: "Semantic Version (SemVer 2.0)", + presetSemverTags: "SemVer,Version,Release", + presetSemverDesc: "Matches major.minor.patch versions with optional pre-release and build metadata.", + presetHexColorTitle: "Hex Color Code (#RGB / #RRGGBB / #RRGGBBAA)", + presetHexColorTags: "Color,HEX,CSS", + presetHexColorDesc: "Matches 3-, 6-, or 8-digit hexadecimal color codes prefixed with #.", slotSec: "Second", slotMin: "Minute", slotHour: "Hour", diff --git a/extensions/regex-cron/src/index.tsx b/extensions/regex-cron/src/index.tsx index b55ebc5d..3658942e 100644 --- a/extensions/regex-cron/src/index.tsx +++ b/extensions/regex-cron/src/index.tsx @@ -12,10 +12,11 @@ import React, { useState } from '@ztools/declarative-ui' import { + applyRegexReplacement, getRegexPresets, parseAndExplainCron } from './regex-cron-service.js' -import type { RegexCronMode, RegexPresetItem, RegexMatchResult } from './types.js' +import type { CronParseResult, RegexCronMode, RegexPresetItem, RegexMatchResult } from './types.js' import { t } from './i18n.js' import { runRegexInWorker } from './regex-worker.js' @@ -35,13 +36,42 @@ const CRON_TEMPLATE_DEFS = [ { id: 'cron-daily-2am', expr: '0 2 * * *', titleKey: 'tplDaily2am' }, { id: 'cron-hourly', expr: '0 * * * *', titleKey: 'tplHourly' }, { id: 'cron-workday-930', expr: '30 9 * * 1-5', titleKey: 'tplWorkday930' }, - { id: 'cron-month-1st', expr: '0 0 1 * *', titleKey: 'tplMonth1st' } + { id: 'cron-month-1st', expr: '0 0 1 * *', titleKey: 'tplMonth1st' }, + { id: 'cron-every-5min', expr: '*/5 * * * *', titleKey: 'tplEvery5Min' }, + { id: 'cron-every-30min', expr: '*/30 * * * *', titleKey: 'tplEvery30Min' }, + { id: 'cron-weekly-mon', expr: '0 9 * * 1', titleKey: 'tplWeeklyMon9am' }, + { id: 'cron-sunday-3am', expr: '0 3 * * 0', titleKey: 'tplSunday3am' } ] as const export function getCronTemplates() { return CRON_TEMPLATE_DEFS.map(tpl => ({ id: tpl.id, expr: tpl.expr, title: t(tpl.titleKey) })) } +function renderCronDetailMarkdown(result: CronParseResult): string { + if (!result.isValid) { + return `### ${t('cronFailedHeading')} +${t('cronErrorLine', { label: t('cronErrorReasonLabel'), reason: result.errorMessage ?? '' })} +` + } + return `### ${t('cronExplainHeading')} +> ${emphasizeLiteral(result.chineseSummary)} + +${t('cronDialectNote', { dialect: result.dialect })} + +#### ${t('cronNextRunsHeading', { tz: result.timeZone })} +| ${t('cronColRun')} | ${t('cronColTime')} | ${t('cronColRelative')} | +| :--- | :--- | :--- | +${result.nextRuns + .map((r, i) => `| ${t('cronRunIndex', { n: i + 1 })} | \`${r.formattedTime} ${r.utcOffset}\` | ${r.relativeTime} |`) + .join('\n')} + +#### ${t('cronSlotsHeading')} +| ${t('cronColSlot')} | ${t('cronColValue')} | ${t('cronColMeaning')} | +| :--- | :--- | :--- | +${result.slots.map((s) => `| ${s.name} | \`${s.value}\` | ${s.meaning} |`).join('\n')} +` +} + /** 用户输入只能作为代码原文显示:围栏比内容中最长的反引号串更长,内容里的 ``` 不会提前结束代码块 */ export function fencedCode(content: string, language = 'text'): string { const body = content.replace(/\r\n?/g, '\n') @@ -70,14 +100,24 @@ export function inlineCode(text: string): string { return `${ticks}${pad}${body}${pad}${ticks}` } -export function EditRegexText({ sample, onSave }: { sample: string; onSave: (value: string) => void }) { +export function EditRegexText({ + sample, + replaceTemplate = '', + onSave +}: { + sample: string + replaceTemplate?: string + onSave: (value: string, nextReplaceTemplate?: string) => void +}) { useLocale() const [value, setValue] = useState(sample) + const [replaceVal, setReplaceVal] = useState(replaceTemplate) const { pop } = useNavigation() return
- { onSave(value); pop() }} /> + { onSave(value, replaceVal); pop() }} /> }> + } @@ -99,10 +139,15 @@ export function RegexCronCommand(props: RegexCronCommandProps = {}) { const searchText = queries[currentMode] const setSearchText = (value: string) => setQueries(prev => ({ ...prev, [currentMode]: value })) const [testSample, setTestSample] = useState(props.initialTestSample ?? '') + const [replaceTemplate, setReplaceTemplate] = useState('') const { push } = useNavigation() const [completed, setCompleted] = useState<{ pattern: string; text: string; result: RegexMatchResult } | null>(null) const activeTesterPattern = queries.tester const regexMatchResult = completed?.pattern === activeTesterPattern && completed?.text === testSample ? completed.result : null + const replacedText = useMemo(() => { + if (!replaceTemplate || !regexMatchResult?.isValidRegex) return null + return applyRegexReplacement(testSample, regexMatchResult, replaceTemplate) + }, [replaceTemplate, regexMatchResult, testSample]) useEffect(() => { if (currentMode !== 'tester') return const controller = new AbortController() @@ -114,7 +159,16 @@ export function RegexCronCommand(props: RegexCronCommandProps = {}) { }, 150) return () => { clearTimeout(timer); controller.abort() } }, [currentMode, activeTesterPattern, testSample]) - const editSample = () => push(() => ) + const editSample = () => push(() => ( + { + setTestSample(nextSample) + if (nextReplace !== undefined) setReplaceTemplate(nextReplace) + }} + /> + )) const filteredRegexList = useMemo(() => { const presets = getRegexPresets() @@ -131,6 +185,12 @@ export function RegexCronCommand(props: RegexCronCommandProps = {}) { const [cronRefresh, setCronRefresh] = useState(0) const cronResult = useMemo(() => parseAndExplainCron(queries.cron), [queries.cron, currentMode, cronRefresh, locale]) + const cronTemplateEntries = useMemo( + () => (currentMode === 'cron' + ? getCronTemplates().map((tpl) => ({ ...tpl, parsed: parseAndExplainCron(tpl.expr) })) + : []), + [currentMode, cronRefresh, locale] + ) const handleLoadIntoTester = (item: RegexPresetItem) => { setQueries(prev => ({ ...prev, tester: `/${item.pattern}/${item.recommendedFlags || ''}` })) setTestSample(item.validExamples[0] ?? '') @@ -280,6 +340,10 @@ ${ }` ) .join('\n') +}${ + replacedText !== null + ? `\n\n#### ${t('testerReplaceHeading')}\n${fencedCode(replacedText)}` + : '' } ` : `### ${t('testerErrorHeading')} @@ -296,6 +360,10 @@ ${!activeTesterPattern.trim() ? t('testerEmptyGuide') : regexMatchResult?.errorM title={t('copyAllMatchesAction')} content={regexMatchResult.matches.map((m) => m.text).join('\n')} />} + {replacedText !== null && } } /> @@ -316,29 +384,7 @@ ${!activeTesterPattern.trim() ? t('testerEmptyGuide') : regexMatchResult?.errorM ]} detail={ ${emphasizeLiteral(cronResult.chineseSummary)} - -${t('cronDialectNote', { dialect: cronResult.dialect })} - -#### ${t('cronNextRunsHeading', { tz: cronResult.timeZone })} -| ${t('cronColRun')} | ${t('cronColTime')} | ${t('cronColRelative')} | -| :--- | :--- | :--- | -${cronResult.nextRuns - .map((r, i) => `| ${t('cronRunIndex', { n: i + 1 })} | \`${r.formattedTime} ${r.utcOffset}\` | ${r.relativeTime} |`) - .join('\n')} - -#### ${t('cronSlotsHeading')} -| ${t('cronColSlot')} | ${t('cronColValue')} | ${t('cronColMeaning')} | -| :--- | :--- | :--- | -${cronResult.slots.map((s) => `| ${s.name} | \`${s.value}\` | ${s.meaning} |`).join('\n')} -` - : `### ${t('cronFailedHeading')} -${t('cronErrorLine', { label: t('cronErrorReasonLabel'), reason: cronResult.errorMessage ?? '' })} -` - } + markdown={renderCronDetailMarkdown(cronResult)} /> } actions={ @@ -351,7 +397,7 @@ ${t('cronErrorLine', { label: t('cronErrorReasonLabel'), reason: cronResult.erro } /> - {getCronTemplates().map((tpl) => ( + {cronTemplateEntries.map((tpl) => ( + } actions={ setSearchText(tpl.expr)} /> + {tpl.parsed.isValid && `${r.formattedTime} ${r.utcOffset}`).join('\n')} + />} } /> diff --git a/extensions/regex-cron/src/regex-cron-service.ts b/extensions/regex-cron/src/regex-cron-service.ts index 0e385a46..d77d5c90 100644 --- a/extensions/regex-cron/src/regex-cron-service.ts +++ b/extensions/regex-cron/src/regex-cron-service.ts @@ -1,7 +1,9 @@ -import type { CronParseResult, RegexPresetItem } from './types.js' +import type { CronParseResult, RegexMatchResult, RegexPresetItem } from './types.js' import { t } from './i18n.js' import { resolveErrorMessage } from './error-i18n.js' import { + CN_CHINESE_CHARS_INVALID_EXAMPLES, + CN_CHINESE_CHARS_VALID_EXAMPLES, CN_LICENSE_PLATE_PATTERN, CN_LICENSE_PLATE_VALID_EXAMPLES, CN_LICENSE_PLATE_INVALID_EXAMPLES @@ -117,6 +119,80 @@ const REGEX_PRESET_DEFS = [ scopeKey: 'scopeAllPlatforms', validExamples: ['dev+ztools@example.com', 'admin@mail.ztools.cn'], invalidExamples: ['plainaddress', '@missing-user.com', 'user@.invalid.com'] + }, + { + id: 'http-url', + titleKey: 'presetUrlTitle', + category: 'network', + categoryLabelKey: 'catNetwork', + tagsKey: 'presetUrlTags', + pattern: '^https?:\\/\\/(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,}(?::\\d{1,5})?(?:\\/[^\\s]*)?$', + recommendedFlags: 'i', + descKey: 'presetUrlDesc', + scopeKey: 'scopeAllPlatforms', + validExamples: ['https://example.com/docs?q=1#top', 'http://api.service.local:8080/v1/health'], + invalidExamples: ['ftp://example.com', 'https://localhost', 'example.com/path'] + }, + { + id: 'iso-date', + titleKey: 'presetIsoDateTitle', + category: 'format', + categoryLabelKey: 'catFormat', + tagsKey: 'presetIsoDateTags', + pattern: '^\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|02-(?:0[1-9]|1\\d|2[0-9]))$', + descKey: 'presetIsoDateDesc', + scopeKey: 'scopeAllPlatforms', + validExamples: ['2026-12-02', '2028-02-29', '2026-04-30'], + invalidExamples: ['2026-02-30', '2026-04-31', '2026-13-01'] + }, + { + id: 'zh-chinese-chars', + titleKey: 'presetChineseTitle', + category: 'format', + categoryLabelKey: 'catFormat', + tagsKey: 'presetChineseTags', + pattern: '^[\\u4e00-\\u9fff]+$', + descKey: 'presetChineseDesc', + scopeKey: 'scopeAllPlatforms', + validExamples: CN_CHINESE_CHARS_VALID_EXAMPLES, + invalidExamples: CN_CHINESE_CHARS_INVALID_EXAMPLES + }, + { + id: 'uuid-v4', + titleKey: 'presetUuidTitle', + category: 'format', + categoryLabelKey: 'catFormat', + tagsKey: 'presetUuidTags', + pattern: '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$', + recommendedFlags: 'i', + descKey: 'presetUuidDesc', + scopeKey: 'scopeAllPlatforms', + validExamples: ['550e8400-e29b-41d4-a716-446655440000', 'F47AC10B-58CC-4372-A567-0E02B2C3D479'], + invalidExamples: ['550e8400-e29b-11d4-a716-446655440000', '550e8400-e29b-41d4-c716-446655440000', 'not-a-uuid'] + }, + { + id: 'semver-version', + titleKey: 'presetSemverTitle', + category: 'format', + categoryLabelKey: 'catFormat', + tagsKey: 'presetSemverTags', + pattern: '^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$', + descKey: 'presetSemverDesc', + scopeKey: 'scopeAllPlatforms', + validExamples: ['1.2.3', '2.0.0-alpha.1+build.42'], + invalidExamples: ['01.2.3', 'v1.2.3', '1.2'] + }, + { + id: 'hex-color', + titleKey: 'presetHexColorTitle', + category: 'format', + categoryLabelKey: 'catFormat', + tagsKey: 'presetHexColorTags', + pattern: '^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$', + descKey: 'presetHexColorDesc', + scopeKey: 'scopeAllPlatforms', + validExamples: ['#fff', '#0A84FF', '#112233CC'], + invalidExamples: ['#1234', '#GGGGGG', '0A84FF'] } ] as const @@ -136,6 +212,27 @@ export function getRegexPresets(): RegexPresetItem[] { })) } +/** 基于 Worker 已返回的匹配区间离线执行替换(零 ReDoS 风险),支持 $$、$&、$1~$9 */ +export function applyRegexReplacement(sample: string, result: RegexMatchResult, template: string): string { + if (!result.isValidRegex || result.matches.length === 0) return sample + let output = '' + let cursor = 0 + for (const match of result.matches) { + if (match.start < cursor) continue + output += sample.slice(cursor, match.start) + output += template.replace(/\$(?:\$|&|[1-9])/g, (token) => { + if (token === '$$') return '$' + if (token === '$&') return match.text + const idx = Number(token.slice(1)) + const group = match.groups.find((g) => g.groupIndex === idx) + return group && group.start >= 0 ? group.value : '' + }) + cursor = match.end + } + output += sample.slice(cursor) + return output +} + const WEEKDAY_MAP: Record = { SUN: 0, MON: 1, diff --git a/extensions/regex-cron/tests/regex-cron.view.test.mjs b/extensions/regex-cron/tests/regex-cron.view.test.mjs index 0383152e..1242cdd5 100644 --- a/extensions/regex-cron/tests/regex-cron.view.test.mjs +++ b/extensions/regex-cron/tests/regex-cron.view.test.mjs @@ -153,7 +153,27 @@ test('Cron 常用模板均为五位 Linux 写法、可解析且不与默认输 assert.doesNotMatch(tree.props.searchBarPlaceholder, /\?/) const tpl = view.item('cron-workday-930') assert.ok(tpl) + assert.match(tpl.props.detail.props.markdown, /未来 5 次执行时间推算/) await view.run(tpl, '推算此 Cron 模板') assert.equal(view.tree().props.searchText, '30 9 * * 1-5') assert.match(view.item('cron-live-result').props.subtitle, /30 9 \* \* 1-5/) }) + +test('正则测试器支持替换模板预览与复制替换结果(含 $1 捕获组与 $$ 转义)', async () => { + const view = await mount(() => RegexCronCommand({ initialMode: 'tester', initialSearchText: '/order_id=(\\d+)/g', initialTestSample: 'ok order_id=10086\nretry order_id=10087' })) + let form + try { + await settled(view) + await view.run(view.item('tester-summary'), '编辑待测文本…') + form = await mountPushed(host) + await form.fill('replaceTemplate', 'id:#$1 ($$)') + await form.run(null, '开始匹配') + form.unmount(); form = null + await settled(view) + const md = view.item('tester-summary').props.detail.props.markdown + assert.match(md, /替换结果预览/) + assert.match(md, /ok id:#10086 \(\$\)/) + await view.run(view.item('tester-summary'), '复制替换结果') + assert.equal(host.clipboard.text, 'ok id:#10086 ($)\nretry id:#10087 ($)') + } finally { form?.unmount(); view.unmount() } +}) diff --git a/extensions/shared/real-host-harness.mjs b/extensions/shared/real-host-harness.mjs new file mode 100644 index 00000000..2c6d467a --- /dev/null +++ b/extensions/shared/real-host-harness.mjs @@ -0,0 +1,371 @@ +/** + * ZTools 真实宿主链路测试底座 (Real Host Chain Test Harness) + * + * 彻底替代假宿主 Mock(createHost / createRealHostStub): + * - 直接装配 electron-client/out/main/services/ 编译出的真实主进程服务: + * 1. FileSystemService(真实 #grants 读写授权表:grantOpenPath 只读、grantFolder 读写、grantResultPaths 结果授权) + * 2. SidecarManager(真实 searchFiles -> extractDirectoryScanTarget -> scanDirectoryForSearch 磁盘扫描) + * 3. BuiltinPluginHostService(真实 storage-host / media-ocr-host,严格注入 pathAuthority 鉴权) + * 4. listSystemVolumes(真实系统挂载卷探测) + * - 零假数据、零假 IPC 返回、零绕过权限;所有文件操作均在 os.tmpdir() 隔离临时目录真实落盘。 + */ +import fs from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import { fileURLToPath } from 'node:url' +import { setDeclarativeBridge, setRuntimeLocale } from '@ztools/declarative-ui' +import { mount, tick } from './test-harness.mjs' + +const __dirname = path.dirname(fileURLToPath(import.meta.url)) +const REPO_ROOT = path.resolve(__dirname, '../..') +const MAIN_OUT = path.join(REPO_ROOT, 'electron-client/out/main') + +// 独立公开插件仓(ZTools-extensions)不含 electron-client 编译产物,仅主仓 monorepo 环境装配真实 Electron 主进程服务 +export const HAS_REAL_ELECTRON_HOST = fs.existsSync(path.join(MAIN_OUT, 'services/file-system-service.js')) +export const REAL_HOST_SKIP_REASON = HAS_REAL_ELECTRON_HOST + ? false + : 'Skipped outside monorepo: electron-client/out/main build output is not available' + +let FileSystemService +let BuiltinPluginHostService +let SidecarManager +let extractDirectoryScanTarget +let expandHomeDir +let listSystemVolumes +let FolderSyncService +let NativePathAccessAdapter +let resolvePathAccessBroker + +if (HAS_REAL_ELECTRON_HOST) { + ;({ FileSystemService } = await import(new URL(`file:///${path.join(MAIN_OUT, 'services/file-system-service.js').replace(/\\/g, '/')}`))) + ;({ BuiltinPluginHostService } = await import(new URL(`file:///${path.join(MAIN_OUT, 'services/builtin-plugin-host-service.js').replace(/\\/g, '/')}`))) + ;({ SidecarManager } = await import(new URL(`file:///${path.join(MAIN_OUT, 'services/sidecar-manager.js').replace(/\\/g, '/')}`))) + ;({ extractDirectoryScanTarget } = await import(new URL(`file:///${path.join(MAIN_OUT, 'services/file-search-query.js').replace(/\\/g, '/')}`))) + ;({ expandHomeDir } = await import(new URL(`file:///${path.join(MAIN_OUT, 'platform/macos/file-indexer.js').replace(/\\/g, '/')}`))) + ;({ listSystemVolumes } = await import(new URL(`file:///${path.join(MAIN_OUT, 'services/volume-service.js').replace(/\\/g, '/')}`))) + ;({ FolderSyncService } = await import(new URL(`file:///${path.join(MAIN_OUT, 'services/folder-sync-service.js').replace(/\\/g, '/')}`))) + ;({ NativePathAccessAdapter } = await import(new URL(`file:///${path.join(MAIN_OUT, 'platform/native-path-access.js').replace(/\\/g, '/')}`))) + ;({ resolvePathAccessBroker } = await import(new URL(`file:///${path.join(MAIN_OUT, 'platform/path-access-broker.js').replace(/\\/g, '/')}`))) +} + +export { mount, tick } + +function createCallerRegistry() { + const listeners = new Set() + return { + onRemoved(fn) { + listeners.add(fn) + return () => listeners.delete(fn) + }, + emitRemoved(id) { + for (const fn of listeners) fn(id) + } + } +} + +/** + * 创建真实宿主链路测试环境(隔离临时根目录 + 真实权限表 + 真实服务实例) + */ +export function createRealHost(options = {}) { + if (!HAS_REAL_ELECTRON_HOST) { + throw new Error('electron-client/out/main build output is missing; run in monorepo or mark test with { skip: REAL_HOST_SKIP_REASON }') + } + const locale = options.locale || 'zh-CN' + setRuntimeLocale(locale) + + const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'ztools-real-host-')) + const cacheRoot = path.join(tempRoot, '.cache') + const dataRoot = path.join(tempRoot, '.data') + const sandboxDirs = { + home: path.join(tempRoot, 'home'), + downloads: path.join(tempRoot, 'home', 'Downloads'), + documents: path.join(tempRoot, 'home', 'Documents'), + desktop: path.join(tempRoot, 'home', 'Desktop'), + videos: path.join(tempRoot, 'home', 'Videos'), + temp: path.join(tempRoot, 'home', 'Temp') + } + for (const d of [cacheRoot, dataRoot, ...Object.values(sandboxDirs)]) { + fs.mkdirSync(d, { recursive: true }) + } + + const registry = createCallerRegistry() + const pluginId = options.pluginId || 'test-plugin' + let declaredPermissions = options.permissions + if (!declaredPermissions) { + const manifestPath = path.join(REPO_ROOT, 'plugins', pluginId, 'plugin.json') + if (fs.existsSync(manifestPath)) { + const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8')) + declaredPermissions = Array.isArray(manifest.permissions) ? manifest.permissions : [] + } else { + declaredPermissions = ['fs', 'system', 'dialog'] + } + } + const caller = { + webContentsId: 1001, + type: 'main', + attributedPlugin: { + pluginId, + permissions: new Set(declaredPermissions) + } + } + const files = new FileSystemService(registry, cacheRoot, Date.now, undefined, { + pathAccessBroker: { + platform: process.platform, + isPackaged: false, + appPath: path.join(REPO_ROOT, 'electron-client'), + resourcesPath: path.join(REPO_ROOT, 'electron-client') + } + }) + const sidecar = new SidecarManager({ isPackaged: false, appRoot: path.join(REPO_ROOT, 'electron-client') }) + const builtinHost = new BuiltinPluginHostService({ + pathAuthority: files, + dataRoot, + platform: process.platform + }) + + // 受控的系统对话框队列:仅模拟“用户在 OS 对话框点选了哪条真实临时路径”,选完 100% 走真实 FileSystemService 签发权限 + const dialogQueues = { + openFiles: [], + selectFolder: [] + } + + let folderSyncInstance = null + const shellCalls = { opened: [], revealed: [], trashed: [] } + const ipcCalls = [] + const toasts = [] + const confirms = [] + const storage = new Map() + const pushed = [] + let confirmAnswer = true + + setDeclarativeBridge({ + showToast(opts) { + toasts.push(opts) + return { id: String(toasts.length), update() {}, hide() {} } + }, + async copyToClipboard() {}, + async readClipboardText() { return '' }, + async readClipboardFiles() { return [] }, + async readClipboardImage() { return null }, + async pasteToActive() {}, + async storageGetItem(key) { return storage.has(key) ? JSON.parse(storage.get(key)) : undefined }, + async storageCompareAndSet(key, expected, value) { + if (storage.get(key) !== JSON.stringify(expected)) return false + storage.set(key, JSON.stringify(value)) + return true + }, + async storageSetItem(key, value) { storage.set(key, JSON.stringify(value)) }, + async storageRemoveItem(key) { storage.delete(key) }, + async confirmAlert(opts) { confirms.push(opts); return confirmAnswer }, + navigation: { + push(target) { pushed.push(target) }, + pop() { pushed.pop() } + } + }) + + async function dispatchRealMethod(method, params = {}) { + ipcCalls.push([method, params]) + switch (method) { + case 'system_list_volumes': { + if (options.volumesOverride) { + const snap = await options.volumesOverride() + await files.grantResultPaths(caller, (snap.volumes || []).map((v) => ({ path: v.path, isDir: true })), 'volume-root') + return snap + } + const snap = await listSystemVolumes() + await files.grantResultPaths(caller, snap.volumes.map((v) => ({ path: v.path, isDir: true })), 'volume-root') + return snap + } + case 'system_get_path': { + const name = String(params?.name || '').toLowerCase() + const target = sandboxDirs[name] || sandboxDirs.home + return { success: true, path: target } + } + case 'system_list_common_folders': { + return { + folders: Object.entries(sandboxDirs).map(([id, p]) => ({ id, path: p, exists: fs.existsSync(p) })) + } + } + case 'system_search_files': { + const query = String(params?.query || '') + const limit = Number(params?.limit) || 50 + const result = await sidecar.searchFiles(query, limit) + const entries = [] + for (const f of result.files || []) { + if (typeof f?.path === 'string') entries.push({ path: f.path, isDir: f.is_dir !== false }) + } + for (const d of result.subdirs || []) { + if (typeof d?.path === 'string') entries.push({ path: d.path, isDir: true }) + } + const scanDir = extractDirectoryScanTarget(query) + if (scanDir) { + await files.grantResultPaths(caller, entries, 'dir-scan', { scanRoot: expandHomeDir(scanDir) }) + } else { + await files.grantResultPaths(caller, entries, 'search') + } + return result + } + case 'window_show_open_dialog': { + const next = dialogQueues.openFiles.shift() + if (!next || next.canceled) return { canceled: true, filePaths: [] } + const filePaths = Array.isArray(next.filePaths) ? next.filePaths : [next] + // 100% 真实宿主行为:showOpenDialog 调用 grantOpenPath(只签发 read: true, write: false!) + for (const p of filePaths) { + await files.grantOpenPath(p, caller) + } + return { canceled: false, filePaths } + } + case 'window_show_select_folder_dialog': { + const next = dialogQueues.selectFolder.shift() + if (!next || next.canceled) return { canceled: true, folderPath: '' } + const folderPath = typeof next === 'string' ? next : next.folderPath + // 100% 真实宿主行为:showSelectFolderDialog 调用 grantFolder(签发递归读写权限!) + await files.grantFolder(folderPath, caller) + return { canceled: false, folderPath } + } + case 'filesystem_file_exists': { + return await files.fileExists(params, caller) + } + case 'filesystem_directory_exists': { + return await files.directoryExists(params, caller) + } + case 'filesystem_get_directory_contents': { + return await files.getDirectoryContents(params, caller) + } + case 'filesystem_get_file_size': { + return await files.getFileSize(params, caller) + } + case 'filesystem_read_file': { + return await files.readFile(params, caller) + } + case 'filesystem_write_file': { + return await files.writeFile(params, caller) + } + case 'filesystem_move_file_no_replace': { + return await files.moveFileNoReplace(params, caller, new AbortController().signal) + } + case 'folder_sync': { + if (!folderSyncInstance) { + folderSyncInstance = new FolderSyncService(files, () => { + const broker = resolvePathAccessBroker({ + platform: process.platform, + isPackaged: false, + appPath: path.join(REPO_ROOT, 'electron-client'), + resourcesPath: path.join(REPO_ROOT, 'electron-client') + }) + if (!broker.available) throw new Error('PathAccessBroker unavailable') + return new NativePathAccessAdapter(broker.executable, 30000) + }) + } + return await folderSyncInstance.execute(params, caller, new AbortController().signal) + } + case 'folder_sync_cancel': { + return folderSyncInstance ? folderSyncInstance.cancel(String(params?.operationId || ''), caller) : { success: true, cancelRequested: false } + } + case 'downloads_manager': { + const action = params?.action + const funcName = action === 'discover' ? 'discoverSources' : 'validateCustomDir' + const payload = action === 'discover' ? { customDirs: params?.customDirs } : { dirPath: params?.dirPath } + const res = await builtinHost.handlePluginCall('DownloadsManagerPlugin', funcName, payload, undefined, caller) + if (action === 'discover' && res && typeof res === 'object' && Array.isArray(res.sources)) { + const dirEntries = res.sources + .filter((s) => typeof s?.path === 'string' && s.path.length > 0 && s.channel !== 'custom') + .map((s) => ({ path: s.path, isDir: true })) + if (dirEntries.length > 0) { + await files.grantResultPaths(caller, dirEntries, 'search') + } + } + return res + } + case 'dllplugin_call': { + const plugin = params.plugin ?? params.pluginName ?? params.name + const func = params.func ?? params.functionName ?? params.method + let rawPayload = params.payload ?? params.params ?? params.args ?? {} + if (typeof rawPayload === 'string') { + try { rawPayload = JSON.parse(rawPayload) } catch { rawPayload = {} } + } + const res = await builtinHost.handlePluginCall(plugin, func, rawPayload, undefined, caller) + if (res && typeof res === 'object' && res.success === false) { + throw Object.assign(new Error(String(res.error || res.message || 'Plugin call failed')), { code: res.code || 'PLUGIN_ERROR' }) + } + return res + } + case 'shell_open_path': { + const resolved = await files.resolveAuthorizedPath(params.fullPath, caller, 'read') + shellCalls.opened.push(resolved) + return { success: true } + } + case 'shell_show_item_in_folder': { + const resolved = await files.resolveAuthorizedPath(params.fullPath, caller, 'read') + shellCalls.revealed.push(resolved) + return { success: true } + } + case 'shell_trash_item': { + const resolved = await files.resolveAuthorizedPath(params.fullPath, caller, 'trash') + // 仅允许真实删除位于 tempRoot 内的测试文件,严禁误删用户真实文件 + if (resolved.toLowerCase().startsWith(tempRoot.toLowerCase()) && fs.existsSync(resolved)) { + fs.rmSync(resolved, { recursive: false, force: true }) + } + shellCalls.trashed.push(resolved) + return { success: true } + } + default: + throw Object.assign(new Error(`REAL_HOST_METHOD_NOT_WIRED: ${method}`), { code: 'METHOD_NOT_FOUND' }) + } + } + + globalThis.window = globalThis.window || globalThis + globalThis.window.__ztoolsDeclarativeFeatures = { fileInput: true } + globalThis.__ztoolsElectron = { + setFileInputInterception() {}, + transport: { + methods: new Proxy({}, { + get(_t, method) { + return async (req) => { + try { + const data = await dispatchRealMethod(String(method), req.params || {}) + return { messageId: req.messageId, success: true, data } + } catch (err) { + return { + messageId: req.messageId, + success: false, + error: { code: err?.code || 'FAILED', message: err instanceof Error ? err.message : String(err) } + } + } + } + } + }) + } + } + + return { + tempRoot, + sandboxDirs, + caller, + services: { files, sidecar, builtinHost }, + shellCalls, + ipcCalls, + toasts, + confirms, + storage, + pushed, + setConfirm(v) { confirmAnswer = v }, + lastToast() { return toasts[toasts.length - 1] }, + queueOpenDialog(filePaths) { dialogQueues.openFiles.push({ canceled: false, filePaths: Array.isArray(filePaths) ? filePaths : [filePaths] }) }, + queueSelectFolderDialog(folderPath) { dialogQueues.selectFolder.push({ canceled: false, folderPath }) }, + queueCancelFolderDialog() { dialogQueues.selectFolder.push({ canceled: true }) }, + /** 在隔离临时目录中创建真实测试文件 */ + writeTempFile(relPath, content) { + const full = path.join(tempRoot, relPath) + fs.mkdirSync(path.dirname(full), { recursive: true }) + fs.writeFileSync(full, content) + return full + }, + async dispose() { + registry.emitRemoved(caller.webContentsId) + if (folderSyncInstance) await folderSyncInstance.stop() + await files.stop() + fs.rmSync(tempRoot, { recursive: true, force: true }) + } + } +} diff --git a/extensions/shredder/package.json b/extensions/shredder/package.json index 5eba708b..95784862 100644 --- a/extensions/shredder/package.json +++ b/extensions/shredder/package.json @@ -1,6 +1,6 @@ { "name": "@ztools/plugin-shredder", - "version": "1.0.0", + "version": "2.0.15", "description": "列出临时文件夹与崩溃转储目录里的文件,勾选并确认后多次覆写文件内容再删除", "main": "dist/index.js", "types": "dist/index.d.ts", diff --git a/extensions/shredder/plugin.json b/extensions/shredder/plugin.json index 9a5ab2a9..8a2c6311 100644 --- a/extensions/shredder/plugin.json +++ b/extensions/shredder/plugin.json @@ -2,7 +2,7 @@ "id": "shredder", "name": "文件粉碎", "description": "选择文件或文件夹导入待粉碎列表,勾选并确认后多次覆写文件内容再删除", - "version": "2.0.14", + "version": "2.0.15", "author": "ZTools Team", "entry": "dist/index.js", "icon": "icon.svg", diff --git a/extensions/shredder/src/i18n.ts b/extensions/shredder/src/i18n.ts index 5178dd8f..7877eb9b 100644 --- a/extensions/shredder/src/i18n.ts +++ b/extensions/shredder/src/i18n.ts @@ -79,7 +79,8 @@ const MESSAGES = { confirmWarning: "粉碎后无法从回收站找回。注意:在 SSD(固态硬盘)上,由于磨损均衡(Wear Leveling)和 TRIM 机制,多次覆写无法保证覆盖原始闪存块,且系统还原点或卷影副本中仍可能留有副本。", shredAllSuccess: "已按「{standard}」粉碎 {count} 个文件({bytes})", shredAllFailed: "粉碎失败,{count} 个文件均未处理。{detail}", - shredPartialResult: "已粉碎 {okCount} 个文件({bytes}),{failCount} 个失败。{detail}" + shredPartialResult: "已粉碎 {okCount} 个文件({bytes}),{failCount} 个失败。{detail}", + authorizeFolderTitle: "授权文件所在文件夹以执行物理粉碎" }, "en-US": { importFailed: "Import failed", @@ -159,7 +160,8 @@ const MESSAGES = { confirmWarning: "Shredded files cannot be recovered from Recycle Bin. Note: On SSDs, wear leveling and TRIM prevent guaranteed overwriting of original flash blocks, and copies may still remain in Restore Points or Volume Shadow Copies.", shredAllSuccess: "Shredded {count} file(s) ({bytes}) using \"{standard}\"", shredAllFailed: "Shredding failed; {count} file(s) unprocessed. {detail}", - shredPartialResult: "Shredded {okCount} file(s) ({bytes}), {failCount} failed. {detail}" + shredPartialResult: "Shredded {okCount} file(s) ({bytes}), {failCount} failed. {detail}", + authorizeFolderTitle: "Authorize Parent Folder for Secure Shredding" } }; diff --git a/extensions/shredder/src/index.ts b/extensions/shredder/src/index.ts index e3282d64..3f608545 100644 --- a/extensions/shredder/src/index.ts +++ b/extensions/shredder/src/index.ts @@ -322,12 +322,12 @@ export function ShredderCommand() { } }; - const handleBatchShred = async () => { + const handleBatchShred = async (explicitTargets?: ShredCandidateItem[]) => { if (shredBusyRef.current) { showToast({ style: Toast.Style.Failure, title: t("shredBusy") }); return; } - const targets = selectedItems; + const targets = explicitTargets && explicitTargets.length > 0 ? explicitTargets : selectedItems; if (targets.length === 0) { showToast({ style: Toast.Style.Failure, title: t("selectFilesFirst") }); return; @@ -339,6 +339,31 @@ export function ShredderCommand() { }); if (!confirmed || !aliveRef.current) return; + // 通过「选择文件 / 拖入」导入的条目仅持只读授权,执行前按父目录补一次目录写授权,避免真实宿主 100% 拒绝写入 + const manualParents = Array.from( + new Set( + targets + .filter((item) => item.source === "manual") + .map((item) => { + const idx = Math.max(item.path.lastIndexOf("\\"), item.path.lastIndexOf("/")); + return idx > 0 ? item.path.slice(0, idx) : ""; + }) + .filter(Boolean) + ) + ); + for (const parentDir of manualParents) { + const grant = await pickFolder(transport, { + title: t("authorizeFolderTitle"), + defaultPath: parentDir + }); + if (grant.canceled || grant.error || !grant.folderPath) { + if (!grant.canceled) { + showToast({ style: Toast.Style.Failure, title: t("shredFailed"), message: resolveErrorMessage(grant, t("noFolderSelected")) }); + } + return; + } + } + shredBusyRef.current = true; setIsShredding(true); setRunningIds(targets.map((t) => t.id)); @@ -403,13 +428,15 @@ export function ShredderCommand() { ? t("emptyPrompt") : t("noMatchingEmpty"); - const shredAction = (title: string) => + const shredAction = (title: string, explicitTargets?: ShredCandidateItem[]) => Action({ title, icon: Icon.Trash, style: Action.Style.Destructive, shortcut: SHORTCUT_SHRED, - onAction: handleBatchShred + onAction: () => { + void handleBatchShred(explicitTargets); + } }); const pickFilesAction = () => @@ -437,64 +464,10 @@ export function ShredderCommand() { onAction: handleClear }); - const leftNavNodes = [ - List.Item({ - id: "nav-shred-all", - title: t("allShredFiles"), - subtitle: t("totalCountSub", { count: items.length }), - icon: Icon.Trash, - onSelect: () => setSelectedSource("all"), - accessories: [ - { tag: { value: t("countTag", { count: items.length }) } }, - { text: formatBytes(totalKnownBytes) } - ], - actions: ActionPanel({ - children: [ - pickFilesAction(), - pickFolderAction(), - shredAction(t("shredCheckedCount", { count: selectedItems.length })), - clearListAction() - ] - }) - }), - ...sources.map((src) => { - const srcItems = items.filter((i) => i.source === src.id); - const srcBytes = sumKnownBytes(srcItems); - const ratio = items.length === 0 ? 0 : Math.min(1, srcBytes / Math.max(1, totalKnownBytes)); - - return List.Item({ - id: `nav-shred-${src.id}`, - title: src.name, - subtitle: src.subtitle, - icon: src.id === "folder" ? Icon.Folder : Icon.Document, - onSelect: () => setSelectedSource(src.id), - accessories: [ - { progress: ratio }, - { tag: { value: t("countTag", { count: srcItems.length }) } }, - { text: formatBytes(srcBytes) } - ], - actions: ActionPanel({ - children: [ - Action({ - title: t("viewSourceAction", { name: src.name }), - icon: Icon.Filter, - onAction: () => setSelectedSource(src.id) - }), - shredAction(t("shredCheckedCount", { count: selectedItems.length })), - pickFilesAction(), - pickFolderAction(), - clearListAction() - ] - }) - }); - }) - ]; - const allChecked = visibleItems.length > 0 && visibleItems.every((i) => checkedSet.has(i.id)); - const someChecked = visibleItems.some((i) => checkedSet.has(i.id)); - const subListItems = visibleItems.map((item) => { + const queueItems = visibleItems.map((item) => { const isChecked = checkedSet.has(item.id); const isProcessing = runningIds.includes(item.id); const ratio = Math.min(1, (item.sizeBytes ?? 0) / maxItemBytes); @@ -516,17 +489,14 @@ export function ShredderCommand() { ], actions: ActionPanel({ children: [ + selectedItems.length > 0 + ? shredAction(t("shredCheckedCountBytes", { count: selectedItems.length, bytes: formatBytes(selectedBytes) })) + : shredAction(t("shredCheckedCountBytes", { count: 1, bytes: formatSize(item.sizeBytes) }), [item]), Action({ title: t("locateFileAction"), icon: Icon.Folder, onAction: () => locateItem(item) }), - Action({ - title: isChecked ? t("uncheckFileAction") : t("checkFileAction"), - icon: Icon.CheckCircle, - onAction: () => toggleItemCheck(item) - }), - shredAction(t("shredCheckedCountBytes", { count: selectedItems.length, bytes: formatBytes(selectedBytes) })), ActionPanel.Section({ title: t("listSectionTitle"), children: [ @@ -556,6 +526,7 @@ export function ShredderCommand() { }); }); + // 布局一(单栏全宽队列):彻底去除反直觉的 32% 左栏来源筛选与 0 项空占位 return List({ ...fileInputProps, isLoading: isImporting || isShredding, @@ -578,56 +549,39 @@ export function ShredderCommand() { }), filterBar: { summaryText, - actions: - selectedItems.length > 0 - ? [ - { - id: "pick-files", - title: t("pickFilesBtn"), - style: "secondary", - onAction: handlePickFiles - }, - { - id: "shred-selected", - title: isShredding ? t("shreddingBtn") : t("shredSelectedBtn", { count: selectedItems.length }), - style: "destructive", - disabled: isShredding, - onAction: () => { - void handleBatchShred(); - } - } - ] - : [ - { - id: "pick-files", - title: t("pickFilesBtn"), - style: "secondary", - onAction: handlePickFiles - }, - { - id: "pick-folder", - title: t("pickFolderBtn"), - style: "secondary", - onAction: handlePickFolder - } - ] - }, - subList: { - title: t("subListTitle", { count: visibleItems.length, bytes: formatBytes(selectedBytes) }), - subtitle: currentStandard.description, - emptyText, - checkable: visibleItems.length > 0, - checked: allChecked ? true : someChecked ? "indeterminate" : false, - onCheckChange: () => toggleAllVisible(), - items: subListItems + actions: [ + { + id: "pick-files", + title: t("pickFilesBtn"), + style: "secondary", + disabled: isShredding, + onAction: handlePickFiles + }, + { + id: "pick-folder", + title: t("pickFolderBtn"), + style: "secondary", + disabled: isShredding, + onAction: handlePickFolder + } + ] }, - children: [ - List.Section({ - title: t("leftSectionTitle"), - subtitle: t("leftSectionSubtitle"), - children: leftNavNodes - }) - ] + children: + queueItems.length > 0 + ? [ + List.Section({ + title: t("subListTitle", { count: visibleItems.length, bytes: formatBytes(selectedBytes) }), + subtitle: currentStandard.description, + children: queueItems + }) + ] + : [ + List.EmptyView({ + title: t("leftSectionTitle"), + description: emptyText, + icon: Icon.Trash + }) + ] }); } diff --git a/extensions/shredder/src/logic.ts b/extensions/shredder/src/logic.ts index aacdec9c..e35af12f 100644 --- a/extensions/shredder/src/logic.ts +++ b/extensions/shredder/src/logic.ts @@ -39,9 +39,10 @@ export const getForbiddenReason = () => t("forbiddenReason"); export const getNotInClientMessage = () => t("notInClient"); export const getShredSupportedText = () => t("supportedText"); -/** 导入规则:任意非空普通文件,系统保护路径一律跳过 */ +/** 导入规则:允许 0 字节文件(如空密钥/锁文件),系统保护路径一律跳过 */ export const SHRED_IMPORT_RULES: FileImportRules = { - forbiddenPath: FORBIDDEN_TARGET_PATTERN + forbiddenPath: FORBIDDEN_TARGET_PATTERN, + skipEmptyFiles: false }; export type ShredStandardId = "dod_3pass" | "seven_pass" | "zero_1pass"; diff --git a/extensions/shredder/tests/shredder.host.test.mjs b/extensions/shredder/tests/shredder.host.test.mjs deleted file mode 100644 index 127f8d30..00000000 --- a/extensions/shredder/tests/shredder.host.test.mjs +++ /dev/null @@ -1,155 +0,0 @@ -import test from 'node:test' -import assert from 'node:assert/strict' -import { setRuntimeLocale } from '@ztools/declarative-ui' -import * as shredder from '../dist/logic.js' - -setRuntimeLocale('zh-CN') - -function createRealHostStub(handlers = {}) { - const calls = [] - const dispatch = async (method, params) => { - calls.push({ channel: method, payload: params }) - if (typeof handlers[method] === 'function') { - return await handlers[method](params) - } - if (method in handlers) { - return handlers[method] - } - throw new Error(`CHANNEL_NOT_IMPLEMENTED: ${method}`) - } - - const stub = { - __isRealHost: true, - calls, - transport: { - call: dispatch - } - } - - for (const key of Object.keys(handlers)) { - stub[key] = (params) => dispatch(key, params) - } - - return stub -} - -test('shredder: 已移除所有自动扫盘与示例数据导出', () => { - assert.equal(typeof shredder.fetchShredCandidates, 'undefined') - assert.equal(typeof shredder.createInitialShredderSnapshot, 'undefined') - assert.equal(typeof shredder.createEmptyShredderSnapshot, 'undefined') - assert.equal(typeof shredder.SHRED_CATEGORIES, 'undefined') -}) - -test('shredder: 导入规则拦截 Windows 系统受保护路径,候选转换保留未知大小', () => { - assert.equal(shredder.SHRED_IMPORT_RULES.forbiddenPath.test('C:\\Windows\\System32\\ntoskrnl.exe'), true) - assert.equal(shredder.SHRED_IMPORT_RULES.forbiddenPath.test('C:\\Program Files\\App\\app.exe'), true) - assert.equal(shredder.SHRED_IMPORT_RULES.forbiddenPath.test('D:\\Secret\\report.docx'), false) - - const a = shredder.toShredCandidate( - { - path: 'D:\\Secret\\Report.docx', - name: 'Report.docx', - parentDir: 'D:\\Secret', - extension: '.docx', - sizeBytes: null, - lastModifiedMs: null - }, - 'manual' - ) - const b = shredder.toShredCandidate( - { - path: 'd:/secret/report.docx', - name: 'Report.docx', - parentDir: 'd:/secret', - extension: '.docx', - sizeBytes: 2048, - lastModifiedMs: null - }, - 'folder' - ) - assert.equal(a.id, b.id) - assert.equal(a.sizeBytes, null) - assert.equal(shredder.formatSize(a.sizeBytes), '大小未识别') - assert.equal(shredder.sumKnownBytes([a, b]), 2048) - - const unknownMsg = shredder.buildShredConfirmMessage([a], 'dod_3pass') - assert.match(unknownMsg, /大小未识别/) - - const many = Array.from({ length: 12 }, (_, idx) => - shredder.toShredCandidate( - { - path: `D:\\Temp\\f${idx}.bin`, - name: `f${idx}.bin`, - parentDir: 'D:\\Temp', - extension: '.bin', - sizeBytes: 1024, - lastModifiedMs: null - }, - 'folder' - ) - ) - const manyMsg = shredder.buildShredConfirmMessage(many, 'dod_3pass') - assert.match(manyMsg, /以及其余 2 个文件/) -}) - -test('shredder: 受保护系统路径与空目标列表一律拦截,绝不调用粉碎能力', async () => { - const host = createRealHostStub({ - dllplugin_call: () => { - throw new Error('不应调用粉碎能力') - } - }) - - const sysRes = await shredder.executeSecureShred( - [ - { - id: 'sys_locked', - name: 'ntoskrnl.exe', - path: 'C:\\Windows\\System32\\ntoskrnl.exe', - source: 'manual', - sourceName: '手动添加', - sizeBytes: 1024 - } - ], - 'dod_3pass', - host - ) - assert.equal(sysRes.ok, false) - assert.equal(sysRes.message, shredder.getForbiddenReason()) - assert.equal(host.calls.length, 0) - - const empty = await shredder.executeSecureShred([], 'dod_3pass', host) - assert.equal(empty.ok, false) - assert.equal(empty.message, '请先勾选要粉碎的文件') -}) - -test('shredder: 部分文件粉碎失败时 ok 为 false 并列出失败原因,不改用普通删除', async () => { - const okPath = 'D:\\Scratch\\a.tmp' - const badPath = 'D:\\Scratch\\b.tmp' - const host = createRealHostStub({ - dllplugin_call: (payload) => { - if (payload.params.path === badPath) return { ok: false, success: false, error: '拒绝访问' } - return { ok: true, success: true, shreddedCount: 1 } - }, - filesystem_delete_file: () => { - throw new Error('不能用普通删除顶替粉碎') - } - }) - const items = [okPath, badPath].map((p, i) => ({ - id: `t${i}`, - name: p.split('\\').pop(), - path: p, - source: 'manual', - sourceName: '手动添加', - sizeBytes: 1024 - })) - const res = await shredder.executeSecureShred(items, 'zero_1pass', host) - assert.equal(res.ok, false) - assert.equal(res.shreddedCount, 1) - assert.deepEqual(res.shreddedPaths, [okPath]) - assert.deepEqual(res.failedPaths, [badPath]) - assert.match(res.message, /1 个失败/) - assert.match(res.message, /拒绝访问/) - assert.equal(host.calls.some((c) => c.channel === 'filesystem_delete_file'), false) - const wipe = host.calls.find((c) => c.channel === 'dllplugin_call') - assert.equal(wipe.payload.params.passes, 1) -}) diff --git a/extensions/shredder/tests/shredder.real-chain.test.mjs b/extensions/shredder/tests/shredder.real-chain.test.mjs new file mode 100644 index 00000000..1212df4f --- /dev/null +++ b/extensions/shredder/tests/shredder.real-chain.test.mjs @@ -0,0 +1,65 @@ +// shredder 真实宿主链路(Real Host Chain)端到端测试 +// 零假宿主 Mock:100% 走真实 FileSystemService.#grants + 真实 BuiltinPluginHostService(ShredderPlugin) + 真实磁盘覆写销毁 +import test from 'node:test' +import assert from 'node:assert/strict' +import fs from 'node:fs' +import path from 'node:path' +import { createRealHost, mount, REAL_HOST_SKIP_REASON, tick } from '../../shared/real-host-harness.mjs' +import { setRuntimeLocale } from '@ztools/declarative-ui' + +setRuntimeLocale('zh-CN') +const { default: ShredderCommand } = await import('../dist/index.js') + +async function waitUntil(pred, timeoutMs = 6000) { + const start = Date.now() + while (Date.now() - start < timeoutMs) { + if (pred()) return true + await new Promise((r) => setTimeout(r, 40)) + } + return false +} + +test('真实链路 JTBD-1: 单栏全宽队列无空左栏 -> 选入真实非空与 0 字节文件 -> 确认并补父目录写授权 -> 真实物理覆写销毁', { skip: REAL_HOST_SKIP_REASON }, async () => { + const realHost = createRealHost({ pluginId: 'shredder' }) + try { + const secretFile = realHost.writeTempFile('private/secret.txt', 'sensitive-credential-data-12345') + const emptyLock = realHost.writeTempFile('private/empty.lock', '') + + const view = await mount(ShredderCommand, realHost) + await tick(10) + + // 1. 验证重构为单栏全宽队列(无 subList、无 32% 左栏空占位) + assert.equal(view.tree().props.subList, undefined, 'shredder 应使用极简单栏布局一,不切分无意义的左栏来源筛选') + assert.ok(view.emptyView(), '空态应使用 List.EmptyView 给出明确引导') + + // 2. 通过顶栏「选择文件」(仅只读授权)导入普通文件 + 0 字节文件 + const pickFilesBtn = view.tree().props.filterBar.actions.find((a) => a.id === 'pick-files') + assert.ok(pickFilesBtn) + realHost.queueOpenDialog([secretFile, emptyLock]) + pickFilesBtn.onAction() + + const imported = await waitUntil(() => view.items().length === 2) + assert.equal(imported, true, `应成功导入普通文件与 0 字节文件,实际: ${view.items().length}`) + + // 勾选 2 个文件后顶栏依然保留「选择文件夹」 + assert.equal(view.tree().props.filterBar.actions.some((a) => a.id === 'pick-folder'), true, '勾选后顶栏仍应保留选择文件夹入口') + + // 勾选全部 2 个文件并触发粉碎:强确认 + 自动按父目录补写授权 -> 真实物理覆写并从磁盘消失 + for (const row of view.items()) { + row.props.onCheckChange(true) + } + await tick(5) + realHost.setConfirm(true) + realHost.queueSelectFolderDialog(path.dirname(secretFile)) + const firstRow = view.items()[0] + await view.run(firstRow, view.actions(firstRow)[0].props.title) + + const shredded = await waitUntil(() => !fs.existsSync(secretFile) && !fs.existsSync(emptyLock)) + assert.equal(shredded, true, `两个真实文件应已被彻底物理销毁,toasts=${JSON.stringify(realHost.toasts)}`) + assert.equal(realHost.lastToast()?.style, 'SUCCESS') + + view.unmount() + } finally { + await realHost.dispose() + } +}) diff --git a/extensions/shredder/tests/shredder.ui.test.mjs b/extensions/shredder/tests/shredder.ui.test.mjs deleted file mode 100644 index aa0417ca..00000000 --- a/extensions/shredder/tests/shredder.ui.test.mjs +++ /dev/null @@ -1,411 +0,0 @@ -import test from 'node:test' -import assert from 'node:assert/strict' -import fs from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import { createHost, installDirectoryHost, mount, tick } from '../../shared/test-harness.mjs' -import ShredderCommand from '../dist/index.js' - -function makeTempTree(spec) { - const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ztools-shredder-')) - for (const [rel, content] of Object.entries(spec)) { - const full = path.join(root, rel) - if (rel.endsWith('/')) { - fs.mkdirSync(full, { recursive: true }) - continue - } - fs.mkdirSync(path.dirname(full), { recursive: true }) - fs.writeFileSync(full, content) - } - return root -} - -function installShredHost(host, { failPaths = [] } = {}) { - const wipeCalls = [] - host.ipc.dllplugin_call = async ({ plugin, func, params }) => { - assert.equal(plugin, 'ShredderPlugin') - assert.equal(func, 'secureWipeFile') - wipeCalls.push(params) - if (failPaths.includes(params.path)) { - return { ok: false, success: false, error: '文件正被其他程序占用' } - } - return { ok: true, success: true, shreddedCount: 1, shredded: [params.path], errors: [] } - } - return wipeCalls -} - -function fileRows(view) { - return view.items().filter((it) => String(it.props.id).startsWith('shred-item-')) -} - -function rowByPath(view, p) { - return fileRows(view).find((it) => it.props.subtitle === p) -} - -test('shredder UI: 挂载时不扫描任何目录、列表为空、顶栏恰为 2 个按钮且空状态提供选择动作', async () => { - const host = createHost() - const view = await mount(ShredderCommand, host) - - assert.equal(fileRows(view).length, 0) - const forbiddenStartupMethods = new Set([ - 'system_get_path', - 'system_list_common_folders', - 'system_search_files', - 'filesystem_get_directory_contents', - 'dllplugin_call' - ]) - assert.equal( - host.ipcCalls.some(([method]) => forbiddenStartupMethods.has(method)), - false, - `挂载时不应调用扫盘或原生能力,实际调用:${JSON.stringify(host.ipcCalls)}` - ) - - const tree = view.tree() - assert.equal(tree.props.isShowingDetail, false) - assert.equal(tree.props.filterBar.actions.length, 2) - assert.deepEqual( - tree.props.filterBar.actions.map((a) => [a.id, a.title]), - [ - ['pick-files', '选择文件'], - ['pick-folder', '选择文件夹'] - ] - ) - assert.match(tree.props.filterBar.summaryText, /尚未添加文件/) - - const rootActionTitles = view.actions(null).map((a) => a.props.title) - assert.equal(rootActionTitles[0], '选择文件…') - assert.equal(rootActionTitles[1], '选择文件夹…') - - view.unmount() -}) - -test('shredder UI: 选择文件支持取消、宿主报错、系统路径拦截,且新导入文件默认不勾选', async () => { - const host = createHost() - const view = await mount(ShredderCommand, host) - - // 1. 取消选择不改变列表也不弹 Toast - host.ipc.window_show_open_dialog = async () => ({ canceled: true }) - await view.tree().props.filterBar.actions[0].onAction() - await tick(10) - assert.equal(fileRows(view).length, 0) - assert.equal(host.toasts.length, 0) - - // 2. 宿主报错如实提示 - host.ipc.window_show_open_dialog = async () => { - throw new Error('当前窗口的文件 capability 数量超过上限') - } - await view.tree().props.filterBar.actions[0].onAction() - await tick(10) - assert.equal(host.lastToast().style, 'FAILURE') - assert.match(host.lastToast().message, /改用「选择文件夹」/) - - // 3. 多选普通文件 + 系统受保护路径 + 未知大小文件:系统路径被拦截,普通文件默认未勾选 - const normalFile = 'D:\\Scratch\\secret.docx' - const unknownSizeFile = 'D:\\Scratch\\unknown.bin' - const systemFile = 'C:\\Windows\\System32\\drivers\\etc\\hosts' - host.ipc.window_show_open_dialog = async (params) => { - assert.deepEqual(params.properties, ['openFile', 'multiSelections']) - return { canceled: false, filePaths: [normalFile, systemFile, unknownSizeFile] } - } - host.ipc.filesystem_get_file_size = async ({ path: p }) => { - if (p === normalFile) return 16384 - throw new Error('未授权') - } - await view.run(null, '选择文件…') - await tick(10) - - const rows = fileRows(view) - assert.equal(rows.length, 2) - assert.ok(rows.every((r) => r.props.checked === false), '新导入文件必须默认不勾选') - assert.equal(rowByPath(view, systemFile), undefined, 'Windows 系统目录文件必须被拦截') - assert.equal(rowByPath(view, normalFile).props.accessories[2].text, '16.0 KB') - assert.equal(rowByPath(view, unknownSizeFile).props.accessories[2].text, '大小未识别') - - view.unmount() -}) - -test('shredder UI: 选择文件夹递归导入非空文件(跳过空文件与系统子目录)、磁盘根目录二次确认及数量截断提示', async () => { - const tmpDir = makeTempTree({ - 'note.txt': 'hello', - 'sub/dump.dmp': 'binary-data', - 'empty.tmp': '', - 'System32/kernel.dll': 'sys', - '.hidden.dat': 'hidden' - }) - try { - const host = createHost() - await installDirectoryHost(host, { authorized: [tmpDir] }) - const view = await mount(ShredderCommand, host) - - // 1. 选磁盘根目录时先弹出 confirmAlert,取消则不读目录 - host.ipc.window_show_select_folder_dialog = async () => ({ canceled: false, folderPath: 'D:\\' }) - host.setConfirm(false) - await view.tree().props.filterBar.actions[1].onAction() - await tick(10) - assert.equal(host.confirms.length, 1) - assert.match(host.confirms[0].title, /导入整个磁盘/) - assert.equal(host.ipcCalls.some(([m]) => m === 'filesystem_get_directory_contents'), false) - - // 2. 选择受保护系统目录直接报错 - host.ipc.window_show_select_folder_dialog = async () => ({ canceled: false, folderPath: 'C:\\Windows\\System32' }) - await view.tree().props.filterBar.actions[1].onAction() - await tick(10) - assert.equal(host.lastToast().style, 'FAILURE') - assert.match(host.lastToast().message, /受保护/) - - // 3. 正常选择临时目录:递归导入,跳过空文件和受保护子目录,全部默认不勾选 - host.ipc.window_show_select_folder_dialog = async () => ({ canceled: false, folderPath: tmpDir }) - await view.run(null, '选择文件夹…') - await tick(15) - - const rows = fileRows(view) - assert.equal(rows.length, 2) - assert.ok(rows.every((r) => r.props.checked === false), '文件夹导入的文件必须默认不勾选') - const noteRow = rowByPath(view, path.join(tmpDir, 'note.txt')) - const dumpRow = rowByPath(view, path.join(tmpDir, 'sub', 'dump.dmp')) - assert.ok(noteRow) - assert.ok(dumpRow) - assert.equal(noteRow.props.accessories[1].tag.value, '文件夹导入') - - // 4. 文件数超过 500 时标记截断并提示「只导入了一部分」 - const bulkHost = createHost() - const bulkDir = 'D:\\BulkLogs' - bulkHost.ipc.window_show_select_folder_dialog = async () => ({ canceled: false, folderPath: bulkDir }) - bulkHost.ipc.filesystem_get_directory_contents = async () => ({ - success: true, - files: Array.from({ length: 505 }, (_, i) => ({ - name: `log_${i}.txt`, - size: 128, - isDirectory: false, - lastModified: '2026-01-01T00:00:00Z' - })) - }) - const bulkView = await mount(ShredderCommand, bulkHost) - await bulkView.tree().props.filterBar.actions[1].onAction() - await tick(15) - assert.equal(fileRows(bulkView).length, 500) - assert.match(bulkHost.lastToast().message, /只导入了一部分/) - - bulkView.unmount() - view.unmount() - } finally { - fs.rmSync(tmpDir, { recursive: true, force: true }) - } -}) - -test('shredder UI: 拖入文件夹(新版含 directories 与旧版回退)、粘贴去重且不丢失原有勾选', async () => { - const tmpDir = makeTempTree({ - 'a.bin': 'aaa', - 'nested/b.log': 'bbb' - }) - try { - const host = createHost() - await installDirectoryHost(host, { authorized: [tmpDir] }) - const pastedFile = path.join(tmpDir, 'a.bin') - const extraFile = 'D:\\Secret\\extra.dat' - host.ipc.filesystem_get_file_size = async ({ path: p }) => (p === extraFile ? 4096 : 3) - host.ipc.filesystem_directory_exists = async ({ path: p }) => path.resolve(p) === path.resolve(tmpDir) - - const view = await mount(ShredderCommand, host) - - // 1. 新版拖入文件夹(携带 directories)不调 filesystem_directory_exists - await view.dropFiles([tmpDir], { directories: [tmpDir] }) - await tick(15) - assert.equal(fileRows(view).length, 2) - assert.equal(host.ipcCalls.some(([m]) => m === 'filesystem_directory_exists'), false) - assert.ok(fileRows(view).every((r) => r.props.checked === false)) - - // 勾选一个已有文件,随后旧版拖入(不带 directories)与粘贴重复文件 - await view.run(rowByPath(view, pastedFile), '勾选此文件') - assert.equal(rowByPath(view, pastedFile).props.checked, true) - - await view.dropFiles([tmpDir, extraFile]) - await tick(15) - assert.equal(host.ipcCalls.some(([m]) => m === 'filesystem_directory_exists'), true) - assert.equal(fileRows(view).length, 3) - assert.equal(rowByPath(view, pastedFile).props.checked, true, '重复导入不能覆盖原有勾选') - assert.equal(rowByPath(view, extraFile).props.checked, false, '新导入文件必须保持未勾选') - - // 全部重复时给出提示 - await view.pasteFiles([extraFile.toUpperCase()]) - await tick(10) - assert.equal(fileRows(view).length, 3) - assert.equal(host.lastToast().title, '这些文件已在列表中') - - view.unmount() - - // 旧版客户端不提供 onFileInput 时通过 plugin_files_dropped 回退入口导入,且默认不勾选 - globalThis.window.__ztoolsDeclarativeFeatures = { fileInput: false } - const legacyView = await mount(ShredderCommand, host) - host.emitEvent('plugin_files_dropped', { payload: { files: [extraFile] } }) - await tick(15) - assert.equal(fileRows(legacyView).length, 1) - assert.equal(rowByPath(legacyView, extraFile).props.checked, false) - legacyView.unmount() - } finally { - fs.rmSync(tmpDir, { recursive: true, force: true }) - } -}) - -test('shredder UI: 确认框逐个列出并支持取消、部分失败保留勾选且不改用普通删除、下拉切换覆写次数', async () => { - const host = createHost() - const FILE_A = 'D:\\Scratch\\a.tmp' - const FILE_B = 'D:\\Scratch\\b.log' - const FILE_C = 'D:\\Scratch\\c.dmp' - const wipeCalls = installShredHost(host, { failPaths: [FILE_C] }) - host.ipc.window_show_open_dialog = async () => ({ canceled: false, filePaths: [FILE_A, FILE_B, FILE_C] }) - host.ipc.filesystem_get_file_size = async ({ path: p }) => (p === FILE_A ? 4096 : p === FILE_B ? 2048 : 8192) - - const view = await mount(ShredderCommand, host) - await view.run(null, '选择文件…') - await tick(10) - - // 未勾选时不弹确认也不调用粉碎 - await view.run(rowByPath(view, FILE_A), '粉碎已勾选文件 (0 项 / 0 B)') - assert.equal(host.confirms.length, 0) - assert.equal(wipeCalls.length, 0) - assert.equal(host.lastToast().title, '请先勾选要粉碎的文件') - - // 勾选 FILE_A 和 FILE_C,取消确认 - await view.run(rowByPath(view, FILE_A), '勾选此文件') - await view.run(rowByPath(view, FILE_C), '勾选此文件') - host.setConfirm(false) - await view.run(rowByPath(view, FILE_A), '粉碎已勾选文件 (2 项 / 12.0 KB)') - - assert.equal(host.confirms.length, 1) - assert.equal(host.confirms[0].title, '确认粉碎 2 个文件?') - assert.match(host.confirms[0].message, /a\.tmp/) - assert.match(host.confirms[0].message, /c\.dmp/) - assert.match(host.confirms[0].message, /磨损均衡/) - assert.match(host.confirms[0].message, /TRIM/) - assert.doesNotMatch(host.confirms[0].message, /b\.log/) - assert.equal(wipeCalls.length, 0) - - // 文件清单项与导航项的 Enter 主动作必须是安全操作,粉碎动作退至次动作并带快捷键 - const rowActions = view.actions(rowByPath(view, FILE_A)) - assert.equal(rowActions[0].props.title, '在资源管理器中定位此文件') - const shredAct = rowActions.find((a) => a.props.title.startsWith('粉碎已勾选文件')) - assert.ok(shredAct && shredAct.props.shortcut, '粉碎动作应配置快捷键并位于次动作') - const navAllActions = view.actions(view.item('nav-shred-all')) - assert.notEqual(navAllActions[0].props.title.startsWith('粉碎已勾选文件'), true) - - // 切换为 7 次覆写并执行粉碎(FILE_C 模拟占用失败) - await view.dropdown('seven_pass') - host.setConfirm(true) - await view.run(rowByPath(view, FILE_A), '粉碎已勾选文件 (2 项 / 12.0 KB)') - - assert.deepEqual(wipeCalls.map((c) => c.path).sort(), [FILE_A, FILE_C].sort()) - assert.equal(wipeCalls[0].passes, 7) - assert.ok(!wipeCalls.some((c) => c.path === FILE_B), '未勾选的文件不能被粉碎') - assert.ok(!host.ipcCalls.some(([m]) => m === 'filesystem_delete_file' || m === 'shell_trash_item')) - - const toast = host.lastToast() - assert.equal(toast.style, 'FAILURE') - assert.equal(toast.title, '部分文件粉碎失败') - assert.match(toast.message, /已粉碎 1 个文件/) - assert.match(toast.message, /1 个失败/) - assert.match(toast.message, /文件正被其他程序占用/) - - assert.equal(rowByPath(view, FILE_A), undefined) - assert.equal(rowByPath(view, FILE_C).props.checked, true) - assert.equal(rowByPath(view, FILE_B).props.checked, false) - - // 定位文件失败如实提示 - await view.run(rowByPath(view, FILE_B), '在资源管理器中定位此文件') - assert.equal(host.lastToast().title, '无法在资源管理器中定位此文件') - - view.unmount() -}) - -test('shredder UI: 从列表移除、全选/取消全选、清空列表、处理中拒绝清空、导入中清空丢弃结果', async () => { - const host = createHost() - const FILE_A = 'D:\\Scratch\\a.bin' - const FILE_B = 'D:\\Scratch\\b.bin' - host.ipc.window_show_open_dialog = async () => ({ canceled: false, filePaths: [FILE_A, FILE_B] }) - host.ipc.filesystem_get_file_size = async () => 1024 - - let releaseWipe - host.ipc.dllplugin_call = async ({ params }) => { - if (params.path === FILE_A) { - await new Promise((resolve) => { - releaseWipe = resolve - }) - } - return { ok: true, success: true, shreddedCount: 1 } - } - - const view = await mount(ShredderCommand, host) - await view.run(null, '选择文件…') - await tick(10) - - // 全选与取消全选 - await view.run(rowByPath(view, FILE_A), '全选') - assert.ok(fileRows(view).every((r) => r.props.checked === true)) - await view.run(rowByPath(view, FILE_A), '取消全选') - assert.ok(fileRows(view).every((r) => r.props.checked === false)) - - // 只勾选 FILE_A 并开始粉碎(挂起),验证处理中状态 - await view.run(rowByPath(view, FILE_A), '勾选此文件') - host.setConfirm(true) - const shredding = view.run(rowByPath(view, FILE_A), '粉碎已勾选文件 (1 项 / 1.0 KB)') - await tick(5) - - // 正在粉碎的条目不提供「从列表移除」 - assert.equal( - view.actions(rowByPath(view, FILE_A)).some((a) => a.props.title === '从列表移除'), - false - ) - - // 处理中点击「清空列表」必须被拒绝 - await view.run(rowByPath(view, FILE_B), '清空列表') - assert.equal(host.lastToast().style, 'FAILURE') - assert.equal(host.lastToast().title, '正在处理,完成后再清空') - assert.equal(fileRows(view).length, 2) - - // 处理过程中将未处理的 FILE_B 从列表移除,完成后不能加回 - await view.run(rowByPath(view, FILE_B), '从列表移除') - assert.equal(rowByPath(view, FILE_B), undefined) - assert.equal(host.ipcCalls.some(([m]) => m === 'filesystem_delete_file'), false) - - releaseWipe() - await shredding - assert.equal(fileRows(view).length, 0) - - // 导入进行中清空列表:迟到的目录结果应被丢弃 - let releaseDir - host.ipc.window_show_select_folder_dialog = async () => ({ canceled: false, folderPath: 'D:\\SlowDir' }) - host.ipc.filesystem_get_directory_contents = async () => - await new Promise((resolve) => { - releaseDir = resolve - }) - const importing = view.tree().props.filterBar.actions[1].onAction() - await tick(5) - assert.match(view.tree().props.filterBar.summaryText, /正在导入/) - - // 通过左侧分类条目触发清空列表 - await view.run(view.item('nav-shred-all'), '清空列表') - assert.equal(fileRows(view).length, 0) - - const toastCountBeforeResolve = host.toasts.length - releaseDir({ - success: true, - files: [{ name: 'late.txt', size: 512, isDirectory: false, lastModified: '2026-01-01T00:00:00Z' }] - }) - await importing - await tick(10) - assert.equal(fileRows(view).length, 0, '导入中清空后,迟到的结果必须被丢弃') - assert.equal(host.toasts.length, toastCountBeforeResolve) - - // 重新导入后空闲清空列表 - host.ipc.filesystem_get_directory_contents = async () => ({ - success: true, - files: [{ name: 'fresh.txt', size: 512, isDirectory: false, lastModified: '2026-01-01T00:00:00Z' }] - }) - await view.tree().props.filterBar.actions[1].onAction() - await tick(10) - assert.equal(fileRows(view).length, 1) - await view.run(rowByPath(view, 'D:\\SlowDir\\fresh.txt'), '清空列表') - assert.equal(fileRows(view).length, 0) - - view.unmount() -}) diff --git a/extensions/snippets/plugin.json b/extensions/snippets/plugin.json index ccdb4519..e4d224c9 100644 --- a/extensions/snippets/plugin.json +++ b/extensions/snippets/plugin.json @@ -1,7 +1,7 @@ { "id": "snippets", "name": "快捷短语", - "version": "1.2.11", + "version": "1.2.12", "minAppVersion": "1.1.8.3", "description": "管理常用开票税号、收件地址、客服话术与常用模板,支持动态日期/时间/剪贴板宏变量,一键穿透上屏或复制", "author": "ZTools Team", diff --git a/extensions/snippets/src/i18n.ts b/extensions/snippets/src/i18n.ts index f8da894e..f23df2cb 100644 --- a/extensions/snippets/src/i18n.ts +++ b/extensions/snippets/src/i18n.ts @@ -54,6 +54,22 @@ const rawT = createTranslator( copyAction: "复制解析后的文本", editAction: "编辑短语", deleteAction: "删除短语", + exportJsonAction: "导出全部为 JSON", + importJsonAction: "导入 JSON 备份", + exportJsonSuccessToast: "已复制 {count} 条短语 JSON 到剪贴板", + exportJsonFailedToast: "导出 JSON 失败", + importFormTitle: "导入短语 JSON 备份", + importJsonLabel: "JSON 备份内容", + importJsonPlaceholder: "粘贴之前导出的快捷短语 JSON 数组...", + importConfirmBtn: "确认导入", + importSuccessToast: "已导入 {count} 条短语", + importFailedToast: "导入失败", + errImportNotArray: "导入内容必须为短语 JSON 数组", + errImportJsonParse: "JSON 解析失败", + sortFrequentAction: "切换为按最近更新排序", + sortRecentAction: "切换为按使用频次排序", + detailTemplateHeading: "模板原文", + detailPreviewHeading: "宏展开预览", errTitleEmpty: "SNIPPET_INVALID_INPUT: 短语标题不能为空", errContentEmpty: "SNIPPET_INVALID_INPUT: 短语模板内容不能为空", errInvalidStorageFormat: "短语存储格式无效,未覆盖原数据", @@ -112,6 +128,22 @@ const rawT = createTranslator( copyAction: "Copy Resolved Text", editAction: "Edit Snippet", deleteAction: "Delete Snippet", + exportJsonAction: "Export All as JSON", + importJsonAction: "Import JSON Backup", + exportJsonSuccessToast: "Copied {count} [[count:snippet|snippets]] JSON to clipboard", + exportJsonFailedToast: "Failed to export JSON", + importFormTitle: "Import Snippets JSON Backup", + importJsonLabel: "JSON Backup Content", + importJsonPlaceholder: "Paste previously exported snippets JSON array...", + importConfirmBtn: "Confirm Import", + importSuccessToast: "Imported {count} [[count:snippet|snippets]]", + importFailedToast: "Import failed", + errImportNotArray: "Import data must be a JSON array of snippets", + errImportJsonParse: "JSON parse failed", + sortFrequentAction: "Sort by Recently Updated", + sortRecentAction: "Sort by Most Used", + detailTemplateHeading: "Template", + detailPreviewHeading: "Macro Expansion Preview", errTitleEmpty: "SNIPPET_INVALID_INPUT: Snippet title cannot be empty", errContentEmpty: "SNIPPET_INVALID_INPUT: Snippet template content cannot be empty", errInvalidStorageFormat: "Invalid snippets storage format; existing data was not overwritten", diff --git a/extensions/snippets/src/index.tsx b/extensions/snippets/src/index.tsx index 7e7f386f..495211a2 100644 --- a/extensions/snippets/src/index.tsx +++ b/extensions/snippets/src/index.tsx @@ -24,11 +24,31 @@ import { resolveMacroTemplate, validateSnippetInput } from './macro-engine.js' -import { SNIPPETS_STORAGE_KEY, assertSnippetUnchanged, parseStoredSnippets, updateSnippets } from './snippets-storage.js' +import { + SNIPPETS_STORAGE_KEY, + assertSnippetUnchanged, + exportSnippetsJson, + importSnippetsJson, + parseStoredSnippets, + sortSnippets, + updateSnippets +} from './snippets-storage.js' +import type { SnippetSortMode } from './snippets-storage.js' import { t } from './i18n.js' export * from './types.js' export * from './macro-engine.js' +export * from './snippets-storage.js' + +const DYNAMIC_MACRO_RE = /\{(date|time|datetime|clipboard)\}/ + +function buildSnippetDetailMarkdown(content: string, clipboardPreview: string): string { + if (!DYNAMIC_MACRO_RE.test(content)) { + return fencedBlock(content) + } + const resolved = resolveMacroTemplate(content, clipboardPreview) + return `#### ${t('detailTemplateHeading')}\n${fencedBlock(content)}\n\n#### ${t('detailPreviewHeading')}\n${fencedBlock(resolved.text)}` +} function fencedBlock(content: string): string { const runs = String(content).match(/`+/g) || [] @@ -145,6 +165,50 @@ export function SnippetEditForm({ initialData, onSave }: SnippetEditFormProps) { ) } +export interface ImportSnippetsFormProps { + onImport: (jsonText: string) => Promise +} + +export function ImportSnippetsForm({ onImport }: ImportSnippetsFormProps) { + useLocale() + const { pop } = useNavigation() + const [jsonText, setJsonText] = useState('') + + const handleSubmit = useCallback(async () => { + try { + const count = await onImport(jsonText) + await showToast({ style: Toast.Style.Success, title: t('importSuccessToast', { count }) }) + pop() + } catch (error) { + await showToast({ + style: Toast.Style.Failure, + title: t('importFailedToast'), + message: error instanceof Error ? error.message : String(error) + }) + } + }, [jsonText, onImport, pop]) + + return ( +
+ + + } + > + + + ) +} + export interface SnippetsProps { featureCode?: string initialSnippets?: SnippetItem[] @@ -156,6 +220,8 @@ export function Snippets({ featureCode = 'snippets-all', initialSnippets }: Snip const [isLoading, setIsLoading] = useState(!initialSnippets) const [snippets, setSnippets] = useState(initialSnippets || []) const [searchText, setSearchText] = useState('') + const [sortMode, setSortMode] = useState('frequent') + const [clipboardPreview, setClipboardPreview] = useState('') const [categoryFilter, setCategoryFilter] = useState(() => { if (featureCode === 'snippets-invoice') return 'invoice' if (featureCode === 'snippets-address') return 'address' @@ -258,15 +324,66 @@ export function Snippets({ featureCode = 'snippets-all', initialSnippets }: Snip await showToast({ style: Toast.Style.Success, title: paste ? t('pastedToast') : t('copiedToast') }) }, [persistSnippets]) + useEffect(() => { + let active = true + void Clipboard.readText() + .then((text) => { + if (active && mountedRef.current) setClipboardPreview(text || '') + }) + .catch((err) => { + console.warn('[snippets] clipboard preview read failed:', err instanceof Error ? err.message : String(err)) + }) + return () => { + active = false + } + }, []) + useEffect(() => { if (featureCode !== 'snippets-new' || isLoading || loadError || openedNewRef.current) return openedNewRef.current = true push() }, [featureCode, isLoading, loadError, handleSaveSnippet, push]) + const handleExportJson = useCallback(async () => { + try { + await Clipboard.copy(exportSnippetsJson(snippets)) + await showToast({ + style: Toast.Style.Success, + title: t('exportJsonSuccessToast', { count: snippets.length }) + }) + } catch (error) { + await showToast({ + style: Toast.Style.Failure, + title: t('exportJsonFailedToast'), + message: error instanceof Error ? error.message : String(error) + }) + } + }, [snippets]) + + const handleImportJson = useCallback(async (jsonText: string): Promise => { + let importedCount = 0 + await persistSnippets((items) => { + const res = importSnippetsJson(jsonText, items) + if (!res.success) { + throw new Error(res.error) + } + importedCount = res.importedCount + return res.result + }) + return importedCount + }, [persistSnippets]) + + const handleOpenImport = useCallback(() => { + push() + }, [push, handleImportJson]) + + const handleToggleSortMode = useCallback(() => { + setSortMode((prev) => (prev === 'frequent' ? 'recent' : 'frequent')) + }, []) + const filteredSnippets = useMemo(() => { const q = searchText.trim().toLowerCase() - return snippets.filter((item: SnippetItem) => { + const matched = snippets.filter((item: SnippetItem) => { if (categoryFilter !== 'all' && (item.category || 'general') !== categoryFilter) { return false } @@ -277,12 +394,41 @@ export function Snippets({ featureCode = 'snippets-all', initialSnippets }: Snip item.content.toLowerCase().includes(q) ) }) - }, [snippets, searchText, categoryFilter]) + return sortSnippets(matched, sortMode) + }, [snippets, searchText, categoryFilter, sortMode]) if (isLoading || loadError) { return } + const globalActions = ( + <> + push()} + /> + + + + + ) + return ( - push()} - /> - - } + actions={{globalActions}} searchBarAccessory={ push()} /> + } /> @@ -360,7 +503,7 @@ export function Snippets({ featureCode = 'snippets-all', initialSnippets }: Snip ]} detail={ ) } /> - push()} - /> + {globalActions} (['invoice', 'address', 'customer_service', 'code', 'general']) + +export type SnippetSortMode = 'frequent' | 'recent' + +/** 按使用频次(默认)或最近更新时间排序;同值保持原有相对顺序 */ +export function sortSnippets(items: SnippetItem[], mode: SnippetSortMode = 'frequent'): SnippetItem[] { + return [...items].sort((a, b) => { + if (mode === 'recent') { + return (b.updatedAt || 0) - (a.updatedAt || 0) + } + const countDiff = (b.useCount || 0) - (a.useCount || 0) + if (countDiff !== 0) return countDiff + return 0 + }) +} + +export function exportSnippetsJson(items: SnippetItem[]): string { + return JSON.stringify(items, null, 2) +} + +export type ImportSnippetsResult = + | { success: true; importedCount: number; skippedCount: number; result: SnippetItem[] } + | { success: false; importedCount: number; skippedCount: number; result: SnippetItem[]; error: string } + +export function importSnippetsJson( + jsonStr: string, + existing: SnippetItem[], + nowMs = Date.now() +): ImportSnippetsResult { + try { + const parsed = JSON.parse(String(jsonStr ?? '')) as unknown + const rawList = Array.isArray(parsed) + ? parsed + : (parsed && typeof parsed === 'object' && Array.isArray((parsed as { items?: unknown }).items) + ? (parsed as { items: unknown[] }).items + : null) + if (!rawList) { + return { success: false, importedCount: 0, skippedCount: 0, result: existing, error: t('errImportNotArray') } + } + + const existingIds = new Set(existing.map((item) => item.id)) + const merged = [...existing] + let importedCount = 0 + let skippedCount = 0 + + for (const raw of rawList) { + if (!raw || typeof raw !== 'object') { + skippedCount++ + continue + } + const record = raw as Record + const title = typeof record.title === 'string' ? record.title.trim() : '' + const content = typeof record.content === 'string' ? record.content : '' + if (!title || !content.trim()) { + skippedCount++ + continue + } + const rawId = typeof record.id === 'string' ? record.id.trim() : '' + const id = rawId || `snip-import-${nowMs}-${importedCount + 1}` + if (existingIds.has(id)) { + skippedCount++ + continue + } + const rawCat = typeof record.category === 'string' ? (record.category as SnippetCategory) : 'general' + const category: SnippetCategory = VALID_CATEGORIES.has(rawCat) ? rawCat : 'general' + const keyword = typeof record.keyword === 'string' && record.keyword.trim() ? record.keyword.trim() : undefined + const useCount = typeof record.useCount === 'number' && Number.isFinite(record.useCount) && record.useCount >= 0 + ? Math.floor(record.useCount) + : 0 + const updatedAt = typeof record.updatedAt === 'number' && Number.isFinite(record.updatedAt) && record.updatedAt > 0 + ? record.updatedAt + : nowMs + const nextItem: SnippetItem = { + id, + title, + category, + categoryLabel: getSnippetCategoryLabel(category), + keyword, + content, + previewText: content.trim().replace(/\s+/g, ' ').slice(0, 72), + useCount, + updatedAt + } + merged.push(nextItem) + existingIds.add(id) + importedCount++ + } + + return { success: true, importedCount, skippedCount, result: merged } + } catch { + return { + success: false, + importedCount: 0, + skippedCount: 0, + result: existing, + error: t('errImportJsonParse') + } + } +} + export function parseStoredSnippets(raw: unknown): SnippetItem[] { if (raw === undefined) return [] if (typeof raw !== 'string') throw new Error(t('errInvalidStorageFormat')) diff --git a/extensions/snippets/tests/actions.test.mjs b/extensions/snippets/tests/actions.test.mjs index 3639eecb..4196260c 100644 --- a/extensions/snippets/tests/actions.test.mjs +++ b/extensions/snippets/tests/actions.test.mjs @@ -351,3 +351,75 @@ test('回归:分类筛选下拉框包含默认分类 general,可单独筛出 view.unmount() } }) + +test('使用频次排序:默认按 useCount 降序,使用后自动排前并支持切换按最近更新排序', async () => { + const host = createHost() + seed(host, [ + { ...fixture('低频条', 'general'), useCount: 1, updatedAt: 200 }, + { ...fixture('高频条', 'invoice'), useCount: 5, updatedAt: 100 } + ]) + const view = await mount(Snippets) + try { + assert.deepEqual(view.items().map((i) => i.props.id), ['高频条', '低频条']) + await view.run(null, '切换为按最近更新排序') + assert.deepEqual(view.items().map((i) => i.props.id), ['低频条', '高频条']) + await view.run(null, '切换为按使用频次排序') + assert.deepEqual(view.items().map((i) => i.props.id), ['高频条', '低频条']) + } finally { view.unmount() } +}) + +test('JSON 导出备份与导入恢复闭环(拒绝非法 JSON,保留已有同 ID 短语)', async () => { + const host = createHost() + seed(host, [fixture('原始短语', 'invoice')]) + const view = await mount(Snippets) + try { + await view.run(null, '导出全部为 JSON') + const exported = JSON.parse(host.clipboard.text) + assert.equal(exported.length, 1) + assert.equal(exported[0].id, '原始短语') + assert.equal(host.lastToast().style, 'SUCCESS') + + await view.run(null, '导入 JSON 备份') + const form = await mountPushed(host) + try { + await form.fill('json', '{broken') + await form.run(null, '确认导入') + assert.equal(host.lastToast().style, 'FAILURE') + assert.equal(host.pushed.length, 1) + + const backup = [ + { id: '原始短语', title: '不应覆盖', content: '覆盖内容', category: 'general' }, + { id: 'imp-addr', title: '导入地址', content: '北京市朝阳区', category: 'address', keyword: 'bj' } + ] + await form.fill('json', JSON.stringify(backup)) + await form.run(null, '确认导入') + assert.equal(host.pushed.length, 0) + assert.equal(host.lastToast().style, 'SUCCESS') + } finally { form.unmount() } + + const all = saved(host) + assert.equal(all.length, 2) + assert.equal(all.find((i) => i.id === '原始短语')?.title, '原始短语') + assert.equal(all.find((i) => i.id === 'imp-addr')?.title, '导入地址') + } finally { view.unmount() } +}) + +test('宏展开预览:带动态宏的短语在右侧 Detail 同时呈现模板原文与实时宏展开预览', async () => { + const host = createHost() + host.clipboard.text = '发票抬头ABC' + seed(host, [ + { ...fixture('带宏短语', 'invoice'), content: '抬头:{clipboard},日期:{date}' }, + { ...fixture('纯文本短语', 'general'), content: '固定收件地址' } + ]) + const view = await mount(Snippets) + try { + await tick() + const macroMd = view.item('带宏短语').props.detail.props.markdown + assert.match(macroMd, /模板原文/) + assert.match(macroMd, /宏展开预览/) + assert.match(macroMd, /抬头:发票抬头ABC,日期:\d{4}-\d{2}-\d{2}/) + + const plainMd = view.item('纯文本短语').props.detail.props.markdown + assert.doesNotMatch(plainMd, /宏展开预览/) + } finally { view.unmount() } +}) diff --git a/extensions/sql-helper/plugin.json b/extensions/sql-helper/plugin.json index a0379f8a..c7640e48 100644 --- a/extensions/sql-helper/plugin.json +++ b/extensions/sql-helper/plugin.json @@ -1,7 +1,7 @@ { "id": "sql-helper", "name": "SQL格式化转换", - "version": "1.0.5", + "version": "1.0.6", "minAppVersion": "1.1.8.0", "description": "SQL美化与精简、MyBatis日志参数核对、CREATE TABLE转TypeScript/Go/Java模型;支持多行编辑与剪贴板输入", "author": "ZTools Team", diff --git a/extensions/sql-helper/src/ddl-service.ts b/extensions/sql-helper/src/ddl-service.ts index 92c23759..addb4c62 100644 --- a/extensions/sql-helper/src/ddl-service.ts +++ b/extensions/sql-helper/src/ddl-service.ts @@ -1,56 +1,143 @@ import { t } from './i18n.js' -import type { DdlParsedColumn, DdlParsedResult, SqlDialect } from './types.js' +import type { + DdlCodegenOptions, + DdlParsedColumn, + DdlParsedResult, + DdlTableResult, + SqlDialect, +} from './types.js' import { sqlIdentifier, tokenizeSql, type SqlToken } from './sql-lexer.js' type TokenList = SqlToken[] -const upper = (t: SqlToken | undefined) => t?.kind === 'word' ? t.text.toUpperCase() : '' +const upper = (tok: SqlToken | undefined): string => (tok?.kind === 'word' ? tok.text.toUpperCase() : '') + function databaseName(token: SqlToken | undefined, dialect: SqlDialect): string { const name = sqlIdentifier(token) - return dialect === 'postgresql' && token?.kind === 'word' ? name.replace(/[A-Z]/g, char => char.toLowerCase()) : name + return dialect === 'postgresql' && token?.kind === 'word' + ? name.replace(/[A-Z]/g, char => char.toLowerCase()) + : name } + function splitDefinitions(tokens: TokenList): TokenList[] { - const result: TokenList[] = []; let depth = 0, start = 0 + const result: TokenList[] = [] + let depth = 0 + let start = 0 for (let i = 0; i < tokens.length; i++) { - const t = tokens[i]! - if (t.text === '(') depth++ - if (t.text === ')') depth-- - if (t.text === ',' && depth === 0) { result.push(tokens.slice(start, i)); start = i + 1 } + const tok = tokens[i]! + if (tok.text === '(') depth++ + if (tok.text === ')') depth-- + if (tok.text === ',' && depth === 0) { + result.push(tokens.slice(start, i)) + start = i + 1 + } } result.push(tokens.slice(start)) if (result.some(part => !part.length)) throw new Error(t('emptyColumnDef')) return result } + function commentValue(token: SqlToken, dialect: SqlDialect): string { const quote = token.text[0] - if (token.kind !== 'quoted' || (quote !== "'" && !(dialect === 'mysql' && quote === '"'))) throw new Error(t('commentNeedsString')) + if (token.kind !== 'quoted' || (quote !== "'" && !(dialect === 'mysql' && quote === '"'))) { + throw new Error(t('commentNeedsString')) + } let value = token.text.slice(1, -1).split(quote + quote).join(quote) - if (dialect === 'mysql') value = value.replace(/\\([\s\S])/g, (_, c: string) => ({ n: '\n', r: '\r', t: '\t', '0': '\0', b: '\b', Z: '\x1a' }[c] ?? c)) + if (dialect === 'mysql') { + value = value.replace( + /\\([\s\S])/g, + (_, c: string) => ({ n: '\n', r: '\r', t: '\t', '0': '\0', b: '\b', Z: '\x1a' }[c] ?? c) + ) + } return value } + function readColumn(tokens: TokenList, dialect: SqlDialect): DdlParsedColumn { const name = databaseName(tokens[0], dialect) if (tokens[1]?.kind !== 'word') throw new Error(t('colMissingType', { name })) - let i = 2, dbType = upper(tokens[1]) + let i = 2 + let dbType = upper(tokens[1]) if (tokens[i]?.text === '(') { - const begin = i++; let depth = 1 - while (i < tokens.length && depth) { if (tokens[i]!.text === '(') depth++; if (tokens[i]!.text === ')') depth--; i++ } + const begin = i++ + let depth = 1 + while (i < tokens.length && depth) { + if (tokens[i]!.text === '(') depth++ + if (tokens[i]!.text === ')') depth-- + i++ + } if (depth || i === begin + 2) throw new Error(t('colIncompleteTypeParams', { name })) - dbType += tokens.slice(begin, i).map(t => t.text).join('') + dbType += tokens.slice(begin, i).map(tok => tok.text).join('') } - for (const phrase of [['DOUBLE', 'PRECISION'], ['CHARACTER', 'VARYING'], ['TIMESTAMP', 'WITH', 'TIME', 'ZONE'], ['TIMESTAMP', 'WITHOUT', 'TIME', 'ZONE'], ['TIME', 'WITH', 'TIME', 'ZONE'], ['TIME', 'WITHOUT', 'TIME', 'ZONE']]) { - if (dbType === phrase[0] && phrase.slice(1).every((word, n) => upper(tokens[i + n]) === word)) { dbType = phrase.join(' '); i += phrase.length - 1; break } + for (const phrase of [ + ['DOUBLE', 'PRECISION'], + ['CHARACTER', 'VARYING'], + ['TIMESTAMP', 'WITH', 'TIME', 'ZONE'], + ['TIMESTAMP', 'WITHOUT', 'TIME', 'ZONE'], + ['TIME', 'WITH', 'TIME', 'ZONE'], + ['TIME', 'WITHOUT', 'TIME', 'ZONE'], + ]) { + if (dbType === phrase[0] && phrase.slice(1).every((word, n) => upper(tokens[i + n]) === word)) { + dbType = phrase.join(' ') + i += phrase.length - 1 + break + } } if (tokens[i]?.text === '(') { - const begin = i++; let depth = 1 - while (i < tokens.length && depth) { if (tokens[i]!.text === '(') depth++; if (tokens[i]!.text === ')') depth--; i++ } + const begin = i++ + let depth = 1 + while (i < tokens.length && depth) { + if (tokens[i]!.text === '(') depth++ + if (tokens[i]!.text === ')') depth-- + i++ + } if (depth) throw new Error(t('colIncompleteTypeParams', { name })) - dbType += tokens.slice(begin, i).map(t => t.text).join('') + dbType += tokens.slice(begin, i).map(tok => tok.text).join('') } - if (dialect === 'postgresql' && ['WITH', 'WITHOUT'].includes(upper(tokens[i])) && upper(tokens[i + 1]) === 'TIME' && upper(tokens[i + 2]) === 'ZONE') { dbType += ' ' + tokens.slice(i, i + 3).map(upper).join(' '); i += 3 } - while (tokens[i]?.text === '[' && tokens[i + 1]?.text === ']') { dbType += '[]'; i += 2 } - let nullable = !((dialect === 'postgresql' && /^(SMALLSERIAL|SERIAL|BIGSERIAL)$/.test(dbType)) || (dialect === 'mysql' && dbType === 'SERIAL')), comment: string | undefined, unsigned = dialect === 'mysql' && dbType === 'SERIAL' + if ( + dialect === 'postgresql' && + ['WITH', 'WITHOUT'].includes(upper(tokens[i])) && + upper(tokens[i + 1]) === 'TIME' && + upper(tokens[i + 2]) === 'ZONE' + ) { + dbType += ' ' + tokens.slice(i, i + 3).map(upper).join(' ') + i += 3 + } + while (tokens[i]?.text === '[' && tokens[i + 1]?.text === ']') { + dbType += '[]' + i += 2 + } + let nullable = !( + (dialect === 'postgresql' && /^(SMALLSERIAL|SERIAL|BIGSERIAL)$/.test(dbType)) || + (dialect === 'mysql' && dbType === 'SERIAL') + ) + let comment: string | undefined + let unsigned = dialect === 'mysql' && dbType === 'SERIAL' + let isPrimaryKey = false const rest = tokens.slice(i) - if (rest.length && !['NOT', 'NULL', 'DEFAULT', 'PRIMARY', 'UNIQUE', 'REFERENCES', 'CHECK', 'CONSTRAINT', 'COLLATE', 'COMMENT', 'AUTO_INCREMENT', 'AUTOINCREMENT', 'UNSIGNED', 'ZEROFILL', 'GENERATED', 'AS', 'CHARACTER'].includes(upper(rest[0]))) throw new Error(t('colUnknownAttr', { name, token: rest[0]!.text })) + if ( + rest.length && + ![ + 'NOT', + 'NULL', + 'DEFAULT', + 'PRIMARY', + 'UNIQUE', + 'REFERENCES', + 'CHECK', + 'CONSTRAINT', + 'COLLATE', + 'COMMENT', + 'AUTO_INCREMENT', + 'AUTOINCREMENT', + 'UNSIGNED', + 'ZEROFILL', + 'GENERATED', + 'AS', + 'CHARACTER', + 'ON', + ].includes(upper(rest[0])) + ) { + throw new Error(t('colUnknownAttr', { name, token: rest[0]!.text })) + } let level = 0 for (let n = 0; n < rest.length; n++) { const token = rest[n]! @@ -59,7 +146,12 @@ function readColumn(tokens: TokenList, dialect: SqlDialect): DdlParsedColumn { if (level) continue const word = upper(token) if (word === 'NOT' && upper(rest[n + 1]) === 'NULL') nullable = false - if (word === 'PRIMARY' && upper(rest[n + 1]) === 'KEY' && (dialect !== 'sqlite' || (dbType === 'INTEGER' && upper(rest[n + 2]) !== 'DESC'))) nullable = false + if (word === 'PRIMARY' && upper(rest[n + 1]) === 'KEY') { + isPrimaryKey = true + if (dialect !== 'sqlite' || (dbType === 'INTEGER' && upper(rest[n + 2]) !== 'DESC')) { + nullable = false + } + } if (word === 'UNSIGNED' || (dialect === 'mysql' && word === 'ZEROFILL')) unsigned = true if (word === 'COMMENT') { if (!rest[n + 1]) throw new Error(t('colMissingComment', { name })) @@ -67,35 +159,98 @@ function readColumn(tokens: TokenList, dialect: SqlDialect): DdlParsedColumn { } if (word === 'DEFAULT' && !rest[n + 1]) throw new Error(t('colMissingDefault', { name })) } - return { name, dbType, nullable, comment, unsigned } + return { name, dbType, nullable, comment, unsigned, isPrimaryKey } +} + +function splitDdlStatements(tokens: TokenList): TokenList[] { + const statements: TokenList[] = [] + let depth = 0 + let start = 0 + for (let i = 0; i < tokens.length; i++) { + const tok = tokens[i]! + if (tok.text === '(') depth++ + else if (tok.text === ')') depth-- + else if (tok.text === ';' && depth === 0) { + const slice = tokens.slice(start, i) + if (slice.length > 0) statements.push(slice) + start = i + 1 + } + } + const tail = tokens.slice(start) + if (tail.length > 0) statements.push(tail) + return statements } -function extractColumns(text: string, dialect: SqlDialect): { tableName: string; columns: DdlParsedColumn[] } { - const tokens = tokenizeSql(text, dialect).filter(t => t.kind !== 'comment' && t.kind !== 'lineComment') + +function extractSingleTable(tokens: TokenList, dialect: SqlDialect): { tableName: string; columns: DdlParsedColumn[] } { let i = 0 - const take = (word: string) => { if (upper(tokens[i++]) !== word) throw new Error(t('needKeywordInCreate', { word })) } + const take = (word: string) => { + if (upper(tokens[i++]) !== word) throw new Error(t('needKeywordInCreate', { word })) + } take('CREATE') if (['TEMP', 'TEMPORARY'].includes(upper(tokens[i]))) i++ take('TABLE') - if (upper(tokens[i]) === 'IF') { i++; take('NOT'); take('EXISTS') } + if (upper(tokens[i]) === 'IF') { + i++ + take('NOT') + take('EXISTS') + } let tableName = databaseName(tokens[i++], dialect) - if (tokens[i]?.text === '.') { i++; tableName = databaseName(tokens[i++], dialect) } + if (tokens[i]?.text === '.') { + i++ + tableName = databaseName(tokens[i++], dialect) + } if (tokens[i++]?.text !== '(') throw new Error(t('needCreateParens')) - const begin = i; let depth = 1 - while (i < tokens.length && depth) { if (tokens[i]!.text === '(') depth++; if (tokens[i]!.text === ')') depth--; i++ } + const begin = i + let depth = 1 + while (i < tokens.length && depth) { + if (tokens[i]!.text === '(') depth++ + if (tokens[i]!.text === ')') depth-- + i++ + } if (depth) throw new Error(t('unclosedColParens')) - const definitions = splitDefinitions(tokens.slice(begin, i - 1)), tail = tokens.slice(i) - if (tail.some((t, n) => t.text === ';' && n !== tail.length - 1) || tail.some(t => ['CREATE', 'SELECT', 'INSERT', 'ALTER', 'DROP'].includes(upper(t)))) throw new Error(t('singleTableOnly')) - if (tail.length && tail[0]!.text !== ';' && !['ENGINE', 'DEFAULT', 'CHARSET', 'CHARACTER', 'COLLATE', 'COMMENT', 'AUTO_INCREMENT', 'WITHOUT', 'STRICT'].includes(upper(tail[0]))) throw new Error(t('unrecognizedTableTail')) - const columns: DdlParsedColumn[] = [], primary: string[] = [] + const definitions = splitDefinitions(tokens.slice(begin, i - 1)) + const tail = tokens.slice(i) + if (tail.some(tok => ['CREATE', 'SELECT', 'INSERT', 'ALTER', 'DROP'].includes(upper(tok)))) { + throw new Error(t('singleTableOnly')) + } + if ( + tail.length && + ![ + 'ENGINE', + 'DEFAULT', + 'CHARSET', + 'CHARACTER', + 'COLLATE', + 'COMMENT', + 'AUTO_INCREMENT', + 'WITHOUT', + 'STRICT', + 'ROW_FORMAT', + ].includes(upper(tail[0])) + ) { + throw new Error(t('unrecognizedTableTail')) + } + const columns: DdlParsedColumn[] = [] + const primary: string[] = [] for (const definition of definitions) { let d = definition - if (upper(d[0]) === 'CONSTRAINT') { sqlIdentifier(d[1]); d = d.slice(2) } + if (upper(d[0]) === 'CONSTRAINT') { + sqlIdentifier(d[1]) + d = d.slice(2) + } const keyword = upper(d[0]) if (['PRIMARY', 'FOREIGN', 'UNIQUE', 'CHECK', 'KEY', 'INDEX', 'FULLTEXT', 'SPATIAL'].includes(keyword)) { - if (!d.some(t => t.text === '(')) throw new Error(t('incompleteTableConstraint')) + if (!d.some(tok => tok.text === '(')) throw new Error(t('incompleteTableConstraint')) if (keyword === 'PRIMARY') { - if (upper(d[1]) !== 'KEY' || d[2]?.text !== '(' || d.at(-1)?.text !== ')') throw new Error(t('unrecognizedPrimaryKey')) - primary.push(...splitDefinitions(d.slice(3, -1)).map(part => { if (part.length !== 1) throw new Error(t('unrecognizedPrimaryCol')); return databaseName(part[0], dialect) })) + if (upper(d[1]) !== 'KEY' || d[2]?.text !== '(' || d.at(-1)?.text !== ')') { + throw new Error(t('unrecognizedPrimaryKey')) + } + primary.push( + ...splitDefinitions(d.slice(3, -1)).map(part => { + if (part.length !== 1) throw new Error(t('unrecognizedPrimaryCol')) + return databaseName(part[0], dialect) + }) + ) } continue } @@ -106,11 +261,21 @@ function extractColumns(text: string, dialect: SqlDialect): { tableName: string; for (const name of primary) { const col = columns.find(c => c.name === name) if (!col) throw new Error(t('missingPrimaryCol', { name })) - if (dialect !== 'sqlite' || primary.length === 1 && col.dbType === 'INTEGER' || tail.some(t => ['WITHOUT', 'STRICT'].includes(upper(t)))) col.nullable = false + col.isPrimaryKey = true + if ( + dialect !== 'sqlite' || + (primary.length === 1 && col.dbType === 'INTEGER') || + tail.some(tok => ['WITHOUT', 'STRICT'].includes(upper(tok))) + ) { + col.nullable = false + } } - if (dialect === 'sqlite' && tail.some(t => ['WITHOUT', 'STRICT'].includes(upper(t)))) { + if (dialect === 'sqlite' && tail.some(tok => ['WITHOUT', 'STRICT'].includes(upper(tok)))) { for (const definition of definitions) { - if (definition.some((t, n) => upper(t) === 'PRIMARY' && upper(definition[n + 1]) === 'KEY') && !['PRIMARY', 'CONSTRAINT'].includes(upper(definition[0]))) { + if ( + definition.some((tok, n) => upper(tok) === 'PRIMARY' && upper(definition[n + 1]) === 'KEY') && + !['PRIMARY', 'CONSTRAINT'].includes(upper(definition[0])) + ) { const col = columns.find(c => c.name === databaseName(definition[0], dialect)) if (col) col.nullable = false } @@ -119,68 +284,273 @@ function extractColumns(text: string, dialect: SqlDialect): { tableName: string; return { tableName, columns } } -function types(column: DdlParsedColumn, dialect: SqlDialect): { ts: string; go: string; java: string; known: boolean } { - const type = column.dbType.toUpperCase(), base = type.split(/[ (]/)[0]! +function mapColumnTypes( + column: DdlParsedColumn, + dialect: SqlDialect +): { ts: string; go: string; java: string; known: boolean } { + const type = column.dbType.toUpperCase() + const base = type.split(/[ (]/)[0]! if (type.endsWith('[]')) return { ts: 'unknown', go: 'string', java: 'Object', known: false } - if (/^(DECIMAL|NUMERIC|NUMBER|MONEY)$/.test(base)) return { ts: 'string', go: 'string', java: 'BigDecimal', known: true } - if (/^(BIGINT|BIGSERIAL|INT8)$/.test(base) || (dialect === 'mysql' && base === 'SERIAL')) return { ts: 'string', go: column.unsigned ? 'uint64' : 'int64', java: column.unsigned ? 'BigInteger' : 'Long', known: true } - if (/^(BOOL|BOOLEAN)$/.test(base) && dialect !== 'mysql') return { ts: 'boolean', go: 'bool', java: 'Boolean', known: true } - if (/^(INT|INTEGER|SMALLINT|TINYINT|MEDIUMINT|SERIAL|SMALLSERIAL|INT2|INT4|BOOL|BOOLEAN)$/.test(base)) return { ts: dialect === 'sqlite' ? 'string' : 'number', go: column.unsigned ? 'uint64' : 'int64', java: column.unsigned || dialect === 'sqlite' ? 'Long' : 'Integer', known: true } + if (/^(DECIMAL|NUMERIC|NUMBER|MONEY)$/.test(base)) { + return { ts: 'string', go: 'string', java: 'BigDecimal', known: true } + } + if (/^(BIGINT|BIGSERIAL|INT8)$/.test(base) || (dialect === 'mysql' && base === 'SERIAL')) { + return { + ts: 'string', + go: column.unsigned ? 'uint64' : 'int64', + java: column.unsigned ? 'BigInteger' : 'Long', + known: true, + } + } + if (/^(BOOL|BOOLEAN)$/.test(base) && dialect !== 'mysql') { + return { ts: 'boolean', go: 'bool', java: 'Boolean', known: true } + } + if (/^(INT|INTEGER|SMALLINT|TINYINT|MEDIUMINT|SERIAL|SMALLSERIAL|INT2|INT4|BOOL|BOOLEAN)$/.test(base)) { + return { + ts: dialect === 'sqlite' ? 'string' : 'number', + go: column.unsigned ? 'uint64' : 'int64', + java: column.unsigned || dialect === 'sqlite' ? 'Long' : 'Integer', + known: true, + } + } if (/^(FLOAT|REAL|DOUBLE)$/.test(base)) return { ts: 'number', go: 'float64', java: 'Double', known: true } if (dialect === 'mysql' && base === 'TIME') return { ts: 'string', go: 'string', java: 'String', known: true } - if (/^(TIMESTAMP|TIMESTAMPTZ|DATETIME|DATE|TIME|TIMETZ)$/.test(base)) return { ts: 'string', go: 'time.Time', java: base === 'DATE' ? 'LocalDate' : /TIME ZONE/.test(type) && !/WITHOUT/.test(type) || /^(TIMESTAMPTZ|TIMETZ)$/.test(base) ? (base.startsWith('TIMESTAMP') ? 'OffsetDateTime' : 'OffsetTime') : /^(TIME|TIMETZ)$/.test(base) ? 'LocalTime' : 'LocalDateTime', known: true } + if (/^(TIMESTAMP|TIMESTAMPTZ|DATETIME|DATE|TIME|TIMETZ)$/.test(base)) { + return { + ts: 'string', + go: 'time.Time', + java: + base === 'DATE' + ? 'LocalDate' + : (/TIME ZONE/.test(type) && !/WITHOUT/.test(type)) || /^(TIMESTAMPTZ|TIMETZ)$/.test(base) + ? base.startsWith('TIMESTAMP') + ? 'OffsetDateTime' + : 'OffsetTime' + : /^(TIME|TIMETZ)$/.test(base) + ? 'LocalTime' + : 'LocalDateTime', + known: true, + } + } if (/^(JSON|JSONB)$/.test(base)) return { ts: 'unknown', go: 'json.RawMessage', java: 'Object', known: true } - if (/^(BLOB|TINYBLOB|MEDIUMBLOB|LONGBLOB|BINARY|VARBINARY|BYTEA)$/.test(base)) return { ts: 'Uint8Array', go: '[]byte', java: 'byte[]', known: true } - const known = /^(CHAR|CHARACTER|VARCHAR|NVARCHAR|NCHAR|TEXT|TINYTEXT|MEDIUMTEXT|LONGTEXT|CLOB|UUID|ENUM|SET)$/.test(base) + if (/^(BLOB|TINYBLOB|MEDIUMBLOB|LONGBLOB|BINARY|VARBINARY|BYTEA)$/.test(base)) { + return { ts: 'Uint8Array', go: '[]byte', java: 'byte[]', known: true } + } + const known = /^(CHAR|CHARACTER|VARCHAR|NVARCHAR|NCHAR|TEXT|TINYTEXT|MEDIUMTEXT|LONGTEXT|CLOB|UUID|ENUM|SET)$/.test( + base + ) return { ts: known ? 'string' : 'unknown', go: 'string', java: known ? 'String' : 'Object', known } } + function identifier(name: string, pascal: boolean): string { const parts = name.replace(/[^A-Za-z0-9_]/g, '_').split('_').filter(Boolean) - let value = parts.map((p, n) => n || pascal ? p[0]!.toUpperCase() + p.slice(1) : p[0]!.toLowerCase() + p.slice(1)).join('') || 'Field' + let value = + parts.map((p, n) => (n || pascal ? p[0]!.toUpperCase() + p.slice(1) : p[0]!.toLowerCase() + p.slice(1))).join('') || + 'Field' if (/^\d/.test(value)) value = `Field${value}` return value } -const JAVA_RESERVED = new Set('abstract assert boolean break byte case catch char class const continue default do double else enum extends final finally float for goto if implements import instanceof int interface long native new package private protected public return short static strictfp super switch synchronized this throw throws transient try void volatile while true false null var record yield sealed permits'.split(' ')) -function safeComment(text: string): string { return text.replace(/[\r\n\u0000-\u001f\u007f\u2028\u2029]/g, ' ').replace(/\\/g, '/').replace(/\*\//g, '* /') } -function generate(tableName: string, columns: DdlParsedColumn[], dialect: SqlDialect): Pick { - const model = identifier(tableName.replace(/^(?:t_|tb_)/i, ''), true) + 'Model' - const warnings = [t('ddlSkeletonWarn')] - const ts = [`export interface ${model} {`], go: string[] = [], java: string[] = [], goImports = new Set(), javaImports = new Set() - const goNames = new Set(), javaNames = new Set() + +const JAVA_RESERVED = new Set( + 'abstract assert boolean break byte case catch char class const continue default do double else enum extends final finally float for goto if implements import instanceof int interface long native new package private protected public return short static strictfp super switch synchronized this throw throws transient try void volatile while true false null var record yield sealed permits'.split( + ' ' + ) +) + +const TS_VALID_IDENT = /^[A-Za-z_$][A-Za-z0-9_$]*$/ + +function safeComment(text: string): string { + return text.replace(/[\r\n\u0000-\u001f\u007f\u2028\u2029]/g, ' ').replace(/\\/g, '/').replace(/\*\//g, '* /') +} + +interface GeneratedTableParts { + modelName: string + tsBlock: string + goImports: Set + goBlock: string + javaImports: Set + javaBlock: string + warnings: string[] +} + +function generateTableParts( + tableName: string, + columns: DdlParsedColumn[], + dialect: SqlDialect, + options: Required +): GeneratedTableParts { + const modelName = identifier(tableName.replace(/^(?:t_|tb_)/i, ''), true) + 'Model' + const warnings: string[] = [] + const tsLines = [`export interface ${modelName} {`] + const goFields: string[] = [] + const javaFields: string[] = [] + const goImports = new Set() + const javaImports = new Set() + const tsNames = new Set() + const goNames = new Set() + const javaNames = new Set() + + if (options.javaLombok) javaImports.add('lombok.Data') + if (options.javaMybatisPlus) { + javaImports.add('com.baomidou.mybatisplus.annotation.TableName') + if (columns.some(c => c.isPrimaryKey)) javaImports.add('com.baomidou.mybatisplus.annotation.TableId') + javaImports.add('com.baomidou.mybatisplus.annotation.TableField') + } + for (const [n, col] of columns.entries()) { - const mapped = types(col, dialect) + const mapped = mapColumnTypes(col, dialect) if (!mapped.known) warnings.push(t('ddlUnmappedTypeWarn', { name: col.name, dbType: col.dbType })) const comment = safeComment(`${col.name}: ${col.dbType}${col.comment ? ' — ' + col.comment : ''}`) - ts.push(` // ${comment}`, ` ${JSON.stringify(col.name)}: ${mapped.ts}${col.nullable && mapped.ts !== 'unknown' ? ' | null' : ''};`) - let goName = identifier(col.name, true), javaName = identifier(col.name, false) + + let tsProp: string + if (options.namingStyle === 'camel') { + let camel = identifier(col.name, false) + if (tsNames.has(camel)) camel += `Field${n + 1}` + while (tsNames.has(camel)) camel += '_' + tsNames.add(camel) + tsProp = TS_VALID_IDENT.test(camel) ? camel : JSON.stringify(camel) + } else { + tsProp = JSON.stringify(col.name) + } + tsLines.push(` // ${comment}`, ` ${tsProp}: ${mapped.ts}${col.nullable && mapped.ts !== 'unknown' ? ' | null' : ''};`) + + let goName = identifier(col.name, true) + let javaName = identifier(col.name, false) if (goNames.has(goName)) goName += `Field${n + 1}` while (goNames.has(goName)) goName += '_' if (JAVA_RESERVED.has(javaName)) javaName += 'Field' if (javaNames.has(javaName)) javaName += `Field${n + 1}` while (javaNames.has(javaName)) javaName += '_' - goNames.add(goName); javaNames.add(javaName) + goNames.add(goName) + javaNames.add(javaName) + if (mapped.go.startsWith('time.')) goImports.add('time') if (mapped.go.startsWith('json.')) goImports.add('encoding/json') - const validJsonName = [...col.name].every(char => /[\p{L}\p{Nd}]/u.test(char) || '!#$%&()*+-./:<=>?@[]^_{|}~ '.includes(char)) - if (!col.name || !validJsonName || col.name === '-' || /[;\\]/.test(col.name)) throw new Error(t('ddlUnsafeGoTag', { name: col.name })) - const tags = `json:${JSON.stringify(col.name)} gorm:${JSON.stringify('column:' + col.name)}` - go.push(` // ${comment}`, ` ${goName} ${col.nullable ? '*' : ''}${mapped.go} ${JSON.stringify(tags)}`) + + const validJsonName = [...col.name].every( + char => /[\p{L}\p{Nd}]/u.test(char) || '!#$%&()*+-./:<=>?@[]^_{|}~ '.includes(char) + ) + if (!col.name || !validJsonName || col.name === '-' || /[;\\]/.test(col.name)) { + throw new Error(t('ddlUnsafeGoTag', { name: col.name })) + } + const jsonKey = options.namingStyle === 'camel' ? identifier(col.name, false) : col.name + const tags = options.goGormTag + ? `json:${JSON.stringify(jsonKey)} gorm:${JSON.stringify('column:' + col.name)}` + : `json:${JSON.stringify(jsonKey)}` + goFields.push(` // ${comment}`, ` ${goName} ${col.nullable ? '*' : ''}${mapped.go} ${JSON.stringify(tags)}`) + if (['BigInteger', 'BigDecimal'].includes(mapped.java)) javaImports.add(`java.math.${mapped.java}`) if (/^(Local|Offset)/.test(mapped.java)) javaImports.add(`java.time.${mapped.java}`) - java.push(` // ${comment}`, ` public ${mapped.java} ${javaName};`) - } - ts.push('}') - return { warnings, generatedCode: { - typescript: ts.join('\n'), - golang: ['package models', '', ...[...goImports].sort().map(p => `import ${JSON.stringify(p)}`), '', `type ${model} struct {`, ...go, '}'].join('\n'), - java: [...[...javaImports].sort().map(p => `import ${p};`), '', `public class ${model} {`, ...java, '}'].join('\n'), - } } + const javaVisibility = options.javaLombok ? 'private' : 'public' + javaFields.push(` // ${comment}`) + if (options.javaMybatisPlus) { + if (col.isPrimaryKey) { + javaFields.push(` @TableId(${JSON.stringify(col.name)})`) + } else { + javaFields.push(` @TableField(${JSON.stringify(col.name)})`) + } + } + javaFields.push(` ${javaVisibility} ${mapped.java} ${javaName};`) + } + tsLines.push('}') + + const javaAnnotations: string[] = [] + if (options.javaLombok) javaAnnotations.push('@Data') + if (options.javaMybatisPlus) javaAnnotations.push(`@TableName(${JSON.stringify(tableName)})`) + + return { + modelName, + tsBlock: tsLines.join('\n'), + goImports, + goBlock: [`type ${modelName} struct {`, ...goFields, '}'].join('\n'), + javaImports, + javaBlock: [...javaAnnotations, `public class ${modelName} {`, ...javaFields, '}'].join('\n'), + warnings, + } +} + +function assembleGoFile(imports: Set, blocks: string[]): string { + const importLines = [...imports].sort().map(p => `import ${JSON.stringify(p)}`) + return ['package models', '', ...importLines, '', blocks.join('\n\n')].join('\n') +} + +function assembleJavaFile(imports: Set, blocks: string[]): string { + const importLines = [...imports].sort().map(p => `import ${p};`) + return [...importLines, '', blocks.join('\n\n')].join('\n') } -export function parseDdlToEntities(rawDdl: string, dialect: SqlDialect = 'mysql'): DdlParsedResult { + +export function parseDdlToEntities( + rawDdl: string, + dialect: SqlDialect = 'mysql', + rawOptions: DdlCodegenOptions = {} +): DdlParsedResult { + const options: Required = { + namingStyle: rawOptions.namingStyle ?? 'snake', + javaLombok: rawOptions.javaLombok ?? false, + javaMybatisPlus: rawOptions.javaMybatisPlus ?? false, + goGormTag: rawOptions.goGormTag ?? true, + } try { - const parsed = extractColumns(rawDdl, dialect) - return { isValid: true, ...parsed, ...generate(parsed.tableName, parsed.columns, dialect) } + const tokens = tokenizeSql(rawDdl, dialect).filter(tok => tok.kind !== 'comment' && tok.kind !== 'lineComment') + const statements = splitDdlStatements(tokens) + if (statements.length === 0) throw new Error(t('needKeywordInCreate', { word: 'CREATE' })) + + const tables: DdlTableResult[] = [] + const allColumns: DdlParsedColumn[] = [] + const allWarnings: string[] = [t('ddlSkeletonWarn')] + const allGoImports = new Set() + const allJavaImports = new Set() + const tsBlocks: string[] = [] + const goBlocks: string[] = [] + const javaBlocks: string[] = [] + + for (const stmt of statements) { + const parsed = extractSingleTable(stmt, dialect) + const parts = generateTableParts(parsed.tableName, parsed.columns, dialect, options) + for (const imp of parts.goImports) allGoImports.add(imp) + for (const imp of parts.javaImports) allJavaImports.add(imp) + tsBlocks.push(parts.tsBlock) + goBlocks.push(parts.goBlock) + javaBlocks.push(parts.javaBlock) + allColumns.push(...parsed.columns) + allWarnings.push(...parts.warnings) + + tables.push({ + tableName: parsed.tableName, + columns: parsed.columns, + warnings: [t('ddlSkeletonWarn'), ...parts.warnings], + generatedCode: { + typescript: parts.tsBlock, + golang: assembleGoFile(parts.goImports, [parts.goBlock]), + java: assembleJavaFile(parts.javaImports, [parts.javaBlock]), + }, + }) + } + + const tableNames = tables.map(item => item.tableName) + return { + isValid: true, + tableName: tableNames[0] ?? '', + tableNames, + columns: allColumns, + tables, + warnings: allWarnings, + generatedCode: { + typescript: tsBlocks.join('\n\n'), + golang: assembleGoFile(allGoImports, goBlocks), + java: assembleJavaFile(allJavaImports, javaBlocks), + }, + } } catch (error) { - return { isValid: false, warningMessage: error instanceof Error ? error.message : String(error), tableName: '', columns: [], warnings: [], generatedCode: { typescript: '', golang: '', java: '' } } + return { + isValid: false, + warningMessage: error instanceof Error ? error.message : String(error), + tableName: '', + tableNames: [], + columns: [], + tables: [], + warnings: [], + generatedCode: { typescript: '', golang: '', java: '' }, + } } } diff --git a/extensions/sql-helper/src/host.ts b/extensions/sql-helper/src/host.ts new file mode 100644 index 00000000..db2c1d52 --- /dev/null +++ b/extensions/sql-helper/src/host.ts @@ -0,0 +1,99 @@ +import { getHostTransport } from '@ztools/declarative-ui' +import { t } from './i18n.js' + +interface SaveDialogData { + canceled?: boolean + filePath?: string +} + +let callSeq = 0 + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} + +function extractErrorMessage(envelope: unknown, fallback: string): string { + if (!isRecord(envelope)) return fallback + const err = envelope.error + if (isRecord(err)) { + const msg = err.message ?? err.code + if (typeof msg === 'string' && msg.trim()) return msg.trim() + } + if (typeof err === 'string' && err.trim()) return err.trim() + return fallback +} + +async function callHostMethod(method: string, params: Record, fallbackErr: string): Promise { + const transport = getHostTransport() + if (transport) { + return transport.call(method, params) + } + const g = globalThis as { + window?: { __ztoolsElectron?: { transport?: { methods?: Record } } } + __ztoolsElectron?: { transport?: { methods?: Record } } + } + const methods = g.window?.__ztoolsElectron?.transport?.methods ?? g.__ztoolsElectron?.transport?.methods + const fn = methods?.[method] + if (typeof fn !== 'function') { + throw new Error(fallbackErr) + } + callSeq = (callSeq + 1) % 1_000_000 + const envelope = await (fn as (req: Record) => Promise)({ + messageId: `sql_helper_${Date.now()}_${callSeq}`, + params, + }) + if (!isRecord(envelope) || envelope.success === false) { + throw new Error(extractErrorMessage(envelope, fallbackErr)) + } + return ('data' in envelope ? envelope.data : envelope) as T +} + +/** 弹出系统保存对话框并将文本内容以 UTF-8 写入目标文件;用户取消时返回 null。 */ +export async function saveTextToFile( + content: string, + defaultName: string, + filters: string +): Promise { + if (!content) throw new Error(t('saveEmptyContentError')) + const data = await callHostMethod( + 'window_show_save_dialog', + { + title: t('saveDialogTitle'), + defaultName, + filters, + }, + t('saveDialogFailed') + ) + if (!data || data.canceled || typeof data.filePath !== 'string' || !data.filePath.trim()) { + return null + } + const filePath = data.filePath.trim() + await callHostMethod( + 'filesystem_write_file', + { + path: filePath, + content, + encoding: 'utf8', + }, + t('saveWriteFailed') + ) + return filePath +} + +interface ReadFileData { + content?: string +} + +/** 以 UTF-8 读取用户拖入或显式选中的本地文本文件内容。 */ +export async function readTextFile(filePath: string): Promise { + const normalized = filePath.trim() + if (!normalized) throw new Error(t('readFileFailed')) + const data = await callHostMethod( + 'filesystem_read_file', + { path: normalized, encoding: 'utf8' }, + t('readFileFailed') + ) + if (typeof data === 'string') return data + if (isRecord(data) && typeof data.content === 'string') return data.content + throw new Error(t('readFileFailed')) +} diff --git a/extensions/sql-helper/src/i18n.ts b/extensions/sql-helper/src/i18n.ts index bb20f654..972519b1 100644 --- a/extensions/sql-helper/src/i18n.ts +++ b/extensions/sql-helper/src/i18n.ts @@ -1,187 +1,331 @@ -import { createTranslator } from "@ztools/declarative-ui"; +import { createTranslator } from '@ztools/declarative-ui' const MESSAGES = { - "zh-CN": { - modeFormatter: "SQL 美化与精简", - modeMybatis: "MyBatis 日志还原", - modeDdl: "建表语句转模型", - guideFormatterTitle: "载入 SQL 开始美化与精简", - guideFormatterDetail: "把 SQL 复制到剪贴板后按回车载入,或打开多行编辑器粘贴。\n\n同时输出美化和精简两种格式;保留大小写、字符串与注释,只调整排版,不检查数据库语法。可选择 MySQL、PostgreSQL 或 SQLite 方言。", - guideMybatisTitle: "载入 MyBatis 日志还原 SQL", - guideMybatisDetail: "需要同一次调用的 Preparing 和 Parameters 两行日志,复制后按回车载入,或打开多行编辑器粘贴。\n\n参数按所选方言转成字面量填回 SQL;日志是有损文本,日期、二进制及自定义类型需核对原始绑定。", - guideDdlTitle: "载入建表语句生成模型", - guideDdlDetail: "需要一条 CREATE TABLE 语句,一次处理一张表,复制后按回车载入,或打开多行编辑器粘贴。\n\n生成 TypeScript、Go 与 Java 模型代码。", - emptyInputError: "请先输入 SQL 或日志", - beautifiedTitle: "美化 SQL", - minifiedTitle: "精简空白", - formatterNotice: "保留大小写、字符串、注释与必要换行;仅排版,不验证数据库语法。", - mergedTitle: "参数还原参考 SQL", - mybatisNotice: "{paramCountDisplay}。日志是有损文本,日期、二进制及自定义类型需核对原始绑定。", - tsModelTitle: "TypeScript 模型", - goModelTitle: "Go 模型", - javaModelTitle: "Java 模型", - ddlNotice: "{tableName} · {count} 个字段\n{warnings}", - cannotGenerate: "无法生成结果", - generateResult: "生成结果", - sqlDialect: "SQL 方言", - dialectMysql: "MySQL(默认反斜杠转义)", - dialectPg: "PostgreSQL(标准字符串)", - dialectSqlite: "SQLite", - sourceMybatisLabel: "两行 MyBatis 日志", - sourceDdlLabel: "CREATE TABLE 语句", - sourceSqlLabel: "SQL 源码", - localOnlyHint: "只在本地处理,最多 256 KiB。", - generatedToast: "已生成结果", - generateFailedToast: "未能生成结果", - searchPlaceholder: "筛选结果;用编辑源码或载入剪贴板输入多行内容", - switchToolTooltip: "切换工具", - loadClipboard: "载入剪贴板", - editSource: "编辑源码", - inputErrorTitle: "输入无法处理", - emptyGuideSubtitle: "回车载入剪贴板,也可以打开多行编辑", - copyItem: "复制{title}", + 'zh-CN': { + modeFormatter: 'SQL 格式化与压缩', + modeMybatis: 'MyBatis 日志还原', + modeDdl: 'DDL 建表转实体', + guideFormatterTitle: '载入 SQL 开始美化与压缩', + guideFormatterDetail: + '把 SQL 复制到剪贴板后按回车载入,或打开多行编辑器粘贴。\n\n支持 SELECT 列换行、WHERE/HAVING 条件缩进、JOIN 对齐、CASE WHEN 与子查询多级缩进,同时输出单行压缩版本;严格保留字符串与注释内容。支持 MySQL、PostgreSQL 与 SQLite 方言。', + guideMybatisTitle: '载入 MyBatis 日志还原可执行 SQL', + guideMybatisDetail: + '可直接粘贴 IDE 控制台的混杂多行日志(含时间戳、INFO/DEBUG 前缀、Total/Updates 行),自动提取并逐组还原全部 Preparing + Parameters 为可读 SQL。\n\n参数按所选方言转成字面量;日志是有损文本,日期、二进制及自定义类型请核对原始绑定。', + guideDdlTitle: '载入 CREATE TABLE 生成实体模型', + guideDdlDetail: + '支持单张或多张 CREATE TABLE 建表语句批量转换,复制到剪贴板后按回车载入,或打开多行编辑器粘贴。\n\n生成 TypeScript、Go 与 Java 模型代码,支持驼峰/蛇形命名、Lombok @Data、MyBatis-Plus 与 GORM 标签配置。', + emptyInputError: '请先输入 SQL、MyBatis 日志或建表语句', + beautifiedTitle: '美化 SQL', + beautifiedSubtitle: '{lines} 行 · {chars} 字符 · {dialect}', + minifiedTitle: '压缩为单行 SQL', + minifiedSubtitle: '{chars} 字符 · 保留注释与必要换行', + formatterNotice: '词法安全排版({dialect} · {caseLabel});严格保护字符串、引用标识符与注释内容。', + mergedTitle: '参数还原参考 SQL', + mergedAllTitle: '全部还原 SQL 合并(共 {count} 组)', + mergedAllSubtitle: '已成功还原 {count} 组 SQL,可直接复制或另存为 .sql', + mybatisEntrySubtitle: '已配对 {count} 个参数 · 第 {prepLine}-{paramLine} 行', + mybatisEntryNoParamSubtitle: '无绑定参数 · 第 {prepLine}-{paramLine} 行', + mybatisEntryErrorSubtitle: '解析失败(第 {line} 行):{error}', + mybatisNotice: '共识别 {total} 组日志,成功 {success} 组{failPart}。日志是有损文本,日期、二进制及自定义类型需核对原始绑定。', + mybatisFailPart: ',异常 {failed} 组', + mybatisEntryDetailHeader: '来源:第 {prepLine} 行 Preparing / 第 {paramLine} 行 Parameters · {paramSummary}', + mybatisErrorDetail: '第 {line} 行解析失败:{error}', + tsModelTitle: 'TypeScript 模型', + goModelTitle: 'Go 模型', + javaModelTitle: 'Java 模型', + ddlModelSubtitle: '{tables} 张表 · {columns} 个字段 · {options}', + ddlTableSectionTitle: '单表模型明细', + ddlSingleTableTitle: '{tableName}({lang})', + ddlSingleTableSubtitle: '{columns} 个字段', + ddlNotice: '{tables} 张表({tableNames})· 共 {count} 个字段\n{warnings}', + cannotGenerate: '无法生成结果', + generateResult: '生成结果', + sqlDialect: 'SQL 方言', + dialectMysql: 'MySQL(默认反斜杠转义)', + dialectPg: 'PostgreSQL(标准字符串)', + dialectSqlite: 'SQLite', + dialectShortMysql: 'MySQL', + dialectShortPg: 'PostgreSQL', + dialectShortSqlite: 'SQLite', + keywordCaseLabel: '关键字大小写', + keywordCaseUpper: '统一大写(推荐)', + keywordCasePreserve: '保留原始大小写', + keywordCaseLower: '统一小写', + keywordCaseShortUpper: '关键字大写', + keywordCaseShortPreserve: '保留大小写', + keywordCaseShortLower: '关键字小写', + indentWidthLabel: '缩进宽度', + indent2: '2 空格', + indent4: '4 空格', + ddlNamingLabel: '字段命名风格', + ddlNamingCamel: '驼峰命名(camelCase)', + ddlNamingSnake: '保留原始列名(snake_case)', + ddlNamingShortCamel: '驼峰', + ddlNamingShortSnake: '原名', + ddlJavaLombokLabel: 'Java Lombok(@Data)', + ddlJavaLombokCheckbox: '启用 @Data 注解与 private 字段', + ddlJavaMpLabel: 'Java MyBatis-Plus', + ddlJavaMpCheckbox: '生成 @TableName / @TableId / @TableField', + ddlGoGormLabel: 'Go GORM 标签', + ddlGoGormCheckbox: '在 struct tag 中包含 gorm:"column:..."', + sourceMybatisLabel: 'MyBatis 日志(支持多行混杂控制台日志)', + sourceDdlLabel: 'CREATE TABLE 建表语句(支持多表批量)', + sourceSqlLabel: 'SQL 源码', + localOnlyHint: '全部在本地词法解析与转换,不上传任何数据,单次最多 256 KiB。', + generatedToast: '已生成结果', + generateFailedToast: '未能生成结果', + searchPlaceholder: '筛选产物结果;点击上方载入剪贴板或编辑 SQL 源码', + switchToolTooltip: '切换模式', + loadClipboard: '读取剪贴板', + loadDetectedClipboard: '一键解析载入', + editSource: '编辑 SQL', + inputErrorTitle: '输入无法处理', + emptyGuideSubtitle: '回车读取剪贴板,或打开多行编辑器输入', + clipboardDetectedMybatis: '检测到剪贴板含 MyBatis 日志({count} 组)', + clipboardDetectedDdl: '检测到剪贴板含建表 DDL({count} 张表)', + clipboardDetectedSql: '检测到剪贴板含 SQL 语句', + copyItem: '复制{title}', + pasteItem: '复制并回贴原编辑器', + saveAsFile: '另存为 {ext} 文件', + savedToast: '已保存到文件', + saveFailedToast: '保存文件失败', + switchDialectAction: '切换方言(当前:{dialect})', + toggleKeywordCaseAction: '切换关键字大小写(当前:{caseLabel})', + toggleDdlNamingAction: '切换命名风格(当前:{naming})', + toggleDdlLombokAction: '切换 Java Lombok(当前:{state})', + toggleDdlMpAction: '切换 Java MyBatis-Plus(当前:{state})', + toggleDdlGormAction: '切换 Go GORM 标签(当前:{state})', + toggleOn: '开', + toggleOff: '关', + saveDialogTitle: '另存为文件', + saveFilterSql: 'SQL 文件|sql', + saveFilterTs: 'TypeScript 文件|ts', + saveFilterGo: 'Go 文件|go', + saveFilterJava: 'Java 文件|java', + saveEmptyContentError: '没有可保存的内容', + saveDialogFailed: '无法打开系统保存对话框', + saveWriteFailed: '写入文件失败', + readFileFailed: '读取文件内容失败', + loadedFileToast: '已载入文件:{name}', + sectionOutputs: '转换产物', + sectionMybatisEntries: '还原 SQL 列表', + sectionDdlMerged: '合并模型代码', // sql-lexer - inputTooLarge: "输入超过 256 KiB,请分段处理", - inputHasNul: "输入包含 NUL 字符", - unclosedBlockComment: "块注释未闭合", - unclosedStringOrId: "字符串或引用标识符未闭合", - unclosedDollarString: "Dollar 引号字符串未闭合", - parenTooDeep: "括号嵌套超过 64 层", - extraRightParen: "存在多余的右括号", - sqlTooLong: "SQL 过长,请分段处理", - unclosedParen: "括号未闭合", - missingIdentifier: "缺少标识符", - unrecognizedIdentifier: "无法识别标识符:{text}", + inputTooLarge: '输入超过 256 KiB,请分段处理', + inputHasNul: '输入包含 NUL 字符', + unclosedBlockComment: '块注释未闭合', + unclosedStringOrId: '字符串或引用标识符未闭合', + unclosedDollarString: 'Dollar 引号字符串未闭合', + parenTooDeep: '括号嵌套超过 64 层', + extraRightParen: '存在多余的右括号', + sqlTooLong: 'SQL 过长,请分段处理', + unclosedParen: '括号未闭合', + missingIdentifier: '缺少标识符', + unrecognizedIdentifier: '无法识别标识符:{text}', // sql-helper-service - enterSqlStatement: "请输入 SQL 语句", - missingTypeTag: "参数缺少 (类型) 标记,或日志包含无法还原的换行", - invalidIntParam: "无效的 {type} 整数", - invalidNumParam: "无效的 {type} 数值", - invalidBoolParam: "布尔参数只能是 true 或 false", - unsupportedParamType: "不支持还原 {type} 参数,请使用原始绑定参数", - mybatisTwoLinesRequired: "请只载入同一次调用的一行 Preparing 和一行 Parameters,保留两行间的换行", - tooManyParams500: "参数超过 500 项,请分段处理", - tooManyParams: "参数超过 500 项", - logMarkersInSql: "日志标记混入 SQL,请保留完整的两行日志", - pgQuestionMarkOperator: "问号可能是 PostgreSQL 操作符,无法可靠识别绑定位置", - paramCountMismatch: "参数数量不匹配或值含歧义:SQL 有 {placeholders} 个占位符,日志有 {parts} 项", - paramMatchedSummary: "已匹配 {count} 个参数;仅供核对,请勿直接执行未知 SQL", - noResultGenerated: "未生成结果", + enterSqlStatement: '请输入 SQL 语句', + missingTypeTag: '参数缺少 (类型) 标记,或日志包含无法还原的换行', + invalidIntParam: '无效的 {type} 整数', + invalidNumParam: '无效的 {type} 数值', + invalidBoolParam: '布尔参数只能是 true 或 false', + unsupportedParamType: '不支持还原 {type} 参数,请使用原始绑定参数', + mybatisTwoLinesRequired: '未检测到可配对的 Preparing 与 Parameters 日志行,请确认包含完整日志', + mybatisMissingParameters: '第 {line} 行的 Preparing 缺少对应的 Parameters 行', + mybatisOrphanParameters: '第 {line} 行出现孤立的 Parameters,前方缺少对应的 Preparing 行', + tooManyParams500: '参数超过 500 项,请分段处理', + tooManyParams: '参数超过 500 项', + logMarkersInSql: '日志标记混入 SQL,请保留完整的 Preparing 与 Parameters 行', + pgQuestionMarkOperator: '问号可能是 PostgreSQL 操作符,无法可靠识别绑定位置', + paramCountMismatch: '参数数量不匹配或值含歧义:SQL 有 {placeholders} 个占位符,日志有 {parts} 项', + paramMatchedSummary: '已匹配 {count} 个参数;仅供核对,请勿直接执行未知 SQL', + noResultGenerated: '未生成结果', // ddl-service - emptyColumnDef: "列定义为空,或存在多余逗号", - commentNeedsString: "COMMENT 后需要字符串", - colMissingType: "字段 {name} 缺少数据库类型", - colIncompleteTypeParams: "字段 {name} 类型参数不完整", - colUnknownAttr: "字段 {name} 存在无法识别的类型或属性:{token}", - colMissingComment: "字段 {name} 缺少注释文本", - colMissingDefault: "字段 {name} 缺少默认值", - needKeywordInCreate: "需要 {word} 建表语句", - needCreateParens: "需要 CREATE TABLE 的完整字段定义括号", - unclosedColParens: "字段定义括号未闭合", - singleTableOnly: "一次只处理一张表的 CREATE TABLE 语句", - unrecognizedTableTail: "无法识别表定义后的语句", - incompleteTableConstraint: "表级约束不完整", - unrecognizedPrimaryKey: "主键约束无法识别", - unrecognizedPrimaryCol: "主键字段定义无法识别", - colCountRange: "需要 1 至 1000 个字段", - duplicateColName: "存在重复字段名", - missingPrimaryCol: "主键字段 {name} 不存在", - ddlSkeletonWarn: "生成结果是字段模型骨架;请按数据库驱动核对日期、JSON、枚举和类型转换。精确小数使用字符串或 BigDecimal。", - ddlUnmappedTypeWarn: "字段 {name} 的类型 {dbType} 未内置映射,已使用通用类型,请手动确认。", - ddlUnsafeGoTag: "字段 {name} 无法安全表达为 Go JSON/GORM 标签,请为此字段提供不含逗号、分号、引号或反斜杠的别名" + emptyColumnDef: '列定义为空,或存在多余逗号', + commentNeedsString: 'COMMENT 后需要字符串', + colMissingType: '字段 {name} 缺少数据库类型', + colIncompleteTypeParams: '字段 {name} 类型参数不完整', + colUnknownAttr: '字段 {name} 存在无法识别的类型或属性:{token}', + colMissingComment: '字段 {name} 缺少注释文本', + colMissingDefault: '字段 {name} 缺少默认值', + needKeywordInCreate: '需要 {word} 建表语句', + needCreateParens: '需要 CREATE TABLE 的完整字段定义括号', + unclosedColParens: '字段定义括号未闭合', + singleTableOnly: '请仅输入 CREATE TABLE 建表语句,不支持混入其他 SQL 语句', + unrecognizedTableTail: '无法识别表定义后的语句', + incompleteTableConstraint: '表级约束不完整', + unrecognizedPrimaryKey: '主键约束无法识别', + unrecognizedPrimaryCol: '主键字段定义无法识别', + colCountRange: '每张表需要 1 至 1000 个字段', + duplicateColName: '存在重复字段名', + missingPrimaryCol: '主键字段 {name} 不存在', + ddlSkeletonWarn: '生成结果是字段模型骨架;请按数据库驱动核对日期、JSON、枚举和类型转换。精确小数使用字符串或 BigDecimal。', + ddlUnmappedTypeWarn: '字段 {name} 的类型 {dbType} 未内置映射,已使用通用类型,请手动确认。', + ddlUnsafeGoTag: '字段 {name} 无法安全表达为 Go JSON/GORM 标签,请为此字段提供不含逗号、分号、引号或反斜杠的别名', }, - "en-US": { - modeFormatter: "Format & Minify SQL", - modeMybatis: "MyBatis Log Merge", - modeDdl: "DDL to Models", - guideFormatterTitle: "Load SQL to Format & Minify", - guideFormatterDetail: "Copy SQL to clipboard and press Enter to load, or open the multiline editor.\n\nOutputs both beautified and minified SQL; preserves case, strings, and comments without validating database syntax. Supports MySQL, PostgreSQL, and SQLite.", - guideMybatisTitle: "Load MyBatis Log to Restore SQL", - guideMybatisDetail: "Provide both Preparing and Parameters lines from the same call. Press Enter to load from clipboard, or open the multiline editor.\n\nParameters are formatted as literals for the selected dialect; verify dates, binaries, and custom types against raw bindings.", - guideDdlTitle: "Load DDL to Generate Models", - guideDdlDetail: "Provide a single CREATE TABLE statement, press Enter to load from clipboard, or open the multiline editor.\n\nGenerates TypeScript, Go, and Java model code.", - emptyInputError: "Please enter SQL or log text first", - beautifiedTitle: "Beautified SQL", - minifiedTitle: "Minified SQL", - formatterNotice: "Preserves case, strings, comments, and required newlines; formatting only, no syntax validation.", - mergedTitle: "Merged Reference SQL", - mybatisNotice: "{paramCountDisplay}. Logs are lossy text; verify dates, binaries, and custom types against raw bindings.", - tsModelTitle: "TypeScript Model", - goModelTitle: "Go Model", - javaModelTitle: "Java Model", - ddlNotice: "{tableName} · {count} [[count:column|columns]]\n{warnings}", - cannotGenerate: "Cannot generate output", - generateResult: "Generate", - sqlDialect: "SQL Dialect", - dialectMysql: "MySQL (backslash escape)", - dialectPg: "PostgreSQL (standard strings)", - dialectSqlite: "SQLite", - sourceMybatisLabel: "Two-Line MyBatis Log", - sourceDdlLabel: "CREATE TABLE Statement", - sourceSqlLabel: "SQL Source", - localOnlyHint: "Processed locally only; max 256 KiB.", - generatedToast: "Generated", - generateFailedToast: "Generation failed", - searchPlaceholder: "Filter results; use Edit Source or Load Clipboard for multiline input", - switchToolTooltip: "Switch Tool", - loadClipboard: "Load Clipboard", - editSource: "Edit Source", - inputErrorTitle: "Cannot process input", - emptyGuideSubtitle: "Press Enter to load clipboard, or open multiline editor", - copyItem: "Copy {title}", + 'en-US': { + modeFormatter: 'Format & Minify SQL', + modeMybatis: 'MyBatis Log Restore', + modeDdl: 'DDL to Entities', + guideFormatterTitle: 'Load SQL to Format & Minify', + guideFormatterDetail: + 'Copy SQL to clipboard and press Enter to load, or open the multiline editor.\n\nSupports SELECT column wrapping, WHERE/HAVING condition indentation, JOIN alignment, CASE WHEN, and nested subquery indentation while preserving strings and comments. Supports MySQL, PostgreSQL, and SQLite.', + guideMybatisTitle: 'Load MyBatis Logs to Restore SQL', + guideMybatisDetail: + 'Paste raw IDE console logs (including timestamps, INFO/DEBUG prefixes, and Total/Updates lines). Automatically extracts and restores every Preparing + Parameters pair into readable SQL.\n\nParameters are formatted as dialect literals; verify dates, binaries, and custom types against raw bindings.', + guideDdlTitle: 'Load CREATE TABLE DDL to Generate Models', + guideDdlDetail: + 'Supports single or multiple CREATE TABLE statements in one batch. Press Enter to load from clipboard, or open the multiline editor.\n\nGenerates TypeScript, Go, and Java models with configurable camelCase/snake_case, Lombok @Data, MyBatis-Plus, and GORM tags.', + emptyInputError: 'Please enter SQL, MyBatis logs, or DDL statements first', + beautifiedTitle: 'Beautified SQL', + beautifiedSubtitle: '{lines} [[lines:line|lines]] · {chars} chars · {dialect}', + minifiedTitle: 'Minified Single-Line SQL', + minifiedSubtitle: '{chars} chars · preserves comments & required newlines', + formatterNotice: 'Lexical-safe formatting ({dialect} · {caseLabel}); preserves strings, quoted identifiers, and comments.', + mergedTitle: 'Restored Reference SQL', + mergedAllTitle: 'All Restored SQL Combined ({count} [[count:query|queries]])', + mergedAllSubtitle: 'Restored {count} [[count:query|queries]] ready to copy or save as .sql', + mybatisEntrySubtitle: 'Matched {count} [[count:param|params]] · lines {prepLine}-{paramLine}', + mybatisEntryNoParamSubtitle: 'No bound params · lines {prepLine}-{paramLine}', + mybatisEntryErrorSubtitle: 'Parse error (line {line}): {error}', + mybatisNotice: 'Detected {total} [[total:group|groups]], restored {success}{failPart}. Logs are lossy text; verify dates, binaries, and custom types against raw bindings.', + mybatisFailPart: ', {failed} failed', + mybatisEntryDetailHeader: 'Source: line {prepLine} Preparing / line {paramLine} Parameters · {paramSummary}', + mybatisErrorDetail: 'Line {line} parse error: {error}', + tsModelTitle: 'TypeScript Model', + goModelTitle: 'Go Model', + javaModelTitle: 'Java Model', + ddlModelSubtitle: '{tables} [[tables:table|tables]] · {columns} [[columns:column|columns]] · {options}', + ddlTableSectionTitle: 'Per-Table Models', + ddlSingleTableTitle: '{tableName} ({lang})', + ddlSingleTableSubtitle: '{columns} [[columns:column|columns]]', + ddlNotice: '{tables} [[tables:table|tables]] ({tableNames}) · {count} [[count:column|columns]]\n{warnings}', + cannotGenerate: 'Cannot generate output', + generateResult: 'Generate', + sqlDialect: 'SQL Dialect', + dialectMysql: 'MySQL (backslash escape)', + dialectPg: 'PostgreSQL (standard strings)', + dialectSqlite: 'SQLite', + dialectShortMysql: 'MySQL', + dialectShortPg: 'PostgreSQL', + dialectShortSqlite: 'SQLite', + keywordCaseLabel: 'Keyword Case', + keywordCaseUpper: 'UPPERCASE (Recommended)', + keywordCasePreserve: 'Preserve Original', + keywordCaseLower: 'lowercase', + keywordCaseShortUpper: 'UPPER', + keywordCaseShortPreserve: 'Preserve', + keywordCaseShortLower: 'lower', + indentWidthLabel: 'Indent Width', + indent2: '2 Spaces', + indent4: '4 Spaces', + ddlNamingLabel: 'Field Naming Style', + ddlNamingCamel: 'camelCase', + ddlNamingSnake: 'Preserve Column Name (snake_case)', + ddlNamingShortCamel: 'camelCase', + ddlNamingShortSnake: 'Original', + ddlJavaLombokLabel: 'Java Lombok (@Data)', + ddlJavaLombokCheckbox: 'Generate @Data annotation with private fields', + ddlJavaMpLabel: 'Java MyBatis-Plus', + ddlJavaMpCheckbox: 'Generate @TableName / @TableId / @TableField', + ddlGoGormLabel: 'Go GORM Tag', + ddlGoGormCheckbox: 'Include gorm:"column:..." in struct tags', + sourceMybatisLabel: 'MyBatis Logs (supports mixed console output)', + sourceDdlLabel: 'CREATE TABLE Statements (supports multiple tables)', + sourceSqlLabel: 'SQL Source', + localOnlyHint: 'Processed locally only; max 256 KiB.', + generatedToast: 'Generated', + generateFailedToast: 'Generation failed', + searchPlaceholder: 'Filter outputs; load from clipboard or edit SQL source above', + switchToolTooltip: 'Switch Mode', + loadClipboard: 'Read Clipboard', + loadDetectedClipboard: 'Parse Clipboard', + editSource: 'Edit SQL', + inputErrorTitle: 'Cannot process input', + emptyGuideSubtitle: 'Press Enter to read clipboard, or open multiline editor', + clipboardDetectedMybatis: 'Clipboard has MyBatis logs ({count} [[count:query|queries]])', + clipboardDetectedDdl: 'Clipboard has CREATE TABLE DDL ({count} [[count:table|tables]])', + clipboardDetectedSql: 'Clipboard has SQL statement', + copyItem: 'Copy {title}', + pasteItem: 'Copy & Paste to Active App', + saveAsFile: 'Save as {ext} File', + savedToast: 'Saved to file', + saveFailedToast: 'Failed to save file', + switchDialectAction: 'Switch Dialect (Current: {dialect})', + toggleKeywordCaseAction: 'Cycle Keyword Case (Current: {caseLabel})', + toggleDdlNamingAction: 'Toggle Naming Style (Current: {naming})', + toggleDdlLombokAction: 'Toggle Java Lombok (Current: {state})', + toggleDdlMpAction: 'Toggle Java MyBatis-Plus (Current: {state})', + toggleDdlGormAction: 'Toggle Go GORM Tag (Current: {state})', + toggleOn: 'On', + toggleOff: 'Off', + saveDialogTitle: 'Save File As', + saveFilterSql: 'SQL File|sql', + saveFilterTs: 'TypeScript File|ts', + saveFilterGo: 'Go File|go', + saveFilterJava: 'Java File|java', + saveEmptyContentError: 'No content to save', + saveDialogFailed: 'Failed to open save dialog', + saveWriteFailed: 'Failed to write file', + readFileFailed: 'Failed to read file content', + loadedFileToast: 'Loaded file: {name}', + sectionOutputs: 'Outputs', + sectionMybatisEntries: 'Restored Queries', + sectionDdlMerged: 'Combined Models', // sql-lexer - inputTooLarge: "Input exceeds 256 KiB; please split it", - inputHasNul: "Input contains NUL character", - unclosedBlockComment: "Unclosed block comment", - unclosedStringOrId: "Unclosed string or quoted identifier", - unclosedDollarString: "Unclosed dollar-quoted string", - parenTooDeep: "Parentheses nested deeper than 64 levels", - extraRightParen: "Extra closing parenthesis", - sqlTooLong: "SQL too long; please split it", - unclosedParen: "Unclosed parenthesis", - missingIdentifier: "Missing identifier", - unrecognizedIdentifier: "Unrecognized identifier: {text}", + inputTooLarge: 'Input exceeds 256 KiB; please split it', + inputHasNul: 'Input contains NUL character', + unclosedBlockComment: 'Unclosed block comment', + unclosedStringOrId: 'Unclosed string or quoted identifier', + unclosedDollarString: 'Unclosed dollar-quoted string', + parenTooDeep: 'Parentheses nested deeper than 64 levels', + extraRightParen: 'Extra closing parenthesis', + sqlTooLong: 'SQL too long; please split it', + unclosedParen: 'Unclosed parenthesis', + missingIdentifier: 'Missing identifier', + unrecognizedIdentifier: 'Unrecognized identifier: {text}', // sql-helper-service - enterSqlStatement: "Please enter a SQL statement", - missingTypeTag: "Parameter is missing (Type) tag, or log contains unrecoverable newlines", - invalidIntParam: "Invalid {type} integer", - invalidNumParam: "Invalid {type} number", - invalidBoolParam: "Boolean parameter must be true or false", - unsupportedParamType: "Cannot restore {type} parameter; use raw bound parameters", - mybatisTwoLinesRequired: "Provide exactly one Preparing line and one Parameters line from the same call, keeping the newline between them", - tooManyParams500: "More than 500 parameters; please process in batches", - tooManyParams: "More than 500 parameters", - logMarkersInSql: "Log markers mixed into SQL; keep the complete two-line log", - pgQuestionMarkOperator: "Question mark may be a PostgreSQL operator; cannot reliably locate bindings", - paramCountMismatch: "Parameter count mismatch or ambiguous values: SQL has {placeholders} [[placeholders:placeholder|placeholders]], log has {parts} [[parts:item|items]]", - paramMatchedSummary: "Matched {count} [[count:parameter|parameters]]; for reference only, do not execute untrusted SQL directly", - noResultGenerated: "No output generated", + enterSqlStatement: 'Please enter a SQL statement', + missingTypeTag: 'Parameter is missing (Type) tag, or log contains unrecoverable newlines', + invalidIntParam: 'Invalid {type} integer', + invalidNumParam: 'Invalid {type} number', + invalidBoolParam: 'Boolean parameter must be true or false', + unsupportedParamType: 'Cannot restore {type} parameter; use raw bound parameters', + mybatisTwoLinesRequired: 'No matching Preparing and Parameters lines found in log', + mybatisMissingParameters: 'Preparing on line {line} has no matching Parameters line', + mybatisOrphanParameters: 'Orphan Parameters on line {line} without a preceding Preparing line', + tooManyParams500: 'More than 500 parameters; please process in batches', + tooManyParams: 'More than 500 parameters', + logMarkersInSql: 'Log markers mixed into SQL; keep complete Preparing and Parameters lines', + pgQuestionMarkOperator: 'Question mark may be a PostgreSQL operator; cannot reliably locate bindings', + paramCountMismatch: 'Parameter count mismatch or ambiguous values: SQL has {placeholders} [[placeholders:placeholder|placeholders]], log has {parts} [[parts:item|items]]', + paramMatchedSummary: 'Matched {count} [[count:parameter|parameters]]; for reference only, do not execute untrusted SQL directly', + noResultGenerated: 'No output generated', // ddl-service - emptyColumnDef: "Empty column definition or trailing comma", - commentNeedsString: "COMMENT requires a string literal", - colMissingType: "Column {name} is missing a database type", - colIncompleteTypeParams: "Column {name} has incomplete type parameters", - colUnknownAttr: "Column {name} has unrecognized type or attribute: {token}", - colMissingComment: "Column {name} is missing comment text", - colMissingDefault: "Column {name} is missing default value", - needKeywordInCreate: "Expected {word} in CREATE TABLE statement", - needCreateParens: "Expected complete column definition parentheses for CREATE TABLE", - unclosedColParens: "Unclosed column definition parentheses", - singleTableOnly: "Only one CREATE TABLE statement is supported at a time", - unrecognizedTableTail: "Unrecognized statement after table definition", - incompleteTableConstraint: "Incomplete table constraint", - unrecognizedPrimaryKey: "Unrecognized PRIMARY KEY constraint", - unrecognizedPrimaryCol: "Unrecognized PRIMARY KEY column definition", - colCountRange: "Requires 1 to 1000 columns", - duplicateColName: "Duplicate column name", - missingPrimaryCol: "Primary key column {name} does not exist", - ddlSkeletonWarn: "Generated code is a model skeleton; verify dates, JSON, enums, and type conversions for your driver. Use string or BigDecimal for exact decimals.", - ddlUnmappedTypeWarn: "Column {name} type {dbType} has no built-in mapping; used generic type, please verify.", - ddlUnsafeGoTag: "Column {name} cannot be safely represented as a Go JSON/GORM tag; provide an alias without commas, semicolons, quotes, or backslashes" - } -}; + emptyColumnDef: 'Empty column definition or trailing comma', + commentNeedsString: 'COMMENT requires a string literal', + colMissingType: 'Column {name} is missing a database type', + colIncompleteTypeParams: 'Column {name} has incomplete type parameters', + colUnknownAttr: 'Column {name} has unrecognized type or attribute: {token}', + colMissingComment: 'Column {name} is missing comment text', + colMissingDefault: 'Column {name} is missing default value', + needKeywordInCreate: 'Expected {word} in CREATE TABLE statement', + needCreateParens: 'Expected complete column definition parentheses for CREATE TABLE', + unclosedColParens: 'Unclosed column definition parentheses', + singleTableOnly: 'Only CREATE TABLE statements are supported; do not mix other SQL statements', + unrecognizedTableTail: 'Unrecognized statement after table definition', + incompleteTableConstraint: 'Incomplete table constraint', + unrecognizedPrimaryKey: 'Unrecognized PRIMARY KEY constraint', + unrecognizedPrimaryCol: 'Unrecognized PRIMARY KEY column definition', + colCountRange: 'Each table requires 1 to 1000 columns', + duplicateColName: 'Duplicate column name', + missingPrimaryCol: 'Primary key column {name} does not exist', + ddlSkeletonWarn: 'Generated code is a model skeleton; verify dates, JSON, enums, and type conversions for your driver. Use string or BigDecimal for exact decimals.', + ddlUnmappedTypeWarn: 'Column {name} type {dbType} has no built-in mapping; used generic type, please verify.', + ddlUnsafeGoTag: 'Column {name} cannot be safely represented as a Go JSON/GORM tag; provide an alias without commas, semicolons, quotes, or backslashes', + }, +} -const rawT = createTranslator(MESSAGES, { defaultLocale: "en-US" }) +const rawT = createTranslator(MESSAGES, { defaultLocale: 'en-US' }) export const t: typeof rawT = (key, params) => { const out = rawT(key, params) if (!out.includes('[[')) return out diff --git a/extensions/sql-helper/src/index.tsx b/extensions/sql-helper/src/index.tsx index 6e5799c3..1bca0504 100644 --- a/extensions/sql-helper/src/index.tsx +++ b/extensions/sql-helper/src/index.tsx @@ -1,120 +1,966 @@ -import React, { Action, ActionPanel, Clipboard, Form, Icon, List, ToastStyle, showToast, useEffect, useLocale, useMemo, useNavigation, useRef, useState } from '@ztools/declarative-ui' +import React, { + Action, + ActionPanel, + Clipboard, + Color, + Form, + Icon, + List, + ToastStyle, + showToast, + useEffect, + useLocale, + useMemo, + useNavigation, + useRef, + useState, + type FileInputPayload, +} from '@ztools/declarative-ui' +import { readTextFile, saveTextToFile } from './host.js' import { t } from './i18n.js' -import { formatAndMinifySql, mergeMyBatisLog, parseDdlToEntities } from './sql-helper-service.js' -import type { SqlDialect, SqlHelperTab } from './types.js' +import { + detectClipboardSqlHint, + extractAndMergeMyBatisLogs, + formatAndMinifySql, + mergeMyBatisLog, + parseDdlToEntities, +} from './sql-helper-service.js' +import type { + ClipboardSqlHint, + DdlCodegenOptions, + DdlNamingStyle, + SqlDialect, + SqlFormatOptions, + SqlHelperTab, + SqlKeywordCase, +} from './types.js' export * from './types.js' export * from './sql-helper-service.js' -interface Source { text: string; dialect: SqlDialect } -interface Output { id: string; title: string; language: string; content: string } -const getModes = (): Record => ({ formatter: t('modeFormatter'), mybatis: t('modeMybatis'), ddl: t('modeDdl') }) -const EMPTY: Source = { text: '', dialect: 'mysql' } -// 每个模式的空状态引导:说明需要什么输入、会得到什么;快捷键由底栏显示,这里不重复 +interface Source { + text: string + dialect: SqlDialect + keywordCase: SqlKeywordCase + indentWidth: 2 | 4 + namingStyle: DdlNamingStyle + javaLombok: boolean + javaMybatisPlus: boolean + goGormTag: boolean +} + +interface OutputItem { + id: string + title: string + subtitle: string + language: 'sql' | 'ts' | 'go' | 'java' + content: string + fileBaseName: string + detailNote: string + isError?: boolean + section: 'primary' | 'secondary' +} + +const DEFAULT_SOURCE: Source = { + text: '', + dialect: 'mysql', + keywordCase: 'upper', + indentWidth: 2, + namingStyle: 'snake', + javaLombok: false, + javaMybatisPlus: false, + goGormTag: true, +} + +const DIALECT_ORDER: SqlDialect[] = ['mysql', 'postgresql', 'sqlite'] +const KEYWORD_CASE_ORDER: SqlKeywordCase[] = ['upper', 'preserve', 'lower'] + +const getModes = (): Record => ({ + formatter: t('modeFormatter'), + mybatis: t('modeMybatis'), + ddl: t('modeDdl'), +}) + +const getDialectShortLabel = (dialect: SqlDialect): string => + dialect === 'postgresql' + ? t('dialectShortPg') + : dialect === 'sqlite' + ? t('dialectShortSqlite') + : t('dialectShortMysql') + +const getKeywordCaseShortLabel = (keywordCase: SqlKeywordCase): string => + keywordCase === 'upper' + ? t('keywordCaseShortUpper') + : keywordCase === 'lower' + ? t('keywordCaseShortLower') + : t('keywordCaseShortPreserve') + const getGuides = (): Record => ({ formatter: { title: t('guideFormatterTitle'), detail: t('guideFormatterDetail') }, mybatis: { title: t('guideMybatisTitle'), detail: t('guideMybatisDetail') }, ddl: { title: t('guideDdlTitle'), detail: t('guideDdlDetail') }, }) -function convert(tab: SqlHelperTab, source: Source): { outputs: Output[]; notice: string } { + +function formatOptionsOf(source: Source): SqlFormatOptions { + return { keywordCase: source.keywordCase, indentWidth: source.indentWidth } +} + +function ddlOptionsOf(source: Source): DdlCodegenOptions { + return { + namingStyle: source.namingStyle, + javaLombok: source.javaLombok, + javaMybatisPlus: source.javaMybatisPlus, + goGormTag: source.goGormTag, + } +} + +function ddlOptionsSummary(source: Source): string { + const parts = [source.namingStyle === 'camel' ? t('ddlNamingShortCamel') : t('ddlNamingShortSnake')] + if (source.javaLombok) parts.push('Lombok') + if (source.javaMybatisPlus) parts.push('MyBatis-Plus') + if (source.goGormTag) parts.push('GORM') + return parts.join(' · ') +} + +function convert(tab: SqlHelperTab, source: Source): { outputs: OutputItem[]; notice: string } { if (!source.text.trim()) throw new Error(t('emptyInputError')) + const dialectLabel = getDialectShortLabel(source.dialect) + const caseLabel = getKeywordCaseShortLabel(source.keywordCase) + if (tab === 'formatter') { - const result = formatAndMinifySql(source.text, source.dialect) - return { outputs: [ - { id: 'beautified', title: t('beautifiedTitle'), language: 'sql', content: result.beautified }, - { id: 'minified', title: t('minifiedTitle'), language: 'sql', content: result.minified }, - ], notice: t('formatterNotice') } + const result = formatAndMinifySql(source.text, source.dialect, formatOptionsOf(source)) + const notice = t('formatterNotice', { dialect: dialectLabel, caseLabel }) + return { + outputs: [ + { + id: 'beautified', + title: t('beautifiedTitle'), + subtitle: t('beautifiedSubtitle', { + lines: result.lineCount, + chars: result.charCount, + dialect: dialectLabel, + }), + language: 'sql', + content: result.beautified, + fileBaseName: 'formatted', + detailNote: notice, + section: 'primary', + }, + { + id: 'minified', + title: t('minifiedTitle'), + subtitle: t('minifiedSubtitle', { chars: result.minified.length }), + language: 'sql', + content: result.minified, + fileBaseName: 'minified', + detailNote: notice, + section: 'primary', + }, + ], + notice, + } } + if (tab === 'mybatis') { - const result = mergeMyBatisLog(source.text, source.dialect) - if (!result.isSuccess) throw new Error(result.errorMessage) - return { outputs: [{ id: 'merged', title: t('mergedTitle'), language: 'sql', content: result.beautifiedMergedSql }], notice: t('mybatisNotice', { paramCountDisplay: result.paramCountDisplay }) } + const batch = extractAndMergeMyBatisLogs(source.text, source.dialect, formatOptionsOf(source)) + if (!batch.isSuccess && batch.entries.length <= 1) { + throw new Error(batch.errorMessage ?? t('mybatisTwoLinesRequired')) + } + const failPart = batch.failureCount > 0 ? t('mybatisFailPart', { failed: batch.failureCount }) : '' + const notice = t('mybatisNotice', { + total: batch.entries.length, + success: batch.successCount, + failPart, + }) + const outputs: OutputItem[] = [] + if (batch.successCount >= 2) { + outputs.push({ + id: 'merged-all', + title: t('mergedAllTitle', { count: batch.successCount }), + subtitle: t('mergedAllSubtitle', { count: batch.successCount }), + language: 'sql', + content: batch.combinedBeautifiedSql, + fileBaseName: 'mybatis-restored-all', + detailNote: notice, + section: 'primary', + }) + } + for (const entry of batch.entries) { + const id = batch.entries.length === 1 && entry.isSuccess ? 'merged' : `mybatis-${entry.index}` + if (entry.isSuccess) { + const prepLine = entry.preparingLine ?? 1 + const paramLine = entry.parametersLine ?? prepLine + 1 + const subtitle = + entry.params.length > 0 + ? t('mybatisEntrySubtitle', { count: entry.params.length, prepLine, paramLine }) + : t('mybatisEntryNoParamSubtitle', { prepLine, paramLine }) + const detailHeader = t('mybatisEntryDetailHeader', { + prepLine, + paramLine, + paramSummary: entry.paramCountDisplay, + }) + outputs.push({ + id, + title: batch.entries.length === 1 ? `${entry.summary} · ${t('mergedTitle')}` : entry.summary, + subtitle, + language: 'sql', + content: entry.beautifiedMergedSql, + fileBaseName: `mybatis-${entry.index}`, + detailNote: `${detailHeader}\n${notice}`, + section: 'primary', + }) + } else { + const errLine = entry.parametersLine ?? entry.preparingLine ?? 1 + const errMsg = entry.errorMessage ?? t('noResultGenerated') + outputs.push({ + id, + title: entry.summary, + subtitle: t('mybatisEntryErrorSubtitle', { line: errLine, error: errMsg }), + language: 'sql', + content: '', + fileBaseName: `mybatis-${entry.index}`, + detailNote: t('mybatisErrorDetail', { line: errLine, error: errMsg }), + isError: true, + section: 'primary', + }) + } + } + return { outputs, notice } } - const result = parseDdlToEntities(source.text, source.dialect) + + const result = parseDdlToEntities(source.text, source.dialect, ddlOptionsOf(source)) if (!result.isValid) throw new Error(result.warningMessage) - return { outputs: [ - { id: 'typescript', title: t('tsModelTitle'), language: 'ts', content: result.generatedCode.typescript }, - { id: 'golang', title: t('goModelTitle'), language: 'go', content: result.generatedCode.golang }, - { id: 'java', title: t('javaModelTitle'), language: 'java', content: result.generatedCode.java }, - ], notice: t('ddlNotice', { tableName: result.tableName, count: result.columns.length, warnings: result.warnings.join('\n') }) } + const optsSummary = ddlOptionsSummary(source) + const notice = t('ddlNotice', { + tables: result.tables.length, + tableNames: result.tableNames.join(', '), + count: result.columns.length, + warnings: result.warnings.join('\n'), + }) + const subtitle = t('ddlModelSubtitle', { + tables: result.tables.length, + columns: result.columns.length, + options: optsSummary, + }) + const outputs: OutputItem[] = [ + { + id: 'typescript', + title: t('tsModelTitle'), + subtitle, + language: 'ts', + content: result.generatedCode.typescript, + fileBaseName: result.tableName || 'models', + detailNote: notice, + section: 'primary', + }, + { + id: 'golang', + title: t('goModelTitle'), + subtitle, + language: 'go', + content: result.generatedCode.golang, + fileBaseName: result.tableName || 'models', + detailNote: notice, + section: 'primary', + }, + { + id: 'java', + title: t('javaModelTitle'), + subtitle, + language: 'java', + content: result.generatedCode.java, + fileBaseName: result.tableName || 'Models', + detailNote: notice, + section: 'primary', + }, + ] + + if (result.tables.length >= 2) { + for (const table of result.tables) { + const tableNotice = t('ddlNotice', { + tables: 1, + tableNames: table.tableName, + count: table.columns.length, + warnings: table.warnings.join('\n'), + }) + const tableSub = t('ddlSingleTableSubtitle', { columns: table.columns.length }) + outputs.push( + { + id: `table-${table.tableName}-ts`, + title: t('ddlSingleTableTitle', { tableName: table.tableName, lang: 'TypeScript' }), + subtitle: tableSub, + language: 'ts', + content: table.generatedCode.typescript, + fileBaseName: table.tableName, + detailNote: tableNotice, + section: 'secondary', + }, + { + id: `table-${table.tableName}-go`, + title: t('ddlSingleTableTitle', { tableName: table.tableName, lang: 'Go' }), + subtitle: tableSub, + language: 'go', + content: table.generatedCode.golang, + fileBaseName: table.tableName, + detailNote: tableNotice, + section: 'secondary', + }, + { + id: `table-${table.tableName}-java`, + title: t('ddlSingleTableTitle', { tableName: table.tableName, lang: 'Java' }), + subtitle: tableSub, + language: 'java', + content: table.generatedCode.java, + fileBaseName: table.tableName, + detailNote: tableNotice, + section: 'secondary', + } + ) + } + } + + return { outputs, notice } } + function noticeMarkdown(value: string): string { return value.replace(/[\\`*_{}\[\]()#+.!<>|~-]/g, '\\$&').split('\n').join('\n\n') } + function fenced(value: string, language = 'text'): string { let n = 3 for (const match of value.matchAll(/`+/g)) n = Math.max(n, match[0].length + 1) const fence = '`'.repeat(n) return `${fence}${language}\n${value}\n${fence}` } -export function SqlSourceForm({ tab, source, save }: { tab: SqlHelperTab; source: Source; save: (value: Source) => void }) { + +function saveFilterForLanguage(language: OutputItem['language']): { ext: string; filter: string } { + if (language === 'ts') return { ext: '.ts', filter: t('saveFilterTs') } + if (language === 'go') return { ext: '.go', filter: t('saveFilterGo') } + if (language === 'java') return { ext: '.java', filter: t('saveFilterJava') } + return { ext: '.sql', filter: t('saveFilterSql') } +} + +function formatClipboardHintText(hint: ClipboardSqlHint): string { + if (hint.tab === 'mybatis') return t('clipboardDetectedMybatis', { count: hint.count }) + if (hint.tab === 'ddl') return t('clipboardDetectedDdl', { count: hint.count }) + return t('clipboardDetectedSql') +} + +export function SqlSourceForm({ + tab, + source, + save, +}: { + tab: SqlHelperTab + source: Source + save: (value: Source) => void +}) { useLocale() const modes = getModes() - const [text, setText] = useState(source.text), [dialect, setDialect] = useState(source.dialect), { pop } = useNavigation() + const [text, setText] = useState(source.text) + const [dialect, setDialect] = useState(source.dialect) + const [keywordCase, setKeywordCase] = useState(source.keywordCase) + const [indentWidth, setIndentWidth] = useState<2 | 4>(source.indentWidth) + const [namingStyle, setNamingStyle] = useState(source.namingStyle) + const [javaLombok, setJavaLombok] = useState(source.javaLombok) + const [javaMybatisPlus, setJavaMybatisPlus] = useState(source.javaMybatisPlus) + const [goGormTag, setGoGormTag] = useState(source.goGormTag) + const { pop } = useNavigation() + const submit = async () => { - try { convert(tab, { text, dialect }); save({ text, dialect }); pop() } - catch (error) { await showToast({ style: ToastStyle.Failure, title: t('cannotGenerate'), message: error instanceof Error ? error.message : String(error) }) } - } - return
}> - setDialect(value as SqlDialect)}> - - - - - - - + const next: Source = { + text, + dialect, + keywordCase, + indentWidth, + namingStyle, + javaLombok, + javaMybatisPlus, + goGormTag, + } + try { + convert(tab, next) + save(next) + pop() + } catch (error) { + await showToast({ + style: ToastStyle.Failure, + title: t('cannotGenerate'), + message: error instanceof Error ? error.message : String(error), + }) + } + } + + return ( +
+ + + } + > + setDialect(value as SqlDialect)} + > + + + + + + {tab !== 'ddl' && ( + setKeywordCase(value as SqlKeywordCase)} + > + + + + + )} + + {tab !== 'ddl' && ( + setIndentWidth(value === '4' ? 4 : 2)} + > + + + + )} + + {tab === 'ddl' && ( + setNamingStyle(value as DdlNamingStyle)} + > + + + + )} + + {tab === 'ddl' && ( + + )} + + {tab === 'ddl' && ( + + )} + + {tab === 'ddl' && ( + + )} + + + + + ) +} + +interface OutputRowHandlers { + tab: SqlHelperTab + source: Source + dialectLabel: string + caseLabel: string + onSave: (item: OutputItem) => void + onEdit: () => void + onCycleDialect: () => void + onCycleKeywordCase: () => void + onToggleDdlNaming: () => void + onToggleDdlLombok: () => void + onToggleDdlMybatisPlus: () => void + onToggleDdlGoGorm: () => void +} + +function buildOutputItemElement(item: OutputItem, ctx: OutputRowHandlers) { + const { ext } = saveFilterForLanguage(item.language) + const detailMarkdown = item.isError + ? fenced(item.detailNote) + : `${fenced(item.content, item.language)}\n\n${noticeMarkdown(item.detailNote)}` + + return ( + } + actions={ + + {!item.isError && ( + + )} + {!item.isError && ( + + )} + {!item.isError && ( + ctx.onSave(item)} + /> + )} + + + {ctx.tab === 'ddl' ? ( + + ) : ( + + )} + {ctx.tab === 'ddl' && ( + + )} + {ctx.tab === 'ddl' && ( + + )} + {ctx.tab === 'ddl' && ( + + )} + + } + /> + ) +} + +interface EmptyStateProps { + isError: boolean + errorMessage?: string + showHintBanner: boolean + clipboardHint: ClipboardSqlHint | null + guide: { title: string; detail: string } + dialectLabel: string + onLoadClipboard: () => void + onEdit: () => void + onCycleDialect: () => void +} + +function buildEmptyStateItem(props: EmptyStateProps) { + const title = props.isError + ? t('inputErrorTitle') + : props.showHintBanner && props.clipboardHint + ? formatClipboardHintText(props.clipboardHint) + : props.guide.title + const subtitle = props.isError ? props.errorMessage ?? '' : t('emptyGuideSubtitle') + const markdown = props.isError ? fenced(props.errorMessage ?? '') : props.guide.detail + + return ( + } + actions={ + + + + + + } + /> + ) +} + +function computeSummaryText(args: { + tab: SqlHelperTab + source: Source + dialectLabel: string + caseLabel: string + hasOutput: boolean + isError: boolean + showHintBanner: boolean + clipboardHint: ClipboardSqlHint | null + modes: Record + guides: Record +}): string { + if (args.hasOutput) { + return args.tab === 'ddl' + ? `${args.modes[args.tab]} · ${args.dialectLabel} · ${ddlOptionsSummary(args.source)}` + : `${args.modes[args.tab]} · ${args.dialectLabel} · ${args.caseLabel}` + } + if (args.isError) return t('inputErrorTitle') + if (args.showHintBanner && args.clipboardHint) { + return `${formatClipboardHintText(args.clipboardHint)} · ${args.dialectLabel}` + } + return `${args.guides[args.tab].title} · ${args.dialectLabel}` } + +function fileNameOf(filePath: string): string { + const parts = filePath.split(/[/\\]/) + return parts[parts.length - 1] || filePath +} + export function SqlHelperCommand({ initialTab = 'formatter' }: { initialTab?: SqlHelperTab } = {}) { const locale = useLocale() const modes = getModes() const guides = getGuides() - const [tab, setTab] = useState(initialTab), [sources, setSources] = useState>({ formatter: EMPTY, mybatis: EMPTY, ddl: EMPTY }), [query, setQuery] = useState('') - const { push } = useNavigation(), revision = useRef(0), mounted = useRef(true) - useEffect(() => () => { mounted.current = false; revision.current++ }, []) + const [tab, setTab] = useState(initialTab) + const [sources, setSources] = useState>({ + formatter: DEFAULT_SOURCE, + mybatis: DEFAULT_SOURCE, + ddl: DEFAULT_SOURCE, + }) + const [query, setQuery] = useState('') + const [clipboardHint, setClipboardHint] = useState(null) + const { push } = useNavigation() + const revision = useRef(0) + const mounted = useRef(true) + + useEffect(() => { + mounted.current = true + const probeRev = revision.current + void (async () => { + try { + const text = (await Clipboard.readText()) || '' + if (!mounted.current || probeRev !== revision.current) return + setClipboardHint(detectClipboardSqlHint(text)) + } catch { + // 静默探测剪贴板失败不影响主流程;用户显式点击读取时会展示真实错误 + } + })() + return () => { + mounted.current = false + revision.current++ + } + }, []) + const source = sources[tab] const state = useMemo(() => { if (!source.text.trim()) return { kind: 'empty' as const } - try { return { kind: 'ready' as const, value: convert(tab, source) } } - catch (error) { return { kind: 'error' as const, message: error instanceof Error ? error.message : String(error) } } + try { + return { kind: 'ready' as const, value: convert(tab, source) } + } catch (error) { + return { kind: 'error' as const, message: error instanceof Error ? error.message : String(error) } + } }, [tab, source, locale]) - const update = (value: Source) => { revision.current++; setSources(previous => ({ ...previous, [tab]: value })); setQuery('') } - const edit = () => { revision.current++; push() } - const clipboard = async () => { + + const updateCurrentSource = (updater: (prev: Source) => Source) => { + revision.current++ + setSources(previous => ({ ...previous, [tab]: updater(previous[tab]) })) + } + + const update = (value: Source) => { + revision.current++ + setSources(previous => ({ ...previous, [tab]: value })) + setClipboardHint(null) + setQuery('') + } + + const edit = () => { + revision.current++ + push() + } + + const cycleDialect = () => { + const nextDialect = DIALECT_ORDER[(DIALECT_ORDER.indexOf(source.dialect) + 1) % DIALECT_ORDER.length]! + updateCurrentSource(prev => ({ ...prev, dialect: nextDialect })) + } + + const cycleKeywordCase = () => { + const nextCase = KEYWORD_CASE_ORDER[(KEYWORD_CASE_ORDER.indexOf(source.keywordCase) + 1) % KEYWORD_CASE_ORDER.length]! + updateCurrentSource(prev => ({ ...prev, keywordCase: nextCase })) + } + + const runWithToast = async ( + task: (isStale: () => boolean) => Promise, + onSuccessTitle?: (res: string) => string + ) => { const request = ++revision.current + const isStale = () => !mounted.current || request !== revision.current + try { + const result = await task(isStale) + if (isStale()) return + if (result !== null && onSuccessTitle) { + await showToast({ style: ToastStyle.Success, title: onSuccessTitle(result) }) + } + } catch (error) { + if (isStale()) return + await showToast({ + style: ToastStyle.Failure, + title: t('generateFailedToast'), + message: error instanceof Error ? error.message : String(error), + }) + } + } + + const applyRawInput = (text: string, autoSwitchTab: boolean) => { + const detected = detectClipboardSqlHint(text) + const targetTab = autoSwitchTab && detected ? detected.tab : tab + const targetSource: Source = { ...sources[targetTab], text } + if (targetTab !== tab) setTab(targetTab) + setSources(previous => ({ ...previous, [targetTab]: targetSource })) + setClipboardHint(null) + setQuery('') + convert(targetTab, targetSource) + } + + const loadFromClipboard = (autoSwitchTab = false) => + runWithToast( + async isStale => { + const text = (await Clipboard.readText()) || '' + if (isStale()) return null + applyRawInput(text, autoSwitchTab) + return '' + }, + () => t('generatedToast') + ) + + const handleTextPaste = (text: string) => + runWithToast( + async isStale => { + if (isStale()) return null + applyRawInput(text, true) + return '' + }, + () => t('generatedToast') + ) + + const handleFileInput = (payload: FileInputPayload) => { + const filePath = payload.files[0] + if (!filePath) return + void runWithToast( + async isStale => { + const content = await readTextFile(filePath) + if (isStale()) return null + applyRawInput(content, true) + return fileNameOf(filePath) + }, + name => t('loadedFileToast', { name }) + ) + } + + const saveOutputItem = async (item: OutputItem) => { try { - const value = { ...source, text: await Clipboard.readText() || '' } - if (!mounted.current || request !== revision.current) return - setSources(previous => ({ ...previous, [tab]: value })); setQuery('') - convert(tab, value) - await showToast({ style: ToastStyle.Success, title: t('generatedToast') }) + const { ext, filter } = saveFilterForLanguage(item.language) + const savedPath = await saveTextToFile(item.content, `${item.fileBaseName}${ext}`, filter) + if (!mounted.current || !savedPath) return + await showToast({ style: ToastStyle.Success, title: t('savedToast'), message: savedPath }) } catch (error) { - if (!mounted.current || request !== revision.current) return - await showToast({ style: ToastStyle.Failure, title: t('generateFailedToast'), message: error instanceof Error ? error.message : String(error) }) + if (!mounted.current) return + await showToast({ + style: ToastStyle.Failure, + title: t('saveFailedToast'), + message: error instanceof Error ? error.message : String(error), + }) } } + const output = state.kind === 'ready' ? state.value : undefined - return { revision.current++; setTab(value as SqlHelperTab); setQuery('') }} tooltip={t('switchToolTooltip')}> - {Object.entries(modes).map(([value, title]) => )} -
} - filterBar={{ - summaryText: output ? `${modes[tab]} · ${source.dialect}` : state.kind === 'error' ? t('inputErrorTitle') : guides[tab].title, - actions: [ - { id: 'clipboard', title: t('loadClipboard'), ...(output ? {} : { style: 'primary' as const }), onAction: () => void clipboard() }, - { id: 'edit', title: t('editSource'), onAction: edit } - ] - }} - > - {!output && } - actions={ void clipboard()} />} - />} - {output?.outputs.filter(item => `${item.title} ${item.language}`.toLowerCase().includes(query.trim().toLowerCase())).map(item => } - actions={} - />)} -
+ const dialectLabel = getDialectShortLabel(source.dialect) + const caseLabel = getKeywordCaseShortLabel(source.keywordCase) + const showHintBanner = !output && clipboardHint !== null + const summaryText = computeSummaryText({ + tab, + source, + dialectLabel, + caseLabel, + hasOutput: Boolean(output), + isError: state.kind === 'error', + showHintBanner, + clipboardHint, + modes, + guides, + }) + + const normalizedQuery = query.trim().toLowerCase() + const filteredOutputs = output + ? output.outputs.filter(item => + `${item.title} ${item.subtitle} ${item.language}`.toLowerCase().includes(normalizedQuery) + ) + : [] + const primaryOutputs = filteredOutputs.filter(item => item.section === 'primary') + const secondaryOutputs = filteredOutputs.filter(item => item.section === 'secondary') + + const rowHandlers: OutputRowHandlers = { + tab, + source, + dialectLabel, + caseLabel, + onSave: item => void saveOutputItem(item), + onEdit: edit, + onCycleDialect: cycleDialect, + onCycleKeywordCase: cycleKeywordCase, + onToggleDdlNaming: () => + updateCurrentSource(prev => ({ ...prev, namingStyle: prev.namingStyle === 'camel' ? 'snake' : 'camel' })), + onToggleDdlLombok: () => updateCurrentSource(prev => ({ ...prev, javaLombok: !prev.javaLombok })), + onToggleDdlMybatisPlus: () => updateCurrentSource(prev => ({ ...prev, javaMybatisPlus: !prev.javaMybatisPlus })), + onToggleDdlGoGorm: () => updateCurrentSource(prev => ({ ...prev, goGormTag: !prev.goGormTag })), + } + const renderOutputItem = (item: OutputItem) => buildOutputItemElement(item, rowHandlers) + + return ( + void handleTextPaste(text), + }} + onFileInput={handleFileInput} + searchBarAccessory={ + { + revision.current++ + setTab(value as SqlHelperTab) + setQuery('') + }} + tooltip={t('switchToolTooltip')} + > + {Object.entries(modes).map(([value, title]) => ( + + ))} + + } + filterBar={{ + summaryText, + actions: [ + { + id: 'clipboard', + title: showHintBanner ? t('loadDetectedClipboard') : t('loadClipboard'), + ...(output ? {} : { style: 'primary' as const }), + onAction: () => void loadFromClipboard(showHintBanner), + }, + { id: 'edit', title: t('editSource'), onAction: edit }, + ], + }} + > + {!output && + buildEmptyStateItem({ + isError: state.kind === 'error', + errorMessage: state.kind === 'error' ? state.message : undefined, + showHintBanner, + clipboardHint, + guide: guides[tab], + dialectLabel, + onLoadClipboard: () => void loadFromClipboard(showHintBanner), + onEdit: edit, + onCycleDialect: cycleDialect, + })} + + {output && primaryOutputs.length > 0 && ( + + {primaryOutputs.map(renderOutputItem)} + + )} + + {output && secondaryOutputs.length > 0 && ( + + {secondaryOutputs.map(renderOutputItem)} + + )} + + ) } + export const commands = { 'sql-formatter': () => , 'mybatis-merge': () => , diff --git a/extensions/sql-helper/src/sql-helper-service.ts b/extensions/sql-helper/src/sql-helper-service.ts index f9f696f3..07e9a9c6 100644 --- a/extensions/sql-helper/src/sql-helper-service.ts +++ b/extensions/sql-helper/src/sql-helper-service.ts @@ -1,61 +1,455 @@ import { t } from './i18n.js' -import type { FormattedSqlOutput, MyBatisParsedResult, SqlDialect } from './types.js' +import type { + ClipboardSqlHint, + FormattedSqlOutput, + MyBatisBatchResult, + MyBatisLogEntry, + MyBatisParsedResult, + SqlDialect, + SqlFormatOptions, + SqlKeywordCase, +} from './types.js' import { tokenizeSql, checkInput, type SqlToken } from './sql-lexer.js' export { parseDdlToEntities } from './ddl-service.js' -const CLAUSES = new Set(['FROM', 'WHERE', 'HAVING', 'LIMIT', 'OFFSET', 'UNION', 'INTERSECT', 'EXCEPT', 'SET', 'VALUES', 'JOIN']) +const CLAUSES = new Set([ + 'FROM', + 'WHERE', + 'HAVING', + 'LIMIT', + 'OFFSET', + 'UNION', + 'INTERSECT', + 'EXCEPT', + 'SET', + 'VALUES', + 'JOIN', + 'RETURNING', +]) + const JOIN_MODIFIERS = new Set(['LEFT', 'RIGHT', 'INNER', 'CROSS', 'FULL', 'NATURAL', 'OUTER']) -const wordOf = (token: SqlToken | undefined) => token?.kind === 'word' ? token.text.toUpperCase() : '' + +const SQL_KEYWORDS = new Set([ + 'SELECT', + 'DISTINCT', + 'ALL', + 'FROM', + 'WHERE', + 'AND', + 'OR', + 'NOT', + 'IN', + 'IS', + 'NULL', + 'TRUE', + 'FALSE', + 'AS', + 'ON', + 'USING', + 'JOIN', + 'LEFT', + 'RIGHT', + 'INNER', + 'OUTER', + 'FULL', + 'CROSS', + 'NATURAL', + 'GROUP', + 'ORDER', + 'BY', + 'ASC', + 'DESC', + 'HAVING', + 'LIMIT', + 'OFFSET', + 'UNION', + 'INTERSECT', + 'EXCEPT', + 'CASE', + 'WHEN', + 'THEN', + 'ELSE', + 'END', + 'BETWEEN', + 'LIKE', + 'ILIKE', + 'EXISTS', + 'INSERT', + 'INTO', + 'VALUES', + 'UPDATE', + 'SET', + 'DELETE', + 'CREATE', + 'TABLE', + 'TEMPORARY', + 'TEMP', + 'IF', + 'WITH', + 'RECURSIVE', + 'RETURNING', + 'OVER', + 'PARTITION', + 'WINDOW', + 'CAST', + 'PRIMARY', + 'KEY', + 'FOREIGN', + 'REFERENCES', + 'UNIQUE', + 'DEFAULT', + 'CHECK', + 'CONSTRAINT', + 'INDEX', + 'COMMENT', + 'ENGINE', + 'CHARSET', + 'COLLATE', + 'CHARACTER', + 'UNSIGNED', + 'AUTO_INCREMENT', + 'AUTOINCREMENT', + 'BIGINT', + 'INT', + 'INTEGER', + 'SMALLINT', + 'TINYINT', + 'VARCHAR', + 'CHAR', + 'TEXT', + 'DECIMAL', + 'NUMERIC', + 'BOOLEAN', + 'BOOL', + 'DATE', + 'TIME', + 'TIMESTAMP', + 'DATETIME', + 'JSON', + 'JSONB', + 'BLOB', + 'FLOAT', + 'DOUBLE', +]) + +const wordOf = (token: SqlToken | undefined): string => + token?.kind === 'word' ? token.text.toUpperCase() : '' + +function nextSignificantIndex(tokens: SqlToken[], start: number): number { + let i = start + while (i < tokens.length && (tokens[i]!.kind === 'comment' || tokens[i]!.kind === 'lineComment')) { + i++ + } + return i +} + +function prevSignificantToken(tokens: SqlToken[], index: number): SqlToken | undefined { + for (let i = index - 1; i >= 0; i--) { + const tok = tokens[i]! + if (tok.kind !== 'comment' && tok.kind !== 'lineComment') return tok + } + return undefined +} /** * 该词是否开始一个新子句:LEFT / INNER / FULL OUTER 等连接修饰词与 JOIN 作为整体换一次行, * LEFT(name, 3)、RIGHT(...) 这类同名函数与 CHARACTER SET 不换行。 */ function startsClause(tokens: SqlToken[], i: number): boolean { - const upper = wordOf(tokens[i]), previous = wordOf(tokens[i - 1]) + const upper = wordOf(tokens[i]) + const previous = wordOf(prevSignificantToken(tokens, i)) if (!upper) return false if (upper === 'JOIN') return !JOIN_MODIFIERS.has(previous) if (JOIN_MODIFIERS.has(upper)) { if (upper === 'OUTER' || JOIN_MODIFIERS.has(previous)) return false - let j = i + 1 - while (JOIN_MODIFIERS.has(wordOf(tokens[j]))) j++ + let j = nextSignificantIndex(tokens, i + 1) + while (JOIN_MODIFIERS.has(wordOf(tokens[j]))) j = nextSignificantIndex(tokens, j + 1) return wordOf(tokens[j]) === 'JOIN' } if (upper === 'SET') return previous !== 'CHARACTER' - if (upper === 'ORDER' || upper === 'GROUP') return wordOf(tokens[i + 1]) === 'BY' + if (upper === 'ORDER' || upper === 'GROUP') { + const nextIdx = nextSignificantIndex(tokens, i + 1) + return wordOf(tokens[nextIdx]) === 'BY' + } + if (upper === 'SELECT') { + return previous !== '' && previous !== '(' + } return CLAUSES.has(upper) } -/** 仅调整 token 间已有空白,绝不替换字符串、注释、标识符或操作符。 */ -export function formatAndMinifySql(rawSql: string, dialect: SqlDialect = 'mysql'): FormattedSqlOutput { + +/** 判断从 SELECT 位置到当前层 FROM/子句结束之间是否包含多个列(存在顶层逗号)。 */ +function selectHasMultipleColumns(tokens: SqlToken[], selectIndex: number): boolean { + let parenDepth = 0 + let caseDepth = 0 + for (let i = selectIndex + 1; i < tokens.length; i++) { + const tok = tokens[i]! + if (tok.kind === 'comment' || tok.kind === 'lineComment') continue + if (tok.text === '(') { + parenDepth++ + continue + } + if (tok.text === ')') { + if (parenDepth === 0) return false + parenDepth-- + continue + } + if (parenDepth > 0) continue + const upper = wordOf(tok) + if (upper === 'CASE') { + caseDepth++ + continue + } + if (upper === 'END' && caseDepth > 0) { + caseDepth-- + continue + } + if (caseDepth > 0) continue + if (tok.text === ',') return true + if (tok.text === ';' || upper === 'FROM' || upper === 'WHERE' || upper === 'UNION' || upper === 'INTERSECT' || upper === 'EXCEPT' || upper === 'LIMIT' || upper === 'ORDER' || upper === 'GROUP') { + return false + } + } + return false +} + +function formatTokenText(tokens: SqlToken[], index: number, keywordCase: SqlKeywordCase): string { + const token = tokens[index]! + if (keywordCase === 'preserve' || token.kind !== 'word') return token.text + const upper = token.text.toUpperCase() + if (!SQL_KEYWORDS.has(upper)) return token.text + const prev = prevSignificantToken(tokens, index) + if (prev?.text === '.') return token.text + const nextIdx = nextSignificantIndex(tokens, index + 1) + if (tokens[nextIdx]?.text === '(' && (upper === 'LEFT' || upper === 'RIGHT' || upper === 'REPLACE' || upper === 'CHAR' || upper === 'DATE' || upper === 'TIME')) { + return token.text + } + return keywordCase === 'upper' ? upper : upper.toLowerCase() +} + +interface ScopeState { + isSubquery: boolean + clause: 'none' | 'select' | 'from' | 'where' | 'having' | 'other' + multilineSelect: boolean + pendingBetween: boolean + caseDepth: number +} + +function createScope(isSubquery: boolean): ScopeState { + return { + isSubquery, + clause: 'none', + multilineSelect: false, + pendingBetween: false, + caseDepth: 0, + } +} + +/** + * 词法安全格式化与单行压缩: + * 仅调整 token 间空白(及可选 SQL 关键字大小写),绝不破坏字符串、引用标识符、注释与操作符语义。 + */ +export function formatAndMinifySql( + rawSql: string, + dialect: SqlDialect = 'mysql', + options: SqlFormatOptions = {} +): FormattedSqlOutput { const tokens = tokenizeSql(rawSql, dialect) - if (!tokens.some(t => t.kind !== 'comment' && t.kind !== 'lineComment')) throw new Error(t('enterSqlStatement')) - let beautified = '', minified = '', depth = 0 - for (const [i, token] of tokens.entries()) { - const previous = tokens[i - 1], gap = previous ? rawSql.slice(previous.end, token.start) : '' - // PostgreSQL 的相邻字符串仅在含换行的空白之间才自动拼接;行注释也必须保留换行。 + if (!tokens.some(tok => tok.kind !== 'comment' && tok.kind !== 'lineComment')) { + throw new Error(t('enterSqlStatement')) + } + + const keywordCase: SqlKeywordCase = options.keywordCase ?? 'preserve' + const indentUnit = ' '.repeat(options.indentWidth === 4 ? 4 : 2) + const scopes: ScopeState[] = [createScope(false)] + let subqueryDepth = 0 + + const currentScope = (): ScopeState => scopes[scopes.length - 1]! + const indentAt = (extra = 0): string => indentUnit.repeat(Math.max(0, subqueryDepth + extra)) + + let beautified = '' + let minified = '' + + for (let i = 0; i < tokens.length; i++) { + const token = tokens[i]! + const previous = tokens[i - 1] + const gap = previous ? rawSql.slice(previous.end, token.start) : '' + const hasGap = gap.length > 0 + const upper = wordOf(token) + const prevSig = prevSignificantToken(tokens, i) + const prevSigUpper = wordOf(prevSig) + + // PostgreSQL 的相邻字符串仅在含换行的空白之间才自动拼接;行注释后也必须保留换行。 const needsNewline = previous?.kind === 'lineComment' || (dialect === 'postgresql' && /[\r\n]/.test(gap)) - const compactGap = needsNewline ? '\n' : gap ? ' ' : '' + const compactGap = needsNewline ? '\n' : hasGap ? ' ' : '' + const displayText = formatTokenText(tokens, i, keywordCase) + + // 先处理闭括号对作用域的出栈 + let closingSubquery = false + if (token.text === ')' && scopes.length > 1) { + const popped = scopes.pop()! + if (popped.isSubquery) { + subqueryDepth = Math.max(0, subqueryDepth - 1) + closingSubquery = true + } + } + + const scope = currentScope() let prettyGap = compactGap - if (gap && (startsClause(tokens, i) || previous?.text === ';')) prettyGap = '\n' + ' '.repeat(depth) - if (token.text === ')') depth-- - beautified += prettyGap + token.text + + if (previous) { + if (closingSubquery) { + prettyGap = '\n' + indentAt() + } else if (previous.text === ';') { + prettyGap = '\n' + indentAt() + } else if (previous.kind === 'lineComment') { + prettyGap = '\n' + indentAt(scope.clause === 'select' && scope.multilineSelect ? 1 : 0) + } else if (hasGap && startsClause(tokens, i)) { + prettyGap = '\n' + indentAt() + } else if ( + hasGap && + (upper === 'AND' || upper === 'OR') && + (scope.clause === 'where' || scope.clause === 'having') && + scope.caseDepth === 0 + ) { + if (upper === 'AND' && scope.pendingBetween) { + scope.pendingBetween = false + } else { + prettyGap = '\n' + indentAt(1) + } + } else if (hasGap && (upper === 'WHEN' || upper === 'ELSE') && scope.caseDepth > 0) { + prettyGap = '\n' + indentAt(scope.caseDepth + 1) + } else if (hasGap && upper === 'END' && scope.caseDepth > 0) { + prettyGap = '\n' + indentAt(scope.caseDepth) + } else if ( + previous.text === ',' && + scope.clause === 'select' && + scope.multilineSelect && + scope.caseDepth === 0 + ) { + prettyGap = '\n' + indentAt(1) + } else if ( + scope.clause === 'select' && + scope.multilineSelect && + hasGap && + (prevSigUpper === 'SELECT' || prevSigUpper === 'DISTINCT' || prevSigUpper === 'ALL') && + upper !== 'DISTINCT' && + upper !== 'ALL' && + token.kind !== 'comment' && + token.kind !== 'lineComment' + ) { + prettyGap = '\n' + indentAt(1) + } else if (previous.text === '(' && scope.isSubquery && (upper === 'SELECT' || upper === 'WITH')) { + prettyGap = '\n' + indentAt() + } + } + + beautified += prettyGap + displayText minified += compactGap + token.text - if (token.text === '(') depth++ + + // 更新当前作用域状态 + if (token.text === ';') { + scope.clause = 'none' + scope.multilineSelect = false + scope.pendingBetween = false + scope.caseDepth = 0 + } else if (token.text === '(') { + const nextIdx = nextSignificantIndex(tokens, i + 1) + const nextUpper = wordOf(tokens[nextIdx]) + const isSub = nextUpper === 'SELECT' || nextUpper === 'WITH' + if (isSub) subqueryDepth++ + scopes.push(createScope(isSub)) + } else if (upper === 'SELECT') { + scope.clause = 'select' + scope.multilineSelect = selectHasMultipleColumns(tokens, i) + scope.pendingBetween = false + } else if (upper === 'FROM') { + scope.clause = 'from' + scope.multilineSelect = false + scope.pendingBetween = false + } else if (upper === 'WHERE') { + scope.clause = 'where' + scope.multilineSelect = false + scope.pendingBetween = false + } else if (upper === 'HAVING') { + scope.clause = 'having' + scope.multilineSelect = false + scope.pendingBetween = false + } else if ( + upper === 'GROUP' || + upper === 'ORDER' || + upper === 'LIMIT' || + upper === 'OFFSET' || + upper === 'UNION' || + upper === 'INTERSECT' || + upper === 'EXCEPT' || + upper === 'SET' || + upper === 'VALUES' || + upper === 'RETURNING' + ) { + scope.clause = 'other' + scope.multilineSelect = false + scope.pendingBetween = false + } else if (upper === 'BETWEEN') { + scope.pendingBetween = true + } else if (upper === 'CASE') { + scope.caseDepth++ + } else if (upper === 'END' && scope.caseDepth > 0) { + scope.caseDepth-- + } + } + + return { + beautified, + minified, + charCount: beautified.length, + lineCount: beautified.split('\n').length, } - return { beautified, minified, charCount: beautified.length, lineCount: beautified.split('\n').length } } -const NUMERIC = new Set(['long', 'integer', 'int', 'short', 'byte', 'double', 'float', 'bigdecimal', 'biginteger', 'number']) -const TEXT = new Set(['string', 'character', 'char', 'uuid', 'date', 'time', 'timestamp', 'localdate', 'localtime', 'localdatetime', 'offsetdatetime', 'offsettime', 'instant']) +const NUMERIC = new Set([ + 'long', + 'integer', + 'int', + 'short', + 'byte', + 'double', + 'float', + 'bigdecimal', + 'biginteger', + 'number', +]) + +const TEXT = new Set([ + 'string', + 'character', + 'char', + 'uuid', + 'date', + 'time', + 'timestamp', + 'localdate', + 'localtime', + 'localdatetime', + 'offsetdatetime', + 'offsettime', + 'instant', +]) + function parameter(part: string, dialect: SqlDialect): MyBatisParsedResult['params'][number] { if (part === 'null') return { value: 'null', type: 'Null', injectedSqlPart: 'NULL' } const match = part.match(/^([\s\S]*)\(([A-Za-z0-9_$.]+)\)$/) if (!match) throw new Error(t('missingTypeTag')) - const value = match[1]!, type = match[2]!.split('.').at(-1)!, lower = type.toLowerCase() + const value = match[1]! + const type = match[2]!.split('.').at(-1)! + const lower = type.toLowerCase() let injectedSqlPart: string if (NUMERIC.has(lower)) { - if (/^(long|integer|int|short|byte|biginteger)$/.test(lower) && !/^[+-]?\d+$/.test(value)) throw new Error(t('invalidIntParam', { type })) - if (!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(value)) throw new Error(t('invalidNumParam', { type })) + if (/^(long|integer|int|short|byte|biginteger)$/.test(lower) && !/^[+-]?\d+$/.test(value)) { + throw new Error(t('invalidIntParam', { type })) + } + if (!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(value)) { + throw new Error(t('invalidNumParam', { type })) + } injectedSqlPart = value } else if (lower === 'boolean' || lower === 'bool') { if (!/^(true|false)$/i.test(value)) throw new Error(t('invalidBoolParam')) @@ -63,45 +457,316 @@ function parameter(part: string, dialect: SqlDialect): MyBatisParsedResult['para } else if (TEXT.has(lower)) { const escaped = (dialect === 'mysql' ? value.replace(/\\/g, '\\\\') : value).replace(/'/g, "''") injectedSqlPart = `'${escaped}'` - } else throw new Error(t('unsupportedParamType', { type })) + } else { + throw new Error(t('unsupportedParamType', { type })) + } return { value, type, injectedSqlPart } } -/** MyBatis 文本日志没有转义协议,只生成核对参考,不宣称可无损还原绑定语义。 */ -export function mergeMyBatisLog(rawLogText: string, dialect: SqlDialect = 'mysql'): MyBatisParsedResult { - let params: MyBatisParsedResult['params'] = [], placeholderCount = 0, rawPreparing = '', hasCountMismatch = false +function summarizeSqlStatement(sql: string, index: number): string { + const cleaned = sql.trim() + const verbMatch = cleaned.match(/^(SELECT|INSERT|UPDATE|DELETE|WITH|MERGE|REPLACE|CALL)\b/i) + const verb = verbMatch ? verbMatch[1]!.toUpperCase() : 'SQL' + let table = '' + if (verb === 'SELECT' || verb === 'DELETE') { + const m = cleaned.match(/\bFROM\s+[`"\[]?([A-Za-z0-9_.$]+)[`"\]]?/i) + table = m?.[1] ?? '' + } else if (verb === 'UPDATE') { + const m = cleaned.match(/\bUPDATE\s+[`"\[]?([A-Za-z0-9_.$]+)[`"\]]?/i) + table = m?.[1] ?? '' + } else if (verb === 'INSERT' || verb === 'REPLACE') { + const m = cleaned.match(/\bINTO\s+[`"\[]?([A-Za-z0-9_.$]+)[`"\]]?/i) + table = m?.[1] ?? '' + } + return table ? `#${index} ${verb} ${table}` : `#${index} ${verb}` +} + +function mergeSinglePair( + rawPreparing: string, + rawParameters: string, + dialect: SqlDialect, + formatOptions: SqlFormatOptions, + preparingLine?: number, + parametersLine?: number +): MyBatisParsedResult { + let params: MyBatisParsedResult['params'] = [] + let placeholderCount = 0 + let hasCountMismatch = false try { - checkInput(rawLogText) - const records = rawLogText.replace(/\r\n/g, '\n').split('\n').filter(line => line.trim() !== '').map(line => line.match(/^(?:.*?==>\s*)?(Preparing|Parameters): ?(.*)$/i)) - if (records.some(record => !record) || records.length !== 2 || records[0]![1]!.toLowerCase() !== 'preparing' || records[1]![1]!.toLowerCase() !== 'parameters') throw new Error(t('mybatisTwoLinesRequired')) - rawPreparing = records[0]![2]! - const rawParameters = records[1]![2]! const tokens = tokenizeSql(rawPreparing, dialect) - const placeholders = tokens.filter(t => t.kind === 'symbol' && t.text === '?') + const placeholders = tokens.filter(tok => tok.kind === 'symbol' && tok.text === '?') placeholderCount = placeholders.length if (placeholderCount > 500) throw new Error(t('tooManyParams500')) - if (tokens.some(t => t.kind === 'word' && /^(Preparing|Parameters)$/i.test(t.text))) throw new Error(t('logMarkersInSql')) + if (tokens.some(tok => tok.kind === 'word' && /^(Preparing|Parameters)$/i.test(tok.text))) { + throw new Error(t('logMarkersInSql')) + } if (dialect === 'postgresql') { for (const p of placeholders) { - const index = tokens.indexOf(p), prev = tokens[index - 1] - if (prev && !['(', ',', '=', '<', '>', '!', '+', '-', '*', '/', '%'].includes(prev.text) && !(prev.kind === 'word' && /^(SELECT|VALUES|WHEN|THEN|ELSE|AND|OR|NOT|LIMIT|OFFSET|BY|RETURNING)$/i.test(prev.text))) throw new Error(t('pgQuestionMarkOperator')) + const idx = tokens.indexOf(p) + const prev = tokens[idx - 1] + if ( + prev && + !['(', ',', '=', '<', '>', '!', '+', '-', '*', '/', '%'].includes(prev.text) && + !( + prev.kind === 'word' && + /^(SELECT|VALUES|WHEN|THEN|ELSE|AND|OR|NOT|LIMIT|OFFSET|BY|RETURNING)$/i.test(prev.text) + ) + ) { + throw new Error(t('pgQuestionMarkOperator')) + } } } const parts: string[] = [] let start = 0 for (let i = 0; i < rawParameters.length; i++) { - if (rawParameters.startsWith(', ', i) && /(?:\([A-Za-z0-9_$.]{1,128}\)|(?:^|, )null)$/.test(rawParameters.slice(Math.max(start, i - 132), i))) { parts.push(rawParameters.slice(start, i)); start = i + 2; if (parts.length > 500) throw new Error(t('tooManyParams')) } + if ( + rawParameters.startsWith(', ', i) && + /(?:\([A-Za-z0-9_$.]{1,128}\)|(?:^|, )null)$/.test(rawParameters.slice(Math.max(start, i - 132), i)) + ) { + parts.push(rawParameters.slice(start, i)) + start = i + 2 + if (parts.length > 500) throw new Error(t('tooManyParams')) + } } if (rawParameters !== '') parts.push(rawParameters.slice(start)) hasCountMismatch = parts.length !== placeholderCount - if (hasCountMismatch) throw new Error(t('paramCountMismatch', { placeholders: placeholderCount, parts: parts.length })) + if (hasCountMismatch) { + throw new Error(t('paramCountMismatch', { placeholders: placeholderCount, parts: parts.length })) + } params = parts.map(part => parameter(part, dialect)) - let mergedSql = '', cursor = 0 - for (const [i, token] of placeholders.entries()) { mergedSql += rawPreparing.slice(cursor, token.start) + params[i]!.injectedSqlPart; cursor = token.end } + let mergedSql = '' + let cursor = 0 + for (const [i, tok] of placeholders.entries()) { + mergedSql += rawPreparing.slice(cursor, tok.start) + params[i]!.injectedSqlPart + cursor = tok.end + } mergedSql += rawPreparing.slice(cursor) - const formatted = formatAndMinifySql(mergedSql, dialect) - return { isSuccess: true, hasCountMismatch: false, rawPreparing, mergedSql, beautifiedMergedSql: formatted.beautified, placeholderCount, params, paramCountDisplay: t('paramMatchedSummary', { count: params.length }) } + const formatted = formatAndMinifySql(mergedSql, dialect, formatOptions) + return { + isSuccess: true, + hasCountMismatch: false, + rawPreparing, + mergedSql, + beautifiedMergedSql: formatted.beautified, + minifiedMergedSql: formatted.minified, + placeholderCount, + params, + preparingLine, + parametersLine, + paramCountDisplay: t('paramMatchedSummary', { count: params.length }), + } } catch (error) { - return { isSuccess: false, hasCountMismatch, errorMessage: error instanceof Error ? error.message : String(error), rawPreparing, mergedSql: '', beautifiedMergedSql: '', paramCountDisplay: t('noResultGenerated'), placeholderCount, params } + return { + isSuccess: false, + hasCountMismatch, + errorMessage: error instanceof Error ? error.message : String(error), + rawPreparing, + mergedSql: '', + beautifiedMergedSql: '', + minifiedMergedSql: '', + paramCountDisplay: t('noResultGenerated'), + placeholderCount, + params, + preparingLine, + parametersLine, + } } } + +const MYBATIS_LINE_PATTERN = + /^(?:.*?==>\s*|(?:\d{4}[-/]\d{2}[-/]\d{2}|\d{2}:\d{2}:\d{2}|\[[^\]]+\]|(?:TRACE|DEBUG|INFO|WARN|ERROR)\b)[^\n]*?[\s:\]-]\s*|\s*)(Preparing|Parameters): ?(.*)$/i + +/** + * 从混杂多行控制台日志中提取全部 Preparing + Parameters 组并逐组还原为可执行参考 SQL。 + * 自动忽略时间戳、INFO/DEBUG 日志前缀、Total/Updates 行与无关业务日志;单组异常精准标注行号。 + */ +export function extractAndMergeMyBatisLogs( + rawLogText: string, + dialect: SqlDialect = 'mysql', + formatOptions: SqlFormatOptions = {} +): MyBatisBatchResult { + try { + checkInput(rawLogText) + const lines = rawLogText.replace(/\r\n/g, '\n').split('\n') + const entries: MyBatisLogEntry[] = [] + let pendingPreparing: { text: string; line: number } | null = null + + const pushMissingParametersEntry = (pending: { text: string; line: number }) => { + const idx = entries.length + 1 + entries.push({ + index: idx, + summary: summarizeSqlStatement(pending.text, idx), + isSuccess: false, + hasCountMismatch: false, + errorMessage: t('mybatisMissingParameters', { line: pending.line }), + rawPreparing: pending.text, + mergedSql: '', + beautifiedMergedSql: '', + minifiedMergedSql: '', + paramCountDisplay: t('noResultGenerated'), + placeholderCount: 0, + params: [], + preparingLine: pending.line, + }) + } + + for (let i = 0; i < lines.length; i++) { + const lineNo = i + 1 + const line = lines[i]! + const trimmed = line.trim() + if (!trimmed) continue + + const match = line.match(MYBATIS_LINE_PATTERN) + if (!match) continue + + const marker = match[1]!.toLowerCase() + const payload = match[2]! + + if (marker === 'preparing') { + if (pendingPreparing) pushMissingParametersEntry(pendingPreparing) + pendingPreparing = { text: payload, line: lineNo } + } else if (marker === 'parameters') { + if (!pendingPreparing) { + const idx = entries.length + 1 + entries.push({ + index: idx, + summary: `#${idx} Parameters`, + isSuccess: false, + hasCountMismatch: false, + errorMessage: t('mybatisOrphanParameters', { line: lineNo }), + rawPreparing: '', + mergedSql: '', + beautifiedMergedSql: '', + minifiedMergedSql: '', + paramCountDisplay: t('noResultGenerated'), + placeholderCount: 0, + params: [], + parametersLine: lineNo, + }) + continue + } + const idx = entries.length + 1 + const parsed = mergeSinglePair( + pendingPreparing.text, + payload, + dialect, + formatOptions, + pendingPreparing.line, + lineNo + ) + entries.push({ + ...parsed, + index: idx, + summary: summarizeSqlStatement(pendingPreparing.text, idx), + }) + pendingPreparing = null + } + } + + if (pendingPreparing) pushMissingParametersEntry(pendingPreparing) + + if (entries.length === 0) { + return { + isSuccess: false, + errorMessage: t('mybatisTwoLinesRequired'), + entries: [], + successCount: 0, + failureCount: 0, + combinedBeautifiedSql: '', + combinedMinifiedSql: '', + } + } + + const succeeded = entries.filter(e => e.isSuccess) + const failed = entries.filter(e => !e.isSuccess) + const ensureSemicolon = (sql: string) => (sql.trimEnd().endsWith(';') ? sql.trimEnd() : `${sql.trimEnd()};`) + + return { + isSuccess: succeeded.length > 0, + errorMessage: succeeded.length === 0 ? failed[0]?.errorMessage ?? t('mybatisTwoLinesRequired') : undefined, + entries, + successCount: succeeded.length, + failureCount: failed.length, + combinedBeautifiedSql: succeeded.map(e => ensureSemicolon(e.beautifiedMergedSql)).join('\n\n'), + combinedMinifiedSql: succeeded.map(e => ensureSemicolon(e.minifiedMergedSql ?? e.mergedSql)).join('\n'), + } + } catch (error) { + return { + isSuccess: false, + errorMessage: error instanceof Error ? error.message : String(error), + entries: [], + successCount: 0, + failureCount: 0, + combinedBeautifiedSql: '', + combinedMinifiedSql: '', + } + } +} + +/** 严格两行 MyBatis 文本日志还原接口(向后兼容单组严格契约)。 */ +export function mergeMyBatisLog( + rawLogText: string, + dialect: SqlDialect = 'mysql', + formatOptions: SqlFormatOptions = {} +): MyBatisParsedResult { + try { + checkInput(rawLogText) + const records = rawLogText + .replace(/\r\n/g, '\n') + .split('\n') + .filter(line => line.trim() !== '') + .map(line => line.match(/^(?:.*?==>\s*)?(Preparing|Parameters): ?(.*)$/i)) + if ( + records.some(record => !record) || + records.length !== 2 || + records[0]![1]!.toLowerCase() !== 'preparing' || + records[1]![1]!.toLowerCase() !== 'parameters' + ) { + throw new Error(t('mybatisTwoLinesRequired')) + } + return mergeSinglePair(records[0]![2]!, records[1]![2]!, dialect, formatOptions, 1, 2) + } catch (error) { + return { + isSuccess: false, + hasCountMismatch: false, + errorMessage: error instanceof Error ? error.message : String(error), + rawPreparing: '', + mergedSql: '', + beautifiedMergedSql: '', + minifiedMergedSql: '', + paramCountDisplay: t('noResultGenerated'), + placeholderCount: 0, + params: [], + } + } +} + +/** 轻量检测剪贴板内容是否命中 MyBatis 日志 / CREATE TABLE DDL / SQL 语句。 */ +export function detectClipboardSqlHint(rawText: string): ClipboardSqlHint | null { + const text = rawText.trim() + if (!text || text.length > 256 * 1024) return null + + const lines = text.replace(/\r\n/g, '\n').split('\n') + let prepCount = 0 + let paramCount = 0 + for (const line of lines) { + const match = line.match(MYBATIS_LINE_PATTERN) + if (!match) continue + if (match[1]!.toLowerCase() === 'preparing') prepCount++ + else paramCount++ + } + if (prepCount > 0 && paramCount > 0) { + return { tab: 'mybatis', count: Math.min(prepCount, paramCount), preview: text.slice(0, 80) } + } + + const createMatches = text.match(/\bCREATE\s+(?:TEMP(?:ORARY)?\s+)?TABLE\b/gi) + if (createMatches && createMatches.length > 0) { + return { tab: 'ddl', count: createMatches.length, preview: text.slice(0, 80) } + } + + if (/^(?:--[^\n]*\n\s*|\/\*[\s\S]*?\*\/\s*)*(?:SELECT|WITH|INSERT\s+INTO|UPDATE\s+\S+\s+SET|DELETE\s+FROM)\b/i.test(text)) { + return { tab: 'formatter', count: 1, preview: text.slice(0, 80) } + } + + return null +} diff --git a/extensions/sql-helper/src/types.ts b/extensions/sql-helper/src/types.ts index da69d2a0..df1269d1 100644 --- a/extensions/sql-helper/src/types.ts +++ b/extensions/sql-helper/src/types.ts @@ -2,6 +2,15 @@ export type SqlDialect = 'mysql' | 'postgresql' | 'sqlite' export type SqlHelperTab = 'formatter' | 'mybatis' | 'ddl' +export type SqlKeywordCase = 'preserve' | 'upper' | 'lower' + +export type DdlNamingStyle = 'camel' | 'snake' + +export interface SqlFormatOptions { + keywordCase?: SqlKeywordCase + indentWidth?: 2 | 4 +} + export interface FormattedSqlOutput { beautified: string minified: string @@ -9,6 +18,12 @@ export interface FormattedSqlOutput { lineCount: number } +export interface MyBatisParamItem { + value: string + type: string + injectedSqlPart: string +} + export interface MyBatisParsedResult { isSuccess: boolean hasCountMismatch: boolean @@ -16,13 +31,34 @@ export interface MyBatisParsedResult { rawPreparing: string mergedSql: string beautifiedMergedSql: string + minifiedMergedSql?: string paramCountDisplay: string placeholderCount: number - params: Array<{ - value: string - type: string - injectedSqlPart: string - }> + params: MyBatisParamItem[] + preparingLine?: number + parametersLine?: number +} + +export interface MyBatisLogEntry extends MyBatisParsedResult { + index: number + summary: string +} + +export interface MyBatisBatchResult { + isSuccess: boolean + errorMessage?: string + entries: MyBatisLogEntry[] + successCount: number + failureCount: number + combinedBeautifiedSql: string + combinedMinifiedSql: string +} + +export interface DdlCodegenOptions { + namingStyle?: DdlNamingStyle + javaLombok?: boolean + javaMybatisPlus?: boolean + goGormTag?: boolean } export interface DdlParsedColumn { @@ -31,13 +67,27 @@ export interface DdlParsedColumn { nullable: boolean comment?: string unsigned?: boolean + isPrimaryKey?: boolean +} + +export interface DdlTableResult { + tableName: string + columns: DdlParsedColumn[] + warnings: string[] + generatedCode: { + typescript: string + golang: string + java: string + } } export interface DdlParsedResult { isValid: boolean warningMessage?: string tableName: string + tableNames: string[] columns: DdlParsedColumn[] + tables: DdlTableResult[] warnings: string[] generatedCode: { typescript: string @@ -45,3 +95,9 @@ export interface DdlParsedResult { java: string } } + +export interface ClipboardSqlHint { + tab: SqlHelperTab + count: number + preview: string +} diff --git a/extensions/sql-helper/tests/index.test.mjs b/extensions/sql-helper/tests/index.test.mjs index 8a472a31..88099557 100644 --- a/extensions/sql-helper/tests/index.test.mjs +++ b/extensions/sql-helper/tests/index.test.mjs @@ -8,47 +8,112 @@ import { fileURLToPath } from 'node:url' import { execFileSync, spawnSync } from 'node:child_process' import { getDeclarativeBridge } from '@ztools/declarative-ui' import { createHost, mount, mountPushed, tick } from '../../shared/test-harness.mjs' -import { commands, formatAndMinifySql, mergeMyBatisLog, parseDdlToEntities } from '../dist/index.js' +import { + commands, + detectClipboardSqlHint, + extractAndMergeMyBatisLogs, + formatAndMinifySql, + mergeMyBatisLog, + parseDdlToEntities, +} from '../dist/index.js' -const host = createHost(), views = [] +const host = createHost() +const views = [] test.beforeEach(() => host.reset()) test.afterEach(() => views.splice(0).forEach(v => v.unmount())) -async function open(tab = 'sql-formatter') { const view = await mount(commands[tab]); views.push(view); return view } + +async function open(tab = 'sql-formatter') { + const view = await mount(commands[tab]) + views.push(view) + return view +} + async function edit(view, source, dialect = 'sqlite') { - if (view.items().some(item => item.props.id === 'input')) await view.run(view.item('input'), '编辑源码') - else { view.tree().props.filterBar.actions.find(a => a.id === 'edit').onAction(); await tick() } - const form = await mountPushed(host); views.push(form) - await form.fill('dialect', dialect); await form.fill('source', source) + if (view.items().some(item => item.props.id === 'input')) { + await view.run(view.item('input'), '编辑 SQL') + } else { + view.tree().props.filterBar.actions.find(a => a.id === 'edit').onAction() + await tick() + } + const form = await mountPushed(host) + views.push(form) + await form.fill('dialect', dialect) + await form.fill('source', source) return form } -async function submit(form) { await form.run(null, '生成结果'); await tick() } + +async function submit(form) { + await form.run(null, '生成结果') + await tick() +} const sqliteCases = [ - "select 1 -- 保留注释结束\n + 2 as total;", + 'select 1 -- 保留注释结束\n + 2 as total;', "select ' a b\n c' as \"order by\", 'O''Reilly' as value;", - "select 4 /* ? */ + 3, 1 != 2, 8 >= 4, 8 << 1;", + 'select 4 /* ? */ + 3, 1 != 2, 8 >= 4, 8 << 1;', "select '__ZSQL_LIT_0__', '__ZSQL_LIT_1__', '```sql', '/*x*/';", - "with sample as (select 1 as n union all select 2) select sum(n) from sample where n > 0;", + 'with sample as (select 1 as n union all select 2) select sum(n) from sample where n > 0;', "select json_extract('{\"x\": 2}', '$.x') as n;", ] + test('SQLite 实际执行:格式化及精简保持注释、字面量和操作符语义', () => { const db = new DatabaseSync(':memory:') try { for (const source of sqliteCases) { - const expected = db.prepare(source).all(), result = formatAndMinifySql(source, 'sqlite') - assert.deepEqual(db.prepare(result.beautified).all(), expected) - assert.deepEqual(db.prepare(result.minified).all(), expected) + const expected = db.prepare(source).all() + for (const keywordCase of ['preserve', 'upper', 'lower']) { + const result = formatAndMinifySql(source, 'sqlite', { keywordCase }) + assert.deepEqual(db.prepare(result.beautified).all(), expected) + assert.deepEqual(db.prepare(result.minified).all(), expected) + } } db.exec('CREATE TABLE unicode_names(foo INTEGER, "foo\u00a0bar" INTEGER); INSERT INTO unicode_names VALUES (1, 2)') const unicodeSql = 'SELECT foo\u00a0bar FROM unicode_names' - for (const output of [formatAndMinifySql(unicodeSql, 'sqlite').beautified, formatAndMinifySql(unicodeSql, 'sqlite').minified]) assert.deepEqual(db.prepare(output).all(), db.prepare(unicodeSql).all()) + for (const output of [ + formatAndMinifySql(unicodeSql, 'sqlite').beautified, + formatAndMinifySql(unicodeSql, 'sqlite').minified, + ]) { + assert.deepEqual(db.prepare(output).all(), db.prepare(unicodeSql).all()) + } db.exec('CREATE TABLE t (__ZSQL_LIT_0__ INTEGER, "order by" TEXT); INSERT INTO t VALUES (4, \'原字段\')') const source = 'select __ZSQL_LIT_0__, `order by` from t' - for (const result of Object.values(formatAndMinifySql(source, 'sqlite')).filter(v => typeof v === 'string')) assert.deepEqual(db.prepare(result).all(), db.prepare(source).all()) - } finally { db.close() } + for (const result of Object.values(formatAndMinifySql(source, 'sqlite')).filter(v => typeof v === 'string')) { + assert.deepEqual(db.prepare(result).all(), db.prepare(source).all()) + } + } finally { + db.close() + } +}) + +test('SQL 多级缩进美化:SELECT 列换行、WHERE AND/OR 缩进、BETWEEN 保护、CASE WHEN 与子查询', () => { + const sql = + "select o.id, o.order_sn, case when o.total > 100 then 'high' else 'low' end as tier from orders o where o.status = 'PAID' and o.created_at between '2026-01-01' and '2026-12-31' and o.user_id in (select u.id from users u where u.active = 1 and u.role = 'vip') group by o.id having count(*) > 0 and sum(o.total) > 10 order by o.id desc limit 20;" + const { beautified } = formatAndMinifySql(sql, 'sqlite', { keywordCase: 'upper', indentWidth: 2 }) + assert.match(beautified, /^SELECT\n o\.id,\n o\.order_sn,/) + assert.match(beautified, /\nWHERE o\.status = 'PAID'\n AND o\.created_at BETWEEN '2026-01-01' AND '2026-12-31'\n AND o\.user_id IN \(\n SELECT u\.id\n FROM users u\n WHERE u\.active = 1\n AND u\.role = 'vip'\n\)/) + assert.match(beautified, /\nGROUP BY o\.id\nHAVING count\(\*\) > 0\n AND sum\(o\.total\) > 10\nORDER BY o\.id DESC\nLIMIT 20;/) + // 确保字符串内字面量大小写未被修改 + assert.match(beautified, /'PAID'/) + assert.match(beautified, /'high'/) + assert.match(beautified, /'vip'/) + + const db = new DatabaseSync(':memory:') + try { + db.exec( + "CREATE TABLE users(id INTEGER, active INTEGER, role TEXT); CREATE TABLE orders(id INTEGER, order_sn TEXT, total INTEGER, status TEXT, created_at TEXT, user_id INTEGER);" + ) + db.exec( + "INSERT INTO users VALUES (1, 1, 'vip'); INSERT INTO orders VALUES (10, 'SN1', 200, 'PAID', '2026-06-01', 1);" + ) + assert.deepEqual(db.prepare(beautified).all(), db.prepare(sql).all()) + } finally { + db.close() + } }) + test('SQL 方言:必要换行、MySQL注释、PG dollar字符串及嵌套注释保持原文', () => { - const pg = "select $tag$ from ' ? \n 中文 $tag$, E'O\\'Reilly', 'one'\n 'two' /* outer /* nested */ still */ from sample" + const pg = + "select $tag$ from ' ? \n 中文 $tag$, E'O\\'Reilly', 'one'\n 'two' /* outer /* nested */ still */ from sample" const formatted = formatAndMinifySql(pg, 'postgresql') for (const output of [formatted.beautified, formatted.minified]) { assert.match(output, /\$tag\$ from ' \? \n 中文 \$tag\$/) @@ -59,27 +124,83 @@ test('SQL 方言:必要换行、MySQL注释、PG dollar字符串及嵌套注 const mysql = "select `order by`, 'a\\'b' # 注释\n from t where x=1--2" assert.match(formatAndMinifySql(mysql).minified, /# 注释\nfrom t/) assert.match(formatAndMinifySql(mysql).minified, /1--2$/) - assert.equal(formatAndMinifySql('select 1 --' + String.fromCharCode(127) + 'note\n+2').minified, 'select 1 --' + String.fromCharCode(127) + 'note\n+2') + assert.equal( + formatAndMinifySql('select 1 --' + String.fromCharCode(127) + 'note\n+2').minified, + 'select 1 --' + String.fromCharCode(127) + 'note\n+2' + ) for (const invalid of ['', '/* 注释 */', "select 'broken", 'select (1', 'select 1)', 'select /* bad', 'select $$bad']) { assert.throws(() => formatAndMinifySql(invalid, 'postgresql')) } assert.throws(() => formatAndMinifySql('x'.repeat(256 * 1024 + 1))) - assert.throws(() => formatAndMinifySql('select (' .repeat(65))) + assert.throws(() => formatAndMinifySql('select ('.repeat(65))) }) + test('MyBatis 实际 SQLite:引号、反斜杠、逗号、NULL、布尔和精确数字还原', () => { - const source = "==> Preparing: SELECT ? as author, ? as path, ? as location, ? as absent, ? as enabled, ? as n, '?' as literal /* ? */\n==> Parameters: O'Reilly(String), C:\\temp\\file(String), Seattle, WA(String), null, true(Boolean), 1.2e3(Double)" + const source = + "==> Preparing: SELECT ? as author, ? as path, ? as location, ? as absent, ? as enabled, ? as n, '?' as literal /* ? */\n==> Parameters: O'Reilly(String), C:\\temp\\file(String), Seattle, WA(String), null, true(Boolean), 1.2e3(Double)" const result = mergeMyBatisLog(source, 'sqlite') assert.equal(result.isSuccess, true, result.errorMessage) assert.equal(result.placeholderCount, 6) const db = new DatabaseSync(':memory:') - try { assert.deepEqual({ ...db.prepare(result.mergedSql).get() }, { author: "O'Reilly", path: 'C:\\temp\\file', location: 'Seattle, WA', absent: null, enabled: 1, n: 1200, literal: '?' }) } - finally { db.close() } - const mysql = mergeMyBatisLog('Preparing: SELECT ?\nParameters: a\\b\'c(String)') + try { + assert.deepEqual({ ...db.prepare(result.mergedSql).get() }, { + author: "O'Reilly", + path: 'C:\\temp\\file', + location: 'Seattle, WA', + absent: null, + enabled: 1, + n: 1200, + literal: '?', + }) + } finally { + db.close() + } + const mysql = mergeMyBatisLog("Preparing: SELECT ?\nParameters: a\\b'c(String)") assert.equal(mysql.mergedSql, "SELECT 'a\\\\b''c'") assert.equal(mergeMyBatisLog('Preparing: SELECT 1\nParameters: ', 'sqlite').isSuccess, true) assert.equal(mergeMyBatisLog('Preparing: SELECT ?\nFROM t\nParameters: 1(Integer)', 'sqlite').isSuccess, false) - assert.equal(mergeMyBatisLog('Preparing: SELECT ?\nParameters: 9223372036854775807(Long)', 'sqlite').mergedSql, 'SELECT 9223372036854775807') + assert.equal( + mergeMyBatisLog('Preparing: SELECT ?\nParameters: 9223372036854775807(Long)', 'sqlite').mergedSql, + 'SELECT 9223372036854775807' + ) +}) + +test('MyBatis 混杂多行控制台日志批量提取:自动忽略时间戳/INFO/Total 并逐组还原与行号隔离', () => { + const mixedLog = [ + '2026-12-01 14:20:01.102 INFO [http-nio-8080-exec-1] c.e.OrderService : start query', + '2026-12-01 14:20:01.115 DEBUG [http-nio-8080-exec-1] c.e.m.OrderMapper.selectList : ==> Preparing: SELECT o.id, o.order_sn FROM orders o WHERE o.status = ? AND o.user_id = ?', + '2026-12-01 14:20:01.116 DEBUG [http-nio-8080-exec-1] c.e.m.OrderMapper.selectList : ==> Parameters: PAID(String), 10086(Long)', + '2026-12-01 14:20:01.120 DEBUG [http-nio-8080-exec-1] c.e.m.OrderMapper.selectList : <== Total: 2', + '', + '2026-12-01 14:20:02.001 DEBUG [http-nio-8080-exec-1] c.e.m.OrderMapper.updateStatus : ==> Preparing: UPDATE orders SET status = ? WHERE id = ?', + '2026-12-01 14:20:02.002 DEBUG [http-nio-8080-exec-1] c.e.m.OrderMapper.updateStatus : ==> Parameters: DONE(String), 10(Long)', + '2026-12-01 14:20:02.005 DEBUG [http-nio-8080-exec-1] c.e.m.OrderMapper.updateStatus : <== Updates: 1', + '2026-12-01 14:20:02.100 DEBUG [http-nio-8080-exec-1] c.e.m.OrderMapper.badQuery : ==> Preparing: SELECT * FROM orders WHERE id = ? AND code = ?', + '2026-12-01 14:20:02.101 DEBUG [http-nio-8080-exec-1] c.e.m.OrderMapper.badQuery : ==> Parameters: 99(Long)', + ].join('\n') + + const batch = extractAndMergeMyBatisLogs(mixedLog, 'sqlite', { keywordCase: 'upper' }) + assert.equal(batch.isSuccess, true) + assert.equal(batch.entries.length, 3) + assert.equal(batch.successCount, 2) + assert.equal(batch.failureCount, 1) + assert.equal(batch.entries[0].summary, '#1 SELECT orders') + assert.equal(batch.entries[0].preparingLine, 2) + assert.equal(batch.entries[0].parametersLine, 3) + assert.match(batch.entries[0].beautifiedMergedSql, /WHERE o\.status = 'PAID'\n AND o\.user_id = 10086/) + assert.equal(batch.entries[1].summary, '#2 UPDATE orders') + assert.equal(batch.entries[1].mergedSql, "UPDATE orders SET status = 'DONE' WHERE id = 10") + assert.equal(batch.entries[2].isSuccess, false) + assert.equal(batch.entries[2].hasCountMismatch, true) + assert.equal(batch.entries[2].parametersLine, 10) + assert.match(batch.combinedBeautifiedSql, /SELECT[\s\S]*UPDATE orders/) + + const hint = detectClipboardSqlHint(mixedLog) + assert.deepEqual(hint?.tab, 'mybatis') + assert.equal(hint?.count, 3) + assert.equal(detectClipboardSqlHint('hello world plain text'), null) }) + test('MyBatis 缺日志、数量不符、歧义和错误类型不产生可复制SQL', () => { for (const input of [ 'Preparing: SELECT ?, ?\nParameters: 1(Integer)', @@ -94,7 +215,9 @@ test('MyBatis 缺日志、数量不符、歧义和错误类型不产生可复制 'Parameters: 1(Integer)\nPreparing: SELECT ?', ]) { const result = mergeMyBatisLog(input, 'sqlite') - assert.equal(result.isSuccess, false, input); assert.equal(result.mergedSql, ''); assert.equal(result.beautifiedMergedSql, '') + assert.equal(result.isSuccess, false, input) + assert.equal(result.mergedSql, '') + assert.equal(result.beautifiedMergedSql, '') } assert.equal(mergeMyBatisLog("Preparing: SELECT doc ? 'key'\nParameters: 1(Integer)", 'postgresql').isSuccess, false) assert.equal(mergeMyBatisLog('Preparing: SELECT ?\nParameters: a (String)', 'sqlite').params[0].value, ' a ') @@ -112,6 +235,7 @@ const ddl = `CREATE TABLE "demo_records" ( "class" TEXT DEFAULT 'ignore,),not null', PRIMARY KEY(id), CHECK (length(name) > 0) );` + test('真实 SQLite 建表结构对照:单行/多行、嵌套默认值、表级主键与可空列', () => { const db = new DatabaseSync(':memory:') try { @@ -120,115 +244,314 @@ test('真实 SQLite 建表结构对照:单行/多行、嵌套默认值、表 for (const input of [ddl, ddl.replace(/\n/g, ' ')]) { const result = parseDdlToEntities(input, 'sqlite') assert.equal(result.isValid, true, result.warningMessage) - assert.deepEqual(result.columns.map(c => c.name), actual.map(c => c.name)) - assert.deepEqual(result.columns.map(c => c.nullable), actual.map(c => !c.notnull && !c.pk)) + assert.deepEqual( + result.columns.map(c => c.name), + actual.map(c => c.name) + ) + assert.deepEqual( + result.columns.map(c => c.nullable), + actual.map(c => !c.notnull && !c.pk) + ) assert.match(result.generatedCode.typescript, /"amount": string;/) assert.match(result.generatedCode.typescript, /"enabled": boolean \| null;/) assert.match(result.generatedCode.golang, /Enabled \*bool/) assert.match(result.generatedCode.java, /import java.time.LocalDate;/) assert.doesNotMatch(result.generatedCode.java, /lombok/) } - } finally { db.close() } + } finally { + db.close() + } }) + +test('DDL 多表批量转换与工程选项:驼峰命名、Lombok @Data、MyBatis-Plus 与 GORM 开关', () => { + const multiDdl = ` + CREATE TABLE t_orders ( + id BIGINT NOT NULL PRIMARY KEY, + order_sn VARCHAR(64) NOT NULL, + created_at TIMESTAMP + ); + CREATE TABLE t_order_items ( + item_id BIGINT NOT NULL PRIMARY KEY, + order_id BIGINT NOT NULL, + unit_price DECIMAL(10,2) NOT NULL + ); + ` + const result = parseDdlToEntities(multiDdl, 'mysql', { + namingStyle: 'camel', + javaLombok: true, + javaMybatisPlus: true, + goGormTag: false, + }) + assert.equal(result.isValid, true, result.warningMessage) + assert.equal(result.tables.length, 2) + assert.deepEqual(result.tableNames, ['t_orders', 't_order_items']) + assert.match(result.generatedCode.typescript, /export interface OrdersModel/) + assert.match(result.generatedCode.typescript, /export interface OrderItemsModel/) + assert.match(result.generatedCode.typescript, /\n orderSn: string;/) + assert.match(result.generatedCode.java, /import lombok\.Data;/) + assert.match(result.generatedCode.java, /@Data\n@TableName\("t_orders"\)/) + assert.match(result.generatedCode.java, /@TableId\("id"\)\n private Long id;/) + assert.match(result.generatedCode.java, /@TableField\("order_sn"\)\n private String orderSn;/) + assert.doesNotMatch(result.generatedCode.golang, /gorm:/) + assert.match(result.generatedCode.golang, /json:\\"orderSn\\"/) + + const hint = detectClipboardSqlHint(multiDdl) + assert.deepEqual(hint?.tab, 'ddl') + assert.equal(hint?.count, 2) +}) + test('生成代码通过真实 TypeScript、Go、Java编译;特殊字段及注释不破坏代码', t => { const root = mkdtempSync(path.join(tmpdir(), 'ztools-sql-model-')) const repo = fileURLToPath(new URL('../../../', import.meta.url)) - const compiler = ['node_modules/typescript/bin/tsc', '../node_modules/typescript/bin/tsc', '../electron-client/node_modules/typescript/bin/tsc'].map(p => path.resolve(repo, p)).find(existsSync) + const compiler = [ + 'node_modules/typescript/bin/tsc', + 'electron-client/node_modules/typescript/bin/tsc', + 'frontend/node_modules/typescript/bin/tsc', + 'packages/declarative-ui/node_modules/typescript/bin/tsc', + '../node_modules/typescript/bin/tsc', + ] + .map(p => path.resolve(repo, p)) + .find(existsSync) assert.ok(compiler, '需要项目 TypeScript 编译器') - const result = parseDdlToEntities("CREATE TABLE demo_models (`first-name` text, first_name text, `class` text, amount decimal(20,4) NOT NULL, birthday date, data json, bytes blob, `中文` text COMMENT '*/ \\\\u000a 注释', id bigint unsigned)") + const result = parseDdlToEntities( + "CREATE TABLE demo_models (`first-name` text, first_name text, `class` text, amount decimal(20,4) NOT NULL, birthday date, data json, bytes blob, `中文` text COMMENT '*/ \\\\u000a 注释', id bigint unsigned)" + ) assert.equal(result.isValid, true, result.warningMessage) try { writeFileSync(path.join(root, 'model.ts'), result.generatedCode.typescript) - execFileSync(process.execPath, [compiler, '--noEmit', '--strict', '--skipLibCheck', '--target', 'ES2022', path.join(root, 'model.ts')], { cwd: root, encoding: 'utf8' }) + execFileSync( + process.execPath, + [compiler, '--noEmit', '--strict', '--skipLibCheck', '--target', 'ES2022', path.join(root, 'model.ts')], + { cwd: root, encoding: 'utf8' } + ) writeFileSync(path.join(root, 'model.go'), result.generatedCode.golang) - if (spawnSync('go', ['version']).status === 0) execFileSync('go', ['test', path.join(root, 'model.go')], { encoding: 'utf8', env: { ...process.env, GOWORK: 'off' } }) - else t.diagnostic('当前环境无 Go;Go 编译需在具备工具链的机器复核') + if (spawnSync('go', ['version']).status === 0) { + execFileSync('go', ['test', path.join(root, 'model.go')], { + encoding: 'utf8', + env: { ...process.env, GOWORK: 'off' }, + }) + } else { + t.diagnostic('当前环境无 Go;Go 编译需在具备工具链的机器复核') + } const name = result.generatedCode.java.match(/public class (\w+)/)[1] writeFileSync(path.join(root, name + '.java'), result.generatedCode.java) - if (spawnSync('javac', ['-version']).status === 0) execFileSync('javac', ['-encoding', 'UTF-8', path.join(root, name + '.java')], { encoding: 'utf8' }) - else t.diagnostic('当前环境无 javac;Java 编译需在具备工具链的机器复核') - } finally { rmSync(root, { recursive: true, force: true }) } + if (spawnSync('javac', ['-version']).status === 0) { + execFileSync('javac', ['-encoding', 'UTF-8', path.join(root, name + '.java')], { encoding: 'utf8' }) + } else { + t.diagnostic('当前环境无 javac;Java 编译需在具备工具链的机器复核') + } + } finally { + rmSync(root, { recursive: true, force: true }) + } }) + test('DDL错误不输出半成品;未知类型提示,引用注释中的逗号括号不拆列', () => { - for (const input of ['', 'SELECT example(\n id int\n)', 'CREATE TABLE demo (id int', 'CREATE TABLE demo (id int,)', 'CREATE TABLE demo (id int); CREATE TABLE other (x int)', 'CREATE TABLE demo (id int, id int)', 'CREATE TABLE demo (id int, PRIMARY KEY (missing))']) { + for (const input of [ + '', + 'SELECT example(\n id int\n)', + 'CREATE TABLE demo (id int', + 'CREATE TABLE demo (id int,)', + 'CREATE TABLE demo (id int); DROP TABLE demo;', + 'CREATE TABLE demo (id int, id int)', + 'CREATE TABLE demo (id int, PRIMARY KEY (missing))', + ]) { const result = parseDdlToEntities(input) - assert.equal(result.isValid, false, input); assert.deepEqual(result.generatedCode, { typescript: '', golang: '', java: '' }) + assert.equal(result.isValid, false, input) + assert.deepEqual(result.generatedCode, { typescript: '', golang: '', java: '' }) } - const result = parseDdlToEntities("CREATE TABLE schema1.demo (id uuid NOT NULL, value custom_type, note text COMMENT 'a,b) and NOT NULL', label enum('a,b', 'c') DEFAULT 'a,b')") + const result = parseDdlToEntities( + "CREATE TABLE schema1.demo (id uuid NOT NULL, value custom_type, note text COMMENT 'a,b) and NOT NULL', label enum('a,b', 'c') DEFAULT 'a,b')" + ) assert.equal(result.isValid, true, result.warningMessage) - assert.equal(result.tableName, 'demo'); assert.equal(result.columns.length, 4) - assert.equal(result.columns[2].nullable, true); assert.equal(result.columns[2].comment, 'a,b) and NOT NULL') + assert.equal(result.tableName, 'demo') + assert.equal(result.columns.length, 4) + assert.equal(result.columns[2].nullable, true) + assert.equal(result.columns[2].comment, 'a,b) and NOT NULL') assert.match(result.warnings.join('\n'), /custom_type|CUSTOM_TYPE/) }) + test('三个显式快捷入口没有示例冒充结果;表单保留多行、取消与错误不替换旧内容', async () => { - for (const [code, tab] of [['sql-formatter', 'formatter'], ['mybatis-merge', 'mybatis'], ['ddl-to-entity', 'ddl']]) { + for (const [code, tab] of [ + ['sql-formatter', 'formatter'], + ['mybatis-merge', 'mybatis'], + ['ddl-to-entity', 'ddl'], + ]) { const v = await open(code) assert.equal(v.tree().props.searchBarAccessory.props.value, tab) - assert.equal(v.items().length, 1); assert.equal(v.items()[0].props.id, 'input') + assert.equal(v.items().length, 1) + assert.equal(v.items()[0].props.id, 'input') assert.doesNotMatch(v.text(), /已美化对齐|t_user_account|张三|复制美化 SQL/) } - const v = await open(), form = await edit(v, sqliteCases[0]); await submit(form) + const v = await open() + const form = await edit(v, sqliteCases[0]) + await submit(form) assert.equal(host.pushed.length, 0) - await v.run(v.item('minified'), '复制精简空白') + await v.run(v.item('minified'), '复制压缩为单行 SQL') assert.match(host.clipboard.text, /-- 保留注释结束\n/) - await v.search('精简'); assert.equal(v.items().length, 1) - const bad = await edit(v, "select 'broken"); await submit(bad) - assert.equal(host.pushed.length, 1); assert.equal(host.lastToast().style, 'FAILURE') - await v.search(''); assert.equal(v.items().length, 2) + await v.search('单行') + assert.equal(v.items().length, 1) + const bad = await edit(v, "select 'broken") + await submit(bad) + assert.equal(host.pushed.length, 1) + assert.equal(host.lastToast().style, 'FAILURE') + await v.search('') + assert.equal(v.items().length, 2) assert.match(v.text(), /保留注释结束/) host.pushed.pop() }) -test('MyBatis与DDL实际声明式链路:成功复制结果,异常剪贴板清旧结果且失败不报成功', async () => { + +test('MyBatis与DDL实际声明式链路:混杂多组日志、复制回贴、另存为文件与错误清理', async () => { const v = await open('mybatis-merge') - host.clipboard.text = 'Preparing: SELECT ?\nParameters: hello(String)' - await v.run(v.item('input'), '载入剪贴板') - await v.run(v.item('merged'), '复制参数还原参考 SQL') - assert.equal(host.clipboard.text, "SELECT 'hello'") + host.clipboard.text = [ + '2026-12-01 INFO start', + '==> Preparing: SELECT id FROM orders WHERE status = ?', + '==> Parameters: PAID(String)', + '<== Total: 1', + '==> Preparing: UPDATE orders SET status = ? WHERE id = ?', + '==> Parameters: DONE(String), 7(Long)', + ].join('\n') + await v.run(v.item('input'), '读取剪贴板') + assert.ok(v.item('merged-all')) + assert.ok(v.item('mybatis-1')) + assert.ok(v.item('mybatis-2')) + await v.run(v.item('mybatis-1'), '复制#1 SELECT orders') + assert.match(host.clipboard.text, /WHERE status = 'PAID'/) + await v.run(v.item('mybatis-2'), '复制并回贴原编辑器') + assert.equal(host.clipboard.pasted.length, 1) + assert.match(host.clipboard.pasted[0], /UPDATE orders\nSET status = 'DONE'\nWHERE id = 7/) + + // 测试另存为 .sql(经由 DeclarativeBridge.hostTransport) + const bridge = getDeclarativeBridge() + const prevTransport = bridge.hostTransport + const calls = [] + try { + bridge.hostTransport = { + async call(method, params) { + calls.push([method, params]) + if (method === 'window_show_save_dialog') return { canceled: false, filePath: '/tmp/restored.sql' } + if (method === 'filesystem_write_file') return { ok: true } + throw new Error(`unexpected ${method}`) + }, + } + await v.run(v.item('merged-all'), '另存为 .sql 文件') + assert.equal(calls.length, 2) + assert.equal(calls[0][0], 'window_show_save_dialog') + assert.equal(calls[1][0], 'filesystem_write_file') + assert.equal(calls[1][1].path, '/tmp/restored.sql') + assert.equal(host.lastToast().style, 'SUCCESS') + } finally { + bridge.hostTransport = prevTransport + } + host.clipboard.text = 'Preparing: SELECT ?\nParameters: ' - await v.tree().props.filterBar.actions.find(a => a.id === 'clipboard').onAction(); await tick() - assert.equal(v.items()[0].props.id, 'input'); assert.equal(host.lastToast().style, 'FAILURE') - await v.dropdown('ddl'); const form = await edit(v, ddl); await submit(form) - for (const [id, title] of [['typescript', 'TypeScript 模型'], ['golang', 'Go 模型'], ['java', 'Java 模型']]) { + await v.tree().props.filterBar.actions.find(a => a.id === 'clipboard').onAction() + await tick() + assert.equal(v.items()[0].props.id, 'input') + assert.equal(host.lastToast().style, 'FAILURE') + + await v.dropdown('ddl') + const form = await edit(v, ddl) + await submit(form) + for (const [id, title] of [ + ['typescript', 'TypeScript 模型'], + ['golang', 'Go 模型'], + ['java', 'Java 模型'], + ]) { await v.run(v.item(id), '复制' + title) assert.equal(host.clipboard.text, parseDdlToEntities(ddl, 'sqlite').generatedCode[id]) } - await v.dropdown('mybatis'); assert.equal(v.items()[0].props.id, 'input', '模式各自保留输入而不混用') + // 快捷切换驼峰命名与 Lombok + await v.run(v.item('typescript'), '切换命名风格(当前:原名)') + await v.run(v.item('typescript'), '复制TypeScript 模型') + assert.match(host.clipboard.text, /\n createdAt: string \| null;/) + await v.dropdown('mybatis') + assert.equal(v.items()[0].props.id, 'input', '模式各自保留输入而不混用') +}) + +test('剪贴板智能探测仅提示不伪造结果,用户点击一键解析载入后才切换并解析', async () => { + host.clipboard.text = '==> Preparing: SELECT * FROM orders WHERE id = ?\n==> Parameters: 42(Long)' + const v = await open('sql-formatter') + assert.equal(v.items().length, 1) + assert.equal(v.items()[0].props.id, 'input') + assert.match(v.tree().props.filterBar.summaryText, /检测到剪贴板含 MyBatis 日志/) + await v.tree().props.filterBar.actions.find(a => a.id === 'clipboard').onAction() + await tick() + assert.equal(v.tree().props.searchBarAccessory.props.value, 'mybatis') + assert.ok(v.item('merged')) + assert.match(v.text(), /WHERE id = 42/) }) test('慢剪贴板读取不会覆盖编辑或串到其他模式;卸载及失败均无假成功', async () => { - const bridge = getDeclarativeBridge(), read = bridge.readClipboardText - let resolve + const bridge = getDeclarativeBridge() + const read = bridge.readClipboardText + const resolvers = [] try { - bridge.readClipboardText = () => new Promise(done => { resolve = done }) + bridge.readClipboardText = () => + new Promise(done => { + resolvers.push(done) + }) const v = await open() - await v.run(v.item('input'), '载入剪贴板') - const form = await edit(v, 'select 42'); await submit(form) - resolve('select 99'); await tick() - assert.match(v.text(), /select 42/); assert.doesNotMatch(v.text(), /select 99/) - await v.tree().props.filterBar.actions[0].onAction(); await tick() - await v.dropdown('mybatis'); resolve('select 100'); await tick() + // 第 1 次是挂载静默探测;第 2 次是用户点击读取剪贴板 + await v.run(v.item('input'), '读取剪贴板') + const form = await edit(v, 'select 42') + await submit(form) + while (resolvers.length) resolvers.shift()('select 99') + await tick() + assert.match(v.text(), /select 42/) + assert.doesNotMatch(v.text(), /select 99/) + + await v.tree().props.filterBar.actions[0].onAction() + await tick() + await v.dropdown('mybatis') + while (resolvers.length) resolvers.shift()('select 100') + await tick() assert.equal(v.items()[0].props.id, 'input') - await v.dropdown('formatter'); assert.match(v.text(), /select 42/) - await v.tree().props.filterBar.actions[0].onAction(); await tick() - v.unmount(); resolve('select 101'); await tick() + + await v.dropdown('formatter') + assert.match(v.text(), /select 42/) + await v.tree().props.filterBar.actions[0].onAction() + await tick() + v.unmount() + while (resolvers.length) resolvers.shift()('select 101') + await tick() assert.equal(host.toasts.length, 0) - bridge.readClipboardText = async () => { throw new Error('测试读取失败') } - const bad = await open(); await bad.run(bad.item('input'), '载入剪贴板') - assert.equal(host.lastToast().style, 'FAILURE'); assert.match(host.lastToast().message, /测试读取失败/) - } finally { bridge.readClipboardText = read } + + bridge.readClipboardText = async () => { + throw new Error('测试读取失败') + } + const bad = await open() + await bad.run(bad.item('input'), '读取剪贴板') + assert.equal(host.lastToast().style, 'FAILURE') + assert.match(host.lastToast().message, /测试读取失败/) + } finally { + bridge.readClipboardText = read + } }) test('SQLite 非整数主键仍允许 NULL;MySQL tinyint(1) 保留整数范围', () => { - const cases = ['CREATE TABLE demo (id TEXT PRIMARY KEY)', 'CREATE TABLE demo (id INTEGER PRIMARY KEY DESC)', 'CREATE TABLE demo (id TEXT, PRIMARY KEY(id))', 'CREATE TABLE demo (id INTEGER PRIMARY KEY)', 'CREATE TABLE demo (id TEXT PRIMARY KEY) WITHOUT ROWID', 'CREATE TABLE demo (id TEXT PRIMARY KEY) STRICT'] + const cases = [ + 'CREATE TABLE demo (id TEXT PRIMARY KEY)', + 'CREATE TABLE demo (id INTEGER PRIMARY KEY DESC)', + 'CREATE TABLE demo (id TEXT, PRIMARY KEY(id))', + 'CREATE TABLE demo (id INTEGER PRIMARY KEY)', + 'CREATE TABLE demo (id TEXT PRIMARY KEY) WITHOUT ROWID', + 'CREATE TABLE demo (id TEXT PRIMARY KEY) STRICT', + ] for (const source of cases) { const db = new DatabaseSync(':memory:') try { db.exec(source) let permitsNull = false - try { db.exec('INSERT INTO demo(id) VALUES (NULL)'); permitsNull = db.prepare('SELECT id FROM demo').get().id === null } - catch (error) { assert.match(error.message, /NOT NULL/) } + try { + db.exec('INSERT INTO demo(id) VALUES (NULL)') + permitsNull = db.prepare('SELECT id FROM demo').get().id === null + } catch (error) { + assert.match(error.message, /NOT NULL/) + } assert.equal(parseDdlToEntities(source, 'sqlite').columns[0].nullable, permitsNull, source) - } finally { db.close() } + } finally { + db.close() + } } const tiny = parseDdlToEntities('CREATE TABLE demo (flag tinyint(1) NOT NULL)') assert.match(tiny.generatedCode.typescript, /"flag": number;/) @@ -240,21 +563,39 @@ test('特殊名称不能被JSON/GORM标签误解释;实际Go序列化保留字 assert.equal(result.isValid, false, name) assert.match(result.warningMessage, /JSON\/GORM/) } - if (spawnSync('go', ['version']).status !== 0) { t.diagnostic('需要 Go 工具链执行序列化验证'); return } + if (spawnSync('go', ['version']).status !== 0) { + t.diagnostic('需要 Go 工具链执行序列化验证') + return + } const dir = mkdtempSync(path.join(tmpdir(), 'ztools-sql-json-')) try { - const result = parseDdlToEntities('CREATE TABLE demo (`first-name` text NOT NULL, `中文` text NOT NULL, `a:b` text NOT NULL)') + const result = parseDdlToEntities( + 'CREATE TABLE demo (`first-name` text NOT NULL, `中文` text NOT NULL, `a:b` text NOT NULL)' + ) assert.equal(result.isValid, true, result.warningMessage) - writeFileSync(path.join(dir, 'main.go'), result.generatedCode.golang.replace('package models', 'package main\nimport "encoding/json"\nimport "fmt"') + '\nfunc main() { data, err := json.Marshal(DemoModel{FirstName: "first", Field: "second", AB: "third"}); if err != nil { panic(err) }; fmt.Println(string(data)) }') - const json = execFileSync('go', ['run', path.join(dir, 'main.go')], { encoding: 'utf8', env: { ...process.env, GOWORK: 'off' } }) - assert.deepEqual(JSON.parse(json), { 'first-name': 'first', '中文': 'second', 'a:b': 'third' }) - } finally { rmSync(dir, { recursive: true, force: true }) } + writeFileSync( + path.join(dir, 'main.go'), + result.generatedCode.golang.replace('package models', 'package main\nimport "encoding/json"\nimport "fmt"') + + '\nfunc main() { data, err := json.Marshal(DemoModel{FirstName: "first", Field: "second", AB: "third"}); if err != nil { panic(err) }; fmt.Println(string(data)) }' + ) + const json = execFileSync('go', ['run', path.join(dir, 'main.go')], { + encoding: 'utf8', + env: { ...process.env, GOWORK: 'off' }, + }) + assert.deepEqual(JSON.parse(json), { 'first-name': 'first', 中文: 'second', 'a:b': 'third' }) + } finally { + rmSync(dir, { recursive: true, force: true }) + } }) test('PostgreSQL仅裸标识符转小写;MySQL SERIAL/ZEROFILL遵循真实整数范围', () => { const pg = parseDdlToEntities('CREATE TABLE Users (UserID BIGINT, "DisplayName" TEXT, PRIMARY KEY(UserID))', 'postgresql') assert.equal(pg.isValid, true, pg.warningMessage) - assert.equal(pg.tableName, 'users'); assert.deepEqual(pg.columns.map(c => c.name), ['userid', 'DisplayName']) + assert.equal(pg.tableName, 'users') + assert.deepEqual( + pg.columns.map(c => c.name), + ['userid', 'DisplayName'] + ) assert.equal(pg.columns[0].nullable, false) assert.match(pg.generatedCode.golang, /column:userid/) const mysql = parseDdlToEntities('CREATE TABLE items (id SERIAL, count BIGINT ZEROFILL)') @@ -268,10 +609,14 @@ test('PostgreSQL仅裸标识符转小写;MySQL SERIAL/ZEROFILL遵循真实整 }) test('美化:连接修饰词与 JOIN 同行,同名函数 LEFT()/RIGHT() 与 CHARACTER SET 不换行,执行结果不变', () => { - const source = "select a.id, left(a.name, 2) as l, right(a.name, 1) as r from a left join b on a.id = b.id inner join c on c.id = a.id left outer join d on d.id = a.id cross join e natural join f where a.id > 0 order by a.id" + const source = + 'select a.id, left(a.name, 2) as l, right(a.name, 1) as r from a left join b on a.id = b.id inner join c on c.id = a.id left outer join d on d.id = a.id cross join e natural join f where a.id > 0 order by a.id' const { beautified } = formatAndMinifySql(source, 'sqlite') assert.deepEqual(beautified.split('\n'), [ - 'select a.id, left(a.name, 2) as l, right(a.name, 1) as r', + 'select', + ' a.id,', + ' left(a.name, 2) as l,', + ' right(a.name, 1) as r', 'from a', 'left join b on a.id = b.id', 'inner join c on c.id = a.id', @@ -279,23 +624,27 @@ test('美化:连接修饰词与 JOIN 同行,同名函数 LEFT()/RIGHT() 与 'cross join e', 'natural join f', 'where a.id > 0', - 'order by a.id' + 'order by a.id', ]) const db = new DatabaseSync(':memory:') try { - db.exec("CREATE TABLE a(id INTEGER, name TEXT); CREATE TABLE b(id INTEGER); CREATE TABLE c(id INTEGER); CREATE TABLE d(id INTEGER); CREATE TABLE e(x INTEGER); CREATE TABLE f(id INTEGER, name TEXT);") - db.exec("INSERT INTO a VALUES (1, '甲乙丙'); INSERT INTO b VALUES (1); INSERT INTO c VALUES (1); INSERT INTO d VALUES (1); INSERT INTO e VALUES (9); INSERT INTO f VALUES (1, '甲乙丙');") - // SQLite 没有 LEFT()/RIGHT() 函数,执行校验用 substr 等价改写后的同结构语句 + db.exec( + 'CREATE TABLE a(id INTEGER, name TEXT); CREATE TABLE b(id INTEGER); CREATE TABLE c(id INTEGER); CREATE TABLE d(id INTEGER); CREATE TABLE e(x INTEGER); CREATE TABLE f(id INTEGER, name TEXT);' + ) + db.exec( + "INSERT INTO a VALUES (1, '甲乙丙'); INSERT INTO b VALUES (1); INSERT INTO c VALUES (1); INSERT INTO d VALUES (1); INSERT INTO e VALUES (9); INSERT INTO f VALUES (1, '甲乙丙');" + ) const runnable = source.replace('left(a.name, 2)', 'substr(a.name, 1, 2)').replace('right(a.name, 1)', 'substr(a.name, -1)') assert.deepEqual(db.prepare(formatAndMinifySql(runnable, 'sqlite').beautified).all(), db.prepare(runnable).all()) - } finally { db.close() } + } finally { + db.close() + } assert.doesNotMatch(formatAndMinifySql('create table t (a varchar(3) character set utf8mb4)').beautified, /\nset/i) assert.match(formatAndMinifySql('update t set a = 1').beautified, /^update t\nset a = 1$/) - // 没有原始空白的位置不插入换行(如 x)left join 这类紧贴写法不改变 token 间距) assert.equal(formatAndMinifySql('select left(x,1)from t').beautified, 'select left(x,1)from t') }) -test('空状态按模式给出不同的引导,标题不缺空格,提示里不写 ⌘/Ctrl 混写快捷键', async () => { +test('空状态按模式给出不同的引导,标题不缺空格,提示里不写 ⌘/Ctrl 混写快捷键,中英双语切换完整', async () => { const seen = new Set() for (const tab of ['sql-formatter', 'mybatis-merge', 'ddl-to-entity']) { const view = await open(tab) @@ -307,7 +656,88 @@ test('空状态按模式给出不同的引导,标题不缺空格,提示里 assert.equal(seen.size, 3) const view = await open('mybatis-merge') assert.match(view.item('input').props.detail.props.markdown, /Preparing/) - await view.run(view.item('input'), '编辑源码') + await view.run(view.item('input'), '编辑 SQL') const form = await mountPushed(host) - try { assert.doesNotMatch(form.text(), /⌘\/Ctrl/) } finally { form.unmount() } + try { + assert.doesNotMatch(form.text(), /⌘\/Ctrl/) + } finally { + form.unmount() + } + host.setLocale('en-US') + const enView = await open('sql-formatter') + assert.match(enView.item('input').props.title, /Load SQL/) +}) + +test('UNION ALL 后的 SELECT 自动换行,无 ==> 前缀的日志框架 MyBatis 输出同样准确提取', () => { + const unionSql = 'select id from t1 union all select id from t2 order by id desc limit 5;' + const { beautified } = formatAndMinifySql(unionSql, 'sqlite', { keywordCase: 'upper', indentWidth: 2 }) + assert.equal( + beautified, + ['SELECT id', 'FROM t1', 'UNION ALL', 'SELECT id', 'FROM t2', 'ORDER BY id DESC', 'LIMIT 5;'].join('\n') + ) + const db = new DatabaseSync(':memory:') + try { + db.exec('CREATE TABLE t1(id INTEGER); CREATE TABLE t2(id INTEGER); INSERT INTO t1 VALUES (1); INSERT INTO t2 VALUES (2);') + assert.deepEqual(db.prepare(beautified).all(), db.prepare(unionSql).all()) + } finally { + db.close() + } + + const logWithoutArrow = [ + '2026-12-01 15:01:00.123 DEBUG [main] c.e.OrderMapper - Preparing: SELECT * FROM orders WHERE id = ?', + '2026-12-01 15:01:00.124 DEBUG [main] c.e.OrderMapper - Parameters: 42(Long)', + '2026-12-01 15:01:00.125 INFO [main] c.e.OrderService - finished', + ].join('\n') + const batch = extractAndMergeMyBatisLogs(logWithoutArrow, 'sqlite', { keywordCase: 'upper' }) + assert.equal(batch.isSuccess, true) + assert.equal(batch.entries.length, 1) + assert.equal(batch.entries[0].mergedSql, 'SELECT * FROM orders WHERE id = 42') +}) + +test('主界面支持直接粘贴文本与拖入 .sql 文件自动识别模式,以及 DDL 快捷开关与读文件异常保护', async () => { + const v = await open('sql-formatter') + const fileInput = v.tree().props.fileInput + assert.ok(fileInput) + assert.deepEqual(fileInput.extensions, ['.sql', '.log', '.txt']) + + // 1. 直接按 Ctrl+V 粘贴 DDL,自动切换到 DDL 模式并生成模型 + fileInput.onTextPaste('CREATE TABLE t_users (id BIGINT NOT NULL PRIMARY KEY, user_name VARCHAR(64) NOT NULL);') + await tick() + assert.equal(v.tree().props.searchBarAccessory.props.value, 'ddl') + assert.ok(v.item('java')) + await v.run(v.item('java'), '切换 Java MyBatis-Plus(当前:关)') + await v.run(v.item('java'), '复制Java 模型') + assert.match(host.clipboard.text, /@TableName\("t_users"\)/) + assert.match(host.clipboard.text, /@TableId\("id"\)/) + await v.run(v.item('golang'), '切换 Go GORM 标签(当前:开)') + await v.run(v.item('golang'), '复制Go 模型') + assert.doesNotMatch(host.clipboard.text, /gorm:/) + + // 2. 拖入 .sql 文件自动读取并切回 SQL 格式化模式 + const bridge = getDeclarativeBridge() + const prevTransport = bridge.hostTransport + try { + bridge.hostTransport = { + async call(method, params) { + if (method === 'filesystem_read_file' && params.path === '/tmp/query.sql') { + return { content: 'select id, name from users where active = 1' } + } + throw new Error('模拟读取失败') + }, + } + v.tree().props.onFileInput({ files: ['/tmp/query.sql'], source: 'drop' }) + await tick() + assert.equal(v.tree().props.searchBarAccessory.props.value, 'formatter') + assert.ok(v.item('beautified')) + assert.match(v.text(), /FROM users/) + + // 3. 读文件失败时弹 Failure Toast 且不破坏已有结果 + v.tree().props.onFileInput({ files: ['/tmp/missing.sql'], source: 'drop' }) + await tick() + assert.equal(host.lastToast().style, 'FAILURE') + assert.match(host.lastToast().message, /模拟读取失败/) + assert.ok(v.item('beautified')) + } finally { + bridge.hostTransport = prevTransport + } }) diff --git a/extensions/ssh-proxy-helper/plugin.json b/extensions/ssh-proxy-helper/plugin.json index ba595910..97c3e048 100644 --- a/extensions/ssh-proxy-helper/plugin.json +++ b/extensions/ssh-proxy-helper/plugin.json @@ -1,7 +1,7 @@ { "id": "ssh-proxy-helper", "name": "主机与代理", - "version": "1.0.8", + "version": "1.0.9", "description": "管理 SSH 主机连接、端口转发及 Git、NPM 和新终端的本地代理配置", "author": "ZTools Team", "category": [ diff --git a/extensions/ssh-proxy-helper/src/i18n.ts b/extensions/ssh-proxy-helper/src/i18n.ts index 47104b82..4309c073 100644 --- a/extensions/ssh-proxy-helper/src/i18n.ts +++ b/extensions/ssh-proxy-helper/src/i18n.ts @@ -23,28 +23,41 @@ const MESSAGES = { terminalOpenedTitle: "已请求打开终端", tunnelTitle: "{alias} · 端口转发", editProxyTitle: "{tool} · 设置代理", + batchProxyTitle: "批量设置 Git 与 NPM 代理", newTerminalProxy: "新终端代理", sourceTitle: "{tool} · 配置来源", navTitle: "主机与代理", - searchPlaceholder: "搜索 SSH 主机、Git、NPM 或代理端口", - viewDropdownTooltip: "查看内容", + searchPlaceholder: "搜索主机别名、IP、用户、代理或隧道...", + viewDropdownTooltip: "筛选视图", catAll: "全部", catHosts: "SSH 主机", catProxy: "开发代理", + catTunnels: "隧道预设", catBackups: "修改备份", readingOrVerifying: "正在读取或核验配置…", - summaryHosts: "{count} 个主机 · Git、NPM 分别管理", + summaryHosts: "{count} 个主机 · {activeProxies}/2 项开发代理已开启 · {backups} 份备份", notReadYet: "尚未读取配置", cancelOp: "取消操作", refresh: "刷新", + newHostAction: "新建主机", readIncompleteTitle: "配置读取未完成", readingConfigTitle: "正在读取配置", readingConfigSubtitle: "读取完成后可连接主机或管理代理", conditionalHostFallback: "目标由 SSH 条件配置决定", hasConditionBadge: "含条件配置", - createLocalTunnel: "建立本地端口转发…", + pinnedBadge: "置顶", + jumpBadge: "跳板", + proxyActiveBadge: "已开启", + proxyUnsetBadge: "未设置", + proxyErrorBadge: "读取异常", + createLocalTunnel: "建立端口转发…", connectInTerminal: "在终端连接", copyConnectCmd: "复制连接命令", + pinHost: "置顶主机", + unpinHost: "取消置顶", + editHostConfig: "生成编辑配置块…", + newHostConfig: "新建主机配置块…", + startConfigForward: "启动配置内转发 ({spec})", toolProxyTitle: "{tool} 代理", proxyUnsetExists: "{file} 未设置通用代理", proxyUnsetMissing: "{file} 尚未创建,未设置通用代理", @@ -52,23 +65,41 @@ const MESSAGES = { setLocalProxyPort: "设置本机代理端口…", clearProxyInFile: "清除此文件中的通用代理", viewConfigSource: "查看配置来源", - terminalProxySubtitle: "只在新窗口设置代理环境,已有终端保持原样", + batchProxyItemTitle: "一键管理开发代理 (Git + NPM)", + batchProxyActiveSubtitle: "已开启 {active}/2 项 · 记忆端口 {port}", + batchProxyIdleSubtitle: "均未开启 · 记忆端口 {port}", + batchEnableProxy: "一键开启 Git + NPM (端口 {port})", + batchClearProxy: "一键清除全部开发代理", + batchEditPort: "自定义端口并批量应用…", + batchAllAlreadySet: "Git 与 NPM 当前均已设置为端口 {port}", + batchNothingToClear: "Git 与 NPM 当前均未设置通用代理", + batchDoneTitle: "批量代理操作已完成", + batchDoneMessage: "已更新 {count} 项开发代理并完成写回核验", + terminalProxySubtitle: "只在新窗口设置代理环境变量,不影响已有终端", openTerminalWithProxy: "打开带代理的新终端…", + openTerminalWithLastPort: "直接以端口 {port} 打开新终端", sshReadFailedTitle: "SSH 配置读取失败", sshNoMatchTitle: "没有匹配的 SSH 主机", - sshNoAliasTitle: "没有明确的 SSH 主机别名", + sshNoAliasTitle: "未读取到 SSH 主机别名", sshEmptySubtitle: "从 {path} 及其 Include 文件读取 Host 别名;通配符规则不单独列为主机。", + sshEmptyGuideTitle: "新建首个 SSH 主机配置块", + sshEmptyGuideSubtitle: "当前 {path} 暂无明确主机,回车生成标准配置块", clearSearch: "清空搜索", retainedOriginalTitle: "最近保留的原文件", copyOriginalLocation: "复制原文件位置", backupReadIncomplete: "备份读取未完成", noMatchingBackups: "没有匹配的修改备份", - backupHint: "修改 Git 或 NPM 配置前会保存原文件", + backupHint: "修改 Git 或 NPM 配置前会自动备份原文件", previewRestore: "预览恢复原配置", invalidPort: "端口请输入 1 到 65535 的整数", invalidRemoteHost: "远端主机请输入域名、IPv4 或方括号内的 IPv6 地址", + invalidAlias: "主机别名仅支持字母、数字、下划线、点、冒号或短横线,且不能以短横线或空格开头", + invalidHostName: "主机地址不能包含空白或控制字符", + invalidFieldLineBreak: "字段内容不能包含换行或控制字符", + invalidLocalForward: "LocalForward 格式应为「[绑定地址:]本地端口 目标主机:目标端口」", opFailed: "操作失败", createTunnelInTerminal: "在终端建立隧道", + copyDynamicTunnelCmd: "复制 SOCKS5 隧道命令", continueAction: "继续", localListenPort: "本机监听端口", localHttpProxyPort: "本机 HTTP 代理端口", @@ -77,10 +108,28 @@ const MESSAGES = { remoteTargetHost: "远端目标主机", remoteTargetPort: "远端目标端口", remotePortExample: "例如 5432", + tunnelModeLabel: "转发模式", + tunnelModeLocal: "本地端口转发 (-L)", + tunnelModeDynamic: "动态 SOCKS5 代理 (-D · 复制命令)", + saveAsPresetLabel: "保存为隧道预设", + saveAsPresetCheckbox: "保存此转发配置到“隧道预设”以便下次一键复用", + presetNameLabel: "预设名称(可选)", + presetNamePlaceholder: "例如 MySQL 生产库隧道", + presetSavedTitle: "已保存隧道预设", + presetDeletedTitle: "已删除隧道预设", + deletePresetAction: "删除此隧道预设", + startPresetTunnel: "在终端启动此隧道", + copyTunnelCmd: "复制隧道命令", + newTunnelPresetAction: "新建隧道预设…", + noTunnelsTitle: "暂无隧道预设", + noTunnelsDesc: "可从 SSH 主机操作菜单创建本地转发 (-L) 或动态 SOCKS5 (-D) 预设", + dynamicCopiedTitle: "已复制动态 SOCKS5 命令", + dynamicCopiedMsg: "当前客户端宿主接口仅开放 -L 本地转发启动,已复制 -D 命令到剪贴板,可在终端执行", incompleteLabel: "未完成", descriptionLabel: "说明", tunnelDesc: "仅在本机 127.0.0.1 监听;目标主机从 SSH 服务器访问。保持终端打开,Ctrl+C 结束。", - proxyDesc: "请先启动对应端口的 HTTP 代理服务。设置代理地址不会代替你启动代理软件。", + dynamicTunnelDesc: "宿主终端接口当前仅支持自动启动 -L 本地转发;动态 SOCKS5 (-D) 将生成标准命令并复制到剪贴板。", + proxyDesc: "请先启动对应端口的 HTTP 代理服务。写入前会先预览差异并备份原文件,设置代理不会代替你启动代理软件。", upgradeClient: "请升级客户端后使用主机与代理", hostOpUnconfirmed: "客户端未确认操作结果,请刷新后检查", scanIncomplete: "主机读取结果不完整,请刷新", @@ -92,7 +141,88 @@ const MESSAGES = { sourceConfigLabel: "配置文件:\n\n{location}\n\n{notices}", terminalOpenUnconfirmed: "终端打开请求未确认,请检查终端窗口", warnCancelUnconfirmed: "主机操作取消未确认", - warnFormCancelUnconfirmed: "主机表单取消未确认" + warnFormCancelUnconfirmed: "主机表单取消未确认", + sectionHosts: "SSH 主机", + sectionProxies: "开发与终端代理", + sectionTunnels: "端口转发与隧道预设", + sectionBackups: "配置修改备份", + sectionConfigForwards: "来自 SSH 配置", + configForwardBadge: "配置内", + presetLocalBadge: "本地 -L", + presetDynamicBadge: "动态 -D", + hostFormNewTitle: "新建 SSH 主机配置块", + hostFormEditTitle: "生成编辑配置块 · {alias}", + hostAliasLabel: "主机别名 (Host)", + hostAliasPlaceholder: "例如 prod-bastion", + hostNameLabel: "主机地址 (HostName)", + hostNamePlaceholder: "例如 10.20.30.40 或 host.example.com", + hostUserLabel: "用户名 (User)", + hostUserPlaceholder: "例如 root 或 ops", + hostPortLabel: "端口 (Port)", + hostPortPlaceholder: "默认 22", + hostIdentityLabel: "私钥路径 (IdentityFile)", + hostIdentityPlaceholder: "例如 ~/.ssh/id_ed25519", + hostProxyJumpLabel: "跳板机 (ProxyJump)", + hostProxyJumpPlaceholder: "例如 prod-bastion(可选)", + hostLocalForwardLabel: "本地转发 (LocalForward)", + hostLocalForwardPlaceholder: "例如 127.0.0.1:13306 127.0.0.1:3306(可选)", + hostFormSubmit: "校验并复制配置块", + hostFormReadonlyNotice: "安全说明:当前客户端宿主 ssh_proxy 接口对 ~/.ssh/config 为只读解析,不提供直接写盘能力。提交后将校验语法并复制标准 Host 配置块到剪贴板,请手动追加至 {path} 后返回刷新。", + hostBlockCopiedTitle: "已复制 SSH Host 配置块", + hostBlockCopiedMessage: "请粘贴到 {path} 并返回列表刷新", + hostBlockPreviewTitle: "SSH 配置块预览 · {alias}", + copyConfigBlockAgain: "再次复制配置块", + backAndRefresh: "返回列表并刷新", + metaHostName: "HostName", + metaUser: "User", + metaPort: "Port", + metaIdentity: "IdentityFile", + metaProxyJump: "ProxyJump", + metaLocalForward: "LocalForward", + metaParseStatus: "解析状态", + metaBackups: "事务备份", + metaTool: "目标工具", + metaProxyStatus: "代理状态", + metaFileExists: "配置文件", + metaValueCount: "生效键值", + metaForwardMode: "转发类型", + metaHostAlias: "目标主机", + metaListenAddr: "本地监听", + metaRemoteTarget: "远端目标", + metaCreatedAt: "备份时间", + metaNone: "无", + metaUnset: "未指定", + metaDefaultPort: "22(默认)", + metaComplete: "静态解析完整", + metaPartial: "含条件配置(由系统 SSH 求值)", + metaExists: "已存在", + metaNotCreated: "尚未创建", + metaBackupCount: "{count} 份", + metaLocalForwardCount: "{count} 条", + detailQuickConnect: "快捷连接命令", + detailLocalForwards: "已配置的本地转发", + detailNotices: "解析提示", + detailTransactionNoteTitle: "只读与事务安全说明", + detailHostReadonlyNote: "当前宿主仅提供 `~/.ssh/config` 只读扫描与终端直连;新建或编辑主机将生成标准配置块供手动追加,不会静默改写 SSH 配置文件。", + detailProxyConfigPath: "配置文件路径", + detailProxyCurrentValues: "当前生效代理值", + detailProxyNoValues: "当前文件未设置通用 HTTP/HTTPS 代理。", + detailProxyTransactionNote: "所有写入严格执行 `prepare -> 差异确认 -> 自动备份 -> apply 写回核验`,失败保留原文件并在「修改备份」中支持无损恢复。", + detailProxySystemNote: "当前宿主接口管理用户级 Git 与 NPM 配置文件,不修改操作系统全局网络代理;如需系统全局代理请在系统网络设置或代理客户端中开启。", + detailProxyCredentialWarn: "包含凭据(已脱敏展示)", + detailProxyDynamicWarn: "含动态/环境变量引用", + detailBatchSummaryTitle: "开发代理状态总览", + detailBatchColTool: "工具", + detailBatchColStatus: "状态", + detailBatchColValue: "当前配置", + detailBatchNote: "批量开启/清除会逐项执行 `prepare -> 差异确认 -> 备份 -> 核验` 事务,任何一项取消或失败都不会静默跳过。", + detailTerminalEnvTitle: "新终端将注入的环境变量", + detailTerminalNote: "仅对新启动的终端会话生效,不修改 `~/.zshrc`、`~/.bashrc` 或已有终端窗口;关闭该终端窗口即自动结束。", + detailTunnelCmdTitle: "隧道执行命令", + detailTunnelLocalNote: "本地转发 (-L) 可直接通过宿主拉起终端执行;保持终端开启即可使用,`Ctrl+C` 终止。", + detailTunnelDynamicNote: "动态 SOCKS5 (-D) 可作为本地 SOCKS5 代理端口使用;因宿主终端接口当前仅开放 `-L` 参数,请复制命令至终端执行。", + detailBackupTitle: "配置备份详情", + detailBackupNote: "恢复前会比对当前文件修订号;若你在备份后手动改过该文件,宿主会主动中止恢复以保护后续编辑。" }, "en-US": { unsupportedPlatform: "SSH & Proxy Helper is not supported on this platform", @@ -116,28 +246,41 @@ const MESSAGES = { terminalOpenedTitle: "Terminal launch requested", tunnelTitle: "{alias} · Port Forward", editProxyTitle: "{tool} · Set Proxy", + batchProxyTitle: "Set Git & NPM Proxy", newTerminalProxy: "New Terminal Proxy", sourceTitle: "{tool} · Config Source", navTitle: "SSH & Proxy", - searchPlaceholder: "Search SSH hosts, Git, NPM, or proxy port", + searchPlaceholder: "Search host alias, IP, user, proxy, or tunnel...", viewDropdownTooltip: "Filter View", catAll: "All", catHosts: "SSH Hosts", catProxy: "Dev Proxy", + catTunnels: "Tunnel Presets", catBackups: "Backups", readingOrVerifying: "Reading or verifying config...", - summaryHosts: "{count} [[count:host|hosts]] · Git & NPM managed separately", + summaryHosts: "{count} [[count:host|hosts]] · {activeProxies}/2 dev proxies active · {backups} [[backups:backup|backups]]", notReadYet: "Config not loaded yet", cancelOp: "Cancel", refresh: "Refresh", + newHostAction: "New Host", readIncompleteTitle: "Config read incomplete", readingConfigTitle: "Loading config", readingConfigSubtitle: "Connect to hosts or manage proxies once loaded", conditionalHostFallback: "Target determined by SSH Match conditions", hasConditionBadge: "Conditional", - createLocalTunnel: "Create Local Port Forward...", + pinnedBadge: "Pinned", + jumpBadge: "Jump", + proxyActiveBadge: "Active", + proxyUnsetBadge: "Unset", + proxyErrorBadge: "Error", + createLocalTunnel: "Create Port Forward...", connectInTerminal: "Connect in Terminal", copyConnectCmd: "Copy SSH Command", + pinHost: "Pin Host", + unpinHost: "Unpin Host", + editHostConfig: "Generate Edit Snippet...", + newHostConfig: "New Host Snippet...", + startConfigForward: "Start Forward ({spec})", toolProxyTitle: "{tool} Proxy", proxyUnsetExists: "No generic proxy in {file}", proxyUnsetMissing: "{file} not created yet; no proxy set", @@ -145,23 +288,41 @@ const MESSAGES = { setLocalProxyPort: "Set Local Proxy Port...", clearProxyInFile: "Clear Generic Proxy", viewConfigSource: "View Config Source", + batchProxyItemTitle: "Toggle All Dev Proxies (Git + NPM)", + batchProxyActiveSubtitle: "{active}/2 active · remembered port {port}", + batchProxyIdleSubtitle: "All off · remembered port {port}", + batchEnableProxy: "Enable Git + NPM (Port {port})", + batchClearProxy: "Clear All Dev Proxies", + batchEditPort: "Custom Port & Apply All...", + batchAllAlreadySet: "Git and NPM are already configured on port {port}", + batchNothingToClear: "Neither Git nor NPM has a generic proxy configured", + batchDoneTitle: "Batch proxy update completed", + batchDoneMessage: "Updated and verified {count} [[count:tool|tools]]", terminalProxySubtitle: "Sets proxy env vars only in a new terminal window", openTerminalWithProxy: "Open Terminal with Proxy...", + openTerminalWithLastPort: "Open Terminal with Port {port}", sshReadFailedTitle: "Failed to read SSH config", sshNoMatchTitle: "No matching SSH hosts", sshNoAliasTitle: "No explicit SSH host aliases", sshEmptySubtitle: "Reads Host aliases from {path} and Includes; wildcard rules are excluded.", + sshEmptyGuideTitle: "Create First SSH Host Snippet", + sshEmptyGuideSubtitle: "No explicit hosts in {path}; press Enter to generate a config snippet", clearSearch: "Clear Search", retainedOriginalTitle: "Latest Retained Original", copyOriginalLocation: "Copy Original Path", backupReadIncomplete: "Backup read incomplete", noMatchingBackups: "No matching backups", - backupHint: "Original files are backed up before modifying Git or NPM config", + backupHint: "Original files are backed up automatically before modifying Git or NPM config", previewRestore: "Preview Restore", invalidPort: "Port must be an integer between 1 and 65535", invalidRemoteHost: "Remote host must be a domain, IPv4, or bracketed IPv6 address", + invalidAlias: "Host alias may only contain letters, digits, _, ., :, or -, and must not start with - or whitespace", + invalidHostName: "HostName must not contain whitespace or control characters", + invalidFieldLineBreak: "Field value must not contain line breaks or control characters", + invalidLocalForward: "LocalForward must be formatted as \"[bind_address:]local_port remote_host:remote_port\"", opFailed: "Operation failed", createTunnelInTerminal: "Start Tunnel in Terminal", + copyDynamicTunnelCmd: "Copy SOCKS5 Tunnel Command", continueAction: "Continue", localListenPort: "Local Listen Port", localHttpProxyPort: "Local HTTP Proxy Port", @@ -170,10 +331,28 @@ const MESSAGES = { remoteTargetHost: "Remote Target Host", remoteTargetPort: "Remote Target Port", remotePortExample: "e.g. 5432", + tunnelModeLabel: "Forward Mode", + tunnelModeLocal: "Local Port Forward (-L)", + tunnelModeDynamic: "Dynamic SOCKS5 (-D · Copy Command)", + saveAsPresetLabel: "Save as Preset", + saveAsPresetCheckbox: "Save this tunnel under \"Tunnel Presets\" for one-click reuse", + presetNameLabel: "Preset Name (Optional)", + presetNamePlaceholder: "e.g. Prod MySQL Tunnel", + presetSavedTitle: "Tunnel preset saved", + presetDeletedTitle: "Tunnel preset deleted", + deletePresetAction: "Delete Tunnel Preset", + startPresetTunnel: "Start Tunnel in Terminal", + copyTunnelCmd: "Copy Tunnel Command", + newTunnelPresetAction: "New Tunnel Preset...", + noTunnelsTitle: "No tunnel presets yet", + noTunnelsDesc: "Create local (-L) or dynamic SOCKS5 (-D) tunnel presets from any SSH host", + dynamicCopiedTitle: "SOCKS5 command copied", + dynamicCopiedMsg: "Host terminal IPC currently launches -L local forwards only; -D command was copied to clipboard", incompleteLabel: "Error", descriptionLabel: "Info", tunnelDesc: "Listens on 127.0.0.1 only; target host is accessed from the SSH server. Keep terminal open; Ctrl+C to stop.", - proxyDesc: "Start your local HTTP proxy service first. Setting the proxy address does not start proxy software.", + dynamicTunnelDesc: "Host terminal IPC currently launches -L local forwards only; dynamic SOCKS5 (-D) copies the ready-to-run command to clipboard.", + proxyDesc: "Start your local HTTP proxy service first. Changes are previewed, backed up, and verified after write.", upgradeClient: "Please upgrade ZTools to use SSH & Proxy Helper", hostOpUnconfirmed: "Host did not confirm operation result; refresh to check", scanIncomplete: "Incomplete host scan result; please refresh", @@ -185,7 +364,88 @@ const MESSAGES = { sourceConfigLabel: "Config file:\n\n{location}\n\n{notices}", terminalOpenUnconfirmed: "Terminal launch request unconfirmed; check terminal window", warnCancelUnconfirmed: "Host operation cancellation unconfirmed", - warnFormCancelUnconfirmed: "Host form cancellation unconfirmed" + warnFormCancelUnconfirmed: "Host form cancellation unconfirmed", + sectionHosts: "SSH Hosts", + sectionProxies: "Dev & Terminal Proxy", + sectionTunnels: "Port Forwards & Tunnel Presets", + sectionBackups: "Configuration Backups", + sectionConfigForwards: "From SSH Config", + configForwardBadge: "Config", + presetLocalBadge: "Local -L", + presetDynamicBadge: "Dynamic -D", + hostFormNewTitle: "New SSH Host Snippet", + hostFormEditTitle: "Generate Edit Snippet · {alias}", + hostAliasLabel: "Host Alias (Host)", + hostAliasPlaceholder: "e.g. prod-bastion", + hostNameLabel: "Host Address (HostName)", + hostNamePlaceholder: "e.g. 10.20.30.40 or host.example.com", + hostUserLabel: "Username (User)", + hostUserPlaceholder: "e.g. root or ops", + hostPortLabel: "Port", + hostPortPlaceholder: "Default 22", + hostIdentityLabel: "Private Key (IdentityFile)", + hostIdentityPlaceholder: "e.g. ~/.ssh/id_ed25519", + hostProxyJumpLabel: "Jump Host (ProxyJump)", + hostProxyJumpPlaceholder: "e.g. prod-bastion (optional)", + hostLocalForwardLabel: "Local Forward (LocalForward)", + hostLocalForwardPlaceholder: "e.g. 127.0.0.1:13306 127.0.0.1:3306 (optional)", + hostFormSubmit: "Validate & Copy Config Snippet", + hostFormReadonlyNotice: "Security notice: the host ssh_proxy IPC reads ~/.ssh/config in read-only mode and does not write it directly. Submitting validates fields and copies a standard Host block to your clipboard—append it to {path} and refresh.", + hostBlockCopiedTitle: "SSH Host snippet copied", + hostBlockCopiedMessage: "Append it to {path}, then refresh the list", + hostBlockPreviewTitle: "SSH Config Snippet · {alias}", + copyConfigBlockAgain: "Copy Config Snippet Again", + backAndRefresh: "Back & Refresh", + metaHostName: "HostName", + metaUser: "User", + metaPort: "Port", + metaIdentity: "IdentityFile", + metaProxyJump: "ProxyJump", + metaLocalForward: "LocalForward", + metaParseStatus: "Parse Status", + metaBackups: "Backups", + metaTool: "Tool", + metaProxyStatus: "Status", + metaFileExists: "Config File", + metaValueCount: "Active Keys", + metaForwardMode: "Mode", + metaHostAlias: "Host Alias", + metaListenAddr: "Local Listen", + metaRemoteTarget: "Remote Target", + metaCreatedAt: "Created At", + metaNone: "None", + metaUnset: "Not set", + metaDefaultPort: "22 (default)", + metaComplete: "Statically complete", + metaPartial: "Conditional (resolved by system SSH)", + metaExists: "Exists", + metaNotCreated: "Not created yet", + metaBackupCount: "{count}", + metaLocalForwardCount: "{count}", + detailQuickConnect: "Quick Connect Command", + detailLocalForwards: "Configured LocalForwards", + detailNotices: "Parser Notices", + detailTransactionNoteTitle: "Read-Only & Transaction Safety", + detailHostReadonlyNote: "Host IPC scans `~/.ssh/config` read-only and launches system terminals. Creating or editing a host generates a standard config block for manual append without silently modifying your SSH file.", + detailProxyConfigPath: "Config File Path", + detailProxyCurrentValues: "Active Proxy Entries", + detailProxyNoValues: "No generic HTTP/HTTPS proxy is configured in this file.", + detailProxyTransactionNote: "Every write follows `prepare -> diff confirm -> backup -> apply & read-back verify`. Originals are retained and restorable from Backups.", + detailProxySystemNote: "Host IPC manages user-level Git and NPM config files and does not alter OS-wide system proxy settings.", + detailProxyCredentialWarn: "Contains credentials (masked)", + detailProxyDynamicWarn: "Contains dynamic/env reference", + detailBatchSummaryTitle: "Dev Proxy Status Overview", + detailBatchColTool: "Tool", + detailBatchColStatus: "Status", + detailBatchColValue: "Current Value", + detailBatchNote: "Batch enable/clear executes `prepare -> diff confirm -> backup -> verify` per tool; cancelling or failing any step will never silently skip verification.", + detailTerminalEnvTitle: "Environment Variables for New Terminal", + detailTerminalNote: "Applies only to the newly launched terminal session without touching shell profiles or existing windows; close the terminal to end.", + detailTunnelCmdTitle: "Tunnel Command", + detailTunnelLocalNote: "Local forwards (-L) can be launched directly via host terminal IPC. Keep the terminal open; press `Ctrl+C` to stop.", + detailTunnelDynamicNote: "Dynamic SOCKS5 (-D) exposes a local SOCKS5 proxy. Host terminal IPC currently supports `-L` only, so copy and run this command in your terminal.", + detailBackupTitle: "Backup Details", + detailBackupNote: "Restore checks the current file revision before writing; if the file was manually edited afterwards, restore aborts safely." } }; diff --git a/extensions/ssh-proxy-helper/src/mac-command.tsx b/extensions/ssh-proxy-helper/src/mac-command.tsx index 5fa8fe32..60b49c35 100644 --- a/extensions/ssh-proxy-helper/src/mac-command.tsx +++ b/extensions/ssh-proxy-helper/src/mac-command.tsx @@ -1,89 +1,1038 @@ -import React, { Action, ActionPanel, Detail, Icon, List, Toast, confirmAlert, showToast, useEffect, useLocale, useNavigation, useRef, useState } from '@ztools/declarative-ui' +import React, { Action, ActionPanel, Clipboard, Detail, Icon, List, Toast, confirmAlert, showToast, useEffect, useLocale, useNavigation, useRef, useState } from '@ztools/declarative-ui' +let fallbackIdSeq = 0 +const randomUUID = (): string => (typeof globalThis.crypto?.randomUUID === 'function' ? globalThis.crypto.randomUUID() : `id-${Date.now()}-${++fallbackIdSeq}`) import { t } from './i18n.js' import { applyProxy, cancelSsh, openSshTerminal, prepareProxy, scanSsh, sourceMarkdown, type ProxyChange, type ProxyRow, type ProxyTool, type Snapshot, type SshHost } from './mac-service.js' -import { ConnectionForm } from './mac-forms.js' +import { ConnectionForm, SshHostForm } from './mac-forms.js' import { resolveErrorMessage } from './error-i18n.js' +import { + buildBackupDetailMarkdown, + buildBatchProxyDetailMarkdown, + buildConnectCommand, + buildDynamicSocksCommand, + buildHostDetailMarkdown, + buildLocalTunnelCommand, + buildProxyDetailMarkdown, + buildTerminalProxyDetailMarkdown, + buildTunnelDetailMarkdown, + extractProxyPortFromSnapshot, + getProxyToolLabel, + isToolAtPort, + loadLastProxyPort, + loadPinnedAliases, + loadTunnelPresets, + parseLocalForward, + saveLastProxyPort, + savePinnedAliases, + saveTunnelPresets, + sshConfigDisplayPath, + type TunnelPreset +} from './ssh-helpers.js' + const failure = (error: unknown) => resolveErrorMessage(error, t('opIncomplete')) -const TOOL_LABEL: Record = { git: 'Git', npm: 'NPM' } -/** 只显示文件名(如 .gitconfig、.npmrc),完整路径在“查看配置来源”里 */ const fileName = (location: string) => location.split(/[\\/]/).filter(Boolean).pop() || location +type ViewCategory = 'all' | 'hosts' | 'proxy' | 'tunnels' | 'backups' + +function initialCategoryFor(featureCode: string): ViewCategory { + if (featureCode === 'ssh-proxy-toggle') return 'proxy' + if (featureCode === 'ssh-tunnel') return 'hosts' + return 'all' +} + export default function MacSshCommand({ featureCode = 'ssh-all', platform = 'macos' }: { featureCode?: string; platform?: 'macos' | 'windows' } = {}) { useLocale() const windows = platform === 'windows' - const [snapshot, setSnapshot] = useState(null), [busy, setBusy] = useState(false), [error, setError] = useState('') - const [query, setQuery] = useState(''), [category, setCategory] = useState(featureCode === 'ssh-proxy-toggle' ? 'proxy' : featureCode === 'ssh-tunnel' ? 'hosts' : 'all') + const configPath = sshConfigDisplayPath(windows) + const [snapshot, setSnapshot] = useState(null) + const [busy, setBusy] = useState(false) + const [error, setError] = useState('') + const [query, setQuery] = useState('') + const [category, setCategory] = useState(initialCategoryFor(featureCode)) const [recoveryPath, setRecoveryPath] = useState('') - const alive = useRef(true), guard = useRef(false), current = useRef(null), { push } = useNavigation() + const [pinnedAliases, setPinnedAliases] = useState([]) + const [presets, setPresets] = useState([]) + const [lastPort, setLastPort] = useState(7890) + const alive = useRef(true) + const guard = useRef(false) + const current = useRef(null) + const { push } = useNavigation() + const reload = async () => { - current.current = null; if (alive.current) setSnapshot(null) + current.current = null + if (alive.current) setSnapshot(null) const next = await scanSsh() - if (alive.current) { current.current = next; setSnapshot(next) } + if (alive.current) { + current.current = next + setSnapshot(next) + const detected = extractProxyPortFromSnapshot(next) + if (detected) { + setLastPort(detected) + void saveLastProxyPort(detected) + } + } } + const run = async (work: () => Promise) => { if (guard.current || !alive.current) return false - guard.current = true; setBusy(true); setError('') - try { await work(); return true } - catch (e) { if (alive.current) { setError(failure(e)); await showToast(Toast.Style.Failure, t('opIncompleteTitle'), failure(e)) }; return false } - finally { guard.current = false; if (alive.current) setBusy(false) } + guard.current = true + setBusy(true) + setError('') + try { + await work() + return true + } catch (e) { + if (alive.current) { + setError(failure(e)) + await showToast(Toast.Style.Failure, t('opIncompleteTitle'), failure(e)) + } + return false + } finally { + guard.current = false + if (alive.current) setBusy(false) + } } - // 取消请求本身失败(如客户端已无此操作)要如实提示,不能变成未处理的异常 + const stop = async () => { - try { await cancelSsh() } - catch (e) { if (alive.current) { setError(t('cancelUnconfirmedPrefix', { error: failure(e) })); await showToast(Toast.Style.Failure, t('cancelUnconfirmedTitle'), failure(e)) } } + try { + await cancelSsh() + } catch (e) { + if (alive.current) { + setError(t('cancelUnconfirmedPrefix', { error: failure(e) })) + await showToast(Toast.Style.Failure, t('cancelUnconfirmedTitle'), failure(e)) + } + } } - useEffect(() => { void run(reload); return () => { alive.current = false; if (guard.current) void cancelSsh().catch(e => console.warn(t('warnCancelUnconfirmed'), e)) } }, []) + + useEffect(() => { + void Promise.all([loadPinnedAliases(), loadTunnelPresets(), loadLastProxyPort()]).then(([pins, savedPresets, port]) => { + if (!alive.current) return + setPinnedAliases(pins) + setPresets(savedPresets) + setLastPort(port) + }) + void run(reload) + return () => { + alive.current = false + if (guard.current) void cancelSsh().catch(e => console.warn(t('warnCancelUnconfirmed'), e)) + } + }, []) + + const applySingleProxyStep = async (tool: ProxyTool, change: ProxyChange, active: () => boolean): Promise => { + const loaded = current.current + if (!loaded || !active()) throw new Error(t('refreshBeforeMutate')) + const plan = await prepareProxy(loaded.sessionId, tool, change) + if (!alive.current || !active()) { + await cancelSsh() + return false + } + const format = (items: typeof plan.before) => + items.length + ? items.map(p => t('confirmTitlePrefix', { key: p.key, value: p.value })).join('\n') + : t('noGenericProxyInFile', { file: fileName(plan.location) }) + const confirmed = await confirmAlert({ + title: plan.summary, + message: t('confirmMessage', { + location: plan.location, + before: format(plan.before), + after: format(plan.after), + notices: plan.notices.join('\n') + }), + primaryAction: { title: t('confirmAndVerify') }, + dismissAction: { title: t('cancel') } + }) + if (!confirmed || !alive.current || !active()) { + await cancelSsh() + return false + } + let operationError = '' + let retained = '' + let applied = false + try { + const result = await applyProxy(plan.planId) + retained = result.recoveryPath || '' + applied = true + if (alive.current && retained) setRecoveryPath(retained) + if (change.kind === 'set' && alive.current) { + setLastPort(change.port) + void saveLastProxyPort(change.port) + } + } catch (e) { + operationError = failure(e) + } + if (alive.current) { + try { + await reload() + } catch (e) { + operationError += `${operationError ? ';' : ''}${t('refreshFailed', { error: failure(e) })}` + } + } + if (operationError) throw new Error(operationError) + if (alive.current && active()) { + await showToast( + Toast.Style.Success, + t('configWrittenTitle'), + t('retainedHint', { retained: retained ? t('retainedPrefix', { path: retained }) : '' }) + ) + } + return applied + } + const mutate = async (tool: ProxyTool, change: ProxyChange, active = () => true) => { let done = false + const ok = await run(async () => { + done = await applySingleProxyStep(tool, change, active) + }) + return ok && done + } + + const mutateBatchProxy = async (mode: 'set' | 'clear', port = lastPort, active = () => true) => { + let appliedCount = 0 const ok = await run(async () => { const loaded = current.current if (!loaded || !active()) throw new Error(t('refreshBeforeMutate')) - const plan = await prepareProxy(loaded.sessionId, tool, change) - if (!alive.current || !active()) { await cancelSsh(); return } - const format = (items: typeof plan.before) => items.length ? items.map(p => t('confirmTitlePrefix', { key: p.key, value: p.value })).join('\n') : t('noGenericProxyInFile', { file: fileName(plan.location) }) - const confirmed = await confirmAlert({ title: plan.summary, message: t('confirmMessage', { location: plan.location, before: format(plan.before), after: format(plan.after), notices: plan.notices.join('\n') }), primaryAction: { title: t('confirmAndVerify') }, dismissAction: { title: t('cancel') } }) - if (!confirmed || !alive.current || !active()) { await cancelSsh(); return } - let operationError = '', retained = '' - try { - const result = await applyProxy(plan.planId); retained = result.recoveryPath || ''; done = true - if (alive.current && retained) setRecoveryPath(retained) - } catch (e) { operationError = failure(e) } - if (alive.current) { try { await reload() } catch (e) { operationError += `${operationError ? ';' : ''}${t('refreshFailed', { error: failure(e) })}` } } - if (operationError) throw new Error(operationError) - if (alive.current && active()) await showToast(Toast.Style.Success, t('configWrittenTitle'), t('retainedHint', { retained: retained ? t('retainedPrefix', { path: retained }) : '' })) + const targets: ProxyTool[] = [] + for (const row of loaded.proxies) { + if (row.status !== 'ready') continue + if (mode === 'set' && !isToolAtPort(row, port)) targets.push(row.tool) + if (mode === 'clear' && row.values.length > 0) targets.push(row.tool) + } + if (targets.length === 0) { + await showToast( + Toast.Style.Success, + t('batchProxyItemTitle'), + mode === 'set' ? t('batchAllAlreadySet', { port }) : t('batchNothingToClear') + ) + return + } + for (const tool of targets) { + if (!alive.current || !active()) break + const change: ProxyChange = mode === 'set' ? { kind: 'set', port } : { kind: 'clear' } + const stepOk = await applySingleProxyStep(tool, change, active) + if (!stepOk) break + appliedCount += 1 + } + if (appliedCount > 0 && alive.current && active()) { + await showToast(Toast.Style.Success, t('batchDoneTitle'), t('batchDoneMessage', { count: appliedCount })) + } }) - return ok && done + return ok && appliedCount > 0 + } + + const terminal = (params: Record, active = () => true) => + run(async () => { + if (!active()) return + const notice = await openSshTerminal(params) + if (params.action === 'terminal-proxy' && typeof params.port === 'number' && alive.current) { + setLastPort(params.port) + void saveLastProxyPort(params.port) + } + if (alive.current && active()) { + await showToast(Toast.Style.Success, t('terminalOpenedTitle'), notice) + } + }) + + const connect = (host: SshHost) => + terminal({ action: 'connect', sessionId: current.current?.sessionId, alias: host.alias }) + + const startLocalForward = (alias: string, localPort: number, remoteHost: string, remotePort: number) => + terminal({ + action: 'tunnel', + sessionId: current.current?.sessionId, + alias, + tunnel: { localPort, remoteHost, remotePort } + }) + + const addPreset = async (preset: Omit) => { + const next: TunnelPreset[] = [ + { ...preset, id: `preset_${randomUUID()}` }, + ...presets + ] + setPresets(next) + await saveTunnelPresets(next) + if (alive.current) await showToast(Toast.Style.Success, t('presetSavedTitle'), preset.name) + } + + const removePreset = async (presetId: string) => { + const next = presets.filter(p => p.id !== presetId) + setPresets(next) + await saveTunnelPresets(next) + if (alive.current) await showToast(Toast.Style.Success, t('presetDeletedTitle')) + } + + const togglePin = async (alias: string) => { + const exists = pinnedAliases.includes(alias) + const next = exists ? pinnedAliases.filter(a => a !== alias) : [alias, ...pinnedAliases] + setPinnedAliases(next) + await savePinnedAliases(next) + } + + const openNewHostForm = (initialHost?: SshHost) => { + if (guard.current) return + push( + { + void run(reload) + }} + /> + ) } - const terminal = (params: Record, active = () => true) => run(async () => { - if (!active()) return - const notice = await openSshTerminal(params) - if (alive.current && active()) await showToast(Toast.Style.Success, t('terminalOpenedTitle'), notice) + + const openTunnelForm = (host: SshHost) => { + if (guard.current) return + push( + + terminal( + { + action: 'tunnel', + sessionId: current.current?.sessionId, + alias: host.alias, + tunnel: { localPort: v.port, remoteHost: v.remoteHost, remotePort: v.remotePort } + }, + active + ) + } + /> + ) + } + + const editProxy = (tool?: ProxyTool) => { + if (guard.current) return + push( + + tool + ? mutate(tool, { kind: 'set', port: v.port }, active) + : terminal({ action: 'terminal-proxy', port: v.port }, active) + } + /> + ) + } + + const editBatchProxy = () => { + if (guard.current) return + push( + mutateBatchProxy('set', v.port, active)} + /> + ) + } + + const sources = (row: ProxyRow) => { + if (row.status === 'ready') { + push() + } + } + + const q = query.trim().toLowerCase() + const showHosts = category === 'all' || category === 'hosts' + const showProxy = category === 'all' || category === 'proxy' + const showTunnels = category === 'all' || category === 'tunnels' + const showBackups = category === 'backups' + + const allHosts = snapshot?.ssh.hosts ?? [] + const sortedHosts = [...allHosts].sort((a, b) => { + const aPinned = pinnedAliases.includes(a.alias) ? 0 : 1 + const bPinned = pinnedAliases.includes(b.alias) ? 0 : 1 + if (aPinned !== bPinned) return aPinned - bPinned + return a.alias.localeCompare(b.alias) }) - const connect = (host: SshHost) => terminal({ action: 'connect', sessionId: current.current?.sessionId, alias: host.alias }) - const tunnel = (host: SshHost) => { if (!guard.current) push( terminal({ action: 'tunnel', sessionId: current.current?.sessionId, alias: host.alias, tunnel: { localPort: v.port, remoteHost: v.remoteHost, remotePort: v.remotePort } }, active)} />) } - const editProxy = (tool?: ProxyTool) => { if (!guard.current) push( tool ? mutate(tool, { kind: 'set', port: v.port }, active) : terminal({ action: 'terminal-proxy', port: v.port }, active)} />) } - const sources = (row: ProxyRow) => { if (row.status === 'ready') push() } - const q = query.trim().toLowerCase(), showHosts = category === 'all' || category === 'hosts', showProxy = category === 'all' || category === 'proxy' - const hosts = showHosts ? snapshot?.ssh.hosts.filter(h => `${h.alias} ${h.hostName || ''} ${h.user || ''}`.toLowerCase().includes(q)) || [] : [] - const proxies = showProxy ? snapshot?.proxies.filter(p => p.tool.includes(q) || (p.status === 'ready' && p.values.some(v => v.value.includes(q)))) || [] : [] - const backups = category === 'backups' ? snapshot?.backups.filter(b => `${b.summary} ${b.createdAt}`.toLowerCase().includes(q)) || [] : [] + const hosts = showHosts + ? sortedHosts.filter(h => + `${h.alias} ${h.hostName || ''} ${h.user || ''} ${h.proxyJump || ''}`.toLowerCase().includes(q) + ) + : [] + + const proxies = showProxy + ? (snapshot?.proxies ?? []).filter( + p => + p.tool.includes(q) || + getProxyToolLabel(p.tool).toLowerCase().includes(q) || + (p.status === 'ready' && p.values.some(v => v.value.toLowerCase().includes(q))) + ) + : [] + + const activeProxyCount = (snapshot?.proxies ?? []).filter(p => p.status === 'ready' && p.values.length > 0).length + const readyProxyCount = (snapshot?.proxies ?? []).filter(p => p.status === 'ready').length + + const configForwards = showTunnels + ? allHosts.flatMap(h => + h.localForwards.map((spec, idx) => ({ + id: `cfgfwd:${h.alias}:${idx}`, + alias: h.alias, + spec, + parsed: parseLocalForward(spec) + })) + ).filter(item => `${item.alias} ${item.spec}`.toLowerCase().includes(q)) + : [] + + const filteredPresets = showTunnels + ? presets.filter(p => `${p.name} ${p.alias} ${p.localPort} ${p.remoteHost || ''}`.toLowerCase().includes(q)) + : [] + + const backups = showBackups + ? (snapshot?.backups ?? []).filter(b => `${b.summary} ${b.createdAt} ${b.tool}`.toLowerCase().includes(q)) + : [] + const notices = snapshot ? [snapshot.ssh.error, ...snapshot.ssh.warnings, snapshot.backupError].filter(Boolean).join(';') : '' - return } - filterBar={{ summaryText: error || notices || (busy ? t('readingOrVerifying') : snapshot ? t('summaryHosts', { count: snapshot.ssh.hosts.length }) : t('notReadYet')), actions: [{ id: 'refresh', title: busy ? t('cancelOp') : t('refresh'), onAction: () => busy ? stop() : run(reload) }] }}> - {!snapshot && } - {hosts.map(h => - { if (featureCode === 'ssh-tunnel') tunnel(h); else await connect(h) }} /> - { if (featureCode === 'ssh-tunnel') await connect(h); else tunnel(h) }} /> - - } />)} - {proxies.map(p => `${v.key}: ${v.value}`).join(' · ') : (p.exists ? t('proxyUnsetExists', { file: fileName(p.location) }) : t('proxyUnsetMissing', { file: fileName(p.location) }))} - actions={{p.status === 'error' && { await run(reload) }} />}{p.status === 'ready' && editProxy(p.tool)} />}{p.status === 'ready' && p.values.length > 0 && { await mutate(p.tool, { kind: 'clear' }) }} />}{p.status === 'ready' && sources(p)} />}} />)} - {snapshot && showProxy && (!q || `${t('newTerminalProxy')} terminal`.toLowerCase().includes(q)) && editProxy()} />} />} - {snapshot && showHosts && !hosts.length && { if (q) setQuery(''); else await run(reload) }} />} />} - {category === 'backups' && recoveryPath && } />} - {category === 'backups' && snapshot && !backups.length && } - {backups.map(b => { await mutate(b.tool, { kind: 'restore', backupId: b.id }) }} />} />)} - + const showBatchProxyItem = + Boolean(snapshot) && + showProxy && + readyProxyCount > 0 && + (!q || `${t('batchProxyItemTitle')} git npm proxy ${lastPort}`.toLowerCase().includes(q)) + const showTerminalProxyItem = + Boolean(snapshot) && + showProxy && + (!q || `${t('newTerminalProxy')} terminal proxy ${lastPort}`.toLowerCase().includes(q)) + + const hasAnyProxyItems = proxies.length > 0 || showBatchProxyItem || showTerminalProxyItem + const hasAnyTunnelItems = configForwards.length > 0 || filteredPresets.length > 0 + const hasAnyBackupItems = Boolean(recoveryPath) || backups.length > 0 + + const renderHostDetail = (h: SshHost) => ( + + + + + + + + + + + + } + /> + ) + + const renderProxyDetail = (p: ProxyRow) => { + const label = getProxyToolLabel(p.tool) + const toolBackups = (snapshot?.backups ?? []).filter(b => b.tool === p.tool).length + return ( + + + 0 + ? t('proxyActiveBadge') + : t('proxyUnsetBadge') + } + /> + {p.status === 'ready' && ( + + )} + {p.status === 'ready' && ( + + )} + + + + } + /> + ) + } + + return ( + setCategory(v as ViewCategory)} + tooltip={t('viewDropdownTooltip')} + > + + + + + + + } + filterBar={{ + summaryText: + error || + notices || + (busy + ? t('readingOrVerifying') + : snapshot + ? t('summaryHosts', { + count: snapshot.ssh.hosts.length, + activeProxies: activeProxyCount, + backups: snapshot.backups.length + }) + : t('notReadYet')), + actions: busy + ? [{ id: 'refresh', title: t('cancelOp'), onAction: () => void stop() }] + : [ + { id: 'new-host', title: t('newHostAction'), icon: Icon.Plus, onAction: () => openNewHostForm() }, + { id: 'refresh', title: t('refresh'), icon: Icon.ArrowClockwise, onAction: () => void run(reload) } + ] + }} + actions={ + + openNewHostForm()} /> + { await run(reload) }} /> + + } + > + {!snapshot && ( + } + actions={ + + { await run(reload) }} /> + + } + /> + )} + + {snapshot && showHosts && hosts.length > 0 && ( + + {hosts.map(h => { + const pinned = pinnedAliases.includes(h.alias) + const firstForward = h.localForwards.map(parseLocalForward).find(f => f !== null) ?? null + const accessories: Array<{ tag?: string; text?: string }> = [] + if (pinned) accessories.push({ tag: t('pinnedBadge') }) + if (h.proxyJump) accessories.push({ tag: t('jumpBadge') }) + if (!h.previewComplete) accessories.push({ text: t('hasConditionBadge') }) + + const hostSubtitle = h.proxyJump + ? `via ${h.proxyJump}${h.user ? ` · ${h.user}` : ''}` + : `${h.hostName || t('conditionalHostFallback')}${h.port ? `:${h.port}` : ''}${h.user ? ` · ${h.user}` : ''}` + + return ( + + { + if (featureCode === 'ssh-tunnel') openTunnelForm(h) + else await connect(h) + }} + /> + { + if (featureCode === 'ssh-tunnel') await connect(h) + else openTunnelForm(h) + }} + /> + + {firstForward && ( + { + await startLocalForward( + h.alias, + firstForward.localPort, + firstForward.remoteHost, + firstForward.remotePort + ) + }} + /> + )} + { + await togglePin(h.alias) + }} + /> + openNewHostForm(h)} + /> + openNewHostForm()} + /> + + } + /> + ) + })} + + )} + + {snapshot && showProxy && hasAnyProxyItems && ( + + {proxies.map(p => { + const toolLabel = getProxyToolLabel(p.tool) + const badge = + p.status === 'error' + ? t('proxyErrorBadge') + : p.values.length > 0 + ? t('proxyActiveBadge') + : t('proxyUnsetBadge') + return ( + `${v.key}: ${v.value}`).join(' · ') + : p.exists + ? t('proxyUnsetExists', { file: fileName(p.location) }) + : t('proxyUnsetMissing', { file: fileName(p.location) }) + } + accessories={[{ tag: badge }]} + detail={renderProxyDetail(p)} + actions={ + + {p.status === 'error' && ( + { await run(reload) }} /> + )} + {p.status === 'ready' && ( + editProxy(p.tool)} /> + )} + {p.status === 'ready' && p.values.length > 0 && ( + { + await mutate(p.tool, { kind: 'clear' }) + }} + /> + )} + {p.status === 'ready' && ( + sources(p)} /> + )} + + } + /> + ) + })} + + {showBatchProxyItem && ( + 0 + ? t('batchProxyActiveSubtitle', { active: activeProxyCount, port: lastPort }) + : t('batchProxyIdleSubtitle', { port: lastPort }) + } + icon={Icon.Gear} + accessories={[{ tag: activeProxyCount > 0 ? t('proxyActiveBadge') : t('proxyUnsetBadge') }]} + detail={ + + + + + + } + /> + } + actions={ + + {activeProxyCount > 0 ? ( + { + await mutateBatchProxy('clear') + }} + /> + ) : ( + { + await mutateBatchProxy('set', lastPort) + }} + /> + )} + editBatchProxy()} /> + {activeProxyCount > 0 && activeProxyCount < readyProxyCount && ( + { + await mutateBatchProxy('set', lastPort) + }} + /> + )} + + } + /> + )} + + {showTerminalProxyItem && ( + + + + } + /> + } + actions={ + + editProxy()} /> + { + await terminal({ action: 'terminal-proxy', port: lastPort }) + }} + /> + + } + /> + )} + + )} + + {snapshot && showTunnels && hasAnyTunnelItems && ( + + {configForwards.map(item => { + const p = item.parsed + const cmd = p + ? buildLocalTunnelCommand(item.alias, p.localPort, p.remoteHost, p.remotePort, windows) + : buildConnectCommand(item.alias, windows) + return ( + + + + + {p && ( + + )} + + } + /> + } + actions={ + + {p && ( + { + await startLocalForward(item.alias, p.localPort, p.remoteHost, p.remotePort) + }} + /> + )} + + + } + /> + ) + })} + + {filteredPresets.map(preset => { + const isLocal = preset.mode === 'local' && Boolean(preset.remoteHost) && Boolean(preset.remotePort) + const cmd = isLocal + ? buildLocalTunnelCommand(preset.alias, preset.localPort, preset.remoteHost!, preset.remotePort!, windows) + : buildDynamicSocksCommand(preset.alias, preset.localPort, windows) + return ( + ${preset.remoteHost}:${preset.remotePort}` + : `${preset.alias} · SOCKS5 127.0.0.1:${preset.localPort}` + } + icon={Icon.Terminal} + accessories={[{ tag: isLocal ? t('presetLocalBadge') : t('presetDynamicBadge') }]} + detail={ + + + + + {isLocal && ( + + )} + + } + /> + } + actions={ + + {isLocal ? ( + { + await startLocalForward(preset.alias, preset.localPort, preset.remoteHost!, preset.remotePort!) + }} + /> + ) : ( + { + await Clipboard.copy(cmd) + if (alive.current) { + await showToast(Toast.Style.Success, t('dynamicCopiedTitle'), t('dynamicCopiedMsg')) + } + }} + /> + )} + + { + await removePreset(preset.id) + }} + /> + + } + /> + ) + })} + + )} + + {snapshot && showHosts && hosts.length === 0 && category === 'all' && ( + + + } + actions={ + + {q ? ( + setQuery('')} /> + ) : snapshot.ssh.status === 'error' ? ( + { await run(reload) }} /> + ) : ( + openNewHostForm()} /> + )} + {!q && snapshot.ssh.status !== 'error' && ( + { await run(reload) }} /> + )} + + } + /> + + )} + + {snapshot && category === 'hosts' && hosts.length === 0 && ( + + )} + + {snapshot && category === 'tunnels' && !hasAnyTunnelItems && ( + + )} + + {showBackups && hasAnyBackupItems && ( + + {recoveryPath && ( + } + actions={ + + + + } + /> + )} + {backups.map(b => ( + + + + + } + /> + } + actions={ + + { + await mutate(b.tool, { kind: 'restore', backupId: b.id }) + }} + /> + + } + /> + ))} + + )} + + {showBackups && snapshot && !hasAnyBackupItems && ( + + )} + + ) } diff --git a/extensions/ssh-proxy-helper/src/mac-forms.tsx b/extensions/ssh-proxy-helper/src/mac-forms.tsx index 99acd6eb..ff4c86ce 100644 --- a/extensions/ssh-proxy-helper/src/mac-forms.tsx +++ b/extensions/ssh-proxy-helper/src/mac-forms.tsx @@ -1,27 +1,380 @@ -import React, { Action, ActionPanel, Form, useEffect, useLocale, useNavigation, useRef, useState } from '@ztools/declarative-ui' +import React, { Action, ActionPanel, Clipboard, Detail, Form, Icon, Toast, showToast, useEffect, useLocale, useNavigation, useRef, useState } from '@ztools/declarative-ui' import { t } from './i18n.js' import { resolveErrorMessage } from './error-i18n.js' -import { cancelSsh } from './mac-service.js' -const portValue = (value: string) => { if (!/^\d+$/.test(value) || Number(value) < 1 || Number(value) > 65535) throw new Error(t('invalidPort')); return Number(value) } -export function ConnectionForm({ title, tunnel = false, save }: { title: string; tunnel?: boolean; save: (values: { port: number; remoteHost: string; remotePort: number }, alive: () => boolean) => Promise }) { +import { cancelSsh, type SshHost } from './mac-service.js' +import { + buildDynamicSocksCommand, + parsePortNumber, + sshConfigDisplayPath, + validateAndFormatSshConfigBlock, + validateRemoteHost, + type SshHostDraft, + type TunnelMode, + type TunnelPreset +} from './ssh-helpers.js' + +export interface ConnectionFormValues { + mode: TunnelMode + port: number + remoteHost: string + remotePort: number + saveAsPreset: boolean + presetName: string +} + +export function ConnectionForm({ + title, + tunnel = false, + alias, + windows = false, + defaultPort = 7890, + save, + onSavePreset +}: { + title: string + tunnel?: boolean + alias?: string + windows?: boolean + defaultPort?: number + save: (values: ConnectionFormValues, alive: () => boolean) => Promise + onSavePreset?: (preset: Omit) => Promise +}) { useLocale() - const [port, setPort] = useState(tunnel ? '' : '7890'), [remoteHost, setRemoteHost] = useState('localhost'), [remotePort, setRemotePort] = useState('') - const [busy, setBusy] = useState(false), [error, setError] = useState(''), alive = useRef(true), guard = useRef(false), { pop } = useNavigation() - useEffect(() => () => { alive.current = false; if (guard.current) void cancelSsh().catch(e => console.warn(t('warnFormCancelUnconfirmed'), e)) }, []) + const [mode, setMode] = useState('local') + const [port, setPort] = useState(tunnel ? '' : String(defaultPort)) + const [remoteHost, setRemoteHost] = useState('localhost') + const [remotePort, setRemotePort] = useState('') + const [saveAsPreset, setSaveAsPreset] = useState(false) + const [presetName, setPresetName] = useState('') + const [busy, setBusy] = useState(false) + const [error, setError] = useState('') + const alive = useRef(true) + const guard = useRef(false) + const { pop } = useNavigation() + + useEffect(() => () => { + alive.current = false + if (guard.current) void cancelSsh().catch(e => console.warn(t('warnFormCancelUnconfirmed'), e)) + }, []) + + const isDynamic = tunnel && mode === 'dynamic' + + const submit = async () => { + if (guard.current) return + guard.current = true + setBusy(true) + setError('') + try { + const local = parsePortNumber(port) + const remote = tunnel && mode === 'local' ? parsePortNumber(remotePort) : 1 + const host = tunnel && mode === 'local' ? validateRemoteHost(remoteHost) : 'localhost' + + if (tunnel && saveAsPreset && alias && onSavePreset) { + const defaultName = mode === 'local' + ? `${alias} (-L ${local} -> ${host}:${remote})` + : `${alias} (-D ${local})` + await onSavePreset({ + name: presetName.trim() || defaultName, + alias, + mode, + localPort: local, + remoteHost: mode === 'local' ? host : undefined, + remotePort: mode === 'local' ? remote : undefined + }) + } + + if (isDynamic && alias) { + const cmd = buildDynamicSocksCommand(alias, local, windows) + await Clipboard.copy(cmd) + if (alive.current) { + await showToast(Toast.Style.Success, t('dynamicCopiedTitle'), t('dynamicCopiedMsg')) + pop() + } + return + } + + const ok = await save( + { + mode, + port: local, + remoteHost: host, + remotePort: remote, + saveAsPreset, + presetName: presetName.trim() + }, + () => alive.current + ) + if (ok && alive.current) pop() + } catch (e) { + if (alive.current) setError(resolveErrorMessage(e, t('opFailed'))) + } finally { + guard.current = false + if (alive.current) setBusy(false) + } + } + + return ( +
+ + + } + > + {tunnel && ( + setMode(v === 'dynamic' ? 'dynamic' : 'local')} + > + + + + )} + + {tunnel && !isDynamic && ( + + )} + {tunnel && !isDynamic && ( + + )} + {tunnel && alias && onSavePreset && ( + + )} + {tunnel && alias && onSavePreset && saveAsPreset && ( + + )} + + + ) +} + +function SshHostPreviewView({ + alias, + configBlock, + configPath, + onDone +}: { + alias: string + configBlock: string + configPath: string + onDone: () => void +}) { + useLocale() + const { pop } = useNavigation() + const markdown = [ + `### ${t('hostBlockPreviewTitle', { alias })}`, + `\`\`\`sshconfig\n${configBlock}\n\`\`\``, + t('hostFormReadonlyNotice', { path: configPath }) + ].join('\n\n') + + return ( + + + { + pop() + pop() + onDone() + }} + /> + + } + /> + ) +} + +export function SshHostForm({ + initialHost, + windows, + onRefreshRequested +}: { + initialHost?: SshHost + windows: boolean + onRefreshRequested: () => void +}) { + useLocale() + const [alias, setAlias] = useState(initialHost?.alias ?? '') + const [hostName, setHostName] = useState(initialHost?.hostName ?? '') + const [user, setUser] = useState(initialHost?.user ?? '') + const [port, setPort] = useState(initialHost?.port ? String(initialHost.port) : '') + const [identityFile, setIdentityFile] = useState(initialHost?.identityFiles?.[0] ?? '') + const [proxyJump, setProxyJump] = useState(initialHost?.proxyJump ?? '') + const [localForward, setLocalForward] = useState(initialHost?.localForwards?.[0] ?? '') + const [busy, setBusy] = useState(false) + const [error, setError] = useState('') + const alive = useRef(true) + const guard = useRef(false) + const { push } = useNavigation() + + useEffect(() => () => { + alive.current = false + }, []) + + const configPath = sshConfigDisplayPath(windows) + const draft: SshHostDraft = { alias, hostName, user, port, identityFile, proxyJump, localForward } + + let livePreview = '' + if (alias.trim()) { + try { + livePreview = `\`\`\`sshconfig\n${validateAndFormatSshConfigBlock(draft)}\n\`\`\`` + } catch { + livePreview = '' + } + } + const submit = async () => { if (guard.current) return - guard.current = true; setBusy(true); setError('') + guard.current = true + setBusy(true) + setError('') try { - const local = portValue(port.trim()), remote = tunnel ? portValue(remotePort.trim()) : 1 - if (tunnel && !/^(?:[A-Za-z0-9_][A-Za-z0-9_.-]{0,252}|\[[A-Fa-f0-9:]{2,45}\])$/.test(remoteHost.trim())) throw new Error(t('invalidRemoteHost')) - if (await save({ port: local, remoteHost: remoteHost.trim(), remotePort: remote }, () => alive.current) && alive.current) pop() - } catch (e) { if (alive.current) setError(resolveErrorMessage(e, t('opFailed'))) } - finally { guard.current = false; if (alive.current) setBusy(false) } + const configBlock = validateAndFormatSshConfigBlock(draft) + await Clipboard.copy(configBlock) + if (!alive.current) return + await showToast( + Toast.Style.Success, + t('hostBlockCopiedTitle'), + t('hostBlockCopiedMessage', { path: configPath }) + ) + push( + + ) + } catch (e) { + if (alive.current) setError(resolveErrorMessage(e, t('opFailed'))) + } finally { + guard.current = false + if (alive.current) setBusy(false) + } } - return
}> - - {tunnel && } - {tunnel && } - - + + return ( +
+ + + } + > + + + + + + + + + + ) } diff --git a/extensions/ssh-proxy-helper/src/ssh-helpers.ts b/extensions/ssh-proxy-helper/src/ssh-helpers.ts new file mode 100644 index 00000000..0090be88 --- /dev/null +++ b/extensions/ssh-proxy-helper/src/ssh-helpers.ts @@ -0,0 +1,368 @@ +import { LocalStorage } from '@ztools/declarative-ui' +import { t } from './i18n.js' +import type { ProxyRow, ProxyTool, Snapshot, SshHost } from './mac-service.js' + +export interface SshHostDraft { + alias: string + hostName: string + user: string + port: string + identityFile: string + proxyJump: string + localForward: string +} + +export interface ParsedLocalForward { + raw: string + bindAddress?: string + localPort: number + remoteHost: string + remotePort: number +} + +export type TunnelMode = 'local' | 'dynamic' + +export interface TunnelPreset { + id: string + name: string + alias: string + mode: TunnelMode + localPort: number + remoteHost?: string + remotePort?: number +} + +const PINNED_KEY = 'ssh-proxy-helper:pinned-aliases:v1' +const PRESETS_KEY = 'ssh-proxy-helper:tunnel-presets:v1' +const LAST_PORT_KEY = 'ssh-proxy-helper:last-proxy-port:v1' +const DEFAULT_PROXY_PORT = 7890 + +const VALID_ALIAS_RE = /^[\p{L}\p{N}_][\p{L}\p{N}_.:-]{0,254}$/u +const VALID_REMOTE_HOST_RE = /^(?:[A-Za-z0-9_][A-Za-z0-9_.-]{0,252}|\[[A-Fa-f0-9:]{2,45}\])$/ +const CONTROL_CHAR_RE = /[\r\n\0\u0001-\u001f\u007f]/ +const WHITESPACE_RE = /\s/ + +export function escapeMarkdownLiteral(value: string): string { + return value.replace(/[\\`*_{}[\]()#+.!|><~:\-]/g, '\\$&') +} + +export function sshConfigDisplayPath(windows: boolean): string { + return windows ? '%USERPROFILE%\\.ssh\\config' : '~/.ssh/config' +} + +export function buildConnectCommand(alias: string, windows: boolean): string { + return windows ? `ssh ${alias}` : `ssh '${alias}'` +} + +export function buildLocalTunnelCommand( + alias: string, + localPort: number, + remoteHost: string, + remotePort: number, + windows: boolean +): string { + const target = windows ? alias : `'${alias}'` + return `ssh -N -o ExitOnForwardFailure=yes -L 127.0.0.1:${localPort}:${remoteHost}:${remotePort} ${target}` +} + +export function buildDynamicSocksCommand(alias: string, localPort: number, windows: boolean): string { + const target = windows ? alias : `'${alias}'` + return `ssh -N -D 127.0.0.1:${localPort} ${target}` +} + +export function parsePortNumber(raw: string): number { + const trimmed = raw.trim() + if (!/^\d+$/.test(trimmed)) throw new Error(t('invalidPort')) + const n = Number(trimmed) + if (!Number.isInteger(n) || n < 1 || n > 65535) throw new Error(t('invalidPort')) + return n +} + +export function validateRemoteHost(raw: string): string { + const trimmed = raw.trim() + if (!VALID_REMOTE_HOST_RE.test(trimmed)) throw new Error(t('invalidRemoteHost')) + return trimmed +} + +/** + * 解析 OpenSSH LocalForward 指令值,如: + * - `13306 127.0.0.1:3306` + * - `127.0.0.1:13306 db.internal:3306` + * - `[::1]:13306 [::1]:3306` + * 不合法或 Unix socket 形式返回 null(不抛错)。 + */ +export function parseLocalForward(raw: string): ParsedLocalForward | null { + const parts = raw.trim().split(/\s+/).filter(Boolean) + if (parts.length !== 2) return null + const [left, right] = parts + + let bindAddress: string | undefined + let localPortStr: string + const leftBracket = left.match(/^\[([A-Fa-f0-9:]+)\]:(\d+)$/) + if (leftBracket) { + bindAddress = `[${leftBracket[1]}]` + localPortStr = leftBracket[2] + } else if (left.includes(':')) { + const idx = left.lastIndexOf(':') + bindAddress = left.slice(0, idx) + localPortStr = left.slice(idx + 1) + } else { + localPortStr = left + } + + let remoteHost: string + let remotePortStr: string + const rightBracket = right.match(/^(\[[A-Fa-f0-9:]+\]):(\d+)$/) + if (rightBracket) { + remoteHost = rightBracket[1] + remotePortStr = rightBracket[2] + } else { + const idx = right.lastIndexOf(':') + if (idx <= 0) return null + remoteHost = right.slice(0, idx) + remotePortStr = right.slice(idx + 1) + } + + if (!/^\d+$/.test(localPortStr) || !/^\d+$/.test(remotePortStr)) return null + const localPort = Number(localPortStr) + const remotePort = Number(remotePortStr) + if (localPort < 1 || localPort > 65535 || remotePort < 1 || remotePort > 65535) return null + if (!VALID_REMOTE_HOST_RE.test(remoteHost)) return null + + return { raw: raw.trim(), bindAddress, localPort, remoteHost, remotePort } +} + +function quoteIfNeeded(value: string): string { + return WHITESPACE_RE.test(value) ? `"${value.replace(/"/g, '\\"')}"` : value +} + +export function validateAndFormatSshConfigBlock(draft: SshHostDraft): string { + const alias = draft.alias.trim() + const hostName = draft.hostName.trim() + const user = draft.user.trim() + const portRaw = draft.port.trim() + const identityFile = draft.identityFile.trim() + const proxyJump = draft.proxyJump.trim() + const localForward = draft.localForward.trim() + + if (!VALID_ALIAS_RE.test(alias)) throw new Error(t('invalidAlias')) + for (const field of [hostName, user, identityFile, proxyJump, localForward]) { + if (CONTROL_CHAR_RE.test(field)) throw new Error(t('invalidFieldLineBreak')) + } + if (hostName && WHITESPACE_RE.test(hostName)) throw new Error(t('invalidHostName')) + if (user && WHITESPACE_RE.test(user)) throw new Error(t('invalidFieldLineBreak')) + if (proxyJump && WHITESPACE_RE.test(proxyJump)) throw new Error(t('invalidFieldLineBreak')) + + let portNum: number | undefined + if (portRaw) portNum = parsePortNumber(portRaw) + + if (localForward && !parseLocalForward(localForward)) { + throw new Error(t('invalidLocalForward')) + } + + const lines: string[] = [`Host ${alias}`] + if (hostName) lines.push(` HostName ${hostName}`) + if (user) lines.push(` User ${user}`) + if (portNum !== undefined) lines.push(` Port ${portNum}`) + if (identityFile) lines.push(` IdentityFile ${quoteIfNeeded(identityFile)}`) + if (proxyJump) lines.push(` ProxyJump ${proxyJump}`) + if (localForward) lines.push(` LocalForward ${localForward}`) + return lines.join('\n') +} + +export function buildHostDetailMarkdown(host: SshHost, windows: boolean): string { + const cmd = buildConnectCommand(host.alias, windows) + const sections: string[] = [ + `### ${t('detailQuickConnect')}\n\n\`\`\`bash\n${cmd}\n\`\`\`` + ] + if (host.localForwards.length > 0) { + const items = host.localForwards.map(spec => { + const parsed = parseLocalForward(spec) + if (!parsed) return `- \`${spec}\`` + return `- \`${spec}\` → \`${buildLocalTunnelCommand(host.alias, parsed.localPort, parsed.remoteHost, parsed.remotePort, windows)}\`` + }) + sections.push(`### ${t('detailLocalForwards')}\n\n${items.join('\n')}`) + } + if (host.notices.length > 0) { + sections.push(`### ${t('detailNotices')}\n\n${host.notices.map(n => `- ${escapeMarkdownLiteral(n)}`).join('\n')}`) + } + sections.push(`### ${t('detailTransactionNoteTitle')}\n\n${t('detailHostReadonlyNote')}`) + return sections.join('\n\n') +} + +export function buildProxyDetailMarkdown(row: ProxyRow, toolLabel: string): string { + if (row.status === 'error') { + return `### ${toolLabel}\n\n${escapeMarkdownLiteral(row.error)}\n\n### ${t('detailTransactionNoteTitle')}\n\n${t('detailProxyTransactionNote')}` + } + const sections: string[] = [ + `### ${t('detailProxyConfigPath')}\n\n\`${row.location.replace(/`/g, '')}\`` + ] + if (row.values.length > 0) { + const lines = row.values.map(v => { + const flags = [ + v.hasCredentials ? t('detailProxyCredentialWarn') : '', + v.dynamic ? t('detailProxyDynamicWarn') : '' + ].filter(Boolean) + return `${v.key} = ${v.value}${flags.length ? ` # ${flags.join(', ')}` : ''}` + }) + sections.push(`### ${t('detailProxyCurrentValues')}\n\n\`\`\`ini\n${lines.join('\n')}\n\`\`\``) + } else { + sections.push(`### ${t('detailProxyCurrentValues')}\n\n${t('detailProxyNoValues')}`) + } + if (row.notices.length > 0) { + sections.push(`### ${t('detailNotices')}\n\n${row.notices.map(n => `- ${escapeMarkdownLiteral(n)}`).join('\n')}`) + } + sections.push(`### ${t('detailTransactionNoteTitle')}\n\n${t('detailProxyTransactionNote')}\n\n${t('detailProxySystemNote')}`) + return sections.join('\n\n') +} + +export function buildBatchProxyDetailMarkdown(proxies: ProxyRow[], lastPort: number): string { + const rows = proxies.map(p => { + const label = p.tool === 'git' ? 'Git' : 'NPM' + if (p.status === 'error') { + return `| ${label} | ${t('proxyErrorBadge')} | ${escapeMarkdownLiteral(p.error)} |` + } + const status = p.values.length > 0 ? t('proxyActiveBadge') : t('proxyUnsetBadge') + const val = p.values.length > 0 ? p.values.map(v => `${v.key}=${v.value}`).join(', ') : t('metaNone') + return `| ${label} | ${status} | \`${val.replace(/`/g, '')}\` |` + }) + return [ + `### ${t('detailBatchSummaryTitle')}`, + `| ${t('detailBatchColTool')} | ${t('detailBatchColStatus')} | ${t('detailBatchColValue')} |\n| --- | --- | --- |\n${rows.join('\n')}`, + `### ${t('detailTransactionNoteTitle')}\n\n${t('detailBatchNote')}\n\n${t('detailProxySystemNote')}\n\n\`http://127.0.0.1:${lastPort}\`` + ].join('\n\n') +} + +export function buildTerminalProxyDetailMarkdown(lastPort: number, windows: boolean): string { + const url = `http://127.0.0.1:${lastPort}` + const envBlock = windows + ? `HTTP_PROXY=${url}\nHTTPS_PROXY=${url}\nALL_PROXY=${url}` + : `http_proxy=${url}\nhttps_proxy=${url}\nall_proxy=${url}\nHTTP_PROXY=${url}\nHTTPS_PROXY=${url}\nALL_PROXY=${url}` + return [ + `### ${t('detailTerminalEnvTitle')}\n\n\`\`\`env\n${envBlock}\n\`\`\``, + `### ${t('detailTransactionNoteTitle')}\n\n${t('detailTerminalNote')}` + ].join('\n\n') +} + +export function buildTunnelDetailMarkdown( + alias: string, + mode: TunnelMode, + localPort: number, + remoteHost: string | undefined, + remotePort: number | undefined, + windows: boolean +): string { + const cmd = mode === 'local' && remoteHost && remotePort + ? buildLocalTunnelCommand(alias, localPort, remoteHost, remotePort, windows) + : buildDynamicSocksCommand(alias, localPort, windows) + const note = mode === 'local' ? t('detailTunnelLocalNote') : t('detailTunnelDynamicNote') + return [ + `### ${t('detailTunnelCmdTitle')}\n\n\`\`\`bash\n${cmd}\n\`\`\``, + `### ${t('descriptionLabel')}\n\n${note}` + ].join('\n\n') +} + +export function buildBackupDetailMarkdown(backup: Snapshot['backups'][number]): string { + return [ + `### ${t('detailBackupTitle')}\n\n- **${t('metaTool')}**: ${backup.tool.toUpperCase()}\n- **${t('metaCreatedAt')}**: \`${backup.createdAt}\`\n- **ID**: \`${backup.id}\``, + escapeMarkdownLiteral(backup.summary), + `### ${t('detailTransactionNoteTitle')}\n\n${t('detailBackupNote')}` + ].join('\n\n') +} + +export function isToolAtPort(row: ProxyRow, port: number): boolean { + if (row.status !== 'ready' || row.values.length === 0) return false + const expected = `http://127.0.0.1:${port}` + return row.values.every(v => v.value === expected) +} + +export async function loadPinnedAliases(): Promise { + try { + const raw = await LocalStorage.getItem(PINNED_KEY) + if (!Array.isArray(raw)) return [] + return raw.filter((item): item is string => typeof item === 'string' && VALID_ALIAS_RE.test(item)) + } catch (error) { + console.warn('loadPinnedAliases failed', error) + return [] + } +} + +export async function savePinnedAliases(aliases: string[]): Promise { + try { + await LocalStorage.setItem(PINNED_KEY, aliases) + } catch (error) { + console.warn('savePinnedAliases failed', error) + } +} + +export async function loadLastProxyPort(): Promise { + try { + const raw = await LocalStorage.getItem(LAST_PORT_KEY) + if (typeof raw === 'number' && Number.isInteger(raw) && raw >= 1 && raw <= 65535) return raw + return DEFAULT_PROXY_PORT + } catch (error) { + console.warn('loadLastProxyPort failed', error) + return DEFAULT_PROXY_PORT + } +} + +export async function saveLastProxyPort(port: number): Promise { + if (!Number.isInteger(port) || port < 1 || port > 65535) return + try { + await LocalStorage.setItem(LAST_PORT_KEY, port) + } catch (error) { + console.warn('saveLastProxyPort failed', error) + } +} + +function isValidPreset(value: unknown): value is TunnelPreset { + if (!value || typeof value !== 'object' || Array.isArray(value)) return false + const r = value as Record + if (typeof r.id !== 'string' || !r.id || typeof r.name !== 'string' || !r.name) return false + if (typeof r.alias !== 'string' || !VALID_ALIAS_RE.test(r.alias)) return false + if (r.mode !== 'local' && r.mode !== 'dynamic') return false + if (typeof r.localPort !== 'number' || !Number.isInteger(r.localPort) || r.localPort < 1 || r.localPort > 65535) return false + if (r.mode === 'local') { + if (typeof r.remoteHost !== 'string' || !VALID_REMOTE_HOST_RE.test(r.remoteHost)) return false + if (typeof r.remotePort !== 'number' || !Number.isInteger(r.remotePort) || r.remotePort < 1 || r.remotePort > 65535) return false + } + return true +} + +export async function loadTunnelPresets(): Promise { + try { + const raw = await LocalStorage.getItem(PRESETS_KEY) + if (!Array.isArray(raw)) return [] + return raw.filter(isValidPreset) + } catch (error) { + console.warn('loadTunnelPresets failed', error) + return [] + } +} + +export async function saveTunnelPresets(presets: TunnelPreset[]): Promise { + try { + await LocalStorage.setItem(PRESETS_KEY, presets) + } catch (error) { + console.warn('saveTunnelPresets failed', error) + } +} + +export function extractProxyPortFromSnapshot(snapshot: Snapshot | null): number | null { + if (!snapshot) return null + for (const row of snapshot.proxies) { + if (row.status !== 'ready') continue + for (const v of row.values) { + const m = v.value.match(/^https?:\/\/(?:127\.0\.0\.1|localhost):(\d{1,5})\/?$/i) + if (m) { + const port = Number(m[1]) + if (port >= 1 && port <= 65535) return port + } + } + } + return null +} + +export function getProxyToolLabel(tool: ProxyTool): string { + return tool === 'git' ? 'Git' : 'NPM' +} diff --git a/extensions/ssh-proxy-helper/tests/mac-ssh.test.mjs b/extensions/ssh-proxy-helper/tests/mac-ssh.test.mjs index 60eae86f..0396987e 100644 --- a/extensions/ssh-proxy-helper/tests/mac-ssh.test.mjs +++ b/extensions/ssh-proxy-helper/tests/mac-ssh.test.mjs @@ -4,112 +4,442 @@ import fs from 'node:fs' import { createHost, mount, mountPushed, tick } from '../../shared/test-harness.mjs' import Command, { commands } from '../dist/index.js' import { scanSsh, applyProxy, openSshTerminal, sourceMarkdown } from '../dist/mac-service.js' +import { + parseLocalForward, + validateAndFormatSshConfigBlock, + buildConnectCommand, + buildLocalTunnelCommand, + buildDynamicSocksCommand +} from '../dist/ssh-helpers.js' + const id = '11111111-1111-4111-8111-111111111111' -const hostEntry = { alias: 'fixture', hostName: '127.0.0.1', user: 'example', port: 2222, identityFiles: [], localForwards: [], previewComplete: true, notices: [] } +const id2 = '22222222-2222-4222-8222-222222222222' +const hostEntry = { + alias: 'fixture', + hostName: '10.20.30.40', + user: 'ops', + port: 2222, + identityFiles: ['~/.ssh/id_ed25519'], + proxyJump: 'bastion', + localForwards: ['127.0.0.1:13306 127.0.0.1:3306'], + previewComplete: true, + notices: [] +} + let host, views, state const calls = action => host.ipcCalls.filter(([m, p]) => m === 'ssh_proxy' && p.action === action) const defer = () => { let resolve; const promise = new Promise(r => { resolve = r }); return { promise, resolve } } + beforeEach(() => { - host = createHost(); views = [] - state = { success: true, sessionId: id, ssh: { status: 'ready', hosts: [], warnings: [] }, proxies: ['git', 'npm'].map(tool => ({ tool, status: 'ready', location: `/fixture/.${tool}config`, exists: true, values: [], notices: ['项目配置可能覆盖此文件'] })), backups: [], backupError: '' } + host = createHost() + views = [] + state = { + success: true, + sessionId: id, + ssh: { status: 'ready', hosts: [], warnings: [] }, + proxies: ['git', 'npm'].map(tool => ({ + tool, + status: 'ready', + location: `/fixture/.${tool}config`, + exists: true, + values: [], + notices: ['项目配置可能覆盖此文件'] + })), + backups: [], + backupError: '' + } host.ipc.system_get_platform = async () => ({ success: true, platform: 'macos' }) host.ipc.ssh_proxy = async p => { if (p.action === 'scan') return structuredClone(state) - if (p.action === 'prepare') return { success: true, planId: id, summary: '修改此文件中的代理', location: '/fixture/.npmrc', before: [], after: [], notices: ['项目配置可能覆盖此文件'] } - if (p.action === 'apply') { state.backups.push({ id, tool: 'npm', createdAt: '2026-10-26T00:00:00Z', summary: '修改 NPM 代理' }); return { success: true, verified: true, summary: '已核验文件', backupId: id, recoveryPath: '/fixture/.ztools-env-recovery-test/original' } } + if (p.action === 'prepare') { + const targetRow = state.proxies.find(row => row.tool === p.tool) + return { + success: true, + planId: id, + summary: `修改 ${String(p.tool).toUpperCase()} 代理`, + location: targetRow?.location || `/fixture/.${p.tool}rc`, + before: targetRow?.values || [], + after: p.change.kind === 'set' + ? [{ key: 'http.proxy', value: `http://127.0.0.1:${p.change.port}`, hasCredentials: false, dynamic: false }] + : [], + notices: ['项目配置可能覆盖此文件'] + } + } + if (p.action === 'apply') { + state.backups.push({ id, tool: 'npm', createdAt: '2026-10-26T00:00:00Z', summary: '修改 NPM 代理' }) + return { + success: true, + verified: true, + summary: '已核验文件', + backupId: id, + recoveryPath: '/fixture/.ztools-env-recovery-test/original' + } + } if (p.action === 'cancel') return { success: true, cancelRequested: true } return { success: true, opened: true, notice: '连接状态以终端为准' } } }) -afterEach(async () => { for (const view of views) view.unmount(); await tick() }) -async function open(command = Command) { const view = await mount(command, host); views.push(view); await tick(); return view } -async function form() { const view = await mountPushed(host); views.push(view); return view } -const refresh = view => view.tree().props.filterBar.actions[0].onAction() -test('Mac 入口使用现代接口,默认无 SSH 时首项仍可 Enter,不显示假代理开关', async () => { + +afterEach(async () => { + for (const view of views) view.unmount() + await tick() +}) + +async function open(command = Command) { + const view = await mount(command, host) + views.push(view) + await tick() + return view +} + +async function form() { + const view = await mountPushed(host) + views.push(view) + return view +} + +const findFilterAction = (view, actionId) => view.tree().props.filterBar.actions.find(a => a.id === actionId) +const refresh = async view => { + const act = findFilterAction(view, 'refresh') + assert.ok(act, 'missing refresh action in filterBar') + await act.onAction() + await tick() +} + +test('布局一开启右栏 Detail,默认无 SSH 时首项仍可 Enter,不显示假主机或假代理开关', async () => { const v = await open() - assert.equal(v.tree().props.isShowingDetail, false) + assert.equal(v.tree().props.isShowingDetail, true) assert.equal(v.items()[0].props.id, 'proxy:git') assert.equal(v.actions(v.items()[0])[0].props.title, '设置本机代理端口…') - assert.match(v.item('proxy:git').props.subtitle, /^\.gitconfig 未设置通用代理$/); assert.equal(v.item('proxy:git').props.title, 'Git 代理'); assert.equal(v.item('proxy:npm').props.title, 'NPM 代理'); assert.ok(!v.text().includes('加速中')) + assert.match(v.item('proxy:git').props.subtitle, /^\.gitconfig 未设置通用代理$/) + assert.equal(v.item('proxy:git').props.title, 'Git 代理') + assert.equal(v.item('proxy:npm').props.title, 'NPM 代理') + assert.ok(!v.text().includes('加速中')) assert.ok(!host.ipcCalls.some(([method]) => method === 'dllplugin_call')) - assert.deepEqual(v.tree().props.filterBar.actions.map(a => a.id), ['refresh']) + assert.deepEqual(v.tree().props.filterBar.actions.map(a => a.id), ['new-host', 'refresh']) + assert.ok(v.item('proxy:git').props.detail, '代理项必须包含右栏 Detail') }) -test('主机 Enter 调用连接;隧道入口打开表单,三个清单命令均映射', async () => { + +test('主机右栏 Detail 完整呈现 HostName/User/Port/IdentityFile/ProxyJump/LocalForward,支持连接与配置内转发', async () => { state.ssh.hosts = [hostEntry] - const v = await open(); await v.run(v.item('ssh:fixture'), '在终端连接') - assert.equal(calls('connect').length, 1); assert.equal(host.clipboard.text, '') + const v = await open() + const item = v.item('ssh:fixture') + const detailText = JSON.stringify(item.props.detail) + assert.match(detailText, /10\.20\.30\.40/) + assert.match(detailText, /ops/) + assert.match(detailText, /2222/) + assert.match(detailText, /id_ed25519/) + assert.match(detailText, /bastion/) + assert.match(detailText, /127\.0\.0\.1:13306 127\.0\.0\.1:3306/) + assert.match(detailText, /ssh 'fixture'/) + + await v.run(item, '在终端连接') + assert.equal(calls('connect').length, 1) + assert.equal(host.clipboard.text, '') assert.match(host.lastToast().message, /终端/) + + await v.run(item, '启动配置内转发 (127.0.0.1:13306 127.0.0.1:3306)') + assert.equal(calls('tunnel').length, 1) + assert.deepEqual(calls('tunnel')[0][1].tunnel, { localPort: 13306, remoteHost: '127.0.0.1', remotePort: 3306 }) + const tunnel = await open(commands['ssh-tunnel']) - assert.equal(tunnel.actions(tunnel.item('ssh:fixture'))[0].props.title, '建立本地端口转发…') + assert.equal(tunnel.actions(tunnel.item('ssh:fixture'))[0].props.title, '建立端口转发…') const manifest = JSON.parse(fs.readFileSync(new URL('../plugin.json', import.meta.url))) assert.deepEqual(Object.keys(commands).sort(), manifest.features.map(feature => feature.code).sort()) }) + +test('新建与编辑 SSH 主机表单严格校验并诚实复制配置块,不伪造写入 ~/.ssh/config', async () => { + state.ssh.hosts = [hostEntry] + const v = await open() + await findFilterAction(v, 'new-host').onAction() + await tick() + const f = await form() + + // 非法别名与非法端口拦截 + await f.fill('alias', '-bad alias') + await f.run(null, '校验并复制配置块') + assert.equal(host.clipboard.text, '') + assert.equal(host.pushed.length, 1) + + await f.fill('alias', 'prod-web') + await f.fill('hostName', '192.168.10.8') + await f.fill('user', 'deploy') + await f.fill('port', '2222') + await f.fill('identityFile', '~/.ssh/prod_ed25519') + await f.fill('proxyJump', 'fixture') + await f.fill('localForward', '127.0.0.1:15432 127.0.0.1:5432') + await f.run(null, '校验并复制配置块') + + assert.match(host.clipboard.text, /^Host prod-web/m) + assert.match(host.clipboard.text, /HostName 192\.168\.10\.8/) + assert.match(host.clipboard.text, /User deploy/) + assert.match(host.clipboard.text, /Port 2222/) + assert.match(host.clipboard.text, /IdentityFile ~\/\.ssh\/prod_ed25519/) + assert.match(host.clipboard.text, /ProxyJump fixture/) + assert.match(host.clipboard.text, /LocalForward 127\.0\.0\.1:15432 127\.0\.0\.1:5432/) + // 绝不伪造写入 IPC + assert.equal(calls('apply').length, 0) + // 推入预览 Detail + assert.equal(host.pushed.length, 2) +}) + +test('主机置顶持久化生效,置顶项排序至最前', async () => { + state.ssh.hosts = [ + { ...hostEntry, alias: 'alpha' }, + { ...hostEntry, alias: 'zebra' } + ] + const v = await open() + assert.equal(v.items()[0].props.id, 'ssh:alpha') + await v.run(v.item('ssh:zebra'), '置顶主机') + await tick() + assert.equal(v.items()[0].props.id, 'ssh:zebra') + await v.run(v.item('ssh:zebra'), '取消置顶') + await tick() + assert.equal(v.items()[0].props.id, 'ssh:alpha') +}) + test('平台、读取或单项错误均明确显示,不回退旧接口或冒充直连', async () => { state.ssh = { status: 'error', hosts: [], warnings: [], error: 'SSH 配置无法读取' } state.proxies[0] = { tool: 'git', status: 'error', error: 'Git 配置语法错误' } - const v = await open(); assert.match(v.text(), /SSH 配置无法读取/); assert.match(v.item('proxy:git').props.subtitle, /语法错误/) - host.ipc.ssh_proxy = async () => { throw new Error('宿主不可用') }; await refresh(v) - assert.match(v.text(), /宿主不可用/); assert.equal(v.items().length, 1) + const v = await open() + assert.match(v.text(), /SSH 配置无法读取/) + assert.match(v.item('proxy:git').props.subtitle, /语法错误/) + host.ipc.ssh_proxy = async () => { throw new Error('宿主不可用') } + await refresh(v) + assert.match(v.text(), /宿主不可用/) + assert.equal(v.items().length, 1) host.ipc.system_get_platform = async () => { throw new Error('平台读取失败') } - assert.match((await open()).text(), /平台读取失败/); assert.ok(!host.ipcCalls.some(([method]) => method === 'dllplugin_call')) + assert.match((await open()).text(), /平台读取失败/) + assert.ok(!host.ipcCalls.some(([method]) => method === 'dllplugin_call')) }) + test('代理表单校验端口,预览、确认、写入核验和恢复位置形成完整链路', async () => { - const v = await open(); await v.run(v.item('proxy:npm'), '设置本机代理端口…'); const f = await form() - for (const port of ['', '-1', '0', '65536', '7890x']) { await f.fill('localPort', port); await f.run(null, '继续'); assert.equal(calls('prepare').length, 0) } - await f.fill('localPort', '7890'); await f.run(null, '继续') + const v = await open() + await v.run(v.item('proxy:npm'), '设置本机代理端口…') + const f = await form() + for (const port of ['', '-1', '0', '65536', '7890x']) { + await f.fill('localPort', port) + await f.run(null, '继续') + assert.equal(calls('prepare').length, 0) + } + await f.fill('localPort', '7890') + await f.run(null, '继续') assert.deepEqual(calls('prepare')[0][1], { action: 'prepare', sessionId: id, tool: 'npm', change: { kind: 'set', port: 7890 } }) - assert.equal(calls('apply').length, 1); assert.equal(host.pushed.length, 0) - assert.match(host.confirms[0].message, /\/fixture\/\.npmrc/) + assert.equal(calls('apply').length, 1) + assert.equal(host.pushed.length, 0) + assert.match(host.confirms[0].message, /\/fixture\/\.npmconfig/) assert.match(host.lastToast().message, /recovery-test\/original/) - await v.dropdown('backups'); await v.run(v.item('retained-original'), '复制原文件位置') + await v.dropdown('backups') + await v.run(v.item('retained-original'), '复制原文件位置') assert.equal(host.clipboard.text, '/fixture/.ztools-env-recovery-test/original') await v.run(v.item(`backup:${id}`), '预览恢复原配置') assert.equal(calls('prepare')[1][1].change.kind, 'restore') }) + +test('一键批量开启 Git + NPM 代理严格逐项走 prepare -> confirm -> apply -> reload 事务', async () => { + let scanCount = 0 + host.ipc.ssh_proxy = async p => { + if (p.action === 'scan') { + scanCount += 1 + return structuredClone({ ...state, sessionId: scanCount === 1 ? id : id2 }) + } + if (p.action === 'prepare') { + return { + success: true, + planId: p.tool === 'git' ? id : id2, + summary: `设置 ${p.tool} 代理`, + location: `/fixture/.${p.tool}config`, + before: [], + after: [{ key: 'proxy', value: `http://127.0.0.1:${p.change.port}`, hasCredentials: false, dynamic: false }], + notices: [] + } + } + if (p.action === 'apply') { + const target = p.planId === id ? 'git' : 'npm' + const row = state.proxies.find(r => r.tool === target) + row.values = [{ key: 'proxy', value: 'http://127.0.0.1:7890', hasCredentials: false, dynamic: false }] + return { success: true, verified: true, summary: '已核验', backupId: id } + } + if (p.action === 'cancel') return { success: true, cancelRequested: true } + return { success: true, opened: true, notice: 'ok' } + } + const v = await open() + await v.run(v.item('proxy:batch'), '一键开启 Git + NPM (端口 7890)') + await tick() + assert.equal(calls('prepare').length, 2) + assert.equal(calls('prepare')[0][1].sessionId, id) + assert.equal(calls('prepare')[1][1].sessionId, id2) + assert.equal(calls('apply').length, 2) + assert.equal(host.confirms.length, 2) +}) + test('取消预览不写配置,失败回执不能提示成功或关闭表单', async () => { host.setConfirm(false) - const v = await open(); await v.run(v.item('proxy:git'), '设置本机代理端口…'); const f = await form() - await f.run(null, '继续'); assert.equal(calls('apply').length, 0); assert.equal(calls('cancel').length, 1); assert.equal(host.pushed.length, 1) + const v = await open() + await v.run(v.item('proxy:git'), '设置本机代理端口…') + const f = await form() + await f.run(null, '继续') + assert.equal(calls('apply').length, 0) + assert.equal(calls('cancel').length, 1) + assert.equal(host.pushed.length, 1) host.setConfirm(true) - const normal = host.ipc.ssh_proxy; host.ipc.ssh_proxy = p => p.action === 'apply' ? { success: true, verified: false } : normal(p) - await f.run(null, '继续'); assert.equal(host.pushed.length, 1); assert.equal(host.lastToast().style, 'FAILURE') + const normal = host.ipc.ssh_proxy + host.ipc.ssh_proxy = p => p.action === 'apply' ? { success: true, verified: false } : normal(p) + await f.run(null, '继续') + assert.equal(host.pushed.length, 1) + assert.equal(host.lastToast().style, 'FAILURE') }) -test('隧道表单提交真实参数,非法远端地址不发请求;终端代理只打开新窗口', async () => { + +test('隧道表单支持本地转发与动态 SOCKS5 命令复制及预设保存;终端代理只打开新窗口', async () => { state.ssh.hosts = [hostEntry] - const v = await open(); await v.run(v.item('ssh:fixture'), '建立本地端口转发…'); const f = await form() - await f.fill('localPort', '15432'); await f.fill('remotePort', '5432'); await f.fill('remoteHost', 'db;touch bad') - await f.run(null, '在终端建立隧道'); assert.equal(calls('tunnel').length, 0) - await f.fill('remoteHost', 'db.internal'); await f.run(null, '在终端建立隧道') + const v = await open() + await v.run(v.item('ssh:fixture'), '建立端口转发…') + const f = await form() + await f.fill('localPort', '15432') + await f.fill('remotePort', '5432') + await f.fill('remoteHost', 'db;touch bad') + await f.run(null, '在终端建立隧道') + assert.equal(calls('tunnel').length, 0) + + await f.fill('remoteHost', 'db.internal') + await f.fill('saveAsPreset', true) + await f.fill('presetName', '测试库转发') + await f.run(null, '在终端建立隧道') assert.deepEqual(calls('tunnel')[0][1].tunnel, { localPort: 15432, remoteHost: 'db.internal', remotePort: 5432 }) - await v.run(v.item('terminal-proxy'), '打开带代理的新终端…'); const proxy = await form(); await proxy.fill('localPort', '10809'); await proxy.run(null, '继续') - assert.deepEqual(calls('terminal-proxy')[0][1], { action: 'terminal-proxy', port: 10809 }); assert.equal(calls('apply').length, 0) + + // 切换到隧道预设视图可看到刚保存的预设和配置内转发 + await v.dropdown('tunnels') + await tick() + assert.match(v.text(), /测试库转发/) + assert.match(v.text(), /127\.0\.0\.1:13306 127\.0\.0\.1:3306/) + + // 切回代理测试终端代理 + await v.dropdown('proxy') + await tick() + await v.run(v.item('terminal-proxy'), '打开带代理的新终端…') + const proxy = await form() + await proxy.fill('localPort', '10809') + await proxy.run(null, '继续') + assert.deepEqual(calls('terminal-proxy')[0][1], { action: 'terminal-proxy', port: 10809 }) + assert.equal(calls('apply').length, 0) }) + test('表单关闭取消在途预览,重复提交和迟到结果不能执行写入', async () => { - const v = await open(); await v.run(v.item('proxy:git'), '设置本机代理端口…'); const f = await form(), pending = defer(), normal = host.ipc.ssh_proxy + const v = await open() + await v.run(v.item('proxy:git'), '设置本机代理端口…') + const f = await form() + const pending = defer() + const normal = host.ipc.ssh_proxy host.ipc.ssh_proxy = p => p.action === 'prepare' ? pending.promise : normal(p) - const submit = f.actions(null)[0].props.onSubmit, first = submit(); await submit(); assert.equal(calls('prepare').length, 1) - f.unmount(); await tick(); pending.resolve({ success: true, planId: id, summary: '旧结果', location: '/fixture/.gitconfig', before: [], after: [], notices: [] }); await first - assert.equal(calls('apply').length, 0); assert.ok(calls('cancel').length >= 1) + const submit = f.actions(null)[0].props.onSubmit + const first = submit() + await submit() + assert.equal(calls('prepare').length, 1) + f.unmount() + await tick() + pending.resolve({ success: true, planId: id, summary: '旧结果', location: '/fixture/.gitconfig', before: [], after: [], notices: [] }) + await first + assert.equal(calls('apply').length, 0) + assert.ok(calls('cancel').length >= 1) }) + test('畸形响应、重复来源及未打开回执拒绝成功;配置路径按 Markdown 字面量显示', async () => { const valid = structuredClone(state) - for (const bad of [{ ...valid, sessionId: '' }, { ...valid, proxies: [valid.proxies[0], valid.proxies[0]] }, { ...valid, ssh: { status: 'error', hosts: [], warnings: [] } }]) { - host.ipc.ssh_proxy = async () => bad; await assert.rejects(scanSsh()) + for (const bad of [ + { ...valid, sessionId: '' }, + { ...valid, proxies: [valid.proxies[0], valid.proxies[0]] }, + { ...valid, ssh: { status: 'error', hosts: [], warnings: [] } } + ]) { + host.ipc.ssh_proxy = async () => bad + await assert.rejects(scanSsh()) } - host.ipc.ssh_proxy = async () => ({ success: true, opened: false, notice: 'no' }); await assert.rejects(openSshTerminal({ action: 'connect' })) - host.ipc.ssh_proxy = async () => ({ success: true, verified: true, backupId: id }); await assert.rejects(applyProxy(id)) + host.ipc.ssh_proxy = async () => ({ success: true, opened: false, notice: 'no' }) + await assert.rejects(openSshTerminal({ action: 'connect' })) + host.ipc.ssh_proxy = async () => ({ success: true, verified: true, backupId: id }) + await assert.rejects(applyProxy(id)) const text = sourceMarkdown({ ...valid.proxies[0], location: '/fixture/![x](https://example.invalid/leak)' }) - assert.ok(text.includes('\\!\\[x\\]\\(https\\:')); assert.ok(!text.includes('![x]')) + assert.ok(text.includes('\\!\\[x\\]\\(https\\:')) + assert.ok(!text.includes('![x]')) }) + test('取消请求失败时如实提示而不是抛出未处理异常;读取失败的代理行可直接重新读取', async () => { state.proxies[0] = { tool: 'git', status: 'error', error: '未找到 git 可执行文件' } const v = await open() assert.equal(v.actions(v.item('proxy:git'))[0].props.title, '重新读取') const pending = defer() - host.ipc.ssh_proxy = async p => { if (p.action === 'scan') return pending.promise; if (p.action === 'cancel') throw new Error('没有正在进行的操作'); return { success: true } } - const reading = v.run(v.item('proxy:git'), '重新读取'); await tick() - assert.equal(v.tree().props.filterBar.actions[0].title, '取消操作') - await v.tree().props.filterBar.actions[0].onAction(); await tick() + host.ipc.ssh_proxy = async p => { + if (p.action === 'scan') return pending.promise + if (p.action === 'cancel') throw new Error('没有正在进行的操作') + return { success: true } + } + const reading = v.run(v.item('proxy:git'), '重新读取') + await tick() + assert.equal(findFilterAction(v, 'refresh').title, '取消操作') + await findFilterAction(v, 'refresh').onAction() + await tick() assert.match(host.lastToast().title, /取消未确认/) - pending.resolve(structuredClone(state)); await reading; await tick() + pending.resolve(structuredClone(state)) + await reading + await tick() +}) + +test('纯函数辅助逻辑:LocalForward 解析、SSH 配置块防注入与双平台命令生成', () => { + assert.deepEqual(parseLocalForward('13306 127.0.0.1:3306'), { + raw: '13306 127.0.0.1:3306', + bindAddress: undefined, + localPort: 13306, + remoteHost: '127.0.0.1', + remotePort: 3306 + }) + assert.deepEqual(parseLocalForward('[::1]:15432 [::1]:5432'), { + raw: '[::1]:15432 [::1]:5432', + bindAddress: '[::1]', + localPort: 15432, + remoteHost: '[::1]', + remotePort: 5432 + }) + assert.equal(parseLocalForward('/var/run/docker.sock /var/run/docker.sock'), null) + assert.equal(parseLocalForward('99999 127.0.0.1:80'), null) + + assert.throws(() => validateAndFormatSshConfigBlock({ + alias: 'prod', + hostName: '10.0.0.1\nProxyCommand evil', + user: '', + port: '', + identityFile: '', + proxyJump: '', + localForward: '' + })) + + assert.equal(buildConnectCommand('prod', true), 'ssh prod') + assert.equal(buildConnectCommand('prod', false), "ssh 'prod'") + assert.equal(buildLocalTunnelCommand('prod', 13306, '127.0.0.1', 3306, true), 'ssh -N -o ExitOnForwardFailure=yes -L 127.0.0.1:13306:127.0.0.1:3306 prod') + assert.equal(buildDynamicSocksCommand('prod', 1080, false), "ssh -N -D 127.0.0.1:1080 'prod'") +}) + +test('中英 i18n 词典键集合与占位符 100% 一致,无空值且无彩色 Emoji', () => { + const src = fs.readFileSync(new URL('../src/i18n.ts', import.meta.url), 'utf8') + const zhBlock = src.slice(src.indexOf('"zh-CN": {'), src.indexOf('"en-US": {')) + const enBlock = src.slice(src.indexOf('"en-US": {'), src.indexOf('const rawT')) + const extract = block => { + const map = new Map() + for (const m of block.matchAll(/^\s*([A-Za-z0-9_]+):\s*"((?:\\.|[^"\\])*)"/gm)) { + map.set(m[1], m[2]) + } + return map + } + const zh = extract(zhBlock) + const en = extract(enBlock) + assert.deepEqual([...zh.keys()].sort(), [...en.keys()].sort()) + const emojiRe = /\p{Extended_Pictographic}/u + for (const [k, zv] of zh) { + const ev = en.get(k) + assert.ok(zv.length > 0, `zh-CN.${k} is empty`) + assert.ok(ev && ev.length > 0, `en-US.${k} is empty`) + assert.ok(!emojiRe.test(zv), `zh-CN.${k} contains emoji`) + assert.ok(!emojiRe.test(ev), `en-US.${k} contains emoji`) + const zhVars = [...new Set([...zv.matchAll(/\{([A-Za-z0-9_]+)\}/g)].map(m => m[1]))].sort() + const enVars = [...new Set([...ev.matchAll(/\{([A-Za-z0-9_]+)\}/g)].map(m => m[1]))].sort() + assert.deepEqual(zhVars, enVars, `placeholder mismatch on key ${k}`) + } }) diff --git a/extensions/ssh-proxy-helper/tests/windows-ssh.test.mjs b/extensions/ssh-proxy-helper/tests/windows-ssh.test.mjs deleted file mode 100644 index 54465d3d..00000000 --- a/extensions/ssh-proxy-helper/tests/windows-ssh.test.mjs +++ /dev/null @@ -1,58 +0,0 @@ -import test, { beforeEach, afterEach } from 'node:test' -import assert from 'node:assert/strict' -import { createHost, mount, mountPushed, tick } from '../../shared/test-harness.mjs' -import Command, { commands } from '../dist/index.js' -import { scanSsh } from '../dist/mac-service.js' -const id = '22222222-2222-4222-8222-222222222222' -const hostEntry = { alias: 'fixture', hostName: '10.0.0.8', user: 'example', port: 22, identityFiles: ['C:\\Users\\fixture\\.ssh\\id_ed25519'], localForwards: [], previewComplete: true, notices: [] } -let host, views, state -const calls = action => host.ipcCalls.filter(([m, p]) => m === 'ssh_proxy' && p.action === action) -const legacy = () => host.ipcCalls.some(([method]) => method === 'dllplugin_call') -beforeEach(() => { - host = createHost(); views = [] - state = { success: true, sessionId: id, ssh: { status: 'ready', hosts: [hostEntry], warnings: [] }, proxies: [ - { tool: 'git', status: 'ready', location: 'C:\\Users\\fixture\\.gitconfig', exists: true, values: [{ key: 'http.proxy', value: 'http://127.0.0.1:7890', hasCredentials: false, dynamic: false }], notices: [] }, - { tool: 'npm', status: 'ready', location: 'C:\\Users\\fixture\\.npmrc', exists: false, values: [], notices: [] }], backups: [], backupError: '' } - host.ipc.system_get_platform = async () => ({ success: true, platform: 'windows' }) - host.ipc.dllplugin_call = async () => ({ ok: true, success: true, isEnabled: true }) - host.ipc.ssh_proxy = async p => { - if (p.action === 'scan') return structuredClone(state) - if (p.action === 'prepare') return { success: true, planId: id, summary: '清除 GIT 此文件中的通用代理', location: 'C:\\Users\\fixture\\.gitconfig', before: state.proxies[0].values, after: [], notices: [] } - if (p.action === 'apply') { state.proxies[0].values = []; return { success: true, verified: true, summary: '已核验', backupId: id, recoveryPath: 'C:\\Users\\fixture\\.ztools-env-recovery-x\\original' } } - if (p.action === 'cancel') return { success: true, cancelRequested: true } - return { success: true, opened: true, notice: '已请求打开新的控制台窗口' } - } -}) -afterEach(async () => { for (const view of views) view.unmount(); await tick() }) -async function open(command = Command) { const view = await mount(command, host); views.push(view); await tick(); return view } -test('Windows 入口走 ssh_proxy 新接口,初始状态取自真实读取结果,不调用旧 dllplugin_call', async () => { - const v = await open() - assert.equal(calls('scan').length, 1); assert.equal(legacy(), false) - assert.match(v.item('proxy:git').props.subtitle, /http\.proxy: http:\/\/127\.0\.0\.1:7890/) - assert.equal(v.item('proxy:npm').props.subtitle, '.npmrc 尚未创建,未设置通用代理') - assert.ok(!v.text().includes('加速中')); assert.ok(!/已启用/.test(v.text())) - await v.run(v.item('ssh:fixture'), '复制连接命令'); assert.equal(host.clipboard.text, 'ssh fixture') - for (const code of Object.keys(commands)) { await open(commands[code]); assert.equal(legacy(), false) } -}) -test('Windows 清除代理先预览再写入并刷新;连接与代理终端只发新接口请求', async () => { - const v = await open() - await v.run(v.item('proxy:git'), '清除此文件中的通用代理') - assert.deepEqual(calls('prepare')[0][1].change, { kind: 'clear' }); assert.equal(calls('apply').length, 1) - assert.match(host.confirms[0].message, /C:\\Users\\fixture\\\.gitconfig/); assert.match(host.confirms[0].message, /修改后:\n\.gitconfig 未设置通用代理/) - assert.equal(v.item('proxy:git').props.subtitle, '.gitconfig 未设置通用代理') - await v.run(v.item('ssh:fixture'), '在终端连接'); assert.equal(calls('connect')[0][1].alias, 'fixture') - await v.run(v.item('terminal-proxy'), '打开带代理的新终端…'); const f = await mountPushed(host); views.push(f) - await f.fill('localPort', '10809'); await f.run(null, '继续') - assert.deepEqual(calls('terminal-proxy')[0][1], { action: 'terminal-proxy', port: 10809 }); assert.equal(legacy(), false) -}) -test('Windows 写入失败、读取失败与相对路径均如实报错,不回退旧接口', async () => { - const normal = host.ipc.ssh_proxy - host.ipc.ssh_proxy = p => p.action === 'apply' ? Promise.reject(new Error('无法写入并验证原配置备份,未修改配置')) : normal(p) - const v = await open(); await v.run(v.item('proxy:git'), '清除此文件中的通用代理') - assert.equal(host.lastToast().style, 'FAILURE'); assert.match(host.lastToast().message, /备份/) - host.ipc.ssh_proxy = async () => ({ ...structuredClone(state), proxies: [{ ...state.proxies[0], location: 'relative\\.gitconfig' }, state.proxies[1]] }) - await assert.rejects(scanSsh(), /不完整/) - host.ipc.ssh_proxy = async () => { throw new Error('未找到 Git(git.exe)') } - await v.tree().props.filterBar.actions[0].onAction() - assert.match(v.text(), /git\.exe/); assert.equal(legacy(), false) -}) diff --git a/extensions/ssl-domain-check/plugin.json b/extensions/ssl-domain-check/plugin.json index 1b857343..54440e75 100644 --- a/extensions/ssl-domain-check/plugin.json +++ b/extensions/ssl-domain-check/plugin.json @@ -1,7 +1,7 @@ { "id": "ssl-domain-check", "name": "域名与SSL诊断", - "version": "1.0.7", + "version": "1.0.8", "description": "查询域名真实 TLS 证书、信任与名称匹配状态、有效期和证书链,并查看 DNS 解析记录", "author": "ZTools Team", "category": [ diff --git a/extensions/ssl-domain-check/src/doh-service.ts b/extensions/ssl-domain-check/src/doh-service.ts index 58da436c..2258c15b 100644 --- a/extensions/ssl-domain-check/src/doh-service.ts +++ b/extensions/ssl-domain-check/src/doh-service.ts @@ -1,50 +1,230 @@ -import type { DnsRecordEntry, DnsRecordType } from './types.js' +import type { DnsQueryError, DnsRecordEntry, DnsRecordType, DohProviderId, DohResolveResult } from './types.js' import { normalizeDomainInput } from './domain.js' +import { DEFAULT_DOH_PROVIDER, isDohProviderId } from './storage.js' import { t } from './i18n.js' -const codes: Record = { A: 1, AAAA: 28, CNAME: 5, MX: 15, TXT: 16 } -const object = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v) + +export const ALL_DNS_RECORD_TYPES: readonly DnsRecordType[] = ['A', 'AAAA', 'CNAME', 'MX', 'TXT', 'NS', 'SOA', 'CAA'] + +export interface DohProviderConfig { + id: DohProviderId + endpoint: string + host: string +} + +export const DOH_PROVIDERS: Readonly> = { + alidns: { + id: 'alidns', + endpoint: 'https://dns.alidns.com/resolve', + host: 'dns.alidns.com' + }, + dnspod: { + id: 'dnspod', + endpoint: 'https://doh.pub/resolve', + host: 'doh.pub' + }, + cloudflare: { + id: 'cloudflare', + endpoint: 'https://cloudflare-dns.com/dns-query', + host: 'cloudflare-dns.com' + } +} + +export const DOH_PROVIDER_LIST: readonly DohProviderConfig[] = [ + DOH_PROVIDERS.alidns, + DOH_PROVIDERS.dnspod, + DOH_PROVIDERS.cloudflare +] + +export function getDohProviderLabel(provider: DohProviderId, short = false): string { + if (provider === 'dnspod') return short ? t('providerShortDnspod') : t('providerDnspod') + if (provider === 'cloudflare') return short ? t('providerShortCloudflare') : t('providerCloudflare') + return short ? t('providerShortAlidns') : t('providerAlidns') +} + +const DNS_TYPE_CODES: Readonly> = { + A: 1, + NS: 2, + CNAME: 5, + SOA: 6, + MX: 15, + TXT: 16, + AAAA: 28, + CAA: 257 +} + +const isPlainObject = (v: unknown): v is Record => Boolean(v) && typeof v === 'object' && !Array.isArray(v) + async function boundedJson(response: Response): Promise { if (!response.body) throw new Error(t('errDnsEmptyBody')) - const reader = response.body.getReader(), parts: Uint8Array[] = []; let size = 0 + const reader = response.body.getReader() + const parts: Uint8Array[] = [] + let size = 0 try { for (;;) { - const next = await reader.read(); if (next.done) break - size += next.value.length; if (size > 256 * 1024) throw new Error(t('errDnsTooLarge')) + const next = await reader.read() + if (next.done) break + size += next.value.length + if (size > 256 * 1024) throw new Error(t('errDnsTooLarge')) parts.push(next.value) } - } finally { reader.releaseLock() } - const bytes = new Uint8Array(size); let offset = 0 - for (const part of parts) { bytes.set(part, offset); offset += part.length } - try { return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)) } - catch { throw new Error(t('errDnsInvalidJson')) } + } finally { + reader.releaseLock() + } + const bytes = new Uint8Array(size) + let offset = 0 + for (const part of parts) { + bytes.set(part, offset) + offset += part.length + } + try { + return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)) + } catch { + throw new Error(t('errDnsInvalidJson')) + } +} + +async function querySingleType( + domain: string, + type: DnsRecordType, + endpoint: string, + fetchFn: typeof fetch, + signal: AbortSignal +): Promise { + signal.throwIfAborted() + const response = await fetchFn(`${endpoint}?name=${encodeURIComponent(domain)}&type=${type}`, { + headers: { accept: 'application/dns-json' }, + credentials: 'omit', + redirect: 'error', + signal + }) + if (!response.ok) throw new Error(t('errDnsHttpFailed', { status: response.status })) + const payload = await boundedJson(response) + if (!isPlainObject(payload) || !Number.isInteger(payload.Status)) throw new Error(t('errDnsMissingStatus')) + if (payload.Status === 3) throw new Error(t('errDnsNxdomain')) + if (payload.Status !== 0) throw new Error(t('errDnsServerError', { status: String(payload.Status) })) + if (payload.TC === true) throw new Error(t('errDnsTruncated')) + if (payload.Answer === undefined) return [] + if (!Array.isArray(payload.Answer) || payload.Answer.length > 128) throw new Error(t('errDnsTooManyRecords')) + + const expectedCode = DNS_TYPE_CODES[type] + const records: DnsRecordEntry[] = [] + for (const answer of payload.Answer) { + if ( + !isPlainObject(answer) || + typeof answer.name !== 'string' || + answer.name.length > 253 || + typeof answer.data !== 'string' || + answer.data.length > 8192 || + !Number.isInteger(answer.type) || + !Number.isInteger(answer.TTL) || + Number(answer.TTL) < 0 || + Number(answer.TTL) > 4294967295 + ) { + throw new Error(t('errDnsIncompleteRecord')) + } + if (answer.type === expectedCode) { + records.push({ + name: answer.name.replace(/\.$/, ''), + type, + ttl: Number(answer.TTL), + data: answer.data + }) + } + } + return records +} + +export interface DohQueryOptions { + signal?: AbortSignal + fetchImpl?: typeof fetch + timeoutMs?: number + provider?: DohProviderId } -export async function resolveDomainDoh(rawDomain: string, types: DnsRecordType[] = ['A', 'AAAA', 'CNAME', 'MX', 'TXT'], options: { signal?: AbortSignal; fetchImpl?: typeof fetch; timeoutMs?: number } = {}): Promise { - const domain = normalizeDomainInput(rawDomain), timeoutMs = options.timeoutMs ?? 8000 - if (!Array.isArray(types) || types.length < 1 || types.length > 5 || new Set(types).size !== types.length || types.some(type => !Object.hasOwn(codes, type)) || !Number.isInteger(timeoutMs) || timeoutMs < 1000 || timeoutMs > 15000) throw new Error(t('errDnsInvalidParams')) + +/** 并发执行多类型 DoH 查询,返回完整记录、部分错误列表及耗时。 */ +export async function resolveDomainDohDetailed( + rawDomain: string, + types: readonly DnsRecordType[] = ALL_DNS_RECORD_TYPES, + options: DohQueryOptions = {} +): Promise { + const domain = normalizeDomainInput(rawDomain) + const timeoutMs = options.timeoutMs ?? 8000 + const provider = options.provider ?? DEFAULT_DOH_PROVIDER + if ( + !Array.isArray(types) || + types.length < 1 || + types.length > ALL_DNS_RECORD_TYPES.length || + new Set(types).size !== types.length || + types.some(type => !Object.hasOwn(DNS_TYPE_CODES, type)) || + !isDohProviderId(provider) || + !Number.isInteger(timeoutMs) || + timeoutMs < 1000 || + timeoutMs > 15000 + ) { + throw new Error(t('errDnsInvalidParams')) + } options.signal?.throwIfAborted() - const controller = new AbortController(), abort = () => controller.abort(), timer = setTimeout(abort, timeoutMs) + + const providerConfig = DOH_PROVIDERS[provider] + const controller = new AbortController() + const abort = () => controller.abort() + const timer = setTimeout(abort, timeoutMs) options.signal?.addEventListener('abort', abort, { once: true }) + const fetchFn = options.fetchImpl ?? globalThis.fetch + const startMs = Date.now() + try { - const results: DnsRecordEntry[] = [], fetchFn = options.fetchImpl ?? globalThis.fetch - for (const type of types) { - controller.signal.throwIfAborted() - const response = await fetchFn(`https://cloudflare-dns.com/dns-query?name=${encodeURIComponent(domain)}&type=${type}`, { headers: { accept: 'application/dns-json' }, credentials: 'omit', redirect: 'error', signal: controller.signal }) - if (!response.ok) throw new Error(t('errDnsHttpFailed', { status: response.status })) - const payload = await boundedJson(response) - if (!object(payload) || !Number.isInteger(payload.Status)) throw new Error(t('errDnsMissingStatus')) - if (payload.Status === 3) throw new Error(t('errDnsNxdomain')) - if (payload.Status !== 0) throw new Error(t('errDnsServerError', { status: String(payload.Status) })) - if (payload.TC === true) throw new Error(t('errDnsTruncated')) - if (payload.Answer === undefined) continue - if (!Array.isArray(payload.Answer) || payload.Answer.length > 128) throw new Error(t('errDnsTooManyRecords')) - for (const answer of payload.Answer) { - if (!object(answer) || typeof answer.name !== 'string' || answer.name.length > 253 || typeof answer.data !== 'string' || answer.data.length > 8192 || !Number.isInteger(answer.type) || !Number.isInteger(answer.TTL) || Number(answer.TTL) < 0 || Number(answer.TTL) > 4294967295) throw new Error(t('errDnsIncompleteRecord')) - if (answer.type === codes[type]) results.push({ name: answer.name.replace(/\.$/, ''), type, ttl: Number(answer.TTL), data: answer.data }) + const settled = await Promise.allSettled( + types.map(type => querySingleType(domain, type, providerConfig.endpoint, fetchFn, controller.signal)) + ) + if (controller.signal.aborted) { + throw new Error(options.signal?.aborted ? t('errDnsCancelled') : t('errDnsTimeout')) + } + + const records: DnsRecordEntry[] = [] + const errors: DnsQueryError[] = [] + for (let i = 0; i < settled.length; i++) { + const outcome = settled[i] + const type = types[i] + if (outcome.status === 'fulfilled') { + records.push(...outcome.value) + } else { + const message = outcome.reason instanceof Error ? outcome.reason.message : String(outcome.reason) + errors.push({ type, message }) } } - controller.signal.throwIfAborted(); return results + + if (errors.length === types.length) { + const nxdomainMsg = t('errDnsNxdomain') + const nx = errors.find(item => item.message === nxdomainMsg) + throw new Error(nx ? nx.message : errors[0].message) + } + + return { + domain, + provider, + records, + errors, + durationMs: Math.max(0, Date.now() - startMs) + } } catch (error) { - if (controller.signal.aborted) throw new Error(options.signal?.aborted ? t('errDnsCancelled') : t('errDnsTimeout')) + if (controller.signal.aborted) { + throw new Error(options.signal?.aborted ? t('errDnsCancelled') : t('errDnsTimeout')) + } throw error - } finally { clearTimeout(timer); options.signal?.removeEventListener('abort', abort); controller.abort() } + } finally { + clearTimeout(timer) + options.signal?.removeEventListener('abort', abort) + controller.abort() + } +} + +/** 兼容接口:并发执行 DoH 查询并直接返回记录数组。 */ +export async function resolveDomainDoh( + rawDomain: string, + types: readonly DnsRecordType[] = ALL_DNS_RECORD_TYPES, + options: DohQueryOptions = {} +): Promise { + const result = await resolveDomainDohDetailed(rawDomain, types, options) + return result.records } diff --git a/extensions/ssl-domain-check/src/domain.ts b/extensions/ssl-domain-check/src/domain.ts index dda918fb..0403880c 100644 --- a/extensions/ssl-domain-check/src/domain.ts +++ b/extensions/ssl-domain-check/src/domain.ts @@ -1,18 +1,68 @@ +import type { TargetAddress } from './types.js' import { t } from './i18n.js' -export function normalizeDomainInput(raw: string): string { - if (typeof raw !== 'string' || !raw.trim() || raw.length > 2048) throw new Error(t('errInvalidDomain')) +const DOMAIN_REGEX = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$/ + +/** 解析用户输入的目标地址,支持 domain、domain:port 以及 http/https URL(端口 1–65535,默认 443)。 */ +export function parseTargetInput(raw: string): TargetAddress { + if (typeof raw !== 'string' || !raw.trim() || raw.length > 2048) { + throw new Error(t('errInvalidDomain')) + } const value = raw.trim() - if (/\s/.test(value)) throw new Error(t('errDomainWhitespace')) + if (/\s/.test(value)) { + throw new Error(t('errDomainWhitespace')) + } + const hasScheme = value.includes('://') + const candidate = hasScheme ? value : `https://${value}` + // 检测显式非法端口(例如 domain:0、domain:99999、domain:abc),避免被 URL 构造器忽略或产生晦涩错误 + const authorityPart = candidate.slice(candidate.indexOf('://') + 3).split(/[/?#]/, 1)[0] ?? '' + if (authorityPart.includes('@')) { + throw new Error(t('errHttpHttpsOnly')) + } + const colonIndex = authorityPart.lastIndexOf(':') + let explicitPort: number | undefined + if (colonIndex !== -1 && !authorityPart.includes('[')) { + const portText = authorityPart.slice(colonIndex + 1) + if (!/^\d+$/.test(portText)) { + throw new Error(t('errInvalidPort')) + } + const parsed = Number(portText) + if (!Number.isInteger(parsed) || parsed < 1 || parsed > 65535) { + throw new Error(t('errInvalidPort')) + } + explicitPort = parsed + } + let url: URL - try { url = new URL(value.includes('://') ? value : `https://${value}`) } - catch { throw new Error(t('errUnrecognizedDomain')) } - if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) throw new Error(t('errHttpHttpsOnly')) - if (url.port && url.port !== '443') throw new Error(t('errPort443Only')) + try { + url = new URL(candidate) + } catch { + throw new Error(t('errUnrecognizedDomain')) + } + if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) { + throw new Error(t('errHttpHttpsOnly')) + } const hostname = url.hostname.toLowerCase().replace(/\.$/, '') - if (hostname.length > 253 || !/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$/.test(hostname)) throw new Error(t('errFullDomainRequired')) - return hostname + if (hostname.length > 253 || !DOMAIN_REGEX.test(hostname)) { + throw new Error(t('errFullDomainRequired')) + } + const port = explicitPort ?? (url.port ? Number(url.port) : 443) + if (!Number.isInteger(port) || port < 1 || port > 65535) { + throw new Error(t('errInvalidPort')) + } + return { domain: hostname, port } } + +/** 仅提取归一化后的域名(兼容已有导出)。 */ +export function normalizeDomainInput(raw: string): string { + return parseTargetInput(raw).domain +} + +/** 格式化展示目标:443 端口省略后缀,非标准端口显式展示 domain:port。 */ +export function formatTarget(domain: string, port = 443): string { + return port === 443 ? domain : `${domain}:${port}` +} + /** 用长于内容的围栏保留原文,避免对端字段生成图片或链接。 */ export function markdownLiteral(value: string): string { const longest = Math.max(0, ...(value.match(/`+/g) ?? []).map(run => run.length)) diff --git a/extensions/ssl-domain-check/src/i18n.ts b/extensions/ssl-domain-check/src/i18n.ts index 81174d97..61727d8e 100644 --- a/extensions/ssl-domain-check/src/i18n.ts +++ b/extensions/ssl-domain-check/src/i18n.ts @@ -1,168 +1,273 @@ -import { createTranslator } from "@ztools/declarative-ui"; +import { createTranslator } from '@ztools/declarative-ui' const rawT = createTranslator( { - "zh-CN": { - errInvalidDomain: "请输入有效域名", - errDomainWhitespace: "域名不能包含空白字符", - errUnrecognizedDomain: "无法识别域名或网址", - errHttpHttpsOnly: "只接受域名或 HTTP/HTTPS 网址,不要包含账号信息", - errPort443Only: "当前查询 HTTPS 的 443 端口,请移除网址中的其他端口", - errFullDomainRequired: "请输入完整域名,例如 example.com", - errDnsEmptyBody: "DNS 服务没有返回内容", - errDnsTooLarge: "DNS 响应超过大小限制", - errDnsInvalidJson: "DNS 服务返回了无效内容", - errDnsInvalidParams: "DNS 查询参数无效", - errDnsHttpFailed: "DNS 查询失败:HTTP {status}", - errDnsMissingStatus: "DNS 响应缺少状态码", - errDnsNxdomain: "域名不存在(NXDOMAIN)", - errDnsServerError: "DNS 服务返回错误 {status}", - errDnsTruncated: "DNS 响应被截断,结果不完整,请稍后重试", - errDnsTooManyRecords: "DNS 记录数量无效或超过限制", - errDnsIncompleteRecord: "DNS 记录字段不完整", - errDnsCancelled: "DNS 查询已取消", - errDnsTimeout: "DNS 查询超时", - errCertIncomplete: "客户端返回的证书或验证状态不完整,请更新客户端后重试", - errTlsInterfaceMissing: "当前客户端缺少证书探测接口,请升级客户端", - errTlsUnconfirmed: "客户端未确认本次证书探测", - errTlsInvalidPortOrTimeout: "探测端口或超时无效", - errTlsTargetMismatch: "证书探测返回了其他目标的结果", - fieldTrustVerify: "证书信任验证", - trustPassed: "通过", - trustFailed: "未通过:{error}", - fieldDomainMatch: "域名匹配", - matched: "匹配", - mismatched: "不匹配", - fieldTlsProtocol: "TLS 协议", - fieldValidFrom: "生效时间", - fieldValidTo: "到期时间", - fieldCommonName: "通用名称", - notProvided: "未提供", - fieldIssuer: "颁发机构", - fieldSan: "备用名称", - fieldSerialNumber: "序列号", - fieldSha256: "SHA-256 指纹", - certChainTitle: "证书链", - unnamed: "未提供名称", - chainIssuer: "颁发机构:{issuer}", - chainValidity: "有效期:{from} 至 {to}", - chainSha256: "SHA-256:{fp}", - chainTruncatedNote: "证书链超过显示上限,仅显示前 8 项。", - statusCancelled: "查询已取消", - statusQuerying: "正在查询 {domain}", - statusAllFailed: "查询失败", - statusPartialFailed: "部分查询失败", - statusCompleted: "查询完成", - statusDnsCount: " · {count} 条 DNS 记录", - certExpired: "已过期", - certNotYetValid: "尚未生效", - certHostnameMismatch: "域名不匹配", - certUntrusted: "信任验证未通过", - certExpiringSoon: "即将到期", - certVerified: "验证通过", - searchPlaceholder: "输入域名或网址,例如 example.com", - filterTooltip: "筛选 DNS 记录", - filterAll: "全部 DNS 记录", - cancelAction: "取消查询", - probeLoadingTitle: "正在查询…", - probeDiagnoseTitle: "诊断 {query}", - probePromptTitle: "输入域名后回车诊断", - probeSubtitle: "检查 HTTPS(443 端口)证书与 DNS 记录", - queryAction: "查询域名", - tlsErrorTitle: "证书查询失败", - retryAction: "重新查询", - copyErrorAction: "复制失败原因", - certExpiredSub: "证书已过期", - certDaysRemainingSub: "剩余 {days} 天", - copyCertDiagAction: "复制证书诊断", - certDiagClipboard: "{domain}:{port}\n{status}\n域名匹配:{matches}\n证书可信:{authorized}\n{authError}\n{protocol}\n有效期:{from} 至 {to}\n{fp}", - dnsErrorTitle: "DNS 查询失败", - dnsTtlSub: "{name} · TTL {ttl} 秒", - dnsDetailMarkdown: "**记录值**\n\n{value}", - copyRecordAction: "复制记录值" + 'zh-CN': { + errInvalidDomain: '请输入有效域名', + errDomainWhitespace: '域名不能包含空白字符', + errUnrecognizedDomain: '无法识别域名或网址', + errHttpHttpsOnly: '只接受域名或 HTTP/HTTPS 网址,不要包含账号信息', + errInvalidPort: '端口必须是 1 至 65535 之间的整数', + errFullDomainRequired: '请输入完整域名,例如 example.com 或 api.example.com:8443', + errDnsEmptyBody: 'DNS 服务没有返回内容', + errDnsTooLarge: 'DNS 响应超过大小限制', + errDnsInvalidJson: 'DNS 服务返回了无效内容', + errDnsInvalidParams: 'DNS 查询参数无效', + errDnsHttpFailed: 'DNS 查询失败:HTTP {status}', + errDnsMissingStatus: 'DNS 响应缺少状态码', + errDnsNxdomain: '域名不存在(NXDOMAIN)', + errDnsServerError: 'DNS 服务返回错误 {status}', + errDnsTruncated: 'DNS 响应被截断,结果不完整,请稍后重试', + errDnsTooManyRecords: 'DNS 记录数量无效或超过限制', + errDnsIncompleteRecord: 'DNS 记录字段不完整', + errDnsCancelled: 'DNS 查询已取消', + errDnsTimeout: 'DNS 查询超时', + errCertIncomplete: '客户端返回的证书或验证状态不完整,请更新客户端后重试', + errTlsInterfaceMissing: '当前客户端缺少证书探测接口,请升级客户端', + errTlsUnconfirmed: '客户端未确认本次证书探测', + errTlsInvalidPortOrTimeout: '探测端口或超时无效', + errTlsTargetMismatch: '证书探测返回了其他目标的结果', + errStorageFailed: '本地配置保存失败', + providerAlidns: '阿里 DNS (dns.alidns.com)', + providerDnspod: '腾讯 DNSPod (doh.pub)', + providerCloudflare: 'Cloudflare (cloudflare-dns.com)', + providerShortAlidns: '阿里 DoH', + providerShortDnspod: '腾讯 DoH', + providerShortCloudflare: 'Cloudflare DoH', + dohProviderTooltip: '选择 DoH 解析源', + dohProviderSwitched: '已切换 DoH 源:{provider}', + fieldTarget: '目标地址', + fieldTrustVerify: '证书信任验证', + trustPassed: '通过', + trustFailed: '未通过:{error}', + fieldDomainMatch: '域名匹配', + matched: '匹配', + mismatched: '不匹配', + fieldTlsProtocol: 'TLS 协议', + fieldTlsCipher: '加密套件', + fieldDaysRemaining: '剩余有效天数', + fieldValidFrom: '生效时间', + fieldValidTo: '到期时间', + fieldCommonName: '通用名称 (CN)', + notProvided: '未提供', + fieldIssuer: '颁发机构', + fieldSan: '备用名称 (SAN)', + fieldSerialNumber: '序列号', + fieldSha256: 'SHA-256 指纹', + certChainTitle: '证书链(共 {count} 级)', + unnamed: '未提供名称', + chainIssuer: '颁发机构:{issuer}', + chainValidity: '有效期:{from} 至 {to}', + chainSha256: 'SHA-256:{fp}', + chainTruncatedNote: '证书链超过显示上限,仅显示前 8 项。', + dnsSummaryTitle: 'DNS 解析摘要(源:{provider})', + dnsNoRecords: '未返回任何 DNS 记录', + dnsPartialFailuresTitle: '部分 DNS 类型查询失败', + statusCancelled: '查询已取消', + statusQuerying: '正在并发诊断 {target}…', + statusRefreshingWatchlist: '正在刷新关注域名({count} 个)…', + statusAllFailed: '查询失败', + statusPartialFailed: '部分失败', + statusCompleted: '并发探测完成', + statusDuration: ' · {ms}ms', + statusDnsCount: ' · {count} 条 DNS ({provider})', + certExpired: '已过期', + certNotYetValid: '尚未生效', + certHostnameMismatch: '域名不匹配', + certUntrusted: '不可信', + certExpiringSoon: '临期 {days} 天', + certHealthyTag: '正常 · 剩 {days} 天', + certVerified: '验证通过', + watchUnchecked: '未检测', + watchErrorTag: '异常', + searchPlaceholder: '输入 domain 或 domain:port(如 api.example.com:8443)', + filterAll: '全部', + filterGroupLabel: 'DNS 类型', + cancelAction: '取消查询', + probeLoadingTitle: '正在并发诊断…', + probeDiagnoseTitle: '诊断 {query}', + probePromptTitle: '输入域名或 domain:port 后回车诊断', + probeSubtitle: '支持自定义端口 TLS 证书链与全量 DNS(A/AAAA/CNAME/MX/TXT/NS/SOA/CAA)并发查询', + queryAction: '执行诊断', + sectionCurrentDiagnosis: '当前诊断', + sectionDnsRecords: 'DNS 记录({count} 条)', + sectionWatchlist: '关注域名盯盘({count} 个)', + tlsErrorTitle: 'TLS 证书探测失败', + retryAction: '重新诊断', + copyErrorAction: '复制失败原因', + copyFullReportAction: '复制完整诊断报告', + certExpiredSub: '证书已过期(超期 {days} 天)', + certDaysRemainingSub: '剩余 {days} 天', + copyCertDiagAction: '复制证书诊断', + certDiagClipboard: '{target}\n状态:{status}\n域名匹配:{matches}\n证书可信:{authorized}\n{authError}\n协议:{protocol}\n有效期:{from} 至 {to}\n指纹:{fp}', + dnsErrorTitle: 'DNS 并发查询失败({provider})', + dnsPartialErrorTitle: '部分 DNS 记录查询失败({count} 类)', + dnsPartialErrorSub: '失败类型:{types}', + dnsTtlSub: '{name} · TTL {ttl} 秒', + dnsDetailMarkdown: '**{type} 记录详情**\n\n- 主机名:`{name}`\n- TTL:`{ttl}s`\n- 解析源:`{provider}`\n\n**原始记录值**\n\n{value}', + tlsErrorDetailMarkdown: '**TLS 证书探测失败**\n\n- 目标:`{target}`\n\n**原始错误**\n\n{error}', + dnsErrorDetailMarkdown: '**DNS 并发查询失败**\n\n- 目标:`{domain}`\n- 解析源:`{provider}`\n\n**原始错误**\n\n{error}', + dnsPartialErrorDetailMarkdown: '**部分 DNS 记录类型查询失败**\n\n- 目标:`{domain}`\n- 解析源:`{provider}`\n\n{details}', + copyRecordAction: '复制记录值', + addWatchAction: '加入关注', + removeWatchAction: '移出关注', + refreshWatchlistAction: '刷新关注列表', + watchAddedToast: '已加入关注列表:{target}', + watchRemovedToast: '已移出关注列表:{target}', + watchRefreshedToast: '关注域名刷新完成:正常 {ok},异常/失败 {fail}', + watchUncheckedSub: '点击回车立即执行 TLS 与 DNS 诊断', + watchLastCheckedSub: '{issuer} · 上次检测 {time}', + watchErrorSub: '上次失败:{error}', + watchDiagnoseAction: '立即诊断', + copyTargetAction: '复制目标地址', + watchDetailTitle: '关注域名盯盘详情', + watchFieldAddedAt: '加入时间', + watchFieldLastChecked: '上次检测', + watchFieldStatus: '证书状态', + watchFieldLastError: '上次错误', + watchNotCheckedYet: '尚未执行检测,按回车可立即发起 TLS 与 DNS 诊断。', + reportHeader: '=== ZTools 域名与 SSL 诊断报告 ===', + reportSectionTls: '[TLS 证书]', + reportSectionDns: '[DNS 记录]', + reportSectionErrors: '[错误信息]', + reportCopied: '已复制完整诊断报告', + daysUnit: '{days} 天' }, - "en-US": { - errInvalidDomain: "Please enter a valid domain", - errDomainWhitespace: "Domain cannot contain whitespace", - errUnrecognizedDomain: "Unrecognized domain or URL", - errHttpHttpsOnly: "Only domains or HTTP/HTTPS URLs are accepted (no credentials)", - errPort443Only: "Only HTTPS port 443 is supported; remove other ports from the URL", - errFullDomainRequired: "Please enter a full domain, e.g. example.com", - errDnsEmptyBody: "DNS service returned an empty body", - errDnsTooLarge: "DNS response exceeded size limit", - errDnsInvalidJson: "DNS service returned invalid JSON", - errDnsInvalidParams: "Invalid DNS query parameters", - errDnsHttpFailed: "DNS query failed: HTTP {status}", - errDnsMissingStatus: "DNS response missing status code", - errDnsNxdomain: "Domain does not exist (NXDOMAIN)", - errDnsServerError: "DNS service returned error {status}", - errDnsTruncated: "DNS response was truncated; please retry later", - errDnsTooManyRecords: "Invalid or excessive DNS record count", - errDnsIncompleteRecord: "Incomplete DNS record fields", - errDnsCancelled: "DNS query cancelled", - errDnsTimeout: "DNS query timed out", - errCertIncomplete: "Incomplete certificate or verification data from client; please update and retry", - errTlsInterfaceMissing: "Client lacks TLS inspection interface; please upgrade", - errTlsUnconfirmed: "Client did not confirm TLS inspection", - errTlsInvalidPortOrTimeout: "Invalid inspection port or timeout", - errTlsTargetMismatch: "TLS inspection returned results for a different target", - fieldTrustVerify: "Trust Verification", - trustPassed: "Passed", - trustFailed: "Failed: {error}", - fieldDomainMatch: "Hostname Match", - matched: "Matched", - mismatched: "Mismatch", - fieldTlsProtocol: "TLS Protocol", - fieldValidFrom: "Valid From", - fieldValidTo: "Valid To", - fieldCommonName: "Common Name", - notProvided: "Not provided", - fieldIssuer: "Issuer", - fieldSan: "Subject Alt Names", - fieldSerialNumber: "Serial Number", - fieldSha256: "SHA-256 Fingerprint", - certChainTitle: "Certificate Chain", - unnamed: "Unnamed", - chainIssuer: "Issuer: {issuer}", - chainValidity: "Validity: {from} to {to}", - chainSha256: "SHA-256: {fp}", - chainTruncatedNote: "Certificate chain exceeds display limit; showing first 8 items.", - statusCancelled: "Query cancelled", - statusQuerying: "Querying {domain}", - statusAllFailed: "Query failed", - statusPartialFailed: "Partial failure", - statusCompleted: "Completed", - statusDnsCount: " · {count} DNS [[count:record|records]]", - certExpired: "Expired", - certNotYetValid: "Not Yet Valid", - certHostnameMismatch: "Hostname Mismatch", - certUntrusted: "Untrusted", - certExpiringSoon: "Expiring Soon", - certVerified: "Verified", - searchPlaceholder: "Enter domain or URL, e.g. example.com", - filterTooltip: "Filter DNS records", - filterAll: "All DNS Records", - cancelAction: "Cancel", - probeLoadingTitle: "Querying…", - probeDiagnoseTitle: "Diagnose {query}", - probePromptTitle: "Enter a domain and press Enter", - probeSubtitle: "Check HTTPS (port 443) certificate and DNS records", - queryAction: "Check Domain", - tlsErrorTitle: "Certificate Check Failed", - retryAction: "Retry", - copyErrorAction: "Copy Error", - certExpiredSub: "Certificate expired", - certDaysRemainingSub: "{days} [[days:day|days]] remaining", - copyCertDiagAction: "Copy Diagnostics", - certDiagClipboard: "{domain}:{port}\n{status}\nHostname Match: {matches}\nTrusted: {authorized}\n{authError}\n{protocol}\nValidity: {from} to {to}\n{fp}", - dnsErrorTitle: "DNS Query Failed", - dnsTtlSub: "{name} · TTL {ttl}s", - dnsDetailMarkdown: "**Record Value**\n\n{value}", - copyRecordAction: "Copy Value" + 'en-US': { + errInvalidDomain: 'Please enter a valid domain', + errDomainWhitespace: 'Domain cannot contain whitespace', + errUnrecognizedDomain: 'Unrecognized domain or URL', + errHttpHttpsOnly: 'Only domains or HTTP/HTTPS URLs are accepted (no credentials)', + errInvalidPort: 'Port must be an integer between 1 and 65535', + errFullDomainRequired: 'Please enter a full domain, e.g. example.com or api.example.com:8443', + errDnsEmptyBody: 'DNS service returned an empty body', + errDnsTooLarge: 'DNS response exceeded size limit', + errDnsInvalidJson: 'DNS service returned invalid JSON', + errDnsInvalidParams: 'Invalid DNS query parameters', + errDnsHttpFailed: 'DNS query failed: HTTP {status}', + errDnsMissingStatus: 'DNS response missing status code', + errDnsNxdomain: 'Domain does not exist (NXDOMAIN)', + errDnsServerError: 'DNS service returned error {status}', + errDnsTruncated: 'DNS response was truncated; please retry later', + errDnsTooManyRecords: 'Invalid or excessive DNS record count', + errDnsIncompleteRecord: 'Incomplete DNS record fields', + errDnsCancelled: 'DNS query cancelled', + errDnsTimeout: 'DNS query timed out', + errCertIncomplete: 'Incomplete certificate or verification data from client; please update and retry', + errTlsInterfaceMissing: 'Client lacks TLS inspection interface; please upgrade', + errTlsUnconfirmed: 'Client did not confirm TLS inspection', + errTlsInvalidPortOrTimeout: 'Invalid inspection port or timeout', + errTlsTargetMismatch: 'TLS inspection returned results for a different target', + errStorageFailed: 'Failed to save local preference', + providerAlidns: 'AliDNS (dns.alidns.com)', + providerDnspod: 'Tencent DNSPod (doh.pub)', + providerCloudflare: 'Cloudflare (cloudflare-dns.com)', + providerShortAlidns: 'AliDNS DoH', + providerShortDnspod: 'DNSPod DoH', + providerShortCloudflare: 'Cloudflare DoH', + dohProviderTooltip: 'Select DoH Provider', + dohProviderSwitched: 'Switched DoH provider: {provider}', + fieldTarget: 'Target', + fieldTrustVerify: 'Trust Verification', + trustPassed: 'Passed', + trustFailed: 'Failed: {error}', + fieldDomainMatch: 'Hostname Match', + matched: 'Matched', + mismatched: 'Mismatch', + fieldTlsProtocol: 'TLS Protocol', + fieldTlsCipher: 'Cipher Suite', + fieldDaysRemaining: 'Days Remaining', + fieldValidFrom: 'Valid From', + fieldValidTo: 'Valid To', + fieldCommonName: 'Common Name (CN)', + notProvided: 'Not provided', + fieldIssuer: 'Issuer', + fieldSan: 'Subject Alt Names (SAN)', + fieldSerialNumber: 'Serial Number', + fieldSha256: 'SHA-256 Fingerprint', + certChainTitle: 'Certificate Chain ({count} [[count:level|levels]])', + unnamed: 'Unnamed', + chainIssuer: 'Issuer: {issuer}', + chainValidity: 'Validity: {from} to {to}', + chainSha256: 'SHA-256: {fp}', + chainTruncatedNote: 'Certificate chain exceeds display limit; showing first 8 items.', + dnsSummaryTitle: 'DNS Summary (Provider: {provider})', + dnsNoRecords: 'No DNS records returned', + dnsPartialFailuresTitle: 'Partial DNS Query Failures', + statusCancelled: 'Query cancelled', + statusQuerying: 'Diagnosing {target}…', + statusRefreshingWatchlist: 'Refreshing watchlist ({count})…', + statusAllFailed: 'Query failed', + statusPartialFailed: 'Partial failure', + statusCompleted: 'Completed', + statusDuration: ' · {ms}ms', + statusDnsCount: ' · {count} DNS ({provider})', + certExpired: 'Expired', + certNotYetValid: 'Not Yet Valid', + certHostnameMismatch: 'Hostname Mismatch', + certUntrusted: 'Untrusted', + certExpiringSoon: 'Expiring in {days}d', + certHealthyTag: 'Healthy · {days}d left', + certVerified: 'Verified', + watchUnchecked: 'Unchecked', + watchErrorTag: 'Error', + searchPlaceholder: 'Enter domain or domain:port (e.g. api.example.com:8443)', + filterAll: 'All', + filterGroupLabel: 'DNS Type', + cancelAction: 'Cancel', + probeLoadingTitle: 'Diagnosing…', + probeDiagnoseTitle: 'Diagnose {query}', + probePromptTitle: 'Enter domain or domain:port and press Enter', + probeSubtitle: 'Inspect custom-port TLS chains & concurrent DNS (A/AAAA/CNAME/MX/TXT/NS/SOA/CAA)', + queryAction: 'Run Diagnostics', + sectionCurrentDiagnosis: 'Current Diagnostics', + sectionDnsRecords: 'DNS Records ({count})', + sectionWatchlist: 'Watched Domains ({count})', + tlsErrorTitle: 'TLS Certificate Check Failed', + retryAction: 'Retry', + copyErrorAction: 'Copy Error', + copyFullReportAction: 'Copy Full Report', + certExpiredSub: 'Certificate expired ({days}d ago)', + certDaysRemainingSub: '{days} [[days:day|days]] remaining', + copyCertDiagAction: 'Copy Cert Diagnostics', + certDiagClipboard: '{target}\nStatus: {status}\nHostname Match: {matches}\nTrusted: {authorized}\n{authError}\nProtocol: {protocol}\nValidity: {from} to {to}\nFingerprint: {fp}', + dnsErrorTitle: 'DNS Query Failed ({provider})', + dnsPartialErrorTitle: 'Partial DNS Failures ({count})', + dnsPartialErrorSub: 'Failed types: {types}', + dnsTtlSub: '{name} · TTL {ttl}s', + dnsDetailMarkdown: '**{type} Record Details**\n\n- Name: `{name}`\n- TTL: `{ttl}s`\n- Provider: `{provider}`\n\n**Raw Record Value**\n\n{value}', + tlsErrorDetailMarkdown: '**TLS Certificate Check Failed**\n\n- Target: `{target}`\n\n**Raw Error**\n\n{error}', + dnsErrorDetailMarkdown: '**DNS Query Failed**\n\n- Domain: `{domain}`\n- Provider: `{provider}`\n\n**Raw Error**\n\n{error}', + dnsPartialErrorDetailMarkdown: '**Partial DNS Record Failures**\n\n- Domain: `{domain}`\n- Provider: `{provider}`\n\n{details}', + copyRecordAction: 'Copy Record Value', + addWatchAction: 'Add to Watchlist', + removeWatchAction: 'Remove from Watchlist', + refreshWatchlistAction: 'Refresh Watchlist', + watchAddedToast: 'Added to watchlist: {target}', + watchRemovedToast: 'Removed from watchlist: {target}', + watchRefreshedToast: 'Watchlist refreshed: {ok} healthy, {fail} failed/alert', + watchUncheckedSub: 'Press Enter to run live TLS & DNS diagnostics', + watchLastCheckedSub: '{issuer} · Checked {time}', + watchErrorSub: 'Last error: {error}', + watchDiagnoseAction: 'Diagnose Now', + copyTargetAction: 'Copy Target', + watchDetailTitle: 'Watched Domain Monitor', + watchFieldAddedAt: 'Added At', + watchFieldLastChecked: 'Last Checked', + watchFieldStatus: 'Certificate Status', + watchFieldLastError: 'Last Error', + watchNotCheckedYet: 'Not checked yet. Press Enter to run live TLS and DNS diagnostics.', + reportHeader: '=== ZTools SSL & Domain Diagnostic Report ===', + reportSectionTls: '[TLS Certificate]', + reportSectionDns: '[DNS Records]', + reportSectionErrors: '[Errors]', + reportCopied: 'Full diagnostic report copied', + daysUnit: '{days} [[days:day|days]]' } }, - { defaultLocale: "en-US" } + { defaultLocale: 'en-US' } ) + export const t: typeof rawT = (key, params) => { const out = rawT(key, params) if (!out.includes('[[')) return out diff --git a/extensions/ssl-domain-check/src/index.tsx b/extensions/ssl-domain-check/src/index.tsx index b27c99fc..5a238869 100644 --- a/extensions/ssl-domain-check/src/index.tsx +++ b/extensions/ssl-domain-check/src/index.tsx @@ -1,97 +1,811 @@ -import React, { List, ActionPanel, Action, Icon, Color, showToast, ToastStyle, useState, useRef, useEffect, useLocale } from '@ztools/declarative-ui' -import type { DnsRecordEntry, SslCertHealthReport } from './types.js' -import { normalizeDomainInput, markdownLiteral, inspectDomainSslCert, resolveDomainDoh } from './ssl-dns-service.js' +import React, { + List, + ActionPanel, + Action, + Icon, + Color, + showToast, + ToastStyle, + useState, + useRef, + useEffect, + useLocale +} from '@ztools/declarative-ui' +import type { + DnsQueryError, + DnsRecordEntry, + DohProviderId, + SslCertHealthReport, + WatchlistEntry +} from './types.js' +import { + ALL_DNS_RECORD_TYPES, + DOH_PROVIDER_LIST, + formatTarget, + getDohProviderLabel, + inspectDomainSslCert, + markdownLiteral, + parseTargetInput, + resolveDomainDohDetailed +} from './ssl-dns-service.js' +import { + DEFAULT_DOH_PROVIDER, + buildWatchlistEntryFromCert, + buildWatchlistEntryFromError, + isDohProviderId, + loadDohProvider, + loadWatchlist, + saveDohProvider, + saveWatchlist +} from './storage.js' +import { + certificateMarkdown, + formatFullDiagnosticReport, + resolveCertificateStatusLabel, + watchlistEntryMarkdown +} from './report.js' import { t } from './i18n.js' + export * from './types.js' export * from './ssl-dns-service.js' -const reason = (error: unknown) => error instanceof Error ? error.message : String(error) -export function certificateMarkdown(cert: SslCertHealthReport): string { - const fields = [ - [t('fieldTrustVerify'), cert.authorized ? t('trustPassed') : t('trustFailed', { error: cert.authorizationError })], - [t('fieldDomainMatch'), cert.hostnameMatches ? t('matched') : t('mismatched')], [t('fieldTlsProtocol'), cert.protocol], - [t('fieldValidFrom'), cert.validFromIso], [t('fieldValidTo'), cert.validToIso], - [t('fieldCommonName'), cert.subjectCN || t('notProvided')], [t('fieldIssuer'), cert.issuerName || t('notProvided')], - [t('fieldSan'), cert.subjectAltName || t('notProvided')], [t('fieldSerialNumber'), cert.serialNumber], [t('fieldSha256'), cert.fingerprint256], - ] - return markdownLiteral(fields.map(([key, value]) => `${key}:${value}`).join('\n\n') + - `\n\n${t('certChainTitle')}\n\n` + cert.chain.map((entry, index) => `${index + 1}. ${entry.subjectCN || t('unnamed')}\n${t('chainIssuer', { issuer: entry.issuerName })}\n${t('chainValidity', { from: entry.validFrom, to: entry.validTo })}\n${t('chainSha256', { fp: entry.fingerprint256 })}`).join('\n\n') + - (cert.chainTruncated ? `\n\n${t('chainTruncatedNote')}` : '')) +export * from './storage.js' +export { certificateMarkdown, formatFullDiagnosticReport, watchlistEntryMarkdown } from './report.js' + +const reason = (error: unknown): string => (error instanceof Error ? error.message : String(error)) + +function formatShortTime(iso?: string): string { + if (!iso) return '' + return iso.slice(0, 16).replace('T', ' ') } + +type AccessoryTag = { tag: string | { value: string; color: Color } } + +function getWatchlistAccessory(entry: WatchlistEntry): AccessoryTag { + if (!entry.lastCheckedAt) { + return { tag: t('watchUnchecked') } + } + if (entry.lastError) { + return { tag: { value: t('watchErrorTag'), color: Color.Red } } + } + if (entry.isExpired) { + return { tag: { value: t('certExpired'), color: Color.Red } } + } + if (entry.isNotYetValid) { + return { tag: { value: t('certNotYetValid'), color: Color.Red } } + } + if (entry.hostnameMatches === false) { + return { tag: { value: t('certHostnameMismatch'), color: Color.Red } } + } + if (entry.authorized === false) { + return { tag: { value: t('certUntrusted'), color: Color.Red } } + } + if (typeof entry.daysRemaining === 'number') { + if (entry.daysRemaining <= 30) { + return { tag: { value: t('certExpiringSoon', { days: entry.daysRemaining }), color: Color.Red } } + } + return { tag: t('certHealthyTag', { days: entry.daysRemaining }) } + } + return { tag: t('certVerified') } +} + +function getWatchlistIcon(entry: WatchlistEntry): Icon { + if (!entry.lastCheckedAt) return Icon.Star + if (entry.lastError || entry.isExpired || entry.isHealthy === false) return Icon.ExclamationMark + if (typeof entry.daysRemaining === 'number' && entry.daysRemaining <= 30) return Icon.Clock + return Icon.Shield +} + +function getCertAccessory(cert: SslCertHealthReport): AccessoryTag { + if (!cert.isHealthy) { + return { tag: { value: resolveCertificateStatusLabel(cert), color: Color.Red } } + } + if (cert.isExpiringSoon) { + return { tag: { value: t('certExpiringSoon', { days: cert.daysRemaining }), color: Color.Red } } + } + return { tag: t('certHealthyTag', { days: cert.daysRemaining }) } +} + +interface StatusState { + type: 'empty' | 'cancelled' | 'querying' | 'refreshing' | 'done' + target?: string + failures?: number + dnsCount?: number + durationMs?: number + provider?: DohProviderId + watchCount?: number +} + +function formatStatusText(statusKey: StatusState, dohProvider: DohProviderId): string { + if (statusKey.type === 'empty') return '' + if (statusKey.type === 'cancelled') return t('statusCancelled') + if (statusKey.type === 'querying') return t('statusQuerying', { target: statusKey.target ?? '' }) + if (statusKey.type === 'refreshing') return t('statusRefreshingWatchlist', { count: statusKey.watchCount ?? 0 }) + const outcome = + statusKey.failures === 2 + ? t('statusAllFailed') + : statusKey.failures + ? t('statusPartialFailed') + : t('statusCompleted') + const durationPart = + typeof statusKey.durationMs === 'number' ? t('statusDuration', { ms: statusKey.durationMs }) : '' + const dnsPart = + statusKey.dnsCount !== undefined + ? t('statusDnsCount', { + count: statusKey.dnsCount, + provider: getDohProviderLabel(statusKey.provider ?? dohProvider, true) + }) + : '' + return `${statusKey.target} · ${outcome}${durationPart}${dnsPart}` +} + +function resolveWatchCandidate(lastTarget: string, query: string): string { + if (lastTarget) return lastTarget + if (!query.trim()) return '' + try { + const parsed = parseTargetInput(query) + return formatTarget(parsed.domain, parsed.port) + } catch { + return '' + } +} + +interface DiagnosisSectionProps { + cert: SslCertHealthReport | null + certError: string + records: DnsRecordEntry[] + dnsError: string + dnsPartialErrors: DnsQueryError[] + dohProvider: DohProviderId + lastTarget: string + query: string + lastDurationMs?: number + fullReportText: string + currentTargetForWatch: string + isCurrentWatched: boolean + onRun: () => void + onToggleWatch: (target: string) => void +} + +function DiagnosisSection(props: DiagnosisSectionProps) { + const { + cert, + certError, + records, + dnsError, + dnsPartialErrors, + dohProvider, + lastTarget, + query, + lastDurationMs, + fullReportText, + currentTargetForWatch, + isCurrentWatched, + onRun, + onToggleWatch + } = props + const providerShortLabel = getDohProviderLabel(dohProvider, true) + const targetLabel = lastTarget || query.trim() + + return ( + + {certError && ( + + } + actions={ + + + + {fullReportText && } + {currentTargetForWatch && ( + onToggleWatch(currentTargetForWatch)} + /> + )} + + } + /> + )} + + {cert && ( + } + actions={ + + + + onToggleWatch(formatTarget(cert.domain, cert.port))} + /> + + + } + /> + )} + + {dnsError && ( + + } + actions={ + + + + {fullReportText && } + + } + /> + )} + + {dnsPartialErrors.length > 0 && ( + e.type).join(', ') })} + icon={Icon.ExclamationMark} + accessories={[{ tag: { value: providerShortLabel, color: Color.Red } }]} + detail={ + `[${e.type}] ${e.message}`).join('\n')) + })} + /> + } + actions={ + + + `[${e.type}] ${e.message}`).join('\n')} + /> + + } + /> + )} + + ) +} + +function WatchlistSection(props: { + watchlist: WatchlistEntry[] + onDiagnose: (entry: WatchlistEntry) => void + onRefreshAll: () => void + onRemove: (target: string) => void +}) { + const { watchlist, onDiagnose, onRefreshAll, onRemove } = props + return ( + + {watchlist.map(entry => { + const subtitle = !entry.lastCheckedAt + ? t('watchUncheckedSub') + : entry.lastError + ? t('watchErrorSub', { error: entry.lastError }) + : t('watchLastCheckedSub', { + issuer: entry.issuerName || entry.protocol || t('notProvided'), + time: formatShortTime(entry.lastCheckedAt) + }) + return ( + } + actions={ + + onDiagnose(entry)} /> + + onRemove(entry.target)} + /> + + + } + /> + ) + })} + + ) +} + export function SslDomainCheckCommand() { useLocale() - const [query, setQuery] = useState(''), [recordFilter, setRecordFilter] = useState('ALL') - const [cert, setCert] = useState(null), [records, setRecords] = useState([]) - const [certError, setCertError] = useState(''), [dnsError, setDnsError] = useState('') - const [statusKey, setStatusKey] = useState<{ type: 'empty' | 'cancelled' | 'querying' | 'done'; domain?: string; failures?: number; dnsCount?: number }>({ type: 'empty' }) + const [query, setQuery] = useState('') + const [dohProvider, setDohProvider] = useState(DEFAULT_DOH_PROVIDER) + const [watchlist, setWatchlist] = useState([]) + const [cert, setCert] = useState(null) + const [records, setRecords] = useState([]) + const [certError, setCertError] = useState('') + const [dnsError, setDnsError] = useState('') + const [dnsPartialErrors, setDnsPartialErrors] = useState([]) + const [lastTarget, setLastTarget] = useState('') + const [lastDurationMs, setLastDurationMs] = useState(undefined) + const [statusKey, setStatusKey] = useState({ type: 'empty' }) const [loading, setLoading] = useState(false) - const operation = useRef(null), generation = useRef(0), alive = useRef(true) - const clear = () => { setCert(null); setRecords([]); setCertError(''); setDnsError('') } + + const operation = useRef(null) + const generation = useRef(0) + const alive = useRef(true) + const watchlistRef = useRef([]) + watchlistRef.current = watchlist + + const clearDiagnosis = () => { + setCert(null) + setRecords([]) + setCertError('') + setDnsError('') + setDnsPartialErrors([]) + setLastTarget('') + setLastDurationMs(undefined) + } + const cancel = () => { - generation.current++; operation.current?.abort(); operation.current = null - setLoading(false); clear(); setStatusKey({ type: 'cancelled' }) + generation.current++ + operation.current?.abort() + operation.current = null + setLoading(false) + clearDiagnosis() + setStatusKey({ type: 'cancelled' }) } + const changeQuery = (value: string) => { - // 输入提示只保留在空状态条目上,工具栏摘要不再重复 - cancel(); setQuery(value); setStatusKey({ type: 'empty' }) + cancel() + setQuery(value) + setStatusKey({ type: 'empty' }) } + useEffect(() => { alive.current = true - return () => { alive.current = false; generation.current++; operation.current?.abort() } + void (async () => { + const [savedProvider, savedWatchlist] = await Promise.all([loadDohProvider(), loadWatchlist()]) + if (!alive.current) return + setDohProvider(savedProvider) + setWatchlist(savedWatchlist) + })() + return () => { + alive.current = false + generation.current++ + operation.current?.abort() + } }, []) - const run = async () => { + + const handleProviderChange = async (value: string) => { + if (!isDohProviderId(value) || value === dohProvider) return + setDohProvider(value) + try { + await saveDohProvider(value) + await showToast({ + style: ToastStyle.Success, + title: t('dohProviderSwitched', { provider: getDohProviderLabel(value, true) }) + }) + } catch (error) { + await showToast({ style: ToastStyle.Failure, title: t('errStorageFailed'), message: reason(error) }) + } + } + + const syncWatchlistAfterProbe = async ( + targetDomain: string, + targetPort: number, + certResult: SslCertHealthReport | null, + tlsFailure: string + ) => { + const target = formatTarget(targetDomain, targetPort) + const current = watchlistRef.current + const idx = current.findIndex(item => item.target === target) + if (idx === -1) return + const nextList = [...current] + nextList[idx] = certResult + ? buildWatchlistEntryFromCert(certResult, current[idx]) + : buildWatchlistEntryFromError(targetDomain, targetPort, tlsFailure || t('errTlsUnconfirmed'), current[idx]) + try { + const saved = await saveWatchlist(nextList) + if (alive.current) setWatchlist(saved) + } catch (error) { + console.warn('[ssl-domain-check] failed to sync watchlist entry:', error) + } + } + + const runTarget = async (rawInput: string) => { if (operation.current) return - let domain: string - try { domain = normalizeDomainInput(query) } - catch (error) { await showToast({ style: ToastStyle.Failure, title: t('errInvalidDomain'), message: reason(error) }); return } - const controller = new AbortController(), id = ++generation.current - operation.current = controller; clear(); setLoading(true); setStatusKey({ type: 'querying', domain }) + let parsed: { domain: string; port: number } + try { + parsed = parseTargetInput(rawInput) + } catch (error) { + await showToast({ style: ToastStyle.Failure, title: t('errInvalidDomain'), message: reason(error) }) + return + } + const target = formatTarget(parsed.domain, parsed.port) + const controller = new AbortController() + const id = ++generation.current + operation.current = controller + clearDiagnosis() + setLastTarget(target) + setLoading(true) + setStatusKey({ type: 'querying', target }) + const startedAt = Date.now() try { const [tls, dns] = await Promise.allSettled([ - inspectDomainSslCert(domain, { signal: controller.signal }), - resolveDomainDoh(domain, undefined, { signal: controller.signal }), + inspectDomainSslCert(target, { signal: controller.signal, port: parsed.port }), + resolveDomainDohDetailed(parsed.domain, ALL_DNS_RECORD_TYPES, { + signal: controller.signal, + provider: dohProvider + }) ]) if (!alive.current || id !== generation.current || controller.signal.aborted) return - if (tls.status === 'fulfilled') setCert(tls.value); else setCertError(reason(tls.reason)) - if (dns.status === 'fulfilled') setRecords(dns.value); else setDnsError(reason(dns.reason)) + const durationMs = Math.max(0, Date.now() - startedAt) + setLastDurationMs(durationMs) + + const nextCert = tls.status === 'fulfilled' ? tls.value : null + const nextCertError = tls.status === 'rejected' ? reason(tls.reason) : '' + if (nextCert) setCert(nextCert) + else setCertError(nextCertError) + + if (dns.status === 'fulfilled') { + setRecords(dns.value.records) + setDnsPartialErrors(dns.value.errors) + } else { + setDnsError(reason(dns.reason)) + } + const failures = Number(tls.status === 'rejected') + Number(dns.status === 'rejected') - setStatusKey({ type: 'done', domain, failures, dnsCount: dns.status === 'fulfilled' ? dns.value.length : undefined }) + setStatusKey({ + type: 'done', + target, + failures, + dnsCount: dns.status === 'fulfilled' ? dns.value.records.length : undefined, + durationMs, + provider: dohProvider + }) + await syncWatchlistAfterProbe(parsed.domain, parsed.port, nextCert, nextCertError) } finally { - if (alive.current && id === generation.current) { operation.current = null; setLoading(false) } + if (alive.current && id === generation.current) { + operation.current = null + setLoading(false) + } + } + } + + const run = () => { + void runTarget(query) + } + + const toggleWatch = async (rawTarget?: string) => { + let parsed: { domain: string; port: number } + try { + parsed = parseTargetInput(rawTarget ?? (lastTarget || query)) + } catch (error) { + await showToast({ style: ToastStyle.Failure, title: t('errInvalidDomain'), message: reason(error) }) + return + } + const target = formatTarget(parsed.domain, parsed.port) + const current = watchlistRef.current + const exists = current.some(item => item.target === target) + try { + const next = exists + ? current.filter(item => item.target !== target) + : [ + ...current, + cert && formatTarget(cert.domain, cert.port) === target + ? buildWatchlistEntryFromCert(cert) + : { target, domain: parsed.domain, port: parsed.port, addedAt: new Date().toISOString() } + ] + const saved = await saveWatchlist(next) + if (alive.current) setWatchlist(saved) + await showToast({ + style: ToastStyle.Success, + title: exists ? t('watchRemovedToast', { target }) : t('watchAddedToast', { target }) + }) + } catch (error) { + await showToast({ style: ToastStyle.Failure, title: t('errStorageFailed'), message: reason(error) }) + } + } + + const refreshWatchlist = async () => { + const current = watchlistRef.current + if (operation.current || current.length === 0) return + const controller = new AbortController() + const id = ++generation.current + operation.current = controller + setLoading(true) + setStatusKey({ type: 'refreshing', watchCount: current.length }) + try { + const settled = await Promise.allSettled( + current.map(entry => inspectDomainSslCert(entry.target, { signal: controller.signal, port: entry.port })) + ) + if (!alive.current || id !== generation.current || controller.signal.aborted) return + let okCount = 0 + let failCount = 0 + const updated = current.map((entry, idx) => { + const result = settled[idx] + if (result.status === 'fulfilled') { + if (result.value.isHealthy && !result.value.isExpiringSoon) okCount++ + else failCount++ + return buildWatchlistEntryFromCert(result.value, entry) + } + failCount++ + return buildWatchlistEntryFromError(entry.domain, entry.port, reason(result.reason), entry) + }) + const saved = await saveWatchlist(updated) + if (!alive.current) return + setWatchlist(saved) + setStatusKey({ type: 'empty' }) + await showToast({ + style: failCount > 0 ? ToastStyle.Failure : ToastStyle.Success, + title: t('watchRefreshedToast', { ok: okCount, fail: failCount }) + }) + } catch (error) { + if (alive.current && !controller.signal.aborted) { + await showToast({ style: ToastStyle.Failure, title: t('errStorageFailed'), message: reason(error) }) + } + } finally { + if (alive.current && id === generation.current) { + operation.current = null + setLoading(false) + } + } + } + + const diagnoseFromWatchlist = (entry: WatchlistEntry) => { + if (operation.current) { + generation.current++ + operation.current.abort() + operation.current = null } + setQuery(entry.target) + void runTarget(entry.target) } - const status = statusKey.type === 'empty' ? '' - : statusKey.type === 'cancelled' ? t('statusCancelled') - : statusKey.type === 'querying' ? t('statusQuerying', { domain: statusKey.domain ?? '' }) - : `${statusKey.domain} · ${statusKey.failures === 2 ? t('statusAllFailed') : statusKey.failures ? t('statusPartialFailed') : t('statusCompleted')}${statusKey.dnsCount !== undefined ? t('statusDnsCount', { count: statusKey.dnsCount }) : ''}` - const filtered = records.filter(record => recordFilter === 'ALL' || record.type === recordFilter) - const certificateStatus = cert ? cert.isExpired ? t('certExpired') : cert.isNotYetValid ? t('certNotYetValid') : !cert.hostnameMatches ? t('certHostnameMismatch') : !cert.authorized ? t('certUntrusted') : cert.isExpiringSoon ? t('certExpiringSoon') : t('certVerified') : '' + + const status = formatStatusText(statusKey, dohProvider) + const providerShortLabel = getDohProviderLabel(dohProvider, true) + const hasDiagnosis = Boolean(cert || records.length || certError || dnsError || dnsPartialErrors.length) + const currentTargetForWatch = resolveWatchCandidate(lastTarget, query) + const isCurrentWatched = Boolean(currentTargetForWatch && watchlist.some(w => w.target === currentTargetForWatch)) + const fullReportText = hasDiagnosis + ? formatFullDiagnosticReport({ + target: lastTarget || query.trim(), + provider: dohProvider, + durationMs: lastDurationMs, + cert, + certError, + records, + dnsError, + dnsPartialErrors + }) + : '' + + const filterBarActions = loading + ? [{ id: 'cancel', title: t('cancelAction'), onAction: cancel }] + : [ + ...(currentTargetForWatch + ? [ + { + id: 'toggle-watch', + title: isCurrentWatched ? t('removeWatchAction') : t('addWatchAction'), + onAction: () => { + void toggleWatch(currentTargetForWatch) + } + } + ] + : []), + ...(watchlist.length > 0 + ? [ + { + id: 'refresh-watchlist', + title: t('refreshWatchlistAction'), + onAction: () => { + void refreshWatchlist() + } + } + ] + : []) + ] + return ( - 0} + isLoading={loading} + searchText={query} + onSearchTextChange={changeQuery} searchBarPlaceholder={t('searchPlaceholder')} - searchBarAccessory={ - - {['A', 'AAAA', 'CNAME', 'MX', 'TXT'].map(type => )} - } - filterBar={{ summaryText: status, actions: loading ? [{ id: 'cancel', title: t('cancelAction'), onAction: cancel }] : [] }}> - } /> - {certError && } - actions={} />} - {cert && } - actions={} />} - {dnsError && } - actions={} />} - {filtered.map((record, index) => } - actions={} />)} + searchBarAccessory={ + { + void handleProviderChange(value) + }} + > + {DOH_PROVIDER_LIST.map(provider => ( + + ))} + + } + filterBar={{ summaryText: status, actions: filterBarActions }} + > + + + {currentTargetForWatch && ( + { + void toggleWatch(currentTargetForWatch) + }} + /> + )} + {fullReportText && ( + + )} + {watchlist.length > 0 && ( + { + void refreshWatchlist() + }} + /> + )} + + } + /> + + {hasDiagnosis && ( + { + void toggleWatch(target) + }} + /> + )} + + {records.length > 0 && ( + + {records.map((record, index) => ( + + } + actions={ + + + {fullReportText && } + + + } + /> + ))} + + )} + + {watchlist.length > 0 && ( + { + void refreshWatchlist() + }} + onRemove={target => { + void toggleWatch(target) + }} + /> + )} ) } + export default SslDomainCheckCommand diff --git a/extensions/ssl-domain-check/src/report.ts b/extensions/ssl-domain-check/src/report.ts new file mode 100644 index 00000000..c0e01e2f --- /dev/null +++ b/extensions/ssl-domain-check/src/report.ts @@ -0,0 +1,179 @@ +import type { DnsQueryError, DnsRecordEntry, DohProviderId, SslCertHealthReport, WatchlistEntry } from './types.js' +import { formatTarget, markdownLiteral } from './domain.js' +import { getDohProviderLabel } from './doh-service.js' +import { t } from './i18n.js' + +export function resolveCertificateStatusLabel(cert: SslCertHealthReport): string { + if (cert.isExpired) return t('certExpired') + if (cert.isNotYetValid) return t('certNotYetValid') + if (!cert.hostnameMatches) return t('certHostnameMismatch') + if (!cert.authorized) return t('certUntrusted') + if (cert.isExpiringSoon) return t('certExpiringSoon', { days: cert.daysRemaining }) + return t('certVerified') +} + +export function certificateMarkdown( + cert: SslCertHealthReport, + dnsRecords?: readonly DnsRecordEntry[], + dnsErrors?: readonly DnsQueryError[], + provider?: DohProviderId +): string { + const fields: Array<[string, string]> = [ + [t('fieldTarget'), formatTarget(cert.domain, cert.port)], + [t('fieldTrustVerify'), cert.authorized ? t('trustPassed') : t('trustFailed', { error: cert.authorizationError })], + [t('fieldDomainMatch'), cert.hostnameMatches ? t('matched') : t('mismatched')], + [t('fieldTlsProtocol'), cert.cipher ? `${cert.protocol} (${cert.cipher})` : cert.protocol], + [t('fieldDaysRemaining'), cert.isExpired ? t('certExpiredSub', { days: Math.abs(cert.daysRemaining) }) : t('daysUnit', { days: cert.daysRemaining })], + [t('fieldValidFrom'), cert.validFromIso], + [t('fieldValidTo'), cert.validToIso], + [t('fieldCommonName'), cert.subjectCN || t('notProvided')], + [t('fieldIssuer'), cert.issuerName || t('notProvided')], + [t('fieldSan'), cert.subjectAltName || t('notProvided')], + [t('fieldSerialNumber'), cert.serialNumber], + [t('fieldSha256'), cert.fingerprint256] + ] + + const sections: string[] = [ + fields.map(([key, value]) => `${key}:${value}`).join('\n\n'), + `${t('certChainTitle', { count: cert.chain.length })}\n\n` + + cert.chain + .map( + (entry, index) => + `${index + 1}. ${entry.subjectCN || t('unnamed')}\n` + + `${t('chainIssuer', { issuer: entry.issuerName })}\n` + + `${t('chainValidity', { from: entry.validFrom, to: entry.validTo })}\n` + + `${t('chainSha256', { fp: entry.fingerprint256 })}` + ) + .join('\n\n') + + (cert.chainTruncated ? `\n\n${t('chainTruncatedNote')}` : '') + ] + + if (provider && (dnsRecords?.length || dnsErrors?.length)) { + const providerLabel = getDohProviderLabel(provider, true) + const dnsLines: string[] = [t('dnsSummaryTitle', { provider: providerLabel })] + if (dnsRecords && dnsRecords.length > 0) { + for (const rec of dnsRecords) { + dnsLines.push(`[${rec.type}] ${rec.name} (TTL ${rec.ttl}s): ${rec.data}`) + } + } else { + dnsLines.push(t('dnsNoRecords')) + } + if (dnsErrors && dnsErrors.length > 0) { + dnsLines.push('') + dnsLines.push(t('dnsPartialFailuresTitle')) + for (const err of dnsErrors) { + dnsLines.push(`[${err.type}] ${err.message}`) + } + } + sections.push(dnsLines.join('\n')) + } + + return markdownLiteral(sections.join('\n\n')) +} + +export function watchlistEntryMarkdown(entry: WatchlistEntry): string { + const lines: string[] = [ + `${t('watchDetailTitle')}`, + `${t('fieldTarget')}:${entry.target}`, + `${t('watchFieldAddedAt')}:${entry.addedAt}` + ] + if (!entry.lastCheckedAt) { + lines.push('', t('watchNotCheckedYet')) + return markdownLiteral(lines.join('\n')) + } + + lines.push(`${t('watchFieldLastChecked')}:${entry.lastCheckedAt}`) + if (entry.lastError) { + lines.push(`${t('watchFieldStatus')}:${t('watchErrorTag')}`) + lines.push(`${t('watchFieldLastError')}:${entry.lastError}`) + return markdownLiteral(lines.join('\n')) + } + + const statusText = entry.isExpired + ? t('certExpired') + : entry.isNotYetValid + ? t('certNotYetValid') + : entry.hostnameMatches === false + ? t('certHostnameMismatch') + : entry.authorized === false + ? t('certUntrusted') + : typeof entry.daysRemaining === 'number' && entry.daysRemaining <= 30 + ? t('certExpiringSoon', { days: entry.daysRemaining }) + : t('certVerified') + + lines.push(`${t('watchFieldStatus')}:${statusText}`) + if (typeof entry.daysRemaining === 'number') { + lines.push( + `${t('fieldDaysRemaining')}:${entry.isExpired ? t('certExpiredSub', { days: Math.abs(entry.daysRemaining) }) : t('daysUnit', { days: entry.daysRemaining })}` + ) + } + if (entry.protocol) { + lines.push(`${t('fieldTlsProtocol')}:${entry.cipher ? `${entry.protocol} (${entry.cipher})` : entry.protocol}`) + } + if (entry.issuerName) lines.push(`${t('fieldIssuer')}:${entry.issuerName}`) + if (entry.validFromIso) lines.push(`${t('fieldValidFrom')}:${entry.validFromIso}`) + if (entry.validToIso) lines.push(`${t('fieldValidTo')}:${entry.validToIso}`) + if (entry.authorizationError) lines.push(`${t('fieldTrustVerify')}:${t('trustFailed', { error: entry.authorizationError })}`) + + return markdownLiteral(lines.join('\n')) +} + +export function formatFullDiagnosticReport(params: { + target: string + provider: DohProviderId + durationMs?: number + cert: SslCertHealthReport | null + certError: string + records: readonly DnsRecordEntry[] + dnsError: string + dnsPartialErrors: readonly DnsQueryError[] +}): string { + const { target, provider, durationMs, cert, certError, records, dnsError, dnsPartialErrors } = params + const lines: string[] = [ + t('reportHeader'), + `${t('fieldTarget')}: ${target}`, + `DoH: ${getDohProviderLabel(provider)}` + ] + if (typeof durationMs === 'number') { + lines.push(`Duration: ${durationMs}ms`) + } + lines.push('', t('reportSectionTls')) + if (cert) { + const status = resolveCertificateStatusLabel(cert) + lines.push(`Status: ${status}`) + lines.push(`Protocol: ${cert.cipher ? `${cert.protocol} (${cert.cipher})` : cert.protocol}`) + lines.push(`Trusted: ${String(cert.authorized)}${cert.authorizationError ? ` (${cert.authorizationError})` : ''}`) + lines.push(`Hostname Match: ${String(cert.hostnameMatches)}`) + lines.push(`Days Remaining: ${cert.daysRemaining}`) + lines.push(`Validity: ${cert.validFromIso} ~ ${cert.validToIso}`) + lines.push(`CN: ${cert.subjectCN || '-'}`) + lines.push(`Issuer: ${cert.issuerName || '-'}`) + lines.push(`SAN: ${cert.subjectAltName || '-'}`) + lines.push(`SHA-256: ${cert.fingerprint256}`) + lines.push(`Chain (${cert.chain.length}): ${cert.chain.map(c => c.subjectCN || t('unnamed')).join(' -> ')}`) + } else if (certError) { + lines.push(`Error: ${certError}`) + } else { + lines.push('-') + } + + lines.push('', t('reportSectionDns')) + if (records.length > 0) { + for (const rec of records) { + lines.push(`[${rec.type}] ${rec.name} TTL=${rec.ttl} ${rec.data}`) + } + } else if (dnsError) { + lines.push(`Error: ${dnsError}`) + } else { + lines.push(t('dnsNoRecords')) + } + + if (dnsPartialErrors.length > 0) { + lines.push('', t('reportSectionErrors')) + for (const err of dnsPartialErrors) { + lines.push(`[DNS ${err.type}] ${err.message}`) + } + } + + return lines.join('\n') +} diff --git a/extensions/ssl-domain-check/src/ssl-dns-service.ts b/extensions/ssl-domain-check/src/ssl-dns-service.ts index 0c9a6875..9184e500 100644 --- a/extensions/ssl-domain-check/src/ssl-dns-service.ts +++ b/extensions/ssl-domain-check/src/ssl-dns-service.ts @@ -1,40 +1,125 @@ import type { CertificateSummary, SslCertHealthReport } from './types.js' -import { normalizeDomainInput } from './domain.js' +import { normalizeDomainInput, parseTargetInput } from './domain.js' import { t } from './i18n.js' import { resolveErrorMessage } from './error-i18n.js' -export { normalizeDomainInput, markdownLiteral } from './domain.js' -export { resolveDomainDoh } from './doh-service.js' -const record = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v) -const text = (v: unknown, max = 8192): v is string => typeof v === 'string' && v.length <= max + +export { parseTargetInput, normalizeDomainInput, formatTarget, markdownLiteral } from './domain.js' +export { + ALL_DNS_RECORD_TYPES, + DOH_PROVIDERS, + DOH_PROVIDER_LIST, + getDohProviderLabel, + resolveDomainDoh, + resolveDomainDohDetailed +} from './doh-service.js' + +const EXPIRING_SOON_THRESHOLD_DAYS = 30 + +const isPlainObject = (v: unknown): v is Record => Boolean(v) && typeof v === 'object' && !Array.isArray(v) +const isBoundedText = (v: unknown, max = 8192): v is string => typeof v === 'string' && v.length <= max + function validSummary(v: unknown): v is CertificateSummary { - return record(v) && ['subjectCN', 'issuerName', 'serialNumber', 'validFrom', 'validTo'].every(key => text(v[key])) && - typeof v.fingerprint256 === 'string' && /^(?:[a-f0-9]{2}:){31}[a-f0-9]{2}$/i.test(v.fingerprint256) && - Number.isFinite(Date.parse(String(v.validFrom))) && Number.isFinite(Date.parse(String(v.validTo))) && Date.parse(String(v.validTo)) > Date.parse(String(v.validFrom)) + return ( + isPlainObject(v) && + ['subjectCN', 'issuerName', 'serialNumber', 'validFrom', 'validTo'].every(key => isBoundedText(v[key])) && + typeof v.fingerprint256 === 'string' && + /^(?:[a-f0-9]{2}:){31}[a-f0-9]{2}$/i.test(v.fingerprint256) && + Number.isFinite(Date.parse(String(v.validFrom))) && + Number.isFinite(Date.parse(String(v.validTo))) && + Date.parse(String(v.validTo)) > Date.parse(String(v.validFrom)) + ) } + export function evaluateSslCertInfo(value: unknown, nowMs = Date.now()): SslCertHealthReport { - if (!record(value) || !validSummary(value) || !text(value.domain, 253) || !Number.isInteger(value.port) || Number(value.port) < 1 || Number(value.port) > 65535 || !text(value.protocol, 128) || !value.protocol || !text(value.subjectAltName, 32768) || - typeof value.authorized !== 'boolean' || typeof value.hostnameMatches !== 'boolean' || !text(value.authorizationError) || typeof value.chainTruncated !== 'boolean' || - !Array.isArray(value.chain) || !value.chain.length || value.chain.length > 8 || !value.chain.every(validSummary) || value.chain[0].fingerprint256 !== value.fingerprint256 || - (value.authorized && (!value.hostnameMatches || value.authorizationError)) || (!value.authorized && !value.authorizationError) || !Number.isFinite(nowMs)) throw new Error(t('errCertIncomplete')) - const from = Date.parse(value.validFrom), to = Date.parse(value.validTo), isExpired = to <= nowMs, daysRemaining = Math.ceil((to - nowMs) / 86400000), isNotYetValid = from > nowMs - return { ...value, domain: normalizeDomainInput(value.domain), port: Number(value.port), validFromIso: new Date(from).toISOString(), validToIso: new Date(to).toISOString(), daysRemaining, isExpired, isNotYetValid, - isExpiringSoon: !isExpired && daysRemaining <= 14, isHealthy: value.authorized && value.hostnameMatches && !isExpired && !isNotYetValid } as SslCertHealthReport + if ( + !isPlainObject(value) || + !validSummary(value) || + !isBoundedText(value.domain, 253) || + !Number.isInteger(value.port) || + Number(value.port) < 1 || + Number(value.port) > 65535 || + !isBoundedText(value.protocol, 128) || + !value.protocol || + (value.cipher !== undefined && !isBoundedText(value.cipher, 256)) || + !isBoundedText(value.subjectAltName, 32768) || + typeof value.authorized !== 'boolean' || + typeof value.hostnameMatches !== 'boolean' || + !isBoundedText(value.authorizationError) || + typeof value.chainTruncated !== 'boolean' || + !Array.isArray(value.chain) || + !value.chain.length || + value.chain.length > 8 || + !value.chain.every(validSummary) || + value.chain[0].fingerprint256 !== value.fingerprint256 || + (value.authorized && (!value.hostnameMatches || value.authorizationError)) || + (!value.authorized && !value.authorizationError) || + !Number.isFinite(nowMs) + ) { + throw new Error(t('errCertIncomplete')) + } + const from = Date.parse(value.validFrom) + const to = Date.parse(value.validTo) + const isExpired = to <= nowMs + const daysRemaining = Math.ceil((to - nowMs) / 86400000) + const isNotYetValid = from > nowMs + return { + ...(value as unknown as CertificateSummary), + domain: normalizeDomainInput(value.domain), + port: Number(value.port), + protocol: value.protocol, + cipher: typeof value.cipher === 'string' && value.cipher.trim() ? value.cipher.trim() : undefined, + subjectAltName: value.subjectAltName, + authorized: value.authorized, + authorizationError: value.authorizationError, + hostnameMatches: value.hostnameMatches, + chain: value.chain, + chainTruncated: value.chainTruncated, + validFromIso: new Date(from).toISOString(), + validToIso: new Date(to).toISOString(), + daysRemaining, + isExpired, + isNotYetValid, + isExpiringSoon: !isExpired && daysRemaining <= EXPIRING_SOON_THRESHOLD_DAYS, + isHealthy: value.authorized && value.hostnameMatches && !isExpired && !isNotYetValid + } } -interface Bridge { transport?: { methods?: { tls_inspect?: (request: unknown) => Promise<{ success?: boolean; data?: unknown; error?: { message?: string } }> } } } + +interface Bridge { + transport?: { + methods?: { + tls_inspect?: (request: unknown) => Promise<{ success?: boolean; data?: unknown; error?: { message?: string } }> + } + } +} + let sequence = 0 -async function tlsCall(params: Record) { + +async function tlsCall(params: Record): Promise> { const method = (globalThis as unknown as { __ztoolsElectron?: Bridge }).__ztoolsElectron?.transport?.methods?.tls_inspect if (!method) throw new Error(t('errTlsInterfaceMissing')) const result = await method({ messageId: `tls_${Date.now()}_${++sequence}`, params, timeoutMs: 20000 }) - if (result?.success !== true || !record(result.data) || result.data.success !== true) throw new Error(resolveErrorMessage(result?.error, t('errTlsUnconfirmed'))) + if (result?.success !== true || !isPlainObject(result.data) || result.data.success !== true) { + throw new Error(resolveErrorMessage(result?.error, t('errTlsUnconfirmed'))) + } return result.data } -export async function inspectDomainSslCert(rawDomain: string, options: { signal?: AbortSignal; port?: number; timeoutMs?: number } = {}): Promise { - const domain = normalizeDomainInput(rawDomain), port = options.port ?? 443, timeoutMs = options.timeoutMs ?? 6000 - if (!Number.isInteger(port) || port < 1 || port > 65535 || !Number.isInteger(timeoutMs) || timeoutMs < 1000 || timeoutMs > 15000) throw new Error(t('errTlsInvalidPortOrTimeout')) + +export async function inspectDomainSslCert( + rawTarget: string, + options: { signal?: AbortSignal; port?: number; timeoutMs?: number } = {} +): Promise { + const parsed = parseTargetInput(rawTarget) + const domain = parsed.domain + const port = options.port ?? parsed.port + const timeoutMs = options.timeoutMs ?? 6000 + if (!Number.isInteger(port) || port < 1 || port > 65535 || !Number.isInteger(timeoutMs) || timeoutMs < 1000 || timeoutMs > 15000) { + throw new Error(t('errTlsInvalidPortOrTimeout')) + } options.signal?.throwIfAborted() const operationId = globalThis.crypto.randomUUID() - const cancel = () => { void tlsCall({ action: 'cancel', operationId }).catch(error => console.warn('TLS probe cancel unconfirmed', error)) } + const cancel = () => { + void tlsCall({ action: 'cancel', operationId }).catch(error => console.warn('TLS probe cancel unconfirmed', error)) + } options.signal?.addEventListener('abort', cancel, { once: true }) try { const response = await tlsCall({ action: 'inspect', operationId, domain, port, timeoutMs }) @@ -42,5 +127,7 @@ export async function inspectDomainSslCert(rawDomain: string, options: { signal? const cert = evaluateSslCertInfo(response.cert) if (cert.domain !== domain || cert.port !== port) throw new Error(t('errTlsTargetMismatch')) return cert - } finally { options.signal?.removeEventListener('abort', cancel) } + } finally { + options.signal?.removeEventListener('abort', cancel) + } } diff --git a/extensions/ssl-domain-check/src/storage.ts b/extensions/ssl-domain-check/src/storage.ts new file mode 100644 index 00000000..57778eb9 --- /dev/null +++ b/extensions/ssl-domain-check/src/storage.ts @@ -0,0 +1,157 @@ +import { LocalStorage } from '@ztools/declarative-ui' +import type { DohProviderId, SslCertHealthReport, WatchlistEntry } from './types.js' +import { formatTarget } from './domain.js' + +export const DOH_PROVIDER_STORAGE_KEY = 'ssl-domain-check:doh-provider' +export const WATCHLIST_STORAGE_KEY = 'ssl-domain-check:watchlist' +export const DEFAULT_DOH_PROVIDER: DohProviderId = 'alidns' + +const VALID_PROVIDERS = new Set(['alidns', 'dnspod', 'cloudflare']) +const MAX_WATCHLIST_ITEMS = 64 + +function isRecord(value: unknown): value is Record { + return Boolean(value) && typeof value === 'object' && !Array.isArray(value) +} + +export function isDohProviderId(value: unknown): value is DohProviderId { + return typeof value === 'string' && VALID_PROVIDERS.has(value as DohProviderId) +} + +export async function loadDohProvider(): Promise { + try { + const stored = await LocalStorage.getItem(DOH_PROVIDER_STORAGE_KEY) + return isDohProviderId(stored) ? stored : DEFAULT_DOH_PROVIDER + } catch (error) { + console.warn('[ssl-domain-check] failed to load DoH provider preference:', error) + return DEFAULT_DOH_PROVIDER + } +} + +export async function saveDohProvider(provider: DohProviderId): Promise { + if (!isDohProviderId(provider)) return + await LocalStorage.setItem(DOH_PROVIDER_STORAGE_KEY, provider) +} + +function sanitizeWatchlistEntry(raw: unknown): WatchlistEntry | null { + if (!isRecord(raw)) return null + if (typeof raw.domain !== 'string' || !raw.domain.trim()) return null + const port = typeof raw.port === 'number' && Number.isInteger(raw.port) && raw.port >= 1 && raw.port <= 65535 ? raw.port : 443 + const domain = raw.domain.trim().toLowerCase() + const target = formatTarget(domain, port) + const entry: WatchlistEntry = { + target, + domain, + port, + addedAt: typeof raw.addedAt === 'string' && raw.addedAt ? raw.addedAt : new Date().toISOString() + } + if (typeof raw.lastCheckedAt === 'string') entry.lastCheckedAt = raw.lastCheckedAt + if (typeof raw.daysRemaining === 'number' && Number.isFinite(raw.daysRemaining)) entry.daysRemaining = raw.daysRemaining + if (typeof raw.isExpired === 'boolean') entry.isExpired = raw.isExpired + if (typeof raw.isExpiringSoon === 'boolean') entry.isExpiringSoon = raw.isExpiringSoon + if (typeof raw.isNotYetValid === 'boolean') entry.isNotYetValid = raw.isNotYetValid + if (typeof raw.isHealthy === 'boolean') entry.isHealthy = raw.isHealthy + if (typeof raw.authorized === 'boolean') entry.authorized = raw.authorized + if (typeof raw.hostnameMatches === 'boolean') entry.hostnameMatches = raw.hostnameMatches + if (typeof raw.authorizationError === 'string') entry.authorizationError = raw.authorizationError + if (typeof raw.protocol === 'string') entry.protocol = raw.protocol + if (typeof raw.cipher === 'string') entry.cipher = raw.cipher + if (typeof raw.issuerName === 'string') entry.issuerName = raw.issuerName + if (typeof raw.validFromIso === 'string') entry.validFromIso = raw.validFromIso + if (typeof raw.validToIso === 'string') entry.validToIso = raw.validToIso + if (typeof raw.lastError === 'string') entry.lastError = raw.lastError + return entry +} + +/** 按紧迫度排序:已过期/异常优先 -> 剩余天数升序 -> 未检测在后 */ +export function sortWatchlist(entries: WatchlistEntry[]): WatchlistEntry[] { + const rank = (item: WatchlistEntry): number => { + if (item.isExpired) return 0 + if (item.lastError || item.isHealthy === false) return 1 + if (typeof item.daysRemaining === 'number') { + if (item.daysRemaining <= 30) return 2 + return 3 + } + return 4 + } + return [...entries].sort((a, b) => { + const diff = rank(a) - rank(b) + if (diff !== 0) return diff + if (typeof a.daysRemaining === 'number' && typeof b.daysRemaining === 'number') { + if (a.daysRemaining !== b.daysRemaining) return a.daysRemaining - b.daysRemaining + } + return a.target.localeCompare(b.target) + }) +} + +export async function loadWatchlist(): Promise { + try { + const stored = await LocalStorage.getItem(WATCHLIST_STORAGE_KEY) + if (!Array.isArray(stored)) return [] + const seen = new Set() + const list: WatchlistEntry[] = [] + for (const item of stored) { + const entry = sanitizeWatchlistEntry(item) + if (!entry || seen.has(entry.target)) continue + seen.add(entry.target) + list.push(entry) + if (list.length >= MAX_WATCHLIST_ITEMS) break + } + return sortWatchlist(list) + } catch (error) { + console.warn('[ssl-domain-check] failed to load watchlist:', error) + return [] + } +} + +export async function saveWatchlist(entries: WatchlistEntry[]): Promise { + const sorted = sortWatchlist(entries).slice(0, MAX_WATCHLIST_ITEMS) + await LocalStorage.setItem(WATCHLIST_STORAGE_KEY, sorted) + return sorted +} + +export function buildWatchlistEntryFromCert( + cert: SslCertHealthReport, + existing?: WatchlistEntry, + nowIso = new Date().toISOString() +): WatchlistEntry { + const target = formatTarget(cert.domain, cert.port) + return { + target, + domain: cert.domain, + port: cert.port, + addedAt: existing?.addedAt ?? nowIso, + lastCheckedAt: nowIso, + daysRemaining: cert.daysRemaining, + isExpired: cert.isExpired, + isExpiringSoon: cert.isExpiringSoon, + isNotYetValid: cert.isNotYetValid, + isHealthy: cert.isHealthy, + authorized: cert.authorized, + hostnameMatches: cert.hostnameMatches, + authorizationError: cert.authorizationError, + protocol: cert.protocol, + cipher: cert.cipher, + issuerName: cert.issuerName, + validFromIso: cert.validFromIso, + validToIso: cert.validToIso, + lastError: undefined + } +} + +export function buildWatchlistEntryFromError( + domain: string, + port: number, + errorMessage: string, + existing?: WatchlistEntry, + nowIso = new Date().toISOString() +): WatchlistEntry { + const target = formatTarget(domain, port) + return { + target, + domain, + port, + addedAt: existing?.addedAt ?? nowIso, + lastCheckedAt: nowIso, + lastError: errorMessage + } +} diff --git a/extensions/ssl-domain-check/src/types.ts b/extensions/ssl-domain-check/src/types.ts index 289bddc7..ba164507 100644 --- a/extensions/ssl-domain-check/src/types.ts +++ b/extensions/ssl-domain-check/src/types.ts @@ -1,13 +1,79 @@ -export type DnsRecordType = 'A' | 'AAAA' | 'CNAME' | 'MX' | 'TXT' +export type DnsRecordType = 'A' | 'AAAA' | 'CNAME' | 'MX' | 'TXT' | 'NS' | 'SOA' | 'CAA' + +export type DohProviderId = 'alidns' | 'dnspod' | 'cloudflare' + +export interface TargetAddress { + domain: string + port: number +} + export interface CertificateSummary { - subjectCN: string; issuerName: string; validFrom: string; validTo: string - serialNumber: string; fingerprint256: string + subjectCN: string + issuerName: string + validFrom: string + validTo: string + serialNumber: string + fingerprint256: string } + export interface SslCertHealthReport extends CertificateSummary { - domain: string; port: number; protocol: string; subjectAltName: string - authorized: boolean; authorizationError: string; hostnameMatches: boolean - chain: CertificateSummary[]; chainTruncated: boolean - validFromIso: string; validToIso: string; daysRemaining: number - isExpired: boolean; isExpiringSoon: boolean; isNotYetValid: boolean; isHealthy: boolean + domain: string + port: number + protocol: string + cipher?: string + subjectAltName: string + authorized: boolean + authorizationError: string + hostnameMatches: boolean + chain: CertificateSummary[] + chainTruncated: boolean + validFromIso: string + validToIso: string + daysRemaining: number + isExpired: boolean + isExpiringSoon: boolean + isNotYetValid: boolean + isHealthy: boolean +} + +export interface DnsRecordEntry { + name: string + type: DnsRecordType + ttl: number + data: string +} + +export interface DnsQueryError { + type: DnsRecordType + message: string +} + +export interface DohResolveResult { + domain: string + provider: DohProviderId + records: DnsRecordEntry[] + errors: DnsQueryError[] + durationMs: number +} + +export interface WatchlistEntry { + target: string + domain: string + port: number + addedAt: string + lastCheckedAt?: string + daysRemaining?: number + isExpired?: boolean + isExpiringSoon?: boolean + isNotYetValid?: boolean + isHealthy?: boolean + authorized?: boolean + hostnameMatches?: boolean + authorizationError?: string + protocol?: string + cipher?: string + issuerName?: string + validFromIso?: string + validToIso?: string + lastError?: string } -export interface DnsRecordEntry { name: string; type: DnsRecordType; ttl: number; data: string } diff --git a/extensions/ssl-domain-check/tests/diagnosis.test.mjs b/extensions/ssl-domain-check/tests/diagnosis.test.mjs index a301eead..1c343962 100644 --- a/extensions/ssl-domain-check/tests/diagnosis.test.mjs +++ b/extensions/ssl-domain-check/tests/diagnosis.test.mjs @@ -1,115 +1,531 @@ import test, { beforeEach, afterEach } from 'node:test' import assert from 'node:assert/strict' import { createHost, mount, tick } from '../../shared/test-harness.mjs' -import Command, { inspectDomainSslCert, evaluateSslCertInfo, resolveDomainDoh, normalizeDomainInput, certificateMarkdown } from '../dist/index.js' +import Command, { + ALL_DNS_RECORD_TYPES, + DOH_PROVIDERS, + DOH_PROVIDER_STORAGE_KEY, + WATCHLIST_STORAGE_KEY, + certificateMarkdown, + evaluateSslCertInfo, + formatFullDiagnosticReport, + formatTarget, + inspectDomainSslCert, + normalizeDomainInput, + parseTargetInput, + resolveDomainDoh, + resolveDomainDohDetailed +} from '../dist/index.js' + const fingerprint = Array(32).fill('AB').join(':') -const leaf = { subjectCN: 'example.com', issuerName: 'Fixture CA', validFrom: '2020-01-01T00:00:00Z', validTo: '2099-01-01T00:00:00Z', serialNumber: '01', fingerprint256: fingerprint } -const certificate = domain => ({ ...leaf, domain, port: 443, protocol: 'TLSv1.3', subjectAltName: `DNS:${domain}`, authorized: true, authorizationError: '', hostnameMatches: true, chain: [leaf], chainTruncated: false }) +const leaf = { + subjectCN: 'example.com', + issuerName: 'Fixture CA', + validFrom: '2020-01-01T00:00:00Z', + validTo: '2099-01-01T00:00:00Z', + serialNumber: '01', + fingerprint256: fingerprint +} +const certificate = (domain, port = 443, overrides = {}) => ({ + ...leaf, + domain, + port, + protocol: 'TLSv1.3', + cipher: 'TLS_AES_256_GCM_SHA384', + subjectAltName: `DNS:${domain}`, + authorized: true, + authorizationError: '', + hostnameMatches: true, + chain: [leaf], + chainTruncated: false, + ...overrides +}) const json = body => new Response(JSON.stringify(body), { headers: { 'content-type': 'application/dns-json' } }) -const defer = () => { let resolve; const promise = new Promise(r => { resolve = r }); return { promise, resolve } } +const defer = () => { + let resolve + const promise = new Promise(r => { + resolve = r + }) + return { promise, resolve } +} + +const DNS_TYPE_CODES = { A: 1, NS: 2, CNAME: 5, SOA: 6, MX: 15, TXT: 16, AAAA: 28, CAA: 257 } + let host, views, requests, originalFetch + beforeEach(() => { - host = createHost(); views = []; requests = []; originalFetch = globalThis.fetch - host.ipc.tls_inspect = async p => p.action === 'cancel' ? { success: true, cancelled: true } : { success: true, cert: certificate(p.domain) } - globalThis.fetch = async url => { const type = new URL(url).searchParams.get('type'); requests.push(type); return json({ Status: 0, Answer: type === 'TXT' ? [{ name: 'example.com.', type: 16, TTL: 0, data: '"verify=literal"' }] : [] }) } + host = createHost() + views = [] + requests = [] + originalFetch = globalThis.fetch + host.ipc.tls_inspect = async p => + p.action === 'cancel' + ? { success: true, cancelled: true } + : { success: true, cert: certificate(p.domain, p.port ?? 443) } + globalThis.fetch = async url => { + const parsed = new URL(url) + const type = parsed.searchParams.get('type') + requests.push({ host: parsed.host, type, url: String(url) }) + if (type === 'TXT') { + return json({ + Status: 0, + Answer: [{ name: 'example.com.', type: 16, TTL: 0, data: '"v=spf1 include:_spf.example.com ~all"' }] + }) + } + if (type === 'NS') { + return json({ + Status: 0, + Answer: [{ name: 'example.com.', type: 2, TTL: 300, data: 'ns1.example.com.' }] + }) + } + if (type === 'CAA') { + return json({ + Status: 0, + Answer: [{ name: 'example.com.', type: 257, TTL: 600, data: '0 issue "letsencrypt.org"' }] + }) + } + return json({ Status: 0, Answer: [] }) + } }) -afterEach(async () => { for (const view of views) view.unmount(); await tick(); globalThis.fetch = originalFetch }) -async function open() { const v = await mount(Command, host); views.push(v); return v } + +afterEach(async () => { + for (const view of views) view.unmount() + await tick() + globalThis.fetch = originalFetch +}) + +async function open() { + const v = await mount(Command, host) + await tick() + views.push(v) + return v +} + const calls = action => host.ipcCalls.filter(([m, p]) => m === 'tls_inspect' && p.action === action) -const run = v => v.run(v.item('ssl-probe-trigger'), '查询域名') -test('打开不联网;输入域名后主动作查询,筛选不重复联网并保留 TXT 引号', async () => { - const v = await open(); assert.equal(requests.length, 0); assert.equal(calls('inspect').length, 0) - assert.equal(v.item('ssl-probe-trigger').props.title, '输入域名后回车诊断') - assert.equal(v.tree().props.filterBar.summaryText, '', '初始工具栏摘要留空,回车提示只在空状态条目出现一次') - assert.equal((JSON.stringify(v.tree().props.searchBarPlaceholder) + v.tree().props.filterBar.summaryText + v.item('ssl-probe-trigger').props.title).match(/回车/g).length, 1) - await run(v); assert.equal(host.lastToast().style, 'FAILURE'); assert.equal(calls('inspect').length, 0) - await v.search('https://EXAMPLE.com/path'); assert.equal(v.item('ssl-probe-trigger').props.title, '诊断 https://EXAMPLE.com/path'); await run(v) - assert.match(v.text(), /查询完成/); assert.match(v.text(), /验证通过/) - assert.equal(calls('inspect')[0][1].domain, 'example.com'); assert.equal(calls('inspect')[0][1].port, 443) - assert.equal(v.tree().props.isShowingDetail, true); assert.deepEqual(requests, ['A', 'AAAA', 'CNAME', 'MX', 'TXT']) - await v.run(v.item('dns-TXT-0'), '复制记录值'); assert.equal(host.clipboard.text, '"verify=literal"') - await v.dropdown('A'); assert.ok(!v.items().some(i => i.props.id.startsWith('dns-'))) - await v.dropdown('TXT'); assert.equal(requests.length, 5) - await v.run(v.item('ssl-certificate'), '复制证书诊断'); assert.match(host.clipboard.text, /证书可信:true/) +const run = v => v.run(v.item('ssl-probe-trigger'), '执行诊断') + +test('打开不联网;输入域名与自定义端口后并发查询 8 类 DNS 与 TLS,筛选不重复联网并保留 TXT 引号', async () => { + const v = await open() + assert.equal(requests.length, 0) + assert.equal(calls('inspect').length, 0) + assert.equal(v.item('ssl-probe-trigger').props.title, '输入域名或 domain:port 后回车诊断') + assert.equal(v.tree().props.filterBar.summaryText, '') + assert.equal(v.tree().props.isShowingDetail, false) + + await run(v) + assert.equal(host.lastToast().style, 'FAILURE') + assert.equal(calls('inspect').length, 0) + + await v.search('api.example.com:8443') + assert.equal(v.item('ssl-probe-trigger').props.title, '诊断 api.example.com:8443') + await run(v) + + assert.match(v.text(), /并发探测完成/) + assert.equal(calls('inspect')[0][1].domain, 'api.example.com') + assert.equal(calls('inspect')[0][1].port, 8443) + assert.equal(v.item('ssl-certificate').props.title, 'api.example.com:8443') + assert.match(v.item('ssl-certificate').props.subtitle, /TLS_AES_256_GCM_SHA384/) + assert.equal(v.tree().props.isShowingDetail, true) + + // 默认使用阿里 DoH 并发查询全部 8 种记录类型 + assert.deepEqual( + requests.map(r => r.type), + [...ALL_DNS_RECORD_TYPES] + ) + assert.ok(requests.every(r => r.host === DOH_PROVIDERS.alidns.host)) + + // 复制单条 TXT 保留原始引号,且全量 DNS 记录(TXT/NS/CAA)直接展示 + await v.run(v.item('dns-TXT-0'), '复制记录值') + assert.equal(host.clipboard.text, '"v=spf1 include:_spf.example.com ~all"') + assert.ok(v.item('dns-NS-1')) + assert.ok(v.item('dns-CAA-2')) + assert.equal(requests.length, ALL_DNS_RECORD_TYPES.length) + + // 复制完整诊断报告与复制证书诊断 + await v.run(v.item('ssl-certificate'), '复制完整诊断报告') + assert.match(host.clipboard.text, /api\.example\.com:8443/) + assert.match(host.clipboard.text, /\[TLS 证书\]/) + assert.match(host.clipboard.text, /\[DNS 记录\]/) + assert.match(host.clipboard.text, /ns1\.example\.com\./) + + await v.run(v.item('ssl-certificate'), '复制证书诊断') + assert.match(host.clipboard.text, /证书可信:true/) assert.ok(!host.ipcCalls.some(([method]) => method === 'dllplugin_call')) }) + +test('DoH 源支持切换(阿里/腾讯/Cloudflare)并持久化至 LocalStorage', async () => { + const v = await open() + await v.dropdown('dnspod') + await tick() + assert.equal(JSON.parse(host.storage.get(DOH_PROVIDER_STORAGE_KEY)), 'dnspod') + + await v.search('example.com') + await run(v) + assert.ok(requests.length === ALL_DNS_RECORD_TYPES.length) + assert.ok(requests.every(r => r.host === DOH_PROVIDERS.dnspod.host)) + + // 切到 Cloudflare 并重新挂载,确认持久化恢复且打开不联网 + await v.dropdown('cloudflare') + await tick() + assert.equal(JSON.parse(host.storage.get(DOH_PROVIDER_STORAGE_KEY)), 'cloudflare') + + requests = [] + const v2 = await open() + assert.equal(requests.length, 0) + assert.equal(v2.tree().props.searchBarAccessory.props.value, 'cloudflare') + await v2.search('example.com') + await run(v2) + assert.ok(requests.every(r => r.host === DOH_PROVIDERS.cloudflare.host)) +}) + +test('并发 DoH 查询使用 Promise.allSettled,真正并发发起请求且部分失败不丢弃已成功记录', async () => { + let inflight = 0 + let maxInflight = 0 + const gates = [] + const concurrentFetch = async url => { + const type = new URL(url).searchParams.get('type') + inflight++ + maxInflight = Math.max(maxInflight, inflight) + const gate = defer() + gates.push({ type, gate }) + if (gates.length === 3) { + for (const item of gates) item.gate.resolve() + } + await gate.promise + inflight-- + if (type === 'CAA') return new Response('unsupported', { status: 502 }) + return json({ + Status: 0, + Answer: [{ name: 'example.com.', type: DNS_TYPE_CODES[type], TTL: 60, data: `val-${type}` }] + }) + } + + const res = await resolveDomainDohDetailed('example.com', ['A', 'TXT', 'CAA'], { + fetchImpl: concurrentFetch, + provider: 'alidns' + }) + assert.equal(maxInflight, 3, '3 类 DNS 必须同时并发发起而非串行') + assert.equal(res.records.length, 2) + assert.equal(res.errors.length, 1) + assert.equal(res.errors[0].type, 'CAA') + assert.match(res.errors[0].message, /HTTP 502/) +}) + +test('关注域名到期盯盘:持久化至 LocalStorage,按过期/临期/正常标注与排序,并支持刷新', async () => { + const now = Date.now() + const isoInDays = days => new Date(now + days * 86400000).toISOString() + + host.ipc.tls_inspect = async p => { + if (p.action === 'cancel') return { success: true, cancelled: true } + if (p.domain === 'expired.example.com') { + return { success: true, cert: certificate(p.domain, p.port ?? 443, { validTo: isoInDays(-5) }) } + } + if (p.domain === 'soon.example.com') { + return { success: true, cert: certificate(p.domain, p.port ?? 443, { validTo: isoInDays(12) }) } + } + if (p.domain === 'warn25.example.com') { + return { success: true, cert: certificate(p.domain, p.port ?? 443, { validTo: isoInDays(25) }) } + } + return { success: true, cert: certificate(p.domain, p.port ?? 443, { validTo: isoInDays(120) }) } + } + + const v = await open() + for (const target of ['healthy.example.com', 'soon.example.com:8443', 'expired.example.com', 'warn25.example.com']) { + await v.search(target) + await run(v) + await v.run(v.item('ssl-certificate'), '加入关注') + await tick() + } + + const stored = JSON.parse(host.storage.get(WATCHLIST_STORAGE_KEY)) + assert.equal(stored.length, 4) + + // 重新打开插件:不发起任何联网请求,直接从 LocalStorage 渲染关注列表并按紧迫度排序 + requests = [] + const inspectBefore = calls('inspect').length + const v2 = await open() + assert.equal(requests.length, 0) + assert.equal(calls('inspect').length, inspectBefore) + assert.equal(v2.tree().props.isShowingDetail, true) + + const watchItems = v2.items().filter(i => i.props.id.startsWith('watch-')) + assert.deepEqual( + watchItems.map(i => i.props.title), + ['expired.example.com', 'soon.example.com:8443', 'warn25.example.com', 'healthy.example.com'] + ) + // 已过期红色高亮 + assert.equal(watchItems[0].props.accessories[0].tag.value, '已过期') + assert.equal(watchItems[0].props.accessories[0].tag.color, 'rgb(255, 69, 58)') + // ≤30 天临期红色警示(遵守 90% 灰阶单色原则,高危告警用 Color.Red) + assert.match(watchItems[1].props.accessories[0].tag.value, /临期/) + assert.equal(watchItems[1].props.accessories[0].tag.color, 'rgb(255, 69, 58)') + assert.match(watchItems[2].props.accessories[0].tag.value, /临期/) + assert.equal(watchItems[2].props.accessories[0].tag.color, 'rgb(255, 69, 58)') + // >30 天正常使用中性灰阶标签 + assert.match(watchItems[3].props.accessories[0].tag, /正常/) + + // 移出关注 + await v2.run(v2.item('watch-warn25.example.com'), '移出关注') + await tick() + assert.equal(JSON.parse(host.storage.get(WATCHLIST_STORAGE_KEY)).length, 3) + + // 批量刷新关注域名 + await v2.run(v2.item('watch-expired.example.com'), '刷新关注列表') + await tick() + assert.equal(calls('inspect').length, inspectBefore + 3) +}) + +test('TLS 失败但 DNS 成功时右侧 Detail 依然开启,完整呈现原始错误与长 TXT 记录', async () => { + const v = await open() + host.ipc.tls_inspect = async () => { + throw new Error('证书握手失败:ECONNREFUSED') + } + await v.search('example.com') + await run(v) + + assert.equal(v.tree().props.isShowingDetail, true, '即使 TLS 失败,右侧 Detail 也必须开启以展示错误和长 TXT') + assert.match(v.text(), /部分失败/) + assert.match(v.item('tls-error').props.subtitle, /握手失败/) + assert.match(v.item('tls-error').props.detail.props.markdown, /ECONNREFUSED/) + assert.ok(!v.items().some(i => i.props.id === 'ssl-certificate')) + assert.ok(v.item('dns-TXT-0')) + assert.match(v.item('dns-TXT-0').props.detail.props.markdown, /v=spf1 include:_spf\.example\.com ~all/) + + globalThis.fetch = async () => json({ Status: 2 }) + await run(v) + assert.match(v.tree().props.filterBar.summaryText, /查询失败/) + assert.equal(v.tree().props.isShowingDetail, true) + assert.ok(v.item('dns-error')) + + host.ipc.tls_inspect = async p => ({ success: true, cert: certificate(p.domain, p.port ?? 443) }) + await run(v) + assert.ok(v.item('ssl-certificate')) + assert.match(v.text(), /部分失败/) +}) + test('切换域名立即清空证书和 DNS,取消旧操作,迟到结果不能覆盖新结果', async () => { - const v = await open(); await v.search('example.com'); await run(v) - const pending = defer(), normal = host.ipc.tls_inspect - host.ipc.tls_inspect = p => p.action === 'inspect' && p.domain === 'old.example.com' ? pending.promise : normal(p) - await v.search('old.example.com'); const older = run(v); await tick(); await run(v) + const v = await open() + await v.search('example.com') + await run(v) + + const pending = defer() + const normal = host.ipc.tls_inspect + host.ipc.tls_inspect = p => (p.action === 'inspect' && p.domain === 'old.example.com' ? pending.promise : normal(p)) + + await v.search('old.example.com') + const older = run(v) + await tick() + await run(v) assert.equal(calls('inspect').length, 2) - await v.search('new.example.com'); assert.ok(!v.items().some(i => i.props.id === 'ssl-certificate')); assert.equal(v.tree().props.isLoading, false) - await run(v); pending.resolve({ success: true, cert: certificate('old.example.com') }); await older - assert.equal(v.item('ssl-certificate').props.title, 'new.example.com'); assert.equal(calls('cancel').length, 1) + + await v.search('new.example.com') + assert.ok(!v.items().some(i => i.props.id === 'ssl-certificate')) + assert.equal(v.tree().props.isLoading, false) + + await run(v) + pending.resolve({ success: true, cert: certificate('old.example.com') }) + await older + assert.equal(v.item('ssl-certificate').props.title, 'new.example.com') + assert.equal(calls('cancel').length, 1) assert.equal(v.tree().props.isLoading, false) }) + test('手动取消和卸载均取消 TLS,在途结果不回写、不报成功', async () => { - const pending = defer(); host.ipc.tls_inspect = p => p.action === 'inspect' ? pending.promise : { success: true, cancelled: true } - const v = await open(); await v.search('example.com'); const work = run(v); await tick() - v.tree().props.filterBar.actions[0].onAction(); await tick(); assert.match(v.text(), /查询已取消/) - const second = run(v); await tick(); v.unmount(); pending.resolve({ success: true, cert: certificate('example.com') }); await Promise.all([work, second]) - assert.equal(calls('cancel').length, 2); assert.equal(host.toasts.length, 0) -}) -test('TLS 或 DNS 单项失败明确区分,旧证书不能留存;两项失败不能报完成', async () => { - const v = await open(); await v.search('example.com'); await run(v) - host.ipc.tls_inspect = async () => { throw Error('证书握手失败') }; await run(v) - assert.match(v.text(), /部分查询失败/); assert.match(v.item('tls-error').props.subtitle, /握手失败/) - assert.ok(!v.items().some(i => i.props.id === 'ssl-certificate')); assert.ok(v.item('dns-TXT-0')) - globalThis.fetch = async () => json({ Status: 2 }); await run(v); assert.match(v.tree().props.filterBar.summaryText, /查询失败/); assert.ok(v.item('dns-error')) - host.ipc.tls_inspect = async p => ({ success: true, cert: certificate(p.domain) }); await run(v) - assert.ok(v.item('ssl-certificate')); assert.match(v.text(), /部分查询失败/) -}) -test('真实状态评价:不可信、名称不符、过期和未来证书不能标为健康', async () => { - const clean = certificate('example.com'), now = Date.parse('2026-01-01T00:00:00Z') + const pending = defer() + host.ipc.tls_inspect = p => (p.action === 'inspect' ? pending.promise : { success: true, cancelled: true }) + const v = await open() + await v.search('example.com') + const work = run(v) + await tick() + v.tree().props.filterBar.actions[0].onAction() + await tick() + assert.match(v.text(), /查询已取消/) + + const second = run(v) + await tick() + v.unmount() + pending.resolve({ success: true, cert: certificate('example.com') }) + await Promise.all([work, second]) + assert.equal(calls('cancel').length, 2) + assert.equal(host.toasts.length, 0) +}) + +test('真实状态评价:不可信、名称不符、过期和未来证书不能标为健康,≤30 天标为即将到期', async () => { + const clean = certificate('example.com') + const now = Date.parse('2026-01-01T00:00:00Z') for (const cert of [ { ...clean, authorized: false, authorizationError: 'SELF_SIGNED_CERT' }, { ...clean, authorized: false, hostnameMatches: false, authorizationError: 'NAME_MISMATCH' }, { ...clean, validTo: '2021-01-01T00:00:00Z' }, - { ...clean, validFrom: '2027-01-01T00:00:00Z' }, - ]) assert.equal(evaluateSslCertInfo(cert, now).isHealthy, false) - host.ipc.tls_inspect = async () => ({ success: true, cert: { ...clean, authorized: false, authorizationError: 'SELF_SIGNED_CERT' } }) - const v = await open(); await v.search('example.com'); await run(v) - assert.match(v.text(), /信任验证未通过/); assert.ok(!v.text().includes('"value":"验证通过"')) - const markdown = certificateMarkdown(evaluateSslCertInfo({ ...clean, issuerName: '```\n![bad](https://example.invalid/leak)' }, now)) - assert.ok(markdown.startsWith('````text\n')); assert.ok(markdown.endsWith('\n````')); assert.ok(markdown.includes('![bad]')) -}) -test('缺接口、失败回执、错目标以及缺失或畸形证书字段全部拒绝', async () => { - const good = certificate('example.com') - for (const change of [{ protocol: '' }, { validTo: 'invalid' }, { chain: [] }, { fingerprint256: '' }, { authorized: true, authorizationError: 'ERROR' }, { hostnameMatches: undefined }, { port: 0 }]) assert.throws(() => evaluateSslCertInfo({ ...good, ...change })) - host.ipc.tls_inspect = async () => ({ success: true, cert: certificate('different.example.com') }); await assert.rejects(inspectDomainSslCert('example.com'), /其他目标/) - host.ipc.tls_inspect = async () => ({ success: false }); await assert.rejects(inspectDomainSslCert('example.com'), /未确认/) - globalThis.__ztoolsElectron = {}; await assert.rejects(inspectDomainSslCert('example.com'), /升级客户端/) - const abort = new AbortController(); abort.abort(); await assert.rejects(inspectDomainSslCert('example.com', { signal: abort.signal })) - for (const domain of ['', 'bad host', 'https://u:p@example.com', 'file:///tmp/a', '-bad.example.com', 'https://example.com:8443']) assert.throws(() => normalizeDomainInput(domain)) + { ...clean, validFrom: '2027-01-01T00:00:00Z' } + ]) { + assert.equal(evaluateSslCertInfo(cert, now).isHealthy, false) + } + + const expiring25 = evaluateSslCertInfo({ ...clean, validTo: '2026-01-26T00:00:00Z' }, now) + assert.equal(expiring25.isHealthy, true) + assert.equal(expiring25.isExpiringSoon, true) + assert.equal(expiring25.daysRemaining, 25) + + const healthy60 = evaluateSslCertInfo({ ...clean, validTo: '2026-03-02T00:00:00Z' }, now) + assert.equal(healthy60.isHealthy, true) + assert.equal(healthy60.isExpiringSoon, false) + + host.ipc.tls_inspect = async () => ({ + success: true, + cert: { ...clean, authorized: false, authorizationError: 'SELF_SIGNED_CERT' } + }) + const v = await open() + await v.search('example.com') + await run(v) + assert.match(v.text(), /不可信/) + assert.ok(!v.text().includes('"value":"验证通过"')) + + const markdown = certificateMarkdown( + evaluateSslCertInfo({ ...clean, issuerName: '```\n![bad](https://example.invalid/leak)' }, now) + ) + assert.ok(markdown.startsWith('````text\n')) + assert.ok(markdown.endsWith('\n````')) + assert.ok(markdown.includes('![bad]')) +}) + +test('输入解析支持 domain:port,缺接口、失败回执、错目标以及畸形证书字段全部拒绝', async () => { + assert.deepEqual(parseTargetInput('example.com'), { domain: 'example.com', port: 443 }) + assert.deepEqual(parseTargetInput('api.example.com:8443'), { domain: 'api.example.com', port: 8443 }) + assert.deepEqual(parseTargetInput('https://EXAMPLE.com:465/path'), { domain: 'example.com', port: 465 }) + assert.deepEqual(parseTargetInput('https://例子.测试:8443/'), { + domain: 'xn--fsqu00a.xn--0zwm56d', + port: 8443 + }) + assert.equal(formatTarget('example.com', 443), 'example.com') + assert.equal(formatTarget('example.com', 8443), 'example.com:8443') + + for (const bad of [ + '', + 'bad host', + 'https://u:p@example.com', + 'file:///tmp/a', + '-bad.example.com', + 'example.com:0', + 'example.com:65536', + 'example.com:abc' + ]) { + assert.throws(() => parseTargetInput(bad), `应拒绝非法目标: ${bad}`) + } assert.equal(normalizeDomainInput('https://例子.测试/'), 'xn--fsqu00a.xn--0zwm56d') + + const good = certificate('example.com') + for (const change of [ + { protocol: '' }, + { validTo: 'invalid' }, + { chain: [] }, + { fingerprint256: '' }, + { authorized: true, authorizationError: 'ERROR' }, + { hostnameMatches: undefined }, + { port: 0 } + ]) { + assert.throws(() => evaluateSslCertInfo({ ...good, ...change })) + } + + host.ipc.tls_inspect = async () => ({ success: true, cert: certificate('different.example.com') }) + await assert.rejects(inspectDomainSslCert('example.com'), /其他目标/) + host.ipc.tls_inspect = async () => ({ success: false }) + await assert.rejects(inspectDomainSslCert('example.com'), /未确认/) + globalThis.__ztoolsElectron = {} + await assert.rejects(inspectDomainSslCert('example.com'), /升级客户端/) + const abort = new AbortController() + abort.abort() + await assert.rejects(inspectDomainSslCert('example.com', { signal: abort.signal })) }) + test('DNS 真空结果与 NXDOMAIN、服务错误、畸形字段及过大内容区别处理', async () => { assert.deepEqual(await resolveDomainDoh('example.com', ['A'], { fetchImpl: async () => json({ Status: 0 }) }), []) - for (const payload of [{ Status: 3 }, { Status: 2 }, {}, { Status: 0, Answer: {} }, { Status: 0, Answer: [{ name: 'example.com', type: 1, TTL: -1, data: '127.0.0.1' }] }]) await assert.rejects(resolveDomainDoh('example.com', ['A'], { fetchImpl: async () => json(payload) })) + for (const payload of [ + { Status: 3 }, + { Status: 2 }, + {}, + { Status: 0, Answer: {} }, + { Status: 0, Answer: [{ name: 'example.com', type: 1, TTL: -1, data: '127.0.0.1' }] } + ]) { + await assert.rejects(resolveDomainDoh('example.com', ['A'], { fetchImpl: async () => json(payload) })) + } await assert.rejects(resolveDomainDoh('example.com', ['toString']), /参数无效/) - for (const Answer of [undefined, [{ name: 'example.com.', type: 1, TTL: 60, data: '127.0.0.1' }]]) await assert.rejects(resolveDomainDoh('example.com', ['A'], { fetchImpl: async () => json({ Status: 0, TC: true, Answer }) }), /截断/) - await assert.rejects(resolveDomainDoh('example.com', ['A'], { fetchImpl: async () => new Response('x'.repeat(262145)) }), /大小限制/) - await assert.rejects(resolveDomainDoh('example.com', ['A'], { fetchImpl: async () => new Response('no', { status: 500 }) }), /HTTP 500/) + await assert.rejects(resolveDomainDoh('example.com', ['A'], { provider: 'invalid' }), /参数无效/) + for (const Answer of [undefined, [{ name: 'example.com.', type: 1, TTL: 60, data: '127.0.0.1' }]]) { + await assert.rejects( + resolveDomainDoh('example.com', ['A'], { fetchImpl: async () => json({ Status: 0, TC: true, Answer }) }), + /截断/ + ) + } + await assert.rejects( + resolveDomainDoh('example.com', ['A'], { fetchImpl: async () => new Response('x'.repeat(262145)) }), + /大小限制/ + ) + await assert.rejects( + resolveDomainDoh('example.com', ['A'], { fetchImpl: async () => new Response('no', { status: 500 }) }), + /HTTP 500/ + ) }) + test('DNS 超时与取消会中止网络请求', async () => { - const abortable = async (_url, { signal }) => new Promise((_, reject) => { signal.addEventListener('abort', () => reject(signal.reason), { once: true }) }) + const abortable = async (_url, { signal }) => + new Promise((_, reject) => { + signal.addEventListener('abort', () => reject(signal.reason), { once: true }) + }) await assert.rejects(resolveDomainDoh('example.com', ['A'], { fetchImpl: abortable, timeoutMs: 1000 }), /超时/) - const controller = new AbortController(), pending = resolveDomainDoh('example.com', ['A'], { fetchImpl: abortable, signal: controller.signal }) - controller.abort(); await assert.rejects(pending, /取消/) + const controller = new AbortController() + const pending = resolveDomainDoh('example.com', ['A'], { fetchImpl: abortable, signal: controller.signal }) + controller.abort() + await assert.rejects(pending, /取消/) }) + test('失败行回车即重新查询,可复制失败原因;重试成功后失败行消失', async () => { - host.ipc.tls_inspect = async p => { if (p.action === 'cancel') return { success: true }; throw new Error('TLS 连接失败:ECONNREFUSED') } - const v = await open(); await v.search('example.com'); await run(v) - assert.equal(v.actions(v.item('tls-error'))[0].props.title, '重新查询') - await v.run(v.item('tls-error'), '复制失败原因'); assert.match(host.clipboard.text, /ECONNREFUSED/) - host.ipc.tls_inspect = async p => p.action === 'cancel' ? { success: true } : { success: true, cert: certificate(p.domain) } - await v.run(v.item('tls-error'), '重新查询'); await tick() - assert.ok(v.item('ssl-certificate')); assert.ok(!v.items().some(i => i.props.id === 'tls-error')) + host.ipc.tls_inspect = async p => { + if (p.action === 'cancel') return { success: true } + throw new Error('TLS 连接失败:ECONNREFUSED') + } + const v = await open() + await v.search('example.com') + await run(v) + assert.equal(v.actions(v.item('tls-error'))[0].props.title, '重新诊断') + await v.run(v.item('tls-error'), '复制失败原因') + assert.match(host.clipboard.text, /ECONNREFUSED/) + + host.ipc.tls_inspect = async p => + p.action === 'cancel' ? { success: true } : { success: true, cert: certificate(p.domain, p.port ?? 443) } + await v.run(v.item('tls-error'), '重新诊断') + await tick() + assert.ok(v.item('ssl-certificate')) + assert.ok(!v.items().some(i => i.props.id === 'tls-error')) }) test('查询完成后改输入:清掉旧结果与摘要,不回填重复的回车提示', async () => { - const v = await open(); await v.search('example.com'); await run(v); assert.match(v.tree().props.filterBar.summaryText, /查询完成/) - await v.search('example.org'); assert.equal(v.tree().props.filterBar.summaryText, ''); assert.deepEqual(v.items().map(i => i.props.id), ['ssl-probe-trigger']) - assert.equal(v.item('ssl-probe-trigger').props.title, '诊断 example.org') + const v = await open() + await v.search('example.com') + await run(v) + assert.match(v.tree().props.filterBar.summaryText, /并发探测完成/) + await v.search('example.org:8443') + assert.equal(v.tree().props.filterBar.summaryText, '') + assert.deepEqual( + v.items().map(i => i.props.id), + ['ssl-probe-trigger'] + ) + assert.equal(v.item('ssl-probe-trigger').props.title, '诊断 example.org:8443') +}) + +test('formatFullDiagnosticReport 输出完整 TLS 与 DNS 报告', () => { + const report = formatFullDiagnosticReport({ + target: 'api.example.com:8443', + provider: 'alidns', + durationMs: 215, + cert: evaluateSslCertInfo(certificate('api.example.com', 8443), Date.parse('2026-01-01T00:00:00Z')), + certError: '', + records: [{ name: 'api.example.com', type: 'A', ttl: 120, data: '93.184.216.34' }], + dnsError: '', + dnsPartialErrors: [{ type: 'CAA', message: 'HTTP 502' }] + }) + assert.match(report, /api\.example\.com:8443/) + assert.match(report, /215ms/) + assert.match(report, /93\.184\.216\.34/) + assert.match(report, /\[DNS CAA\] HTTP 502/) }) diff --git a/extensions/svg-icon-studio/plugin.json b/extensions/svg-icon-studio/plugin.json index ce05434b..b0626d8c 100644 --- a/extensions/svg-icon-studio/plugin.json +++ b/extensions/svg-icon-studio/plugin.json @@ -1,7 +1,7 @@ { "id": "svg-icon-studio", "name": "SVG预览与压缩", - "version": "1.0.11", + "version": "1.0.12", "minAppVersion": "1.1.8.0", "description": "静态 SVG 校验、清理与代码预览,保留文字和数值精度,导出 React TSX / Vue 3 SFC / Data URI", "author": "ZTools Team", diff --git a/extensions/svg-icon-studio/src/i18n.ts b/extensions/svg-icon-studio/src/i18n.ts index 1a5b9564..18cae392 100644 --- a/extensions/svg-icon-studio/src/i18n.ts +++ b/extensions/svg-icon-studio/src/i18n.ts @@ -26,6 +26,9 @@ export const t = createTranslator( errExpandedNodesLimit: "SVG 引用展开超过 20000 个节点上限", errEmptySvg: "SVG 源码不能为空", errSizeLimit: "SVG 源码不能超过 256 KiB", + errPngRendererUnavailable: "当前运行环境不支持 Canvas/Image 渲染,无法光栅化导出 PNG", + errPngRenderFailed: "SVG 渲染为 PNG 失败,请检查 SVG 尺寸与语法", + errPngInvalidSize: "PNG 输出尺寸无效或超出 4096px 限制", vueSfcComment: "// 静态 SVG 图标;文本按字面内容保留。", viewBoxUnset: "未设置", errHostUnavailable: "当前环境不支持 {method}", @@ -33,41 +36,110 @@ export const t = createTranslator( errHostCallFailed: "{method} 调用失败", dialogPickTitle: "选择 SVG 图标文件", dialogPickFilter: "SVG 文件|*.svg;svg", + dialogSaveSvgTitle: "另存为优化后的 SVG", + dialogSaveSvgFilter: "SVG 文件|svg", + dialogSaveTsxTitle: "另存为 React TSX 组件", + dialogSaveTsxFilter: "TypeScript React|tsx", + dialogSaveVueTitle: "另存为 Vue 3 SFC 组件", + dialogSaveVueFilter: "Vue 单文件组件|vue", + dialogSaveUriTitle: "另存为 Data URI 文本", + dialogSaveUriFilter: "文本文件|txt", + dialogSavePngTitle: "另存为 PNG 图片", + dialogSavePngFilter: "PNG 图片|png", errInvalidSvgFile: "请选择 .svg 图标文件", toastValidationFailed: "SVG 校验未通过", formNavTitle: "编辑 SVG 源码", - formSubmitTitle: "校验并生成", + formSubmitTitle: "校验并压缩", formFieldTitle: "SVG 源码", - formDesc: "保留多行文字和空白;最多 256 KiB。{modEnter} 校验并生成,Esc 取消修改。", - previewAlt: "清理后的 SVG 预览", - toastLoadedSuccess: "已载入并校验 SVG", + formComponentNameTitle: "React 组件名", + formComponentNamePlaceholder: "默认 SvgIcon(自动规范为 PascalCase)", + formDesc: "保留 内文字与空白;最多 256 KiB。{modEnter} 校验并压缩,Esc 取消修改。", + previewAlt: "SVG 实时预览", + toastLoadedSuccess: "已载入并完成压缩", toastLoadFailed: "未能载入有效 SVG", toastDropInvalid: "请拖入 .svg 图标文件", toastPasteInvalid: "请粘贴包含 {opt} (节省 {pct}%)", + metaSizeAdded: "{orig} -> {opt} (增加 {pct}%)", + metaGeometry: "几何信息", + metaGeometryValue: "viewBox {viewBox} | {width}×{height} | 路径 {paths} 条", + metaCleanup: "净化压缩", + metaCleanupNone: "结构已精简,无需额外清理", + metaCleanupComments: "注释({n})", + metaCleanupMetadata: "元数据({n})", + metaCleanupEmptyGroups: "空({n})", + metaCleanupDefaultAttrs: "默认属性({n})", + metaCleanupXmlns: "冗余命名空间({n})", + metaCleanupWhitespace: "空白节点({n})", + metaCleanupRounded: "精度收敛({n})", + metaCleanupCurrentColor: "currentColor({n})", + metaCleanupRemovedSecurity: "安全移除({n})", + metaParams: "当前参数", + metaParamsValue: "精度 {precision} · currentColor {cc} · PNG {scale}x", + searchPlaceholder: "过滤导出格式或压缩参数…", + actionPickFile: "选择 SVG 文件", + actionLoadClipboard: "读取剪贴板", actionEditSource: "编辑源码", - actionPickFile: "选择文件", emptyErrorTitle: "SVG 无法处理", - emptyReadyTitle: "载入 SVG 源码开始", - emptyReadySub: "仅在本地处理静态 SVG,支持最多 256 KiB", - emptyReadyDetail: "按 Enter 从剪贴板载入完整 SVG;按 {modEnter} 打开多行源码编辑器。\n\n保留文字、空白与坐标精度;移除的内容会列出提示。复杂样式或无效 XML 会停止处理。", - actionLoadFromClipboard: "从剪贴板载入 SVG", + emptyReadyTitle: "载入 SVG 源码开始预览与压缩", + emptyReadySub: "点击上方「选择 SVG 文件」「读取剪贴板」「编辑源码」,或直接拖入 .svg 文件(最大 256 KiB)", + emptyReadyDetail: "仅在本机离线处理静态 SVG(最大 256 KiB)。支持路径数值精度压缩、默认属性与空组清理、透明/浅/深色背景预览,以及 React TSX / Vue 3 SFC / Data URI / 1x–3x PNG 导出与文件另存为。", + actionLoadFromClipboard: "读取剪贴板 SVG", actionPickSvgFile: "选择 SVG 文件…", - warningsHeading: "清理提示(可能改变外观):\n\n{warnings}\n\n", + warningsHeading: "安全净化提示(可能改变外观):\n\n{warnings}\n\n", actionCopyPrefix: "复制{title}", - actionCopyBase64Uri: "复制 Base64 Data URI" + actionSaveAsFile: "另存为文件…", + actionCopyBase64Uri: "复制 Base64 Data URI", + actionCopyPngImage: "复制 PNG 图片 ({scale}x)", + actionSavePngFile: "另存为 PNG 文件 ({scale}x)…", + actionCopyPngDataUrl: "复制 PNG Data URL ({scale}x)", + actionTogglePrecision: "切换浮点精度", + actionToggleCurrentColor: "切换 currentColor", + actionCyclePngScale: "切换 PNG 倍率 (1x / 2x / 3x)", + submenuOptions: "压缩与导出参数", + kwSvg: "svg svgo xml minify compress 优化 压缩", + kwReact: "react tsx jsx component 组件", + kwVue: "vue sfc template 组件", + kwUri: "uri data css base64", + kwPng: "png image raster export 图片 导出", + kwPrecision: "precision float decimal 精度 小数", + kwCurrentColor: "currentcolor color fill stroke 颜色", + kwPngScale: "png scale 1x 2x 3x 倍率 分辨率", + pngPreviewDetail: "### 透明背景 PNG 光栅化导出\n\n- **输出倍率**:`{scale}x`\n- **目标像素**:`{width} × {height} px`(透明底)\n- **主动作(Enter)**:实时光栅化并复制 PNG 位图到剪贴板,可直接粘贴进聊天工具或文档\n- **次动作({modEnter})**:另存为 `.png` 文件\n- **更多操作**:可在动作面板复制 `data:image/png;base64,...` 或切换 `1x / 2x / 3x` 倍率" }, "en-US": { errUnsupportedDtd: "DTD and entity definitions are not supported; use standalone static SVG", @@ -93,6 +165,9 @@ export const t = createTranslator( errExpandedNodesLimit: "SVG reference expansion exceeds 20000 nodes", errEmptySvg: "SVG source cannot be empty", errSizeLimit: "SVG source cannot exceed 256 KiB", + errPngRendererUnavailable: "Canvas/Image renderer is unavailable in the current environment; cannot rasterize PNG", + errPngRenderFailed: "Failed to rasterize SVG to PNG; please verify SVG dimensions and syntax", + errPngInvalidSize: "PNG output dimensions are invalid or exceed the 4096px limit", vueSfcComment: "// Static SVG icon; text content preserved literally.", viewBoxUnset: "Not set", errHostUnavailable: "{method} is not supported in the current environment", @@ -100,41 +175,110 @@ export const t = createTranslator( errHostCallFailed: "{method} call failed", dialogPickTitle: "Select SVG Icon File", dialogPickFilter: "SVG Files|*.svg;svg", + dialogSaveSvgTitle: "Save Optimized SVG As", + dialogSaveSvgFilter: "SVG File|svg", + dialogSaveTsxTitle: "Save React TSX Component As", + dialogSaveTsxFilter: "TypeScript React|tsx", + dialogSaveVueTitle: "Save Vue 3 SFC Component As", + dialogSaveVueFilter: "Vue Single-File Component|vue", + dialogSaveUriTitle: "Save Data URI Text As", + dialogSaveUriFilter: "Text File|txt", + dialogSavePngTitle: "Save PNG Image As", + dialogSavePngFilter: "PNG Image|png", errInvalidSvgFile: "Please select a .svg icon file", toastValidationFailed: "SVG validation failed", formNavTitle: "Edit SVG Source", - formSubmitTitle: "Validate & Generate", + formSubmitTitle: "Validate & Optimize", formFieldTitle: "SVG Source", - formDesc: "Preserves multiline text and whitespace; max 256 KiB. {modEnter} to validate & generate, Esc to cancel.", - previewAlt: "Cleaned SVG Preview", - toastLoadedSuccess: "SVG loaded and validated", + formComponentNameTitle: "React Component Name", + formComponentNamePlaceholder: "Default SvgIcon (normalized to PascalCase)", + formDesc: "Preserves text and whitespace inside ; max 256 KiB. {modEnter} to validate & optimize, Esc to cancel.", + previewAlt: "Live SVG Preview", + toastLoadedSuccess: "SVG loaded and optimized", toastLoadFailed: "Failed to load valid SVG", toastDropInvalid: "Please drop a .svg icon file", toastPasteInvalid: "Please paste source text containing {opt} (saved {pct}%)", + metaSizeAdded: "{orig} -> {opt} (+{pct}%)", + metaGeometry: "Geometry", + metaGeometryValue: "viewBox {viewBox} | {width}×{height} | {paths} path(s)", + metaCleanup: "Sanitize & Optimize", + metaCleanupNone: "Already clean; no redundant items removed", + metaCleanupComments: "comments({n})", + metaCleanupMetadata: "metadata({n})", + metaCleanupEmptyGroups: "empty ({n})", + metaCleanupDefaultAttrs: "default attrs({n})", + metaCleanupXmlns: "unused xmlns({n})", + metaCleanupWhitespace: "whitespace({n})", + metaCleanupRounded: "rounded nums({n})", + metaCleanupCurrentColor: "currentColor({n})", + metaCleanupRemovedSecurity: "sanitized({n})", + metaParams: "Active Options", + metaParamsValue: "Precision {precision} · currentColor {cc} · PNG {scale}x", + searchPlaceholder: "Filter export formats or optimization options…", + actionPickFile: "Select SVG File", + actionLoadClipboard: "Read Clipboard", actionEditSource: "Edit Source", - actionPickFile: "Select File", emptyErrorTitle: "Unable to Process SVG", - emptyReadyTitle: "Load SVG Source to Begin", - emptyReadySub: "Processes static SVG locally, up to 256 KiB", - emptyReadyDetail: "Press Enter to load full SVG from clipboard; press {modEnter} to open multiline source editor.\n\nPreserves text, whitespace, and coordinate precision; removed items are listed. Complex styles or invalid XML will stop processing.", - actionLoadFromClipboard: "Load SVG from Clipboard", + emptyReadyTitle: "Load an SVG to Preview & Optimize", + emptyReadySub: "Use Select SVG File, Read Clipboard, Edit Source, or drop a .svg file (max 256 KiB)", + emptyReadyDetail: "Processes static SVG locally offline (max 256 KiB). Supports path float precision rounding, default attribute & empty group cleanup, checkerboard/light/dark preview backgrounds, and React TSX / Vue 3 SFC / Data URI / 1x–3x PNG export with Save As.", + actionLoadFromClipboard: "Read SVG from Clipboard", actionPickSvgFile: "Select SVG File…", - warningsHeading: "Cleanup warnings (may affect appearance):\n\n{warnings}\n\n", + warningsHeading: "Sanitization warnings (may affect appearance):\n\n{warnings}\n\n", actionCopyPrefix: "Copy {title}", - actionCopyBase64Uri: "Copy Base64 Data URI" + actionSaveAsFile: "Save As File…", + actionCopyBase64Uri: "Copy Base64 Data URI", + actionCopyPngImage: "Copy PNG Image ({scale}x)", + actionSavePngFile: "Save PNG File ({scale}x)…", + actionCopyPngDataUrl: "Copy PNG Data URL ({scale}x)", + actionTogglePrecision: "Cycle Float Precision", + actionToggleCurrentColor: "Toggle currentColor", + actionCyclePngScale: "Cycle PNG Scale (1x / 2x / 3x)", + submenuOptions: "Optimization & Export Options", + kwSvg: "svg svgo xml minify compress optimize", + kwReact: "react tsx jsx component", + kwVue: "vue sfc template component", + kwUri: "uri data css base64", + kwPng: "png image raster export", + kwPrecision: "precision float decimal digits", + kwCurrentColor: "currentcolor color fill stroke", + kwPngScale: "png scale 1x 2x 3x resolution", + pngPreviewDetail: "### Transparent PNG Rasterization\n\n- **Export Scale**: `{scale}x`\n- **Output Dimensions**: `{width} × {height} px` (transparent background)\n- **Primary Action (Enter)**: Rasterize and copy PNG image to clipboard for pasting into chats or slides\n- **Secondary Action ({modEnter})**: Save as `.png` file\n- **More Actions**: Copy `data:image/png;base64,...` or switch `1x / 2x / 3x` scale in Action Panel" } }, { defaultLocale: "en-US" } diff --git a/extensions/svg-icon-studio/src/index.tsx b/extensions/svg-icon-studio/src/index.tsx index 440b443a..427137f8 100644 --- a/extensions/svg-icon-studio/src/index.tsx +++ b/extensions/svg-icon-studio/src/index.tsx @@ -1,33 +1,143 @@ -import React, { List, Form, ActionPanel, Action, Icon, Clipboard, showToast, ToastStyle, useState, useMemo, useNavigation, useRef, useEffect, useLocale } from '@ztools/declarative-ui' +import React, { + List, + Form, + ActionPanel, + Action, + Icon, + Clipboard, + showToast, + ToastStyle, + useState, + useMemo, + useNavigation, + useRef, + useEffect, + useLocale +} from '@ztools/declarative-ui' import { createCompatFileInputProps, isDeclarativeFileInputSupported } from './host-compat.js' -import { optimizeSvgSource, extractDroppedSvgPath, pickSvgFilePath, readSvgFileContent } from './svg-service.js' +import { + buildPreviewSvgDataUri, + copyPngImageToClipboard, + deriveComponentName, + deriveFileBaseName, + extractDroppedSvgPath, + optimizeSvgSource, + pickSvgFilePath, + readSvgFileContent, + renderSvgToPng, + savePngArtifactFile, + saveTextArtifactFile +} from './svg-service.js' +import type { FloatPrecision, PngScale, PreviewBackground, SvgOptimizeMetrics } from './types.js' import { t } from './i18n.js' export * from './types.js' export * from './svg-service.js' +const PRECISION_CYCLE: FloatPrecision[] = [2, 3, 1, 0, null] +const PNG_SCALE_CYCLE: PngScale[] = [1, 2, 3] + /** 快捷键文案按平台区分:macOS 只写 ⌘,Windows 写 Ctrl */ export function modEnterLabel(): string { const nav = typeof navigator === 'undefined' ? undefined : navigator return /Mac/i.test(nav?.platform || nav?.userAgent || '') ? '⌘Enter' : 'Ctrl+Enter' } -export function SvgSourceForm({ initial, save }: { initial: string; save: (source: string) => void }) { +function formatBytes(bytes: number): string { + if (bytes < 1024) return `${bytes} B` + if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(2)} KB` + return `${(bytes / (1024 * 1024)).toFixed(2)} MB` +} + +function formatByteNumber(bytes: number): string { + return `${bytes.toLocaleString('en-US')} B` +} + +function precisionLabel(precision: FloatPrecision): string { + return precision === null ? t('optPrecisionRaw') : t('optPrecisionDigits', { n: precision }) +} + +function buildCleanupSummary(metrics: SvgOptimizeMetrics): string { + const parts: string[] = [] + const s = metrics.stats + if (s.removedMetadata > 0) parts.push(t('metaCleanupMetadata', { n: s.removedMetadata })) + if (s.removedComments > 0) parts.push(t('metaCleanupComments', { n: s.removedComments })) + if (s.removedEmptyGroups > 0) parts.push(t('metaCleanupEmptyGroups', { n: s.removedEmptyGroups })) + if (s.removedDefaultAttrs > 0) parts.push(t('metaCleanupDefaultAttrs', { n: s.removedDefaultAttrs })) + if (s.removedUnusedXmlns > 0) parts.push(t('metaCleanupXmlns', { n: s.removedUnusedXmlns })) + if (s.removedWhitespaceNodes > 0) parts.push(t('metaCleanupWhitespace', { n: s.removedWhitespaceNodes })) + if (s.roundedNumbers > 0) parts.push(t('metaCleanupRounded', { n: s.roundedNumbers })) + if (s.currentColorReplacements > 0) parts.push(t('metaCleanupCurrentColor', { n: s.currentColorReplacements })) + if (metrics.removedItems > 0) parts.push(t('metaCleanupRemovedSecurity', { n: metrics.removedItems })) + return parts.length > 0 ? parts.join(' / ') : t('metaCleanupNone') +} + +export function SvgSourceForm({ + initial, + initialComponentName, + floatPrecision, + useCurrentColor, + save +}: { + initial: string + initialComponentName: string + floatPrecision: FloatPrecision + useCurrentColor: boolean + save: (source: string, componentName: string) => void +}) { useLocale() - const [source, setSource] = useState(initial), { pop } = useNavigation() + const [source, setSource] = useState(initial) + const [compName, setCompName] = useState(initialComponentName) + const { pop } = useNavigation() + const submit = async () => { - try { optimizeSvgSource(source); save(source); pop() } - catch (error) { await showToast({ style: ToastStyle.Failure, title: t('toastValidationFailed'), message: error instanceof Error ? error.message : String(error) }) } + try { + optimizeSvgSource(source, { + floatPrecision, + useCurrentColor, + componentName: compName + }) + save(source, compName) + pop() + } catch (error) { + await showToast({ + style: ToastStyle.Failure, + title: t('toastValidationFailed'), + message: error instanceof Error ? error.message : String(error) + }) + } } - return
}> - - -
+ + return ( +
+ + + } + > + + + +
+ ) } -/** 清理后 SVG 的真实渲染预览:以图片方式显示(不执行脚本、不插入界面 DOM),看清理是否改变了外观 */ -function previewImage(base64DataUri: string): string { - return `![${t('previewAlt')}](${base64DataUri})\n\n` +function previewImage(dataUri: string): string { + return `![${t('previewAlt')}](${dataUri})\n\n` } function codeBlock(source: string, language: string): string { @@ -40,22 +150,57 @@ function codeBlock(source: string, language: string): string { export function SvgIconStudioCommand() { const locale = useLocale() const [rawSvg, setRawSvg] = useState('') - const [query, setQuery] = useState(''), { push } = useNavigation() - const revision = useRef(0), mounted = useRef(true) - useEffect(() => () => { mounted.current = false; revision.current++ }, []) + const [sourceName, setSourceName] = useState('') + const [customComponentName, setCustomComponentName] = useState('') + const [query, setQuery] = useState('') + const [previewBg, setPreviewBg] = useState('checkerboard') + const [floatPrecision, setFloatPrecision] = useState(2) + const [useCurrentColor, setUseCurrentColor] = useState(false) + const [pngScale, setPngScale] = useState(2) + const { push } = useNavigation() + const revision = useRef(0) + const mounted = useRef(true) + + useEffect(() => () => { + mounted.current = false + revision.current++ + }, []) + + const updateSource = (source: string, label: string, nextCompName?: string) => { + setRawSvg(source) + setSourceName(label) + if (nextCompName !== undefined) { + setCustomComponentName(nextCompName) + } + setQuery('') + } + + const effectiveComponentName = customComponentName.trim() || deriveComponentName(sourceName) + const loadSvgFromFile = async (filePath: string): Promise => { const request = ++revision.current try { const text = await readSvgFileContent(filePath) if (!mounted.current || request !== revision.current) return - updateSource(text || '') - optimizeSvgSource(text || '') + const fileName = filePath.split(/[\\/]/).pop() || filePath + const nextComp = deriveComponentName(fileName) + updateSource(text || '', fileName, nextComp) + optimizeSvgSource(text || '', { + floatPrecision, + useCurrentColor, + componentName: nextComp + }) await showToast({ style: ToastStyle.Success, title: t('toastLoadedSuccess') }) } catch (error) { if (!mounted.current || request !== revision.current) return - await showToast({ style: ToastStyle.Failure, title: t('toastLoadFailed'), message: error instanceof Error ? error.message : String(error) }) + await showToast({ + style: ToastStyle.Failure, + title: t('toastLoadFailed'), + message: error instanceof Error ? error.message : String(error) + }) } } + const handlePickSvgFile = async (): Promise => { try { const picked = await pickSvgFilePath() @@ -63,9 +208,14 @@ export function SvgIconStudioCommand() { await loadSvgFromFile(picked.filePath) } catch (error) { if (!mounted.current) return - await showToast({ style: ToastStyle.Failure, title: t('toastLoadFailed'), message: error instanceof Error ? error.message : String(error) }) + await showToast({ + style: ToastStyle.Failure, + title: t('toastLoadFailed'), + message: error instanceof Error ? error.message : String(error) + }) } } + const handleDrop = (envelope: unknown) => { const dropped = extractDroppedSvgPath(envelope) if (!dropped) { @@ -74,6 +224,7 @@ export function SvgIconStudioCommand() { } void loadSvgFromFile(dropped) } + const fileInputProps = createCompatFileInputProps( files => handleDrop({ files }), { @@ -85,21 +236,31 @@ export function SvgIconStudioCommand() { } const request = ++revision.current try { - updateSource(text) - optimizeSvgSource(text) + updateSource(text, '', '') + optimizeSvgSource(text, { floatPrecision, useCurrentColor }) if (!mounted.current || request !== revision.current) return await showToast({ style: ToastStyle.Success, title: t('toastLoadedSuccess') }) } catch (error) { if (!mounted.current || request !== revision.current) return - await showToast({ style: ToastStyle.Failure, title: t('toastLoadFailed'), message: error instanceof Error ? error.message : String(error) }) + await showToast({ + style: ToastStyle.Failure, + title: t('toastLoadFailed'), + message: error instanceof Error ? error.message : String(error) + }) } } } ) + useEffect(() => { if (isDeclarativeFileInputSupported()) return undefined const w = typeof window !== 'undefined' ? (window as unknown as Record) : null - const eventsApi = (w?.ztools as { events?: { on?: (ev: string, cb: (payload: unknown) => void) => unknown; off?: (ev: string, cb: (payload: unknown) => void) => void } } | undefined)?.events + const eventsApi = (w?.ztools as { + events?: { + on?: (ev: string, cb: (payload: unknown) => void) => unknown + off?: (ev: string, cb: (payload: unknown) => void) => void + } + } | undefined)?.events if (!eventsApi || typeof eventsApi.on !== 'function') return undefined const dispose = eventsApi.on('plugin_files_dropped', handleDrop) return () => { @@ -107,79 +268,499 @@ export function SvgIconStudioCommand() { else if (typeof eventsApi.off === 'function') eventsApi.off('plugin_files_dropped', handleDrop) } }, []) - const updateSource = (source: string) => { setRawSvg(source); setQuery('') } - const saveSource = (source: string) => { revision.current++; updateSource(source) } - const editSource = () => { revision.current++; push() } - const svgState = useMemo(() => { - if (!rawSvg.trim()) return { status: 'empty' as const } - try { return { status: 'ready' as const, result: optimizeSvgSource(rawSvg) } } - catch (error) { return { status: 'error' as const, error: error instanceof Error ? error.message : String(error) } } - }, [rawSvg, locale]) + + const saveSource = (source: string, nextCompName: string) => { + revision.current++ + updateSource(source, sourceName || t('sourceManual'), nextCompName) + } + + const editSource = () => { + revision.current++ + push( + + ) + } + const handleLoadClipboard = async (): Promise => { const request = ++revision.current try { const text = await Clipboard.readText() if (!mounted.current || request !== revision.current) return - updateSource(text || '') - optimizeSvgSource(text || '') + updateSource(text || '', '', '') + optimizeSvgSource(text || '', { floatPrecision, useCurrentColor }) await showToast({ style: ToastStyle.Success, title: t('toastLoadedSuccess') }) } catch (error) { if (!mounted.current || request !== revision.current) return - await showToast({ style: ToastStyle.Failure, title: t('toastLoadFailed'), message: error instanceof Error ? error.message : String(error) }) + await showToast({ + style: ToastStyle.Failure, + title: t('toastLoadFailed'), + message: error instanceof Error ? error.message : String(error) + }) } } + + const cyclePrecision = () => { + setFloatPrecision(prev => { + const idx = PRECISION_CYCLE.indexOf(prev) + return PRECISION_CYCLE[(idx + 1) % PRECISION_CYCLE.length] + }) + } + + const toggleCurrentColor = () => { + setUseCurrentColor(prev => !prev) + } + + const cyclePngScale = () => { + setPngScale(prev => { + const idx = PNG_SCALE_CYCLE.indexOf(prev) + return PNG_SCALE_CYCLE[(idx + 1) % PNG_SCALE_CYCLE.length] + }) + } + + const svgState = useMemo(() => { + if (!rawSvg.trim()) return { status: 'empty' as const } + try { + return { + status: 'ready' as const, + result: optimizeSvgSource(rawSvg, { + floatPrecision, + useCurrentColor, + componentName: effectiveComponentName + }) + } + } catch (error) { + return { + status: 'error' as const, + error: error instanceof Error ? error.message : String(error) + } + } + }, [rawSvg, floatPrecision, useCurrentColor, effectiveComponentName, locale]) + const result = svgState.status === 'ready' ? svgState.result : null - const exports = result ? [ - { id: 'svg', title: t('exportSvgTitle'), subtitle: t('exportSvgSub'), language: 'xml', content: result.optimizedSvg }, - { id: 'react', title: t('exportReactTitle'), subtitle: t('exportReactSub'), language: 'tsx', content: result.reactTsxCode }, - { id: 'vue', title: t('exportVueTitle'), subtitle: t('exportVueSub'), language: 'vue', content: result.vueSfcCode }, - { id: 'uri', title: t('exportUriTitle'), subtitle: t('exportUriSub'), language: 'text', content: result.dataUri }, - ] : [] - const summary = result ? `${result.metrics.originalBytes} B → ${result.metrics.optimizedBytes} B · ${result.metrics.savedBytes >= 0 ? t('summaryReduced') : t('summaryIncreased')} ${Math.abs(result.metrics.savedBytes)} B${result.metrics.removedItems ? t('summaryRemovedItems', { count: result.metrics.removedItems }) : ''}` : '' + + const previewDataUri = useMemo(() => { + if (!result) return '' + return buildPreviewSvgDataUri(result.optimizedSvg, result.metrics.width, result.metrics.height, previewBg) + }, [result, previewBg]) + + const handleSaveTextArtifact = async ( + content: string, + defaultName: string, + dialogTitle: string, + dialogFilter: string + ): Promise => { + try { + const savedPath = await saveTextArtifactFile(content, defaultName, dialogTitle, dialogFilter) + if (!savedPath || !mounted.current) return + await showToast({ style: ToastStyle.Success, title: t('toastSavedFile'), message: savedPath }) + } catch (error) { + if (!mounted.current) return + await showToast({ + style: ToastStyle.Failure, + title: t('toastSaveFailed'), + message: error instanceof Error ? error.message : String(error) + }) + } + } + + const handleCopyPng = async (scale: PngScale = pngScale): Promise => { + if (!result) return + try { + const png = await renderSvgToPng(result.optimizedSvg, result.metrics.width, result.metrics.height, scale) + if (!mounted.current) return + await copyPngImageToClipboard(png.dataUrl) + if (!mounted.current) return + await showToast({ + style: ToastStyle.Success, + title: t('toastPngCopied'), + message: `${png.width}×${png.height} px · ${formatBytes(png.bytes)}` + }) + } catch (error) { + if (!mounted.current) return + await showToast({ + style: ToastStyle.Failure, + title: t('toastPngFailed'), + message: error instanceof Error ? error.message : String(error) + }) + } + } + + const handleSavePng = async (scale: PngScale = pngScale): Promise => { + if (!result) return + try { + const png = await renderSvgToPng(result.optimizedSvg, result.metrics.width, result.metrics.height, scale) + if (!mounted.current) return + const baseName = deriveFileBaseName(sourceName) + const savedPath = await savePngArtifactFile(png.base64, `${baseName}@${scale}x.png`) + if (!savedPath || !mounted.current) return + await showToast({ + style: ToastStyle.Success, + title: t('toastSavedFile'), + message: `${savedPath} (${png.width}×${png.height} px)` + }) + } catch (error) { + if (!mounted.current) return + await showToast({ + style: ToastStyle.Failure, + title: t('toastPngFailed'), + message: error instanceof Error ? error.message : String(error) + }) + } + } + + const handleCopyPngDataUrl = async (scale: PngScale = pngScale): Promise => { + if (!result) return + try { + const png = await renderSvgToPng(result.optimizedSvg, result.metrics.width, result.metrics.height, scale) + if (!mounted.current) return + await Clipboard.copy(png.dataUrl) + if (!mounted.current) return + await showToast({ + style: ToastStyle.Success, + title: t('toastPngDataUrlCopied'), + message: `${png.width}×${png.height} px · ${formatBytes(png.bytes)}` + }) + } catch (error) { + if (!mounted.current) return + await showToast({ + style: ToastStyle.Failure, + title: t('toastPngFailed'), + message: error instanceof Error ? error.message : String(error) + }) + } + } + + const baseFileName = deriveFileBaseName(sourceName) + const pngOutWidth = result ? Math.round(result.metrics.width * pngScale) : 0 + const pngOutHeight = result ? Math.round(result.metrics.height * pngScale) : 0 + + const renderMetadata = () => { + if (!result) return undefined + const m = result.metrics + const sizeText = m.savedBytes >= 0 + ? t('metaSizeSaved', { orig: formatByteNumber(m.originalBytes), opt: formatByteNumber(m.optimizedBytes), pct: Math.abs(m.savedPercentage) }) + : t('metaSizeAdded', { orig: formatByteNumber(m.originalBytes), opt: formatByteNumber(m.optimizedBytes), pct: Math.abs(m.savedPercentage) }) + return ( + + + + + + + ) + } + + const renderSharedOptionsMenu = () => ( + + + + + + + void handlePickSvgFile()} /> + void handleLoadClipboard()} /> + + + ) + + const exportItems = result + ? [ + { + id: 'svg', + title: t('exportSvgTitle'), + subtitle: t('exportSvgSub'), + accessory: formatBytes(result.metrics.optimizedBytes), + icon: Icon.Code, + language: 'xml', + content: result.optimizedSvg, + saveName: `${baseFileName}.min.svg`, + saveTitle: t('dialogSaveSvgTitle'), + saveFilter: t('dialogSaveSvgFilter'), + keywords: t('kwSvg').split(' ') + }, + { + id: 'react', + title: t('exportReactTitle'), + subtitle: t('exportReactSub'), + accessory: '.tsx', + icon: Icon.Code, + language: 'tsx', + content: result.reactTsxCode, + saveName: `${result.componentName}.tsx`, + saveTitle: t('dialogSaveTsxTitle'), + saveFilter: t('dialogSaveTsxFilter'), + keywords: t('kwReact').split(' ') + }, + { + id: 'vue', + title: t('exportVueTitle'), + subtitle: t('exportVueSub'), + accessory: '.vue', + icon: Icon.Code, + language: 'vue', + content: result.vueSfcCode, + saveName: `${result.componentName}.vue`, + saveTitle: t('dialogSaveVueTitle'), + saveFilter: t('dialogSaveVueFilter'), + keywords: t('kwVue').split(' ') + }, + { + id: 'uri', + title: t('exportUriTitle'), + subtitle: t('exportUriSub'), + accessory: 'base64', + icon: Icon.Code, + language: 'text', + content: result.dataUri, + saveName: `${baseFileName}-data-uri.txt`, + saveTitle: t('dialogSaveUriTitle'), + saveFilter: t('dialogSaveUriFilter'), + keywords: t('kwUri').split(' ') + } + ] + : [] + + const normalizedQuery = query.trim().toLowerCase() + const matchesQuery = (title: string, subtitle: string, keywords: string[]) => { + if (!normalizedQuery) return true + return ( + title.toLowerCase().includes(normalizedQuery) || + subtitle.toLowerCase().includes(normalizedQuery) || + keywords.some(k => k.toLowerCase().includes(normalizedQuery)) + ) + } + + const filteredExports = exportItems.filter(item => matchesQuery(item.title, item.subtitle, item.keywords)) + const pngTitle = t('exportPngTitle', { scale: pngScale }) + const pngSub = t('exportPngSub', { width: pngOutWidth, height: pngOutHeight }) + const showPngItem = Boolean(result) && matchesQuery(pngTitle, pngSub, t('kwPng').split(' ')) + + const optionItems = result + ? [ + { + id: 'opt-precision', + title: t('optPrecisionTitle', { label: precisionLabel(floatPrecision) }), + subtitle: t('optPrecisionSub'), + icon: Icon.Gear, + keywords: t('kwPrecision').split(' '), + onAction: cyclePrecision + }, + { + id: 'opt-current-color', + title: t('optCurrentColorTitle', { state: useCurrentColor ? t('optStateOn') : t('optStateOff') }), + subtitle: t('optCurrentColorSub'), + icon: Icon.Brush, + keywords: t('kwCurrentColor').split(' '), + onAction: toggleCurrentColor + }, + { + id: 'opt-png-scale', + title: t('optPngScaleTitle', { scale: pngScale }), + subtitle: t('optPngScaleSub', { width: pngOutWidth, height: pngOutHeight }), + icon: Icon.Maximize, + keywords: t('kwPngScale').split(' '), + onAction: cyclePngScale + } + ].filter(item => matchesQuery(item.title, item.subtitle, item.keywords)) + : [] + + const sourceLabel = sourceName || t('sourceClipboard') + const summaryText = result + ? `${sourceLabel} | ${formatBytes(result.metrics.originalBytes)} -> ${formatBytes(result.metrics.optimizedBytes)} (${result.metrics.savedBytes >= 0 ? '-' : '+'}${Math.abs(result.metrics.savedPercentage)}%)` + : svgState.status === 'error' + ? t('emptyErrorTitle') + : t('emptyReadySub') + + const warningBlock = result && result.warnings.length > 0 + ? t('warningsHeading', { warnings: codeBlock(result.warnings.join('\n'), 'text') }) + : '' + return ( void handleLoadClipboard() }, - { id: 'edit', title: t('actionEditSource'), onAction: editSource }, - ] } : { summaryText: svgState.status === 'error' ? t('emptyErrorTitle') : t('emptyReadySub'), actions: [ - { id: 'load', title: t('actionLoadClipboard'), style: 'primary', onAction: () => void handleLoadClipboard() }, - { id: 'pick-file', title: t('actionPickFile'), onAction: () => void handlePickSvgFile() }, - ] }} + searchBarAccessory={ + { + if (val === 'checkerboard' || val === 'light' || val === 'dark') { + setPreviewBg(val) + } + }} + > + + + + + } + filterBar={{ + summaryText, + actions: [ + { + id: 'pick-file', + title: t('actionPickFile'), + icon: Icon.Folder, + style: !result ? 'primary' : undefined, + onAction: () => void handlePickSvgFile() + }, + { + id: 'load-clipboard', + title: t('actionLoadClipboard'), + icon: Icon.Clipboard, + onAction: () => void handleLoadClipboard() + }, + { + id: 'edit-source', + title: t('actionEditSource'), + icon: Icon.Code, + onAction: editSource + } + ] + }} + actions={ + + void handlePickSvgFile()} /> + void handleLoadClipboard()} /> + + + } > {!result && ( - } - actions={ - void handleLoadClipboard()} /> - - void handlePickSvgFile()} /> - } + title={svgState.status === 'error' ? t('emptyErrorTitle') : t('emptyReadyTitle')} + description={svgState.status === 'error' ? svgState.error : t('emptyReadyDetail')} /> )} - {exports.filter(item => item.title.toLowerCase().includes(query.trim().toLowerCase())).map(item => ( - } - actions={ - - {item.id === 'uri' && } - void handlePickSvgFile()} /> - } - /> - ))} + + {result && (filteredExports.length > 0 || showPngItem) && ( + + {filteredExports.map(item => ( + + } + actions={ + + + void handleSaveTextArtifact(item.content, item.saveName, item.saveTitle, item.saveFilter)} + /> + {item.id === 'uri' && ( + + )} + {renderSharedOptionsMenu()} + + } + /> + ))} + + {showPngItem && ( + + } + actions={ + + void handleCopyPng(pngScale)} + /> + void handleSavePng(pngScale)} + /> + void handleCopyPngDataUrl(pngScale)} + /> + {renderSharedOptionsMenu()} + + } + /> + )} + + )} + + {result && optionItems.length > 0 && ( + + {optionItems.map(opt => ( + + } + actions={ + + + {renderSharedOptionsMenu()} + + } + /> + ))} + + )} ) } diff --git a/extensions/svg-icon-studio/src/svg-service.ts b/extensions/svg-icon-studio/src/svg-service.ts index 1f84fc04..47393718 100644 --- a/extensions/svg-icon-studio/src/svg-service.ts +++ b/extensions/svg-icon-studio/src/svg-service.ts @@ -1,17 +1,33 @@ -import type { SvgProcessResult } from './types.js' +import type { + FloatPrecision, + PngExportResult, + PngScale, + PreviewBackground, + SvgOptimizationStats, + SvgOptimizeOptions, + SvgProcessResult +} from './types.js' import { t } from './i18n.js' import { resolveErrorMessage } from './error-i18n.js' const SVG_NS = 'http://www.w3.org/2000/svg' const XML_NS = 'http://www.w3.org/XML/1998/namespace' const XLINK_NS = 'http://www.w3.org/1999/xlink' +const XMLNS_NS = 'http://www.w3.org/2000/xmlns/' + const elements = new Set(('svg g a defs symbol use path rect circle ellipse line polyline polygon text tspan textPath title desc linearGradient radialGradient stop clipPath mask pattern marker filter feBlend feColorMatrix feComponentTransfer feComposite feConvolveMatrix feDiffuseLighting feDisplacementMap feDistantLight feDropShadow feFlood feFuncA feFuncB feFuncG feFuncR feGaussianBlur feMerge feMergeNode feMorphology feOffset fePointLight feSpecularLighting feSpotLight feTile feTurbulence').split(' ')) const presentation = new Set(('alignment-baseline baseline-shift clip-path clip-rule color color-interpolation color-interpolation-filters direction display dominant-baseline fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight image-rendering isolation letter-spacing lighting-color marker-end marker-mid marker-start mask opacity overflow paint-order pointer-events shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering unicode-bidi vector-effect visibility white-space word-spacing writing-mode').split(' ')) const attributes = new Set(('id class role tabindex focusable width height x y x1 y1 x2 y2 cx cy r rx ry d points pathLength dx dy rotate textLength lengthAdjust startOffset method spacing side viewBox preserveAspectRatio transform gradientUnits gradientTransform spreadMethod offset fx fy fr clipPathUnits maskUnits maskContentUnits patternUnits patternContentUnits patternTransform markerWidth markerHeight markerUnits refX refY orient filterUnits primitiveUnits in in2 result mode type values operator k1 k2 k3 k4 order kernelMatrix divisor bias targetX targetY edgeMode kernelUnitLength preserveAlpha surfaceScale diffuseConstant scale xChannelSelector yChannelSelector azimuth elevation stdDeviation tableValues slope intercept amplitude exponent radius specularConstant specularExponent limitingConeAngle pointsAtX pointsAtY pointsAtZ z baseFrequency numOctaves seed stitchTiles').split(' ')) const geometry = new Set('path rect circle ellipse line polyline polygon'.split(' ')) +const textContainers = new Set(['text', 'tspan', 'textPath']) +const numericSingleAttrs = new Set(['x', 'y', 'x1', 'y1', 'x2', 'y2', 'cx', 'cy', 'r', 'rx', 'ry', 'width', 'height', 'stroke-width', 'stroke-miterlimit', 'opacity', 'fill-opacity', 'stroke-opacity', 'offset', 'dx', 'dy']) +const numericListAttrs = new Set(['points', 'viewBox']) const localId = /^[A-Za-z_][\w:.-]{0,255}$/ const camelName = (name: string) => name.replace(/[:-]([a-z])/g, (_, letter: string) => letter.toUpperCase()) -function fail(code: string, message: string): never { throw new Error(`${code}: ${message}`) } + +function fail(code: string, message: string): never { + throw new Error(`${code}: ${message}`) +} interface SvgElement { name: string @@ -27,15 +43,234 @@ function escapeXml(text: string, attribute = false): string { return attribute ? escaped.replace(/"/g, '"').replace(/\t/g, ' ').replace(/\n/g, ' ').replace(/\r/g, ' ') : escaped.replace(/\r/g, ' ') } -// 组件模板中的内容始终作为字符串;包括实体、插值分隔符和换行分隔符。 function literal(value: string | Record): string { const unsafe = typeof value === 'string' ? /[<>&{}\u2028\u2029]/g : /[<>&\u2028\u2029]/g return JSON.stringify(value).replace(unsafe, char => `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`) } -function readStaticSvg(input: string) { +function encodeBase64Utf8(text: string): string { + const encoded = new TextEncoder().encode(text) + let binary = '' + for (const byte of encoded) binary += String.fromCharCode(byte) + return btoa(binary) +} + +/** 将文件名或自定义名称规范为合法的 PascalCase React 组件名 */ +export function deriveComponentName(nameHint?: string): string { + const raw = (nameHint || '').trim() + if (!raw) return 'SvgIcon' + const base = raw.split(/[\\/]/).pop() || '' + const withoutExt = base.replace(/\.svg$/i, '') + const tokens = withoutExt + .replace(/([a-z0-9])([A-Z])/g, '$1 $2') + .split(/[^A-Za-z0-9]+/) + .filter(Boolean) + if (tokens.length === 0) return 'SvgIcon' + let pascal = tokens.map(tok => tok.charAt(0).toUpperCase() + tok.slice(1)).join('') + if (/^\d/.test(pascal)) pascal = `Icon${pascal}` + if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(pascal)) return 'SvgIcon' + return pascal +} + +/** 将源文件路径或名称转为安全导出文件基名(不含扩展名) */ +export function deriveFileBaseName(nameHint?: string): string { + const raw = (nameHint || '').trim() + if (!raw) return 'icon' + const base = (raw.split(/[\\/]/).pop() || '').replace(/\.svg$/i, '').replace(/[^A-Za-z0-9._-]+/g, '-').replace(/^-+|-+$/g, '') + return base || 'icon' +} + +/** 格式化数字到指定小数位数,去尾随零与 -0 */ +function formatFloat(raw: string, precision: number): { text: string; changed: boolean } { + const n = Number(raw) + if (!Number.isFinite(n)) return { text: raw, changed: false } + const rounded = Number(n.toFixed(precision)) + const normalized = Object.is(rounded, -0) ? 0 : rounded + const out = String(normalized) + return { text: out, changed: out !== raw } +} + +const PATH_PARAM_COUNTS: Record = { + M: 2, m: 2, L: 2, l: 2, T: 2, t: 2, + H: 1, h: 1, V: 1, v: 1, + S: 4, s: 4, Q: 4, q: 4, + C: 6, c: 6, + A: 7, a: 7, + Z: 0, z: 0 +} + +/** + * 规范化并按指定浮点精度压缩 SVG path d 属性。 + * 严格遵循 SVG path 词法,特别保护弧线命令 A/a 的 large-arc-flag 与 sweep-flag。 + */ +export function roundPathData(d: string, precision: number): { value: string; rounded: number } { + const len = d.length + let i = 0 + let cmd = '' + let paramIdx = 0 + let roundedCount = 0 + const out: string[] = [] + let prevWasNumber = false + + const skipSep = () => { + while (i < len && (d[i] === ' ' || d[i] === '\t' || d[i] === '\n' || d[i] === '\r' || d[i] === ',')) i++ + } + + while (i < len) { + skipSep() + if (i >= len) break + const ch = d[i] + if (ch in PATH_PARAM_COUNTS) { + cmd = ch + paramIdx = 0 + out.push(ch) + prevWasNumber = false + i++ + continue + } + if (!cmd || PATH_PARAM_COUNTS[cmd] === 0) { + return { value: d.trim(), rounded: 0 } + } + const arity = PATH_PARAM_COUNTS[cmd] + const slot = paramIdx % arity + if ((cmd === 'A' || cmd === 'a') && (slot === 3 || slot === 4)) { + if (ch !== '0' && ch !== '1') return { value: d.trim(), rounded: 0 } + if (prevWasNumber) out.push(' ') + out.push(ch) + prevWasNumber = true + paramIdx++ + i++ + continue + } + const numMatch = d.slice(i).match(/^[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/) + if (!numMatch) return { value: d.trim(), rounded: 0 } + const rawNum = numMatch[0] + i += rawNum.length + const { text, changed } = formatFloat(rawNum, precision) + if (changed) roundedCount++ + if (prevWasNumber && !text.startsWith('-')) out.push(' ') + out.push(text) + prevWasNumber = true + paramIdx++ + } + + return { value: out.join(''), rounded: roundedCount } +} + +function roundNumericList(raw: string, precision: number): { value: string; rounded: number } { + const parts = raw.trim().split(/[\s,]+/).filter(Boolean) + if (parts.length === 0) return { value: raw.trim(), rounded: 0 } + let rounded = 0 + const formatted = parts.map(part => { + if (!/^[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?$/.test(part)) return part + const res = formatFloat(part, precision) + if (res.changed) rounded++ + return res.text + }) + return { value: formatted.join(' '), rounded } +} + +function roundSingleNumeric(raw: string, precision: number): { value: string; rounded: number } { + const trimmed = raw.trim() + const match = trimmed.match(/^([+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?)(px|%)?$/) + if (!match) return { value: trimmed, rounded: 0 } + const res = formatFloat(match[1], precision) + const unit = match[2] === 'px' ? '' : (match[2] || '') + return { + value: `${res.text}${unit}`, + rounded: res.changed || (match[2] === 'px') ? 1 : 0 + } +} + +function isNumericDefault(raw: string, expected: number): boolean { + const trimmed = raw.trim() + if (expected === 1 && trimmed === '100%') return true + const match = trimmed.match(/^([+-]?(?:\d+\.?\d*|\.\d+))(?:px)?$/) + if (!match) return false + return Number(match[1]) === expected +} + +function isDefaultAttribute( + elementName: string, + key: string, + value: string, + inheritedAttrs: ReadonlySet +): boolean { + const trimmed = value.trim() + if (key === 'opacity' && isNumericDefault(trimmed, 1)) return true + if (key === 'xml:space' && trimmed === 'default') return true + if (elementName === 'svg') { + if ((key === 'x' || key === 'y') && isNumericDefault(trimmed, 0)) return true + } + if (inheritedAttrs.has(key)) return false + if (key === 'fill-opacity' && isNumericDefault(trimmed, 1)) return true + if (key === 'stroke-opacity' && isNumericDefault(trimmed, 1)) return true + if (key === 'stroke-width' && isNumericDefault(trimmed, 1)) return true + if (key === 'stroke-dashoffset' && isNumericDefault(trimmed, 0)) return true + if (key === 'stroke-miterlimit' && isNumericDefault(trimmed, 4)) return true + if (key === 'stroke-linecap' && trimmed === 'butt') return true + if (key === 'stroke-linejoin' && trimmed === 'miter') return true + if (key === 'fill-rule' && trimmed === 'nonzero') return true + if (key === 'clip-rule' && trimmed === 'nonzero') return true + return false +} + +const INHERITABLE_CHECK_ATTRS = new Set([ + 'fill-opacity', + 'stroke-opacity', + 'stroke-width', + 'stroke-dashoffset', + 'stroke-miterlimit', + 'stroke-linecap', + 'stroke-linejoin', + 'fill-rule', + 'clip-rule' +]) + +function shouldReplaceWithCurrentColor(value: string): boolean { + const trimmed = value.trim() + if (!trimmed) return false + const lower = trimmed.toLowerCase() + if (lower === 'none' || lower === 'transparent' || lower === 'currentcolor' || lower === 'inherit') return false + if (/^url\s*\(/i.test(trimmed)) return false + return true +} + +function parsePositiveDimension(raw: string | undefined): number | null { + if (!raw) return null + const match = raw.trim().match(/^(\d+(?:\.\d+)?)(?:px)?$/i) + if (!match) return null + const val = Number(match[1]) + return Number.isFinite(val) && val > 0 ? val : null +} + +/** 从 SVG 根节点推导逻辑宽高(优先 width/height,次选 viewBox,兜底 256×256) */ +function resolveSvgDimensions(root: SvgElement): { width: number; height: number; viewBox: string } { + const widthAttr = root.attrs.find(([k]) => k === 'width')?.[1] + const heightAttr = root.attrs.find(([k]) => k === 'height')?.[1] + const viewBoxAttr = root.attrs.find(([k]) => k === 'viewBox')?.[1] + let vbW: number | null = null + let vbH: number | null = null + if (viewBoxAttr) { + const parts = viewBoxAttr.trim().split(/[\s,]+/).map(Number) + if (parts.length === 4 && parts.every(Number.isFinite) && parts[2] > 0 && parts[3] > 0) { + vbW = parts[2] + vbH = parts[3] + } + } + const attrW = parsePositiveDimension(widthAttr) + const attrH = parsePositiveDimension(heightAttr) + const width = Math.max(1, Math.round(attrW ?? vbW ?? 256)) + const height = Math.max(1, Math.round(attrH ?? vbH ?? 256)) + return { width, height, viewBox: viewBoxAttr || t('viewBoxUnset') } +} + +function readStaticSvg(input: string, options: SvgOptimizeOptions = {}) { if (/(), ids = new Map() - let nodeCount = 0, removedItems = 0, pathCount = 0 - const removed = (reason: string) => { removedItems++; if (warnings.size < 30) warnings.add(reason) } + const warnings = new Set() + const ids = new Map() + let nodeCount = 0 + let removedItems = 0 + let pathCount = 0 + const stats: SvgOptimizationStats = { + removedComments: 0, + removedMetadata: 0, + removedEmptyGroups: 0, + removedDefaultAttrs: 0, + removedUnusedXmlns: 0, + removedWhitespaceNodes: 0, + roundedNumbers: 0, + currentColorReplacements: 0 + } + + const removed = (reason: string) => { + removedItems++ + if (warnings.size < 30) warnings.add(reason) + } + function safeValue(name: string, value: string, references: string[]): boolean { if (name === 'href') { if (!value.startsWith('#') || !localId.test(value.slice(1))) return false references.push(value.slice(1)) return true } - // CSS 转义及注释会改变 URL 词法,静态子集不接收这些写法。 if (/[\\<>@{}]|\/\*|\*\//.test(value)) return false const rest = value.replace(/url\(\s*(?:"#([\w:.-]+)"|'#([\w:.-]+)'|#([\w:.-]+))\s*\)/gi, (_match, a: string, b: string, c: string) => { const id = a || b || c @@ -62,6 +314,7 @@ function readStaticSvg(input: string) { }) return !/url\s*\(/i.test(rest) } + function readStyle(source: string, references: string[]) { const style: Record = {} const names = new Set() @@ -71,13 +324,13 @@ function readStaticSvg(input: string) { if (!match || !presentation.has(match[1].toLowerCase()) || /!|[\\{}@]|\/\*|\*\//.test(match[2]) || !/^(?:[^'"]|'[^']*'|"[^"]*")*$/.test(match[2])) { fail('UNSUPPORTED_STYLE', t('errUnsupportedStyle')) } - const name = match[1].toLowerCase(), value = match[2] + const name = match[1].toLowerCase() + const value = match[2] const refs: string[] = [] if (!safeValue(name, value, refs)) fail('UNSAFE_STYLE', t('errUnsafeStyle')) names.add(name) references.push(...refs) } - // 由浏览器 CSS 解析器决定重复/无效声明的最终值;只读独立文档中的样式数据。 const cssRoot = new DOMParser().parseFromString(``, 'image/svg+xml').documentElement as unknown as SVGElement if (!cssRoot.style) fail('CSS_PARSER_UNAVAILABLE', t('errNoCssParser')) for (const name of names) { @@ -87,27 +340,68 @@ function readStaticSvg(input: string) { } return { values: style, cssText: cssRoot.style.cssText } } - function read(node: Node, depth: number): SvgNode | null { + + function read( + node: Node, + depth: number, + preserveWhitespace: boolean, + inheritedAttrs: ReadonlySet + ): SvgNode | null { if (++nodeCount > 5000 || depth > 64) fail('SVG_COMPLEXITY_LIMIT', t('errComplexityNodes')) - if (node.nodeType === 3 || node.nodeType === 4) return node.nodeValue || '' + if (node.nodeType === 8) { + stats.removedComments++ + return null + } + if (node.nodeType === 3 || node.nodeType === 4) { + const text = node.nodeValue || '' + if (!preserveWhitespace && /^\s+$/.test(text)) { + stats.removedWhitespaceNodes++ + return null + } + return text + } if (node.nodeType !== 1) { if (node.nodeType === 7) removed(t('warnRemovedPi')) return null } - const element = node as Element, name = element.localName + const element = node as Element + const name = element.localName + if (name === 'metadata') { + stats.removedMetadata++ + return null + } if (element.namespaceURI !== acceptedNamespace || !elements.has(name)) { removed(t('warnRemovedNonStaticElement', { tag: element.tagName })) return null } const item: SvgElement = { name, attrs: [], styleValues: {}, children: [], references: [] } if (geometry.has(name)) pathCount++ + + let xmlSpacePreserve = preserveWhitespace || textContainers.has(name) + const nextInherited = new Set(inheritedAttrs) + for (const attr of Array.from(element.attributes)) { - if (attr.namespaceURI === 'http://www.w3.org/2000/xmlns/') continue + if (attr.namespaceURI === XMLNS_NS) { + if (attr.name !== 'xmlns' || attr.value !== SVG_NS) { + stats.removedUnusedXmlns++ + } + continue + } let key = attr.name - const value = attr.value + let value = attr.value if (attr.namespaceURI === XLINK_NS && attr.localName === 'href') key = 'href' else if (attr.namespaceURI === XML_NS && ['space', 'lang'].includes(attr.localName)) key = `xml:${attr.localName}` - else if (attr.namespaceURI) { removed(t('warnRemovedNsAttr', { key })); continue } + else if (attr.namespaceURI) { + removed(t('warnRemovedNsAttr', { key })) + continue + } + if (key === 'version' && name === 'svg') { + stats.removedDefaultAttrs++ + continue + } + if (key === 'xml:space' && value.trim() === 'preserve') { + xmlSpacePreserve = true + } if (key === 'style') { const style = readStyle(value, item.references) item.styleValues = style.values @@ -126,23 +420,76 @@ function readStaticSvg(input: string) { if (key === 'preserveAlpha' && !['true', 'false'].includes(value)) fail('INVALID_SVG_ATTRIBUTE', t('errPreserveAlphaBool')) if (presentation.has(key) || key === 'href') { const refs: string[] = [] - if (!safeValue(key, value, refs)) { removed(t('warnRemovedExternalOrUnsupportedAttr', { key })); continue } + if (!safeValue(key, value, refs)) { + removed(t('warnRemovedExternalOrUnsupportedAttr', { key })) + continue + } item.references.push(...refs) } if (item.attrs.some(([previous]) => previous === key)) fail('DUPLICATE_SVG_ATTRIBUTE', t('errDuplicateAttr', { key })) + + // 清理默认值属性(不破坏祖先继承覆盖) + if (isDefaultAttribute(name, key, value, inheritedAttrs)) { + stats.removedDefaultAttrs++ + continue + } + + // 数值精度收敛 + if (floatPrecision !== null) { + if (key === 'd' && name === 'path') { + const res = roundPathData(value, floatPrecision) + value = res.value + stats.roundedNumbers += res.rounded + } else if (numericListAttrs.has(key)) { + const res = roundNumericList(value, floatPrecision) + value = res.value + stats.roundedNumbers += res.rounded + } else if (numericSingleAttrs.has(key)) { + const res = roundSingleNumeric(value, floatPrecision) + value = res.value + stats.roundedNumbers += res.rounded + } + } + + // currentColor 替换 + if (useCurrentColor && (key === 'fill' || key === 'stroke') && shouldReplaceWithCurrentColor(value)) { + value = 'currentColor' + stats.currentColorReplacements++ + } + + if (INHERITABLE_CHECK_ATTRS.has(key)) { + nextInherited.add(key) + } item.attrs.push([key, value]) } + for (const child of Array.from(element.childNodes)) { - const result = read(child, depth + 1) + const result = read(child, depth + 1, xmlSpacePreserve, nextInherited) if (result !== null) item.children.push(result) } + + // 自底向上裁剪无 id 的空 / + if ((name === 'g' || name === 'defs') && item.children.length === 0) { + const hasId = item.attrs.some(([k]) => k === 'id') + if (!hasId) { + stats.removedEmptyGroups++ + return null + } + } + return item } - // XML 声明以外的顶层处理指令也不能带进导出结果。 - for (const node of Array.from(parsed.childNodes)) if (node.nodeType === 7 && node.nodeName !== 'xml') removed(t('warnRemovedPi')) - const tree = read(root, 0) as SvgElement + + for (const node of Array.from(parsed.childNodes)) { + if (node.nodeType === 8) stats.removedComments++ + else if (node.nodeType === 7 && node.nodeName !== 'xml') removed(t('warnRemovedPi')) + } + + const tree = read(root, 0, false, new Set()) as SvgElement tree.attrs.unshift(['xmlns', SVG_NS]) - const visiting = new Set(), sizes = new Map() + + const visiting = new Set() + const sizes = new Map() function expandedSize(item: SvgElement, depth = 0): { size: number; height: number } { if (depth > 128) fail('SVG_COMPLEXITY_LIMIT', t('errRefChainLimit')) if (visiting.has(item)) fail('CYCLIC_SVG_REFERENCE', t('errCyclicRef')) @@ -152,7 +499,8 @@ function readStaticSvg(input: string) { return cached } visiting.add(item) - let size = 1, height = 0 + let size = 1 + let height = 0 const targets = item.references.map(id => ids.get(id) || fail('MISSING_SVG_REFERENCE', t('errMissingRef', { id }))) for (const child of [...item.children.filter((child): child is SvgElement => typeof child !== 'string'), ...targets]) { const expanded = expandedSize(child, depth + 1) @@ -162,55 +510,273 @@ function readStaticSvg(input: string) { } if (depth + height > 128) fail('SVG_COMPLEXITY_LIMIT', t('errRefChainLimit')) const measured = { size, height } - visiting.delete(item); sizes.set(item, measured) + visiting.delete(item) + sizes.set(item, measured) return measured } expandedSize(tree) - return { tree, warnings: [...warnings], removedItems, pathCount } + + return { tree, warnings: [...warnings], removedItems, pathCount, stats } } -function serialize(node: SvgNode, format: 'svg' | 'react' | 'vue', root = false): string { +const HTML_CONFLICT_TAGS: Record = { + a: 'React.SVGProps', + title: 'React.SVGProps' +} + +function serializeXml(node: SvgNode, forVue = false): string { if (typeof node === 'string') { - if (format === 'svg') return escapeXml(node) - return format === 'react' ? literal(node) : `{{ ${literal(node)} }}` - } - const children = node.children.map(child => serialize(child, format)) - if (format === 'react') { - const props: Record = {} - for (const [key, value] of node.attrs) { - const prop = key === 'class' ? 'className' : key === 'tabindex' ? 'tabIndex' : /^(aria|data)-/.test(key) ? key : camelName(key) - props[prop] = key === 'style' ? node.styleValues : key === 'tabindex' ? Number(value) : key === 'preserveAlpha' ? value === 'true' : value - } - // createElement 按 SVG 上下文渲染,也避免 JSX 把 a/title 错判为 HTML 属性类型。 - const properties = root ? `{ ...${literal(props)}, ...props }` : literal(props) - return `React.createElement(${literal(node.name)}, ${properties}${children.length ? ', ' + children.join(', ') : ''})` + return forVue ? `{{ ${literal(node)} }}` : escapeXml(node) } + const children = node.children.map(child => serializeXml(child, forVue)) const attrs = node.attrs.map(([key, value]) => ` ${key}="${escapeXml(value, true)}"`).join('') const opening = `<${node.name}${attrs}` return children.length ? `${opening}>${children.join('')}` : `${opening}/>` } -export function optimizeSvgSource(rawInput: string): SvgProcessResult { +function serializeReactJsx(node: SvgNode, root = false, indent = 4): string { + const pad = ' '.repeat(indent) + if (typeof node === 'string') { + return `{${literal(node)}}` + } + + const jsxAttrs: string[] = [] + const conflictExtraProps: Record = {} + const conflictType = HTML_CONFLICT_TAGS[node.name] + + for (const [key, value] of node.attrs) { + const prop = key === 'class' ? 'className' : key === 'tabindex' ? 'tabIndex' : /^(aria|data)-/.test(key) ? key : camelName(key) + if (conflictType && prop !== 'id' && prop !== 'className' && prop !== 'href' && prop !== 'tabIndex' && prop !== 'role' && !/^(aria|data)-/.test(prop)) { + conflictExtraProps[prop] = key === 'style' ? node.styleValues : value + continue + } + if (key === 'style') { + jsxAttrs.push(`style={${literal(node.styleValues)}}`) + } else if (key === 'tabindex') { + jsxAttrs.push(`tabIndex={${Number(value)}}`) + } else if (key === 'preserveAlpha') { + jsxAttrs.push(`preserveAlpha={${value === 'true'}}`) + } else if (/["\n\r\t<>&{}]/.test(value)) { + jsxAttrs.push(`${prop}={${literal(value)}}`) + } else { + jsxAttrs.push(`${prop}="${value}"`) + } + } + + if (conflictType && Object.keys(conflictExtraProps).length > 0) { + jsxAttrs.push(`{...(${literal(conflictExtraProps)} as unknown as Record)}`) + } + if (root) { + jsxAttrs.push('{...props}') + } + + const attrStr = jsxAttrs.length > 0 ? ' ' + jsxAttrs.join(' ') : '' + if (node.children.length === 0) { + return `${pad}<${node.name}${attrStr} />` + } + + const hasElementChild = node.children.some(child => typeof child !== 'string') + if (!hasElementChild) { + const inlineText = node.children.map(child => serializeReactJsx(child, false, 0)).join('') + return `${pad}<${node.name}${attrStr}>${inlineText}` + } + + const renderedChildren = node.children.map(child => + typeof child === 'string' + ? `${' '.repeat(indent + 2)}{${literal(child)}}` + : serializeReactJsx(child, false, indent + 2) + ) + return `${pad}<${node.name}${attrStr}>\n${renderedChildren.join('\n')}\n${pad}` +} + +export function optimizeSvgSource(rawInput: string, options: SvgOptimizeOptions = {}): SvgProcessResult { if (typeof rawInput !== 'string' || !rawInput.trim()) fail('EMPTY_SVG_INPUT', t('errEmptySvg')) const originalBytes = new TextEncoder().encode(rawInput).length if (originalBytes > 256 * 1024) fail('SVG_SIZE_LIMIT', t('errSizeLimit')) - const { tree, warnings, removedItems, pathCount } = readStaticSvg(rawInput) - const optimizedSvg = serialize(tree, 'svg') + + const { tree, warnings, removedItems, pathCount, stats } = readStaticSvg(rawInput, options) + const optimizedSvg = serializeXml(tree, false) const encoded = new TextEncoder().encode(optimizedSvg) const savedBytes = originalBytes - encoded.length - const reactTsxCode = ["import React from 'react'", '', 'export function SvgIcon(props: React.SVGProps): React.ReactElement {', ` return (${serialize(tree, 'react', true)})`, '}', '', 'export default SvgIcon'].join('\n') - const vueSfcCode = ['', '', ''].join('\n') - let binary = '' - for (const byte of encoded) binary += String.fromCharCode(byte) + const componentName = deriveComponentName(options.componentName) + const dims = resolveSvgDimensions(tree) + + const reactTsxCode = [ + "import React from 'react'", + '', + `export function ${componentName}(props: React.SVGProps): React.ReactElement {`, + ' return (', + serializeReactJsx(tree, true, 4), + ' )', + '}', + '', + `export default ${componentName}` + ].join('\n') + + const vueSfcCode = [ + '', + '', + '' + ].join('\n') + + const base64DataUri = `data:image/svg+xml;base64,${encodeBase64Utf8(optimizedSvg)}` + return { - originalSvg: rawInput, optimizedSvg, reactTsxCode, vueSfcCode, + originalSvg: rawInput, + optimizedSvg, + reactTsxCode, + vueSfcCode, dataUri: `data:image/svg+xml;charset=utf-8,${encodeURIComponent(optimizedSvg)}`, - base64DataUri: `data:image/svg+xml;base64,${btoa(binary)}`, + base64DataUri, + componentName, warnings, - metrics: { originalBytes, optimizedBytes: encoded.length, savedBytes, savedPercentage: Math.round(savedBytes / originalBytes * 1000) / 10, viewBox: tree.attrs.find(([key]) => key === 'viewBox')?.[1] || t('viewBoxUnset'), pathCount, removedItems }, + metrics: { + originalBytes, + optimizedBytes: encoded.length, + savedBytes, + savedPercentage: Math.round((savedBytes / originalBytes) * 1000) / 10, + viewBox: dims.viewBox, + width: dims.width, + height: dims.height, + pathCount, + removedItems, + stats + } } } +/** + * 为已净化的 SVG 包装带背景的居中安全预览图(棋盘格透明 / 浅色底 / 深色底)。 + * 全程采用 rgb() 色值与标准矢量嵌套,零 DOM 侵入。 + */ +export function buildPreviewSvgDataUri( + optimizedSvg: string, + width: number, + height: number, + background: PreviewBackground +): string { + const canvasW = 320 + const canvasH = 160 + const padX = 24 + const padY = 16 + const innerW = canvasW - padX * 2 + const innerH = canvasH - padY * 2 + + let checkerId = '__ztools_svg_checker__' + while (optimizedSvg.includes(checkerId)) { + checkerId = `${checkerId}x` + } + + let bgLayer = '' + if (background === 'light') { + bgLayer = `` + } else if (background === 'dark') { + bgLayer = `` + } else { + bgLayer = [ + ``, + '', + '', + '', + '', + `` + ].join('') + } + + // 将外层 替换并注入居中定位与尺寸约束,保留原有 viewBox(无 viewBox 时按推导尺寸补齐) + const wrappedInner = optimizedSvg.replace(/^]*)>/i, (_full, attrPart: string) => { + const hasViewBox = /\bviewBox\s*=/i.test(attrPart) + const cleaned = attrPart + .replace(/\s+\b(?:x|y|width|height|preserveAspectRatio)\s*=\s*"[^"]*"/gi, '') + const vbAttr = hasViewBox ? '' : ` viewBox="0 0 ${Math.max(1, width)} ${Math.max(1, height)}"` + return `` + }) + + const previewSvg = `${bgLayer}${wrappedInner}` + return `data:image/svg+xml;base64,${encodeBase64Utf8(previewSvg)}` +} + +function withExplicitSvgSize(optimizedSvg: string, width: number, height: number): string { + return optimizedSvg.replace(/^]*)>/i, (_full, attrPart: string) => { + const cleaned = attrPart.replace(/\s+\b(?:width|height)\s*=\s*"[^"]*"/gi, '') + return `` + }) +} + +async function blobToBase64(blob: Blob): Promise { + const buf = new Uint8Array(await blob.arrayBuffer()) + let binary = '' + for (const byte of buf) binary += String.fromCharCode(byte) + return btoa(binary) +} + +/** + * 基于浏览器/Electron 渲染进程原生 Image + OffscreenCanvas 将净化后的 SVG 渲染为真实透明背景 PNG(零 DOM 侵入)。 + * 在无 OffscreenCanvas/Image 的纯 Node 环境下诚实抛出 PNG_RENDERER_UNAVAILABLE 错误,绝不造假。 + */ +export async function renderSvgToPng( + optimizedSvg: string, + baseWidth: number, + baseHeight: number, + scale: PngScale = 2 +): Promise { + const targetWidth = Math.round(baseWidth * scale) + const targetHeight = Math.round(baseHeight * scale) + if (!Number.isFinite(targetWidth) || !Number.isFinite(targetHeight) || targetWidth <= 0 || targetHeight <= 0 || targetWidth > 4096 || targetHeight > 4096) { + fail('PNG_INVALID_SIZE', t('errPngInvalidSize')) + } + + const ImageCtor = typeof Image === 'function' ? Image : undefined + const OffscreenCtor = typeof OffscreenCanvas === 'function' ? OffscreenCanvas : undefined + if (!ImageCtor || !OffscreenCtor) { + fail('PNG_RENDERER_UNAVAILABLE', t('errPngRendererUnavailable')) + } + + const sizedSvg = withExplicitSvgSize(optimizedSvg, targetWidth, targetHeight) + const svgDataUrl = `data:image/svg+xml;base64,${encodeBase64Utf8(sizedSvg)}` + + const img = await new Promise((resolve, reject) => { + const image = new ImageCtor() + const timer = setTimeout(() => { + reject(new Error(`PNG_RENDER_FAILED: ${t('errPngRenderFailed')}`)) + }, 8000) + image.onload = () => { + clearTimeout(timer) + resolve(image) + } + image.onerror = () => { + clearTimeout(timer) + reject(new Error(`PNG_RENDER_FAILED: ${t('errPngRenderFailed')}`)) + } + image.src = svgDataUrl + }) + + const canvas = new OffscreenCtor(targetWidth, targetHeight) + const ctx = canvas.getContext('2d') + if (!ctx) fail('PNG_RENDERER_UNAVAILABLE', t('errPngRendererUnavailable')) + ctx.clearRect(0, 0, targetWidth, targetHeight) + ctx.drawImage(img, 0, 0, targetWidth, targetHeight) + const blob = await canvas.convertToBlob({ type: 'image/png' }) + const base64 = await blobToBase64(blob) + if (!base64) fail('PNG_RENDER_FAILED', t('errPngRenderFailed')) + const dataUrl = `data:image/png;base64,${base64}` + + const padding = base64.endsWith('==') ? 2 : base64.endsWith('=') ? 1 : 0 + const bytes = Math.max(0, Math.floor((base64.length * 3) / 4) - padding) + + return { + dataUrl, + base64, + width: targetWidth, + height: targetHeight, + scale, + bytes + } +} let svgHostSeq = 0 @@ -284,3 +850,34 @@ export async function readSvgFileContent(filePath: string): Promise { const read = await callSvgHost<{ content?: string }>('filesystem_read_file', { path: filePath, encoding: 'utf8' }) return typeof read?.content === 'string' ? read.content : '' } + +export async function copyPngImageToClipboard(pngDataUrl: string): Promise { + await callSvgHost('clipboard_copy_image', { image: pngDataUrl }) +} + +export async function saveTextArtifactFile( + content: string, + defaultName: string, + dialogTitle: string, + dialogFilter: string +): Promise { + const picked = await callSvgHost<{ canceled?: boolean; filePath?: string }>('window_show_save_dialog', { + title: dialogTitle, + defaultName, + filters: dialogFilter + }) + if (!picked || picked.canceled || !picked.filePath) return null + await callSvgHost('filesystem_write_file', { path: picked.filePath, content, encoding: 'utf8' }) + return picked.filePath +} + +export async function savePngArtifactFile(pngBase64: string, defaultName: string): Promise { + const picked = await callSvgHost<{ canceled?: boolean; filePath?: string }>('window_show_save_dialog', { + title: t('dialogSavePngTitle'), + defaultName, + filters: t('dialogSavePngFilter') + }) + if (!picked || picked.canceled || !picked.filePath) return null + await callSvgHost('filesystem_write_file', { path: picked.filePath, content: pngBase64, encoding: 'base64' }) + return picked.filePath +} diff --git a/extensions/svg-icon-studio/src/types.ts b/extensions/svg-icon-studio/src/types.ts index 10c32044..3b0e88eb 100644 --- a/extensions/svg-icon-studio/src/types.ts +++ b/extensions/svg-icon-studio/src/types.ts @@ -1,11 +1,40 @@ +export type PreviewBackground = 'checkerboard' | 'light' | 'dark' + +export type PngScale = 1 | 2 | 3 + +export type FloatPrecision = 0 | 1 | 2 | 3 | null + +export interface SvgOptimizeOptions { + /** 路径与几何浮点小数精度;null 表示保留原始精度,默认 2 */ + floatPrecision?: FloatPrecision + /** 是否将静态单色 fill/stroke 转为 currentColor,默认 false */ + useCurrentColor?: boolean + /** 导出的 React/Vue 组件名称(默认 SvgIcon) */ + componentName?: string +} + +export interface SvgOptimizationStats { + removedComments: number + removedMetadata: number + removedEmptyGroups: number + removedDefaultAttrs: number + removedUnusedXmlns: number + removedWhitespaceNodes: number + roundedNumbers: number + currentColorReplacements: number +} + export interface SvgOptimizeMetrics { originalBytes: number optimizedBytes: number savedBytes: number savedPercentage: number viewBox: string + width: number + height: number pathCount: number removedItems: number + stats: SvgOptimizationStats } export interface SvgProcessResult { @@ -15,6 +44,16 @@ export interface SvgProcessResult { vueSfcCode: string dataUri: string base64DataUri: string + componentName: string warnings: string[] metrics: SvgOptimizeMetrics } + +export interface PngExportResult { + dataUrl: string + base64: string + width: number + height: number + scale: PngScale + bytes: number +} diff --git a/extensions/svg-icon-studio/tests/browser-cases.mjs b/extensions/svg-icon-studio/tests/browser-cases.mjs index 969f7672..3bfae8be 100644 --- a/extensions/svg-icon-studio/tests/browser-cases.mjs +++ b/extensions/svg-icon-studio/tests/browser-cases.mjs @@ -45,7 +45,7 @@ test.after(() => { browser.window.close(); fs.rmSync(root, { recursive: true, fo test('真实编译及 SSR:文字、实体、花括号、换行和数值精度在三个格式一致', async () => { const source = svg('标题link 余额 123.4567 元 {1+1} {{7*7}} &quot; < >\n换行 中间 尾部 ') - const result = optimizeSvgSource(source), original = xml(source) + const result = optimizeSvgSource(source, { floatPrecision: null }), original = xml(source) for (const rendered of [xml(result.optimizedSvg), ...await renderComponents(result)]) { assert.equal(rendered.getElementsByTagName('parsererror').length, 0) assert.equal(rendered.getElementsByTagName('text')[1].textContent, original.getElementsByTagName('text')[1].textContent) @@ -62,7 +62,7 @@ test('真实编译及 SSR:文字、实体、花括号、换行和数值精度 }) test('样式使用真实 CSSOM,重复无效声明不覆盖有效值;React 属性类型正确', async () => { - const result = optimizeSvgSource(svg('')) + const result = optimizeSvgSource(svg(''), { floatPrecision: null }) for (const rendered of [xml(result.optimizedSvg), ...await renderComponents(result)]) { const group = rendered.getElementsByTagName('g')[0] assert.equal(group.style.fill, 'red') @@ -102,44 +102,44 @@ test('XML 畸形与输入上限拒绝,自闭合 SVG 与体积增长如实显 assert.match(empty.optimizedSvg, /xmlns=/) }) -test('声明式真实链路:四项结果分别复制;异常新输入清除旧结果;剪贴板校验后才报成功', async () => { +test('声明式真实链路:导出产物分别复制;异常新输入清除旧结果;剪贴板校验后才报成功', async () => { const view = await mount(Command); views.push(view) host.clipboard.text = svg('余额123.4567 ``` {{7*7}}') const result = optimizeSvgSource(host.clipboard.text) - await view.run(view.item('svg-input'), '从剪贴板载入 SVG') - assert.match(host.lastToast().title, /已载入并校验/) - assert.equal(view.items().length, 4); assert.equal(view.tree().props.searchBarAccessory, undefined) + await view.tree().props.filterBar.actions[1].onAction(); await tick() + assert.match(host.lastToast().title, /已载入并完成压缩/) + assert.equal(view.items().length, 8); assert.ok(view.tree().props.searchBarAccessory) const expected = { svg: result.optimizedSvg, react: result.reactTsxCode, vue: result.vueSfcCode, uri: result.dataUri } - for (const item of view.items()) { + for (const id of ['svg', 'react', 'vue', 'uri']) { + const item = view.item(id) const action = view.actions(item)[0] await view.run(item, action.props.title) - assert.equal(host.clipboard.text, expected[item.props.id]) + assert.equal(host.clipboard.text, expected[id]) } await view.run(view.item('uri'), '复制 Base64 Data URI') assert.equal(host.clipboard.text, result.base64DataUri) - assert.match(view.item('svg').props.detail.props.markdown, /^````xml/) + assert.match(view.item('svg').props.detail.props.markdown, /````xml/) host.clipboard.text = '' - await view.tree().props.filterBar.actions[0].onAction(); await tick() + await view.tree().props.filterBar.actions[1].onAction(); await tick() assert.match(host.lastToast().title, /未能载入/) - assert.deepEqual(view.items().map(item => item.props.id), ['svg-input']) - assert.match(view.text(), /INVALID_SVG_DOCUMENT/) + assert.equal(view.items().length, 0) }) test('多行源码表单提交保留换行,格式筛选不修改源码,错误编辑不能替换已有结果', async () => { const view = await mount(Command); views.push(view) - await view.run(view.item('svg-input'), '编辑源码') + await view.tree().props.filterBar.actions[2].onAction(); await tick() const form = await mountPushed(host); views.push(form) const source = svg('第一行\n 第二行') await form.fill('source', source) - await form.run(null, '校验并生成') + await form.run(null, '校验并压缩') assert.match(view.item('svg').props.detail.props.markdown, /第一行\n 第二行/) await view.search('vue'); assert.deepEqual(view.items().map(item => item.props.id), ['vue']) - await view.search(''); await view.tree().props.filterBar.actions[1].onAction(); await tick() + await view.search(''); await view.tree().props.filterBar.actions[2].onAction(); await tick() const badForm = await mountPushed(host); views.push(badForm) assert.equal(badForm.field('source').props.value, source) await badForm.fill('source', '') - await badForm.run(null, '校验并生成') + await badForm.run(null, '校验并压缩') assert.match(host.lastToast().title, /校验未通过/) assert.equal(host.pushed.length, 1) assert.match(view.item('svg').props.detail.props.markdown, /第一行\n 第二行/) @@ -151,19 +151,19 @@ test('延迟剪贴板读取不能覆盖新编辑;卸载丢弃回包;读取 try { bridge.readClipboardText = () => new Promise(done => { resolve = done }) const view = await mount(Command); views.push(view) - await view.run(view.item('svg-input'), '从剪贴板载入 SVG') - await view.run(view.item('svg-input'), '编辑源码') + void view.tree().props.filterBar.actions[1].onAction() + await view.tree().props.filterBar.actions[2].onAction(); await tick() const form = await mountPushed(host); views.push(form) - await form.fill('source', svg('新的编辑')); await form.run(null, '校验并生成') + await form.fill('source', svg('新的编辑')); await form.run(null, '校验并压缩') resolve(svg('过期剪贴板')); await tick() assert.match(view.text(), /新的编辑/); assert.doesNotMatch(view.text(), /过期剪贴板/) assert.equal(host.toasts.length, 0) - await view.tree().props.filterBar.actions[0].onAction(); await tick() + void view.tree().props.filterBar.actions[1].onAction() view.unmount(); resolve(svg('卸载后返回')); await tick() assert.equal(host.toasts.length, 0) bridge.readClipboardText = async () => { throw new Error('读取失败测试') } const failed = await mount(Command); views.push(failed) - await failed.run(failed.item('svg-input'), '从剪贴板载入 SVG') + await failed.tree().props.filterBar.actions[1].onAction(); await tick() assert.match(host.lastToast().title, /未能载入/) assert.match(host.lastToast().message, /读取失败测试/) } finally { bridge.readClipboardText = read } diff --git a/extensions/svg-icon-studio/tests/index.test.mjs b/extensions/svg-icon-studio/tests/index.test.mjs deleted file mode 100644 index 54656a5a..00000000 --- a/extensions/svg-icon-studio/tests/index.test.mjs +++ /dev/null @@ -1,200 +0,0 @@ -import test from 'node:test' -import assert from 'node:assert/strict' -import { setRuntimeLocale } from '@ztools/declarative-ui' -import { createHost, mount, tick } from '../../shared/test-harness.mjs' -import Command, { optimizeSvgSource } from '../dist/index.js' -import { pickSvgFilePath } from '../dist/svg-service.js' - -const host = createHost() -test('无输入不显示示例或虚构成功,缺少解析器明确停止', async () => { - const view = await mount(Command) - try { - assert.deepEqual(view.items().map(item => item.props.id), ['svg-input']) - assert.match(view.text(), /载入 SVG 源码开始/) - assert.throws(() => optimizeSvgSource(''), /EMPTY_SVG_INPUT/) - assert.throws(() => optimizeSvgSource(''), /XML_PARSER_UNAVAILABLE/) - host.clipboard.text = '' - await view.run(view.items()[0], '从剪贴板载入 SVG') - assert.match(view.text(), /XML_PARSER_UNAVAILABLE/) - assert.equal(view.actions(view.items()[0]).some(action => action.type === 'Action.CopyToClipboard'), false) - host.clipboard.text = '' - await view.run(view.items()[0], '从剪贴板载入 SVG') - await tick() - assert.match(host.lastToast().title, /未能载入/) - assert.match(view.text(), /载入 SVG 源码开始/) - } finally { view.unmount() } -}) - -// 借用前端依赖里的 jsdom 提供 XML 解析器;没有安装时跳过(完整的浏览器用例见 browser-cases.mjs) -import { createRequire } from 'node:module' -let JSDOM = null -try { JSDOM = createRequire(new URL('../../../frontend/package.json', import.meta.url))('jsdom').JSDOM } catch { /* 未安装前端依赖 */ } - -test('导出结果的详情里显示清理后 SVG 的真实图片预览(Base64 Data URI,不内联 SVG 标记)', { skip: !JSDOM && '需要 frontend 依赖中的 jsdom' }, async () => { - const previous = globalThis.DOMParser - globalThis.DOMParser = new JSDOM('').window.DOMParser - const view = await mount(Command) - try { - host.clipboard.text = '' - await view.run(view.items()[0], '从剪贴板载入 SVG') - await tick() - const expected = optimizeSvgSource(host.clipboard.text).base64DataUri - for (const item of view.items()) { - const md = item.props.detail.props.markdown - assert.ok(md.startsWith(`![清理后的 SVG 预览](${expected})`), item.props.id) - assert.doesNotMatch(md.split('\n')[0], / { - const { modEnterLabel } = await import('../dist/index.js') - const original = Object.getOwnPropertyDescriptor(globalThis, 'navigator') - const setNav = value => Object.defineProperty(globalThis, 'navigator', { value, configurable: true, writable: true }) - try { - setNav({ platform: 'MacIntel', userAgent: '' }) - assert.equal(modEnterLabel(), '⌘Enter') - const mac = await mount(Command) - try { - const md = mac.item('svg-input').props.detail.props.markdown - assert.match(md, /⌘Enter/); assert.doesNotMatch(md, /Ctrl|⌘\//) - } finally { mac.unmount() } - setNav({ platform: 'Win32', userAgent: 'Mozilla/5.0 (Windows NT 10.0)' }) - assert.equal(modEnterLabel(), 'Ctrl+Enter') - const win = await mount(Command) - try { assert.doesNotMatch(win.item('svg-input').props.detail.props.markdown, /⌘/) } finally { win.unmount() } - setNav(undefined) - assert.equal(modEnterLabel(), 'Ctrl+Enter') - } finally { - if (original) Object.defineProperty(globalThis, 'navigator', original); else delete globalThis.navigator - } -}) - - -test('选择 SVG 文件对话框与原生拖拽接收:支持读取本地 .svg 文件并拒绝非 .svg 文件', { skip: !JSDOM && '需要 frontend 依赖中的 jsdom' }, async () => { - const previous = globalThis.DOMParser - globalThis.DOMParser = new JSDOM('').window.DOMParser - const sampleSvg = '' - host.ipc.window_show_open_dialog = async () => ({ - canceled: false, - filePath: 'D:\\Icons\\logo.svg' - }) - host.ipc.filesystem_get_file_size = async () => ({ size: sampleSvg.length }) - host.ipc.filesystem_read_file = async ({ path: p }) => ({ - content: p.endsWith('dropped.svg') - ? '' - : sampleSvg - }) - - let droppedListener = null - const prevFeatures = globalThis.window?.__ztoolsDeclarativeFeatures - globalThis.window = globalThis.window || {} - globalThis.window.__ztoolsDeclarativeFeatures = { fileInput: false } - globalThis.window.ztools = { - ...(globalThis.window.ztools || {}), - events: { - on(event, cb) { - if (event === 'plugin_files_dropped') droppedListener = cb - return () => { - if (droppedListener === cb) droppedListener = null - } - } - } - } - - const view = await mount(Command) - try { - await view.run(view.item('svg-input'), '选择 SVG 文件…') - await tick(10) - assert.equal(host.lastToast().title, '已载入并校验 SVG') - assert.equal(view.items().length, 4) - - assert.equal(typeof droppedListener, 'function', '应注册 plugin_files_dropped 拖拽监听') - droppedListener({ payload: { files: ['D:\\Icons\\dropped.svg'] } }) - await tick(10) - assert.equal(host.lastToast().title, '已载入并校验 SVG') - assert.match(view.item('svg').props.detail.props.markdown, /viewBox="0 0 24 24"/) - - droppedListener({ payload: { files: ['D:\\Icons\\photo.png'] } }) - await tick(10) - assert.equal(host.lastToast().title, '未能载入有效 SVG') - } finally { - view.unmount() - globalThis.window.__ztoolsDeclarativeFeatures = prevFeatures - assert.equal(droppedListener, null, '卸载时应清理拖拽监听') - globalThis.DOMParser = previous - } -}) - -test('支持通过 pasteFiles 粘贴 .svg 文件与 pasteText 粘贴 SVG 源码文本直接解析', { skip: !JSDOM && '需要 frontend 依赖中的 jsdom' }, async () => { - const previous = globalThis.DOMParser - globalThis.DOMParser = new JSDOM('').window.DOMParser - const sampleSvg = '' - host.ipc.filesystem_get_file_size = async () => ({ size: sampleSvg.length }) - host.ipc.filesystem_read_file = async () => ({ content: sampleSvg }) - - const view = await mount(Command) - try { - await view.pasteFiles(['D:\\Icons\\pasted.svg']) - await tick(10) - assert.equal(host.lastToast().title, '已载入并校验 SVG') - assert.match(view.item('svg').props.detail.props.markdown, /viewBox="0 0 32 32"/) - - await view.pasteText('') - await tick(10) - assert.equal(host.lastToast().title, '已载入并校验 SVG') - assert.match(view.item('svg').props.detail.props.markdown, /viewBox="0 0 48 48"/) - } finally { - view.unmount() - globalThis.DOMParser = previous - } -}) - -test('callSvgHost 英文模式下屏蔽老宿主字符串中文报错并识别顶层 code/details', async () => { - const prevMethods = globalThis.window.__ztoolsElectron.transport.methods - try { - setRuntimeLocale('en-US') - globalThis.window.__ztoolsElectron.transport.methods = { - ...prevMethods, - window_show_open_dialog: async () => ({ - success: false, - error: '老版本宿主返回的中文报错' - }) - } - await assert.rejects( - () => pickSvgFilePath(), - (err) => { - assert.equal(/[\u4e00-\u9fa5]/.test(err.message), false) - assert.match(err.message, /window_show_open_dialog/) - return true - } - ) - - globalThis.window.__ztoolsElectron.transport.methods = { - ...prevMethods, - window_show_open_dialog: async () => ({ - success: false, - code: 'PERMISSION_DENIED', - error: '权限不足' - }) - } - await assert.rejects(() => pickSvgFilePath(), /Permission denied/) - - globalThis.window.__ztoolsElectron.transport.methods = { - ...prevMethods, - window_show_open_dialog: async () => ({ - success: false, - details: { hostCode: 'REQUEST_TIMEOUT' }, - error: '请求超时' - }) - } - await assert.rejects(() => pickSvgFilePath(), /Request timed out/) - } finally { - globalThis.window.__ztoolsElectron.transport.methods = prevMethods - setRuntimeLocale('zh-CN') - } -}) diff --git a/extensions/svg-icon-studio/tests/svg-icon-studio.test.mjs b/extensions/svg-icon-studio/tests/svg-icon-studio.test.mjs new file mode 100644 index 00000000..a653a8fd --- /dev/null +++ b/extensions/svg-icon-studio/tests/svg-icon-studio.test.mjs @@ -0,0 +1,494 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import { createHost, mount, mountPushed, tick } from '../../shared/test-harness.mjs' +import { getDeclarativeBridge } from '@ztools/declarative-ui' +import Command, { + buildPreviewSvgDataUri, + deriveComponentName, + optimizeSvgSource, + renderSvgToPng, + roundPathData +} from '../dist/index.js' + +const SVG_NS = 'http://www.w3.org/2000/svg' +const XML_NS = 'http://www.w3.org/XML/1998/namespace' +const XLINK_NS = 'http://www.w3.org/1999/xlink' +const XMLNS_NS = 'http://www.w3.org/2000/xmlns/' + +function decodeXmlEntities(text) { + return text.replace(/&(#x[0-9a-fA-F]+|#\d+|amp|lt|gt|quot|apos);/g, (m, ent) => { + if (ent === 'amp') return '&' + if (ent === 'lt') return '<' + if (ent === 'gt') return '>' + if (ent === 'quot') return '"' + if (ent === 'apos') return "'" + if (ent.startsWith('#x')) return String.fromCodePoint(parseInt(ent.slice(2), 16)) + if (ent.startsWith('#')) return String.fromCodePoint(parseInt(ent.slice(1), 10)) + return m + }) +} + +/** + * 轻量 XML DOMParser(仅用于纯 Node 无 jsdom 环境的回归测试,真实 XML 节点/属性/命名空间/注释/PI 解析) + */ +class MiniDOMParser { + parseFromString(source) { + const makeParserError = (msg) => { + const errEl = { + nodeType: 1, + localName: 'parsererror', + tagName: 'parsererror', + namespaceURI: 'http://www.mozilla.org/newlayout/xml/parsererror.xml', + attributes: [], + childNodes: [{ nodeType: 3, nodeValue: msg }] + } + return { + documentElement: errEl, + childNodes: [errEl], + getElementsByTagNameNS: (_ns, name) => (name === 'parsererror' ? [errEl] : []) + } + } + + let i = 0 + const len = source.length + const topNodes = [] + const stack = [] + let root = null + + const createElement = (tagName, rawAttrs, parentNsMap) => { + const nsMap = { ...parentNsMap } + const attrs = [] + const seenNames = new Set() + const attrRe = /([A-Za-z_][\w:.-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g + let consumed = 0 + let match + const attrPairs = [] + while ((match = attrRe.exec(rawAttrs)) !== null) { + const between = rawAttrs.slice(consumed, match.index) + if (between.trim()) return { error: 'Malformed attribute syntax' } + consumed = match.index + match[0].length + const name = match[1] + if (seenNames.has(name)) return { error: `Duplicate attribute ${name}` } + seenNames.add(name) + const val = decodeXmlEntities(match[2] !== undefined ? match[2] : match[3]) + attrPairs.push([name, val]) + if (name === 'xmlns') nsMap[''] = val + else if (name.startsWith('xmlns:')) nsMap[name.slice(6)] = val + } + if (rawAttrs.slice(consumed).trim()) return { error: 'Trailing invalid attribute text' } + + for (const [name, value] of attrPairs) { + let namespaceURI = null + let localName = name + if (name === 'xmlns' || name.startsWith('xmlns:')) { + namespaceURI = XMLNS_NS + localName = name === 'xmlns' ? 'xmlns' : name.slice(6) + } else if (name.includes(':')) { + const [prefix, local] = name.split(':', 2) + localName = local + if (prefix === 'xml') namespaceURI = XML_NS + else if (prefix === 'xlink') namespaceURI = nsMap.xlink || XLINK_NS + else namespaceURI = nsMap[prefix] || `urn:unknown:${prefix}` + } + attrs.push({ name, localName, value, namespaceURI }) + } + + let elNs = nsMap[''] || null + let localName = tagName + if (tagName.includes(':')) { + const [prefix, local] = tagName.split(':', 2) + localName = local + elNs = nsMap[prefix] || null + } + + // 模拟最小 SVGElement style CSSOM 供 readStyle 测试 + const styleAttr = attrs.find(a => a.name === 'style')?.value || '' + const styleMap = new Map() + if (styleAttr) { + for (const decl of styleAttr.split(';')) { + const m = decl.match(/^\s*([a-z-]+)\s*:\s*(.+?)\s*$/i) + if (m && m[2] !== 'not-a-color') { + styleMap.set(m[1].toLowerCase(), m[2].trim()) + } + } + } + + return { + element: { + nodeType: 1, + tagName, + localName, + namespaceURI: elNs, + attributes: attrs, + childNodes: [], + _nsMap: nsMap, + style: { + getPropertyValue: (k) => styleMap.get(k) || '', + cssText: [...styleMap.entries()].map(([k, v]) => `${k}: ${v};`).join(' ') + } + } + } + } + + while (i < len) { + if (source.startsWith('', i + 4) + if (end < 0) return makeParserError('Unclosed comment') + const node = { nodeType: 8, nodeValue: source.slice(i + 4, end) } + if (stack.length) stack[stack.length - 1].childNodes.push(node) + else topNodes.push(node) + i = end + 3 + continue + } + if (source.startsWith('', i + 2) + if (end < 0) return makeParserError('Unclosed PI') + const body = source.slice(i + 2, end).trim() + const nodeName = body.split(/\s+/)[0] || '' + const node = { nodeType: 7, nodeName, nodeValue: body } + if (stack.length) stack[stack.length - 1].childNodes.push(node) + else topNodes.push(node) + i = end + 2 + continue + } + if (source[i] === '<') { + if (source[i + 1] === '/') { + const end = source.indexOf('>', i + 2) + if (end < 0) return makeParserError('Unclosed closing tag') + const closeName = source.slice(i + 2, end).trim() + const open = stack.pop() + if (!open || open.tagName !== closeName) return makeParserError(`Mismatched closing tag `) + i = end + 1 + continue + } + const end = source.indexOf('>', i + 1) + if (end < 0) return makeParserError('Unclosed start tag') + let inner = source.slice(i + 1, end) + const selfClosing = inner.endsWith('/') + if (selfClosing) inner = inner.slice(0, -1) + const nameMatch = inner.match(/^([A-Za-z_][\w:.-]*)([\s\S]*)$/) + if (!nameMatch) return makeParserError('Invalid tag name') + const tagName = nameMatch[1] + const rawAttrs = nameMatch[2] + const parentNs = stack.length ? stack[stack.length - 1]._nsMap : {} + const built = createElement(tagName, rawAttrs, parentNs) + if (built.error) return makeParserError(built.error) + const el = built.element + if (stack.length) { + stack[stack.length - 1].childNodes.push(el) + } else { + if (root) return makeParserError('Multiple root elements') + root = el + topNodes.push(el) + } + if (!selfClosing) stack.push(el) + i = end + 1 + continue + } + const nextTag = source.indexOf('<', i) + const rawText = nextTag < 0 ? source.slice(i) : source.slice(i, nextTag) + i = nextTag < 0 ? len : nextTag + if (!stack.length) { + if (rawText.trim()) return makeParserError('Unexpected text outside root') + continue + } + if (/&[A-Za-z_][\w.-]*;/.test(rawText.replace(/&(amp|lt|gt|quot|apos);/g, ''))) { + return makeParserError('Unknown XML entity') + } + stack[stack.length - 1].childNodes.push({ nodeType: 3, nodeValue: decodeXmlEntities(rawText) }) + } + + if (stack.length || !root) return makeParserError('Incomplete XML document') + const hasParserError = (el) => { + if (el.localName === 'parsererror') return true + return el.childNodes.some(c => c.nodeType === 1 && hasParserError(c)) + } + return { + documentElement: root, + childNodes: topNodes, + getElementsByTagNameNS: (_ns, name) => (name === 'parsererror' && hasParserError(root) ? [root] : []) + } + } +} + +globalThis.DOMParser = MiniDOMParser + +const host = createHost() +const views = [] + +test.afterEach(() => { + views.splice(0).forEach(view => view.unmount()) + host.reset() + delete globalThis.__ztoolsElectron + delete globalThis.window + delete globalThis.Image + delete globalThis.OffscreenCanvas +}) + +test('roundPathData 精确收敛浮点并保护 A/a 弧线标志位', () => { + const simple = roundPathData('M 1.23456 2.34567 L 4.000 -5.6789 Z', 2) + assert.equal(simple.value, 'M1.23 2.35L4-5.68Z') + assert.equal(simple.rounded, 4) + + const arc = roundPathData('M10 10 a10.123 10.456 0 015.678 5.432', 2) + assert.equal(arc.value, 'M10 10a10.12 10.46 0 0 1 5.68 5.43') + assert.equal(arc.rounded, 4) +}) + +test('真实 SVGO 级压缩:移除注释/metadata/空组/默认属性/多余xmlns/空白并收敛路径精度', () => { + const messySvg = ` + + + editor-info + + + + + + + + + ` + + const result = optimizeSvgSource(messySvg, { floatPrecision: 2 }) + assert.doesNotMatch(result.optimizedSvg, /Exported from Design Tool|metadata|xmlns:xlink|version=|fill-opacity|stroke-opacity|opacity="1"|stroke-linecap|stroke-linejoin|stroke-miterlimit|fill-rule|<\/g>/) + // 继承保护:父级 内的子 path 显式 stroke-width="1" 必须保留! + assert.match(result.optimizedSvg, //) + // 非继承下的默认 stroke-width="1" 应被清理 + assert.match(result.optimizedSvg, //) + assert.ok(result.metrics.savedBytes > 0) + assert.ok(result.metrics.savedPercentage > 30) + assert.equal(result.metrics.viewBox, '0 0 24 24') + assert.equal(result.metrics.width, 24) + assert.equal(result.metrics.height, 24) + assert.equal(result.metrics.pathCount, 2) + assert.equal(result.metrics.stats.removedComments, 1) + assert.equal(result.metrics.stats.removedMetadata, 1) + assert.ok(result.metrics.stats.removedEmptyGroups >= 3) + assert.ok(result.metrics.stats.removedDefaultAttrs >= 8) + assert.ok(result.metrics.stats.removedUnusedXmlns >= 1) + assert.ok(result.metrics.stats.roundedNumbers >= 6) + + // 验证保留原始精度选项 + const rawPrec = optimizeSvgSource(messySvg, { floatPrecision: null }) + assert.match(rawPrec.optimizedSvg, /M1\.23456 2\.34567/) +}) + +test('currentColor 开关与 React 标准 JSX / 组件名推导', () => { + assert.equal(deriveComponentName('arrow-left.svg'), 'ArrowLeft') + assert.equal(deriveComponentName('24-home_icon.svg'), 'Icon24HomeIcon') + assert.equal(deriveComponentName(''), 'SvgIcon') + + const svg = '' + const result = optimizeSvgSource(svg, { useCurrentColor: true, componentName: 'arrow-left.svg' }) + + assert.equal(result.componentName, 'ArrowLeft') + assert.match(result.optimizedSvg, /fill="currentColor"/) + assert.match(result.optimizedSvg, /stroke="none"/) + assert.match(result.optimizedSvg, /fill="url\(#g\)"/) + assert.match(result.optimizedSvg, /stroke="currentColor"/) + assert.equal(result.metrics.stats.currentColorReplacements, 2) + + // React TSX 必须使用标准 JSX 而非 React.createElement + assert.match(result.reactTsxCode, /export function ArrowLeft\(props: React\.SVGProps\)/) + assert.match(result.reactTsxCode, //) + assert.doesNotMatch(result.reactTsxCode, /React\.createElement/) +}) + +test('安全净化:拒绝 DTD/畸形 XML/循环引用,移除脚本与外链', () => { + assert.throws(() => optimizeSvgSource(''), /EMPTY_SVG_INPUT/) + assert.throws(() => optimizeSvgSource(''), /UNSUPPORTED_DTD/) + assert.throws(() => optimizeSvgSource(''), /INVALID_SVG_DOCUMENT/) + assert.throws(() => optimizeSvgSource(''), /CYCLIC_SVG_REFERENCE/) + assert.throws(() => optimizeSvgSource(''), /MISSING_SVG_REFERENCE/) + + const dirty = '' + const res = optimizeSvgSource(dirty) + assert.doesNotMatch(res.optimizedSvg, /script|foreignObject|onload/) + assert.ok(res.metrics.removedItems >= 3) + assert.ok(res.warnings.length >= 2) +}) + +test('buildPreviewSvgDataUri 支持棋盘格 / 浅色底 / 深色底三种安全背景', () => { + const svg = '' + const checker = Buffer.from(buildPreviewSvgDataUri(svg, 24, 24, 'checkerboard').split(',')[1], 'base64').toString('utf8') + const light = Buffer.from(buildPreviewSvgDataUri(svg, 24, 24, 'light').split(',')[1], 'base64').toString('utf8') + const dark = Buffer.from(buildPreviewSvgDataUri(svg, 24, 24, 'dark').split(',')[1], 'base64').toString('utf8') + + assert.match(checker, / { + const svg = '' + await assert.rejects(() => renderSvgToPng(svg, 24, 24, 2), /PNG_RENDERER_UNAVAILABLE/) + await assert.rejects(() => renderSvgToPng(svg, 5000, 5000, 1), /PNG_INVALID_SIZE/) + + // 模拟浏览器渲染进程 Image + Canvas + const drawCalls = [] + globalThis.Image = class FakeImage { + set src(val) { + this._src = val + queueMicrotask(() => { + if (typeof this.onload === 'function') this.onload() + }) + } + get src() { return this._src } + } + // 最小合法 1x1 透明 PNG base64 + const validPngBase64 = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=' + const validPngBytes = Buffer.from(validPngBase64, 'base64') + globalThis.OffscreenCanvas = class FakeOffscreenCanvas { + constructor(width, height) { + this.width = width + this.height = height + } + getContext(type) { + assert.equal(type, '2d') + return { + clearRect(x, y, w, h) { drawCalls.push({ op: 'clear', x, y, w, h }) }, + drawImage(_img, x, y, w, h) { drawCalls.push({ op: 'draw', x, y, w, h }) } + } + } + async convertToBlob({ type }) { + assert.equal(type, 'image/png') + return { + arrayBuffer: async () => validPngBytes.buffer.slice(validPngBytes.byteOffset, validPngBytes.byteOffset + validPngBytes.byteLength) + } + } + } + + const png2x = await renderSvgToPng(svg, 24, 24, 2) + assert.equal(png2x.width, 48) + assert.equal(png2x.height, 48) + assert.equal(png2x.scale, 2) + assert.equal(png2x.base64, validPngBase64) + assert.equal(png2x.dataUrl, `data:image/png;base64,${validPngBase64}`) + assert.ok(png2x.bytes > 0) + assert.deepEqual(drawCalls, [ + { op: 'clear', x: 0, y: 0, w: 48, h: 48 }, + { op: 'draw', x: 0, y: 0, w: 48, h: 48 } + ]) +}) + +test('声明式 UI 完整链路:常驻三按钮、背景切换、压缩参数、PNG 导出与文件另存为', async () => { + const hostCalls = [] + globalThis.__ztoolsElectron = { + transport: { + methods: { + window_show_save_dialog: async ({ params }) => { + hostCalls.push({ method: 'window_show_save_dialog', params }) + return { success: true, data: { canceled: false, filePath: `E:\\tmp\\${params.defaultName}` } } + }, + filesystem_write_file: async ({ params }) => { + hostCalls.push({ method: 'filesystem_write_file', params }) + return { success: true, data: { written: true } } + }, + clipboard_copy_image: async ({ params }) => { + hostCalls.push({ method: 'clipboard_copy_image', params }) + return { success: true, data: { copied: true } } + } + } + } + } + globalThis.Image = class FakeImage { + set src(val) { + this._src = val + queueMicrotask(() => { if (typeof this.onload === 'function') this.onload() }) + } + } + const validPngBase64 = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=' + const validPngBytes = Buffer.from(validPngBase64, 'base64') + globalThis.OffscreenCanvas = class FakeOffscreenCanvas { + constructor(width, height) { this.width = width; this.height = height } + getContext() { return { clearRect() {}, drawImage() {} } } + async convertToBlob() { + return { + arrayBuffer: async () => validPngBytes.buffer.slice(validPngBytes.byteOffset, validPngBytes.byteOffset + validPngBytes.byteLength) + } + } + } + + const view = await mount(Command) + views.push(view) + + // 1. 空态:零假数据,顶栏常驻 3 按钮 + 右上角背景切换 Dropdown + assert.equal(view.items().length, 0) + const emptyActions = view.tree().props.filterBar.actions.map(a => a.id) + assert.deepEqual(emptyActions, ['pick-file', 'load-clipboard', 'edit-source']) + assert.ok(view.tree().props.searchBarAccessory) + + // 2. 读取剪贴板载入真实 SVG + host.clipboard.text = 'x' + await view.tree().props.filterBar.actions[1].onAction() + await tick() + assert.match(host.lastToast().title, /已载入并完成压缩/) + + // 载入后顶栏仍保留 3 个按钮(解决原“加载后选文件按钮消失”的 P1 问题) + assert.deepEqual(view.tree().props.filterBar.actions.map(a => a.id), ['pick-file', 'load-clipboard', 'edit-source']) + assert.match(view.tree().props.filterBar.summaryText, /->.*-/) + + // 列表应含 5 个导出产物 + 3 个压缩参数 + const ids = view.items().map(i => i.props.id) + assert.deepEqual(ids, ['svg', 'react', 'vue', 'uri', 'png', 'opt-precision', 'opt-current-color', 'opt-png-scale']) + + // 3. 切换背景 Dropdown:checkerboard -> dark + const beforeMd = view.item('svg').props.detail.props.markdown + await view.tree().props.searchBarAccessory.props.onChange('dark') + await tick() + const afterMd = view.item('svg').props.detail.props.markdown + assert.notEqual(beforeMd, afterMd) + const darkPreviewB64 = afterMd.match(/data:image\/svg\+xml;base64,([A-Za-z0-9+/=]+)/)[1] + assert.match(Buffer.from(darkPreviewB64, 'base64').toString('utf8'), /rgb\(24, 24, 27\)/) + + // 4. 开启 currentColor 参数 + await view.run(view.item('opt-current-color'), view.actions(view.item('opt-current-color'))[0].props.title) + assert.match(view.item('svg').props.detail.props.markdown, /fill="currentColor"/) + + // 5. 另存为优化后 SVG 文件 + await view.run(view.item('svg'), '另存为文件…') + assert.ok(hostCalls.some(c => c.method === 'filesystem_write_file' && c.params.encoding === 'utf8' && c.params.path.endsWith('.min.svg'))) + + // 6. 复制 PNG 图片到剪贴板 & 另存为 PNG 文件 + await view.run(view.item('png'), '复制 PNG 图片 (2x)') + assert.ok(hostCalls.some(c => c.method === 'clipboard_copy_image' && c.params.image.startsWith('data:image/png;base64,'))) + await view.run(view.item('png'), '另存为 PNG 文件 (2x)…') + assert.ok(hostCalls.some(c => c.method === 'filesystem_write_file' && c.params.encoding === 'base64' && c.params.path.endsWith('@2x.png'))) + + // 7. 编辑源码表单:非法输入不覆盖旧结果,合法输入可修改组件名 + await view.tree().props.filterBar.actions[2].onAction() + await tick() + const form = await mountPushed(host) + views.push(form) + await form.fill('source', '') + await form.run(null, '校验并压缩') + assert.match(host.lastToast().title, /校验未通过/) + await form.fill('componentName', 'BrandLogo') + await form.fill('source', '') + await form.run(null, '校验并压缩') + assert.match(view.item('react').props.detail.props.markdown, /export function BrandLogo/) +}) + +test('延迟剪贴板读取不能覆盖新编辑;卸载丢弃回包', async () => { + const bridge = getDeclarativeBridge() + const originalRead = bridge.readClipboardText + let resolveClip + try { + bridge.readClipboardText = () => new Promise(done => { resolveClip = done }) + const view = await mount(Command) + views.push(view) + void view.tree().props.filterBar.actions[1].onAction() + await view.tree().props.filterBar.actions[2].onAction() + const form = await mountPushed(host) + views.push(form) + await form.fill('source', '新的编辑') + await form.run(null, '校验并压缩') + resolveClip('过期剪贴板') + await tick() + assert.match(view.item('svg').props.detail.props.markdown, /新的编辑/) + assert.doesNotMatch(view.item('svg').props.detail.props.markdown, /过期剪贴板/) + } finally { + bridge.readClipboardText = originalRead + } +}) diff --git a/extensions/table-converter/plugin.json b/extensions/table-converter/plugin.json index 58159538..455c6d5b 100644 --- a/extensions/table-converter/plugin.json +++ b/extensions/table-converter/plugin.json @@ -1,7 +1,7 @@ { "id": "table-converter", "name": "表格互转", - "version": "1.0.6", + "version": "1.0.7", "minAppVersion": "1.1.8.0", "description": "离线转换 Excel 复制文本/TSV/CSV、JSON 数组、Markdown、HTML 文字表格与 SQLite INSERT,保留长数字和 JSON 类型,回车复制", "author": "ZTools Team", diff --git a/extensions/table-converter/src/host-io.ts b/extensions/table-converter/src/host-io.ts new file mode 100644 index 00000000..e7f90edf --- /dev/null +++ b/extensions/table-converter/src/host-io.ts @@ -0,0 +1,103 @@ +import { t } from './i18n.js' + +let hostCallSeq = 0 + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} + +function resolveHostMethod(method: string): ((req: Record) => Promise) | undefined { + const g = globalThis as { + window?: { __ztoolsElectron?: { transport?: { methods?: Record } } } + __ztoolsElectron?: { transport?: { methods?: Record } } + } + const methods = g.window?.__ztoolsElectron?.transport?.methods ?? g.__ztoolsElectron?.transport?.methods + const fn = methods?.[method] + return typeof fn === 'function' ? (fn as (req: Record) => Promise) : undefined +} + +async function callTableHost(method: string, params: Record, missingErrorKey: 'errHostNoReadFile' | 'errHostNoWriteFile' | 'errHostNoOpenDialog' | 'errHostNoSaveDialog', fallbackErrorKey: 'errReadFileFailed' | 'errWriteFileFailed'): Promise { + const fn = resolveHostMethod(method) + if (!fn) throw new Error(t(missingErrorKey)) + hostCallSeq = (hostCallSeq + 1) % 1_000_000 + const raw = await fn({ + messageId: `table_io_${Date.now()}_${hostCallSeq}`, + params + }) + if (isRecord(raw) && raw.success === false) { + const err = raw.error + const msg = isRecord(err) + ? String(err.message || err.code || t(fallbackErrorKey)) + : String(err || t(fallbackErrorKey)) + throw new Error(msg) + } + return isRecord(raw) && 'data' in raw ? raw.data : raw +} + +export async function pickTableFileFromHost(): Promise<{ canceled: boolean; filePath?: string }> { + const data = await callTableHost( + 'window_show_open_dialog', + { + title: t('dialogPickTitle'), + filters: t('dialogPickFilter'), + properties: ['openFile'] + }, + 'errHostNoOpenDialog', + 'errReadFileFailed' + ) + if (!isRecord(data) || data.canceled) return { canceled: true } + const firstFromList = Array.isArray(data.filePaths) && data.filePaths.length > 0 + ? (typeof data.filePaths[0] === 'string' + ? data.filePaths[0] + : isRecord(data.filePaths[0]) && typeof data.filePaths[0].path === 'string' + ? data.filePaths[0].path + : '') + : '' + const filePath = (typeof data.filePath === 'string' && data.filePath.trim()) || firstFromList.trim() + if (!filePath) return { canceled: true } + return { canceled: false, filePath } +} + +export async function readTableFileFromHost(filePath: string): Promise { + const data = await callTableHost( + 'filesystem_read_file', + { path: filePath, encoding: 'utf8' }, + 'errHostNoReadFile', + 'errReadFileFailed' + ) + if (typeof data === 'string') return data + if (isRecord(data) && typeof data.content === 'string') return data.content + throw new Error(t('errReadFileInvalid')) +} + +export async function saveTableFileToHost( + content: string, + defaultName: string, + filters: string +): Promise<{ canceled: boolean; filePath?: string }> { + const dialogData = await callTableHost( + 'window_show_save_dialog', + { + title: t('dialogSaveTitle'), + defaultName, + filters + }, + 'errHostNoSaveDialog', + 'errWriteFileFailed' + ) + if (!isRecord(dialogData) || dialogData.canceled) return { canceled: true } + const filePath = typeof dialogData.filePath === 'string' ? dialogData.filePath.trim() : '' + if (!filePath) return { canceled: true } + await callTableHost( + 'filesystem_write_file', + { + path: filePath, + content, + encoding: 'utf8', + overwrite: true + }, + 'errHostNoWriteFile', + 'errWriteFileFailed' + ) + return { canceled: false, filePath } +} diff --git a/extensions/table-converter/src/i18n.ts b/extensions/table-converter/src/i18n.ts index 61711bb1..ac15cca1 100644 --- a/extensions/table-converter/src/i18n.ts +++ b/extensions/table-converter/src/i18n.ts @@ -3,7 +3,7 @@ import { createTranslator } from "@ztools/declarative-ui"; const rawT = createTranslator( { "zh-CN": { - errDelimiterOnly: "仅支持逗号或制表符分隔。", + errDelimiterOnly: "仅支持逗号、制表符、分号或竖线分隔。", errQuotedPosition: "分隔表格的引号位置不正确,请使用成对双引号,并将内部引号写成两个双引号。", errUnclosedQuote: "分隔表格存在未闭合的双引号。", errUnsupportedHtmlEntity: "表格含暂不支持的 HTML 字符实体,请先改为文字或数字实体。", @@ -30,7 +30,7 @@ const rawT = createTranslator( errJsonMustBeArray: "JSON 输入必须是对象数组或二维数组。", errJsonMixedRows: "JSON 每行必须都是对象,或每行都是数组,不能混合。", errClipboardLimit: "输出超过剪贴板 8 MiB 上限,请拆分输入后转换。", - errSqlSyntax: "SQL INSERT {msg};仅支持 SQLite 常量 VALUES 语句。", + errSqlSyntax: "SQL INSERT {msg};仅支持常量 VALUES 语句。", errSqlUnclosedQuote: "SQL 中存在未闭合的引号。", errSqlMissingTableOrCol: "缺少表名或列名", errSqlUnsupportedExpr: "含不支持的表达式", @@ -42,77 +42,143 @@ const rawT = createTranslator( errSqlMissingRow: "缺少数据行", errSqlUnclosedRow: "数据行未闭合或包含表达式", errSqlSingleStmtOnly: "一次仅支持一条 INSERT VALUES;不接受后续语句、注释或表达式。", - errSqlCaseInsensitiveCol: "SQLite 列名不能仅有英文字母大小写差异,请修改表头或使用其他输出格式。", + errSqlCaseInsensitiveCol: "SQL 列名不能仅有英文字母大小写差异,请修改表头或使用其他输出格式。", errSqlEmptyOrNulName: "SQL 表名和列名不能为空或包含 NUL 字符。", - errSqlNulText: "SQLite SQL 文本不能直接包含 NUL,请使用 JSON 或 CSV 输出。", + errSqlNulText: "SQL 文本不能直接包含 NUL,请使用 JSON 或 CSV 输出。", errInputCharLimit: "单次输入最多 200 万字符,请拆分后转换。", targetMdTitle: "Markdown 对齐表格", targetMdSub: "文字表格;嵌套值转为 JSON 文本", - targetMdBadge: "文档", + targetMdBadgeSource: "源码", + targetMdBadgeRendered: "渲染", + targetTsvTitle: "TSV(Excel / 飞书直贴)", + targetTsvSub: "Tab 制表符分隔;直接粘贴进 Excel / WPS / 飞书表格自动分列", + targetTsvBadge: "Tab 分隔", targetJsonTitle: "JSON 结构化对象数组", targetJsonSub: "保留 JSON 原类型;文本列仅推断可安全转换的数字和布尔值", - targetJsonBadge: "结构数据", - targetSqlTitle: "SQLite INSERT 语句({table})", - targetSqlSub: "SQLite 字面量语法;嵌套值转为 JSON 文本,缺失键映射 NULL", - errSqlNoDataRows: "没有数据行,无法生成 INSERT 语句。首行已作为表头时,请补充数据行或切换为“无表头”。", + targetJsonBadgePretty: "格式化", + targetJsonBadgeCompact: "压缩", + targetSqlTitle: "SQL ({dialect}) · {table}", + targetSqlSubInsertOnly: "{dialect} 批量 INSERT 语句;嵌套值转为 JSON 文本,缺失键映射 NULL", + targetSqlSubWithDdl: "{dialect} CREATE TABLE 建表 DDL + 批量 INSERT 语句", + targetSqlBadgeDdl: "含 DDL", + errSqlNoDataRows: "没有数据行,无法生成 INSERT 语句。请补充数据行、开启 CREATE TABLE DDL 或切换为“无表头”。", targetHtmlTitle: "HTML 表格源码", targetHtmlSub: "文字表格;单元格内容转义后输出", - targetHtmlBadge: "网页", + targetHtmlBadge: "
", targetCsvTitle: "CSV 表格", + targetCsvTitleBom: "CSV(UTF-8 BOM)", targetCsvSub: "CRLF 分行;null 与缺失键输出为空单元格,嵌套值为 JSON 文本", - targetCsvBadge: "表格文本", - previewTruncatedNote: "\n(预览已截断,复制包含完整结果)", + targetCsvSubBom: "带 UTF-8 BOM 防 Excel 打开中文乱码;CRLF 分行", + targetCsvBadgeBom: "防乱码", + targetCsvBadgePlain: "UTF-8", + previewTruncatedNote: "\n(仅预览前 100 行,复制/另存为包含全部结果)", errSqlTableNameInvalid: "请填写不含 NUL 字符的 SQL 表名。", toastInputInvalid: "输入尚不能转换,原文已保留", - formNavTitle: "编辑表格输入", + formNavTitle: "编辑表格源码与参数", formSubmitTitle: "应用输入", formFieldText: "原始表格", - formFieldTextInfo: "最多 200 万字符;Excel 请复制单元格文本,不能直接读取 xlsx 文件。", + formFieldTextInfo: "最多 200 万字符;Excel 请复制单元格文本或选择本地 .csv/.tsv 文件。", formFieldSource: "输入格式", + formFieldDelimiter: "自定义分隔符", + delimiterAuto: "自动识别", + delimiterComma: "逗号 (,)", + delimiterTab: "制表符 (Tab)", + delimiterSemicolon: "分号 (;)", + delimiterPipe: "竖线 (|)", sourceAuto: "自动识别", sourceTsv: "TSV / Excel 复制文本", sourceJson: "JSON 数组", sourceMarkdown: "Markdown 表格", sourceHtml: "HTML 文字表格", - sourceSql: "SQLite INSERT VALUES", + sourceSql: "SQL INSERT VALUES", formFieldSqlTable: "输出 SQL 表名", - formFieldSqlTableInfo: "生成 SQLite INSERT 文本,不连接或执行数据库操作。", + formFieldSqlTableInfo: "仅离线生成 SQL 文本,不连接或执行数据库操作。", + formFieldSqlDialect: "SQL 方言", + formFieldSqlDdl: "建表语句", + formFieldSqlDdlLabel: "包含 CREATE TABLE DDL 推断语句", errHostNoReadFile: "当前客户端不支持读取本地文件", + errHostNoWriteFile: "当前客户端不支持保存本地文件", + errHostNoOpenDialog: "当前客户端不支持打开文件选择器", + errHostNoSaveDialog: "当前客户端不支持打开保存对话框", errReadFileFailed: "读取文件失败", errReadFileInvalid: "文件读取结果无效", - goalMarkdown: "粘贴表格后生成 Markdown 表格", - goalJson: "粘贴表格后生成 JSON 对象数组", - goalSql: "粘贴表格后生成 SQL INSERT", - goalDefault: "粘贴表格后生成 Markdown、JSON、SQL、HTML 或 CSV", + errWriteFileFailed: "保存文件失败", + dialogPickTitle: "选择表格文件", + dialogPickFilter: "表格文件 (*.csv, *.tsv, *.json, *.md, *.sql, *.txt)|*.csv;*.tsv;*.json;*.md;*.sql;*.txt", + dialogSaveTitle: "另存为表格文件", + dialogFilterCsv: "CSV 表格 (*.csv)|*.csv", + dialogFilterTsv: "TSV 表格 (*.tsv)|*.tsv", + dialogFilterJson: "JSON 文件 (*.json)|*.json", + dialogFilterMd: "Markdown 文件 (*.md)|*.md", + dialogFilterSql: "SQL 脚本 (*.sql)|*.sql", + dialogFilterHtml: "HTML 文件 (*.html)|*.html", + goalMarkdown: "点击选择文件、拖入 .csv/.tsv/.json/.md/.sql 或读取剪贴板,即可生成 Markdown 表格", + goalJson: "点击选择文件、拖入 .csv/.tsv/.json/.md/.sql 或读取剪贴板,即可生成 JSON 对象数组", + goalSql: "点击选择文件、拖入 .csv/.tsv/.json/.md/.sql 或读取剪贴板,即可生成多方言 SQL 与 DDL", + goalDefault: "点击选择文件、拖入 .csv/.tsv/.json/.md/.sql 或粘贴表格文本,离线互转 Markdown / TSV / JSON / SQL / CSV / HTML", errClipboardReadBanner: "剪贴板读取失败,保留上一次输入。", toastClipboardReadFailed: "未能读取剪贴板", summaryParseError: "解析失败,原文保留,可编辑后重试。", - summaryUnrecognized: "未识别到表格", + summaryUnrecognized: "未识别到表格,可选择本地文件或编辑源码。", summaryDimensions: "{format} · {rows} 行 × {cols} 列", + summaryFromFile: "来源: {fileName} ({rows} 行 × {cols} 列)", + actionPickFile: "选择文件", actionReadClipboard: "读取剪贴板", - actionEditInput: "编辑输入", + actionEditInput: "编辑源码", + actionSaveFile: "另存为文件", + actionToggleTranspose: "切换行列转置", + actionToggleBom: "切换 CSV UTF-8 BOM", + actionToggleMdPreview: "切换 Markdown 源码/渲染预览", + actionToggleJsonPretty: "切换 JSON 格式化/压缩", + actionToggleSqlDdl: "切换包含 CREATE TABLE DDL", + actionSqlDialectMenu: "切换 SQL 方言", + actionSqlDialectOption: "使用 {dialect} 方言", + toastSavedFile: "已保存文件", + toastSaveFileFailed: "保存文件失败", errFileReadBanner: "文件读取失败,保留上一次输入。", toastFileReadFailed: "未能读取表格文件", navTitle: "表格互转", - searchPlaceholder: "筛选输出格式(Markdown / JSON / SQL / HTML / CSV)", + searchPlaceholder: "过滤目标格式 (Markdown / TSV / JSON / SQL / CSV / HTML)...", headerModeTooltip: "表头识别模式", - headerFirstRow: "首行为表头", - headerNoHeader: "无表头,自动命名列", + headerFirstRow: "表头: 首行表头", + headerNoHeader: "表头: 自动列名", itemParseErrorTitle: "无法转换当前输入", itemParseErrorSub: "原文已保留,可编辑后重试", - itemNotTableTitle: "剪贴板内容不像表格,请粘贴 CSV/TSV/Markdown 表格", + itemNotTableTitle: "当前内容不像表格数据", itemNoMatchTitle: "没有匹配的输出格式", itemWaitingTitle: "等待表格数据", - metaSizeTitle: "数据规模", + metaSourceTitle: "识别来源", + metaSizeTitle: "数据维度", metaSizeText: "{rows} 行 × {cols} 列", metaCharsTitle: "输出字符数", metaTypesTitle: "列类型", + metaOptionsTitle: "选项状态", metaHeaderTitle: "表头处理", + metaStateOn: "开", + metaStateOff: "关", + metaOptTranspose: "转置[{state}]", + metaOptPreviewSource: "预览[源码]", + metaOptPreviewRendered: "预览[渲染]", + metaOptBom: "UTF-8 BOM[{state}]", + metaOptDdl: "DDL[{state}]", + metaOptJsonPretty: "JSON[格式化]", + metaOptJsonCompact: "JSON[压缩]", + srcDescCsvComma: "CSV (逗号分隔)", + srcDescCsvSemicolon: "CSV (分号分隔)", + srcDescCsvPipe: "CSV (竖线分隔)", + srcDescTsv: "TSV (Tab 分隔)", + srcDescJson: "JSON 数组", + srcDescMarkdown: "Markdown 表格", + srcDescHtml: "HTML 表格", + srcDescSql: "SQL INSERT", actionCopyResult: "复制转换结果", - actionPasteResult: "直接上屏粘贴" + actionPasteResult: "直接上屏粘贴", + sectionOutputActions: "输出与保存", + sectionFormatOptions: "格式与清洗选项", + sectionInputActions: "数据源" }, "en-US": { - errDelimiterOnly: "Only comma or tab delimiters are supported.", + errDelimiterOnly: "Only comma, tab, semicolon, or pipe delimiters are supported.", errQuotedPosition: "Invalid quote placement; wrap fields in matching double quotes and escape inner quotes as \"\".", errUnclosedQuote: "Unclosed double quote in delimited table.", errUnsupportedHtmlEntity: "Table contains unsupported HTML character entities; use plain text or numeric entities.", @@ -139,7 +205,7 @@ const rawT = createTranslator( errJsonMustBeArray: "JSON input must be an array of objects or a 2D array.", errJsonMixedRows: "JSON rows must all be objects or all be arrays, not mixed.", errClipboardLimit: "Output exceeds 8 MiB clipboard limit; split input first.", - errSqlSyntax: "SQL INSERT {msg}; only SQLite literal VALUES statements are supported.", + errSqlSyntax: "SQL INSERT {msg}; only literal VALUES statements are supported.", errSqlUnclosedQuote: "Unclosed quote in SQL.", errSqlMissingTableOrCol: "missing table or column name", errSqlUnsupportedExpr: "contains unsupported expression", @@ -151,74 +217,140 @@ const rawT = createTranslator( errSqlMissingRow: "missing data row", errSqlUnclosedRow: "Unclosed data row or contains expressions", errSqlSingleStmtOnly: "Only a single INSERT VALUES statement is supported; trailing statements, comments, or expressions are rejected.", - errSqlCaseInsensitiveCol: "SQLite column names cannot differ only by case; rename headers or choose another format.", + errSqlCaseInsensitiveCol: "SQL column names cannot differ only by case; rename headers or choose another format.", errSqlEmptyOrNulName: "SQL table and column names cannot be empty or contain NUL bytes.", - errSqlNulText: "SQLite SQL text cannot contain NUL bytes; use JSON or CSV instead.", + errSqlNulText: "SQL text cannot contain NUL bytes; use JSON or CSV instead.", errInputCharLimit: "Input exceeds 2,000,000 characters; split input first.", targetMdTitle: "Markdown Aligned Table", targetMdSub: "Text table; nested values serialized as JSON", - targetMdBadge: "Docs", + targetMdBadgeSource: "Source", + targetMdBadgeRendered: "Rendered", + targetTsvTitle: "TSV (Excel / Sheets Paste)", + targetTsvSub: "Tab-separated; paste directly into Excel, WPS, or Lark Sheets", + targetTsvBadge: "Tab", targetJsonTitle: "JSON Object Array", targetJsonSub: "Preserves JSON types; safely infers numbers and booleans", - targetJsonBadge: "JSON", - targetSqlTitle: "SQLite INSERT ({table})", - targetSqlSub: "SQLite literals; nested values as JSON, missing keys as NULL", - errSqlNoDataRows: "No data rows to generate INSERT statements. Add rows or switch to No Header.", + targetJsonBadgePretty: "Pretty", + targetJsonBadgeCompact: "Compact", + targetSqlTitle: "SQL ({dialect}) · {table}", + targetSqlSubInsertOnly: "{dialect} batch INSERT; nested values as JSON, missing keys as NULL", + targetSqlSubWithDdl: "{dialect} inferred CREATE TABLE DDL + batch INSERT", + targetSqlBadgeDdl: "With DDL", + errSqlNoDataRows: "No data rows to generate INSERT statements. Add rows, enable CREATE TABLE DDL, or switch to No Header.", targetHtmlTitle: "HTML Table Source", targetHtmlSub: "Text table with escaped cell content", - targetHtmlBadge: "Web", + targetHtmlBadge: "
", targetCsvTitle: "CSV Table", + targetCsvTitleBom: "CSV (UTF-8 BOM)", targetCsvSub: "CRLF line endings; null/missing as empty, nested values as JSON", - targetCsvBadge: "CSV", - previewTruncatedNote: "\n(Preview truncated; copy includes full output)", + targetCsvSubBom: "UTF-8 BOM prevents garbled CJK text in Excel; CRLF endings", + targetCsvBadgeBom: "BOM", + targetCsvBadgePlain: "UTF-8", + previewTruncatedNote: "\n(Preview truncated to first 100 lines; copy/save includes full output)", errSqlTableNameInvalid: "Enter a SQL table name without NUL characters.", toastInputInvalid: "Unable to convert input; original text preserved", - formNavTitle: "Edit Table Input", + formNavTitle: "Edit Table Source & Options", formSubmitTitle: "Apply Input", formFieldText: "Raw Table", - formFieldTextInfo: "Max 2,000,000 chars; copy cells from Excel (xlsx files cannot be read directly).", + formFieldTextInfo: "Max 2,000,000 chars; copy cells from Excel or pick a local .csv/.tsv file.", formFieldSource: "Input Format", + formFieldDelimiter: "Custom Delimiter", + delimiterAuto: "Auto Detect", + delimiterComma: "Comma (,)", + delimiterTab: "Tab (\\t)", + delimiterSemicolon: "Semicolon (;)", + delimiterPipe: "Pipe (|)", sourceAuto: "Auto Detect", sourceTsv: "TSV / Excel Clipboard", sourceJson: "JSON Array", sourceMarkdown: "Markdown Table", sourceHtml: "HTML Table", - sourceSql: "SQLite INSERT VALUES", + sourceSql: "SQL INSERT VALUES", formFieldSqlTable: "Output SQL Table", - formFieldSqlTableInfo: "Generates SQLite INSERT text only; no database connection.", + formFieldSqlTableInfo: "Generates offline SQL text only; no database connection.", + formFieldSqlDialect: "SQL Dialect", + formFieldSqlDdl: "DDL Statement", + formFieldSqlDdlLabel: "Include inferred CREATE TABLE DDL", errHostNoReadFile: "Client does not support reading local files", + errHostNoWriteFile: "Client does not support saving local files", + errHostNoOpenDialog: "Client does not support file open dialog", + errHostNoSaveDialog: "Client does not support file save dialog", errReadFileFailed: "Failed to read file", errReadFileInvalid: "Invalid file read result", - goalMarkdown: "Paste a table to generate Markdown", - goalJson: "Paste a table to generate JSON object array", - goalSql: "Paste a table to generate SQL INSERT", - goalDefault: "Paste a table to generate Markdown, JSON, SQL, HTML, or CSV", + errWriteFileFailed: "Failed to save file", + dialogPickTitle: "Select Table File", + dialogPickFilter: "Table Files (*.csv, *.tsv, *.json, *.md, *.sql, *.txt)|*.csv;*.tsv;*.json;*.md;*.sql;*.txt", + dialogSaveTitle: "Save Table File As", + dialogFilterCsv: "CSV Table (*.csv)|*.csv", + dialogFilterTsv: "TSV Table (*.tsv)|*.tsv", + dialogFilterJson: "JSON File (*.json)|*.json", + dialogFilterMd: "Markdown File (*.md)|*.md", + dialogFilterSql: "SQL Script (*.sql)|*.sql", + dialogFilterHtml: "HTML File (*.html)|*.html", + goalMarkdown: "Choose a file, drop .csv/.tsv/.json/.md/.sql, or read clipboard to generate a Markdown table", + goalJson: "Choose a file, drop .csv/.tsv/.json/.md/.sql, or read clipboard to generate a JSON object array", + goalSql: "Choose a file, drop .csv/.tsv/.json/.md/.sql, or read clipboard to generate multi-dialect SQL & DDL", + goalDefault: "Choose a file, drop .csv/.tsv/.json/.md/.sql, or paste table text to convert across Markdown, TSV, JSON, SQL, CSV, and HTML", errClipboardReadBanner: "Failed to read clipboard; previous input preserved.", toastClipboardReadFailed: "Unable to Read Clipboard", summaryParseError: "Parse failed; original input preserved for editing.", - summaryUnrecognized: "Unrecognized table", + summaryUnrecognized: "Unrecognized table; pick a local file or edit source.", summaryDimensions: "{format} · {rows} [[rows:row|rows]] × {cols} [[cols:col|cols]]", + summaryFromFile: "Source: {fileName} ({rows} [[rows:row|rows]] × {cols} [[cols:col|cols]])", + actionPickFile: "Choose File", actionReadClipboard: "Read Clipboard", - actionEditInput: "Edit Input", + actionEditInput: "Edit Source", + actionSaveFile: "Save As File", + actionToggleTranspose: "Toggle Transpose Rows/Cols", + actionToggleBom: "Toggle CSV UTF-8 BOM", + actionToggleMdPreview: "Toggle Markdown Source/Rendered", + actionToggleJsonPretty: "Toggle JSON Pretty/Compact", + actionToggleSqlDdl: "Toggle CREATE TABLE DDL", + actionSqlDialectMenu: "Switch SQL Dialect", + actionSqlDialectOption: "Use {dialect} Dialect", + toastSavedFile: "File Saved", + toastSaveFileFailed: "Failed to Save File", errFileReadBanner: "Failed to read file; previous input preserved.", toastFileReadFailed: "Unable to Read Table File", navTitle: "Table Converter", - searchPlaceholder: "Filter output format (Markdown / JSON / SQL / HTML / CSV)", + searchPlaceholder: "Filter target format (Markdown / TSV / JSON / SQL / CSV / HTML)...", headerModeTooltip: "Header Mode", - headerFirstRow: "First Row as Header", - headerNoHeader: "No Header (Auto-Name)", + headerFirstRow: "Header: First Row", + headerNoHeader: "Header: Auto-Name", itemParseErrorTitle: "Unable to Convert Input", itemParseErrorSub: "Original text preserved; edit and retry", - itemNotTableTitle: "Clipboard content does not look like a table; paste CSV/TSV/Markdown", + itemNotTableTitle: "Content does not look like a table", itemNoMatchTitle: "No matching output format", itemWaitingTitle: "Waiting for Table Data", + metaSourceTitle: "Detected Source", metaSizeTitle: "Dimensions", metaSizeText: "{rows} [[rows:row|rows]] × {cols} [[cols:col|cols]]", metaCharsTitle: "Output Length", metaTypesTitle: "Column Types", + metaOptionsTitle: "Options", metaHeaderTitle: "Headers", + metaStateOn: "On", + metaStateOff: "Off", + metaOptTranspose: "Transpose[{state}]", + metaOptPreviewSource: "Preview[Source]", + metaOptPreviewRendered: "Preview[Rendered]", + metaOptBom: "UTF-8 BOM[{state}]", + metaOptDdl: "DDL[{state}]", + metaOptJsonPretty: "JSON[Pretty]", + metaOptJsonCompact: "JSON[Compact]", + srcDescCsvComma: "CSV (Comma)", + srcDescCsvSemicolon: "CSV (Semicolon)", + srcDescCsvPipe: "CSV (Pipe)", + srcDescTsv: "TSV (Tab)", + srcDescJson: "JSON Array", + srcDescMarkdown: "Markdown Table", + srcDescHtml: "HTML Table", + srcDescSql: "SQL INSERT", actionCopyResult: "Copy Result", - actionPasteResult: "Paste to Active App" + actionPasteResult: "Paste to Active App", + sectionOutputActions: "Output & Save", + sectionFormatOptions: "Format & Transform", + sectionInputActions: "Data Source" } }, { defaultLocale: "en-US" } diff --git a/extensions/table-converter/src/index.tsx b/extensions/table-converter/src/index.tsx index 8833b358..d43f6534 100644 --- a/extensions/table-converter/src/index.tsx +++ b/extensions/table-converter/src/index.tsx @@ -1,42 +1,78 @@ -import React, { Action, ActionPanel, Clipboard, Icon, List, Toast, showToast, useEffect, useLocale, useMemo, useState, useRef, useNavigation } from '@ztools/declarative-ui' -import { buildAllConversionTargets, detectAndParse, fencedPreview } from './table-service.js' +import React, { + Action, + ActionPanel, + Clipboard, + Icon, + List, + Toast, + showToast, + useEffect, + useLocale, + useMemo, + useNavigation, + useRef, + useState +} from '@ztools/declarative-ui' +import { + buildAllConversionTargets, + detectAndParse, + fencedPreview, + sqlDialectLabel, + transposeGrid +} from './table-service.js' +import { pickTableFileFromHost, readTableFileFromHost, saveTableFileToHost } from './host-io.js' import { TableInputForm } from './input-form.js' import { createCompatFileInputProps } from './host-compat.js' -import type { SourceFormat } from './types.js' +import type { + ConversionTargetId, + DelimiterOption, + DetectedSourceFormat, + SourceFormat, + SqlDialect, + TableConversionTarget +} from './types.js' import { t } from './i18n.js' + export * from './types.js' export * from './table-service.js' -let tableFileSeq = 0 +const SUPPORTED_EXTENSIONS = ['.csv', '.tsv', '.json', '.md', '.sql', '.txt'] -function isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value) +function extractBaseName(filePath: string): string { + const parts = filePath.split(/[\\/]/) + return parts[parts.length - 1] || filePath } -async function readTableFileFromHost(filePath: string): Promise { - const g = globalThis as { - window?: { __ztoolsElectron?: { transport?: { methods?: Record } } } - __ztoolsElectron?: { transport?: { methods?: Record } } - } - const methods = g.window?.__ztoolsElectron?.transport?.methods ?? g.__ztoolsElectron?.transport?.methods - const fn = methods?.filesystem_read_file - if (typeof fn !== 'function') { - throw new Error(t('errHostNoReadFile')) +function buildDefaultSaveName(sourceFileName: string, extension: string): string { + if (!sourceFileName) return `table${extension}` + const stem = sourceFileName.replace(/\.[^.\\/]+$/, '') || 'table' + return `${stem}${extension}` +} + +function saveDialogFilterForTarget(id: ConversionTargetId): string { + switch (id) { + case 'markdown': return t('dialogFilterMd') + case 'tsv': return t('dialogFilterTsv') + case 'json': return t('dialogFilterJson') + case 'sql': return t('dialogFilterSql') + case 'csv': return t('dialogFilterCsv') + case 'html': return t('dialogFilterHtml') } - tableFileSeq = (tableFileSeq + 1) % 1_000_000 - const raw = await (fn as (req: Record) => Promise)({ - messageId: `table_file_${Date.now()}_${tableFileSeq}`, - params: { path: filePath, encoding: 'utf8' } - }) - if (isRecord(raw) && raw.success === false) { - const err = raw.error - const msg = isRecord(err) ? String(err.message || err.code || t('errReadFileFailed')) : String(err || t('errReadFileFailed')) - throw new Error(msg) +} + +function describeDetectedSource(format?: DetectedSourceFormat, delimiter?: ',' | '\t' | ';' | '|'): string { + switch (format) { + case 'csv': + if (delimiter === ';') return t('srcDescCsvSemicolon') + if (delimiter === '|') return t('srcDescCsvPipe') + return t('srcDescCsvComma') + case 'tsv': return t('srcDescTsv') + case 'json': return t('srcDescJson') + case 'markdown': return t('srcDescMarkdown') + case 'html': return t('srcDescHtml') + case 'sql': return t('srcDescSql') + default: return '' } - const data = isRecord(raw) && 'data' in raw ? raw.data : raw - if (typeof data === 'string') return data - if (isRecord(data) && typeof data.content === 'string') return data.content - throw new Error(t('errReadFileInvalid')) } export interface TableConverterCommandProps { @@ -45,6 +81,8 @@ export interface TableConverterCommandProps { initialHeaderMode?: 'first-row-header' | 'no-header' initialSqlTableName?: string initialSourceFormat?: SourceFormat + initialSqlDialect?: SqlDialect + initialSqlIncludeDdl?: boolean } /** 空状态说明:按入口写明目标,没有专门入口时列出全部输出格式 */ @@ -60,24 +98,76 @@ export function featureGoal(featureCode?: string): string { export function TableConverterCommand(props: TableConverterCommandProps = {}) { const locale = useLocale() const [rawText, setRawText] = useState(props.initialRawText ?? '') - const [headerMode, setHeaderMode] = useState(props.initialHeaderMode ?? 'first-row-header') + const [sourceFileName, setSourceFileName] = useState('') + const [headerMode, setHeaderMode] = useState<'first-row-header' | 'no-header'>(props.initialHeaderMode ?? 'first-row-header') const [sqlTableName, setSqlTableName] = useState(props.initialSqlTableName ?? 'my_table') + const [sqlDialect, setSqlDialect] = useState(props.initialSqlDialect ?? 'sqlite') + const [sqlIncludeDdl, setSqlIncludeDdl] = useState(props.initialSqlIncludeDdl ?? false) + const [csvBom, setCsvBom] = useState(true) + const [jsonPretty, setJsonPretty] = useState(true) + const [markdownRendered, setMarkdownRendered] = useState(false) + const [transpose, setTranspose] = useState(false) const [source, setSource] = useState(props.initialSourceFormat ?? 'auto') + const [delimiter, setDelimiter] = useState('auto') const [searchText, setSearchText] = useState('') const [isReading, setIsReading] = useState(false) const [readErrorKey, setReadErrorKey] = useState<'' | 'clipboard' | 'file'>('') - const generation = useRef(0), alive = useRef(true) + const generation = useRef(0) + const alive = useRef(true) const { push } = useNavigation() - useEffect(() => () => { alive.current = false; generation.current++ }, []) + + useEffect(() => () => { + alive.current = false + generation.current++ + }, []) + + const loadFileFromPath = async (targetPath: string) => { + const trimmed = targetPath.trim() + if (!trimmed) return + const request = ++generation.current + setIsReading(true) + setReadErrorKey('') + try { + const content = await readTableFileFromHost(trimmed) + if (!alive.current || request !== generation.current) return + setSource('auto') + setDelimiter('auto') + setSourceFileName(extractBaseName(trimmed)) + setRawText(content) + } catch (error) { + if (!alive.current || request !== generation.current) return + const message = error instanceof Error ? error.message : String(error) + setReadErrorKey('file') + await showToast({ style: Toast.Style.Failure, title: t('toastFileReadFailed'), message }) + } finally { + if (alive.current && request === generation.current) setIsReading(false) + } + } + + const handlePickFile = async () => { + const request = ++generation.current + setReadErrorKey('') + try { + const picked = await pickTableFileFromHost() + if (!alive.current || request !== generation.current || picked.canceled || !picked.filePath) return + await loadFileFromPath(picked.filePath) + } catch (error) { + if (!alive.current || request !== generation.current) return + const message = error instanceof Error ? error.message : String(error) + setReadErrorKey('file') + await showToast({ style: Toast.Style.Failure, title: t('toastFileReadFailed'), message }) + } + } const handleReadClipboard = async () => { const request = ++generation.current - setIsReading(true); setReadErrorKey('') + setIsReading(true) + setReadErrorKey('') try { const text = await Clipboard.readText() if (!alive.current || request !== generation.current) return + setSourceFileName('') setRawText(text ?? '') - // 读取成功不等于转换成功;无效输入仍保存,供编辑修正。 } catch (error) { if (!alive.current || request !== generation.current) return const message = error instanceof Error ? error.message : String(error) @@ -88,99 +178,315 @@ export function TableConverterCommand(props: TableConverterCommandProps = {}) { } } + const handleSaveTarget = async (target: TableConversionTarget) => { + try { + const defaultName = buildDefaultSaveName(sourceFileName, target.fileExtension) + const filters = saveDialogFilterForTarget(target.id) + const saved = await saveTableFileToHost(target.fullText, defaultName, filters) + if (!alive.current || saved.canceled || !saved.filePath) return + await showToast({ + style: Toast.Style.Success, + title: t('toastSavedFile'), + message: extractBaseName(saved.filePath) + }) + } catch (error) { + if (!alive.current) return + const message = error instanceof Error ? error.message : String(error) + await showToast({ style: Toast.Style.Failure, title: t('toastSaveFileFailed'), message }) + } + } + useEffect(() => { if (props.initialRawText === undefined) void handleReadClipboard() }, [props.featureCode]) const result = useMemo(() => { try { - const parsed = detectAndParse(rawText, headerMode === 'first-row-header', source) - const targets = parsed.format === 'empty' || parsed.format === 'unrecognized' ? [] : buildAllConversionTargets(parsed.grid, sqlTableName) - return { parsed, targets, error: '' } + const parsed = detectAndParse(rawText, headerMode === 'first-row-header', source, delimiter) + if (parsed.format === 'empty' || parsed.format === 'unrecognized') { + return { parsed, activeGrid: null, targets: [] as TableConversionTarget[], error: '' } + } + const activeGrid = transpose ? transposeGrid(parsed.grid) : parsed.grid + const targets = buildAllConversionTargets(activeGrid, { + sqlTableName, + sqlDialect, + sqlIncludeDdl, + csvBom, + jsonPretty + }) + return { parsed, activeGrid, targets, error: '' } } catch (error) { - return { parsed: null, targets: [], error: error instanceof Error ? error.message : String(error) } + return { + parsed: null, + activeGrid: null, + targets: [] as TableConversionTarget[], + error: error instanceof Error ? error.message : String(error) + } } - }, [rawText, headerMode, source, sqlTableName, locale]) + }, [rawText, headerMode, source, delimiter, sqlTableName, sqlDialect, sqlIncludeDdl, csvBom, jsonPretty, transpose, locale]) + const preferred = props.featureCode?.replace('table-to-', '') - const targets = [...result.targets].sort((a, b) => Number(b.id === preferred) - Number(a.id === preferred)) - .filter(target => [target.id, target.title, target.subtitle].some(text => text.toLowerCase().includes(searchText.trim().toLowerCase()))) - const grid = result.parsed?.grid - const summary = result.error ? t('summaryParseError') : result.parsed?.format === 'empty' ? '' : result.parsed?.format === 'unrecognized' ? t('summaryUnrecognized') : t('summaryDimensions', { format: result.parsed?.format.toUpperCase() ?? '', rows: grid?.rows.length ?? 0, cols: grid?.headers.length ?? 0 }) - const readError = readErrorKey === 'clipboard' ? t('errClipboardReadBanner') : readErrorKey === 'file' ? t('errFileReadBanner') : '' + const targets = [...result.targets] + .sort((a, b) => Number(b.id === preferred) - Number(a.id === preferred)) + .filter(target => [target.id, target.title, target.subtitle, target.badge].some(text => + text.toLowerCase().includes(searchText.trim().toLowerCase()) + )) + + const grid = result.activeGrid + const summary = result.error + ? t('summaryParseError') + : result.parsed?.format === 'empty' + ? '' + : result.parsed?.format === 'unrecognized' + ? t('summaryUnrecognized') + : sourceFileName + ? t('summaryFromFile', { fileName: sourceFileName, rows: grid?.rows.length ?? 0, cols: grid?.headers.length ?? 0 }) + : t('summaryDimensions', { format: result.parsed?.format.toUpperCase() ?? '', rows: grid?.rows.length ?? 0, cols: grid?.headers.length ?? 0 }) + + const readError = readErrorKey === 'clipboard' + ? t('errClipboardReadBanner') + : readErrorKey === 'file' + ? t('errFileReadBanner') + : '' + const editInput = () => { - generation.current++; setIsReading(false) - push( { - if (!alive.current) return - generation.current++; setRawText(value.text); setSource(value.source); setSqlTableName(value.sqlTableName); setReadErrorKey('') - }} />) + generation.current++ + setIsReading(false) + push( + { + if (!alive.current) return + generation.current++ + setRawText(value.text) + setSource(value.source) + setDelimiter(value.delimiter) + setSqlTableName(value.sqlTableName) + setSqlDialect(value.sqlDialect) + setSqlIncludeDdl(value.sqlIncludeDdl) + setSourceFileName('') + setReadErrorKey('') + }} + /> + ) } const goal = featureGoal(props.featureCode) - const inputActions = - - - + const inputActions = ( + + + + + + ) const fileInputProps = createCompatFileInputProps( async (files) => { const targetPath = files[0]?.trim() if (!targetPath) return - const request = ++generation.current - setIsReading(true); setReadErrorKey('') - try { - const content = await readTableFileFromHost(targetPath) - if (!alive.current || request !== generation.current) return - setSource('auto') - setRawText(content) - } catch (error) { - if (!alive.current || request !== generation.current) return - const message = error instanceof Error ? error.message : String(error) - setReadErrorKey('file') - await showToast({ style: Toast.Style.Failure, title: t('toastFileReadFailed'), message }) - } finally { - if (alive.current && request === generation.current) setIsReading(false) - } + await loadFileFromPath(targetPath) }, { - extensions: ['.csv', '.tsv', '.json', '.md', '.txt'], + extensions: SUPPORTED_EXTENSIONS, onTextPaste: (text) => { if (!alive.current || !text) return generation.current++ setIsReading(false) setReadErrorKey('') + setSourceFileName('') setRawText(text) } } ) - return setHeaderMode(value as typeof headerMode)} tooltip={t('headerModeTooltip')}> - - - } - filterBar={{ summaryText: readError || summary, actions: [ - { id: 'read-clipboard', title: t('actionReadClipboard'), onAction: handleReadClipboard }, - { id: 'edit-input', title: t('actionEditInput'), onAction: editInput } - ] }}> - {!isReading && result.error ? } /> : null} - {!isReading && result.parsed?.format === 'unrecognized' ? } /> : null} - {!isReading && !result.error && result.parsed?.format !== 'unrecognized' && !targets.length ? } /> : null} - {!isReading && targets.map(target => - - - - {grid?.warnings?.map((warning, i) => )} - } />} - actions={target.error ? undefined : - - - } />)} - + const formatTargetOptions = (target: TableConversionTarget): string => { + const items = [t('metaOptTranspose', { state: transpose ? t('metaStateOn') : t('metaStateOff') })] + if (target.id === 'markdown') { + items.push(markdownRendered ? t('metaOptPreviewRendered') : t('metaOptPreviewSource')) + } else if (target.id === 'csv') { + items.push(t('metaOptBom', { state: csvBom ? t('metaStateOn') : t('metaStateOff') })) + } else if (target.id === 'sql') { + items.push(sqlDialectLabel(sqlDialect)) + items.push(t('metaOptDdl', { state: sqlIncludeDdl ? t('metaStateOn') : t('metaStateOff') })) + } else if (target.id === 'json') { + items.push(jsonPretty ? t('metaOptJsonPretty') : t('metaOptJsonCompact')) + } + return items.join(' · ') + } + + const sourceDesc = describeDetectedSource(result.parsed?.format, result.parsed?.delimiter) + + return ( + setHeaderMode(value as 'first-row-header' | 'no-header')} + tooltip={t('headerModeTooltip')} + > + + + + } + filterBar={{ + summaryText: readError || summary, + actions: [ + { id: 'pick-file', title: t('actionPickFile'), icon: Icon.Folder, onAction: handlePickFile }, + { id: 'read-clipboard', title: t('actionReadClipboard'), icon: Icon.Clipboard, onAction: handleReadClipboard }, + { id: 'edit-input', title: t('actionEditInput'), icon: Icon.Pencil, onAction: editInput } + ] + }} + > + {!isReading && result.error ? ( + } + /> + ) : null} + + {!isReading && !result.error && result.parsed?.format === 'unrecognized' ? ( + + ) : null} + + {!isReading && !result.error && result.parsed?.format !== 'unrecognized' && !targets.length ? ( + + ) : null} + + {!isReading && targets.map(target => { + const displayBadge = target.id === 'markdown' + ? (markdownRendered ? t('targetMdBadgeRendered') : t('targetMdBadgeSource')) + : target.badge + const detailMarkdown = target.error + ? fencedPreview(target.error, 'text') + : target.id === 'markdown' && markdownRendered + ? target.previewText + : fencedPreview(target.previewText, target.language) + + return ( + + {sourceDesc ? : null} + + + + + {grid?.warnings?.map((warning, i) => ( + + ))} + + } + /> + } + actions={ + target.error ? inputActions : ( + + + + + handleSaveTarget(target)} + /> + + + {target.id === 'sql' ? ( + + {(['sqlite', 'mysql', 'postgresql'] as const).map(dialect => ( + setSqlDialect(dialect)} + /> + ))} + + ) : null} + {target.id === 'sql' ? ( + setSqlIncludeDdl(v => !v)} + /> + ) : null} + {target.id === 'csv' ? ( + setCsvBom(v => !v)} + /> + ) : null} + {target.id === 'markdown' ? ( + setMarkdownRendered(v => !v)} + /> + ) : null} + {target.id === 'json' ? ( + setJsonPretty(v => !v)} + /> + ) : null} + setTranspose(v => !v)} + /> + + + + + + + + ) + } + /> + ) + })} + + ) } + export const commands = { 'table-auto': TableConverterCommand, 'table-to-markdown': () => TableConverterCommand({ featureCode: 'table-to-markdown' }), diff --git a/extensions/table-converter/src/input-form.tsx b/extensions/table-converter/src/input-form.tsx index eb15d71c..c9288d96 100644 --- a/extensions/table-converter/src/input-form.tsx +++ b/extensions/table-converter/src/input-form.tsx @@ -1,37 +1,84 @@ import React, { Form, ActionPanel, Action, useState, useNavigation, useLocale, showToast, Toast } from '@ztools/declarative-ui' import { detectAndParse } from './table-service.js' -import type { SourceFormat } from './types.js' +import type { DelimiterOption, SourceFormat, SqlDialect } from './types.js' import { t } from './i18n.js' export interface TableInput { text: string source: SourceFormat + delimiter: DelimiterOption sqlTableName: string + sqlDialect: SqlDialect + sqlIncludeDdl: boolean } -export function TableInputForm({ initial, hasHeader, onApply }: { initial: TableInput; hasHeader: boolean; onApply: (value: TableInput) => void }) { +export function TableInputForm({ + initial, + hasHeader, + onApply +}: { + initial: TableInput + hasHeader: boolean + onApply: (value: TableInput) => void +}) { useLocale() const [text, setText] = useState(initial.text) const [source, setSource] = useState(initial.source) + const [delimiter, setDelimiter] = useState(initial.delimiter) const [sqlTableName, setSqlTableName] = useState(initial.sqlTableName) + const [sqlDialect, setSqlDialect] = useState(initial.sqlDialect) + const [sqlIncludeDdl, setSqlIncludeDdl] = useState(initial.sqlIncludeDdl) const { pop } = useNavigation() + const apply = async () => { try { - detectAndParse(text, hasHeader, source) + detectAndParse(text, hasHeader, source, delimiter) if (!sqlTableName || sqlTableName.includes('\0')) throw new Error(t('errSqlTableNameInvalid')) - onApply({ text, source, sqlTableName }); pop() + onApply({ text, source, delimiter, sqlTableName, sqlDialect, sqlIncludeDdl }) + pop() } catch (error) { - await showToast({ style: Toast.Style.Failure, title: t('toastInputInvalid'), message: error instanceof Error ? error.message : String(error) }) + await showToast({ + style: Toast.Style.Failure, + title: t('toastInputInvalid'), + message: error instanceof Error ? error.message : String(error) + }) } } - return
}> - - setSource(value as SourceFormat)}> - - - - - - - + + return ( +
+ + + } + > + + setSource(value as SourceFormat)}> + + + + + + + + + setDelimiter(value as DelimiterOption)}> + + + + + + + + + setSqlDialect(value as SqlDialect)}> + + + + + + + ) } diff --git a/extensions/table-converter/src/sql-format.ts b/extensions/table-converter/src/sql-format.ts index 35319426..8784dd28 100644 --- a/extensions/table-converter/src/sql-format.ts +++ b/extensions/table-converter/src/sql-format.ts @@ -1,10 +1,73 @@ import { boundedJoin, cellValue, displayValue, makeGrid, parseJsonPreservingData } from './table-model.js' -import type { JsonValue, TableGrid } from './types.js' +import type { JsonValue, SqlDialect, SqlFormatOptions, TableGrid } from './types.js' import { t } from './i18n.js' const identifierKey = (name: string) => name.replace(/[A-Z]/g, letter => letter.toLowerCase()) -/** SQLite 字面量 INSERT 子集:只解析文本,从不执行 SQL。 */ +export function sqlDialectLabel(dialect: SqlDialect): string { + switch (dialect) { + case 'mysql': return 'MySQL' + case 'postgresql': return 'PostgreSQL' + default: return 'SQLite' + } +} + +function quoteSqlIdentifier(name: string, dialect: SqlDialect): string { + if (dialect === 'mysql') return `\`${name.replace(/`/g, '``')}\`` + return `"${name.replace(/"/g, '""')}"` +} + +function quoteSqlString(text: string, dialect: SqlDialect): string { + if (dialect === 'mysql') { + return `'${text.replace(/\\/g, '\\\\').replace(/'/g, "''")}'` + } + return `'${text.replace(/'/g, "''")}'` +} + +function inferSqlColumnType(grid: TableGrid, colIndex: number, dialect: SqlDialect): string { + const kind = grid.inferredTypes[colIndex] + if (kind === 'number') { + let allInt = true + let needsBigInt = false + for (let r = 0; r < grid.rows.length; r++) { + const value = cellValue(grid, r, colIndex) + if (value === null || value === undefined) continue + if (typeof value !== 'number' || !Number.isInteger(value)) { + allInt = false + break + } + if (value < -2147483648 || value > 2147483647) needsBigInt = true + } + if (allInt) { + if (dialect === 'sqlite') return 'INTEGER' + return needsBigInt ? 'BIGINT' : 'INTEGER' + } + if (dialect === 'sqlite') return 'REAL' + if (dialect === 'mysql') return 'DOUBLE' + return 'DOUBLE PRECISION' + } + if (kind === 'boolean') { + if (dialect === 'sqlite') return 'INTEGER' + if (dialect === 'mysql') return 'TINYINT(1)' + return 'BOOLEAN' + } + if (kind === 'json') { + if (dialect === 'mysql') return 'JSON' + if (dialect === 'postgresql') return 'JSONB' + return 'TEXT' + } + if (dialect === 'mysql') { + let maxLen = 0 + for (let r = 0; r < grid.rows.length; r++) { + const len = (grid.rows[r]?.[colIndex] ?? '').length + if (len > maxLen) maxLen = len + } + return maxLen > 255 ? 'TEXT' : 'VARCHAR(255)' + } + return 'TEXT' +} + +/** 字面量 INSERT 子集:只解析文本,从不执行 SQL。 */ export function parseSqlInsert(text: string): TableGrid { let position = 0 const rest = () => text.slice(position) @@ -60,25 +123,47 @@ export function parseSqlInsert(text: string): TableGrid { return { ...result, headers, warnings: [] } } -export function gridToSql(grid: TableGrid, tableName = 'my_table'): string { - if (!grid.headers.length || !grid.rows.length) return '' +function assertValidSqlIdentifiers(grid: TableGrid, tableName: string): void { if (new Set(grid.headers.map(identifierKey)).size !== grid.headers.length) throw new Error(t('errSqlCaseInsensitiveCol')) - const quoteIdentifier = (name: string) => `"${name.replace(/"/g, '""')}"` if (!tableName || /\0/.test(tableName) || grid.headers.some(name => name.includes('\0'))) throw new Error(t('errSqlEmptyOrNulName')) +} + +export function gridToSqlDdl(grid: TableGrid, tableName = 'my_table', dialect: SqlDialect = 'sqlite'): string { + if (!grid.headers.length) return '' + assertValidSqlIdentifiers(grid, tableName) + const quoteIdentifier = (name: string) => quoteSqlIdentifier(name, dialect) + const columns = grid.headers.map((name, i) => ` ${quoteIdentifier(name)} ${inferSqlColumnType(grid, i, dialect)}`) + return `CREATE TABLE ${quoteIdentifier(tableName)} (\n${columns.join(',\n')}\n);` +} + +export function gridToSql(grid: TableGrid, tableName = 'my_table', options: SqlFormatOptions = {}): string { + const dialect: SqlDialect = options.dialect ?? 'sqlite' + const includeDdl = options.includeDdl ?? false + if (!grid.headers.length) return '' + if (!grid.rows.length && !includeDdl) return '' + assertValidSqlIdentifiers(grid, tableName) + const quoteIdentifier = (name: string) => quoteSqlIdentifier(name, dialect) + const ddlPrefix = includeDdl ? `${gridToSqlDdl(grid, tableName, dialect)}${grid.rows.length ? '\n\n' : ''}` : '' + if (!grid.rows.length) return ddlPrefix function* tuples() { for (let r = 0; r < grid.rows.length; r++) { const row = grid.rows[r]! - const cells = grid.headers.map((_, c) => { - const value = cellValue(grid, r, c) - if (value === null || value === undefined) return 'NULL' - if (typeof value === 'number') return String(value) - if (typeof value === 'boolean') return value ? 'TRUE' : 'FALSE' - const text = typeof value === 'object' ? JSON.stringify(value) : row[c]! - if (text.includes('\0')) throw new Error(t('errSqlNulText')) - return `'${text.replace(/'/g, "''")}'` - }) + const cells = grid.headers.map((_, c) => { + const value = cellValue(grid, r, c) + if (value === null || value === undefined) return 'NULL' + if (typeof value === 'number') return String(value) + if (typeof value === 'boolean') return value ? 'TRUE' : 'FALSE' + const text = typeof value === 'object' ? JSON.stringify(value) : row[c]! + if (text.includes('\0')) throw new Error(t('errSqlNulText')) + return quoteSqlString(text, dialect) + }) yield ` (${cells.join(', ')})` } } - return boundedJoin(tuples(), ',\n', `INSERT INTO ${quoteIdentifier(tableName)} (${grid.headers.map(quoteIdentifier).join(', ')})\nVALUES\n`, ';') + return boundedJoin( + tuples(), + ',\n', + `${ddlPrefix}INSERT INTO ${quoteIdentifier(tableName)} (${grid.headers.map(quoteIdentifier).join(', ')})\nVALUES\n`, + ';' + ) } diff --git a/extensions/table-converter/src/table-model.ts b/extensions/table-converter/src/table-model.ts index a9cb555e..786f15af 100644 --- a/extensions/table-converter/src/table-model.ts +++ b/extensions/table-converter/src/table-model.ts @@ -117,6 +117,21 @@ export function cellValue(grid: TableGrid, r: number, c: number): JsonValue | un return raw } +/** 行列转置:原表头作为新第一列,原各行数据依次作为后续列。 */ +export function transposeGrid(grid: TableGrid): TableGrid { + if (!grid.headers.length) return makeGrid([], []) + const matrix: string[][] = [grid.headers, ...grid.rows] + const rowCount = matrix.length + const colCount = grid.headers.length + assertGridSize(rowCount, colCount) + const transposed: string[][] = Array.from({ length: colCount }, (_, c) => + Array.from({ length: rowCount }, (_, r) => matrix[r]?.[c] ?? '') + ) + const newHeaders = transposed[0] ?? [] + const newRows = transposed.slice(1) + return makeGrid(newHeaders, newRows) +} + /** 逐行累计预算,避免长表头或转义导致输出在检查前膨胀。 */ export function boundedJoin(parts: Iterable, separator: string, prefix = '', suffix = ''): string { const encoder = new TextEncoder(), result: string[] = [] diff --git a/extensions/table-converter/src/table-service.ts b/extensions/table-converter/src/table-service.ts index f0324c85..935d2e85 100644 --- a/extensions/table-converter/src/table-service.ts +++ b/extensions/table-converter/src/table-service.ts @@ -1,24 +1,58 @@ -import type { DetectedSourceFormat, SourceFormat, TableConversionTarget, TableGrid, JsonValue } from './types.js' -import { boundedJoin, cellValue, jsonGrid, makeGrid, matrixGrid } from './table-model.js' +import type { + ConversionOptions, + DelimiterOption, + DetectedSourceFormat, + JsonValue, + SourceFormat, + SqlDialect, + TableConversionTarget, + TableGrid +} from './types.js' +import { boundedJoin, cellValue, jsonGrid, makeGrid, matrixGrid, transposeGrid } from './table-model.js' import { parseDelimitedRows, parseHtmlTable, parseMarkdownTable, markdownCell, escapeHtml } from './text-formats.js' -import { parseSqlInsert, gridToSql } from './sql-format.js' +import { parseSqlInsert, gridToSql, gridToSqlDdl, sqlDialectLabel } from './sql-format.js' import { t } from './i18n.js' -export { parseDelimitedRows, gridToSql } -export function detectAndParse(rawText: string, hasHeader = true, source: SourceFormat = 'auto'): { format: DetectedSourceFormat; grid: TableGrid } { +export { parseDelimitedRows, gridToSql, gridToSqlDdl, sqlDialectLabel, transposeGrid } + +export interface ParsedTableResult { + format: DetectedSourceFormat + grid: TableGrid + delimiter?: ',' | '\t' | ';' | '|' +} + +export function detectAndParse( + rawText: string, + hasHeader = true, + source: SourceFormat = 'auto', + customDelimiter: DelimiterOption = 'auto' +): ParsedTableResult { if (rawText.length > 2_000_000) throw new Error(t('errInputCharLimit')) const text = rawText.replace(/^\uFEFF/, ''), trimmed = text.trim() if (!text.length) return { format: 'empty', grid: makeGrid([], []) } + let format: Exclude - if (source !== 'auto') format = source - else if (/^[\[{]/.test(trimmed)) format = 'json' - else if (/^INSERT\b/i.test(trimmed)) format = 'sql' - else if (/^<(?:table\b|!--)/i.test(trimmed)) format = 'html' - // GFM 分隔行:每格至少一个 -,可带 : 对齐标记(|-|-|、|:-:|--:|、--- | --- 均合法) - else if (/^[ \t]*\|?(?:[ \t]*:?-+:?[ \t]*\|)+(?:[ \t]*:?-+:?[ \t]*)?$/m.test(text)) format = 'markdown' - else { + let detectedDelimiter: ',' | '\t' | ';' | '|' | undefined + + if (source !== 'auto') { + format = source + if (format === 'tsv') detectedDelimiter = customDelimiter === 'auto' ? '\t' : customDelimiter + else if (format === 'csv') detectedDelimiter = customDelimiter === 'auto' ? ',' : customDelimiter + } else if (customDelimiter !== 'auto') { + detectedDelimiter = customDelimiter + format = customDelimiter === '\t' ? 'tsv' : 'csv' + } else if (/^[\[{]/.test(trimmed)) { + format = 'json' + } else if (/^INSERT\b/i.test(trimmed)) { + format = 'sql' + } else if (/^<(?:table\b|!--)/i.test(trimmed)) { + format = 'html' + } else if (/^[ \t]*\|?(?:[ \t]*:?-+:?[ \t]*\|)+(?:[ \t]*:?-+:?[ \t]*)?$/m.test(text)) { + // GFM 分隔行:每格至少一个 -,可带 : 对齐标记(|-|-|、|:-:|--:|、--- | --- 均合法) + format = 'markdown' + } else { // 仅统计首条记录引号外的分隔符,避免把 CSV 单元格内的制表符识别成 TSV。 - let quoted = false, tabs = 0, commas = 0 + let quoted = false, tabs = 0, commas = 0, semicolons = 0 for (let i = 0; i < text.length; i++) { const char = text[i] if (char === '"') { @@ -28,21 +62,52 @@ export function detectAndParse(rawText: string, hasHeader = true, source: Source if (char === '\r' || char === '\n') break if (char === '\t') tabs++ if (char === ',') commas++ + if (char === ';') semicolons++ } } // 自动识别时,单行且没有任何分隔符的普通文本不是表格,交给界面给出中性引导而不是“0 行 × 1 列”。 - if (trimmed && !tabs && !commas && !/[\r\n]/.test(trimmed)) return { format: 'unrecognized', grid: makeGrid([], []) } - format = tabs > commas ? 'tsv' : 'csv' + if (trimmed && !tabs && !commas && !semicolons && !/[\r\n]/.test(trimmed)) { + return { format: 'unrecognized', grid: makeGrid([], []) } + } + if (tabs > commas && tabs >= semicolons) { + format = 'tsv' + detectedDelimiter = '\t' + } else if (semicolons > commas && commas === 0 && tabs === 0) { + format = 'csv' + detectedDelimiter = ';' + } else { + format = 'csv' + detectedDelimiter = ',' + } } - const grid = format === 'json' ? jsonGrid(trimmed, hasHeader) - : format === 'sql' ? parseSqlInsert(text) - : matrixGrid(format === 'html' ? parseHtmlTable(trimmed) : format === 'markdown' ? parseMarkdownTable(trimmed) - : parseDelimitedRows(text, format === 'tsv' ? '\t' : ','), hasHeader) - return { format, grid } + + const grid = format === 'json' + ? jsonGrid(trimmed, hasHeader) + : format === 'sql' + ? parseSqlInsert(text) + : matrixGrid( + format === 'html' + ? parseHtmlTable(trimmed) + : format === 'markdown' + ? parseMarkdownTable(trimmed) + : parseDelimitedRows(text, detectedDelimiter ?? (format === 'tsv' ? '\t' : ',')), + hasHeader + ) + return { format, grid, ...(detectedDelimiter ? { delimiter: detectedDelimiter } : {}) } } -export function gridToJson(grid: TableGrid): string { +export function gridToJson(grid: TableGrid, pretty = true): string { if (!grid.rows.length) return '[]' + if (!pretty) { + function* compactRows() { + for (let r = 0; r < grid.rows.length; r++) { + const item: Record = Object.create(null) + grid.headers.forEach((name, c) => { item[name] = cellValue(grid, r, c) }) + yield JSON.stringify(item) + } + } + return boundedJoin(compactRows(), ',', '[', ']') + } function* rows() { for (let r = 0; r < grid.rows.length; r++) { const item: Record = Object.create(null) @@ -75,14 +140,25 @@ export function gridToHtml(grid: TableGrid): string { return boundedJoin(rows(), '\n', `
\n ${header}\n \n`, '\n \n
') } -export function gridToCsv(grid: TableGrid): string { +export function gridToTsv(grid: TableGrid): string { + if (!grid.headers.length) return '' + const encode = (text: string) => /[\t"\r\n]/.test(text) ? `"${text.replace(/"/g, '""')}"` : text + function* rows() { + yield grid.headers.map(encode).join('\t') + for (const row of grid.rows) yield row.map(encode).join('\t') + } + return boundedJoin(rows(), '\r\n') +} + +export function gridToCsv(grid: TableGrid, options: { bom?: boolean } = {}): string { if (!grid.headers.length) return '' const encode = (text: string) => /[,"\r\n]/.test(text) || text === '' ? `"${text.replace(/"/g, '""')}"` : text function* rows() { yield grid.headers.map(encode).join(',') for (const row of grid.rows) yield row.map(encode).join(',') } - return boundedJoin(rows(), '\r\n') + const content = boundedJoin(rows(), '\r\n') + return options.bom ? `\uFEFF${content}` : content } export function fencedPreview(content: string, language: string): string { @@ -93,24 +169,95 @@ export function fencedPreview(content: string, language: string): string { return `${fence}${language}\n${normalized}\n${fence}` } -export function buildAllConversionTargets(grid: TableGrid, sqlTableName = 'my_table'): TableConversionTarget[] { - const typeSummary = grid.headers.map((h, i) => `${h}: ${grid.inferredTypes[i]}`).join(' · ') +export function buildAllConversionTargets( + grid: TableGrid, + sqlTableNameOrOptions: string | ConversionOptions = 'my_table' +): TableConversionTarget[] { + const options: ConversionOptions = typeof sqlTableNameOrOptions === 'string' + ? { sqlTableName: sqlTableNameOrOptions } + : sqlTableNameOrOptions + const sqlTableName = options.sqlTableName ?? 'my_table' + const sqlDialect: SqlDialect = options.sqlDialect ?? 'sqlite' + const sqlIncludeDdl = options.sqlIncludeDdl ?? false + const csvBom = options.csvBom ?? false + const jsonPretty = options.jsonPretty ?? true + const workingGrid = options.transpose ? transposeGrid(grid) : grid + + const typeSummary = workingGrid.headers.map((h, i) => `${h}: ${workingGrid.inferredTypes[i]}`).join(' · ') + const dialectName = sqlDialectLabel(sqlDialect) + const specs = [ - ['markdown', t('targetMdTitle'), t('targetMdSub'), t('targetMdBadge'), () => gridToMarkdown(grid)], - ['json', t('targetJsonTitle'), t('targetJsonSub'), t('targetJsonBadge'), () => gridToJson(grid)], - ['sql', t('targetSqlTitle', { table: sqlTableName }), t('targetSqlSub'), 'SQLite', () => { - if (grid.headers.length && !grid.rows.length) throw new Error(t('errSqlNoDataRows')) - return gridToSql(grid, sqlTableName) - }], - ['html', t('targetHtmlTitle'), t('targetHtmlSub'), t('targetHtmlBadge'), () => gridToHtml(grid)], - ['csv', t('targetCsvTitle'), t('targetCsvSub'), t('targetCsvBadge'), () => gridToCsv(grid)] + [ + 'markdown', + t('targetMdTitle'), + t('targetMdSub'), + t('targetMdBadgeSource'), + 'markdown', + '.md', + () => gridToMarkdown(workingGrid) + ], + [ + 'tsv', + t('targetTsvTitle'), + t('targetTsvSub'), + t('targetTsvBadge'), + 'tsv', + '.tsv', + () => gridToTsv(workingGrid) + ], + [ + 'json', + t('targetJsonTitle'), + t('targetJsonSub'), + jsonPretty ? t('targetJsonBadgePretty') : t('targetJsonBadgeCompact'), + 'json', + '.json', + () => gridToJson(workingGrid, jsonPretty) + ], + [ + 'sql', + t('targetSqlTitle', { dialect: dialectName, table: sqlTableName }), + sqlIncludeDdl ? t('targetSqlSubWithDdl', { dialect: dialectName }) : t('targetSqlSubInsertOnly', { dialect: dialectName }), + sqlIncludeDdl ? t('targetSqlBadgeDdl') : dialectName, + 'sql', + '.sql', + () => { + if (workingGrid.headers.length && !workingGrid.rows.length && !sqlIncludeDdl) { + throw new Error(t('errSqlNoDataRows')) + } + return gridToSql(workingGrid, sqlTableName, { dialect: sqlDialect, includeDdl: sqlIncludeDdl }) + } + ], + [ + 'csv', + csvBom ? t('targetCsvTitleBom') : t('targetCsvTitle'), + csvBom ? t('targetCsvSubBom') : t('targetCsvSub'), + csvBom ? t('targetCsvBadgeBom') : t('targetCsvBadgePlain'), + 'csv', + '.csv', + () => gridToCsv(workingGrid, { bom: csvBom }) + ], + [ + 'html', + t('targetHtmlTitle'), + t('targetHtmlSub'), + t('targetHtmlBadge'), + 'html', + '.html', + () => gridToHtml(workingGrid) + ] ] as const - return specs.map(([id, title, subtitle, badge, convert]) => { - const base = { id, title, subtitle, badge, language: id, typeSummary } + + return specs.map(([id, title, subtitle, badge, language, fileExtension, convert]) => { + const base = { id, title, subtitle, badge, language, fileExtension, typeSummary } try { - const fullText = convert(), lines = fullText.split(/\r?\n/) - const clipped = lines.length > 100 || fullText.length > 30_000 - const previewText = clipped ? lines.slice(0, 100).join('\n').slice(0, 30_000) + t('previewTruncatedNote') : fullText + const fullText = convert() + const visibleText = fullText.replace(/^\uFEFF/, '') + const lines = visibleText.split(/\r?\n/) + const clipped = lines.length > 100 || visibleText.length > 30_000 + const previewText = clipped + ? lines.slice(0, 100).join('\n').slice(0, 30_000) + t('previewTruncatedNote') + : visibleText return { ...base, fullText, previewText } } catch (error) { return { ...base, fullText: '', previewText: '', error: error instanceof Error ? error.message : String(error) } diff --git a/extensions/table-converter/src/text-formats.ts b/extensions/table-converter/src/text-formats.ts index 20a09752..f289cd84 100644 --- a/extensions/table-converter/src/text-formats.ts +++ b/extensions/table-converter/src/text-formats.ts @@ -2,7 +2,7 @@ import { t } from './i18n.js' export function parseDelimitedRows(text: string, delimiter: string): string[][] { if (!text.length) return [] - if (delimiter !== ',' && delimiter !== '\t') throw new Error(t('errDelimiterOnly')) + if (delimiter !== ',' && delimiter !== '\t' && delimiter !== ';' && delimiter !== '|') throw new Error(t('errDelimiterOnly')) const rows: string[][] = [] let row: string[] = [], cell = '', state: 'start' | 'plain' | 'quoted' | 'closed' = 'start' let recordStarted = false diff --git a/extensions/table-converter/src/types.ts b/extensions/table-converter/src/types.ts index 71e3ca46..fde806ac 100644 --- a/extensions/table-converter/src/types.ts +++ b/extensions/table-converter/src/types.ts @@ -2,6 +2,9 @@ export type JsonValue = string | number | boolean | null | JsonValue[] | { [key: export type InferredColumnType = 'number' | 'boolean' | 'string' | 'null' | 'json' | 'mixed' export type DetectedSourceFormat = 'tsv' | 'csv' | 'json' | 'markdown' | 'html' | 'sql' | 'empty' | 'unrecognized' export type SourceFormat = Exclude | 'auto' +export type DelimiterOption = 'auto' | ',' | '\t' | ';' | '|' +export type SqlDialect = 'sqlite' | 'mysql' | 'postgresql' +export type ConversionTargetId = 'markdown' | 'tsv' | 'json' | 'sql' | 'csv' | 'html' export interface TableGrid { headers: string[] @@ -12,12 +15,27 @@ export interface TableGrid { warnings?: string[] } +export interface SqlFormatOptions { + dialect?: SqlDialect + includeDdl?: boolean +} + +export interface ConversionOptions { + sqlTableName?: string + sqlDialect?: SqlDialect + sqlIncludeDdl?: boolean + csvBom?: boolean + jsonPretty?: boolean + transpose?: boolean +} + export interface TableConversionTarget { - id: 'markdown' | 'json' | 'sql' | 'html' | 'csv' + id: ConversionTargetId title: string subtitle: string badge: string language: string + fileExtension: string fullText: string previewText: string typeSummary: string diff --git a/extensions/table-converter/tests/command.test.mjs b/extensions/table-converter/tests/command.test.mjs deleted file mode 100644 index 04b2f670..00000000 --- a/extensions/table-converter/tests/command.test.mjs +++ /dev/null @@ -1,219 +0,0 @@ -import test from 'node:test' -import assert from 'node:assert/strict' -import { Clipboard } from '@ztools/declarative-ui' -import { createHost, mount, mountPushed, tick } from '../../shared/test-harness.mjs' -import { TableConverterCommand, commands } from '../dist/index.js' -const action = (view, id) => view.tree().props.filterBar.actions.find(a => a.id === id) - -test('空剪贴板显示等待输入,不提供虚构示例或可复制结果', async () => { - const host = createHost(), view = await mount(TableConverterCommand, host) - try { - assert.deepEqual(view.items().map(i => i.props.id), ['empty-input']) - assert.equal(host.toasts.length, 0) - assert.doesNotMatch(view.text(), /48500|12800|19200/) - } finally { view.unmount() } -}) - -test('JSON 快捷命令首项正确,真实 SDK 复制和粘贴发送完整原类型数据', async () => { - const host = createHost(), input = [{ name: '001', data: { a: 1 } }] - host.clipboard.text = JSON.stringify(input) - const view = await mount(commands['table-to-json'], host) - try { - assert.equal(view.items()[0].props.id, 'json') - await view.run(view.item('json'), '复制转换结果') - assert.deepEqual(JSON.parse(host.clipboard.text), input) - await view.run(view.item('json'), '直接上屏粘贴') - assert.deepEqual(JSON.parse(host.clipboard.pasted[0]), input) - } finally { view.unmount() } -}) - -test('解析错误清空转换动作,并在编辑表单保留完整原文', async () => { - const host = createHost(), input = 'a\n"unterminated' - const view = await mount(() => TableConverterCommand({ initialRawText: input }), host) - let form - try { - assert.deepEqual(view.items().map(i => i.props.id), ['parse-error']) - assert.deepEqual(view.actions(view.item('parse-error')).map(a => a.props.title), ['读取剪贴板', '编辑输入']) - assert.doesNotMatch(view.text(), /复制转换结果/) - await action(view, 'edit-input').onAction(); form = await mountPushed(host) - assert.equal(form.field('text').props.value, input) - await form.run(null, '应用输入') - assert.equal(host.lastToast().style, 'FAILURE') - assert.equal(host.pushed.length, 1) - assert.equal(form.field('text').props.value, input) - await form.fill('text', 'a\nfixed'); await form.fill('sqlTableName', '自定义表') - await form.run(null, '应用输入'); await tick() - assert.equal(host.pushed.length, 0) - await view.run(view.item('sql'), '复制转换结果') - assert.match(host.clipboard.text, /INSERT INTO "自定义表"/) - } finally { form?.unmount(); view.unmount() } -}) - -test('剪贴板读取失败保留前次输入,提示失败不冒充更新成功', async () => { - const host = createHost(), view = await mount(() => TableConverterCommand({ initialRawText: 'a\nold' }), host) - const read = Clipboard.readText - try { - Clipboard.readText = async () => { throw new Error('读取被拒绝') } - await action(view, 'read-clipboard').onAction(); await tick() - assert.equal(host.lastToast().style, 'FAILURE') - assert.match(view.tree().props.filterBar.summaryText, /保留上一次/) - await action(view, 'edit-input').onAction(); const form = await mountPushed(host) - try { assert.equal(form.field('text').props.value, 'a\nold') } finally { form.unmount() } - } finally { Clipboard.readText = read; view.unmount() } -}) - -test('迟到的剪贴板读取不能覆盖新读取、手动输入或已退出页面', async () => { - const host = createHost(), view = await mount(() => TableConverterCommand({ initialRawText: 'a\nold' }), host) - const read = Clipboard.readText, pending = [] - try { - Clipboard.readText = () => new Promise(resolve => pending.push(resolve)) - const first = action(view, 'read-clipboard').onAction(), second = action(view, 'read-clipboard').onAction() - pending[1]('a\nnew'); await second; pending[0]('a\nstale'); await first - await view.run(view.item('json'), '复制转换结果'); assert.equal(JSON.parse(host.clipboard.text)[0].a, 'new') - const third = action(view, 'read-clipboard').onAction() - await action(view, 'edit-input').onAction(); const form = await mountPushed(host) - try { await form.fill('text', 'a\nmanual'); await form.run(null, '应用输入') } finally { form.unmount() } - pending[2]('a\nstale-again'); await third - await view.run(view.item('json'), '复制转换结果'); assert.equal(JSON.parse(host.clipboard.text)[0].a, 'manual') - const fourth = action(view, 'read-clipboard').onAction() - view.unmount(); pending[3]('a\nlate'); await fourth - assert.equal(JSON.parse(host.clipboard.text)[0].a, 'manual') - } finally { Clipboard.readText = read; view.unmount() } -}) - -test('格式转换局部失败不能复制空文本,其他格式仍可用', async () => { - const host = createHost(), view = await mount(() => TableConverterCommand({ initialRawText: '[{"a":"\\u0000"}]' }), host) - try { - assert.equal(view.item('sql').props.actions, undefined) - await view.run(view.item('json'), '复制转换结果') - assert.equal(JSON.parse(host.clipboard.text)[0].a, '\0') - } finally { view.unmount() } -}) - -test('预览截断不影响复制完整内容,围栏按用户内容长度扩展', async () => { - const host = createHost(), input = [{ a: '```\r\n![x](https://example.invalid/x)\r\n' + 'x'.repeat(35_000) }] - const view = await mount(() => TableConverterCommand({ initialRawText: JSON.stringify(input) }), host) - try { - assert.match(view.item('csv').props.detail.props.markdown, /^````csv/) - assert.match(view.item('csv').props.detail.props.markdown, /预览已截断/) - await view.run(view.item('csv'), '复制转换结果') - assert.ok(host.clipboard.text.length > 35_000) - assert.ok(host.clipboard.text.endsWith('x'.repeat(100) + '"')) - } finally { view.unmount() } -}) - -test('清空剪贴板移除旧结果,快捷入口覆盖清单中的全部命令', async () => { - const host = createHost() - for (const [code, first] of [['table-auto', 'markdown'], ['table-to-markdown', 'markdown'], ['table-to-json', 'json'], ['table-to-sql', 'sql']]) { - host.clipboard.text = 'a\nx' - const view = await mount(commands[code], host) - try { - assert.equal(view.items()[0].props.id, first) - host.clipboard.text = ''; await action(view, 'read-clipboard').onAction() - assert.equal(view.items()[0].props.id, 'empty-input') - } finally { view.unmount() } - } -}) - -test('真实 SDK 复制与粘贴失败不提示成功,不触发读取或改写原输入', async () => { - const host = createHost(), view = await mount(() => TableConverterCommand({ initialRawText: 'a\nkeep' }), host) - const copy = Clipboard.copy, paste = Clipboard.paste - try { - Clipboard.copy = async () => { throw new Error('剪贴板写入被拒绝') } - Clipboard.paste = async () => { throw new Error('没有可用的粘贴目标') } - await assert.rejects(view.run(view.item('json'), '复制转换结果'), /拒绝/) - await assert.rejects(view.run(view.item('json'), '直接上屏粘贴'), /目标/) - assert.equal(host.toasts.length, 0) - assert.equal(host.clipboard.text, '') - assert.match(view.item('json').props.detail.props.markdown, /keep/) - } finally { Clipboard.copy = copy; Clipboard.paste = paste; view.unmount() } -}) - -test('单行无分隔符的普通文本给出中性引导,不冒充 0 行表格', async () => { - const host = createHost(), view = await mount(() => TableConverterCommand({ featureCode: 'table-to-sql', initialRawText: '这是一段普通文字' }), host) - try { - assert.deepEqual(view.items().map(i => i.props.id), ['not-table']) - assert.match(view.item('not-table').props.title, /不像表格/) - assert.doesNotMatch(view.tree().props.filterBar.summaryText, /0 行/) - } finally { view.unmount() } -}) - -test('只有表头没有数据行时 SQL 输出明确错误条目且不可复制', async () => { - const host = createHost(), view = await mount(() => TableConverterCommand({ featureCode: 'table-to-sql', initialRawText: 'id,name' }), host) - try { - assert.equal(view.items()[0].props.id, 'sql') - assert.match(view.text(), /没有数据行,无法生成 INSERT/) - assert.equal(view.item('sql').props.actions, undefined) - } finally { view.unmount() } -}) - -test('多行单列文本仍按 CSV 识别,SQL 正常生成', async () => { - const host = createHost(), view = await mount(() => TableConverterCommand({ featureCode: 'table-to-sql', initialRawText: 'name\n甲' }), host) - try { - await view.run(view.item('sql'), '复制转换结果') - assert.match(host.clipboard.text, /INSERT INTO "my_table" \("name"\)/) - } finally { view.unmount() } -}) - -test('空状态与非表格提示有主动作「读取剪贴板」、次动作「编辑输入」,并按入口写明目标', async () => { - const host = createHost() - for (const [code, goal] of [['table-to-sql', /生成 SQL INSERT/], ['table-to-json', /JSON 对象数组/], ['table-to-markdown', /Markdown 表格/], ['table-auto', /Markdown、JSON、SQL/]]) { - host.clipboard.text = '' - const view = await mount(commands[code], host) - try { - const empty = view.item('empty-input') - assert.match(empty.props.subtitle, goal) - assert.deepEqual(view.actions(empty).map(a => a.props.title), ['读取剪贴板', '编辑输入']) - host.clipboard.text = 'a,b\n1,2' - await view.run(empty, '读取剪贴板') - assert.ok(view.items().some(i => i.props.id === 'sql'), '读取后进入转换结果') - } finally { view.unmount() } - } - const view = await mount(() => TableConverterCommand({ featureCode: 'table-to-sql', initialRawText: '普通文字' }), host) - try { - const item = view.item('not-table') - assert.match(item.props.subtitle, /生成 SQL INSERT/) - await view.run(item, '编辑输入') - const form = await mountPushed(host) - assert.equal(form.field('text').props.value, '普通文字') - form.unmount() - } finally { view.unmount() } -}) - -test('[破坏性] 空状态主动作读取剪贴板失败时保留原输入并提示失败', async () => { - const host = createHost(), view = await mount(() => TableConverterCommand({ initialRawText: '普通文字' }), host) - const read = Clipboard.readText - try { - Clipboard.readText = async () => { throw new Error('剪贴板被占用') } - await view.run(view.item('not-table'), '读取剪贴板') - assert.equal(host.lastToast().style, 'FAILURE') - assert.ok(view.item('not-table')) - assert.match(view.tree().props.filterBar.summaryText, /读取失败/) - } finally { Clipboard.readText = read; view.unmount() } -}) - -test('粘贴表格文件与纯文本:支持 Ctrl+V 粘贴 .csv 文件读取内容转换,以及粘贴表格文本', async () => { - const host = createHost() - host.ipc.filesystem_read_file = async (params) => { - assert.equal(params.path, '/Users/me/report.csv') - assert.equal(params.encoding, 'utf8') - return { content: 'id,name\n1,Alice\n2,Bob' } - } - const view = await mount(TableConverterCommand, host) - try { - await view.pasteFiles(['/Users/me/report.csv']) - await tick() - await view.run(view.item('json'), '复制转换结果') - assert.deepEqual(JSON.parse(host.clipboard.text), [ - { id: 1, name: 'Alice' }, - { id: 2, name: 'Bob' } - ]) - - await view.pasteText('col1,col2\n10,20') - await tick() - await view.run(view.item('json'), '复制转换结果') - assert.deepEqual(JSON.parse(host.clipboard.text), [{ col1: 10, col2: 20 }]) - } finally { - view.unmount() - } -}) diff --git a/extensions/table-converter/tests/integrity.test.mjs b/extensions/table-converter/tests/integrity.test.mjs index c1c3cd40..29d51963 100644 --- a/extensions/table-converter/tests/integrity.test.mjs +++ b/extensions/table-converter/tests/integrity.test.mjs @@ -1,7 +1,20 @@ import test from 'node:test' import assert from 'node:assert/strict' -import { setRuntimeLocale } from '@ztools/declarative-ui' -import { detectAndParse, parseDelimitedRows, gridToJson, gridToCsv, gridToHtml, gridToMarkdown, gridToSql } from '../dist/table-service.js' +import { Toast, renderDeclarativeRoot, setDeclarativeBridge, setRuntimeLocale } from '@ztools/declarative-ui' +import { + buildAllConversionTargets, + detectAndParse, + parseDelimitedRows, + gridToJson, + gridToCsv, + gridToTsv, + gridToHtml, + gridToMarkdown, + gridToSql, + gridToSqlDdl, + transposeGrid +} from '../dist/table-service.js' +import TableConverterCommand from '../dist/index.js' setRuntimeLocale('zh-CN') const grid = (text, header = true) => detectAndParse(text, header).grid @@ -174,3 +187,207 @@ test('Markdown 输出中普通小数和时间保持可读,网址与邮箱仍 // 文字表格不携带类型:读回时 3.14 按可安全往返的数字推断为数值,其余文本原样 assert.deepEqual(json(markdown), [{ ...source[0], price: 3.14 }]) }) + +test('TSV 输出兼容 Excel/飞书直贴,含制表符、换行与双引号可无损往返', () => { + const source = [ + { order_id: '900719925474099312', user: '张三', note: '含\t制表符\n与"引号"', empty: '' }, + { order_id: '900719925474099313', user: 'Alice', note: '正常文本', empty: '' } + ] + const tsv = gridToTsv(grid(JSON.stringify(source))) + assert.match(tsv, /^order_id\tuser\tnote\tempty\r\n/) + const reparsed = detectAndParse(tsv) + assert.equal(reparsed.format, 'tsv') + assert.deepEqual(JSON.parse(gridToJson(reparsed.grid)), source) +}) + +test('CSV UTF-8 BOM 导出与无 BOM 兼容,previewText 不含不可见 BOM', () => { + const g = grid('姓名,金额\n张三,199.5') + const plain = gridToCsv(g) + const withBom = gridToCsv(g, { bom: true }) + assert.equal(plain.startsWith('\uFEFF'), false) + assert.equal(withBom.startsWith('\uFEFF'), true) + assert.equal(withBom.slice(1), plain) + assert.deepEqual(json(withBom), [{ 姓名: '张三', 金额: 199.5 }]) + + const targets = buildAllConversionTargets(g, { csvBom: true }) + const csvTarget = targets.find(item => item.id === 'csv') + assert.ok(csvTarget) + assert.equal(csvTarget.fullText.startsWith('\uFEFF'), true) + assert.equal(csvTarget.previewText.startsWith('\uFEFF'), false) +}) + +test('SQL 多方言(MySQL / PostgreSQL / SQLite)与 CREATE TABLE DDL 推断生成', () => { + const source = [ + { + id: 3000000000, + small_n: 42, + price: 19.95, + active: true, + meta: { tag: 'vip' }, + note: "a\\b'c" + } + ] + const g = grid(JSON.stringify(source)) + + const mysql = gridToSql(g, 'orders`v1', { dialect: 'mysql', includeDdl: true }) + assert.match(mysql, /CREATE TABLE `orders``v1` \(/) + assert.match(mysql, /`id` BIGINT/) + assert.match(mysql, /`small_n` INTEGER/) + assert.match(mysql, /`price` DOUBLE/) + assert.match(mysql, /`active` TINYINT\(1\)/) + assert.match(mysql, /`meta` JSON/) + assert.match(mysql, /`note` VARCHAR\(255\)/) + assert.match(mysql, /INSERT INTO `orders``v1`/) + assert.match(mysql, /'a\\\\b''c'/) + + const pg = gridToSql(g, 'orders', { dialect: 'postgresql', includeDdl: true }) + assert.match(pg, /CREATE TABLE "orders" \(/) + assert.match(pg, /"id" BIGINT/) + assert.match(pg, /"price" DOUBLE PRECISION/) + assert.match(pg, /"active" BOOLEAN/) + assert.match(pg, /"meta" JSONB/) + assert.match(pg, /'a\\b''c'/) + + const sqliteDdl = gridToSqlDdl(g, 'orders', 'sqlite') + assert.match(sqliteDdl, /"id" INTEGER/) + assert.match(sqliteDdl, /"price" REAL/) + assert.match(sqliteDdl, /"note" TEXT/) + + // 仅表头无数据行:开启 DDL 时可输出建表语句,未开启时报错 + const headerOnly = grid('id,name') + const withDdl = buildAllConversionTargets(headerOnly, { sqlDialect: 'mysql', sqlIncludeDdl: true }) + assert.match(withDdl.find(item => item.id === 'sql').fullText, /CREATE TABLE `my_table`/) + const withoutDdl = buildAllConversionTargets(headerOnly, { sqlDialect: 'mysql', sqlIncludeDdl: false }) + assert.match(withoutDdl.find(item => item.id === 'sql').error, /没有数据行/) +}) + +test('自定义分隔符(分号自动识别 / 竖线手动指定)与非法分隔符拒绝', () => { + const semi = detectAndParse('a;b;c\n1;2;3') + assert.equal(semi.format, 'csv') + assert.equal(semi.delimiter, ';') + assert.deepEqual(semi.grid.rows, [['1', '2', '3']]) + + const pipe = detectAndParse('a|b|c\n1|2|3', true, 'auto', '|') + assert.equal(pipe.format, 'csv') + assert.equal(pipe.delimiter, '|') + assert.deepEqual(pipe.grid.rows, [['1', '2', '3']]) + + assert.throws(() => parseDelimitedRows('a:b', ':'), /分隔/) +}) + +test('行列转置与 JSON 压缩模式正确工作', () => { + const g = grid('name,score\nAlice,95\nBob,88') + const transposed = transposeGrid(g) + assert.deepEqual(transposed.headers, ['name', 'Alice', 'Bob']) + assert.deepEqual(transposed.rows, [['score', '95', '88']]) + + const compact = gridToJson(g, false) + assert.equal(compact.includes('\n'), false) + assert.deepEqual(JSON.parse(compact), [{ name: 'Alice', score: 95 }, { name: 'Bob', score: 88 }]) +}) + +test('UI 集成:空剪贴板零假数据、显式选文件与另存为落盘及失败 Fail-Fast', async () => { + const toasts = [] + const savedWrites = [] + let openDialogResult = { canceled: false, filePath: 'orders.csv' } + let saveDialogResult = { canceled: false, filePath: 'out.csv' } + let writeShouldFail = false + + setDeclarativeBridge({ + readClipboardText: async () => '', + showToast: (opts) => { + toasts.push(opts) + return { id: String(toasts.length), update: () => {}, hide: () => {} } + } + }) + + const prevHost = globalThis.__ztoolsElectron + globalThis.__ztoolsElectron = { + transport: { + methods: { + window_show_open_dialog: async () => ({ success: true, data: openDialogResult }), + filesystem_read_file: async () => ({ + success: true, + data: { content: 'order_id,user,amount\n900719925474099312,张三,199.5' } + }), + window_show_save_dialog: async () => ({ success: true, data: saveDialogResult }), + filesystem_write_file: async (req) => { + if (writeShouldFail) return { success: false, error: { message: '磁盘已满' } } + savedWrites.push(req.params) + return { success: true, data: { written: true } } + } + } + } + } + + const flush = () => new Promise(resolve => setTimeout(resolve, 20)) + const root = renderDeclarativeRoot(() => TableConverterCommand({})) + + try { + await flush() + const emptyTree = root.getLatest() + assert.equal(emptyTree.type, 'List') + assert.equal(emptyTree.props.isShowingDetail, true) + assert.deepEqual( + emptyTree.props.filterBar.actions.map(a => a.id), + ['pick-file', 'read-clipboard', 'edit-input'] + ) + const emptyViews = (emptyTree.children || []).filter(c => c && c.type === 'List.EmptyView') + assert.equal(emptyViews.length, 1) + assert.equal((emptyTree.children || []).filter(c => c && c.type === 'List.Item').length, 0) + + // 触发「选择文件」 + const pickAction = emptyTree.props.filterBar.actions.find(a => a.id === 'pick-file') + await pickAction.onAction() + await flush() + + const loadedTree = root.getLatest() + assert.match(loadedTree.props.filterBar.summaryText, /orders\.csv/) + const items = (loadedTree.children || []).filter(c => c && c.type === 'List.Item') + assert.deepEqual(items.map(i => i.props.id), ['markdown', 'tsv', 'json', 'sql', 'csv', 'html']) + + // 触发 CSV 项的「另存为文件」 + const csvItem = items.find(i => i.props.id === 'csv') + const findActions = (node, acc = []) => { + if (!node || typeof node !== 'object') return acc + if (node.type === 'Action') acc.push(node) + if (Array.isArray(node.children)) node.children.forEach(c => findActions(c, acc)) + return acc + } + const csvActions = findActions(csvItem.props.actions) + const saveAction = csvActions.find(a => a.props.title === '另存为文件') + assert.ok(saveAction) + await saveAction.props.onAction() + await flush() + + assert.equal(savedWrites.length, 1) + assert.equal(savedWrites[0].path, 'out.csv') + assert.equal(savedWrites[0].content.startsWith('\uFEFF'), true) + + // 用户取消保存不写盘 + saveDialogResult = { canceled: true } + await saveAction.props.onAction() + await flush() + assert.equal(savedWrites.length, 1) + + // 写入失败时 Fail-Fast 弹失败 Toast + saveDialogResult = { canceled: false, filePath: 'fail.csv' } + writeShouldFail = true + await saveAction.props.onAction() + await flush() + assert.ok(toasts.some(toast => toast.style === Toast.Style.Failure && /磁盘已满/.test(toast.message || ''))) + + // 英文 locale 切换验证 + setRuntimeLocale('en-US') + root.forceRender() + await flush() + const enTree = root.getLatest() + assert.equal(enTree.props.navigationTitle, 'Table Converter') + } finally { + root.unmount() + setRuntimeLocale('zh-CN') + setDeclarativeBridge(null) + if (prevHost === undefined) delete globalThis.__ztoolsElectron + else globalThis.__ztoolsElectron = prevHost + } +}) diff --git a/extensions/text-formatter/package.json b/extensions/text-formatter/package.json index d5e74b4e..1ac644bb 100644 --- a/extensions/text-formatter/package.json +++ b/extensions/text-formatter/package.json @@ -1,6 +1,6 @@ { "name": "text-formatter", - "version": "1.0.9", + "version": "1.0.10", "description": "文本排版与格式化:大小写转换、全半角互转、标点中英文切换、Markdown自动排版、去除首尾/全部空白与空行,一键复制", "type": "module", "main": "dist/index.js", diff --git a/extensions/text-formatter/plugin.json b/extensions/text-formatter/plugin.json index 20981c1b..257b8a6f 100644 --- a/extensions/text-formatter/plugin.json +++ b/extensions/text-formatter/plugin.json @@ -1,7 +1,7 @@ { "id": "text-formatter", "name": "文本排版", - "version": "1.0.9", + "version": "1.0.10", "minAppVersion": "1.1.8.0", "description": "中英文混排自动加空格、中英标点互转、全半角转换、大小写转换与清除多余空行空白", "author": "ZTools Team", diff --git a/extensions/text-formatter/src/i18n.ts b/extensions/text-formatter/src/i18n.ts index 30641c24..906a1978 100644 --- a/extensions/text-formatter/src/i18n.ts +++ b/extensions/text-formatter/src/i18n.ts @@ -3,11 +3,6 @@ import { createTranslator } from "@ztools/declarative-ui"; const rawT = createTranslator( { "zh-CN": { - sampleText: `ZTools 文本格式化工具,支持中英文混排! - 这里有 多余的空格 和不规范的标点. -例如:fullwidth 全角半角转换, -大小写转换,Markdown标题自动空格。 -第二段可以自动首行缩进,并按句子重新分段。`, itemZhSmart: "中文智能排版 (中英空格+标点规范+缩进分段)", itemCjkSpacing: "中英文混排加空格 (规范盘古之白)", itemMarkdownFmt: "Markdown 自动排版 (规范标题与列表空格)", @@ -42,7 +37,7 @@ const rawT = createTranslator( editFormPanelTitle: "待排版文本", editFormSubmitTitle: "应用文本", editFormFieldTitle: "待排版文本", - editFormPlaceholder: "输入或粘贴多行文本,{modEnter} 应用;留空则使用示例文本", + editFormPlaceholder: "输入或粘贴多行文本,{modEnter} 应用;留空则清空当前文本", toastNothingToCopy: "没有可复制的内容", toastNothingToCopyMsg: "{label} 对当前文本没有输出", toastCopied: "已复制: {label}", @@ -55,15 +50,17 @@ const rawT = createTranslator( toastClipboardEmpty: "剪贴板中没有文本内容", toastClipboardReadFailed: "读取剪贴板失败", toastTextUpdated: "已更新待排版文本", - toastResetToSample: "已清空,使用示例文本", + toastCleared: "已清空待排版文本", actionEditText: "编辑待排版文本", actionPasteText: "从剪贴板粘贴文本", sourceBlankLabel: "(空白文本)", sourceEmptyTitle: "输入或粘贴待排版文本", sourceCurrentTag: "当前文本", - sourceSampleTag: "示例文本", + sourceClipboardTag: "来自剪贴板", + sourceEmptySub: "等待输入 · 复制文本后重新读取,或点击编辑待排版文本", + sourceEmptyDetail: "### 等待待排版文本\n\n当前剪贴板为空。你可以:\n\n- 按 **Enter** 打开多行编辑器输入或粘贴待排版文本\n- 先复制任意文本,再点击顶部「从剪贴板粘贴文本」\n- 载入文本后即可即时预览 24 种离线排版结果,并支持将结果设为输入继续链式接力处理", sourceStatsSub: "{tag} · {chars} 字符 · {lines} 行", - actionResetSample: "重置为默认示例文本", + actionClearText: "清空当前文本", navTitle: "文本排版与格式化助手", searchPlaceholder: "筛选转换方式,例如 大写、行号、繁体", filterTooltip: "筛选格式化分类", @@ -71,7 +68,9 @@ const rawT = createTranslator( globalActionsTitle: "全局操作", resultsSectionTitle: "格式化结果 ({count} 项)", charsCount: "{count} 字符", + waitingInputTag: "待输入", noOutputTag: "无输出", + emptyInputDetail: "尚未输入待排版文本,请先编辑文本或从剪贴板读取", noOutputDetail: "该转换对当前文本没有输出内容", actionCopyPrefix: "复制: {label}", actionPasteResultPrefix: "粘贴到前台: {label}", @@ -80,11 +79,6 @@ const rawT = createTranslator( toastAppliedAsInput: "已应用为当前输入" }, "en-US": { - sampleText: `ZTools Text Formatter, smart formatting! - Extra spaces and mixed punct. -e.g. fullwidth halfwidth conversion, -case styles, Markdown heading spacing. -Auto-format lines, lists, and text.`, itemZhSmart: "Smart Chinese Typesetting (Spacing + Punct + Indent)", itemCjkSpacing: "Add CJK-Latin Spacing", itemMarkdownFmt: "Markdown Auto-Format (Headings & Lists)", @@ -119,7 +113,7 @@ Auto-format lines, lists, and text.`, editFormPanelTitle: "Input Text", editFormSubmitTitle: "Apply Text", editFormFieldTitle: "Input Text", - editFormPlaceholder: "Enter or paste multiline text, {modEnter} to apply; leave empty for sample", + editFormPlaceholder: "Enter or paste multiline text, {modEnter} to apply; leave empty to clear", toastNothingToCopy: "Nothing to copy", toastNothingToCopyMsg: "{label} produced no output for current text", toastCopied: "Copied: {label}", @@ -132,15 +126,17 @@ Auto-format lines, lists, and text.`, toastClipboardEmpty: "Clipboard contains no text", toastClipboardReadFailed: "Failed to read clipboard", toastTextUpdated: "Input text updated", - toastResetToSample: "Cleared; using sample text", + toastCleared: "Input text cleared", actionEditText: "Edit Input Text", actionPasteText: "Paste from Clipboard", sourceBlankLabel: "(Blank text)", sourceEmptyTitle: "Enter or Paste Text to Format", sourceCurrentTag: "Current", - sourceSampleTag: "Sample", + sourceClipboardTag: "Clipboard", + sourceEmptySub: "Waiting for input · Copy text and paste from clipboard, or edit input text", + sourceEmptyDetail: "### Waiting for Input Text\n\nYour clipboard is currently empty. You can:\n\n- Press **Enter** to open the multiline editor and enter or paste text\n- Copy any text and click **Paste from Clipboard** above\n- Once loaded, preview all 24 offline transforms and chain results as input", sourceStatsSub: "{tag} · {chars} [[chars:char|chars]] · {lines} [[lines:line|lines]]", - actionResetSample: "Reset to Sample Text", + actionClearText: "Clear Input Text", navTitle: "Text Formatter", searchPlaceholder: "Filter transforms, e.g. uppercase, sort, camelCase", filterTooltip: "Filter category", @@ -148,7 +144,9 @@ Auto-format lines, lists, and text.`, globalActionsTitle: "Global Actions", resultsSectionTitle: "Results ({count})", charsCount: "{count} [[count:char|chars]]", + waitingInputTag: "Waiting", noOutputTag: "Empty", + emptyInputDetail: "No input text yet. Edit input text or paste from clipboard to preview.", noOutputDetail: "This transform produced no output for the current text", actionCopyPrefix: "Copy: {label}", actionPasteResultPrefix: "Paste to Frontmost App: {label}", diff --git a/extensions/text-formatter/src/index.ts b/extensions/text-formatter/src/index.ts index 4d0cf36f..5ec7d0d3 100644 --- a/extensions/text-formatter/src/index.ts +++ b/extensions/text-formatter/src/index.ts @@ -9,6 +9,8 @@ import { Clipboard, useLocale, useState, + useEffect, + useRef, useMemo, useNavigation } from "@ztools/declarative-ui"; @@ -318,20 +320,42 @@ export function EditTextForm({ initialText, onApply }: { initialText: string; on export default function TextFormatterCommand() { const locale = useLocale(); const [inputText, setInputText] = useState(""); + const [inputSource, setInputSource] = useState<"empty" | "clipboard" | "manual">("empty"); const [category, setCategory] = useState("all"); const [searchText, setSearchText] = useState(""); + const userEditedRef = useRef(false); const { push } = useNavigation(); - const effectiveText = inputText || t("sampleText"); - const stats = useMemo(() => getTextStats(effectiveText), [effectiveText]); + // 启动时静默尝试读取剪贴板;空剪贴板或读取失败时保持诚实空态引导,不塞示例文本 + useEffect(() => { + let cancelled = false; + (async () => { + try { + const clipboardText = await Clipboard.readText(); + if (!cancelled && !userEditedRef.current && typeof clipboardText === "string" && clipboardText.length > 0) { + setInputText(clipboardText); + setInputSource("clipboard"); + } + } catch { + // 启动静默读取失败不打扰用户,保持空态引导 + } + })(); + return () => { + cancelled = true; + }; + }, []); + + const hasInput = inputText.length > 0; + const stats = useMemo(() => getTextStats(inputText), [inputText]); const formatItems = useMemo(() => getFormatItems(), [locale]); const categoryLabels = useMemo(() => getCategoryLabels(), [locale]); // 结果只随文本变化重新计算,筛选、切换分类不重复跑 24 种转换 const results = useMemo(() => { const map = new Map(); - for (const item of formatItems) map.set(item.id, item.transform(effectiveText)); + if (!hasInput) return map; + for (const item of formatItems) map.set(item.id, item.transform(inputText)); return map; - }, [effectiveText, formatItems]); + }, [hasInput, inputText, formatItems]); const handleCopy = async (result: string, label: string) => { if (!result) { @@ -363,7 +387,9 @@ export default function TextFormatterCommand() { try { const clipboardText = await Clipboard.readText(); if (clipboardText) { + userEditedRef.current = true; setInputText(clipboardText); + setInputSource("clipboard"); await showToast(Toast.Style.Success, t("toastClipboardRead")); } else { await showToast(Toast.Style.Failure, t("toastClipboardEmpty")); @@ -373,13 +399,21 @@ export default function TextFormatterCommand() { } }; + const handleClear = () => { + userEditedRef.current = true; + setInputText(""); + setInputSource("empty"); + }; + const openEditor = () => push(() => EditTextForm({ initialText: inputText, onApply: (text: string) => { + userEditedRef.current = true; setInputText(text); - showToast(Toast.Style.Success, text ? t("toastTextUpdated") : t("toastResetToSample")); + setInputSource(text ? "manual" : "empty"); + showToast(Toast.Style.Success, text ? t("toastTextUpdated") : t("toastCleared")); } }) ); @@ -393,25 +427,34 @@ export default function TextFormatterCommand() { const editAction = Action({ title: t("actionEditText"), icon: Icon.Pencil, onAction: openEditor }); const pasteAction = Action({ title: t("actionPasteText"), icon: Icon.CopyClipboard, onAction: handlePaste }); + const sourceSummary = hasInput + ? t("sourceStatsSub", { + tag: inputSource === "clipboard" ? t("sourceClipboardTag") : t("sourceCurrentTag"), + chars: stats.characters, + lines: stats.lines + }) + : t("sourceEmptySub"); const sourceItem = List.Item({ id: "source-text", - title: inputText ? firstLine(inputText) || t("sourceBlankLabel") : t("sourceEmptyTitle"), - subtitle: t("sourceStatsSub", { - tag: inputText ? t("sourceCurrentTag") : t("sourceSampleTag"), - chars: stats.characters, - lines: stats.lines - }), + title: hasInput ? firstLine(inputText) || t("sourceBlankLabel") : t("sourceEmptyTitle"), + subtitle: sourceSummary, icon: Icon.Pencil, - detail: List.Item.Detail({ markdown: textPreviewMarkdown(effectiveText, "") }), + detail: List.Item.Detail({ + markdown: hasInput ? textPreviewMarkdown(inputText, "") : t("sourceEmptyDetail") + }), actions: ActionPanel({ title: t("editFormPanelTitle") }, [ editAction, pasteAction, - Action({ - title: t("actionResetSample"), - icon: Icon.Repeat, - onAction: () => setInputText("") - }) + ...(hasInput + ? [ + Action({ + title: t("actionClearText"), + icon: Icon.Trash, + onAction: handleClear + }) + ] + : []) ]) }); @@ -423,11 +466,7 @@ export default function TextFormatterCommand() { onSearchTextChange: (text: string) => setSearchText(text), isShowingDetail: true, filterBar: { - summaryText: t("sourceStatsSub", { - tag: inputText ? t("sourceCurrentTag") : t("sourceSampleTag"), - chars: stats.characters, - lines: stats.lines - }), + summaryText: sourceSummary, actions: [ { id: "edit-text", title: t("actionEditText"), style: "primary", onAction: openEditor }, { id: "paste-text", title: t("actionPasteText"), onAction: handlePaste } @@ -451,11 +490,15 @@ export default function TextFormatterCommand() { actions: ActionPanel({ title: t("globalActionsTitle") }, [ editAction, pasteAction, - Action({ - title: t("actionResetSample"), - icon: Icon.Repeat, - onAction: () => setInputText("") - }) + ...(hasInput + ? [ + Action({ + title: t("actionClearText"), + icon: Icon.Trash, + onAction: handleClear + }) + ] + : []) ]) }, [ @@ -469,9 +512,19 @@ export default function TextFormatterCommand() { id: item.id, title: item.label, icon: item.icon, - accessories: [{ text: result ? t("charsCount", { count: result.length }) : t("noOutputTag") }], + accessories: [ + { + text: hasInput + ? result + ? t("charsCount", { count: result.length }) + : t("noOutputTag") + : t("waitingInputTag") + } + ], detail: List.Item.Detail({ - markdown: textPreviewMarkdown(result, t("noOutputDetail")) + markdown: hasInput + ? textPreviewMarkdown(result, t("noOutputDetail")) + : t("emptyInputDetail") }), actions: ActionPanel({ title: item.label }, [ Action({ @@ -493,7 +546,9 @@ export default function TextFormatterCommand() { await showToast(Toast.Style.Failure, t("toastEmptyResult")); return; } + userEditedRef.current = true; setInputText(result); + setInputSource("manual"); await showToast(Toast.Style.Success, t("toastAppliedAsInput")); } }) diff --git a/extensions/text-formatter/tests/fixes.test.mjs b/extensions/text-formatter/tests/fixes.test.mjs index 6e42504d..ca1f87c9 100644 --- a/extensions/text-formatter/tests/fixes.test.mjs +++ b/extensions/text-formatter/tests/fixes.test.mjs @@ -52,7 +52,7 @@ test('多行正文走 TextArea 编辑页,换行完整保留,行操作按行 assert.equal(previewBody(detailOf(view, 'dedupe-lines')).split('\n').filter((l) => l === 'banana').length, 1) }) -test('编辑页预填当前文本;清空后应用回到示例文本', async () => { +test('编辑页预填当前文本;清空后应用回到诚实空态引导(不塞示例文本)', async () => { const view = await mount(TextFormatterCommand) await applyViaEditor(view, 'a\nb') await view.run(view.item('source-text'), '编辑待排版文本') @@ -61,8 +61,9 @@ test('编辑页预填当前文本;清空后应用回到示例文本', async () await form.fill('text', '') await form.run(null, '应用文本') await tick() - assert.match(sourceSubtitle(view), /^示例文本/) - assert.equal(host.lastToast().title, '已清空,使用示例文本') + assert.match(sourceSubtitle(view), /^等待输入/) + assert.equal(host.lastToast().title, '已清空待排版文本') + assert.deepEqual(view.item('upper-case').props.accessories, [{ text: '待输入' }]) }) test('从剪贴板读取多行文本后,在搜索框输入只筛选转换项,不会覆盖或拍平正文', async () => { @@ -342,16 +343,35 @@ test('清单版本已升级,package.json 与 plugin.json 一致', () => { assert.equal(pkg.version, manifest.version) }) -test('示例文本每行显示宽度不超过 44(中文按 2 计),详情栏代码块不会被横向截断;编辑框快捷键按平台显示', async () => { - const host = createHost() - const view = await mount(TextFormatterCommand, host) +test('启动时静默读取剪贴板;空剪贴板时保持诚实空态引导且不塞示例文本;编辑框快捷键按平台显示', async () => { + // 1. 空剪贴板启动:保持诚实空态,无示例文本,不弹失败 Toast + const emptyHost = createHost() + const emptyView = await mount(TextFormatterCommand, emptyHost) try { - const md = view.item('source-text').props.detail.props.markdown - const body = md.split('\n').slice(1, -1) - assert.ok(body.length >= 4) - const width = line => [...line].reduce((sum, ch) => sum + (/[\u2E80-\uFFEF]/.test(ch) ? 2 : 1), 0) - for (const line of body) assert.ok(width(line) <= 44, `${line} 宽 ${width(line)}`) - } finally { view.unmount() } + await tick() + assert.match(sourceSubtitle(emptyView), /^等待输入/) + assert.match(detailOf(emptyView, 'source-text'), /当前剪贴板为空/) + assert.doesNotMatch(detailOf(emptyView, 'source-text'), /ZTools 文本格式化工具/) + assert.equal(emptyView.items().filter((i) => i.props.id !== 'source-text').length, 24) + assert.deepEqual(emptyView.item('upper-case').props.accessories, [{ text: '待输入' }]) + assert.equal(emptyHost.lastToast(), undefined) + } finally { + emptyView.unmount() + } + + // 2. 剪贴板有文本启动:静默自动载入并即时预览 24 种排版结果 + const filledHost = createHost() + filledHost.clipboard.text = 'hello ztools\nsecond line' + const filledView = await mount(TextFormatterCommand, filledHost) + try { + await tick() + assert.match(sourceSubtitle(filledView), /来自剪贴板 · 24 字符 · 2 行/) + assert.equal(previewBody(detailOf(filledView, 'upper-case')), 'HELLO ZTOOLS\nSECOND LINE') + } finally { + filledView.unmount() + } + + // 3. 编辑框快捷键按平台显示 const { modEnterLabel } = await import('../dist/index.js') const original = Object.getOwnPropertyDescriptor(globalThis, 'navigator') try { diff --git a/extensions/timestamp/package.json b/extensions/timestamp/package.json index 442d9727..0d3ecb3e 100644 --- a/extensions/timestamp/package.json +++ b/extensions/timestamp/package.json @@ -1,6 +1,6 @@ { "name": "timestamp", - "version": "1.1.2", + "version": "1.1.7", "description": "秒与毫秒时间戳双向转换、多时区对照与友好相对时间显示", "type": "module", "main": "dist/index.js", diff --git a/extensions/timestamp/plugin.json b/extensions/timestamp/plugin.json index 1b696028..4c6b96bc 100644 --- a/extensions/timestamp/plugin.json +++ b/extensions/timestamp/plugin.json @@ -1,7 +1,7 @@ { "id": "timestamp", "name": "时间戳转换", - "version": "1.1.6", + "version": "1.1.7", "minAppVersion": "1.1.8.0", "description": "秒与毫秒时间戳、日期格式实时互转,支持全球城市世界时钟与多时区时差换算", "author": "ZTools Team", diff --git a/extensions/timestamp/src/i18n.ts b/extensions/timestamp/src/i18n.ts index 7adf19f0..f00ba3c4 100644 --- a/extensions/timestamp/src/i18n.ts +++ b/extensions/timestamp/src/i18n.ts @@ -5,7 +5,15 @@ export const t = createTranslator( "zh-CN": { navTitle: "时间戳转换助手", worldClockAction: "世界时钟…", - searchPlaceholder: "输入10/13位时间戳或日期字符串 (留空即实时当前时间)...", + worldClockBtn: "世界时钟", + searchPlaceholder: "输入10/13/16/19位时间戳、日期或算式 (如 now + 7d)...", + summaryLive: "实时模式 · 每秒刷新 · 本地 UTC{offset}", + summaryPrecisionSeconds: "已识别 10位秒级时间戳", + summaryPrecisionMs: "已识别 13位毫秒级时间戳", + summaryPrecisionUs: "已识别 16位微秒级时间戳", + summaryPrecisionNs: "已识别 19位纳秒级时间戳", + summaryPrecisionDate: "已解析标准日期时间", + summaryPrecisionExpr: "日期偏移算式: {expr}", sectionLive: "当前实时时间", sectionParsed: "指定时间解析结果", sectionError: "解析错误", @@ -31,6 +39,14 @@ export const t = createTranslator( msAcc: "13位 毫秒", copyMs: "复制毫秒级时间戳", labelMs: "毫秒级时间戳", + usSubtitle: "微秒级 Unix 时间戳 (16位)", + usAcc: "16位 微秒", + copyUs: "复制微秒级时间戳", + labelUs: "微秒级时间戳", + nsSubtitle: "纳秒级 Unix 时间戳 (19位)", + nsAcc: "19位 纳秒", + copyNs: "复制纳秒级时间戳", + labelNs: "纳秒级时间戳", localSubtitle: "本地格式化时间 ({dayOfWeek})", localAccFallback: "本地时间", copyLocal: "复制本地格式化时间", @@ -41,6 +57,10 @@ export const t = createTranslator( utcSubtitle: "国际标准 ISO 8601 时间 (UTC)", copyUtc: "复制 ISO 8601 时间", labelUtc: "UTC标准时间", + compactSubtitle: "紧凑文件名时间戳 (YYYYMMDD_HHmmss)", + compactAcc: "文件命名", + copyCompact: "复制紧凑文件名时间戳", + labelCompact: "紧凑时间戳", relativeSubtitle: "相对友好时间", relativeAcc: "相对时间", copyRelative: "复制相对时间", @@ -52,27 +72,67 @@ export const t = createTranslator( // World clock wcFormTitle: "设置要换算的时刻", wcFormSubmit: "换算时间", - wcFormRequired: "请输入时间戳或日期", - wcFormFieldTitle: "时间戳或日期", - wcFormDesc: "带时区的日期按给定偏移换算;未写时区时按本机时区解释。", + wcFormRequired: "请输入时间戳、日期或偏移算式", + wcFormFieldTitle: "时间戳、日期或当地时间", + wcFormDesc: "支持时间戳、偏移算式 (如 now + 2h)、带时区日期,或按当前参考时区 ({ref}) 解释的当地时间 (如 2026-06-01 09:30 或 09:30),自动校验夏令时跳过时段。", + wcFormDstInvalid: "该时间在 {ref} 中不存在(日期越界,或落在夏令时跳过的无效时段)", wcNavTitle: "世界时钟", - wcSearchPlaceholder: "搜索城市、国家或 IANA 时区,如 旧金山、Tokyo、Europe/Paris", + wcSearchPlaceholder: "搜索 320+ 城市、国家或 IANA 时区,如 旧金山、Tokyo、Europe/Paris", wcRefTooltip: "时差参考时区", wcConvertAction: "换算指定时间…", wcResetAction: "恢复当前时间", + wcSwitchTimestampBtn: "时间戳转换", + wcCopySummaryBtn: "复制会议汇总", + wcCopySummaryAction: "复制多时区会议汇总", + wcCopiedSummaryToast: "已复制多时区会议汇总 ({count} 个时区)", + wcSummaryEmptyToast: "当前没有可汇总的城市", + wcSummaryHeader: "多时区会议时间对照(基准:{ref})", + wcSummaryLive: "实时时钟 · 基准 {ref} · 已收藏 {count} 城", + wcSummaryFixed: "换算时刻 {time} · 基准 {ref} · 已收藏 {count} 城", + wcSectionFavorites: "已收藏城市 ({count}) · 置顶", wcSectionLive: "当前时间 · 相对 {ref} 的时差", wcSectionFixed: "指定时刻 · 相对 {ref} 的时差", + wcSectionMore: "更多全球城市 · 相对 {ref} 的时差", wcOffsetAcc: "时差 {offset}", wcDayDiffPlus: "+{days}天", wcDayDiffMinus: "-{days}天", + wcPeriodWork: "办公时段", + wcPeriodWorkTooltip: "办公时段 09:00–18:00", + wcPeriodDay: "白天", + wcPeriodDayTooltip: "非办公白天时段 (06:00–09:00 / 18:00–22:00)", + wcPeriodNight: "夜间", + wcPeriodNightTooltip: "夜间休息时段 (22:00–06:00)", + wcDstTag: "DST", + wcDstTooltip: "当前处于夏令时 (DST)", wcCopyLocal: "复制当地时间", wcCopiedLocalToast: "已复制当地时间", - wcSetRef: "设为时差参考" + wcSetRef: "设为时差参考", + wcPinFavorite: "收藏并置顶城市", + wcUnpinFavorite: "取消收藏", + wcMoveFavoriteTop: "移到收藏首位", + wcPinnedToast: "已收藏置顶 {city}", + wcUnpinnedToast: "已取消收藏 {city}", + wcMovedTopToast: "已将 {city} 移至收藏首位", + wcStorageReadFailedToast: "读取收藏城市失败", + wcStorageWriteFailedToast: "保存收藏城市失败", + wcStepForward1h: "基准时间 +1 小时", + wcStepBackward1h: "基准时间 -1 小时", + wcSteppedToast: "已将换算基准调整 {delta}", + wcEmptyTitle: "未找到匹配的城市或时区", + wcEmptyDesc: "可尝试输入中英文城市名、国家名或标准 IANA 时区(如 America/New_York)" }, "en-US": { navTitle: "Timestamp Converter", worldClockAction: "World Clock…", - searchPlaceholder: "Enter 10/13-digit timestamp or date string (blank for live time)...", + worldClockBtn: "World Clock", + searchPlaceholder: "Enter 10/13/16/19-digit timestamp, date, or offset (e.g. now + 7d)...", + summaryLive: "Live mode · 1s tick · Local UTC{offset}", + summaryPrecisionSeconds: "Detected 10-digit Unix seconds", + summaryPrecisionMs: "Detected 13-digit Unix milliseconds", + summaryPrecisionUs: "Detected 16-digit Unix microseconds", + summaryPrecisionNs: "Detected 19-digit Unix nanoseconds", + summaryPrecisionDate: "Parsed standard date & time", + summaryPrecisionExpr: "Date offset expression: {expr}", sectionLive: "Current Live Time", sectionParsed: "Parsed Time Result", sectionError: "Parse Error", @@ -98,6 +158,14 @@ export const t = createTranslator( msAcc: "13d ms", copyMs: "Copy Unix Milliseconds", labelMs: "Unix Milliseconds", + usSubtitle: "Unix Timestamp in Microseconds (16 digits)", + usAcc: "16d us", + copyUs: "Copy Unix Microseconds", + labelUs: "Unix Microseconds", + nsSubtitle: "Unix Timestamp in Nanoseconds (19 digits)", + nsAcc: "19d ns", + copyNs: "Copy Unix Nanoseconds", + labelNs: "Unix Nanoseconds", localSubtitle: "Local Formatted Time ({dayOfWeek})", localAccFallback: "Local Time", copyLocal: "Copy Local Time", @@ -108,6 +176,10 @@ export const t = createTranslator( utcSubtitle: "ISO 8601 Time (UTC)", copyUtc: "Copy ISO 8601 Time", labelUtc: "UTC ISO Time", + compactSubtitle: "Compact Filename Timestamp (YYYYMMDD_HHmmss)", + compactAcc: "Filename", + copyCompact: "Copy Compact Filename Timestamp", + labelCompact: "Compact Timestamp", relativeSubtitle: "Relative Time", relativeAcc: "Relative", copyRelative: "Copy Relative Time", @@ -119,22 +191,54 @@ export const t = createTranslator( // World clock wcFormTitle: "Set Reference Time", wcFormSubmit: "Convert Time", - wcFormRequired: "Please enter a timestamp or date", - wcFormFieldTitle: "Timestamp or Date", - wcFormDesc: "Dates with timezone offsets are converted accordingly; otherwise local timezone is used.", + wcFormRequired: "Please enter a timestamp, date, or offset expression", + wcFormFieldTitle: "Timestamp, Date, or Local Time", + wcFormDesc: "Supports Unix timestamps, offset expressions (e.g. now + 2h), zoned dates, or local time in {ref} (e.g. 2026-06-01 09:30 or 09:30) with DST gap validation.", + wcFormDstInvalid: "This time does not exist in {ref} (invalid date or falls inside a DST spring-forward gap)", wcNavTitle: "World Clock", - wcSearchPlaceholder: "Search city, country, or IANA timezone, e.g. San Francisco, Tokyo, Europe/Paris", + wcSearchPlaceholder: "Search 320+ cities, countries, or IANA zones, e.g. San Francisco, Tokyo, Europe/Paris", wcRefTooltip: "Reference Timezone", wcConvertAction: "Convert Specific Time…", wcResetAction: "Restore Current Time", + wcSwitchTimestampBtn: "Timestamp", + wcCopySummaryBtn: "Copy Summary", + wcCopySummaryAction: "Copy Multi-Timezone Meeting Summary", + wcCopiedSummaryToast: "Copied meeting summary ({count} timezones)", + wcSummaryEmptyToast: "No cities available to summarize", + wcSummaryHeader: "Meeting Time Across Timezones (Ref: {ref})", + wcSummaryLive: "Live Clock · Ref {ref} · {count} pinned", + wcSummaryFixed: "Converted {time} · Ref {ref} · {count} pinned", + wcSectionFavorites: "Pinned Cities ({count})", wcSectionLive: "Current Time · Offset vs {ref}", wcSectionFixed: "Selected Time · Offset vs {ref}", + wcSectionMore: "More Global Cities · Offset vs {ref}", wcOffsetAcc: "Offset {offset}", wcDayDiffPlus: "+{days}d", wcDayDiffMinus: "-{days}d", + wcPeriodWork: "Work Hours", + wcPeriodWorkTooltip: "Work Hours 09:00–18:00", + wcPeriodDay: "Daytime", + wcPeriodDayTooltip: "Off-peak Daytime (06:00–09:00 / 18:00–22:00)", + wcPeriodNight: "Night", + wcPeriodNightTooltip: "Night Hours (22:00–06:00)", + wcDstTag: "DST", + wcDstTooltip: "Daylight Saving Time active", wcCopyLocal: "Copy Local Time", wcCopiedLocalToast: "Copied local time", - wcSetRef: "Set as Reference Zone" + wcSetRef: "Set as Reference Zone", + wcPinFavorite: "Pin to Favorites", + wcUnpinFavorite: "Remove from Favorites", + wcMoveFavoriteTop: "Move to Top of Favorites", + wcPinnedToast: "Pinned {city}", + wcUnpinnedToast: "Unpinned {city}", + wcMovedTopToast: "Moved {city} to top of favorites", + wcStorageReadFailedToast: "Failed to load pinned cities", + wcStorageWriteFailedToast: "Failed to save pinned cities", + wcStepForward1h: "Shift Reference +1 Hour", + wcStepBackward1h: "Shift Reference -1 Hour", + wcSteppedToast: "Shifted reference time by {delta}", + wcEmptyTitle: "No matching cities or timezones", + wcEmptyDesc: "Try searching by city name, country, or IANA timezone (e.g. America/New_York)" } }, { defaultLocale: "en-US" } diff --git a/extensions/timestamp/src/index.ts b/extensions/timestamp/src/index.ts index 33430541..de7eab27 100644 --- a/extensions/timestamp/src/index.ts +++ b/extensions/timestamp/src/index.ts @@ -3,7 +3,6 @@ import { ActionPanel, Action, Icon, - Color, showToast, Toast, Clipboard, @@ -14,19 +13,137 @@ import { } from "@ztools/declarative-ui"; import { parseTimeInput, type ParsedTimeResult } from "./logic.js"; import { t } from "./i18n.js"; -import WorldClockCommand from "./world-clock.js"; -import { resolveErrorMessage } from './error-i18n.js' +import WorldClockCommand, { detectLocalTimeZone, worldTime, zoneLabel } from "./world-clock.js"; +import { resolveErrorMessage } from "./error-i18n.js"; + export { - default as tzWorld, detectLocalTimeZone, getDayDiff, formatDayDiffLabel, - searchWorldZones + searchWorldZones, + getTimePeriod, + isDaylightSavingTime, + parseZonedDateTime, + parseWorldReferenceInput, + formatMeetingSummary, + FAVORITES_STORAGE_KEY } from "./world-clock.js"; +export function tzWorld() { + const { push } = useNavigation(); + return WorldClockCommand({ + onSwitchToTimestamp: () => push(TimestampCommand) + }); +} + +function buildFilterSummary(parsed: ParsedTimeResult, isLive: boolean, now: number): string { + if (isLive) { + const localZone = detectLocalTimeZone(); + const offset = zoneLabel(worldTime(new Date(now), localZone).offsetMinutes, true); + return t("summaryLive", { offset }); + } + if (!parsed.valid) { + return t("formatErrorAcc"); + } + switch (parsed.detectedPrecision) { + case "seconds": + return t("summaryPrecisionSeconds"); + case "milliseconds": + return t("summaryPrecisionMs"); + case "microseconds": + return t("summaryPrecisionUs"); + case "nanoseconds": + return t("summaryPrecisionNs"); + case "expression": + return t("summaryPrecisionExpr", { expr: parsed.expressionLabel || "" }); + default: + return t("summaryPrecisionDate"); + } +} + +function renderParsedResultItems( + parsed: ParsedTimeResult, + renderTimeActions: (key: keyof ParsedTimeResult, copyTitle: string, label: string) => ReturnType +) { + return [ + List.Item({ + id: "item-seconds", + title: String(parsed.unixSeconds), + subtitle: t("secondsSubtitle"), + icon: Icon.Key, + accessories: [{ text: t("secondsAcc") }], + actions: renderTimeActions("unixSeconds", t("copySeconds"), t("labelSeconds")) + }), + List.Item({ + id: "item-ms", + title: String(parsed.unixMilliseconds), + subtitle: t("msSubtitle"), + icon: Icon.Key, + accessories: [{ text: t("msAcc") }], + actions: renderTimeActions("unixMilliseconds", t("copyMs"), t("labelMs")) + }), + List.Item({ + id: "item-us", + title: String(parsed.unixMicroseconds || ""), + subtitle: t("usSubtitle"), + icon: Icon.Key, + accessories: [{ text: t("usAcc") }], + actions: renderTimeActions("unixMicroseconds", t("copyUs"), t("labelUs")) + }), + List.Item({ + id: "item-ns", + title: String(parsed.unixNanoseconds || ""), + subtitle: t("nsSubtitle"), + icon: Icon.Key, + accessories: [{ text: t("nsAcc") }], + actions: renderTimeActions("unixNanoseconds", t("copyNs"), t("labelNs")) + }), + List.Item({ + id: "item-local", + title: parsed.localDateTime || "", + subtitle: t("localSubtitle", { dayOfWeek: parsed.dayOfWeek || "" }), + icon: Icon.Calendar, + accessories: [{ text: parsed.dayOfWeek || t("localAccFallback") }], + actions: renderTimeActions("localDateTime", t("copyLocal"), t("labelLocal")) + }), + List.Item({ + id: "item-beijing", + title: parsed.beijingDateTime || "", + subtitle: t("beijingSubtitle"), + icon: Icon.Globe, + accessories: [{ text: "UTC+8" }], + actions: renderTimeActions("beijingDateTime", t("copyBeijing"), t("labelBeijing")) + }), + List.Item({ + id: "item-utc", + title: parsed.utcIso || "", + subtitle: t("utcSubtitle"), + icon: Icon.Document, + accessories: [{ text: "ISO 8601" }], + actions: renderTimeActions("utcIso", t("copyUtc"), t("labelUtc")) + }), + List.Item({ + id: "item-compact", + title: parsed.compactDateTime || "", + subtitle: t("compactSubtitle"), + icon: Icon.Tag, + accessories: [{ text: t("compactAcc") }], + actions: renderTimeActions("compactDateTime", t("copyCompact"), t("labelCompact")) + }), + List.Item({ + id: "item-relative", + title: parsed.relativeTime || "", + subtitle: t("relativeSubtitle"), + icon: Icon.Clock, + accessories: [{ text: t("relativeAcc") }], + actions: renderTimeActions("relativeTime", t("copyRelative"), t("labelRelative")) + }) + ]; +} + export default function TimestampCommand() { useLocale(); - const { push } = useNavigation(); + const { push, pop } = useNavigation(); const [searchText, setSearchText] = useState(""); // 留空时展示的“当前时间”与输入内容的相对时间都依赖 now:每秒推进一次,卸载时清理 const [now, setNow] = useState(() => Date.now()); @@ -43,6 +160,14 @@ export default function TimestampCommand() { const pick = (key: K): ParsedTimeResult[K] => (isLive ? parseTimeInput("", new Date()) : parsed)[key]; + const openWorldClock = () => { + push(() => + WorldClockCommand({ + onSwitchToTimestamp: () => pop() + }) + ); + }; + const handleCopy = async (key: keyof ParsedTimeResult, label: string) => { const val = String(pick(key) ?? ""); await Clipboard.copy(val); @@ -55,7 +180,7 @@ export default function TimestampCommand() { await Clipboard.paste(val); await showToast(Toast.Style.Success, t("pastedToast", { label, val })); } catch (err: unknown) { - await showToast(Toast.Style.Failure, t("pasteFailedToast"), err instanceof Error ? err.message : String(err)); + await showToast(Toast.Style.Failure, t("pasteFailedToast"), resolveErrorMessage(err, t("pasteFailedToast"))); } }; @@ -64,7 +189,11 @@ export default function TimestampCommand() { try { text = String((await Clipboard.readText()) ?? "").trim(); } catch (err: unknown) { - await showToast(Toast.Style.Failure, t("readClipboardFailedToast"), err instanceof Error ? err.message : String(err)); + await showToast( + Toast.Style.Failure, + t("readClipboardFailedToast"), + resolveErrorMessage(err, t("readClipboardFailedToast")) + ); return; } if (!text) { @@ -105,6 +234,11 @@ export default function TimestampCommand() { icon: Icon.Repeat, shortcut: { modifiers: ["ctrl"], key: "r" }, onAction: resetToNow + }), + Action({ + title: t("worldClockAction"), + icon: Icon.Globe, + onAction: openWorldClock }) ]); @@ -112,6 +246,7 @@ export default function TimestampCommand() { { navigationTitle: t("navTitle"), filterBar: { + summaryText: buildFilterSummary(parsed, isLive, now), actions: [ { id: "parse-clipboard", @@ -124,14 +259,12 @@ export default function TimestampCommand() { } }, { - id: "reset-now", - label: t("resetNowBtn"), - title: t("refreshNow"), - icon: Icon.Repeat, + id: "switch-world-clock", + label: t("worldClockBtn"), + title: t("worldClockAction"), + icon: Icon.Globe, style: "secondary", - onAction: () => { - void resetToNow(); - } + onAction: openWorldClock } ] }, @@ -142,7 +275,17 @@ export default function TimestampCommand() { shortcut: { modifiers: ["ctrl", "shift"], key: "v" }, onAction: handleParseClipboard }), - Action({ title: t("worldClockAction"), icon: Icon.Globe, onAction: () => push(WorldClockCommand) }) + Action({ + title: t("worldClockAction"), + icon: Icon.Globe, + onAction: openWorldClock + }), + Action({ + title: t("refreshNow"), + icon: Icon.Repeat, + shortcut: { modifiers: ["ctrl"], key: "r" }, + onAction: resetToNow + }) ]), searchBarPlaceholder: t("searchPlaceholder"), searchText, @@ -152,56 +295,7 @@ export default function TimestampCommand() { parsed.valid ? List.Section( { title: isLive ? t("sectionLive") : t("sectionParsed") }, - [ - List.Item({ - id: "item-seconds", - title: String(parsed.unixSeconds), - subtitle: t("secondsSubtitle"), - icon: Icon.Key, - accessories: [{ text: t("secondsAcc") }], - actions: renderTimeActions("unixSeconds", t("copySeconds"), t("labelSeconds")) - }), - List.Item({ - id: "item-ms", - title: String(parsed.unixMilliseconds), - subtitle: t("msSubtitle"), - icon: Icon.Key, - accessories: [{ text: t("msAcc") }], - actions: renderTimeActions("unixMilliseconds", t("copyMs"), t("labelMs")) - }), - List.Item({ - id: "item-local", - title: parsed.localDateTime || "", - subtitle: t("localSubtitle", { dayOfWeek: parsed.dayOfWeek || "" }), - icon: Icon.Calendar, - accessories: [{ text: parsed.dayOfWeek || t("localAccFallback") }], - actions: renderTimeActions("localDateTime", t("copyLocal"), t("labelLocal")) - }), - List.Item({ - id: "item-beijing", - title: parsed.beijingDateTime || "", - subtitle: t("beijingSubtitle"), - icon: Icon.Globe, - accessories: [{ text: "UTC+8" }], - actions: renderTimeActions("beijingDateTime", t("copyBeijing"), t("labelBeijing")) - }), - List.Item({ - id: "item-utc", - title: parsed.utcIso || "", - subtitle: t("utcSubtitle"), - icon: Icon.Document, - accessories: [{ text: "ISO 8601" }], - actions: renderTimeActions("utcIso", t("copyUtc"), t("labelUtc")) - }), - List.Item({ - id: "item-relative", - title: parsed.relativeTime || "", - subtitle: t("relativeSubtitle"), - icon: Icon.Clock, - accessories: [{ text: t("relativeAcc") }], - actions: renderTimeActions("relativeTime", t("copyRelative"), t("labelRelative")) - }) - ] + renderParsedResultItems(parsed, renderTimeActions) ) : List.Section( { title: t("sectionError") }, diff --git a/extensions/timestamp/src/logic.ts b/extensions/timestamp/src/logic.ts index 38371fda..6e71294c 100644 --- a/extensions/timestamp/src/logic.ts +++ b/extensions/timestamp/src/logic.ts @@ -1,4 +1,5 @@ import { getLocale } from "@ztools/declarative-ui"; +import { ZH_YMD_REGEX_PREFIX } from "./world-clock.zh-data.js"; /** * ZTools 时间戳助手核心转换逻辑 (纯函数) @@ -43,7 +44,7 @@ const LOGIC_STRINGS: Record `${n} 年前`, errOverflow: "时间戳数值超出安全表示范围", errInvalidDate: (text) => `「${text}」不是一个存在的日期或时间`, - errUnparseable: (text) => `无法解析的时间内容: "${text}",支持秒/毫秒时间戳,或带年份的标准日期(如 2024-01-31 08:00:00、ISO 8601、RFC 2822)`, + errUnparseable: (text) => `无法解析的时间内容: "${text}",支持 10/13/16/19 位时间戳、标准日期(ISO 8601 / RFC 2822)或偏移算式(如 now + 7d)`, errYearRange: (year) => `年份超出合理范围 (${year}),请检查时间戳位数是否混淆` }, "en-US": { @@ -64,8 +65,8 @@ const LOGIC_STRINGS: Record `${n}y ago`, errOverflow: "Timestamp value exceeds safe numeric range", errInvalidDate: (text) => `"${text}" is not a valid calendar date or time`, - errUnparseable: (text) => `Unable to parse "${text}". Supports Unix timestamps (sec/ms) or standard dates (e.g. 2024-01-31 08:00:00, ISO 8601, RFC 2822)`, - errYearRange: (year) => `Year (${year}) is out of supported range (1970-2200); check seconds vs. milliseconds` + errUnparseable: (text) => `Unable to parse "${text}". Supports 10/13/16/19-digit Unix timestamps, standard dates (ISO 8601 / RFC 2822), or offsets (e.g. now + 7d)`, + errYearRange: (year) => `Year (${year}) is out of supported range (1970-2200); check timestamp digit precision` } }; @@ -74,14 +75,28 @@ function currentStrings() { return LOGIC_STRINGS[loc] ?? LOGIC_STRINGS["en-US"]; } +export type TimestampPrecision = + | "live" + | "seconds" + | "milliseconds" + | "microseconds" + | "nanoseconds" + | "date" + | "expression"; + export interface ParsedTimeResult { valid: boolean; error?: string; date?: Date; + detectedPrecision?: TimestampPrecision; + expressionLabel?: string; unixSeconds?: number; unixMilliseconds?: number; + unixMicroseconds?: string; + unixNanoseconds?: string; localDateTime?: string; beijingDateTime?: string; + compactDateTime?: string; utcIso?: string; relativeTime?: string; dayOfWeek?: string; @@ -101,6 +116,16 @@ export function formatDateTime(d: Date): string { return `${y}-${m}-${day} ${h}:${min}:${s}`; } +export function formatCompactDateTime(d: Date): string { + const y = d.getFullYear(); + const m = pad(d.getMonth() + 1); + const day = pad(d.getDate()); + const h = pad(d.getHours()); + const min = pad(d.getMinutes()); + const s = pad(d.getSeconds()); + return `${y}${m}${day}_${h}${min}${s}`; +} + export function formatBeijingTime(d: Date): string { // 只读 UTC 字段,避免本地 DST 偏移在加八小时后发生变化。 return new Date(d.getTime() + 3600000 * 8).toISOString().slice(0, 19).replace("T", " "); @@ -145,8 +170,6 @@ const WEEKDAYS = "(?:mon|tue|wed|thu|fri|sat|sun)"; const MONTH_NAMES = "(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)"; const ZONE = "(z|utc|gmt|ut|[+-]\\d{2}:?\\d{2})"; -import { ZH_YMD_REGEX_PREFIX } from "./world-clock.zh-data.js"; - // 年-月-日[ 时:分[:秒[.毫秒]]][时区]:- / . 年月日 分隔,日期与时间之间用空格或 T(ISO 8601) const YMD_RE = new RegExp( ZH_YMD_REGEX_PREFIX + ZONE + "?$", @@ -251,53 +274,315 @@ function buildExactDate(f: DateFields): Date | null { return exact ? new Date(wall.getTime() - f.offsetMinutes * 60000) : null; } +interface ParsedNumericTimestamp { + date: Date; + precision: "seconds" | "milliseconds" | "microseconds" | "nanoseconds"; + unixMicroseconds: string; + unixNanoseconds: string; +} + /** - * 解析用户输入的时间戳或日期字符串 + * 解析纯数字 Unix 时间戳,按位数自动识别秒 (<=11位) / 毫秒 (12-14位) / 微秒 (15-16位) / 纳秒 (18-19位)。 + * 使用 BigInt 保证 16 位微秒与 19 位纳秒零精度丢失。 + */ +function parseNumericTimestamp(text: string): { ok: true; data: ParsedNumericTimestamp } | { ok: false; error: string } { + const s = currentStrings(); + const isNegative = text.startsWith("-"); + const digits = isNegative ? text.slice(1) : text; + const digitCount = digits.length; + + // 17 位或 >=20 位不属于标准秒/毫秒/微秒/纳秒位数,直接拒绝 + if (digitCount === 17 || digitCount >= 20) { + return { ok: false, error: s.errOverflow }; + } + + let big: bigint; + try { + big = BigInt(text); + } catch { + return { ok: false, error: s.errOverflow }; + } + + if (digitCount <= 11) { + const msBig = big * 1000n; + const ms = Number(msBig); + if (!Number.isSafeInteger(ms)) return { ok: false, error: s.errOverflow }; + return { + ok: true, + data: { + date: new Date(ms), + precision: "seconds", + unixMicroseconds: (msBig * 1000n).toString(), + unixNanoseconds: (msBig * 1000000n).toString() + } + }; + } + + if (digitCount <= 14) { + const ms = Number(big); + if (!Number.isSafeInteger(ms)) return { ok: false, error: s.errOverflow }; + return { + ok: true, + data: { + date: new Date(ms), + precision: "milliseconds", + unixMicroseconds: (big * 1000n).toString(), + unixNanoseconds: (big * 1000000n).toString() + } + }; + } + + if (digitCount <= 16) { + const msBig = big / 1000n; + const ms = Number(msBig); + if (!Number.isSafeInteger(ms)) return { ok: false, error: s.errOverflow }; + return { + ok: true, + data: { + date: new Date(ms), + precision: "microseconds", + unixMicroseconds: big.toString(), + unixNanoseconds: (big * 1000n).toString() + } + }; + } + + // 18-19 digits: nanoseconds + const msBig = big / 1000000n; + const usBig = big / 1000n; + const ms = Number(msBig); + if (!Number.isSafeInteger(ms)) return { ok: false, error: s.errOverflow }; + return { + ok: true, + data: { + date: new Date(ms), + precision: "nanoseconds", + unixMicroseconds: usBig.toString(), + unixNanoseconds: big.toString() + } + }; +} + +interface OffsetToken { + sign: 1 | -1; + amount: number; + unit: "ms" | "s" | "m" | "h" | "d" | "w" | "mo" | "y"; +} + +function normalizeOffsetUnit(raw: string): OffsetToken["unit"] | null { + const u = raw.toLowerCase(); + if (u === "ms" || u === "msec" || u === "millisecond" || u === "milliseconds") return "ms"; + if (u === "s" || u === "sec" || u === "secs" || u === "second" || u === "seconds") return "s"; + if (u === "m" || u === "min" || u === "mins" || u === "minute" || u === "minutes") return "m"; + if (u === "h" || u === "hr" || u === "hrs" || u === "hour" || u === "hours") return "h"; + if (u === "d" || u === "day" || u === "days") return "d"; + if (u === "w" || u === "wk" || u === "wks" || u === "week" || u === "weeks") return "w"; + if (u === "mo" || u === "mon" || u === "month" || u === "months") return "mo"; + if (u === "y" || u === "yr" || u === "yrs" || u === "year" || u === "years") return "y"; + return null; +} + +/** 按日历月份安全加减月数(如 1 月 31 日 + 1mo → 2 月 28/29 日,不跨月溢出) */ +function addCalendarMonths(base: Date, deltaMonths: number): Date { + const year = base.getFullYear(); + const month = base.getMonth() + deltaMonths; + const day = base.getDate(); + const targetYear = year + Math.floor(month / 12); + const targetMonth = ((month % 12) + 12) % 12; + const maxDay = new Date(targetYear, targetMonth + 1, 0).getDate(); + return new Date( + targetYear, + targetMonth, + Math.min(day, maxDay), + base.getHours(), + base.getMinutes(), + base.getSeconds(), + base.getMilliseconds() + ); +} + +function applyOffsetTokens(base: Date, tokens: readonly OffsetToken[]): Date { + let current = new Date(base.getTime()); + for (const token of tokens) { + const signed = token.sign * token.amount; + switch (token.unit) { + case "ms": + current = new Date(current.getTime() + signed); + break; + case "s": + current = new Date(current.getTime() + signed * 1000); + break; + case "m": + current = new Date(current.getTime() + signed * 60000); + break; + case "h": + current = new Date(current.getTime() + signed * 3600000); + break; + case "d": + current = new Date(current.getTime() + signed * 86400000); + break; + case "w": + current = new Date(current.getTime() + signed * 7 * 86400000); + break; + case "mo": + current = addCalendarMonths(current, signed); + break; + case "y": + current = addCalendarMonths(current, signed * 12); + break; + } + } + return current; +} + +const OFFSET_UNIT_PATTERN = "(?:milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|months?|mon|mo|m|hours?|hrs?|h|days?|d|weeks?|wks?|w|years?|yrs?|y)"; +const OFFSET_TERM_RE = new RegExp(`([+-])\\s*(\\d+)\\s*(${OFFSET_UNIT_PATTERN})`, "gi"); +const OFFSET_TAIL_RE = new RegExp(`^\\s*(?:[+-]\\s*\\d+\\s*${OFFSET_UNIT_PATTERN}\\s*)+$`, "i"); + +function parseOffsetTerms(tail: string): OffsetToken[] | null { + if (!OFFSET_TAIL_RE.test(tail)) return null; + const tokens: OffsetToken[] = []; + for (const match of tail.matchAll(OFFSET_TERM_RE)) { + const amount = Number(match[2]); + const unit = normalizeOffsetUnit(match[3]); + if (!Number.isSafeInteger(amount) || !unit) return null; + tokens.push({ + sign: match[1] === "-" ? -1 : 1, + amount, + unit + }); + } + return tokens.length > 0 ? tokens : null; +} + +/** + * 解析日期加减偏移算式: + * - "now" + * - "+7d" / "-3h" / "+1d -2h" + * - "now + 7d" / "now - 3h" / "now + 1mo - 2d" + * - "<时间戳或日期> + 7d" / "<时间戳或日期> - 3h" + */ +function parseOffsetExpression(text: string, referenceNow: Date): { date: Date; label: string } | null { + if (/^now$/i.test(text)) { + return { date: new Date(referenceNow.getTime()), label: "now" }; + } + + // 1. 纯偏移简写:+7d / -3h / +1d -30m + if (/^[+-]/.test(text)) { + const tokens = parseOffsetTerms(text); + if (!tokens) return null; + return { date: applyOffsetTokens(referenceNow, tokens), label: text }; + } + + // 2. "now +/- ..." + const nowMatch = text.match(/^now\s*([+-][\s\S]+)$/i); + if (nowMatch) { + const tokens = parseOffsetTerms(nowMatch[1]); + if (!tokens) return null; + return { date: applyOffsetTokens(referenceNow, tokens), label: text }; + } + + // 3. " +/- ":从右向左寻找合法的偏移尾部,避免破坏日期中的 "-" 或时区偏移 "+08:00" + const splitRegex = new RegExp(`\\s+([+-]\\s*\\d+\\s*${OFFSET_UNIT_PATTERN}(?:\\s*[+-]\\s*\\d+\\s*${OFFSET_UNIT_PATTERN})*)$`, "i"); + const splitMatch = text.match(splitRegex); + if (!splitMatch || splitMatch.index === undefined) return null; + + const baseRaw = text.slice(0, splitMatch.index).trim(); + const tailRaw = splitMatch[1].trim(); + if (!baseRaw) return null; + + const tokens = parseOffsetTerms(tailRaw); + if (!tokens) return null; + + const baseDate = parseBaseTimeOnly(baseRaw, referenceNow); + if (!baseDate) return null; + + return { date: applyOffsetTokens(baseDate, tokens), label: text }; +} + +function parseBaseTimeOnly(baseText: string, referenceNow: Date): Date | null { + if (/^now$/i.test(baseText)) return new Date(referenceNow.getTime()); + if (/^-?\d+$/.test(baseText)) { + const numRes = parseNumericTimestamp(baseText); + return numRes.ok ? numRes.data.date : null; + } + const fields = matchDateFields(baseText); + if (!fields) return null; + return buildExactDate(fields); +} + +function buildSuccessResult( + date: Date, + referenceNow: Date, + precision: TimestampPrecision, + options?: { unixMicroseconds?: string; unixNanoseconds?: string; expressionLabel?: string; isLive?: boolean } +): ParsedTimeResult { + const s = currentStrings(); + const ms = date.getTime(); + const msBig = BigInt(ms); + return { + valid: true, + date, + detectedPrecision: precision, + expressionLabel: options?.expressionLabel, + unixSeconds: Math.floor(ms / 1000), + unixMilliseconds: ms, + unixMicroseconds: options?.unixMicroseconds ?? (msBig * 1000n).toString(), + unixNanoseconds: options?.unixNanoseconds ?? (msBig * 1000000n).toString(), + localDateTime: formatDateTime(date), + beijingDateTime: formatBeijingTime(date), + compactDateTime: formatCompactDateTime(date), + utcIso: date.toISOString(), + relativeTime: options?.isLive ? s.nowJustNow : getRelativeTime(date, referenceNow), + dayOfWeek: s.weekdays[date.getDay()] + }; +} + +/** + * 解析用户输入的时间戳、日期字符串或偏移算式 */ export function parseTimeInput(rawInput?: string, referenceNow: Date = new Date()): ParsedTimeResult { const text = (rawInput || "").trim(); - const s = currentStrings(); + // 空输入默认当前时间 if (!text) { - const d = referenceNow; - return { - valid: true, - date: d, - unixSeconds: Math.floor(d.getTime() / 1000), - unixMilliseconds: d.getTime(), - localDateTime: formatDateTime(d), - beijingDateTime: formatBeijingTime(d), - utcIso: d.toISOString(), - relativeTime: s.nowJustNow, - dayOfWeek: s.weekdays[d.getDay()] - }; + return buildSuccessResult(referenceNow, referenceNow, "live", { isLive: true }); } let date: Date | null = null; + let precision: TimestampPrecision = "date"; + let unixMicroseconds: string | undefined; + let unixNanoseconds: string | undefined; + let expressionLabel: string | undefined; - // 1. 纯数字时间戳判断 + // 1. 纯数字时间戳判断(自动识别 10位秒 / 13位毫秒 / 16位微秒 / 19位纳秒) if (/^-?\d+$/.test(text)) { - const num = Number(text); - if (isNaN(num)) { - return { valid: false, error: s.errOverflow }; - } - // 10 位数左右 (秒级) - if (Math.abs(num) < 1e11) { - date = new Date(num * 1000); - } else { - // 13 位数 (毫秒级) - date = new Date(num); + const parsedNum = parseNumericTimestamp(text); + if (!parsedNum.ok) { + return { valid: false, error: parsedNum.error }; } + date = parsedNum.data.date; + precision = parsedNum.data.precision; + unixMicroseconds = parsedNum.data.unixMicroseconds; + unixNanoseconds = parsedNum.data.unixNanoseconds; } else { - // 2. 只接受白名单内的日期写法并逐字段严格校验;不再交给宽松的 Date.parse, - // 否则 "abc 1"、"version 3.2"、"Oct 21" 会被 V8 补成 2001 年的伪造日期 + // 2. 先尝试严格白名单日期解析(避免干扰 ISO 8601 时区偏移如 +08:00) const fields = matchDateFields(text); if (fields) { date = buildExactDate(fields); if (!date) { return { valid: false, error: s.errInvalidDate(text) }; } + precision = "date"; + } else { + // 3. 尝试日期加减偏移算式(如 now + 7d / now - 3h / +2h / 1700000000 + 30m) + const expr = parseOffsetExpression(text, referenceNow); + if (expr) { + date = expr.date; + precision = "expression"; + expressionLabel = expr.label; + } } } @@ -308,7 +593,7 @@ export function parseTimeInput(rawInput?: string, referenceNow: Date = new Date( }; } - // 边界保护:检查年份合理范围 (1970 ~ 2100) + // 边界保护:检查年份合理范围 (1970 ~ 2200) const fullYear = date.getUTCFullYear(); if (fullYear < 1970 || fullYear > 2200) { return { @@ -317,15 +602,9 @@ export function parseTimeInput(rawInput?: string, referenceNow: Date = new Date( }; } - return { - valid: true, - date, - unixSeconds: Math.floor(date.getTime() / 1000), - unixMilliseconds: date.getTime(), - localDateTime: formatDateTime(date), - beijingDateTime: formatBeijingTime(date), - utcIso: date.toISOString(), - relativeTime: getRelativeTime(date, referenceNow), - dayOfWeek: s.weekdays[date.getDay()] - }; + return buildSuccessResult(date, referenceNow, precision, { + unixMicroseconds, + unixNanoseconds, + expressionLabel + }); } diff --git a/extensions/timestamp/src/world-clock.ts b/extensions/timestamp/src/world-clock.ts index ad097c2d..d3e1990b 100644 --- a/extensions/timestamp/src/world-clock.ts +++ b/extensions/timestamp/src/world-clock.ts @@ -1,6 +1,22 @@ -import { List, Form, ActionPanel, Action, Icon, Clipboard, getLocale, showToast, Toast, useState, useEffect, useNavigation, useLocale } from "@ztools/declarative-ui"; +import { + List, + Form, + ActionPanel, + Action, + Icon, + Clipboard, + LocalStorage, + getLocale, + showToast, + Toast, + useState, + useEffect, + useNavigation, + useLocale +} from "@ztools/declarative-ui"; import { parseTimeInput } from "./logic.js"; import { t } from "./i18n.js"; +import { resolveErrorMessage } from "./error-i18n.js"; import { CITY_NAMES_ZH, WORLD_CITIES, type WorldCityDef } from "./world-clock.zh-data.js"; const CITY_NAMES_EN: Record = { @@ -17,6 +33,7 @@ const CITY_NAMES_BY_LOCALE: Record> = { }; const DEFAULT_FALLBACK_TIMEZONE = "Asia/Shanghai"; +export const FAVORITES_STORAGE_KEY = "world-clock:favorites:v1"; // 按 IANA 时区索引城市库,避免每次渲染线性扫描 const CITIES_BY_ZONE = new Map(); @@ -27,7 +44,8 @@ for (const city of WORLD_CITIES) { } const formatters = new Map(); -export function worldTime(date: Date, zone: string): { time: string; offsetMinutes: number } { + +export function worldTime(date: Date, zone: string): { time: string; offsetMinutes: number; hour: number } { const locale = getLocale(); const cacheKey = `${locale}|${zone}`; let formatter = formatters.get(cacheKey); @@ -47,8 +65,10 @@ export function worldTime(date: Date, zone: string): { time: string; offsetMinut } const parts = formatter.formatToParts(date); const value = (type: Intl.DateTimeFormatPartTypes) => parts.find(part => part.type === type)?.value || ""; - const time = `${value("year")}-${value("month")}-${value("day")} ${value("hour")}:${value("minute")}:${value("second")}`; - return { time, offsetMinutes: Math.round((Date.parse(time.replace(" ", "T") + "Z") - Math.floor(date.getTime() / 1000) * 1000) / 60000) }; + const hourStr = value("hour"); + const time = `${value("year")}-${value("month")}-${value("day")} ${hourStr}:${value("minute")}:${value("second")}`; + const offsetMinutes = Math.round((Date.parse(time.replace(" ", "T") + "Z") - Math.floor(date.getTime() / 1000) * 1000) / 60000); + return { time, offsetMinutes, hour: Number(hourStr) }; } /** ascii=true 时用普通减号:复制出去的文本要能被其它程序当作时区偏移解析,U+2212 减号不行 */ @@ -57,16 +77,27 @@ export function zoneLabel(minutes: number, ascii = false): string { return `${minutes < 0 ? (ascii ? "-" : "−") : "+"}${String(Math.floor(abs / 60)).padStart(2, "0")}:${String(abs % 60).padStart(2, "0")}`; } +export function isValidTimeZone(zone: string): boolean { + if (!zone || typeof zone !== "string") return false; + try { + new Intl.DateTimeFormat("en", { timeZone: zone }); + return true; + } catch (err: unknown) { + return err === null; + } +} + /** 自动检测本机系统时区;取不到或不是合法 IANA 时区时才降级到 Asia/Shanghai */ export function detectLocalTimeZone(fallback = DEFAULT_FALLBACK_TIMEZONE): string { try { const tz = Intl.DateTimeFormat().resolvedOptions().timeZone; - if (tz) { - new Intl.DateTimeFormat("en", { timeZone: tz }); + if (tz && isValidTimeZone(tz)) { return tz; } - } catch { - // 降级到 fallback + } catch (err: unknown) { + if (err !== undefined) { + return fallback; + } } return fallback; } @@ -87,6 +118,188 @@ export function formatDayDiffLabel(dayDiff: number): string { return dayDiff > 0 ? t("wcDayDiffPlus", { days }) : t("wcDayDiffMinus", { days }); } +export type DayPeriod = "work" | "day" | "night"; + +/** + * 判断当地小时数所属时段: + * - 09:00–17:59: work (办公时段) + * - 06:00–08:59 / 18:00–21:59: day (白天) + * - 22:00–05:59: night (夜间) + */ +export function getTimePeriod(hour: number): DayPeriod { + if (hour >= 9 && hour < 18) return "work"; + if ((hour >= 6 && hour < 9) || (hour >= 18 && hour < 22)) return "day"; + return "night"; +} + +function getPeriodMeta(period: DayPeriod): { label: string; tooltip: string } { + if (period === "work") { + return { label: t("wcPeriodWork"), tooltip: t("wcPeriodWorkTooltip") }; + } + if (period === "day") { + return { label: t("wcPeriodDay"), tooltip: t("wcPeriodDayTooltip") }; + } + return { label: t("wcPeriodNight"), tooltip: t("wcPeriodNightTooltip") }; +} + +/** + * 精准判断目标 IANA 时区在给定时刻是否处于夏令时 (DST)。 + * 同时兼容北半球(纽约/伦敦)与南半球(悉尼/奥克兰),无夏令时地区恒返回 false。 + */ +export function isDaylightSavingTime(date: Date, zone: string): boolean { + const year = date.getUTCFullYear(); + const janOffset = worldTime(new Date(Date.UTC(year, 0, 1, 12, 0, 0)), zone).offsetMinutes; + const julOffset = worldTime(new Date(Date.UTC(year, 6, 1, 12, 0, 0)), zone).offsetMinutes; + if (janOffset === julOffset) return false; + const standardOffset = Math.min(janOffset, julOffset); + return worldTime(date, zone).offsetMinutes > standardOffset; +} + +interface ZonedParts { + year: number; + month: number; + day: number; + hour: number; + minute: number; + second: number; +} + +function getZonedDateTimeParts(date: Date, tz: string): ZonedParts { + const parts = new Intl.DateTimeFormat("en-GB", { + timeZone: tz, + year: "numeric", + month: "2-digit", + day: "2-digit", + hour: "2-digit", + minute: "2-digit", + second: "2-digit", + hourCycle: "h23", + numberingSystem: "latn" + }).formatToParts(date); + const get = (type: Intl.DateTimeFormatPartTypes) => + Number(parts.find(part => part.type === type)?.value ?? Number.NaN); + return { + year: get("year"), + month: get("month"), + day: get("day"), + hour: get("hour"), + minute: get("minute"), + second: get("second") + }; +} + +/** + * 将不带偏移量的当地日期时间(YYYY-MM-DDTHH:MM[:SS])按指定 IANA 时区解释为绝对时间。 + * - 夏令时秋季回拨产生两个候选时确定性地取较早一次; + * - 夏令时春季跳过不存在的无效时段(如 America/New_York 2026-03-08 02:30)返回 null。 + */ +export function parseZonedDateTime(value: string, tz: string): Date | null { + const match = value.match(/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2}))?$/); + if (!match) return null; + + const expected: ZonedParts = { + year: Number(match[1]), + month: Number(match[2]), + day: Number(match[3]), + hour: Number(match[4]), + minute: Number(match[5]), + second: Number(match[6] ?? 0) + }; + const wallClockUtc = Date.UTC( + expected.year, + expected.month - 1, + expected.day, + expected.hour, + expected.minute, + expected.second + ); + const validated = new Date(wallClockUtc); + if ( + validated.getUTCFullYear() !== expected.year || + validated.getUTCMonth() + 1 !== expected.month || + validated.getUTCDate() !== expected.day || + validated.getUTCHours() !== expected.hour || + validated.getUTCMinutes() !== expected.minute || + validated.getUTCSeconds() !== expected.second + ) { + return null; + } + + if (!isValidTimeZone(tz)) return null; + + const offsets = new Set(); + for (const delta of [-86400000, 0, 86400000]) { + const sample = new Date(wallClockUtc + delta); + const parts = getZonedDateTimeParts(sample, tz); + offsets.add( + Date.UTC(parts.year, parts.month - 1, parts.day, parts.hour, parts.minute, parts.second) - sample.getTime() + ); + } + + const candidates = [...offsets] + .map(offset => new Date(wallClockUtc - offset)) + .filter(candidate => { + const parts = getZonedDateTimeParts(candidate, tz); + return ( + parts.year === expected.year && + parts.month === expected.month && + parts.day === expected.day && + parts.hour === expected.hour && + parts.minute === expected.minute && + parts.second === expected.second + ); + }) + .sort((a, b) => a.getTime() - b.getTime()); + + return candidates[0] ?? null; +} + +/** + * 解析世界时钟换算表单输入: + * - 纯当地时间(如 "09:30" 或 "2026-03-08 02:30")按参考时区 referenceZone 做 DST 严格解析; + * - 其余(时间戳、偏移算式、带时区 ISO/RFC 日期)走 parseTimeInput。 + */ +export function parseWorldReferenceInput( + raw: string, + referenceZone: string, + now: Date = new Date() +): { ok: true; date: Date } | { ok: false; error: string } { + const text = raw.trim().replace(/\s+/g, " "); + if (!text) return { ok: false, error: t("wcFormRequired") }; + + const pad2 = (s: string) => s.padStart(2, "0"); + + // 1. 仅输入时间 HH:MM[:SS] -> 取参考时区当天 + const timeOnly = text.match(/^(\d{1,2}):(\d{2})(?::(\d{2}))?$/); + if (timeOnly) { + const today = worldTime(now, referenceZone).time.slice(0, 10); + const normalized = `${today}T${pad2(timeOnly[1])}:${timeOnly[2]}${timeOnly[3] ? ":" + timeOnly[3] : ""}`; + const resolved = parseZonedDateTime(normalized, referenceZone); + if (!resolved) { + return { ok: false, error: t("wcFormDstInvalid", { ref: resolveZoneLabel(referenceZone) }) }; + } + return { ok: true, date: resolved }; + } + + // 2. 不带时区后缀的 YYYY-MM-DD HH:MM[:SS] / YYYY/MM/DD HH:MM[:SS] -> 按参考时区做 DST 校验 + const zonedWall = text.match(/^(\d{4})[-/](\d{1,2})[-/](\d{1,2})[ T](\d{1,2}):(\d{2})(?::(\d{2}))?$/); + if (zonedWall) { + const normalized = `${zonedWall[1]}-${pad2(zonedWall[2])}-${pad2(zonedWall[3])}T${pad2(zonedWall[4])}:${zonedWall[5]}${zonedWall[6] ? ":" + zonedWall[6] : ""}`; + const resolved = parseZonedDateTime(normalized, referenceZone); + if (!resolved) { + return { ok: false, error: t("wcFormDstInvalid", { ref: resolveZoneLabel(referenceZone) }) }; + } + return { ok: true, date: resolved }; + } + + // 3. 其它标准时间戳、带偏移日期、日期偏移算式 + const parsed = parseTimeInput(text, now); + if (!parsed.valid || !parsed.date) { + return { ok: false, error: resolveErrorMessage(parsed, t("parseErrorFallback")) }; + } + return { ok: true, date: parsed.date }; +} + /** 根据当前语言解析某 IANA 时区的友好显示名称 */ export function resolveZoneLabel(zone: string, locale = getLocale()): string { const isZh = locale === "zh-CN"; @@ -104,6 +317,50 @@ export interface WorldZoneEntry { title: string; } +/** + * 生成便于直接粘贴进跨国会议邀请的多时区时间对照汇总文案。 + */ +export function formatMeetingSummary( + date: Date, + entries: readonly WorldZoneEntry[], + referenceZone: string, + locale = getLocale() +): string { + const refLabel = resolveZoneLabel(referenceZone, locale); + const header = t("wcSummaryHeader", { ref: refLabel }); + const lines = entries.map(({ zone, title }) => { + const info = worldTime(date, zone); + const dst = isDaylightSavingTime(date, zone); + const period = getPeriodMeta(getTimePeriod(info.hour)).label; + const dayLabel = formatDayDiffLabel(getDayDiff(date, zone, referenceZone)); + const offsetStr = `UTC${zoneLabel(info.offsetMinutes, true)}${dst ? ` ${t("wcDstTag")}` : ""}`; + const timeShort = info.time.slice(0, 16); + const dayPart = dayLabel ? ` (${dayLabel})` : ""; + return `- ${title} (${zone}): ${timeShort}${dayPart} [${offsetStr} · ${period}]`; + }); + return [header, ...lines].join("\n"); +} + +function parseStoredFavorites(raw: unknown): string[] { + let list: unknown = raw; + if (typeof raw === "string") { + const trimmed = raw.trim(); + if (!trimmed) return []; + list = JSON.parse(trimmed); + } + if (!Array.isArray(list)) return []; + const deduped: string[] = []; + const seen = new Set(); + for (const item of list) { + if (typeof item !== "string") continue; + const zone = item.trim(); + if (!zone || seen.has(zone) || !isValidTimeZone(zone)) continue; + seen.add(zone); + deduped.push(zone); + } + return deduped; +} + function availableZones(): string[] { const intl = Intl as typeof Intl & { supportedValuesOf?: (key: "timeZone") => string[] }; return [ @@ -165,103 +422,403 @@ export function searchWorldZones(query: string, zones: readonly string[], locale return results; } -function ReferenceTimeForm({ onSave }: { onSave: (date: Date) => void }) { - useLocale(); +function ReferenceTimeForm({ + referenceZone, + onSave +}: { + referenceZone: string; + onSave: (date: Date) => void; +}) { + const locale = useLocale(); const [text, setText] = useState(""); const [error, setError] = useState(undefined); const { pop } = useNavigation(); - return Form({ - navigationTitle: t("wcFormTitle"), + const refLabel = resolveZoneLabel(referenceZone, locale); + + return Form( + { + navigationTitle: t("wcFormTitle"), + actions: ActionPanel({}, [ + Action.SubmitForm({ + title: t("wcFormSubmit"), + onSubmit: () => { + const result = parseWorldReferenceInput(text, referenceZone, new Date()); + if (!result.ok) { + setError(result.error); + return; + } + onSave(result.date); + pop(); + } + }) + ]) + }, + [ + Form.TextField({ + id: "time", + title: t("wcFormFieldTitle"), + value: text, + placeholder: "2026-03-08 09:30 / 2026-03-08T12:00:00+08:00 / now + 2h", + error, + onChange: value => { + setText(value); + setError(undefined); + } + }), + Form.Description({ text: t("wcFormDesc", { ref: refLabel }) }) + ] + ); +} + +function buildSummaryEntries( + reference: string, + favorites: readonly string[], + filtered: readonly WorldZoneEntry[], + locale: string +): WorldZoneEntry[] { + const seen = new Set(); + const list: WorldZoneEntry[] = []; + const addZone = (zone: string, title?: string) => { + if (seen.has(zone)) return; + seen.add(zone); + list.push({ zone, title: title ?? resolveZoneLabel(zone, locale) }); + }; + + if (favorites.length > 0) { + addZone(reference); + for (const fav of favorites) { + addZone(fav); + } + return list; + } + + addZone(reference); + for (const entry of filtered) { + if (list.length >= 6) break; + addZone(entry.zone, entry.title); + } + return list; +} + +function partitionWorldEntries( + query: string, + favorites: readonly string[], + filtered: readonly WorldZoneEntry[], + locale: string +): { favoriteEntries: WorldZoneEntry[]; remainingEntries: WorldZoneEntry[] } { + const favoriteSet = new Set(favorites); + if (!query.trim()) { + return { + favoriteEntries: favorites.map(zone => ({ zone, title: resolveZoneLabel(zone, locale) })), + remainingEntries: filtered.filter(entry => !favoriteSet.has(entry.zone)) + }; + } + const matchedByZone = new Map(filtered.map(entry => [entry.zone, entry])); + return { + favoriteEntries: favorites + .map(zone => matchedByZone.get(zone)) + .filter((entry): entry is WorldZoneEntry => entry !== undefined), + remainingEntries: filtered.filter(entry => !favoriteSet.has(entry.zone)) + }; +} + +interface RenderZoneItemContext { + date: Date; + fixed: number | null; + reference: string; + baseline: number; + favorites: readonly string[]; + favoriteSet: ReadonlySet; + sharedActions: ReturnType[]; + onToggleFavorite: (zone: string) => Promise; + onMoveFavoriteTop: (zone: string) => Promise; + onSetReference: (zone: string) => void; +} + +function renderWorldZoneItem(entry: WorldZoneEntry, ctx: RenderZoneItemContext) { + const { zone, title } = entry; + const value = worldTime(ctx.date, zone); + const dayLabel = formatDayDiffLabel(getDayDiff(ctx.date, zone, ctx.reference)); + const period = getTimePeriod(value.hour); + const periodMeta = getPeriodMeta(period); + const dst = isDaylightSavingTime(ctx.date, zone); + const isFav = ctx.favoriteSet.has(zone); + const isFirstFav = ctx.favorites[0] === zone; + + return List.Item({ + id: zone, + title, + subtitle: `${value.time} · UTC${zoneLabel(value.offsetMinutes)}${dst ? ` · ${t("wcDstTag")}` : ""}`, + icon: isFav ? Icon.Star : period === "night" ? Icon.Moon : Icon.Clock, + accessories: [ + ...(dayLabel ? [{ text: dayLabel }] : []), + { tag: periodMeta.label, tooltip: periodMeta.tooltip }, + ...(dst ? [{ tag: t("wcDstTag"), tooltip: t("wcDstTooltip") }] : []), + { text: t("wcOffsetAcc", { offset: zoneLabel(value.offsetMinutes - ctx.baseline) }) } + ], actions: ActionPanel({}, [ - Action.SubmitForm({ - title: t("wcFormSubmit"), - onSubmit: () => { - if (!text.trim()) { setError(t("wcFormRequired")); return; } - const parsed = parseTimeInput(text); - if (!parsed.valid || !parsed.date) { setError(parsed.error); return; } - onSave(parsed.date); - pop(); + Action({ + title: t("wcCopyLocal"), + icon: Icon.CopyClipboard, + onAction: async () => { + const current = worldTime(new Date(ctx.fixed ?? Date.now()), zone); + await Clipboard.copy(`${current.time} UTC${zoneLabel(current.offsetMinutes, true)} (${zone})`); + await showToast(Toast.Style.Success, t("wcCopiedLocalToast")); } - }) + }), + Action({ + title: isFav ? t("wcUnpinFavorite") : t("wcPinFavorite"), + icon: isFav ? Icon.StarDisabled : Icon.Star, + shortcut: { modifiers: ["ctrl"], key: "p" }, + onAction: () => ctx.onToggleFavorite(zone) + }), + ...(isFav && !isFirstFav + ? [ + Action({ + title: t("wcMoveFavoriteTop"), + icon: Icon.ArrowUp, + onAction: () => ctx.onMoveFavoriteTop(zone) + }) + ] + : []), + ...(zone === ctx.reference + ? [] + : [ + Action({ + title: t("wcSetRef"), + icon: Icon.Pin, + onAction: () => ctx.onSetReference(zone) + }) + ]), + ...ctx.sharedActions ]) - }, [ - Form.TextField({ - id: "time", - title: t("wcFormFieldTitle"), - value: text, - placeholder: "2026-03-08T12:00:00+08:00", - error, - onChange: value => { setText(value); setError(undefined); } - }), - Form.Description({ text: t("wcFormDesc") }) - ]); + }); +} + +export interface WorldClockCommandProps { + onSwitchToTimestamp?: () => void; } -export default function WorldClockCommand() { +export default function WorldClockCommand(props?: WorldClockCommandProps) { const locale = useLocale(); const cityNames = CITY_NAMES_BY_LOCALE[locale] ?? CITY_NAMES_BY_LOCALE["en-US"]; const [query, setQuery] = useState(""); const [reference, setReference] = useState(() => detectLocalTimeZone()); const [fixed, setFixed] = useState(null); - const [now, setNow] = useState(Date.now()); + const [now, setNow] = useState(() => Date.now()); + const [favorites, setFavorites] = useState([]); const [zones] = useState(availableZones); - const { push } = useNavigation(); + const { push, pop } = useNavigation(); + useEffect(() => { if (fixed !== null) return; const timer = setInterval(() => setNow(Date.now()), 1000); return () => clearInterval(timer); }, [fixed]); + useEffect(() => { + let active = true; + const load = async () => { + try { + const stored = await LocalStorage.getItem(FAVORITES_STORAGE_KEY); + if (!active) return; + setFavorites(parseStoredFavorites(stored)); + } catch (err: unknown) { + if (!active) return; + await showToast( + Toast.Style.Failure, + t("wcStorageReadFailedToast"), + resolveErrorMessage(err, t("wcStorageReadFailedToast")) + ); + } + }; + void load(); + return () => { + active = false; + }; + }, []); + + const persistFavorites = async (next: string[], successMessage: string) => { + const previous = favorites; + setFavorites(next); + try { + await LocalStorage.setItem(FAVORITES_STORAGE_KEY, JSON.stringify(next)); + await showToast(Toast.Style.Success, successMessage); + } catch (err: unknown) { + setFavorites(previous); + await showToast( + Toast.Style.Failure, + t("wcStorageWriteFailedToast"), + resolveErrorMessage(err, t("wcStorageWriteFailedToast")) + ); + } + }; + + const toggleFavorite = async (zone: string) => { + const cityLabel = resolveZoneLabel(zone, locale); + if (favorites.includes(zone)) { + await persistFavorites( + favorites.filter(z => z !== zone), + t("wcUnpinnedToast", { city: cityLabel }) + ); + } else { + await persistFavorites([...favorites, zone], t("wcPinnedToast", { city: cityLabel })); + } + }; + + const moveFavoriteToTop = async (zone: string) => { + const cityLabel = resolveZoneLabel(zone, locale); + await persistFavorites( + [zone, ...favorites.filter(z => z !== zone)], + t("wcMovedTopToast", { city: cityLabel }) + ); + }; + + const stepReferenceHours = async (deltaHours: number) => { + const nextMs = (fixed ?? Date.now()) + deltaHours * 3600000; + setFixed(nextMs); + await showToast(Toast.Style.Success, t("wcSteppedToast", { delta: deltaHours > 0 ? `+${deltaHours}h` : `${deltaHours}h` })); + }; + const date = new Date(fixed ?? now); const baseline = worldTime(date, reference).offsetMinutes; - const actions = [ - Action({ title: t("wcConvertAction"), icon: Icon.Calendar, onAction: () => push(() => ReferenceTimeForm({ onSave: value => setFixed(value.getTime()) })) }), - Action({ title: t("wcResetAction"), icon: Icon.Repeat, onAction: () => { setFixed(null); setNow(Date.now()); } }) + const refLabel = resolveZoneLabel(reference, locale); + const filtered = searchWorldZones(query, zones, locale); + const favoriteSet = new Set(favorites); + const { favoriteEntries, remainingEntries } = partitionWorldEntries(query, favorites, filtered, locale); + + const handleCopyMeetingSummary = async () => { + const entries = buildSummaryEntries(reference, favorites, filtered, locale); + if (entries.length === 0) { + await showToast(Toast.Style.Failure, t("wcSummaryEmptyToast")); + return; + } + const summaryText = formatMeetingSummary(new Date(fixed ?? Date.now()), entries, reference, locale); + await Clipboard.copy(summaryText); + await showToast(Toast.Style.Success, t("wcCopiedSummaryToast", { count: entries.length })); + }; + + const handleSwitchToTimestamp = () => { + if (props?.onSwitchToTimestamp) { + props.onSwitchToTimestamp(); + return; + } + pop(); + }; + + const sharedActions = [ + Action({ + title: t("wcCopySummaryAction"), + icon: Icon.CopyClipboard, + shortcut: { modifiers: ["ctrl", "shift"], key: "c" }, + onAction: handleCopyMeetingSummary + }), + Action({ title: t("wcStepForward1h"), icon: Icon.Plus, onAction: () => stepReferenceHours(1) }), + Action({ title: t("wcStepBackward1h"), icon: Icon.Minus, onAction: () => stepReferenceHours(-1) }), + Action({ + title: t("wcConvertAction"), + icon: Icon.Calendar, + onAction: () => + push(() => ReferenceTimeForm({ referenceZone: reference, onSave: value => setFixed(value.getTime()) })) + }), + Action({ + title: t("wcResetAction"), + icon: Icon.Repeat, + onAction: () => { + setFixed(null); + setNow(Date.now()); + } + }) ]; + const referenceOptions = cityNames[reference] ? Object.keys(cityNames) : [...Object.keys(cityNames), reference]; - const filtered = searchWorldZones(query, zones, locale); - const refLabel = resolveZoneLabel(reference, locale); + const refTimeShort = worldTime(date, reference).time.slice(0, 16); + const itemCtx: RenderZoneItemContext = { + date, + fixed, + reference, + baseline, + favorites, + favoriteSet, + sharedActions, + onToggleFavorite: toggleFavorite, + onMoveFavoriteTop: moveFavoriteToTop, + onSetReference: setReference + }; - return List({ - navigationTitle: t("wcNavTitle"), - searchText: query, - onSearchTextChange: setQuery, - searchBarPlaceholder: t("wcSearchPlaceholder"), - searchBarAccessory: List.Dropdown( - { tooltip: t("wcRefTooltip"), value: reference, onChange: value => { if (zones.includes(value)) setReference(value); } }, - referenceOptions.map(zone => List.Dropdown.Item({ value: zone, title: resolveZoneLabel(zone, locale) })) - ), - actions: ActionPanel({}, actions) - }, [ - List.Section( - { title: fixed === null ? t("wcSectionLive", { ref: refLabel }) : t("wcSectionFixed", { ref: refLabel }) }, - filtered.map(({ zone, title }) => { - const value = worldTime(date, zone); - const dayLabel = formatDayDiffLabel(getDayDiff(date, zone, reference)); - return List.Item({ - id: zone, - title, - subtitle: `${value.time} · UTC${zoneLabel(value.offsetMinutes)}`, - icon: Icon.Clock, - accessories: [ - ...(dayLabel ? [{ text: dayLabel }] : []), - { text: t("wcOffsetAcc", { offset: zoneLabel(value.offsetMinutes - baseline) }) } - ], - actions: ActionPanel({}, [ - Action({ - title: t("wcCopyLocal"), - icon: Icon.CopyClipboard, - onAction: async () => { - const current = worldTime(new Date(fixed ?? Date.now()), zone); - await Clipboard.copy(`${current.time} UTC${zoneLabel(current.offsetMinutes, true)} (${zone})`); - await showToast(Toast.Style.Success, t("wcCopiedLocalToast")); - } - }), - ...(zone === reference ? [] : [Action({ title: t("wcSetRef"), icon: Icon.Pin, onAction: () => setReference(zone) })]), - ...actions - ]) - }); - }) - ) - ]); + const sections = [ + ...(favoriteEntries.length > 0 + ? [ + List.Section( + { title: t("wcSectionFavorites", { count: favoriteEntries.length }) }, + favoriteEntries.map(entry => renderWorldZoneItem(entry, itemCtx)) + ) + ] + : []), + ...(remainingEntries.length > 0 + ? [ + List.Section( + { + title: + favoriteEntries.length > 0 + ? t("wcSectionMore", { ref: refLabel }) + : fixed === null + ? t("wcSectionLive", { ref: refLabel }) + : t("wcSectionFixed", { ref: refLabel }) + }, + remainingEntries.map(entry => renderWorldZoneItem(entry, itemCtx)) + ) + ] + : []), + ...(favoriteEntries.length === 0 && remainingEntries.length === 0 + ? [List.EmptyView({ title: t("wcEmptyTitle"), description: t("wcEmptyDesc"), icon: Icon.Globe })] + : []) + ]; + + return List( + { + navigationTitle: t("wcNavTitle"), + searchText: query, + onSearchTextChange: setQuery, + searchBarPlaceholder: t("wcSearchPlaceholder"), + filterBar: { + summaryText: + fixed === null + ? t("wcSummaryLive", { ref: refLabel, count: favorites.length }) + : t("wcSummaryFixed", { time: refTimeShort, ref: refLabel, count: favorites.length }), + actions: [ + { + id: "copy-meeting-summary", + label: t("wcCopySummaryBtn"), + title: t("wcCopySummaryAction"), + icon: Icon.CopyClipboard, + style: "primary", + onAction: () => { + void handleCopyMeetingSummary(); + } + }, + { + id: "switch-timestamp", + label: t("wcSwitchTimestampBtn"), + title: t("wcSwitchTimestampBtn"), + icon: Icon.Clock, + style: "secondary", + onAction: handleSwitchToTimestamp + } + ] + }, + searchBarAccessory: List.Dropdown( + { + tooltip: t("wcRefTooltip"), + value: reference, + onChange: value => { + if (zones.includes(value)) setReference(value); + } + }, + referenceOptions.map(zone => List.Dropdown.Item({ value: zone, title: resolveZoneLabel(zone, locale) })) + ), + actions: ActionPanel({}, sharedActions) + }, + sections + ); } diff --git a/extensions/timestamp/tests/i18n.test.mjs b/extensions/timestamp/tests/i18n.test.mjs index 47659201..77b871b8 100644 --- a/extensions/timestamp/tests/i18n.test.mjs +++ b/extensions/timestamp/tests/i18n.test.mjs @@ -59,14 +59,14 @@ test('i18n 运行时热切换: zh-CN -> en-US -> zh-CN 实时更新时间戳与 setRuntimeLocale('en-US') await tick() assert.equal(view.tree().props.navigationTitle, 'Timestamp Converter') - assert.match(String(view.tree().props.searchBarPlaceholder), /Enter 10\/13-digit timestamp/) + assert.match(String(view.tree().props.searchBarPlaceholder), /Enter 10\/13\/16\/19-digit timestamp/) assert.ok(!/[\u4e00-\u9fa5]/.test(view.text()), `en-US 时间戳视图不应包含中文: ${view.text()}`) // 热切换回 zh-CN setRuntimeLocale('zh-CN') await tick() assert.equal(view.tree().props.navigationTitle, '时间戳转换助手') - assert.match(String(view.tree().props.searchBarPlaceholder), /输入10\/13位时间戳/) + assert.match(String(view.tree().props.searchBarPlaceholder), /输入10\/13\/16\/19位时间戳/) } finally { view.unmount() } diff --git a/extensions/timestamp/tests/premium-refactor.test.mjs b/extensions/timestamp/tests/premium-refactor.test.mjs new file mode 100644 index 00000000..6c26f92f --- /dev/null +++ b/extensions/timestamp/tests/premium-refactor.test.mjs @@ -0,0 +1,302 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import { setRuntimeLocale } from '@ztools/declarative-ui' +import { createHost, mount, mountPushed, tick } from '../../shared/test-harness.mjs' +import TimestampCommand, { + tzWorld, + getTimePeriod, + isDaylightSavingTime, + parseZonedDateTime, + parseWorldReferenceInput, + formatMeetingSummary, + FAVORITES_STORAGE_KEY +} from '../dist/index.js' +import { parseTimeInput, formatCompactDateTime } from '../dist/logic.js' + +const host = createHost() + +test.beforeEach(() => { + host.reset() + host.toasts.length = 0 + setRuntimeLocale('zh-CN') +}) + +test('16 位微秒与 19 位纳秒时间戳自动识别并保持 BigInt 零精度丢失', async () => { + const us = parseTimeInput('1700000000123456') + assert.equal(us.valid, true) + assert.equal(us.detectedPrecision, 'microseconds') + assert.equal(us.unixSeconds, 1700000000) + assert.equal(us.unixMilliseconds, 1700000000123) + assert.equal(us.unixMicroseconds, '1700000000123456') + assert.equal(us.unixNanoseconds, '1700000000123456000') + assert.equal(us.utcIso, '2023-11-14T22:13:20.123Z') + + const ns = parseTimeInput('1700000000123456789') + assert.equal(ns.valid, true) + assert.equal(ns.detectedPrecision, 'nanoseconds') + assert.equal(ns.unixSeconds, 1700000000) + assert.equal(ns.unixMilliseconds, 1700000000123) + assert.equal(ns.unixMicroseconds, '1700000000123456') + assert.equal(ns.unixNanoseconds, '1700000000123456789') + + // 17 位与 20 位超长数字应拒绝 + assert.equal(parseTimeInput('17000000000000000').valid, false) + assert.equal(parseTimeInput('17000000000000000000').valid, false) + + // UI 复制微秒与纳秒精确值 + const view = await mount(TimestampCommand) + try { + await view.search('1700000000123456789') + assert.equal(view.item('item-us').props.title, '1700000000123456') + assert.equal(view.item('item-ns').props.title, '1700000000123456789') + await view.run(view.item('item-ns'), '复制纳秒级时间戳') + assert.equal(host.clipboard.text, '1700000000123456789') + await view.run(view.item('item-us'), '复制微秒级时间戳') + assert.equal(host.clipboard.text, '1700000000123456') + } finally { + view.unmount() + } +}) + +test('日期加减偏移算式解析:支持 now +/-、简写 +/-、基准时间 +/- 与月末安全夹紧', () => { + const ref = new Date('2026-06-15T10:00:00.000Z') + + const plus7d = parseTimeInput('now + 7d', ref) + assert.equal(plus7d.valid, true) + assert.equal(plus7d.detectedPrecision, 'expression') + assert.equal(plus7d.utcIso, '2026-06-22T10:00:00.000Z') + + const minus3h = parseTimeInput('now - 3h', ref) + assert.equal(minus3h.valid, true) + assert.equal(minus3h.utcIso, '2026-06-15T07:00:00.000Z') + + const shorthand = parseTimeInput('+45m', ref) + assert.equal(shorthand.valid, true) + assert.equal(shorthand.utcIso, '2026-06-15T10:45:00.000Z') + + const chained = parseTimeInput('now + 1d - 2h + 30m', ref) + assert.equal(chained.valid, true) + assert.equal(chained.utcIso, '2026-06-16T08:30:00.000Z') + + const fromUnix = parseTimeInput('1700000000 + 30m', ref) + assert.equal(fromUnix.valid, true) + assert.equal(fromUnix.unixSeconds, 1700001800) + + const fromIso = parseTimeInput('2026-06-01T00:00:00Z + 2w', ref) + assert.equal(fromIso.valid, true) + assert.equal(fromIso.utcIso, '2026-06-15T00:00:00.000Z') + + // 月末夹紧:2026-01-31 + 1mo -> 2026-02-28,不溢出到 3 月 + const monthClamp = parseTimeInput('2026-01-31 08:00:00 + 1mo', ref) + assert.equal(monthClamp.valid, true) + assert.equal(monthClamp.localDateTime, '2026-02-28 08:00:00') + + // 紧凑文件名时间戳输出 + assert.equal(monthClamp.compactDateTime, formatCompactDateTime(monthClamp.date)) + assert.equal(monthClamp.compactDateTime, '20260228_080000') + + // 非法算式拒绝 + for (const bad of ['now +', 'now + 5x', '+7', 'abc + 1d']) { + assert.equal(parseTimeInput(bad, ref).valid, false, bad) + } +}) + +test('昼夜/工作时段识别与南北半球夏令时 (DST) 精准检测', () => { + assert.equal(getTimePeriod(9), 'work') + assert.equal(getTimePeriod(17), 'work') + assert.equal(getTimePeriod(8), 'day') + assert.equal(getTimePeriod(18), 'day') + assert.equal(getTimePeriod(21), 'day') + assert.equal(getTimePeriod(22), 'night') + assert.equal(getTimePeriod(0), 'night') + assert.equal(getTimePeriod(5), 'night') + + // 北半球(纽约、伦敦):7 月 DST,1 月非 DST + assert.equal(isDaylightSavingTime(new Date('2026-07-01T12:00:00Z'), 'America/New_York'), true) + assert.equal(isDaylightSavingTime(new Date('2026-01-15T12:00:00Z'), 'America/New_York'), false) + assert.equal(isDaylightSavingTime(new Date('2026-07-01T12:00:00Z'), 'Europe/London'), true) + assert.equal(isDaylightSavingTime(new Date('2026-01-15T12:00:00Z'), 'Europe/London'), false) + + // 南半球(悉尼):1 月 DST,7 月非 DST + assert.equal(isDaylightSavingTime(new Date('2026-01-15T12:00:00Z'), 'Australia/Sydney'), true) + assert.equal(isDaylightSavingTime(new Date('2026-07-01T12:00:00Z'), 'Australia/Sydney'), false) + + // 无夏令时地区:恒为 false + assert.equal(isDaylightSavingTime(new Date('2026-07-01T12:00:00Z'), 'Asia/Shanghai'), false) + assert.equal(isDaylightSavingTime(new Date('2026-07-01T12:00:00Z'), 'Asia/Tokyo'), false) + assert.equal(isDaylightSavingTime(new Date('2026-07-01T12:00:00Z'), 'UTC'), false) +}) + +test('夏令时边界校验:拦截春季跳过无效时段,秋季回拨确定性取较早时刻', async () => { + // 2026-03-08 02:30 在 America/New_York 被夏令时跳过(01:59 -> 03:00) + assert.equal(parseZonedDateTime('2026-03-08T02:30:00', 'America/New_York'), null) + + const gapResult = parseWorldReferenceInput('2026-03-08 02:30', 'America/New_York') + assert.equal(gapResult.ok, false) + assert.match(gapResult.error, /夏令时/) + + // 2026-11-01 01:30 在 America/New_York 出现两次,取较早一次 (EDT UTC-4 -> 05:30Z) + const fallbackDate = parseZonedDateTime('2026-11-01T01:30:00', 'America/New_York') + assert.ok(fallbackDate) + assert.equal(fallbackDate.toISOString(), '2026-11-01T05:30:00.000Z') + + // 表单实测拦截 DST 无效时间 + const view = await mount(tzWorld) + try { + await view.dropdown('America/New_York') + await view.run(null, '换算指定时间…') + const form = await mountPushed(host) + try { + await form.fill('time', '2026-03-08 02:30') + await form.run(null, '换算时间') + assert.ok(form.field('time').props.error, 'DST 跳过时段应拦截报错') + assert.equal(host.pushed.length, 1, '校验失败不应关闭表单') + } finally { + form.unmount() + } + } finally { + view.unmount() + } +}) + +test('世界时钟收藏置顶持久化至 LocalStorage,重开保持顺序且零假收藏', async () => { + // 首次打开:无收藏时不渲染「已收藏城市」分组 + const view1 = await mount(tzWorld) + try { + await tick() + assert.doesNotMatch(view1.text(), /已收藏城市/) + + // 收藏纽约与伦敦 + await view1.run(view1.item('America/New_York'), '收藏并置顶城市') + await view1.run(view1.item('Europe/London'), '收藏并置顶城市') + assert.match(view1.text(), /已收藏城市 \(2\)/) + + // 校验已写入 LocalStorage + assert.ok(host.storage.has(FAVORITES_STORAGE_KEY)) + assert.deepEqual(JSON.parse(JSON.parse(host.storage.get(FAVORITES_STORAGE_KEY))), [ + 'America/New_York', + 'Europe/London' + ]) + + // 伦敦移至收藏首位 + await view1.run(view1.item('Europe/London'), '移到收藏首位') + assert.deepEqual(JSON.parse(JSON.parse(host.storage.get(FAVORITES_STORAGE_KEY))), [ + 'Europe/London', + 'America/New_York' + ]) + } finally { + view1.unmount() + } + + // 重新挂载后自动恢复收藏顺序且不重复展示同一时区 + const view2 = await mount(tzWorld) + try { + await tick() + assert.match(view2.text(), /已收藏城市 \(2\)/) + const ids = view2.items().map((item) => item.props.id) + assert.equal(ids[0], 'Europe/London') + assert.equal(ids[1], 'America/New_York') + assert.equal(new Set(ids).size, ids.length, '收藏城市不应在底部列表中重复出现') + + // 取消收藏 + await view2.run(view2.item('Europe/London'), '取消收藏') + assert.match(view2.text(), /已收藏城市 \(1\)/) + } finally { + view2.unmount() + } +}) + +test('[异常] LocalStorage 读写故障时如实提示错误并回滚收藏状态', async () => { + host.faults.storageWrite = new Error('disk full') + const view = await mount(tzWorld) + try { + await tick() + await view.run(view.item('America/New_York'), '收藏并置顶城市') + assert.doesNotMatch(view.text(), /已收藏城市/, '写入失败后必须回滚状态') + assert.equal(host.lastToast().style, 'FAILURE') + } finally { + host.faults.storageWrite = null + view.unmount() + } +}) + +test('世界时钟顶栏一键复制多时区会议汇总、+1h/-1h 步进与顶栏双向视图切换', async () => { + // 先预置收藏:上海、伦敦、旧金山 + host.storage.set( + FAVORITES_STORAGE_KEY, + JSON.stringify(JSON.stringify(['Europe/London', 'America/Los_Angeles'])) + ) + + const fixedDate = new Date('2026-06-15T09:00:00.000Z') + const summaryZh = formatMeetingSummary( + fixedDate, + [ + { zone: 'Asia/Shanghai', title: '北京 / 上海' }, + { zone: 'Europe/London', title: '伦敦' }, + { zone: 'America/Los_Angeles', title: '旧金山' } + ], + 'Asia/Shanghai', + 'zh-CN' + ) + assert.match(summaryZh, /多时区会议时间对照(基准:北京 \/ 上海)/) + assert.match(summaryZh, /UTC\+08:00 · 办公时段/) + assert.match(summaryZh, /UTC\+01:00 DST · 办公时段/) + assert.match(summaryZh, /UTC-07:00 DST · 夜间/) + + setRuntimeLocale('en-US') + const summaryEn = formatMeetingSummary( + fixedDate, + [ + { zone: 'Asia/Shanghai', title: 'Beijing / Shanghai' }, + { zone: 'Europe/London', title: 'London' } + ], + 'Asia/Shanghai', + 'en-US' + ) + assert.match(summaryEn, /Meeting Time Across Timezones/) + assert.ok(!/[\u4e00-\u9fa5]/.test(summaryEn), 'en-US 会议汇总不应含中文') + setRuntimeLocale('zh-CN') + + // 顶栏按钮:时间戳转换 -> 切世界时钟 -> 复制会议汇总 -> 切回时间戳转换 + const tsView = await mount(TimestampCommand) + try { + const wcBtn = tsView.tree().props.filterBar.actions.find((a) => a.id === 'switch-world-clock') + assert.ok(wcBtn, '时间戳主视图顶栏应有「世界时钟」切换按钮') + wcBtn.onAction() + assert.equal(host.pushed.length, 1) + + const wcView = await mountPushed(host) + try { + await tick() + // 验证城市右侧展示时段标签与 DST 标签 + const london = wcView.item('Europe/London') + assert.ok( + london.props.accessories.some((acc) => ['办公时段', '白天', '夜间'].includes(acc.tag)), + `伦敦右侧应展示时段标签,实际: ${JSON.stringify(london.props.accessories)}` + ) + + // 点击顶栏「复制会议汇总」 + const copyBtn = wcView.tree().props.filterBar.actions.find((a) => a.id === 'copy-meeting-summary') + assert.ok(copyBtn, '世界时钟顶栏应有「复制会议汇总」按钮') + copyBtn.onAction() + await tick() + assert.match(host.clipboard.text, /多时区会议时间对照/) + assert.match(host.clipboard.text, /Europe\/London/) + assert.match(host.clipboard.text, /America\/Los_Angeles/) + + // +1h 步进切换到换算时刻模式 + await wcView.run(null, '基准时间 +1 小时') + assert.match(wcView.tree().props.filterBar.summaryText, /换算时刻/) + + // 点击顶栏「时间戳转换」返回主视图 + const backBtn = wcView.tree().props.filterBar.actions.find((a) => a.id === 'switch-timestamp') + assert.ok(backBtn, '世界时钟顶栏应有「时间戳转换」切换按钮') + backBtn.onAction() + assert.equal(host.pushed.length, 0) + } finally { + wcView.unmount() + } + } finally { + tsView.unmount() + } +}) diff --git a/extensions/todo/package.json b/extensions/todo/package.json index c7f30f4b..96db69eb 100644 --- a/extensions/todo/package.json +++ b/extensions/todo/package.json @@ -1,6 +1,6 @@ { "name": "todo", - "version": "1.0.3", + "version": "1.0.11", "description": "极速记录个人待办、状态过滤、优先级标记与 LocalStorage 本地持久化", "type": "module", "main": "dist/index.js", diff --git a/extensions/todo/plugin.json b/extensions/todo/plugin.json index 36684c66..75a55263 100644 --- a/extensions/todo/plugin.json +++ b/extensions/todo/plugin.json @@ -1,7 +1,7 @@ { "id": "todo", "name": "待办清单", - "version": "1.0.10", + "version": "1.0.11", "minAppVersion": "1.1.8.0", "description": "极简任务待办清单,回车快速添加任务,支持高优标记与完成状态筛选", "author": "ZTools Team", diff --git a/extensions/todo/src/i18n.ts b/extensions/todo/src/i18n.ts index e7d76199..414715cc 100644 --- a/extensions/todo/src/i18n.ts +++ b/extensions/todo/src/i18n.ts @@ -19,6 +19,12 @@ export const t = createTranslator( priorityHigh: "高优先级", priorityMedium: "中优先级", priorityLow: "低优先级", + tagsField: "标签(空格或逗号分隔)", + tagsPlaceholder: "例如:工作, 发版", + dueDateField: "截止日期(YYYY-MM-DD)", + dueDatePlaceholder: "留空表示无截止日,例如 2026-12-31", + dueDateInvalidError: "截止日期格式应为 YYYY-MM-DD(有效日期)", + dueDateInvalidToast: "截止日期格式无效", readFailed: "读取待办失败", cannotEditTitle: "暂不能修改待办", cannotEditDesc: "请先成功读取已有数据", @@ -51,18 +57,29 @@ export const t = createTranslator( reloadTodos: "重新读取待办", backupAndRestart: "备份原数据并重新开始", newTodo: "新建待办事项", + exportMarkdown: "导出为 Markdown 清单", + exportMarkdownEmpty: "当前列表没有可导出的待办", + exportMarkdownSuccess: "已复制 {count} 条待办为 Markdown 清单", + exportMarkdownFailed: "导出 Markdown 失败", clearCompleted: "清空已完成待办", navTitle: "极简待办清单", - searchPlaceholder: "搜索待办事项,或按回车快速添加...", + searchPlaceholder: "搜索或回车快录(支持 !! 高优 / #标签 / @today)...", filterTooltip: "筛选待办状态", filterAll: "全部待办", + filterToday: "今日待办", filterActive: "进行中", filterCompleted: "已完成", sectionAll: "全部待办 ({count})", + sectionToday: "今日待办 ({count})", sectionActive: "进行中 ({count})", sectionCompleted: "已完成 ({count})", + summaryBar: "待办 {active} · 今日 {today} · 已完成 {completed}", quickAddTitle: "添加待办「{title}」", quickAddSubtitle: "按回车直接添加(中优先级)", + quickAddSugarSubtitle: "按回车直接添加:{details}", + dueTodayTag: "今日截止", + dueOverdueTag: "已逾期", + dueDateTag: "截止 {date}", actionsTitle: "操作", quickAddAction: "添加待办", addWithDetailsAction: "填写详情后添加…", @@ -102,6 +119,12 @@ export const t = createTranslator( priorityHigh: "High Priority", priorityMedium: "Medium Priority", priorityLow: "Low Priority", + tagsField: "Tags (space or comma separated)", + tagsPlaceholder: "e.g. work, release", + dueDateField: "Due Date (YYYY-MM-DD)", + dueDatePlaceholder: "Optional, e.g. 2026-12-31", + dueDateInvalidError: "Due date must be a valid YYYY-MM-DD date", + dueDateInvalidToast: "Invalid due date format", readFailed: "Failed to load tasks", cannotEditTitle: "Cannot modify tasks right now", cannotEditDesc: "Please load existing data first", @@ -134,18 +157,29 @@ export const t = createTranslator( reloadTodos: "Reload Tasks", backupAndRestart: "Back Up Data & Reset", newTodo: "New To-Do", + exportMarkdown: "Export as Markdown Checklist", + exportMarkdownEmpty: "No tasks to export in current view", + exportMarkdownSuccess: "Copied {count} task(s) as Markdown checklist", + exportMarkdownFailed: "Failed to export Markdown", clearCompleted: "Clear Completed Tasks", navTitle: "To-Do List", - searchPlaceholder: "Search tasks or press Enter to quick-add...", + searchPlaceholder: "Search or quick-add (supports !! high / #tag / @today)...", filterTooltip: "Filter by status", filterAll: "All Tasks", + filterToday: "Due Today", filterActive: "Active", filterCompleted: "Completed", sectionAll: "All Tasks ({count})", + sectionToday: "Due Today ({count})", sectionActive: "Active ({count})", sectionCompleted: "Completed ({count})", + summaryBar: "Active {active} · Today {today} · Done {completed}", quickAddTitle: "Add Task \"{title}\"", quickAddSubtitle: "Press Enter to add immediately (Medium priority)", + quickAddSugarSubtitle: "Press Enter to add: {details}", + dueTodayTag: "Due Today", + dueOverdueTag: "Overdue", + dueDateTag: "Due {date}", actionsTitle: "Actions", quickAddAction: "Add Task", addWithDetailsAction: "Add with Details…", diff --git a/extensions/todo/src/index.ts b/extensions/todo/src/index.ts index 9d13587b..360a2967 100644 --- a/extensions/todo/src/index.ts +++ b/extensions/todo/src/index.ts @@ -25,13 +25,20 @@ import { filterAndSearchTodos, readStoredTodos, formatListDate, + formatLocalDateKey, + isValidDateKey, + isTodoDueTodayOrOverdue, + parseQuickAddInput, + normalizeTags, + exportTodosToMarkdown, CorruptTodosError, isBlankQuery, quickAddTitle, TODOS_STORAGE_KEY, type TodoItem, type TodoPriority, - type TodoFilter + type TodoFilter, + type ParsedQuickAdd } from "./logic.js"; import { updateStorageItem, hostUpgradeError } from "./host-compat.js"; @@ -39,21 +46,53 @@ function errorMessage(err: unknown): string { return err instanceof Error && err.message ? err.message : String(err); } -/** - * 新建待办事项 Form 表单 - */ -export function CreateTodoForm({ onCreated, initialTitle = "" }: { onCreated: (item: TodoItem) => Promise; initialTitle?: string }) { +function parseTagsText(raw: string): string[] { + return normalizeTags((raw || "").split(/[\s,,]+/).filter(Boolean)); +} + +function formatPriorityLabel(priority: TodoPriority): string { + return priority === "high" ? t("priorityHigh") : priority === "low" ? t("priorityLow") : t("priorityMedium"); +} + +function formatQuickAddSubtitle(parsed: ParsedQuickAdd): string { + if (!parsed.hasSyntaxSugar) return t("quickAddSubtitle"); + const parts: string[] = [formatPriorityLabel(parsed.priority)]; + if (parsed.tags.length > 0) { + parts.push(parsed.tags.map((tag) => `#${tag}`).join(" ")); + } + if (parsed.dueDate) { + const todayKey = formatLocalDateKey(); + parts.push(parsed.dueDate === todayKey ? t("dueTodayTag") : t("dueDateTag", { date: parsed.dueDate })); + } + return t("quickAddSugarSubtitle", { details: parts.join(" · ") }); +} + +function TodoFormEditor(options: { + navigationTitle: string; + initialTitle: string; + initialPriority: TodoPriority; + initialTags: string[]; + initialDueDate: string; + successToastKey: "createSuccess" | "editSuccess"; + failedToastKey: "createFailed" | "editFailed"; + onSave: (payload: { title: string; priority: TodoPriority; tags: string[]; dueDate: string }) => Promise; +}) { useLocale(); const { pop } = useNavigation(); - const [title, setTitle] = useState(initialTitle); - const [priority, setPriority] = useState("medium"); + const [title, setTitle] = useState(options.initialTitle); + const [priority, setPriority] = useState(options.initialPriority); + const [tagsText, setTagsText] = useState(options.initialTags.join(" ")); + const [dueDate, setDueDate] = useState(options.initialDueDate); const [error, setError] = useState(undefined); - // 保存进行中再按 ⌘↵ 不会重复创建 + const [dueDateError, setDueDateError] = useState(undefined); + // 保存进行中再按 ⌘↵ 不会重复提交 const submitting = useRef(false); const handleSubmit = async (values: Record) => { const todoTitle = typeof values.title === "string" && values.title ? values.title : title; const todoPriority = (typeof values.priority === "string" && values.priority ? values.priority : priority) as TodoPriority; + const todoTagsRaw = typeof values.tags === "string" ? values.tags : tagsText; + const todoDueRaw = (typeof values.dueDate === "string" ? values.dueDate : dueDate).trim(); if (!todoTitle || !todoTitle.trim()) { setError(t("titleEmptyError")); @@ -61,45 +100,33 @@ export function CreateTodoForm({ onCreated, initialTitle = "" }: { onCreated: (i return; } + if (todoDueRaw && !isValidDateKey(todoDueRaw)) { + setDueDateError(t("dueDateInvalidError")); + await showToast(Toast.Style.Failure, t("dueDateInvalidToast"), t("dueDateInvalidError")); + return; + } + if (submitting.current) return; submitting.current = true; try { - const newTodo = createTodo(todoTitle, todoPriority); - if (!(await onCreated(newTodo))) return; - await showToast(Toast.Style.Success, t("createSuccess")); + const ok = await options.onSave({ + title: todoTitle.trim(), + priority: todoPriority, + tags: parseTagsText(todoTagsRaw), + dueDate: todoDueRaw + }); + if (!ok) return; + await showToast(Toast.Style.Success, t(options.successToastKey)); pop(); } catch (err: unknown) { const message = errorMessage(err); setError(message); - await showToast(Toast.Style.Failure, t("createFailed"), message); + await showToast(Toast.Style.Failure, t(options.failedToastKey), message); } finally { submitting.current = false; } }; - return renderTodoFormView({ - navigationTitle: t("formNavTitle"), - title, - priority, - error, - onTitleChange: (val) => { - setTitle(val); - if (error) setError(undefined); - }, - onPriorityChange: setPriority, - onSubmit: handleSubmit - }); -} - -function renderTodoFormView(options: { - navigationTitle: string; - title: string; - priority: TodoPriority; - error: string | undefined; - onTitleChange: (val: string) => void; - onPriorityChange: (val: TodoPriority) => void; - onSubmit: (values: Record) => Promise; -}) { return Form( { navigationTitle: options.navigationTitle, @@ -108,7 +135,7 @@ function renderTodoFormView(options: { Action.SubmitForm({ title: t("saveTodo"), icon: Icon.Check, - onSubmit: options.onSubmit + onSubmit: handleSubmit }) ]) }, @@ -117,28 +144,83 @@ function renderTodoFormView(options: { id: "title", title: t("titleField"), placeholder: t("titlePlaceholder"), - value: options.title, - error: options.error, + value: title, + error, autoFocus: true, - onChange: options.onTitleChange + onChange: (val) => { + setTitle(val); + if (error) setError(undefined); + } }), Form.Dropdown( { id: "priority", title: t("priorityField"), - value: options.priority, - onChange: (val) => options.onPriorityChange(val as TodoPriority) + value: priority, + onChange: (val) => setPriority(val as TodoPriority) }, [ Form.Dropdown.Item({ title: t("priorityHigh"), value: "high" }), Form.Dropdown.Item({ title: t("priorityMedium"), value: "medium" }), Form.Dropdown.Item({ title: t("priorityLow"), value: "low" }) ] - ) + ), + Form.TextField({ + id: "tags", + title: t("tagsField"), + placeholder: t("tagsPlaceholder"), + value: tagsText, + onChange: setTagsText + }), + Form.TextField({ + id: "dueDate", + title: t("dueDateField"), + placeholder: t("dueDatePlaceholder"), + value: dueDate, + error: dueDateError, + onChange: (val) => { + setDueDate(val); + if (dueDateError) setDueDateError(undefined); + } + }) ] ); } +/** + * 新建待办事项 Form 表单 + */ +export function CreateTodoForm({ + onCreated, + initialTitle = "", + initialPriority = "medium", + initialTags = [], + initialDueDate = "" +}: { + onCreated: (item: TodoItem) => Promise; + initialTitle?: string; + initialPriority?: TodoPriority; + initialTags?: string[]; + initialDueDate?: string; +}) { + return TodoFormEditor({ + navigationTitle: t("formNavTitle"), + initialTitle, + initialPriority, + initialTags, + initialDueDate, + successToastKey: "createSuccess", + failedToastKey: "createFailed", + onSave: async ({ title, priority, tags, dueDate }) => { + const newTodo = createTodo(title, priority, { + tags, + dueDate: dueDate || undefined + }); + return onCreated(newTodo); + } + }); +} + /** * 编辑已有待办事项 Form 表单(保留原完成状态与创建时间) */ @@ -147,51 +229,17 @@ export function EditTodoForm({ onSaved }: { todo: TodoItem; - onSaved: (updates: { title: string; priority: TodoPriority }) => Promise; + onSaved: (updates: { title: string; priority: TodoPriority; tags?: string[]; dueDate?: string }) => Promise; }) { - useLocale(); - const { pop } = useNavigation(); - const [title, setTitle] = useState(todo.title); - const [priority, setPriority] = useState(todo.priority); - const [error, setError] = useState(undefined); - const submitting = useRef(false); - - const handleSubmit = async (values: Record) => { - const todoTitle = typeof values.title === "string" && values.title ? values.title : title; - const todoPriority = (typeof values.priority === "string" && values.priority ? values.priority : priority) as TodoPriority; - - if (!todoTitle || !todoTitle.trim()) { - setError(t("titleEmptyError")); - await showToast(Toast.Style.Failure, t("titleEmptyToast")); - return; - } - - if (submitting.current) return; - submitting.current = true; - try { - if (!(await onSaved({ title: todoTitle.trim(), priority: todoPriority }))) return; - await showToast(Toast.Style.Success, t("editSuccess")); - pop(); - } catch (err: unknown) { - const message = errorMessage(err); - setError(message); - await showToast(Toast.Style.Failure, t("editFailed"), message); - } finally { - submitting.current = false; - } - }; - - return renderTodoFormView({ + return TodoFormEditor({ navigationTitle: t("formEditNavTitle"), - title, - priority, - error, - onTitleChange: (val) => { - setTitle(val); - if (error) setError(undefined); - }, - onPriorityChange: setPriority, - onSubmit: handleSubmit + initialTitle: todo.title, + initialPriority: todo.priority, + initialTags: todo.tags || [], + initialDueDate: todo.dueDate || "", + successToastKey: "editSuccess", + failedToastKey: "editFailed", + onSave: onSaved }); } @@ -325,11 +373,14 @@ export default function TodoCommand() { } }; - const handleQuickAdd = async (title: string) => { + const handleQuickAdd = async (parsed: ParsedQuickAdd) => { if (adding.current) return; adding.current = true; try { - const item = createTodo(title, "medium"); + const item = createTodo(parsed.title, parsed.priority, { + tags: parsed.tags, + dueDate: parsed.dueDate + }); if (await commit(current => [item, ...current])) { setSearchText(""); if (filter === "completed") setFilter("all"); @@ -342,14 +393,33 @@ export default function TodoCommand() { } }; - const handleOpenCreateForm = (initialTitle = "") => { + const handleExportMarkdown = async () => { + const target = filtered.length > 0 ? filtered : todos; + if (target.length === 0) { + await showToast(Toast.Style.Failure, t("exportMarkdownEmpty")); + return; + } + try { + const markdown = exportTodosToMarkdown(target); + await Clipboard.copy(markdown); + await showToast(Toast.Style.Success, t("exportMarkdownSuccess", { count: target.length })); + } catch (err: unknown) { + await showToast(Toast.Style.Failure, t("exportMarkdownFailed"), errorMessage(err)); + } + }; + + const handleOpenCreateForm = (initialInput = "") => { if (!writable.current) { showToast(Toast.Style.Failure, t("cannotEditTitle"), t("cannotEditDesc")); return; } + const parsed = parseQuickAddInput(initialInput); push(() => CreateTodoForm({ - initialTitle, + initialTitle: parsed.hasSyntaxSugar ? parsed.title : initialInput.trim(), + initialPriority: parsed.hasSyntaxSugar ? parsed.priority : "medium", + initialTags: parsed.hasSyntaxSugar ? parsed.tags : [], + initialDueDate: parsed.hasSyntaxSugar ? (parsed.dueDate || "") : "", onCreated: async (newTodo) => { const ok = await commit(current => [newTodo, ...current]); if (ok && filter === "completed") setFilter("all"); @@ -415,6 +485,12 @@ export default function TodoCommand() { shortcut: { modifiers: ["ctrl"], key: "n" }, onAction: () => handleOpenCreateForm() }), + ...(todos.length > 0 && !loadError ? [Action({ + title: t("exportMarkdown"), + icon: Icon.Document, + shortcut: { modifiers: ["ctrl", "shift"], key: "m" }, + onAction: handleExportMarkdown + })] : []), // 没有已完成项时不提供「清空已完成」,避免空状态下次动作是无效操作 ...(todos.some((item) => item.completed) ? [Action({ title: t("clearCompleted"), @@ -426,6 +502,12 @@ export default function TodoCommand() { // 有输入且没有标题完全相同的待办时,「添加待办」始终排第一,回车即添加; // 部分匹配的已有待办排在后面,要操作它们用 ↓ 选中 const quickTitle = loaded && !loadError ? quickAddTitle(filtered, searchText) : null; + const parsedQuick = quickTitle ? parseQuickAddInput(searchText) : null; + + const todayKey = formatLocalDateKey(); + const activeCount = todos.filter((item) => !item.completed).length; + const todayCount = todos.filter((item) => !item.completed && Boolean(item.dueDate) && item.dueDate! <= todayKey).length; + const completedCount = todos.length - activeCount; const emptyTitle = loadError ? (loadError.corrupt ? t("emptyCorrupt") : t("emptyLoadErr")) : blankQuery ? t("emptyBlankQuery") @@ -436,6 +518,15 @@ export default function TodoCommand() { : t("emptyFilterNone"); const emptyDescription = loadError ? (loadError.corrupt ? t("emptyLoadErrCorruptSub", { message: loadError.message }) : t("emptyLoadErrSub", { message: loadError.message })) : blankQuery ? t("emptyBlankQuerySub") : !loaded ? "" : t("emptyHintSub"); + const sectionTitle = + filter === "all" + ? t("sectionAll", { count: filtered.length }) + : filter === "today" + ? t("sectionToday", { count: filtered.length }) + : filter === "active" + ? t("sectionActive", { count: filtered.length }) + : t("sectionCompleted", { count: filtered.length }); + return List( { // 读取完成前交给客户端显示加载状态,不提前下「还没有待办」的结论 @@ -446,6 +537,7 @@ export default function TodoCommand() { onSearchTextChange: (text: string) => setSearchText(text), ...(loadError ? {} : { filterBar: { + ...(todos.length > 0 ? { summaryText: t("summaryBar", { active: activeCount, today: todayCount, completed: completedCount }) } : {}), actions: [ { id: "new-todo", @@ -466,6 +558,7 @@ export default function TodoCommand() { }, [ List.Dropdown.Item({ title: t("filterAll"), value: "all" }), + List.Dropdown.Item({ title: t("filterToday"), value: "today" }), List.Dropdown.Item({ title: t("filterActive"), value: "active" }), List.Dropdown.Item({ title: t("filterCompleted"), value: "completed" }) ] @@ -476,30 +569,40 @@ export default function TodoCommand() { // 没有任何条目时不输出分组:否则空状态上方会多一个「全部待办 (0)」标题 ...(quickTitle || filtered.length > 0 ? [List.Section( { - title: filter === "all" ? t("sectionAll", { count: filtered.length }) : filter === "active" ? t("sectionActive", { count: filtered.length }) : t("sectionCompleted", { count: filtered.length }) + title: sectionTitle }, [ - ...(quickTitle + ...(quickTitle && parsedQuick ? [ List.Item({ id: "quick-add", title: t("quickAddTitle", { title: quickTitle }), - subtitle: t("quickAddSubtitle"), + subtitle: formatQuickAddSubtitle(parsedQuick), icon: Icon.Plus, actions: ActionPanel({ title: t("actionsTitle") }, [ - Action({ title: t("quickAddAction"), icon: Icon.Plus, onAction: () => handleQuickAdd(quickTitle) }), - Action({ title: t("addWithDetailsAction"), icon: Icon.Pencil, onAction: () => handleOpenCreateForm(quickTitle) }) + Action({ title: t("quickAddAction"), icon: Icon.Plus, onAction: () => handleQuickAdd(parsedQuick) }), + Action({ title: t("addWithDetailsAction"), icon: Icon.Pencil, onAction: () => handleOpenCreateForm(searchText) }) ]) }) ] : []), - ...filtered.map((item) => - List.Item({ + ...filtered.map((item) => { + const dueState = !item.completed ? isTodoDueTodayOrOverdue(item) : null; + const dueAccessory = item.dueDate + ? dueState === "overdue" + ? { tag: { value: t("dueOverdueTag"), color: Color.Red } } + : dueState === "today" + ? { tag: t("dueTodayTag") } + : { tag: item.dueDate } + : null; + return List.Item({ id: item.id, title: item.title, - subtitle: item.priority === "high" ? t("priorityHigh") : item.priority === "medium" ? t("priorityMedium") : t("priorityLow"), + subtitle: formatPriorityLabel(item.priority), icon: item.completed ? Icon.Check : Icon.Circle, accessories: [ + ...(item.tags && item.tags.length > 0 ? item.tags.map((tag) => ({ tag: `#${tag}` })) : []), + ...(dueAccessory ? [dueAccessory] : []), { text: item.completed ? t("statusCompleted") : t("statusPending") }, @@ -530,8 +633,8 @@ export default function TodoCommand() { onAction: () => handleDelete(item) }) ]) - }) - ) + }); + }) ] )] : []), // 没有可显示的待办时用空状态说明原因与下一步,不再塞一条可选中的占位行; diff --git a/extensions/todo/src/logic.ts b/extensions/todo/src/logic.ts index 5963ba10..93b88498 100644 --- a/extensions/todo/src/logic.ts +++ b/extensions/todo/src/logic.ts @@ -27,7 +27,7 @@ function todoLogicStrings() { } export type TodoPriority = "high" | "medium" | "low"; -export type TodoFilter = "all" | "active" | "completed"; +export type TodoFilter = "all" | "today" | "active" | "completed"; export interface TodoItem { id: string; @@ -36,9 +36,122 @@ export interface TodoItem { priority: TodoPriority; createdAt: number; completedAt?: number; + tags?: string[]; + dueDate?: string; } -export function createTodo(title: string, priority: TodoPriority = "medium"): TodoItem { +export interface ParsedQuickAdd { + title: string; + priority: TodoPriority; + tags: string[]; + dueDate?: string; + hasSyntaxSugar: boolean; +} + +export function formatLocalDateKey(timestamp: number = Date.now()): string { + const d = new Date(timestamp); + const year = d.getFullYear(); + const month = String(d.getMonth() + 1).padStart(2, "0"); + const day = String(d.getDate()).padStart(2, "0"); + return `${year}-${month}-${day}`; +} + +export function isValidDateKey(value: unknown): value is string { + if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return false; + const [y, m, d] = value.split("-").map(Number); + const date = new Date(y, m - 1, d); + return date.getFullYear() === y && date.getMonth() === m - 1 && date.getDate() === d; +} + +export function normalizeTags(tags: readonly string[] | undefined): string[] { + if (!Array.isArray(tags)) return []; + const seen = new Set(); + const out: string[] = []; + for (const raw of tags) { + if (typeof raw !== "string") continue; + const cleaned = raw.trim().replace(/^#+/, "").trim(); + if (!cleaned) continue; + const key = cleaned.toLowerCase(); + if (seen.has(key)) continue; + seen.add(key); + out.push(cleaned); + if (out.length >= 5) break; + } + return out; +} + +/** + * 解析搜索框快录语法糖: + * - `!!` 或 `!high` 设为高优先级,`!low` 设为低优先级 + * - `#标签` 提取标签(最多 5 个,去重) + * - `@today` / `@今天` / `@tomorrow` / `@明天` / `@YYYY-MM-DD` 设置截止日期 + */ +export function parseQuickAddInput(input: string, now: number = Date.now()): ParsedQuickAdd { + const raw = (input || "").trim(); + if (!raw) { + return { title: "", priority: "medium", tags: [], hasSyntaxSugar: false }; + } + + let priority: TodoPriority = "medium"; + const rawTags: string[] = []; + let dueDate: string | undefined; + let hasSyntaxSugar = false; + const titleParts: string[] = []; + + for (const token of raw.split(/\s+/)) { + const lower = token.toLowerCase(); + if (token === "!!" || lower === "!high") { + priority = "high"; + hasSyntaxSugar = true; + continue; + } + if (lower === "!low") { + priority = "low"; + hasSyntaxSugar = true; + continue; + } + if (token.startsWith("#") && token.length > 1) { + const tag = token.slice(1).replace(/^#+/, ""); + if (tag) { + rawTags.push(tag); + hasSyntaxSugar = true; + continue; + } + } + if (lower === "@today") { + dueDate = formatLocalDateKey(now); + hasSyntaxSugar = true; + continue; + } + if (lower === "@tomorrow") { + const tomorrow = new Date(now); + tomorrow.setDate(tomorrow.getDate() + 1); + dueDate = formatLocalDateKey(tomorrow.getTime()); + hasSyntaxSugar = true; + continue; + } + if (token.startsWith("@") && isValidDateKey(token.slice(1))) { + dueDate = token.slice(1); + hasSyntaxSugar = true; + continue; + } + titleParts.push(token); + } + + return { + title: titleParts.join(" ").trim(), + priority, + tags: normalizeTags(rawTags), + ...(dueDate ? { dueDate } : {}), + hasSyntaxSugar + }; +} + +export function createTodo( + title: string, + priority: TodoPriority = "medium", + extra?: { tags?: string[]; dueDate?: string } +): TodoItem { const s = todoLogicStrings(); const trimmed = (title || "").trim(); if (!trimmed) { @@ -47,12 +160,16 @@ export function createTodo(title: string, priority: TodoPriority = "medium"): To if (typeof globalThis.crypto?.randomUUID !== 'function') { throw new Error(s.uuidUnavailable) } + const tags = normalizeTags(extra?.tags); + const dueDate = isValidDateKey(extra?.dueDate) ? extra.dueDate : undefined; return { id: "todo_" + Date.now().toString(36) + "_" + globalThis.crypto.randomUUID(), title: trimmed, completed: false, priority, - createdAt: Date.now() + createdAt: Date.now(), + ...(tags.length > 0 ? { tags } : {}), + ...(dueDate ? { dueDate } : {}) }; } @@ -73,7 +190,7 @@ export function toggleTodoStatus(todos: TodoItem[], id: string): TodoItem[] { export function updateTodoItem( todos: TodoItem[], id: string, - updates: { title: string; priority: TodoPriority } + updates: { title: string; priority: TodoPriority; tags?: string[]; dueDate?: string } ): TodoItem[] { const s = todoLogicStrings(); const trimmed = (updates.title || "").trim(); @@ -84,11 +201,27 @@ export function updateTodoItem( updates.priority === "high" || updates.priority === "low" ? updates.priority : "medium"; return todos.map((item) => { if (item.id === id) { - return { + const nextTags = updates.tags !== undefined ? normalizeTags(updates.tags) : item.tags; + const nextDueDate = + updates.dueDate !== undefined + ? (isValidDateKey(updates.dueDate) ? updates.dueDate : undefined) + : item.dueDate; + const next: TodoItem = { ...item, title: trimmed, priority }; + if (nextTags && nextTags.length > 0) { + next.tags = nextTags; + } else { + delete next.tags; + } + if (nextDueDate) { + next.dueDate = nextDueDate; + } else { + delete next.dueDate; + } + return next; } return item; }); @@ -102,24 +235,43 @@ export function clearCompletedTodos(todos: TodoItem[]): TodoItem[] { return todos.filter((item) => !item.completed); } +export function isTodoDueTodayOrOverdue(item: TodoItem, now: number = Date.now()): "overdue" | "today" | null { + if (!item.dueDate || !isValidDateKey(item.dueDate)) return null; + const today = formatLocalDateKey(now); + if (item.dueDate < today) return "overdue"; + if (item.dueDate === today) return "today"; + return null; +} + export function filterAndSearchTodos( todos: TodoItem[], filter: TodoFilter = "all", - searchQuery = "" + searchQuery = "", + now: number = Date.now() ): TodoItem[] { let list = todos; + const todayKey = formatLocalDateKey(now); // 1. 状态过滤 if (filter === "active") { list = list.filter((item) => !item.completed); } else if (filter === "completed") { list = list.filter((item) => item.completed); + } else if (filter === "today") { + list = list.filter((item) => !item.completed && Boolean(item.dueDate) && item.dueDate! <= todayKey); } - // 2. 关键词检索 + // 2. 关键词检索(支持标题、#标签、@today 匹配) const q = (searchQuery || "").trim().toLowerCase(); if (q) { - list = list.filter((item) => item.title.toLowerCase().includes(q)); + const tagQuery = q.startsWith("#") ? q.slice(1) : q; + list = list.filter((item) => { + if (item.title.toLowerCase().includes(q)) return true; + if (item.tags?.some((tag) => tag.toLowerCase().includes(tagQuery) || `#${tag.toLowerCase()}` === q)) return true; + if (q === "@today" && item.dueDate === todayKey) return true; + if (item.dueDate && item.dueDate.includes(q.replace(/^@/, ""))) return true; + return false; + }); } // 3. 排序:有关键词时标题完全相同的排最前;其余未完成在前(高优先级排前),已完成在后 @@ -154,13 +306,33 @@ export function isBlankQuery(searchText: string): boolean { } /** - * 回车快速添加的标题:输入非空、且当前可见列表里没有标题完全相同(忽略大小写)的待办时返回去空格后的标题,否则返回 null。 + * 回车快速添加的标题:解析语法糖后标题非空、且当前可见列表里没有标题完全相同(忽略大小写)的待办时返回纯标题,否则返回 null。 * 只是部分匹配已有待办时照样可以添加,「添加待办」条目排在第一位,回车不会误改已有待办。 */ export function quickAddTitle(visible: TodoItem[], searchText: string): string | null { - const title = (searchText || "").trim(); - if (!title) return null; - return visible.some((item) => isSameTitle(item.title, title)) ? null : title; + const parsed = parseQuickAddInput(searchText); + if (!parsed.title) return null; + return visible.some((item) => isSameTitle(item.title, parsed.title)) ? null : parsed.title; +} + +/** + * 将待办列表导出为标准 Markdown Checklist,便于直接粘贴进日报/周报或笔记文档 + */ +export function exportTodosToMarkdown(todos: readonly TodoItem[], heading?: string): string { + if (!Array.isArray(todos) || todos.length === 0) return ""; + const lines = todos.map((item) => { + const box = item.completed ? "x" : " "; + const parts = [`- [${box}] ${item.title}`]; + if (item.priority === "high") parts.push("[!]"); + if (item.tags && item.tags.length > 0) { + parts.push(item.tags.map((tag: string) => `#${tag}`).join(" ")); + } + if (item.dueDate) { + parts.push(`@${item.dueDate}`); + } + return parts.join(" "); + }); + return heading ? `## ${heading}\n\n${lines.join("\n")}` : lines.join("\n"); } export const TODOS_STORAGE_KEY = "todo.items.v1"; @@ -179,13 +351,17 @@ export function sanitizeStoredTodos(raw: unknown): TodoItem[] { if (typeof t.title !== "string" || !t.title.trim()) continue; seen.add(t.id); const priority: TodoPriority = t.priority === "high" || t.priority === "low" ? t.priority : "medium"; + const tags = Array.isArray(t.tags) ? normalizeTags(t.tags.filter((v): v is string => typeof v === "string")) : []; + const dueDate = isValidDateKey(t.dueDate) ? t.dueDate : undefined; out.push({ id: t.id, title: t.title, completed: t.completed === true, priority, createdAt: typeof t.createdAt === "number" ? t.createdAt : 0, - ...(t.completed === true && typeof t.completedAt === "number" ? { completedAt: t.completedAt } : {}) + ...(t.completed === true && typeof t.completedAt === "number" ? { completedAt: t.completedAt } : {}), + ...(tags.length > 0 ? { tags } : {}), + ...(dueDate ? { dueDate } : {}) }); } return out; diff --git a/extensions/todo/tests/quick-sugar-export.test.mjs b/extensions/todo/tests/quick-sugar-export.test.mjs new file mode 100644 index 00000000..5d08b0f2 --- /dev/null +++ b/extensions/todo/tests/quick-sugar-export.test.mjs @@ -0,0 +1,94 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import { createHost, mount, mountPushed, tick } from '../../shared/test-harness.mjs' +import TodoCommand from '../dist/index.js' +import { + createTodo, + exportTodosToMarkdown, + filterAndSearchTodos, + formatLocalDateKey, + parseQuickAddInput, + TODOS_STORAGE_KEY +} from '../dist/logic.js' + +const host = createHost() +test.beforeEach(() => host.reset()) + +const saved = () => JSON.parse(host.storage.get(TODOS_STORAGE_KEY)) + +test('parseQuickAddInput: 解析 !! 高优、#标签 与 @today 截止日期', () => { + const fixedNow = new Date(2026, 4, 15, 10, 0, 0).getTime() + const parsed = parseQuickAddInput('提交 v2.4 发版单 !! #工作 #发版 @today', fixedNow) + assert.equal(parsed.title, '提交 v2.4 发版单') + assert.equal(parsed.priority, 'high') + assert.deepEqual(parsed.tags, ['工作', '发版']) + assert.equal(parsed.dueDate, '2026-05-15') + assert.equal(parsed.hasSyntaxSugar, true) + + // 仅包含语法糖而无实质标题时返回空标题 + const emptyTitle = parseQuickAddInput('!! #工作 @today', fixedNow) + assert.equal(emptyTitle.title, '') + + // 普通无语法糖输入保持默认中优先级 + const plain = parseQuickAddInput('买咖啡', fixedNow) + assert.equal(plain.title, '买咖啡') + assert.equal(plain.priority, 'medium') + assert.deepEqual(plain.tags, []) + assert.equal(plain.dueDate, undefined) + assert.equal(plain.hasSyntaxSugar, false) +}) + +test('搜索框快录语法糖端到端:回车创建带高优/标签/今日截止的待办,并支持今日待办筛选', async () => { + const view = await mount(TodoCommand) + const todayKey = formatLocalDateKey() + + await view.search('提交发版单 !! #工作 @today') + const quick = view.item('quick-add') + assert.ok(quick) + assert.equal(quick.props.title, '添加待办「提交发版单」') + assert.match(String(quick.props.subtitle), /高优先级/) + assert.match(String(quick.props.subtitle), /#工作/) + assert.match(String(quick.props.subtitle), /今日截止/) + + await view.run(quick, '添加待办') + await tick() + + const list = saved() + assert.equal(list.length, 1) + assert.equal(list[0].title, '提交发版单') + assert.equal(list[0].priority, 'high') + assert.deepEqual(list[0].tags, ['工作']) + assert.equal(list[0].dueDate, todayKey) + + // 验证今日待办筛选 + const todayOnly = filterAndSearchTodos(list, 'today') + assert.equal(todayOnly.length, 1) + assert.equal(todayOnly[0].title, '提交发版单') + + // 「填写详情后添加…」应预填语法糖解析结果 + await view.search('重构核心模块 !! #架构 @today') + await view.run(view.item('quick-add'), '填写详情后添加…') + const form = await mountPushed(host) + assert.equal(form.field('title').props.value, '重构核心模块') + assert.equal(form.field('priority').props.value, 'high') + assert.equal(form.field('tags').props.value, '架构') + assert.equal(form.field('dueDate').props.value, todayKey) + form.unmount() + view.unmount() +}) + +test('Markdown 导出:纯函数与全局动作一键复制标准 Checklist,剪贴板失败如实报错', async () => { + const t1 = { ...createTodo('完成接口联调', 'high', { tags: ['后端'], dueDate: '2026-05-15' }), completed: true } + const t2 = createTodo('整理周报', 'medium', { tags: ['日常'] }) + const md = exportTodosToMarkdown([t1, t2]) + assert.equal(md, '- [x] 完成接口联调 [!] #后端 @2026-05-15\n- [ ] 整理周报 #日常') + assert.equal(exportTodosToMarkdown([]), '') + + host.storage.set(TODOS_STORAGE_KEY, JSON.stringify([t1, t2])) + const view = await mount(TodoCommand) + await view.run(null, '导出为 Markdown 清单') + assert.ok(host.clipboard.text.includes('- [x] 完成接口联调 [!] #后端 @2026-05-15')) + assert.ok(host.clipboard.text.includes('- [ ] 整理周报 #日常')) + assert.match(String(host.lastToast().title), /已复制 2 条待办/) + view.unmount() +}) diff --git a/extensions/vscode-projects/plugin.json b/extensions/vscode-projects/plugin.json index 83371141..de5cc644 100644 --- a/extensions/vscode-projects/plugin.json +++ b/extensions/vscode-projects/plugin.json @@ -1,7 +1,7 @@ { "id": "vscode-projects", "name": "最近项目", - "version": "1.0.8", + "version": "1.0.9", "description": "聚合检索 VS Code、Cursor、Trae、Windsurf 与 JetBrains 的本地最近项目,查看 Git 分支并打开编辑器或终端", "author": "ZTools Team", "category": [ diff --git a/extensions/vscode-projects/src/i18n.ts b/extensions/vscode-projects/src/i18n.ts index f15f38ff..4611d572 100644 --- a/extensions/vscode-projects/src/i18n.ts +++ b/extensions/vscode-projects/src/i18n.ts @@ -41,13 +41,40 @@ const rawT = createTranslator( tagPathUnreadable: "无法访问", tagPinned: "已置顶", actionOpenWithEditor: "用 {editor} 打开项目", + actionOpenWithOther: "用其他编辑器打开", + actionOpenWithSpecific: "用 {editor} 打开", + toastCopiedEditorCmdTitle: "已复制 {editor} 打开命令", + toastCopiedEditorCmdMsg: "该仓库尚无 {editor} 历史记录,已复制:{cmd}", actionOpenInTerminal: "在终端打开", actionRevealInFinder: "在访达中显示", actionRevealInExplorer: "在资源管理器中显示", + actionOpenFolder: "打开项目目录", actionPinProject: "置顶项目", actionUnpinProject: "取消置顶", actionCopyPath: "复制项目路径", actionCopyBranch: "复制 Git 分支", + actionManageScanDirs: "扫描目录", + actionManageScanDirsCount: "扫描目录 ({count})", + tagCustomDir: "自定义目录", + scanDirsNavTitle: "自定义扫描目录", + scanDirsSearchPlaceholder: "筛选已配置的扫描目录...", + scanDirsSummary: "已配置 {count} 个自定义目录(LocalStorage 持久化)", + scanDirsAddPicker: "选择文件夹添加", + scanDirsAddManual: "手动输入路径添加", + scanDirsRemove: "移除此目录", + scanDirsEmptyTitle: "尚未添加自定义扫描目录", + scanDirsEmptySub: "点击「选择文件夹添加」或按回车,将本地代码根目录纳入检索", + scanDirsFormTitle: "添加自定义扫描目录", + scanDirsFieldPath: "目录路径", + scanDirsFieldPlaceholder: "例如 D:\\work 或 /Users/name/projects", + scanDirsSave: "保存目录", + scanDirsPathEmpty: "请输入有效的本地目录路径", + scanDirsAdded: "已添加扫描目录", + scanDirsAlreadyExists: "该目录已在扫描列表中", + scanDirsRemoved: "已移除扫描目录", + scanDirsSaveFailed: "保存扫描目录失败", + scanDirsPickerUnavailable: "当前客户端不支持目录选择框,请改用「手动输入路径添加」", + scanDirsReadFailed: "扫描自定义目录失败({dir}):{reason}", emptyNoMatch: "没有匹配的项目", emptyNoHistory: "没有找到本地项目历史", emptyErrorSub: "原始历史记录未修改,可重新扫描", @@ -96,13 +123,40 @@ const rawT = createTranslator( tagPathUnreadable: "Unreadable", tagPinned: "Pinned", actionOpenWithEditor: "Open in {editor}", + actionOpenWithOther: "Open With Other Editor", + actionOpenWithSpecific: "Open in {editor}", + toastCopiedEditorCmdTitle: "Copied {editor} open command", + toastCopiedEditorCmdMsg: "No {editor} history for this repo yet; copied: {cmd}", actionOpenInTerminal: "Open in Terminal", actionRevealInFinder: "Reveal in Finder", actionRevealInExplorer: "Reveal in Explorer", + actionOpenFolder: "Open Project Folder", actionPinProject: "Pin Project", actionUnpinProject: "Unpin Project", actionCopyPath: "Copy Project Path", actionCopyBranch: "Copy Git Branch", + actionManageScanDirs: "Scan Folders", + actionManageScanDirsCount: "Scan Folders ({count})", + tagCustomDir: "Custom Dir", + scanDirsNavTitle: "Custom Scan Directories", + scanDirsSearchPlaceholder: "Filter configured scan directories...", + scanDirsSummary: "{count} custom [[count:directory|directories]] configured (persisted)", + scanDirsAddPicker: "Choose Folder...", + scanDirsAddManual: "Enter Path Manually...", + scanDirsRemove: "Remove Directory", + scanDirsEmptyTitle: "No custom scan directories yet", + scanDirsEmptySub: "Choose a local workspace root folder to include its projects in search", + scanDirsFormTitle: "Add Custom Scan Directory", + scanDirsFieldPath: "Directory Path", + scanDirsFieldPlaceholder: "e.g. D:\\work or /Users/name/projects", + scanDirsSave: "Save Directory", + scanDirsPathEmpty: "Please enter a valid local directory path", + scanDirsAdded: "Scan directory added", + scanDirsAlreadyExists: "Directory is already in the scan list", + scanDirsRemoved: "Scan directory removed", + scanDirsSaveFailed: "Failed to save scan directories", + scanDirsPickerUnavailable: "Folder picker unavailable; use Enter Path Manually instead", + scanDirsReadFailed: "Failed to scan custom directory ({dir}): {reason}", emptyNoMatch: "No matching projects", emptyNoHistory: "No local project history found", emptyErrorSub: "Original history is untouched; you can rescan", diff --git a/extensions/vscode-projects/src/mac-command.tsx b/extensions/vscode-projects/src/mac-command.tsx index 4ad20e91..6ba5c0ba 100644 --- a/extensions/vscode-projects/src/mac-command.tsx +++ b/extensions/vscode-projects/src/mac-command.tsx @@ -1,48 +1,309 @@ -import React, { Action, ActionPanel, Icon, List, LocalStorage, Toast, showToast, useEffect, useLocale, useRef, useState, getLocale } from '@ztools/declarative-ui' +import React, { + Action, ActionPanel, Form, Icon, List, LocalStorage, Toast, showToast, + useEffect, useLocale, useNavigation, useRef, useState, getLocale +} from '@ztools/declarative-ui' import { - cancelMacProjects, describeOpenError, filterMacProjects, normalizePinnedProjectIds, - openMacProject, PINNED_PROJECTS_STORAGE_KEY, projectOperationId, revealMacProjectInFolder, - scanMacProjects, sortProjectsWithPinned, togglePinnedProjectId, - type MacProject, type MacProjectsReport + addCustomScanDir, cancelMacProjects, CUSTOM_SCAN_DIRS_STORAGE_KEY, describeOpenError, + filterMacProjects, mergeProjectsWithCustom, normalizeCustomScanDirs, normalizePinnedProjectIds, + openMacProject, openPathInSystem, openProjectWithOtherEditor, OTHER_EDITORS, + PINNED_PROJECTS_STORAGE_KEY, projectOperationId, removeCustomScanDir, revealMacProjectInFolder, + scanCustomScanDirs, scanMacProjects, selectCustomScanFolder, sortProjectsWithPinned, + togglePinnedProjectId, type MacProject, type MacProjectsReport, type OtherEditorId } from './mac-service.js' import { t } from './i18n.js' +function AddCustomScanDirForm({ onAdd }: { onAdd: (dirPath: string) => Promise }) { + useLocale() + const { pop } = useNavigation() + const [dirPath, setDirPath] = useState('') + const [error, setError] = useState(undefined) + const submitting = useRef(false) + + const handleSubmit = async (values: Record) => { + const raw = typeof values.dirPath === 'string' && values.dirPath ? values.dirPath : dirPath + const trimmed = raw.trim() + if (!trimmed || !/^(\/|[A-Za-z]:[\\/]|\\\\)/.test(trimmed)) { + setError(t('scanDirsPathEmpty')) + await showToast({ style: Toast.Style.Failure, title: t('scanDirsPathEmpty') }) + return + } + if (submitting.current) return + submitting.current = true + try { + const ok = await onAdd(trimmed) + if (ok) pop() + } finally { + submitting.current = false + } + } + + return ( +
+ + + } + > + { + setDirPath(val) + if (error) setError(undefined) + }} + /> + + ) +} + +function CustomScanDirsView({ + initialDirs, + onChange +}: { + initialDirs: string[] + onChange: (nextDirs: string[]) => void +}) { + useLocale() + const { push } = useNavigation() + const [dirs, setDirs] = useState(initialDirs) + const [query, setQuery] = useState('') + const alive = useRef(true) + + useEffect(() => { + alive.current = true + return () => { alive.current = false } + }, []) + + const persistDir = async (dirPath: string): Promise => { + const { next, added } = addCustomScanDir(dirs, dirPath) + if (!added) { + await showToast({ style: Toast.Style.Failure, title: t('scanDirsAlreadyExists'), message: dirPath }) + return false + } + try { + await LocalStorage.setItem(CUSTOM_SCAN_DIRS_STORAGE_KEY, next) + if (alive.current) { + setDirs(next) + onChange(next) + await showToast({ style: Toast.Style.Success, title: t('scanDirsAdded'), message: dirPath }) + } + return true + } catch (e) { + if (alive.current) { + await showToast({ style: Toast.Style.Failure, title: t('scanDirsSaveFailed'), message: e instanceof Error ? e.message : String(e) }) + } + return false + } + } + + const pickFolder = async () => { + try { + const folderPath = await selectCustomScanFolder(t('scanDirsFormTitle')) + if (!folderPath || !alive.current) return + await persistDir(folderPath) + } catch (e) { + if (alive.current) { + await showToast({ style: Toast.Style.Failure, title: t('scanDirsSaveFailed'), message: e instanceof Error ? e.message : String(e) }) + } + } + } + + const removeDir = async (dirPath: string) => { + const next = removeCustomScanDir(dirs, dirPath) + try { + await LocalStorage.setItem(CUSTOM_SCAN_DIRS_STORAGE_KEY, next) + if (alive.current) { + setDirs(next) + onChange(next) + await showToast({ style: Toast.Style.Success, title: t('scanDirsRemoved'), message: dirPath }) + } + } catch (e) { + if (alive.current) { + await showToast({ style: Toast.Style.Failure, title: t('scanDirsSaveFailed'), message: e instanceof Error ? e.message : String(e) }) + } + } + } + + const q = query.trim().toLowerCase() + const filtered = q ? dirs.filter(d => d.toLowerCase().includes(q)) : dirs + + const globalActions = ( + + + push()} /> + + ) + + return ( + push() } + ] + }} + actions={globalActions} + > + {filtered.map(dir => ( + + removeDir(dir)} /> + + + } + /> + ))} + {!filtered.length && ( + + )} + + ) +} + export default function MacProjectsCommand({ featureCode, platform = 'macos' }: { featureCode?: string; platform?: 'macos' | 'windows' }) { useLocale() + const { push } = useNavigation() const [report, setReport] = useState(null), [error, setError] = useState(''), [busy, setBusy] = useState(false) const [query, setQuery] = useState(''), [family, setFamily] = useState(featureCode === 'projects-vscode-cursor' ? 'vsc' : featureCode === 'projects-jetbrains' ? 'jetbrains' : 'all'), [hideMissing, setHideMissing] = useState(false) const [pinnedIds, setPinnedIds] = useState([]) + const [customDirs, setCustomDirs] = useState([]) + const [customProjects, setCustomProjects] = useState([]) + const [customWarnings, setCustomWarnings] = useState([]) + const customDirsRef = useRef([]) const alive = useRef(true), guard = useRef(false), pending = useRef(null), pendingAction = useRef<'scan' | 'open' | null>(null), cancelled = useRef(false) - const scan = async () => { + + const refreshCustomProjects = async (dirs: readonly string[]) => { + const res = await scanCustomScanDirs(dirs) + if (alive.current) { + setCustomProjects(res.projects) + setCustomWarnings(res.warnings) + } + } + + const scan = async (dirsOverride?: readonly string[]) => { if (guard.current) return guard.current = true; cancelled.current = false; setBusy(true); setError('') const operationId = projectOperationId(); pending.current = operationId; pendingAction.current = 'scan' - try { const data = await scanMacProjects(operationId); if (alive.current && !cancelled.current) setReport(data) } - catch (e) { if (alive.current && !cancelled.current) { setReport(null); setError(e instanceof Error ? e.message : String(e)) } } - finally { pending.current = null; pendingAction.current = null; guard.current = false; if (alive.current) setBusy(false) } + const dirsToScan = dirsOverride ?? customDirsRef.current + try { + const [data, customRes] = await Promise.all([ + scanMacProjects(operationId), + scanCustomScanDirs(dirsToScan) + ]) + if (alive.current && !cancelled.current) { + setReport(data) + setCustomProjects(customRes.projects) + setCustomWarnings(customRes.warnings) + } + } catch (e) { + if (alive.current && !cancelled.current) { + setReport(null) + setError(e instanceof Error ? e.message : String(e)) + } + } finally { + pending.current = null; pendingAction.current = null; guard.current = false; if (alive.current) setBusy(false) + } } + const stop = async () => { cancelled.current = true const message = pendingAction.current === 'scan' ? t('statusScanStopped') : t('statusOpenCancelled') try { if (pending.current) await cancelMacProjects(pending.current); if (alive.current) { if (pendingAction.current === 'scan') setReport(null); setError(message) } } catch (e) { if (alive.current) setError(e instanceof Error ? e.message : String(e)) } } + useEffect(() => { - alive.current = true; void scan() + alive.current = true void LocalStorage.getItem(PINNED_PROJECTS_STORAGE_KEY) .then(raw => { if (alive.current) setPinnedIds(normalizePinnedProjectIds(raw)) }) .catch(() => { if (alive.current) setPinnedIds([]) }) + void LocalStorage.getItem(CUSTOM_SCAN_DIRS_STORAGE_KEY) + .then(raw => { + const dirs = normalizeCustomScanDirs(raw) + customDirsRef.current = dirs + if (alive.current) setCustomDirs(dirs) + void scan(dirs) + }) + .catch(() => { + customDirsRef.current = [] + if (alive.current) setCustomDirs([]) + void scan([]) + }) return () => { alive.current = false; cancelled.current = true; if (pending.current) void cancelMacProjects(pending.current).catch(e => console.error('Stop project scan failed', e)) } }, []) + const open = async (item: MacProject, action: 'open' | 'terminal') => { if (guard.current) return // 扫描时已确认路径不存在:直接如实提示,不再向系统发送注定失败的打开请求 if (item.pathState === 'missing') { await showToast({ style: Toast.Style.Failure, title: t('toastPathMissingTitle'), message: t('toastPathMissingMsg', { path: item.path }) }); return } + if (item.isCustom) { + try { + await openPathInSystem(item.path) + if (alive.current) await showToast({ style: Toast.Style.Success, title: platform === 'macos' ? t('toastRevealedFinder') : t('toastRevealedExplorer'), message: item.path }) + } catch (e) { + if (alive.current) await showToast({ style: Toast.Style.Failure, title: t('toastOpenFailed'), message: describeOpenError(e, item) }) + } + return + } guard.current = true; cancelled.current = false; pending.current = item.id; pendingAction.current = 'open'; setBusy(true); setError('') try { await openMacProject(item, action); if (alive.current && !cancelled.current) await showToast({ style: Toast.Style.Success, title: action === 'open' ? t('toastOpenedEditor', { editor: item.editorName }) : t('toastOpenedTerminal') }) } catch (e) { if (alive.current && !cancelled.current) await showToast({ style: Toast.Style.Failure, title: t('toastOpenFailed'), message: describeOpenError(e, item) }) } finally { if (pending.current === item.id) { pending.current = null; pendingAction.current = null }; guard.current = false; if (alive.current) setBusy(false) } } + + const openWithOther = async (item: MacProject, targetEditor: OtherEditorId) => { + if (guard.current) return + if (item.pathState === 'missing') { + await showToast({ style: Toast.Style.Failure, title: t('toastPathMissingTitle'), message: t('toastPathMissingMsg', { path: item.path }) }) + return + } + guard.current = true; cancelled.current = false; pending.current = item.id; pendingAction.current = 'open'; setBusy(true); setError('') + try { + const outcome = await openProjectWithOtherEditor(item, targetEditor, report?.projects || []) + if (alive.current && !cancelled.current) { + if (outcome.mode === 'launched') { + await showToast({ style: Toast.Style.Success, title: t('toastOpenedEditor', { editor: outcome.editorName }) }) + } else { + await showToast({ + style: Toast.Style.Success, + title: t('toastCopiedEditorCmdTitle', { editor: outcome.editorName }), + message: t('toastCopiedEditorCmdMsg', { editor: outcome.editorName, cmd: outcome.command }) + }) + } + } + } catch (e) { + if (alive.current && !cancelled.current) { + await showToast({ style: Toast.Style.Failure, title: t('toastOpenFailed'), message: describeOpenError(e, item) }) + } + } finally { + if (pending.current === item.id) { pending.current = null; pendingAction.current = null } + guard.current = false + if (alive.current) setBusy(false) + } + } + const reveal = async (item: MacProject) => { if (item.pathState === 'missing') { await showToast({ style: Toast.Style.Failure, title: t('toastPathMissingTitle'), message: t('toastPathMissingMsg', { path: item.path }) }); return } try { @@ -52,6 +313,7 @@ export default function MacProjectsCommand({ featureCode, platform = 'macos' }: if (alive.current) await showToast({ style: Toast.Style.Failure, title: t('toastRevealFailed'), message: describeOpenError(e, item) }) } } + const togglePin = async (item: MacProject) => { const { next, pinned } = togglePinnedProjectId(pinnedIds, item.id) try { @@ -64,34 +326,86 @@ export default function MacProjectsCommand({ featureCode, platform = 'macos' }: if (alive.current) await showToast({ style: Toast.Style.Failure, title: t('toastPinSaveFailed'), message: e instanceof Error ? e.message : String(e) }) } } + + const openManageScanDirs = () => { + push( + { + customDirsRef.current = nextDirs + if (alive.current) { + setCustomDirs(nextDirs) + void refreshCustomProjects(nextDirs) + } + }} + /> + ) + } + const pinnedSet = new Set(pinnedIds) - const rows = sortProjectsWithPinned(filterMacProjects(report?.projects || [], query, family, hideMissing), pinnedIds) + const mergedProjects = mergeProjectsWithCustom(report?.projects || [], customProjects) + const rows = sortProjectsWithPinned(filterMacProjects(mergedProjects, query, family, hideMissing), pinnedIds) + const allWarnings = [...(report?.warnings || []), ...customWarnings] const revealTitle = platform === 'macos' ? t('actionRevealInFinder') : t('actionRevealInExplorer') + const manageScanDirsTitle = customDirs.length > 0 + ? t('actionManageScanDirsCount', { count: customDirs.length }) + : t('actionManageScanDirs') + + const globalActions = ( + + scan()} /> + + setHideMissing(!hideMissing)} /> + + ) + return } - filterBar={{ summaryText: busy ? (pendingAction.current === 'scan' ? t('summaryScanning') : t('summaryOpening')) : error || t('summaryReady', { count: rows.length, sources: report?.sourcesRead || 0, skipped: report?.skippedRemote ? t('summarySkippedRemote', { count: report.skippedRemote }) : '' }), actions: [ - // 空状态条目的主动作已是“重新扫描”,此时工具栏不再重复;扫描/打开进行中始终保留停止入口 - ...(!busy && !rows.length ? [] : [{ id: 'scan', title: busy ? (pendingAction.current === 'scan' ? t('actionStopScan') : t('actionCancelOpen')) : t('actionRescan'), onAction: () => busy ? stop() : scan() }]), - { id: 'missing', title: hideMissing ? t('actionShowMissing') : t('actionHideMissing'), onAction: () => setHideMissing(!hideMissing) } - ] }}> + filterBar={{ + summaryText: busy ? (pendingAction.current === 'scan' ? t('summaryScanning') : t('summaryOpening')) : error || t('summaryReady', { count: rows.length, sources: (report?.sourcesRead || 0) + customDirs.length, skipped: report?.skippedRemote ? t('summarySkippedRemote', { count: report.skippedRemote }) : '' }), + actions: [ + ...(!busy && !rows.length ? [] : [{ id: 'scan', title: busy ? (pendingAction.current === 'scan' ? t('actionStopScan') : t('actionCancelOpen')) : t('actionRescan'), onAction: () => busy ? stop() : scan() }]), + { id: 'custom-dirs', title: manageScanDirsTitle, icon: Icon.Folder, onAction: openManageScanDirs } + ] + }} + actions={globalActions}> {rows.map(item => { const isPinned = pinnedSet.has(item.id) + const otherEditorOptions = OTHER_EDITORS.filter(opt => item.isCustom || !opt.matchEditors.includes(item.editor)) return - open(item, 'open')} /> - open(item, 'terminal')} /> - reveal(item)} /> + {item.isCustom + ? open(item, 'open')} /> + : open(item, 'open')} />} + {item.isCustom + ? reveal(item)} /> + : open(item, 'terminal')} />} + + {otherEditorOptions.map(opt => ( + openWithOther(item, opt.id)} + /> + ))} + + {!item.isCustom && reveal(item)} />} togglePin(item)} /> - + {item.gitBranch && } + setHideMissing(!hideMissing)} /> } /> })} - {!rows.length && !busy && scan()} />} />} - {report?.warnings.map((warning, index) => )} + {!rows.length && !busy && + scan()} /> + + } />} + {allWarnings.map((warning, index) => )} } diff --git a/extensions/vscode-projects/src/mac-service.ts b/extensions/vscode-projects/src/mac-service.ts index af74ed2f..cd9385fe 100644 --- a/extensions/vscode-projects/src/mac-service.ts +++ b/extensions/vscode-projects/src/mac-service.ts @@ -1,7 +1,23 @@ +import { Clipboard } from '@ztools/declarative-ui' import { t } from './i18n.js' import { resolveErrorMessage } from './error-i18n.js' -export interface MacProject { id: string; path: string; name: string; editor: string; editorName: string; family: 'vsc' | 'jetbrains'; kind: 'folder' | 'workspace'; lastOpenedMs: number | null; gitBranch: string | null; pathState: 'available' | 'missing' | 'unreadable'; pathError: string | null } +export interface MacProject { id: string; path: string; name: string; editor: string; editorName: string; family: 'vsc' | 'jetbrains'; kind: 'folder' | 'workspace'; lastOpenedMs: number | null; gitBranch: string | null; pathState: 'available' | 'missing' | 'unreadable'; pathError: string | null; isCustom?: boolean } export interface MacProjectsReport { projects: MacProject[]; warnings: string[]; sourcesRead: number; skippedRemote: number } + +export type OtherEditorId = 'vscode' | 'cursor' | 'trae' | 'windsurf' +export interface OtherEditorOption { + id: OtherEditorId + name: string + cli: string + matchEditors: readonly string[] +} +export const OTHER_EDITORS: readonly OtherEditorOption[] = [ + { id: 'vscode', name: 'VS Code', cli: 'code', matchEditors: ['vscode', 'vscode-insiders'] }, + { id: 'cursor', name: 'Cursor', cli: 'cursor', matchEditors: ['cursor'] }, + { id: 'trae', name: 'Trae', cli: 'trae', matchEditors: ['trae', 'trae-cn'] }, + { id: 'windsurf', name: 'Windsurf', cli: 'windsurf', matchEditors: ['windsurf'] } +] + interface Bridge { transport?: { methods?: Record Promise<{ success?: boolean; data?: unknown; error?: { message?: string } }>> } } const record = (value: unknown): value is Record => !!value && typeof value === 'object' && !Array.isArray(value) let sequence = 0 @@ -86,3 +102,186 @@ export function filterMacProjects(items: MacProject[], query: string, family: st return items.filter(p => (family === 'all' || p.family === family) && (!hideMissing || p.pathState !== 'missing') && [p.name, p.path, p.editorName, p.gitBranch || ''].some(v => v.toLocaleLowerCase().includes(q))) } + +export function normalizeProjectPath(rawPath: string): string { + const trimmed = (rawPath || '').trim() + if (!trimmed) return '' + // 去除末尾多余斜杠(保留盘符根目录如 C:\ 或 /) + const stripped = trimmed.length > 1 && !/^[A-Za-z]:[\\/]$/.test(trimmed) + ? trimmed.replace(/[\\/]+$/, '') + : trimmed + if (/^[A-Za-z]:[\\/]/.test(stripped)) { + return stripped.replace(/\//g, '\\').toLowerCase() + } + return stripped.replace(/\\/g, '/') +} + +export function buildEditorCliCommand(editorId: OtherEditorId, projectPath: string): string { + const option = OTHER_EDITORS.find(e => e.id === editorId) + const cli = option ? option.cli : editorId + const escaped = projectPath.replace(/"/g, '\\"') + return `${cli} "${escaped}"` +} + +export function findMatchingEditorProject( + allProjects: readonly MacProject[], + targetPath: string, + targetEditor: OtherEditorId +): MacProject | undefined { + const option = OTHER_EDITORS.find(e => e.id === targetEditor) + if (!option) return undefined + const targetNorm = normalizeProjectPath(targetPath) + if (!targetNorm) return undefined + return allProjects.find( + p => !p.isCustom && option.matchEditors.includes(p.editor) && normalizeProjectPath(p.path) === targetNorm + ) +} + +export async function openProjectWithOtherEditor( + project: MacProject, + targetEditor: OtherEditorId, + allProjects: readonly MacProject[] +): Promise<{ mode: 'launched'; editorName: string } | { mode: 'copied-cli'; editorName: string; command: string }> { + const option = OTHER_EDITORS.find(e => e.id === targetEditor) + const editorName = option?.name ?? targetEditor + const matched = findMatchingEditorProject(allProjects, project.path, targetEditor) + if (matched) { + await openMacProject(matched, 'open') + return { mode: 'launched', editorName } + } + const command = buildEditorCliCommand(targetEditor, project.path) + await Clipboard.copy(command) + return { mode: 'copied-cli', editorName, command } +} + +export async function openPathInSystem(targetPath: string): Promise { + const invoke = (globalThis as unknown as { __ztoolsElectron?: Bridge }).__ztoolsElectron?.transport?.methods?.shell_open_path + if (!invoke) throw new Error(t('errUpgradeClient')) + const result = await invoke({ messageId: projectOperationId(), params: { fullPath: targetPath }, timeoutMs: 25000 }) + if (result?.success !== true || (record(result.data) && result.data.success === false)) { + throw new Error(resolveErrorMessage(result?.error ?? result?.data, t('errOperationUnconfirmed'))) + } +} + +export const CUSTOM_SCAN_DIRS_STORAGE_KEY = 'ztools-vscode-projects-custom-dirs-v1' + +export function normalizeCustomScanDirs(raw: unknown): string[] { + if (!Array.isArray(raw)) return [] + const seen = new Set() + const out: string[] = [] + for (const item of raw) { + if (typeof item !== 'string') continue + const trimmed = item.trim() + if (!trimmed || !/^(\/|[A-Za-z]:[\\/]|\\\\)/.test(trimmed)) continue + const norm = normalizeProjectPath(trimmed) + if (!norm || seen.has(norm)) continue + seen.add(norm) + out.push(trimmed) + } + return out +} + +export function addCustomScanDir(dirs: readonly string[], dirPath: string): { next: string[]; added: boolean } { + const trimmed = (dirPath || '').trim() + if (!trimmed || !/^(\/|[A-Za-z]:[\\/]|\\\\)/.test(trimmed)) { + return { next: [...dirs], added: false } + } + const norm = normalizeProjectPath(trimmed) + if (dirs.some(d => normalizeProjectPath(d) === norm)) { + return { next: [...dirs], added: false } + } + return { next: [...dirs, trimmed], added: true } +} + +export function removeCustomScanDir(dirs: readonly string[], dirPath: string): string[] { + const norm = normalizeProjectPath(dirPath) + return dirs.filter(d => normalizeProjectPath(d) !== norm) +} + +export async function selectCustomScanFolder(title: string): Promise { + const invoke = (globalThis as unknown as { __ztoolsElectron?: Bridge }).__ztoolsElectron?.transport?.methods?.window_show_select_folder_dialog + if (!invoke) throw new Error(t('scanDirsPickerUnavailable')) + const result = await invoke({ messageId: projectOperationId(), params: { title }, timeoutMs: 120000 }) + if (result?.success !== true || !record(result.data)) { + throw new Error(resolveErrorMessage(result?.error ?? result?.data, t('scanDirsPickerUnavailable'))) + } + if (result.data.canceled === true) return null + const folderPath = typeof result.data.folderPath === 'string' ? result.data.folderPath.trim() : '' + return folderPath || null +} + +const IGNORED_CUSTOM_DIR_NAMES = new Set([ + 'node_modules', 'dist', 'build', 'out', 'target', '__pycache__', '.git', '.svn', '.hg', '.idea', '.vscode' +]) + +function joinChildPath(parent: string, name: string): string { + const sep = parent.includes('\\') && !parent.includes('/') ? '\\' : '/' + if (parent.endsWith('/') || parent.endsWith('\\')) return `${parent}${name}` + return `${parent}${sep}${name}` +} + +export async function scanCustomScanDirs( + dirs: readonly string[] +): Promise<{ projects: MacProject[]; warnings: string[] }> { + if (!dirs.length) return { projects: [], warnings: [] } + const invoke = (globalThis as unknown as { __ztoolsElectron?: Bridge }).__ztoolsElectron?.transport?.methods?.filesystem_get_directory_contents + if (!invoke) return { projects: [], warnings: [] } + + const projects: MacProject[] = [] + const warnings: string[] = [] + const seen = new Set() + + for (const dir of dirs) { + try { + const result = await invoke({ messageId: projectOperationId(), params: { path: dir }, timeoutMs: 15000 }) + if (result?.success !== true || !record(result.data) || !Array.isArray(result.data.files)) { + warnings.push(t('scanDirsReadFailed', { dir, reason: resolveErrorMessage(result?.error ?? result?.data, t('errOperationUnconfirmed')) })) + continue + } + for (const rawEntry of result.data.files) { + if (!record(rawEntry)) continue + const isDirectory = rawEntry.isDirectory === true || rawEntry.type === 'directory' + if (!isDirectory) continue + const name = typeof rawEntry.name === 'string' ? rawEntry.name.trim() : '' + if (!name || name.startsWith('.') || IGNORED_CUSTOM_DIR_NAMES.has(name.toLowerCase())) continue + const fullPath = typeof rawEntry.path === 'string' && rawEntry.path.trim() + ? rawEntry.path.trim() + : joinChildPath(dir, name) + const norm = normalizeProjectPath(fullPath) + if (!norm || seen.has(norm)) continue + seen.add(norm) + const mtimeMs = typeof rawEntry.mtimeMs === 'number' && Number.isFinite(rawEntry.mtimeMs) && rawEntry.mtimeMs > 0 + ? Math.floor(rawEntry.mtimeMs) + : null + projects.push({ + id: `custom:${norm}`, + path: fullPath, + name, + editor: 'vscode', + editorName: t('tagCustomDir'), + family: 'vsc', + kind: 'folder', + lastOpenedMs: mtimeMs, + gitBranch: null, + pathState: 'available', + pathError: null, + isCustom: true + }) + } + } catch (e) { + warnings.push(t('scanDirsReadFailed', { dir, reason: e instanceof Error ? e.message : String(e) })) + } + } + + return { projects, warnings } +} + +export function mergeProjectsWithCustom( + ideProjects: readonly MacProject[], + customProjects: readonly MacProject[] +): MacProject[] { + if (!customProjects.length) return [...ideProjects] + const existing = new Set(ideProjects.map(p => normalizeProjectPath(p.path))) + const extras = customProjects.filter(p => !existing.has(normalizeProjectPath(p.path))) + return [...ideProjects, ...extras] +} diff --git a/extensions/vscode-projects/tests/mac-projects.test.mjs b/extensions/vscode-projects/tests/mac-projects.test.mjs deleted file mode 100644 index 360830a8..00000000 --- a/extensions/vscode-projects/tests/mac-projects.test.mjs +++ /dev/null @@ -1,125 +0,0 @@ -import test, { beforeEach, afterEach } from 'node:test' -import assert from 'node:assert/strict' -import { createHost, mount, tick } from '../../shared/test-harness.mjs' -import Command, { commands } from '../dist/index.js' -import { scanMacProjects, openMacProject } from '../dist/mac-service.js' -const project = (editor = 'cursor', state = 'available') => ({ id: (editor === 'cursor' ? 'a' : 'b').repeat(64), name: '工程 $&', path: '/tmp/工程 $&', editor, editorName: editor === 'cursor' ? 'Cursor' : 'GoLand', family: editor === 'cursor' ? 'vsc' : 'jetbrains', kind: 'folder', lastOpenedMs: null, gitBranch: 'feature/工作树', pathState: state, pathError: null }) -const report = () => ({ success: true, projects: [project(), project('goland', 'missing')], sourcesRead: 2, skippedRemote: 1, warnings: [] }) -let host, views -beforeEach(() => { host = createHost(); views = []; host.ipc.system_get_platform = async () => ({ success: true, platform: 'macos' }); host.ipc.recent_projects = async p => p.action === 'scan' ? report() : p.action === 'cancel' ? { success: true, cancelled: true } : { success: true, id: p.id, action: p.action, accepted: true } }) -afterEach(async () => { for (const v of views) v.unmount(); await tick() }) -async function open(command = Command) { const v = await mount(command, host); views.push(v); await tick(); return v } -const bar = (v, id) => v.tree().props.filterBar.actions.find(a => a.id === id) -const calls = action => host.ipcCalls.filter(([m,p]) => m === 'recent_projects' && p.action === action) -test('真实 SDK 首屏扫描、宽列表和主次动作;不走 DLL、不伪造时间', async () => { - const v = await open(); assert.equal(calls('scan').length, 1); assert.equal(v.tree().props.isShowingDetail, false); assert.match(v.text(), /跳过 1 条远程/); assert.doesNotMatch(v.text(), /刚刚打开|分钟前/) - assert.ok(!host.ipcCalls.some(([m]) => m === 'dllplugin_call')) - const item = v.item('a'.repeat(64)), actions = v.actions(item) - assert.match(actions[0].props.title, /Cursor/); assert.equal(actions[1].props.title, '在终端打开'); assert.deepEqual(actions[1].props.shortcut, { modifiers: ['ctrl'], key: 'return' }) - await v.run(item, '用 Cursor 打开项目'); assert.equal(calls('open').length, 1); await v.run(item, '在终端打开'); assert.equal(calls('terminal').length, 1) - await v.run(item, '复制项目路径'); assert.equal(host.clipboard.text, project().path) -}) -test('三个入口正确分组,搜索、隐藏失效与恢复不写入编辑器历史', async () => { - const v = await open(commands['projects-jetbrains']); assert.equal(v.items().length, 1); assert.match(v.text(), /GoLand/) - await bar(v, 'missing').onAction(); await tick(); assert.match(v.text(), /没有匹配/) - await bar(v, 'missing').onAction(); await tick(); assert.match(v.text(), /路径不存在/) - await v.dropdown('all'); await v.search('feature/工作树'); assert.equal(v.items().length, 2) - const other = await open(commands['projects-vscode-cursor']); assert.equal(other.items().length, 1); assert.match(other.text(), /Cursor/) - assert.equal(host.storage.size, 0); assert.equal(calls('open').length, 0) -}) -test('扫描/打开失败真实显示,重扫移除旧结果,错误回执不能报成功', async () => { - const v = await open(); host.ipc.recent_projects = async () => { throw new Error('数据库权限不足') } - await v.run(v.item('a'.repeat(64)), '用 Cursor 打开项目'); assert.match(host.lastToast().message, /权限不足/) - await v.tree().props.filterBar.actions[0].onAction(); await tick(); assert.match(v.text(), /权限不足/); assert.equal(v.items().length, 1) - host.ipc.recent_projects = async () => ({ success: true }); await assert.rejects(openMacProject(project(), 'open'), /未确认/) -}) -test('严格响应校验,数组平台和枚举不冒充字符串', async () => { - for (const patch of [{ projects: null }, { sourcesRead: -1 }, { projects: [project(), project()] }, { projects: [{ ...project(), family: ['vsc'] }] }, { projects: [{ ...project(), pathState: ['available'] }] }]) { - host.ipc.recent_projects = async () => ({ ...report(), ...patch }); await assert.rejects(scanMacProjects('test'), /无效|不完整/) - } - host.ipc.system_get_platform = async () => ({ success: true, platform: ['macos'] }); const v = await open(); assert.match(v.text(), /不支持/) -}) -test('重复扫描互斥,取消及卸载不会展示迟到结果', async () => { - const v = await open(); let finish - host.ipc.recent_projects = async p => p.action === 'scan' ? new Promise(resolve => { finish = resolve }) : { success: true, cancelled: true } - const action = v.tree().props.filterBar.actions[0]; const pending = action.onAction(); await tick(); await action.onAction(); assert.equal(calls('scan').length, 2) - await v.tree().props.filterBar.actions[0].onAction(); finish(report()); await pending; await tick(); assert.match(v.text(), /已停止/) - assert.equal(bar(v, 'scan'), undefined); const next = v.run(v.item('empty'), '重新扫描'); await tick(); v.unmount(); views = []; finish(report()); await next; assert.equal(calls('cancel').length, 2) -}) -test('离开页面会取消打开任务,迟到成功不产生 Toast;打开中的按钮正确标注取消', async () => { - const v = await open(); let finish - host.ipc.recent_projects = async p => p.action === 'open' ? new Promise(resolve => { finish = resolve }) : { success: true, cancelled: true } - const job = v.run(v.item('a'.repeat(64)), '用 Cursor 打开项目'); await tick() - assert.equal(v.tree().props.filterBar.actions[0].title, '取消打开') - const before = host.toasts.length; v.unmount(); views = []; await tick() - assert.equal(calls('cancel').at(-1)[1].operationId, 'a'.repeat(64)) - finish({ success: true, id: 'a'.repeat(64), action: 'open', accepted: true }); await job; await tick(); assert.equal(host.toasts.length, before) -}) -test('扫描时已失效的项目不再发送打开请求,如实提示;宿主原始 ENOENT/EACCES 转成中文且不误伤其他错误', async () => { - const v = await open(commands['projects-jetbrains']) - const missing = v.item('b'.repeat(64)) - await v.run(missing, '用 GoLand 打开项目'); assert.equal(calls('open').length, 0); assert.match(host.lastToast().title, /路径不存在/) - await v.run(missing, '在终端打开'); assert.equal(calls('terminal').length, 0) - const all = await open(); const item = all.item('a'.repeat(64)) - host.ipc.recent_projects = async () => { throw new Error(`ENOENT: no such file or directory, stat '${project().path}'`) } - await all.run(item, '用 Cursor 打开项目'); assert.match(host.lastToast().message, /项目路径已不存在/) - host.ipc.recent_projects = async () => { throw new Error(`EACCES: permission denied, stat '${project().path}'`) } - await all.run(item, '在终端打开'); assert.match(host.lastToast().message, /没有访问项目路径的权限/) - host.ipc.recent_projects = async () => { throw new Error('spawn /Applications/Cursor.app/Contents/MacOS/Cursor ENOENT') } - await all.run(item, '用 Cursor 打开项目'); assert.ok(host.lastToast().message); assert.doesNotMatch(host.lastToast().message, /项目路径已不存在/) -}) -test('一份历史都没读到时展示具体失败原因,不用笼统提示覆盖', async () => { - host.ipc.recent_projects = async () => ({ success: true, projects: [], sourcesRead: 0, skippedRemote: 0, warnings: ['Cursor:database is locked'] }) - await assert.rejects(scanMacProjects('t'), /database is locked/) - const v = await open(); assert.match(v.text(), /database is locked/); assert.equal(v.items().length, 1) -}) - -test('空状态主动作是重新扫描,工具栏不重复;重新扫描真实发出请求并展示结果', async () => { - host.ipc.recent_projects = async p => p.action === 'scan' ? { ...report(), projects: [] } : { success: true } - const v = await open(); assert.match(v.item('empty').props.title, /没有找到本地项目历史/) - assert.deepEqual(v.actions(v.item('empty')).map(a => a.props.title), ['重新扫描']); assert.equal(bar(v, 'scan'), undefined) - host.ipc.recent_projects = async p => p.action === 'scan' ? report() : { success: true } - await v.run(v.item('empty'), '重新扫描'); await tick(); assert.equal(calls('scan').length, 2); assert.equal(v.items().length, 2); assert.equal(bar(v, 'scan').title, '重新扫描') - host.ipc.recent_projects = async () => { throw new Error('磁盘不可读') } - await bar(v, 'scan').onAction(); await tick(); assert.match(v.item('empty').props.title, /磁盘不可读/); assert.deepEqual(v.actions(v.item('empty')).map(a => a.props.title), ['重新扫描']) -}) - -test('在访达 / 资源管理器中显示:按平台展示正确文案并调用 shell_show_item_in_folder,失效项目不发送请求', async () => { - const revealed = [] - host.ipc.shell_show_item_in_folder = async ({ fullPath }) => { revealed.push(fullPath); return { success: true } } - const macView = await open() - await macView.run(macView.item('a'.repeat(64)), '在访达中显示') - assert.deepEqual(revealed, [project().path]) - assert.equal(host.lastToast().title, '已在访达中显示') - await macView.run(macView.item('b'.repeat(64)), '在访达中显示') - assert.equal(revealed.length, 1) - assert.match(host.lastToast().title, /路径不存在/) - - host.ipc.system_get_platform = async () => ({ success: true, platform: 'windows' }) - const winView = await open() - await winView.run(winView.item('a'.repeat(64)), '在资源管理器中显示') - assert.equal(revealed.length, 2) - assert.equal(host.lastToast().title, '已在资源管理器中显示') -}) - -test('常用项目置顶 / 取消置顶:持久化到 LocalStorage,置顶项目排在顶部并显示标记,写入失败不篡改状态', async () => { - const v = await open() - assert.deepEqual(v.items().map(i => i.props.id), ['a'.repeat(64), 'b'.repeat(64)]) - await v.run(v.item('b'.repeat(64)), '置顶项目') - assert.equal(host.lastToast().title, '已置顶项目') - assert.deepEqual(v.items().map(i => i.props.id), ['b'.repeat(64), 'a'.repeat(64)]) - assert.ok(JSON.stringify(v.items()[0].props.accessories).includes('已置顶')) - - // 重挂载后置顶顺序仍在 - const v2 = await open() - assert.deepEqual(v2.items().map(i => i.props.id), ['b'.repeat(64), 'a'.repeat(64)]) - await v2.run(v2.item('b'.repeat(64)), '取消置顶') - assert.equal(host.lastToast().title, '已取消置顶') - assert.deepEqual(v2.items().map(i => i.props.id), ['a'.repeat(64), 'b'.repeat(64)]) - - // 写入失败时不篡改状态 - host.faults.storageWrite = new Error('存储不可写') - await v2.run(v2.item('b'.repeat(64)), '置顶项目') - assert.equal(host.lastToast().title, '保存置顶状态失败') - assert.deepEqual(v2.items().map(i => i.props.id), ['a'.repeat(64), 'b'.repeat(64)]) -}) diff --git a/extensions/vscode-projects/tests/vscode-projects.test.mjs b/extensions/vscode-projects/tests/vscode-projects.test.mjs new file mode 100644 index 00000000..51d96110 --- /dev/null +++ b/extensions/vscode-projects/tests/vscode-projects.test.mjs @@ -0,0 +1,195 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import { setRuntimeLocale } from '@ztools/declarative-ui' +import { createHost, mount, mountPushed, tick } from '../../shared/test-harness.mjs' +import MacProjectsCommand from '../dist/mac-command.js' +import { + addCustomScanDir, + buildEditorCliCommand, + CUSTOM_SCAN_DIRS_STORAGE_KEY, + mergeProjectsWithCustom, + normalizeCustomScanDirs, + removeCustomScanDir +} from '../dist/mac-service.js' +import { t } from '../dist/i18n.js' + +const host = createHost() + +function makeId(ch) { + return ch.repeat(64) +} + +function setupMockElectron(handlers) { + const prev = globalThis.__ztoolsElectron + globalThis.__ztoolsElectron = { + transport: { + methods: handlers + } + } + return () => { + if (prev === undefined) delete globalThis.__ztoolsElectron + else globalThis.__ztoolsElectron = prev + } +} + +test.beforeEach(() => { + host.reset() + setRuntimeLocale('zh-CN') +}) + +test('自定义扫描目录纯函数:规范化、添加去重、移除与合并去重', () => { + assert.deepEqual( + normalizeCustomScanDirs(['D:\\work\\', 'd:/work', '', 'relative/path', '/Users/dev/repos']), + ['D:\\work\\', '/Users/dev/repos'] + ) + const added1 = addCustomScanDir(['D:\\work'], 'D:\\work\\') + assert.equal(added1.added, false) + const added2 = addCustomScanDir(['D:\\work'], 'E:\\repos') + assert.equal(added2.added, true) + assert.deepEqual(added2.next, ['D:\\work', 'E:\\repos']) + assert.deepEqual(removeCustomScanDir(added2.next, 'd:/work'), ['E:\\repos']) + + assert.equal(buildEditorCliCommand('cursor', 'D:\\work\\ZTools'), 'cursor "D:\\work\\ZTools"') + assert.equal(buildEditorCliCommand('trae', '/Users/dev/my app'), 'trae "/Users/dev/my app"') + + const merged = mergeProjectsWithCustom( + [{ id: makeId('a'), path: 'D:\\work\\ZTools', name: 'ZTools', editor: 'vscode', editorName: 'VS Code', family: 'vsc', kind: 'folder', lastOpenedMs: 1000, gitBranch: 'main', pathState: 'available', pathError: null }], + [ + { id: 'custom:d:\\work\\ztools', path: 'D:\\work\\ZTools', name: 'ZTools', editor: 'vscode', editorName: '自定义目录', family: 'vsc', kind: 'folder', lastOpenedMs: null, gitBranch: null, pathState: 'available', pathError: null, isCustom: true }, + { id: 'custom:d:\\work\\new-repo', path: 'D:\\work\\new-repo', name: 'new-repo', editor: 'vscode', editorName: '自定义目录', family: 'vsc', kind: 'folder', lastOpenedMs: null, gitBranch: null, pathState: 'available', pathError: null, isCustom: true } + ] + ) + assert.deepEqual(merged.map(p => p.name), ['ZTools', 'new-repo']) + assert.equal(merged[0].isCustom, undefined, 'IDE 历史记录优先保留') + assert.equal(merged[1].isCustom, true) +}) + +test('用其他编辑器打开子菜单:命中同路径 Cursor 记录直启;未命中 Windsurf 复制 CLI 命令', async () => { + const openedIds = [] + const vsId = makeId('1') + const cursorId = makeId('2') + const restore = setupMockElectron({ + recent_projects: async ({ params }) => { + if (params.action === 'scan') { + return { + success: true, + data: { + success: true, + sourcesRead: 2, + skippedRemote: 0, + warnings: [], + projects: [ + { id: vsId, path: 'D:\\work\\ZTools', name: 'ZTools', editor: 'vscode', editorName: 'VS Code', family: 'vsc', kind: 'folder', lastOpenedMs: 2000, gitBranch: 'main', pathState: 'available', pathError: null }, + { id: cursorId, path: 'D:\\work\\ZTools', name: 'ZTools', editor: 'cursor', editorName: 'Cursor', family: 'vsc', kind: 'folder', lastOpenedMs: 1000, gitBranch: 'main', pathState: 'available', pathError: null } + ] + } + } + } + if (params.action === 'open') { + openedIds.push(params.id) + return { success: true, data: { success: true, accepted: true, id: params.id, action: 'open' } } + } + return { success: true, data: { success: true } } + } + }) + + try { + const view = await mount(() => MacProjectsCommand({ platform: 'windows' })) + await tick() + const item = view.item(vsId) + assert.ok(item) + + const actionTitles = view.actions(item).map(a => a.props.title) + assert.ok(actionTitles.includes('用 Cursor 打开')) + assert.ok(actionTitles.includes('用 Trae 打开')) + assert.ok(actionTitles.includes('用 Windsurf 打开')) + + // 1. 用 Cursor 打开:命中真实 Cursor 记录 -> 直启 cursorId + await view.run(item, '用 Cursor 打开') + assert.deepEqual(openedIds, [cursorId]) + assert.match(String(host.lastToast().title), /Cursor/) + + // 2. 用 Windsurf 打开:无历史记录 -> 复制 CLI 启动命令 + await view.run(item, '用 Windsurf 打开') + assert.equal(host.clipboard.text, 'windsurf "D:\\work\\ZTools"') + assert.match(String(host.lastToast().title), /已复制 Windsurf 打开命令/) + view.unmount() + } finally { + restore() + } +}) + +test('自定义扫描目录:LocalStorage 持久化、自动扫描合并与管理页增删', async () => { + host.storage.set(CUSTOM_SCAN_DIRS_STORAGE_KEY, JSON.stringify(['D:\\repos'])) + const restore = setupMockElectron({ + recent_projects: async ({ params }) => { + if (params.action === 'scan') { + return { + success: true, + data: { success: true, sourcesRead: 1, skippedRemote: 0, warnings: [], projects: [] } + } + } + return { success: true, data: { success: true } } + }, + filesystem_get_directory_contents: async ({ params }) => { + if (params.path === 'D:\\repos') { + return { + success: true, + data: { + success: true, + files: [ + { name: 'alpha-service', path: 'D:\\repos\\alpha-service', isDirectory: true, mtimeMs: 5000 }, + { name: 'node_modules', path: 'D:\\repos\\node_modules', isDirectory: true }, + { name: 'README.md', path: 'D:\\repos\\README.md', isDirectory: false } + ] + } + } + } + return { success: false, error: { message: 'ENOENT' } } + }, + window_show_select_folder_dialog: async () => ({ + success: true, + data: { canceled: false, folderPath: 'E:\\more-repos' } + }) + }) + + try { + const view = await mount(() => MacProjectsCommand({ platform: 'windows' })) + await tick() + assert.ok(view.items().some(i => i.props.title === 'alpha-service'), '应扫描出自定义目录下的项目') + assert.ok(!view.items().some(i => i.props.title === 'node_modules'), '应忽略 node_modules') + + // 进入管理自定义扫描目录视图 + await view.run(null, '扫描目录 (1)') + const dirView = await mountPushed(host) + assert.equal(dirView.items().length, 1) + assert.equal(dirView.items()[0].props.title, 'D:\\repos') + + // 通过目录选择器添加新目录 + await dirView.run(null, '选择文件夹添加') + await tick() + assert.deepEqual(JSON.parse(host.storage.get(CUSTOM_SCAN_DIRS_STORAGE_KEY)), ['D:\\repos', 'E:\\more-repos']) + + // 移除原目录 + await dirView.run(dirView.item('custom-dir:D:\\repos'), '移除此目录') + await tick() + assert.deepEqual(JSON.parse(host.storage.get(CUSTOM_SCAN_DIRS_STORAGE_KEY)), ['E:\\more-repos']) + + dirView.unmount() + view.unmount() + } finally { + restore() + } +}) + +test('i18n: 新增文案在 en-US 下无中文残留', () => { + setRuntimeLocale('en-US') + const keys = [ + 'actionOpenWithOther', 'actionOpenWithSpecific', 'toastCopiedEditorCmdTitle', + 'actionManageScanDirs', 'scanDirsNavTitle', 'scanDirsAddPicker', 'scanDirsAddManual' + ] + for (const key of keys) { + const text = t(key, { editor: 'Cursor', cmd: 'cursor "."', count: 2 }) + assert.ok(text.length > 0 && !/[\u4e00-\u9fa5]/.test(text), `en-US key ${key} 不应含中文: ${text}`) + } +}) diff --git a/extensions/window-manager/package.json b/extensions/window-manager/package.json index 4f32aac1..fcec69b6 100644 --- a/extensions/window-manager/package.json +++ b/extensions/window-manager/package.json @@ -1,6 +1,6 @@ { "name": "@ztools/plugin-window-manager", - "version": "1.0.0", + "version": "2.0.14", "description": "基于 Win32 原生窗口 API 枚举全部活动桌面窗口,支持一键窗口置顶 (Always on Top)、透明度调节、尺寸锁定与极速分屏贴靠", "main": "dist/index.js", "types": "dist/index.d.ts", diff --git a/extensions/window-manager/plugin.json b/extensions/window-manager/plugin.json index 57a6d3a3..897bf19d 100644 --- a/extensions/window-manager/plugin.json +++ b/extensions/window-manager/plugin.json @@ -2,7 +2,7 @@ "id": "window-manager", "name": "窗口管理", "description": "管理活动窗口的半屏、四角、三分屏、居中与跨显示器移动", - "version": "2.0.13", + "version": "2.0.14", "author": "ZTools Team", "entry": "dist/index.js", "icon": "icon.svg", diff --git a/extensions/window-manager/src/i18n.ts b/extensions/window-manager/src/i18n.ts index 8d330622..1bdce569 100644 --- a/extensions/window-manager/src/i18n.ts +++ b/extensions/window-manager/src/i18n.ts @@ -12,8 +12,28 @@ const rawT = createTranslator( actionFailedTitle: "窗口操作失败", searchPlaceholder: "搜索窗口动作:左半屏、四角、居中、显示器…", loadingSummary: "正在读取可用动作…", - availableSummary: "可用动作 {count} 项", + availableSummary: "可用动作 {count} 项 · 外边距 {outerGap}px · 内间距 {innerGap}px · 占比 {pct}%", refreshTitle: "重新读取", + preferencesTitle: "间距与占比偏好", + preferencesFormTitle: "窗口布局间距与占比偏好", + preferencesSaveAction: "保存偏好", + preferencesResetAction: "恢复默认偏好", + preferencesOuterGapLabel: "屏幕外边距 (outerGap, px)", + preferencesInnerGapLabel: "窗口内间距 (innerGap, px)", + preferencesPercentageLabel: "近似最大化占比 (50-100%)", + preferencesCycleModeLabel: "连续触发循环模式", + preferencesCycleSizes: "按比例循环切换", + preferencesCycleDisabled: "关闭循环", + preferencesNoteLabel: "持久化说明", + preferencesNoteText: "偏好已通过 LocalStorage 持久化保存,用于几何布局计算与偏好展示。", + preferencesInvalidGap: "边距必须为 0 到 120 之间的整数", + preferencesInvalidPercentage: "占比必须为 50 到 100 之间的整数", + preferencesSavedTitle: "窗口偏好已保存", + preferencesSavedMessage: "外边距 {outerGap}px · 内间距 {innerGap}px · 占比 {pct}%", + preferencesResetMessage: "已恢复默认间距与占比偏好", + preferencesSaveFailedTitle: "保存偏好失败", + directCommandTag: "no-view · {cmd}", + unboundHotkeyHint: "未绑定全局热键", filterTooltip: "按分类筛选", allActions: "全部动作", executeAction: "执行 {name}", @@ -77,8 +97,28 @@ const rawT = createTranslator( actionFailedTitle: "Window action failed", searchPlaceholder: "Search window actions: left half, quarters, center, display…", loadingSummary: "Loading available actions…", - availableSummary: "{count} available [[count:action|actions]]", + availableSummary: "{count} [[count:action|actions]] · Outer {outerGap}px · Inner {innerGap}px · Scale {pct}%", refreshTitle: "Reload", + preferencesTitle: "Gap & Scale Preferences", + preferencesFormTitle: "Window Layout Gap & Scale Preferences", + preferencesSaveAction: "Save Preferences", + preferencesResetAction: "Reset to Defaults", + preferencesOuterGapLabel: "Outer Margin (outerGap, px)", + preferencesInnerGapLabel: "Inner Gap (innerGap, px)", + preferencesPercentageLabel: "Almost-Maximize Scale (50-100%)", + preferencesCycleModeLabel: "Repeated Trigger Cycle Mode", + preferencesCycleSizes: "Cycle sizes", + preferencesCycleDisabled: "Disabled", + preferencesNoteLabel: "Persistence Note", + preferencesNoteText: "Preferences are persisted in LocalStorage for geometry calculation and layout defaults.", + preferencesInvalidGap: "Gap must be an integer between 0 and 120", + preferencesInvalidPercentage: "Scale percentage must be an integer between 50 and 100", + preferencesSavedTitle: "Window Preferences Saved", + preferencesSavedMessage: "Outer {outerGap}px · Inner {innerGap}px · Scale {pct}%", + preferencesResetMessage: "Restored default gap and scale preferences", + preferencesSaveFailedTitle: "Failed to Save Preferences", + directCommandTag: "no-view · {cmd}", + unboundHotkeyHint: "No global hotkey", filterTooltip: "Filter by category", allActions: "All Actions", executeAction: "Run {name}", diff --git a/extensions/window-manager/src/index.tsx b/extensions/window-manager/src/index.tsx index 5125cc5b..e5cba0a8 100644 --- a/extensions/window-manager/src/index.tsx +++ b/extensions/window-manager/src/index.tsx @@ -1,6 +1,26 @@ -import React, { List, ActionPanel, Action, Icon, showToast, Toast, useState, useEffect, useRef, useLocale } from "@ztools/declarative-ui"; -import { WindowActionDefinition, WindowActionCategory } from "./types.js"; -import { filterWindowActions, executeWindowAction, loadSupportedWindowActions } from "./window-actions.js"; +import React, { + List, + Form, + ActionPanel, + Action, + Icon, + showToast, + Toast, + useState, + useEffect, + useRef, + useLocale, + useNavigation +} from "@ztools/declarative-ui"; +import { WindowActionDefinition, WindowActionCategory, WindowManagementPreferences } from "./types.js"; +import { + DEFAULT_WINDOW_PREFERENCES, + filterWindowActions, + executeWindowAction, + loadSupportedWindowActions, + getWindowPreferences, + saveWindowPreferences +} from "./window-actions.js"; import { resolveErrorMessage } from "./error-i18n.js"; import { t } from "./i18n.js"; @@ -24,6 +44,38 @@ export const FEATURE_DIRECT_ACTIONS: Readonly> = { "win-next-display": "next-display" }; +export const ACTION_LAYOUT_GLYPHS: Readonly> = { + "left-half": "[==== ]", + "right-half": "[ ====]", + "top-half": "[^^^^^^^^]", + "bottom-half": "[vvvvvvvv]", + "first-third": "[=== ]", + "center-third": "[ ==== ]", + "last-third": "[ ===]", + "first-two-thirds": "[====== ]", + "last-two-thirds": "[ ======]", + "top-left": "[== / ]", + "top-right": "[ ==/ ]", + "bottom-left": "[ /== ]", + "bottom-right": "[ / ==]", + maximize: "[========]", + restore: "[<- UNDO ]", + "reasonable-size": "[ ====== ]", + center: "[ ==== ]", + "next-display": "[-> SCR2 ]", + "previous-display": "[<- SCR1 ]", + "make-larger": "[+ GROW ]", + "make-smaller": "[- SHRINK]" +}; + +const DIRECT_COMMAND_HINTS: Readonly> = { + "left-half": "win left", + "right-half": "win right", + maximize: "win max", + center: "win center", + "next-display": "win next display" +}; + export async function runDirectWindowAction( actionId: string, options: DirectWindowCommandOptions = {} @@ -80,14 +132,143 @@ const ACTION_TEXT_KEYS: Record[0]; desc: Pa "make-smaller": { name: "actionNameMakeSmaller", desc: "actionDescMakeSmaller" } }; +function parseGapInput(raw: unknown): number | null { + const num = Number(String(raw ?? "").trim()); + if (!Number.isInteger(num) || num < 0 || num > 120) return null; + return num; +} + +function parsePercentageInput(raw: unknown): number | null { + const num = Number(String(raw ?? "").trim()); + if (!Number.isInteger(num) || num < 50 || num > 100) return null; + return num; +} + +function WindowPreferencesForm(props: { + initial: WindowManagementPreferences; + onSaved: (next: WindowManagementPreferences) => void; +}) { + useLocale(); + const { pop } = useNavigation(); + const [outerGapInput, setOuterGapInput] = useState(String(props.initial.outerGap)); + const [innerGapInput, setInnerGapInput] = useState(String(props.initial.innerGap)); + const [pctInput, setPctInput] = useState(String(Math.round(props.initial.percentage * 100))); + const [cycleModeInput, setCycleModeInput] = useState<"sizes" | "disabled">(props.initial.cycleMode); + const [outerGapError, setOuterGapError] = useState(undefined); + const [innerGapError, setInnerGapError] = useState(undefined); + const [pctError, setPctError] = useState(undefined); + + const handleSubmit = async (values?: Record) => { + const outerGap = parseGapInput(values?.outerGap ?? outerGapInput); + const innerGap = parseGapInput(values?.innerGap ?? innerGapInput); + const pct = parsePercentageInput(values?.percentage ?? pctInput); + setOuterGapError(outerGap === null ? t("preferencesInvalidGap") : undefined); + setInnerGapError(innerGap === null ? t("preferencesInvalidGap") : undefined); + setPctError(pct === null ? t("preferencesInvalidPercentage") : undefined); + if (outerGap === null || innerGap === null || pct === null) return; + const rawCycle = values?.cycleMode ?? cycleModeInput; + const cycleMode = rawCycle === "disabled" ? "disabled" : "sizes"; + try { + const saved = await saveWindowPreferences({ + outerGap, + innerGap, + percentage: Number((pct / 100).toFixed(2)), + cycleMode + }); + props.onSaved(saved); + await showToast({ + style: Toast.Style.Success, + title: t("preferencesSavedTitle"), + message: t("preferencesSavedMessage", { + outerGap: saved.outerGap, + innerGap: saved.innerGap, + pct: Math.round(saved.percentage * 100) + }) + }); + pop(); + } catch (cause) { + await showToast({ + style: Toast.Style.Failure, + title: t("preferencesSaveFailedTitle"), + message: cause instanceof Error ? cause.message : String(cause) + }); + } + }; + + const handleReset = async () => { + try { + const saved = await saveWindowPreferences({ ...DEFAULT_WINDOW_PREFERENCES }); + props.onSaved(saved); + await showToast({ + style: Toast.Style.Success, + title: t("preferencesSavedTitle"), + message: t("preferencesResetMessage") + }); + pop(); + } catch (cause) { + await showToast({ + style: Toast.Style.Failure, + title: t("preferencesSaveFailedTitle"), + message: cause instanceof Error ? cause.message : String(cause) + }); + } + }; + + return ( +
+ + + + } + > + { setOuterGapInput(value); setOuterGapError(undefined); }} + /> + { setInnerGapInput(value); setInnerGapError(undefined); }} + /> + { setPctInput(value); setPctError(undefined); }} + /> + setCycleModeInput(value === "disabled" ? "disabled" : "sizes")} + > + + + + + + ); +} + /** 布局一:找到宿主支持的动作后直接执行;若通过直达 featureCode 进入则立即触发对应动作。 */ export default function WindowManagementCommand(props: WindowManagementCommandProps = {}) { useLocale(); + const { push } = useNavigation(); const [searchText, setSearchText] = useState(""); const [category, setCategory] = useState( props.featureCode === "win-display" ? "displays" : "all" ); const [actions, setActions] = useState([]); + const [preferences, setPreferences] = useState({ ...DEFAULT_WINDOW_PREFERENCES }); const [error, setError] = useState(""); const [loading, setLoading] = useState(true); const directTriggered = useRef(false); @@ -95,13 +276,19 @@ export default function WindowManagementCommand(props: WindowManagementCommandPr const reload = async () => { setLoading(true); try { - setActions(await loadSupportedWindowActions()); + const [supported, savedPrefs] = await Promise.all([ + loadSupportedWindowActions(), + getWindowPreferences() + ]); + setActions(supported); + setPreferences(savedPrefs); setError(""); } catch (cause) { setActions([]); setError(cause instanceof Error ? cause.message : String(cause)); } finally { setLoading(false); } }; + useEffect(() => { void reload(); const directActionId = props.featureCode ? FEATURE_DIRECT_ACTIONS[props.featureCode] : undefined; @@ -116,6 +303,10 @@ export default function WindowManagementCommand(props: WindowManagementCommandPr } }, [props.featureCode]); + const openPreferences = () => { + push(); + }; + const filtered = filterWindowActions(actions, { category, query: searchText }); const execute = async (item: WindowActionDefinition) => { const result = await executeWindowAction(item.id); @@ -124,12 +315,38 @@ export default function WindowManagementCommand(props: WindowManagementCommandPr const getName = (item: WindowActionDefinition) => ACTION_TEXT_KEYS[item.id] ? t(ACTION_TEXT_KEYS[item.id].name) : item.name; const getDesc = (item: WindowActionDefinition) => ACTION_TEXT_KEYS[item.id] ? t(ACTION_TEXT_KEYS[item.id].desc) : item.description; + const getDisplayTitle = (item: WindowActionDefinition) => { + const glyph = ACTION_LAYOUT_GLYPHS[item.id]; + const name = getName(item); + return glyph ? `${glyph} ${name}` : name; + }; + const getAccessories = (item: WindowActionDefinition): Array<{ text?: string; tag?: { value: string } }> => { + const directCmd = DIRECT_COMMAND_HINTS[item.id]; + if (directCmd) { + return [{ tag: { value: t("directCommandTag", { cmd: directCmd }) } }]; + } + return [{ text: t("unboundHotkeyHint") }]; + }; + + const summaryText = error || (loading + ? t("loadingSummary") + : t("availableSummary", { + count: actions.length, + outerGap: preferences.outerGap, + innerGap: preferences.innerGap, + pct: Math.round(preferences.percentage * 100) + })); return ( setCategory(value as WindowActionCategory | "all")}> @@ -142,9 +359,20 @@ export default function WindowManagementCommand(props: WindowManagementCommandPr return items.length ? {items.map(item => { const name = getName(item); - return execute(item)} />} />; + accessories={getAccessories(item)} + actions={ + + execute(item)} /> + + + } />; })} : null; })} diff --git a/extensions/window-manager/tests/window-manager.ui.test.mjs b/extensions/window-manager/tests/window-manager.ui.test.mjs index 701633cb..dd87621c 100644 --- a/extensions/window-manager/tests/window-manager.ui.test.mjs +++ b/extensions/window-manager/tests/window-manager.ui.test.mjs @@ -4,7 +4,7 @@ import fs from 'node:fs' import path from 'node:path' import { fileURLToPath } from 'node:url' import { Toast } from '@ztools/declarative-ui' -import { createHost, mount, tick } from '../../shared/test-harness.mjs' +import { createHost, mount, mountPushed, tick } from '../../shared/test-harness.mjs' import WindowManagementCommand, { WINDOW_ACTIONS, commands } from '../dist/index.js' const __dirname = path.dirname(fileURLToPath(import.meta.url)) @@ -28,13 +28,42 @@ test('窗口列表:宿主拒绝执行时显示失败原因,绝不静默报 } finally { view.unmount() } }) -test('窗口列表只展示宿主支持动作,没有无法兑现的偏好与虚构快捷键', async () => { +test('窗口列表只展示宿主支持动作,包含 ASCII 布局比例标识与直达命令提示,不虚构不支持动作', async () => { host.ipc.window_manage_list_actions = async () => [{ name: 'left-half' }, { name: 'top-left' }, { name: 'next-display' }, { name: 'center-half' }] const view = await mount(WindowManagementCommand) try { assert.deepEqual(view.items().map(item => item.props.id), ['left-half', 'top-left', 'next-display']) - for (const item of view.items()) assert.equal(view.actions(item).length, 1) - assert.doesNotMatch(JSON.stringify(view.tree()), /边距|快捷键|sixths|center-half/) + assert.match(view.item('left-half').props.title, /^\[====\s+\]/) + assert.match(view.item('next-display').props.title, /^\[-> SCR2 \]/) + assert.equal(view.item('left-half').props.accessories[0].tag.value, 'no-view · win left') + assert.equal(view.item('top-left').props.accessories[0].text, '未绑定全局热键') + assert.doesNotMatch(JSON.stringify(view.tree()), /sixths|center-half/) + } finally { view.unmount() } +}) + +test('间距与占比偏好持久化:通过 UI 表单修改并持久保存,重载后继续生效,声明 Win+macOS 双端', async () => { + assert.ok(manifest.targets.some(t => t.id === 'windows-electron-any')) + assert.ok(manifest.targets.some(t => t.id === 'macos-electron-any')) + const view = await mount(WindowManagementCommand) + try { + assert.match(view.tree().props.filterBar.summaryText, /外边距 0px · 内间距 0px · 占比 90%/) + const prefBtn = view.tree().props.filterBar.actions.find(a => a.id === 'preferences') + assert.ok(prefBtn) + prefBtn.onAction() + await tick() + const form = await mountPushed(host) + try { + await form.fill('outerGap', '12') + await form.fill('innerGap', '8') + await form.fill('percentage', '85') + await form.fill('cycleMode', 'disabled') + await form.run(null, '保存偏好') + await tick() + } finally { form.unmount() } + assert.match(view.tree().props.filterBar.summaryText, /外边距 12px · 内间距 8px · 占比 85%/) + const raw = host.storage.get('ztools-window-management-preferences-v1') + assert.ok(raw) + assert.deepEqual(JSON.parse(raw), { outerGap: 12, innerGap: 8, percentage: 0.85, cycleMode: 'disabled' }) } finally { view.unmount() } }) diff --git a/scripts/deploy-plugins-storage.mjs b/scripts/deploy-plugins-storage.mjs index 6e6528ed..d3f7416e 100644 --- a/scripts/deploy-plugins-storage.mjs +++ b/scripts/deploy-plugins-storage.mjs @@ -52,8 +52,9 @@ export function loadEnvFile(envPath) { return env } -// 自动预加载本地环境变量 -loadEnvFile() +// 自动预加载本地环境变量:优先级 外部显式环境变量 > .env.local > .env(避免被根目录 .env 占位符屏蔽) +loadEnvFile(path.join(rootDir, '.env.local')) +loadEnvFile(path.join(rootDir, '.env')) // 存储桶与地域由环境变量 OSS_BUCKET / OSS_REGION 注入(演练模式未传时使用占位值) export const DEFAULT_CDN_BASE_URL = 'https://cdn.ztools.cn' @@ -843,6 +844,9 @@ export async function deployPluginsStorage(options = {}) { if (!ossConfig.accessKeyId || !ossConfig.accessKeySecret) { throw new Error('缺少阿里云 OSS 凭证 (OSS_ACCESS_KEY_ID / OSS_ACCESS_KEY_SECRET),已停止上传。仅想演练请加 --dry-run') } + if (!dryRun && (!/^[\x21-\x7E]+$/.test(ossConfig.accessKeyId) || !/^[\x21-\x7E]+$/.test(ossConfig.accessKeySecret))) { + throw new Error('阿里云 OSS 凭证包含非法字符或未替换的占位文本,请检查 .env.local 或环境变量 OSS_ACCESS_KEY_ID / OSS_ACCESS_KEY_SECRET') + } if (!ossConfig.bucket || (!ossConfig.region && !ossConfig.endpoint)) { throw new Error('缺少阿里云 OSS 存储桶配置 (OSS_BUCKET / OSS_REGION),已停止上传。仅想演练请加 --dry-run') }