name: npm-publish

on:
  workflow_dispatch:
    inputs:
      dry-run:
        description: 'Run in dry-run mode (no actual publish)'
        required: false
        default: false
        type: boolean

jobs:
  publish:
    runs-on: ubuntu-latest
    timeout-minutes: 30
    permissions:
      contents: read
      id-token: write # Required for OIDC trusted publishing
    steps:
      - name: Checkout
        uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
        with:
          persist-credentials: false

      - name: Setup Node.js
        uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
        with:
          node-version-file: .tool-versions
          registry-url: 'https://registry.npmjs.org'

      - name: Update npm to latest version
        run: npm install -g npm@latest

      - name: Install dependencies
        run: npm ci

      - name: Check if version already published
        run: |
          PACKAGE_VERSION=$(node -p "require('./package.json').version")
          if npm view "repomix@${PACKAGE_VERSION}" version 2>/dev/null; then
            echo "::error::Version ${PACKAGE_VERSION} is already published to npm"
            exit 1
          fi
          echo "Version ${PACKAGE_VERSION} is not yet published"

      - name: Lint
        run: node --run lint

      - name: Test
        run: node --run test-coverage

      - name: Build
        run: node --run build

      - name: Verify npm audit signatures
        run: npm audit signatures
        env:
          # Disable min-release-age during audit to avoid ETARGET errors for recently published dependencies
          npm_config_min_release_age: 0

      - name: Publish (dry-run)
        if: ${{ inputs.dry-run }}
        run: npm publish --provenance --access public --dry-run

      - name: Publish
        if: ${{ !inputs.dry-run }}
        run: npm publish --provenance --access public
