name: Release

on:
  push:
    tags:
      - '*'

jobs:

  build-artifact:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@master

      - name: npm pack
        run: |
          export REPO_NAME=$(echo ${{ github.repository }} | awk -F"/" '{print $2}')
          npm pack
          cp ${REPO_NAME}*.tgz ${REPO_NAME}-latest.tgz

      - uses: actions/upload-artifact@master
        with:
          name: artifact-tgz
          path: |
            ./*.tgz

      - name: Create Release
        id: create_release
        uses: actions/create-release@master
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        with:
          tag_name: ${{ github.ref }}
          release_name: Release ${{ github.ref }}
          draft: false
          prerelease: false

      - name: Upload Release Asset
        id: upload-release-asset
        uses: svenstaro/upload-release-action@v2
        with:
          repo_token: ${{ secrets.GITHUB_TOKEN }}
          file: ./*.tgz
          tag: ${{ github.ref }}
          overwrite: true
          file_glob: true
  
  publish-to-npm:
    runs-on: ubuntu-latest
    permissions:
      id-token: write   # required for npm OIDC trusted publishing
      contents: read
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: '22.x'
          registry-url: 'https://registry.npmjs.org'
      # Trusted publishing (OIDC) requires npm >= 11.5.1; Node 22 ships npm 10.x.
      - run: npm install -g npm@latest
      # No NODE_AUTH_TOKEN: npm exchanges the GitHub OIDC id-token for a
      # short-lived publish credential and attaches provenance automatically.
      - run: npm publish