Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -274,11 +274,18 @@ trace-engine-cli --help
| Option | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| `-f, --format` | `'toon' \| 'md' \| 'json'` | `'toon'` | Output serialization format |
| `--time-range` | `string` | — | Filter window relative to trace start (e.g. `"3500,4200"`, `"3.5s,4.2s"`, `"100ms-500ms"`) |
| `--absolute-timestamps` | `boolean` | `false` | Treat time ranges as raw absolute trace timestamps rather than relative to trace start |
| `--trace-engine`| `string` | — | Path to a custom DevTools trace engine bundle |
| `--help` | `boolean` | — | Show help and synopsis |

### Time Range Options

All commands except `threads`, `diff` and `scan` accept these options. `diff` accepts `--absolute-timestamps` for its `--window-a` and `--window-b` values. `threads` and `scan` reject both options.

| Option | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| `--time-range` | `string` | — | Filter window relative to trace start (e.g. `"3500,4200"`, `"3.5s,4.2s"`, `"100ms-500ms"`) |
| `--absolute-timestamps` | `boolean` | `false` | Treat time ranges as raw absolute trace timestamps rather than relative to trace start |

---

## Relative vs. Absolute Timestamps & Units
Expand Down Expand Up @@ -434,6 +441,8 @@ trace-engine-cli profile trace.json.gz --time-range "3.5s,4.1s"
trace-engine-cli profile trace.json.gz --time-range "3500ms,4100ms" --bucket 50ms --top 5
```

`--bucket` must be at least `0.01ms`. A profile can have a maximum of 1000 buckets. If the time range divided by the bucket size is more than 1000, the command fails and shows the smallest valid bucket size.

---

### 6. `diff`
Expand Down
108 changes: 74 additions & 34 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import { extractInteractions } from './engine/extractors/interactions.js';
import { extractNavigations } from './engine/extractors/navigations.js';
import { extractNetwork } from './engine/extractors/network.js';
import { extractOverview } from './engine/extractors/overview.js';
import { extractProfile } from './engine/extractors/profile.js';
import { extractProfile, MIN_BUCKET_MS } from './engine/extractors/profile.js';
import {
DEFAULT_REPORT_SECTIONS,
extractReport,
Expand Down Expand Up @@ -60,13 +60,33 @@ const THREAD_OPTION = {
describe: 'Renderer thread as PID:TID. Use threads <file> to look up a frame URL.',
} satisfies import('yargs').Options;

const TIME_RANGE_OPTION = {
type: 'string',
describe:
'Time window (relative to trace start by default, e.g. "3500,4200", "3.5s,4.2s", "100ms-500ms")',
} satisfies import('yargs').Options;

const ABSOLUTE_TIMESTAMPS_OPTION = {
type: 'boolean',
default: false,
describe:
'Treat time ranges as raw absolute trace timestamps rather than relative to trace start (default: false)',
} satisfies import('yargs').Options;

function positiveInteger(value: number): number {
if (!Number.isSafeInteger(value) || value < 1) {
throw new Error('Result limits must be positive integers.');
}
return value;
}

function nonNegativeMinDuration(value: number): number {
if (!Number.isFinite(value) || value < 0) {
throw new Error(`--min-duration must be a number >= 0. Received: ${value}`);
}
return value;
}

function parseReportSections(value?: string): ReportSection[] {
if (value === undefined) return DEFAULT_REPORT_SECTIONS;

Expand Down Expand Up @@ -98,26 +118,19 @@ export async function runCli(argv: string[]): Promise<void> {
type: 'string',
describe: 'Path to custom trace engine bundle',
})
.option('time-range', {
type: 'string',
describe:
'Time window (relative to trace start by default, e.g. "3500,4200", "3.5s,4.2s", "100ms-500ms")',
})
.option('absolute-timestamps', {
type: 'boolean',
default: false,
describe:
'Treat time ranges as raw absolute trace timestamps rather than relative to trace start (default: false)',
})
.command(
['overview <file>', '$0 <file>'],
'High-level trace metadata, Core Web Vitals, and main thread category breakdown (default command)',
(y) =>
y.option('thread', THREAD_OPTION).positional('file', {
describe: 'Path to trace file (.json or .json.gz)',
type: 'string',
demandOption: true,
}),
y
.option('thread', THREAD_OPTION)
.positional('file', {
describe: 'Path to trace file (.json or .json.gz)',
type: 'string',
demandOption: true,
})
.option('time-range', TIME_RANGE_OPTION)
.option('absolute-timestamps', ABSOLUTE_TIMESTAMPS_OPTION),
async (args) => {
const loaded = await loadTraceFromFile(
args.file as string,
Expand Down Expand Up @@ -150,6 +163,8 @@ export async function runCli(argv: string[]): Promise<void> {
type: 'string',
demandOption: true,
})
.option('time-range', TIME_RANGE_OPTION)
.option('absolute-timestamps', ABSOLUTE_TIMESTAMPS_OPTION)
.option('sections', {
type: 'string',
describe: `Comma-separated analyses: ${REPORT_SECTIONS.join(', ')} (default: ${DEFAULT_REPORT_SECTIONS.join(',')})`,
Expand Down Expand Up @@ -207,6 +222,8 @@ export async function runCli(argv: string[]): Promise<void> {
type: 'string',
demandOption: true,
})
.option('time-range', TIME_RANGE_OPTION)
.option('absolute-timestamps', ABSOLUTE_TIMESTAMPS_OPTION)
.option('category', {
type: 'string',
choices: ['lcp', 'inp', 'cls', 'render-blocking', 'third-parties'] as const,
Expand Down Expand Up @@ -257,8 +274,11 @@ export async function runCli(argv: string[]): Promise<void> {
type: 'string',
demandOption: true,
})
.option('time-range', TIME_RANGE_OPTION)
.option('absolute-timestamps', ABSOLUTE_TIMESTAMPS_OPTION)
.option('min-duration', {
type: 'number',
coerce: nonNegativeMinDuration,
default: 50,
describe: 'Minimum task duration threshold in milliseconds (default: 50ms)',
})
Expand Down Expand Up @@ -317,6 +337,8 @@ export async function runCli(argv: string[]): Promise<void> {
type: 'string',
demandOption: true,
})
.option('time-range', TIME_RANGE_OPTION)
.option('absolute-timestamps', ABSOLUTE_TIMESTAMPS_OPTION)
.option('function', {
alias: ['fn', 'name'],
type: 'string',
Expand Down Expand Up @@ -370,6 +392,8 @@ export async function runCli(argv: string[]): Promise<void> {
type: 'string',
demandOption: true,
})
.option('time-range', TIME_RANGE_OPTION)
.option('absolute-timestamps', ABSOLUTE_TIMESTAMPS_OPTION)
.option('bucket', {
type: 'string',
describe:
Expand All @@ -394,8 +418,8 @@ export async function runCli(argv: string[]): Promise<void> {
args.absoluteTimestamps as boolean,
);
const bucketMs = args.bucket === undefined ? undefined : parseTimeValue(args.bucket);
if (bucketMs !== undefined && (!Number.isFinite(bucketMs) || bucketMs < 0.01)) {
throw new Error('--bucket must be at least 0.01ms.');
if (bucketMs !== undefined && (!Number.isFinite(bucketMs) || bucketMs < MIN_BUCKET_MS)) {
throw new Error(`--bucket must be at least ${MIN_BUCKET_MS}ms.`);
}
const result = extractProfile(loaded, {
timeRange,
Expand All @@ -422,6 +446,7 @@ export async function runCli(argv: string[]): Promise<void> {
type: 'string',
demandOption: true,
})
.option('absolute-timestamps', ABSOLUTE_TIMESTAMPS_OPTION)
.option('window-a', {
type: 'string',
demandOption: true,
Expand Down Expand Up @@ -476,11 +501,14 @@ export async function runCli(argv: string[]): Promise<void> {
'scheduling <file>',
'Async task and animation frame scheduling, cancellation, and churn metrics',
(y) =>
y.positional('file', {
describe: 'Path to trace file (.json or .json.gz)',
type: 'string',
demandOption: true,
}),
y
.positional('file', {
describe: 'Path to trace file (.json or .json.gz)',
type: 'string',
demandOption: true,
})
.option('time-range', TIME_RANGE_OPTION)
.option('absolute-timestamps', ABSOLUTE_TIMESTAMPS_OPTION),
async (args) => {
const loaded = await loadTraceFromFile(
args.file as string,
Expand Down Expand Up @@ -511,6 +539,8 @@ export async function runCli(argv: string[]): Promise<void> {
type: 'string',
demandOption: true,
})
.option('time-range', TIME_RANGE_OPTION)
.option('absolute-timestamps', ABSOLUTE_TIMESTAMPS_OPTION)
.option('strip-query', {
type: 'boolean',
describe: 'Remove query strings from request and initiator URLs in the output',
Expand Down Expand Up @@ -562,11 +592,14 @@ export async function runCli(argv: string[]): Promise<void> {
'interactions <file>',
'User interaction latencies and target DOM elements',
(y) =>
y.positional('file', {
describe: 'Path to trace file (.json or .json.gz)',
type: 'string',
demandOption: true,
}),
y
.positional('file', {
describe: 'Path to trace file (.json or .json.gz)',
type: 'string',
demandOption: true,
})
.option('time-range', TIME_RANGE_OPTION)
.option('absolute-timestamps', ABSOLUTE_TIMESTAMPS_OPTION),
async (args) => {
const loaded = await loadTraceFromFile(
args.file as string,
Expand Down Expand Up @@ -597,6 +630,8 @@ export async function runCli(argv: string[]): Promise<void> {
type: 'string',
demandOption: true,
})
.option('time-range', TIME_RANGE_OPTION)
.option('absolute-timestamps', ABSOLUTE_TIMESTAMPS_OPTION)
.option('events', {
type: 'boolean',
default: false,
Expand Down Expand Up @@ -635,6 +670,8 @@ export async function runCli(argv: string[]): Promise<void> {
type: 'string',
demandOption: true,
})
.option('time-range', TIME_RANGE_OPTION)
.option('absolute-timestamps', ABSOLUTE_TIMESTAMPS_OPTION)
.option('name', {
alias: ['event'],
type: 'string',
Expand Down Expand Up @@ -696,11 +733,14 @@ export async function runCli(argv: string[]): Promise<void> {
['navigations <file>', 'navs <file>'],
'List all navigations in the trace and their InsightSet mappings',
(y) =>
y.positional('file', {
describe: 'Path to trace file (.json or .json.gz)',
type: 'string',
demandOption: true,
}),
y
.positional('file', {
describe: 'Path to trace file (.json or .json.gz)',
type: 'string',
demandOption: true,
})
.option('time-range', TIME_RANGE_OPTION)
.option('absolute-timestamps', ABSOLUTE_TIMESTAMPS_OPTION),
async (args) => {
const loaded = await loadTraceFromFile(
args.file as string,
Expand Down
19 changes: 18 additions & 1 deletion src/engine/extractors/profile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ import { getRendererThread, MISSING_CPU_SAMPLES, rendererCpuFilter } from '../he
import type { LoadedTrace } from '../loader.js';
import type { ProfileResult } from '../types.js';

export const MIN_BUCKET_MS = 0.01;
export const MAX_BUCKETS = 1000;

export interface ExtractProfileOptions {
threadId?: string;
timeRange?: TimeRange;
Expand All @@ -40,9 +43,23 @@ export function extractProfile(
const endMs = options?.timeRange ? options.timeRange.endMs : round(microToMilli(traceBounds.max));

const totalRangeMs = Math.max(1, endMs - startMs);
const bucketSizeMs = options?.bucketMs ?? Math.max(10, round(totalRangeMs / 20));
if (options?.bucketMs !== undefined && options.bucketMs < MIN_BUCKET_MS) {
throw new Error(
`Bucket size ${options.bucketMs}ms is below the minimum of ${MIN_BUCKET_MS}ms.`,
);
}
const bucketSizeMs = round(options?.bucketMs ?? Math.max(10, totalRangeMs / 20));
const topCount = options?.top ?? 3;

const rangeMs = endMs - startMs;
if (bucketSizeMs < rangeMs / MAX_BUCKETS) {
const bucketCount = Math.ceil(rangeMs / bucketSizeMs);
const minBucketMs = Math.ceil((rangeMs / MAX_BUCKETS) * 100) / 100;
throw new Error(
`Bucket size ${bucketSizeMs}ms creates ${bucketCount} buckets over ${round(rangeMs)}ms. The maximum is ${MAX_BUCKETS}. Use a bucket size of at least ${minBucketMs}ms.`,
);
}

const result: ProfileResult = {
threadId: options?.threadId,
timeRange: { startMs, endMs },
Expand Down
77 changes: 77 additions & 0 deletions test/cli.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -442,3 +442,80 @@ describe('CLI Dispatcher', () => {
);
});
});

describe('CLI option validation', () => {
const tracePath = path.resolve(import.meta.dirname, 'fixtures/basic-trace.json');
const fixturesDir = path.resolve(import.meta.dirname, 'fixtures');
const cli = ['node', 'trace-engine-cli'];

test('rejects negative --min-duration on tasks', async () => {
await assert.rejects(
captureCliOutput([...cli, 'tasks', tracePath, '--min-duration', '-5']),
/--min-duration must be a number >= 0\./,
);
});

test('rejects non-numeric --min-duration on tasks', async () => {
await assert.rejects(
captureCliOutput([...cli, 'tasks', tracePath, '--min-duration', 'abc']),
/--min-duration must be a number >= 0\./,
);
});

test('accepts --min-duration 0 on tasks', async () => {
const output = await captureCliOutput([...cli, 'tasks', tracePath, '--min-duration', '0']);
assert.match(output, /^mode: list$/m);
});

test('rejects --time-range on diff', async () => {
await assert.rejects(
captureCliOutput([
...cli,
'diff',
tracePath,
'--window-a',
'0,50',
'--window-b',
'50,100',
'--time-range',
'0,10',
]),
/Unknown arguments: time-range/,
);
});

test('rejects --time-range on threads', async () => {
await assert.rejects(
captureCliOutput([...cli, 'threads', tracePath, '--time-range', '0,10']),
/Unknown arguments: time-range/,
);
});

test('rejects --absolute-timestamps on threads', async () => {
await assert.rejects(
captureCliOutput([...cli, 'threads', tracePath, '--absolute-timestamps']),
/Unknown arguments: absolute-timestamps/,
);
});

test('rejects --time-range on scan', async () => {
await assert.rejects(
captureCliOutput([...cli, 'scan', fixturesDir, '--name', 'RunTask', '--time-range', '0,10']),
/Unknown arguments: time-range/,
);
});

test('rejects --absolute-timestamps on scan', async () => {
await assert.rejects(
captureCliOutput([...cli, 'scan', fixturesDir, '--name', 'RunTask', '--absolute-timestamps']),
/Unknown arguments: absolute-timestamps/,
);
});

test('rejects --bucket that creates more than 1000 buckets on profile', async () => {
await assert.rejects(
captureCliOutput([...cli, 'profile', tracePath, '--bucket', '10us']),
/Bucket size 0\.01ms creates 16000 buckets over 160ms\. The maximum is 1000\./,
);
});
});
Loading