beddel 0.1.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 (236) hide show
  1. package/README.md +297 -0
  2. package/dist/agents/agentRegistry.d.ts +68 -0
  3. package/dist/agents/agentRegistry.d.ts.map +1 -0
  4. package/dist/agents/agentRegistry.js +222 -0
  5. package/dist/agents/agentRegistry.js.map +1 -0
  6. package/dist/agents/formatter-agent.d.ts +10 -0
  7. package/dist/agents/formatter-agent.d.ts.map +1 -0
  8. package/dist/agents/formatter-agent.js +49 -0
  9. package/dist/agents/formatter-agent.js.map +1 -0
  10. package/dist/agents/genkit-agent.d.ts +12 -0
  11. package/dist/agents/genkit-agent.d.ts.map +1 -0
  12. package/dist/agents/genkit-agent.js +119 -0
  13. package/dist/agents/genkit-agent.js.map +1 -0
  14. package/dist/agents/i18n-messages.d.ts +17 -0
  15. package/dist/agents/i18n-messages.d.ts.map +1 -0
  16. package/dist/agents/i18n-messages.js +92 -0
  17. package/dist/agents/i18n-messages.js.map +1 -0
  18. package/dist/agents/index.d.ts +10 -0
  19. package/dist/agents/index.d.ts.map +1 -0
  20. package/dist/agents/index.js +26 -0
  21. package/dist/agents/index.js.map +1 -0
  22. package/dist/agents/pipeline.d.ts +15 -0
  23. package/dist/agents/pipeline.d.ts.map +1 -0
  24. package/dist/agents/pipeline.js +45 -0
  25. package/dist/agents/pipeline.js.map +1 -0
  26. package/dist/agents/schema-factory.d.ts +40 -0
  27. package/dist/agents/schema-factory.d.ts.map +1 -0
  28. package/dist/agents/schema-factory.js +121 -0
  29. package/dist/agents/schema-factory.js.map +1 -0
  30. package/dist/agents/translation-validators.d.ts +26 -0
  31. package/dist/agents/translation-validators.d.ts.map +1 -0
  32. package/dist/agents/translation-validators.js +77 -0
  33. package/dist/agents/translation-validators.js.map +1 -0
  34. package/dist/agents/translator-agents.d.ts +184 -0
  35. package/dist/agents/translator-agents.d.ts.map +1 -0
  36. package/dist/agents/translator-agents.js +613 -0
  37. package/dist/agents/translator-agents.js.map +1 -0
  38. package/dist/agents/types/translation.types.d.ts +100 -0
  39. package/dist/agents/types/translation.types.d.ts.map +1 -0
  40. package/dist/agents/types/translation.types.js +3 -0
  41. package/dist/agents/types/translation.types.js.map +1 -0
  42. package/dist/agents/validator-agent.d.ts +42 -0
  43. package/dist/agents/validator-agent.d.ts.map +1 -0
  44. package/dist/agents/validator-agent.js +122 -0
  45. package/dist/agents/validator-agent.js.map +1 -0
  46. package/dist/audit/auditTrail.d.ts +55 -0
  47. package/dist/audit/auditTrail.d.ts.map +1 -0
  48. package/dist/audit/auditTrail.js +93 -0
  49. package/dist/audit/auditTrail.js.map +1 -0
  50. package/dist/compliance/gdprEngine.d.ts +44 -0
  51. package/dist/compliance/gdprEngine.d.ts.map +1 -0
  52. package/dist/compliance/gdprEngine.js +178 -0
  53. package/dist/compliance/gdprEngine.js.map +1 -0
  54. package/dist/compliance/lgpdEngine.d.ts +51 -0
  55. package/dist/compliance/lgpdEngine.d.ts.map +1 -0
  56. package/dist/compliance/lgpdEngine.js +221 -0
  57. package/dist/compliance/lgpdEngine.js.map +1 -0
  58. package/dist/config.d.ts +78 -0
  59. package/dist/config.d.ts.map +1 -0
  60. package/dist/config.js +77 -0
  61. package/dist/config.js.map +1 -0
  62. package/dist/errors.d.ts +17 -0
  63. package/dist/errors.d.ts.map +1 -0
  64. package/dist/errors.js +40 -0
  65. package/dist/errors.js.map +1 -0
  66. package/dist/firebase/tenantManager.d.ts +84 -0
  67. package/dist/firebase/tenantManager.d.ts.map +1 -0
  68. package/dist/firebase/tenantManager.js +378 -0
  69. package/dist/firebase/tenantManager.js.map +1 -0
  70. package/dist/index.d.ts +36 -0
  71. package/dist/index.d.ts.map +1 -0
  72. package/dist/index.js +118 -0
  73. package/dist/index.js.map +1 -0
  74. package/dist/integration/secure-yaml-runtime.d.ts +68 -0
  75. package/dist/integration/secure-yaml-runtime.d.ts.map +1 -0
  76. package/dist/integration/secure-yaml-runtime.js +245 -0
  77. package/dist/integration/secure-yaml-runtime.js.map +1 -0
  78. package/dist/parser/secure-yaml-parser.d.ts +62 -0
  79. package/dist/parser/secure-yaml-parser.d.ts.map +1 -0
  80. package/dist/parser/secure-yaml-parser.js +234 -0
  81. package/dist/parser/secure-yaml-parser.js.map +1 -0
  82. package/dist/performance/autoscaling.d.ts +100 -0
  83. package/dist/performance/autoscaling.d.ts.map +1 -0
  84. package/dist/performance/autoscaling.js +339 -0
  85. package/dist/performance/autoscaling.js.map +1 -0
  86. package/dist/performance/benchmark.d.ts +104 -0
  87. package/dist/performance/benchmark.d.ts.map +1 -0
  88. package/dist/performance/benchmark.js +514 -0
  89. package/dist/performance/benchmark.js.map +1 -0
  90. package/dist/performance/index.d.ts +14 -0
  91. package/dist/performance/index.d.ts.map +1 -0
  92. package/dist/performance/index.js +35 -0
  93. package/dist/performance/index.js.map +1 -0
  94. package/dist/performance/monitor.d.ts +126 -0
  95. package/dist/performance/monitor.d.ts.map +1 -0
  96. package/dist/performance/monitor.js +324 -0
  97. package/dist/performance/monitor.js.map +1 -0
  98. package/dist/performance/streaming.d.ts +82 -0
  99. package/dist/performance/streaming.d.ts.map +1 -0
  100. package/dist/performance/streaming.js +287 -0
  101. package/dist/performance/streaming.js.map +1 -0
  102. package/dist/runtime/audit.d.ts +240 -0
  103. package/dist/runtime/audit.d.ts.map +1 -0
  104. package/dist/runtime/audit.js +641 -0
  105. package/dist/runtime/audit.js.map +1 -0
  106. package/dist/runtime/declarativeAgentRuntime.d.ts +123 -0
  107. package/dist/runtime/declarativeAgentRuntime.d.ts.map +1 -0
  108. package/dist/runtime/declarativeAgentRuntime.js +576 -0
  109. package/dist/runtime/declarativeAgentRuntime.js.map +1 -0
  110. package/dist/runtime/isolatedRuntime.d.ts +119 -0
  111. package/dist/runtime/isolatedRuntime.d.ts.map +1 -0
  112. package/dist/runtime/isolatedRuntime.js +425 -0
  113. package/dist/runtime/isolatedRuntime.js.map +1 -0
  114. package/dist/runtime/schemaCompiler.d.ts +35 -0
  115. package/dist/runtime/schemaCompiler.d.ts.map +1 -0
  116. package/dist/runtime/schemaCompiler.js +151 -0
  117. package/dist/runtime/schemaCompiler.js.map +1 -0
  118. package/dist/runtime/simpleRuntime.d.ts +57 -0
  119. package/dist/runtime/simpleRuntime.d.ts.map +1 -0
  120. package/dist/runtime/simpleRuntime.js +187 -0
  121. package/dist/runtime/simpleRuntime.js.map +1 -0
  122. package/dist/security/dashboard.d.ts +89 -0
  123. package/dist/security/dashboard.d.ts.map +1 -0
  124. package/dist/security/dashboard.js +300 -0
  125. package/dist/security/dashboard.js.map +1 -0
  126. package/dist/security/hardening.d.ts +130 -0
  127. package/dist/security/hardening.d.ts.map +1 -0
  128. package/dist/security/hardening.js +414 -0
  129. package/dist/security/hardening.js.map +1 -0
  130. package/dist/security/index.d.ts +128 -0
  131. package/dist/security/index.d.ts.map +1 -0
  132. package/dist/security/index.js +353 -0
  133. package/dist/security/index.js.map +1 -0
  134. package/dist/security/monitor.d.ts +88 -0
  135. package/dist/security/monitor.d.ts.map +1 -0
  136. package/dist/security/monitor.js +356 -0
  137. package/dist/security/monitor.js.map +1 -0
  138. package/dist/security/scanner.d.ts +104 -0
  139. package/dist/security/scanner.d.ts.map +1 -0
  140. package/dist/security/scanner.js +298 -0
  141. package/dist/security/scanner.js.map +1 -0
  142. package/dist/security/score.d.ts +150 -0
  143. package/dist/security/score.d.ts.map +1 -0
  144. package/dist/security/score.js +983 -0
  145. package/dist/security/score.js.map +1 -0
  146. package/dist/security/test-security.d.ts +22 -0
  147. package/dist/security/test-security.d.ts.map +1 -0
  148. package/dist/security/test-security.js +154 -0
  149. package/dist/security/test-security.js.map +1 -0
  150. package/dist/security/threatDetector.d.ts +39 -0
  151. package/dist/security/threatDetector.d.ts.map +1 -0
  152. package/dist/security/threatDetector.js +354 -0
  153. package/dist/security/threatDetector.js.map +1 -0
  154. package/dist/security/validation.d.ts +69 -0
  155. package/dist/security/validation.d.ts.map +1 -0
  156. package/dist/security/validation.js +286 -0
  157. package/dist/security/validation.js.map +1 -0
  158. package/dist/server/api/clientsRoute.d.ts +9 -0
  159. package/dist/server/api/clientsRoute.d.ts.map +1 -0
  160. package/dist/server/api/clientsRoute.js +71 -0
  161. package/dist/server/api/clientsRoute.js.map +1 -0
  162. package/dist/server/api/endpointsRoute.d.ts +8 -0
  163. package/dist/server/api/endpointsRoute.d.ts.map +1 -0
  164. package/dist/server/api/endpointsRoute.js +76 -0
  165. package/dist/server/api/endpointsRoute.js.map +1 -0
  166. package/dist/server/api/graphql.d.ts +9 -0
  167. package/dist/server/api/graphql.d.ts.map +1 -0
  168. package/dist/server/api/graphql.js +180 -0
  169. package/dist/server/api/graphql.js.map +1 -0
  170. package/dist/server/errors.d.ts +19 -0
  171. package/dist/server/errors.d.ts.map +1 -0
  172. package/dist/server/errors.js +42 -0
  173. package/dist/server/errors.js.map +1 -0
  174. package/dist/server/index.d.ts +7 -0
  175. package/dist/server/index.d.ts.map +1 -0
  176. package/dist/server/index.js +24 -0
  177. package/dist/server/index.js.map +1 -0
  178. package/dist/server/kvStore.d.ts +27 -0
  179. package/dist/server/kvStore.d.ts.map +1 -0
  180. package/dist/server/kvStore.js +128 -0
  181. package/dist/server/kvStore.js.map +1 -0
  182. package/dist/server/runtimeSecurity.d.ts +28 -0
  183. package/dist/server/runtimeSecurity.d.ts.map +1 -0
  184. package/dist/server/runtimeSecurity.js +85 -0
  185. package/dist/server/runtimeSecurity.js.map +1 -0
  186. package/dist/server/types.d.ts +53 -0
  187. package/dist/server/types.d.ts.map +1 -0
  188. package/dist/server/types.js +8 -0
  189. package/dist/server/types.js.map +1 -0
  190. package/dist/types/executionContext.d.ts +16 -0
  191. package/dist/types/executionContext.d.ts.map +1 -0
  192. package/dist/types/executionContext.js +3 -0
  193. package/dist/types/executionContext.js.map +1 -0
  194. package/package.json +77 -0
  195. package/src/agents/agentRegistry.ts +272 -0
  196. package/src/agents/image-agent.yaml +86 -0
  197. package/src/agents/joker-agent.yaml +47 -0
  198. package/src/agents/translator-agent.yaml +80 -0
  199. package/src/audit/auditTrail.ts +134 -0
  200. package/src/compliance/gdprEngine.ts +209 -0
  201. package/src/compliance/lgpdEngine.ts +268 -0
  202. package/src/config.ts +179 -0
  203. package/src/errors.ts +35 -0
  204. package/src/firebase/tenantManager.ts +443 -0
  205. package/src/index.ts +125 -0
  206. package/src/integration/secure-yaml-runtime.ts +341 -0
  207. package/src/parser/secure-yaml-parser.ts +273 -0
  208. package/src/performance/autoscaling.ts +495 -0
  209. package/src/performance/benchmark.ts +644 -0
  210. package/src/performance/index.ts +34 -0
  211. package/src/performance/monitor.ts +469 -0
  212. package/src/performance/streaming.ts +317 -0
  213. package/src/runtime/audit.ts +907 -0
  214. package/src/runtime/declarativeAgentRuntime.ts +836 -0
  215. package/src/runtime/isolatedRuntime.ts +572 -0
  216. package/src/runtime/schemaCompiler.ts +228 -0
  217. package/src/runtime/simpleRuntime.ts +201 -0
  218. package/src/security/dashboard.ts +462 -0
  219. package/src/security/hardening.ts +560 -0
  220. package/src/security/index.ts +439 -0
  221. package/src/security/monitor.ts +490 -0
  222. package/src/security/scanner.ts +368 -0
  223. package/src/security/score.ts +1138 -0
  224. package/src/security/threatDetector.ts +481 -0
  225. package/src/security/validation.ts +365 -0
  226. package/src/server/api/clientsRoute.ts +92 -0
  227. package/src/server/api/endpointsRoute.ts +97 -0
  228. package/src/server/api/graphql.ts +249 -0
  229. package/src/server/errors.ts +38 -0
  230. package/src/server/index.ts +6 -0
  231. package/src/server/kvStore.ts +152 -0
  232. package/src/server/runtimeSecurity.ts +102 -0
  233. package/src/server/types.ts +60 -0
  234. package/src/types/executionContext.ts +16 -0
  235. package/tools/seed.ts +365 -0
  236. package/tools/test-endpoints.ts +174 -0
