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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**

 * PerformanceAnalyzer - Detect performance bottlenecks and anti-patterns

 * Identifies: Nested loops, sync I/O, N+1 queries, memory leaks, blocking operations

 */
class PerformanceAnalyzer {
    constructor() {
        this.version = '1.0.0';
    }

    /**

     * Analyze performance patterns

     * @param {Array} files - All files with content

     * @returns {Object} Performance analysis

     */
    analyze(files) {
        const nestedLoops = this.detectNestedLoops(files);
        const syncIO = this.detectSynchronousIO(files);
        const nPlusOne = this.detectNPlusOneQueries(files);
        const memoryLeaks = this.detectMemoryLeakPatterns(files);
        const blockingOps = this.detectBlockingOperations(files);
        const inefficientRegex = this.detectInefficientRegex(files);
        const hotspots = this.identifyHotspots(nestedLoops, syncIO, nPlusOne, memoryLeaks, blockingOps);

        return {
            nestedLoops,
            synchronousIO: syncIO,
            nPlusOneQueries: nPlusOne,
            memoryLeaks,
            blockingOperations: blockingOps,
            inefficientRegex,
            hotspots,
            summary: this.generateSummary(nestedLoops, syncIO, nPlusOne, memoryLeaks, blockingOps, inefficientRegex)
        };
    }

