name: Publish package

on:
  release:
    types: [published]

# Trusted publishing uses GitHub's OIDC token instead of an npm token.
permissions:
  contents: read
  id-token: write

concurrency:
  group: publish-${{ github.event.release.tag_name }}
  cancel-in-progress: false

jobs:
  publish:
    name: Publish ${{ github.event.release.tag_name }} to npm
    runs-on: ubuntu-latest

    steps:
      - name: Check out released tag
        uses: actions/checkout@v6
        with:
          ref: ${{ github.event.release.tag_name }}
          fetch-depth: 1

      - name: Set up Node.js
        uses: actions/setup-node@v6
        with:
          node-version: 24.x
          registry-url: https://registry.npmjs.org
          cache: npm

      - name: Verify tag matches package version
        id: package
        env:
          RELEASE_TAG: ${{ github.event.release.tag_name }}
        run: |
          node <<'NODE'
          const fs = require('node:fs');
          const packageJson = JSON.parse(fs.readFileSync('package.json', 'utf8'));
          const tag = process.env.RELEASE_TAG;
          const expectedTag = `v${packageJson.version}`;
          if (tag !== expectedTag) {
            console.error(`Release tag ${tag} does not match package version ${packageJson.version} (expected ${expectedTag})`);
            process.exit(1);
          }
          console.log(`Publishing ${packageJson.name}@${packageJson.version}`);
          fs.appendFileSync(process.env.GITHUB_OUTPUT, `name=${packageJson.name}\nversion=${packageJson.version}\n`);
          NODE

      # npm versions are immutable. This makes the workflow safe to rerun and
      # also lets the first release be bootstrapped manually before OIDC is
      # configured for the newly-created npm package.
      - name: Check whether this version is already published
        id: npm
        env:
          PACKAGE_NAME: ${{ steps.package.outputs.name }}
          PACKAGE_VERSION: ${{ steps.package.outputs.version }}
        run: |
          if npm view "${PACKAGE_NAME}@${PACKAGE_VERSION}" version --registry=https://registry.npmjs.org >/dev/null 2>&1; then
            echo "published=true" >> "$GITHUB_OUTPUT"
            echo "${PACKAGE_NAME}@${PACKAGE_VERSION} is already published; skipping npm publish."
          else
            echo "published=false" >> "$GITHUB_OUTPUT"
          fi

      - name: Install dependencies
        run: npm ci

      - name: Run tests
        run: npm test

      - name: Publish to npm
        if: steps.npm.outputs.published != 'true'
        run: npm publish --access public --provenance
