name: Publish

on:
  push:
    tags:
      - "v*"

jobs:
  build:
    strategy:
      matrix:
        os: [ubuntu-latest]
        node-version: [20.x, 22.x]
    runs-on: ${{ matrix.os }}

    steps:
      - uses: actions/checkout@v4
      - name: Use Node.js ${{ matrix.node-version }}
        uses: actions/setup-node@v4
        with:
          node-version: ${{ matrix.node-version }}
      - name: install pnpm
        run: npm install -g pnpm
      - run: pnpm install --frozen-lockfile
      - run: pnpm build
      - run: pnpm test

  publish-npm:
    needs: build
    runs-on: ubuntu-latest
    permissions:
      id-token: write
      contents: read
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 20
          registry-url: https://registry.npmjs.org/
      - name: Upgrade npm for trusted publishers (requires npm 11.5.1+)
        run: npm install -g npm@latest
      - name: install pnpm
        run: npm install -g pnpm

      - name: Set VERSION variable from tag
        run: echo "VERSION=${GITHUB_REF/refs\/tags\/v/}" >> $GITHUB_ENV
      - name: Print version
        run: echo $VERSION
      - name: Verify commit exists in origin/main
        run: |
          git fetch --no-tags --prune --depth=1 origin +refs/heads/*:refs/remotes/origin/*
          git branch --remote --contains | grep origin/main
      - name: Verify that the version exists in package.json
        run: 'sudo apt-get install -y jq && [[ "$(jq -r ".version" package.json)" == "$VERSION" ]]'

      - run: pnpm install --frozen-lockfile
      - run: pnpm build
      - run: npm publish --access=public
