Skip to content

Commit 5412067

Browse files
committed
feat(react-devtools): drill into the saved React profile by component and commit
1 parent 7c60d2d commit 5412067

9 files changed

Lines changed: 420 additions & 18 deletions

File tree

‎src/cli/react-profiler/react-profile-command.test.ts‎

Lines changed: 62 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,20 @@ test('profile start, an interaction, and profile stop print a compact diagnosis
9696
'1. memo-defeated Row: memo bypassed on 36/36 updates; new onPress (function) on those updates from List -> wrap those props in useCallback/useMemo in List',
9797
);
9898
assert.ok(fs.existsSync(path.join(stateDir, 'react-profiles', 'qa.json')));
99+
100+
const report = await run('report', 'Row');
101+
assert.match(
102+
report.text,
103+
/^Row \[memo\] self 108ms avg 3\.0ms max 3\.0ms renders 36 12 inst\ncauses: props 36\nchanged props: onPress 36 \(function\)/,
104+
);
105+
assert.match(
106+
(await run('timeline', '--sort', 'duration', '--limit', '1')).text,
107+
/^Slowest commits \(1 of 3\):\n {2}#0 \+0\.0s 40ms 13 rendered <- List/,
108+
);
109+
assert.match(
110+
(await run('commit', '#1')).text,
111+
/^#1 \+0\.2s 40ms 13 rendered <- List\n {2}Row x12 self 36ms props/,
112+
);
99113
});
100114

