Skip to content
Draft
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
9 changes: 6 additions & 3 deletions packages/rolldown/src/app/components/compare/DeltaValue.vue
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { bytesToHumanSize } from '@vitejs/devtools-ui/utils/format'
import { computed } from 'vue'

const props = withDefaults(defineProps<{
value: number
value: number | null
format?: 'bytes' | 'duration' | 'number'
signed?: boolean
}>(), {
Expand All @@ -12,18 +12,21 @@ const props = withDefaults(defineProps<{
})

const sign = computed(() => {
if (!props.signed || props.value === 0)
if (!props.signed || props.value == null || props.value === 0)
return ''
return props.value > 0 ? '+' : '-'
})

const colorClass = computed(() => {
if (!props.signed || props.value === 0)
if (!props.signed || props.value == null || props.value === 0)
return 'text-gray-500'
return props.value > 0 ? 'text-red-500' : 'text-green-500'
})

const formatted = computed(() => {
if (props.value == null)
return { amount: 'Unavailable', unit: '' }

const value = props.signed ? Math.abs(props.value) : props.value

if (props.format === 'bytes') {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ withDefaults(defineProps<{
sessionLabel: string
title: string
titleMeta?: string
delta: number
delta: number | null
format: 'bytes' | 'duration' | 'number'
subtitle?: string
link?: string
Expand Down
10 changes: 5 additions & 5 deletions packages/rolldown/src/app/components/compare/SplitRow.vue
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,9 @@ const props = withDefaults(defineProps<{
currentStats?: SplitDiffStat[]
previousBadges?: string[]
currentBadges?: string[]
previous: number
current: number
delta: number
previous: number | null
current: number | null
delta: number | null
format: 'bytes' | 'duration' | 'number'
ratioText?: string
selectable?: boolean
Expand All @@ -42,9 +42,9 @@ const emit = defineEmits<{
}>()

const ratioClass = computed(() => {
if (props.delta > 0)
if (props.delta != null && props.delta > 0)
return 'text-red-500'
if (props.delta < 0)
if (props.delta != null && props.delta < 0)
return 'text-green-500'
return 'text-gray-500'
})
Expand Down
61 changes: 37 additions & 24 deletions packages/rolldown/src/app/components/compare/TabView.vue
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,11 @@ import type {
} from '~~/shared/types'
import { bytesToHumanSize } from '@vitejs/devtools-ui/utils/format'
import { computed, ref, watch } from 'vue'
import { formatMetricRatio, sumMetrics } from '~~/shared/utils/compare-metrics'
import { useRoute, useRouter } from '#app/composables/router'

type CompareTab = 'overview' | 'plugins' | 'chunks' | 'modules' | 'assets' | 'packages'
type DiffMode = 'changed' | 'added' | 'removed'
type DiffMode = 'changed' | 'added' | 'removed' | 'unavailable'
type DiffFormat = 'bytes' | 'duration' | 'number'
type SummaryTone = 'increase' | 'decrease'

Expand All @@ -29,7 +30,7 @@ interface SplitDiffStat {
hidden?: boolean
}

interface SplitDiffRow extends SessionCompareMetricValue {
interface SplitDiffRow extends SessionCompareMetricValue<number | null> {
key: string
status: SessionCompareChangeStatus
previousTitle?: string
Expand Down Expand Up @@ -253,7 +254,7 @@ const sessionSummaries = computed(() => {
},
{
label: 'Calls',
value: pluginStats.calls.toLocaleString(),
value: pluginStats.calls?.toLocaleString() ?? 'Unavailable',
icon: 'i-ph-arrow-counter-clockwise-duotone',
tone: getSummaryTone(index, pluginStats.calls, pluginStatsA.calls),
},
Expand Down Expand Up @@ -416,12 +417,16 @@ const activeRows = computed(() => {
}
})

const unavailableRows = computed(() => activeRows.value.filter(item => item.status === 'unavailable'))

const changedRows = computed(() => activeRows.value.filter(item => item.status === 'changed'))
const addedRows = computed(() => activeRows.value.filter(item => item.status === 'added'))
const removedRows = computed(() => activeRows.value.filter(item => item.status === 'removed'))

const activeDiffRows = computed(() => {
switch (activeDiffMode.value) {
case 'unavailable':
return unavailableRows.value
case 'added':
return addedRows.value
case 'removed':
Expand All @@ -438,7 +443,7 @@ const diffModeOptions = computed<Array<{
description: string
icon: string
count: number
delta: number
delta: number | null
rows: SplitDiffRow[]
}>>(() => {
return [
Expand Down Expand Up @@ -469,6 +474,17 @@ const diffModeOptions = computed<Array<{
delta: sumDelta(removedRows.value),
rows: removedRows.value.slice(0, TABLE_LIMIT),
},
...(props.tab === 'modules'
? [{
id: 'unavailable' as const,
label: 'Unavailable',
icon: 'i-ph-question-duotone',
description: 'Matched modules without a size measurement on one or both sides.',
count: unavailableRows.value.length,
delta: null,
rows: unavailableRows.value.slice(0, TABLE_LIMIT),
}]
: []),
]
})

Expand All @@ -487,6 +503,8 @@ const activeDiffFormat = computed(() => activeRows.value[0]?.format || 'bytes')

const activeDiffEmptyText = computed(() => {
switch (activeDiffMode.value) {
case 'unavailable':
return 'No unavailable measurements'
case 'added':
return 'No added entries'
case 'removed':
Expand Down Expand Up @@ -607,20 +625,13 @@ function getStatTone(value: number, baseline: number | undefined): SplitDiffStat
function createSplitRow(row: Omit<SplitDiffRow, 'ratioText'>): SplitDiffRow {
return {
...row,
ratioText: formatRatio(row),
ratioText: formatMetricRatio(row),
}
}

function formatRatio(item: SessionCompareMetricValue) {
if (item.deltaRatio == null)
return item.previous === 0 && item.current > 0 ? 'new' : '-'
if (item.deltaRatio === 0)
return '0%'
const sign = item.deltaRatio > 0 ? '+' : ''
return `${sign}${(item.deltaRatio * 100).toFixed(2)}%`
}

function formatValue(value: number, format: DiffFormat) {
function formatValue(value: number | null, format: DiffFormat) {
if (value == null)
return 'Unavailable'
if (format === 'duration') {
if (value >= 1000)
return `${+(value / 1000).toFixed(2)}s`
Expand All @@ -630,14 +641,16 @@ function formatValue(value: number, format: DiffFormat) {
return value.toLocaleString()
}

function formatBytesSummary(value: number) {
function formatBytesSummary(value: number | null) {
if (value == null)
return 'Unavailable'
if (!value)
return '0 B'
return bytesToHumanSize(value).join(' ')
}

function getSummaryTone(index: number, value: number, baseline: number | undefined): SummaryTone | undefined {
if (index === 0 || baseline == null || value === baseline)
function getSummaryTone(index: number, value: number | null, baseline: number | null | undefined): SummaryTone | undefined {
if (index === 0 || value == null || baseline == null || value === baseline)
return undefined
return value > baseline ? 'increase' : 'decrease'
}
Expand All @@ -662,12 +675,12 @@ function getPluginSummaryStats(index: number, session: NormalizedSessionCompareC
}
}

function sumCompareSide<T>(items: T[] | undefined, index: number, getPrevious: (item: T) => number, getCurrent: (item: T) => number) {
return (items ?? []).reduce((total, item) => total + (index === 0 ? getPrevious(item) : getCurrent(item)), 0)
function sumCompareSide<T>(items: T[] | undefined, index: number, getPrevious: (item: T) => number | null, getCurrent: (item: T) => number | null) {
return sumMetrics((items ?? []).map(item => index === 0 ? getPrevious(item) : getCurrent(item)))
}

function sumDelta(rows: SplitDiffRow[]) {
return rows.reduce((total, row) => total + row.delta, 0)
return sumMetrics(rows.map(row => row.delta))
}
</script>

Expand Down Expand Up @@ -712,7 +725,7 @@ function sumDelta(rows: SplitDiffRow[]) {
</button>
</div>

<div class="grid grid-cols-3 gap-3">
<div class="grid gap-3" :class="props.tab === 'modules' ? 'grid-cols-4' : 'grid-cols-3'">
<button
v-for="item of diffModeOptions"
:key="item.id"
Expand All @@ -728,13 +741,13 @@ function sumDelta(rows: SplitDiffRow[]) {
</div>
<div class="flex items-end gap-2">
<span class="text-3xl font-mono font-600">{{ item.count }}</span>
<CompareDeltaValue v-if="item.delta" :value="item.delta" :format="activeDiffFormat" signed />
<CompareDeltaValue v-if="item.delta !== 0" :value="item.delta" :format="activeDiffFormat" signed />
</div>
</button>
</div>

<section v-if="activeDiffOption" class="flex flex-col gap-2">
<template v-if="activeDiffMode === 'changed'">
<template v-if="activeDiffMode === 'changed' || activeDiffMode === 'unavailable'">
<CompareSplitRow
v-for="row of activeDiffOption.rows"
:key="row.key"
Expand Down
6 changes: 3 additions & 3 deletions packages/rolldown/src/app/components/modules/BuildMetrics.vue
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@ const sourceCodeSize = computed(() => {
})

const transformedCodeSize = computed(() => {
const data = props.metrics?.transforms.filter(t => t.transformed_code_size)
return data.at(-1)?.transformed_code_size
const data = props.metrics?.transforms
return data?.at(-1)?.transformed_code_size
})
</script>

Expand Down Expand Up @@ -69,7 +69,7 @@ const transformedCodeSize = computed(() => {
>
<span class="i-ph-clock-duotone inline-block" />
</DisplayDuration>
<template v-if="sourceCodeSize && transformedCodeSize">
<template v-if="sourceCodeSize != null && transformedCodeSize != null">
<span class="op40">|</span>
<div class="flex gap-1 items-center">
<DisplayFileSizeBadge title="Source code size" :bytes="sourceCodeSize" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,16 +58,18 @@ describe('reader index codec', () => {
})

describe('rolldown log cache', () => {
function writeLog() {
function writeLog(finalContent = 'b') {
const dir = mkdtempSync(join(tmpdir(), 'rolldown-log-cache-'))
dirs.push(dir)
const base = { build_id: 'bid_1', session_id: 'sid_1' }
const lines = [
{ timestamp: 1, action: 'BuildStart', ...base },
{ timestamp: 2, action: 'HookResolveIdCallStart', importer: null, module_request: '/src/main.ts', import_kind: 'import-statement', plugin_name: 'p', plugin_id: 0, trigger: 'automatic', call_id: 'c1', ...base },
{ timestamp: 3, action: 'HookResolveIdCallEnd', resolved_id: '/src/main.ts', is_external: false, plugin_name: 'p', plugin_id: 0, trigger: 'automatic', call_id: 'c1', ...base },
{ timestamp: 3.2, action: 'HookTransformCallStart', module_id: '/src/main.ts', content: 'aa', plugin_name: 'first', plugin_id: 1, trigger: 'automatic', call_id: 'first', ...base },
{ timestamp: 3.3, action: 'HookTransformCallEnd', module_id: '/src/main.ts', content: 'a', plugin_name: 'first', plugin_id: 1, trigger: 'automatic', call_id: 'first', ...base },
{ timestamp: 4, action: 'HookTransformCallStart', module_id: '/src/main.ts', content: 'a', plugin_name: 'p', plugin_id: 0, trigger: 'automatic', call_id: 'c2', ...base },
{ timestamp: 5, action: 'HookTransformCallEnd', module_id: '/src/main.ts', content: 'b', plugin_name: 'p', plugin_id: 0, trigger: 'automatic', call_id: 'c2', ...base },
{ timestamp: 5, action: 'HookTransformCallEnd', module_id: '/src/main.ts', content: finalContent, plugin_name: 'p', plugin_id: 0, trigger: 'automatic', call_id: 'c2', ...base },
{ timestamp: 6, action: 'BuildEnd', ...base },
]
const filepath = join(dir, 'logs.json')
Expand All @@ -80,16 +82,16 @@ describe('rolldown log cache', () => {
return [state.moduleEventIndex, state.stringRefIndex, state.pendingHookCallStarts, state.assetsReadyLocations]
}

it('restores the summary with module metrics but without the index, then restores the same index on a full read', async () => {
const filepath = writeLog()
it.each(['b', ''])('preserves the final transform %j through summary, full and detail cache reads', async (content) => {
const filepath = writeLog(content)
const cold = RolldownEventsReader.get(filepath)
await cold.read()
expect((cold as unknown as { moduleEventIndex: Map<string, unknown> }).moduleEventIndex.size).toBeGreaterThan(0)
const coldIndex = structuredClone(indexOf(cold))
const coldEvents = cold.manager.eventCount
const coldModules = cold.manager.module_build_metrics.size
const coldMetrics = cold.manager.module_build_metrics.get('/src/main.ts')!
expect(coldMetrics.transforms).toHaveLength(1)
expect(coldMetrics.transforms).toHaveLength(2)
cold.dispose()

const warm = RolldownEventsReader.get(filepath)
Expand All @@ -106,6 +108,8 @@ describe('rolldown log cache', () => {
await warm.read()
expect(indexOf(warm)).toEqual(coldIndex)
expect(warm.manager.eventCount).toBe(coldEvents)
const detail = await warm.readModuleBuildMetrics('/src/main.ts')
expect(detail.transforms.at(-1)?.transformed_code_size).toBe(content.length)
}
finally {
warm.dispose()
Expand Down
11 changes: 4 additions & 7 deletions packages/rolldown/src/node/rolldown/log-cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export const ROLLDOWN_LOG_READER_INDEX_CACHE_FILENAME = 'reader-index.bin'
export const ROLLDOWN_LOG_PACKAGE_SUMMARY_CACHE_FILENAME = 'package-summary.json'
export const ROLLDOWN_LOG_PLUGIN_SUMMARY_CACHE_FILENAME = 'plugin-summary.json'
export const ROLLDOWN_LOG_MODULE_METRICS_SUMMARY_CACHE_FILENAME = 'module-metrics-summary.json'
const ROLLDOWN_LOG_CACHE_VERSION = 3
const ROLLDOWN_LOG_CACHE_VERSION = 4

type ManagerSnapshot = ReturnType<RolldownEventsManager['snapshot']>

Expand Down Expand Up @@ -232,12 +232,9 @@ function compactModuleBuildMetrics(metrics: ModuleBuildMetrics): ModuleBuildMetr
: []

const transformsByPlugin = new Map<number, ModuleBuildMetrics['transforms'][number]>()
let finalTransformedCodeSize = 0
const finalTransformedCodeSize = metrics.transforms.at(-1)?.transformed_code_size
for (const transform of metrics.transforms) {
if (transform.transformed_code_size)
finalTransformedCodeSize = transform.transformed_code_size

if (!transform.transformed_code_size || transform.source_code_size === transform.transformed_code_size)
if (transform.source_code_size === transform.transformed_code_size)
continue

const item = transformsByPlugin.get(transform.plugin_id)
Expand Down Expand Up @@ -275,7 +272,7 @@ function compactModuleBuildMetrics(metrics: ModuleBuildMetrics): ModuleBuildMetr
})
}

if (finalTransformedCodeSize && metrics.transforms.length) {
if (finalTransformedCodeSize != null && metrics.transforms.length) {
transforms.push({
...metrics.transforms.at(-1)!,
id: '',
Expand Down
50 changes: 50 additions & 0 deletions packages/rolldown/src/node/rpc/__tests__/module-compare.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { RolldownEventsReader } from '../../rolldown/events-reader'
import { rolldownGetSessionCompareDetails } from '../functions/rolldown-get-session-compare-details'

const { manager } = vi.hoisted(() => ({ manager: { loadAssetSession: vi.fn() } }))
vi.mock('../utils', () => ({ getLogsManager: () => manager }))

const readers: RolldownEventsReader[] = []
afterEach(() => {
readers.splice(0).forEach(reader => reader.dispose())
vi.restoreAllMocks()
vi.resetAllMocks()
})

function fixture(session: string, sizes: Record<string, number | null>) {
const reader = RolldownEventsReader.get(`/module-compare-test/${session}/logs.json`)
readers.push(reader)
vi.spyOn(reader, 'readPluginBuildMetricsSummary').mockResolvedValue(new Map())
reader.manager.chunks.set(0, { chunk_id: 0, name: 'main', imports: [], modules: Object.keys(sizes) } as any)
for (const [id, size] of Object.entries(sizes)) {
reader.manager.modules.set(id, {
id,
imports: [],
importers: [],
build_metrics: { resolve_ids: [], loads: [], transforms: size == null ? [] : [{ transformed_code_size: size }] },
} as any)
}
return reader
}

describe('module comparison RPC', () => {
it('preserves presence, missing metrics and measured zero through JSON transport', async () => {
const a = fixture('a', { unknown: null, zero: 0, stable: 12, removed: 9, removedUnknown: null })
const b = fixture('b', { unknown: 42, zero: 42, stable: 12, added: 9, addedUnknown: null })
manager.loadAssetSession.mockImplementation(async id => id === 'a' ? a : b)
const { handler } = await rolldownGetSessionCompareDetails.setup!({ cwd: '/' } as any)
const result = JSON.parse(JSON.stringify(await handler!({ sessions: ['a', 'b'] })))
const byId = Object.fromEntries(result.modules.map((item: any) => [item.key, item]))
expect(byId.unknown).toMatchObject({ status: 'unavailable', previous: null, current: 42, delta: null })
expect(byId.zero).toMatchObject({ status: 'changed', previous: 0, current: 42, delta: 42 })
expect(byId.added.previousId).toBeUndefined()
expect(byId.removed.currentId).toBeUndefined()
expect(byId.stable).toMatchObject({ status: 'unchanged', delta: 0 })
expect(byId.added).toMatchObject({ status: 'added', delta: 9 })
expect(byId.removed).toMatchObject({ status: 'removed', delta: -9 })
expect(byId.addedUnknown).toMatchObject({ status: 'added', current: null, delta: null })
expect(byId.removedUnknown).toMatchObject({ status: 'removed', previous: null, delta: null })
expect(result.modules.slice(-3).map((item: any) => item.key).sort()).toEqual(['addedUnknown', 'removedUnknown', 'unknown'])
})
})
Loading
Loading