name: Dispatch Publish

# 触发条件配置
on:
  workflow_dispatch:
    inputs:
      version:
        description: 输入您将要发布的版本号(默认使用 package.json 中的版本号),例如:`0.1.0`。
        required: false
        type: string
      tag:
        description: "选择发布/部署版本tag (alpha/beta/rc/latest)"
        required: true
        default: "alpha"
        type: choice
        options:
          - alpha
          - beta
          - rc
          - latest

concurrency:
  group: ${{ github.workflow }}-${{ github.sha }}
  cancel-in-progress: true

jobs:
  build:
    runs-on: ubuntu-latest
    outputs:
      version: ${{ steps.ver.outputs.value }}
    steps:
      - name: CheckOut Code
        uses: actions/checkout@v4
        with:
          ref: ${{ github.ref_name }}

      - name: Setup pnpm
        uses: pnpm/action-setup@v4
        with:
          version: 9

      - name: Setup Node
        uses: actions/setup-node@v4
        with:
          node-version: 20
          registry-url: "https://registry.npmjs.org"

      - name: Get pnpm store directory
        id: pnpm-cache
        run: |
          echo "pnpm_cache_dir=$(pnpm store path)" >> $GITHUB_OUTPUT

      - uses: actions/cache@v3
        name: Setup pnpm cache
        with:
          path: ${{ steps.pnpm-cache.outputs.pnpm_cache_dir }}
          key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }}
          restore-keys: |
            ${{ runner.os }}-pnpm-store-

      - name: Install dependencies
        run: pnpm i --no-frozen-lockfile
      - name: Get version
        id: ver
        run: |
          # 优先用手动输入的版本号
          if [ -n "${{ inputs.version }}" ]; then
            VERSION="${{ inputs.version }}"
          else
            VERSION="$(node -p "require('./package.json').version")"
          fi
          echo "version: $VERSION"
          echo "value=$VERSION" >> $GITHUB_OUTPUT
      - name: Bump version
        run: |
          # pnpm 自带 npm 版本管理
          pnpm version ${{ steps.ver.outputs.value }} --no-git-tag-version
          # 显示确认
          cat package.json | jq .version
      - name: Build
        run: pnpm build
      - name: Clean node_modules
        run: |
          # 删除任何意外混进去的 node_modules
          ls
          rm -rf node_modules
          find template -type d -name node_modules -prune -exec rm -rf {} +
          # 生成待发布 tarball(验证用)
          npm pack --dry-run
      - name: Show version and tag
        run: |
          echo "publish version: ${{ needs.build.outputs.version }}"
          echo "publish tag: ${{ inputs.tag }}"
      - name: Publish @opentiny/tiny-toolkit-pro
        run: |
          echo "//registry.npmjs.org/:_authToken=${NODE_AUTH_TOKEN}" > ~/.npmrc
          npm publish --tag ${{ inputs.tag }}
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}