name: npm publish

on:
  workflow_dispatch:
    inputs:
      tag:
        description: "Git tag to publish (e.g. v1.6.0)"
        required: true
        type: string
      dist-tag:
        description: "npm dist-tag (e.g. latest, next, beta)"
        required: false
        type: string
        default: "latest"
  workflow_call:
    inputs:
      tag:
        description: "Git tag to publish (e.g. v1.6.0)"
        required: true
        type: string
      dist-tag:
        description: "npm dist-tag (e.g. latest, next, beta)"
        required: false
        type: string
        default: "latest"

permissions:
  contents: read
  id-token: write # OIDC for npm Trusted Publishing

jobs:
  publish:
    if: github.repository == 'mdn/mdn-http-observatory'
    runs-on: ubuntu-latest
    permissions:
      id-token: write
    steps:
      - name: Checkout
        uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
        with:
          ref: ${{ inputs.tag }}
          persist-credentials: false

      - name: Setup Node
        uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
        with:
          node-version-file: .nvmrc
          registry-url: https://registry.npmjs.org
          package-manager-cache: false

      - name: Install npm@^11.8.0
        run: npm install -g npm@^11.8.0

      - name: Install
        run: npm ci

      # Backfill repository field for older tags.
      # Otherwise npm provenance fails with error code E422.
      - name: Ensure repository field in package.json
        env:
          REPO_URL: ${{ github.server_url }}/${{ github.repository }}
        run: |
          npm pkg set repository="$REPO_URL"
          npm pkg fix

      - name: Publish to npm
        run: npm publish --access public --provenance --tag ${{ inputs.dist-tag }}
