From 6ba748e531ae5e479c5702fdd07f9fc1689c1c25 Mon Sep 17 00:00:00 2001 From: yunyingk Date: Mon, 16 Nov 2026 16:42:43 +0800 Subject: [PATCH] =?UTF-8?q?feat(docs):=20=E6=94=AF=E6=8C=81=E5=A4=9A?= =?UTF-8?q?=E8=AF=8D=E5=88=86=E8=AF=8D=E6=A8=A1=E7=B3=8A=E6=A3=80=E7=B4=A2?= =?UTF-8?q?=E4=B8=8E=E5=8C=B9=E9=85=8D=E4=BE=9D=E6=8D=AE=E7=89=87=E6=AE=B5?= =?UTF-8?q?=E9=AB=98=E4=BA=AE=E5=B1=95=E7=A4=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 增强 `src/domains/docs/tools.ts` 的搜索评分引擎,支持自然多词组合与分词(如 "员工 手机"、"报销 审批") - 扩充正文段落、请求参数表格、返回报文 JSON 与 CURL 示例的多层级深度匹配 - 新增 `matchReason` 匹配依据与上下文片段(Snippet)生成,在 CLI 表格及 JSON 结果中清晰呈现命中理由 - 完善 `src/domains/docs/docs.test.ts` 跨正文分词检索测试用例 --- src/cli/commands/docs.ts | 26 ++++-- src/domains/docs/docs.test.ts | 8 ++ src/domains/docs/tools.ts | 156 ++++++++++++++++++++++++++++------ src/domains/docs/types.ts | 1 + 4 files changed, 157 insertions(+), 34 deletions(-) diff --git a/src/cli/commands/docs.ts b/src/cli/commands/docs.ts index dbbd248..f42287c 100644 --- a/src/cli/commands/docs.ts +++ b/src/cli/commands/docs.ts @@ -182,6 +182,7 @@ export async function handleDocsCommand( path: item.path, url: item.url, permalink: item.permalink, + matchReason: item.matchReason || undefined, })); return { stdout: printJson( @@ -208,14 +209,25 @@ export async function handleDocsCommand( }; } - const rows = searchRes.items.map((item) => [ - item.method || "DOC", - item.path || item.url, - item.title, - item.category, - ]); + const hasKeyword = Boolean(keyword); + const headers = hasKeyword + ? ["Method", "Path / URL", "标题", "分类", "匹配依据"] + : ["Method", "Path / URL", "标题", "分类"]; - const table = printTable(["Method", "Path / URL", "标题", "分类"], rows); + const rows = searchRes.items.map((item) => { + const base = [ + item.method || "DOC", + item.path || item.url, + item.title, + item.category, + ]; + if (hasKeyword) { + base.push(item.matchReason || "-"); + } + return base; + }); + + const table = printTable(headers, rows); const filterDesc = [ keyword ? `关键词: '${keyword}'` : "", category ? `分类: '${category}'` : "", diff --git a/src/domains/docs/docs.test.ts b/src/domains/docs/docs.test.ts index 5884112..9520bea 100644 --- a/src/domains/docs/docs.test.ts +++ b/src/domains/docs/docs.test.ts @@ -109,6 +109,14 @@ describe("Docs Domain - 开放平台文档域", () => { expect(res.total).toBeGreaterThanOrEqual(1); expect(res.items[0]?.path).toBe("/api/openapi/v1/roleDefGroups"); expect(res.items[0]?.title).toBe("查询角色组和角色"); + expect(res.items[0]?.matchReason).toBeDefined(); + }); + + it("searchDocs 支持多词分词与跨正文/参数模糊检索", async () => { + const res = await searchDocs({ keyword: "员工 手机" }); + expect(res.total).toBeGreaterThanOrEqual(1); + expect(res.items.some((i) => i.title.includes("员工"))).toBe(true); + expect(res.items[0]?.matchReason).toBeDefined(); }); it("searchDocs 支持按分类与 HTTP 方法精确过滤", async () => { diff --git a/src/domains/docs/tools.ts b/src/domains/docs/tools.ts index c0b69ad..a935ad4 100644 --- a/src/domains/docs/tools.ts +++ b/src/domains/docs/tools.ts @@ -49,43 +49,146 @@ export async function getDocsCatalog(options?: { } /** - * 计算文档项与搜索关键词的相关度得分 + * 计算文档项与搜索关键词的相关度得分,并生成高亮命中摘要 */ -function scoreDocItem(item: OpenApiDocItem, queryLower: string): number { +function evaluateDocMatch( + item: OpenApiDocItem, + rawKeyword: string +): { item: OpenApiDocItem; score: number } | null { + const queryLower = rawKeyword.trim().toLowerCase(); + if (!queryLower) return null; + + const tokens = queryLower.split(/[\s,+/]+/).filter(Boolean); + if (tokens.length === 0) return null; + let score = 0; + const matchReasons: string[] = []; + const pathLower = (item.path || "").toLowerCase(); const titleLower = item.title.toLowerCase(); const categoryLower = item.category.toLowerCase(); - const urlLower = item.url.toLowerCase(); + const paramLower = (item.parameters || "").toLowerCase(); + const curlLower = (item.curl || "").toLowerCase(); + const respLower = (item.responseSample || "").toLowerCase(); + const allSectionsText = item.sections.map((s) => s.content).join(" "); + const sectionsLower = allSectionsText.toLowerCase(); - // 路径完全匹配 - if (pathLower === queryLower) score += 100; - else if (pathLower.includes(queryLower)) score += 60; + // 1. 完整短语匹配加分 (Phrase match) + if (queryLower.length > 1) { + if (pathLower === queryLower) { + score += 120; + matchReasons.push("路径完全匹配"); + } else if (pathLower.includes(queryLower)) { + score += 80; + matchReasons.push(`路径包含 "${queryLower}"`); + } - // 标题完全匹配或包含 - if (titleLower === queryLower) score += 80; - else if (titleLower.includes(queryLower)) score += 40; + if (titleLower === queryLower) { + score += 100; + matchReasons.push("标题完全匹配"); + } else if (titleLower.includes(queryLower)) { + score += 60; + matchReasons.push(`标题包含 "${queryLower}"`); + } - // 分类完全匹配或包含 - if (categoryLower === queryLower) score += 50; - else if (categoryLower.includes(queryLower)) score += 20; + if (categoryLower.includes(queryLower)) { + score += 40; + matchReasons.push(`模块: ${item.category}`); + } - // URL 路径包含 - if (urlLower.includes(queryLower)) score += 30; + if (paramLower.includes(queryLower)) { + score += 45; + const idx = paramLower.indexOf(queryLower); + const snippet = (item.parameters || "") + .substring(Math.max(0, idx - 12), Math.min(item.parameters?.length || 0, idx + 30)) + .replace(/\s+/g, " "); + matchReasons.push(`参数规格: ...${snippet}...`); + } - // CURL 或参数定义中出现 - if (item.curl && item.curl.toLowerCase().includes(queryLower)) score += 25; - if (item.parameters && item.parameters.toLowerCase().includes(queryLower)) score += 20; - - // 正文段落包含 - for (const s of item.sections) { - if (s.content.toLowerCase().includes(queryLower)) { - score += 10; - break; + if (sectionsLower.includes(queryLower)) { + score += 35; + const idx = sectionsLower.indexOf(queryLower); + const snippet = allSectionsText + .substring(Math.max(0, idx - 12), Math.min(allSectionsText.length, idx + 30)) + .replace(/\s+/g, " "); + matchReasons.push(`正文段落: ...${snippet}...`); } } - return score; + // 2. Token 分词逐项匹配 (Multi-token match) + let tokensMatched = 0; + for (const token of tokens) { + let tokenMatched = false; + + if (pathLower.includes(token)) { + score += 30; + tokenMatched = true; + if (!matchReasons.some((r) => r.includes(token))) { + matchReasons.push(`路径含 "${token}"`); + } + } + if (titleLower.includes(token)) { + score += 25; + tokenMatched = true; + if (!matchReasons.some((r) => r.includes(token))) { + matchReasons.push(`标题含 "${token}"`); + } + } + if (categoryLower.includes(token)) { + score += 20; + tokenMatched = true; + if (!matchReasons.some((r) => r.includes(token))) { + matchReasons.push(`分类含 "${token}"`); + } + } + if (paramLower.includes(token)) { + score += 20; + tokenMatched = true; + if (!matchReasons.some((r) => r.includes(token))) { + const idx = paramLower.indexOf(token); + const snippet = (item.parameters || "") + .substring(Math.max(0, idx - 10), Math.min(item.parameters?.length || 0, idx + 25)) + .replace(/\s+/g, " "); + matchReasons.push(`参数: ...${snippet}...`); + } + } + if (sectionsLower.includes(token)) { + score += 15; + tokenMatched = true; + if (!matchReasons.some((r) => r.includes(token))) { + const idx = sectionsLower.indexOf(token); + const snippet = allSectionsText + .substring(Math.max(0, idx - 10), Math.min(allSectionsText.length, idx + 25)) + .replace(/\s+/g, " "); + matchReasons.push(`正文: ...${snippet}...`); + } + } + if (curlLower.includes(token) || respLower.includes(token)) { + score += 15; + tokenMatched = true; + if (!matchReasons.some((r) => r.includes(token))) { + matchReasons.push(`请求/响应含 "${token}"`); + } + } + + if (tokenMatched) tokensMatched++; + } + + // 多词全部命中奖励 (All-tokens match bonus) + if (tokens.length > 1 && tokensMatched === tokens.length) { + score += 50; + } + + if (score <= 0 || tokensMatched === 0) return null; + + const matchReason = matchReasons.slice(0, 2).join(" | "); + return { + item: { + ...item, + matchReason, + }, + score, + }; } /** @@ -123,10 +226,9 @@ export async function searchDocs( // 4. 关键词打分与排序 const rawKeyword = query.keyword?.trim(); if (rawKeyword) { - const keywordLower = rawKeyword.toLowerCase(); const scored = items - .map((item) => ({ item, score: scoreDocItem(item, keywordLower) })) - .filter((entry) => entry.score > 0) + .map((item) => evaluateDocMatch(item, rawKeyword)) + .filter((entry): entry is { item: OpenApiDocItem; score: number } => entry !== null) .sort((a, b) => b.score - a.score); items = scored.map((entry) => entry.item); diff --git a/src/domains/docs/types.ts b/src/domains/docs/types.ts index 6c3ebd1..dc990f7 100644 --- a/src/domains/docs/types.ts +++ b/src/domains/docs/types.ts @@ -19,6 +19,7 @@ export const OpenApiDocItemSchema = z.object({ parameters: z.string().optional(), curl: z.string().optional(), responseSample: z.string().optional(), + matchReason: z.string().optional(), }); export const DocCatalogSchema = z.object({