mcp-wordpress 2.11.13 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (247) hide show
  1. package/README.md +14 -29
  2. package/dist/cache/CacheInvalidation.js.map +1 -1
  3. package/dist/cache/CacheManager.d.ts +7 -0
  4. package/dist/cache/CacheManager.d.ts.map +1 -1
  5. package/dist/cache/CacheManager.js +21 -7
  6. package/dist/cache/CacheManager.js.map +1 -1
  7. package/dist/cache/HttpCacheWrapper.js.map +1 -1
  8. package/dist/cache/SEOCacheManager.d.ts.map +1 -1
  9. package/dist/cache/SEOCacheManager.js +6 -1
  10. package/dist/cache/SEOCacheManager.js.map +1 -1
  11. package/dist/cache/index.d.ts.map +1 -1
  12. package/dist/cache/index.js.map +1 -1
  13. package/dist/client/CachedWordPressClient.d.ts.map +1 -1
  14. package/dist/client/CachedWordPressClient.js.map +1 -1
  15. package/dist/client/MockWordPressClient.d.ts.map +1 -1
  16. package/dist/client/MockWordPressClient.js.map +1 -1
  17. package/dist/client/SEOWordPressClient.d.ts.map +1 -1
  18. package/dist/client/SEOWordPressClient.js.map +1 -1
  19. package/dist/client/api.d.ts +11 -26
  20. package/dist/client/api.d.ts.map +1 -1
  21. package/dist/client/api.js +111 -203
  22. package/dist/client/api.js.map +1 -1
  23. package/dist/client/auth.d.ts.map +1 -1
  24. package/dist/client/auth.js.map +1 -1
  25. package/dist/client/managers/AuthManager.d.ts.map +1 -1
  26. package/dist/client/managers/RequestManager.d.ts.map +1 -1
  27. package/dist/client/managers/RequestManager.js +6 -5
  28. package/dist/client/managers/RequestManager.js.map +1 -1
  29. package/dist/client/managers/composed/MigrationAdapter.d.ts +3 -3
  30. package/dist/client/managers/composed/MigrationAdapter.d.ts.map +1 -1
  31. package/dist/client/managers/composed/MigrationAdapter.js +2 -2
  32. package/dist/client/managers/composed/MigrationAdapter.js.map +1 -1
  33. package/dist/client/managers/composed/index.d.ts +7 -7
  34. package/dist/client/managers/composed/index.d.ts.map +1 -1
  35. package/dist/client/managers/composed/index.js +6 -6
  36. package/dist/client/managers/composed/index.js.map +1 -1
  37. package/dist/client/managers/implementations/ConfigurationProviderImpl.d.ts +1 -1
  38. package/dist/client/managers/implementations/ConfigurationProviderImpl.d.ts.map +1 -1
  39. package/dist/client/managers/implementations/ErrorHandlerImpl.d.ts +1 -1
  40. package/dist/client/managers/implementations/ErrorHandlerImpl.d.ts.map +1 -1
  41. package/dist/client/managers/implementations/ParameterValidatorImpl.d.ts +1 -1
  42. package/dist/client/managers/implementations/ParameterValidatorImpl.d.ts.map +1 -1
  43. package/dist/client/operations/comments.d.ts +58 -0
  44. package/dist/client/operations/comments.d.ts.map +1 -0
  45. package/dist/client/operations/comments.js +74 -0
  46. package/dist/client/operations/comments.js.map +1 -0
  47. package/dist/client/operations/index.d.ts +12 -0
  48. package/dist/client/operations/index.d.ts.map +1 -0
  49. package/dist/client/operations/index.js +12 -0
  50. package/dist/client/operations/index.js.map +1 -0
  51. package/dist/client/operations/media.d.ts +55 -0
  52. package/dist/client/operations/media.d.ts.map +1 -0
  53. package/dist/client/operations/media.js +132 -0
  54. package/dist/client/operations/media.js.map +1 -0
  55. package/dist/client/operations/pages.d.ts +50 -0
  56. package/dist/client/operations/pages.d.ts.map +1 -0
  57. package/dist/client/operations/pages.js +56 -0
  58. package/dist/client/operations/pages.js.map +1 -0
  59. package/dist/client/operations/posts.d.ts +50 -0
  60. package/dist/client/operations/posts.d.ts.map +1 -0
  61. package/dist/client/operations/posts.js +53 -0
  62. package/dist/client/operations/posts.js.map +1 -0
  63. package/dist/client/operations/site.d.ts +60 -0
  64. package/dist/client/operations/site.d.ts.map +1 -0
  65. package/dist/client/operations/site.js +83 -0
  66. package/dist/client/operations/site.js.map +1 -0
  67. package/dist/client/operations/taxonomies.d.ts +69 -0
  68. package/dist/client/operations/taxonomies.d.ts.map +1 -0
  69. package/dist/client/operations/taxonomies.js +87 -0
  70. package/dist/client/operations/taxonomies.js.map +1 -0
  71. package/dist/client/operations/users.d.ts +50 -0
  72. package/dist/client/operations/users.d.ts.map +1 -0
  73. package/dist/client/operations/users.js +57 -0
  74. package/dist/client/operations/users.js.map +1 -0
  75. package/dist/config/ServerConfiguration.d.ts.map +1 -1
  76. package/dist/config/ServerConfiguration.js.map +1 -1
  77. package/dist/docs/DocumentationGenerator.js.map +1 -1
  78. package/dist/performance/MetricsCollector.d.ts.map +1 -1
  79. package/dist/performance/MetricsCollector.js.map +1 -1
  80. package/dist/performance/PerformanceMonitor.js.map +1 -1
  81. package/dist/security/AISecurityScanner.d.ts.map +1 -1
  82. package/dist/security/AISecurityScanner.js +3 -2
  83. package/dist/security/AISecurityScanner.js.map +1 -1
  84. package/dist/security/AutomatedRemediation.js.map +1 -1
  85. package/dist/security/InputValidator.d.ts.map +1 -1
  86. package/dist/security/InputValidator.js +30 -18
  87. package/dist/security/InputValidator.js.map +1 -1
  88. package/dist/security/SecurityCIPipeline.d.ts +19 -196
  89. package/dist/security/SecurityCIPipeline.d.ts.map +1 -1
  90. package/dist/security/SecurityCIPipeline.js +95 -639
  91. package/dist/security/SecurityCIPipeline.js.map +1 -1
  92. package/dist/security/SecurityConfig.js.map +1 -1
  93. package/dist/security/SecurityConfigManager.js.map +1 -1
  94. package/dist/security/SecurityGateExecutor.d.ts +67 -0
  95. package/dist/security/SecurityGateExecutor.d.ts.map +1 -0
  96. package/dist/security/SecurityGateExecutor.js +363 -0
  97. package/dist/security/SecurityGateExecutor.js.map +1 -0
  98. package/dist/security/SecurityMonitoring.js.map +1 -1
  99. package/dist/security/SecurityReportGenerator.d.ts +65 -0
  100. package/dist/security/SecurityReportGenerator.d.ts.map +1 -0
  101. package/dist/security/SecurityReportGenerator.js +210 -0
  102. package/dist/security/SecurityReportGenerator.js.map +1 -0
  103. package/dist/security/SecurityReviewer.js.map +1 -1
  104. package/dist/security/SecurityTypes.d.ts +188 -0
  105. package/dist/security/SecurityTypes.d.ts.map +1 -0
  106. package/dist/security/SecurityTypes.js +6 -0
  107. package/dist/security/SecurityTypes.js.map +1 -0
  108. package/dist/security/index.d.ts +5 -28
  109. package/dist/security/index.d.ts.map +1 -1
  110. package/dist/security/index.js +4 -0
  111. package/dist/security/index.js.map +1 -1
  112. package/dist/server/ConnectionTester.d.ts.map +1 -1
  113. package/dist/server/ConnectionTester.js.map +1 -1
  114. package/dist/server/ToolRegistry.d.ts.map +1 -1
  115. package/dist/server/ToolRegistry.js.map +1 -1
  116. package/dist/tools/BaseToolManager.d.ts.map +1 -1
  117. package/dist/tools/BaseToolManager.js.map +1 -1
  118. package/dist/tools/auth.d.ts.map +1 -1
  119. package/dist/tools/auth.js.map +1 -1
  120. package/dist/tools/cache.d.ts.map +1 -1
  121. package/dist/tools/cache.js.map +1 -1
  122. package/dist/tools/comments.d.ts.map +1 -1
  123. package/dist/tools/comments.js.map +1 -1
  124. package/dist/tools/media.d.ts.map +1 -1
  125. package/dist/tools/media.js.map +1 -1
  126. package/dist/tools/pages.d.ts.map +1 -1
  127. package/dist/tools/pages.js.map +1 -1
  128. package/dist/tools/performance/PerformanceHelpers.d.ts +116 -0
  129. package/dist/tools/performance/PerformanceHelpers.d.ts.map +1 -0
  130. package/dist/tools/performance/PerformanceHelpers.js +298 -0
  131. package/dist/tools/performance/PerformanceHelpers.js.map +1 -0
  132. package/dist/tools/performance/PerformanceTools.d.ts +54 -0
  133. package/dist/tools/performance/PerformanceTools.d.ts.map +1 -0
  134. package/dist/tools/performance/PerformanceTools.js +687 -0
  135. package/dist/tools/performance/PerformanceTools.js.map +1 -0
  136. package/dist/tools/performance/index.d.ts +8 -0
  137. package/dist/tools/performance/index.d.ts.map +1 -0
  138. package/dist/tools/performance/index.js +8 -0
  139. package/dist/tools/performance/index.js.map +1 -0
  140. package/dist/tools/performance.d.ts +12 -69
  141. package/dist/tools/performance.d.ts.map +1 -1
  142. package/dist/tools/performance.js +12 -920
  143. package/dist/tools/performance.js.map +1 -1
  144. package/dist/tools/posts.d.ts.map +1 -1
  145. package/dist/tools/seo/analyzers/ContentAnalyzer.d.ts.map +1 -1
  146. package/dist/tools/seo/analyzers/ContentAnalyzer.js +14 -3
  147. package/dist/tools/seo/analyzers/ContentAnalyzer.js.map +1 -1
  148. package/dist/tools/seo/auditors/SiteAuditor.d.ts.map +1 -1
  149. package/dist/tools/seo/auditors/SiteAuditor.js +12 -3
  150. package/dist/tools/seo/auditors/SiteAuditor.js.map +1 -1
  151. package/dist/tools/seo/generators/MetaGenerator.d.ts.map +1 -1
  152. package/dist/tools/seo/generators/MetaGenerator.js +25 -8
  153. package/dist/tools/seo/generators/MetaGenerator.js.map +1 -1
  154. package/dist/tools/seo/generators/SchemaGenerator.d.ts.map +1 -1
  155. package/dist/tools/seo/generators/SchemaGenerator.js.map +1 -1
  156. package/dist/tools/seo/optimizers/InternalLinkingSuggester.d.ts.map +1 -1
  157. package/dist/tools/seo/optimizers/InternalLinkingSuggester.js.map +1 -1
  158. package/dist/tools/site.d.ts.map +1 -1
  159. package/dist/tools/site.js.map +1 -1
  160. package/dist/tools/taxonomies.d.ts.map +1 -1
  161. package/dist/tools/taxonomies.js.map +1 -1
  162. package/dist/tools/users.d.ts.map +1 -1
  163. package/dist/tools/users.js.map +1 -1
  164. package/dist/utils/CircuitBreaker.d.ts +243 -0
  165. package/dist/utils/CircuitBreaker.d.ts.map +1 -0
  166. package/dist/utils/CircuitBreaker.js +456 -0
  167. package/dist/utils/CircuitBreaker.js.map +1 -0
  168. package/dist/utils/debug.d.ts.map +1 -1
  169. package/dist/utils/debug.js.map +1 -1
  170. package/dist/utils/error.js.map +1 -1
  171. package/dist/utils/index.d.ts +1 -0
  172. package/dist/utils/index.d.ts.map +1 -1
  173. package/dist/utils/index.js +2 -0
  174. package/dist/utils/index.js.map +1 -1
  175. package/dist/utils/logger.js.map +1 -1
  176. package/dist/utils/toolWrapper.d.ts.map +1 -1
  177. package/docs/DEPRECATIONS.md +157 -0
  178. package/package.json +2 -3
  179. package/src/cache/CacheInvalidation.ts +1 -1
  180. package/src/cache/CacheManager.ts +25 -8
  181. package/src/cache/HttpCacheWrapper.ts +1 -1
  182. package/src/cache/SEOCacheManager.ts +9 -3
  183. package/src/cache/index.ts +1 -1
  184. package/src/client/CachedWordPressClient.ts +6 -6
  185. package/src/client/MockWordPressClient.ts +3 -3
  186. package/src/client/SEOWordPressClient.ts +6 -6
  187. package/src/client/api.ts +129 -215
  188. package/src/client/auth.ts +3 -3
  189. package/src/client/managers/AuthManager.ts +1 -1
  190. package/src/client/managers/RequestManager.ts +6 -7
  191. package/src/client/managers/composed/MigrationAdapter.ts +4 -4
  192. package/src/client/managers/composed/index.ts +7 -7
  193. package/src/client/managers/implementations/ConfigurationProviderImpl.ts +1 -1
  194. package/src/client/managers/implementations/ErrorHandlerImpl.ts +1 -1
  195. package/src/client/managers/implementations/ParameterValidatorImpl.ts +1 -1
  196. package/src/client/operations/comments.ts +96 -0
  197. package/src/client/operations/index.ts +12 -0
  198. package/src/client/operations/media.ts +162 -0
  199. package/src/client/operations/pages.ts +71 -0
  200. package/src/client/operations/posts.ts +68 -0
  201. package/src/client/operations/site.ts +106 -0
  202. package/src/client/operations/taxonomies.ts +115 -0
  203. package/src/client/operations/users.ts +72 -0
  204. package/src/config/ServerConfiguration.ts +6 -6
  205. package/src/docs/DocumentationGenerator.ts +3 -3
  206. package/src/performance/MetricsCollector.ts +4 -4
  207. package/src/performance/PerformanceMonitor.ts +1 -1
  208. package/src/security/AISecurityScanner.ts +4 -3
  209. package/src/security/AutomatedRemediation.ts +1 -1
  210. package/src/security/InputValidator.ts +36 -19
  211. package/src/security/SecurityCIPipeline.ts +130 -953
  212. package/src/security/SecurityConfig.ts +1 -1
  213. package/src/security/SecurityConfigManager.ts +1 -1
  214. package/src/security/SecurityGateExecutor.ts +485 -0
  215. package/src/security/SecurityMonitoring.ts +1 -1
  216. package/src/security/SecurityReportGenerator.ts +272 -0
  217. package/src/security/SecurityReviewer.ts +1 -1
  218. package/src/security/SecurityTypes.ts +199 -0
  219. package/src/security/index.ts +6 -1
  220. package/src/server/ConnectionTester.ts +4 -4
  221. package/src/server/ToolRegistry.ts +6 -6
  222. package/src/tools/BaseToolManager.ts +2 -2
  223. package/src/tools/auth.ts +3 -3
  224. package/src/tools/cache.ts +3 -3
  225. package/src/tools/comments.ts +3 -3
  226. package/src/tools/media.ts +3 -3
  227. package/src/tools/pages.ts +3 -3
  228. package/src/tools/performance/PerformanceHelpers.ts +330 -0
  229. package/src/tools/performance/PerformanceTools.ts +854 -0
  230. package/src/tools/performance/index.ts +8 -0
  231. package/src/tools/performance.ts +12 -1073
  232. package/src/tools/posts.ts +1 -1
  233. package/src/tools/seo/analyzers/ContentAnalyzer.ts +21 -7
  234. package/src/tools/seo/auditors/SiteAuditor.ts +18 -7
  235. package/src/tools/seo/generators/MetaGenerator.ts +33 -12
  236. package/src/tools/seo/generators/SchemaGenerator.ts +3 -3
  237. package/src/tools/seo/optimizers/InternalLinkingSuggester.ts +4 -4
  238. package/src/tools/site.ts +3 -3
  239. package/src/tools/taxonomies.ts +3 -3
  240. package/src/tools/users.ts +4 -4
  241. package/src/utils/CircuitBreaker.ts +572 -0
  242. package/src/utils/debug.ts +3 -3
  243. package/src/utils/error.ts +1 -1
  244. package/src/utils/index.ts +3 -0
  245. package/src/utils/logger.ts +1 -1
  246. package/src/utils/toolWrapper.ts +2 -2
  247. package/docs/BRANCH_PROTECTION.md +0 -0
