name: NPM Publish

on:
  release:
    types: [created]

jobs:
  publish-stable:
    if: ${{ github.event.release.prerelease == false }}
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Verify tag matches package.json
        run: |
          TAG="${{ github.event.release.tag_name }}"
          VERSION="${TAG#v}"
          PKG_VERSION="$(node -p "require('./package.json').version")"
          if [ "$VERSION" != "$PKG_VERSION" ]; then
            echo "Release tag $TAG does not match package.json version $PKG_VERSION" >&2
            exit 1
          fi
      - uses: actions/setup-node@v4
        with:
          node-version: 20
          registry-url: https://registry.npmjs.org/
          cache: npm
          cache-dependency-path: package-lock.json
      - run: npm ci
      - run: npm run build
      - run: npm publish --access public
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}

  publish-sandbox:
    if: ${{ github.event.release.prerelease == true && contains(github.event.release.tag_name, 'sandbox') }}
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Set version from release tag
        run: |
          TAG="${{ github.event.release.tag_name }}"
          export VERSION="${TAG#v}"
          node -e "const fs = require('fs'); const pkg = require('./package.json'); pkg.version = process.env.VERSION; fs.writeFileSync('package.json', JSON.stringify(pkg, null, 2) + '\n');"
      - uses: actions/setup-node@v4
        with:
          node-version: 20
          registry-url: https://registry.npmjs.org/
          cache: npm
          cache-dependency-path: package-lock.json
      - run: npm ci
      - run: npm run build
      - run: npm publish --tag sandbox --access public
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}

  publish-dev:
    if: ${{ github.event.release.prerelease == true && contains(github.event.release.tag_name, 'dev') }}
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Set version from release tag
        run: |
          TAG="${{ github.event.release.tag_name }}"
          export VERSION="${TAG#v}"
          node -e "const fs = require('fs'); const pkg = require('./package.json'); pkg.version = process.env.VERSION; fs.writeFileSync('package.json', JSON.stringify(pkg, null, 2) + '\n');"
      - uses: actions/setup-node@v4
        with:
          node-version: 20
          registry-url: https://registry.npmjs.org/
          cache: npm
          cache-dependency-path: package-lock.json
      - run: npm ci
      - run: npm run build
      - run: npm publish --tag dev --access public
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