101115
test('profile stop --json returns the findings and where the profile was saved', async () => {
@@ -182,6 +196,10 @@ test('runtime failures carry a typed reason and a hint', async () => {
182196
);
183197
});
184198

199+
test('drill-down views need a saved profile', async () => {
200+
await assert.rejects(harness().run('slow'), /No React profile saved for session qa/);
201+
});
202+
185203
test('explicit dev-server flags override the session binding', async () => {
186204
const { run, requested } = harness();
187205
await run('status', '--metro-port', '8082');
@@ -209,15 +227,29 @@ test('a remote bridge profiles through the public dev-server URL without its bun
209227
assert.deepEqual(requested, ['https://metro.example.test/json/list']);
210228
});
211229

230+
test('a corrupt saved profile asks for a new recording', async () => {
231+
const { run, stateDir } = harness();
232+
fs.mkdirSync(path.join(stateDir, 'react-profiles'), { recursive: true });
233+
const file = path.join(stateDir, 'react-profiles', 'qa.json');
234+
fs.writeFileSync(file, '{"analysis":');
235+
await assert.rejects(run('slow'), /unsupported format/);
236+
fs.writeFileSync(file, JSON.stringify({ analysis: { version: 1, components: {} } }));
237+
await assert.rejects(run('slow'), /unsupported format/);
238+
});
239+
212240
test('unknown profile commands and malformed options are invalid arguments', async () => {
213241
const { run } = harness();
214242
const cases: Array<[string[], RegExp]> = [
215243
[['export', 'out.json'], /Unknown react-devtools profile command: export/],
216-
[['stop', '--limit', '0'], /Invalid --limit: 0/],
217-
[['stop', '--limit', '10garbage'], /Invalid --limit: 10garbage/],
218-
[['stop', '--limit', '1.5'], /Invalid --limit: 1\.5/],
244+
[['slow', '--limit', '0'], /Invalid --limit: 0/],
245+
[['slow', '--limit', '10garbage'], /Invalid --limit: 10garbage/],
246+
[['slow', '--limit', '1.5'], /Invalid --limit: 1\.5/],
247+
[['timeline', '--sort', 'name'], /Invalid --sort: name/],
219248
[['stop', 'extra'], /Unexpected argument for react-devtools profile stop: extra/],
220249
[['start', '--limit', '5'], /react-devtools profile start does not take --limit/],
250+
[['report', 'Row', 'extra'], /Unexpected argument for react-devtools profile report: extra/],
251+
[['report', 'Row', '--limit', '2'], /react-devtools profile report does not take --limit/],
252+
[['slow', '--sort', 'duration'], /react-devtools profile slow does not take --sort/],
221253
];
222254
for (const [args, message] of cases) {
223255
await assert.rejects(run(...args), (error: { code: string; message: string }) => {
@@ -227,3 +259,30 @@ test('unknown profile commands and malformed options are invalid arguments', asy
227259
});
228260
}
229261
});
262+
263+
test('profile commit --json honors --limit like the text view', async () => {
264+
const { app, run, options } = harness();
265+
await run('start');
266+
recordRowRenders(app);
267+
await run('stop');
268+
options.flags = { json: true };
269+
const { text } = await run('commit', '1', '--limit', '1');
270+
const parsed = JSON.parse(text) as { data: { top: Array<{ name: string }>; rendered: number } };
271+
assert.deepEqual(
272+
parsed.data.top.map((entry) => entry.name),
273+
['Row'],
274+
);
275+
assert.equal(parsed.data.rendered, 13);
276+
});
277+
278+
test('commit selectors must be whole indexes', async () => {
279+
const { app, run } = harness();
280+
await run('start');
281+
recordRowRenders(app);
282+
await run('stop');
283+
await assert.rejects(
284+
run('commit', '#1junk'),
285+
(error: { code: string }) => error.code === 'INVALID_ARGS',
286+
);
287+
assert.match((await run('commit', '#1')).text, /^#1 /);
288+
});

‎src/cli/react-profiler/react-profile-command.ts‎

Lines changed: 128 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -22,16 +22,35 @@ import {
2222
import { analyzeReactProfile, type ReactProfileAnalysis } from './react-profile-analysis.ts';
2323
import {
2424
selectPropKindRequests,
25+
type CommitProfile,
26+
type ComponentProfile,
2527
type PropKindsById,
2628
type RawReactProfile,
2729
} from './react-profile-renders.ts';
2830
import {
31+
componentsByRenders,
2932
DEFAULT_FINDING_LIMIT,
30-
formatProfileSummary,
33+
findComponent,
3134
formatSeconds,
35+
formatCommit,
36+
formatComponentReport,
37+
formatProfileSummary,
38+
formatRerenders,
39+
formatSlowComponents,
40+
formatTimeline,
41+
timelineCommits,
3242
} from './react-profile-format.ts';
3343

34-
const REACT_PROFILE_SUBCOMMANDS = ['start', 'stop', 'status'] as const;
44+
const REACT_PROFILE_SUBCOMMANDS = [
45+
'start',
46+
'stop',
47+
'status',
48+
'slow',
49+
'rerenders',
50+
'report',
51+
'timeline',
52+
'commit',
53+
] as const;
3554

3655
type ReactProfileSubcommand = (typeof REACT_PROFILE_SUBCOMMANDS)[number];
3756

@@ -43,15 +62,17 @@ export type ReactProfileCommandOptions = {
4362

4463
type ProfileArgs = {
4564
subcommand: ReactProfileSubcommand;
65+
target?: string;
4666
limit?: number;
4767
app?: string;
4868
metroDevice?: string;
4969
metroHost?: string;
5070
metroPort?: string;
5171
bundleUrl?: string;
72+
sort?: 'timeline' | 'duration';
5273
};
5374

54-
/** Analysis plus the runtime it came from, as `profile stop` saves it for the session. */
75+
/** Analysis plus the runtime it came from, as `profile stop` saves it for the drill-down views. */
5576
type SavedReactProfile = {
5677
savedAt: string;
5778
appId?: string;
@@ -64,6 +85,7 @@ type StartResult = { ok: true; attach: string } | RuntimeFailure;
6485
type StopResult = ({ ok: true } & RawReactProfile) | RuntimeFailure;
6586
type StatusResult = { profiling: boolean; elapsedMs: number | null };
6687

88+
const SUBCOMMANDS_WITH_TARGET = new Set<ReactProfileSubcommand>(['report', 'commit']);
6789
const POSITIVE_INTEGER = /^[1-9]\d*$/;
6890

6991
function isReactProfileSubcommand(value: string | undefined): value is ReactProfileSubcommand {
@@ -77,6 +99,7 @@ const PROFILE_OPTIONS = {
7799
'metro-host': { type: 'string' },
78100
'metro-port': { type: 'string' },
79101
'bundle-url': { type: 'string' },
102+
sort: { type: 'string' },
80103
} as const;
81104

82105
type ProfileOption = keyof typeof PROFILE_OPTIONS;
@@ -94,6 +117,11 @@ const SUBCOMMAND_OPTIONS: Record<ReactProfileSubcommand, readonly ProfileOption[
94117
start: RUNTIME_OPTIONS,
95118
status: RUNTIME_OPTIONS,
96119
stop: [...RUNTIME_OPTIONS, 'limit'],
120+
slow: ['limit'],
121+
rerenders: ['limit'],
122+
report: [],
123+
timeline: ['limit', 'sort'],
124+
commit: ['limit'],
97125
};
98126

99127
function parseProfileOptions(args: string[]) {
@@ -123,24 +151,30 @@ function parseProfileArgs(args: string[]): ProfileArgs {
123151
`react-devtools profile ${subcommand} does not take --${unread}.`,
124152
);
125153
}
126-
if (positionals.length > 0) {
154+
const expected = SUBCOMMANDS_WITH_TARGET.has(subcommand) ? 1 : 0;
155+
if (positionals.length > expected) {
127156
throw new AppError(
128157
'INVALID_ARGS',
129-
`Unexpected argument for react-devtools profile ${subcommand}: ${positionals[0]}.`,
158+
`Unexpected argument for react-devtools profile ${subcommand}: ${positionals[expected]}.`,
130159
);
131160
}
132161
if (values.limit !== undefined && !POSITIVE_INTEGER.test(values.limit)) {
133162
throw new AppError('INVALID_ARGS', `Invalid --limit: ${values.limit}. Use a positive integer.`);
134163
}
135164
const limit = values.limit === undefined ? undefined : Number(values.limit);
165+
if (values.sort !== undefined && values.sort !== 'timeline' && values.sort !== 'duration') {
166+
throw new AppError('INVALID_ARGS', `Invalid --sort: ${values.sort}. Use timeline or duration.`);
167+
}
136168
return {
137169
subcommand,
170+
target: positionals[0],
138171
limit,
139172
app: values.app,
140173
metroDevice: values['metro-device'],
141174
metroHost: values['metro-host'],
142175
metroPort: values['metro-port'],
143176
bundleUrl: values['bundle-url'],
177+
sort: values.sort as ProfileArgs['sort'],
144178
};
145179
}
146180

@@ -250,6 +284,39 @@ function writeSavedProfile(
250284
return filePath;
251285
}
252286

287+
function isSavedProfile(value: SavedReactProfile | undefined): value is SavedReactProfile {
288+
const analysis = value?.analysis;
289+
return (
290+
analysis?.version === 1 &&
291+
Array.isArray(analysis.components) &&
292+
Array.isArray(analysis.commits) &&
293+
Array.isArray(analysis.findings)
294+
);
295+
}
296+
297+
function readSavedProfile(options: ReactProfileCommandOptions): SavedReactProfile {
298+
let raw: string;
299+
try {
300+
raw = fs.readFileSync(savedProfilePath(options), 'utf8');
301+
} catch {
302+
throw new AppError('COMMAND_FAILED', `No React profile saved for session ${options.session}.`, {
303+
hint: 'Run react-devtools profile start, perform the interaction, then react-devtools profile stop.',
304+
});
305+
}
306+
let saved: SavedReactProfile | undefined;
307+
try {
308+
saved = JSON.parse(raw) as SavedReactProfile;
309+
} catch {
310+
saved = undefined;
311+
}
312+
if (!isSavedProfile(saved)) {
313+
throw new AppError('COMMAND_FAILED', 'The saved React profile has an unsupported format.', {
314+
hint: 'Record a new profile with react-devtools profile start and stop.',
315+
});
316+
}
317+
return saved;
318+
}
319+
253320
const elapsed = (elapsedMs: number) => formatSeconds(Math.max(0, elapsedMs));
254321

255322
async function startProfile(
@@ -328,6 +395,32 @@ type SubcommandHandler = (
328395
emit: Emit,
329396
) => Promise<void>;
330397

398+
function requireComponent(
399+
analysis: ReactProfileAnalysis,
400+
name: string | undefined,
401+
): ComponentProfile {
402+
if (!name)
403+
throw new AppError('INVALID_ARGS', 'react-devtools profile report requires a component name.');
404+
const component = findComponent(analysis, name);
405+
if (!component) {
406+
throw new AppError('COMMAND_FAILED', `No renders of ${name} in the saved profile.`, {
407+
hint: 'Use a name from react-devtools profile slow or profile rerenders.',
408+
});
409+
}
410+
return component;
411+
}
412+
413+
function requireCommit(analysis: ReactProfileAnalysis, target: string | undefined): CommitProfile {
414+
const digits = (target ?? '').replace(/^#/, '');
415+
const commit = /^\d+$/.test(digits) ? analysis.commits[Number(digits)] : undefined;
416+
if (!commit) {
417+
throw new AppError('INVALID_ARGS', `No commit ${target ?? '(none)'} in the saved profile.`, {
418+
hint: `Use a commit index from 0 to ${Math.max(analysis.commits.length - 1, 0)}.`,
419+
});
420+
}
421+
return commit;
422+
}
423+
331424
const SUBCOMMAND_HANDLERS: Record<ReactProfileSubcommand, SubcommandHandler> = {
332425
start: async (args, options, emit) => {
333426
const started = await startProfile(args, options);
@@ -354,6 +447,36 @@ const SUBCOMMAND_HANDLERS: Record<ReactProfileSubcommand, SubcommandHandler> = {
354447
savedTo: savedProfilePath(options),
355448
});
356449
},
450+
slow: async (args, options, emit) => {
451+
const { analysis } = readSavedProfile(options);
452+
const limit = args.limit ?? 10;
453+
emit(formatSlowComponents(analysis, limit), analysis.components.slice(0, limit));
454+
},
455+
rerenders: async (args, options, emit) => {
456+
const { analysis } = readSavedProfile(options);
457+
const limit = args.limit ?? 10;
458+
emit(formatRerenders(analysis, limit), componentsByRenders(analysis).slice(0, limit));
459+
},
460+
report: async (args, options, emit) => {
461+
const { analysis } = readSavedProfile(options);
462+
const component = requireComponent(analysis, args.target);
463+
emit(formatComponentReport(analysis, component), component);
464+
},
465+
timeline: async (args, options, emit) => {
466+
const { analysis } = readSavedProfile(options);
467+
const limit = args.limit ?? 20;
468+
const byDuration = args.sort === 'duration';
469+
emit(
470+
formatTimeline(analysis, limit, byDuration),
471+
timelineCommits(analysis, byDuration).slice(0, limit),
472+
);
473+
},
474+
commit: async (args, options, emit) => {
475+
const { analysis } = readSavedProfile(options);
476+
const commit = requireCommit(analysis, args.target);
477+
const limit = args.limit ?? 10;
478+
emit(formatCommit(commit, limit), { ...commit, top: commit.top.slice(0, limit) });
479+
},
357480
};
358481

359482
export async function runReactProfileCommand(

0 commit comments

Comments
 (0)