# This workflow will do a clean installation of node dependencies, cache/restore them, build the source code and run tests across different versions of node
# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-nodejs

name: Node.js CI

on:
  push:
    branches: [ "main" ]
    tags: [ "v*" ]
  pull_request:
    branches: [ "main" ]

jobs:
  build:

    runs-on: ubuntu-latest

    strategy:
      matrix:
        node-version: [18.x, 20.x, 22.x]
        # See supported Node.js release schedule at https://nodejs.org/en/about/releases/

    steps:
    - uses: actions/checkout@v4
    - name: Cache node modules
      uses: actions/cache@v4
      with:
        path: |
          node_modules
          dist
        key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
        restore-keys: |
          ${{ runner.os }}-node-
    - name: Use Node.js ${{ matrix.node-version }}
      uses: actions/setup-node@v4
      with:
        node-version: ${{ matrix.node-version }}
        cache: 'npm'
        registry-url: 'https://registry.npmjs.org'
    - run: npm ci
    - run: npm run build --if-present
    - name: Upload build artifacts
      uses: actions/upload-artifact@v4
      with:
        name: dist
        path: dist
    # Publish to npm only on version tags (v*). Requires NPM_TOKEN secret.
    # registry-url above makes setup-node write the .npmrc that npm needs
    # to pick up NODE_AUTH_TOKEN (without it: ENEEDAUTH).
    - name: Publish to npm
      if: startsWith(github.ref, 'refs/tags/v')
      run: |
        PKG=$(node -p "require('./package.json').name")
        VER=$(node -p "require('./package.json').version")
        if npm view "$PKG@$VER" version >/dev/null 2>&1; then
          echo "Version $VER already published — skipping"
        else
          npm publish --access public
        fi
      env:
        NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
