diff --git a/.github/workflows/pr-bundle-size-comment.yml b/.github/workflows/pr-bundle-size-comment.yml index 1895e8376e..f4d22d92e8 100644 --- a/.github/workflows/pr-bundle-size-comment.yml +++ b/.github/workflows/pr-bundle-size-comment.yml @@ -26,6 +26,11 @@ jobs: ref: ${{ github.event.repository.default_branch }} persist-credentials: false + - name: Set up Node.js + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + with: + node-version: '22' + - name: Download bundle-size report uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 with: @@ -35,6 +40,9 @@ jobs: repository: ${{ github.repository }} run-id: ${{ github.event.workflow_run.id }} + - name: Validate downloaded bundle size report + run: node apps/bundle-size/scripts/validate-report.mts bundle-size-analysis/report.md + - name: Publish bundle size PR comment env: EXPECTED_HEAD_REPOSITORY: ${{ github.event.workflow_run.head_repository.full_name }} @@ -43,4 +51,4 @@ jobs: PR_NUMBER_PATH: bundle-size-analysis/pull-request-number.txt REPORT_PATH: bundle-size-analysis/report.md SOURCE_RUN_ID: ${{ github.event.workflow_run.id }} - run: node apps/bundle-size/scripts/post-pr-comment.mjs + run: node apps/bundle-size/scripts/post-pr-comment.mts diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index 2e4e41d98b..41fe1c36aa 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -75,6 +75,9 @@ jobs: - name: Measure bundle sizes run: yarn bundle-size --baseline "$env:RUNNER_TEMP\bundle-size-baseline.json" + - name: Validate bundle size report + run: yarn workspace @fluentui-react-native/bundle-size validate-report + - name: Publish bundle size summary run: Get-Content apps\bundle-size\dist\bundle-size\report.md -Raw | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Append @@ -87,7 +90,7 @@ jobs: PR_NUMBER: ${{ github.event.pull_request.number }} REPORT_PATH: apps/bundle-size/dist/bundle-size/report.md SOURCE_RUN_ID: ${{ github.run_id }} - run: node apps/bundle-size/scripts/post-pr-comment.mjs + run: node apps/bundle-size/scripts/post-pr-comment.mts - name: Add pull request metadata env: diff --git a/apps/bundle-size/README.md b/apps/bundle-size/README.md index f472889dad..3a8f69c341 100644 --- a/apps/bundle-size/README.md +++ b/apps/bundle-size/README.md @@ -1,10 +1,8 @@ # Bundle-size fixture -This private app measures minified, tree-shaken Metro consumer bundles without including a test -app or Storybook catalog. It uses `@rnx-kit/metro-config`, -`@rnx-kit/metro-resolver-symlinks` with `oxc-resolver`, and -`@rnx-kit/metro-serializer-esbuild`. Each target scenario is compared with the same React Native -shell on macOS, Win32, and Windows. +This private app measures minified, tree-shaken esbuild consumer bundles without including a test +app or Storybook catalog. React, React Native, React Native SVG, desktop React Native forks, and +`@svgo` imports are external so measurements contain only the package code under test. Run every configured scenario from the repository root: @@ -12,6 +10,10 @@ Run every configured scenario from the repository root: yarn bundle-size ``` +The fixture scripts run as native TypeScript (`.mts`) modules. Run +`yarn workspace @fluentui-react-native/bundle-size build` to type-check them; +the repository's `yarn build` includes this check. + Limit a local run to one or more platforms: ```sh @@ -20,16 +22,12 @@ yarn bundle-size --platform macos --platform win32 ``` Results, source maps, and esbuild metafiles are written to the ignored `dist/bundle-size` -directory. The runner passes `--tree-shake true` and `--metafile .meta.json` to -`rnx-cli bundle`. The JSON report contains raw bytes, gzip bytes, contributing esbuild input -counts, Metro source-map counts, workspace package contribution bytes, and shell deltas. Raw -bytes are the primary comparison; gzip and module attribution are diagnostic signals. The -terminal summary shows the shell's absolute cost and each package scenario's incremental module -and byte cost above its platform shell, plus signed deltas from the baseline. - -The Babel configuration preserves ESM for the serializer while explicitly lowering JSX. The -explicit JSX transform is required because the desktop React Native packages publish JSX in -`.js` files, which esbuild otherwise parses with its plain JavaScript loader. +directory. Platform-specific module resolution prefers `.`, then `.native`, then +generic TypeScript and JavaScript extensions. Package exports use the `react-native` condition. +The JSON report contains raw bytes, gzip bytes, contributing esbuild input counts, and workspace +package contribution bytes. Raw bytes are the primary comparison; gzip and module attribution +are diagnostic signals. The terminal summary shows each scenario's absolute module and byte cost +plus signed deltas from the baseline. ## Baselines and pull requests @@ -42,18 +40,19 @@ yarn bundle-size:update ``` Review the baseline diff together with the implementation that caused it. The PR workflow adds -the Markdown comparison to its job summary, updates one persistent PR comment, and uploads the -complete `dist/bundle-size` directory, including the esbuild metafiles, for investigation. -Same-repository PRs publish directly; fork and Dependabot reports are strictly validated and -published by a separate trusted completion workflow. +the Markdown comparison to its job summary only after validating the trusted report format, +updates one persistent PR comment, and uploads the complete `dist/bundle-size` directory, +including the esbuild metafiles, for investigation. Same-repository PRs publish directly; fork +and Dependabot reports are validated again and published by a separate trusted completion +workflow. ## Adding a package or submodule -1. Add the package to this fixture's dependencies so the pnpm linker exposes it to Metro. +1. Add the package to this fixture's dependencies so the pnpm linker exposes it to esbuild. 2. Add a scenario to `scenarios.json` with a stable name, module specifier, and either `exports` or `namespace: true`. -3. Run `yarn bundle-size` and inspect the shell delta and generated esbuild metafile. The - metafile can also be loaded into the esbuild bundle analyzer. +3. Run `yarn bundle-size` and inspect the generated esbuild metafile. The metafile can also be + loaded into the esbuild bundle analyzer. Use a supported public package or subpath export when measuring consumer cost. A source-relative module path is useful for diagnostics, but it does not prove the cost of the published API. diff --git a/apps/bundle-size/babel.config.js b/apps/bundle-size/babel.config.js deleted file mode 100644 index 51af4a05a3..0000000000 --- a/apps/bundle-size/babel.config.js +++ /dev/null @@ -1,13 +0,0 @@ -const env = process.env.BABEL_ENV || process.env.NODE_ENV; - -module.exports = { - presets: [ - [ - 'module:@react-native/babel-preset', - { - disableImportExportTransform: env === 'production' && Boolean(process.env.RNX_METRO_SERIALIZER_ESBUILD), - }, - ], - ], - plugins: [['@babel/plugin-transform-react-jsx', { runtime: 'automatic' }]], -}; diff --git a/apps/bundle-size/baseline.json b/apps/bundle-size/baseline.json index abf8eb3ce7..0284ef4267 100644 --- a/apps/bundle-size/baseline.json +++ b/apps/bundle-size/baseline.json @@ -1,234 +1,232 @@ { - "schemaVersion": 1, + "schemaVersion": 2, "results": [ - { - "platform": "macos", - "scenario": "shell", - "rawBytes": 820522, - "gzipBytes": 236436, - "moduleCount": 497, - "metroModuleCount": 495, - "metafileInputCount": 497, - "workspaceModules": {}, - "workspaceBytes": {} - }, { "platform": "macos", "scenario": "components-button", - "rawBytes": 871797, - "gzipBytes": 249494, - "moduleCount": 554, - "metroModuleCount": 550, - "metafileInputCount": 758, + "rawBytes": 49943, + "gzipBytes": 13307, + "moduleCount": 62, + "metafileInputCount": 176, "workspaceModules": { - "@fluentui-react-native/components": 10, + "@fluentui-react-native/components": 16, "@fluentui-react-native/design": 21, - "@fluentui-react-native/framework-base": 26 + "@fluentui-react-native/framework-base": 24 }, "workspaceBytes": { - "@fluentui-react-native/components": 9482, - "@fluentui-react-native/design": 30207, - "@fluentui-react-native/framework-base": 11146 + "@fluentui-react-native/components": 9312, + "@fluentui-react-native/design": 28715, + "@fluentui-react-native/framework-base": 11880 } }, { "platform": "macos", "scenario": "components-catalog", - "rawBytes": 1094254, - "gzipBytes": 302948, - "moduleCount": 754, - "metroModuleCount": 749, - "metafileInputCount": 758, + "rawBytes": 155264, + "gzipBytes": 38617, + "moduleCount": 159, + "metafileInputCount": 176, "workspaceModules": { - "@fluentui-react-native/components": 98, + "@fluentui-react-native/components": 112, "@fluentui-react-native/design": 21, - "@fluentui-react-native/framework-base": 26 + "@fluentui-react-native/framework-base": 25 }, "workspaceBytes": { - "@fluentui-react-native/components": 122383, - "@fluentui-react-native/design": 30391, - "@fluentui-react-native/framework-base": 12813 + "@fluentui-react-native/components": 111700, + "@fluentui-react-native/design": 28810, + "@fluentui-react-native/framework-base": 14625 } }, { "platform": "macos", "scenario": "design-theme-state", - "rawBytes": 854603, - "gzipBytes": 243954, - "moduleCount": 541, - "metroModuleCount": 535, - "metafileInputCount": 542, + "rawBytes": 30109, + "gzipBytes": 6425, + "moduleCount": 33, + "metafileInputCount": 58, "workspaceModules": { - "@fluentui-react-native/design": 18, - "@fluentui-react-native/framework-base": 26 + "@fluentui-react-native/design": 15, + "@fluentui-react-native/framework-base": 17 }, "workspaceBytes": { - "@fluentui-react-native/design": 30289, - "@fluentui-react-native/framework-base": 3413 + "@fluentui-react-native/design": 28151, + "@fluentui-react-native/framework-base": 1918 + } + }, + { + "platform": "macos", + "scenario": "design-themed-root", + "rawBytes": 32074, + "gzipBytes": 7103, + "moduleCount": 37, + "metafileInputCount": 58, + "workspaceModules": { + "@fluentui-react-native/design": 19, + "@fluentui-react-native/framework-base": 17 + }, + "workspaceBytes": { + "@fluentui-react-native/design": 30116, + "@fluentui-react-native/framework-base": 1918 } }, { "platform": "macos", "scenario": "design-color-lib", - "rawBytes": 827767, - "gzipBytes": 239469, - "moduleCount": 503, - "metroModuleCount": 501, - "metafileInputCount": 503, + "rawBytes": 6328, + "gzipBytes": 2794, + "moduleCount": 6, + "metafileInputCount": 7, "workspaceModules": { - "@fluentui-react-native/design": 6 + "@fluentui-react-native/design": 5 }, "workspaceBytes": { - "@fluentui-react-native/design": 7097 + "@fluentui-react-native/design": 6289 } }, { "platform": "macos", "scenario": "design-theme-state-legacy-source", - "rawBytes": 856701, - "gzipBytes": 244382, - "moduleCount": 543, - "metroModuleCount": 537, - "metafileInputCount": 545, + "rawBytes": 31765, + "gzipBytes": 6747, + "moduleCount": 34, + "metafileInputCount": 61, "workspaceModules": { - "@fluentui-react-native/design": 20, - "@fluentui-react-native/framework-base": 26 + "@fluentui-react-native/design": 16, + "@fluentui-react-native/framework-base": 17 }, "workspaceBytes": { - "@fluentui-react-native/design": 32361, - "@fluentui-react-native/framework-base": 3413 + "@fluentui-react-native/design": 29807, + "@fluentui-react-native/framework-base": 1918 } }, { "platform": "macos", "scenario": "design-legacy-theme-from-flex", - "rawBytes": 923158, - "gzipBytes": 257703, - "moduleCount": 563, - "metroModuleCount": 558, - "metafileInputCount": 566, + "rawBytes": 97724, + "gzipBytes": 19857, + "moduleCount": 57, + "metafileInputCount": 82, "workspaceModules": { - "@fluentui-react-native/design": 32, - "@fluentui-react-native/framework-base": 26 + "@fluentui-react-native/design": 28, + "@fluentui-react-native/framework-base": 20 }, "workspaceBytes": { - "@fluentui-react-native/design": 61746, - "@fluentui-react-native/framework-base": 4291 + "@fluentui-react-native/design": 58553, + "@fluentui-react-native/framework-base": 2484 } }, - { - "platform": "windows", - "scenario": "shell", - "rawBytes": 829655, - "gzipBytes": 237915, - "moduleCount": 502, - "metroModuleCount": 500, - "metafileInputCount": 502, - "workspaceModules": {}, - "workspaceBytes": {} - }, { "platform": "windows", "scenario": "components-button", - "rawBytes": 880864, - "gzipBytes": 250891, - "moduleCount": 560, - "metroModuleCount": 556, - "metafileInputCount": 764, + "rawBytes": 49867, + "gzipBytes": 13278, + "moduleCount": 63, + "metafileInputCount": 177, "workspaceModules": { - "@fluentui-react-native/components": 10, + "@fluentui-react-native/components": 16, "@fluentui-react-native/design": 22, - "@fluentui-react-native/framework-base": 26 + "@fluentui-react-native/framework-base": 24 }, "workspaceBytes": { - "@fluentui-react-native/components": 9480, - "@fluentui-react-native/design": 30142, - "@fluentui-react-native/framework-base": 11146 + "@fluentui-react-native/components": 9312, + "@fluentui-react-native/design": 28639, + "@fluentui-react-native/framework-base": 11880 } }, { "platform": "windows", "scenario": "components-catalog", - "rawBytes": 1103086, - "gzipBytes": 304267, - "moduleCount": 760, - "metroModuleCount": 755, - "metafileInputCount": 764, + "rawBytes": 155188, + "gzipBytes": 38584, + "moduleCount": 160, + "metafileInputCount": 177, "workspaceModules": { - "@fluentui-react-native/components": 98, + "@fluentui-react-native/components": 112, "@fluentui-react-native/design": 22, - "@fluentui-react-native/framework-base": 26 + "@fluentui-react-native/framework-base": 25 }, "workspaceBytes": { - "@fluentui-react-native/components": 122346, - "@fluentui-react-native/design": 30326, - "@fluentui-react-native/framework-base": 12813 + "@fluentui-react-native/components": 111700, + "@fluentui-react-native/design": 28734, + "@fluentui-react-native/framework-base": 14625 } }, { "platform": "windows", "scenario": "design-theme-state", - "rawBytes": 863667, - "gzipBytes": 245363, - "moduleCount": 547, - "metroModuleCount": 541, - "metafileInputCount": 548, + "rawBytes": 30033, + "gzipBytes": 6394, + "moduleCount": 34, + "metafileInputCount": 59, "workspaceModules": { - "@fluentui-react-native/design": 19, - "@fluentui-react-native/framework-base": 26 + "@fluentui-react-native/design": 16, + "@fluentui-react-native/framework-base": 17 + }, + "workspaceBytes": { + "@fluentui-react-native/design": 28075, + "@fluentui-react-native/framework-base": 1918 + } + }, + { + "platform": "windows", + "scenario": "design-themed-root", + "rawBytes": 31998, + "gzipBytes": 7069, + "moduleCount": 38, + "metafileInputCount": 59, + "workspaceModules": { + "@fluentui-react-native/design": 20, + "@fluentui-react-native/framework-base": 17 }, "workspaceBytes": { - "@fluentui-react-native/design": 30222, - "@fluentui-react-native/framework-base": 3413 + "@fluentui-react-native/design": 30039, + "@fluentui-react-native/framework-base": 1918 } }, { "platform": "windows", "scenario": "design-color-lib", - "rawBytes": 836902, - "gzipBytes": 240953, - "moduleCount": 508, - "metroModuleCount": 506, - "metafileInputCount": 508, + "rawBytes": 6328, + "gzipBytes": 2794, + "moduleCount": 6, + "metafileInputCount": 7, "workspaceModules": { - "@fluentui-react-native/design": 6 + "@fluentui-react-native/design": 5 }, "workspaceBytes": { - "@fluentui-react-native/design": 7097 + "@fluentui-react-native/design": 6289 } }, { "platform": "windows", "scenario": "design-theme-state-legacy-source", - "rawBytes": 865767, - "gzipBytes": 245825, - "moduleCount": 549, - "metroModuleCount": 543, - "metafileInputCount": 551, + "rawBytes": 31689, + "gzipBytes": 6714, + "moduleCount": 35, + "metafileInputCount": 62, "workspaceModules": { - "@fluentui-react-native/design": 21, - "@fluentui-react-native/framework-base": 26 + "@fluentui-react-native/design": 17, + "@fluentui-react-native/framework-base": 17 }, "workspaceBytes": { - "@fluentui-react-native/design": 32294, - "@fluentui-react-native/framework-base": 3413 + "@fluentui-react-native/design": 29731, + "@fluentui-react-native/framework-base": 1918 } }, { "platform": "windows", "scenario": "design-legacy-theme-from-flex", - "rawBytes": 932037, - "gzipBytes": 259016, - "moduleCount": 569, - "metroModuleCount": 564, - "metafileInputCount": 572, + "rawBytes": 97591, + "gzipBytes": 19778, + "moduleCount": 58, + "metafileInputCount": 83, "workspaceModules": { - "@fluentui-react-native/design": 33, - "@fluentui-react-native/framework-base": 26 + "@fluentui-react-native/design": 29, + "@fluentui-react-native/framework-base": 20 }, "workspaceBytes": { - "@fluentui-react-native/design": 61490, - "@fluentui-react-native/framework-base": 4291 + "@fluentui-react-native/design": 58420, + "@fluentui-react-native/framework-base": 2484 } } ] diff --git a/apps/bundle-size/metro.config.js b/apps/bundle-size/metro.config.js deleted file mode 100644 index 873ca98564..0000000000 --- a/apps/bundle-size/metro.config.js +++ /dev/null @@ -1,32 +0,0 @@ -const { makeMetroConfig } = require('@rnx-kit/metro-config'); -const MetroSymlinksResolver = require('@rnx-kit/metro-resolver-symlinks'); - -const symlinkResolver = MetroSymlinksResolver({ - resolver: 'oxc-resolver', -}); - -function resolvePlatformModule(moduleName, platform) { - if (platform !== 'win32') { - return moduleName; - } - - if (moduleName === 'react-native') { - return '@office-iss/react-native-win32'; - } - - if (moduleName.startsWith('react-native/')) { - return `@office-iss/react-native-win32/${moduleName.slice('react-native/'.length)}`; - } - - return moduleName; -} - -module.exports = makeMetroConfig({ - resolver: { - resolveRequest: (context, moduleName, platform) => symlinkResolver(context, resolvePlatformModule(moduleName, platform), platform), - unstable_enablePackageExports: true, - unstable_conditionNames: ['react-native', 'import', 'require'], - disableHierarchicalLookup: true, - enableSymlinks: true, - }, -}); diff --git a/apps/bundle-size/package.json b/apps/bundle-size/package.json index 3a456e4307..6ef8f40e5e 100644 --- a/apps/bundle-size/package.json +++ b/apps/bundle-size/package.json @@ -2,14 +2,16 @@ "name": "@fluentui-react-native/bundle-size", "version": "0.0.0", "private": true, - "description": "Deterministic Metro consumer-bundle measurements", + "description": "Deterministic esbuild consumer-bundle measurements", "license": "MIT", "scripts": { + "build": "tsc -b", "format": "fluentui-scripts format", "lint": "fluentui-scripts lint", - "measure": "node scripts/measure.mjs", - "test": "node --test scripts/*.test.mjs", - "update-baseline": "node scripts/measure.mjs --update-baseline" + "measure": "node scripts/measure.mts", + "test": "node --test scripts/*.test.mts", + "update-baseline": "node scripts/measure.mts --update-baseline", + "validate-report": "node scripts/validate-report.mts" }, "dependencies": { "@fluentui-react-native/components": "workspace:*", @@ -23,38 +25,14 @@ "react-native-windows": "^0.81.0" }, "devDependencies": { - "@babel/core": "catalog:", - "@babel/plugin-transform-react-jsx": "catalog:", "@fluentui-react-native/scripts": "workspace:*", - "@react-native-community/cli": "^20.0.0", - "@react-native-community/cli-platform-android": "^20.0.0", - "@react-native-community/cli-platform-ios": "^20.0.0", - "@react-native-windows/cli": "^0.81.0", - "@react-native/babel-preset": "^0.81.0", - "@react-native/metro-config": "^0.81.0", - "@rnx-kit/cli": "catalog:", - "@rnx-kit/metro-config": "catalog:", - "@rnx-kit/metro-resolver-symlinks": "catalog:", - "@rnx-kit/metro-serializer-esbuild": "catalog:", "@rnx-kit/tools-filesystem": "^0.2.0", "@rnx-kit/tools-formatting": "^0.1.0", - "metro": "^0.83.8", - "oxc-resolver": "catalog:" + "@rnx-kit/tsconfig": "catalog:", + "esbuild": "^0.28.2" }, "rnx-kit": { "kitType": "app", - "bundle": [ - { - "id": "measure", - "entryFile": "src/bootstrap.js", - "treeShake": true, - "targets": [ - "macos", - "win32", - "windows" - ] - } - ], "alignDeps": { "requirements": { "production": [ @@ -62,14 +40,10 @@ ] }, "capabilities": [ - "babel-preset-react-native", - "community/cli", "core", "core-macos", "core-win32", - "core-windows", - "core/metro-config", - "metro" + "core-windows" ] }, "extends": "@fluentui-react-native/scripts/kit-config" diff --git a/apps/bundle-size/scenarios.json b/apps/bundle-size/scenarios.json index d86c4dda25..bd5bb63949 100644 --- a/apps/bundle-size/scenarios.json +++ b/apps/bundle-size/scenarios.json @@ -1,9 +1,6 @@ { "platforms": ["macos", "windows"], "scenarios": [ - { - "name": "shell" - }, { "name": "components-button", "module": "@fluentui-react-native/components", diff --git a/apps/bundle-size/scripts/esbuild-config.mts b/apps/bundle-size/scripts/esbuild-config.mts new file mode 100644 index 0000000000..f4f5e7e8ef --- /dev/null +++ b/apps/bundle-size/scripts/esbuild-config.mts @@ -0,0 +1,55 @@ +import type { BuildOptions } from 'esbuild'; + +const sourceExtensions = ['tsx', 'ts', 'jsx', 'js']; + +export const externalPackages = [ + 'react-native', + 'react', + '@svgo', + 'react-native-svg', + 'react-native-windows', + 'react-native-macos', + '@office-iss/react-native-win32', +]; + +export function getResolveExtensions(platform: string): string[] { + return [ + ...sourceExtensions.map((extension) => `.${platform}.${extension}`), + ...sourceExtensions.map((extension) => `.native.${extension}`), + ...sourceExtensions.map((extension) => `.${extension}`), + '.mjs', + '.cjs', + '.json', + ]; +} + +export function createEsbuildOptions({ + bundlePath, + entryPath, + platform, + workspaceRoot, +}: { + bundlePath: string; + entryPath: string; + platform: string; + workspaceRoot: string; +}): BuildOptions { + return { + absWorkingDir: workspaceRoot, + bundle: true, + conditions: ['react-native'], + entryPoints: [entryPath], + external: externalPackages.flatMap((packageName) => [packageName, `${packageName}/*`]), + format: 'esm', + jsx: 'automatic', + legalComments: 'none', + mainFields: ['react-native', 'module', 'main'], + metafile: true, + minify: true, + outfile: bundlePath, + platform: 'neutral', + resolveExtensions: getResolveExtensions(platform), + sourcemap: 'external', + treeShaking: true, + }; +} diff --git a/apps/bundle-size/scripts/esbuild-config.test.mts b/apps/bundle-size/scripts/esbuild-config.test.mts new file mode 100644 index 0000000000..32ed0bdda5 --- /dev/null +++ b/apps/bundle-size/scripts/esbuild-config.test.mts @@ -0,0 +1,44 @@ +import assert from 'node:assert/strict'; +import { describe, it } from 'node:test'; + +import { createEsbuildOptions, externalPackages, getResolveExtensions } from './esbuild-config.mts'; + +describe('getResolveExtensions', () => { + it('prefers the requested platform, then native, then generic modules', () => { + assert.deepEqual(getResolveExtensions('windows'), [ + '.windows.tsx', + '.windows.ts', + '.windows.jsx', + '.windows.js', + '.native.tsx', + '.native.ts', + '.native.jsx', + '.native.js', + '.tsx', + '.ts', + '.jsx', + '.js', + '.mjs', + '.cjs', + '.json', + ]); + }); +}); + +describe('createEsbuildOptions', () => { + it('uses React Native package conditions and externalizes runtime packages and subpaths', () => { + const options = createEsbuildOptions({ + bundlePath: '/fixture/output.js', + entryPath: '/fixture/input.js', + platform: 'macos', + workspaceRoot: '/fixture', + }); + + assert.deepEqual(options.conditions, ['react-native']); + assert.deepEqual(options.mainFields, ['react-native', 'module', 'main']); + assert.deepEqual( + options.external, + externalPackages.flatMap((packageName) => [packageName, `${packageName}/*`]), + ); + }); +}); diff --git a/apps/bundle-size/scripts/format.mjs b/apps/bundle-size/scripts/format.mjs deleted file mode 100644 index 5ab029b6a1..0000000000 --- a/apps/bundle-size/scripts/format.mjs +++ /dev/null @@ -1,45 +0,0 @@ -import { formatAsTable } from '@rnx-kit/tools-formatting'; - -const kilobyteFormatter = new Intl.NumberFormat('en-US', { - minimumFractionDigits: 2, - maximumFractionDigits: 2, -}); - -const integerFormatter = new Intl.NumberFormat('en-US', { - maximumFractionDigits: 0, -}); - -export function formatSize(bytes) { - const absoluteBytes = Math.abs(bytes); - if (absoluteBytes < 1000) { - return `${bytes}b`; - } - - const sign = bytes < 0 ? '-' : ''; - return `${sign}${kilobyteFormatter.format(absoluteBytes / 1000)}k`; -} - -function formatSigned(value, formatter) { - const sign = value < 0 ? '-' : '+'; - return `${sign}${formatter(Math.abs(value))}`; -} - -export function formatBundleSizeTable(results) { - const rows = results.map(({ platform, scenario, comparison }) => [ - `${platform}: ${scenario}`, - comparison.currentModuleCost, - comparison.status === 'new' ? 'New' : formatSigned(comparison.moduleCostDelta, integerFormatter.format), - formatSize(comparison.currentCost), - comparison.status === 'new' ? 'New' : formatSigned(comparison.costDelta, formatSize), - ]); - - return formatAsTable(rows, { - columns: [ - { label: 'Platform: scenario' }, - { label: 'New modules', align: 'right', format: integerFormatter.format }, - { label: 'Module delta', align: 'right' }, - { label: 'New size', align: 'right' }, - { label: 'Size delta', align: 'right' }, - ], - }); -} diff --git a/apps/bundle-size/scripts/format.mts b/apps/bundle-size/scripts/format.mts new file mode 100644 index 0000000000..37a7402a10 --- /dev/null +++ b/apps/bundle-size/scripts/format.mts @@ -0,0 +1,81 @@ +import { formatAsTable } from '@rnx-kit/tools-formatting'; + +import type { Comparison, ScenarioComparison } from './types.mts'; + +const kilobyteFormatter = new Intl.NumberFormat('en-US', { + minimumFractionDigits: 2, + maximumFractionDigits: 2, +}); + +const integerFormatter = new Intl.NumberFormat('en-US', { + maximumFractionDigits: 0, +}); + +export function formatSize(bytes: number): string { + const absoluteBytes = Math.abs(bytes); + if (absoluteBytes < 1000) { + return `${bytes}b`; + } + + const sign = bytes < 0 ? '-' : ''; + return `${sign}${kilobyteFormatter.format(absoluteBytes / 1000)}k`; +} + +function formatSigned(value: number, formatter: (value: number) => string): string { + const sign = value < 0 ? '-' : '+'; + return `${sign}${formatter(Math.abs(value))}`; +} + +function formatWithDelta(value: number, formatter: (value: number) => string, comparison: Comparison, metric: 'size' | 'module'): string { + if (comparison.status === 'new') { + return `${formatter(value)} (New)`; + } + + const delta = metric === 'size' ? comparison.costDelta : comparison.moduleCostDelta; + const magnitude = formatter(Math.abs(delta)); + const integerDigits = magnitude.match(/^[\d,]+/)?.[0].replaceAll(',', '').length ?? 0; + const padding = integerDigits === 1 ? ' ' : ''; + return `${formatter(value)} ${padding}(${formatSigned(delta, formatter)})`; +} + +export function groupComparisonsByScenario(results: ScenarioComparison[]): Map> { + const scenarios = new Map>(); + for (const { platform, scenario, comparison } of results) { + const platformResults = scenarios.get(scenario) ?? new Map(); + platformResults.set(platform, comparison); + scenarios.set(scenario, platformResults); + } + return scenarios; +} + +export function formatModuleComparison(comparison?: Comparison): string { + return comparison ? formatWithDelta(comparison.currentModuleCost, integerFormatter.format, comparison, 'module') : '-'; +} + +export function formatSizeComparison(comparison?: Comparison): string { + return comparison ? formatWithDelta(comparison.currentCost, formatSize, comparison, 'size') : '-'; +} + +export function formatBundleSizeTable(results: ScenarioComparison[]): string { + const rows = [...groupComparisonsByScenario(results)].map(([scenario, platformResults]) => { + const macos = platformResults.get('macos'); + const windows = platformResults.get('windows'); + return [ + scenario, + formatModuleComparison(macos), + formatModuleComparison(windows), + formatSizeComparison(macos), + formatSizeComparison(windows), + ]; + }); + + return formatAsTable(rows, { + columns: [ + { label: 'Scenario' }, + { label: 'Modules-Mac (Δ)', align: 'right' }, + { label: 'Modules-Win (Δ)', align: 'right' }, + { label: 'Size-Mac (Δ)', align: 'right' }, + { label: 'Size-Win (Δ)', align: 'right' }, + ], + }); +} diff --git a/apps/bundle-size/scripts/format.test.mjs b/apps/bundle-size/scripts/format.test.mts similarity index 54% rename from apps/bundle-size/scripts/format.test.mjs rename to apps/bundle-size/scripts/format.test.mts index 88f17003da..9489866fe0 100644 --- a/apps/bundle-size/scripts/format.test.mjs +++ b/apps/bundle-size/scripts/format.test.mts @@ -1,7 +1,7 @@ import assert from 'node:assert/strict'; import { describe, it } from 'node:test'; -import { formatBundleSizeTable, formatSize } from './format.mjs'; +import { formatBundleSizeTable, formatSize } from './format.mts'; describe('formatSize', () => { it('formats bytes below 1000 without scaling', () => { @@ -18,15 +18,11 @@ describe('formatSize', () => { }); describe('formatBundleSizeTable', () => { - it('shows shell-relative costs and signed baseline deltas', () => { + it('shows bundle costs and signed baseline deltas', () => { const output = formatBundleSizeTable([ { platform: 'macos', scenario: 'components-button', - moduleCount: 1234, - rawBytes: 1_234_560, - deltaModules: 737, - deltaBytes: 414_038, comparison: { status: 'compared', currentModuleCost: 737, @@ -35,24 +31,9 @@ describe('formatBundleSizeTable', () => { costDelta: -999, }, }, - { - platform: 'win32', - scenario: 'shell', - moduleCount: 497, - rawBytes: 999, - comparison: { - status: 'new', - currentModuleCost: 497, - currentCost: 999, - }, - }, { platform: 'windows', - scenario: 'components-catalog', - moduleCount: 2000, - rawBytes: 2000, - deltaModules: 1503, - deltaBytes: 1000, + scenario: 'components-button', comparison: { status: 'compared', currentModuleCost: 1503, @@ -61,22 +42,27 @@ describe('formatBundleSizeTable', () => { costDelta: 1000, }, }, + { + platform: 'macos', + scenario: 'design-color-lib', + comparison: { + status: 'new', + currentModuleCost: 6, + currentCost: 999, + }, + }, ]); - assert.match(output, /Platform: scenario/); - assert.match(output, /New modules/); - assert.match(output, /macos: components-button/); - assert.match(output, /737/); - assert.match(output, /\+2/); - assert.match(output, /414\.04k/); + assert.match(output, /Scenario/); + assert.match(output, /Modules-Mac \(Δ\)/); + assert.match(output, /Modules-Win \(Δ\)/); + assert.match(output, /Size-Mac \(Δ\)/); + assert.match(output, /Size-Win \(Δ\)/); + assert.match( + output, + /components-button\s+│\s+737 {2}\(\+2\)\s+│\s+1,503 \(-12\)\s+│\s+414\.04k \(-999b\)\s+│\s+1\.00k {2}\(\+1\.00k\)/, + ); assert.doesNotMatch(output, /1,234\.56k/); - assert.match(output, /-999b/); - assert.match(output, /win32: shell/); - assert.match(output, /999b/); - assert.match(output, /New/); - assert.match(output, /windows: components-catalog/); - assert.match(output, /1,503/); - assert.match(output, /-12/); - assert.match(output, /\+1\.00k/); + assert.match(output, /design-color-lib\s+│\s+6 \(New\)\s+│\s+-\s+│\s+999b \(New\)\s+│\s+-/); }); }); diff --git a/apps/bundle-size/scripts/measure.mjs b/apps/bundle-size/scripts/measure.mts similarity index 54% rename from apps/bundle-size/scripts/measure.mjs rename to apps/bundle-size/scripts/measure.mts index 533d1d1661..171b7e58e5 100644 --- a/apps/bundle-size/scripts/measure.mjs +++ b/apps/bundle-size/scripts/measure.mts @@ -1,27 +1,40 @@ import { readJSONFileSync, writeJSONFileSync } from '@rnx-kit/tools-filesystem'; -import { spawnSync } from 'node:child_process'; +import { build } from 'esbuild'; +import type { Metafile } from 'esbuild'; import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'; import { mkdir } from 'node:fs/promises'; import { dirname, isAbsolute, join, relative, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import { gzipSync } from 'node:zlib'; -import { formatBundleSizeTable } from './format.mjs'; +import { createEsbuildOptions } from './esbuild-config.mts'; +import { formatBundleSizeTable, formatModuleComparison, formatSizeComparison, groupComparisonsByScenario } from './format.mts'; +import type { BaselineResult, Comparison, Measurement, Scenario, ScenarioComparison, ScenarioConfig, ScenarioImport } from './types.mts'; const workspaceRoot = dirname(dirname(fileURLToPath(import.meta.url))); const repositoryRoot = dirname(dirname(workspaceRoot)); -const yarnVersion = readJSONFileSync(join(repositoryRoot, 'package.json')).packageManager.split('@')[1]; -const yarnPath = join(repositoryRoot, '.yarn', 'releases', `yarn-${yarnVersion}.cjs`); const configPath = join(workspaceRoot, 'scenarios.json'); const defaultBaselinePath = join(workspaceRoot, 'baseline.json'); const outputRoot = join(workspaceRoot, 'dist', 'bundle-size'); const entryRoot = join(outputRoot, 'entries'); -function parseArgs(args) { - const options = { baseline: defaultBaselinePath, config: configPath, platforms: undefined, updateBaseline: false }; +interface MeasureOptions { + baseline: string; + config: string; + platforms?: string[]; + updateBaseline: boolean; +} + +function parseArgs(args: string[]): MeasureOptions { + const options: MeasureOptions = { baseline: defaultBaselinePath, config: configPath, updateBaseline: false }; for (let index = 0; index < args.length; index += 1) { const argument = args[index]; + if (argument === '--baseline' || argument === '--config' || argument === '--platform') { + if (!args[index + 1]) { + throw new Error(`Missing value for ${argument}`); + } + } if (argument === '--baseline') { options.baseline = resolve(args[++index]); } else if (argument === '--config') { @@ -39,11 +52,12 @@ function parseArgs(args) { return options; } -function createEntry(scenario) { - const lines = []; - const targets = []; +function createEntry(scenario: Scenario): string { + const lines: string[] = []; + const targets: string[] = []; - const imports = scenario.imports ?? (scenario.module ? [scenario] : []); + const imports: ScenarioImport[] = + scenario.imports ?? (scenario.module ? [{ module: scenario.module, namespace: scenario.namespace, exports: scenario.exports }] : []); for (const [index, moduleImport] of imports.entries()) { if (moduleImport.namespace) { const target = `bundleSizeTarget${index}`; @@ -61,13 +75,10 @@ function createEntry(scenario) { lines.push(`globalThis.__bundleSizeTarget = [${targets.join(', ')}];`); } - const bootstrapPath = relative(entryRoot, join(workspaceRoot, 'src', 'bootstrap.js')).replaceAll('\\', '/'); - lines.push(`import ${JSON.stringify(bootstrapPath.startsWith('.') ? bootstrapPath : `./${bootstrapPath}`)};`, ''); - - return lines.join('\n'); + return `${lines.join('\n')}\n`; } -function getWorkspacePackage(source) { +function getWorkspacePackage(source: string): string | undefined { const packagesRoot = join(repositoryRoot, 'packages'); const sourcePath = isAbsolute(source) ? source : resolve(workspaceRoot, source); if (!sourcePath.startsWith(packagesRoot)) { @@ -86,10 +97,10 @@ function getWorkspacePackage(source) { return undefined; } -function getWorkspaceContributions(metafile) { - const packageModules = new Map(); - const packageBytes = new Map(); - const contributingInputs = new Map(); +function getWorkspaceContributions(metafile: Metafile) { + const packageModules = new Map(); + const packageBytes = new Map(); + const contributingInputs = new Map(); for (const output of Object.values(metafile.outputs)) { for (const [source, contribution] of Object.entries(output.inputs ?? {})) { @@ -107,7 +118,8 @@ function getWorkspaceContributions(metafile) { } } - const sortPackages = (entries) => Object.fromEntries([...entries].sort(([left], [right]) => left.localeCompare(right))); + const sortPackages = (entries: Map): Record => + Object.fromEntries([...entries].sort(([left], [right]) => left.localeCompare(right))); return { moduleCount: contributingInputs.size, workspaceModules: sortPackages(packageModules), @@ -115,56 +127,22 @@ function getWorkspaceContributions(metafile) { }; } -function runBundle(platform, scenario, resetCache) { +async function runBundle(platform: string, scenario: Scenario): Promise { const entryPath = join(entryRoot, `${scenario.name}.js`); const bundlePath = join(outputRoot, platform, `${scenario.name}.bundle`); - const sourceMapPath = `${bundlePath}.map`; const metafileName = `${scenario.name}.meta.json`; const metafilePath = join(dirname(bundlePath), metafileName); const metafileOutput = relative(workspaceRoot, metafilePath).replaceAll('\\', '/'); writeFileSync(entryPath, createEntry(scenario)); mkdirSync(dirname(bundlePath), { recursive: true }); - const bundleArgs = [ - yarnPath, - 'workspace', - '@fluentui-react-native/bundle-size', - 'rnx-cli', - 'bundle', - '--id', - 'measure', - '--entry-file', - entryPath, - '--platform', - platform, - '--dev', - 'false', - '--minify', - 'true', - '--tree-shake', - 'true', - '--metafile', - metafileOutput, - '--bundle-output', - bundlePath, - '--sourcemap-output', - sourceMapPath, - ]; - if (resetCache) { - bundleArgs.push('--reset-cache'); - } - - const result = spawnSync(process.execPath, bundleArgs, { cwd: repositoryRoot, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }); - - if (result.status !== 0) { - process.stderr.write(result.stdout ?? ''); - process.stderr.write(result.stderr ?? ''); - throw new Error(`Metro failed for ${scenario.name} on ${platform}: ${result.error?.message ?? `exit ${result.status}`}`); + const { metafile } = await build(createEsbuildOptions({ bundlePath, entryPath, platform, workspaceRoot })); + if (!metafile) { + throw new Error(`esbuild did not produce a metafile for "${scenario.name}"`); } + writeJSONFileSync(metafilePath, metafile); const bundle = readFileSync(bundlePath); - const sourceMap = readJSONFileSync(sourceMapPath); - const metafile = readJSONFileSync(metafilePath); const inputPaths = Object.keys(metafile.inputs).map((source) => source.replaceAll('\\', '/')); for (const pattern of scenario.forbiddenInputPatterns ?? []) { const match = inputPaths.find((source) => source.includes(pattern)); @@ -180,11 +158,11 @@ function runBundle(platform, scenario, resetCache) { const contributions = getWorkspaceContributions(metafile); return { + platform, scenario: scenario.name, rawBytes: statSync(bundlePath).size, - gzipBytes: gzipSync(bundle, { level: 9, mtime: 0 }).byteLength, + gzipBytes: gzipSync(bundle, { level: 9 }).byteLength, moduleCount: contributions.moduleCount, - metroModuleCount: sourceMap.sources.length, metafileInputCount: Object.keys(metafile.inputs).length, metafile: metafileOutput, workspaceModules: contributions.workspaceModules, @@ -192,38 +170,32 @@ function runBundle(platform, scenario, resetCache) { }; } -function baselineResult(measurement) { - const { platform, scenario, rawBytes, gzipBytes, moduleCount, metroModuleCount, metafileInputCount, workspaceModules, workspaceBytes } = - measurement; +function baselineResult(measurement: Measurement): BaselineResult { + const { platform, scenario, rawBytes, gzipBytes, moduleCount, metafileInputCount, workspaceModules, workspaceBytes } = measurement; return { platform, scenario, rawBytes, gzipBytes, moduleCount, - metroModuleCount, metafileInputCount, workspaceModules, workspaceBytes, }; } -function resultKey({ platform, scenario }) { +function resultKey({ platform, scenario }: Pick): string { return `${platform}:${scenario}`; } -function createComparison(measurement, baseline, baselineShell) { - const isShell = measurement.scenario === 'shell'; - const currentCost = isShell ? measurement.rawBytes : measurement.deltaBytes; - const currentModuleCost = isShell ? measurement.moduleCount : measurement.deltaModules; - if (!baseline || (!isShell && !baselineShell)) { +function createComparison(measurement: Measurement, baseline?: BaselineResult): Comparison { + const currentCost = measurement.rawBytes; + const currentModuleCost = measurement.moduleCount; + if (!baseline) { return { status: 'new', currentCost, currentModuleCost }; } - const baselineCost = isShell ? baseline.rawBytes : baseline.rawBytes - baselineShell.rawBytes; - const baselineGzipCost = isShell ? baseline.gzipBytes : baseline.gzipBytes - baselineShell.gzipBytes; - const currentGzipCost = isShell ? measurement.gzipBytes : measurement.deltaGzipBytes; - const baselineModuleCost = isShell ? baseline.moduleCount : baseline.moduleCount - baselineShell.moduleCount; + const baselineCost = baseline.rawBytes; const costDelta = currentCost - baselineCost; return { status: 'compared', @@ -232,43 +204,27 @@ function createComparison(measurement, baseline, baselineShell) { currentModuleCost, costDelta, costPercent: baselineCost === 0 ? 0 : (costDelta / baselineCost) * 100, - gzipCostDelta: currentGzipCost - baselineGzipCost, - moduleCostDelta: currentModuleCost - baselineModuleCost, - absoluteRawDelta: measurement.rawBytes - baseline.rawBytes, + gzipCostDelta: measurement.gzipBytes - baseline.gzipBytes, + moduleCostDelta: currentModuleCost - baseline.moduleCount, }; } -function formatBytes(bytes) { - const sign = bytes > 0 ? '+' : ''; - return `${sign}${(bytes / 1024).toFixed(1)} KiB`; -} - -function formatPercent(percent) { - const sign = percent > 0 ? '+' : ''; - return `${sign}${percent.toFixed(2)}%`; -} - -function createMarkdownReport(results) { +function createMarkdownReport(results: ScenarioComparison[]): string { const lines = [ '# Bundle size report', '', - 'Tree-shaken production Metro bundles. Component costs are relative to their platform shell; shell costs are absolute.', + 'Tree-shaken, minified production esbuild bundles with React and React Native runtimes externalized.', '', - '| Platform | Scenario | Baseline cost | Current cost | Cost delta | Change | Gzip delta | Module delta |', - '| --- | --- | ---: | ---: | ---: | ---: | ---: | ---: |', + '| Scenario | Modules-Mac (Δ) | Modules-Win (Δ) | Size-Mac (Δ) | Size-Win (Δ) |', + '| --- | ---: | ---: | ---: | ---: |', ]; - for (const result of results) { - const { comparison } = result; - if (comparison.status === 'new') { - lines.push( - `| ${result.platform} | ${result.scenario} | New | ${(comparison.currentCost / 1024).toFixed(1)} KiB | New | New | New | New |`, - ); - } else { - lines.push( - `| ${result.platform} | ${result.scenario} | ${(comparison.baselineCost / 1024).toFixed(1)} KiB | ${(comparison.currentCost / 1024).toFixed(1)} KiB | ${formatBytes(comparison.costDelta)} | ${formatPercent(comparison.costPercent)} | ${formatBytes(comparison.gzipCostDelta)} | ${comparison.moduleCostDelta >= 0 ? '+' : ''}${comparison.moduleCostDelta} |`, - ); - } + for (const [scenario, platformResults] of groupComparisonsByScenario(results)) { + const macos = platformResults.get('macos'); + const windows = platformResults.get('windows'); + lines.push( + `| ${scenario} | ${formatModuleComparison(macos)} | ${formatModuleComparison(windows)} | ${formatSizeComparison(macos)} | ${formatSizeComparison(windows)} |`, + ); } lines.push( @@ -288,48 +244,44 @@ const { if (updateBaseline && selectedPlatforms) { throw new Error('Baseline updates must include every configured platform; omit --platform'); } -const selectedConfig = readJSONFileSync(selectedConfigPath); +const selectedConfig: ScenarioConfig = readJSONFileSync(selectedConfigPath); const platforms = selectedPlatforms ?? selectedConfig.platforms; await mkdir(entryRoot, { recursive: true }); const measurements = []; for (const platform of platforms) { - for (const [scenarioIndex, scenario] of selectedConfig.scenarios.entries()) { + for (const scenario of selectedConfig.scenarios) { process.stdout.write(`Bundling ${scenario.name} for ${platform}...\n`); - measurements.push({ platform, ...runBundle(platform, scenario, scenarioIndex === 0) }); + measurements.push(await runBundle(platform, scenario)); } } -const shells = new Map( - measurements.filter(({ scenario }) => scenario === 'shell').map((measurement) => [measurement.platform, measurement]), -); const currentBaseline = { - schemaVersion: 1, + schemaVersion: 2, results: measurements.map(baselineResult), }; if (updateBaseline) { writeJSONFileSync(selectedBaselinePath, currentBaseline); } -const baseline = existsSync(selectedBaselinePath) ? readJSONFileSync(selectedBaselinePath) : { schemaVersion: 1, results: [] }; -if (baseline.schemaVersion !== 1) { +const baseline: { schemaVersion: number; results: BaselineResult[] } = existsSync(selectedBaselinePath) + ? readJSONFileSync(selectedBaselinePath) + : { schemaVersion: 2, results: [] }; +if (baseline.schemaVersion !== 1 && baseline.schemaVersion !== 2) { throw new Error(`Unsupported baseline schema version: ${baseline.schemaVersion}`); } -const baselineResults = new Map(baseline.results.map((result) => [resultKey(result), result])); -const baselineShells = new Map(baseline.results.filter(({ scenario }) => scenario === 'shell').map((result) => [result.platform, result])); +if (baseline.schemaVersion === 1) { + process.stderr.write('Baseline schema version 1 contains Metro shell-relative measurements; treating all esbuild scenarios as new.\n'); +} +const baselineResults = new Map( + baseline.schemaVersion === 2 ? baseline.results.map((result) => [resultKey(result), result]) : [], +); const results = measurements.map((measurement) => { - const shell = shells.get(measurement.platform); - const result = { - ...measurement, - deltaBytes: measurement.rawBytes - shell.rawBytes, - deltaGzipBytes: measurement.gzipBytes - shell.gzipBytes, - deltaModules: measurement.moduleCount - shell.moduleCount, - }; return { - ...result, - comparison: createComparison(result, baselineResults.get(resultKey(result)), baselineShells.get(result.platform)), + ...measurement, + comparison: createComparison(measurement, baselineResults.get(resultKey(measurement))), }; }); const report = { diff --git a/apps/bundle-size/scripts/post-pr-comment.mjs b/apps/bundle-size/scripts/post-pr-comment.mts similarity index 67% rename from apps/bundle-size/scripts/post-pr-comment.mjs rename to apps/bundle-size/scripts/post-pr-comment.mts index 31f5590cdf..9f492bfe98 100644 --- a/apps/bundle-size/scripts/post-pr-comment.mjs +++ b/apps/bundle-size/scripts/post-pr-comment.mts @@ -5,18 +5,20 @@ import { pathToFileURL } from 'node:url'; export const bundleSizeCommentMarker = ''; const reportHeader = '# Bundle size report'; -const reportDescription = - 'Tree-shaken production Metro bundles. Component costs are relative to their platform shell; shell costs are absolute.'; -const tableHeader = '| Platform | Scenario | Baseline cost | Current cost | Cost delta | Change | Gzip delta | Module delta |'; -const tableSeparator = '| --- | --- | ---: | ---: | ---: | ---: | ---: | ---: |'; +const reportDescription = 'Tree-shaken, minified production esbuild bundles with React and React Native runtimes externalized.'; +const tableHeader = '| Scenario | Modules-Mac (Δ) | Modules-Win (Δ) | Size-Mac (Δ) | Size-Win (Δ) |'; +const tableSeparator = '| --- | ---: | ---: | ---: | ---: |'; const reportFooter = 'The job is advisory: size changes are reported but do not fail the pull request. Bundle or analysis errors still fail.'; -const tableRowPattern = - /^\| [A-Za-z0-9][A-Za-z0-9._/-]{0,79} \| [A-Za-z0-9][A-Za-z0-9._:/-]{0,79} \| (?:New|[+-]?\d+\.\d KiB) \| (?:New|[+-]?\d+\.\d KiB) \| (?:New|[+-]?\d+\.\d KiB) \| (?:New|[+-]?\d+\.\d{2}%) \| (?:New|[+-]?\d+\.\d KiB) \| (?:New|[+-]?\d+) \|$/; +const moduleValuePattern = String.raw`(?:-|[0-9,]+ {1,2}\((?:New|[+-][0-9,]+)\))`; +const sizeValuePattern = String.raw`(?:-|(?:\d+b|[\d,]+\.\d{2}k) {1,2}\((?:New|[+-](?:\d+b|[\d,]+\.\d{2}k))\))`; +const tableRowPattern = new RegExp( + String.raw`^\| [A-Za-z0-9][A-Za-z0-9._:/-]{0,79} \| ${moduleValuePattern} \| ${moduleValuePattern} \| ${sizeValuePattern} \| ${sizeValuePattern} \|$`, +); const maximumReportBytes = 60_000; const repositoryPattern = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/; -export function validateBundleSizeReport(report) { +export function validateBundleSizeReport(report: string): string { if (Buffer.byteLength(report, 'utf8') > maximumReportBytes) { throw new Error(`Bundle-size report exceeds ${maximumReportBytes} bytes`); } @@ -47,7 +49,7 @@ export function validateBundleSizeReport(report) { return normalized; } -export function createBundleSizeComment(report, repository, runId) { +export function createBundleSizeComment(report: string, repository: string, runId: string): string { if (!repositoryPattern.test(repository) || !/^\d+$/.test(runId)) { throw new Error('Invalid bundle-size workflow identity'); } @@ -56,7 +58,7 @@ export function createBundleSizeComment(report, repository, runId) { return `${bundleSizeCommentMarker}\n${validateBundleSizeReport(report)}\n\n---\n[View bundle-size workflow run](${runUrl})`; } -export function parsePullRequestNumber(value) { +export function parsePullRequestNumber(value: string): number { const normalized = value.trim(); if (!/^[1-9]\d*$/.test(normalized)) { throw new Error(`Invalid pull request number: ${normalized}`); @@ -70,7 +72,22 @@ export function parsePullRequestNumber(value) { return pullRequestNumber; } -async function requestJson(fetchImplementation, url, token, options = {}) { +interface PullRequest { + head: { sha: string; repo: { full_name: string } | null }; +} + +interface IssueComment { + id: number; + body?: string; + user?: { login: string }; +} + +async function requestJson( + fetchImplementation: typeof fetch, + url: string, + token: string, + options: RequestInit = {}, +): Promise { const response = await fetchImplementation(url, { ...options, headers: { @@ -86,7 +103,18 @@ async function requestJson(fetchImplementation, url, token, options = {}) { throw new Error(`GitHub API request failed (${response.status}): ${await response.text()}`); } - return response.status === 204 ? undefined : response.json(); + return response.status === 204 ? undefined : ((await response.json()) as T); +} + +interface CommentOptions { + apiUrl?: string; + body: string; + expectedHeadRepository: string; + expectedHeadSha: string; + fetchImplementation?: typeof fetch; + pullRequestNumber: number; + repository: string; + token: string; } export async function upsertBundleSizeComment({ @@ -98,7 +126,7 @@ export async function upsertBundleSizeComment({ pullRequestNumber, repository, token, -}) { +}: CommentOptions): Promise { if (!repositoryPattern.test(repository)) { throw new Error(`Invalid GitHub repository: ${repository}`); } @@ -110,15 +138,22 @@ export async function upsertBundleSizeComment({ .split('/') .map((part) => encodeURIComponent(part)) .join('/'); - const request = (path, options) => requestJson(fetchImplementation, `${apiUrl}/repos/${repositoryPath}${path}`, token, options); - const pullRequest = await request(`/pulls/${pullRequestNumber}`); + const request = (path: string, options?: RequestInit) => + requestJson(fetchImplementation, `${apiUrl}/repos/${repositoryPath}${path}`, token, options); + const pullRequest = await request(`/pulls/${pullRequestNumber}`); + if (!pullRequest) { + throw new Error('GitHub API returned an empty pull request'); + } if (pullRequest.head.sha !== expectedHeadSha || pullRequest.head.repo?.full_name !== expectedHeadRepository) { throw new Error('Workflow run does not match the current pull request head'); } let existingComment; for (let page = 1; page <= 20 && !existingComment; page += 1) { - const comments = await request(`/issues/${pullRequestNumber}/comments?per_page=100&page=${page}`); + const comments = await request(`/issues/${pullRequestNumber}/comments?per_page=100&page=${page}`); + if (!comments) { + throw new Error('GitHub API returned an empty comment list'); + } existingComment = comments.find( (comment) => comment.user?.login === 'github-actions[bot]' && comment.body?.includes(bundleSizeCommentMarker), ); @@ -165,7 +200,12 @@ async function main() { throw new Error('Missing required bundle-size PR comment environment'); } - const pullRequestNumber = parsePullRequestNumber(pullRequestNumberValue ?? (await readFile(pullRequestNumberPath, 'utf8'))); + const pullRequestNumberInput = + pullRequestNumberValue ?? (pullRequestNumberPath ? await readFile(pullRequestNumberPath, 'utf8') : undefined); + if (!pullRequestNumberInput) { + throw new Error('Missing required bundle-size PR comment environment'); + } + const pullRequestNumber = parsePullRequestNumber(pullRequestNumberInput); const report = await readFile(reportPath, 'utf8'); const body = createBundleSizeComment(report, repository, runId); await upsertBundleSizeComment({ diff --git a/apps/bundle-size/scripts/post-pr-comment.test.mjs b/apps/bundle-size/scripts/post-pr-comment.test.mts similarity index 76% rename from apps/bundle-size/scripts/post-pr-comment.test.mjs rename to apps/bundle-size/scripts/post-pr-comment.test.mts index cf156aca71..582249610e 100644 --- a/apps/bundle-size/scripts/post-pr-comment.test.mjs +++ b/apps/bundle-size/scripts/post-pr-comment.test.mts @@ -7,27 +7,22 @@ import { parsePullRequestNumber, upsertBundleSizeComment, validateBundleSizeReport, -} from './post-pr-comment.mjs'; +} from './post-pr-comment.mts'; const validReport = `# Bundle size report -Tree-shaken production Metro bundles. Component costs are relative to their platform shell; shell costs are absolute. +Tree-shaken, minified production esbuild bundles with React and React Native runtimes externalized. -| Platform | Scenario | Baseline cost | Current cost | Cost delta | Change | Gzip delta | Module delta | -| --- | --- | ---: | ---: | ---: | ---: | ---: | ---: | -| macos | shell | 801.3 KiB | 801.3 KiB | 0.0 KiB | 0.00% | 0.0 KiB | +0 | -| macos | components-button | New | 46.4 KiB | New | New | New | New | +| Scenario | Modules-Mac (Δ) | Modules-Win (Δ) | Size-Mac (Δ) | Size-Win (Δ) | +| --- | ---: | ---: | ---: | ---: | +| design-color-lib | 6 (+0) | 6 (+0) | 6.33k (+0b) | 6.33k (+0b) | +| components-button | 62 (New) | 63 (New) | 49.48k (New) | 49.40k (New) | The job is advisory: size changes are reported but do not fail the pull request. Bundle or analysis errors still fail. `; -function jsonResponse(value, status = 200) { - return { - ok: status >= 200 && status < 300, - status, - json: async () => value, - text: async () => JSON.stringify(value), - }; +function jsonResponse(value: unknown, status = 200): Response { + return new Response(JSON.stringify(value), { status, headers: { 'Content-Type': 'application/json' } }); } describe('validateBundleSizeReport', () => { @@ -48,6 +43,8 @@ describe('createBundleSizeComment', () => { const comment = createBundleSizeComment(validReport, 'microsoft/fluentui-react-native', '123'); assert.match(comment, new RegExp(`^${bundleSizeCommentMarker.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}`)); + assert.match(comment, /\| Scenario \| Modules-Mac \(Δ\) \| Modules-Win \(Δ\) \| Size-Mac \(Δ\) \| Size-Win \(Δ\) \|/); + assert.match(comment, /\| design-color-lib \| 6 {2}\(\+0\) \| 6 {2}\(\+0\) \| 6\.33k {2}\(\+0b\) \| 6\.33k {2}\(\+0b\) \|/); assert.match(comment, /https:\/\/github\.com\/microsoft\/fluentui-react-native\/actions\/runs\/123\)$/); }); @@ -69,8 +66,9 @@ describe('parsePullRequestNumber', () => { describe('upsertBundleSizeComment', () => { it('updates the existing Actions comment after verifying the pull request head', async () => { - const requests = []; - const fetchImplementation = async (url, options) => { + const requests: { url: string; options?: RequestInit }[] = []; + const fetchImplementation = async (input: string | URL | Request, options?: RequestInit): Promise => { + const url = String(input); requests.push({ url, options }); if (url.endsWith('/pulls/42')) { return jsonResponse({ head: { sha: 'abc123', repo: { full_name: 'contributor/fluentui-react-native' } } }); @@ -94,13 +92,16 @@ describe('upsertBundleSizeComment', () => { token: 'test-token', }); - assert.equal(requests.at(-1).options.method, 'PATCH'); - assert.deepEqual(JSON.parse(requests.at(-1).options.body), { body: `${bundleSizeCommentMarker}\nnew` }); + assert.equal(requests.at(-1)?.options?.method, 'PATCH'); + const requestBody = requests.at(-1)?.options?.body; + assert.ok(typeof requestBody === 'string'); + assert.deepEqual(JSON.parse(requestBody), { body: `${bundleSizeCommentMarker}\nnew` }); }); it('creates a comment when no prior marker exists', async () => { - const requests = []; - const fetchImplementation = async (url, options) => { + const requests: { url: string; options?: RequestInit }[] = []; + const fetchImplementation = async (input: string | URL | Request, options?: RequestInit): Promise => { + const url = String(input); requests.push({ url, options }); if (url.endsWith('/pulls/42')) { return jsonResponse({ head: { sha: 'abc123', repo: { full_name: 'microsoft/fluentui-react-native' } } }); @@ -124,7 +125,7 @@ describe('upsertBundleSizeComment', () => { token: 'test-token', }); - assert.equal(requests.at(-1).options.method, 'POST'); + assert.equal(requests.at(-1)?.options?.method, 'POST'); }); it('rejects a stale workflow run before reading comments', async () => { diff --git a/apps/bundle-size/scripts/types.mts b/apps/bundle-size/scripts/types.mts new file mode 100644 index 0000000000..57f3e3889a --- /dev/null +++ b/apps/bundle-size/scripts/types.mts @@ -0,0 +1,54 @@ +export interface ScenarioImport { + module: string; + namespace?: boolean; + exports?: string[]; +} + +export interface Scenario { + name: string; + module?: string; + namespace?: boolean; + exports?: string[]; + imports?: ScenarioImport[]; + forbiddenInputPatterns?: string[]; + requiredInputPatterns?: string[]; +} + +export interface ScenarioConfig { + platforms: string[]; + scenarios: Scenario[]; +} + +export interface BaselineResult { + platform: string; + scenario: string; + rawBytes: number; + gzipBytes: number; + moduleCount: number; + metafileInputCount: number; + workspaceModules: Record; + workspaceBytes: Record; +} + +export interface Measurement extends BaselineResult { + metafile: string; +} + +export type Comparison = + | { status: 'new'; currentCost: number; currentModuleCost: number } + | { + status: 'compared'; + currentCost: number; + currentModuleCost: number; + costDelta: number; + moduleCostDelta: number; + baselineCost?: number; + costPercent?: number; + gzipCostDelta?: number; + }; + +export interface ScenarioComparison { + platform: string; + scenario: string; + comparison: Comparison; +} diff --git a/apps/bundle-size/scripts/validate-report.mts b/apps/bundle-size/scripts/validate-report.mts new file mode 100644 index 0000000000..1ebf09401c --- /dev/null +++ b/apps/bundle-size/scripts/validate-report.mts @@ -0,0 +1,11 @@ +import { readFile } from 'node:fs/promises'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import { validateBundleSizeReport } from './post-pr-comment.mts'; + +const workspaceRoot = dirname(dirname(fileURLToPath(import.meta.url))); +const reportPath = process.argv[2] ? resolve(process.argv[2]) : join(workspaceRoot, 'dist', 'bundle-size', 'report.md'); + +validateBundleSizeReport(await readFile(reportPath, 'utf8')); +process.stdout.write(`Validated bundle-size report: ${reportPath}\n`); diff --git a/apps/bundle-size/src/bootstrap.js b/apps/bundle-size/src/bootstrap.js deleted file mode 100644 index bb2235ff78..0000000000 --- a/apps/bundle-size/src/bootstrap.js +++ /dev/null @@ -1,8 +0,0 @@ -import React from 'react'; -import { AppRegistry, View } from 'react-native'; - -function BundleSizeApp() { - return React.createElement(View); -} - -AppRegistry.registerComponent('BundleSize', () => BundleSizeApp); diff --git a/apps/bundle-size/targets/tsconfig.check.json b/apps/bundle-size/targets/tsconfig.check.json new file mode 100644 index 0000000000..01ff1d1e87 --- /dev/null +++ b/apps/bundle-size/targets/tsconfig.check.json @@ -0,0 +1,15 @@ +{ + "extends": "@rnx-kit/tsconfig/tsconfig.node.json", + "compilerOptions": { + "rootDir": "..", + "module": "nodenext", + "moduleResolution": "nodenext", + "noEmit": true, + "allowSyntheticDefaultImports": true, + "target": "es2022", + "composite": true, + "tsBuildInfoFile": "../.cache/tsconfig.tsbuildinfo" + }, + "include": ["../scripts/**/*.mts"], + "exclude": ["../node_modules", "../lib", "../dist"] +} diff --git a/apps/bundle-size/tsconfig.json b/apps/bundle-size/tsconfig.json new file mode 100644 index 0000000000..ef3ab10de4 --- /dev/null +++ b/apps/bundle-size/tsconfig.json @@ -0,0 +1,20 @@ +{ + "files": [], + "compilerOptions": { + "composite": true + }, + "references": [ + { + "path": "../../packages/agentic/components/tsconfig.json" + }, + { + "path": "../../packages/agentic/design/tsconfig.json" + }, + { + "path": "../../scripts/tsconfig.json" + }, + { + "path": "./targets/tsconfig.check.json" + } + ] +} diff --git a/tsconfig.json b/tsconfig.json index 9444b81477..d2f500b851 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -4,6 +4,9 @@ { "path": "apps/E2E/tsconfig.json" }, + { + "path": "apps/bundle-size/tsconfig.json" + }, { "path": "apps/fluent-tester/tsconfig.json" }, @@ -19,18 +22,18 @@ { "path": "packages/agentic/components/tsconfig.json" }, - { - "path": "packages/agentic/desktop-driver/tsconfig.json" - }, { "path": "packages/agentic/design/tsconfig.json" }, { - "path": "packages/agentic/storybook-desktop-runtime/tsconfig.json" + "path": "packages/agentic/desktop-driver/tsconfig.json" }, { "path": "packages/agentic/storybook-desktop/tsconfig.json" }, + { + "path": "packages/agentic/storybook-desktop-runtime/tsconfig.json" + }, { "path": "packages/codemods/tsconfig.json" }, @@ -206,13 +209,13 @@ "path": "packages/native/Callout/tsconfig.json" }, { - "path": "packages/shim/theme-tokens/tsconfig.json" + "path": "packages/shim/theme/tsconfig.json" }, { - "path": "packages/shim/theme-types/tsconfig.json" + "path": "packages/shim/theme-tokens/tsconfig.json" }, { - "path": "packages/shim/theme/tsconfig.json" + "path": "packages/shim/theme-types/tsconfig.json" }, { "path": "packages/shim/themed-stylesheet/tsconfig.json" diff --git a/yarn.lock b/yarn.lock index ca2e8eeaf6..b2df5bfca2 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2749,27 +2749,15 @@ __metadata: version: 0.0.0-use.local resolution: "@fluentui-react-native/bundle-size@workspace:apps/bundle-size" dependencies: - "@babel/core": "catalog:" - "@babel/plugin-transform-react-jsx": "catalog:" "@fluentui-react-native/components": "workspace:*" "@fluentui-react-native/design": "workspace:*" "@fluentui-react-native/scripts": "workspace:*" "@office-iss/react-native-win32": "npm:^0.81.0" - "@react-native-community/cli": "npm:^20.0.0" - "@react-native-community/cli-platform-android": "npm:^20.0.0" - "@react-native-community/cli-platform-ios": "npm:^20.0.0" - "@react-native-windows/cli": "npm:^0.81.0" - "@react-native/babel-preset": "npm:^0.81.0" - "@react-native/metro-config": "npm:^0.81.0" - "@rnx-kit/cli": "catalog:" - "@rnx-kit/metro-config": "catalog:" - "@rnx-kit/metro-resolver-symlinks": "catalog:" - "@rnx-kit/metro-serializer-esbuild": "catalog:" "@rnx-kit/tools-filesystem": "npm:^0.2.0" "@rnx-kit/tools-formatting": "npm:^0.1.0" + "@rnx-kit/tsconfig": "catalog:" "@types/react": "npm:~19.1.4" - metro: "npm:^0.83.8" - oxc-resolver: "catalog:" + esbuild: "npm:^0.28.2" react: "npm:19.1.4" react-native: "npm:^0.81.6" react-native-macos: "npm:^0.81.0" @@ -14919,7 +14907,7 @@ __metadata: languageName: node linkType: hard -"esbuild@npm:^0.18.0 || ^0.19.0 || ^0.20.0 || ^0.21.0 || ^0.22.0 || ^0.23.0 || ^0.24.0 || ^0.25.0 || ^0.26.0 || ^0.27.0 || ^0.28.0, esbuild@npm:^0.28.0, esbuild@npm:^0.28.1": +"esbuild@npm:^0.18.0 || ^0.19.0 || ^0.20.0 || ^0.21.0 || ^0.22.0 || ^0.23.0 || ^0.24.0 || ^0.25.0 || ^0.26.0 || ^0.27.0 || ^0.28.0, esbuild@npm:^0.28.0, esbuild@npm:^0.28.1, esbuild@npm:^0.28.2": version: 0.28.2 resolution: "esbuild@npm:0.28.2" dependencies: