name: CI

on:
  push:
    branches: [main]
  pull_request:

permissions:
  contents: read

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
        with:
          fetch-depth: 0
      - uses: actions/setup-node@v7
        with:
          node-version: 22
          cache: npm
      - run: npm ci --ignore-scripts
      - run: node --check src/foldbox.js
      - name: Build
        run: npm run build

      # The steps below run in this job (not their own) because "build" is the
      # check the "Protect main" ruleset requires before merging.
      - name: Size limits
        run: npm run size

      - name: TypeScript types
        run: npm run test:types

      - name: Unit tests (item detection and options)
        run: npm run test:unit

      - name: Install Chromium, Firefox and WebKit for the browser tests
        run: npx playwright install --with-deps chromium firefox webkit

      - name: Browser tests
        run: npm run test:e2e

      - name: Upload the test traces
        if: failure()
        uses: actions/upload-artifact@v4
        with:
          name: playwright-traces
          path: test-results/
          retention-days: 7

      # dist/ and CHANGELOG.md are written by the release workflow only. If a PR
      # changes them too, every release makes the open PRs conflict.
      - name: PR leaves dist/ and CHANGELOG.md to the release workflow
        if: github.event_name == 'pull_request'
        env:
          BASE: ${{ github.event.pull_request.base.sha }}
        run: |
          changed="$(git diff --name-only "$BASE"...HEAD -- dist CHANGELOG.md)"
          if [ -n "$changed" ]; then
            echo "::error::Please don't commit these files; the release workflow writes them when your PR is merged:"
            echo "$changed"
            echo "Undo with: git checkout origin/main -- dist CHANGELOG.md"
            exit 1
          fi