@@ -0,0 +1,469 @@
1
+ /**
2
+ * Performance Monitor - Execution Performance Tracking
3
+ * Monitors execution performance with <50ms target and memory tracking
4
+ */
5
+ import { performance } from "node:perf_hooks";
6
+ import { performanceTargets } from "../config";
7
+
8
+ export interface PerformanceMetric {
9
+ metric: string;
10
+ value: number;
11
+ timestamp: Date;
12
+ executionId: string;
13
+ tenantId?: string;
14
+ context?: any;
15
+ }
16
+
17
+ export interface PerformanceSnapshot {
18
+ timestamp: Date;
19
+ metrics: Record<string, number[]>;
20
+ averages: Record<string, number>;
21
+ violations: Violation[];
22
+ recommendations: Recommendation[];
23
+ }
24
+
25
+ export interface Violation {
26
+ metric: string;
27
+ value: number;
28
+ target: number;
29
+ severity: "warning" | "critical";
30
+ timestamp: Date;
31
+ executionId: string;
32
+ }
33
+
34
+ export interface Recommendation {
35
+ type: "performance" | "memory" | "security" | "scaling";
36
+ priority: "high" | "medium" | "low";
37
+ description: string;
38
+ action: string;
39
+ estimatedImpact: number; // percentage improvement
40
+ }
41
+
42
+ export interface BenchmarkResult {
43
+ label: string;
44
+ iterations: number;
45
+ averageTime: number;
46
+ minTime: number;
47
+ maxTime: number;
48
+ payloadSize?: number;
49
+ }
50
+
51
+ export class PerformanceMonitor {
52
+ private metrics: Map<string, PerformanceMetric[]> = new Map();
53
+ private violations: Violation[] = [];
54
+ private recommendations: Recommendation[] = [];
55
+
56
+ private readonly retentionPeriod = 60 * 60 * 1000; // 1 hour
57
+ private readonly alertThreshold = 0.8; // 80% of target
58
+ private readonly criticalThreshold = 1.5; // 150% of target
59
+
60
+ constructor() {
61
+ this.startCleanupInterval();
62
+ }
63
+
64
+ /**
65
+ * Record a performance metric
66
+ */
67
+ public recordMetric(metric: PerformanceMetric): void {
68
+ if (!this.metrics.has(metric.metric)) {
69
+ this.metrics.set(metric.metric, []);
70
+ }
71
+
72
+ const metrics = this.metrics.get(metric.metric)!;
73
+ metrics.push(metric);
74
+
75
+ // Check for violations
76
+ const target = performanceTargets.find((t) => t.metric === metric.metric);
77
+ if (target) {
78
+ const violation = this.checkViolation(metric, target);
79
+ if (violation) {
80
+ this.violations.push(violation);
81
+ this.logViolation(violation);
82
+ }
83
+ }
84
+
85
+ // Keep only metrics within retention period
86
+ this.cleanupOldMetrics(metric.metric, this.retentionPeriod);
87
+ }
88
+
89
+ /**
90
+ * Record execution performance metrics
91
+ */
92
+ public recordExecution(
93
+ executionId: string,
94
+ executionTime: number,
95
+ memoryUsed: number,
96
+ tenantId?: string
97
+ ): void {
98
+ const timestamp = new Date();
99
+
100
+ // Record execution time
101
+ this.recordMetric({
102
+ metric: "executionTime",
103
+ value: executionTime,
104
+ timestamp,
105
+ executionId,
106
+ tenantId,
107
+ });
108
+
109
+ // Record memory usage
110
+ this.recordMetric({
111
+ metric: "memoryUsage",
112
+ value: memoryUsed,
113
+ timestamp,
114
+ executionId,
115
+ tenantId,
116
+ });
117
+
118
+ // Generate recommendations based on metrics
119
+ this.generateRecommendations(executionTime, memoryUsed, tenantId);
120
+ }
121
+
122
+ /**
123
+ * Simple benchmarking helper so downstream modules can compare strategies.
124
+ */
125
+ public async benchmark<T>(
126
+ fn: () => Promise<T> | T,
127
+ label: string,
128
+ iterations = 1,
129
+ payloadSize?: number
130
+ ): Promise<BenchmarkResult> {
131
+ if (iterations < 1) {
132
+ throw new Error("Benchmark iterations must be >= 1");
133
+ }
134
+
135
+ const samples: number[] = [];
136
+
137
+ for (let i = 0; i < iterations; i++) {
138
+ const start = performance.now();
139
+ await Promise.resolve(fn());
140
+ const duration = performance.now() - start;
141
+ samples.push(duration);
142
+
143
+ this.recordMetric({
144
+ metric: "benchmark",
145
+ value: duration,
146
+ timestamp: new Date(),
147
+ executionId: `${label}-${i}`,
148
+ });
149
+ }
150
+
151
+ const averageTime =
152
+ samples.reduce((total, value) => total + value, 0) / samples.length;
153
+
154
+ return {
155
+ label,
156
+ iterations,
157
+ averageTime,
158
+ minTime: Math.min(...samples),
159
+ maxTime: Math.max(...samples),
160
+ payloadSize,
161
+ };
162
+ }
163
+
164
+ /**
165
+ * Check for performance violations
166
+ */
167
+ private checkViolation(
168
+ metric: PerformanceMetric,
169
+ target: (typeof performanceTargets)[0]
170
+ ): Violation | null {
171
+ const threshold = target.threshold;
172
+ const isViolation = metric.value > threshold;
173
+
174
+ if (!isViolation) return null;
175
+
176
+ const severity =
177
+ metric.value > target.target * this.criticalThreshold
178
+ ? "critical"
179
+ : "warning";
180
+
181
+ return {
182
+ metric: metric.metric,
183
+ value: metric.value,
184
+ target: target.target,
185
+ severity,
186
+ timestamp: metric.timestamp,
187
+ executionId: metric.executionId,
188
+ };
189
+ }
190
+
191
+ /**
192
+ * Log violations for monitoring
193
+ */
194
+ private logViolation(violation: Violation): void {
195
+ const message = `[PERFORMANCE_${violation.severity.toUpperCase()}] ${
196
+ violation.metric
197
+ }: ${violation.value} ${performanceTargets
198
+ .find((t) => t.metric === violation.metric)
199
+ ?.unit?.toLowerCase()} (target: ${violation.target}) - Execution ID: ${
200
+ violation.executionId
201
+ }`;
202
+
203
+ console.log(`[${violation.timestamp.toISOString()}] ${message}`);
204
+ }
205
+
206
+ /**
207
+ * Generate performance recommendations
208
+ */
209
+ private generateRecommendations(
210
+ executionTime: number,
211
+ memoryUsed: number,
212
+ tenantId?: string
213
+ ): void {
214
+ const executionTimeTarget =
215
+ performanceTargets.find((t) => t.metric === "executionTime")?.target ||
216
+ 50;
217
+ const memoryTarget =
218
+ performanceTargets.find((t) => t.metric === "memoryUsage")?.target || 2;
219
+
220
+ // Execution time recommendations
221
+ if (executionTime > executionTimeTarget * 1.2) {
222
+ this.recommendations.push({
223
+ type: "performance",
224
+ priority: "high",
225
+ description: `Execution time ${executionTime}ms exceeds target by ${(
226
+ ((executionTime - executionTimeTarget) / executionTimeTarget) *
227
+ 100
228
+ ).toFixed(1)}%`,
229
+ action: "Consider optimizing code complexity or splitting execution",
230
+ estimatedImpact: -30, // 30% improvement
231
+ });
232
+ }
233
+
234
+ // Memory usage recommendations
235
+ if (memoryUsed > memoryTarget * 1.5) {
236
+ this.recommendations.push({
237
+ type: "memory",
238
+ priority: "medium",
239
+ description: `Memory usage ${memoryUsed}MB exceeds target by ${(
240
+ ((memoryUsed - memoryTarget) / memoryTarget) *
241
+ 100
242
+ ).toFixed(1)}%`,
243
+ action: "Review memory allocation patterns and object cleanup",
244
+ estimatedImpact: -25,
245
+ });
246
+ }
247
+
248
+ // Pool scaling recommendations
249
+ if (executionTime > executionTimeTarget * 1.5) {
250
+ this.recommendations.push({
251
+ type: "scaling",
252
+ priority: "medium",
253
+ description: "Pool may need scaling due to high execution times",
254
+ action: "Consider increasing pool size or optimizing isolation setup",
255
+ estimatedImpact: -20,
256
+ });
257
+ }
258
+ }
259
+
260
+ /**
261
+ * Get current performance snapshot
262
+ */
263
+ public getSnapshot(): PerformanceSnapshot {
264
+ const snapshot: PerformanceSnapshot = {
265
+ timestamp: new Date(),
266
+ metrics: {},
267
+ averages: {},
268
+ violations: [...this.violations],
269
+ recommendations: [...this.recommendations],
270
+ };
271
+
272
+ // Calculate averages for each metric
273
+ for (const target of performanceTargets) {
274
+ const metrics = this.metrics.get(target.metric) || [];
275
+ if (metrics.length > 0) {
276
+ const values = metrics.map((m) => m.value);
277
+ const average = values.reduce((a, b) => a + b, 0) / values.length;
278
+ snapshot.metrics[target.metric] = values;
279
+ snapshot.averages[target.metric] = Math.round(average * 100) / 100;
280
+ }
281
+ }
282
+
283
+ return snapshot;
284
+ }
285
+
286
+ /**
287
+ * Get performance statistics for a specific period
288
+ */
289
+ public getStats(
290
+ metric: string,
291
+ period: number = 5 * 60 * 1000
292
+ ): {
293
+ average: number;
294
+ min: number;
295
+ max: number;
296
+ count: number;
297
+ violations: number;
298
+ } {
299
+ const metrics = this.metrics.get(metric) || [];
300
+ const cutoff = new Date(Date.now() - period);
301
+
302
+ const recentMetrics = metrics.filter((m) => m.timestamp >= cutoff);
303
+ if (recentMetrics.length === 0) {
304
+ return {
305
+ average: 0,
306
+ min: 0,
307
+ max: 0,
308
+ count: 0,
309
+ violations: 0,
310
+ };
311
+ }
312
+
313
+ const values = recentMetrics.map((m) => m.value);
314
+ const target = performanceTargets.find((t) => t.metric === metric);
315
+
316
+ return {
317
+ average: values.reduce((a, b) => a + b, 0) / recentMetrics.length,
318
+ min: Math.min(...values),
319
+ max: Math.max(...values),
320
+ count: recentMetrics.length,
321
+ violations: this.violations.filter((v) => {
322
+ return (
323
+ v.metric === metric &&
324
+ v.timestamp >= cutoff &&
325
+ v.value > (target?.target || 0)
326
+ );
327
+ }).length,
328
+ };
329
+ }
330
+
331
+ /**
332
+ * Check if performance is within acceptable ranges
333
+ */
334
+ public isPerformanceHealthy(): boolean {
335
+ const snapshot = this.getSnapshot();
336
+
337
+ // Check if any critical violations in last 5 minutes
338
+ const recentViolations = this.violations.filter(
339
+ (v) =>
340
+ v.timestamp >= new Date(Date.now() - 5 * 60 * 1000) &&
341
+ v.severity === "critical"
342
+ );
343
+
344
+ if (recentViolations.length > 3) {
345
+ return false; // More than 3 critical violations
346
+ }
347
+
348
+ // Check if averages are within acceptable ranges
349
+ for (const target of performanceTargets) {
350
+ const average = snapshot.averages[target.metric];
351
+ if (average && average > target.target * this.alertThreshold) {
352
+ return false; // Performance target exceeded
353
+ }
354
+ }
355
+
356
+ return true;
357
+ }
358
+
359
+ /**
360
+ * Get performance alerts
361
+ */
362
+ public getAlerts(): {
363
+ warnings: Violation[];
364
+ criticals: Violation[];
365
+ } {
366
+ const now = new Date();
367
+ const recentViolations = this.violations.filter(
368
+ (v) => v.timestamp >= new Date(now.getTime() - 15 * 60 * 1000) // Last 15 minutes
369
+ );
370
+
371
+ return {
372
+ warnings: recentViolations.filter((v) => v.severity === "warning"),
373
+ criticals: recentViolations.filter((v) => v.severity === "critical"),
374
+ };
375
+ }
376
+
377
+ /**
378
+ * Cleanup metrics older than retention period
379
+ */
380
+ private cleanupOldMetrics(metric: string, maxAge: number): void {
381
+ const metrics = this.metrics.get(metric) || [];
382
+ const cutoff = new Date(Date.now() - maxAge);
383
+
384
+ const filteredMetrics = metrics.filter((m) => m.timestamp >= cutoff);
385
+ this.metrics.set(metric, filteredMetrics);
386
+ }
387
+
388
+ /**
389
+ * Start periodic cleanup interval
390
+ */
391
+ private startCleanupInterval(): void {
392
+ setInterval(() => {
393
+ for (const [metric] of this.metrics) {
394
+ this.cleanupOldMetrics(metric, this.retentionPeriod);
395
+ }
396
+
397
+ // Remove old violations
398
+ const cutoff = new Date(Date.now() - this.retentionPeriod);
399
+ this.violations = this.violations.filter((v) => v.timestamp >= cutoff);
400
+
401
+ // Remove old recommendations
402
+ if (this.recommendations.length > 100) {
403
+ this.recommendations = this.recommendations.slice(-100);
404
+ }
405
+ }, this.retentionPeriod / 2);
406
+ }
407
+
408
+ /**
409
+ * Get performance summary
410
+ */
411
+ public getPerformanceSummary(): {
412
+ overall: "excellent" | "good" | "warning" | "critical";
413
+ executionTime: number; // average ms
414
+ memoryUsage: number; // average MB
415
+ successRate: number; // percentage
416
+ alerts: number;
417
+ recommendations: number;
418
+ } {
419
+ const snapshot = this.getSnapshot();
420
+ const alerts = this.getAlerts();
421
+
422
+ // Calculate overall performance rating
423
+ let overall: "excellent" | "good" | "warning" | "critical" = "excellent";
424
+ if (alerts.criticals.length > 0) overall = "critical";
425
+ else if (alerts.warnings.length > 3) overall = "warning";
426
+ else if (alerts.warnings.length > 0) overall = "good";
427
+
428
+ return {
429
+ overall,
430
+ executionTime: snapshot.averages["executionTime"] || 0,
431
+ memoryUsage: snapshot.averages["memoryUsage"] || 0,
432
+ successRate: snapshot.averages["successRate"] || 99.9,
433
+ alerts: alerts.warnings.length + alerts.criticals.length,
434
+ recommendations: this.recommendations.length,
435
+ };
436
+ }
437
+
438
+ /**
439
+ * Dump performance data for analysis
440
+ */
441
+ public dumpData(): string {
442
+ const snapshot = this.getSnapshot();
443
+ const summary = this.getPerformanceSummary();
444
+
445
+ return JSON.stringify(
446
+ {
447
+ snapshot,
448
+ summary,
449
+ violations: this.violations.slice(-50), // Last 50 violations
450
+ recommendations: this.recommendations.slice(-20), // Last 20 recommendations
451
+ },
452
+ null,
453
+ 2
454
+ );
455
+ }
456
+
457
+ /**
458
+ * Dispose of monitor resources
459
+ */
460
+ public dispose(): void {
461
+ this.metrics.clear();
462
+ this.violations = [];
463
+ this.recommendations = [];
464
+ }
465
+ }
466
+
467
+ // Singleton instance
468
+ export const performanceMonitor = new PerformanceMonitor();
469
+ export default PerformanceMonitor;