diff --git a/.changeset/rsbuild-client-build-capture.md b/.changeset/rsbuild-client-build-capture.md new file mode 100644 index 0000000000..70fbc4c839 --- /dev/null +++ b/.changeset/rsbuild-client-build-capture.md @@ -0,0 +1,5 @@ +--- +'@tanstack/start-plugin-core': patch +--- + +Make Start manifest generation faster for Rsbuild client builds with many chunks. diff --git a/packages/start-plugin-core/src/rsbuild/normalized-client-build.ts b/packages/start-plugin-core/src/rsbuild/normalized-client-build.ts index a7dae0c379..dd75269da5 100644 --- a/packages/start-plugin-core/src/rsbuild/normalized-client-build.ts +++ b/packages/start-plugin-core/src/rsbuild/normalized-client-build.ts @@ -111,6 +111,40 @@ function getHydrationIdsFromModules( return hydrationIds ?? [] } +function isRouteOrHydrationModule(module: RspackModule): boolean { + const identifier = module.identifier() + return identifier.includes(tsrSplit) || identifier.includes(tssHydrate) +} + +/** + * Find chunks whose modules may contain route or hydration metadata. A tagged + * module can be nested in a concatenated module with an untagged identifier. + */ +function findRouteAndHydrationChunks( + compilation: RspackCompilation, +): Set { + const routeAndHydrationChunks = new Set() + for (const mod of compilation.modules) { + let tagged = isRouteOrHydrationModule(mod) + if (!tagged) { + const concatenatedModules = ( + mod as RspackModule & { modules?: Array } + ).modules + if (concatenatedModules) { + tagged = getModulesIncludingConcatenated(concatenatedModules).some( + isRouteOrHydrationModule, + ) + } + } + if (tagged) { + for (const chunk of compilation.chunkGraph.getModuleChunks(mod)) { + routeAndHydrationChunks.add(chunk) + } + } + } + return routeAndHydrationChunks +} + /** * Returns true for Rspack/webpack HMR runtime chunks that should never be * surfaced to the Start manifest. These files are emitted on every rebuild @@ -131,35 +165,93 @@ function isManifestJsAsset(file: string): boolean { } /** - * Get all JS file names from a chunk. + * Caches each graph read for this normalization call. Callers must not + * modify the returned arrays. */ -function getChunkJsFiles(chunk: RspackCompilationChunk): Array { - const jsFiles: Array = [] - for (const file of chunk.files) { - if (isManifestJsAsset(file)) { - jsFiles.push(file) +function memoizeGraphRead( + read: (target: TTarget) => Array, +): (target: TTarget) => Array { + const cache = new Map>() + return (target) => { + let value = cache.get(target) + if (!value) { + value = read(target) + cache.set(target, value) } + return value } - return jsFiles } /** - * Get unique CSS file names from both primary and auxiliary chunk assets. + * Joins file lists in order and keeps the first occurrence of each file. */ -function getChunkCssFiles(chunk: RspackCompilationChunk): Array { - const cssFiles: Array = [] +function mergeJsFiles(fileLists: Array>): Array { + const files: Array = [] const seen = new Set() - - for (const file of [...chunk.auxiliaryFiles, ...chunk.files]) { - if (file.endsWith('.css') && !seen.has(file)) { - seen.add(file) - cssFiles.push(file) + for (const list of fileLists) { + for (const file of list) { + if (!seen.has(file)) { + seen.add(file) + files.push(file) + } } } + return files +} - return cssFiles +/** + * Reads each chunk and chunk group property at most once per normalization. + * Rspack builds a new collection on each property read. + */ +function createChunkGraphReader() { + const getFiles = memoizeGraphRead((chunk: RspackCompilationChunk) => + Array.from(chunk.files), + ) + const getAuxiliaryFiles = memoizeGraphRead((chunk: RspackCompilationChunk) => + Array.from(chunk.auxiliaryFiles), + ) + const getGroups = memoizeGraphRead((chunk: RspackCompilationChunk) => + Array.from(chunk.groupsIterable), + ) + const getGroupChunks = memoizeGraphRead((group: Rspack.ChunkGroup) => + Array.from(group.chunks), + ) + const getChunkJsFiles = memoizeGraphRead((chunk: RspackCompilationChunk) => + getFiles(chunk).filter(isManifestJsAsset), + ) + const getGroupJsFiles = memoizeGraphRead((group: Rspack.ChunkGroup) => + mergeJsFiles(getGroupChunks(group).map(getChunkJsFiles)), + ) + const getChildGroupJsFiles = memoizeGraphRead((group: Rspack.ChunkGroup) => + mergeJsFiles(Array.from(group.childrenIterable).map(getGroupJsFiles)), + ) + + return { + getFiles, + getAuxiliaryFiles, + getGroups, + getGroupChunks, + getChunkJsFiles, + // The returned CSS list is mutable; dependency CSS is prepended later. + getChunkCssFiles(chunk: RspackCompilationChunk) { + const cssFiles: Array = [] + const seen = new Set() + for (const file of [...getAuxiliaryFiles(chunk), ...getFiles(chunk)]) { + if (file.endsWith('.css') && !seen.has(file)) { + seen.add(file) + cssFiles.push(file) + } + } + return cssFiles + }, + computeDynamicImports(chunk: RspackCompilationChunk) { + return mergeJsFiles(getGroups(chunk).map(getChildGroupJsFiles)) + }, + } } +type ChunkGraphReader = ReturnType + /** * Include inner modules so concatenation does not hide route metadata or * static dependency edges. @@ -182,35 +274,6 @@ function getModulesIncludingConcatenated( return Array.from(allModules) } -/** - * Compute dynamicImports for a chunk by traversing its chunk groups' - * childrenIterable (async/dynamic import edges). - * - * In rspack, a chunk belongs to one or more ChunkGroups. Each ChunkGroup - * has childrenIterable — child ChunkGroups representing dynamic import() - * points. The JS files from those child groups' chunks are the - * dynamicImports (analogous to Rollup's OutputChunk.dynamicImports). - */ -function computeDynamicImports(chunk: RspackCompilationChunk): Array { - const dynamicImportFiles: Array = [] - const seen = new Set() - - for (const group of chunk.groupsIterable) { - for (const childGroup of group.childrenIterable) { - for (const childChunk of childGroup.chunks) { - for (const file of childChunk.files) { - if (isManifestJsAsset(file) && !seen.has(file)) { - seen.add(file) - dynamicImportFiles.push(file) - } - } - } - } - } - - return dynamicImportFiles -} - /** * Compute the emitted chunks reached by active static module dependencies. * Dependencies nested in async blocks are deliberately excluded: those are @@ -219,6 +282,7 @@ function computeDynamicImports(chunk: RspackCompilationChunk): Array { function computeStaticDependencyChunks( compilation: RspackCompilation, chunk: RspackCompilationChunk, + graph: ChunkGraphReader, chunksOfModule: (module: RspackModule) => Array, ): Array { const importedChunks: Array = [] @@ -236,11 +300,11 @@ function computeStaticDependencyChunks( // chunk is satisfied per group, by that group's own chunk, so neither // route's chunk is a dependency of the shared chunk (#8780). let availableChunks: Set | undefined - for (const group of chunk.groupsIterable) { + for (const group of graph.getGroups(chunk)) { const groupChunks = new Set() const ancestors = new Set([group]) for (const ancestor of ancestors) { - for (const availableChunk of ancestor.chunks) { + for (const availableChunk of graph.getGroupChunks(ancestor)) { groupChunks.add(availableChunk) } for (const parent of ancestor.getParents()) { @@ -305,6 +369,7 @@ type GetStaticDependencyChunks = ( */ function createStaticDependencyChunkResolver( compilation: RspackCompilation, + graph: ChunkGraphReader, ): GetStaticDependencyChunks { const cache = new Map>() const moduleChunks = new Map>() @@ -325,6 +390,7 @@ function createStaticDependencyChunkResolver( importedChunks = computeStaticDependencyChunks( compilation, chunk, + graph, chunksOfModule, ) cache.set(chunk, importedChunks) @@ -340,13 +406,14 @@ function createStaticDependencyChunkResolver( function computeCssOnlyDependencyFiles( getStaticDependencyChunks: GetStaticDependencyChunks, chunks: Array, + graph: ChunkGraphReader, ): Array { const cssFiles: Array = [] const seenChunks = new Set() const seenFiles = new Set() const visit = (chunk: RspackCompilationChunk) => { - if (seenChunks.has(chunk) || getChunkJsFiles(chunk).length > 0) { + if (seenChunks.has(chunk) || graph.getChunkJsFiles(chunk).length > 0) { return } seenChunks.add(chunk) @@ -355,7 +422,7 @@ function computeCssOnlyDependencyFiles( visit(importedChunk) } - for (const cssFile of getChunkCssFiles(chunk)) { + for (const cssFile of graph.getChunkCssFiles(chunk)) { if (!seenFiles.has(cssFile)) { seenFiles.add(cssFile) cssFiles.push(cssFile) @@ -380,6 +447,15 @@ export function normalizeRspackClientBuild( compilation: RspackCompilation, inlineCssEnabled = false, ): NormalizedClientBuild { + const graph = createChunkGraphReader() + const { + getFiles, + getAuxiliaryFiles, + getGroupChunks, + getChunkJsFiles, + getChunkCssFiles, + computeDynamicImports, + } = graph const chunksByFileName = new Map() let cssContentByFileName: Map | undefined let entryChunkFileName: string | undefined @@ -390,33 +466,36 @@ export function normalizeRspackClientBuild( const initialJsFileNames: Array = [] const entryChunkSet = new Set() if (entrypoint) { - for (const chunk of entrypoint.chunks) { + for (const chunk of getGroupChunks(entrypoint)) { entryChunkSet.add(chunk) - for (const file of chunk.files) { - if (isManifestJsAsset(file)) { - initialJsFileNames.push(file) - } - } + initialJsFileNames.push(...getChunkJsFiles(chunk)) } } - const getStaticDependencyChunks = - createStaticDependencyChunkResolver(compilation) + const getStaticDependencyChunks = createStaticDependencyChunkResolver( + compilation, + graph, + ) + const routeAndHydrationChunks = findRouteAndHydrationChunks(compilation) // Iterate ALL chunks (initial + async) to capture route-split chunks for (const chunk of compilation.chunks) { - const modules = getModulesIncludingConcatenated( - compilation.chunkGraph.getChunkModules(chunk), - ) - const routeFilePaths = getRouteFilePathsFromModules(modules) - const hydrationIds = getHydrationIdsFromModules(modules) + const modules = routeAndHydrationChunks.has(chunk) + ? getModulesIncludingConcatenated( + compilation.chunkGraph.getChunkModules(chunk), + ) + : undefined + const routeFilePaths = modules ? getRouteFilePathsFromModules(modules) : [] + const hydrationIds = modules ? getHydrationIdsFromModules(modules) : [] const cssFiles = getChunkCssFiles(chunk) // The entry chunk is the one named 'index' in the 'index' entrypoint const isEntryChunk = chunk.name === 'index' && entryChunkSet.has(chunk) const jsFiles = getChunkJsFiles(chunk) - if (jsFiles.length === 0) continue + if (jsFiles.length === 0) { + continue + } // Compute dynamicImports from chunk group children const dynamicImports = computeDynamicImports(chunk) @@ -424,6 +503,7 @@ export function normalizeRspackClientBuild( const dependencyCssFiles = computeCssOnlyDependencyFiles( getStaticDependencyChunks, staticDependencyChunks, + graph, ).filter((cssFile) => !cssFiles.includes(cssFile)) if (dependencyCssFiles.length > 0) { cssFiles.unshift(...dependencyCssFiles) @@ -493,8 +573,8 @@ export function normalizeRspackClientBuild( if (rscEntrypoint && entryChunkFileName) { const mainEntryChunk = chunksByFileName.get(entryChunkFileName) if (mainEntryChunk) { - for (const rscChunk of rscEntrypoint.chunks) { - const allFiles = [...rscChunk.files, ...rscChunk.auxiliaryFiles] + for (const rscChunk of getGroupChunks(rscEntrypoint)) { + const allFiles = [...getFiles(rscChunk), ...getAuxiliaryFiles(rscChunk)] for (const file of allFiles) { if (file.endsWith('.css') && !mainEntryChunk.css.includes(file)) { mainEntryChunk.css.push(file) diff --git a/packages/start-plugin-core/tests/rsbuild/normalized-client-build.test.ts b/packages/start-plugin-core/tests/rsbuild/normalized-client-build.test.ts index 66e6c58cea..cc55498d92 100644 --- a/packages/start-plugin-core/tests/rsbuild/normalized-client-build.test.ts +++ b/packages/start-plugin-core/tests/rsbuild/normalized-client-build.test.ts @@ -10,7 +10,11 @@ import { } from '../../src/rsbuild/normalized-client-build' import { buildStartManifest } from '../../src/start-manifest-plugin/manifestBuilder' import type { RsbuildPluginAPI, Rspack } from '@rsbuild/core' -import type { GetConfigFn, NormalizedClientBuild } from '../../src/types' +import type { + GetConfigFn, + NormalizedClientBuild, + NormalizedClientChunk, +} from '../../src/types' async function buildClientFixture( files: Record, @@ -121,30 +125,267 @@ function makeWindowsCompilation(readCss: () => string | Uint8Array) { { name: 'root.css', source: { source: readCss } }, { name: 'posts.css', source: { source: readCss } }, ] + const routeModule = { + dependencies: [], + identifier: () => + 'builtin:swc-loader??ruleSet[0]!C:\\app\\src\\routes\\posts.tsx?tsr-split=component', + nameForCondition: () => 'C:\\app\\src\\routes\\posts.tsx', + } const compilation = { entrypoints: new Map([['index', { chunks: [entryChunk] }]]), chunks: new Set([entryChunk, routeChunk]), + modules: new Set([routeModule]), moduleGraph: { getConnection: () => undefined }, chunkGraph: { getModuleChunksIterable: () => [], getChunkModules: (chunk: unknown) => - chunk === routeChunk - ? [ - { - dependencies: [], - identifier: () => - 'builtin:swc-loader??ruleSet[0]!C:\\app\\src\\routes\\posts.tsx?tsr-split=component', - nameForCondition: () => 'C:\\app\\src\\routes\\posts.tsx', - }, - ] - : [], + chunk === routeChunk ? [routeModule] : [], + getModuleChunks: (module: unknown) => + module === routeModule ? [routeChunk] : [], }, getAssets, } as unknown as Rspack.Compilation return compilation } +type MockChunk = { + name: string + files: Set + auxiliaryFiles: Set + groupsIterable: Set + runtime: Set +} +type MockChunkGroup = { + chunks: Array + childrenIterable: Set + getParents: () => Array +} + +// The entry group lazy-loads the posts and about routes, which share a chunk. +// The posts route lazy-loads the post route, which contains a hydration island. +function makeChunkGraph() { + const chunk = ( + name: string, + files: Array, + auxiliaryFiles: Array = [], + ): MockChunk => ({ + name, + files: new Set(files), + auxiliaryFiles: new Set(auxiliaryFiles), + groupsIterable: new Set(), + runtime: new Set(['index']), + }) + const group = ( + chunks: Array, + children: Array = [], + ): MockChunkGroup => { + const chunkGroup = { + chunks, + childrenIterable: new Set(children), + getParents: () => [], + } + for (const member of chunks) { + member.groupsIterable.add(chunkGroup) + } + return chunkGroup + } + + const index = chunk('index', [ + 'index.js', + 'index.abc123.hot-update.js', + 'root.css', + ]) + const vendor = chunk('vendor', ['vendor.js']) + const shared = chunk('shared', ['shared.js', 'shared.abc123.hot-update.js']) + const posts = chunk('posts', ['posts.js'], ['posts.css']) + const about = chunk('about', ['about.js']) + const post = chunk('post', ['post.js']) + const postGroup = group([post]) + const postsGroup = group([shared, posts], [postGroup]) + const aboutGroup = group([shared, about]) + const entryGroup = group([vendor, index], [postsGroup, aboutGroup]) + + const sharedDependency = {} + const sharedModule = { identifier: () => '/shared.ts', dependencies: [] } + const moduleChunks = new Map>([ + [ + { + identifier: () => '/routes/posts.tsx?tsr-split=component', + nameForCondition: () => '/routes/posts.tsx', + dependencies: [sharedDependency], + }, + [posts], + ], + [ + { + identifier: () => '/islands/counter.tsx?tss-hydrate=counter', + dependencies: [], + }, + [post], + ], + [sharedModule, [shared]], + ]) + const getChunkModules = vi.fn((target: MockChunk) => + Array.from(moduleChunks.keys()).filter((mod) => + moduleChunks.get(mod)!.includes(target), + ), + ) + const chunks = [index, vendor, shared, posts, about, post] + const compilation = { + entrypoints: new Map([['index', entryGroup]]), + chunks: new Set(chunks), + modules: new Set(moduleChunks.keys()), + moduleGraph: { + getConnection: (dependency: object) => + dependency === sharedDependency + ? { module: sharedModule, getActiveState: () => true } + : undefined, + }, + chunkGraph: { + getChunkModules, + getModuleChunks: (mod: object) => moduleChunks.get(mod) ?? [], + getModuleChunksIterable: (mod: object) => moduleChunks.get(mod) ?? [], + }, + } as unknown as Rspack.Compilation + + return { + compilation, + getChunkModules, + graphObjects: [...chunks, postGroup, postsGroup, aboutGroup, entryGroup], + } +} + +// Counts reads of the chunk and chunk group properties that build a new +// collection on every read in Rspack. Returns the highest count for any one +// property of any one object. +function trackGraphPropertyReads(graphObjects: Array) { + let maxReads = 0 + for (const graphObject of graphObjects) { + for (const key of [ + 'files', + 'auxiliaryFiles', + 'groupsIterable', + 'chunks', + 'childrenIterable', + ]) { + if (!(key in graphObject)) { + continue + } + const value: unknown = Reflect.get(graphObject, key) + let reads = 0 + Object.defineProperty(graphObject, key, { + get() { + reads += 1 + maxReads = Math.max(maxReads, reads) + return value + }, + }) + } + } + return () => maxReads +} + +function expectedChunk( + fileName: string, + fields: Partial = {}, +): NormalizedClientChunk { + return { + fileName, + isEntry: false, + imports: [], + dynamicImports: [], + css: [], + routeFilePaths: [], + hydrationIds: [], + ...fields, + } +} + describe('normalizeRspackClientBuild', () => { + test('lists static and dynamic imports in first-seen order', () => { + const { compilation } = makeChunkGraph() + const clientBuild = normalizeRspackClientBuild(compilation) + const lazyRoutes = ['shared.js', 'posts.js', 'about.js'] + + expect(clientBuild.entryChunkFileName).toBe('index.js') + expect(Array.from(clientBuild.chunksByFileName.values())).toEqual([ + expectedChunk('index.js', { + isEntry: true, + imports: ['vendor.js'], + dynamicImports: lazyRoutes, + css: ['root.css'], + }), + expectedChunk('vendor.js', { + dynamicImports: lazyRoutes, + }), + expectedChunk('shared.js', { + dynamicImports: ['post.js'], + }), + expectedChunk('posts.js', { + imports: ['shared.js'], + dynamicImports: ['post.js'], + css: ['posts.css'], + routeFilePaths: ['/routes/posts.tsx'], + }), + expectedChunk('about.js'), + expectedChunk('post.js', { hydrationIds: ['counter'] }), + ]) + }) + + test('reads untagged chunk modules only for static dependencies', () => { + const { compilation, getChunkModules } = makeChunkGraph() + normalizeRspackClientBuild(compilation) + + const reads = new Map() + for (const [chunk] of getChunkModules.mock.calls) { + reads.set(chunk.name, (reads.get(chunk.name) ?? 0) + 1) + } + expect(reads).toEqual( + new Map([ + ['index', 1], + ['vendor', 1], + ['shared', 1], + ['posts', expect.any(Number)], + ['about', 1], + ['post', expect.any(Number)], + ]), + ) + expect(reads.get('posts')).toBeLessThanOrEqual(2) + expect(reads.get('post')).toBeLessThanOrEqual(2) + }) + + test('reads each chunk and chunk group property at most once', () => { + const { compilation, graphObjects } = makeChunkGraph() + const maxReads = trackGraphPropertyReads(graphObjects) + normalizeRspackClientBuild(compilation) + + // 1, not 0, also confirms the read counters were installed. + expect(maxReads()).toBe(1) + }) + + test('retains route and hydration metadata from concatenated inner modules', async () => { + const { clientBuild, directory } = await buildClientFixture( + { + 'index.js': `globalThis.load = () => import(/* webpackChunkName: "wrapper" */ './wrapper.js')`, + 'wrapper.js': ` + import { route } from './route.js?tsr-split=component' + import { island } from './island.js?tss-hydrate=counter' + globalThis.values = [route(), island()] + `, + 'route.js': `export const route = () => Math.random()`, + 'island.js': `export const island = () => Math.random()`, + }, + { optimization: { concatenateModules: true } }, + ) + + expect( + clientBuild.chunksByFileName.get('wrapper.js')?.routeFilePaths, + ).toEqual([join(directory, 'route.js')]) + expect( + clientBuild.chunksByFileName.get('wrapper.js')?.hydrationIds, + ).toEqual(['counter']) + }) + test.each( ['shared', 'none', 'css-module', 'css-only'].flatMap((extraction) => [false, true].flatMap((concatenateModules) =>