    /**

     * Detect nested loops (O(n²) or worse complexity)

     */
    detectNestedLoops(files) {
        const issues = [];

        files.forEach(file => {
            if (!file.content) return;

            const lines = file.content.split('\n');
            const loopStack = [];

            lines.forEach((line, lineIndex) => {
                const trimmed = line.trim();

                // Detect loop start
                if (/\b(?:for|while|forEach|map|filter|reduce)\s*\(/.test(trimmed)) {
                    loopStack.push({
                        type: this.identifyLoopType(trimmed),
                        line: lineIndex + 1,
                        depth: loopStack.length + 1
                    });
                }

                // Detect loop end (simplified - check closing braces)
                if (trimmed === '}' && loopStack.length > 0) {
                    const loop = loopStack.pop();

                    // Report nested loops
                    if (loop.depth >= 2) {
                        const complexity = this.calculateLoopComplexity(loop.depth);
                        issues.push({
                            type: 'NESTED_LOOP',
                            file: file.filePath,
                            line: loop.line,
                            depth: loop.depth,
                            complexity,
                            severity: loop.depth >= 3 ? 'CRITICAL' : 'HIGH',
                            message: `Nested loop with depth ${loop.depth} (${complexity} complexity)`,
                            recommendation: 'Consider using hash maps, caching, or algorithmic optimization',
                            performanceImpact: this.estimatePerformanceImpact(loop.depth)
                        });
                    }
                }
            });
        });

        return issues;
    }

    /**

     * Identify loop type

     */
    identifyLoopType(line) {
        if (/\bfor\s*\(/.test(line)) return 'for';
        if (/\bwhile\s*\(/.test(line)) return 'while';
        if (/\bforEach\s*\(/.test(line)) return 'forEach';
        if (/\bmap\s*\(/.test(line)) return 'map';
        if (/\bfilter\s*\(/.test(line)) return 'filter';
        if (/\breduce\s*\(/.test(line)) return 'reduce';
        return 'loop';
    }

    /**

     * Calculate loop complexity notation

     */
    calculateLoopComplexity(depth) {
        const notations = ['O(n)', 'O(n²)', 'O(n³)', 'O(n⁴)', 'O(n⁵)'];
        return notations[depth - 1] || `O(n^${depth})`;
    }

    /**

     * Estimate performance impact

     */
    estimatePerformanceImpact(depth) {
        const impacts = {
            1: 'LINEAR - Acceptable',
            2: 'QUADRATIC - May slow with large datasets',
            3: 'CUBIC - Critical performance issue',
            4: 'POLYNOMIAL - Severe performance bottleneck'
        };
        return impacts[depth] || 'EXPONENTIAL - Catastrophic performance';
    }

    /**

     * Detect synchronous I/O in async context

     */
    detectSynchronousIO(files) {
        const issues = [];

        const syncPatterns = [
            { pattern: /fs\.readFileSync\(/g, api: 'fs.readFileSync', alternative: 'fs.promises.readFile' },
            { pattern: /fs\.writeFileSync\(/g, api: 'fs.writeFileSync', alternative: 'fs.promises.writeFile' },
            { pattern: /fs\.readdirSync\(/g, api: 'fs.readdirSync', alternative: 'fs.promises.readdir' },
            { pattern: /fs\.statSync\(/g, api: 'fs.statSync', alternative: 'fs.promises.stat' },
            { pattern: /child_process\.execSync\(/g, api: 'child_process.execSync', alternative: 'child_process.exec with promises' },
            { pattern: /child_process\.spawnSync\(/g, api: 'child_process.spawnSync', alternative: 'child_process.spawn' },
            { pattern: /crypto\.pbkdf2Sync\(/g, api: 'crypto.pbkdf2Sync', alternative: 'crypto.pbkdf2 (async)' }
        ];

        files.forEach(file => {
            if (!file.content) return;

            const lines = file.content.split('\n');
            const isAsync = file.content.includes('async ') || file.content.includes('await ');

            lines.forEach((line, lineIndex) => {
                syncPatterns.forEach(({ pattern, api, alternative }) => {
                    if (pattern.test(line)) {
                        issues.push({
                            type: 'SYNCHRONOUS_IO',
                            file: file.filePath,
                            line: lineIndex + 1,
                            api,
                            severity: isAsync ? 'CRITICAL' : 'HIGH',
                            message: `Synchronous I/O operation ${api} ${isAsync ? 'in async function' : ''}`,
                            recommendation: `Replace with ${alternative}`,
                            performanceImpact: 'Blocks event loop, reduces throughput'
                        });
                    }
                    pattern.lastIndex = 0;
                });
            });
        });

        return issues;
    }

    /**

     * Detect N+1 query patterns

     */
    detectNPlusOneQueries(files) {
        const issues = [];

        files.forEach(file => {
            if (!file.content) return;

            const lines = file.content.split('\n');
            
            // Pattern: Query in loop
            let inLoop = false;
            let loopStartLine = 0;

            lines.forEach((line, lineIndex) => {
                // Detect loop
                if (/\b(?:for|while|forEach|map)\s*\(/.test(line)) {
                    inLoop = true;
                    loopStartLine = lineIndex + 1;
                }

                // Detect query inside loop
                if (inLoop) {
                    const queryPatterns = [
                        /\.find\(/,
                        /\.findOne\(/,
                        /\.findById\(/,
                        /\.get\(/,
                        /\.query\(/,
                        /SELECT\s+.*FROM/i,
                        /await\s+\w+\.(find|get|query)/
                    ];

                    if (queryPatterns.some(pattern => pattern.test(line))) {
                        issues.push({
                            type: 'N_PLUS_ONE_QUERY',
                            file: file.filePath,
                            line: lineIndex + 1,
                            loopLine: loopStartLine,
                            severity: 'CRITICAL',
                            message: 'Database query inside loop (N+1 problem)',
                            recommendation: 'Use batch loading, joins, or eager loading (e.g., .populate(), .include())',
                            performanceImpact: 'Exponential database queries, severe performance degradation'
                        });
                    }
                }

                // Detect loop end
                if (line.trim() === '}' && inLoop) {
                    inLoop = false;
                }
            });
        });

        return issues;
    }

    /**

     * Detect memory leak patterns

     */
    detectMemoryLeakPatterns(files) {
        const issues = [];

        files.forEach(file => {
            if (!file.content) return;

            const lines = file.content.split('\n');

            lines.forEach((line, lineIndex) => {
                // Event listeners without removal
                if (/\.addEventListener\(|\.on\(/.test(line)) {
                    const hasRemoveListener = file.content.includes('removeEventListener') || 
                                             file.content.includes('.off(') ||
                                             file.content.includes('cleanup');
                    
                    if (!hasRemoveListener) {
                        issues.push({
                            type: 'MEMORY_LEAK_EVENT_LISTENER',
                            file: file.filePath,
                            line: lineIndex + 1,
                            severity: 'HIGH',
                            message: 'Event listener added without cleanup',
                            recommendation: 'Add removeEventListener in cleanup/unmount',
                            performanceImpact: 'Memory accumulation over time'
                        });
                    }
                }

                // Timers without clearing
                if (/setInterval\(|setTimeout\(/.test(line)) {
                    const hasClearTimer = file.content.includes('clearInterval') || 
                                         file.content.includes('clearTimeout');
                    
                    if (!hasClearTimer) {
                        issues.push({
                            type: 'MEMORY_LEAK_TIMER',
                            file: file.filePath,
                            line: lineIndex + 1,
                            severity: 'HIGH',
                            message: 'Timer created without cleanup',
                            recommendation: 'Clear timer in cleanup function',
                            performanceImpact: 'Memory and CPU accumulation'
                        });
                    }
                }

                // Closures holding large objects
                if (/function\s*\([^)]*\)\s*{[\s\S]*?const\s+\w+\s*=\s*\[/.test(line)) {
                    issues.push({
                        type: 'MEMORY_LEAK_CLOSURE',
                        file: file.filePath,
                        line: lineIndex + 1,
                        severity: 'MEDIUM',
                        message: 'Closure may capture large data structures',
                        recommendation: 'Review closure scope, release references when done',
                        performanceImpact: 'Prevents garbage collection'
                    });
                }

                // Unclosed resources
                const resourcePatterns = [
                    { pattern: /new\s+FileReader\(/, cleanup: 'abort()' },
                    { pattern: /fs\.createReadStream\(/, cleanup: '.close()' },
                    { pattern: /new\s+WebSocket\(/, cleanup: '.close()' },
                    { pattern: /database\.connect\(/, cleanup: '.disconnect()' }
                ];

                resourcePatterns.forEach(({ pattern, cleanup }) => {
                    if (pattern.test(line) && !file.content.includes(cleanup)) {
                        issues.push({
                            type: 'UNCLOSED_RESOURCE',
                            file: file.filePath,
                            line: lineIndex + 1,
                            severity: 'HIGH',
                            message: 'Resource opened without explicit cleanup',
                            recommendation: `Ensure ${cleanup} is called`,
                            performanceImpact: 'Resource exhaustion, file descriptor leaks'
                        });
                    }
                });
            });
        });

        return issues;
    }

    /**

     * Detect blocking operations

     */
    detectBlockingOperations(files) {
        const issues = [];

        const blockingPatterns = [
            { pattern: /while\s*\(\s*true\s*\)/g, name: 'Infinite loop', severity: 'CRITICAL' },
            { pattern: /for\s*\(\s*;\s*;\s*\)/g, name: 'Infinite for loop', severity: 'CRITICAL' },
            { pattern: /\.sort\(\s*\)/g, name: 'Array sort (O(n log n))', severity: 'MEDIUM' },
            { pattern: /JSON\.parse\(/g, name: 'JSON.parse (synchronous)', severity: 'LOW' },
            { pattern: /JSON\.stringify\(/g, name: 'JSON.stringify (synchronous)', severity: 'LOW' },
            { pattern: /crypto\.pbkdf2Sync\(/g, name: 'Synchronous crypto operation', severity: 'HIGH' },
            { pattern: /\.match\([^)]{50,}\)/g, name: 'Complex regex match', severity: 'MEDIUM' }
        ];

        files.forEach(file => {
            if (!file.content) return;

            const lines = file.content.split('\n');

            lines.forEach((line, lineIndex) => {
                blockingPatterns.forEach(({ pattern, name, severity }) => {
                    if (pattern.test(line)) {
                        issues.push({
                            type: 'BLOCKING_OPERATION',
                            file: file.filePath,
                            line: lineIndex + 1,
                            operation: name,
                            severity,
                            message: `Blocking operation: ${name}`,
                            recommendation: this.getBlockingRecommendation(name),
                            performanceImpact: 'Blocks event loop, reduces responsiveness'
                        });
                    }
                    pattern.lastIndex = 0;
                });
            });
        });

        return issues;
    }

    /**

     * Get recommendation for blocking operation

     */
    getBlockingRecommendation(operation) {
        const recommendations = {
            'Infinite loop': 'Add exit condition or use worker thread',
            'Infinite for loop': 'Add proper loop termination',
            'Array sort (O(n log n))': 'Consider pre-sorting or using indexed structure',
            'JSON.parse (synchronous)': 'For large JSON, consider streaming parser',
            'JSON.stringify (synchronous)': 'For large objects, consider streaming serializer',
            'Synchronous crypto operation': 'Use async version',
            'Complex regex match': 'Simplify regex or use multiple simpler patterns'
        };
        return recommendations[operation] || 'Optimize or make async';
    }

    /**

     * Detect inefficient regex patterns

     */
    detectInefficientRegex(files) {
        const issues = [];

        files.forEach(file => {
            if (!file.content) return;

            const lines = file.content.split('\n');

            lines.forEach((line, lineIndex) => {
                // Find regex patterns
                const regexMatches = line.match(/\/([^\/]+)\/[gimuy]*/g) || [];
                
                regexMatches.forEach(regexStr => {
                    // Detect catastrophic backtracking patterns
                    const catastrophicPatterns = [
                        { pattern: /\(\.\*\)\+|\(\.\+\)\+/, issue: 'Nested quantifiers' },
                        { pattern: /\([^)]*\*[^)]*\)\*/, issue: 'Nested star operators' },
                        { pattern: /\([^)]*\+[^)]*\)\+/, issue: 'Nested plus operators' },
                        { pattern: /\([^|]+\|[^|]+\)\+/, issue: 'Alternation with quantifier' }
                    ];

                    catastrophicPatterns.forEach(({ pattern, issue }) => {
                        if (pattern.test(regexStr)) {
                            issues.push({
                                type: 'CATASTROPHIC_BACKTRACKING',
                                file: file.filePath,
                                line: lineIndex + 1,
                                regex: regexStr,
                                issue,
                                severity: 'CRITICAL',
                                message: `Regex with potential catastrophic backtracking: ${issue}`,
                                recommendation: 'Simplify regex, use atomic groups, or non-backtracking patterns',
                                performanceImpact: 'Exponential time complexity, can hang application'
                            });
                        }
                    });

                    // Detect overly complex regex
                    if (regexStr.length > 100) {
                        issues.push({
                            type: 'COMPLEX_REGEX',
                            file: file.filePath,
                            line: lineIndex + 1,
                            regex: regexStr.substring(0, 50) + '...',
                            severity: 'MEDIUM',
                            message: 'Overly complex regex pattern',
                            recommendation: 'Break into smaller patterns or use parser',
                            performanceImpact: 'Slow pattern matching'
                        });
                    }
                });
            });
        });

        return issues;
    }

    /**

     * Identify performance hotspots

     */
    identifyHotspots(nestedLoops, syncIO, nPlusOne, memoryLeaks, blockingOps) {
        const allIssues = [
            ...nestedLoops,
            ...syncIO,
            ...nPlusOne,
            ...memoryLeaks,
            ...blockingOps
        ];

        // Group by file
        const byFile = {};
        allIssues.forEach(issue => {
            if (!byFile[issue.file]) {
                byFile[issue.file] = {
                    file: issue.file,
                    issues: [],
                    criticalCount: 0,
                    highCount: 0,
                    score: 0
                };
            }

            byFile[issue.file].issues.push(issue);
            
            if (issue.severity === 'CRITICAL') {
                byFile[issue.file].criticalCount++;
                byFile[issue.file].score += 10;
            } else if (issue.severity === 'HIGH') {
                byFile[issue.file].highCount++;
                byFile[issue.file].score += 5;
            } else {
                byFile[issue.file].score += 1;
            }
        });

        // Top 10 hotspots
        return Object.values(byFile)
            .sort((a, b) => b.score - a.score)
            .slice(0, 10)
            .map(hotspot => ({
                ...hotspot,
                priority: hotspot.criticalCount > 0 ? 'CRITICAL' : hotspot.highCount > 2 ? 'HIGH' : 'MEDIUM',
                recommendation: this.generateHotspotRecommendation(hotspot)
            }));
    }

    /**

     * Generate hotspot recommendation

     */
    generateHotspotRecommendation(hotspot) {
        const recommendations = [];

        if (hotspot.criticalCount > 0) {
            recommendations.push(`Address ${hotspot.criticalCount} critical performance issues immediately`);
        }

        const types = hotspot.issues.map(i => i.type);
        if (types.includes('NESTED_LOOP')) {
            recommendations.push('Optimize nested loops with better algorithms or caching');
        }
        if (types.includes('N_PLUS_ONE_QUERY')) {
            recommendations.push('Implement batch loading or eager loading for database queries');
        }
        if (types.includes('SYNCHRONOUS_IO')) {
            recommendations.push('Convert synchronous I/O to async operations');
        }

        return recommendations.length > 0 ? recommendations : ['Review and optimize performance patterns'];
    }

    /**

     * Generate summary

     */
    generateSummary(nestedLoops, syncIO, nPlusOne, memoryLeaks, blockingOps, inefficientRegex) {
        return {
            totalIssues: nestedLoops.length + syncIO.length + nPlusOne.length + memoryLeaks.length + blockingOps.length + inefficientRegex.length,
            nestedLoops: nestedLoops.length,
            synchronousIO: syncIO.length,
            nPlusOneQueries: nPlusOne.length,
            memoryLeaks: memoryLeaks.length,
            blockingOperations: blockingOps.length,
            inefficientRegex: inefficientRegex.length,
            criticalIssues: [
                ...nestedLoops.filter(i => i.severity === 'CRITICAL'),
                ...syncIO.filter(i => i.severity === 'CRITICAL'),
                ...nPlusOne,
                ...inefficientRegex.filter(i => i.severity === 'CRITICAL')
            ].length
        };
    }
}

module.exports = PerformanceAnalyzer;