name: Publish to npm

# Publishes the package to npm after a PR is merged into main.
#
# A merge is just a push to main, so we run on that. To avoid re-publishing the
# same version on every merge, the job first checks whether the version in
# package.json is already on npm and skips publishing if it is. Bump the version
# in package.json in your PR whenever you want a merge to trigger a release.
#
# Requires an npm automation token stored as the repository secret NPM_TOKEN
# (npm → Access Tokens → Generate → Automation). See:
# https://docs.github.com/actions/security-guides/using-secrets-in-github-actions

on:
  push:
    branches: [main]

permissions:
  contents: read

jobs:
  publish:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: 20
          registry-url: 'https://registry.npmjs.org'

      - name: Install dependencies
        run: npm ci

      - name: Lint
        run: npm run lint

      - name: Test
        run: npm test

      - name: Build
        run: npm run build

      - name: Check if version is already published
        id: check
        run: |
          NAME=$(node -p "require('./package.json').name")
          VERSION=$(node -p "require('./package.json').version")
          echo "Local version: $NAME@$VERSION"
          if npm view "$NAME@$VERSION" version > /dev/null 2>&1; then
            echo "published=true" >> "$GITHUB_OUTPUT"
            echo "$NAME@$VERSION is already on npm — skipping publish."
          else
            echo "published=false" >> "$GITHUB_OUTPUT"
            echo "$NAME@$VERSION is new — will publish."
          fi

      - name: Publish
        if: steps.check.outputs.published == 'false'
        run: npm publish --access public
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
