import embeddedCatalog from "../../../specs/docs-catalog.json" with { type: "json" }; import { getGlobalCache } from "../../core/cache/index.js"; import { fetchLiveDocsCatalog } from "./api.js"; import type { DocCatalog, DocCategoryInfo, DocSearchQuery, DocSearchResult, OpenApiDocItem, } from "./types.js"; const CACHE_KEY = "docs:catalog:v1"; const CACHE_TTL_MS = 24 * 60 * 60 * 1000; // 24小时缓存 /** * 获取接口文档目录(具备实时拉取 + L1/L2 缓存 + 静态内嵌保底能力) */ export async function getDocsCatalog(options?: { forceRefresh?: boolean; baseUrl?: string; }): Promise { const cache = getGlobalCache(); if (!options?.forceRefresh) { const cached = cache.get(CACHE_KEY, "docs"); if (cached && Array.isArray(cached.items) && cached.items.length > 0) { return cached; } } // 尝试从线上获取最新规范 try { const liveCatalog = await fetchLiveDocsCatalog({ baseUrl: options?.baseUrl }); cache.set(CACHE_KEY, liveCatalog, { ttlMs: CACHE_TTL_MS, namespace: "docs", }); return liveCatalog; } catch (error) { // 若强制刷新失败且存在历史缓存,则返回历史缓存 const cached = cache.get(CACHE_KEY, "docs"); if (cached && Array.isArray(cached.items) && cached.items.length > 0) { return cached; } // 线上无法连通且无历史缓存时,安全降级至本地内嵌预编译规格 return embeddedCatalog as unknown as DocCatalog; } } /** * 计算文档项与搜索关键词的相关度得分,并生成高亮命中摘要 */ 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 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(); // 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 += 100; matchReasons.push("标题完全匹配"); } else if (titleLower.includes(queryLower)) { score += 60; matchReasons.push(`标题包含 "${queryLower}"`); } if (categoryLower.includes(queryLower)) { score += 40; matchReasons.push(`模块: ${item.category}`); } 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}...`); } 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}...`); } } // 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, }; } /** * 搜索开放平台接口与指南文档 */ export async function searchDocs( query: DocSearchQuery = {}, options?: { forceRefresh?: boolean; baseUrl?: string } ): Promise { const catalog = await getDocsCatalog(options); let items = catalog.items; // 1. 分类过滤 if (query.category) { const catLower = query.category.trim().toLowerCase(); items = items.filter((item) => item.category.toLowerCase().includes(catLower) ); } // 2. HTTP 方法过滤 if (query.method) { const methodUpper = query.method.trim().toUpperCase(); items = items.filter((item) => item.method === methodUpper); } // 3. 接口路径匹配过滤 if (query.path) { const pathLower = query.path.trim().toLowerCase(); items = items.filter((item) => (item.path || "").toLowerCase().includes(pathLower) ); } // 4. 关键词打分与排序 const rawKeyword = query.keyword?.trim(); if (rawKeyword) { const scored = items .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); } const total = items.length; const limit = Math.max(1, Math.min(query.limit ?? 20, 100)); const pagedItems = items.slice(0, limit); return { total, keyword: rawKeyword, category: query.category, method: query.method, items: pagedItems, }; } /** * 按 ID、Path、URL 或文档标题精确解析单篇文档详情 */ export async function getDocDetail( target: string, options?: { forceRefresh?: boolean; baseUrl?: string } ): Promise { const catalog = await getDocsCatalog(options); const cleanTarget = target.trim(); if (!cleanTarget) return undefined; const targetLower = cleanTarget.toLowerCase(); // 1. 按数字 ID 精确查找 const idNum = Number(cleanTarget); if (!Number.isNaN(idNum)) { const byId = catalog.items.find((item) => item.id === idNum); if (byId) return byId; } // 2. 按接口 Path 精确查找 (如 /api/openapi/v1/roleDefGroups) const byExactPath = catalog.items.find( (item) => (item.path || "").toLowerCase() === targetLower ); if (byExactPath) return byExactPath; // 3. 按文档 URL 精确查找 (如 /docs/open-api/corporation/get-roles-group) const byExactUrl = catalog.items.find( (item) => item.url.toLowerCase() === targetLower ); if (byExactUrl) return byExactUrl; // 4. 按标题精确查找 const byExactTitle = catalog.items.find( (item) => item.title.toLowerCase() === targetLower ); if (byExactTitle) return byExactTitle; // 5. 模糊前缀/子串匹配(取最相似的第一个) return ( catalog.items.find((item) => (item.path || "").toLowerCase().includes(targetLower)) || catalog.items.find((item) => item.url.toLowerCase().includes(targetLower)) || catalog.items.find((item) => item.title.toLowerCase().includes(targetLower)) ); } /** * 获取开放平台所有业务模块分类与文档数量汇总 */ export async function listCategories(options?: { forceRefresh?: boolean; baseUrl?: string; }): Promise { const catalog = await getDocsCatalog(options); const map = new Map(); for (const item of catalog.items) { const cat = item.category || "未分类"; const current = map.get(cat) || { count: 0, endpointsCount: 0 }; current.count += 1; if (item.method && item.path) { current.endpointsCount += 1; } map.set(cat, current); } const result: DocCategoryInfo[] = []; for (const [name, stats] of map.entries()) { result.push({ name, count: stats.count, endpointsCount: stats.endpointsCount, }); } return result.sort((a, b) => b.count - a.count); } /** * 手动强制同步线上文档中心索引并重载本地持久化缓存 */ export async function syncDocsCatalog(options?: { baseUrl?: string; }): Promise<{ success: boolean; totalDocs: number; totalEndpoints: number; source: string; updatedAt: string; }> { const catalog = await getDocsCatalog({ forceRefresh: true, baseUrl: options?.baseUrl, }); return { success: true, totalDocs: catalog.totalDocs, totalEndpoints: catalog.totalEndpoints, source: catalog.sourceUrl, updatedAt: catalog.updatedAt, }; }