name: JS
on:
  push:
    tags:
      - v*
    branches:
      - master
    paths:
      - "js/**"
      - "config/**"
      - ".github/workflows/js.yml"
  pull_request:
    paths:
      - "js/**"
      - "config/**"
      - ".github/workflows/js.yml"

jobs:
  build-and-lint:
    runs-on: ubuntu-latest
    name: Build, lint and test JS
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Load variables from file
        uses: antifree/json-to-variables@v1.0.1
        with:
          filename: .github/workflows/utils/variables.json

      - name: Setup asdf
        uses: asdf-vm/actions/setup@9cd779f40fe38688dd19505ccbc4eaaf018b44e7
        with:
          asdf_version: 0.16.7

      - name: Setup node
        working-directory: js
        run: |
          asdf plugin add nodejs
          asdf install nodejs
          echo "node_version=$(asdf current nodejs | xargs | cut -d ' ' -f 6)" >> $GITHUB_ENV

      - name: Setup yarn
        working-directory: js
        run: |
          asdf plugin add yarn
          asdf install yarn

      - name: Cache node modules
        uses: actions/cache@v4
        with:
          path: js/node_modules
          key: ${{ runner.OS }}-node-${{ env.node_version }}-${{ env.json_cache-versions_node }}-${{ hashFiles('js/yarn.lock') }}
          restore-keys: ${{ runner.OS }}-node-${{ env.node_version }}-${{ env.json_cache-versions_node }}-

      - name: Cache web node modules
        uses: actions/cache@v4
        with:
          path: js/web/node_modules
          key: ${{ runner.OS }}-nodeweb-${{ env.node_version }}-${{ env.json_cache-versions_nodeweb }}-${{ hashFiles('js/web/yarn.lock') }}
          restore-keys: ${{ runner.OS }}-nodeweb-${{ env.node_version }}-${{ env.json_cache-versions_nodeweb }}-

      - name: Fetch common node modules
        working-directory: js
        run: make node_modules

      - name: Fetch web node modules
        working-directory: js
        run: make web/node_modules

      - name: Run tests
        working-directory: js
        run: make test

      - name: Lint
        working-directory: js
        run: make lint

      - name: Build web client
        working-directory: js
        run: make web.build

      - name: Upload coverage to Codecov
        uses: codecov/codecov-action@v2.1.0
        env:
          OS: ${{ runner.os }}
          NODE: ${{ env.node_version }}
        with:
          file: ./js/coverage/coverage-final.json
          flags: js.unittests
          env_vars: OS,NODE
          name: codecov-umbrella
          fail_ci_if_error: false
