|
| 1 | +#!/usr/bin/env node |
| 2 | +/** |
| 3 | + * Consumer type-check budget. |
| 4 | + * |
| 5 | + * Generates a fixture in the shape large apps actually have -- many styled |
| 6 | + * components, `styled(Component)` wrapping, attrs chains, and a minority of |
| 7 | + * polymorphic `as` call sites -- type-checks it against the BUILT `dist/*.d.ts` |
| 8 | + * (what consumers and editors resolve, not `src`), and fails when types or |
| 9 | + * instantiations exceed the committed budget. |
| 10 | + * |
| 11 | + * This exists because 6.4.3 shipped a regression that tripled consumer |
| 12 | + * type-check cost and nothing in CI could see it (#5767). |
| 13 | + * |
| 14 | + * node scripts/typePerf.mjs check against the budget |
| 15 | + * node scripts/typePerf.mjs --update rewrite the budget from this run |
| 16 | + * node scripts/typePerf.mjs --count 500 |
| 17 | + * |
| 18 | + * Requires `pnpm build` first. |
| 19 | + */ |
| 20 | +import { execFileSync } from 'node:child_process'; |
| 21 | +import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; |
| 22 | +import { dirname, join, resolve } from 'node:path'; |
| 23 | +import { fileURLToPath } from 'node:url'; |
| 24 | + |
| 25 | +const pkgRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..'); |
| 26 | +const workDir = join(pkgRoot, '.type-perf'); |
| 27 | +const budgetFile = join(pkgRoot, 'type-perf.budget.json'); |
| 28 | + |
| 29 | +const args = process.argv.slice(2); |
| 30 | +const update = args.includes('--update'); |
| 31 | + |
| 32 | +// Parsed explicitly rather than via indexOf+1, which reads argv[0] when the flag |
| 33 | +// is absent (indexOf returns -1) and silently falls back to the default when the |
| 34 | +// flag is present but valueless. A miscounted fixture measures the wrong thing. |
| 35 | +const countFlag = args.indexOf('--count'); |
| 36 | +let count = 100; |
| 37 | +if (countFlag !== -1) { |
| 38 | + count = Number(args[countFlag + 1]); |
| 39 | + if (!Number.isInteger(count) || count < 1) { |
| 40 | + console.error(`type-perf: --count needs a positive integer, got ${args[countFlag + 1]}`); |
| 41 | + process.exit(1); |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +if (!existsSync(join(pkgRoot, 'dist', 'index.d.ts'))) { |
| 46 | + console.error('type-perf: dist/index.d.ts missing -- run `pnpm build` first.'); |
| 47 | + process.exit(1); |
| 48 | +} |
| 49 | + |
| 50 | +// -- fixture --------------------------------------------------------------- |
| 51 | + |
| 52 | +const TAGS = ['div', 'span', 'button', 'a', 'p', 'section', 'li', 'input']; |
| 53 | +const AS_TAGS = ['a', 'button', 'label', 'section', 'video', 'ul']; |
| 54 | + |
| 55 | +const HEADER = `import * as React from 'react'; |
| 56 | +import styled from 'styled-components'; |
| 57 | +
|
| 58 | +interface BaseProps { |
| 59 | + $variant?: 'primary' | 'secondary'; |
| 60 | + $size?: number; |
| 61 | + $active?: boolean; |
| 62 | + label?: string; |
| 63 | +} |
| 64 | +
|
| 65 | +const Plain = (props: BaseProps & { className?: string; children?: React.ReactNode }) => ( |
| 66 | + <div className={props.className}>{props.children}</div> |
| 67 | +); |
| 68 | +
|
| 69 | +const Other = (props: { href?: string; children?: React.ReactNode }) => <a {...props} />; |
| 70 | +`; |
| 71 | + |
| 72 | +function unit(i) { |
| 73 | + const tag = TAGS[i % TAGS.length]; |
| 74 | + const kind = i % 20; |
| 75 | + const N = `C${i}`; |
| 76 | + let decl; |
| 77 | + |
| 78 | + if (kind < 8) { |
| 79 | + decl = `const ${N} = styled.${tag}<{ $a${i}?: number; $b${i}?: string; $c${i}?: boolean }>\` |
| 80 | + color: \${p => (p.$c${i} ? 'red' : 'blue')}; |
| 81 | + padding: \${p => p.$a${i} ?? 0}px; |
| 82 | +\`;`; |
| 83 | + } else if (kind < 13) { |
| 84 | + decl = `const ${N} = styled(Plain)<{ $a${i}?: number }>\` |
| 85 | + margin: \${p => p.$a${i} ?? 0}px; |
| 86 | + color: \${p => (p.$active ? 'green' : 'gray')}; |
| 87 | +\`;`; |
| 88 | + } else if (kind < 16) { |
| 89 | + decl = `const ${N} = styled(${i > 0 ? `C${i - 1}` : 'Plain'})<{ $x${i}?: string }>\` |
| 90 | + border-color: \${p => p.$x${i} ?? 'black'}; |
| 91 | +\`;`; |
| 92 | + } else if (kind < 18) { |
| 93 | + decl = `const ${N} = styled.${tag}.attrs<{ $a${i}?: number }>({ $a${i}: ${i} })\` |
| 94 | + width: \${p => p.$a${i}}px; |
| 95 | +\`;`; |
| 96 | + } else { |
| 97 | + decl = `const ${N} = styled(Plain).attrs({ $size: ${i} })\` |
| 98 | + height: \${p => p.$size}px; |
| 99 | +\`;`; |
| 100 | + } |
| 101 | + |
| 102 | + const sites = [`<${N} />`, `<${N} className="x">{'t'}</${N}>`]; |
| 103 | + if (i % 10 === 0) sites.push(`<${N} as="${AS_TAGS[i % AS_TAGS.length]}" />`); |
| 104 | + if (i % 33 === 0) sites.push(`<${N} as={Other} href="/x" />`); |
| 105 | + if (i % 50 === 0) sites.push(`<${N} forwardedAs="ul" />`); |
| 106 | + |
| 107 | + return `${decl} |
| 108 | +
|
| 109 | +export const Use${i} = () => ( |
| 110 | + <> |
| 111 | + ${sites.join('\n ')} |
| 112 | + </> |
| 113 | +); |
| 114 | +`; |
| 115 | +} |
| 116 | + |
| 117 | +rmSync(workDir, { recursive: true, force: true }); |
| 118 | +mkdirSync(join(workDir, 'src'), { recursive: true }); |
| 119 | + |
| 120 | +const PER_FILE = 20; |
| 121 | +for (let start = 0, f = 0; start < count; start += PER_FILE, f++) { |
| 122 | + const body = []; |
| 123 | + for (let i = start; i < Math.min(start + PER_FILE, count); i++) body.push(unit(i)); |
| 124 | + writeFileSync(join(workDir, 'src', `mod${f}.tsx`), `${HEADER}\n${body.join('\n')}`); |
| 125 | +} |
| 126 | + |
| 127 | +writeFileSync( |
| 128 | + join(workDir, 'tsconfig.json'), |
| 129 | + `${JSON.stringify( |
| 130 | + { |
| 131 | + compilerOptions: { |
| 132 | + baseUrl: '.', |
| 133 | + jsx: 'react-jsx', |
| 134 | + lib: ['ES2021', 'DOM'], |
| 135 | + module: 'ESNext', |
| 136 | + moduleResolution: 'bundler', |
| 137 | + noEmit: true, |
| 138 | + // Resolve the package the way a consumer does, through its `types` entry. |
| 139 | + paths: { 'styled-components': ['..'] }, |
| 140 | + skipLibCheck: true, |
| 141 | + strict: true, |
| 142 | + target: 'ES2020', |
| 143 | + types: [], |
| 144 | + }, |
| 145 | + include: ['src'], |
| 146 | + }, |
| 147 | + null, |
| 148 | + 2 |
| 149 | + )}\n` |
| 150 | +); |
| 151 | + |
| 152 | +// -- measure --------------------------------------------------------------- |
| 153 | + |
| 154 | +const tsc = join(pkgRoot, 'node_modules', 'typescript', 'lib', 'tsc.js'); |
| 155 | +const tscPath = existsSync(tsc) |
| 156 | + ? tsc |
| 157 | + : resolve(pkgRoot, '..', '..', 'node_modules', 'typescript', 'lib', 'tsc.js'); |
| 158 | + |
| 159 | +function run(extraArgs) { |
| 160 | + try { |
| 161 | + return execFileSync(process.execPath, [tscPath, '-p', workDir, ...extraArgs], { |
| 162 | + encoding: 'utf8', |
| 163 | + maxBuffer: 64 * 1024 * 1024, |
| 164 | + }); |
| 165 | + } catch (error) { |
| 166 | + // tsc exits non-zero when the fixture has type errors; keep its output. |
| 167 | + return `${error.stdout ?? ''}${error.stderr ?? ''}`; |
| 168 | + } |
| 169 | +} |
| 170 | + |
| 171 | +// A fixture that fails to resolve the package type-checks almost instantly and |
| 172 | +// looks like an enormous win. Never report numbers for a run that isn't clean. |
| 173 | +const errors = run([]) |
| 174 | + .split('\n') |
| 175 | + .filter(line => line.includes('error TS')); |
| 176 | +if (errors.length > 0) { |
| 177 | + console.error(`type-perf: fixture did not compile cleanly (${errors.length} errors):`); |
| 178 | + console.error(errors.slice(0, 5).join('\n')); |
| 179 | + process.exit(1); |
| 180 | +} |
| 181 | + |
| 182 | +const out = run(['--extendedDiagnostics']); |
| 183 | +const read = label => Number((out.match(new RegExp(`^${label}:\\s+(\\d+)`, 'm')) ?? [])[1]); |
| 184 | +const measured = { instantiations: read('Instantiations'), types: read('Types') }; |
| 185 | + |
| 186 | +if (!measured.types || !measured.instantiations) { |
| 187 | + console.error('type-perf: could not parse tsc diagnostics.\n', out); |
| 188 | + process.exit(1); |
| 189 | +} |
| 190 | + |
| 191 | +const tsVersion = run(['--version']).trim(); |
| 192 | +console.log(`type-perf: ${count} components, ${tsVersion}`); |
| 193 | +console.log(` types: ${measured.types.toLocaleString()}`); |
| 194 | +console.log(` instantiations: ${measured.instantiations.toLocaleString()}`); |
| 195 | + |
| 196 | +if (update) { |
| 197 | + // Headroom absorbs ordinary compiler and @types/react patch drift while still |
| 198 | + // catching a regression of the size #5767 reported (+75% instantiations). |
| 199 | + const pad = n => Math.ceil((n * 1.15) / 1000) * 1000; |
| 200 | + writeFileSync( |
| 201 | + budgetFile, |
| 202 | + `${JSON.stringify( |
| 203 | + { count, maxInstantiations: pad(measured.instantiations), maxTypes: pad(measured.types) }, |
| 204 | + null, |
| 205 | + 2 |
| 206 | + )}\n` |
| 207 | + ); |
| 208 | + console.log(`type-perf: budget updated in ${budgetFile}`); |
| 209 | + process.exit(0); |
| 210 | +} |
| 211 | + |
| 212 | +const budget = JSON.parse(readFileSync(budgetFile, 'utf8')); |
| 213 | +if (budget.count !== count) { |
| 214 | + console.error(`type-perf: budget is for ${budget.count} components, measured ${count}.`); |
| 215 | + process.exit(1); |
| 216 | +} |
| 217 | + |
| 218 | +const over = [ |
| 219 | + ['types', measured.types, budget.maxTypes], |
| 220 | + ['instantiations', measured.instantiations, budget.maxInstantiations], |
| 221 | +].filter(([, actual, max]) => actual > max); |
| 222 | + |
| 223 | +if (over.length > 0) { |
| 224 | + for (const [label, actual, max] of over) { |
| 225 | + console.error( |
| 226 | + `type-perf: ${label} ${actual.toLocaleString()} exceeds budget ${max.toLocaleString()} ` + |
| 227 | + `(+${Math.round((actual / max - 1) * 100)}%)` |
| 228 | + ); |
| 229 | + } |
| 230 | + console.error( |
| 231 | + 'Consumer type-check cost grew. Find the cause before raising the budget; ' + |
| 232 | + 'run with --update only when the increase is understood and intended.' |
| 233 | + ); |
| 234 | + process.exit(1); |
| 235 | +} |
| 236 | + |
| 237 | +console.log('type-perf: within budget'); |
0 commit comments