@oxog/react-check 1.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.
@@ -0,0 +1,1660 @@
1
+ 'use strict';
2
+
3
+ // src/utils/event-emitter.ts
4
+ var EventEmitter = class {
5
+ /** Map of event names to their listeners */
6
+ _listeners = /* @__PURE__ */ new Map();
7
+ /** Map of event names to their one-time listeners */
8
+ _onceListeners = /* @__PURE__ */ new Map();
9
+ /** Maximum number of listeners per event (0 = unlimited) */
10
+ maxListeners = 0;
11
+ /**
12
+ * Add an event listener
13
+ * @param event - Event name
14
+ * @param listener - Callback function
15
+ * @returns this for chaining
16
+ */
17
+ on(event, listener) {
18
+ let eventListeners = this._listeners.get(event);
19
+ if (!eventListeners) {
20
+ eventListeners = /* @__PURE__ */ new Set();
21
+ this._listeners.set(event, eventListeners);
22
+ }
23
+ if (this.maxListeners > 0 && eventListeners.size >= this.maxListeners) {
24
+ console.warn(
25
+ `Warning: Possible EventEmitter memory leak detected. ${eventListeners.size + 1} listeners added for event "${String(event)}". Use setMaxListeners() to increase limit.`
26
+ );
27
+ }
28
+ eventListeners.add(listener);
29
+ return this;
30
+ }
31
+ /**
32
+ * Alias for on()
33
+ */
34
+ addListener(event, listener) {
35
+ return this.on(event, listener);
36
+ }
37
+ /**
38
+ * Add a one-time event listener
39
+ * @param event - Event name
40
+ * @param listener - Callback function
41
+ * @returns this for chaining
42
+ */
43
+ once(event, listener) {
44
+ let eventListeners = this._onceListeners.get(event);
45
+ if (!eventListeners) {
46
+ eventListeners = /* @__PURE__ */ new Set();
47
+ this._onceListeners.set(event, eventListeners);
48
+ }
49
+ eventListeners.add(listener);
50
+ return this;
51
+ }
52
+ /**
53
+ * Remove an event listener
54
+ * @param event - Event name
55
+ * @param listener - Callback function to remove
56
+ * @returns this for chaining
57
+ */
58
+ off(event, listener) {
59
+ const eventListeners = this._listeners.get(event);
60
+ if (eventListeners) {
61
+ eventListeners.delete(listener);
62
+ if (eventListeners.size === 0) {
63
+ this._listeners.delete(event);
64
+ }
65
+ }
66
+ const onceEventListeners = this._onceListeners.get(event);
67
+ if (onceEventListeners) {
68
+ onceEventListeners.delete(listener);
69
+ if (onceEventListeners.size === 0) {
70
+ this._onceListeners.delete(event);
71
+ }
72
+ }
73
+ return this;
74
+ }
75
+ /**
76
+ * Alias for off()
77
+ */
78
+ removeListener(event, listener) {
79
+ return this.off(event, listener);
80
+ }
81
+ /**
82
+ * Remove all listeners for an event, or all events if no event specified
83
+ * @param event - Optional event name
84
+ * @returns this for chaining
85
+ */
86
+ removeAllListeners(event) {
87
+ if (event !== void 0) {
88
+ this._listeners.delete(event);
89
+ this._onceListeners.delete(event);
90
+ } else {
91
+ this._listeners.clear();
92
+ this._onceListeners.clear();
93
+ }
94
+ return this;
95
+ }
96
+ /**
97
+ * Emit an event
98
+ * @param event - Event name
99
+ * @param data - Event data
100
+ * @returns true if any listeners were called
101
+ */
102
+ emit(event, data) {
103
+ let called = false;
104
+ const eventListeners = this._listeners.get(event);
105
+ if (eventListeners) {
106
+ for (const listener of eventListeners) {
107
+ try {
108
+ listener(data);
109
+ called = true;
110
+ } catch (error) {
111
+ if (event !== "error") {
112
+ this.emit("error", error);
113
+ } else {
114
+ throw error;
115
+ }
116
+ }
117
+ }
118
+ }
119
+ const onceEventListeners = this._onceListeners.get(event);
120
+ if (onceEventListeners) {
121
+ const listenersToCall = Array.from(onceEventListeners);
122
+ this._onceListeners.delete(event);
123
+ for (const listener of listenersToCall) {
124
+ try {
125
+ listener(data);
126
+ called = true;
127
+ } catch (error) {
128
+ if (event !== "error") {
129
+ this.emit("error", error);
130
+ } else {
131
+ throw error;
132
+ }
133
+ }
134
+ }
135
+ }
136
+ return called;
137
+ }
138
+ /**
139
+ * Get all listener functions for an event
140
+ * @param event - Event name
141
+ * @returns Array of listener functions
142
+ */
143
+ getListeners(event) {
144
+ const regular = this._listeners.get(event);
145
+ const once = this._onceListeners.get(event);
146
+ const result = [];
147
+ if (regular) {
148
+ result.push(...Array.from(regular));
149
+ }
150
+ if (once) {
151
+ result.push(...Array.from(once));
152
+ }
153
+ return result;
154
+ }
155
+ /**
156
+ * Get the number of listeners for an event
157
+ * @param event - Event name
158
+ * @returns Number of listeners
159
+ */
160
+ listenerCount(event) {
161
+ const regular = this._listeners.get(event)?.size ?? 0;
162
+ const once = this._onceListeners.get(event)?.size ?? 0;
163
+ return regular + once;
164
+ }
165
+ /**
166
+ * Get all event names that have listeners
167
+ * @returns Array of event names
168
+ */
169
+ eventNames() {
170
+ const names = /* @__PURE__ */ new Set();
171
+ for (const name of this._listeners.keys()) {
172
+ names.add(name);
173
+ }
174
+ for (const name of this._onceListeners.keys()) {
175
+ names.add(name);
176
+ }
177
+ return Array.from(names);
178
+ }
179
+ /**
180
+ * Set the maximum number of listeners per event
181
+ * @param n - Maximum listeners (0 for unlimited)
182
+ * @returns this for chaining
183
+ */
184
+ setMaxListeners(n) {
185
+ this.maxListeners = n;
186
+ return this;
187
+ }
188
+ /**
189
+ * Get the maximum number of listeners per event
190
+ * @returns Maximum listeners
191
+ */
192
+ getMaxListeners() {
193
+ return this.maxListeners;
194
+ }
195
+ /**
196
+ * Prepend a listener to the beginning of the listeners array
197
+ * @param event - Event name
198
+ * @param listener - Callback function
199
+ * @returns this for chaining
200
+ */
201
+ prependListener(event, listener) {
202
+ const eventListeners = this._listeners.get(event);
203
+ if (!eventListeners) {
204
+ return this.on(event, listener);
205
+ }
206
+ const arr = Array.from(eventListeners);
207
+ arr.unshift(listener);
208
+ this._listeners.set(event, new Set(arr));
209
+ return this;
210
+ }
211
+ /**
212
+ * Prepend a one-time listener to the beginning
213
+ * @param event - Event name
214
+ * @param listener - Callback function
215
+ * @returns this for chaining
216
+ */
217
+ prependOnceListener(event, listener) {
218
+ const eventListeners = this._onceListeners.get(event);
219
+ if (!eventListeners) {
220
+ return this.once(event, listener);
221
+ }
222
+ const arr = Array.from(eventListeners);
223
+ arr.unshift(listener);
224
+ this._onceListeners.set(event, new Set(arr));
225
+ return this;
226
+ }
227
+ /**
228
+ * Wait for an event to be emitted
229
+ * @param event - Event name
230
+ * @param timeout - Optional timeout in milliseconds
231
+ * @returns Promise that resolves with the event data
232
+ */
233
+ waitFor(event, timeout) {
234
+ return new Promise((resolve, reject) => {
235
+ let timeoutId;
236
+ const listener = (data) => {
237
+ if (timeoutId) {
238
+ clearTimeout(timeoutId);
239
+ }
240
+ resolve(data);
241
+ };
242
+ this.once(event, listener);
243
+ if (timeout !== void 0 && timeout > 0) {
244
+ timeoutId = setTimeout(() => {
245
+ this.off(event, listener);
246
+ reject(new Error(`Timeout waiting for event "${String(event)}"`));
247
+ }, timeout);
248
+ }
249
+ });
250
+ }
251
+ };
252
+
253
+ // src/core/stats.ts
254
+ var DEFAULT_THRESHOLDS = {
255
+ critical: 50,
256
+ warning: 20,
257
+ fps: 30
258
+ };
259
+ var StatsCollector = class extends EventEmitter {
260
+ /** Map of component names to their statistics */
261
+ components = /* @__PURE__ */ new Map();
262
+ /** Threshold configuration */
263
+ thresholds;
264
+ /** Session start time */
265
+ sessionStart;
266
+ /** Total render count across all components */
267
+ totalRenders = 0;
268
+ /** FPS samples for averaging */
269
+ fpsSamples = [];
270
+ /** Maximum FPS samples to keep */
271
+ maxFpsSamples = 100;
272
+ /**
273
+ * Create a new StatsCollector
274
+ * @param thresholds - Threshold configuration
275
+ */
276
+ constructor(thresholds = {}) {
277
+ super();
278
+ this.thresholds = { ...DEFAULT_THRESHOLDS, ...thresholds };
279
+ this.sessionStart = Date.now();
280
+ }
281
+ /**
282
+ * Add a render event to the statistics
283
+ * @param render - Render information
284
+ */
285
+ addRender(render) {
286
+ const stats = this.getOrCreateStats(render.componentName);
287
+ const previousSeverity = stats.severity;
288
+ stats.renders++;
289
+ this.totalRenders++;
290
+ stats.totalRenderTime += render.renderTime;
291
+ stats.avgRenderTime = stats.totalRenderTime / stats.renders;
292
+ stats.maxRenderTime = Math.max(stats.maxRenderTime, render.renderTime);
293
+ stats.minRenderTime = Math.min(stats.minRenderTime, render.renderTime);
294
+ if (!render.necessary) {
295
+ stats.unnecessary++;
296
+ }
297
+ if (stats.firstRender === 0) {
298
+ stats.firstRender = render.timestamp;
299
+ }
300
+ stats.lastRender = render.timestamp;
301
+ if (render.changedProps && render.changedProps.length > 0) {
302
+ stats.propsChanged = true;
303
+ }
304
+ if (render.changedState && render.changedState.length > 0) {
305
+ stats.stateChanged = true;
306
+ }
307
+ const sessionDuration = Date.now() - this.sessionStart;
308
+ const sessionMinutes = sessionDuration / 6e4;
309
+ stats.expectedRenders = Math.max(1, Math.ceil(sessionMinutes * 5));
310
+ this.updateSeverity(stats);
311
+ this.emit("update", stats);
312
+ if (stats.severity !== previousSeverity) {
313
+ this.emit("severityChange", {
314
+ component: stats.name,
315
+ from: previousSeverity,
316
+ to: stats.severity
317
+ });
318
+ if (stats.severity === "critical" && previousSeverity !== "critical") {
319
+ this.emit("critical", stats);
320
+ } else if (stats.severity === "warning" && previousSeverity === "healthy") {
321
+ this.emit("warning", stats);
322
+ }
323
+ }
324
+ }
325
+ /**
326
+ * Record an FPS sample
327
+ * @param fps - FPS value
328
+ */
329
+ addFpsSample(fps) {
330
+ this.fpsSamples.push(fps);
331
+ if (this.fpsSamples.length > this.maxFpsSamples) {
332
+ this.fpsSamples.shift();
333
+ }
334
+ }
335
+ /**
336
+ * Get or create stats for a component
337
+ * @param name - Component name
338
+ * @returns Component stats
339
+ */
340
+ getOrCreateStats(name) {
341
+ let stats = this.components.get(name);
342
+ if (!stats) {
343
+ stats = this.createEmptyStats(name);
344
+ this.components.set(name, stats);
345
+ }
346
+ return stats;
347
+ }
348
+ /**
349
+ * Create empty stats for a component
350
+ * @param name - Component name
351
+ * @returns Empty component stats
352
+ */
353
+ createEmptyStats(name) {
354
+ return {
355
+ name,
356
+ renders: 0,
357
+ expectedRenders: 1,
358
+ avgRenderTime: 0,
359
+ maxRenderTime: 0,
360
+ minRenderTime: Infinity,
361
+ totalRenderTime: 0,
362
+ unnecessary: 0,
363
+ severity: "healthy",
364
+ chain: [],
365
+ fixes: [],
366
+ firstRender: 0,
367
+ lastRender: 0,
368
+ propsChanged: false,
369
+ stateChanged: false
370
+ };
371
+ }
372
+ /**
373
+ * Update severity for a component based on thresholds
374
+ * @param stats - Component stats to update
375
+ */
376
+ updateSeverity(stats) {
377
+ if (stats.renders >= this.thresholds.critical) {
378
+ stats.severity = "critical";
379
+ } else if (stats.renders >= this.thresholds.warning) {
380
+ stats.severity = "warning";
381
+ } else {
382
+ stats.severity = "healthy";
383
+ }
384
+ }
385
+ /**
386
+ * Get stats for a specific component
387
+ * @param name - Component name
388
+ * @returns Component stats or undefined
389
+ */
390
+ getComponentStats(name) {
391
+ return this.components.get(name);
392
+ }
393
+ /**
394
+ * Get all component stats
395
+ * @returns Array of component stats
396
+ */
397
+ getAllStats() {
398
+ return Array.from(this.components.values());
399
+ }
400
+ /**
401
+ * Get a snapshot of all stats sorted by severity/render count
402
+ * @returns Sorted array of component stats
403
+ */
404
+ getSnapshot() {
405
+ return this.getAllStats().sort((a, b) => {
406
+ const severityOrder = {
407
+ critical: 0,
408
+ warning: 1,
409
+ info: 2,
410
+ healthy: 3
411
+ };
412
+ const severityDiff = severityOrder[a.severity] - severityOrder[b.severity];
413
+ if (severityDiff !== 0) return severityDiff;
414
+ return b.renders - a.renders;
415
+ });
416
+ }
417
+ /**
418
+ * Get components by severity
419
+ * @param severity - Severity level to filter
420
+ * @returns Array of matching component stats
421
+ */
422
+ getComponentsBySeverity(severity) {
423
+ return this.getAllStats().filter((s) => s.severity === severity);
424
+ }
425
+ /**
426
+ * Get session summary
427
+ * @returns Session summary statistics
428
+ */
429
+ getSummary() {
430
+ const stats = this.getAllStats();
431
+ const criticalCount = stats.filter((s) => s.severity === "critical").length;
432
+ const warningCount = stats.filter((s) => s.severity === "warning").length;
433
+ const healthyCount = stats.filter((s) => s.severity === "healthy").length;
434
+ const unnecessaryCount = stats.reduce((sum, s) => sum + s.unnecessary, 0);
435
+ let avgFps = 60;
436
+ let minFps = 60;
437
+ if (this.fpsSamples.length > 0) {
438
+ avgFps = this.fpsSamples.reduce((a, b) => a + b, 0) / this.fpsSamples.length;
439
+ minFps = Math.min(...this.fpsSamples);
440
+ }
441
+ return {
442
+ totalComponents: stats.length,
443
+ totalRenders: this.totalRenders,
444
+ criticalIssues: criticalCount,
445
+ warnings: warningCount,
446
+ healthy: healthyCount,
447
+ avgFps: Math.round(avgFps),
448
+ minFps: Math.round(minFps),
449
+ unnecessaryRenders: unnecessaryCount
450
+ };
451
+ }
452
+ /**
453
+ * Get the most problematic components
454
+ * @param limit - Maximum number to return
455
+ * @returns Top problematic components
456
+ */
457
+ getTopProblems(limit = 10) {
458
+ return this.getSnapshot().filter((s) => s.severity !== "healthy").slice(0, limit);
459
+ }
460
+ /**
461
+ * Update chain information for a component
462
+ * @param componentName - Component name
463
+ * @param chain - Render chain
464
+ */
465
+ setComponentChain(componentName, chain) {
466
+ const stats = this.components.get(componentName);
467
+ if (stats) {
468
+ stats.chain = chain;
469
+ }
470
+ }
471
+ /**
472
+ * Update parent information for a component
473
+ * @param componentName - Component name
474
+ * @param parentName - Parent component name
475
+ */
476
+ setComponentParent(componentName, parentName) {
477
+ const stats = this.components.get(componentName);
478
+ if (stats) {
479
+ stats.parent = parentName;
480
+ }
481
+ }
482
+ /**
483
+ * Reset all statistics
484
+ */
485
+ reset() {
486
+ this.components.clear();
487
+ this.totalRenders = 0;
488
+ this.fpsSamples = [];
489
+ this.sessionStart = Date.now();
490
+ }
491
+ /**
492
+ * Update threshold configuration
493
+ * @param thresholds - New thresholds
494
+ */
495
+ setThresholds(thresholds) {
496
+ this.thresholds = { ...this.thresholds, ...thresholds };
497
+ for (const stats of this.components.values()) {
498
+ const previousSeverity = stats.severity;
499
+ this.updateSeverity(stats);
500
+ if (stats.severity !== previousSeverity) {
501
+ this.emit("severityChange", {
502
+ component: stats.name,
503
+ from: previousSeverity,
504
+ to: stats.severity
505
+ });
506
+ }
507
+ }
508
+ }
509
+ /**
510
+ * Get current thresholds
511
+ * @returns Current threshold configuration
512
+ */
513
+ getThresholds() {
514
+ return { ...this.thresholds };
515
+ }
516
+ /**
517
+ * Get session duration in milliseconds
518
+ * @returns Session duration
519
+ */
520
+ getSessionDuration() {
521
+ return Date.now() - this.sessionStart;
522
+ }
523
+ /**
524
+ * Get total render count
525
+ * @returns Total renders across all components
526
+ */
527
+ getTotalRenders() {
528
+ return this.totalRenders;
529
+ }
530
+ /**
531
+ * Get component count
532
+ * @returns Number of tracked components
533
+ */
534
+ getComponentCount() {
535
+ return this.components.size;
536
+ }
537
+ /**
538
+ * Check if FPS is below threshold
539
+ * @returns true if average FPS is below threshold
540
+ */
541
+ isFpsBelowThreshold() {
542
+ if (this.fpsSamples.length === 0) return false;
543
+ const avgFps = this.fpsSamples.reduce((a, b) => a + b, 0) / this.fpsSamples.length;
544
+ return avgFps < this.thresholds.fps;
545
+ }
546
+ /**
547
+ * Export stats for serialization
548
+ * @returns Serializable stats object
549
+ */
550
+ export() {
551
+ return {
552
+ components: this.getSnapshot(),
553
+ summary: this.getSummary(),
554
+ thresholds: this.getThresholds(),
555
+ sessionDuration: this.getSessionDuration()
556
+ };
557
+ }
558
+ };
559
+
560
+ // src/core/chain.ts
561
+ var ChainAnalyzer = class extends EventEmitter {
562
+ /** Time window size in ms (one frame at 60fps) */
563
+ windowSize;
564
+ /** Current render windows being tracked */
565
+ windows = /* @__PURE__ */ new Map();
566
+ /** Component parent relationships */
567
+ parentMap = /* @__PURE__ */ new Map();
568
+ /** Recently detected chains to avoid duplicates */
569
+ recentChains = /* @__PURE__ */ new Set();
570
+ /** Minimum chain depth to report */
571
+ minChainDepth;
572
+ /** Maximum time to keep recent chains */
573
+ recentChainTtl;
574
+ /**
575
+ * Create a new ChainAnalyzer
576
+ * @param options - Configuration options
577
+ */
578
+ constructor(options = {}) {
579
+ super();
580
+ this.windowSize = options.windowSize ?? 16;
581
+ this.minChainDepth = options.minChainDepth ?? 2;
582
+ this.recentChainTtl = options.recentChainTtl ?? 1e3;
583
+ }
584
+ /**
585
+ * Add a render event for analysis
586
+ * @param render - Render information
587
+ * @param parent - Optional parent component name
588
+ */
589
+ addRender(render, parent) {
590
+ const trackedRender = {
591
+ ...render,
592
+ ...parent !== void 0 ? { parent } : {},
593
+ contextTriggered: this.isContextTriggered(render)
594
+ };
595
+ if (parent) {
596
+ this.parentMap.set(render.componentName, parent);
597
+ }
598
+ const windowKey = this.getWindowKey(render.timestamp);
599
+ let window = this.windows.get(windowKey);
600
+ if (!window) {
601
+ window = {
602
+ renders: [],
603
+ startTime: render.timestamp
604
+ };
605
+ this.windows.set(windowKey, window);
606
+ }
607
+ window.renders.push(trackedRender);
608
+ if (window.renders.length >= this.minChainDepth) {
609
+ this.analyzeWindow(windowKey);
610
+ }
611
+ this.cleanupWindows(render.timestamp);
612
+ }
613
+ /**
614
+ * Set parent relationship for a component
615
+ * @param child - Child component name
616
+ * @param parent - Parent component name
617
+ */
618
+ setParent(child, parent) {
619
+ this.parentMap.set(child, parent);
620
+ }
621
+ /**
622
+ * Get window key for a timestamp
623
+ * @param timestamp - Timestamp in ms
624
+ * @returns Window key
625
+ */
626
+ getWindowKey(timestamp) {
627
+ return Math.floor(timestamp / this.windowSize);
628
+ }
629
+ /**
630
+ * Check if a render was likely triggered by context
631
+ * @param render - Render information
632
+ * @returns true if context-triggered
633
+ */
634
+ isContextTriggered(render) {
635
+ return !render.changedProps?.length && !render.changedState?.length && render.phase === "update";
636
+ }
637
+ /**
638
+ * Analyze a render window for chains
639
+ * @param windowKey - Window key to analyze
640
+ */
641
+ analyzeWindow(windowKey) {
642
+ const window = this.windows.get(windowKey);
643
+ if (!window || window.renders.length < this.minChainDepth) {
644
+ return;
645
+ }
646
+ const sortedRenders = [...window.renders].sort((a, b) => a.timestamp - b.timestamp);
647
+ const chains = this.buildChains(sortedRenders);
648
+ for (const chain of chains) {
649
+ const chainKey = this.getChainKey(chain);
650
+ if (this.recentChains.has(chainKey)) {
651
+ continue;
652
+ }
653
+ this.recentChains.add(chainKey);
654
+ setTimeout(() => {
655
+ this.recentChains.delete(chainKey);
656
+ }, this.recentChainTtl);
657
+ this.emit("chain", chain);
658
+ if (chain.isContextTriggered) {
659
+ this.emit("contextChain", chain);
660
+ }
661
+ }
662
+ }
663
+ /**
664
+ * Build chains from a sorted render sequence
665
+ * @param renders - Sorted render events
666
+ * @returns Detected chains
667
+ */
668
+ buildChains(renders) {
669
+ const chains = [];
670
+ const visited = /* @__PURE__ */ new Set();
671
+ const chainComponents = [];
672
+ for (const render of renders) {
673
+ if (visited.has(render.componentName)) {
674
+ continue;
675
+ }
676
+ const chain = this.traceChain(render.componentName, renders, visited);
677
+ if (chain.length >= this.minChainDepth) {
678
+ chainComponents.push(chain);
679
+ }
680
+ }
681
+ for (const chain of chainComponents) {
682
+ const chainRenders = renders.filter((r) => chain.includes(r.componentName));
683
+ const isContextTriggered = chainRenders.some((r) => r.contextTriggered);
684
+ const rootCause = this.findRootCause(chain, renders);
685
+ const trigger = this.determineTrigger(rootCause, renders);
686
+ chains.push({
687
+ trigger,
688
+ chain,
689
+ depth: chain.length,
690
+ totalRenders: chainRenders.length,
691
+ rootCause,
692
+ timestamp: Date.now(),
693
+ isContextTriggered
694
+ });
695
+ }
696
+ return chains;
697
+ }
698
+ /**
699
+ * Trace a chain starting from a component
700
+ * @param startComponent - Starting component
701
+ * @param renders - All renders in window
702
+ * @param visited - Already visited components
703
+ * @returns Chain of component names
704
+ */
705
+ traceChain(startComponent, renders, visited) {
706
+ const chain = [];
707
+ const queue = [startComponent];
708
+ while (queue.length > 0) {
709
+ const current = queue.shift();
710
+ if (!current || visited.has(current)) {
711
+ continue;
712
+ }
713
+ visited.add(current);
714
+ chain.push(current);
715
+ const parent = this.parentMap.get(current);
716
+ if (parent && renders.some((r) => r.componentName === parent) && !visited.has(parent)) {
717
+ queue.unshift(parent);
718
+ }
719
+ for (const [child, p] of this.parentMap) {
720
+ if (p === current && renders.some((r) => r.componentName === child) && !visited.has(child)) {
721
+ queue.push(child);
722
+ }
723
+ }
724
+ }
725
+ return chain;
726
+ }
727
+ /**
728
+ * Find the root cause component in a chain
729
+ * @param chain - Component chain
730
+ * @param renders - All renders
731
+ * @returns Root cause component name
732
+ */
733
+ findRootCause(chain, renders) {
734
+ const chainRenders = renders.filter((r) => chain.includes(r.componentName)).sort((a, b) => a.timestamp - b.timestamp);
735
+ for (const render of chainRenders) {
736
+ if (render.changedState?.length ?? render.changedProps?.length) {
737
+ return render.componentName;
738
+ }
739
+ }
740
+ return chain[0] ?? "Unknown";
741
+ }
742
+ /**
743
+ * Determine what triggered a chain
744
+ * @param rootCause - Root cause component
745
+ * @param renders - All renders
746
+ * @returns Trigger description
747
+ */
748
+ determineTrigger(rootCause, renders) {
749
+ const render = renders.find((r) => r.componentName === rootCause);
750
+ if (!render) {
751
+ return `Unknown trigger in ${rootCause}`;
752
+ }
753
+ if (render.changedState?.length) {
754
+ return `setState in ${rootCause}`;
755
+ }
756
+ if (render.changedProps?.length) {
757
+ const props = render.changedProps.slice(0, 3).join(", ");
758
+ const more = render.changedProps.length > 3 ? "..." : "";
759
+ return `Props changed (${props}${more}) in ${rootCause}`;
760
+ }
761
+ if (render.contextTriggered) {
762
+ return `Context update affecting ${rootCause}`;
763
+ }
764
+ if (render.phase === "mount") {
765
+ return `Initial mount of ${rootCause}`;
766
+ }
767
+ return `Re-render of ${rootCause}`;
768
+ }
769
+ /**
770
+ * Generate a unique key for a chain to detect duplicates
771
+ * @param chain - Chain info
772
+ * @returns Unique key
773
+ */
774
+ getChainKey(chain) {
775
+ return `${chain.rootCause}:${chain.chain.join("->")}`;
776
+ }
777
+ /**
778
+ * Clean up old render windows
779
+ * @param currentTime - Current timestamp
780
+ */
781
+ cleanupWindows(currentTime) {
782
+ const cutoff = currentTime - this.windowSize * 10;
783
+ for (const [key, window] of this.windows) {
784
+ if (window.startTime < cutoff) {
785
+ this.windows.delete(key);
786
+ }
787
+ }
788
+ }
789
+ /**
790
+ * Get the parent of a component
791
+ * @param componentName - Component name
792
+ * @returns Parent name or undefined
793
+ */
794
+ getParent(componentName) {
795
+ return this.parentMap.get(componentName);
796
+ }
797
+ /**
798
+ * Get all known parent relationships
799
+ * @returns Map of child to parent
800
+ */
801
+ getParentMap() {
802
+ return new Map(this.parentMap);
803
+ }
804
+ /**
805
+ * Build a full chain for a component (tracing up to root)
806
+ * @param componentName - Starting component
807
+ * @returns Chain from root to component
808
+ */
809
+ getComponentChain(componentName) {
810
+ const chain = [];
811
+ let current = componentName;
812
+ while (current) {
813
+ chain.unshift(current);
814
+ current = this.parentMap.get(current);
815
+ if (chain.length > 100) {
816
+ break;
817
+ }
818
+ }
819
+ return chain;
820
+ }
821
+ /**
822
+ * Clear all tracked data
823
+ */
824
+ reset() {
825
+ this.windows.clear();
826
+ this.parentMap.clear();
827
+ this.recentChains.clear();
828
+ }
829
+ /**
830
+ * Get statistics about current tracking
831
+ * @returns Tracking statistics
832
+ */
833
+ getStats() {
834
+ return {
835
+ windowCount: this.windows.size,
836
+ parentRelationships: this.parentMap.size,
837
+ recentChains: this.recentChains.size
838
+ };
839
+ }
840
+ };
841
+
842
+ // src/core/fix.ts
843
+ var BUILTIN_RULES = [
844
+ // React.memo rule
845
+ {
846
+ id: "unnecessary-rerenders-memo",
847
+ name: "Unnecessary Re-renders (memo)",
848
+ description: "Component re-renders frequently without prop changes",
849
+ fixType: "React.memo",
850
+ priority: 1,
851
+ detect: (stats) => {
852
+ const unnecessaryRatio = stats.renders > 0 ? stats.unnecessary / stats.renders : 0;
853
+ return stats.renders >= 10 && unnecessaryRatio >= 0.5 && !stats.propsChanged;
854
+ },
855
+ suggest: (stats) => ({
856
+ severity: stats.severity === "healthy" ? "info" : stats.severity,
857
+ issue: `Component "${stats.name}" re-renders ${stats.unnecessary} times unnecessarily out of ${stats.renders} total renders`,
858
+ cause: stats.parent ? `Parent component "${stats.parent}" re-renders and causes cascading updates` : "Parent component re-renders propagate to this component",
859
+ codeBefore: generateComponentCode(stats.name),
860
+ codeAfter: generateMemoCode(stats.name),
861
+ explanation: "React.memo is a higher-order component that prevents re-renders when props are unchanged. It performs a shallow comparison of props and skips rendering if they match.",
862
+ impact: `Could prevent ~${stats.unnecessary} unnecessary renders (${Math.round(stats.unnecessary / stats.renders * 100)}% reduction)`
863
+ })
864
+ },
865
+ // useMemo rule for expensive computations
866
+ {
867
+ id: "expensive-computation-memo",
868
+ name: "Expensive Computation",
869
+ description: "Component has high render times suggesting expensive calculations",
870
+ fixType: "useMemo",
871
+ priority: 2,
872
+ detect: (stats) => {
873
+ return stats.avgRenderTime > 16 && stats.renders >= 5;
874
+ },
875
+ suggest: (stats) => ({
876
+ severity: stats.avgRenderTime > 50 ? "critical" : "warning",
877
+ issue: `Component "${stats.name}" has slow renders averaging ${stats.avgRenderTime.toFixed(1)}ms`,
878
+ cause: "Expensive calculations or data transformations are being performed on every render",
879
+ codeBefore: generateExpensiveCode(stats.name),
880
+ codeAfter: generateUseMemoCode(stats.name),
881
+ explanation: "useMemo caches the result of expensive computations between renders. It only recalculates when dependencies change, improving performance.",
882
+ impact: `Could reduce render time from ${stats.avgRenderTime.toFixed(1)}ms to <1ms for cached renders`
883
+ })
884
+ },
885
+ // useCallback rule for function props
886
+ {
887
+ id: "function-prop-stability",
888
+ name: "Unstable Function Props",
889
+ description: "Component passes inline functions as props causing child re-renders",
890
+ fixType: "useCallback",
891
+ priority: 3,
892
+ detect: (stats) => {
893
+ return stats.renders >= 15 && stats.propsChanged;
894
+ },
895
+ suggest: (stats) => ({
896
+ severity: stats.severity === "healthy" ? "info" : stats.severity,
897
+ issue: `Component "${stats.name}" may be passing unstable function references as props`,
898
+ cause: "Inline arrow functions are recreated on every render, causing children with React.memo to re-render",
899
+ codeBefore: generateInlineFunctionCode(stats.name),
900
+ codeAfter: generateUseCallbackCode(stats.name),
901
+ explanation: "useCallback returns a memoized callback that only changes when dependencies change. This stabilizes function references passed to child components.",
902
+ impact: "Stabilized function props allow memoized children to skip re-renders"
903
+ })
904
+ },
905
+ // Context split rule
906
+ {
907
+ id: "context-over-subscription",
908
+ name: "Context Over-subscription",
909
+ description: "Context updates trigger unnecessary re-renders in unrelated components",
910
+ fixType: "context-split",
911
+ priority: 4,
912
+ detect: (stats) => {
913
+ return stats.renders >= 20 && stats.unnecessary > stats.renders * 0.7 && !stats.propsChanged && !stats.stateChanged;
914
+ },
915
+ suggest: (stats) => ({
916
+ severity: stats.severity === "healthy" ? "warning" : stats.severity,
917
+ issue: `Component "${stats.name}" re-renders due to context updates it doesn't use`,
918
+ cause: "A context this component subscribes to contains unrelated state that changes frequently",
919
+ codeBefore: generateContextCode("AppContext"),
920
+ codeAfter: generateSplitContextCode(),
921
+ explanation: "Splitting large contexts into smaller, focused contexts prevents unrelated updates from triggering re-renders in components that only need part of the context.",
922
+ impact: `Could eliminate ${stats.unnecessary} unnecessary renders caused by unrelated context updates`
923
+ })
924
+ },
925
+ // State colocation rule
926
+ {
927
+ id: "state-too-high",
928
+ name: "State Location",
929
+ description: "State is managed too high in the component tree",
930
+ fixType: "state-colocation",
931
+ priority: 5,
932
+ detect: (stats) => {
933
+ const chainDepth = stats.chain.length;
934
+ return stats.renders >= 30 && chainDepth >= 3 && stats.stateChanged;
935
+ },
936
+ suggest: (stats) => ({
937
+ severity: stats.severity === "healthy" ? "warning" : stats.severity,
938
+ issue: `State changes in "${stats.name}" trigger a cascade of ${stats.chain.length} component re-renders`,
939
+ cause: `State that only affects a subtree is managed at the "${stats.name}" level, causing unnecessary updates`,
940
+ codeBefore: generateStateHighCode(stats.name),
941
+ codeAfter: generateStateColocationCode(stats.name),
942
+ explanation: "Moving state closer to where it's used (colocation) reduces the re-render scope. Only components that actually need the state will update.",
943
+ impact: `Could reduce cascade depth from ${stats.chain.length} to 1-2 components`
944
+ })
945
+ },
946
+ // Component extraction rule
947
+ {
948
+ id: "extract-heavy-child",
949
+ name: "Component Extraction",
950
+ description: "Part of the component updates independently and should be extracted",
951
+ fixType: "component-extraction",
952
+ priority: 6,
953
+ detect: (stats) => {
954
+ return stats.renders >= 50 && stats.avgRenderTime > 5;
955
+ },
956
+ suggest: (stats) => ({
957
+ severity: stats.severity === "healthy" ? "info" : stats.severity,
958
+ issue: `Component "${stats.name}" renders frequently (${stats.renders} times) with mixed concerns`,
959
+ cause: "The component contains parts that update at different rates, causing full re-renders",
960
+ codeBefore: generateMonolithCode(stats.name),
961
+ codeAfter: generateExtractedCode(stats.name),
962
+ explanation: "Extracting frequently-updating parts into separate components allows React to optimize renders for each part independently.",
963
+ impact: "Isolates render cycles so fast-updating parts don't affect slow-updating parts"
964
+ })
965
+ }
966
+ ];
967
+ function generateComponentCode(name, type) {
968
+ return `function ${name}({ prop1, prop2 }) {
969
+ return (
970
+ <div>
971
+ {/* component content */}
972
+ </div>
973
+ );
974
+ }
975
+
976
+ export default ${name};`;
977
+ }
978
+ function generateMemoCode(name) {
979
+ return `import { memo } from 'react';
980
+
981
+ const ${name} = memo(function ${name}({ prop1, prop2 }) {
982
+ return (
983
+ <div>
984
+ {/* component content */}
985
+ </div>
986
+ );
987
+ });
988
+
989
+ export default ${name};`;
990
+ }
991
+ function generateExpensiveCode(name) {
992
+ return `function ${name}({ items }) {
993
+ // Expensive computation on every render
994
+ const processed = items
995
+ .filter(item => item.active)
996
+ .map(item => transform(item))
997
+ .sort((a, b) => a.value - b.value);
998
+
999
+ return <List items={processed} />;
1000
+ }`;
1001
+ }
1002
+ function generateUseMemoCode(name) {
1003
+ return `import { useMemo } from 'react';
1004
+
1005
+ function ${name}({ items }) {
1006
+ // Computation cached until items change
1007
+ const processed = useMemo(() => {
1008
+ return items
1009
+ .filter(item => item.active)
1010
+ .map(item => transform(item))
1011
+ .sort((a, b) => a.value - b.value);
1012
+ }, [items]);
1013
+
1014
+ return <List items={processed} />;
1015
+ }`;
1016
+ }
1017
+ function generateInlineFunctionCode(name) {
1018
+ return `function ${name}({ data }) {
1019
+ return (
1020
+ <ChildComponent
1021
+ onAction={(id) => handleAction(id)} // New function every render!
1022
+ onClick={() => setOpen(true)} // New function every render!
1023
+ />
1024
+ );
1025
+ }`;
1026
+ }
1027
+ function generateUseCallbackCode(name) {
1028
+ return `import { useCallback } from 'react';
1029
+
1030
+ function ${name}({ data }) {
1031
+ const handleAction = useCallback((id) => {
1032
+ // Handle action
1033
+ }, []); // Empty deps if no external dependencies
1034
+
1035
+ const handleClick = useCallback(() => {
1036
+ setOpen(true);
1037
+ }, []);
1038
+
1039
+ return (
1040
+ <ChildComponent
1041
+ onAction={handleAction} // Stable reference
1042
+ onClick={handleClick} // Stable reference
1043
+ />
1044
+ );
1045
+ }`;
1046
+ }
1047
+ function generateContextCode(contextName) {
1048
+ return `// Single large context with mixed concerns
1049
+ const ${contextName} = createContext({
1050
+ user: null,
1051
+ theme: 'light',
1052
+ notifications: [],
1053
+ settings: {},
1054
+ cart: [],
1055
+ // ... many more values
1056
+ });
1057
+
1058
+ // Every consumer re-renders when ANY value changes
1059
+ function Component() {
1060
+ const { theme } = useContext(${contextName});
1061
+ // Re-renders when user, notifications, cart change too!
1062
+ return <div className={theme}>...</div>;
1063
+ }`;
1064
+ }
1065
+ function generateSplitContextCode() {
1066
+ return `// Split into focused contexts
1067
+ const UserContext = createContext(null);
1068
+ const ThemeContext = createContext('light');
1069
+ const NotificationContext = createContext([]);
1070
+
1071
+ // Only re-renders when theme changes
1072
+ function Component() {
1073
+ const theme = useContext(ThemeContext);
1074
+ return <div className={theme}>...</div>;
1075
+ }
1076
+
1077
+ // Provider composition
1078
+ function App() {
1079
+ return (
1080
+ <UserContext.Provider value={user}>
1081
+ <ThemeContext.Provider value={theme}>
1082
+ <NotificationContext.Provider value={notifications}>
1083
+ <MainContent />
1084
+ </NotificationContext.Provider>
1085
+ </ThemeContext.Provider>
1086
+ </UserContext.Provider>
1087
+ );
1088
+ }`;
1089
+ }
1090
+ function generateStateHighCode(name) {
1091
+ return `function ${name}() {
1092
+ // State managed at top level
1093
+ const [search, setSearch] = useState('');
1094
+ const [filter, setFilter] = useState('all');
1095
+
1096
+ return (
1097
+ <div>
1098
+ <Header />
1099
+ <Sidebar />
1100
+ {/* Only SearchBox needs search state */}
1101
+ <SearchBox value={search} onChange={setSearch} />
1102
+ <MainContent filter={filter} />
1103
+ <Footer />
1104
+ </div>
1105
+ );
1106
+ }`;
1107
+ }
1108
+ function generateStateColocationCode(name) {
1109
+ return `function ${name}() {
1110
+ // Only filter needed at this level
1111
+ const [filter, setFilter] = useState('all');
1112
+
1113
+ return (
1114
+ <div>
1115
+ <Header />
1116
+ <Sidebar />
1117
+ {/* SearchBox manages its own state */}
1118
+ <SearchBox />
1119
+ <MainContent filter={filter} />
1120
+ <Footer />
1121
+ </div>
1122
+ );
1123
+ }
1124
+
1125
+ // State colocated with component that uses it
1126
+ function SearchBox() {
1127
+ const [search, setSearch] = useState('');
1128
+ return <input value={search} onChange={e => setSearch(e.target.value)} />;
1129
+ }`;
1130
+ }
1131
+ function generateMonolithCode(name) {
1132
+ return `function ${name}() {
1133
+ const [counter, setCounter] = useState(0);
1134
+ const [data, setData] = useState(null);
1135
+
1136
+ // Counter updates 10x/second
1137
+ useEffect(() => {
1138
+ const id = setInterval(() => setCounter(c => c + 1), 100);
1139
+ return () => clearInterval(id);
1140
+ }, []);
1141
+
1142
+ return (
1143
+ <div>
1144
+ <span>Count: {counter}</span> {/* Updates frequently */}
1145
+ <ExpensiveChart data={data} /> {/* Re-renders unnecessarily! */}
1146
+ <DataTable data={data} /> {/* Re-renders unnecessarily! */}
1147
+ </div>
1148
+ );
1149
+ }`;
1150
+ }
1151
+ function generateExtractedCode(name) {
1152
+ return `function ${name}() {
1153
+ const [data, setData] = useState(null);
1154
+
1155
+ return (
1156
+ <div>
1157
+ <LiveCounter /> {/* Isolated updates */}
1158
+ <ExpensiveChart data={data} /> {/* Only updates when data changes */}
1159
+ <DataTable data={data} /> {/* Only updates when data changes */}
1160
+ </div>
1161
+ );
1162
+ }
1163
+
1164
+ // Extracted component with isolated state
1165
+ function LiveCounter() {
1166
+ const [counter, setCounter] = useState(0);
1167
+
1168
+ useEffect(() => {
1169
+ const id = setInterval(() => setCounter(c => c + 1), 100);
1170
+ return () => clearInterval(id);
1171
+ }, []);
1172
+
1173
+ return <span>Count: {counter}</span>;
1174
+ }`;
1175
+ }
1176
+ var FixSuggester = class extends EventEmitter {
1177
+ /** Active rules */
1178
+ rules;
1179
+ /** Generated suggestions cache */
1180
+ suggestions = /* @__PURE__ */ new Map();
1181
+ /** Rule configuration */
1182
+ ruleConfig = /* @__PURE__ */ new Map();
1183
+ /**
1184
+ * Create a new FixSuggester
1185
+ * @param options - Configuration options
1186
+ */
1187
+ constructor(options = {}) {
1188
+ super();
1189
+ this.rules = [...BUILTIN_RULES];
1190
+ if (options.rules) {
1191
+ for (const [ruleId, setting] of Object.entries(options.rules)) {
1192
+ this.ruleConfig.set(ruleId, setting);
1193
+ }
1194
+ }
1195
+ }
1196
+ /**
1197
+ * Analyze a component and generate fix suggestions
1198
+ * @param stats - Component statistics
1199
+ * @returns Array of fix suggestions
1200
+ */
1201
+ analyze(stats) {
1202
+ const suggestions = [];
1203
+ for (const rule of this.rules) {
1204
+ const config = this.ruleConfig.get(rule.id);
1205
+ if (config === "off") {
1206
+ continue;
1207
+ }
1208
+ if (!rule.detect(stats)) {
1209
+ continue;
1210
+ }
1211
+ const partialSuggestion = rule.suggest(stats);
1212
+ const suggestion = {
1213
+ componentName: stats.name,
1214
+ fix: rule.fixType,
1215
+ ...partialSuggestion
1216
+ };
1217
+ if (config === "warn") {
1218
+ suggestion.severity = "warning";
1219
+ } else if (config === "error") {
1220
+ suggestion.severity = "critical";
1221
+ }
1222
+ suggestions.push(suggestion);
1223
+ this.emit("suggestion", suggestion);
1224
+ }
1225
+ suggestions.sort((a, b) => {
1226
+ const severityOrder = { critical: 0, warning: 1, info: 2 };
1227
+ const severityDiff = severityOrder[a.severity] - severityOrder[b.severity];
1228
+ if (severityDiff !== 0) return severityDiff;
1229
+ const ruleA = this.rules.find((r) => r.fixType === a.fix);
1230
+ const ruleB = this.rules.find((r) => r.fixType === b.fix);
1231
+ return (ruleA?.priority ?? 99) - (ruleB?.priority ?? 99);
1232
+ });
1233
+ this.suggestions.set(stats.name, suggestions);
1234
+ return suggestions;
1235
+ }
1236
+ /**
1237
+ * Get cached suggestions for a component
1238
+ * @param componentName - Component name
1239
+ * @returns Cached suggestions or empty array
1240
+ */
1241
+ getSuggestions(componentName) {
1242
+ return this.suggestions.get(componentName) ?? [];
1243
+ }
1244
+ /**
1245
+ * Get all cached suggestions
1246
+ * @returns All suggestions
1247
+ */
1248
+ getAllSuggestions() {
1249
+ return Array.from(this.suggestions.values()).flat();
1250
+ }
1251
+ /**
1252
+ * Get suggestions by severity
1253
+ * @param severity - Severity level
1254
+ * @returns Matching suggestions
1255
+ */
1256
+ getSuggestionsBySeverity(severity) {
1257
+ return this.getAllSuggestions().filter((s) => s.severity === severity);
1258
+ }
1259
+ /**
1260
+ * Get suggestions by fix type
1261
+ * @param fixType - Fix type
1262
+ * @returns Matching suggestions
1263
+ */
1264
+ getSuggestionsByType(fixType) {
1265
+ return this.getAllSuggestions().filter((s) => s.fix === fixType);
1266
+ }
1267
+ /**
1268
+ * Clear cached suggestions
1269
+ * @param componentName - Optional component to clear (clears all if not specified)
1270
+ */
1271
+ clearSuggestions(componentName) {
1272
+ if (componentName) {
1273
+ this.suggestions.delete(componentName);
1274
+ } else {
1275
+ this.suggestions.clear();
1276
+ }
1277
+ }
1278
+ /**
1279
+ * Configure a rule
1280
+ * @param ruleId - Rule identifier
1281
+ * @param setting - Rule setting
1282
+ */
1283
+ configureRule(ruleId, setting) {
1284
+ this.ruleConfig.set(ruleId, setting);
1285
+ }
1286
+ /**
1287
+ * Get available rule IDs
1288
+ * @returns Array of rule IDs
1289
+ */
1290
+ getRuleIds() {
1291
+ return this.rules.map((r) => r.id);
1292
+ }
1293
+ /**
1294
+ * Get rule information
1295
+ * @param ruleId - Rule identifier
1296
+ * @returns Rule info or undefined
1297
+ */
1298
+ getRule(ruleId) {
1299
+ const rule = this.rules.find((r) => r.id === ruleId);
1300
+ if (!rule) return void 0;
1301
+ return {
1302
+ id: rule.id,
1303
+ name: rule.name,
1304
+ description: rule.description,
1305
+ fixType: rule.fixType
1306
+ };
1307
+ }
1308
+ };
1309
+
1310
+ // src/core/scanner.ts
1311
+ var DEFAULT_CONFIG = {
1312
+ trackUnnecessary: true,
1313
+ fpsThreshold: 30,
1314
+ highlightRenders: true,
1315
+ animationSpeed: "fast"
1316
+ };
1317
+ var DEFAULT_THRESHOLDS2 = {
1318
+ critical: 50,
1319
+ warning: 20,
1320
+ fps: 30
1321
+ };
1322
+ var Scanner = class extends EventEmitter {
1323
+ /** Statistics collector */
1324
+ stats;
1325
+ /** Chain analyzer */
1326
+ chainAnalyzer;
1327
+ /** Fix suggester */
1328
+ fixSuggester;
1329
+ /** Scanner configuration */
1330
+ config;
1331
+ /** Whether scanner is currently running */
1332
+ running = false;
1333
+ /** Last recorded FPS */
1334
+ lastFps = 60;
1335
+ /** FPS tracking */
1336
+ frameCount = 0;
1337
+ lastFpsUpdate = 0;
1338
+ fpsInterval = null;
1339
+ /** Batch processing */
1340
+ renderBatch = [];
1341
+ batchTimeout = null;
1342
+ batchSize = 10;
1343
+ batchDelay = 100;
1344
+ /**
1345
+ * Create a new Scanner instance
1346
+ * @param options - Configuration options
1347
+ */
1348
+ constructor(options = {}) {
1349
+ super();
1350
+ this.config = { ...DEFAULT_CONFIG, ...options.config };
1351
+ const thresholds = { ...DEFAULT_THRESHOLDS2, ...options.thresholds };
1352
+ this.stats = new StatsCollector(thresholds);
1353
+ this.chainAnalyzer = new ChainAnalyzer();
1354
+ this.fixSuggester = new FixSuggester();
1355
+ this.setupEventForwarding();
1356
+ }
1357
+ /**
1358
+ * Set up event forwarding from sub-modules
1359
+ */
1360
+ setupEventForwarding() {
1361
+ this.stats.on("update", (stats) => {
1362
+ this.emit("stats", stats);
1363
+ });
1364
+ this.stats.on("severityChange", (change) => {
1365
+ this.emit("severityChange", change);
1366
+ const stats = this.stats.getComponentStats(change.component);
1367
+ if (stats && (change.to === "critical" || change.to === "warning")) {
1368
+ const suggestions = this.fixSuggester.analyze(stats);
1369
+ for (const suggestion of suggestions) {
1370
+ this.emit("fix", suggestion);
1371
+ }
1372
+ }
1373
+ });
1374
+ this.chainAnalyzer.on("chain", (chain) => {
1375
+ this.emit("chain", chain);
1376
+ for (const componentName of chain.chain) {
1377
+ this.stats.setComponentChain(componentName, chain.chain);
1378
+ }
1379
+ });
1380
+ }
1381
+ /**
1382
+ * Start the scanner
1383
+ */
1384
+ start() {
1385
+ if (this.running) return;
1386
+ this.running = true;
1387
+ this.lastFpsUpdate = Date.now();
1388
+ this.frameCount = 0;
1389
+ this.startFpsMonitoring();
1390
+ this.emit("start", void 0);
1391
+ }
1392
+ /**
1393
+ * Stop the scanner
1394
+ */
1395
+ stop() {
1396
+ if (!this.running) return;
1397
+ this.running = false;
1398
+ this.stopFpsMonitoring();
1399
+ this.flushBatch();
1400
+ this.emit("stop", void 0);
1401
+ }
1402
+ /**
1403
+ * Reset the scanner, clearing all data
1404
+ */
1405
+ reset() {
1406
+ this.stop();
1407
+ this.stats.reset();
1408
+ this.chainAnalyzer.reset();
1409
+ this.fixSuggester.clearSuggestions();
1410
+ this.renderBatch = [];
1411
+ this.emit("reset", void 0);
1412
+ }
1413
+ /**
1414
+ * Process a render event
1415
+ * @param render - Render information
1416
+ * @param parent - Optional parent component name
1417
+ */
1418
+ addRender(render, parent) {
1419
+ if (!this.running) return;
1420
+ this.renderBatch.push(render);
1421
+ this.stats.addRender(render);
1422
+ this.chainAnalyzer.addRender(render, parent);
1423
+ this.emit("render", render);
1424
+ this.frameCount++;
1425
+ this.scheduleBatchProcessing();
1426
+ }
1427
+ /**
1428
+ * Record a frame for FPS calculation
1429
+ */
1430
+ recordFrame() {
1431
+ this.frameCount++;
1432
+ }
1433
+ /**
1434
+ * Schedule batch processing
1435
+ */
1436
+ scheduleBatchProcessing() {
1437
+ if (this.batchTimeout) return;
1438
+ if (this.renderBatch.length >= this.batchSize) {
1439
+ this.flushBatch();
1440
+ } else {
1441
+ this.batchTimeout = setTimeout(() => {
1442
+ this.flushBatch();
1443
+ }, this.batchDelay);
1444
+ }
1445
+ }
1446
+ /**
1447
+ * Flush the render batch
1448
+ */
1449
+ flushBatch() {
1450
+ if (this.batchTimeout) {
1451
+ clearTimeout(this.batchTimeout);
1452
+ this.batchTimeout = null;
1453
+ }
1454
+ if (this.renderBatch.length === 0) return;
1455
+ this.processBatch(this.renderBatch);
1456
+ this.renderBatch = [];
1457
+ }
1458
+ /**
1459
+ * Process a batch of renders for patterns
1460
+ * @param batch - Render batch
1461
+ */
1462
+ processBatch(batch) {
1463
+ const byComponent = /* @__PURE__ */ new Map();
1464
+ for (const render of batch) {
1465
+ const existing = byComponent.get(render.componentName) ?? [];
1466
+ existing.push(render);
1467
+ byComponent.set(render.componentName, existing);
1468
+ }
1469
+ for (const [componentName, renders] of byComponent) {
1470
+ if (renders.length >= 3) {
1471
+ const stats = this.stats.getComponentStats(componentName);
1472
+ if (stats) {
1473
+ const suggestions = this.fixSuggester.analyze(stats);
1474
+ for (const suggestion of suggestions) {
1475
+ this.emit("fix", suggestion);
1476
+ }
1477
+ }
1478
+ }
1479
+ }
1480
+ }
1481
+ /**
1482
+ * Start FPS monitoring
1483
+ */
1484
+ startFpsMonitoring() {
1485
+ this.fpsInterval = setInterval(() => {
1486
+ const now = Date.now();
1487
+ const elapsed = now - this.lastFpsUpdate;
1488
+ if (elapsed > 0) {
1489
+ this.lastFps = Math.round(this.frameCount * 1e3 / elapsed);
1490
+ this.stats.addFpsSample(this.lastFps);
1491
+ if (this.lastFps < this.config.fpsThreshold) {
1492
+ this.emit("fps-drop", this.lastFps);
1493
+ }
1494
+ }
1495
+ this.frameCount = 0;
1496
+ this.lastFpsUpdate = now;
1497
+ }, 1e3);
1498
+ }
1499
+ /**
1500
+ * Stop FPS monitoring
1501
+ */
1502
+ stopFpsMonitoring() {
1503
+ if (this.fpsInterval) {
1504
+ clearInterval(this.fpsInterval);
1505
+ this.fpsInterval = null;
1506
+ }
1507
+ }
1508
+ /**
1509
+ * Get current FPS
1510
+ * @returns Current FPS value
1511
+ */
1512
+ getFps() {
1513
+ return this.lastFps;
1514
+ }
1515
+ /**
1516
+ * Check if scanner is running
1517
+ * @returns true if running
1518
+ */
1519
+ isRunning() {
1520
+ return this.running;
1521
+ }
1522
+ /**
1523
+ * Get scanner configuration
1524
+ * @returns Current configuration
1525
+ */
1526
+ getConfig() {
1527
+ return { ...this.config };
1528
+ }
1529
+ /**
1530
+ * Update scanner configuration
1531
+ * @param config - Partial configuration to update
1532
+ */
1533
+ configure(config) {
1534
+ this.config = { ...this.config, ...config };
1535
+ }
1536
+ /**
1537
+ * Update threshold configuration
1538
+ * @param thresholds - New thresholds
1539
+ */
1540
+ setThresholds(thresholds) {
1541
+ this.stats.setThresholds(thresholds);
1542
+ }
1543
+ /**
1544
+ * Get current thresholds
1545
+ * @returns Current threshold configuration
1546
+ */
1547
+ getThresholds() {
1548
+ return this.stats.getThresholds();
1549
+ }
1550
+ /**
1551
+ * Get component statistics
1552
+ * @param name - Component name (optional, returns all if not specified)
1553
+ * @returns Component stats
1554
+ */
1555
+ getStats(name) {
1556
+ if (name) {
1557
+ return this.stats.getComponentStats(name);
1558
+ }
1559
+ return this.stats.getAllStats();
1560
+ }
1561
+ /**
1562
+ * Get a snapshot of all stats sorted by severity
1563
+ * @returns Sorted stats array
1564
+ */
1565
+ getSnapshot() {
1566
+ return this.stats.getSnapshot();
1567
+ }
1568
+ /**
1569
+ * Get session summary
1570
+ * @returns Session summary statistics
1571
+ */
1572
+ getSummary() {
1573
+ return this.stats.getSummary();
1574
+ }
1575
+ /**
1576
+ * Get top problematic components
1577
+ * @param limit - Maximum number to return
1578
+ * @returns Top problems
1579
+ */
1580
+ getTopProblems(limit = 10) {
1581
+ return this.stats.getTopProblems(limit);
1582
+ }
1583
+ /**
1584
+ * Get all fix suggestions
1585
+ * @returns All suggestions
1586
+ */
1587
+ getSuggestions() {
1588
+ return this.fixSuggester.getAllSuggestions();
1589
+ }
1590
+ /**
1591
+ * Get suggestions for a specific component
1592
+ * @param componentName - Component name
1593
+ * @returns Component suggestions
1594
+ */
1595
+ getComponentSuggestions(componentName) {
1596
+ return this.fixSuggester.getSuggestions(componentName);
1597
+ }
1598
+ /**
1599
+ * Set parent relationship for a component
1600
+ * @param child - Child component name
1601
+ * @param parent - Parent component name
1602
+ */
1603
+ setParent(child, parent) {
1604
+ this.chainAnalyzer.setParent(child, parent);
1605
+ this.stats.setComponentParent(child, parent);
1606
+ }
1607
+ /**
1608
+ * Get the render chain for a component
1609
+ * @param componentName - Component name
1610
+ * @returns Render chain
1611
+ */
1612
+ getComponentChain(componentName) {
1613
+ return this.chainAnalyzer.getComponentChain(componentName);
1614
+ }
1615
+ /**
1616
+ * Get session duration
1617
+ * @returns Duration in milliseconds
1618
+ */
1619
+ getSessionDuration() {
1620
+ return this.stats.getSessionDuration();
1621
+ }
1622
+ /**
1623
+ * Export scanner data for reporting
1624
+ * @returns Exportable data object
1625
+ */
1626
+ export() {
1627
+ return {
1628
+ stats: this.stats.export(),
1629
+ suggestions: this.getSuggestions(),
1630
+ config: this.getConfig()
1631
+ };
1632
+ }
1633
+ /**
1634
+ * Analyze a specific component and generate suggestions
1635
+ * @param componentName - Component name
1636
+ * @returns Fix suggestions for the component
1637
+ */
1638
+ analyzeComponent(componentName) {
1639
+ const stats = this.stats.getComponentStats(componentName);
1640
+ if (!stats) return [];
1641
+ return this.fixSuggester.analyze(stats);
1642
+ }
1643
+ /**
1644
+ * Analyze all components and generate suggestions
1645
+ * @returns All fix suggestions
1646
+ */
1647
+ analyzeAll() {
1648
+ const allStats = this.stats.getAllStats();
1649
+ const allSuggestions = [];
1650
+ for (const stats of allStats) {
1651
+ const suggestions = this.fixSuggester.analyze(stats);
1652
+ allSuggestions.push(...suggestions);
1653
+ }
1654
+ return allSuggestions;
1655
+ }
1656
+ };
1657
+
1658
+ exports.Scanner = Scanner;
1659
+ //# sourceMappingURL=scanner.cjs.map
1660
+ //# sourceMappingURL=scanner.cjs.map