name: 'Publish to NPM'

on:
    push:
        tags:
            - 'v*.*.*'

permissions:
    id-token: write
    contents: read

env:
    NODE_VERSION: 24

jobs:
    publish:
        runs-on: ubuntu-latest

        steps:
            - uses: actions/checkout@v7
              with:
                  fetch-depth: 0

            - name: 'Setup Node'
              uses: actions/setup-node@v6
              with:
                  node-version: '${{ env.NODE_VERSION }}.x'
                  cache: 'npm'
                  registry-url: 'https://registry.npmjs.org'

            # Keep npm on a major compatible with Node 24.
            - name: Update npm
              run: npm install -g npm@^11

            - name: 'Install dependencies'
              run: npm ci

            - name: 'Build'
              run: npm run build

            - name: 'Compute npm publish args'
              id: publish_meta
              run: |
                  VERSION="${GITHUB_REF_NAME#v}"
                  if [[ "$VERSION" == *-* ]]; then
                      PRERELEASE="${VERSION#*-}"
                      DIST_TAG="${PRERELEASE%%.*}"
                      echo "publish_args=--access public --tag ${DIST_TAG}" >> "$GITHUB_OUTPUT"
                  else
                      echo "publish_args=--access public" >> "$GITHUB_OUTPUT"
                  fi

            - name: 'Publish to npm'
              run: npm publish ${{ steps.publish_meta.outputs.publish_args }}
