@oxog/react-check 1.2.0 → 1.3.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.
- package/CHANGELOG.md +86 -0
- package/README.md +142 -50
- package/dist/browser-inject.global.js +13 -13
- package/dist/chain.cjs +8 -531
- package/dist/chain.cjs.map +1 -1
- package/dist/chain.d.cts +2 -2
- package/dist/chain.d.ts +2 -2
- package/dist/chain.js +2 -533
- package/dist/chain.js.map +1 -1
- package/dist/chunk-27R56V2S.js +473 -0
- package/dist/chunk-27R56V2S.js.map +1 -0
- package/dist/chunk-3K2AER5M.cjs +356 -0
- package/dist/chunk-3K2AER5M.cjs.map +1 -0
- package/dist/chunk-7R4KKJTW.cjs +255 -0
- package/dist/chunk-7R4KKJTW.cjs.map +1 -0
- package/dist/chunk-7YYMP3PP.js +723 -0
- package/dist/chunk-7YYMP3PP.js.map +1 -0
- package/dist/chunk-DWM55ACO.cjs +294 -0
- package/dist/chunk-DWM55ACO.cjs.map +1 -0
- package/dist/chunk-G7YVIPS7.cjs +475 -0
- package/dist/chunk-G7YVIPS7.cjs.map +1 -0
- package/dist/chunk-GE2ZX7I7.cjs +727 -0
- package/dist/chunk-GE2ZX7I7.cjs.map +1 -0
- package/dist/chunk-GS7T56RP.cjs +9 -0
- package/dist/chunk-GS7T56RP.cjs.map +1 -0
- package/dist/chunk-IM6OG2IC.js +338 -0
- package/dist/chunk-IM6OG2IC.js.map +1 -0
- package/dist/chunk-RQYHXWUC.js +292 -0
- package/dist/chunk-RQYHXWUC.js.map +1 -0
- package/dist/chunk-WLN7ZVO4.js +253 -0
- package/dist/chunk-WLN7ZVO4.js.map +1 -0
- package/dist/cli.js +975 -204
- package/dist/cli.js.map +1 -1
- package/dist/detect.cjs +22 -324
- package/dist/detect.cjs.map +1 -1
- package/dist/detect.d.cts +8 -2
- package/dist/detect.d.ts +8 -2
- package/dist/detect.js +1 -324
- package/dist/detect.js.map +1 -1
- package/dist/{event-emitter-CxKUDo9q.d.cts → event-emitter-BVYUPYLd.d.cts} +3 -2
- package/dist/{event-emitter-CxKUDo9q.d.ts → event-emitter-BVYUPYLd.d.ts} +3 -2
- package/dist/fix.cjs +6 -715
- package/dist/fix.cjs.map +1 -1
- package/dist/fix.d.cts +2 -2
- package/dist/fix.d.ts +2 -2
- package/dist/fix.js +2 -719
- package/dist/fix.js.map +1 -1
- package/dist/index.cjs +1238 -2987
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +166 -50
- package/dist/index.d.ts +166 -50
- package/dist/index.js +1137 -2959
- package/dist/index.js.map +1 -1
- package/dist/{scanner-Cc2187fH.d.ts → scanner-D0mBQGTx.d.ts} +23 -3
- package/dist/{scanner-S7BtVIpW.d.cts → scanner-DUBgwztZ.d.cts} +23 -3
- package/dist/scanner.cjs +8 -1652
- package/dist/scanner.cjs.map +1 -1
- package/dist/scanner.d.cts +3 -3
- package/dist/scanner.d.ts +3 -3
- package/dist/scanner.js +4 -1656
- package/dist/scanner.js.map +1 -1
- package/dist/{types-DuZyBVVV.d.cts → types-BZ3OeZ-5.d.cts} +28 -10
- package/dist/{types-DuZyBVVV.d.ts → types-BZ3OeZ-5.d.ts} +28 -10
- package/package.json +16 -9
package/dist/index.js
CHANGED
|
@@ -1,916 +1,17 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
import { matchComponentPattern, Scanner } from './chunk-7YYMP3PP.js';
|
|
2
|
+
export { Scanner, StatsCollector, matchComponentPattern } from './chunk-7YYMP3PP.js';
|
|
3
|
+
export { ChainAnalyzer } from './chunk-RQYHXWUC.js';
|
|
4
|
+
export { FixSuggester } from './chunk-27R56V2S.js';
|
|
5
|
+
import { EventEmitter } from './chunk-WLN7ZVO4.js';
|
|
6
|
+
export { EventEmitter } from './chunk-WLN7ZVO4.js';
|
|
7
|
+
import { ensureDir, joinPath, writeTextFile } from './chunk-IM6OG2IC.js';
|
|
8
|
+
export { detectFramework, detectFrameworkFromWindow, ensureDir, exists, findUp, FRAMEWORK_DETECTORS as frameworkDetectors, getBaseName, getDirName, getExtension, getFrameworkTips, joinPath, readJsonFile, readTextFile, resolvePath, writeJsonFile, writeTextFile } from './chunk-IM6OG2IC.js';
|
|
4
9
|
import { createServer, request as request$1 } from 'http';
|
|
5
10
|
import { createHash } from 'crypto';
|
|
6
11
|
import { request } from 'https';
|
|
7
|
-
import { URL } from 'url';
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
11
|
-
var __esm = (fn, res) => function __init() {
|
|
12
|
-
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
13
|
-
};
|
|
14
|
-
var __export = (target, all) => {
|
|
15
|
-
for (var name in all)
|
|
16
|
-
__defProp(target, name, { get: all[name], enumerable: true });
|
|
17
|
-
};
|
|
18
|
-
|
|
19
|
-
// src/utils/event-emitter.ts
|
|
20
|
-
var EventEmitter;
|
|
21
|
-
var init_event_emitter = __esm({
|
|
22
|
-
"src/utils/event-emitter.ts"() {
|
|
23
|
-
EventEmitter = class {
|
|
24
|
-
/** Map of event names to their listeners */
|
|
25
|
-
_listeners = /* @__PURE__ */ new Map();
|
|
26
|
-
/** Map of event names to their one-time listeners */
|
|
27
|
-
_onceListeners = /* @__PURE__ */ new Map();
|
|
28
|
-
/** Maximum number of listeners per event (0 = unlimited) */
|
|
29
|
-
maxListeners = 0;
|
|
30
|
-
/**
|
|
31
|
-
* Add an event listener
|
|
32
|
-
* @param event - Event name
|
|
33
|
-
* @param listener - Callback function
|
|
34
|
-
* @returns this for chaining
|
|
35
|
-
*/
|
|
36
|
-
on(event, listener) {
|
|
37
|
-
let eventListeners = this._listeners.get(event);
|
|
38
|
-
if (!eventListeners) {
|
|
39
|
-
eventListeners = /* @__PURE__ */ new Set();
|
|
40
|
-
this._listeners.set(event, eventListeners);
|
|
41
|
-
}
|
|
42
|
-
if (this.maxListeners > 0 && eventListeners.size >= this.maxListeners) {
|
|
43
|
-
console.warn(
|
|
44
|
-
`Warning: Possible EventEmitter memory leak detected. ${eventListeners.size + 1} listeners added for event "${String(event)}". Use setMaxListeners() to increase limit.`
|
|
45
|
-
);
|
|
46
|
-
}
|
|
47
|
-
eventListeners.add(listener);
|
|
48
|
-
return this;
|
|
49
|
-
}
|
|
50
|
-
/**
|
|
51
|
-
* Alias for on()
|
|
52
|
-
*/
|
|
53
|
-
addListener(event, listener) {
|
|
54
|
-
return this.on(event, listener);
|
|
55
|
-
}
|
|
56
|
-
/**
|
|
57
|
-
* Add a one-time event listener
|
|
58
|
-
* @param event - Event name
|
|
59
|
-
* @param listener - Callback function
|
|
60
|
-
* @returns this for chaining
|
|
61
|
-
*/
|
|
62
|
-
once(event, listener) {
|
|
63
|
-
let eventListeners = this._onceListeners.get(event);
|
|
64
|
-
if (!eventListeners) {
|
|
65
|
-
eventListeners = /* @__PURE__ */ new Set();
|
|
66
|
-
this._onceListeners.set(event, eventListeners);
|
|
67
|
-
}
|
|
68
|
-
eventListeners.add(listener);
|
|
69
|
-
return this;
|
|
70
|
-
}
|
|
71
|
-
/**
|
|
72
|
-
* Remove an event listener
|
|
73
|
-
* @param event - Event name
|
|
74
|
-
* @param listener - Callback function to remove
|
|
75
|
-
* @returns this for chaining
|
|
76
|
-
*/
|
|
77
|
-
off(event, listener) {
|
|
78
|
-
const eventListeners = this._listeners.get(event);
|
|
79
|
-
if (eventListeners) {
|
|
80
|
-
eventListeners.delete(listener);
|
|
81
|
-
if (eventListeners.size === 0) {
|
|
82
|
-
this._listeners.delete(event);
|
|
83
|
-
}
|
|
84
|
-
}
|
|
85
|
-
const onceEventListeners = this._onceListeners.get(event);
|
|
86
|
-
if (onceEventListeners) {
|
|
87
|
-
onceEventListeners.delete(listener);
|
|
88
|
-
if (onceEventListeners.size === 0) {
|
|
89
|
-
this._onceListeners.delete(event);
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
return this;
|
|
93
|
-
}
|
|
94
|
-
/**
|
|
95
|
-
* Alias for off()
|
|
96
|
-
*/
|
|
97
|
-
removeListener(event, listener) {
|
|
98
|
-
return this.off(event, listener);
|
|
99
|
-
}
|
|
100
|
-
/**
|
|
101
|
-
* Remove all listeners for an event, or all events if no event specified
|
|
102
|
-
* @param event - Optional event name
|
|
103
|
-
* @returns this for chaining
|
|
104
|
-
*/
|
|
105
|
-
removeAllListeners(event) {
|
|
106
|
-
if (event !== void 0) {
|
|
107
|
-
this._listeners.delete(event);
|
|
108
|
-
this._onceListeners.delete(event);
|
|
109
|
-
} else {
|
|
110
|
-
this._listeners.clear();
|
|
111
|
-
this._onceListeners.clear();
|
|
112
|
-
}
|
|
113
|
-
return this;
|
|
114
|
-
}
|
|
115
|
-
/**
|
|
116
|
-
* Emit an event
|
|
117
|
-
* @param event - Event name
|
|
118
|
-
* @param data - Event data
|
|
119
|
-
* @returns true if any listeners were called
|
|
120
|
-
*/
|
|
121
|
-
emit(event, data) {
|
|
122
|
-
let called = false;
|
|
123
|
-
const eventListeners = this._listeners.get(event);
|
|
124
|
-
if (eventListeners) {
|
|
125
|
-
for (const listener of eventListeners) {
|
|
126
|
-
try {
|
|
127
|
-
listener(data);
|
|
128
|
-
called = true;
|
|
129
|
-
} catch (error) {
|
|
130
|
-
if (event !== "error") {
|
|
131
|
-
this.emit("error", error);
|
|
132
|
-
} else {
|
|
133
|
-
throw error;
|
|
134
|
-
}
|
|
135
|
-
}
|
|
136
|
-
}
|
|
137
|
-
}
|
|
138
|
-
const onceEventListeners = this._onceListeners.get(event);
|
|
139
|
-
if (onceEventListeners) {
|
|
140
|
-
const listenersToCall = Array.from(onceEventListeners);
|
|
141
|
-
this._onceListeners.delete(event);
|
|
142
|
-
for (const listener of listenersToCall) {
|
|
143
|
-
try {
|
|
144
|
-
listener(data);
|
|
145
|
-
called = true;
|
|
146
|
-
} catch (error) {
|
|
147
|
-
if (event !== "error") {
|
|
148
|
-
this.emit("error", error);
|
|
149
|
-
} else {
|
|
150
|
-
throw error;
|
|
151
|
-
}
|
|
152
|
-
}
|
|
153
|
-
}
|
|
154
|
-
}
|
|
155
|
-
return called;
|
|
156
|
-
}
|
|
157
|
-
/**
|
|
158
|
-
* Get all listener functions for an event
|
|
159
|
-
* @param event - Event name
|
|
160
|
-
* @returns Array of listener functions
|
|
161
|
-
*/
|
|
162
|
-
getListeners(event) {
|
|
163
|
-
const regular = this._listeners.get(event);
|
|
164
|
-
const once = this._onceListeners.get(event);
|
|
165
|
-
const result = [];
|
|
166
|
-
if (regular) {
|
|
167
|
-
result.push(...Array.from(regular));
|
|
168
|
-
}
|
|
169
|
-
if (once) {
|
|
170
|
-
result.push(...Array.from(once));
|
|
171
|
-
}
|
|
172
|
-
return result;
|
|
173
|
-
}
|
|
174
|
-
/**
|
|
175
|
-
* Get the number of listeners for an event
|
|
176
|
-
* @param event - Event name
|
|
177
|
-
* @returns Number of listeners
|
|
178
|
-
*/
|
|
179
|
-
listenerCount(event) {
|
|
180
|
-
const regular = this._listeners.get(event)?.size ?? 0;
|
|
181
|
-
const once = this._onceListeners.get(event)?.size ?? 0;
|
|
182
|
-
return regular + once;
|
|
183
|
-
}
|
|
184
|
-
/**
|
|
185
|
-
* Get all event names that have listeners
|
|
186
|
-
* @returns Array of event names
|
|
187
|
-
*/
|
|
188
|
-
eventNames() {
|
|
189
|
-
const names = /* @__PURE__ */ new Set();
|
|
190
|
-
for (const name of this._listeners.keys()) {
|
|
191
|
-
names.add(name);
|
|
192
|
-
}
|
|
193
|
-
for (const name of this._onceListeners.keys()) {
|
|
194
|
-
names.add(name);
|
|
195
|
-
}
|
|
196
|
-
return Array.from(names);
|
|
197
|
-
}
|
|
198
|
-
/**
|
|
199
|
-
* Set the maximum number of listeners per event
|
|
200
|
-
* @param n - Maximum listeners (0 for unlimited)
|
|
201
|
-
* @returns this for chaining
|
|
202
|
-
*/
|
|
203
|
-
setMaxListeners(n) {
|
|
204
|
-
this.maxListeners = n;
|
|
205
|
-
return this;
|
|
206
|
-
}
|
|
207
|
-
/**
|
|
208
|
-
* Get the maximum number of listeners per event
|
|
209
|
-
* @returns Maximum listeners
|
|
210
|
-
*/
|
|
211
|
-
getMaxListeners() {
|
|
212
|
-
return this.maxListeners;
|
|
213
|
-
}
|
|
214
|
-
/**
|
|
215
|
-
* Prepend a listener to the beginning of the listeners array
|
|
216
|
-
* @param event - Event name
|
|
217
|
-
* @param listener - Callback function
|
|
218
|
-
* @returns this for chaining
|
|
219
|
-
*/
|
|
220
|
-
prependListener(event, listener) {
|
|
221
|
-
const eventListeners = this._listeners.get(event);
|
|
222
|
-
if (!eventListeners) {
|
|
223
|
-
return this.on(event, listener);
|
|
224
|
-
}
|
|
225
|
-
const arr = Array.from(eventListeners);
|
|
226
|
-
arr.unshift(listener);
|
|
227
|
-
this._listeners.set(event, new Set(arr));
|
|
228
|
-
return this;
|
|
229
|
-
}
|
|
230
|
-
/**
|
|
231
|
-
* Prepend a one-time listener to the beginning
|
|
232
|
-
* @param event - Event name
|
|
233
|
-
* @param listener - Callback function
|
|
234
|
-
* @returns this for chaining
|
|
235
|
-
*/
|
|
236
|
-
prependOnceListener(event, listener) {
|
|
237
|
-
const eventListeners = this._onceListeners.get(event);
|
|
238
|
-
if (!eventListeners) {
|
|
239
|
-
return this.once(event, listener);
|
|
240
|
-
}
|
|
241
|
-
const arr = Array.from(eventListeners);
|
|
242
|
-
arr.unshift(listener);
|
|
243
|
-
this._onceListeners.set(event, new Set(arr));
|
|
244
|
-
return this;
|
|
245
|
-
}
|
|
246
|
-
/**
|
|
247
|
-
* Wait for an event to be emitted
|
|
248
|
-
* @param event - Event name
|
|
249
|
-
* @param timeout - Optional timeout in milliseconds
|
|
250
|
-
* @returns Promise that resolves with the event data
|
|
251
|
-
*/
|
|
252
|
-
waitFor(event, timeout) {
|
|
253
|
-
return new Promise((resolve2, reject) => {
|
|
254
|
-
let timeoutId;
|
|
255
|
-
const listener = (data) => {
|
|
256
|
-
if (timeoutId) {
|
|
257
|
-
clearTimeout(timeoutId);
|
|
258
|
-
}
|
|
259
|
-
resolve2(data);
|
|
260
|
-
};
|
|
261
|
-
this.once(event, listener);
|
|
262
|
-
if (timeout !== void 0 && timeout > 0) {
|
|
263
|
-
timeoutId = setTimeout(() => {
|
|
264
|
-
this.off(event, listener);
|
|
265
|
-
reject(new Error(`Timeout waiting for event "${String(event)}"`));
|
|
266
|
-
}, timeout);
|
|
267
|
-
}
|
|
268
|
-
});
|
|
269
|
-
}
|
|
270
|
-
};
|
|
271
|
-
}
|
|
272
|
-
});
|
|
273
|
-
|
|
274
|
-
// src/utils/colors.ts
|
|
275
|
-
function checkColorSupport() {
|
|
276
|
-
if (process.env["FORCE_COLOR"] !== void 0) {
|
|
277
|
-
return process.env["FORCE_COLOR"] !== "0";
|
|
278
|
-
}
|
|
279
|
-
if (process.env["NO_COLOR"] !== void 0) {
|
|
280
|
-
return false;
|
|
281
|
-
}
|
|
282
|
-
if (!process.stdout.isTTY) {
|
|
283
|
-
return false;
|
|
284
|
-
}
|
|
285
|
-
if (process.env["TERM"] === "dumb") {
|
|
286
|
-
return false;
|
|
287
|
-
}
|
|
288
|
-
if (process.env["CI"] !== void 0) {
|
|
289
|
-
const ciEnvs = ["TRAVIS", "CIRCLECI", "GITHUB_ACTIONS", "GITLAB_CI", "BUILDKITE"];
|
|
290
|
-
return ciEnvs.some((env) => process.env[env] !== void 0);
|
|
291
|
-
}
|
|
292
|
-
return true;
|
|
293
|
-
}
|
|
294
|
-
function colorize(text, ...codes) {
|
|
295
|
-
if (!supportsColor || codes.length === 0) {
|
|
296
|
-
return text;
|
|
297
|
-
}
|
|
298
|
-
return codes.join("") + text + colors.reset;
|
|
299
|
-
}
|
|
300
|
-
function createColorizer(code) {
|
|
301
|
-
return (text) => colorize(text, code);
|
|
302
|
-
}
|
|
303
|
-
function stripAnsi(text) {
|
|
304
|
-
return text.replace(/\x1b\[[0-9;]*m/g, "");
|
|
305
|
-
}
|
|
306
|
-
var supportsColor, colors, semantic;
|
|
307
|
-
var init_colors = __esm({
|
|
308
|
-
"src/utils/colors.ts"() {
|
|
309
|
-
supportsColor = checkColorSupport();
|
|
310
|
-
colors = {
|
|
311
|
-
// Reset
|
|
312
|
-
reset: supportsColor ? "\x1B[0m" : "",
|
|
313
|
-
// Text styles
|
|
314
|
-
bold: supportsColor ? "\x1B[1m" : "",
|
|
315
|
-
dim: supportsColor ? "\x1B[2m" : "",
|
|
316
|
-
italic: supportsColor ? "\x1B[3m" : "",
|
|
317
|
-
underline: supportsColor ? "\x1B[4m" : "",
|
|
318
|
-
blink: supportsColor ? "\x1B[5m" : "",
|
|
319
|
-
inverse: supportsColor ? "\x1B[7m" : "",
|
|
320
|
-
hidden: supportsColor ? "\x1B[8m" : "",
|
|
321
|
-
strikethrough: supportsColor ? "\x1B[9m" : "",
|
|
322
|
-
// Foreground colors
|
|
323
|
-
black: supportsColor ? "\x1B[30m" : "",
|
|
324
|
-
red: supportsColor ? "\x1B[31m" : "",
|
|
325
|
-
green: supportsColor ? "\x1B[32m" : "",
|
|
326
|
-
yellow: supportsColor ? "\x1B[33m" : "",
|
|
327
|
-
blue: supportsColor ? "\x1B[34m" : "",
|
|
328
|
-
magenta: supportsColor ? "\x1B[35m" : "",
|
|
329
|
-
cyan: supportsColor ? "\x1B[36m" : "",
|
|
330
|
-
white: supportsColor ? "\x1B[37m" : "",
|
|
331
|
-
gray: supportsColor ? "\x1B[90m" : "",
|
|
332
|
-
grey: supportsColor ? "\x1B[90m" : "",
|
|
333
|
-
// Bright foreground colors
|
|
334
|
-
brightRed: supportsColor ? "\x1B[91m" : "",
|
|
335
|
-
brightGreen: supportsColor ? "\x1B[92m" : "",
|
|
336
|
-
brightYellow: supportsColor ? "\x1B[93m" : "",
|
|
337
|
-
brightBlue: supportsColor ? "\x1B[94m" : "",
|
|
338
|
-
brightMagenta: supportsColor ? "\x1B[95m" : "",
|
|
339
|
-
brightCyan: supportsColor ? "\x1B[96m" : "",
|
|
340
|
-
brightWhite: supportsColor ? "\x1B[97m" : "",
|
|
341
|
-
// Background colors
|
|
342
|
-
bgBlack: supportsColor ? "\x1B[40m" : "",
|
|
343
|
-
bgRed: supportsColor ? "\x1B[41m" : "",
|
|
344
|
-
bgGreen: supportsColor ? "\x1B[42m" : "",
|
|
345
|
-
bgYellow: supportsColor ? "\x1B[43m" : "",
|
|
346
|
-
bgBlue: supportsColor ? "\x1B[44m" : "",
|
|
347
|
-
bgMagenta: supportsColor ? "\x1B[45m" : "",
|
|
348
|
-
bgCyan: supportsColor ? "\x1B[46m" : "",
|
|
349
|
-
bgWhite: supportsColor ? "\x1B[47m" : "",
|
|
350
|
-
bgGray: supportsColor ? "\x1B[100m" : "",
|
|
351
|
-
// Bright background colors
|
|
352
|
-
bgBrightRed: supportsColor ? "\x1B[101m" : "",
|
|
353
|
-
bgBrightGreen: supportsColor ? "\x1B[102m" : "",
|
|
354
|
-
bgBrightYellow: supportsColor ? "\x1B[103m" : "",
|
|
355
|
-
bgBrightBlue: supportsColor ? "\x1B[104m" : "",
|
|
356
|
-
bgBrightMagenta: supportsColor ? "\x1B[105m" : "",
|
|
357
|
-
bgBrightCyan: supportsColor ? "\x1B[106m" : "",
|
|
358
|
-
bgBrightWhite: supportsColor ? "\x1B[107m" : ""
|
|
359
|
-
};
|
|
360
|
-
semantic = {
|
|
361
|
-
/** Critical issues (red) */
|
|
362
|
-
critical: createColorizer(colors.red),
|
|
363
|
-
/** Warnings (yellow) */
|
|
364
|
-
warning: createColorizer(colors.yellow),
|
|
365
|
-
/** Healthy/success (green) */
|
|
366
|
-
healthy: createColorizer(colors.green),
|
|
367
|
-
/** Info/links (blue) */
|
|
368
|
-
info: createColorizer(colors.blue),
|
|
369
|
-
/** Secondary text (gray) */
|
|
370
|
-
secondary: createColorizer(colors.gray),
|
|
371
|
-
/** Highlighted text (cyan) */
|
|
372
|
-
highlight: createColorizer(colors.cyan),
|
|
373
|
-
/** Error text (bright red, bold) */
|
|
374
|
-
error: (text) => colorize(text, colors.brightRed, colors.bold),
|
|
375
|
-
/** Success text (bright green, bold) */
|
|
376
|
-
success: (text) => colorize(text, colors.brightGreen, colors.bold),
|
|
377
|
-
/** Title text (bold) */
|
|
378
|
-
title: createColorizer(colors.bold),
|
|
379
|
-
/** Dimmed text */
|
|
380
|
-
dimmed: createColorizer(colors.dim)
|
|
381
|
-
};
|
|
382
|
-
}
|
|
383
|
-
});
|
|
384
|
-
|
|
385
|
-
// src/utils/logger.ts
|
|
386
|
-
var LogLevel, LOG_LEVEL_NAMES, Logger;
|
|
387
|
-
var init_logger = __esm({
|
|
388
|
-
"src/utils/logger.ts"() {
|
|
389
|
-
init_colors();
|
|
390
|
-
LogLevel = /* @__PURE__ */ ((LogLevel2) => {
|
|
391
|
-
LogLevel2[LogLevel2["DEBUG"] = 0] = "DEBUG";
|
|
392
|
-
LogLevel2[LogLevel2["INFO"] = 1] = "INFO";
|
|
393
|
-
LogLevel2[LogLevel2["WARN"] = 2] = "WARN";
|
|
394
|
-
LogLevel2[LogLevel2["ERROR"] = 3] = "ERROR";
|
|
395
|
-
LogLevel2[LogLevel2["SILENT"] = 4] = "SILENT";
|
|
396
|
-
return LogLevel2;
|
|
397
|
-
})(LogLevel || {});
|
|
398
|
-
LOG_LEVEL_NAMES = {
|
|
399
|
-
[0 /* DEBUG */]: "DEBUG",
|
|
400
|
-
[1 /* INFO */]: "INFO",
|
|
401
|
-
[2 /* WARN */]: "WARN",
|
|
402
|
-
[3 /* ERROR */]: "ERROR",
|
|
403
|
-
[4 /* SILENT */]: "SILENT"
|
|
404
|
-
};
|
|
405
|
-
Logger = class _Logger {
|
|
406
|
-
prefix;
|
|
407
|
-
level;
|
|
408
|
-
showTimestamp;
|
|
409
|
-
showLevel;
|
|
410
|
-
output;
|
|
411
|
-
/**
|
|
412
|
-
* Create a new Logger instance
|
|
413
|
-
* @param options - Logger configuration
|
|
414
|
-
*/
|
|
415
|
-
constructor(options = {}) {
|
|
416
|
-
this.prefix = options.prefix ?? "";
|
|
417
|
-
this.level = options.level ?? 1 /* INFO */;
|
|
418
|
-
this.showTimestamp = options.showTimestamp ?? false;
|
|
419
|
-
this.showLevel = options.showLevel ?? true;
|
|
420
|
-
this.output = options.output ?? {
|
|
421
|
-
/* eslint-disable no-console */
|
|
422
|
-
log: (msg) => console.log(msg),
|
|
423
|
-
warn: (msg) => console.warn(msg),
|
|
424
|
-
error: (msg) => console.error(msg)
|
|
425
|
-
/* eslint-enable no-console */
|
|
426
|
-
};
|
|
427
|
-
}
|
|
428
|
-
/**
|
|
429
|
-
* Format a log message
|
|
430
|
-
* @param level - Log level
|
|
431
|
-
* @param message - Message to format
|
|
432
|
-
* @returns Formatted message
|
|
433
|
-
*/
|
|
434
|
-
format(level, message) {
|
|
435
|
-
const parts = [];
|
|
436
|
-
if (this.showTimestamp) {
|
|
437
|
-
const now = /* @__PURE__ */ new Date();
|
|
438
|
-
const time = now.toISOString().slice(11, 23);
|
|
439
|
-
parts.push(semantic.secondary(`[${time}]`));
|
|
440
|
-
}
|
|
441
|
-
if (this.showLevel) {
|
|
442
|
-
const levelName = LOG_LEVEL_NAMES[level] ?? "UNKNOWN";
|
|
443
|
-
let levelStr;
|
|
444
|
-
switch (level) {
|
|
445
|
-
case 0 /* DEBUG */:
|
|
446
|
-
levelStr = semantic.secondary(levelName);
|
|
447
|
-
break;
|
|
448
|
-
case 1 /* INFO */:
|
|
449
|
-
levelStr = semantic.info(levelName);
|
|
450
|
-
break;
|
|
451
|
-
case 2 /* WARN */:
|
|
452
|
-
levelStr = semantic.warning(levelName);
|
|
453
|
-
break;
|
|
454
|
-
case 3 /* ERROR */:
|
|
455
|
-
levelStr = semantic.error(levelName);
|
|
456
|
-
break;
|
|
457
|
-
default:
|
|
458
|
-
levelStr = levelName;
|
|
459
|
-
}
|
|
460
|
-
parts.push(`[${levelStr}]`);
|
|
461
|
-
}
|
|
462
|
-
if (this.prefix) {
|
|
463
|
-
parts.push(semantic.highlight(`[${this.prefix}]`));
|
|
464
|
-
}
|
|
465
|
-
parts.push(message);
|
|
466
|
-
return parts.join(" ");
|
|
467
|
-
}
|
|
468
|
-
/**
|
|
469
|
-
* Log a debug message
|
|
470
|
-
* @param message - Message to log
|
|
471
|
-
* @param args - Additional arguments to log
|
|
472
|
-
*/
|
|
473
|
-
debug(message, ...args) {
|
|
474
|
-
if (this.level > 0 /* DEBUG */) return;
|
|
475
|
-
const formatted = this.format(0 /* DEBUG */, message);
|
|
476
|
-
if (args.length > 0) {
|
|
477
|
-
this.output.log(formatted + " " + args.map(String).join(" "));
|
|
478
|
-
} else {
|
|
479
|
-
this.output.log(formatted);
|
|
480
|
-
}
|
|
481
|
-
}
|
|
482
|
-
/**
|
|
483
|
-
* Log an info message
|
|
484
|
-
* @param message - Message to log
|
|
485
|
-
* @param args - Additional arguments to log
|
|
486
|
-
*/
|
|
487
|
-
info(message, ...args) {
|
|
488
|
-
if (this.level > 1 /* INFO */) return;
|
|
489
|
-
const formatted = this.format(1 /* INFO */, message);
|
|
490
|
-
if (args.length > 0) {
|
|
491
|
-
this.output.log(formatted + " " + args.map(String).join(" "));
|
|
492
|
-
} else {
|
|
493
|
-
this.output.log(formatted);
|
|
494
|
-
}
|
|
495
|
-
}
|
|
496
|
-
/**
|
|
497
|
-
* Log a warning message
|
|
498
|
-
* @param message - Message to log
|
|
499
|
-
* @param args - Additional arguments to log
|
|
500
|
-
*/
|
|
501
|
-
warn(message, ...args) {
|
|
502
|
-
if (this.level > 2 /* WARN */) return;
|
|
503
|
-
const formatted = this.format(2 /* WARN */, message);
|
|
504
|
-
if (args.length > 0) {
|
|
505
|
-
this.output.warn(formatted + " " + args.map(String).join(" "));
|
|
506
|
-
} else {
|
|
507
|
-
this.output.warn(formatted);
|
|
508
|
-
}
|
|
509
|
-
}
|
|
510
|
-
/**
|
|
511
|
-
* Log an error message
|
|
512
|
-
* @param message - Message to log
|
|
513
|
-
* @param args - Additional arguments to log
|
|
514
|
-
*/
|
|
515
|
-
error(message, ...args) {
|
|
516
|
-
if (this.level > 3 /* ERROR */) return;
|
|
517
|
-
const formatted = this.format(3 /* ERROR */, message);
|
|
518
|
-
if (args.length > 0) {
|
|
519
|
-
this.output.error(formatted + " " + args.map(String).join(" "));
|
|
520
|
-
} else {
|
|
521
|
-
this.output.error(formatted);
|
|
522
|
-
}
|
|
523
|
-
}
|
|
524
|
-
/**
|
|
525
|
-
* Log a success message (always shown unless silent)
|
|
526
|
-
* @param message - Message to log
|
|
527
|
-
*/
|
|
528
|
-
success(message) {
|
|
529
|
-
if (this.level >= 4 /* SILENT */) return;
|
|
530
|
-
const prefix = this.prefix ? `[${semantic.highlight(this.prefix)}] ` : "";
|
|
531
|
-
this.output.log(prefix + semantic.success("\u2713 ") + message);
|
|
532
|
-
}
|
|
533
|
-
/**
|
|
534
|
-
* Log a failure message (always shown unless silent)
|
|
535
|
-
* @param message - Message to log
|
|
536
|
-
*/
|
|
537
|
-
fail(message) {
|
|
538
|
-
if (this.level >= 4 /* SILENT */) return;
|
|
539
|
-
const prefix = this.prefix ? `[${semantic.highlight(this.prefix)}] ` : "";
|
|
540
|
-
this.output.error(prefix + semantic.error("\u2717 ") + message);
|
|
541
|
-
}
|
|
542
|
-
/**
|
|
543
|
-
* Create a child logger with a sub-prefix
|
|
544
|
-
* @param prefix - Sub-prefix for the child logger
|
|
545
|
-
* @returns New Logger instance
|
|
546
|
-
*/
|
|
547
|
-
child(prefix) {
|
|
548
|
-
const childPrefix = this.prefix ? `${this.prefix}:${prefix}` : prefix;
|
|
549
|
-
return new _Logger({
|
|
550
|
-
prefix: childPrefix,
|
|
551
|
-
level: this.level,
|
|
552
|
-
showTimestamp: this.showTimestamp,
|
|
553
|
-
showLevel: this.showLevel,
|
|
554
|
-
output: this.output
|
|
555
|
-
});
|
|
556
|
-
}
|
|
557
|
-
/**
|
|
558
|
-
* Set the log level
|
|
559
|
-
* @param level - New log level
|
|
560
|
-
*/
|
|
561
|
-
setLevel(level) {
|
|
562
|
-
this.level = level;
|
|
563
|
-
}
|
|
564
|
-
/**
|
|
565
|
-
* Get the current log level
|
|
566
|
-
* @returns Current log level
|
|
567
|
-
*/
|
|
568
|
-
getLevel() {
|
|
569
|
-
return this.level;
|
|
570
|
-
}
|
|
571
|
-
/**
|
|
572
|
-
* Check if a log level is enabled
|
|
573
|
-
* @param level - Level to check
|
|
574
|
-
* @returns true if the level would be logged
|
|
575
|
-
*/
|
|
576
|
-
isLevelEnabled(level) {
|
|
577
|
-
return this.level <= level;
|
|
578
|
-
}
|
|
579
|
-
/**
|
|
580
|
-
* Create a timer for performance logging
|
|
581
|
-
* @param label - Timer label
|
|
582
|
-
* @returns Object with end() method to log duration
|
|
583
|
-
*/
|
|
584
|
-
time(label) {
|
|
585
|
-
const start = performance.now();
|
|
586
|
-
return {
|
|
587
|
-
end: () => {
|
|
588
|
-
const duration = performance.now() - start;
|
|
589
|
-
this.debug(`${label}: ${duration.toFixed(2)}ms`);
|
|
590
|
-
}
|
|
591
|
-
};
|
|
592
|
-
}
|
|
593
|
-
/**
|
|
594
|
-
* Log a table of data
|
|
595
|
-
* @param data - Array of objects to display
|
|
596
|
-
* @param columns - Optional column names to show
|
|
597
|
-
*/
|
|
598
|
-
table(data, columns) {
|
|
599
|
-
if (this.level >= 4 /* SILENT */) return;
|
|
600
|
-
if (data.length === 0) {
|
|
601
|
-
this.info("(empty table)");
|
|
602
|
-
return;
|
|
603
|
-
}
|
|
604
|
-
const cols = columns ?? Object.keys(data[0] ?? {});
|
|
605
|
-
if (cols.length === 0) {
|
|
606
|
-
this.info("(no columns)");
|
|
607
|
-
return;
|
|
608
|
-
}
|
|
609
|
-
const widths = {};
|
|
610
|
-
for (const col of cols) {
|
|
611
|
-
widths[col] = col.length;
|
|
612
|
-
for (const row of data) {
|
|
613
|
-
const value = String(row[col] ?? "");
|
|
614
|
-
widths[col] = Math.max(widths[col] ?? 0, value.length);
|
|
615
|
-
}
|
|
616
|
-
}
|
|
617
|
-
const header = cols.map((col) => col.padEnd(widths[col] ?? 0)).join(" \u2502 ");
|
|
618
|
-
const separator = cols.map((col) => "\u2500".repeat(widths[col] ?? 0)).join("\u2500\u253C\u2500");
|
|
619
|
-
this.output.log(colors.bold + header + colors.reset);
|
|
620
|
-
this.output.log(separator);
|
|
621
|
-
for (const row of data) {
|
|
622
|
-
const line = cols.map((col) => String(row[col] ?? "").padEnd(widths[col] ?? 0)).join(" \u2502 ");
|
|
623
|
-
this.output.log(line);
|
|
624
|
-
}
|
|
625
|
-
}
|
|
626
|
-
/**
|
|
627
|
-
* Log a progress message (overwrites previous line)
|
|
628
|
-
* @param message - Progress message
|
|
629
|
-
*/
|
|
630
|
-
progress(message) {
|
|
631
|
-
if (this.level >= 4 /* SILENT */) return;
|
|
632
|
-
if (process.stdout.isTTY) {
|
|
633
|
-
process.stdout.write(`\r\x1B[K${message}`);
|
|
634
|
-
}
|
|
635
|
-
}
|
|
636
|
-
/**
|
|
637
|
-
* Clear the progress line
|
|
638
|
-
*/
|
|
639
|
-
clearProgress() {
|
|
640
|
-
if (process.stdout.isTTY) {
|
|
641
|
-
process.stdout.write("\r\x1B[K");
|
|
642
|
-
}
|
|
643
|
-
}
|
|
644
|
-
/**
|
|
645
|
-
* Log a newline
|
|
646
|
-
*/
|
|
647
|
-
newline() {
|
|
648
|
-
if (this.level >= 4 /* SILENT */) return;
|
|
649
|
-
this.output.log("");
|
|
650
|
-
}
|
|
651
|
-
/**
|
|
652
|
-
* Log a horizontal rule
|
|
653
|
-
* @param char - Character to use for the rule
|
|
654
|
-
* @param width - Width of the rule
|
|
655
|
-
*/
|
|
656
|
-
hr(char = "\u2500", width = 60) {
|
|
657
|
-
if (this.level >= 4 /* SILENT */) return;
|
|
658
|
-
this.output.log(colors.gray + char.repeat(width) + colors.reset);
|
|
659
|
-
}
|
|
660
|
-
/**
|
|
661
|
-
* Group related log messages
|
|
662
|
-
* @param label - Group label
|
|
663
|
-
* @param fn - Function containing log calls
|
|
664
|
-
*/
|
|
665
|
-
group(label, fn) {
|
|
666
|
-
if (this.level >= 4 /* SILENT */) return;
|
|
667
|
-
this.output.log(colors.bold + "\u250C " + label + colors.reset);
|
|
668
|
-
fn();
|
|
669
|
-
this.output.log(colors.bold + "\u2514" + "\u2500".repeat(label.length + 1) + colors.reset);
|
|
670
|
-
}
|
|
671
|
-
};
|
|
672
|
-
new Logger({ prefix: "ReactCheck" });
|
|
673
|
-
}
|
|
674
|
-
});
|
|
675
|
-
|
|
676
|
-
// src/server/browser.ts
|
|
677
|
-
var browser_exports = {};
|
|
678
|
-
__export(browser_exports, {
|
|
679
|
-
BrowserLauncher: () => BrowserLauncher,
|
|
680
|
-
isPuppeteerAvailable: () => isPuppeteerAvailable
|
|
681
|
-
});
|
|
682
|
-
async function isPuppeteerAvailable() {
|
|
683
|
-
try {
|
|
684
|
-
await import('puppeteer');
|
|
685
|
-
return true;
|
|
686
|
-
} catch {
|
|
687
|
-
return false;
|
|
688
|
-
}
|
|
689
|
-
}
|
|
690
|
-
var logger3, BrowserLauncher;
|
|
691
|
-
var init_browser = __esm({
|
|
692
|
-
"src/server/browser.ts"() {
|
|
693
|
-
init_event_emitter();
|
|
694
|
-
init_logger();
|
|
695
|
-
logger3 = new Logger({ prefix: "browser", level: 0 /* DEBUG */ });
|
|
696
|
-
BrowserLauncher = class extends EventEmitter {
|
|
697
|
-
/** Puppeteer browser instance */
|
|
698
|
-
browser = null;
|
|
699
|
-
/** Active page */
|
|
700
|
-
page = null;
|
|
701
|
-
/** Launch options */
|
|
702
|
-
options;
|
|
703
|
-
/** Injection script */
|
|
704
|
-
injectionScript = null;
|
|
705
|
-
/**
|
|
706
|
-
* Create a new browser launcher
|
|
707
|
-
* @param options - Launch options
|
|
708
|
-
*/
|
|
709
|
-
constructor(options) {
|
|
710
|
-
super();
|
|
711
|
-
this.options = {
|
|
712
|
-
url: options.url,
|
|
713
|
-
headless: options.headless ?? false,
|
|
714
|
-
width: options.width ?? 1280,
|
|
715
|
-
height: options.height ?? 800,
|
|
716
|
-
wsPort: options.wsPort ?? 3099,
|
|
717
|
-
args: options.args ?? [],
|
|
718
|
-
slowMo: options.slowMo ?? 0,
|
|
719
|
-
timeout: options.timeout ?? 3e4
|
|
720
|
-
};
|
|
721
|
-
}
|
|
722
|
-
/**
|
|
723
|
-
* Set the injection script
|
|
724
|
-
* @param script - Script to inject before page loads
|
|
725
|
-
*/
|
|
726
|
-
setInjectionScript(script) {
|
|
727
|
-
this.injectionScript = script;
|
|
728
|
-
}
|
|
729
|
-
/**
|
|
730
|
-
* Launch the browser
|
|
731
|
-
*/
|
|
732
|
-
async launch() {
|
|
733
|
-
try {
|
|
734
|
-
const puppeteer = await import('puppeteer');
|
|
735
|
-
const args = [
|
|
736
|
-
"--no-sandbox",
|
|
737
|
-
"--disable-setuid-sandbox",
|
|
738
|
-
"--disable-dev-shm-usage",
|
|
739
|
-
"--disable-gpu",
|
|
740
|
-
"--ignore-certificate-errors",
|
|
741
|
-
"--ignore-certificate-errors-spki-list",
|
|
742
|
-
`--window-size=${this.options.width},${this.options.height}`,
|
|
743
|
-
...this.options.args
|
|
744
|
-
];
|
|
745
|
-
this.browser = await puppeteer.default.launch({
|
|
746
|
-
headless: this.options.headless,
|
|
747
|
-
args,
|
|
748
|
-
slowMo: this.options.slowMo,
|
|
749
|
-
defaultViewport: {
|
|
750
|
-
width: this.options.width,
|
|
751
|
-
height: this.options.height
|
|
752
|
-
}
|
|
753
|
-
});
|
|
754
|
-
const pages = await this.browser.pages();
|
|
755
|
-
this.page = pages[0] ?? await this.browser.newPage();
|
|
756
|
-
this.setupPageHandlers();
|
|
757
|
-
if (this.injectionScript) {
|
|
758
|
-
logger3.debug("Injecting ReactCheck script into page...");
|
|
759
|
-
await this.page.evaluateOnNewDocument(this.injectionScript);
|
|
760
|
-
logger3.debug("Injection script registered");
|
|
761
|
-
}
|
|
762
|
-
this.emit("launched", void 0);
|
|
763
|
-
logger3.info("Browser launched");
|
|
764
|
-
await this.navigate(this.options.url);
|
|
765
|
-
} catch (error) {
|
|
766
|
-
const err = error instanceof Error ? error : new Error(String(error));
|
|
767
|
-
this.emit("error", err);
|
|
768
|
-
throw err;
|
|
769
|
-
}
|
|
770
|
-
}
|
|
771
|
-
/**
|
|
772
|
-
* Set up page event handlers
|
|
773
|
-
*/
|
|
774
|
-
setupPageHandlers() {
|
|
775
|
-
if (!this.page) return;
|
|
776
|
-
this.page.on("console", (msg) => {
|
|
777
|
-
this.emit("console", {
|
|
778
|
-
type: msg.type(),
|
|
779
|
-
text: msg.text()
|
|
780
|
-
});
|
|
781
|
-
});
|
|
782
|
-
this.page.on("pageerror", (error) => {
|
|
783
|
-
this.emit("error", error);
|
|
784
|
-
});
|
|
785
|
-
this.page.on("framenavigated", (frame) => {
|
|
786
|
-
if (frame === this.page?.mainFrame()) {
|
|
787
|
-
this.emit("navigated", { url: frame.url() });
|
|
788
|
-
}
|
|
789
|
-
});
|
|
790
|
-
this.page.on("load", () => {
|
|
791
|
-
this.emit("loaded", void 0);
|
|
792
|
-
});
|
|
793
|
-
}
|
|
794
|
-
/**
|
|
795
|
-
* Navigate to a URL with retry support
|
|
796
|
-
* @param url - URL to navigate to
|
|
797
|
-
* @param retries - Number of retries (default: 3)
|
|
798
|
-
* @param retryDelay - Delay between retries in ms (default: 2000)
|
|
799
|
-
*/
|
|
800
|
-
async navigate(url, retries = 3, retryDelay = 2e3) {
|
|
801
|
-
if (!this.page) {
|
|
802
|
-
throw new Error("Browser not launched");
|
|
803
|
-
}
|
|
804
|
-
let lastError = null;
|
|
805
|
-
for (let attempt = 1; attempt <= retries; attempt++) {
|
|
806
|
-
try {
|
|
807
|
-
await this.page.goto(url, {
|
|
808
|
-
waitUntil: "networkidle2",
|
|
809
|
-
timeout: this.options.timeout
|
|
810
|
-
});
|
|
811
|
-
this.emit("navigated", { url });
|
|
812
|
-
logger3.info(`Navigated to ${url}`);
|
|
813
|
-
return;
|
|
814
|
-
} catch (error) {
|
|
815
|
-
lastError = error instanceof Error ? error : new Error(String(error));
|
|
816
|
-
this.emit("error", lastError);
|
|
817
|
-
if (lastError.message.includes("ERR_CONNECTION_REFUSED") && attempt < retries) {
|
|
818
|
-
logger3.warn(`Connection refused, retrying in ${retryDelay}ms... (${attempt}/${retries})`);
|
|
819
|
-
await new Promise((resolve2) => setTimeout(resolve2, retryDelay));
|
|
820
|
-
continue;
|
|
821
|
-
}
|
|
822
|
-
throw lastError;
|
|
823
|
-
}
|
|
824
|
-
}
|
|
825
|
-
throw lastError ?? new Error("Navigation failed");
|
|
826
|
-
}
|
|
827
|
-
/**
|
|
828
|
-
* Execute script in page context
|
|
829
|
-
* @param script - Script to execute
|
|
830
|
-
* @returns Script result
|
|
831
|
-
*/
|
|
832
|
-
async evaluate(script) {
|
|
833
|
-
if (!this.page) {
|
|
834
|
-
throw new Error("Browser not launched");
|
|
835
|
-
}
|
|
836
|
-
return this.page.evaluate(script);
|
|
837
|
-
}
|
|
838
|
-
/**
|
|
839
|
-
* Wait for selector
|
|
840
|
-
* @param selector - CSS selector
|
|
841
|
-
* @param timeout - Timeout in ms
|
|
842
|
-
*/
|
|
843
|
-
async waitForSelector(selector, timeout) {
|
|
844
|
-
if (!this.page) {
|
|
845
|
-
throw new Error("Browser not launched");
|
|
846
|
-
}
|
|
847
|
-
await this.page.waitForSelector(selector, {
|
|
848
|
-
timeout: timeout ?? this.options.timeout
|
|
849
|
-
});
|
|
850
|
-
}
|
|
851
|
-
/**
|
|
852
|
-
* Take a screenshot
|
|
853
|
-
* @param path - File path to save screenshot
|
|
854
|
-
*/
|
|
855
|
-
async screenshot(path) {
|
|
856
|
-
if (!this.page) {
|
|
857
|
-
throw new Error("Browser not launched");
|
|
858
|
-
}
|
|
859
|
-
await this.page.screenshot({ path, fullPage: true });
|
|
860
|
-
logger3.info(`Screenshot saved to ${path}`);
|
|
861
|
-
}
|
|
862
|
-
/**
|
|
863
|
-
* Reload the page
|
|
864
|
-
*/
|
|
865
|
-
async reload() {
|
|
866
|
-
if (!this.page) {
|
|
867
|
-
throw new Error("Browser not launched");
|
|
868
|
-
}
|
|
869
|
-
await this.page.reload({ waitUntil: "networkidle2" });
|
|
870
|
-
}
|
|
871
|
-
/**
|
|
872
|
-
* Get current URL
|
|
873
|
-
* @returns Current page URL
|
|
874
|
-
*/
|
|
875
|
-
getUrl() {
|
|
876
|
-
return this.page?.url() ?? null;
|
|
877
|
-
}
|
|
878
|
-
/**
|
|
879
|
-
* Close the browser
|
|
880
|
-
*/
|
|
881
|
-
async close() {
|
|
882
|
-
if (this.browser) {
|
|
883
|
-
await this.browser.close();
|
|
884
|
-
this.browser = null;
|
|
885
|
-
this.page = null;
|
|
886
|
-
this.emit("closed", void 0);
|
|
887
|
-
logger3.info("Browser closed");
|
|
888
|
-
}
|
|
889
|
-
}
|
|
890
|
-
/**
|
|
891
|
-
* Check if browser is open
|
|
892
|
-
* @returns true if browser is open
|
|
893
|
-
*/
|
|
894
|
-
isOpen() {
|
|
895
|
-
return this.browser !== null && this.browser.connected;
|
|
896
|
-
}
|
|
897
|
-
/**
|
|
898
|
-
* Get the page instance (for advanced usage)
|
|
899
|
-
* @returns Puppeteer page or null
|
|
900
|
-
*/
|
|
901
|
-
getPage() {
|
|
902
|
-
return this.page;
|
|
903
|
-
}
|
|
904
|
-
/**
|
|
905
|
-
* Get the browser instance (for advanced usage)
|
|
906
|
-
* @returns Puppeteer browser or null
|
|
907
|
-
*/
|
|
908
|
-
getBrowser() {
|
|
909
|
-
return this.browser;
|
|
910
|
-
}
|
|
911
|
-
};
|
|
912
|
-
}
|
|
913
|
-
});
|
|
12
|
+
import { URL, fileURLToPath } from 'url';
|
|
13
|
+
import { readFile } from 'fs/promises';
|
|
14
|
+
import { dirname, resolve } from 'path';
|
|
914
15
|
|
|
915
16
|
// src/types.ts
|
|
916
17
|
var ErrorCode = /* @__PURE__ */ ((ErrorCode2) => {
|
|
@@ -935,1418 +36,7 @@ var ReactCheckError = class extends Error {
|
|
|
935
36
|
super(message);
|
|
936
37
|
this.name = "ReactCheckError";
|
|
937
38
|
this.code = code;
|
|
938
|
-
this.details = details;
|
|
939
|
-
}
|
|
940
|
-
};
|
|
941
|
-
|
|
942
|
-
// src/core/scanner.ts
|
|
943
|
-
init_event_emitter();
|
|
944
|
-
|
|
945
|
-
// src/core/stats.ts
|
|
946
|
-
init_event_emitter();
|
|
947
|
-
var DEFAULT_THRESHOLDS = {
|
|
948
|
-
critical: 50,
|
|
949
|
-
warning: 20,
|
|
950
|
-
fps: 30
|
|
951
|
-
};
|
|
952
|
-
var StatsCollector = class extends EventEmitter {
|
|
953
|
-
/** Map of component names to their statistics */
|
|
954
|
-
components = /* @__PURE__ */ new Map();
|
|
955
|
-
/** Threshold configuration */
|
|
956
|
-
thresholds;
|
|
957
|
-
/** Session start time */
|
|
958
|
-
sessionStart;
|
|
959
|
-
/** Total render count across all components */
|
|
960
|
-
totalRenders = 0;
|
|
961
|
-
/** FPS samples for averaging */
|
|
962
|
-
fpsSamples = [];
|
|
963
|
-
/** Maximum FPS samples to keep */
|
|
964
|
-
maxFpsSamples = 100;
|
|
965
|
-
/**
|
|
966
|
-
* Create a new StatsCollector
|
|
967
|
-
* @param thresholds - Threshold configuration
|
|
968
|
-
*/
|
|
969
|
-
constructor(thresholds = {}) {
|
|
970
|
-
super();
|
|
971
|
-
this.thresholds = { ...DEFAULT_THRESHOLDS, ...thresholds };
|
|
972
|
-
this.sessionStart = Date.now();
|
|
973
|
-
}
|
|
974
|
-
/**
|
|
975
|
-
* Add a render event to the statistics
|
|
976
|
-
* @param render - Render information
|
|
977
|
-
*/
|
|
978
|
-
addRender(render) {
|
|
979
|
-
const stats = this.getOrCreateStats(render.componentName);
|
|
980
|
-
const previousSeverity = stats.severity;
|
|
981
|
-
stats.renders++;
|
|
982
|
-
this.totalRenders++;
|
|
983
|
-
stats.totalRenderTime += render.renderTime;
|
|
984
|
-
stats.avgRenderTime = stats.totalRenderTime / stats.renders;
|
|
985
|
-
stats.maxRenderTime = Math.max(stats.maxRenderTime, render.renderTime);
|
|
986
|
-
stats.minRenderTime = Math.min(stats.minRenderTime, render.renderTime);
|
|
987
|
-
if (!render.necessary) {
|
|
988
|
-
stats.unnecessary++;
|
|
989
|
-
}
|
|
990
|
-
if (stats.firstRender === 0) {
|
|
991
|
-
stats.firstRender = render.timestamp;
|
|
992
|
-
}
|
|
993
|
-
stats.lastRender = render.timestamp;
|
|
994
|
-
if (render.changedProps && render.changedProps.length > 0) {
|
|
995
|
-
stats.propsChanged = true;
|
|
996
|
-
}
|
|
997
|
-
if (render.changedState && render.changedState.length > 0) {
|
|
998
|
-
stats.stateChanged = true;
|
|
999
|
-
}
|
|
1000
|
-
const sessionDuration = Date.now() - this.sessionStart;
|
|
1001
|
-
const sessionMinutes = sessionDuration / 6e4;
|
|
1002
|
-
stats.expectedRenders = Math.max(1, Math.ceil(sessionMinutes * 5));
|
|
1003
|
-
this.updateSeverity(stats);
|
|
1004
|
-
this.emit("update", stats);
|
|
1005
|
-
if (stats.severity !== previousSeverity) {
|
|
1006
|
-
this.emit("severityChange", {
|
|
1007
|
-
component: stats.name,
|
|
1008
|
-
from: previousSeverity,
|
|
1009
|
-
to: stats.severity
|
|
1010
|
-
});
|
|
1011
|
-
if (stats.severity === "critical" && previousSeverity !== "critical") {
|
|
1012
|
-
this.emit("critical", stats);
|
|
1013
|
-
} else if (stats.severity === "warning" && previousSeverity === "healthy") {
|
|
1014
|
-
this.emit("warning", stats);
|
|
1015
|
-
}
|
|
1016
|
-
}
|
|
1017
|
-
}
|
|
1018
|
-
/**
|
|
1019
|
-
* Record an FPS sample
|
|
1020
|
-
* @param fps - FPS value
|
|
1021
|
-
*/
|
|
1022
|
-
addFpsSample(fps) {
|
|
1023
|
-
this.fpsSamples.push(fps);
|
|
1024
|
-
if (this.fpsSamples.length > this.maxFpsSamples) {
|
|
1025
|
-
this.fpsSamples.shift();
|
|
1026
|
-
}
|
|
1027
|
-
}
|
|
1028
|
-
/**
|
|
1029
|
-
* Get or create stats for a component
|
|
1030
|
-
* @param name - Component name
|
|
1031
|
-
* @returns Component stats
|
|
1032
|
-
*/
|
|
1033
|
-
getOrCreateStats(name) {
|
|
1034
|
-
let stats = this.components.get(name);
|
|
1035
|
-
if (!stats) {
|
|
1036
|
-
stats = this.createEmptyStats(name);
|
|
1037
|
-
this.components.set(name, stats);
|
|
1038
|
-
}
|
|
1039
|
-
return stats;
|
|
1040
|
-
}
|
|
1041
|
-
/**
|
|
1042
|
-
* Create empty stats for a component
|
|
1043
|
-
* @param name - Component name
|
|
1044
|
-
* @returns Empty component stats
|
|
1045
|
-
*/
|
|
1046
|
-
createEmptyStats(name) {
|
|
1047
|
-
return {
|
|
1048
|
-
name,
|
|
1049
|
-
renders: 0,
|
|
1050
|
-
expectedRenders: 1,
|
|
1051
|
-
avgRenderTime: 0,
|
|
1052
|
-
maxRenderTime: 0,
|
|
1053
|
-
minRenderTime: Infinity,
|
|
1054
|
-
totalRenderTime: 0,
|
|
1055
|
-
unnecessary: 0,
|
|
1056
|
-
severity: "healthy",
|
|
1057
|
-
chain: [],
|
|
1058
|
-
fixes: [],
|
|
1059
|
-
firstRender: 0,
|
|
1060
|
-
lastRender: 0,
|
|
1061
|
-
propsChanged: false,
|
|
1062
|
-
stateChanged: false
|
|
1063
|
-
};
|
|
1064
|
-
}
|
|
1065
|
-
/**
|
|
1066
|
-
* Update severity for a component based on thresholds
|
|
1067
|
-
* @param stats - Component stats to update
|
|
1068
|
-
*/
|
|
1069
|
-
updateSeverity(stats) {
|
|
1070
|
-
if (stats.renders >= this.thresholds.critical) {
|
|
1071
|
-
stats.severity = "critical";
|
|
1072
|
-
} else if (stats.renders >= this.thresholds.warning) {
|
|
1073
|
-
stats.severity = "warning";
|
|
1074
|
-
} else {
|
|
1075
|
-
stats.severity = "healthy";
|
|
1076
|
-
}
|
|
1077
|
-
}
|
|
1078
|
-
/**
|
|
1079
|
-
* Get stats for a specific component
|
|
1080
|
-
* @param name - Component name
|
|
1081
|
-
* @returns Component stats or undefined
|
|
1082
|
-
*/
|
|
1083
|
-
getComponentStats(name) {
|
|
1084
|
-
return this.components.get(name);
|
|
1085
|
-
}
|
|
1086
|
-
/**
|
|
1087
|
-
* Get all component stats
|
|
1088
|
-
* @returns Array of component stats
|
|
1089
|
-
*/
|
|
1090
|
-
getAllStats() {
|
|
1091
|
-
return Array.from(this.components.values());
|
|
1092
|
-
}
|
|
1093
|
-
/**
|
|
1094
|
-
* Get a snapshot of all stats sorted by severity/render count
|
|
1095
|
-
* @returns Sorted array of component stats
|
|
1096
|
-
*/
|
|
1097
|
-
getSnapshot() {
|
|
1098
|
-
return this.getAllStats().sort((a, b) => {
|
|
1099
|
-
const severityOrder = {
|
|
1100
|
-
critical: 0,
|
|
1101
|
-
warning: 1,
|
|
1102
|
-
info: 2,
|
|
1103
|
-
healthy: 3
|
|
1104
|
-
};
|
|
1105
|
-
const severityDiff = severityOrder[a.severity] - severityOrder[b.severity];
|
|
1106
|
-
if (severityDiff !== 0) return severityDiff;
|
|
1107
|
-
return b.renders - a.renders;
|
|
1108
|
-
});
|
|
1109
|
-
}
|
|
1110
|
-
/**
|
|
1111
|
-
* Get components by severity
|
|
1112
|
-
* @param severity - Severity level to filter
|
|
1113
|
-
* @returns Array of matching component stats
|
|
1114
|
-
*/
|
|
1115
|
-
getComponentsBySeverity(severity) {
|
|
1116
|
-
return this.getAllStats().filter((s) => s.severity === severity);
|
|
1117
|
-
}
|
|
1118
|
-
/**
|
|
1119
|
-
* Get session summary
|
|
1120
|
-
* @returns Session summary statistics
|
|
1121
|
-
*/
|
|
1122
|
-
getSummary() {
|
|
1123
|
-
const stats = this.getAllStats();
|
|
1124
|
-
const criticalCount = stats.filter((s) => s.severity === "critical").length;
|
|
1125
|
-
const warningCount = stats.filter((s) => s.severity === "warning").length;
|
|
1126
|
-
const healthyCount = stats.filter((s) => s.severity === "healthy").length;
|
|
1127
|
-
const unnecessaryCount = stats.reduce((sum, s) => sum + s.unnecessary, 0);
|
|
1128
|
-
let avgFps = 60;
|
|
1129
|
-
let minFps = 60;
|
|
1130
|
-
if (this.fpsSamples.length > 0) {
|
|
1131
|
-
avgFps = this.fpsSamples.reduce((a, b) => a + b, 0) / this.fpsSamples.length;
|
|
1132
|
-
minFps = Math.min(...this.fpsSamples);
|
|
1133
|
-
}
|
|
1134
|
-
return {
|
|
1135
|
-
totalComponents: stats.length,
|
|
1136
|
-
totalRenders: this.totalRenders,
|
|
1137
|
-
criticalIssues: criticalCount,
|
|
1138
|
-
warnings: warningCount,
|
|
1139
|
-
healthy: healthyCount,
|
|
1140
|
-
avgFps: Math.round(avgFps),
|
|
1141
|
-
minFps: Math.round(minFps),
|
|
1142
|
-
unnecessaryRenders: unnecessaryCount
|
|
1143
|
-
};
|
|
1144
|
-
}
|
|
1145
|
-
/**
|
|
1146
|
-
* Get the most problematic components
|
|
1147
|
-
* @param limit - Maximum number to return
|
|
1148
|
-
* @returns Top problematic components
|
|
1149
|
-
*/
|
|
1150
|
-
getTopProblems(limit = 10) {
|
|
1151
|
-
return this.getSnapshot().filter((s) => s.severity !== "healthy").slice(0, limit);
|
|
1152
|
-
}
|
|
1153
|
-
/**
|
|
1154
|
-
* Update chain information for a component
|
|
1155
|
-
* @param componentName - Component name
|
|
1156
|
-
* @param chain - Render chain
|
|
1157
|
-
*/
|
|
1158
|
-
setComponentChain(componentName, chain) {
|
|
1159
|
-
const stats = this.components.get(componentName);
|
|
1160
|
-
if (stats) {
|
|
1161
|
-
stats.chain = chain;
|
|
1162
|
-
}
|
|
1163
|
-
}
|
|
1164
|
-
/**
|
|
1165
|
-
* Update parent information for a component
|
|
1166
|
-
* @param componentName - Component name
|
|
1167
|
-
* @param parentName - Parent component name
|
|
1168
|
-
*/
|
|
1169
|
-
setComponentParent(componentName, parentName) {
|
|
1170
|
-
const stats = this.components.get(componentName);
|
|
1171
|
-
if (stats) {
|
|
1172
|
-
stats.parent = parentName;
|
|
1173
|
-
}
|
|
1174
|
-
}
|
|
1175
|
-
/**
|
|
1176
|
-
* Reset all statistics
|
|
1177
|
-
*/
|
|
1178
|
-
reset() {
|
|
1179
|
-
this.components.clear();
|
|
1180
|
-
this.totalRenders = 0;
|
|
1181
|
-
this.fpsSamples = [];
|
|
1182
|
-
this.sessionStart = Date.now();
|
|
1183
|
-
}
|
|
1184
|
-
/**
|
|
1185
|
-
* Update threshold configuration
|
|
1186
|
-
* @param thresholds - New thresholds
|
|
1187
|
-
*/
|
|
1188
|
-
setThresholds(thresholds) {
|
|
1189
|
-
this.thresholds = { ...this.thresholds, ...thresholds };
|
|
1190
|
-
for (const stats of this.components.values()) {
|
|
1191
|
-
const previousSeverity = stats.severity;
|
|
1192
|
-
this.updateSeverity(stats);
|
|
1193
|
-
if (stats.severity !== previousSeverity) {
|
|
1194
|
-
this.emit("severityChange", {
|
|
1195
|
-
component: stats.name,
|
|
1196
|
-
from: previousSeverity,
|
|
1197
|
-
to: stats.severity
|
|
1198
|
-
});
|
|
1199
|
-
}
|
|
1200
|
-
}
|
|
1201
|
-
}
|
|
1202
|
-
/**
|
|
1203
|
-
* Get current thresholds
|
|
1204
|
-
* @returns Current threshold configuration
|
|
1205
|
-
*/
|
|
1206
|
-
getThresholds() {
|
|
1207
|
-
return { ...this.thresholds };
|
|
1208
|
-
}
|
|
1209
|
-
/**
|
|
1210
|
-
* Get session duration in milliseconds
|
|
1211
|
-
* @returns Session duration
|
|
1212
|
-
*/
|
|
1213
|
-
getSessionDuration() {
|
|
1214
|
-
return Date.now() - this.sessionStart;
|
|
1215
|
-
}
|
|
1216
|
-
/**
|
|
1217
|
-
* Get total render count
|
|
1218
|
-
* @returns Total renders across all components
|
|
1219
|
-
*/
|
|
1220
|
-
getTotalRenders() {
|
|
1221
|
-
return this.totalRenders;
|
|
1222
|
-
}
|
|
1223
|
-
/**
|
|
1224
|
-
* Get component count
|
|
1225
|
-
* @returns Number of tracked components
|
|
1226
|
-
*/
|
|
1227
|
-
getComponentCount() {
|
|
1228
|
-
return this.components.size;
|
|
1229
|
-
}
|
|
1230
|
-
/**
|
|
1231
|
-
* Check if FPS is below threshold
|
|
1232
|
-
* @returns true if average FPS is below threshold
|
|
1233
|
-
*/
|
|
1234
|
-
isFpsBelowThreshold() {
|
|
1235
|
-
if (this.fpsSamples.length === 0) return false;
|
|
1236
|
-
const avgFps = this.fpsSamples.reduce((a, b) => a + b, 0) / this.fpsSamples.length;
|
|
1237
|
-
return avgFps < this.thresholds.fps;
|
|
1238
|
-
}
|
|
1239
|
-
/**
|
|
1240
|
-
* Export stats for serialization
|
|
1241
|
-
* @returns Serializable stats object
|
|
1242
|
-
*/
|
|
1243
|
-
export() {
|
|
1244
|
-
return {
|
|
1245
|
-
components: this.getSnapshot(),
|
|
1246
|
-
summary: this.getSummary(),
|
|
1247
|
-
thresholds: this.getThresholds(),
|
|
1248
|
-
sessionDuration: this.getSessionDuration()
|
|
1249
|
-
};
|
|
1250
|
-
}
|
|
1251
|
-
};
|
|
1252
|
-
|
|
1253
|
-
// src/core/chain.ts
|
|
1254
|
-
init_event_emitter();
|
|
1255
|
-
var ChainAnalyzer = class extends EventEmitter {
|
|
1256
|
-
/** Time window size in ms (one frame at 60fps) */
|
|
1257
|
-
windowSize;
|
|
1258
|
-
/** Current render windows being tracked */
|
|
1259
|
-
windows = /* @__PURE__ */ new Map();
|
|
1260
|
-
/** Component parent relationships */
|
|
1261
|
-
parentMap = /* @__PURE__ */ new Map();
|
|
1262
|
-
/** Recently detected chains to avoid duplicates */
|
|
1263
|
-
recentChains = /* @__PURE__ */ new Set();
|
|
1264
|
-
/** Minimum chain depth to report */
|
|
1265
|
-
minChainDepth;
|
|
1266
|
-
/** Maximum time to keep recent chains */
|
|
1267
|
-
recentChainTtl;
|
|
1268
|
-
/**
|
|
1269
|
-
* Create a new ChainAnalyzer
|
|
1270
|
-
* @param options - Configuration options
|
|
1271
|
-
*/
|
|
1272
|
-
constructor(options = {}) {
|
|
1273
|
-
super();
|
|
1274
|
-
this.windowSize = options.windowSize ?? 16;
|
|
1275
|
-
this.minChainDepth = options.minChainDepth ?? 2;
|
|
1276
|
-
this.recentChainTtl = options.recentChainTtl ?? 1e3;
|
|
1277
|
-
}
|
|
1278
|
-
/**
|
|
1279
|
-
* Add a render event for analysis
|
|
1280
|
-
* @param render - Render information
|
|
1281
|
-
* @param parent - Optional parent component name
|
|
1282
|
-
*/
|
|
1283
|
-
addRender(render, parent) {
|
|
1284
|
-
const trackedRender = {
|
|
1285
|
-
...render,
|
|
1286
|
-
...parent !== void 0 ? { parent } : {},
|
|
1287
|
-
contextTriggered: this.isContextTriggered(render)
|
|
1288
|
-
};
|
|
1289
|
-
if (parent) {
|
|
1290
|
-
this.parentMap.set(render.componentName, parent);
|
|
1291
|
-
}
|
|
1292
|
-
const windowKey = this.getWindowKey(render.timestamp);
|
|
1293
|
-
let window2 = this.windows.get(windowKey);
|
|
1294
|
-
if (!window2) {
|
|
1295
|
-
window2 = {
|
|
1296
|
-
renders: [],
|
|
1297
|
-
startTime: render.timestamp
|
|
1298
|
-
};
|
|
1299
|
-
this.windows.set(windowKey, window2);
|
|
1300
|
-
}
|
|
1301
|
-
window2.renders.push(trackedRender);
|
|
1302
|
-
if (window2.renders.length >= this.minChainDepth) {
|
|
1303
|
-
this.analyzeWindow(windowKey);
|
|
1304
|
-
}
|
|
1305
|
-
this.cleanupWindows(render.timestamp);
|
|
1306
|
-
}
|
|
1307
|
-
/**
|
|
1308
|
-
* Set parent relationship for a component
|
|
1309
|
-
* @param child - Child component name
|
|
1310
|
-
* @param parent - Parent component name
|
|
1311
|
-
*/
|
|
1312
|
-
setParent(child, parent) {
|
|
1313
|
-
this.parentMap.set(child, parent);
|
|
1314
|
-
}
|
|
1315
|
-
/**
|
|
1316
|
-
* Get window key for a timestamp
|
|
1317
|
-
* @param timestamp - Timestamp in ms
|
|
1318
|
-
* @returns Window key
|
|
1319
|
-
*/
|
|
1320
|
-
getWindowKey(timestamp) {
|
|
1321
|
-
return Math.floor(timestamp / this.windowSize);
|
|
1322
|
-
}
|
|
1323
|
-
/**
|
|
1324
|
-
* Check if a render was likely triggered by context
|
|
1325
|
-
* @param render - Render information
|
|
1326
|
-
* @returns true if context-triggered
|
|
1327
|
-
*/
|
|
1328
|
-
isContextTriggered(render) {
|
|
1329
|
-
return !render.changedProps?.length && !render.changedState?.length && render.phase === "update";
|
|
1330
|
-
}
|
|
1331
|
-
/**
|
|
1332
|
-
* Analyze a render window for chains
|
|
1333
|
-
* @param windowKey - Window key to analyze
|
|
1334
|
-
*/
|
|
1335
|
-
analyzeWindow(windowKey) {
|
|
1336
|
-
const window2 = this.windows.get(windowKey);
|
|
1337
|
-
if (!window2 || window2.renders.length < this.minChainDepth) {
|
|
1338
|
-
return;
|
|
1339
|
-
}
|
|
1340
|
-
const sortedRenders = [...window2.renders].sort((a, b) => a.timestamp - b.timestamp);
|
|
1341
|
-
const chains = this.buildChains(sortedRenders);
|
|
1342
|
-
for (const chain of chains) {
|
|
1343
|
-
const chainKey = this.getChainKey(chain);
|
|
1344
|
-
if (this.recentChains.has(chainKey)) {
|
|
1345
|
-
continue;
|
|
1346
|
-
}
|
|
1347
|
-
this.recentChains.add(chainKey);
|
|
1348
|
-
setTimeout(() => {
|
|
1349
|
-
this.recentChains.delete(chainKey);
|
|
1350
|
-
}, this.recentChainTtl);
|
|
1351
|
-
this.emit("chain", chain);
|
|
1352
|
-
if (chain.isContextTriggered) {
|
|
1353
|
-
this.emit("contextChain", chain);
|
|
1354
|
-
}
|
|
1355
|
-
}
|
|
1356
|
-
}
|
|
1357
|
-
/**
|
|
1358
|
-
* Build chains from a sorted render sequence
|
|
1359
|
-
* @param renders - Sorted render events
|
|
1360
|
-
* @returns Detected chains
|
|
1361
|
-
*/
|
|
1362
|
-
buildChains(renders) {
|
|
1363
|
-
const chains = [];
|
|
1364
|
-
const visited = /* @__PURE__ */ new Set();
|
|
1365
|
-
const chainComponents = [];
|
|
1366
|
-
for (const render of renders) {
|
|
1367
|
-
if (visited.has(render.componentName)) {
|
|
1368
|
-
continue;
|
|
1369
|
-
}
|
|
1370
|
-
const chain = this.traceChain(render.componentName, renders, visited);
|
|
1371
|
-
if (chain.length >= this.minChainDepth) {
|
|
1372
|
-
chainComponents.push(chain);
|
|
1373
|
-
}
|
|
1374
|
-
}
|
|
1375
|
-
for (const chain of chainComponents) {
|
|
1376
|
-
const chainRenders = renders.filter((r) => chain.includes(r.componentName));
|
|
1377
|
-
const isContextTriggered = chainRenders.some((r) => r.contextTriggered);
|
|
1378
|
-
const rootCause = this.findRootCause(chain, renders);
|
|
1379
|
-
const trigger = this.determineTrigger(rootCause, renders);
|
|
1380
|
-
chains.push({
|
|
1381
|
-
trigger,
|
|
1382
|
-
chain,
|
|
1383
|
-
depth: chain.length,
|
|
1384
|
-
totalRenders: chainRenders.length,
|
|
1385
|
-
rootCause,
|
|
1386
|
-
timestamp: Date.now(),
|
|
1387
|
-
isContextTriggered
|
|
1388
|
-
});
|
|
1389
|
-
}
|
|
1390
|
-
return chains;
|
|
1391
|
-
}
|
|
1392
|
-
/**
|
|
1393
|
-
* Trace a chain starting from a component
|
|
1394
|
-
* @param startComponent - Starting component
|
|
1395
|
-
* @param renders - All renders in window
|
|
1396
|
-
* @param visited - Already visited components
|
|
1397
|
-
* @returns Chain of component names
|
|
1398
|
-
*/
|
|
1399
|
-
traceChain(startComponent, renders, visited) {
|
|
1400
|
-
const chain = [];
|
|
1401
|
-
const queue = [startComponent];
|
|
1402
|
-
while (queue.length > 0) {
|
|
1403
|
-
const current = queue.shift();
|
|
1404
|
-
if (!current || visited.has(current)) {
|
|
1405
|
-
continue;
|
|
1406
|
-
}
|
|
1407
|
-
visited.add(current);
|
|
1408
|
-
chain.push(current);
|
|
1409
|
-
const parent = this.parentMap.get(current);
|
|
1410
|
-
if (parent && renders.some((r) => r.componentName === parent) && !visited.has(parent)) {
|
|
1411
|
-
queue.unshift(parent);
|
|
1412
|
-
}
|
|
1413
|
-
for (const [child, p] of this.parentMap) {
|
|
1414
|
-
if (p === current && renders.some((r) => r.componentName === child) && !visited.has(child)) {
|
|
1415
|
-
queue.push(child);
|
|
1416
|
-
}
|
|
1417
|
-
}
|
|
1418
|
-
}
|
|
1419
|
-
return chain;
|
|
1420
|
-
}
|
|
1421
|
-
/**
|
|
1422
|
-
* Find the root cause component in a chain
|
|
1423
|
-
* @param chain - Component chain
|
|
1424
|
-
* @param renders - All renders
|
|
1425
|
-
* @returns Root cause component name
|
|
1426
|
-
*/
|
|
1427
|
-
findRootCause(chain, renders) {
|
|
1428
|
-
const chainRenders = renders.filter((r) => chain.includes(r.componentName)).sort((a, b) => a.timestamp - b.timestamp);
|
|
1429
|
-
for (const render of chainRenders) {
|
|
1430
|
-
if (render.changedState?.length ?? render.changedProps?.length) {
|
|
1431
|
-
return render.componentName;
|
|
1432
|
-
}
|
|
1433
|
-
}
|
|
1434
|
-
return chain[0] ?? "Unknown";
|
|
1435
|
-
}
|
|
1436
|
-
/**
|
|
1437
|
-
* Determine what triggered a chain
|
|
1438
|
-
* @param rootCause - Root cause component
|
|
1439
|
-
* @param renders - All renders
|
|
1440
|
-
* @returns Trigger description
|
|
1441
|
-
*/
|
|
1442
|
-
determineTrigger(rootCause, renders) {
|
|
1443
|
-
const render = renders.find((r) => r.componentName === rootCause);
|
|
1444
|
-
if (!render) {
|
|
1445
|
-
return `Unknown trigger in ${rootCause}`;
|
|
1446
|
-
}
|
|
1447
|
-
if (render.changedState?.length) {
|
|
1448
|
-
return `setState in ${rootCause}`;
|
|
1449
|
-
}
|
|
1450
|
-
if (render.changedProps?.length) {
|
|
1451
|
-
const props = render.changedProps.slice(0, 3).join(", ");
|
|
1452
|
-
const more = render.changedProps.length > 3 ? "..." : "";
|
|
1453
|
-
return `Props changed (${props}${more}) in ${rootCause}`;
|
|
1454
|
-
}
|
|
1455
|
-
if (render.contextTriggered) {
|
|
1456
|
-
return `Context update affecting ${rootCause}`;
|
|
1457
|
-
}
|
|
1458
|
-
if (render.phase === "mount") {
|
|
1459
|
-
return `Initial mount of ${rootCause}`;
|
|
1460
|
-
}
|
|
1461
|
-
return `Re-render of ${rootCause}`;
|
|
1462
|
-
}
|
|
1463
|
-
/**
|
|
1464
|
-
* Generate a unique key for a chain to detect duplicates
|
|
1465
|
-
* @param chain - Chain info
|
|
1466
|
-
* @returns Unique key
|
|
1467
|
-
*/
|
|
1468
|
-
getChainKey(chain) {
|
|
1469
|
-
return `${chain.rootCause}:${chain.chain.join("->")}`;
|
|
1470
|
-
}
|
|
1471
|
-
/**
|
|
1472
|
-
* Clean up old render windows
|
|
1473
|
-
* @param currentTime - Current timestamp
|
|
1474
|
-
*/
|
|
1475
|
-
cleanupWindows(currentTime) {
|
|
1476
|
-
const cutoff = currentTime - this.windowSize * 10;
|
|
1477
|
-
for (const [key, window2] of this.windows) {
|
|
1478
|
-
if (window2.startTime < cutoff) {
|
|
1479
|
-
this.windows.delete(key);
|
|
1480
|
-
}
|
|
1481
|
-
}
|
|
1482
|
-
}
|
|
1483
|
-
/**
|
|
1484
|
-
* Get the parent of a component
|
|
1485
|
-
* @param componentName - Component name
|
|
1486
|
-
* @returns Parent name or undefined
|
|
1487
|
-
*/
|
|
1488
|
-
getParent(componentName) {
|
|
1489
|
-
return this.parentMap.get(componentName);
|
|
1490
|
-
}
|
|
1491
|
-
/**
|
|
1492
|
-
* Get all known parent relationships
|
|
1493
|
-
* @returns Map of child to parent
|
|
1494
|
-
*/
|
|
1495
|
-
getParentMap() {
|
|
1496
|
-
return new Map(this.parentMap);
|
|
1497
|
-
}
|
|
1498
|
-
/**
|
|
1499
|
-
* Build a full chain for a component (tracing up to root)
|
|
1500
|
-
* @param componentName - Starting component
|
|
1501
|
-
* @returns Chain from root to component
|
|
1502
|
-
*/
|
|
1503
|
-
getComponentChain(componentName) {
|
|
1504
|
-
const chain = [];
|
|
1505
|
-
let current = componentName;
|
|
1506
|
-
while (current) {
|
|
1507
|
-
chain.unshift(current);
|
|
1508
|
-
current = this.parentMap.get(current);
|
|
1509
|
-
if (chain.length > 100) {
|
|
1510
|
-
break;
|
|
1511
|
-
}
|
|
1512
|
-
}
|
|
1513
|
-
return chain;
|
|
1514
|
-
}
|
|
1515
|
-
/**
|
|
1516
|
-
* Clear all tracked data
|
|
1517
|
-
*/
|
|
1518
|
-
reset() {
|
|
1519
|
-
this.windows.clear();
|
|
1520
|
-
this.parentMap.clear();
|
|
1521
|
-
this.recentChains.clear();
|
|
1522
|
-
}
|
|
1523
|
-
/**
|
|
1524
|
-
* Get statistics about current tracking
|
|
1525
|
-
* @returns Tracking statistics
|
|
1526
|
-
*/
|
|
1527
|
-
getStats() {
|
|
1528
|
-
return {
|
|
1529
|
-
windowCount: this.windows.size,
|
|
1530
|
-
parentRelationships: this.parentMap.size,
|
|
1531
|
-
recentChains: this.recentChains.size
|
|
1532
|
-
};
|
|
1533
|
-
}
|
|
1534
|
-
};
|
|
1535
|
-
|
|
1536
|
-
// src/core/fix.ts
|
|
1537
|
-
init_event_emitter();
|
|
1538
|
-
var BUILTIN_RULES = [
|
|
1539
|
-
// React.memo rule
|
|
1540
|
-
{
|
|
1541
|
-
id: "unnecessary-rerenders-memo",
|
|
1542
|
-
name: "Unnecessary Re-renders (memo)",
|
|
1543
|
-
description: "Component re-renders frequently without prop changes",
|
|
1544
|
-
fixType: "React.memo",
|
|
1545
|
-
priority: 1,
|
|
1546
|
-
detect: (stats) => {
|
|
1547
|
-
const unnecessaryRatio = stats.renders > 0 ? stats.unnecessary / stats.renders : 0;
|
|
1548
|
-
return stats.renders >= 10 && unnecessaryRatio >= 0.5 && !stats.propsChanged;
|
|
1549
|
-
},
|
|
1550
|
-
suggest: (stats) => ({
|
|
1551
|
-
severity: stats.severity === "healthy" ? "info" : stats.severity,
|
|
1552
|
-
issue: `Component "${stats.name}" re-renders ${stats.unnecessary} times unnecessarily out of ${stats.renders} total renders`,
|
|
1553
|
-
cause: stats.parent ? `Parent component "${stats.parent}" re-renders and causes cascading updates` : "Parent component re-renders propagate to this component",
|
|
1554
|
-
codeBefore: generateComponentCode(stats.name),
|
|
1555
|
-
codeAfter: generateMemoCode(stats.name),
|
|
1556
|
-
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.",
|
|
1557
|
-
impact: `Could prevent ~${stats.unnecessary} unnecessary renders (${Math.round(stats.unnecessary / stats.renders * 100)}% reduction)`
|
|
1558
|
-
})
|
|
1559
|
-
},
|
|
1560
|
-
// useMemo rule for expensive computations
|
|
1561
|
-
{
|
|
1562
|
-
id: "expensive-computation-memo",
|
|
1563
|
-
name: "Expensive Computation",
|
|
1564
|
-
description: "Component has high render times suggesting expensive calculations",
|
|
1565
|
-
fixType: "useMemo",
|
|
1566
|
-
priority: 2,
|
|
1567
|
-
detect: (stats) => {
|
|
1568
|
-
return stats.avgRenderTime > 16 && stats.renders >= 5;
|
|
1569
|
-
},
|
|
1570
|
-
suggest: (stats) => ({
|
|
1571
|
-
severity: stats.avgRenderTime > 50 ? "critical" : "warning",
|
|
1572
|
-
issue: `Component "${stats.name}" has slow renders averaging ${stats.avgRenderTime.toFixed(1)}ms`,
|
|
1573
|
-
cause: "Expensive calculations or data transformations are being performed on every render",
|
|
1574
|
-
codeBefore: generateExpensiveCode(stats.name),
|
|
1575
|
-
codeAfter: generateUseMemoCode(stats.name),
|
|
1576
|
-
explanation: "useMemo caches the result of expensive computations between renders. It only recalculates when dependencies change, improving performance.",
|
|
1577
|
-
impact: `Could reduce render time from ${stats.avgRenderTime.toFixed(1)}ms to <1ms for cached renders`
|
|
1578
|
-
})
|
|
1579
|
-
},
|
|
1580
|
-
// useCallback rule for function props
|
|
1581
|
-
{
|
|
1582
|
-
id: "function-prop-stability",
|
|
1583
|
-
name: "Unstable Function Props",
|
|
1584
|
-
description: "Component passes inline functions as props causing child re-renders",
|
|
1585
|
-
fixType: "useCallback",
|
|
1586
|
-
priority: 3,
|
|
1587
|
-
detect: (stats) => {
|
|
1588
|
-
return stats.renders >= 15 && stats.propsChanged;
|
|
1589
|
-
},
|
|
1590
|
-
suggest: (stats) => ({
|
|
1591
|
-
severity: stats.severity === "healthy" ? "info" : stats.severity,
|
|
1592
|
-
issue: `Component "${stats.name}" may be passing unstable function references as props`,
|
|
1593
|
-
cause: "Inline arrow functions are recreated on every render, causing children with React.memo to re-render",
|
|
1594
|
-
codeBefore: generateInlineFunctionCode(stats.name),
|
|
1595
|
-
codeAfter: generateUseCallbackCode(stats.name),
|
|
1596
|
-
explanation: "useCallback returns a memoized callback that only changes when dependencies change. This stabilizes function references passed to child components.",
|
|
1597
|
-
impact: "Stabilized function props allow memoized children to skip re-renders"
|
|
1598
|
-
})
|
|
1599
|
-
},
|
|
1600
|
-
// Context split rule
|
|
1601
|
-
{
|
|
1602
|
-
id: "context-over-subscription",
|
|
1603
|
-
name: "Context Over-subscription",
|
|
1604
|
-
description: "Context updates trigger unnecessary re-renders in unrelated components",
|
|
1605
|
-
fixType: "context-split",
|
|
1606
|
-
priority: 4,
|
|
1607
|
-
detect: (stats) => {
|
|
1608
|
-
return stats.renders >= 20 && stats.unnecessary > stats.renders * 0.7 && !stats.propsChanged && !stats.stateChanged;
|
|
1609
|
-
},
|
|
1610
|
-
suggest: (stats) => ({
|
|
1611
|
-
severity: stats.severity === "healthy" ? "warning" : stats.severity,
|
|
1612
|
-
issue: `Component "${stats.name}" re-renders due to context updates it doesn't use`,
|
|
1613
|
-
cause: "A context this component subscribes to contains unrelated state that changes frequently",
|
|
1614
|
-
codeBefore: generateContextCode("AppContext"),
|
|
1615
|
-
codeAfter: generateSplitContextCode(),
|
|
1616
|
-
explanation: "Splitting large contexts into smaller, focused contexts prevents unrelated updates from triggering re-renders in components that only need part of the context.",
|
|
1617
|
-
impact: `Could eliminate ${stats.unnecessary} unnecessary renders caused by unrelated context updates`
|
|
1618
|
-
})
|
|
1619
|
-
},
|
|
1620
|
-
// State colocation rule
|
|
1621
|
-
{
|
|
1622
|
-
id: "state-too-high",
|
|
1623
|
-
name: "State Location",
|
|
1624
|
-
description: "State is managed too high in the component tree",
|
|
1625
|
-
fixType: "state-colocation",
|
|
1626
|
-
priority: 5,
|
|
1627
|
-
detect: (stats) => {
|
|
1628
|
-
const chainDepth = stats.chain.length;
|
|
1629
|
-
return stats.renders >= 30 && chainDepth >= 3 && stats.stateChanged;
|
|
1630
|
-
},
|
|
1631
|
-
suggest: (stats) => ({
|
|
1632
|
-
severity: stats.severity === "healthy" ? "warning" : stats.severity,
|
|
1633
|
-
issue: `State changes in "${stats.name}" trigger a cascade of ${stats.chain.length} component re-renders`,
|
|
1634
|
-
cause: `State that only affects a subtree is managed at the "${stats.name}" level, causing unnecessary updates`,
|
|
1635
|
-
codeBefore: generateStateHighCode(stats.name),
|
|
1636
|
-
codeAfter: generateStateColocationCode(stats.name),
|
|
1637
|
-
explanation: "Moving state closer to where it's used (colocation) reduces the re-render scope. Only components that actually need the state will update.",
|
|
1638
|
-
impact: `Could reduce cascade depth from ${stats.chain.length} to 1-2 components`
|
|
1639
|
-
})
|
|
1640
|
-
},
|
|
1641
|
-
// Component extraction rule
|
|
1642
|
-
{
|
|
1643
|
-
id: "extract-heavy-child",
|
|
1644
|
-
name: "Component Extraction",
|
|
1645
|
-
description: "Part of the component updates independently and should be extracted",
|
|
1646
|
-
fixType: "component-extraction",
|
|
1647
|
-
priority: 6,
|
|
1648
|
-
detect: (stats) => {
|
|
1649
|
-
return stats.renders >= 50 && stats.avgRenderTime > 5;
|
|
1650
|
-
},
|
|
1651
|
-
suggest: (stats) => ({
|
|
1652
|
-
severity: stats.severity === "healthy" ? "info" : stats.severity,
|
|
1653
|
-
issue: `Component "${stats.name}" renders frequently (${stats.renders} times) with mixed concerns`,
|
|
1654
|
-
cause: "The component contains parts that update at different rates, causing full re-renders",
|
|
1655
|
-
codeBefore: generateMonolithCode(stats.name),
|
|
1656
|
-
codeAfter: generateExtractedCode(stats.name),
|
|
1657
|
-
explanation: "Extracting frequently-updating parts into separate components allows React to optimize renders for each part independently.",
|
|
1658
|
-
impact: "Isolates render cycles so fast-updating parts don't affect slow-updating parts"
|
|
1659
|
-
})
|
|
1660
|
-
}
|
|
1661
|
-
];
|
|
1662
|
-
function generateComponentCode(name, type) {
|
|
1663
|
-
return `function ${name}({ prop1, prop2 }) {
|
|
1664
|
-
return (
|
|
1665
|
-
<div>
|
|
1666
|
-
{/* component content */}
|
|
1667
|
-
</div>
|
|
1668
|
-
);
|
|
1669
|
-
}
|
|
1670
|
-
|
|
1671
|
-
export default ${name};`;
|
|
1672
|
-
}
|
|
1673
|
-
function generateMemoCode(name) {
|
|
1674
|
-
return `import { memo } from 'react';
|
|
1675
|
-
|
|
1676
|
-
const ${name} = memo(function ${name}({ prop1, prop2 }) {
|
|
1677
|
-
return (
|
|
1678
|
-
<div>
|
|
1679
|
-
{/* component content */}
|
|
1680
|
-
</div>
|
|
1681
|
-
);
|
|
1682
|
-
});
|
|
1683
|
-
|
|
1684
|
-
export default ${name};`;
|
|
1685
|
-
}
|
|
1686
|
-
function generateExpensiveCode(name) {
|
|
1687
|
-
return `function ${name}({ items }) {
|
|
1688
|
-
// Expensive computation on every render
|
|
1689
|
-
const processed = items
|
|
1690
|
-
.filter(item => item.active)
|
|
1691
|
-
.map(item => transform(item))
|
|
1692
|
-
.sort((a, b) => a.value - b.value);
|
|
1693
|
-
|
|
1694
|
-
return <List items={processed} />;
|
|
1695
|
-
}`;
|
|
1696
|
-
}
|
|
1697
|
-
function generateUseMemoCode(name) {
|
|
1698
|
-
return `import { useMemo } from 'react';
|
|
1699
|
-
|
|
1700
|
-
function ${name}({ items }) {
|
|
1701
|
-
// Computation cached until items change
|
|
1702
|
-
const processed = useMemo(() => {
|
|
1703
|
-
return items
|
|
1704
|
-
.filter(item => item.active)
|
|
1705
|
-
.map(item => transform(item))
|
|
1706
|
-
.sort((a, b) => a.value - b.value);
|
|
1707
|
-
}, [items]);
|
|
1708
|
-
|
|
1709
|
-
return <List items={processed} />;
|
|
1710
|
-
}`;
|
|
1711
|
-
}
|
|
1712
|
-
function generateInlineFunctionCode(name) {
|
|
1713
|
-
return `function ${name}({ data }) {
|
|
1714
|
-
return (
|
|
1715
|
-
<ChildComponent
|
|
1716
|
-
onAction={(id) => handleAction(id)} // New function every render!
|
|
1717
|
-
onClick={() => setOpen(true)} // New function every render!
|
|
1718
|
-
/>
|
|
1719
|
-
);
|
|
1720
|
-
}`;
|
|
1721
|
-
}
|
|
1722
|
-
function generateUseCallbackCode(name) {
|
|
1723
|
-
return `import { useCallback } from 'react';
|
|
1724
|
-
|
|
1725
|
-
function ${name}({ data }) {
|
|
1726
|
-
const handleAction = useCallback((id) => {
|
|
1727
|
-
// Handle action
|
|
1728
|
-
}, []); // Empty deps if no external dependencies
|
|
1729
|
-
|
|
1730
|
-
const handleClick = useCallback(() => {
|
|
1731
|
-
setOpen(true);
|
|
1732
|
-
}, []);
|
|
1733
|
-
|
|
1734
|
-
return (
|
|
1735
|
-
<ChildComponent
|
|
1736
|
-
onAction={handleAction} // Stable reference
|
|
1737
|
-
onClick={handleClick} // Stable reference
|
|
1738
|
-
/>
|
|
1739
|
-
);
|
|
1740
|
-
}`;
|
|
1741
|
-
}
|
|
1742
|
-
function generateContextCode(contextName) {
|
|
1743
|
-
return `// Single large context with mixed concerns
|
|
1744
|
-
const ${contextName} = createContext({
|
|
1745
|
-
user: null,
|
|
1746
|
-
theme: 'light',
|
|
1747
|
-
notifications: [],
|
|
1748
|
-
settings: {},
|
|
1749
|
-
cart: [],
|
|
1750
|
-
// ... many more values
|
|
1751
|
-
});
|
|
1752
|
-
|
|
1753
|
-
// Every consumer re-renders when ANY value changes
|
|
1754
|
-
function Component() {
|
|
1755
|
-
const { theme } = useContext(${contextName});
|
|
1756
|
-
// Re-renders when user, notifications, cart change too!
|
|
1757
|
-
return <div className={theme}>...</div>;
|
|
1758
|
-
}`;
|
|
1759
|
-
}
|
|
1760
|
-
function generateSplitContextCode() {
|
|
1761
|
-
return `// Split into focused contexts
|
|
1762
|
-
const UserContext = createContext(null);
|
|
1763
|
-
const ThemeContext = createContext('light');
|
|
1764
|
-
const NotificationContext = createContext([]);
|
|
1765
|
-
|
|
1766
|
-
// Only re-renders when theme changes
|
|
1767
|
-
function Component() {
|
|
1768
|
-
const theme = useContext(ThemeContext);
|
|
1769
|
-
return <div className={theme}>...</div>;
|
|
1770
|
-
}
|
|
1771
|
-
|
|
1772
|
-
// Provider composition
|
|
1773
|
-
function App() {
|
|
1774
|
-
return (
|
|
1775
|
-
<UserContext.Provider value={user}>
|
|
1776
|
-
<ThemeContext.Provider value={theme}>
|
|
1777
|
-
<NotificationContext.Provider value={notifications}>
|
|
1778
|
-
<MainContent />
|
|
1779
|
-
</NotificationContext.Provider>
|
|
1780
|
-
</ThemeContext.Provider>
|
|
1781
|
-
</UserContext.Provider>
|
|
1782
|
-
);
|
|
1783
|
-
}`;
|
|
1784
|
-
}
|
|
1785
|
-
function generateStateHighCode(name) {
|
|
1786
|
-
return `function ${name}() {
|
|
1787
|
-
// State managed at top level
|
|
1788
|
-
const [search, setSearch] = useState('');
|
|
1789
|
-
const [filter, setFilter] = useState('all');
|
|
1790
|
-
|
|
1791
|
-
return (
|
|
1792
|
-
<div>
|
|
1793
|
-
<Header />
|
|
1794
|
-
<Sidebar />
|
|
1795
|
-
{/* Only SearchBox needs search state */}
|
|
1796
|
-
<SearchBox value={search} onChange={setSearch} />
|
|
1797
|
-
<MainContent filter={filter} />
|
|
1798
|
-
<Footer />
|
|
1799
|
-
</div>
|
|
1800
|
-
);
|
|
1801
|
-
}`;
|
|
1802
|
-
}
|
|
1803
|
-
function generateStateColocationCode(name) {
|
|
1804
|
-
return `function ${name}() {
|
|
1805
|
-
// Only filter needed at this level
|
|
1806
|
-
const [filter, setFilter] = useState('all');
|
|
1807
|
-
|
|
1808
|
-
return (
|
|
1809
|
-
<div>
|
|
1810
|
-
<Header />
|
|
1811
|
-
<Sidebar />
|
|
1812
|
-
{/* SearchBox manages its own state */}
|
|
1813
|
-
<SearchBox />
|
|
1814
|
-
<MainContent filter={filter} />
|
|
1815
|
-
<Footer />
|
|
1816
|
-
</div>
|
|
1817
|
-
);
|
|
1818
|
-
}
|
|
1819
|
-
|
|
1820
|
-
// State colocated with component that uses it
|
|
1821
|
-
function SearchBox() {
|
|
1822
|
-
const [search, setSearch] = useState('');
|
|
1823
|
-
return <input value={search} onChange={e => setSearch(e.target.value)} />;
|
|
1824
|
-
}`;
|
|
1825
|
-
}
|
|
1826
|
-
function generateMonolithCode(name) {
|
|
1827
|
-
return `function ${name}() {
|
|
1828
|
-
const [counter, setCounter] = useState(0);
|
|
1829
|
-
const [data, setData] = useState(null);
|
|
1830
|
-
|
|
1831
|
-
// Counter updates 10x/second
|
|
1832
|
-
useEffect(() => {
|
|
1833
|
-
const id = setInterval(() => setCounter(c => c + 1), 100);
|
|
1834
|
-
return () => clearInterval(id);
|
|
1835
|
-
}, []);
|
|
1836
|
-
|
|
1837
|
-
return (
|
|
1838
|
-
<div>
|
|
1839
|
-
<span>Count: {counter}</span> {/* Updates frequently */}
|
|
1840
|
-
<ExpensiveChart data={data} /> {/* Re-renders unnecessarily! */}
|
|
1841
|
-
<DataTable data={data} /> {/* Re-renders unnecessarily! */}
|
|
1842
|
-
</div>
|
|
1843
|
-
);
|
|
1844
|
-
}`;
|
|
1845
|
-
}
|
|
1846
|
-
function generateExtractedCode(name) {
|
|
1847
|
-
return `function ${name}() {
|
|
1848
|
-
const [data, setData] = useState(null);
|
|
1849
|
-
|
|
1850
|
-
return (
|
|
1851
|
-
<div>
|
|
1852
|
-
<LiveCounter /> {/* Isolated updates */}
|
|
1853
|
-
<ExpensiveChart data={data} /> {/* Only updates when data changes */}
|
|
1854
|
-
<DataTable data={data} /> {/* Only updates when data changes */}
|
|
1855
|
-
</div>
|
|
1856
|
-
);
|
|
1857
|
-
}
|
|
1858
|
-
|
|
1859
|
-
// Extracted component with isolated state
|
|
1860
|
-
function LiveCounter() {
|
|
1861
|
-
const [counter, setCounter] = useState(0);
|
|
1862
|
-
|
|
1863
|
-
useEffect(() => {
|
|
1864
|
-
const id = setInterval(() => setCounter(c => c + 1), 100);
|
|
1865
|
-
return () => clearInterval(id);
|
|
1866
|
-
}, []);
|
|
1867
|
-
|
|
1868
|
-
return <span>Count: {counter}</span>;
|
|
1869
|
-
}`;
|
|
1870
|
-
}
|
|
1871
|
-
var FixSuggester = class extends EventEmitter {
|
|
1872
|
-
/** Active rules */
|
|
1873
|
-
rules;
|
|
1874
|
-
/** Generated suggestions cache */
|
|
1875
|
-
suggestions = /* @__PURE__ */ new Map();
|
|
1876
|
-
/** Rule configuration */
|
|
1877
|
-
ruleConfig = /* @__PURE__ */ new Map();
|
|
1878
|
-
/**
|
|
1879
|
-
* Create a new FixSuggester
|
|
1880
|
-
* @param options - Configuration options
|
|
1881
|
-
*/
|
|
1882
|
-
constructor(options = {}) {
|
|
1883
|
-
super();
|
|
1884
|
-
this.rules = [...BUILTIN_RULES];
|
|
1885
|
-
if (options.rules) {
|
|
1886
|
-
for (const [ruleId, setting] of Object.entries(options.rules)) {
|
|
1887
|
-
this.ruleConfig.set(ruleId, setting);
|
|
1888
|
-
}
|
|
1889
|
-
}
|
|
1890
|
-
}
|
|
1891
|
-
/**
|
|
1892
|
-
* Analyze a component and generate fix suggestions
|
|
1893
|
-
* @param stats - Component statistics
|
|
1894
|
-
* @returns Array of fix suggestions
|
|
1895
|
-
*/
|
|
1896
|
-
analyze(stats) {
|
|
1897
|
-
const suggestions = [];
|
|
1898
|
-
for (const rule of this.rules) {
|
|
1899
|
-
const config = this.ruleConfig.get(rule.id);
|
|
1900
|
-
if (config === "off") {
|
|
1901
|
-
continue;
|
|
1902
|
-
}
|
|
1903
|
-
if (!rule.detect(stats)) {
|
|
1904
|
-
continue;
|
|
1905
|
-
}
|
|
1906
|
-
const partialSuggestion = rule.suggest(stats);
|
|
1907
|
-
const suggestion = {
|
|
1908
|
-
componentName: stats.name,
|
|
1909
|
-
fix: rule.fixType,
|
|
1910
|
-
...partialSuggestion
|
|
1911
|
-
};
|
|
1912
|
-
if (config === "warn") {
|
|
1913
|
-
suggestion.severity = "warning";
|
|
1914
|
-
} else if (config === "error") {
|
|
1915
|
-
suggestion.severity = "critical";
|
|
1916
|
-
}
|
|
1917
|
-
suggestions.push(suggestion);
|
|
1918
|
-
this.emit("suggestion", suggestion);
|
|
1919
|
-
}
|
|
1920
|
-
suggestions.sort((a, b) => {
|
|
1921
|
-
const severityOrder = { critical: 0, warning: 1, info: 2 };
|
|
1922
|
-
const severityDiff = severityOrder[a.severity] - severityOrder[b.severity];
|
|
1923
|
-
if (severityDiff !== 0) return severityDiff;
|
|
1924
|
-
const ruleA = this.rules.find((r) => r.fixType === a.fix);
|
|
1925
|
-
const ruleB = this.rules.find((r) => r.fixType === b.fix);
|
|
1926
|
-
return (ruleA?.priority ?? 99) - (ruleB?.priority ?? 99);
|
|
1927
|
-
});
|
|
1928
|
-
this.suggestions.set(stats.name, suggestions);
|
|
1929
|
-
return suggestions;
|
|
1930
|
-
}
|
|
1931
|
-
/**
|
|
1932
|
-
* Get cached suggestions for a component
|
|
1933
|
-
* @param componentName - Component name
|
|
1934
|
-
* @returns Cached suggestions or empty array
|
|
1935
|
-
*/
|
|
1936
|
-
getSuggestions(componentName) {
|
|
1937
|
-
return this.suggestions.get(componentName) ?? [];
|
|
1938
|
-
}
|
|
1939
|
-
/**
|
|
1940
|
-
* Get all cached suggestions
|
|
1941
|
-
* @returns All suggestions
|
|
1942
|
-
*/
|
|
1943
|
-
getAllSuggestions() {
|
|
1944
|
-
return Array.from(this.suggestions.values()).flat();
|
|
1945
|
-
}
|
|
1946
|
-
/**
|
|
1947
|
-
* Get suggestions by severity
|
|
1948
|
-
* @param severity - Severity level
|
|
1949
|
-
* @returns Matching suggestions
|
|
1950
|
-
*/
|
|
1951
|
-
getSuggestionsBySeverity(severity) {
|
|
1952
|
-
return this.getAllSuggestions().filter((s) => s.severity === severity);
|
|
1953
|
-
}
|
|
1954
|
-
/**
|
|
1955
|
-
* Get suggestions by fix type
|
|
1956
|
-
* @param fixType - Fix type
|
|
1957
|
-
* @returns Matching suggestions
|
|
1958
|
-
*/
|
|
1959
|
-
getSuggestionsByType(fixType) {
|
|
1960
|
-
return this.getAllSuggestions().filter((s) => s.fix === fixType);
|
|
1961
|
-
}
|
|
1962
|
-
/**
|
|
1963
|
-
* Clear cached suggestions
|
|
1964
|
-
* @param componentName - Optional component to clear (clears all if not specified)
|
|
1965
|
-
*/
|
|
1966
|
-
clearSuggestions(componentName) {
|
|
1967
|
-
if (componentName) {
|
|
1968
|
-
this.suggestions.delete(componentName);
|
|
1969
|
-
} else {
|
|
1970
|
-
this.suggestions.clear();
|
|
1971
|
-
}
|
|
1972
|
-
}
|
|
1973
|
-
/**
|
|
1974
|
-
* Configure a rule
|
|
1975
|
-
* @param ruleId - Rule identifier
|
|
1976
|
-
* @param setting - Rule setting
|
|
1977
|
-
*/
|
|
1978
|
-
configureRule(ruleId, setting) {
|
|
1979
|
-
this.ruleConfig.set(ruleId, setting);
|
|
1980
|
-
}
|
|
1981
|
-
/**
|
|
1982
|
-
* Get available rule IDs
|
|
1983
|
-
* @returns Array of rule IDs
|
|
1984
|
-
*/
|
|
1985
|
-
getRuleIds() {
|
|
1986
|
-
return this.rules.map((r) => r.id);
|
|
1987
|
-
}
|
|
1988
|
-
/**
|
|
1989
|
-
* Get rule information
|
|
1990
|
-
* @param ruleId - Rule identifier
|
|
1991
|
-
* @returns Rule info or undefined
|
|
1992
|
-
*/
|
|
1993
|
-
getRule(ruleId) {
|
|
1994
|
-
const rule = this.rules.find((r) => r.id === ruleId);
|
|
1995
|
-
if (!rule) return void 0;
|
|
1996
|
-
return {
|
|
1997
|
-
id: rule.id,
|
|
1998
|
-
name: rule.name,
|
|
1999
|
-
description: rule.description,
|
|
2000
|
-
fixType: rule.fixType
|
|
2001
|
-
};
|
|
2002
|
-
}
|
|
2003
|
-
};
|
|
2004
|
-
|
|
2005
|
-
// src/core/scanner.ts
|
|
2006
|
-
var DEFAULT_CONFIG = {
|
|
2007
|
-
trackUnnecessary: true,
|
|
2008
|
-
fpsThreshold: 30,
|
|
2009
|
-
highlightRenders: true,
|
|
2010
|
-
animationSpeed: "fast"
|
|
2011
|
-
};
|
|
2012
|
-
var DEFAULT_THRESHOLDS2 = {
|
|
2013
|
-
critical: 50,
|
|
2014
|
-
warning: 20,
|
|
2015
|
-
fps: 30
|
|
2016
|
-
};
|
|
2017
|
-
var Scanner = class extends EventEmitter {
|
|
2018
|
-
/** Statistics collector */
|
|
2019
|
-
stats;
|
|
2020
|
-
/** Chain analyzer */
|
|
2021
|
-
chainAnalyzer;
|
|
2022
|
-
/** Fix suggester */
|
|
2023
|
-
fixSuggester;
|
|
2024
|
-
/** Scanner configuration */
|
|
2025
|
-
config;
|
|
2026
|
-
/** Whether scanner is currently running */
|
|
2027
|
-
running = false;
|
|
2028
|
-
/** Last recorded FPS */
|
|
2029
|
-
lastFps = 60;
|
|
2030
|
-
/** FPS tracking */
|
|
2031
|
-
frameCount = 0;
|
|
2032
|
-
lastFpsUpdate = 0;
|
|
2033
|
-
fpsInterval = null;
|
|
2034
|
-
/** Batch processing */
|
|
2035
|
-
renderBatch = [];
|
|
2036
|
-
batchTimeout = null;
|
|
2037
|
-
batchSize = 10;
|
|
2038
|
-
batchDelay = 100;
|
|
2039
|
-
/**
|
|
2040
|
-
* Create a new Scanner instance
|
|
2041
|
-
* @param options - Configuration options
|
|
2042
|
-
*/
|
|
2043
|
-
constructor(options = {}) {
|
|
2044
|
-
super();
|
|
2045
|
-
this.config = { ...DEFAULT_CONFIG, ...options.config };
|
|
2046
|
-
const thresholds = { ...DEFAULT_THRESHOLDS2, ...options.thresholds };
|
|
2047
|
-
this.stats = new StatsCollector(thresholds);
|
|
2048
|
-
this.chainAnalyzer = new ChainAnalyzer();
|
|
2049
|
-
this.fixSuggester = new FixSuggester();
|
|
2050
|
-
this.setupEventForwarding();
|
|
2051
|
-
}
|
|
2052
|
-
/**
|
|
2053
|
-
* Set up event forwarding from sub-modules
|
|
2054
|
-
*/
|
|
2055
|
-
setupEventForwarding() {
|
|
2056
|
-
this.stats.on("update", (stats) => {
|
|
2057
|
-
this.emit("stats", stats);
|
|
2058
|
-
});
|
|
2059
|
-
this.stats.on("severityChange", (change) => {
|
|
2060
|
-
this.emit("severityChange", change);
|
|
2061
|
-
const stats = this.stats.getComponentStats(change.component);
|
|
2062
|
-
if (stats && (change.to === "critical" || change.to === "warning")) {
|
|
2063
|
-
const suggestions = this.fixSuggester.analyze(stats);
|
|
2064
|
-
for (const suggestion of suggestions) {
|
|
2065
|
-
this.emit("fix", suggestion);
|
|
2066
|
-
}
|
|
2067
|
-
}
|
|
2068
|
-
});
|
|
2069
|
-
this.chainAnalyzer.on("chain", (chain) => {
|
|
2070
|
-
this.emit("chain", chain);
|
|
2071
|
-
for (const componentName of chain.chain) {
|
|
2072
|
-
this.stats.setComponentChain(componentName, chain.chain);
|
|
2073
|
-
}
|
|
2074
|
-
});
|
|
2075
|
-
}
|
|
2076
|
-
/**
|
|
2077
|
-
* Start the scanner
|
|
2078
|
-
*/
|
|
2079
|
-
start() {
|
|
2080
|
-
if (this.running) return;
|
|
2081
|
-
this.running = true;
|
|
2082
|
-
this.lastFpsUpdate = Date.now();
|
|
2083
|
-
this.frameCount = 0;
|
|
2084
|
-
this.startFpsMonitoring();
|
|
2085
|
-
this.emit("start", void 0);
|
|
2086
|
-
}
|
|
2087
|
-
/**
|
|
2088
|
-
* Stop the scanner
|
|
2089
|
-
*/
|
|
2090
|
-
stop() {
|
|
2091
|
-
if (!this.running) return;
|
|
2092
|
-
this.running = false;
|
|
2093
|
-
this.stopFpsMonitoring();
|
|
2094
|
-
this.flushBatch();
|
|
2095
|
-
this.emit("stop", void 0);
|
|
2096
|
-
}
|
|
2097
|
-
/**
|
|
2098
|
-
* Reset the scanner, clearing all data
|
|
2099
|
-
*/
|
|
2100
|
-
reset() {
|
|
2101
|
-
this.stop();
|
|
2102
|
-
this.stats.reset();
|
|
2103
|
-
this.chainAnalyzer.reset();
|
|
2104
|
-
this.fixSuggester.clearSuggestions();
|
|
2105
|
-
this.renderBatch = [];
|
|
2106
|
-
this.emit("reset", void 0);
|
|
2107
|
-
}
|
|
2108
|
-
/**
|
|
2109
|
-
* Process a render event
|
|
2110
|
-
* @param render - Render information
|
|
2111
|
-
* @param parent - Optional parent component name
|
|
2112
|
-
*/
|
|
2113
|
-
addRender(render, parent) {
|
|
2114
|
-
if (!this.running) return;
|
|
2115
|
-
this.renderBatch.push(render);
|
|
2116
|
-
this.stats.addRender(render);
|
|
2117
|
-
this.chainAnalyzer.addRender(render, parent);
|
|
2118
|
-
this.emit("render", render);
|
|
2119
|
-
this.frameCount++;
|
|
2120
|
-
this.scheduleBatchProcessing();
|
|
2121
|
-
}
|
|
2122
|
-
/**
|
|
2123
|
-
* Record a frame for FPS calculation
|
|
2124
|
-
*/
|
|
2125
|
-
recordFrame() {
|
|
2126
|
-
this.frameCount++;
|
|
2127
|
-
}
|
|
2128
|
-
/**
|
|
2129
|
-
* Schedule batch processing
|
|
2130
|
-
*/
|
|
2131
|
-
scheduleBatchProcessing() {
|
|
2132
|
-
if (this.batchTimeout) return;
|
|
2133
|
-
if (this.renderBatch.length >= this.batchSize) {
|
|
2134
|
-
this.flushBatch();
|
|
2135
|
-
} else {
|
|
2136
|
-
this.batchTimeout = setTimeout(() => {
|
|
2137
|
-
this.flushBatch();
|
|
2138
|
-
}, this.batchDelay);
|
|
2139
|
-
}
|
|
2140
|
-
}
|
|
2141
|
-
/**
|
|
2142
|
-
* Flush the render batch
|
|
2143
|
-
*/
|
|
2144
|
-
flushBatch() {
|
|
2145
|
-
if (this.batchTimeout) {
|
|
2146
|
-
clearTimeout(this.batchTimeout);
|
|
2147
|
-
this.batchTimeout = null;
|
|
2148
|
-
}
|
|
2149
|
-
if (this.renderBatch.length === 0) return;
|
|
2150
|
-
this.processBatch(this.renderBatch);
|
|
2151
|
-
this.renderBatch = [];
|
|
2152
|
-
}
|
|
2153
|
-
/**
|
|
2154
|
-
* Process a batch of renders for patterns
|
|
2155
|
-
* @param batch - Render batch
|
|
2156
|
-
*/
|
|
2157
|
-
processBatch(batch) {
|
|
2158
|
-
const byComponent = /* @__PURE__ */ new Map();
|
|
2159
|
-
for (const render of batch) {
|
|
2160
|
-
const existing = byComponent.get(render.componentName) ?? [];
|
|
2161
|
-
existing.push(render);
|
|
2162
|
-
byComponent.set(render.componentName, existing);
|
|
2163
|
-
}
|
|
2164
|
-
for (const [componentName, renders] of byComponent) {
|
|
2165
|
-
if (renders.length >= 3) {
|
|
2166
|
-
const stats = this.stats.getComponentStats(componentName);
|
|
2167
|
-
if (stats) {
|
|
2168
|
-
const suggestions = this.fixSuggester.analyze(stats);
|
|
2169
|
-
for (const suggestion of suggestions) {
|
|
2170
|
-
this.emit("fix", suggestion);
|
|
2171
|
-
}
|
|
2172
|
-
}
|
|
2173
|
-
}
|
|
2174
|
-
}
|
|
2175
|
-
}
|
|
2176
|
-
/**
|
|
2177
|
-
* Start FPS monitoring
|
|
2178
|
-
*/
|
|
2179
|
-
startFpsMonitoring() {
|
|
2180
|
-
this.fpsInterval = setInterval(() => {
|
|
2181
|
-
const now = Date.now();
|
|
2182
|
-
const elapsed = now - this.lastFpsUpdate;
|
|
2183
|
-
if (elapsed > 0) {
|
|
2184
|
-
this.lastFps = Math.round(this.frameCount * 1e3 / elapsed);
|
|
2185
|
-
this.stats.addFpsSample(this.lastFps);
|
|
2186
|
-
if (this.lastFps < this.config.fpsThreshold) {
|
|
2187
|
-
this.emit("fps-drop", this.lastFps);
|
|
2188
|
-
}
|
|
2189
|
-
}
|
|
2190
|
-
this.frameCount = 0;
|
|
2191
|
-
this.lastFpsUpdate = now;
|
|
2192
|
-
}, 1e3);
|
|
2193
|
-
}
|
|
2194
|
-
/**
|
|
2195
|
-
* Stop FPS monitoring
|
|
2196
|
-
*/
|
|
2197
|
-
stopFpsMonitoring() {
|
|
2198
|
-
if (this.fpsInterval) {
|
|
2199
|
-
clearInterval(this.fpsInterval);
|
|
2200
|
-
this.fpsInterval = null;
|
|
2201
|
-
}
|
|
2202
|
-
}
|
|
2203
|
-
/**
|
|
2204
|
-
* Get current FPS
|
|
2205
|
-
* @returns Current FPS value
|
|
2206
|
-
*/
|
|
2207
|
-
getFps() {
|
|
2208
|
-
return this.lastFps;
|
|
2209
|
-
}
|
|
2210
|
-
/**
|
|
2211
|
-
* Check if scanner is running
|
|
2212
|
-
* @returns true if running
|
|
2213
|
-
*/
|
|
2214
|
-
isRunning() {
|
|
2215
|
-
return this.running;
|
|
2216
|
-
}
|
|
2217
|
-
/**
|
|
2218
|
-
* Get scanner configuration
|
|
2219
|
-
* @returns Current configuration
|
|
2220
|
-
*/
|
|
2221
|
-
getConfig() {
|
|
2222
|
-
return { ...this.config };
|
|
2223
|
-
}
|
|
2224
|
-
/**
|
|
2225
|
-
* Update scanner configuration
|
|
2226
|
-
* @param config - Partial configuration to update
|
|
2227
|
-
*/
|
|
2228
|
-
configure(config) {
|
|
2229
|
-
this.config = { ...this.config, ...config };
|
|
2230
|
-
}
|
|
2231
|
-
/**
|
|
2232
|
-
* Update threshold configuration
|
|
2233
|
-
* @param thresholds - New thresholds
|
|
2234
|
-
*/
|
|
2235
|
-
setThresholds(thresholds) {
|
|
2236
|
-
this.stats.setThresholds(thresholds);
|
|
2237
|
-
}
|
|
2238
|
-
/**
|
|
2239
|
-
* Get current thresholds
|
|
2240
|
-
* @returns Current threshold configuration
|
|
2241
|
-
*/
|
|
2242
|
-
getThresholds() {
|
|
2243
|
-
return this.stats.getThresholds();
|
|
2244
|
-
}
|
|
2245
|
-
/**
|
|
2246
|
-
* Get component statistics
|
|
2247
|
-
* @param name - Component name (optional, returns all if not specified)
|
|
2248
|
-
* @returns Component stats
|
|
2249
|
-
*/
|
|
2250
|
-
getStats(name) {
|
|
2251
|
-
if (name) {
|
|
2252
|
-
return this.stats.getComponentStats(name);
|
|
2253
|
-
}
|
|
2254
|
-
return this.stats.getAllStats();
|
|
2255
|
-
}
|
|
2256
|
-
/**
|
|
2257
|
-
* Get a snapshot of all stats sorted by severity
|
|
2258
|
-
* @returns Sorted stats array
|
|
2259
|
-
*/
|
|
2260
|
-
getSnapshot() {
|
|
2261
|
-
return this.stats.getSnapshot();
|
|
2262
|
-
}
|
|
2263
|
-
/**
|
|
2264
|
-
* Get session summary
|
|
2265
|
-
* @returns Session summary statistics
|
|
2266
|
-
*/
|
|
2267
|
-
getSummary() {
|
|
2268
|
-
return this.stats.getSummary();
|
|
2269
|
-
}
|
|
2270
|
-
/**
|
|
2271
|
-
* Get top problematic components
|
|
2272
|
-
* @param limit - Maximum number to return
|
|
2273
|
-
* @returns Top problems
|
|
2274
|
-
*/
|
|
2275
|
-
getTopProblems(limit = 10) {
|
|
2276
|
-
return this.stats.getTopProblems(limit);
|
|
2277
|
-
}
|
|
2278
|
-
/**
|
|
2279
|
-
* Get all fix suggestions
|
|
2280
|
-
* @returns All suggestions
|
|
2281
|
-
*/
|
|
2282
|
-
getSuggestions() {
|
|
2283
|
-
return this.fixSuggester.getAllSuggestions();
|
|
2284
|
-
}
|
|
2285
|
-
/**
|
|
2286
|
-
* Get suggestions for a specific component
|
|
2287
|
-
* @param componentName - Component name
|
|
2288
|
-
* @returns Component suggestions
|
|
2289
|
-
*/
|
|
2290
|
-
getComponentSuggestions(componentName) {
|
|
2291
|
-
return this.fixSuggester.getSuggestions(componentName);
|
|
2292
|
-
}
|
|
2293
|
-
/**
|
|
2294
|
-
* Set parent relationship for a component
|
|
2295
|
-
* @param child - Child component name
|
|
2296
|
-
* @param parent - Parent component name
|
|
2297
|
-
*/
|
|
2298
|
-
setParent(child, parent) {
|
|
2299
|
-
this.chainAnalyzer.setParent(child, parent);
|
|
2300
|
-
this.stats.setComponentParent(child, parent);
|
|
2301
|
-
}
|
|
2302
|
-
/**
|
|
2303
|
-
* Get the render chain for a component
|
|
2304
|
-
* @param componentName - Component name
|
|
2305
|
-
* @returns Render chain
|
|
2306
|
-
*/
|
|
2307
|
-
getComponentChain(componentName) {
|
|
2308
|
-
return this.chainAnalyzer.getComponentChain(componentName);
|
|
2309
|
-
}
|
|
2310
|
-
/**
|
|
2311
|
-
* Get session duration
|
|
2312
|
-
* @returns Duration in milliseconds
|
|
2313
|
-
*/
|
|
2314
|
-
getSessionDuration() {
|
|
2315
|
-
return this.stats.getSessionDuration();
|
|
2316
|
-
}
|
|
2317
|
-
/**
|
|
2318
|
-
* Export scanner data for reporting
|
|
2319
|
-
* @returns Exportable data object
|
|
2320
|
-
*/
|
|
2321
|
-
export() {
|
|
2322
|
-
return {
|
|
2323
|
-
stats: this.stats.export(),
|
|
2324
|
-
suggestions: this.getSuggestions(),
|
|
2325
|
-
config: this.getConfig()
|
|
2326
|
-
};
|
|
2327
|
-
}
|
|
2328
|
-
/**
|
|
2329
|
-
* Analyze a specific component and generate suggestions
|
|
2330
|
-
* @param componentName - Component name
|
|
2331
|
-
* @returns Fix suggestions for the component
|
|
2332
|
-
*/
|
|
2333
|
-
analyzeComponent(componentName) {
|
|
2334
|
-
const stats = this.stats.getComponentStats(componentName);
|
|
2335
|
-
if (!stats) return [];
|
|
2336
|
-
return this.fixSuggester.analyze(stats);
|
|
2337
|
-
}
|
|
2338
|
-
/**
|
|
2339
|
-
* Analyze all components and generate suggestions
|
|
2340
|
-
* @returns All fix suggestions
|
|
2341
|
-
*/
|
|
2342
|
-
analyzeAll() {
|
|
2343
|
-
const allStats = this.stats.getAllStats();
|
|
2344
|
-
const allSuggestions = [];
|
|
2345
|
-
for (const stats of allStats) {
|
|
2346
|
-
const suggestions = this.fixSuggester.analyze(stats);
|
|
2347
|
-
allSuggestions.push(...suggestions);
|
|
2348
|
-
}
|
|
2349
|
-
return allSuggestions;
|
|
39
|
+
this.details = details;
|
|
2350
40
|
}
|
|
2351
41
|
};
|
|
2352
42
|
|
|
@@ -2450,6 +140,24 @@ function isUserComponent(fiber) {
|
|
|
2450
140
|
const { tag } = fiber;
|
|
2451
141
|
return tag === FiberTag.FunctionComponent || tag === FiberTag.ClassComponent || tag === FiberTag.MemoComponent || tag === FiberTag.SimpleMemoComponent || tag === FiberTag.ForwardRef || tag === FiberTag.LazyComponent;
|
|
2452
142
|
}
|
|
143
|
+
var PERFORMED_WORK_FLAG = 1;
|
|
144
|
+
function didFiberRender(fiber) {
|
|
145
|
+
const prev = fiber.alternate;
|
|
146
|
+
if (!prev) return true;
|
|
147
|
+
switch (fiber.tag) {
|
|
148
|
+
case FiberTag.FunctionComponent:
|
|
149
|
+
case FiberTag.ClassComponent:
|
|
150
|
+
case FiberTag.ContextConsumer:
|
|
151
|
+
case FiberTag.ForwardRef:
|
|
152
|
+
case FiberTag.MemoComponent:
|
|
153
|
+
case FiberTag.SimpleMemoComponent: {
|
|
154
|
+
const flags = fiber.flags ?? fiber.effectTag ?? 0;
|
|
155
|
+
return (flags & PERFORMED_WORK_FLAG) === PERFORMED_WORK_FLAG;
|
|
156
|
+
}
|
|
157
|
+
default:
|
|
158
|
+
return prev.memoizedProps !== fiber.memoizedProps || prev.memoizedState !== fiber.memoizedState;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
2453
161
|
function isHostComponent(fiber) {
|
|
2454
162
|
return fiber.tag === FiberTag.HostComponent;
|
|
2455
163
|
}
|
|
@@ -2766,6 +474,9 @@ function formatRenderTime(ms) {
|
|
|
2766
474
|
}
|
|
2767
475
|
return `${(ms / 1e3).toFixed(2)}s`;
|
|
2768
476
|
}
|
|
477
|
+
function formatDate(date = /* @__PURE__ */ new Date()) {
|
|
478
|
+
return date.toISOString();
|
|
479
|
+
}
|
|
2769
480
|
function pad(str, length, char = " ", position = "right") {
|
|
2770
481
|
if (str.length >= length) {
|
|
2771
482
|
return str;
|
|
@@ -2789,6 +500,11 @@ function escapeHtml(str) {
|
|
|
2789
500
|
};
|
|
2790
501
|
return str.replace(/[&<>"']/g, (char) => escapeMap[char] ?? char);
|
|
2791
502
|
}
|
|
503
|
+
function generateId(prefix = "") {
|
|
504
|
+
const timestamp = Date.now().toString(36);
|
|
505
|
+
const random = Math.random().toString(36).slice(2, 8);
|
|
506
|
+
return prefix ? `${prefix}_${timestamp}${random}` : `${timestamp}${random}`;
|
|
507
|
+
}
|
|
2792
508
|
|
|
2793
509
|
// src/report/markdown.ts
|
|
2794
510
|
function generateMarkdownReport(report) {
|
|
@@ -3500,71 +1216,6 @@ function renderFooter(report) {
|
|
|
3500
1216
|
</footer>
|
|
3501
1217
|
`;
|
|
3502
1218
|
}
|
|
3503
|
-
async function exists(path) {
|
|
3504
|
-
try {
|
|
3505
|
-
await access(path, constants.F_OK);
|
|
3506
|
-
return true;
|
|
3507
|
-
} catch {
|
|
3508
|
-
return false;
|
|
3509
|
-
}
|
|
3510
|
-
}
|
|
3511
|
-
async function readTextFile(path, encoding = "utf-8") {
|
|
3512
|
-
return readFile(path, { encoding });
|
|
3513
|
-
}
|
|
3514
|
-
async function writeTextFile(path, content, encoding = "utf-8") {
|
|
3515
|
-
const dir = dirname(path);
|
|
3516
|
-
await ensureDir(dir);
|
|
3517
|
-
await writeFile(path, content, { encoding });
|
|
3518
|
-
}
|
|
3519
|
-
async function readJsonFile(path) {
|
|
3520
|
-
const content = await readTextFile(path);
|
|
3521
|
-
return JSON.parse(content);
|
|
3522
|
-
}
|
|
3523
|
-
async function writeJsonFile(path, data, pretty = true) {
|
|
3524
|
-
const content = pretty ? JSON.stringify(data, null, 2) : JSON.stringify(data);
|
|
3525
|
-
await writeTextFile(path, content);
|
|
3526
|
-
}
|
|
3527
|
-
async function ensureDir(path) {
|
|
3528
|
-
if (!await exists(path)) {
|
|
3529
|
-
await mkdir(path, { recursive: true });
|
|
3530
|
-
}
|
|
3531
|
-
}
|
|
3532
|
-
function getExtension(path) {
|
|
3533
|
-
return extname(path).slice(1);
|
|
3534
|
-
}
|
|
3535
|
-
function getBaseName(path) {
|
|
3536
|
-
const ext = extname(path);
|
|
3537
|
-
return basename(path, ext);
|
|
3538
|
-
}
|
|
3539
|
-
function resolvePath(base, ...paths) {
|
|
3540
|
-
return resolve(base, ...paths);
|
|
3541
|
-
}
|
|
3542
|
-
function joinPath(...paths) {
|
|
3543
|
-
return join(...paths);
|
|
3544
|
-
}
|
|
3545
|
-
function getDirName(path) {
|
|
3546
|
-
return dirname(path);
|
|
3547
|
-
}
|
|
3548
|
-
async function findUp(filename, startDir = process.cwd()) {
|
|
3549
|
-
let currentDir = resolve(startDir);
|
|
3550
|
-
const root = dirname(currentDir);
|
|
3551
|
-
while (currentDir !== root) {
|
|
3552
|
-
const filePath = join(currentDir, filename);
|
|
3553
|
-
if (await exists(filePath)) {
|
|
3554
|
-
return filePath;
|
|
3555
|
-
}
|
|
3556
|
-
const parentDir = dirname(currentDir);
|
|
3557
|
-
if (parentDir === currentDir) {
|
|
3558
|
-
break;
|
|
3559
|
-
}
|
|
3560
|
-
currentDir = parentDir;
|
|
3561
|
-
}
|
|
3562
|
-
const rootFilePath = join(currentDir, filename);
|
|
3563
|
-
if (await exists(rootFilePath)) {
|
|
3564
|
-
return rootFilePath;
|
|
3565
|
-
}
|
|
3566
|
-
return null;
|
|
3567
|
-
}
|
|
3568
1219
|
|
|
3569
1220
|
// src/report/index.ts
|
|
3570
1221
|
function generateReport(report, format) {
|
|
@@ -3576,7 +1227,7 @@ function generateReport(report, format) {
|
|
|
3576
1227
|
case "md":
|
|
3577
1228
|
return generateMarkdownReport(report);
|
|
3578
1229
|
default:
|
|
3579
|
-
throw new Error(`Unknown report format: ${format}`);
|
|
1230
|
+
throw new Error(`Unknown report format: ${String(format)}`);
|
|
3580
1231
|
}
|
|
3581
1232
|
}
|
|
3582
1233
|
async function saveReport(report, format, outputDir, filename) {
|
|
@@ -3670,289 +1321,417 @@ var ReportGenerator = class {
|
|
|
3670
1321
|
}
|
|
3671
1322
|
};
|
|
3672
1323
|
|
|
3673
|
-
// src/
|
|
3674
|
-
|
|
3675
|
-
|
|
3676
|
-
|
|
3677
|
-
name: "next",
|
|
3678
|
-
dependencies: ["next"],
|
|
3679
|
-
features: [
|
|
3680
|
-
{
|
|
3681
|
-
name: "app-router",
|
|
3682
|
-
detect: async (_, dir) => exists(joinPath(dir, "app"))
|
|
3683
|
-
},
|
|
3684
|
-
{
|
|
3685
|
-
name: "pages-router",
|
|
3686
|
-
detect: async (_, dir) => exists(joinPath(dir, "pages"))
|
|
3687
|
-
},
|
|
3688
|
-
{
|
|
3689
|
-
name: "rsc",
|
|
3690
|
-
deps: ["next"],
|
|
3691
|
-
detect: async (pkg) => {
|
|
3692
|
-
const version = pkg.dependencies?.["next"] ?? "";
|
|
3693
|
-
const major = parseInt(version.replace(/[^0-9]/g, "").slice(0, 2), 10);
|
|
3694
|
-
return major >= 13;
|
|
3695
|
-
}
|
|
3696
|
-
},
|
|
3697
|
-
{
|
|
3698
|
-
name: "middleware",
|
|
3699
|
-
detect: async (_, dir) => exists(joinPath(dir, "middleware.ts")) || exists(joinPath(dir, "middleware.js"))
|
|
3700
|
-
}
|
|
3701
|
-
],
|
|
3702
|
-
tips: [
|
|
3703
|
-
'Use "use client" directive only for interactive components',
|
|
3704
|
-
"Keep server components as the default for better performance",
|
|
3705
|
-
"Consider using Server Actions for mutations",
|
|
3706
|
-
"Use next/dynamic for code splitting heavy components",
|
|
3707
|
-
"Avoid passing serializable props through server/client boundary"
|
|
3708
|
-
]
|
|
3709
|
-
},
|
|
3710
|
-
// Remix
|
|
3711
|
-
{
|
|
3712
|
-
name: "remix",
|
|
3713
|
-
dependencies: ["@remix-run/react", "@remix-run/node", "@remix-run/cloudflare"],
|
|
3714
|
-
features: [
|
|
3715
|
-
{
|
|
3716
|
-
name: "v2-routes",
|
|
3717
|
-
detect: async (_, dir) => exists(joinPath(dir, "app", "routes"))
|
|
3718
|
-
},
|
|
3719
|
-
{
|
|
3720
|
-
name: "defer",
|
|
3721
|
-
deps: ["@remix-run/react"],
|
|
3722
|
-
detect: async (pkg) => {
|
|
3723
|
-
const version = pkg.dependencies?.["@remix-run/react"] ?? "";
|
|
3724
|
-
return version.includes("1.") || version.includes("2.");
|
|
3725
|
-
}
|
|
3726
|
-
}
|
|
3727
|
-
],
|
|
3728
|
-
tips: [
|
|
3729
|
-
"Use loader data efficiently to minimize client state",
|
|
3730
|
-
"Prefer fetcher over useNavigate for non-navigation mutations",
|
|
3731
|
-
"Use defer for streaming slow data",
|
|
3732
|
-
"Consider using useFetcher.load for background data fetching",
|
|
3733
|
-
"Avoid useEffect for data fetching, use loaders instead"
|
|
3734
|
-
]
|
|
3735
|
-
},
|
|
3736
|
-
// Vite
|
|
3737
|
-
{
|
|
3738
|
-
name: "vite",
|
|
3739
|
-
dependencies: [],
|
|
3740
|
-
devDependencies: ["vite"],
|
|
3741
|
-
features: [
|
|
3742
|
-
{
|
|
3743
|
-
name: "react-plugin",
|
|
3744
|
-
deps: ["@vitejs/plugin-react", "@vitejs/plugin-react-swc"]
|
|
3745
|
-
},
|
|
3746
|
-
{
|
|
3747
|
-
name: "ssr",
|
|
3748
|
-
detect: async (_, dir) => exists(joinPath(dir, "vite.config.ts")) || exists(joinPath(dir, "vite.config.js"))
|
|
3749
|
-
}
|
|
3750
|
-
],
|
|
3751
|
-
tips: [
|
|
3752
|
-
"Use React.lazy with Suspense for code splitting",
|
|
3753
|
-
"Configure build.rollupOptions.output.manualChunks for optimal chunking",
|
|
3754
|
-
"Enable build.sourcemap only in development",
|
|
3755
|
-
"Use @vitejs/plugin-react-swc for faster builds",
|
|
3756
|
-
"Consider using vite-plugin-pwa for PWA support"
|
|
3757
|
-
]
|
|
3758
|
-
},
|
|
3759
|
-
// Create React App
|
|
3760
|
-
{
|
|
3761
|
-
name: "cra",
|
|
3762
|
-
dependencies: ["react-scripts"],
|
|
3763
|
-
features: [
|
|
3764
|
-
{
|
|
3765
|
-
name: "typescript",
|
|
3766
|
-
deps: ["typescript"]
|
|
3767
|
-
},
|
|
3768
|
-
{
|
|
3769
|
-
name: "testing-library",
|
|
3770
|
-
deps: ["@testing-library/react"]
|
|
3771
|
-
}
|
|
3772
|
-
],
|
|
3773
|
-
tips: [
|
|
3774
|
-
"Consider migrating to Vite for faster development builds",
|
|
3775
|
-
"Use React.lazy for code splitting",
|
|
3776
|
-
'Run "npm run build -- --stats" to analyze bundle size',
|
|
3777
|
-
"Use REACT_APP_ prefix for environment variables",
|
|
3778
|
-
"Consider ejecting only if absolutely necessary"
|
|
3779
|
-
]
|
|
3780
|
-
},
|
|
3781
|
-
// Gatsby
|
|
3782
|
-
{
|
|
3783
|
-
name: "gatsby",
|
|
3784
|
-
dependencies: ["gatsby"],
|
|
3785
|
-
features: [
|
|
3786
|
-
{
|
|
3787
|
-
name: "v5",
|
|
3788
|
-
deps: ["gatsby"],
|
|
3789
|
-
detect: async (pkg) => {
|
|
3790
|
-
const version = pkg.dependencies?.["gatsby"] ?? "";
|
|
3791
|
-
return version.includes("5.") || version.includes("^5");
|
|
3792
|
-
}
|
|
3793
|
-
},
|
|
3794
|
-
{
|
|
3795
|
-
name: "image",
|
|
3796
|
-
deps: ["gatsby-plugin-image"]
|
|
3797
|
-
},
|
|
3798
|
-
{
|
|
3799
|
-
name: "graphql",
|
|
3800
|
-
deps: ["gatsby"]
|
|
3801
|
-
}
|
|
3802
|
-
],
|
|
3803
|
-
tips: [
|
|
3804
|
-
"Use gatsby-plugin-image for optimized images",
|
|
3805
|
-
"Prefer StaticQuery over page queries for reusable components",
|
|
3806
|
-
"Use incremental builds for faster development",
|
|
3807
|
-
"Configure proper caching headers for static assets",
|
|
3808
|
-
"Consider using DSG (Deferred Static Generation) for large sites"
|
|
3809
|
-
]
|
|
3810
|
-
}
|
|
3811
|
-
];
|
|
3812
|
-
async function detectFramework(packageJsonPath) {
|
|
3813
|
-
let pkgPath = packageJsonPath;
|
|
3814
|
-
if (!pkgPath) {
|
|
3815
|
-
pkgPath = await findUp("package.json") ?? void 0;
|
|
3816
|
-
}
|
|
3817
|
-
if (!pkgPath || !await exists(pkgPath)) {
|
|
3818
|
-
return null;
|
|
1324
|
+
// src/utils/colors.ts
|
|
1325
|
+
function checkColorSupport() {
|
|
1326
|
+
if (process.env["FORCE_COLOR"] !== void 0) {
|
|
1327
|
+
return process.env["FORCE_COLOR"] !== "0";
|
|
3819
1328
|
}
|
|
3820
|
-
|
|
3821
|
-
|
|
3822
|
-
packageJson = await readJsonFile(pkgPath);
|
|
3823
|
-
} catch {
|
|
3824
|
-
return null;
|
|
1329
|
+
if (process.env["NO_COLOR"] !== void 0) {
|
|
1330
|
+
return false;
|
|
3825
1331
|
}
|
|
3826
|
-
|
|
3827
|
-
|
|
3828
|
-
|
|
3829
|
-
|
|
3830
|
-
|
|
3831
|
-
|
|
3832
|
-
|
|
3833
|
-
|
|
3834
|
-
|
|
3835
|
-
|
|
3836
|
-
|
|
3837
|
-
tips: [
|
|
3838
|
-
"Consider using React.memo for frequently re-rendering components",
|
|
3839
|
-
"Use useCallback for event handlers passed to child components",
|
|
3840
|
-
"Use useMemo for expensive computations",
|
|
3841
|
-
"Avoid inline object/array creation in render"
|
|
3842
|
-
]
|
|
3843
|
-
};
|
|
1332
|
+
if (!process.stdout.isTTY) {
|
|
1333
|
+
return false;
|
|
1334
|
+
}
|
|
1335
|
+
if (process.env["TERM"] === "dumb") {
|
|
1336
|
+
return false;
|
|
1337
|
+
}
|
|
1338
|
+
if (process.env["CI"] !== void 0) {
|
|
1339
|
+
const ciEnvs = ["TRAVIS", "CIRCLECI", "GITHUB_ACTIONS", "GITLAB_CI", "BUILDKITE"];
|
|
1340
|
+
return ciEnvs.some((env) => process.env[env] !== void 0);
|
|
1341
|
+
}
|
|
1342
|
+
return true;
|
|
3844
1343
|
}
|
|
3845
|
-
|
|
3846
|
-
|
|
3847
|
-
|
|
3848
|
-
|
|
3849
|
-
|
|
3850
|
-
|
|
3851
|
-
|
|
3852
|
-
|
|
1344
|
+
var supportsColor = checkColorSupport();
|
|
1345
|
+
var colors = {
|
|
1346
|
+
// Reset
|
|
1347
|
+
reset: supportsColor ? "\x1B[0m" : "",
|
|
1348
|
+
// Text styles
|
|
1349
|
+
bold: supportsColor ? "\x1B[1m" : "",
|
|
1350
|
+
dim: supportsColor ? "\x1B[2m" : "",
|
|
1351
|
+
italic: supportsColor ? "\x1B[3m" : "",
|
|
1352
|
+
underline: supportsColor ? "\x1B[4m" : "",
|
|
1353
|
+
blink: supportsColor ? "\x1B[5m" : "",
|
|
1354
|
+
inverse: supportsColor ? "\x1B[7m" : "",
|
|
1355
|
+
hidden: supportsColor ? "\x1B[8m" : "",
|
|
1356
|
+
strikethrough: supportsColor ? "\x1B[9m" : "",
|
|
1357
|
+
// Foreground colors
|
|
1358
|
+
black: supportsColor ? "\x1B[30m" : "",
|
|
1359
|
+
red: supportsColor ? "\x1B[31m" : "",
|
|
1360
|
+
green: supportsColor ? "\x1B[32m" : "",
|
|
1361
|
+
yellow: supportsColor ? "\x1B[33m" : "",
|
|
1362
|
+
blue: supportsColor ? "\x1B[34m" : "",
|
|
1363
|
+
magenta: supportsColor ? "\x1B[35m" : "",
|
|
1364
|
+
cyan: supportsColor ? "\x1B[36m" : "",
|
|
1365
|
+
white: supportsColor ? "\x1B[37m" : "",
|
|
1366
|
+
gray: supportsColor ? "\x1B[90m" : "",
|
|
1367
|
+
grey: supportsColor ? "\x1B[90m" : "",
|
|
1368
|
+
// Bright foreground colors
|
|
1369
|
+
brightRed: supportsColor ? "\x1B[91m" : "",
|
|
1370
|
+
brightGreen: supportsColor ? "\x1B[92m" : "",
|
|
1371
|
+
brightYellow: supportsColor ? "\x1B[93m" : "",
|
|
1372
|
+
brightBlue: supportsColor ? "\x1B[94m" : "",
|
|
1373
|
+
brightMagenta: supportsColor ? "\x1B[95m" : "",
|
|
1374
|
+
brightCyan: supportsColor ? "\x1B[96m" : "",
|
|
1375
|
+
brightWhite: supportsColor ? "\x1B[97m" : "",
|
|
1376
|
+
// Background colors
|
|
1377
|
+
bgBlack: supportsColor ? "\x1B[40m" : "",
|
|
1378
|
+
bgRed: supportsColor ? "\x1B[41m" : "",
|
|
1379
|
+
bgGreen: supportsColor ? "\x1B[42m" : "",
|
|
1380
|
+
bgYellow: supportsColor ? "\x1B[43m" : "",
|
|
1381
|
+
bgBlue: supportsColor ? "\x1B[44m" : "",
|
|
1382
|
+
bgMagenta: supportsColor ? "\x1B[45m" : "",
|
|
1383
|
+
bgCyan: supportsColor ? "\x1B[46m" : "",
|
|
1384
|
+
bgWhite: supportsColor ? "\x1B[47m" : "",
|
|
1385
|
+
bgGray: supportsColor ? "\x1B[100m" : "",
|
|
1386
|
+
// Bright background colors
|
|
1387
|
+
bgBrightRed: supportsColor ? "\x1B[101m" : "",
|
|
1388
|
+
bgBrightGreen: supportsColor ? "\x1B[102m" : "",
|
|
1389
|
+
bgBrightYellow: supportsColor ? "\x1B[103m" : "",
|
|
1390
|
+
bgBrightBlue: supportsColor ? "\x1B[104m" : "",
|
|
1391
|
+
bgBrightMagenta: supportsColor ? "\x1B[105m" : "",
|
|
1392
|
+
bgBrightCyan: supportsColor ? "\x1B[106m" : "",
|
|
1393
|
+
bgBrightWhite: supportsColor ? "\x1B[107m" : ""
|
|
1394
|
+
};
|
|
1395
|
+
function colorize(text, ...codes) {
|
|
1396
|
+
if (!supportsColor || codes.length === 0) {
|
|
1397
|
+
return text;
|
|
1398
|
+
}
|
|
1399
|
+
return codes.join("") + text + colors.reset;
|
|
1400
|
+
}
|
|
1401
|
+
function createColorizer(code) {
|
|
1402
|
+
return (text) => colorize(text, code);
|
|
1403
|
+
}
|
|
1404
|
+
var semantic = {
|
|
1405
|
+
/** Critical issues (red) */
|
|
1406
|
+
critical: createColorizer(colors.red),
|
|
1407
|
+
/** Warnings (yellow) */
|
|
1408
|
+
warning: createColorizer(colors.yellow),
|
|
1409
|
+
/** Healthy/success (green) */
|
|
1410
|
+
healthy: createColorizer(colors.green),
|
|
1411
|
+
/** Info/links (blue) */
|
|
1412
|
+
info: createColorizer(colors.blue),
|
|
1413
|
+
/** Secondary text (gray) */
|
|
1414
|
+
secondary: createColorizer(colors.gray),
|
|
1415
|
+
/** Highlighted text (cyan) */
|
|
1416
|
+
highlight: createColorizer(colors.cyan),
|
|
1417
|
+
/** Error text (bright red, bold) */
|
|
1418
|
+
error: (text) => colorize(text, colors.brightRed, colors.bold),
|
|
1419
|
+
/** Success text (bright green, bold) */
|
|
1420
|
+
success: (text) => colorize(text, colors.brightGreen, colors.bold),
|
|
1421
|
+
/** Title text (bold) */
|
|
1422
|
+
title: createColorizer(colors.bold),
|
|
1423
|
+
/** Dimmed text */
|
|
1424
|
+
dimmed: createColorizer(colors.dim)
|
|
1425
|
+
};
|
|
1426
|
+
function stripAnsi(text) {
|
|
1427
|
+
return text.replace(/\x1b\[[0-9;]*m/g, "");
|
|
1428
|
+
}
|
|
1429
|
+
|
|
1430
|
+
// src/utils/logger.ts
|
|
1431
|
+
var LogLevel = /* @__PURE__ */ ((LogLevel2) => {
|
|
1432
|
+
LogLevel2[LogLevel2["DEBUG"] = 0] = "DEBUG";
|
|
1433
|
+
LogLevel2[LogLevel2["INFO"] = 1] = "INFO";
|
|
1434
|
+
LogLevel2[LogLevel2["WARN"] = 2] = "WARN";
|
|
1435
|
+
LogLevel2[LogLevel2["ERROR"] = 3] = "ERROR";
|
|
1436
|
+
LogLevel2[LogLevel2["SILENT"] = 4] = "SILENT";
|
|
1437
|
+
return LogLevel2;
|
|
1438
|
+
})(LogLevel || {});
|
|
1439
|
+
var LOG_LEVEL_NAMES = {
|
|
1440
|
+
[0 /* DEBUG */]: "DEBUG",
|
|
1441
|
+
[1 /* INFO */]: "INFO",
|
|
1442
|
+
[2 /* WARN */]: "WARN",
|
|
1443
|
+
[3 /* ERROR */]: "ERROR",
|
|
1444
|
+
[4 /* SILENT */]: "SILENT"
|
|
1445
|
+
};
|
|
1446
|
+
var Logger = class _Logger {
|
|
1447
|
+
prefix;
|
|
1448
|
+
level;
|
|
1449
|
+
showTimestamp;
|
|
1450
|
+
showLevel;
|
|
1451
|
+
output;
|
|
1452
|
+
/**
|
|
1453
|
+
* Create a new Logger instance
|
|
1454
|
+
* @param options - Logger configuration
|
|
1455
|
+
*/
|
|
1456
|
+
constructor(options = {}) {
|
|
1457
|
+
this.prefix = options.prefix ?? "";
|
|
1458
|
+
this.level = options.level ?? 1 /* INFO */;
|
|
1459
|
+
this.showTimestamp = options.showTimestamp ?? false;
|
|
1460
|
+
this.showLevel = options.showLevel ?? true;
|
|
1461
|
+
this.output = options.output ?? {
|
|
1462
|
+
/* eslint-disable no-console */
|
|
1463
|
+
log: (msg) => console.log(msg),
|
|
1464
|
+
warn: (msg) => console.warn(msg),
|
|
1465
|
+
error: (msg) => console.error(msg)
|
|
1466
|
+
/* eslint-enable no-console */
|
|
1467
|
+
};
|
|
3853
1468
|
}
|
|
3854
|
-
|
|
3855
|
-
|
|
3856
|
-
|
|
3857
|
-
|
|
3858
|
-
|
|
3859
|
-
|
|
3860
|
-
|
|
3861
|
-
|
|
3862
|
-
|
|
3863
|
-
|
|
3864
|
-
|
|
1469
|
+
/**
|
|
1470
|
+
* Format a log message
|
|
1471
|
+
* @param level - Log level
|
|
1472
|
+
* @param message - Message to format
|
|
1473
|
+
* @returns Formatted message
|
|
1474
|
+
*/
|
|
1475
|
+
format(level, message) {
|
|
1476
|
+
const parts = [];
|
|
1477
|
+
if (this.showTimestamp) {
|
|
1478
|
+
const now = /* @__PURE__ */ new Date();
|
|
1479
|
+
const time = now.toISOString().slice(11, 23);
|
|
1480
|
+
parts.push(semantic.secondary(`[${time}]`));
|
|
1481
|
+
}
|
|
1482
|
+
if (this.showLevel) {
|
|
1483
|
+
const levelName = LOG_LEVEL_NAMES[level] ?? "UNKNOWN";
|
|
1484
|
+
let levelStr;
|
|
1485
|
+
switch (level) {
|
|
1486
|
+
case 0 /* DEBUG */:
|
|
1487
|
+
levelStr = semantic.secondary(levelName);
|
|
3865
1488
|
break;
|
|
3866
|
-
|
|
1489
|
+
case 1 /* INFO */:
|
|
1490
|
+
levelStr = semantic.info(levelName);
|
|
1491
|
+
break;
|
|
1492
|
+
case 2 /* WARN */:
|
|
1493
|
+
levelStr = semantic.warning(levelName);
|
|
1494
|
+
break;
|
|
1495
|
+
case 3 /* ERROR */:
|
|
1496
|
+
levelStr = semantic.error(levelName);
|
|
1497
|
+
break;
|
|
1498
|
+
default:
|
|
1499
|
+
levelStr = levelName;
|
|
3867
1500
|
}
|
|
1501
|
+
parts.push(`[${levelStr}]`);
|
|
3868
1502
|
}
|
|
3869
|
-
if (
|
|
3870
|
-
|
|
3871
|
-
detected = await feature.detect(packageJson, projectDir);
|
|
3872
|
-
} catch {
|
|
3873
|
-
}
|
|
1503
|
+
if (this.prefix) {
|
|
1504
|
+
parts.push(semantic.highlight(`[${this.prefix}]`));
|
|
3874
1505
|
}
|
|
3875
|
-
|
|
3876
|
-
|
|
1506
|
+
parts.push(message);
|
|
1507
|
+
return parts.join(" ");
|
|
1508
|
+
}
|
|
1509
|
+
/**
|
|
1510
|
+
* Log a debug message
|
|
1511
|
+
* @param message - Message to log
|
|
1512
|
+
* @param args - Additional arguments to log
|
|
1513
|
+
*/
|
|
1514
|
+
debug(message, ...args) {
|
|
1515
|
+
if (this.level > 0 /* DEBUG */) return;
|
|
1516
|
+
const formatted = this.format(0 /* DEBUG */, message);
|
|
1517
|
+
if (args.length > 0) {
|
|
1518
|
+
this.output.log(formatted + " " + args.map(String).join(" "));
|
|
1519
|
+
} else {
|
|
1520
|
+
this.output.log(formatted);
|
|
3877
1521
|
}
|
|
3878
1522
|
}
|
|
3879
|
-
|
|
3880
|
-
|
|
3881
|
-
|
|
3882
|
-
|
|
3883
|
-
|
|
3884
|
-
|
|
3885
|
-
|
|
3886
|
-
|
|
3887
|
-
|
|
3888
|
-
|
|
3889
|
-
|
|
3890
|
-
|
|
3891
|
-
case "next":
|
|
3892
|
-
tips.push("Consider using server components to avoid client-side context re-renders");
|
|
3893
|
-
break;
|
|
3894
|
-
case "remix":
|
|
3895
|
-
tips.push("Use loader data instead of context for server data");
|
|
3896
|
-
break;
|
|
3897
|
-
default:
|
|
3898
|
-
tips.push("Split large contexts into smaller, focused contexts");
|
|
1523
|
+
/**
|
|
1524
|
+
* Log an info message
|
|
1525
|
+
* @param message - Message to log
|
|
1526
|
+
* @param args - Additional arguments to log
|
|
1527
|
+
*/
|
|
1528
|
+
info(message, ...args) {
|
|
1529
|
+
if (this.level > 1 /* INFO */) return;
|
|
1530
|
+
const formatted = this.format(1 /* INFO */, message);
|
|
1531
|
+
if (args.length > 0) {
|
|
1532
|
+
this.output.log(formatted + " " + args.map(String).join(" "));
|
|
1533
|
+
} else {
|
|
1534
|
+
this.output.log(formatted);
|
|
3899
1535
|
}
|
|
3900
1536
|
}
|
|
3901
|
-
|
|
3902
|
-
|
|
3903
|
-
|
|
3904
|
-
|
|
3905
|
-
|
|
3906
|
-
|
|
3907
|
-
|
|
3908
|
-
|
|
3909
|
-
|
|
3910
|
-
|
|
1537
|
+
/**
|
|
1538
|
+
* Log a warning message
|
|
1539
|
+
* @param message - Message to log
|
|
1540
|
+
* @param args - Additional arguments to log
|
|
1541
|
+
*/
|
|
1542
|
+
warn(message, ...args) {
|
|
1543
|
+
if (this.level > 2 /* WARN */) return;
|
|
1544
|
+
const formatted = this.format(2 /* WARN */, message);
|
|
1545
|
+
if (args.length > 0) {
|
|
1546
|
+
this.output.warn(formatted + " " + args.map(String).join(" "));
|
|
1547
|
+
} else {
|
|
1548
|
+
this.output.warn(formatted);
|
|
3911
1549
|
}
|
|
3912
1550
|
}
|
|
3913
|
-
|
|
3914
|
-
|
|
3915
|
-
|
|
3916
|
-
|
|
3917
|
-
|
|
1551
|
+
/**
|
|
1552
|
+
* Log an error message
|
|
1553
|
+
* @param message - Message to log
|
|
1554
|
+
* @param args - Additional arguments to log
|
|
1555
|
+
*/
|
|
1556
|
+
error(message, ...args) {
|
|
1557
|
+
if (this.level > 3 /* ERROR */) return;
|
|
1558
|
+
const formatted = this.format(3 /* ERROR */, message);
|
|
1559
|
+
if (args.length > 0) {
|
|
1560
|
+
this.output.error(formatted + " " + args.map(String).join(" "));
|
|
1561
|
+
} else {
|
|
1562
|
+
this.output.error(formatted);
|
|
1563
|
+
}
|
|
3918
1564
|
}
|
|
3919
|
-
|
|
3920
|
-
|
|
3921
|
-
|
|
3922
|
-
|
|
3923
|
-
|
|
3924
|
-
|
|
3925
|
-
|
|
3926
|
-
|
|
3927
|
-
tips: []
|
|
3928
|
-
};
|
|
1565
|
+
/**
|
|
1566
|
+
* Log a success message (always shown unless silent)
|
|
1567
|
+
* @param message - Message to log
|
|
1568
|
+
*/
|
|
1569
|
+
success(message) {
|
|
1570
|
+
if (this.level >= 4 /* SILENT */) return;
|
|
1571
|
+
const prefix = this.prefix ? `[${semantic.highlight(this.prefix)}] ` : "";
|
|
1572
|
+
this.output.log(prefix + semantic.success("\u2713 ") + message);
|
|
3929
1573
|
}
|
|
3930
|
-
|
|
3931
|
-
|
|
3932
|
-
|
|
3933
|
-
|
|
3934
|
-
|
|
3935
|
-
|
|
3936
|
-
};
|
|
1574
|
+
/**
|
|
1575
|
+
* Log a failure message (always shown unless silent)
|
|
1576
|
+
* @param message - Message to log
|
|
1577
|
+
*/
|
|
1578
|
+
fail(message) {
|
|
1579
|
+
if (this.level >= 4 /* SILENT */) return;
|
|
1580
|
+
const prefix = this.prefix ? `[${semantic.highlight(this.prefix)}] ` : "";
|
|
1581
|
+
this.output.error(prefix + semantic.error("\u2717 ") + message);
|
|
1582
|
+
}
|
|
1583
|
+
/**
|
|
1584
|
+
* Create a child logger with a sub-prefix
|
|
1585
|
+
* @param prefix - Sub-prefix for the child logger
|
|
1586
|
+
* @returns New Logger instance
|
|
1587
|
+
*/
|
|
1588
|
+
child(prefix) {
|
|
1589
|
+
const childPrefix = this.prefix ? `${this.prefix}:${prefix}` : prefix;
|
|
1590
|
+
return new _Logger({
|
|
1591
|
+
prefix: childPrefix,
|
|
1592
|
+
level: this.level,
|
|
1593
|
+
showTimestamp: this.showTimestamp,
|
|
1594
|
+
showLevel: this.showLevel,
|
|
1595
|
+
output: this.output
|
|
1596
|
+
});
|
|
1597
|
+
}
|
|
1598
|
+
/**
|
|
1599
|
+
* Set the log level
|
|
1600
|
+
* @param level - New log level
|
|
1601
|
+
*/
|
|
1602
|
+
setLevel(level) {
|
|
1603
|
+
this.level = level;
|
|
3937
1604
|
}
|
|
3938
|
-
|
|
1605
|
+
/**
|
|
1606
|
+
* Get the current log level
|
|
1607
|
+
* @returns Current log level
|
|
1608
|
+
*/
|
|
1609
|
+
getLevel() {
|
|
1610
|
+
return this.level;
|
|
1611
|
+
}
|
|
1612
|
+
/**
|
|
1613
|
+
* Check if a log level is enabled
|
|
1614
|
+
* @param level - Level to check
|
|
1615
|
+
* @returns true if the level would be logged
|
|
1616
|
+
*/
|
|
1617
|
+
isLevelEnabled(level) {
|
|
1618
|
+
return this.level <= level;
|
|
1619
|
+
}
|
|
1620
|
+
/**
|
|
1621
|
+
* Create a timer for performance logging
|
|
1622
|
+
* @param label - Timer label
|
|
1623
|
+
* @returns Object with end() method to log duration
|
|
1624
|
+
*/
|
|
1625
|
+
time(label) {
|
|
1626
|
+
const start = performance.now();
|
|
3939
1627
|
return {
|
|
3940
|
-
|
|
3941
|
-
|
|
3942
|
-
|
|
3943
|
-
|
|
1628
|
+
end: () => {
|
|
1629
|
+
const duration = performance.now() - start;
|
|
1630
|
+
this.debug(`${label}: ${duration.toFixed(2)}ms`);
|
|
1631
|
+
}
|
|
3944
1632
|
};
|
|
3945
1633
|
}
|
|
3946
|
-
|
|
1634
|
+
/**
|
|
1635
|
+
* Log a table of data
|
|
1636
|
+
* @param data - Array of objects to display
|
|
1637
|
+
* @param columns - Optional column names to show
|
|
1638
|
+
*/
|
|
1639
|
+
table(data, columns) {
|
|
1640
|
+
if (this.level >= 4 /* SILENT */) return;
|
|
1641
|
+
if (data.length === 0) {
|
|
1642
|
+
this.info("(empty table)");
|
|
1643
|
+
return;
|
|
1644
|
+
}
|
|
1645
|
+
const cols = columns ?? Object.keys(data[0] ?? {});
|
|
1646
|
+
if (cols.length === 0) {
|
|
1647
|
+
this.info("(no columns)");
|
|
1648
|
+
return;
|
|
1649
|
+
}
|
|
1650
|
+
const widths = {};
|
|
1651
|
+
for (const col of cols) {
|
|
1652
|
+
widths[col] = col.length;
|
|
1653
|
+
for (const row of data) {
|
|
1654
|
+
const value = formatCell(row[col]);
|
|
1655
|
+
widths[col] = Math.max(widths[col] ?? 0, value.length);
|
|
1656
|
+
}
|
|
1657
|
+
}
|
|
1658
|
+
const header = cols.map((col) => col.padEnd(widths[col] ?? 0)).join(" \u2502 ");
|
|
1659
|
+
const separator = cols.map((col) => "\u2500".repeat(widths[col] ?? 0)).join("\u2500\u253C\u2500");
|
|
1660
|
+
this.output.log(colors.bold + header + colors.reset);
|
|
1661
|
+
this.output.log(separator);
|
|
1662
|
+
for (const row of data) {
|
|
1663
|
+
const line = cols.map((col) => formatCell(row[col]).padEnd(widths[col] ?? 0)).join(" \u2502 ");
|
|
1664
|
+
this.output.log(line);
|
|
1665
|
+
}
|
|
1666
|
+
}
|
|
1667
|
+
/**
|
|
1668
|
+
* Log a progress message (overwrites previous line)
|
|
1669
|
+
* @param message - Progress message
|
|
1670
|
+
*/
|
|
1671
|
+
progress(message) {
|
|
1672
|
+
if (this.level >= 4 /* SILENT */) return;
|
|
1673
|
+
if (process.stdout.isTTY) {
|
|
1674
|
+
process.stdout.write(`\r\x1B[K${message}`);
|
|
1675
|
+
}
|
|
1676
|
+
}
|
|
1677
|
+
/**
|
|
1678
|
+
* Clear the progress line
|
|
1679
|
+
*/
|
|
1680
|
+
clearProgress() {
|
|
1681
|
+
if (process.stdout.isTTY) {
|
|
1682
|
+
process.stdout.write("\r\x1B[K");
|
|
1683
|
+
}
|
|
1684
|
+
}
|
|
1685
|
+
/**
|
|
1686
|
+
* Log a newline
|
|
1687
|
+
*/
|
|
1688
|
+
newline() {
|
|
1689
|
+
if (this.level >= 4 /* SILENT */) return;
|
|
1690
|
+
this.output.log("");
|
|
1691
|
+
}
|
|
1692
|
+
/**
|
|
1693
|
+
* Log a horizontal rule
|
|
1694
|
+
* @param char - Character to use for the rule
|
|
1695
|
+
* @param width - Width of the rule
|
|
1696
|
+
*/
|
|
1697
|
+
hr(char = "\u2500", width = 60) {
|
|
1698
|
+
if (this.level >= 4 /* SILENT */) return;
|
|
1699
|
+
this.output.log(colors.gray + char.repeat(width) + colors.reset);
|
|
1700
|
+
}
|
|
1701
|
+
/**
|
|
1702
|
+
* Group related log messages
|
|
1703
|
+
* @param label - Group label
|
|
1704
|
+
* @param fn - Function containing log calls
|
|
1705
|
+
*/
|
|
1706
|
+
group(label, fn) {
|
|
1707
|
+
if (this.level >= 4 /* SILENT */) return;
|
|
1708
|
+
this.output.log(colors.bold + "\u250C " + label + colors.reset);
|
|
1709
|
+
fn();
|
|
1710
|
+
this.output.log(colors.bold + "\u2514" + "\u2500".repeat(label.length + 1) + colors.reset);
|
|
1711
|
+
}
|
|
1712
|
+
};
|
|
1713
|
+
new Logger({ prefix: "ReactCheck" });
|
|
1714
|
+
function formatCell(value) {
|
|
1715
|
+
if (value === null || value === void 0) return "";
|
|
1716
|
+
if (typeof value === "object") {
|
|
1717
|
+
try {
|
|
1718
|
+
return JSON.stringify(value);
|
|
1719
|
+
} catch {
|
|
1720
|
+
return Object.prototype.toString.call(value);
|
|
1721
|
+
}
|
|
1722
|
+
}
|
|
1723
|
+
switch (typeof value) {
|
|
1724
|
+
case "string":
|
|
1725
|
+
return value;
|
|
1726
|
+
case "number":
|
|
1727
|
+
case "boolean":
|
|
1728
|
+
case "bigint":
|
|
1729
|
+
case "symbol":
|
|
1730
|
+
return value.toString();
|
|
1731
|
+
default:
|
|
1732
|
+
return "[function]";
|
|
1733
|
+
}
|
|
3947
1734
|
}
|
|
3948
|
-
|
|
3949
|
-
// src/utils/index.ts
|
|
3950
|
-
init_colors();
|
|
3951
|
-
init_event_emitter();
|
|
3952
|
-
init_logger();
|
|
3953
|
-
|
|
3954
|
-
// src/server/websocket.ts
|
|
3955
|
-
init_event_emitter();
|
|
3956
1735
|
var OPCODE = {
|
|
3957
1736
|
TEXT: 1,
|
|
3958
1737
|
BINARY: 2,
|
|
@@ -3961,6 +1740,7 @@ var OPCODE = {
|
|
|
3961
1740
|
PONG: 10
|
|
3962
1741
|
};
|
|
3963
1742
|
var WS_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
|
|
1743
|
+
var MAX_FRAME_PAYLOAD = 16 * 1024 * 1024;
|
|
3964
1744
|
var WebSocketClient = class extends EventEmitter {
|
|
3965
1745
|
/** Socket connection */
|
|
3966
1746
|
socket;
|
|
@@ -3997,7 +1777,7 @@ var WebSocketClient = class extends EventEmitter {
|
|
|
3997
1777
|
* Process received frames
|
|
3998
1778
|
*/
|
|
3999
1779
|
processFrames() {
|
|
4000
|
-
while (this.frameBuffer.length >= 2) {
|
|
1780
|
+
while (this.isOpen && this.frameBuffer.length >= 2) {
|
|
4001
1781
|
const frame = this.parseFrame();
|
|
4002
1782
|
if (!frame) break;
|
|
4003
1783
|
switch (frame.opcode) {
|
|
@@ -4037,8 +1817,18 @@ var WebSocketClient = class extends EventEmitter {
|
|
|
4037
1817
|
offset = 4;
|
|
4038
1818
|
} else if (payloadLength === 127) {
|
|
4039
1819
|
if (this.frameBuffer.length < 10) return null;
|
|
1820
|
+
const high = this.frameBuffer.readUInt32BE(2);
|
|
4040
1821
|
payloadLength = this.frameBuffer.readUInt32BE(6);
|
|
4041
1822
|
offset = 10;
|
|
1823
|
+
if (high !== 0) {
|
|
1824
|
+
payloadLength = Number.POSITIVE_INFINITY;
|
|
1825
|
+
}
|
|
1826
|
+
}
|
|
1827
|
+
if (payloadLength > MAX_FRAME_PAYLOAD) {
|
|
1828
|
+
this.frameBuffer = Buffer.alloc(0);
|
|
1829
|
+
this.close(1009, "Message too big");
|
|
1830
|
+
this.socket.destroy();
|
|
1831
|
+
return null;
|
|
4042
1832
|
}
|
|
4043
1833
|
let maskingKey = null;
|
|
4044
1834
|
if (masked) {
|
|
@@ -4236,6 +2026,10 @@ var WebSocketServer = class extends EventEmitter {
|
|
|
4236
2026
|
this.server.once("error", reject);
|
|
4237
2027
|
this.server.listen(this.port, () => {
|
|
4238
2028
|
this.server.removeListener("error", reject);
|
|
2029
|
+
const address = this.server.address();
|
|
2030
|
+
if (address && typeof address === "object") {
|
|
2031
|
+
this.port = address.port;
|
|
2032
|
+
}
|
|
4239
2033
|
this.emit("listening", { port: this.port });
|
|
4240
2034
|
resolve2();
|
|
4241
2035
|
});
|
|
@@ -4255,6 +2049,14 @@ var WebSocketServer = class extends EventEmitter {
|
|
|
4255
2049
|
});
|
|
4256
2050
|
});
|
|
4257
2051
|
}
|
|
2052
|
+
/**
|
|
2053
|
+
* Get the port the server listens on (the real port after start() when
|
|
2054
|
+
* constructed with port 0)
|
|
2055
|
+
* @returns Port number
|
|
2056
|
+
*/
|
|
2057
|
+
getPort() {
|
|
2058
|
+
return this.port;
|
|
2059
|
+
}
|
|
4258
2060
|
/**
|
|
4259
2061
|
* Broadcast message to all clients
|
|
4260
2062
|
* @param message - Message to broadcast
|
|
@@ -4290,130 +2092,96 @@ var WebSocketServer = class extends EventEmitter {
|
|
|
4290
2092
|
};
|
|
4291
2093
|
function handleBrowserMessages(client, handler) {
|
|
4292
2094
|
client.on("message", (data) => {
|
|
2095
|
+
let message;
|
|
4293
2096
|
try {
|
|
4294
|
-
|
|
4295
|
-
|
|
4296
|
-
|
|
2097
|
+
message = JSON.parse(data);
|
|
2098
|
+
} catch {
|
|
2099
|
+
return;
|
|
2100
|
+
}
|
|
2101
|
+
if (message === null || typeof message !== "object" || typeof message.type !== "string") {
|
|
2102
|
+
return;
|
|
4297
2103
|
}
|
|
2104
|
+
handler(message);
|
|
4298
2105
|
});
|
|
4299
2106
|
}
|
|
4300
|
-
|
|
4301
|
-
|
|
4302
|
-
|
|
4303
|
-
|
|
4304
|
-
|
|
4305
|
-
|
|
4306
|
-
|
|
4307
|
-
|
|
4308
|
-
|
|
4309
|
-
|
|
4310
|
-
|
|
4311
|
-
|
|
4312
|
-
|
|
4313
|
-
injectionScript;
|
|
4314
|
-
/**
|
|
4315
|
-
* Create a new proxy server
|
|
4316
|
-
* @param options - Proxy options
|
|
4317
|
-
*/
|
|
4318
|
-
constructor(options) {
|
|
4319
|
-
super();
|
|
4320
|
-
this.options = options;
|
|
4321
|
-
this.targetUrl = new URL(options.target);
|
|
4322
|
-
this.injectionScript = options.injectionScript ?? this.buildInjectionScript();
|
|
4323
|
-
this.server = createServer((req, res) => {
|
|
4324
|
-
this.handleRequest(req, res).catch((error) => {
|
|
4325
|
-
logger2.error("Request handling error:", error);
|
|
4326
|
-
this.emit("error", error);
|
|
4327
|
-
res.statusCode = 500;
|
|
4328
|
-
res.end("Internal Server Error");
|
|
4329
|
-
});
|
|
4330
|
-
});
|
|
4331
|
-
this.server.on("error", (error) => {
|
|
4332
|
-
this.emit("error", error);
|
|
4333
|
-
});
|
|
4334
|
-
}
|
|
4335
|
-
/**
|
|
4336
|
-
* Build the injection script
|
|
4337
|
-
* @returns Injection script string
|
|
4338
|
-
*/
|
|
4339
|
-
buildInjectionScript() {
|
|
4340
|
-
const { wsPort } = this.options;
|
|
4341
|
-
return `
|
|
4342
|
-
(function() {
|
|
4343
|
-
if (window.__REACTCHECK_INJECTED__) return;
|
|
4344
|
-
window.__REACTCHECK_INJECTED__ = true;
|
|
4345
|
-
window.__REACTCHECK_PORT__ = ${wsPort};
|
|
4346
|
-
|
|
4347
|
-
// Load the main scanner script
|
|
4348
|
-
const script = document.createElement('script');
|
|
4349
|
-
script.src = '/__reactcheck__/scanner.js';
|
|
4350
|
-
script.async = true;
|
|
4351
|
-
document.head.appendChild(script);
|
|
4352
|
-
|
|
4353
|
-
// Fallback: Connect WebSocket directly if script fails to load
|
|
4354
|
-
script.onerror = function() {
|
|
4355
|
-
console.warn('[ReactCheck] Failed to load scanner script, using minimal mode');
|
|
4356
|
-
connectWebSocket();
|
|
4357
|
-
};
|
|
4358
|
-
|
|
4359
|
-
function connectWebSocket() {
|
|
4360
|
-
const ws = new WebSocket('ws://localhost:${wsPort}');
|
|
4361
|
-
|
|
4362
|
-
ws.onopen = function() {
|
|
4363
|
-
ws.send(JSON.stringify({
|
|
4364
|
-
type: 'ready',
|
|
4365
|
-
payload: { reactVersion: detectReactVersion() }
|
|
4366
|
-
}));
|
|
4367
|
-
};
|
|
4368
|
-
|
|
4369
|
-
ws.onmessage = function(event) {
|
|
4370
|
-
try {
|
|
4371
|
-
const msg = JSON.parse(event.data);
|
|
4372
|
-
handleMessage(msg);
|
|
4373
|
-
} catch (e) {}
|
|
4374
|
-
};
|
|
4375
|
-
|
|
4376
|
-
ws.onerror = function(error) {
|
|
4377
|
-
console.error('[ReactCheck] WebSocket error:', error);
|
|
4378
|
-
};
|
|
4379
|
-
|
|
4380
|
-
ws.onclose = function() {
|
|
4381
|
-
// Try to reconnect after 2 seconds
|
|
4382
|
-
setTimeout(connectWebSocket, 2000);
|
|
4383
|
-
};
|
|
2107
|
+
var INJECTION_SCRIPT_FILE = "browser-inject.global.js";
|
|
2108
|
+
function getInjectionScriptCandidates() {
|
|
2109
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
2110
|
+
return [
|
|
2111
|
+
resolve(here, INJECTION_SCRIPT_FILE),
|
|
2112
|
+
resolve(here, "..", INJECTION_SCRIPT_FILE),
|
|
2113
|
+
resolve(here, "..", "..", "dist", INJECTION_SCRIPT_FILE)
|
|
2114
|
+
];
|
|
2115
|
+
}
|
|
2116
|
+
async function loadInjectionScript(wsPort) {
|
|
2117
|
+
const port = Math.trunc(Number(wsPort));
|
|
2118
|
+
if (!Number.isInteger(port) || port < 0 || port > 65535) {
|
|
2119
|
+
throw new RangeError(`Invalid WebSocket port: ${String(wsPort)}`);
|
|
4384
2120
|
}
|
|
4385
|
-
|
|
4386
|
-
|
|
4387
|
-
|
|
4388
|
-
return window.
|
|
4389
|
-
|
|
4390
|
-
|
|
4391
|
-
const renderers = window.__REACT_DEVTOOLS_GLOBAL_HOOK__.renderers;
|
|
4392
|
-
if (renderers && renderers.size > 0) {
|
|
4393
|
-
const renderer = renderers.values().next().value;
|
|
4394
|
-
if (renderer && renderer.version) {
|
|
4395
|
-
return renderer.version;
|
|
4396
|
-
}
|
|
4397
|
-
}
|
|
2121
|
+
for (const candidate of getInjectionScriptCandidates()) {
|
|
2122
|
+
try {
|
|
2123
|
+
const script = await readFile(candidate, "utf8");
|
|
2124
|
+
return `window.__REACTCHECK_PORT__ = ${port};
|
|
2125
|
+
${script}`;
|
|
2126
|
+
} catch {
|
|
4398
2127
|
}
|
|
4399
|
-
return 'unknown';
|
|
4400
2128
|
}
|
|
2129
|
+
throw new Error(
|
|
2130
|
+
`ReactCheck browser script (${INJECTION_SCRIPT_FILE}) not found next to the installed package. Reinstall @oxog/react-check or run "npm run build" when working from source.`
|
|
2131
|
+
);
|
|
2132
|
+
}
|
|
4401
2133
|
|
|
4402
|
-
|
|
4403
|
-
|
|
4404
|
-
|
|
4405
|
-
|
|
4406
|
-
|
|
4407
|
-
|
|
4408
|
-
|
|
4409
|
-
|
|
4410
|
-
|
|
4411
|
-
|
|
4412
|
-
|
|
4413
|
-
|
|
4414
|
-
|
|
4415
|
-
|
|
4416
|
-
|
|
2134
|
+
// src/server/proxy.ts
|
|
2135
|
+
var logger2 = new Logger({ prefix: "proxy", level: 1 /* INFO */ });
|
|
2136
|
+
var SCANNER_SCRIPT_PATH = "/__reactcheck__/scanner.js";
|
|
2137
|
+
function injectScriptTag(html) {
|
|
2138
|
+
const tag = `<script src="${SCANNER_SCRIPT_PATH}"></script>`;
|
|
2139
|
+
if (html.includes(tag)) return html;
|
|
2140
|
+
const head = /<head(?:\s[^>]*)?>/i.exec(html);
|
|
2141
|
+
if (head) {
|
|
2142
|
+
const at = head.index + head[0].length;
|
|
2143
|
+
return html.slice(0, at) + tag + html.slice(at);
|
|
2144
|
+
}
|
|
2145
|
+
const htmlTag = /<html(?:\s[^>]*)?>/i.exec(html);
|
|
2146
|
+
if (htmlTag) {
|
|
2147
|
+
const at = htmlTag.index + htmlTag[0].length;
|
|
2148
|
+
return html.slice(0, at) + tag + html.slice(at);
|
|
2149
|
+
}
|
|
2150
|
+
const doctype = /^\s*<!doctype[^>]*>/i.exec(html);
|
|
2151
|
+
if (doctype) {
|
|
2152
|
+
return doctype[0] + tag + html.slice(doctype[0].length);
|
|
2153
|
+
}
|
|
2154
|
+
return tag + html;
|
|
2155
|
+
}
|
|
2156
|
+
var ProxyServer = class extends EventEmitter {
|
|
2157
|
+
/** HTTP server instance */
|
|
2158
|
+
server;
|
|
2159
|
+
/** Proxy options */
|
|
2160
|
+
options;
|
|
2161
|
+
/** Target URL parsed */
|
|
2162
|
+
targetUrl;
|
|
2163
|
+
/** Injection script (loaded from the bundled browser script on start() when not provided) */
|
|
2164
|
+
injectionScript;
|
|
2165
|
+
/**
|
|
2166
|
+
* Create a new proxy server
|
|
2167
|
+
* @param options - Proxy options
|
|
2168
|
+
*/
|
|
2169
|
+
constructor(options) {
|
|
2170
|
+
super();
|
|
2171
|
+
this.options = options;
|
|
2172
|
+
this.targetUrl = new URL(options.target);
|
|
2173
|
+
this.injectionScript = options.injectionScript ?? null;
|
|
2174
|
+
this.server = createServer((req, res) => {
|
|
2175
|
+
this.handleRequest(req, res).catch((error) => {
|
|
2176
|
+
logger2.error("Request handling error:", error);
|
|
2177
|
+
this.emit("error", error);
|
|
2178
|
+
res.statusCode = 500;
|
|
2179
|
+
res.end("Internal Server Error");
|
|
2180
|
+
});
|
|
2181
|
+
});
|
|
2182
|
+
this.server.on("error", (error) => {
|
|
2183
|
+
this.emit("error", error);
|
|
2184
|
+
});
|
|
4417
2185
|
}
|
|
4418
2186
|
/**
|
|
4419
2187
|
* Handle incoming request
|
|
@@ -4436,12 +2204,13 @@ var ProxyServer = class extends EventEmitter {
|
|
|
4436
2204
|
* @param res - Server response
|
|
4437
2205
|
*/
|
|
4438
2206
|
handleReactCheckRoute(url, res) {
|
|
4439
|
-
if (url ===
|
|
2207
|
+
if (url === SCANNER_SCRIPT_PATH || url.startsWith(`${SCANNER_SCRIPT_PATH}?`)) {
|
|
4440
2208
|
res.writeHead(200, {
|
|
4441
|
-
"Content-Type": "application/javascript",
|
|
4442
|
-
"Cache-Control": "no-cache"
|
|
2209
|
+
"Content-Type": "application/javascript; charset=utf-8",
|
|
2210
|
+
"Cache-Control": "no-cache",
|
|
2211
|
+
"Access-Control-Allow-Origin": "*"
|
|
4443
2212
|
});
|
|
4444
|
-
res.end(
|
|
2213
|
+
res.end(this.injectionScript ?? "");
|
|
4445
2214
|
return;
|
|
4446
2215
|
}
|
|
4447
2216
|
res.writeHead(404);
|
|
@@ -4469,7 +2238,8 @@ var ProxyServer = class extends EventEmitter {
|
|
|
4469
2238
|
};
|
|
4470
2239
|
const proxyReq = requestFn(options, (proxyRes) => {
|
|
4471
2240
|
const contentType = proxyRes.headers["content-type"] ?? "";
|
|
4472
|
-
|
|
2241
|
+
const contentEncoding = String(proxyRes.headers["content-encoding"] ?? "identity").toLowerCase();
|
|
2242
|
+
if (contentType.includes("text/html") && (contentEncoding === "identity" || contentEncoding === "")) {
|
|
4473
2243
|
this.injectAndRespond(proxyRes, res, targetUrl.href);
|
|
4474
2244
|
resolve2();
|
|
4475
2245
|
return;
|
|
@@ -4498,19 +2268,12 @@ var ProxyServer = class extends EventEmitter {
|
|
|
4498
2268
|
});
|
|
4499
2269
|
proxyRes.on("end", () => {
|
|
4500
2270
|
const body = Buffer.concat(chunks).toString("utf-8");
|
|
4501
|
-
|
|
4502
|
-
const scriptTag = `<script>${this.injectionScript}</script>`;
|
|
4503
|
-
if (body.includes("</body>")) {
|
|
4504
|
-
injected = body.replace("</body>", `${scriptTag}</body>`);
|
|
4505
|
-
} else if (body.includes("</head>")) {
|
|
4506
|
-
injected = body.replace("</head>", `${scriptTag}</head>`);
|
|
4507
|
-
} else {
|
|
4508
|
-
injected = body + scriptTag;
|
|
4509
|
-
}
|
|
2271
|
+
const injected = injectScriptTag(body);
|
|
4510
2272
|
this.emit("inject", { url });
|
|
4511
2273
|
const headers = {};
|
|
4512
2274
|
for (const [key, value] of Object.entries(proxyRes.headers)) {
|
|
4513
|
-
|
|
2275
|
+
const lower = key.toLowerCase();
|
|
2276
|
+
if (lower !== "content-length" && lower !== "transfer-encoding" && value !== void 0) {
|
|
4514
2277
|
headers[key] = Array.isArray(value) ? value.join(", ") : value;
|
|
4515
2278
|
}
|
|
4516
2279
|
}
|
|
@@ -4527,11 +2290,18 @@ var ProxyServer = class extends EventEmitter {
|
|
|
4527
2290
|
/**
|
|
4528
2291
|
* Start the proxy server
|
|
4529
2292
|
*/
|
|
4530
|
-
start() {
|
|
2293
|
+
async start() {
|
|
2294
|
+
if (this.injectionScript === null) {
|
|
2295
|
+
this.injectionScript = await loadInjectionScript(this.options.wsPort);
|
|
2296
|
+
}
|
|
4531
2297
|
return new Promise((resolve2, reject) => {
|
|
4532
2298
|
this.server.once("error", reject);
|
|
4533
2299
|
this.server.listen(this.options.port, () => {
|
|
4534
2300
|
this.server.removeListener("error", reject);
|
|
2301
|
+
const address = this.server.address();
|
|
2302
|
+
if (address && typeof address === "object") {
|
|
2303
|
+
this.options.port = address.port;
|
|
2304
|
+
}
|
|
4535
2305
|
this.emit("listening", { port: this.options.port });
|
|
4536
2306
|
logger2.info(`Proxy server listening on http://localhost:${this.options.port}`);
|
|
4537
2307
|
logger2.info(`Proxying to ${this.options.target}`);
|
|
@@ -4566,14 +2336,238 @@ var ProxyServer = class extends EventEmitter {
|
|
|
4566
2336
|
}
|
|
4567
2337
|
};
|
|
4568
2338
|
|
|
4569
|
-
// src/server/
|
|
4570
|
-
|
|
4571
|
-
|
|
4572
|
-
|
|
4573
|
-
|
|
2339
|
+
// src/server/browser.ts
|
|
2340
|
+
var logger3 = new Logger({ prefix: "browser", level: 1 /* INFO */ });
|
|
2341
|
+
var BrowserLauncher = class extends EventEmitter {
|
|
2342
|
+
/** Puppeteer browser instance */
|
|
2343
|
+
browser = null;
|
|
2344
|
+
/** Active page */
|
|
2345
|
+
page = null;
|
|
2346
|
+
/** Launch options */
|
|
2347
|
+
options;
|
|
2348
|
+
/** Injection script */
|
|
2349
|
+
injectionScript = null;
|
|
2350
|
+
/**
|
|
2351
|
+
* Create a new browser launcher
|
|
2352
|
+
* @param options - Launch options
|
|
2353
|
+
*/
|
|
2354
|
+
constructor(options) {
|
|
2355
|
+
super();
|
|
2356
|
+
this.options = {
|
|
2357
|
+
url: options.url,
|
|
2358
|
+
headless: options.headless ?? false,
|
|
2359
|
+
width: options.width ?? 1280,
|
|
2360
|
+
height: options.height ?? 800,
|
|
2361
|
+
wsPort: options.wsPort ?? 3099,
|
|
2362
|
+
args: options.args ?? [],
|
|
2363
|
+
slowMo: options.slowMo ?? 0,
|
|
2364
|
+
timeout: options.timeout ?? 3e4
|
|
2365
|
+
};
|
|
2366
|
+
}
|
|
2367
|
+
/**
|
|
2368
|
+
* Set the injection script
|
|
2369
|
+
* @param script - Script to inject before page loads
|
|
2370
|
+
*/
|
|
2371
|
+
setInjectionScript(script) {
|
|
2372
|
+
this.injectionScript = script;
|
|
2373
|
+
}
|
|
2374
|
+
/**
|
|
2375
|
+
* Launch the browser
|
|
2376
|
+
*/
|
|
2377
|
+
async launch() {
|
|
2378
|
+
try {
|
|
2379
|
+
const puppeteer = await import('puppeteer');
|
|
2380
|
+
const args = [
|
|
2381
|
+
"--no-sandbox",
|
|
2382
|
+
"--disable-setuid-sandbox",
|
|
2383
|
+
"--disable-dev-shm-usage",
|
|
2384
|
+
"--disable-gpu",
|
|
2385
|
+
"--ignore-certificate-errors",
|
|
2386
|
+
"--ignore-certificate-errors-spki-list",
|
|
2387
|
+
`--window-size=${this.options.width},${this.options.height}`,
|
|
2388
|
+
...this.options.args
|
|
2389
|
+
];
|
|
2390
|
+
this.browser = await puppeteer.default.launch({
|
|
2391
|
+
headless: this.options.headless,
|
|
2392
|
+
args,
|
|
2393
|
+
slowMo: this.options.slowMo,
|
|
2394
|
+
defaultViewport: {
|
|
2395
|
+
width: this.options.width,
|
|
2396
|
+
height: this.options.height
|
|
2397
|
+
}
|
|
2398
|
+
});
|
|
2399
|
+
const pages = await this.browser.pages();
|
|
2400
|
+
this.page = pages[0] ?? await this.browser.newPage();
|
|
2401
|
+
this.setupPageHandlers();
|
|
2402
|
+
if (this.injectionScript) {
|
|
2403
|
+
logger3.debug("Injecting ReactCheck script into page...");
|
|
2404
|
+
await this.page.evaluateOnNewDocument(this.injectionScript);
|
|
2405
|
+
logger3.debug("Injection script registered");
|
|
2406
|
+
}
|
|
2407
|
+
this.emit("launched", void 0);
|
|
2408
|
+
logger3.info("Browser launched");
|
|
2409
|
+
await this.navigate(this.options.url);
|
|
2410
|
+
} catch (error) {
|
|
2411
|
+
const err = error instanceof Error ? error : new Error(String(error));
|
|
2412
|
+
this.emit("error", err);
|
|
2413
|
+
throw err;
|
|
2414
|
+
}
|
|
2415
|
+
}
|
|
2416
|
+
/**
|
|
2417
|
+
* Set up page event handlers
|
|
2418
|
+
*/
|
|
2419
|
+
setupPageHandlers() {
|
|
2420
|
+
if (!this.page) return;
|
|
2421
|
+
this.page.on("console", (msg) => {
|
|
2422
|
+
this.emit("console", {
|
|
2423
|
+
type: msg.type(),
|
|
2424
|
+
text: msg.text()
|
|
2425
|
+
});
|
|
2426
|
+
});
|
|
2427
|
+
this.page.on("pageerror", (error) => {
|
|
2428
|
+
this.emit("error", error);
|
|
2429
|
+
});
|
|
2430
|
+
this.page.on("framenavigated", (frame) => {
|
|
2431
|
+
if (frame === this.page?.mainFrame()) {
|
|
2432
|
+
this.emit("navigated", { url: frame.url() });
|
|
2433
|
+
}
|
|
2434
|
+
});
|
|
2435
|
+
this.page.on("load", () => {
|
|
2436
|
+
this.emit("loaded", void 0);
|
|
2437
|
+
});
|
|
2438
|
+
}
|
|
2439
|
+
/**
|
|
2440
|
+
* Navigate to a URL with retry support
|
|
2441
|
+
* @param url - URL to navigate to
|
|
2442
|
+
* @param retries - Number of retries (default: 3)
|
|
2443
|
+
* @param retryDelay - Delay between retries in ms (default: 2000)
|
|
2444
|
+
*/
|
|
2445
|
+
async navigate(url, retries = 3, retryDelay = 2e3) {
|
|
2446
|
+
if (!this.page) {
|
|
2447
|
+
throw new Error("Browser not launched");
|
|
2448
|
+
}
|
|
2449
|
+
let lastError = null;
|
|
2450
|
+
for (let attempt = 1; attempt <= retries; attempt++) {
|
|
2451
|
+
try {
|
|
2452
|
+
await this.page.goto(url, {
|
|
2453
|
+
waitUntil: "networkidle2",
|
|
2454
|
+
timeout: this.options.timeout
|
|
2455
|
+
});
|
|
2456
|
+
this.emit("navigated", { url });
|
|
2457
|
+
logger3.info(`Navigated to ${url}`);
|
|
2458
|
+
return;
|
|
2459
|
+
} catch (error) {
|
|
2460
|
+
lastError = error instanceof Error ? error : new Error(String(error));
|
|
2461
|
+
this.emit("error", lastError);
|
|
2462
|
+
if (lastError.message.includes("ERR_CONNECTION_REFUSED") && attempt < retries) {
|
|
2463
|
+
logger3.warn(`Connection refused, retrying in ${retryDelay}ms... (${attempt}/${retries})`);
|
|
2464
|
+
await new Promise((resolve2) => setTimeout(resolve2, retryDelay));
|
|
2465
|
+
continue;
|
|
2466
|
+
}
|
|
2467
|
+
throw lastError;
|
|
2468
|
+
}
|
|
2469
|
+
}
|
|
2470
|
+
throw lastError ?? new Error("Navigation failed");
|
|
2471
|
+
}
|
|
2472
|
+
/**
|
|
2473
|
+
* Execute script in page context
|
|
2474
|
+
* @param script - Script to execute
|
|
2475
|
+
* @returns Script result
|
|
2476
|
+
*/
|
|
2477
|
+
async evaluate(script) {
|
|
2478
|
+
if (!this.page) {
|
|
2479
|
+
throw new Error("Browser not launched");
|
|
2480
|
+
}
|
|
2481
|
+
return this.page.evaluate(script);
|
|
2482
|
+
}
|
|
2483
|
+
/**
|
|
2484
|
+
* Wait for selector
|
|
2485
|
+
* @param selector - CSS selector
|
|
2486
|
+
* @param timeout - Timeout in ms
|
|
2487
|
+
*/
|
|
2488
|
+
async waitForSelector(selector, timeout) {
|
|
2489
|
+
if (!this.page) {
|
|
2490
|
+
throw new Error("Browser not launched");
|
|
2491
|
+
}
|
|
2492
|
+
await this.page.waitForSelector(selector, {
|
|
2493
|
+
timeout: timeout ?? this.options.timeout
|
|
2494
|
+
});
|
|
2495
|
+
}
|
|
2496
|
+
/**
|
|
2497
|
+
* Take a screenshot
|
|
2498
|
+
* @param path - File path to save screenshot
|
|
2499
|
+
*/
|
|
2500
|
+
async screenshot(path) {
|
|
2501
|
+
if (!this.page) {
|
|
2502
|
+
throw new Error("Browser not launched");
|
|
2503
|
+
}
|
|
2504
|
+
await this.page.screenshot({ path, fullPage: true });
|
|
2505
|
+
logger3.info(`Screenshot saved to ${path}`);
|
|
2506
|
+
}
|
|
2507
|
+
/**
|
|
2508
|
+
* Reload the page
|
|
2509
|
+
*/
|
|
2510
|
+
async reload() {
|
|
2511
|
+
if (!this.page) {
|
|
2512
|
+
throw new Error("Browser not launched");
|
|
2513
|
+
}
|
|
2514
|
+
await this.page.reload({ waitUntil: "networkidle2" });
|
|
2515
|
+
}
|
|
2516
|
+
/**
|
|
2517
|
+
* Get current URL
|
|
2518
|
+
* @returns Current page URL
|
|
2519
|
+
*/
|
|
2520
|
+
getUrl() {
|
|
2521
|
+
return this.page?.url() ?? null;
|
|
2522
|
+
}
|
|
2523
|
+
/**
|
|
2524
|
+
* Close the browser
|
|
2525
|
+
*/
|
|
2526
|
+
async close() {
|
|
2527
|
+
if (this.browser) {
|
|
2528
|
+
await this.browser.close();
|
|
2529
|
+
this.browser = null;
|
|
2530
|
+
this.page = null;
|
|
2531
|
+
this.emit("closed", void 0);
|
|
2532
|
+
logger3.info("Browser closed");
|
|
2533
|
+
}
|
|
2534
|
+
}
|
|
2535
|
+
/**
|
|
2536
|
+
* Check if browser is open
|
|
2537
|
+
* @returns true if browser is open
|
|
2538
|
+
*/
|
|
2539
|
+
isOpen() {
|
|
2540
|
+
return this.browser !== null && this.browser.connected;
|
|
2541
|
+
}
|
|
2542
|
+
/**
|
|
2543
|
+
* Get the page instance (for advanced usage)
|
|
2544
|
+
* @returns Puppeteer page or null
|
|
2545
|
+
*/
|
|
2546
|
+
getPage() {
|
|
2547
|
+
return this.page;
|
|
2548
|
+
}
|
|
2549
|
+
/**
|
|
2550
|
+
* Get the browser instance (for advanced usage)
|
|
2551
|
+
* @returns Puppeteer browser or null
|
|
2552
|
+
*/
|
|
2553
|
+
getBrowser() {
|
|
2554
|
+
return this.browser;
|
|
2555
|
+
}
|
|
2556
|
+
};
|
|
2557
|
+
async function isPuppeteerAvailable() {
|
|
2558
|
+
try {
|
|
2559
|
+
await import('puppeteer');
|
|
2560
|
+
return true;
|
|
2561
|
+
} catch {
|
|
2562
|
+
return false;
|
|
2563
|
+
}
|
|
2564
|
+
}
|
|
4574
2565
|
|
|
4575
2566
|
// src/browser/overlay.ts
|
|
4576
|
-
|
|
2567
|
+
function escapeOverlayHtml(value) {
|
|
2568
|
+
return String(value).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
2569
|
+
}
|
|
2570
|
+
var DEFAULT_CONFIG = {
|
|
4577
2571
|
enabled: true,
|
|
4578
2572
|
highlightRenders: true,
|
|
4579
2573
|
showToolbar: true,
|
|
@@ -4622,10 +2616,14 @@ var Overlay = class _Overlay {
|
|
|
4622
2616
|
* @param config - Overlay configuration
|
|
4623
2617
|
*/
|
|
4624
2618
|
constructor(config = {}) {
|
|
4625
|
-
this.config = { ...
|
|
2619
|
+
this.config = { ...DEFAULT_CONFIG, ...config };
|
|
4626
2620
|
}
|
|
4627
2621
|
/** Retry count for init */
|
|
4628
2622
|
initRetryCount = 0;
|
|
2623
|
+
/** Pending init retry timer (document.body not ready yet) */
|
|
2624
|
+
initRetryTimer = null;
|
|
2625
|
+
/** Aborts document-level listeners (drag handling) on destroy */
|
|
2626
|
+
documentListeners = null;
|
|
4629
2627
|
/**
|
|
4630
2628
|
* Initialize the overlay
|
|
4631
2629
|
*/
|
|
@@ -4634,9 +2632,12 @@ var Overlay = class _Overlay {
|
|
|
4634
2632
|
return;
|
|
4635
2633
|
}
|
|
4636
2634
|
if (!document.body) {
|
|
4637
|
-
if (this.initRetryCount < 10) {
|
|
2635
|
+
if (this.initRetryCount < 10 && this.initRetryTimer === null) {
|
|
4638
2636
|
this.initRetryCount++;
|
|
4639
|
-
setTimeout(() =>
|
|
2637
|
+
this.initRetryTimer = setTimeout(() => {
|
|
2638
|
+
this.initRetryTimer = null;
|
|
2639
|
+
this.init();
|
|
2640
|
+
}, 100);
|
|
4640
2641
|
}
|
|
4641
2642
|
return;
|
|
4642
2643
|
}
|
|
@@ -4667,6 +2668,14 @@ var Overlay = class _Overlay {
|
|
|
4667
2668
|
* Destroy the overlay
|
|
4668
2669
|
*/
|
|
4669
2670
|
destroy() {
|
|
2671
|
+
if (this.initRetryTimer !== null) {
|
|
2672
|
+
clearTimeout(this.initRetryTimer);
|
|
2673
|
+
this.initRetryTimer = null;
|
|
2674
|
+
}
|
|
2675
|
+
if (this.documentListeners) {
|
|
2676
|
+
this.documentListeners.abort();
|
|
2677
|
+
this.documentListeners = null;
|
|
2678
|
+
}
|
|
4670
2679
|
if (this.statsInterval) {
|
|
4671
2680
|
clearInterval(this.statsInterval);
|
|
4672
2681
|
this.statsInterval = null;
|
|
@@ -5601,6 +3610,8 @@ var Overlay = class _Overlay {
|
|
|
5601
3610
|
initialX = element.offsetLeft;
|
|
5602
3611
|
initialY = element.offsetTop;
|
|
5603
3612
|
});
|
|
3613
|
+
this.documentListeners ??= new AbortController();
|
|
3614
|
+
const { signal } = this.documentListeners;
|
|
5604
3615
|
document.addEventListener("mousemove", (e) => {
|
|
5605
3616
|
if (!isDragging) return;
|
|
5606
3617
|
const dx = e.clientX - startX;
|
|
@@ -5608,10 +3619,10 @@ var Overlay = class _Overlay {
|
|
|
5608
3619
|
element.style.left = `${initialX + dx}px`;
|
|
5609
3620
|
element.style.top = `${initialY + dy}px`;
|
|
5610
3621
|
element.style.right = "auto";
|
|
5611
|
-
});
|
|
3622
|
+
}, { signal });
|
|
5612
3623
|
document.addEventListener("mouseup", () => {
|
|
5613
3624
|
isDragging = false;
|
|
5614
|
-
});
|
|
3625
|
+
}, { signal });
|
|
5615
3626
|
}
|
|
5616
3627
|
/** Maximum number of highlights to show at once */
|
|
5617
3628
|
static MAX_HIGHLIGHTS = 50;
|
|
@@ -5886,7 +3897,7 @@ var Overlay = class _Overlay {
|
|
|
5886
3897
|
<div class="component-item">
|
|
5887
3898
|
<div class="component-severity" style="background: ${color}"></div>
|
|
5888
3899
|
<div class="component-info">
|
|
5889
|
-
<div class="component-name">${name}</div>
|
|
3900
|
+
<div class="component-name">${escapeOverlayHtml(name)}</div>
|
|
5890
3901
|
<div class="component-meta">${avgTime}ms avg \xB7 ${timeStr}</div>
|
|
5891
3902
|
</div>
|
|
5892
3903
|
<div class="component-count" style="color: ${color}">${tracked.count}</div>
|
|
@@ -5911,11 +3922,11 @@ var Overlay = class _Overlay {
|
|
|
5911
3922
|
return;
|
|
5912
3923
|
}
|
|
5913
3924
|
list.innerHTML = this.renderChains.slice(0, 10).map((chain) => {
|
|
5914
|
-
const flow = chain.chain.map((c) => `<span class="chain-node">${c}</span>`).join('<span class="chain-arrow">\u2192</span>');
|
|
3925
|
+
const flow = chain.chain.map((c) => `<span class="chain-node">${escapeOverlayHtml(c)}</span>`).join('<span class="chain-arrow">\u2192</span>');
|
|
5915
3926
|
return `
|
|
5916
3927
|
<div class="chain-item">
|
|
5917
3928
|
<div class="chain-header">
|
|
5918
|
-
<span class="chain-trigger">${chain.trigger}</span>
|
|
3929
|
+
<span class="chain-trigger">${escapeOverlayHtml(chain.trigger)}</span>
|
|
5919
3930
|
<span class="chain-count">${chain.chain.length} components</span>
|
|
5920
3931
|
</div>
|
|
5921
3932
|
<div class="chain-flow">${flow}</div>
|
|
@@ -5995,7 +4006,7 @@ var Overlay = class _Overlay {
|
|
|
5995
4006
|
};
|
|
5996
4007
|
|
|
5997
4008
|
// src/browser/scanner.ts
|
|
5998
|
-
var
|
|
4009
|
+
var DEFAULT_CONFIG2 = {
|
|
5999
4010
|
trackUnnecessary: true,
|
|
6000
4011
|
fpsThreshold: 30,
|
|
6001
4012
|
highlightRenders: true,
|
|
@@ -6008,8 +4019,6 @@ var BrowserScanner = class extends EventEmitter {
|
|
|
6008
4019
|
running = false;
|
|
6009
4020
|
/** React version detected */
|
|
6010
4021
|
reactVersion = "unknown";
|
|
6011
|
-
/** Previous fiber states for comparison */
|
|
6012
|
-
prevFiberStates = /* @__PURE__ */ new WeakMap();
|
|
6013
4022
|
/** Component render counts */
|
|
6014
4023
|
renderCounts = /* @__PURE__ */ new Map();
|
|
6015
4024
|
/** Original DevTools hook methods */
|
|
@@ -6025,7 +4034,7 @@ var BrowserScanner = class extends EventEmitter {
|
|
|
6025
4034
|
*/
|
|
6026
4035
|
constructor(config = {}, win) {
|
|
6027
4036
|
super();
|
|
6028
|
-
this.config = { ...
|
|
4037
|
+
this.config = { ...DEFAULT_CONFIG2, ...config };
|
|
6029
4038
|
this.win = win ?? (typeof window !== "undefined" ? window : {});
|
|
6030
4039
|
}
|
|
6031
4040
|
/**
|
|
@@ -6036,6 +4045,9 @@ var BrowserScanner = class extends EventEmitter {
|
|
|
6036
4045
|
* @returns DOM Element or null
|
|
6037
4046
|
*/
|
|
6038
4047
|
getDOMElement(fiber) {
|
|
4048
|
+
if (typeof Element === "undefined") {
|
|
4049
|
+
return null;
|
|
4050
|
+
}
|
|
6039
4051
|
if (fiber.stateNode instanceof Element) {
|
|
6040
4052
|
return fiber.stateNode;
|
|
6041
4053
|
}
|
|
@@ -6112,7 +4124,6 @@ var BrowserScanner = class extends EventEmitter {
|
|
|
6112
4124
|
*/
|
|
6113
4125
|
reset() {
|
|
6114
4126
|
this.renderCounts.clear();
|
|
6115
|
-
this.prevFiberStates = /* @__PURE__ */ new WeakMap();
|
|
6116
4127
|
}
|
|
6117
4128
|
/**
|
|
6118
4129
|
* Hook into React DevTools global hook
|
|
@@ -6123,12 +4134,13 @@ var BrowserScanner = class extends EventEmitter {
|
|
|
6123
4134
|
this.installHook();
|
|
6124
4135
|
return;
|
|
6125
4136
|
}
|
|
6126
|
-
|
|
4137
|
+
const original = hook.onCommitFiberRoot;
|
|
4138
|
+
this.originalOnCommitFiberRoot = original;
|
|
6127
4139
|
hook.onCommitFiberRoot = (rendererID, root, priorityLevel) => {
|
|
6128
|
-
|
|
6129
|
-
|
|
4140
|
+
original.call(hook, rendererID, root, priorityLevel);
|
|
4141
|
+
if (this.running) {
|
|
4142
|
+
this.processCommit(root.current);
|
|
6130
4143
|
}
|
|
6131
|
-
this.processCommit(root.current);
|
|
6132
4144
|
};
|
|
6133
4145
|
this.reactVersion = this.detectReactVersion(hook);
|
|
6134
4146
|
this.emit("ready", { reactVersion: this.reactVersion });
|
|
@@ -6146,7 +4158,9 @@ var BrowserScanner = class extends EventEmitter {
|
|
|
6146
4158
|
return id;
|
|
6147
4159
|
},
|
|
6148
4160
|
onCommitFiberRoot: (_rendererID, root, _priorityLevel) => {
|
|
6149
|
-
this.
|
|
4161
|
+
if (this.running) {
|
|
4162
|
+
this.processCommit(root.current);
|
|
4163
|
+
}
|
|
6150
4164
|
},
|
|
6151
4165
|
onCommitFiberUnmount: () => {
|
|
6152
4166
|
}
|
|
@@ -6180,25 +4194,37 @@ var BrowserScanner = class extends EventEmitter {
|
|
|
6180
4194
|
return "unknown";
|
|
6181
4195
|
}
|
|
6182
4196
|
/**
|
|
6183
|
-
* Process a fiber commit (public for IIFE hook integration)
|
|
6184
|
-
*
|
|
4197
|
+
* Process a fiber commit (public for IIFE hook integration).
|
|
4198
|
+
*
|
|
4199
|
+
* Only components that actually rendered in this commit are reported: React
|
|
4200
|
+
* reuses untouched subtrees (their `child` pointer is shared with the
|
|
4201
|
+
* alternate) and bailed-out components do not get the `PerformedWork` flag.
|
|
4202
|
+
* @param rootFiber - Root fiber of the committed tree (`root.current`)
|
|
6185
4203
|
*/
|
|
6186
4204
|
processCommit(rootFiber) {
|
|
6187
|
-
|
|
6188
|
-
|
|
6189
|
-
|
|
6190
|
-
|
|
6191
|
-
|
|
6192
|
-
|
|
6193
|
-
|
|
6194
|
-
|
|
6195
|
-
|
|
6196
|
-
|
|
6197
|
-
|
|
6198
|
-
|
|
4205
|
+
const stack = [{ fiber: rootFiber, parent: null }];
|
|
4206
|
+
while (stack.length > 0) {
|
|
4207
|
+
const item = stack.pop();
|
|
4208
|
+
if (!item) continue;
|
|
4209
|
+
const { fiber } = item;
|
|
4210
|
+
let parent = item.parent;
|
|
4211
|
+
if (fiber.sibling) {
|
|
4212
|
+
stack.push({ fiber: fiber.sibling, parent: item.parent });
|
|
4213
|
+
}
|
|
4214
|
+
if (isUserComponent(fiber)) {
|
|
4215
|
+
if (fiber.tag !== FiberTag.MemoComponent && didFiberRender(fiber)) {
|
|
4216
|
+
this.processFiber(fiber, parent);
|
|
4217
|
+
}
|
|
4218
|
+
parent = getComponentName(fiber);
|
|
4219
|
+
}
|
|
4220
|
+
const alternate = fiber.alternate;
|
|
4221
|
+
if (alternate && fiber !== rootFiber && fiber.child === alternate.child) {
|
|
4222
|
+
continue;
|
|
4223
|
+
}
|
|
4224
|
+
if (fiber.child) {
|
|
4225
|
+
stack.push({ fiber: fiber.child, parent });
|
|
4226
|
+
}
|
|
6199
4227
|
}
|
|
6200
|
-
this.walkFiber(fiber.child, parent);
|
|
6201
|
-
this.walkFiber(fiber.sibling, parent);
|
|
6202
4228
|
}
|
|
6203
4229
|
/**
|
|
6204
4230
|
* Process a single fiber
|
|
@@ -6210,22 +4236,18 @@ var BrowserScanner = class extends EventEmitter {
|
|
|
6210
4236
|
if (this.shouldFilterComponent(componentName)) {
|
|
6211
4237
|
return;
|
|
6212
4238
|
}
|
|
6213
|
-
const
|
|
6214
|
-
const phase =
|
|
4239
|
+
const alternate = fiber.alternate ?? null;
|
|
4240
|
+
const phase = alternate ? "update" : "mount";
|
|
6215
4241
|
const renderInfo = createRenderInfo(
|
|
6216
4242
|
fiber,
|
|
6217
4243
|
phase,
|
|
6218
|
-
|
|
6219
|
-
|
|
4244
|
+
alternate ? alternate.memoizedProps ?? {} : null,
|
|
4245
|
+
alternate ? alternate.memoizedState : void 0
|
|
6220
4246
|
);
|
|
6221
4247
|
const currentCount = this.renderCounts.get(componentName) ?? 0;
|
|
6222
4248
|
const newCount = currentCount + 1;
|
|
6223
4249
|
this.renderCounts.set(componentName, newCount);
|
|
6224
4250
|
renderInfo.renderCount = newCount;
|
|
6225
|
-
this.prevFiberStates.set(fiber, {
|
|
6226
|
-
props: fiber.memoizedProps,
|
|
6227
|
-
state: fiber.memoizedState
|
|
6228
|
-
});
|
|
6229
4251
|
const domElement = this.getDOMElement(fiber);
|
|
6230
4252
|
if (this.overlay && this.config.highlightRenders) {
|
|
6231
4253
|
if (domElement) {
|
|
@@ -6264,13 +4286,7 @@ var BrowserScanner = class extends EventEmitter {
|
|
|
6264
4286
|
* @returns true if matches
|
|
6265
4287
|
*/
|
|
6266
4288
|
matchPattern(name, pattern) {
|
|
6267
|
-
|
|
6268
|
-
try {
|
|
6269
|
-
const regex = new RegExp(`^${regexPattern}$`);
|
|
6270
|
-
return regex.test(name);
|
|
6271
|
-
} catch {
|
|
6272
|
-
return false;
|
|
6273
|
-
}
|
|
4289
|
+
return matchComponentPattern(name, pattern);
|
|
6274
4290
|
}
|
|
6275
4291
|
/**
|
|
6276
4292
|
* Get current configuration
|
|
@@ -6317,7 +4333,10 @@ var BrowserScanner = class extends EventEmitter {
|
|
|
6317
4333
|
}
|
|
6318
4334
|
};
|
|
6319
4335
|
|
|
6320
|
-
// src/browser/
|
|
4336
|
+
// src/browser/injector.ts
|
|
4337
|
+
var MAX_QUEUED_MESSAGES = 5e3;
|
|
4338
|
+
var MAX_PENDING_COMMITS = 500;
|
|
4339
|
+
var RECONNECT_DELAY_MS = 2e3;
|
|
6321
4340
|
var ReactCheckInjector = class {
|
|
6322
4341
|
/** Browser scanner instance */
|
|
6323
4342
|
scanner;
|
|
@@ -6331,36 +4350,69 @@ var ReactCheckInjector = class {
|
|
|
6331
4350
|
reconnectTimeout = null;
|
|
6332
4351
|
/** Whether initialized */
|
|
6333
4352
|
initialized = false;
|
|
4353
|
+
/** Whether destroyed (no more reconnects, commits are ignored) */
|
|
4354
|
+
destroyed = false;
|
|
4355
|
+
/** Whether commit processing is paused (CLI sent `stop`) */
|
|
4356
|
+
paused = false;
|
|
4357
|
+
/** Commits received before `init()` */
|
|
4358
|
+
pendingCommits = [];
|
|
4359
|
+
/** Message queue for messages sent before connection */
|
|
4360
|
+
messageQueue = [];
|
|
4361
|
+
/** requestAnimationFrame handle for FPS measurement */
|
|
4362
|
+
rafHandle = null;
|
|
4363
|
+
/** Restores the React DevTools hook to its state before installation */
|
|
4364
|
+
restoreHook = null;
|
|
4365
|
+
/** Window reference */
|
|
4366
|
+
win;
|
|
6334
4367
|
/**
|
|
6335
4368
|
* Create the injector
|
|
4369
|
+
* @param win - Window object (defaults to the global window)
|
|
6336
4370
|
*/
|
|
6337
|
-
constructor() {
|
|
6338
|
-
|
|
6339
|
-
this.wsPort = win.__REACTCHECK_PORT__ ?? 3099;
|
|
4371
|
+
constructor(win) {
|
|
4372
|
+
this.win = win ?? window;
|
|
4373
|
+
this.wsPort = this.win.__REACTCHECK_PORT__ ?? 3099;
|
|
6340
4374
|
this.scanner = new BrowserScanner({
|
|
6341
4375
|
trackUnnecessary: true,
|
|
6342
4376
|
highlightRenders: true,
|
|
6343
4377
|
animationSpeed: "fast"
|
|
6344
|
-
}, win);
|
|
4378
|
+
}, this.win);
|
|
6345
4379
|
this.overlay = new Overlay({
|
|
6346
4380
|
enabled: true,
|
|
6347
4381
|
highlightRenders: true,
|
|
6348
4382
|
showToolbar: true
|
|
6349
4383
|
});
|
|
6350
4384
|
}
|
|
4385
|
+
/**
|
|
4386
|
+
* Feed a committed fiber root to the scanner. Called from the React DevTools
|
|
4387
|
+
* hook installed by {@link installReactCheck}.
|
|
4388
|
+
* @param root - Fiber root passed to `onCommitFiberRoot`
|
|
4389
|
+
*/
|
|
4390
|
+
handleCommit(root) {
|
|
4391
|
+
if (this.destroyed || this.paused || !root?.current) return;
|
|
4392
|
+
if (!this.initialized) {
|
|
4393
|
+
if (this.pendingCommits.length >= MAX_PENDING_COMMITS) {
|
|
4394
|
+
this.pendingCommits.shift();
|
|
4395
|
+
}
|
|
4396
|
+
this.pendingCommits.push(root.current);
|
|
4397
|
+
return;
|
|
4398
|
+
}
|
|
4399
|
+
this.scanner.processCommit(root.current);
|
|
4400
|
+
}
|
|
6351
4401
|
/**
|
|
6352
4402
|
* Initialize the injector
|
|
6353
4403
|
*/
|
|
6354
4404
|
init() {
|
|
6355
|
-
if (this.initialized) return;
|
|
4405
|
+
if (this.initialized || this.destroyed) return;
|
|
6356
4406
|
this.initialized = true;
|
|
6357
4407
|
this.overlay.init();
|
|
6358
4408
|
this.setupScannerEvents();
|
|
6359
4409
|
this.connect();
|
|
6360
|
-
const
|
|
6361
|
-
|
|
6362
|
-
|
|
4410
|
+
const pending = this.pendingCommits;
|
|
4411
|
+
this.pendingCommits = [];
|
|
4412
|
+
for (const fiber of pending) {
|
|
4413
|
+
this.scanner.processCommit(fiber);
|
|
6363
4414
|
}
|
|
4415
|
+
this.startFpsMeasurement();
|
|
6364
4416
|
console.log("[ReactCheck] Initialized");
|
|
6365
4417
|
}
|
|
6366
4418
|
/**
|
|
@@ -6384,16 +4436,46 @@ var ReactCheckInjector = class {
|
|
|
6384
4436
|
});
|
|
6385
4437
|
});
|
|
6386
4438
|
}
|
|
4439
|
+
/**
|
|
4440
|
+
* Measure frames per second with requestAnimationFrame and report it
|
|
4441
|
+
*/
|
|
4442
|
+
startFpsMeasurement() {
|
|
4443
|
+
const raf = this.win.requestAnimationFrame;
|
|
4444
|
+
if (typeof raf !== "function") return;
|
|
4445
|
+
let frames = 0;
|
|
4446
|
+
let windowStart = Date.now();
|
|
4447
|
+
const tick = () => {
|
|
4448
|
+
if (this.destroyed) return;
|
|
4449
|
+
frames++;
|
|
4450
|
+
const now = Date.now();
|
|
4451
|
+
const elapsed = now - windowStart;
|
|
4452
|
+
if (elapsed >= 1e3) {
|
|
4453
|
+
const fps = Math.round(frames * 1e3 / elapsed);
|
|
4454
|
+
frames = 0;
|
|
4455
|
+
windowStart = now;
|
|
4456
|
+
this.overlay.updateFps(fps);
|
|
4457
|
+
if (!this.paused) {
|
|
4458
|
+
this.send({ type: "fps", payload: fps });
|
|
4459
|
+
}
|
|
4460
|
+
}
|
|
4461
|
+
this.rafHandle = raf.call(this.win, tick);
|
|
4462
|
+
};
|
|
4463
|
+
this.rafHandle = raf.call(this.win, tick);
|
|
4464
|
+
}
|
|
6387
4465
|
/**
|
|
6388
4466
|
* Connect to CLI WebSocket server
|
|
6389
4467
|
*/
|
|
6390
4468
|
connect() {
|
|
4469
|
+
if (this.destroyed) return;
|
|
6391
4470
|
if (this.ws) {
|
|
4471
|
+
this.detachSocket(this.ws);
|
|
6392
4472
|
this.ws.close();
|
|
4473
|
+
this.ws = null;
|
|
6393
4474
|
}
|
|
6394
4475
|
try {
|
|
6395
|
-
|
|
6396
|
-
this.ws
|
|
4476
|
+
const ws = new WebSocket(`ws://localhost:${this.wsPort}`);
|
|
4477
|
+
this.ws = ws;
|
|
4478
|
+
ws.onopen = () => {
|
|
6397
4479
|
console.log("[ReactCheck] Connected to CLI");
|
|
6398
4480
|
if (this.reconnectTimeout) {
|
|
6399
4481
|
clearTimeout(this.reconnectTimeout);
|
|
@@ -6405,7 +4487,7 @@ var ReactCheckInjector = class {
|
|
|
6405
4487
|
});
|
|
6406
4488
|
this.flushMessageQueue();
|
|
6407
4489
|
};
|
|
6408
|
-
|
|
4490
|
+
ws.onmessage = (event) => {
|
|
6409
4491
|
try {
|
|
6410
4492
|
const message = JSON.parse(event.data);
|
|
6411
4493
|
this.handleMessage(message);
|
|
@@ -6413,10 +4495,10 @@ var ReactCheckInjector = class {
|
|
|
6413
4495
|
console.warn("[ReactCheck] Invalid message:", error);
|
|
6414
4496
|
}
|
|
6415
4497
|
};
|
|
6416
|
-
|
|
4498
|
+
ws.onerror = (error) => {
|
|
6417
4499
|
console.warn("[ReactCheck] WebSocket error:", error);
|
|
6418
4500
|
};
|
|
6419
|
-
|
|
4501
|
+
ws.onclose = () => {
|
|
6420
4502
|
console.log("[ReactCheck] Disconnected from CLI");
|
|
6421
4503
|
this.scheduleReconnect();
|
|
6422
4504
|
};
|
|
@@ -6425,16 +4507,28 @@ var ReactCheckInjector = class {
|
|
|
6425
4507
|
this.scheduleReconnect();
|
|
6426
4508
|
}
|
|
6427
4509
|
}
|
|
4510
|
+
/**
|
|
4511
|
+
* Remove event handlers from a socket so that closing it does not trigger
|
|
4512
|
+
* reconnects
|
|
4513
|
+
* @param ws - Socket
|
|
4514
|
+
*/
|
|
4515
|
+
detachSocket(ws) {
|
|
4516
|
+
ws.onopen = null;
|
|
4517
|
+
ws.onmessage = null;
|
|
4518
|
+
ws.onerror = null;
|
|
4519
|
+
ws.onclose = null;
|
|
4520
|
+
}
|
|
6428
4521
|
/**
|
|
6429
4522
|
* Schedule a reconnection attempt
|
|
6430
4523
|
*/
|
|
6431
4524
|
scheduleReconnect() {
|
|
6432
|
-
if (this.reconnectTimeout) return;
|
|
4525
|
+
if (this.reconnectTimeout || this.destroyed) return;
|
|
6433
4526
|
this.reconnectTimeout = setTimeout(() => {
|
|
6434
4527
|
this.reconnectTimeout = null;
|
|
4528
|
+
if (this.destroyed) return;
|
|
6435
4529
|
console.log("[ReactCheck] Attempting to reconnect...");
|
|
6436
4530
|
this.connect();
|
|
6437
|
-
},
|
|
4531
|
+
}, RECONNECT_DELAY_MS);
|
|
6438
4532
|
}
|
|
6439
4533
|
/**
|
|
6440
4534
|
* Handle message from CLI
|
|
@@ -6443,11 +4537,11 @@ var ReactCheckInjector = class {
|
|
|
6443
4537
|
handleMessage(message) {
|
|
6444
4538
|
switch (message.type) {
|
|
6445
4539
|
case "start":
|
|
6446
|
-
this.
|
|
4540
|
+
this.paused = false;
|
|
6447
4541
|
this.overlay.show();
|
|
6448
4542
|
break;
|
|
6449
4543
|
case "stop":
|
|
6450
|
-
this.
|
|
4544
|
+
this.paused = true;
|
|
6451
4545
|
break;
|
|
6452
4546
|
case "reset":
|
|
6453
4547
|
this.scanner.reset();
|
|
@@ -6502,16 +4596,18 @@ var ReactCheckInjector = class {
|
|
|
6502
4596
|
this.overlay.configure({ highlightRenders: config.highlightRenders });
|
|
6503
4597
|
}
|
|
6504
4598
|
}
|
|
6505
|
-
/** Message queue for messages sent before connection */
|
|
6506
|
-
messageQueue = [];
|
|
6507
4599
|
/**
|
|
6508
4600
|
* Send message to CLI
|
|
6509
4601
|
* @param message - Browser message
|
|
6510
4602
|
*/
|
|
6511
4603
|
send(message) {
|
|
4604
|
+
if (this.destroyed) return;
|
|
6512
4605
|
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
|
|
6513
4606
|
this.ws.send(JSON.stringify(message));
|
|
6514
4607
|
} else {
|
|
4608
|
+
if (this.messageQueue.length >= MAX_QUEUED_MESSAGES) {
|
|
4609
|
+
this.messageQueue.shift();
|
|
4610
|
+
}
|
|
6515
4611
|
this.messageQueue.push(message);
|
|
6516
4612
|
}
|
|
6517
4613
|
}
|
|
@@ -6527,160 +4623,242 @@ var ReactCheckInjector = class {
|
|
|
6527
4623
|
}
|
|
6528
4624
|
}
|
|
6529
4625
|
/**
|
|
6530
|
-
*
|
|
4626
|
+
* Register a function that restores the DevTools hook on destroy
|
|
4627
|
+
* @param restore - Restore callback
|
|
4628
|
+
*/
|
|
4629
|
+
setHookRestorer(restore) {
|
|
4630
|
+
this.restoreHook = restore;
|
|
4631
|
+
}
|
|
4632
|
+
/**
|
|
4633
|
+
* Destroy the injector: stops reconnecting, closes the socket, restores the
|
|
4634
|
+
* React DevTools hook, removes the overlay and cancels all timers.
|
|
6531
4635
|
*/
|
|
6532
4636
|
destroy() {
|
|
4637
|
+
if (this.destroyed) return;
|
|
4638
|
+
this.destroyed = true;
|
|
6533
4639
|
if (this.reconnectTimeout) {
|
|
6534
4640
|
clearTimeout(this.reconnectTimeout);
|
|
4641
|
+
this.reconnectTimeout = null;
|
|
4642
|
+
}
|
|
4643
|
+
if (this.rafHandle !== null) {
|
|
4644
|
+
const caf = this.win.cancelAnimationFrame;
|
|
4645
|
+
if (typeof caf === "function") {
|
|
4646
|
+
caf.call(this.win, this.rafHandle);
|
|
4647
|
+
}
|
|
4648
|
+
this.rafHandle = null;
|
|
6535
4649
|
}
|
|
6536
4650
|
if (this.ws) {
|
|
4651
|
+
this.detachSocket(this.ws);
|
|
6537
4652
|
this.ws.close();
|
|
4653
|
+
this.ws = null;
|
|
6538
4654
|
}
|
|
4655
|
+
if (this.restoreHook) {
|
|
4656
|
+
this.restoreHook();
|
|
4657
|
+
this.restoreHook = null;
|
|
4658
|
+
}
|
|
4659
|
+
this.pendingCommits = [];
|
|
4660
|
+
this.messageQueue = [];
|
|
6539
4661
|
this.scanner.stop();
|
|
4662
|
+
this.scanner.removeAllListeners();
|
|
6540
4663
|
this.overlay.destroy();
|
|
6541
4664
|
this.initialized = false;
|
|
6542
4665
|
}
|
|
6543
4666
|
};
|
|
6544
|
-
|
|
6545
|
-
const currentUrl =
|
|
4667
|
+
function installReactCheck(win) {
|
|
4668
|
+
const currentUrl = win.location.href;
|
|
6546
4669
|
if (currentUrl === "about:blank" || currentUrl.startsWith("chrome://") || currentUrl.startsWith("chrome-extension://") || currentUrl.startsWith("devtools://")) {
|
|
6547
|
-
return;
|
|
4670
|
+
return null;
|
|
6548
4671
|
}
|
|
6549
|
-
const win = window;
|
|
6550
4672
|
if (win.__REACTCHECK_INJECTED__) {
|
|
6551
|
-
return;
|
|
4673
|
+
return null;
|
|
6552
4674
|
}
|
|
6553
4675
|
win.__REACTCHECK_INJECTED__ = true;
|
|
6554
|
-
const injector = new ReactCheckInjector();
|
|
6555
|
-
const
|
|
6556
|
-
|
|
6557
|
-
const handleCommit = (root) => {
|
|
6558
|
-
if (injectorReady) {
|
|
6559
|
-
const scanner = injector.scanner;
|
|
6560
|
-
if (scanner) {
|
|
6561
|
-
const fiber = root.current;
|
|
6562
|
-
scanner.processCommit(fiber);
|
|
6563
|
-
}
|
|
6564
|
-
} else {
|
|
6565
|
-
pendingCommits.push({ rendererID: 0, root });
|
|
6566
|
-
}
|
|
6567
|
-
};
|
|
6568
|
-
const processPendingCommits = () => {
|
|
6569
|
-
injectorReady = true;
|
|
6570
|
-
const scanner = injector.scanner;
|
|
6571
|
-
if (scanner) {
|
|
6572
|
-
for (const { root } of pendingCommits) {
|
|
6573
|
-
scanner.processCommit(root.current);
|
|
6574
|
-
}
|
|
6575
|
-
pendingCommits.length = 0;
|
|
6576
|
-
}
|
|
6577
|
-
};
|
|
6578
|
-
if (!win.__REACT_DEVTOOLS_GLOBAL_HOOK__) {
|
|
4676
|
+
const injector = new ReactCheckInjector(win);
|
|
4677
|
+
const existingHook = win.__REACT_DEVTOOLS_GLOBAL_HOOK__;
|
|
4678
|
+
if (!existingHook) {
|
|
6579
4679
|
const hook = {
|
|
6580
4680
|
renderers: /* @__PURE__ */ new Map(),
|
|
6581
4681
|
supportsFiber: true,
|
|
6582
|
-
inject
|
|
6583
|
-
const id =
|
|
6584
|
-
|
|
4682
|
+
inject(renderer) {
|
|
4683
|
+
const id = hook.renderers.size + 1;
|
|
4684
|
+
hook.renderers.set(id, renderer);
|
|
6585
4685
|
return id;
|
|
6586
4686
|
},
|
|
6587
|
-
onCommitFiberRoot
|
|
6588
|
-
handleCommit(root);
|
|
4687
|
+
onCommitFiberRoot(_rendererID, root) {
|
|
4688
|
+
injector.handleCommit(root);
|
|
6589
4689
|
},
|
|
6590
|
-
onCommitFiberUnmount
|
|
4690
|
+
onCommitFiberUnmount() {
|
|
6591
4691
|
}
|
|
6592
4692
|
};
|
|
6593
4693
|
win.__REACT_DEVTOOLS_GLOBAL_HOOK__ = hook;
|
|
4694
|
+
injector.setHookRestorer(() => {
|
|
4695
|
+
hook.onCommitFiberRoot = () => {
|
|
4696
|
+
};
|
|
4697
|
+
});
|
|
6594
4698
|
console.log("[ReactCheck] DevTools hook installed");
|
|
6595
4699
|
} else {
|
|
6596
|
-
const
|
|
6597
|
-
const originalOnCommit = existingHook.onCommitFiberRoot.bind(existingHook);
|
|
4700
|
+
const originalOnCommit = existingHook.onCommitFiberRoot;
|
|
6598
4701
|
existingHook.onCommitFiberRoot = (rendererID, root, priorityLevel) => {
|
|
6599
|
-
originalOnCommit(rendererID, root, priorityLevel);
|
|
6600
|
-
handleCommit(root);
|
|
4702
|
+
originalOnCommit.call(existingHook, rendererID, root, priorityLevel);
|
|
4703
|
+
injector.handleCommit(root);
|
|
6601
4704
|
};
|
|
4705
|
+
injector.setHookRestorer(() => {
|
|
4706
|
+
existingHook.onCommitFiberRoot = originalOnCommit;
|
|
4707
|
+
});
|
|
6602
4708
|
console.log("[ReactCheck] Wrapped existing DevTools hook");
|
|
6603
4709
|
}
|
|
6604
|
-
|
|
6605
|
-
|
|
6606
|
-
|
|
6607
|
-
if (document.readyState === "loading") {
|
|
6608
|
-
document.addEventListener("DOMContentLoaded", () => {
|
|
4710
|
+
const doc = win.document;
|
|
4711
|
+
if (doc.readyState === "loading") {
|
|
4712
|
+
doc.addEventListener("DOMContentLoaded", () => {
|
|
6609
4713
|
injector.init();
|
|
6610
|
-
});
|
|
4714
|
+
}, { once: true });
|
|
6611
4715
|
} else {
|
|
6612
4716
|
injector.init();
|
|
6613
4717
|
}
|
|
6614
|
-
|
|
6615
|
-
|
|
6616
|
-
|
|
6617
|
-
// src/index.ts
|
|
6618
|
-
var VERSION = "1.0.0";
|
|
6619
|
-
function createScanner(options = {}) {
|
|
6620
|
-
return new Scanner({
|
|
6621
|
-
thresholds: {
|
|
6622
|
-
critical: options.thresholds?.critical ?? 50,
|
|
6623
|
-
warning: options.thresholds?.warning ?? 20
|
|
6624
|
-
}
|
|
6625
|
-
});
|
|
6626
|
-
}
|
|
6627
|
-
function createReportGenerator(options = {}) {
|
|
6628
|
-
return new ReportGenerator({
|
|
6629
|
-
enabled: true,
|
|
6630
|
-
formats: options.formats ?? ["html", "json"],
|
|
6631
|
-
output: options.output ?? "./reactcheck-reports",
|
|
6632
|
-
includeSourceCode: options.includeSourceCode ?? false
|
|
6633
|
-
});
|
|
4718
|
+
win.__REACTCHECK__ = injector;
|
|
4719
|
+
return injector;
|
|
6634
4720
|
}
|
|
4721
|
+
|
|
4722
|
+
// src/version.ts
|
|
4723
|
+
var VERSION = "1.3.0";
|
|
4724
|
+
|
|
4725
|
+
// src/quick-scan.ts
|
|
6635
4726
|
async function quickScan(url, options = {}) {
|
|
6636
|
-
|
|
6637
|
-
const puppeteerAvailable = await isPuppeteerAvailable2();
|
|
6638
|
-
if (!puppeteerAvailable) {
|
|
4727
|
+
if (!await isPuppeteerAvailable()) {
|
|
6639
4728
|
throw new ReactCheckError(
|
|
6640
4729
|
"BROWSER_LAUNCH_FAILED" /* BROWSER_LAUNCH_FAILED */,
|
|
6641
4730
|
"Puppeteer is required for quickScan. Install it with: npm install puppeteer"
|
|
6642
4731
|
);
|
|
6643
4732
|
}
|
|
6644
|
-
const
|
|
6645
|
-
url,
|
|
6646
|
-
headless: options.headless ?? true
|
|
6647
|
-
});
|
|
4733
|
+
const target = url.includes("://") ? url : `http://${url}`;
|
|
6648
4734
|
const duration = options.duration ?? 3e4;
|
|
6649
|
-
|
|
6650
|
-
|
|
6651
|
-
|
|
6652
|
-
|
|
6653
|
-
|
|
6654
|
-
|
|
6655
|
-
|
|
6656
|
-
|
|
6657
|
-
|
|
6658
|
-
|
|
6659
|
-
|
|
6660
|
-
|
|
4735
|
+
const startTime = Date.now();
|
|
4736
|
+
const scanner = new Scanner({
|
|
4737
|
+
thresholds: {
|
|
4738
|
+
critical: options.thresholds?.critical ?? 50,
|
|
4739
|
+
warning: options.thresholds?.warning ?? 20,
|
|
4740
|
+
...options.thresholds?.fps !== void 0 ? { fps: options.thresholds.fps } : {}
|
|
4741
|
+
},
|
|
4742
|
+
config: {
|
|
4743
|
+
...options.include ? { include: options.include } : {},
|
|
4744
|
+
...options.exclude ? { exclude: options.exclude } : {}
|
|
4745
|
+
}
|
|
4746
|
+
});
|
|
4747
|
+
const chains = [];
|
|
4748
|
+
const suggestions = [];
|
|
4749
|
+
scanner.on("chain", (chain) => {
|
|
4750
|
+
chains.push(chain);
|
|
4751
|
+
});
|
|
4752
|
+
scanner.on("fix", (suggestion) => {
|
|
4753
|
+
if (!suggestions.some((s) => s.componentName === suggestion.componentName && s.fix === suggestion.fix)) {
|
|
4754
|
+
suggestions.push(suggestion);
|
|
4755
|
+
}
|
|
6661
4756
|
});
|
|
6662
|
-
|
|
6663
|
-
|
|
4757
|
+
const wsServer = new WebSocketServer(options.port ?? 0);
|
|
4758
|
+
let launcher = null;
|
|
4759
|
+
try {
|
|
4760
|
+
await wsServer.start();
|
|
4761
|
+
wsServer.on("connection", (client) => {
|
|
4762
|
+
handleBrowserMessages(client, (message) => {
|
|
4763
|
+
switch (message.type) {
|
|
4764
|
+
case "render":
|
|
4765
|
+
scanner.addRender(message.payload);
|
|
4766
|
+
break;
|
|
4767
|
+
case "fps":
|
|
4768
|
+
scanner.recordFps(message.payload);
|
|
4769
|
+
break;
|
|
4770
|
+
case "ready":
|
|
4771
|
+
client.send(JSON.stringify({ type: "start" }));
|
|
4772
|
+
break;
|
|
4773
|
+
default:
|
|
4774
|
+
break;
|
|
4775
|
+
}
|
|
4776
|
+
});
|
|
4777
|
+
});
|
|
4778
|
+
scanner.start();
|
|
4779
|
+
launcher = new BrowserLauncher({
|
|
4780
|
+
url: target,
|
|
4781
|
+
headless: options.headless ?? true,
|
|
4782
|
+
wsPort: wsServer.getPort(),
|
|
4783
|
+
...options.browserArgs ? { args: options.browserArgs } : {}
|
|
4784
|
+
});
|
|
4785
|
+
launcher.on("error", () => {
|
|
4786
|
+
});
|
|
4787
|
+
launcher.setInjectionScript(await loadInjectionScript(wsServer.getPort()));
|
|
4788
|
+
try {
|
|
4789
|
+
await launcher.launch();
|
|
4790
|
+
} catch (error) {
|
|
4791
|
+
throw new ReactCheckError(
|
|
4792
|
+
"BROWSER_LAUNCH_FAILED" /* BROWSER_LAUNCH_FAILED */,
|
|
4793
|
+
`Could not open ${target}: ${error instanceof Error ? error.message : String(error)}`
|
|
4794
|
+
);
|
|
4795
|
+
}
|
|
4796
|
+
await new Promise((resolve2) => setTimeout(resolve2, duration));
|
|
4797
|
+
} finally {
|
|
4798
|
+
scanner.stop();
|
|
4799
|
+
if (launcher) {
|
|
4800
|
+
await launcher.close().catch(() => void 0);
|
|
4801
|
+
}
|
|
4802
|
+
await wsServer.stop();
|
|
4803
|
+
}
|
|
4804
|
+
const exported = scanner.export();
|
|
4805
|
+
if (exported.stats.summary.totalRenders === 0) {
|
|
6664
4806
|
throw new ReactCheckError(
|
|
6665
4807
|
"REACT_NOT_FOUND" /* REACT_NOT_FOUND */,
|
|
6666
|
-
"
|
|
4808
|
+
"No React renders were observed. Make sure the page uses React (development or production build) and is reachable."
|
|
6667
4809
|
);
|
|
6668
4810
|
}
|
|
6669
|
-
|
|
6670
|
-
|
|
6671
|
-
|
|
6672
|
-
|
|
6673
|
-
|
|
6674
|
-
|
|
6675
|
-
|
|
6676
|
-
|
|
6677
|
-
|
|
4811
|
+
const report = {
|
|
4812
|
+
version: VERSION,
|
|
4813
|
+
generated: formatDate(),
|
|
4814
|
+
session: {
|
|
4815
|
+
url: target,
|
|
4816
|
+
duration: Date.now() - startTime,
|
|
4817
|
+
timestamp: formatDate(new Date(startTime)),
|
|
4818
|
+
id: generateId("scan")
|
|
4819
|
+
},
|
|
4820
|
+
summary: exported.stats.summary,
|
|
4821
|
+
components: exported.stats.components,
|
|
4822
|
+
chains,
|
|
4823
|
+
timeline: [],
|
|
4824
|
+
framework: null,
|
|
4825
|
+
suggestions
|
|
4826
|
+
};
|
|
4827
|
+
if (options.output) {
|
|
4828
|
+
const generator = new ReportGenerator({
|
|
4829
|
+
enabled: true,
|
|
4830
|
+
formats: options.formats ?? ["html", "json"],
|
|
4831
|
+
output: options.output,
|
|
4832
|
+
includeSourceCode: false
|
|
6678
4833
|
});
|
|
6679
|
-
await generator.saveAll(
|
|
4834
|
+
await generator.saveAll(report);
|
|
6680
4835
|
}
|
|
6681
|
-
return
|
|
4836
|
+
return report;
|
|
4837
|
+
}
|
|
4838
|
+
|
|
4839
|
+
// src/index.ts
|
|
4840
|
+
function createScanner(options = {}) {
|
|
4841
|
+
const config = {};
|
|
4842
|
+
if (options.include) config.include = options.include;
|
|
4843
|
+
if (options.exclude) config.exclude = options.exclude;
|
|
4844
|
+
return new Scanner({
|
|
4845
|
+
thresholds: {
|
|
4846
|
+
critical: options.thresholds?.critical ?? 50,
|
|
4847
|
+
warning: options.thresholds?.warning ?? 20,
|
|
4848
|
+
...options.thresholds?.fps !== void 0 ? { fps: options.thresholds.fps } : {}
|
|
4849
|
+
},
|
|
4850
|
+
config
|
|
4851
|
+
});
|
|
4852
|
+
}
|
|
4853
|
+
function createReportGenerator(options = {}) {
|
|
4854
|
+
return new ReportGenerator({
|
|
4855
|
+
enabled: true,
|
|
4856
|
+
formats: options.formats ?? ["html", "json"],
|
|
4857
|
+
output: options.output ?? "./reactcheck-reports",
|
|
4858
|
+
includeSourceCode: options.includeSourceCode ?? false
|
|
4859
|
+
});
|
|
6682
4860
|
}
|
|
6683
4861
|
|
|
6684
|
-
export { BrowserLauncher, BrowserScanner,
|
|
4862
|
+
export { BrowserLauncher, BrowserScanner, ErrorCode, FiberTag, LogLevel, Logger, Overlay, ProxyServer, ReactCheckError, ReactCheckInjector, ReportGenerator, VERSION, WebSocketClient, WebSocketServer, colors, createRenderInfo, createReportGenerator, createScanner, escapeHtml, findFiberByName, formatBytes, formatDuration, formatNumber, formatPercent, formatRenderTime, generateHTMLReport, generateJSONReport, generateMarkdownReport, generateReport, getChangedProps, getComponentName, getComponentPath, getFiberDOMNode, getOwner, getParentFiber, getReactVersion, handleBrowserMessages, installReactCheck, isHostComponent, isMemoized, isPuppeteerAvailable, isUserComponent, loadInjectionScript, pad, parseJSONReport, quickScan, saveReport, saveReports, shallowEqual, stripAnsi, supportsColor, truncate, validateJSONReport, walkFiberTree };
|
|
6685
4863
|
//# sourceMappingURL=index.js.map
|
|
6686
4864
|
//# sourceMappingURL=index.js.map
|