Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 | import * as fs from 'node:fs' import * as path from 'node:path' import AdmZip from 'adm-zip' import fetch from 'node-fetch' import * as vscode from 'vscode' import { logger } from '../utils/logger-adapter' // 分析结果接口 export interface WorkspaceAnalysisResult { projectStructure: Array<{ path: string type: 'file' | 'directory' name: string extension?: string size?: number analysis: string }> summary: string analysisStats: { totalDirectories: number analyzedDirectories: number analysisTime: number inputMethod: string isTemporaryProject: boolean analyzedPath: string // 添加实际分析的路径信息 } } // 缓存的分析结果 export interface CachedAnalysisResult { workspacePath: string workspaceName: string sourcePath: string // 添加源码路径信息 analysis: WorkspaceAnalysisResult timestamp: number hash: string // 工作区内容哈希,用于检测变化 } export class WorkspaceAnalysisService { private readonly cacheKey = 'dalidev-workspace-analysis' private readonly maxAge = 365 * 24 * 60 * 60 * 1000 // 1年缓存 constructor(private context: vscode.ExtensionContext) {} /** * 分析工作区源码目录 */ async analyzeWorkspace(): Promise<WorkspaceAnalysisResult> { const workspaceFolder = vscode.workspace.workspaceFolders?.[0] if (!workspaceFolder) { throw new Error('未找到工作区文件夹') } const workspacePath = workspaceFolder.uri.fsPath const workspaceName = workspaceFolder.name // 智能检测源码目录 const sourcePath = await this.detectSourceDirectory(workspacePath) logger.info(`开始分析工作区源码: ${workspaceName} -> ${sourcePath}`) // 检查缓存 const cachedResult = await this.getCachedAnalysis(workspacePath, sourcePath) if (cachedResult) { logger.info('使用缓存的分析结果') return cachedResult.analysis } // 创建源码目录 zip 文件 const zipBuffer = await this.createSourceZip(sourcePath) // 调用后端分析接口 const analysisResult = await this.callAnalysisAPI(zipBuffer, sourcePath) // 缓存结果 await this.cacheAnalysisResult(workspacePath, workspaceName, sourcePath, analysisResult) logger.info('工作区源码分析完成') return analysisResult } /** * 智能检测源码目录 */ private async detectSourceDirectory(workspacePath: string): Promise<string> { logger.info(`开始检测工作区源码目录: ${workspacePath}`) // 常见的源码目录名称,按优先级排序 const commonSourceDirs = [ 'src', 'source', 'lib', 'app', 'client', 'frontend', 'web', 'packages/web/src', 'packages/client/src', ] // 检查是否存在这些目录 for (const dir of commonSourceDirs) { const fullPath = path.join(workspacePath, dir) if (fs.existsSync(fullPath) && fs.statSync(fullPath).isDirectory()) { logger.info(`检测到源码目录: ${dir}`) return fullPath } } logger.info('未找到常见源码目录,尝试从配置文件推断...') // 如果没有找到常见的源码目录,检查是否有 package.json const packageJsonPath = path.join(workspacePath, 'package.json') if (fs.existsSync(packageJsonPath)) { try { const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')) // 检查 main 字段指向的目录 if (packageJson.main) { const mainDir = path.dirname(path.resolve(workspacePath, packageJson.main)) if (fs.existsSync(mainDir) && mainDir !== workspacePath) { logger.info(`从 package.json main 字段检测到源码目录: ${path.relative(workspacePath, mainDir)}`) return mainDir } } // 检查是否有 TypeScript 配置 const tsconfigPath = path.join(workspacePath, 'tsconfig.json') if (fs.existsSync(tsconfigPath)) { try { const tsconfig = JSON.parse(fs.readFileSync(tsconfigPath, 'utf8')) if (tsconfig.compilerOptions?.rootDir) { const rootDir = path.resolve(workspacePath, tsconfig.compilerOptions.rootDir) if (fs.existsSync(rootDir)) { logger.info(`从 tsconfig.json 检测到源码目录: ${path.relative(workspacePath, rootDir)}`) return rootDir } } } catch (error) { logger.warn('解析 tsconfig.json 失败:', error) } } } catch (error) { logger.warn('解析 package.json 失败:', error) } } logger.info('配置文件推断失败,使用源码文件统计分析...') // 如果都没有找到,寻找包含最多 .js/.ts/.vue 文件的目录 const candidateDirs = fs.readdirSync(workspacePath) .filter((item) => { const fullPath = path.join(workspacePath, item) return fs.statSync(fullPath).isDirectory() && !this.shouldIgnoreDirectory(item) }) logger.info(`候选目录: ${candidateDirs.join(', ')}`) let bestDir = workspacePath let maxSourceFiles = 0 for (const dir of candidateDirs) { const fullPath = path.join(workspacePath, dir) const sourceFileCount = await this.countSourceFiles(fullPath) logger.info(`目录 ${dir} 包含 ${sourceFileCount} 个源码文件`) if (sourceFileCount > maxSourceFiles) { maxSourceFiles = sourceFileCount bestDir = fullPath } } if (bestDir !== workspacePath) { logger.info(`通过源码文件数量检测到源码目录: ${path.relative(workspacePath, bestDir)} (${maxSourceFiles} 个源码文件)`) return bestDir } // 最后默认返回工作区根目录 logger.info('未检测到明确的源码目录,使用工作区根目录') return workspacePath } /** * 统计目录中的源码文件数量 */ private async countSourceFiles(dirPath: string, maxDepth: number = 3): Promise<number> { if (maxDepth <= 0) return 0 try { const items = fs.readdirSync(dirPath) let count = 0 for (const item of items) { if (this.shouldIgnoreFile(item, [])) continue const fullPath = path.join(dirPath, item) const stats = fs.statSync(fullPath) if (stats.isFile() && this.isSourceFile(item)) { count++ } else if (stats.isDirectory() && !this.shouldIgnoreDirectory(item)) { count += await this.countSourceFiles(fullPath, maxDepth - 1) } } return count } catch (error) { return 0 } } /** * 判断是否为源码文件 */ private isSourceFile(fileName: string): boolean { const sourceExtensions = [ '.js', '.ts', '.jsx', '.tsx', '.vue', '.py', '.java', '.cpp', '.c', '.cs', '.go', '.php', '.rb', '.css', '.scss', '.less', '.sass', '.html', '.htm', ] const ext = path.extname(fileName).toLowerCase() return sourceExtensions.includes(ext) } /** * 判断是否应该忽略的目录 */ private shouldIgnoreDirectory(dirName: string): boolean { const ignoreDirs = [ 'node_modules', '.git', 'dist', 'build', '.next', '.nuxt', '.vscode', '.idea', 'coverage', '.nyc_output', 'logs', 'tmp', 'temp', ] return ignoreDirs.includes(dirName) || dirName.startsWith('.') } /** * 创建源码目录 zip 文件(排除 .gitignore 中的文件) */ private async createSourceZip(sourcePath: string): Promise<Buffer> { logger.info(`开始打包源码目录: ${sourcePath}`) const zip = new AdmZip() const workspacePath = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath || path.dirname(sourcePath) const gitignorePatterns = await this.parseGitignore(workspacePath) logger.info(`Gitignore patterns: ${gitignorePatterns.length} 条规则`) // 递归添加源码文件到 zip,使用相对于源码目录的路径 await this.addDirectoryToZip(zip, sourcePath, '', gitignorePatterns) // 检查zip文件中的条目 const entries = zip.getEntries() logger.info(`Zip文件包含 ${entries.length} 个文件`) if (entries.length === 0) { throw new Error('没有找到源码文件进行打包,请检查源码目录结构') } // 记录前几个文件名,用于调试 const sampleFiles = entries.slice(0, 5).map(entry => entry.entryName).join(', ') logger.info(`示例文件: ${sampleFiles}`) const zipBuffer = zip.toBuffer() logger.info(`源码打包完成,大小: ${(zipBuffer.length / 1024 / 1024).toFixed(2)} MB`) if (zipBuffer.length === 0) { throw new Error('生成的zip文件为空') } // 验证zip文件的有效性 try { const testZip = new AdmZip(zipBuffer) const testEntries = testZip.getEntries() logger.info(`Zip文件验证成功,包含 ${testEntries.length} 个条目`) } catch (error) { logger.error('Zip文件验证失败:', error) throw new Error(`生成的zip文件无效: ${error}`) } return zipBuffer } /** * 解析 .gitignore 文件 */ private async parseGitignore(workspacePath: string): Promise<string[]> { const gitignorePath = path.join(workspacePath, '.gitignore') const defaultIgnorePatterns = [ 'node_modules/**', '.git/**', 'dist/**', 'build/**', '.vscode/**', '.idea/**', '*.log', '.DS_Store', 'Thumbs.db', '.env*', '.dalidev-templates/**', // 排除我们自己的模板缓存目录 // 源码分析时也要排除的文件 '*.min.js', '*.min.css', 'package-lock.json', 'yarn.lock', 'pnpm-lock.yaml', ] try { if (fs.existsSync(gitignorePath)) { const gitignoreContent = fs.readFileSync(gitignorePath, 'utf8') const patterns = gitignoreContent .split('\n') .map(line => line.trim()) .filter(line => line && !line.startsWith('#')) .map((pattern) => { // 转换 gitignore 模式为简单匹配模式 if (pattern.endsWith('/')) { return `${pattern}**` } return pattern }) return [...defaultIgnorePatterns, ...patterns] } } catch (error) { logger.warn('解析 .gitignore 文件失败:', error) } return defaultIgnorePatterns } /** * 检查文件是否应该被忽略 */ private shouldIgnoreFile(filePath: string, patterns: string[]): boolean { // 额外的源码分析过滤规则 const fileName = path.basename(filePath) // 忽略隐藏文件(除了某些重要文件) if (fileName.startsWith('.') && !['/.gitignore', '/.eslintrc', '/.prettierrc'].some(f => filePath.endsWith(f))) { return true } // 先检查是否是源码文件或重要配置文件,如果是则不忽略 if (this.isSourceFile(fileName) || this.isImportantConfigFile(fileName)) { return false } // 忽略非源码文件 const nonSourceFiles = ['.md', '.txt', '.yaml', '.yml', '.xml', '.svg', '.png', '.jpg', '.jpeg', '.gif', '.ico'] const ext = path.extname(fileName).toLowerCase() if (nonSourceFiles.includes(ext)) { return true } // 使用简单的模式匹配 for (const pattern of patterns) { if (this.matchPattern(filePath, pattern)) { return true } } return false } /** * 简单的模式匹配实现 */ private matchPattern(filePath: string, pattern: string): boolean { // 处理 ** 通配符 if (pattern.includes('**')) { const regexPattern = pattern .replace(/\*\*/g, '.*') .replace(/\*/g, '[^/]*') .replace(/\?/g, '[^/]') const regex = new RegExp(`^${regexPattern}$`) return regex.test(filePath) } // 处理普通通配符 const regexPattern = pattern .replace(/\*/g, '[^/]*') .replace(/\?/g, '[^/]') const regex = new RegExp(`^${regexPattern}$`) return regex.test(filePath) || filePath.includes(pattern) } /** * 递归添加目录到 zip */ private async addDirectoryToZip( zip: AdmZip, basePath: string, relativePath: string, ignorePatterns: string[], ): Promise<void> { const fullPath = path.join(basePath, relativePath) try { const stats = fs.statSync(fullPath) if (stats.isDirectory()) { const items = fs.readdirSync(fullPath) logger.debug(`处理目录: ${fullPath}, 包含 ${items.length} 个项目`) for (const item of items) { const itemRelativePath = relativePath ? path.join(relativePath, item) : item const normalizedPath = itemRelativePath.replace(/\\/g, '/') // 统一使用正斜杠 // 检查是否应该忽略此文件/目录 if (this.shouldIgnoreFile(normalizedPath, ignorePatterns)) { logger.debug(`忽略文件: ${normalizedPath}`) continue } await this.addDirectoryToZip(zip, basePath, itemRelativePath, ignorePatterns) } } else if (stats.isFile()) { const fileName = path.basename(fullPath) // 只添加源码文件到 zip if (this.isSourceFile(fileName) || this.isImportantConfigFile(fileName)) { const fileContent = fs.readFileSync(fullPath) const zipPath = relativePath.replace(/\\/g, '/') zip.addFile(zipPath, fileContent) logger.debug(`添加源码文件: ${zipPath} (${fileContent.length} bytes)`) } else { logger.debug(`跳过非源码文件: ${fileName}`) } } } catch (error) { logger.warn(`处理文件失败 ${fullPath}:`, error) } } /** * 判断是否为重要的配置文件 */ private isImportantConfigFile(fileName: string): boolean { const importantFiles = [ 'package.json', 'tsconfig.json', 'vite.config.ts', 'vite.config.js', 'vue.config.js', 'nuxt.config.ts', 'nuxt.config.js', 'next.config.js', '.eslintrc.js', '.eslintrc.json', 'prettier.config.js', 'tailwind.config.js', 'webpack.config.js', 'rollup.config.js', 'babel.config.js', ] return importantFiles.includes(fileName) } /** * 调用后端分析 API */ private async callAnalysisAPI(zipBuffer: Buffer, sourcePath: string): Promise<WorkspaceAnalysisResult> { logger.info('调用后端分析接口...') // 获取后端 API 地址 const webUrl = vscode.workspace.getConfiguration('dalidev').get<string>('webUrl', 'http://localhost:8099') const apiUrl = `${webUrl.replace(/\/$/, '')}/cms-server/dalidev/analyze-frontend-overview` logger.info(`API URL: ${apiUrl}`) logger.info(`Zip buffer size: ${zipBuffer.length} bytes`) // 先测试后端连接 try { logger.info('测试后端服务连接...') const testUrl = `${webUrl.replace(/\/$/, '')}/cms-server/health` // 简单的健康检查 const testResponse = await fetch(testUrl, { method: 'GET', timeout: 5000, } as any) logger.info(`后端连接测试: ${testResponse.status}`) } catch (testError) { logger.warn('后端连接测试失败,但继续尝试分析接口:', testError) } try { const FormData = require('form-data') // 验证zipBuffer不为空 if (!zipBuffer || zipBuffer.length === 0) { throw new Error('Zip buffer is empty') } logger.info(`准备创建FormData,zipBuffer大小: ${zipBuffer.length} bytes`) const formData = new FormData() // 添加zip文件,使用更兼容的方式 formData.append('zipFile', zipBuffer, { filename: 'source-code.zip', contentType: 'application/zip', }) logger.info('已添加zipFile到FormData') // 添加其他参数 - 源码分析可以深度一些 formData.append('maxDepth', '3') logger.info('已添加maxDepth参数到FormData') // 获取FormData的headers(包含正确的Content-Type和boundary) const headers = formData.getHeaders() // 手动计算Content-Length,因为某些版本的form-data不会自动设置 return new Promise<WorkspaceAnalysisResult>((resolve, reject) => { formData.getLength((err: any, length: number) => { if (err) { logger.warn('无法获取FormData长度,使用默认方式:', err) } else { headers['content-length'] = length.toString() logger.info(`手动设置Content-Length: ${length} bytes`) } logger.info('发送请求到后端...') logger.info(`Content-Type: ${headers['content-type']}`) logger.info(`Content-Length: ${headers['content-length'] || 'auto'}`) console.log('Final Headers:', headers) // 发送请求,增加更详细的错误处理 fetch(apiUrl, { method: 'POST', body: formData, headers, timeout: 120000, // 增加到2分钟超时 } as any) .then(async (response) => { logger.info(`Response status: ${response.status}`) logger.info(`Response headers:`, response.headers.raw()) if (!response.ok) { const errorText = await response.text() logger.error(`Response error (${response.status}): ${errorText}`) throw new Error(`分析 API 调用失败: ${response.status} ${response.statusText} - ${errorText}`) } const result: any = await response.json() if (result.errNo !== 0) { throw new Error(`分析失败: ${result.errStr || '未知错误'}`) } // 根据新的API响应格式转换数据 const apiData = result.data const analysisResult: WorkspaceAnalysisResult = { summary: apiData.summary || '项目分析完成', projectStructure: apiData.projectStructure || [], analysisStats: { ...apiData.analysisStats, analyzedPath: sourcePath, inputMethod: 'zip_upload', isTemporaryProject: true, }, } logger.info('后端源码分析完成') logger.info(`项目摘要: ${analysisResult.summary.substring(0, 100)}...`) resolve(analysisResult) }) .catch((fetchError) => { logger.error('Fetch请求失败:', fetchError) logger.error('错误详情:', { message: fetchError.message, code: fetchError.code, type: fetchError.type, errno: fetchError.errno, }) reject(new Error(`网络请求失败: ${fetchError.message}`)) }) }) }) } catch (error) { logger.error('调用分析 API 失败:', error) throw error } } /** * 测试后端连接 */ async testBackendConnection(): Promise<boolean> { try { const webUrl = vscode.workspace.getConfiguration('dalidev').get<string>('webUrl', 'http://localhost:8099') logger.info(`测试后端连接: ${webUrl}`) // 尝试不同的健康检查端点 const testUrls = [ `${webUrl}/cms-server/health`, `${webUrl}/cms-server/`, `${webUrl}/health`, `${webUrl}/`, ] for (const testUrl of testUrls) { try { logger.info(`尝试连接: ${testUrl}`) const response = await fetch(testUrl, { method: 'GET', timeout: 5000, } as any) logger.info(`${testUrl} 响应: ${response.status}`) if (response.status < 500) { // 任何非服务器错误都认为是连接成功 return true } } catch (error) { logger.warn(`${testUrl} 连接失败:`, error) } } return false } catch (error) { logger.error('后端连接测试失败:', error) return false } } /** * 生成工作区内容哈希(针对源码目录优化) */ private async generateWorkspaceHash(workspacePath: string, sourcePath: string): Promise<string> { // 针对源码目录生成哈希 try { const packageJsonPath = path.join(workspacePath, 'package.json') const gitPath = path.join(workspacePath, '.git', 'logs', 'HEAD') let hash = sourcePath if (fs.existsSync(packageJsonPath)) { const stats = fs.statSync(packageJsonPath) hash += stats.mtime.getTime() + stats.size } if (fs.existsSync(gitPath)) { const stats = fs.statSync(gitPath) hash += stats.mtime.getTime() + stats.size } // 添加源码目录的修改时间 if (fs.existsSync(sourcePath)) { const stats = fs.statSync(sourcePath) hash += stats.mtime.getTime() } // 简单的字符串哈希 let hashNumber = 0 for (let i = 0; i < hash.length; i++) { const char = hash.charCodeAt(i) hashNumber = ((hashNumber << 5) - hashNumber) + char hashNumber = hashNumber & hashNumber // 转换为32位整数 } return Math.abs(hashNumber).toString(36) } catch (error) { logger.warn('生成工作区哈希失败:', error) return Date.now().toString(36) } } /** * 缓存分析结果 */ private async cacheAnalysisResult( workspacePath: string, workspaceName: string, sourcePath: string, analysis: WorkspaceAnalysisResult, ): Promise<void> { try { const hash = await this.generateWorkspaceHash(workspacePath, sourcePath) const cachedResult: CachedAnalysisResult = { workspacePath, workspaceName, sourcePath, analysis, timestamp: Date.now(), hash, } // 使用 VSCode 的存储 API await this.context.globalState.update( `${this.cacheKey}-${workspacePath}`, cachedResult, ) logger.info('分析结果已缓存') } catch (error) { logger.warn('缓存分析结果失败:', error) } } /** * 获取缓存的分析结果 */ private async getCachedAnalysis(workspacePath: string, sourcePath: string): Promise<CachedAnalysisResult | null> { try { const cachedResult = this.context.globalState.get<CachedAnalysisResult>( `${this.cacheKey}-${workspacePath}`, ) if (!cachedResult) { return null } // 检查源码路径是否一致 if (cachedResult.sourcePath !== sourcePath) { logger.info('源码路径已变化,删除旧缓存') await this.context.globalState.update(`${this.cacheKey}-${workspacePath}`, undefined) return null } // 检查缓存是否过期 if (Date.now() - cachedResult.timestamp > this.maxAge) { logger.info('缓存已过期,删除旧缓存') await this.context.globalState.update(`${this.cacheKey}-${workspacePath}`, undefined) return null } // 检查工作区是否有变化 const currentHash = await this.generateWorkspaceHash(workspacePath, sourcePath) if (currentHash !== cachedResult.hash) { logger.info('工作区内容已变化,删除旧缓存') await this.context.globalState.update(`${this.cacheKey}-${workspacePath}`, undefined) return null } return cachedResult } catch (error) { logger.warn('获取缓存分析结果失败:', error) return null } } /** * 清理所有缓存 */ async clearCache(): Promise<void> { try { const keys = this.context.globalState.keys() const cacheKeys = keys.filter(key => key.startsWith(this.cacheKey)) for (const key of cacheKeys) { await this.context.globalState.update(key, undefined) } logger.info(`已清理 ${cacheKeys.length} 个缓存条目`) } catch (error) { logger.error('清理缓存失败:', error) throw error } } /** * 获取缓存统计信息 */ getCacheStats(): { count: number, keys: string[] } { const keys = this.context.globalState.keys() const cacheKeys = keys.filter(key => key.startsWith(this.cacheKey)) return { count: cacheKeys.length, keys: cacheKeys, } } } |