@@ -1,1077 +1,16 @@
1
1
  /**
2
2
  * Performance Monitoring MCP Tools for WordPress Server
3
- * Provides comprehensive performance insights and management
3
+ *
4
+ * This module has been refactored into a modular structure.
5
+ * The implementation is now in ./performance/ directory:
6
+ * - PerformanceTools.ts: Main tool class with 6 MCP tools
7
+ * - PerformanceHelpers.ts: Extracted helper/utility functions
8
+ *
9
+ * This file re-exports for backward compatibility.
10
+ *
11
+ * @module tools/performance
4
12
  */
5
- /**
6
- * Performance Monitoring MCP Tools for WordPress Server
7
- * Provides comprehensive performance insights and management
8
- */
9
-
10
- import type { ToolDefinition } from "../server/ToolRegistry.js";
11
- import {
12
- PerformanceMonitor,
13
- type PerformanceMetrics,
14
- type PerformanceAlert,
15
- } from "../performance/PerformanceMonitor.js";
16
- import { MetricsCollector } from "../performance/MetricsCollector.js";
17
- import {
18
- PerformanceAnalytics,
19
- type BenchmarkComparison,
20
- type PerformanceAnomaly,
21
- } from "../performance/PerformanceAnalytics.js";
22
- import { toolWrapper } from "../utils/toolWrapper.js";
23
- import { ConfigHelpers } from "../config/Config.js";
24
- import { LoggerFactory } from "../utils/logger.js";
25
- import type { WordPressClient } from "../client/api.js";
26
-
27
- // Using existing performance interfaces from PerformanceMonitor/PerformanceAnalytics
28
-
29
- /**
30
- * Performance Tools Class
31
- */
32
- export default class PerformanceTools {
33
- private monitor: PerformanceMonitor;
34
- private collector: MetricsCollector;
35
- private analytics: PerformanceAnalytics;
36
- private logger: ReturnType<typeof LoggerFactory.performance>;
37
- private historicalDataInterval?: NodeJS.Timeout | undefined;
38
-
39
- constructor(clients?: Map<string, unknown>) {
40
- // Initialize logger first
41
- this.logger = LoggerFactory.performance();
42
-
43
- // Initialize performance monitoring system
44
- this.monitor = new PerformanceMonitor({
45
- enableRealTimeMonitoring: true,
46
- enableHistoricalData: true,
47
- enableAlerts: true,
48
- });
49
-
50
- this.collector = new MetricsCollector(this.monitor, {
51
- enableRealTime: true,
52
- enableToolTracking: true,
53
- enableCacheIntegration: true,
54
- });
55
-
56
- this.analytics = new PerformanceAnalytics(this.collector, {
57
- enablePredictiveAnalysis: true,
58
- enableAnomalyDetection: true,
59
- enableTrendAnalysis: true,
60
- });
61
-
62
- // Register clients if provided
63
- if (clients) {
64
- for (const [siteId, client] of clients) {
65
- this.collector.registerClient(siteId, client);
66
-
67
- // Register cache manager if client has one
68
- const possibleCacheMgr = (client as Record<string, unknown>)?.cacheManager as unknown;
69
- if (possibleCacheMgr) {
70
- this.collector.registerCacheManager(siteId, possibleCacheMgr);
71
- }
72
- }
73
- }
74
-
75
- // Only start historical data collection in production environments
76
- if (ConfigHelpers.isProd() || ConfigHelpers.isDev()) {
77
- this.startHistoricalDataCollection();
78
- }
79
- }
80
-
81
- /**
82
- * Get all performance monitoring tools
83
- */
84
- getTools(): ToolDefinition[] {
85
- return [
86
- {
87
- name: "wp_performance_stats",
88
- description: "Get real-time performance statistics and metrics",
89
- parameters: [
90
- {
91
- name: "site",
92
- type: "string",
93
- description: "Specific site ID for multi-site setups (optional for single site)",
94
- required: false,
95
- },
96
- {
97
- name: "category",
98
- type: "string",
99
- description: "Category of metrics to return (overview, requests, cache, system, tools, all)",
100
- required: false,
101
- },
102
- {
103
- name: "format",
104
- type: "string",
105
- description: "Detail level of the response (summary, detailed, raw)",
106
- required: false,
107
- },
108
- ],
109
- handler: this.getPerformanceStats.bind(this),
110
- },
111
- {
112
- name: "wp_performance_history",
113
- description: "Get historical performance data and trends",
114
- parameters: [
115
- {
116
- name: "site",
117
- type: "string",
118
- description: "Specific site ID for multi-site setups (optional for single site)",
119
- required: false,
120
- },
121
- {
122
- name: "timeframe",
123
- type: "string",
124
- description: "Time period for historical data (1h, 6h, 12h, 24h, 7d)",
125
- required: false,
126
- },
127
- {
128
- name: "metrics",
129
- type: "array",
130
- description:
131
- "Specific metrics to include (responseTime, cacheHitRate, errorRate, memoryUsage, requestVolume)",
132
- required: false,
133
- },
134
- {
135
- name: "includeTrends",
136
- type: "boolean",
137
- description: "Include trend analysis (default: true)",
138
- required: false,
139
- },
140
- ],
141
- handler: this.getPerformanceHistory.bind(this),
142
- },
143
- {
144
- name: "wp_performance_benchmark",
145
- description: "Compare current performance against industry benchmarks",
146
- parameters: [
147
- {
148
- name: "site",
149
- type: "string",
150
- description: "Specific site ID for multi-site setups (optional for single site)",
151
- required: false,
152
- },
153
- {
154
- name: "category",
155
- type: "string",
156
- description: "Benchmark category (response_time, cache_performance, error_rate, system_resources, all)",
157
- required: false,
158
- },
159
- {
160
- name: "includeRecommendations",
161
- type: "boolean",
162
- description: "Include improvement recommendations (default: true)",
163
- required: false,
164
- },
165
- ],
166
- handler: this.getBenchmarkComparison.bind(this),
167
- },
168
- {
169
- name: "wp_performance_alerts",
170
- description: "Get performance alerts and anomaly detection results",
171
- parameters: [
172
- {
173
- name: "site",
174
- type: "string",
175
- description: "Specific site ID for multi-site setups (optional for single site)",
176
- required: false,
177
- },
178
- {
179
- name: "severity",
180
- type: "string",
181
- description: "Filter alerts by severity level (info, warning, error, critical)",
182
- required: false,
183
- },
184
- {
185
- name: "category",
186
- type: "string",
187
- description: "Filter alerts by category (performance, cache, system, wordpress)",
188
- required: false,
189
- },
190
- {
191
- name: "limit",
192
- type: "number",
193
- description: "Maximum number of alerts to return (default: 20)",
194
- required: false,
195
- },
196
- {
197
- name: "includeAnomalies",
198
- type: "boolean",
199
- description: "Include detected anomalies (default: true)",
200
- required: false,
201
- },
202
- ],
203
- handler: this.getPerformanceAlerts.bind(this),
204
- },
205
- {
206
- name: "wp_performance_optimize",
207
- description: "Get optimization recommendations and insights",
208
- parameters: [
209
- {
210
- name: "site",
211
- type: "string",
212
- description: "Specific site ID for multi-site setups (optional for single site)",
213
- required: false,
214
- },
215
- {
216
- name: "focus",
217
- type: "string",
218
- description: "Optimization focus area (speed, reliability, efficiency, scaling)",
219
- required: false,
220
- },
221
- {
222
- name: "priority",
223
- type: "string",
224
- description: "Implementation timeline (quick_wins, medium_term, long_term, all)",
225
- required: false,
226
- },
227
- {
228
- name: "includeROI",
229
- type: "boolean",
230
- description: "Include ROI estimates (default: true)",
231
- required: false,
232
- },
233
- {
234
- name: "includePredictions",
235
- type: "boolean",
236
- description: "Include performance predictions (default: true)",
237
- required: false,
238
- },
239
- ],
240
- handler: this.getOptimizationRecommendations.bind(this),
241
- },
242
- {
243
- name: "wp_performance_export",
244
- description: "Export comprehensive performance report",
245
- parameters: [
246
- {
247
- name: "site",
248
- type: "string",
249
- description: "Specific site ID for multi-site setups (optional for single site)",
250
- required: false,
251
- },
252
- {
253
- name: "format",
254
- type: "string",
255
- description: "Export format (json, csv, summary)",
256
- required: false,
257
- },
258
- {
259
- name: "includeHistorical",
260
- type: "boolean",
261
- description: "Include historical data (default: true)",
262
- required: false,
263
- },
264
- {
265
- name: "includeAnalytics",
266
- type: "boolean",
267
- description: "Include analytics and insights (default: true)",
268
- required: false,
269
- },
270
- {
271
- name: "timeRange",
272
- type: "string",
273
- description: "Time range for data export (1h, 6h, 24h, 7d, 30d)",
274
- required: false,
275
- },
276
- ],
277
- handler: this.exportPerformanceReport.bind(this),
278
- },
279
- ];
280
- }
281
-
282
- /**
283
- * Get real-time performance statistics
284
- */
285
- private async getPerformanceStats(_client: WordPressClient, params: Record<string, unknown>): Promise<unknown> {
286
- return toolWrapper(async () => {
287
- const {
288
- site,
289
- category = "overview",
290
- format = "summary",
291
- } = params as { site?: string; category?: string; format?: string };
292
-
293
- // Get current metrics
294
- const metrics = this.collector.collectCurrentMetrics();
295
-
296
- // Get site-specific metrics if requested
297
- let siteMetrics = null;
298
- if (site) {
299
- siteMetrics = this.collector.getSiteMetrics(site as string);
300
- }
301
-
302
- // Filter by category
303
- const result: Record<string, unknown> = {};
304
-
305
- if (category === "overview" || category === "all") {
306
- result.overview = {
307
- overallHealth: this.calculateHealthStatus(metrics),
308
- performanceScore: this.calculatePerformanceScore(metrics),
309
- totalRequests: metrics.requests.total,
310
- averageResponseTime: `${metrics.requests.averageResponseTime.toFixed(0)}ms`,
311
- cacheHitRate: `${(metrics.cache.hitRate * 100).toFixed(1)}%`,
312
- errorRate: `${((metrics.requests.failed / Math.max(metrics.requests.total, 1)) * 100).toFixed(2)}%`,
313
- uptime: this.formatUptime(metrics.system.uptime),
314
- };
315
- }
316
-
317
- if (category === "requests" || category === "all") {
318
- result.requests = {
319
- ...metrics.requests,
320
- requestsPerSecond: metrics.requests.requestsPerSecond.toFixed(2),
321
- p50ResponseTime: `${metrics.requests.p50ResponseTime}ms`,
322
- p95ResponseTime: `${metrics.requests.p95ResponseTime}ms`,
323
- p99ResponseTime: `${metrics.requests.p99ResponseTime}ms`,
324
- };
325
- }
326
-
327
- if (category === "cache" || category === "all") {
328
- result.cache = {
329
- ...metrics.cache,
330
- hitRate: `${(metrics.cache.hitRate * 100).toFixed(1)}%`,
331
- memoryUsage: `${metrics.cache.memoryUsageMB.toFixed(1)}MB`,
332
- efficiency: this.calculateCacheEfficiency(metrics.cache),
333
- };
334
- }
335
-
336
- if (category === "system" || category === "all") {
337
- result.system = {
338
- ...metrics.system,
339
- memoryUsage: `${metrics.system.memoryUsage}%`,
340
- cpuUsage: `${metrics.system.cpuUsage}%`,
341
- uptime: this.formatUptime(metrics.system.uptime),
342
- };
343
- }
344
-
345
- if (category === "tools" || category === "all") {
346
- result.tools = {
347
- mostUsedTool: metrics.tools.mostUsedTool,
348
- totalToolCalls: Object.values(metrics.tools.toolUsageCount).reduce(
349
- (sum: number, count: unknown) => sum + (typeof count === "number" ? count : 0),
350
- 0,
351
- ),
352
- topTools: Object.entries(metrics.tools.toolUsageCount)
353
- .sort(([, a], [, b]) => (b as number) - (a as number))
354
- .slice(0, 5)
355
- .map(([tool, count]) => ({ tool, count })),
356
- toolPerformance: format === "detailed" ? metrics.tools.toolPerformance : undefined,
357
- };
358
- }
359
-
360
- // Add site-specific data if requested
361
- if (siteMetrics && siteMetrics.isActive) {
362
- result.siteSpecific = {
363
- siteId: site,
364
- cache: siteMetrics.cache,
365
- client: siteMetrics.client,
366
- };
367
- }
368
-
369
- // Add metadata
370
- result.metadata = {
371
- timestamp: new Date().toISOString(),
372
- category,
373
- format,
374
- site: site || "all",
375
- monitoringEnabled: true,
376
- };
377
-
378
- return {
379
- success: true,
380
- data: result,
381
- };
382
- });
383
- }
384
-
385
- /**
386
- * Get historical performance data and trends
387
- */
388
- private async getPerformanceHistory(_client: WordPressClient, params: Record<string, unknown>): Promise<unknown> {
389
- return toolWrapper(async () => {
390
- const {
391
- site,
392
- timeframe = "24h",
393
- metrics: requestedMetrics,
394
- includeTrends = true,
395
- } = params as { site?: string; timeframe?: string; metrics?: string[]; includeTrends?: boolean };
396
-
397
- // Convert timeframe to milliseconds
398
- const timeframMs = this.parseTimeframe(timeframe);
399
- const startTime = Date.now() - timeframMs;
400
-
401
- // Get historical data
402
- const historicalData = this.monitor.getHistoricalData(startTime);
403
-
404
- // Analyze trends if requested
405
- let trends = null;
406
- if (includeTrends) {
407
- // Add current data for trend analysis
408
- this.analytics.addDataPoint(this.collector.collectCurrentMetrics());
409
- trends = this.analytics.analyzeTrends();
410
-
411
- // Filter trends by requested metrics
412
- if (requestedMetrics && Array.isArray(requestedMetrics)) {
413
- trends = trends.filter((trend) => requestedMetrics.includes(trend.metric));
414
- }
415
- }
416
-
417
- // Process historical data for charting
418
- const chartData = this.processHistoricalDataForChart(historicalData, requestedMetrics as string[] | undefined);
419
-
420
- return {
421
- success: true,
422
- data: {
423
- timeframe,
424
- dataPoints: historicalData.length,
425
- historicalData: chartData,
426
- trends: trends || [],
427
- summary: {
428
- averageResponseTime: this.calculateAverage(historicalData.map((d) => d.requests.averageResponseTime)),
429
- averageCacheHitRate: this.calculateAverage(historicalData.map((d) => d.cache.hitRate)),
430
- averageErrorRate: this.calculateAverage(
431
- historicalData.map((d) => (d.requests.total > 0 ? d.requests.failed / d.requests.total : 0)),
432
- ),
433
- totalRequests: historicalData.reduce((sum, d) => sum + d.requests.total, 0),
434
- },
435
- metadata: {
436
- timestamp: new Date().toISOString(),
437
- site: site || "all",
438
- requestedMetrics: requestedMetrics || ["all"],
439
- },
440
- },
441
- };
442
- });
443
- }
444
-
445
- /**
446
- * Get benchmark comparison
447
- */
448
- private async getBenchmarkComparison(_client: WordPressClient, params: Record<string, unknown>): Promise<unknown> {
449
- return toolWrapper(async () => {
450
- const {
451
- site,
452
- category = "all",
453
- includeRecommendations = true,
454
- } = params as { site?: string; category?: string; includeRecommendations?: boolean };
455
-
456
- // Get benchmark comparisons
457
- const benchmarks = this.analytics.benchmarkPerformance() as BenchmarkComparison[];
458
-
459
- // Filter by category if specified
460
- let filteredBenchmarks = benchmarks;
461
- if (category !== "all") {
462
- const categoryMap: Record<string, string> = {
463
- response_time: "Response Time",
464
- cache_performance: "Cache Hit Rate",
465
- error_rate: "Error Rate",
466
- system_resources: "Memory Usage",
467
- };
468
- const targetCategory = categoryMap[category as string];
469
- if (targetCategory) {
470
- filteredBenchmarks = benchmarks.filter((b) => b.category === targetCategory);
471
- }
472
- }
473
-
474
- // Get recommendations if requested
475
- let recommendations = null;
476
- if (includeRecommendations) {
477
- const insights = this.analytics.generateInsights();
478
- recommendations = insights
479
- .filter((insight) => insight.category === "optimization")
480
- .map((insight) => ({
481
- title: insight.title,
482
- description: insight.description,
483
- priority: insight.priority,
484
- estimatedImprovement: insight.estimatedImprovement,
485
- implementationEffort: insight.implementationEffort,
486
- }));
487
- }
488
-
489
- return {
490
- success: true,
491
- data: {
492
- benchmarks: filteredBenchmarks.map((benchmark) => ({
493
- ...benchmark,
494
- status: this.formatBenchmarkStatus(benchmark.status),
495
- improvement:
496
- benchmark.improvement > 0
497
- ? {
498
- needed: benchmark.improvement,
499
- description: this.getBenchmarkImprovementDescription(benchmark),
500
- }
501
- : null,
502
- })),
503
- overallRanking: this.calculateOverallRanking(benchmarks),
504
- recommendations: recommendations || [],
505
- metadata: {
506
- timestamp: new Date().toISOString(),
507
- category,
508
- site: site || "all",
509
- benchmarkVersion: "2024-industry-standards",
510
- },
511
- },
512
- };
513
- });
514
- }
515
-
516
- /**
517
- * Get performance alerts and anomalies
518
- */
519
- private async getPerformanceAlerts(_client: WordPressClient, params: Record<string, unknown>): Promise<unknown> {
520
- return toolWrapper(async () => {
521
- const {
522
- site,
523
- severity,
524
- category,
525
- limit = 20,
526
- includeAnomalies = true,
527
- } = params as { site?: string; severity?: string; category?: string; limit?: number; includeAnomalies?: boolean };
528
-
529
- // Get alerts from monitor
530
- let alerts = this.monitor.getAlerts(severity) as PerformanceAlert[];
531
-
532
- // Filter by category if specified
533
- if (category) {
534
- alerts = alerts.filter((alert) => alert.category === category);
535
- }
536
-
537
- // Limit results
538
- alerts = alerts.slice(-(limit as number));
539
-
540
- // Get anomalies if requested
541
- let anomalies: PerformanceAnomaly[] = [];
542
- if (includeAnomalies) {
543
- anomalies = this.analytics.getAnomalies(severity) as PerformanceAnomaly[];
544
- }
545
-
546
- // Calculate alert summary
547
- const alertSummary = {
548
- total: alerts.length,
549
- critical: alerts.filter((a) => a.severity === "critical").length,
550
- error: alerts.filter((a) => a.severity === "error").length,
551
- warning: alerts.filter((a) => a.severity === "warning").length,
552
- info: alerts.filter((a) => a.severity === "info").length,
553
- };
554
-
555
- const anomalySummary = {
556
- total: anomalies.length,
557
- critical: anomalies.filter((a) => a.severity === "critical").length,
558
- major: anomalies.filter((a) => a.severity === "major").length,
559
- moderate: anomalies.filter((a) => a.severity === "moderate").length,
560
- minor: anomalies.filter((a) => a.severity === "minor").length,
561
- };
562
-
563
- return {
564
- success: true,
565
- data: {
566
- alerts: alerts.map((alert) => ({
567
- ...alert,
568
- timestamp: new Date(alert.timestamp).toISOString(),
569
- formattedMessage: this.formatAlertMessage(alert),
570
- })),
571
- anomalies: anomalies.map((anomaly) => ({
572
- ...anomaly,
573
- timestamp: new Date(anomaly.timestamp).toISOString(),
574
- formattedDescription: this.formatAnomalyDescription(anomaly),
575
- })),
576
- summary: {
577
- alerts: alertSummary,
578
- anomalies: anomalySummary,
579
- overallStatus: this.calculateAlertStatus(alertSummary, anomalySummary),
580
- },
581
- metadata: {
582
- timestamp: new Date().toISOString(),
583
- filters: { severity, category, site: site || "all" },
584
- limit,
585
- },
586
- },
587
- };
588
- });
589
- }
590
-
591
- /**
592
- * Get optimization recommendations
593
- */
594
- private async getOptimizationRecommendations(
595
- _client: WordPressClient,
596
- params: Record<string, unknown>,
597
- ): Promise<unknown> {
598
- return toolWrapper(async () => {
599
- const {
600
- site,
601
- focus = "speed",
602
- priority = "all",
603
- includeROI = true,
604
- includePredictions = true,
605
- } = params as {
606
- site?: string;
607
- focus?: string;
608
- priority?: string;
609
- includeROI?: boolean;
610
- includePredictions?: boolean;
611
- };
612
-
613
- // Generate optimization plan
614
- const optimizationPlan = this.analytics.generateOptimizationPlan();
615
-
616
- // Filter by priority
617
- let recommendations: Array<{
618
- priority: string;
619
- impact: string;
620
- implementationEffort: string;
621
- [key: string]: unknown;
622
- }> = [];
623
- if (priority === "quick_wins" || priority === "all") {
624
- recommendations.push(
625
- ...optimizationPlan.quickWins.map((r) => ({
626
- ...r,
627
- timeline: "quick_wins",
628
- })),
629
- );
630
- }
631
- if (priority === "medium_term" || priority === "all") {
632
- recommendations.push(
633
- ...optimizationPlan.mediumTerm.map((r) => ({
634
- ...r,
635
- timeline: "medium_term",
636
- })),
637
- );
638
- }
639
- if (priority === "long_term" || priority === "all") {
640
- recommendations.push(
641
- ...optimizationPlan.longTerm.map((r) => ({
642
- ...r,
643
- timeline: "long_term",
644
- })),
645
- );
646
- }
647
-
648
- // Filter by focus area
649
- if (focus !== "speed") {
650
- const focusMap: Record<string, string[]> = {
651
- reliability: ["reliability"],
652
- efficiency: ["cost", "performance"],
653
- scaling: ["performance", "reliability"],
654
- };
655
- const targetImpacts = focusMap[focus] || [];
656
- recommendations = recommendations.filter((r) => targetImpacts.includes(r.impact));
657
- }
658
-
659
- // Get predictions if requested
660
- let predictions: Record<string, unknown> | null = null;
661
- if (includePredictions) {
662
- predictions = this.analytics.predictPerformance(60); // 1 hour prediction
663
- }
664
-
665
- return {
666
- success: true,
667
- data: {
668
- recommendations: recommendations.map((rec) => ({
669
- ...rec,
670
- formattedPriority: this.formatPriority(rec.priority),
671
- formattedEffort: this.formatEffort(rec.implementationEffort),
672
- })),
673
- roi: includeROI ? optimizationPlan.estimatedROI : null,
674
- predictions: predictions || null,
675
- summary: {
676
- totalRecommendations: recommendations.length,
677
- quickWins: optimizationPlan.quickWins.length,
678
- mediumTerm: optimizationPlan.mediumTerm.length,
679
- longTerm: optimizationPlan.longTerm.length,
680
- estimatedImpact: this.calculateEstimatedImpact(recommendations),
681
- },
682
- metadata: {
683
- timestamp: new Date().toISOString(),
684
- focus,
685
- priority,
686
- site: site || "all",
687
- },
688
- },
689
- };
690
- });
691
- }
692
-
693
- /**
694
- * Export comprehensive performance report
695
- */
696
- private async exportPerformanceReport(_client: WordPressClient, params: Record<string, unknown>): Promise<unknown> {
697
- return toolWrapper(async () => {
698
- const {
699
- site,
700
- format = "json",
701
- includeHistorical = true,
702
- includeAnalytics = true,
703
- timeRange = "24h",
704
- } = params as {
705
- site?: string;
706
- format?: string;
707
- includeHistorical?: boolean;
708
- includeAnalytics?: boolean;
709
- timeRange?: string;
710
- };
711
-
712
- // Generate comprehensive analytics report
713
- const report = this.analytics.exportAnalyticsReport();
714
-
715
- // Add additional data based on parameters
716
- const exportData: { currentMetrics: PerformanceMetrics; [key: string]: unknown } = {
717
- metadata: {
718
- generatedAt: new Date().toISOString(),
719
- site: site || "all",
720
- timeRange,
721
- format,
722
- version: "1.0.0",
723
- },
724
- summary: report.summary,
725
- currentMetrics: this.collector.collectCurrentMetrics(),
726
- };
727
-
728
- if (includeHistorical) {
729
- const timeframMs = this.parseTimeframe(timeRange);
730
- const startTime = Date.now() - timeframMs;
731
- exportData.historicalData = this.monitor.getHistoricalData(startTime);
732
- }
733
-
734
- if (includeAnalytics) {
735
- exportData.analytics = {
736
- trends: report.trends,
737
- benchmarks: report.benchmarks,
738
- insights: report.insights,
739
- anomalies: report.anomalies,
740
- predictions: report.predictions,
741
- optimizationPlan: report.optimizationPlan,
742
- };
743
- }
744
-
745
- // Add aggregated statistics
746
- exportData.aggregatedStats = {
747
- cache: this.collector.getAggregatedCacheStats(),
748
- client: this.collector.getAggregatedClientStats(),
749
- };
750
-
751
- // Add site comparison if multi-site
752
- if (!site) {
753
- exportData.siteComparison = this.collector.compareSitePerformance();
754
- }
755
-
756
- // Format output based on requested format
757
- let formattedOutput: unknown;
758
- if (format === "csv") {
759
- formattedOutput = this.convertToCSV(exportData);
760
- } else if (format === "summary") {
761
- formattedOutput = this.createSummaryReport(exportData);
762
- } else {
763
- formattedOutput = exportData;
764
- }
765
-
766
- return {
767
- success: true,
768
- data: formattedOutput,
769
- metadata: {
770
- timestamp: new Date().toISOString(),
771
- format,
772
- dataSize: JSON.stringify(exportData).length,
773
- site: site || "all",
774
- },
775
- };
776
- });
777
- }
778
-
779
- // Helper methods
780
-
781
- private calculateHealthStatus(metrics: PerformanceMetrics): string {
782
- let score = 100;
783
-
784
- if (metrics.requests.averageResponseTime > 2000) score -= 30;
785
- else if (metrics.requests.averageResponseTime > 1000) score -= 15;
786
-
787
- const errorRate = metrics.requests.failed / Math.max(metrics.requests.total, 1);
788
- if (errorRate > 0.05) score -= 30;
789
- else if (errorRate > 0.02) score -= 15;
790
-
791
- if (metrics.cache.hitRate < 0.7) score -= 25;
792
- else if (metrics.cache.hitRate < 0.85) score -= 10;
793
-
794
- if (metrics.system.memoryUsage > 85) score -= 15;
795
-
796
- if (score >= 90) return "Excellent";
797
- if (score >= 75) return "Good";
798
- if (score >= 60) return "Fair";
799
- if (score >= 40) return "Poor";
800
- return "Critical";
801
- }
802
-
803
- private calculatePerformanceScore(metrics: PerformanceMetrics): number {
804
- let score = 100;
805
-
806
- // Response time scoring
807
- if (metrics.requests.averageResponseTime > 3000) score -= 40;
808
- else if (metrics.requests.averageResponseTime > 1500) score -= 25;
809
- else if (metrics.requests.averageResponseTime > 800) score -= 10;
810
-
811
- // Error rate scoring
812
- const errorRate = metrics.requests.failed / Math.max(metrics.requests.total, 1);
813
- if (errorRate > 0.1) score -= 30;
814
- else if (errorRate > 0.05) score -= 20;
815
- else if (errorRate > 0.02) score -= 10;
816
-
817
- // Cache performance scoring
818
- if (metrics.cache.hitRate < 0.5) score -= 20;
819
- else if (metrics.cache.hitRate < 0.75) score -= 10;
820
- else if (metrics.cache.hitRate < 0.9) score -= 5;
821
-
822
- // System resource scoring
823
- if (metrics.system.memoryUsage > 90) score -= 10;
824
- else if (metrics.system.memoryUsage > 80) score -= 5;
825
-
826
- return Math.max(0, Math.min(100, score));
827
- }
828
-
829
- private calculateCacheEfficiency(cacheMetrics: PerformanceMetrics["cache"]): string {
830
- const efficiency =
831
- cacheMetrics.hitRate * 100 + (cacheMetrics.totalSize > 0 ? 10 : 0) - (cacheMetrics.evictions > 100 ? 10 : 0);
832
-
833
- if (efficiency >= 95) return "Excellent";
834
- if (efficiency >= 85) return "Good";
835
- if (efficiency >= 70) return "Fair";
836
- return "Poor";
837
- }
838
-
839
- private formatUptime(uptimeMs: number): string {
840
- const seconds = Math.floor(uptimeMs / 1000);
841
- const minutes = Math.floor(seconds / 60);
842
- const hours = Math.floor(minutes / 60);
843
- const days = Math.floor(hours / 24);
844
-
845
- if (days > 0) return `${days}d ${hours % 24}h ${minutes % 60}m`;
846
- if (hours > 0) return `${hours}h ${minutes % 60}m`;
847
- if (minutes > 0) return `${minutes}m ${seconds % 60}s`;
848
- return `${seconds}s`;
849
- }
850
-
851
- private parseTimeframe(timeframe: string): number {
852
- const map: Record<string, number> = {
853
- "1h": 60 * 60 * 1000,
854
- "6h": 6 * 60 * 60 * 1000,
855
- "12h": 12 * 60 * 60 * 1000,
856
- "24h": 24 * 60 * 60 * 1000,
857
- "7d": 7 * 24 * 60 * 60 * 1000,
858
- "30d": 30 * 24 * 60 * 60 * 1000,
859
- };
860
- return map[timeframe] || map["24h"];
861
- }
862
-
863
- private processHistoricalDataForChart(
864
- data: PerformanceMetrics[],
865
- requestedMetrics?: string[],
866
- ): Record<string, unknown> {
867
- if (!data.length) return {};
868
-
869
- const allMetrics = ["responseTime", "cacheHitRate", "errorRate", "memoryUsage", "requestVolume"];
870
- const metricsToProcess = requestedMetrics || allMetrics;
871
-
872
- const result: Record<string, unknown> = {};
873
-
874
- for (const metric of metricsToProcess) {
875
- result[metric] = data.map((point, index) => ({
876
- timestamp: point.system.uptime,
877
- value: this.extractMetricValue(point, metric),
878
- index,
879
- }));
880
- }
881
-
882
- return result;
883
- }
884
-
885
- private extractMetricValue(dataPoint: PerformanceMetrics, metric: string): number {
886
- switch (metric) {
887
- case "responseTime":
888
- return dataPoint.requests.averageResponseTime;
889
- case "cacheHitRate":
890
- return dataPoint.cache.hitRate * 100;
891
- case "errorRate":
892
- return (dataPoint.requests.failed / Math.max(dataPoint.requests.total, 1)) * 100;
893
- case "memoryUsage":
894
- return dataPoint.system.memoryUsage;
895
- case "requestVolume":
896
- return dataPoint.requests.requestsPerSecond;
897
- default:
898
- return 0;
899
- }
900
- }
901
-
902
- private calculateAverage(values: number[]): number {
903
- if (values.length === 0) return 0;
904
- return values.reduce((sum, val) => sum + val, 0) / values.length;
905
- }
906
-
907
- private formatBenchmarkStatus(status: string): string {
908
- const statusMap: Record<string, string> = {
909
- excellent: "🟢 Excellent",
910
- good: "🟡 Good",
911
- average: "🟠 Average",
912
- below_average: "🔴 Below Average",
913
- poor: "⚫ Poor",
914
- };
915
- return statusMap[status] || status;
916
- }
917
-
918
- private getBenchmarkImprovementDescription(benchmark: BenchmarkComparison): string {
919
- const improvements: Record<string, string> = {
920
- "Response Time": `Reduce by ${benchmark.improvement.toFixed(0)}ms`,
921
- "Cache Hit Rate": `Increase by ${benchmark.improvement.toFixed(1)}%`,
922
- "Error Rate": `Reduce by ${benchmark.improvement.toFixed(2)}%`,
923
- "Memory Usage": `Reduce by ${benchmark.improvement.toFixed(0)}%`,
924
- };
925
- return improvements[benchmark.category] || `Improve by ${benchmark.improvement}`;
926
- }
927
-
928
- private calculateOverallRanking(benchmarks: BenchmarkComparison[]): {
929
- percentile: number;
930
- status: string;
931
- } {
932
- const statuses = benchmarks.map((b) => b.status);
933
- const excellentCount = statuses.filter((s) => s === "excellent").length;
934
- const goodCount = statuses.filter((s) => s === "good").length;
935
-
936
- const percentile = ((excellentCount + goodCount * 0.8) / statuses.length) * 100;
937
-
938
- let status = "Needs Improvement";
939
- if (percentile >= 90) status = "Top Performer";
940
- else if (percentile >= 75) status = "Above Average";
941
- else if (percentile >= 50) status = "Average";
942
-
943
- return { percentile: Math.round(percentile), status };
944
- }
945
-
946
- private formatAlertMessage(alert: PerformanceAlert): string {
947
- return `${alert.severity.toUpperCase()}: ${alert.message} (${alert.metric}: ${alert.actualValue} vs threshold: ${
948
- alert.threshold
949
- })`;
950
- }
951
-
952
- private formatAnomalyDescription(anomaly: PerformanceAnomaly): string {
953
- const direction = anomaly.actualValue > anomaly.expectedValue ? "higher" : "lower";
954
- return `${anomaly.metric} is ${Math.abs(anomaly.deviation).toFixed(
955
- 1,
956
- )}% ${direction} than expected (${anomaly.expectedValue.toFixed(2)} vs ${anomaly.actualValue.toFixed(2)})`;
957
- }
958
-
959
- private calculateAlertStatus(
960
- alertSummary: { critical: number; error: number; warning: number },
961
- anomalySummary: { critical: number; major: number; moderate: number; minor: number },
962
- ): string {
963
- const critical = alertSummary.critical + anomalySummary.critical;
964
- const high = alertSummary.error + anomalySummary.major;
965
-
966
- if (critical > 0) return "Critical Issues Detected";
967
- if (high > 2) return "High Priority Issues";
968
- if (alertSummary.warning + anomalySummary.moderate > 5) return "Performance Warnings";
969
- return "System Healthy";
970
- }
971
-
972
- private formatPriority(priority: string): string {
973
- const map: Record<string, string> = {
974
- critical: "🔴 Critical",
975
- high: "🟠 High",
976
- medium: "🟡 Medium",
977
- low: "🟢 Low",
978
- };
979
- return map[priority] || priority;
980
- }
981
-
982
- private formatEffort(effort: string): string {
983
- const map: Record<string, string> = {
984
- low: "⚡ Low Effort",
985
- medium: "⚖️ Medium Effort",
986
- high: "🏋️ High Effort",
987
- };
988
- return map[effort] || effort;
989
- }
990
-
991
- private calculateEstimatedImpact(recommendations: Array<{ priority: string }>): string {
992
- const highImpact = recommendations.filter((r) => ["critical", "high"].includes(r.priority)).length;
993
- const totalImpact = recommendations.length;
994
-
995
- if (highImpact >= 3) return "Significant Performance Gains Expected";
996
- if (totalImpact >= 5) return "Moderate Performance Improvements";
997
- if (totalImpact > 0) return "Minor Performance Optimizations";
998
- return "System Already Optimized";
999
- }
1000
-
1001
- private convertToCSV(data: { currentMetrics: PerformanceMetrics }): string {
1002
- // Simplified CSV conversion for current metrics
1003
- const metrics = data.currentMetrics;
1004
- const csv = [
1005
- "Metric,Value,Unit",
1006
- `Total Requests,${metrics.requests.total},count`,
1007
- `Average Response Time,${metrics.requests.averageResponseTime.toFixed(0)},ms`,
1008
- `Success Rate,${((metrics.requests.successful / Math.max(metrics.requests.total, 1)) * 100).toFixed(1)},%`,
1009
- `Cache Hit Rate,${(metrics.cache.hitRate * 100).toFixed(1)},%`,
1010
- `Cache Size,${metrics.cache.totalSize},entries`,
1011
- `Memory Usage,${metrics.system.memoryUsage},percent`,
1012
- `Uptime,${metrics.system.uptime},ms`,
1013
- ];
1014
-
1015
- return csv.join("\n");
1016
- }
1017
-
1018
- private createSummaryReport(data: {
1019
- currentMetrics: PerformanceMetrics;
1020
- analytics?: { insights?: unknown[] };
1021
- }): Record<string, unknown> {
1022
- const metrics = data.currentMetrics;
1023
- return {
1024
- summary: `Performance Report - ${new Date().toISOString()}`,
1025
- overallHealth: this.calculateHealthStatus(metrics),
1026
- keyMetrics: {
1027
- averageResponseTime: `${metrics.requests.averageResponseTime.toFixed(0)}ms`,
1028
- cacheEfficiency: `${(metrics.cache.hitRate * 100).toFixed(1)}%`,
1029
- systemLoad: `${metrics.system.memoryUsage}%`,
1030
- errorRate: `${((metrics.requests.failed / Math.max(metrics.requests.total, 1)) * 100).toFixed(2)}%`,
1031
- },
1032
- recommendations: data.analytics?.insights?.slice(0, 3) || [],
1033
- nextSteps: "Review detailed metrics and implement high-priority optimizations",
1034
- };
1035
- }
1036
-
1037
- private startHistoricalDataCollection(): void {
1038
- // Skip in test environments to prevent performance issues
1039
- if (ConfigHelpers.isTest() || ConfigHelpers.isCI()) {
1040
- this.logger.debug("Skipping historical data collection in test/CI environment");
1041
- return;
1042
- }
1043
-
1044
- // Adjust collection frequency based on environment
1045
- const interval = ConfigHelpers.isDev() ? 60000 : 30000; // 1 minute in dev, 30 seconds in prod
1046
-
1047
- this.logger.info("Starting historical data collection", {
1048
- interval: `${interval / 1000}s`,
1049
- environment: ConfigHelpers.get().get().app.nodeEnv,
1050
- });
1051
-
1052
- this.historicalDataInterval = setInterval(() => {
1053
- try {
1054
- const currentMetrics = this.collector.collectCurrentMetrics();
1055
- this.analytics.addDataPoint(currentMetrics);
1056
- this.logger.debug("Historical metrics collected", {
1057
- timestamp: new Date().toISOString(),
1058
- });
1059
- } catch (_error) {
1060
- this.logger.error("Failed to collect historical metrics", {
1061
- _error: _error instanceof Error ? _error.message : String(_error),
1062
- });
1063
- }
1064
- }, interval);
1065
- }
1066
13
 
1067
- /**
1068
- * Stop historical data collection and cleanup resources
1069
- */
1070
- public destroy(): void {
1071
- if (this.historicalDataInterval) {
1072
- clearInterval(this.historicalDataInterval);
1073
- this.historicalDataInterval = undefined;
1074
- this.logger.info("Historical data collection stopped");
1075
- }
1076
- }
1077
- }
14
+ export { default } from "./performance/index.js";
15
+ export { PerformanceTools } from "./performance/index.js";
16
+ export * from "./performance/PerformanceHelpers.js";