diff --git a/client/CLAUDE.md b/client/CLAUDE.md index 56b73f0b2..6dbf6927a 100644 --- a/client/CLAUDE.md +++ b/client/CLAUDE.md @@ -11,7 +11,7 @@ npm run typecheck # tsc --noEmit (CI) npm run lint # eslint . (lint:check in CI) npm run lint:pages # enforce the Page pattern (CI gate) npm run lint:rtl # physical left/right sides may only shrink per file (CI gate; --list shows them, --update lowers the baseline) -npm run lint:size # no source file past 1000 lines; longer ones may only shrink (CI gate; --update lowers the baseline) +npm run lint:size # no source file or stylesheet past 1000 lines, no test past 2000, counted wrapped at 120 columns; longer ones may only shrink (CI gate; --update lowers the baseline) npm run test # vitest run (tests/** + co-located src/**/*.test.{ts,tsx}); also test:unit / test:integration / test:coverage npm run e2e # Playwright (CI runs --project=public --project=app; e2e:report opens the last report) npm run shots # Playwright screenshot project (shots:promote to accept) diff --git a/client/scripts/lib/ratchet.mjs b/client/scripts/lib/ratchet.mjs new file mode 100644 index 000000000..57ba97091 --- /dev/null +++ b/client/scripts/lib/ratchet.mjs @@ -0,0 +1,148 @@ +/* + * The parts every ratchet in scripts/ shares: walking the tree, reading a file + * the same way on Windows and Linux, and reading, lowering and writing a + * baseline. + * + * A ratchet fails closed. A baseline that is missing, cannot be parsed or has + * the wrong shape stops the run with its reason instead of reading as empty + * (as empty, the check would fail with no hint at the cause, and --update + * would write an empty file over the real one). A directory that should be + * scanned and is not there, or a scan that finds no file at all, stops it too: + * a check that looked at nothing must not report green. + */ +import { existsSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs' +import { basename, join, relative } from 'node:path' + +/** A problem with the check itself rather than a violation it found. */ +export class RatchetError extends Error {} + +export const TEST_FILE = /\.(?:test|spec)\.[cm]?[jt]sx?$/ + +/** Every file under root/ for each dir whose path passes accept, as absolute paths. */ +export function listFiles(root, dirs, accept) { + const files = [] + const walk = (dir) => { + for (const name of readdirSync(dir)) { + if (name === 'node_modules') continue + const path = join(dir, name) + if (statSync(path).isDirectory()) walk(path) + else if (accept(toKey(root, path))) files.push(path) + } + } + for (const dir of dirs) { + const path = join(root, dir) + if (!existsSync(path) || !statSync(path).isDirectory()) { + throw new RatchetError(`${dir}/ does not exist under ${root}, so there is nothing to check`) + } + walk(path) + } + if (!files.length) throw new RatchetError(`no file to check under ${dirs.map((d) => `${d}/`).join(', ')}`) + return files.sort() +} + +/** A path relative to root with forward slashes, the form every baseline uses. */ +export function toKey(root, path) { + return relative(root, path).split('\\').join('/') +} + +/** + * A text file as the repository holds it: without a byte order mark and with + * LF line ends, so a Windows checkout with CRLF counts the same as CI. + */ +export function readText(path) { + const text = readFileSync(path, 'utf8') + return (text.charCodeAt(0) === 0xfeff ? text.slice(1) : text).replace(/\r\n?/g, '\n') +} + +const isCount = (n) => Number.isInteger(n) && n > 0 + +/** A JSON object of file → positive count. */ +export function countMap(value) { + if (!value || typeof value !== 'object' || Array.isArray(value)) return 'it is not an object of file → count' + for (const [key, n] of Object.entries(value)) if (!isCount(n)) return `"${key}" holds ${JSON.stringify(n)}, not a positive whole number` + return null +} + +/** A JSON array of distinct file paths. */ +export function fileList(value) { + if (!Array.isArray(value)) return 'it is not an array of file paths' + const seen = new Set() + for (const entry of value) { + if (typeof entry !== 'string' || !entry) return `${JSON.stringify(entry)} is not a file path` + if (seen.has(entry)) return `"${entry}" is listed twice` + seen.add(entry) + } + return null +} + +/** + * The baseline as committed, checked against shape (one of the validators + * above, which returns null when the value fits and the reason otherwise). + */ +export function readBaseline(path, shape) { + const name = basename(path) + let text + try { + text = readFileSync(path, 'utf8') + } catch (err) { + throw new RatchetError(`scripts/${name} cannot be read (${err.code ?? err.message}); restore it from git`) + } + let value + try { + value = JSON.parse(text) + } catch (err) { + throw new RatchetError(`scripts/${name} is not valid JSON (${err.message}); restore it from git`) + } + const problem = shape(value) + if (problem) throw new RatchetError(`scripts/${name} has the wrong shape: ${problem}; restore it from git`) + return value +} + +/** Writes value as sorted, two-space JSON with a final newline. */ +export function writeBaseline(path, value) { + const sorted = Array.isArray(value) + ? [...value].sort() + : Object.fromEntries(Object.entries(value).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) + writeFileSync(path, JSON.stringify(sorted, null, 2) + '\n') +} + +/** + * The baseline lowered to the counts measured now. An entry never rises, a + * file that is not in the baseline never enters it, and an entry whose count + * fell to floor or below leaves. floor is a number, or a function of the key + * when the limit differs between files. + * + * @param {Record} baseline + * @param {Record} counts + * @param {number | ((key: string) => number)} [floor] + */ +export function lowerCounts(baseline, counts, floor = 0) { + const lowered = {} + for (const [key, allowed] of Object.entries(baseline)) { + const now = counts[key] ?? 0 + if (now > (typeof floor === 'function' ? floor(key) : floor)) lowered[key] = Math.min(allowed, now) + } + return lowered +} + +/** The baseline entries that are still offenders: a list only ever loses files. */ +export function lowerList(baseline, offenders) { + const now = new Set(offenders) + return baseline.filter((file) => now.has(file)) +} + +/** + * Runs one ratchet as a command. main returns the exit code; a RatchetError is + * printed as a failure of the check itself. There is no "am I the entry + * point" guard to get wrong: the command files only ever run, and the logic + * they call lives in scripts/lib/ where tests import it. + */ +export async function runCli(name, main) { + try { + process.exitCode = await main(process.argv.slice(2)) + } catch (err) { + if (!(err instanceof RatchetError)) throw err + console.error(`FAIL ${name}: ${err.message}`) + process.exitCode = 1 + } +} diff --git a/client/scripts/lib/size.mjs b/client/scripts/lib/size.mjs new file mode 100644 index 000000000..dd4af41e9 --- /dev/null +++ b/client/scripts/lib/size.mjs @@ -0,0 +1,78 @@ +/* + * The measuring and the comparison behind lint:size (scripts/size-lint.mjs). + * + * A file's size is its lines as an editor wraps them at WIDTH columns: a line + * up to WIDTH characters counts once, a longer one once per WIDTH characters + * it spans. Counting newlines alone let a file stay under its entry by joining + * lines, and the trip planner page already held a 3760 character one; WIDTH is + * the printWidth in .prettierrc, so formatted code counts what it shows. + */ +import { join } from 'node:path' +import { countMap, listFiles, lowerCounts, readBaseline, readText, TEST_FILE, toKey, writeBaseline } from './ratchet.mjs' + +export const WIDTH = 120 + +/** + * The kinds of file the check covers, each with the size a file without a + * baseline entry may reach. Tests get more room: a spec mirrors the component + * it covers and holds fixtures, but past LIMIT it is a god file too. + */ +export const GROUPS = [ + { name: 'test', limit: 2000, accepts: (key) => /\.tsx?$/.test(key) && (key.startsWith('tests/') || TEST_FILE.test(key)) }, + { name: 'source', limit: 1000, accepts: (key) => key.startsWith('src/') && /\.tsx?$/.test(key) && !TEST_FILE.test(key) }, + { name: 'stylesheet', limit: 1000, accepts: (key) => key.startsWith('src/') && key.endsWith('.css') }, +] + +export const DIRS = ['src', 'tests'] + +export function groupOf(key) { + return GROUPS.find((group) => group.accepts(key)) ?? null +} + +/** The size of a text as wrapped at WIDTH; a final newline does not start another line. */ +export function sizeOf(text) { + if (text === '') return 0 + const lines = text.replace(/\r\n?/g, '\n').split('\n') + if (text.endsWith('\n')) lines.pop() + return lines.reduce((sum, line) => sum + Math.max(1, Math.ceil(line.length / WIDTH)), 0) +} + +/** Every covered file under root with its size, keyed by its path from root. */ +export function measure(root) { + const sizes = {} + for (const path of listFiles(root, DIRS, (key) => groupOf(key) !== null)) sizes[toKey(root, path)] = sizeOf(readText(path)) + return sizes +} + +const limitOf = (key) => groupOf(key)?.limit ?? 0 + +/** + * Runs the check against the baseline at baselinePath. With update, the + * baseline is lowered first. Returns the exit code. + */ +export function check({ root, baselinePath = join(root, 'scripts/size-baseline.json'), update = false, log = console.log, error = console.error }) { + const sizes = measure(root) + let baseline = readBaseline(baselinePath, countMap) + + if (update) { + baseline = lowerCounts(baseline, sizes, limitOf) + writeBaseline(baselinePath, baseline) + } + + const grown = Object.entries(sizes).filter(([key, n]) => n > Math.max(baseline[key] ?? 0, limitOf(key))) + const lowerable = Object.entries(baseline).filter(([key, n]) => (sizes[key] ?? 0) < n) + + for (const [key, n] of grown) { + const entry = baseline[key] + error( + `FAIL ${key}: ${n} lines (wrapped at ${WIDTH} columns), ` + + (entry ? `its baseline is ${entry}. ` : `the limit for a ${groupOf(key).name} file is ${limitOf(key)}. `) + + 'Move a concern into a module of its own instead of growing the file or packing its lines.', + ) + } + if (lowerable.length && !update) { + log(`${lowerable.length} file(s) are smaller than their baseline now: run with --update to lower it.`) + } + log(`size: ${Object.keys(sizes).length} file(s), ${Object.keys(baseline).length} past their limit held at their baseline`) + return grown.length ? 1 : 0 +} diff --git a/client/scripts/size-baseline.json b/client/scripts/size-baseline.json index 5dcf30138..39a9323ab 100644 --- a/client/scripts/size-baseline.json +++ b/client/scripts/size-baseline.json @@ -1,24 +1,38 @@ { - "api/client.ts": 1685, - "components/Admin/AdminPluginsPanel.tsx": 2274, - "components/Budget/CostsPanel.tsx": 2107, - "components/Map/MapView.tsx": 1482, - "components/Map/MapViewGL.tsx": 2572, - "components/Map/RouteCalculator.ts": 1190, - "components/PDF/TripPDF.tsx": 1025, - "components/Planner/DayPlanSidebar.tsx": 3051, - "components/Planner/PlaceFormModal.tsx": 1633, - "components/Planner/PlaceInspector.tsx": 1273, - "components/Planner/TransportModal.tsx": 1199, - "components/Studio/autoLayout.ts": 1676, - "components/Studio/bookTemplates.data.ts": 1279, - "components/Studio/TravelElements.tsx": 1745, - "mobile/screens/admin/MAdminPluginsPanel.tsx": 2105, - "mobile/screens/journey/MJourneyEntrySheet.tsx": 1060, - "mobile/screens/trip/sheets/MTransportFormSheet.tsx": 1127, - "mobile/screens/trip/tabs/MCostsTab.tsx": 1011, - "mobile/screens/trip/tabs/MPackingListTab.tsx": 1017, - "pages/atlas/useAtlas.ts": 1246, - "pages/LoginPage.tsx": 1340, - "pages/TripPlannerPage.tsx": 1081 + "src/api/client.ts": 1916, + "src/components/Admin/AdminPluginsPanel.test.tsx": 2704, + "src/components/Admin/AdminPluginsPanel.tsx": 2431, + "src/components/Budget/CostsPanel.test.tsx": 2854, + "src/components/Budget/CostsPanel.tsx": 2366, + "src/components/Journey/JourneyDetailPageEntryEditor.tsx": 1014, + "src/components/Map/MapView.tsx": 1526, + "src/components/Map/MapViewGL.test.tsx": 2920, + "src/components/Map/MapViewGL.tsx": 2607, + "src/components/Map/RouteCalculator.ts": 1196, + "src/components/PDF/TripPDF.tsx": 1097, + "src/components/Planner/DayDetailPanel.test.tsx": 2333, + "src/components/Planner/DayPlanSidebar.test.tsx": 5400, + "src/components/Planner/DayPlanSidebar.tsx": 3319, + "src/components/Planner/PlaceFormModal.test.tsx": 2864, + "src/components/Planner/PlaceFormModal.tsx": 1669, + "src/components/Planner/PlaceInspector.tsx": 1357, + "src/components/Planner/TransportModal.tsx": 1254, + "src/components/Studio/TravelElements.tsx": 1747, + "src/components/Studio/autoLayout.ts": 1691, + "src/components/Studio/bookTemplates.data.ts": 1309, + "src/components/Studio/countryShapes.ts": 2595, + "src/index.css": 1636, + "src/mobile/screens/admin/MAdminPluginsPanel.tsx": 2262, + "src/mobile/screens/journey/MJourneyEntrySheet.tsx": 1122, + "src/mobile/screens/trip/sheets/MTransportFormSheet.tsx": 1194, + "src/mobile/screens/trip/tabs/MCostsTab.tsx": 1095, + "src/mobile/screens/trip/tabs/MPackingListTab.tsx": 1080, + "src/pages/JourneyDetailPage.test.tsx": 4030, + "src/pages/LoginPage.tsx": 1348, + "src/pages/TripPlannerPage.tsx": 1259, + "src/pages/TripPlannerPage.wiring.test.tsx": 2049, + "src/pages/atlas/useAtlas.ts": 1288, + "src/pages/tripPlanner/useTripPlanner.roadtrip.test.tsx": 3531, + "src/pages/tripPlanner/useTripPlanner.test.tsx": 3307, + "src/styles/studio.css": 2087 } diff --git a/client/scripts/size-lint.mjs b/client/scripts/size-lint.mjs index 6447ad69c..26e4ee179 100644 --- a/client/scripts/size-lint.mjs +++ b/client/scripts/size-lint.mjs @@ -1,101 +1,27 @@ #!/usr/bin/env node /* - * lint:size: keeps source files from growing into the next god file. + * lint:size: keeps files from growing into the next god file. * * A file past a thousand lines holds several concerns that no longer fit in * one reading, and every change to one of them risks the others. Each source - * file under src/ (tests aside) may hold LIMIT lines; the files that were - * already longer are listed in scripts/size-baseline.json with the length - * they had, and the check fails when one of them grows past its entry. A + * file and stylesheet under src/ may hold 1000 lines, each test (under tests/ + * or a co-located *.test.*) 2000. Lines are counted as an editor wraps them + * at 120 columns, so joining lines does not make a file smaller. The files + * that were already larger are listed in scripts/size-baseline.json with the + * size they had, and the check fails when one of them grows past its entry. A * file that needs to grow is split by concern instead (the trip planner hook, * page and road trip sidebar are the precedent). * * npm run lint:size check against the baseline (CI) * npm run lint:size -- --update lower the baseline to what the files hold now; * it never raises an entry, and drops a file - * that is back under the limit + * that is back under its limit + * + * The measuring lives in scripts/lib/size.mjs. */ -import { existsSync, readdirSync, readFileSync, realpathSync, statSync, writeFileSync } from 'node:fs' -import { join, relative } from 'node:path' import { fileURLToPath } from 'node:url' +import { runCli } from './lib/ratchet.mjs' +import { check } from './lib/size.mjs' -const SRC = fileURLToPath(new URL('../src', import.meta.url)) -const BASELINE = fileURLToPath(new URL('./size-baseline.json', import.meta.url)) - -/** The most lines a file without a baseline entry may hold. */ -export const LIMIT = 1000 - -function walk(dir, files = []) { - for (const name of readdirSync(dir)) { - const path = join(dir, name) - if (statSync(path).isDirectory()) walk(path, files) - else if (/\.tsx?$/.test(name) && !/\.(?:test|spec)\./.test(name)) files.push(path) - } - return files -} - -/** Lines as an editor numbers them: a final newline does not start another. */ -export function lineCount(text) { - if (text === '') return 0 - const breaks = text.split('\n').length - 1 - return text.endsWith('\n') ? breaks : breaks + 1 -} - -function scan() { - const counts = {} - for (const path of walk(SRC)) counts[relative(SRC, path).split('\\').join('/')] = lineCount(readFileSync(path, 'utf8')) - return counts -} - -/** - * The baseline as committed. A missing file is an empty baseline. One that cannot be - * read or parsed stops the run with its reason: read as empty, every long file would - * fail with no hint at the cause, and --update would replace it with an empty one. - */ -function readBaseline() { - try { - return JSON.parse(readFileSync(BASELINE, 'utf8')) - } catch (err) { - if (err.code === 'ENOENT') return {} - console.error(`FAIL scripts/size-baseline.json cannot be read: ${err.message}`) - console.error('Restore the file from git before running the check or --update again.') - process.exit(1) - } -} - -// Compared by real path, so the check still runs when the script is started through a symlink. -const isCli = - Boolean(process.argv[1]) && existsSync(process.argv[1]) && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url) -if (isCli) { - const counts = scan() - let baseline = readBaseline() - - if (process.argv.includes('--update')) { - const lowered = {} - for (const [file, allowed] of Object.entries(baseline)) { - const now = counts[file] ?? 0 - if (now > LIMIT) lowered[file] = Math.min(allowed, now) - } - const sorted = Object.fromEntries(Object.entries(lowered).sort(([a], [b]) => a.localeCompare(b))) - writeFileSync(BASELINE, JSON.stringify(sorted, null, 2) + '\n') - baseline = sorted - } - - const grown = Object.entries(counts).filter(([file, n]) => n > Math.max(baseline[file] ?? 0, LIMIT)) - const lowerable = Object.entries(baseline).filter(([file, n]) => (counts[file] ?? 0) < n) - - for (const [file, n] of grown) { - const entry = baseline[file] - console.error( - `FAIL ${file}: ${n} lines, ` + - (entry ? `its baseline is ${entry}. ` : `the limit is ${LIMIT}. `) + - 'Move a concern into a hook or component of its own instead of growing the file.', - ) - } - if (lowerable.length && !process.argv.includes('--update')) { - console.log(`${lowerable.length} file(s) are shorter than their baseline now: run with --update to lower it.`) - } - const listed = Object.keys(baseline).length - console.log(`size: ${Object.keys(counts).length} file(s), ${listed} over ${LIMIT} lines held at their baseline`) - if (grown.length) process.exit(1) -} +const root = fileURLToPath(new URL('..', import.meta.url)) +await runCli('lint:size', (args) => check({ root, update: args.includes('--update') })) diff --git a/client/tests/helpers/ratchetFixture.ts b/client/tests/helpers/ratchetFixture.ts new file mode 100644 index 000000000..fe2df018a --- /dev/null +++ b/client/tests/helpers/ratchetFixture.ts @@ -0,0 +1,47 @@ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join } from 'node:path'; + +/** + * A throwaway client tree for the ratchet scripts in scripts/lib/: each key is + * a path from the tree's root, each value the file's text. The checks are run + * against it with their output collected, so a test sees exactly what CI would + * print and the exit code it would end with. + */ +export interface RatchetTree { + root: string; + write: (files: Record) => void; + path: (key: string) => string; + log: string[]; + error: string[]; + out: { log: (line: string) => void; error: (line: string) => void }; + remove: () => void; +} + +export function ratchetTree(files: Record = {}): RatchetTree { + const root = mkdtempSync(join(tmpdir(), 'trek-ratchet-')); + const log: string[] = []; + const error: string[] = []; + const write = (more: Record) => { + for (const [key, text] of Object.entries(more)) { + const path = join(root, key); + mkdirSync(dirname(path), { recursive: true }); + writeFileSync(path, text); + } + }; + write(files); + return { + root, + write, + path: (key) => join(root, key), + log, + error, + out: { log: (line) => log.push(line), error: (line) => error.push(line) }, + remove: () => rmSync(root, { recursive: true, force: true }), + }; +} + +/** n lines of short code, each ending in a newline. */ +export function lines(n: number, text = 'const a = 1'): string { + return `${text}\n`.repeat(n); +} diff --git a/client/tests/unit/scripts/ratchet.test.ts b/client/tests/unit/scripts/ratchet.test.ts new file mode 100644 index 000000000..0dc3ce67e --- /dev/null +++ b/client/tests/unit/scripts/ratchet.test.ts @@ -0,0 +1,82 @@ +import { afterEach, describe, expect, it } from 'vitest'; +import { + countMap, + fileList, + listFiles, + lowerCounts, + lowerList, + RatchetError, + readBaseline, + readText, + writeBaseline, +} from '../../../scripts/lib/ratchet.mjs'; +import { ratchetTree, type RatchetTree } from '../../helpers/ratchetFixture'; + +let tree: RatchetTree; +afterEach(() => tree?.remove()); + +describe('scripts/lib/ratchet', () => { + it('RATCHET-001: lists the accepted files under each directory, sorted', () => { + tree = ratchetTree({ 'src/b.ts': '', 'src/a/c.tsx': '', 'src/d.css': '', 'tests/e.ts': '' }); + const files = listFiles(tree.root, ['src', 'tests'], (key: string) => /\.tsx?$/.test(key)); + expect( + files.map((f: string) => + f + .slice(tree.root.length + 1) + .split('\\') + .join('/') + ) + ).toEqual(['src/a/c.tsx', 'src/b.ts', 'tests/e.ts']); + }); + + it('RATCHET-002: a directory that is not there stops the scan instead of passing it', () => { + tree = ratchetTree({ 'src/a.ts': '' }); + expect(() => listFiles(tree.root, ['src', 'tests'], () => true)).toThrow(RatchetError); + expect(() => listFiles(tree.root, ['src', 'tests'], () => true)).toThrow(/tests\/ does not exist/); + }); + + it('RATCHET-003: a scan that finds no file at all fails', () => { + tree = ratchetTree({ 'src/a.md': '' }); + expect(() => listFiles(tree.root, ['src'], (key: string) => key.endsWith('.ts'))).toThrow(/no file to check/); + }); + + it('RATCHET-004: reads CRLF and a byte order mark as the LF text git holds', () => { + tree = ratchetTree({ 'a.ts': '\uFEFFone\r\ntwo\r\n' }); + expect(readText(tree.path('a.ts'))).toBe('one\ntwo\n'); + }); + + it('RATCHET-005: a missing, broken or misshapen baseline is an error, never an empty one', () => { + tree = ratchetTree({ + 'broken.json': '{ "a": ', + 'array.json': '["a"]', + 'zero.json': '{ "a": 0 }', + 'twice.json': '["a", "a"]', + }); + expect(() => readBaseline(tree.path('missing.json'), countMap)).toThrow(/cannot be read/); + expect(() => readBaseline(tree.path('broken.json'), countMap)).toThrow(/not valid JSON/); + expect(() => readBaseline(tree.path('array.json'), countMap)).toThrow(/wrong shape/); + expect(() => readBaseline(tree.path('zero.json'), countMap)).toThrow(/positive whole number/); + expect(() => readBaseline(tree.path('twice.json'), fileList)).toThrow(/listed twice/); + }); + + it('RATCHET-006: writes a baseline sorted, with a final newline, and reads it back', () => { + tree = ratchetTree(); + writeBaseline(tree.path('b.json'), { 'src/z.ts': 2, 'src/a.ts': 1 }); + expect(readText(tree.path('b.json'))).toBe('{\n "src/a.ts": 1,\n "src/z.ts": 2\n}\n'); + expect(readBaseline(tree.path('b.json'), countMap)).toEqual({ 'src/a.ts': 1, 'src/z.ts': 2 }); + }); + + it('RATCHET-007: lowering never raises an entry, never adds one and drops what fell to the floor', () => { + const lowered = lowerCounts( + { grew: 5, shrank: 5, gone: 5, floor: 5 }, + { grew: 9, shrank: 3, floor: 2, fresh: 7 }, + 2 + ); + expect(lowered).toEqual({ grew: 5, shrank: 3 }); + expect(lowerCounts({ a: 9 }, { a: 4 }, (key: string) => (key === 'a' ? 4 : 0))).toEqual({}); + }); + + it('RATCHET-008: a file list only loses the files that stopped offending', () => { + expect(lowerList(['a', 'b', 'c'], ['c', 'a', 'new'])).toEqual(['a', 'c']); + }); +}); diff --git a/client/tests/unit/scripts/size-lint.test.ts b/client/tests/unit/scripts/size-lint.test.ts new file mode 100644 index 000000000..cab635499 --- /dev/null +++ b/client/tests/unit/scripts/size-lint.test.ts @@ -0,0 +1,87 @@ +import { readFileSync } from 'node:fs'; +import { afterEach, describe, expect, it } from 'vitest'; +import { RatchetError } from '../../../scripts/lib/ratchet.mjs'; +import { check, groupOf, sizeOf, WIDTH } from '../../../scripts/lib/size.mjs'; +import { lines, ratchetTree, type RatchetTree } from '../../helpers/ratchetFixture'; + +let tree: RatchetTree; +afterEach(() => tree?.remove()); + +const BASELINE = 'scripts/size-baseline.json'; + +function run(baseline: Record, files: Record, update = false) { + tree = ratchetTree({ [BASELINE]: JSON.stringify(baseline), 'tests/keep.test.ts': lines(1), ...files }); + return check({ root: tree.root, baselinePath: tree.path(BASELINE), update, ...tree.out }); +} + +describe('lint:size', () => { + it('SIZE-001: counts lines as an editor wraps them, so joining lines does not shrink a file', () => { + expect(sizeOf('')).toBe(0); + expect(sizeOf('a\nb\n')).toBe(2); + expect(sizeOf('a\nb')).toBe(2); + expect(sizeOf('a\r\nb\r\n')).toBe(2); + expect(sizeOf('x'.repeat(WIDTH))).toBe(1); + expect(sizeOf('x'.repeat(WIDTH + 1))).toBe(2); + expect(sizeOf(`${'x'.repeat(3760)}\n`)).toBe(Math.ceil(3760 / WIDTH)); + expect(sizeOf('\n\n')).toBe(2); + }); + + it('SIZE-002: sorts files into source, stylesheet and test, each with its own limit', () => { + expect(groupOf('src/a/B.tsx')).toMatchObject({ name: 'source', limit: 1000 }); + expect(groupOf('src/index.css')).toMatchObject({ name: 'stylesheet', limit: 1000 }); + expect(groupOf('src/a/B.test.tsx')).toMatchObject({ name: 'test', limit: 2000 }); + expect(groupOf('tests/unit/x.ts')).toMatchObject({ name: 'test', limit: 2000 }); + expect(groupOf('src/a/notes.md')).toBeNull(); + }); + + it('SIZE-003: passes files within their limits', () => { + const code = run({}, { 'src/a.ts': lines(1000), 'src/a.css': lines(1000), 'tests/a.test.ts': lines(2000) }); + expect(code).toBe(0); + expect(tree.error).toEqual([]); + }); + + it('SIZE-004: fails a new source file past 1000 lines', () => { + expect(run({}, { 'src/big.tsx': lines(1001) })).toBe(1); + expect(tree.error.join('\n')).toMatch(/src\/big\.tsx: 1001 lines .*limit for a source file is 1000/); + }); + + it('SIZE-005: fails a file that packs its code into long lines', () => { + expect(run({}, { 'src/packed.tsx': `${'x'.repeat(WIDTH * 2)}\n`.repeat(600) })).toBe(1); + expect(tree.error.join('\n')).toMatch(/src\/packed\.tsx: 1200 lines/); + }); + + it('SIZE-006: covers stylesheets and tests', () => { + expect(run({}, { 'src/styles/a.css': lines(1001), 'src/A.test.tsx': lines(2001) })).toBe(1); + expect(tree.error.join('\n')).toMatch(/src\/styles\/a\.css/); + expect(tree.error.join('\n')).toMatch(/src\/A\.test\.tsx: 2001 lines .*test file is 2000/); + }); + + it('SIZE-007: holds a baselined file at its entry and fails it once it grows', () => { + expect(run({ 'src/big.ts': 1200 }, { 'src/big.ts': lines(1200) })).toBe(0); + tree.remove(); + expect(run({ 'src/big.ts': 1200 }, { 'src/big.ts': lines(1201) })).toBe(1); + expect(tree.error.join('\n')).toMatch(/its baseline is 1200/); + }); + + it('SIZE-008: --update lowers an entry, drops one back under the limit and never raises', () => { + run( + { 'src/shrank.ts': 1500, 'src/back.ts': 1200, 'src/grew.ts': 1100 }, + { + 'src/shrank.ts': lines(1300), + 'src/back.ts': lines(900), + 'src/grew.ts': lines(1150), + }, + true + ); + expect(JSON.parse(readFileSync(tree.path(BASELINE), 'utf8'))).toEqual({ + 'src/shrank.ts': 1300, + 'src/grew.ts': 1100, + }); + expect(tree.error.join('\n')).toMatch(/src\/grew\.ts: 1150 lines/); + }); + + it('SIZE-009: a broken baseline stops the check', () => { + tree = ratchetTree({ [BASELINE]: '{', 'src/a.ts': lines(1), 'tests/a.ts': lines(1) }); + expect(() => check({ root: tree.root, baselinePath: tree.path(BASELINE), ...tree.out })).toThrow(RatchetError); + }); +});