| 1 | // Builds the stress kit (packages/stress): every level of every load of loads.ts as a widget, and |
| 2 | // manifest.json. Then the gates, which fail the build: |
| 3 | // - size: every widget is a mini-widget (at most 3800 B after zlib at level 9 and 32 KB of HTML); |
| 4 | // - through the sandbox (the dev app, Shadow DOM renderer, the measuring configuration of CLIENTS.md): |
| 5 |
| // every widget boots, publishes `data-stress` and keeps its frame loop running, uses nothing outside |
| 6 | // widget profile 1 (no profile, dropped-CSS, dropped-tag or blocked-URL diagnostic), throws nothing, |
| 7 | // and is at most 560 px tall at 320 px wide. The nodes and the largest validated batch it measures go |
| 8 | // into the manifest next to the table's estimates. |
| 9 | // |
| 10 | // corepack pnpm tsx scripts/stress/build.ts [--sizes] [--origin http://127.0.0.1:5178] [--only shadow-] |
| 11 | // Without --origin it starts a dev server of this checkout on a free port; --sizes skips the sandbox gate |
| 12 | // (and keeps the measured values of the last full build). |
| 13 |
| 14 | import fs from 'node:fs'; |
| 15 | import path from 'node:path'; |
| 16 | import { chromium } from '@playwright/test'; |
| 17 | import { MAX_HEIGHT, MEASURE_PARAMS, SIZE_LIMIT, STRESS, WIDGETS, crossesOf, generate, loadWidget, openDevApp, published, withDevServer, type Manifest, type ManifestWidget } from './lib'; |
| 18 |
| 19 | const args = process.argv.slice(2); |
| 20 | const opt = (name: string) => (args.includes('--' + name) ? args[args.indexOf('--' + name) + 1] : undefined); |
| 21 | const ONLY = opt('only'); |
| 22 |
| 23 | /** Diagnostics that mean a widget used something outside widget profile 1 or the validator removed part of it. */ |
| 24 | const PROFILE_DIAGS = /^(profile|css-dropped|tag-dropped|tag-replaced|attr-dropped|url-blocked|protocol-violation)$/; |
| 25 |
| 26 | async function gate(widgets: (ManifestWidget & { html: string })[], origin: string): Promise<string[]> { |
| 27 | const failures: string[] = []; |
| 28 | const browser = await chromium.launch(); |
| 29 | const page = await (await browser.newContext({ viewport: { width: 1200, height: 1000 }, deviceScaleFactor: 2 })).newPage(); |
| 30 | await openDevApp(page, origin, 'shadow', MEASURE_PARAMS); |
| 31 | console.log(`\nthrough the sandbox (${origin}, shadow, compat): boots, frames, profile, at most ${MAX_HEIGHT.height} px at ${MAX_HEIGHT.width} px wide`); |
| 32 | for (const w of widgets) { |
| 33 | await loadWidget(page, w.html, `stress/${w.id}.html`, MAX_HEIGHT.width); |
| 34 | const t0 = Date.now(); |
| 35 | let pub = null; |
| 36 | let dead: string | null = null; |
| 37 | // Two publishes after the first frame: the loop runs, and the second one carries a whole second of frames. |
| 38 | while (Date.now() - t0 < 20_000) { |
| 39 | pub = await published(page); |
| 40 | dead = await page.evaluate(() => (window as any).__tw.state.dead); |
| 41 | if (dead || (pub && pub.status === 'running' && pub.t >= 1000)) break; |
| 42 | await page.waitForTimeout(150); |
| 43 | } |
| 44 | await page.waitForTimeout(300); |
| 45 | const s = await page.evaluate(() => { |
| 46 | const st = (window as any).__tw.state, x = (window as any).__stress; |
| 47 | return { height: Math.ceil(x.height), maxBatch: x.maxBatch, nodes: st.stats?.nodes ?? 0, diags: Object.fromEntries(Object.entries(st.diags as Record<string, { count: number; details: string[] }>).map(([k, v]) => [k, v.details[0] ?? ''])), errors: (st.logs as { level: string; text: string }[]).filter((l) => l.level === 'error').map((l) => l.text.split('\n')[0]) }; |
| 48 | }); |
| 49 | const bad: string[] = []; |
| 50 | if (dead) bad.push(`died: ${dead}`); |
| 51 | else if (!pub || pub.status !== 'running' || pub.frames < 2) bad.push(`no running data-stress (${pub ? pub.status + ', ' + pub.frames + ' frames' : 'none'})`); |
| 52 | const profile = Object.entries(s.diags).filter(([k]) => PROFILE_DIAGS.test(k)); |
| 53 | if (profile.length) bad.push('outside the profile: ' + profile.map(([k, d]) => `${k} ${d}`).join('; ').slice(0, 200)); |
| 54 | if (s.errors.length) bad.push('errors: ' + s.errors.join('; ').slice(0, 200)); |
| 55 | if (s.height > MAX_HEIGHT.height) bad.push(`${s.height} px tall`); |
| 56 | w.measured = { nodes: s.nodes, maxBatchOps: s.maxBatch, height: s.height }; |
| 57 | console.log(` ${w.id.padEnd(30)} ${String(s.height).padStart(4)} px ${String(s.nodes).padStart(5)} nodes ${String(s.maxBatch).padStart(6)} ops/batch ${pub ? String(pub.fps).padStart(3) + ' fps' : ''}${bad.length ? ' FAIL ' + bad.join(' | ') : ''}`); |
| 58 | if (bad.length) failures.push(`${w.id}: ${bad.join(' | ')}`); |
| 59 | } |
| 60 | await browser.close(); |
| 61 | return failures; |
| 62 | } |
| 63 |
| 64 | /** The README's table of loads, between its stress:loads markers. */ |
| 65 | function writeReadmeTable(m: Manifest) { |
| 66 | const file = path.join(STRESS, 'README.md'); |
| 67 | const rows = ['| load | what it stresses | levels (over a strict limit in bold) | fit |', '|---|---|---|---|']; |
| 68 | for (const l of m.loads) { |
| 69 | const levels = l.widgets.map((id) => m.widgets.find((w) => w.id === id)!).map((w) => (w.crosses.length ? `**${w.value}**` : String(w.value))).join(', '); |
| 70 | rows.push(`| \`${l.id}\` | ${l.title}: ${l.stresses} | ${levels} ${l.unit} | ${l.fit === 'heavy' ? 'A' : l.fit === 'plain' ? 'B' : ''} |`); |
| 71 | } |
| 72 | const text = fs.readFileSync(file, 'utf8'); |
| 73 | const begin = '<!-- stress:loads -->', end = '<!-- /stress:loads -->'; |
| 74 | const i = text.indexOf(begin), j = text.indexOf(end); |
| 75 | if (i < 0 || j < i) throw new Error('README.md has no stress:loads markers'); |
| 76 | fs.writeFileSync(file, text.slice(0, i + begin.length) + '\n' + rows.join('\n') + '\n' + text.slice(j)); |
| 77 | } |
| 78 |
| 79 | async function main() { |
| 80 | const { widgets: all, manifest } = generate(); |
| 81 | const widgets = ONLY ? all.filter((w) => w.id.includes(ONLY)) : all; |
| 82 | // A partial or --sizes build keeps the measured values of the last full build. |
| 83 | const prevFile = path.join(STRESS, 'manifest.json'); |
| 84 | const prev = fs.existsSync(prevFile) ? new Map((JSON.parse(fs.readFileSync(prevFile, 'utf8')) as Manifest).widgets.map((w) => [w.id, w.measured])) : new Map(); |
| 85 | for (const w of all) w.measured = prev.get(w.id); |
| 86 |
| 87 | if (!ONLY) fs.rmSync(WIDGETS, { recursive: true, force: true }); |
| 88 | for (const w of widgets) { |
| 89 | fs.mkdirSync(path.dirname(path.join(STRESS, w.file)), { recursive: true }); |
| 90 | fs.writeFileSync(path.join(STRESS, w.file), w.html); |
| 91 | } |
| 92 | console.log(`${widgets.length} widgets in ${manifest.loads.length} loads`); |
| 93 | const over = widgets.filter((w) => w.size.zlib > SIZE_LIMIT.zlib || w.size.raw > SIZE_LIMIT.raw); |
| 94 | const largest = [...widgets].sort((a, b) => b.size.zlib - a.size.zlib)[0]; |
| 95 | console.log(`largest: ${largest.id}, ${largest.size.zlib} B after zlib -9, ${largest.size.raw} B of HTML (limits ${SIZE_LIMIT.zlib} / ${SIZE_LIMIT.raw})`); |
| 96 | for (const w of over) console.log(` OVER ${w.id}: ${w.size.zlib} B compressed, ${w.size.raw} B of HTML`); |
| 97 |
| 98 | let failures: string[] = over.map((w) => `${w.id}: too large`); |
| 99 | if (!args.includes('--sizes')) failures.push(...(await withDevServer(opt('origin'), (origin) => gate(widgets, origin)))); |
| 100 |
| 101 | for (const w of all) w.crosses = crossesOf(w); |
| 102 | const out: Manifest = { ...manifest, widgets: all.map(({ html: _h, ...w }) => w) }; |
| 103 | fs.writeFileSync(prevFile, JSON.stringify(out, null, 1) + '\n'); |
| 104 | writeReadmeTable(out); |
| 105 | if (failures.length) { |
| 106 | console.log(`\n${failures.length} widget(s) failed:`); |
| 107 | for (const f of failures) console.log(' ' + f); |
| 108 | process.exitCode = 1; |
| 109 | } else console.log('\nall gates passed'); |
| 110 | } |
| 111 |
| 112 | main().catch((e) => { console.error(e); process.exit(1); }); |
| 113 |