From 1f012d24790e057dcd773e8ba05dd0266c3bae44 Mon Sep 17 00:00:00 2001 From: William Mikal Ruud Schmidt Date: Wed, 11 Nov 2026 15:09:13 +0100 Subject: [PATCH 1/4] "npm run check" --- .claude/launch.json | 11 + .github/workflows/check.yml | 44 ++++ README.md | 4 +- docs/requirements.md | 63 +++++ docs/workflow.md | 64 +++-- frontend/package.json | 2 +- frontend/scripts/coverage-report.mjs | 106 +++++++++ frontend/scripts/coverage.mjs | 25 ++ frontend/scripts/kk-report.css | 337 +++++++++++++++++++++++++++ frontend/vitest.config.ts | 8 + package.json | 11 + scripts/check.mjs | 127 ++++++++++ 12 files changed, 781 insertions(+), 21 deletions(-) create mode 100644 .claude/launch.json create mode 100644 .github/workflows/check.yml create mode 100644 docs/requirements.md create mode 100644 frontend/scripts/coverage-report.mjs create mode 100644 frontend/scripts/coverage.mjs create mode 100644 frontend/scripts/kk-report.css create mode 100644 package.json create mode 100644 scripts/check.mjs diff --git a/.claude/launch.json b/.claude/launch.json new file mode 100644 index 0000000..7ae701b --- /dev/null +++ b/.claude/launch.json @@ -0,0 +1,11 @@ +{ + "version": "0.0.1", + "configurations": [ + { + "name": "coverage-report", + "runtimeExecutable": "python3", + "runtimeArgs": ["-m", "http.server", "5179", "--directory", "frontend/coverage"], + "port": 5179 + } + ] +} diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml new file mode 100644 index 0000000..39b6dda --- /dev/null +++ b/.github/workflows/check.yml @@ -0,0 +1,44 @@ +# Runs the same pre-PR check as `npm run check` on every pull request and on main. +# git.ntnu.no has no shared runners, so this needs a self-hosted runner registered for +# this repository (see docs/workflow.md). Until one exists, runs wait as "Queued". +name: Check + +on: + pull_request: + push: + branches: [main] + +# A new push to the same pull request cancels the run that is still going. +concurrency: + group: check-${{ github.ref }} + cancel-in-progress: true + +jobs: + check: + runs-on: [self-hosted, t18] + timeout-minutes: 20 + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-node@v4 + with: + node-version: 24 + + - name: Install dependencies + run: | + npm ci --prefix frontend --no-audit --no-fund + npm ci --prefix backend --no-audit --no-fund + + - name: Prettier, ESLint, TypeScript, tests with coverage and build + run: npm run check + + # The coverage report, downloadable from the run's summary page. + # GitHub Enterprise Server needs the v3 node20 build of upload-artifact. + - name: Upload coverage report + if: always() + uses: actions/upload-artifact@v3.2.1-node20 + with: + name: coverage-report + path: frontend/coverage/ + if-no-files-found: ignore + retention-days: 14 diff --git a/README.md b/README.md index 2435ae8..477fc1e 100644 --- a/README.md +++ b/README.md @@ -262,7 +262,7 @@ Vitest enforces a minimum of 80 % for lines, functions and statements and 75 % f We will add the missing tests before raising the limits further, and we do not lower the limits to make the run pass. We leave out `main.tsx`, test files, test helpers and mock data, because they contain no application logic. -Run `npm run test:coverage` in `frontend/` to see the full report. +Run `npm run test:coverage` in `frontend/` to see the full report. It prints a link to an HTML report in `frontend/coverage/`, coloured green at 100 %, yellow from 80 %, orange below 80 % and red at 0 %. ### Run the tests @@ -282,7 +282,7 @@ npm test - One issue per task and one branch per issue. Changes go through a pull request. - Make tests and preferably update documentation as you go. - Another group member must review every pull request (`.github/CODEOWNERS`). -- Before a pull request, run lint, Prettier, type checking, tests and build. See [workflow](docs/workflow.md). +- Before a pull request, run `npm run check` from the repository root. It runs Prettier, ESLint, type checking, tests with coverage and the build, and links to the coverage report. See [workflow](docs/workflow.md). ### Tools diff --git a/docs/requirements.md b/docs/requirements.md new file mode 100644 index 0000000..918bfcb --- /dev/null +++ b/docs/requirements.md @@ -0,0 +1,63 @@ +# Requirements: IT2810 Project 2 + +Short version of the course text. A full-stack, searchable catalogue that should in theory scale to any data size. + +## Functionality + +- [ ] Search on single terms, case-insensitive, without needless requests (debounce or a button) +- [ ] Result list built for large result sets: pages, or loading more on scroll +- [ ] Detail view for each item +- [ ] Sorting and filtering on the **whole** result set, not only what the client has loaded +- [ ] User-generated data (reviews, ratings, lists, search history, …) stored on the database server and shown in the app +- [ ] Accessibility (universell utforming) +- [ ] Sustainable web development, through design choices +- [ ] Good design and choices that fit the data +- [ ] Database and backend hosted on the group's VM at submission + +## Technology + +- [ ] React + TypeScript, set up with Vite +- [ ] State management (Redux, MobX, Apollo local state, …) +- [ ] Our own GraphQL backend in Node + TypeScript +- [ ] Any database, installed by us directly on the VM. No Docker. +- [ ] Reuse good third-party components and libraries + +## Quality, testing and docs + +- [ ] Linting and Prettier +- [ ] Component tests with Vitest +- [ ] Automated end-to-end tests (a longer sequence of interactions) and API tests +- [ ] README that discusses and explains all major choices, including components and API +- [ ] Readable, well-structured code, commented for outside readers +- [ ] Reproducible: easy for others (staff) to install and run +- [ ] AI use documented, with our own control shown through issues, PRs, code review and systematic collaboration +- [ ] Individual contributions summarised in a separate file in Canvas/Blackboard, **not** in git + +## VM setup + +- [ ] Served by Apache at `http://it2810-18.idi.ntnu.no/project2` +- [ ] Backend preferably on port 3001 +- [ ] Everything needed to start the backend is available to staff (in git, or a file readable with sudo on the VM) + +## Deliveries + +All go to git.ntnu.no plus the prototype on the VM, followed by peer review in FeedbackFruits. + +| # | Due | Peer review by | Expected | Extra | +|---|---|---|---|---| +| 1 | 2 Oct | 9 Oct | Specification or draft with mock data | | +| 2 | 16 Oct | 21 Oct | Database and backend running on the VM, some client interaction | | +| 3 | 30 Oct | 6 Nov | First complete prototype (beta): search, paging, sort, filter, sustainability, accessibility | Timesheet | +| 4 | 13 Nov | 20 Nov | Finished project; testing is assessed too | Timesheet for all of Project 2 | +| Final | 27 Nov | | Projects 1 and 2, can still change after peer review | Individual timesheet and description | + +## Grading + +- Each approved delivery with peer review participation: 10 % of the portfolio. +- Qualitative assessment of the projects: 50 % of the grade, mostly Project 2 (45 %). +- Meeting the requirements alone is not enough for a top grade. It also needs: + - **Application understanding:** good insight into this kind of app, explores better solutions instead of easy ones, focus on usability and user experience. + - **Technical understanding:** scales with any amount of data, thoroughly tested for typical and atypical use, efficient and sustainable solutions, competence at every level, reproducible setup and clear docs. + - **Design:** excellent visual and interaction design, thorough focus on accessibility. + +Budget: about 8 hours a week per group member. diff --git a/docs/workflow.md b/docs/workflow.md index 04b12ff..298d21f 100644 --- a/docs/workflow.md +++ b/docs/workflow.md @@ -1,25 +1,53 @@ # Workflow -Create one issue per task and one branch per issue. Submit changes through a pull request. -Another team member must review and merge the pull request and close the issue. -Co-authorship does not prevent that person from merging. +## From task to `main` -Use branch prefixes such as `feature-`, `fix-`, `docs-`, `test-`, or `chore-`. +1. **Issue:** one per task, with a goal, tasks and «done when». +2. **Branch:** one per issue, named `-`, e.g. `33-reviews`. +3. **Commits:** small, in English, [Conventional Commits](https://www.conventionalcommits.org/) with the issue number: + `feat(search): add filter chips (#35)`. +4. **Check:** `npm run check` passes (see below). +5. **Pull request:** links the issue (`Closes #33`) and says what was tested and how. +6. **Review:** another group member reviews (`.github/CODEOWNERS`), merges and closes the issue. + Co-authorship does not stop that person from merging. -Before a pull request, run the frontend checks from the project folder: +## Before a pull request -```bash -cd frontend -npm run format -npm run lint -npm run format:check -npm test -- --run -npm run build -``` +Run from the repository root: -Check the backend manually with `npm start` from `backend/`. -Open [localhost:3001](http://localhost:3001/) and confirm it returns database information. -The backend does not have automated tests yet. +| Command | Does | +| ------------------------ | ------------------------------------------------------------------------------------------- | +| `npm run check` | Prettier, ESLint, TypeScript, tests with coverage and build, for `frontend/` and `backend/` | +| `npm run check -- --fix` | Runs Prettier and ESLint fixes first | +| `npm run check -- --e2e` | Also runs the Playwright tests | -Keep documentation current and record AI assistance during development. -Submit personal time logs and contribution summaries in Canvas. +- Every step runs, even after a failure. Steps a package lacks show as «not set up». +- The output ends with a summary, the coverage numbers and a link to the report. +- Coverage report: `frontend/coverage/index.html`. 100 % green, 80–99 % yellow, 1–79 % orange, 0 % red. + +## CI + +`.github/workflows/check.yml` runs `npm run check` on every pull request and push to `main`, and uploads the coverage report. + +git.ntnu.no has no shared runners, so it needs a self-hosted runner on the VM with the label `t18`. One-time setup (needs repo admin): + +1. git.ntnu.no: **Settings → Actions → Runners → New self-hosted runner** (Linux x64). +2. On the VM, as a user without sudo, so PR code can't change the server: + + ```bash + sudo adduser --disabled-password --gecos "" github-runner + sudo -iu github-runner + # download commands from the runner page, then: + ./config.sh --url https://git.ntnu.no/IT2810-H26/T18-Project-2 --token --name it2810-18 --labels t18 + exit + cd /home/github-runner/actions-runner && sudo ./svc.sh install github-runner && sudo ./svc.sh start + ``` + +3. The runner shows «Idle» under **Settings → Actions → Runners**. Until then, runs wait as «Queued». + +## Conventions + +- **Language:** English in code, commits, PRs and docs. Norwegian (bokmål) in everything users see. +- **Docs:** update README and `docs/` in the same PR as the change. +- **AI:** allowed. AI-written code goes through the same checks and review, and we record how we used it. +- **Personal:** time logs and contribution summaries go in Canvas/Blackboard, never in git. diff --git a/frontend/package.json b/frontend/package.json index f96215a..41b8b8d 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -13,7 +13,7 @@ "format:check": "prettier --check .", "test": "vitest", "test:run": "vitest run", - "test:coverage": "vitest run --coverage", + "test:coverage": "node scripts/coverage.mjs", "typecheck": "tsc -b --noEmit", "e2e": "playwright test" }, diff --git a/frontend/scripts/coverage-report.mjs b/frontend/scripts/coverage-report.mjs new file mode 100644 index 0000000..853bea8 --- /dev/null +++ b/frontend/scripts/coverage-report.mjs @@ -0,0 +1,106 @@ +// Restyles Istanbul's HTML coverage report (coverage/) after Vitest has written it. +// +// Istanbul only has three colour levels. We want four, so this script replaces its +// low/medium/high classes with our own: +// 100 % → full (green) +// 80–99.99 % → partial (yellow) +// 0.01–79.99 % → low (orange) +// 0 % → none (red) +// It also links kk-report.css, a cleaner stylesheet with dark mode. +// +// Run directly with `node scripts/coverage-report.mjs`, or through scripts/coverage.mjs. +import { copyFileSync, readFileSync, readdirSync, writeFileSync } from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const ISTANBUL_LEVELS = /\b(low|medium|high)\b/g; + +export function coverageLevel(percent) { + if (percent >= 100) return 'full'; + if (percent >= 80) return 'partial'; + if (percent > 0) return 'low'; + return 'none'; +} + +/** Replaces Istanbul's level class in a tag's class attribute with ours. */ +function withLevel(tag, level) { + return tag.replace(/class=(["'])([^"']*)\1/, (_match, quote, classes) => { + const kept = classes.replace(ISTANBUL_LEVELS, '').replace(/\s+/g, ' ').trim(); + return `class=${quote}${kept} kk-${level}${quote}`; + }); +} + +/** + * One summary row: file name, bar, then a percentage and a count per metric. + * The file name and the bar follow statements; each count follows its percentage. + */ +function restyleRow(row) { + const cells = (row.match(/]*>/g) ?? []).map((tag) => ({ + kind: /class="(\w+)/.exec(tag)?.[1], + value: Number(/data-value="([^"]*)"/.exec(tag)?.[1]), + })); + const statements = cells.find((cell) => cell.kind === 'pct'); + if (!statements) return row; + + const rowLevel = coverageLevel(statements.value); + let current = rowLevel; + const levels = cells.map((cell) => { + if (cell.kind === 'pct') current = coverageLevel(cell.value); + return cell.kind === 'file' || cell.kind === 'pic' ? rowLevel : current; + }); + + let index = 0; + return row.replace(/]*>/g, (tag) => withLevel(tag, levels[index++])); +} + +export function restyleHtml(html, prefix) { + if (html.includes('kk-report.css')) return html; // already done + + let statementsLevel; + let result = html + // The four metric boxes at the top of each page. + .replace( + /
(\s*([\d.]+)% <\/span>)/g, + (_match, inner, percent) => { + const level = coverageLevel(Number(percent)); + statementsLevel ??= level; + return `
${inner}`; + }, + ) + .replace(/[\s\S]*?<\/tr>/g, restyleRow) + .replace( + //, + (link) => `${link}\n `, + ) + .replace( + '', + '\n ', + ); + + if (statementsLevel) { + result = result.replace(/class='status-line \w+'/, `class='status-line kk-${statementsLevel}'`); + } + return result; +} + +export function restyleReport(reportDir) { + copyFileSync(path.join(here, 'kk-report.css'), path.join(reportDir, 'kk-report.css')); + + const walk = (dir) => { + for (const entry of readdirSync(dir, { withFileTypes: true })) { + const full = path.join(dir, entry.name); + if (entry.isDirectory()) walk(full); + else if (entry.name.endsWith('.html')) { + const depth = path.relative(reportDir, dir).split(path.sep).filter(Boolean).length; + const html = readFileSync(full, 'utf8'); + writeFileSync(full, restyleHtml(html, '../'.repeat(depth))); + } + } + }; + walk(reportDir); +} + +if (process.argv[1] === fileURLToPath(import.meta.url)) { + restyleReport(path.resolve(here, '..', 'coverage')); +} diff --git a/frontend/scripts/coverage.mjs b/frontend/scripts/coverage.mjs new file mode 100644 index 0000000..70d1b5a --- /dev/null +++ b/frontend/scripts/coverage.mjs @@ -0,0 +1,25 @@ +// `npm run test:coverage`: runs Vitest with coverage, restyles the HTML report and +// prints a link to it. Exits with Vitest's exit code, so failing tests or coverage +// below the thresholds in vitest.config.ts still fail the command. +import { spawnSync } from 'node:child_process'; +import { existsSync } from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import { restyleReport } from './coverage-report.mjs'; + +const frontend = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); +const reportDir = path.join(frontend, 'coverage'); + +const vitest = spawnSync('npx', ['vitest', 'run', '--coverage', ...process.argv.slice(2)], { + cwd: frontend, + stdio: 'inherit', + shell: process.platform === 'win32', +}); + +const index = path.join(reportDir, 'index.html'); +if (existsSync(index)) { + restyleReport(reportDir); + console.log(`\nCoverage report: ${pathToFileURL(index).href}`); +} + +process.exit(vitest.status ?? 1); diff --git a/frontend/scripts/kk-report.css b/frontend/scripts/kk-report.css new file mode 100644 index 0000000..1803304 --- /dev/null +++ b/frontend/scripts/kk-report.css @@ -0,0 +1,337 @@ +/* + * Overrides for Istanbul's coverage report (loaded after base.css). + * Levels set by coverage-report.mjs: full 100 %, partial 80–99 %, low 1–79 %, none 0 %. + */ +:root { + --bg: #f6f7f9; + --surface: #ffffff; + --text: #1f2328; + --muted: #656d76; + --border: #d8dee4; + --link: #0969da; + --brand: #6b1d2f; + + --full: #1a7f37; + --full-bar: #2da44e; + --full-bg: #dafbe1; + --partial: #7d5800; + --partial-bar: #d4a72c; + --partial-bg: #fff8c5; + --low: #a14000; + --low-bar: #e16f24; + --low-bg: #ffead6; + --none: #c21c2c; + --none-bar: #cf222e; + --none-bg: #ffebe9; + + --line-hit: #dafbe1; + --line-miss: #ffd7d5; + --code-bg: #ffffff; +} + +@media (prefers-color-scheme: dark) { + :root { + --bg: #0d1117; + --surface: #161b22; + --text: #e6edf3; + --muted: #8d96a0; + --border: #30363d; + --link: #4493f8; + --brand: #c9506b; + + --full: #3fb950; + --full-bg: rgba(46, 160, 67, 0.18); + --partial: #d29922; + --partial-bg: rgba(210, 153, 34, 0.18); + --low: #f0883e; + --low-bg: rgba(240, 136, 62, 0.18); + --none: #ff7b72; + --none-bg: rgba(248, 81, 73, 0.2); + + --line-hit: rgba(46, 160, 67, 0.25); + --line-miss: rgba(248, 81, 73, 0.35); + --code-bg: #0d1117; + } +} + +/* Page */ +body { + font-family: + system-ui, + -apple-system, + 'Segoe UI', + Roboto, + sans-serif; + font-size: 14px; + color: var(--text); + background: var(--bg); +} +.wrapper { + max-width: 1200px; + margin: 0 auto; + min-height: auto; + height: auto; +} +.pad1 { + padding: 24px 24px 12px; +} +a { + color: var(--link); +} +.quiet, +.quiet a { + color: var(--muted); +} +h1 { + font-size: 22px; + font-weight: 650; + margin-bottom: 16px; + padding-left: 12px; + border-left: 4px solid var(--brand); +} +h1 a { + color: var(--link); +} + +/* Metric tiles at the top */ +.clearfix { + display: flex; + flex-wrap: wrap; + gap: 12px; +} +.clearfix::after { + display: none; +} +.kk-metric { + float: none; + display: grid; + grid-template-columns: auto 1fr; + column-gap: 8px; + align-items: baseline; + min-width: 170px; + margin: 0; + padding: 12px 16px; + background: var(--surface); + border: 1px solid var(--border); + border-top: 4px solid var(--level-bar); + border-radius: 10px; +} +.kk-metric .strong { + font-size: 24px; + font-weight: 700; + color: var(--level-text); +} +.kk-metric .quiet { + color: var(--text); + font-weight: 600; +} +.kk-metric .fraction { + grid-column: 1 / -1; + margin-top: 2px; + padding: 0; + background: none; + color: var(--muted); + font-size: 12px; +} + +/* Level colours, shared by tiles, table cells, bars and the status line */ +.kk-full { + --level-text: var(--full); + --level-bar: var(--full-bar, var(--full)); + --level-bg: var(--full-bg); +} +.kk-partial { + --level-text: var(--partial); + --level-bar: var(--partial-bar, var(--partial)); + --level-bg: var(--partial-bg); +} +.kk-low { + --level-text: var(--low); + --level-bar: var(--low-bar, var(--low)); + --level-bg: var(--low-bg); +} +.kk-none { + --level-text: var(--none); + --level-bar: var(--none-bar, var(--none)); + --level-bg: var(--none-bg); +} + +.status-line { + height: 4px; + margin: 0 24px; + border-radius: 2px; + background: var(--level-bar); +} + +/* Summary table: scrolls sideways on narrow windows instead of being cut off */ +.pad1:has(> .coverage-summary) { + overflow-x: auto; +} +.coverage-summary { + width: 100%; + border-collapse: separate; + border-spacing: 0; + background: var(--surface); + border: 1px solid var(--border); + border-radius: 10px; + overflow: hidden; +} +.coverage-summary th { + padding: 10px 12px; + border-bottom: 1px solid var(--border); + background: var(--surface); + color: var(--muted); + font-size: 12px; + font-weight: 600; + text-transform: uppercase; + letter-spacing: 0.04em; +} +.coverage-summary td { + padding: 8px 12px; + border-top: 1px solid var(--border); + border-right: 0; +} +.coverage-summary tbody tr:first-child td { + border-top: 0; +} +.coverage-summary tbody tr:hover td { + filter: brightness(0.97); +} +.coverage-summary td.file a { + font-weight: 600; +} +.coverage-summary td.pct { + font-weight: 700; + text-align: right; +} +.coverage-summary td.pct, +.coverage-summary td.abs { + color: var(--level-text); + background: var(--level-bg); +} +.coverage-summary td.abs { + color: var(--muted); + font-size: 12px; +} +.coverage-summary td.file, +.coverage-summary td.pic { + background: var(--surface); +} +.coverage-summary .sorter { + filter: grayscale(1) opacity(0.6); +} + +/* Bars */ +td.pic .chart { + width: 120px; + height: 8px; + margin-top: 4px; + border: 0; + border-radius: 4px; + overflow: hidden; + background: var(--border); +} +.chart .cover-fill { + height: 8px; + border: 0; + background: var(--level-bar); +} +.chart .cover-empty { + height: 8px; + background: transparent; +} + +/* Search box above the table */ +#fileSearch { + padding: 6px 10px; + border: 1px solid var(--border); + border-radius: 6px; + background: var(--surface); + color: var(--text); + font: inherit; +} + +/* Source view */ +table.coverage { + width: 100%; + margin-top: 16px; + background: var(--code-bg); + border: 1px solid var(--border); + border-radius: 10px; + overflow: hidden; +} +table.coverage td { + color: var(--text); +} +table.coverage td.line-count, +table.coverage td.line-coverage { + color: var(--muted); + background: var(--surface); +} +.cline-yes { + background: var(--line-hit); +} +.cline-no { + background: var(--line-miss); +} +span.cline-neutral { + background: transparent; +} +.cstat-no, +.fstat-no, +.cbranch-no { + background: var(--line-miss); + border-radius: 2px; +} +.missing-if-branch, +.skip-if-branch { + border-radius: 3px; +} +pre.prettyprint { + border: 0 !important; + padding: 0 8px !important; +} + +@media (prefers-color-scheme: dark) { + .pln, + .pun, + .opn, + .clo { + color: #e6edf3; + } + .str, + .atv { + color: #a5d6ff; + } + .kwd, + .tag { + color: #ff7b72; + } + .com { + color: #8b949e; + } + .typ, + .atn, + .dec, + .var { + color: #ffa657; + } + .lit { + color: #79c0ff; + } + .fun { + color: #d2a8ff; + } +} + +/* Footer */ +.footer { + max-width: 1200px; + margin: 0 auto; + padding: 16px 24px 32px; + color: var(--muted); + background: transparent; +} +.push { + display: none; +} diff --git a/frontend/vitest.config.ts b/frontend/vitest.config.ts index 5a9f8e6..c6fb3ea 100644 --- a/frontend/vitest.config.ts +++ b/frontend/vitest.config.ts @@ -18,6 +18,14 @@ export default mergeConfig( exclude: ['src/**/*.test.{ts,tsx}', 'src/test/**', 'src/main.tsx', 'src/**/mock*.ts'], // Startterskel. Skru opp mot ~90 % etter hvert som resten av appen kommer på plass. thresholds: { lines: 80, functions: 80, branches: 75, statements: 80 }, + // Colours in the terminal table: under 80 % red, 80–99 % yellow, 100 % green. + // The HTML report gets four levels from scripts/coverage-report.mjs. + watermarks: { + statements: [80, 100], + branches: [80, 100], + functions: [80, 100], + lines: [80, 100], + }, }, }, }), diff --git a/package.json b/package.json new file mode 100644 index 0000000..c4d3529 --- /dev/null +++ b/package.json @@ -0,0 +1,11 @@ +{ + "name": "kork-og-krone", + "private": true, + "description": "Repository-level scripts. The app lives in frontend/ and backend/.", + "engines": { + "node": ">=24" + }, + "scripts": { + "check": "node scripts/check.mjs" + } +} diff --git a/scripts/check.mjs b/scripts/check.mjs new file mode 100644 index 0000000..0aa97fd --- /dev/null +++ b/scripts/check.mjs @@ -0,0 +1,127 @@ +#!/usr/bin/env node +// Pre-PR check: runs formatting, linting, type checking, tests with coverage and the +// build for frontend and backend, then prints a summary and a link to the coverage +// report. Run from the repository root: +// +// npm run check all checks +// npm run check -- --fix run Prettier and ESLint fixes first +// npm run check -- --e2e also run the Playwright tests +// +// A step is skipped when its npm script does not exist in that package (for example +// lint in the backend before ESLint is set up). Every step runs even if an earlier one +// fails, so you see all problems at once. Exits with 1 if anything failed. +import { spawn } from 'node:child_process'; +import { existsSync, readFileSync } from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import { styleText } from 'node:util'; + +const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); +const args = new Set(process.argv.slice(2)); + +const STEPS = [ + { pkg: 'frontend', name: 'Prettier', script: 'format:check', fix: 'format' }, + { pkg: 'frontend', name: 'ESLint', script: 'lint', fix: 'lint -- --fix' }, + { pkg: 'frontend', name: 'TypeScript', script: 'typecheck' }, + { pkg: 'frontend', name: 'Tests + coverage', script: 'test:coverage' }, + { pkg: 'frontend', name: 'Build', script: 'build' }, + { pkg: 'frontend', name: 'E2E (Playwright)', script: 'e2e', only: '--e2e' }, + { pkg: 'backend', name: 'Prettier', script: 'format:check', fix: 'format' }, + { pkg: 'backend', name: 'ESLint', script: 'lint', fix: 'lint -- --fix' }, + { pkg: 'backend', name: 'TypeScript', script: 'typecheck' }, + { pkg: 'backend', name: 'Tests', script: 'test' }, +]; + +const scriptsOf = (pkg) => + JSON.parse(readFileSync(path.join(root, pkg, 'package.json'), 'utf8')).scripts ?? {}; + +function run(pkg, script) { + return new Promise((resolve) => { + const started = performance.now(); + let output = ''; + const child = spawn(`npm run ${script}`, { + cwd: path.join(root, pkg), + shell: true, + env: { ...process.env, FORCE_COLOR: '1' }, + }); + child.stdout.on('data', (chunk) => (output += chunk)); + child.stderr.on('data', (chunk) => (output += chunk)); + child.on('close', (code) => { + resolve({ + ok: code === 0, + output, + seconds: (performance.now() - started) / 1000, + }); + }); + }); +} + +const label = (step) => `${step.pkg.padEnd(9)}${step.name}`; + +if (args.has('--fix')) { + for (const step of STEPS.filter((s) => s.fix && scriptsOf(s.pkg)[s.script])) { + process.stdout.write(`fix ${label(step)} … `); + const result = await run(step.pkg, step.fix); + console.log(result.ok ? 'done' : styleText('yellow', 'could not fix everything')); + } + console.log(); +} + +const results = []; +for (const step of STEPS) { + if (step.only && !args.has(step.only)) continue; + if (!scriptsOf(step.pkg)[step.script]) { + console.log(styleText('gray', ` – ${label(step)} not set up`)); + results.push({ step, skipped: true }); + continue; + } + // In a terminal, show the running step and overwrite it with the result. + if (process.stdout.isTTY) process.stdout.write(` … ${label(step)}`); + const result = await run(step.pkg, step.script); + const mark = result.ok ? styleText('green', '✓') : styleText('red', '✗'); + const time = styleText('gray', `${result.seconds.toFixed(1)} s`); + if (process.stdout.isTTY) process.stdout.write('\r'); + console.log(` ${mark} ${label(step)} ${time}`); + results.push({ step, ...result }); +} + +const failed = results.filter((r) => r.ok === false); +for (const { step, output } of failed) { + console.log(styleText(['red', 'bold'], `\n── ${label(step).replace(/\s+/, ' ')} failed ──`)); + console.log(output.trim()); +} + +// The coverage summary that Vitest prints at the end of the run, coloured like the +// HTML report: 100 % green, 80–99 % yellow, under 80 % orange, 0 % red. +// Basic terminal colours have no orange, so that one uses the 256-colour code 208. +const orange = (text) => (process.stdout.isTTY ? `\x1b[38;5;208m${text}\x1b[39m` : text); +const colourByLevel = (percent, text) => { + if (percent >= 100) return styleText('green', text); + if (percent >= 80) return styleText('yellow', text); + if (percent > 0) return orange(text); + return styleText('red', text); +}; +const coverage = results.find((r) => r.step.script === 'test:coverage'); +const plain = coverage?.output.replace(/\x1b\[[0-9;]*m/g, '') ?? ''; +const summary = plain.match(/^(Statements|Branches|Functions|Lines)\s*:\s*([\d.]+)%.*$/gm); +if (summary) { + console.log('\nCoverage (frontend)'); + for (const line of summary) { + const percent = Number(/:\s*([\d.]+)%/.exec(line)[1]); + console.log(` ${colourByLevel(percent, line)}`); + } +} + +const report = path.join(root, 'frontend', 'coverage', 'index.html'); +if (existsSync(report)) console.log(`\nCoverage report: ${pathToFileURL(report).href}`); + +const ran = results.filter((r) => !r.skipped).length; +console.log( + failed.length + ? styleText( + ['red', 'bold'], + `\n${failed.length} of ${ran} checks failed. Fix them before opening a PR.`, + ) + : styleText(['green', 'bold'], `\nAll ${ran} checks passed. Ready for a PR.`), +); +process.exit(failed.length ? 1 : 0); From 69e51aef1902e406307d4abb494daaf3be227704 Mon Sep 17 00:00:00 2001 From: William Mikal Ruud Schmidt Date: Wed, 11 Nov 2026 15:10:22 +0100 Subject: [PATCH 2/4] chore: remove local preview config Co-Authored-By: Claude Opus 5.5 --- .claude/launch.json | 11 ----------- 1 file changed, 11 deletions(-) delete mode 100644 .claude/launch.json diff --git a/.claude/launch.json b/.claude/launch.json deleted file mode 100644 index 7ae701b..0000000 --- a/.claude/launch.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "version": "0.0.1", - "configurations": [ - { - "name": "coverage-report", - "runtimeExecutable": "python3", - "runtimeArgs": ["-m", "http.server", "5179", "--directory", "frontend/coverage"], - "port": 5179 - } - ] -} From e7f432bb544d6a7cf3b29792fc7176f3a86290e4 Mon Sep 17 00:00:00 2001 From: William Mikal Ruud Schmidt Date: Wed, 11 Nov 2026 15:10:44 +0100 Subject: [PATCH 3/4] chore: ignore local .claude settings Co-Authored-By: Claude Opus 5.5 --- .gitignore | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.gitignore b/.gitignore index 438657a..5a05918 100644 --- a/.gitignore +++ b/.gitignore @@ -23,3 +23,6 @@ dist-ssr *.njsproj *.sln *.sw? + +# Local Claude Code settings +.claude/ From e647769d0cf1e2ee08531b73d09d2de781d448c8 Mon Sep 17 00:00:00 2001 From: William Mikal Ruud Schmidt Date: Wed, 11 Nov 2026 15:15:24 +0100 Subject: [PATCH 4/4] ci: remove check workflow until we have a runner git.ntnu.no has no shared runners, so the job never started. npm run check stays as the local pre-PR check. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/check.yml | 44 ------------------------------------- docs/workflow.md | 20 ----------------- 2 files changed, 64 deletions(-) delete mode 100644 .github/workflows/check.yml diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml deleted file mode 100644 index 39b6dda..0000000 --- a/.github/workflows/check.yml +++ /dev/null @@ -1,44 +0,0 @@ -# Runs the same pre-PR check as `npm run check` on every pull request and on main. -# git.ntnu.no has no shared runners, so this needs a self-hosted runner registered for -# this repository (see docs/workflow.md). Until one exists, runs wait as "Queued". -name: Check - -on: - pull_request: - push: - branches: [main] - -# A new push to the same pull request cancels the run that is still going. -concurrency: - group: check-${{ github.ref }} - cancel-in-progress: true - -jobs: - check: - runs-on: [self-hosted, t18] - timeout-minutes: 20 - steps: - - uses: actions/checkout@v4 - - - uses: actions/setup-node@v4 - with: - node-version: 24 - - - name: Install dependencies - run: | - npm ci --prefix frontend --no-audit --no-fund - npm ci --prefix backend --no-audit --no-fund - - - name: Prettier, ESLint, TypeScript, tests with coverage and build - run: npm run check - - # The coverage report, downloadable from the run's summary page. - # GitHub Enterprise Server needs the v3 node20 build of upload-artifact. - - name: Upload coverage report - if: always() - uses: actions/upload-artifact@v3.2.1-node20 - with: - name: coverage-report - path: frontend/coverage/ - if-no-files-found: ignore - retention-days: 14 diff --git a/docs/workflow.md b/docs/workflow.md index 298d21f..1571764 100644 --- a/docs/workflow.md +++ b/docs/workflow.md @@ -25,26 +25,6 @@ Run from the repository root: - The output ends with a summary, the coverage numbers and a link to the report. - Coverage report: `frontend/coverage/index.html`. 100 % green, 80–99 % yellow, 1–79 % orange, 0 % red. -## CI - -`.github/workflows/check.yml` runs `npm run check` on every pull request and push to `main`, and uploads the coverage report. - -git.ntnu.no has no shared runners, so it needs a self-hosted runner on the VM with the label `t18`. One-time setup (needs repo admin): - -1. git.ntnu.no: **Settings → Actions → Runners → New self-hosted runner** (Linux x64). -2. On the VM, as a user without sudo, so PR code can't change the server: - - ```bash - sudo adduser --disabled-password --gecos "" github-runner - sudo -iu github-runner - # download commands from the runner page, then: - ./config.sh --url https://git.ntnu.no/IT2810-H26/T18-Project-2 --token --name it2810-18 --labels t18 - exit - cd /home/github-runner/actions-runner && sudo ./svc.sh install github-runner && sudo ./svc.sh start - ``` - -3. The runner shows «Idle» under **Settings → Actions → Runners**. Until then, runs wait as «Queued». - ## Conventions - **Language:** English in code, commits, PRs and docs. Norwegian (bokmål) in everything users see.