name: Test and Publish CI/CD

on:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]
  release:
    types: [ published ]
  workflow_dispatch:

jobs:
  build_and_test:

    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v6

    - name: Setup emsdk
      uses: mymindstorm/setup-emsdk@v14
      with:
        # Make sure to set a version number!
        version: 4.0.23
        # This is the name of the cache folder.
        # The cache folder will be placed in the build directory,
        #  so make sure it doesn't conflict with anything!
        actions-cache-folder: 'emsdk-cache'
    - name: build wasm
      run: make

    - uses: actions/setup-node@v6
      with:
        node-version: 24

    - name: build js
      run: |
        npm i
        npm run build

    - name: check environment
      run: |
        pwd
        ls -al ./test

    - name: test
      run: npm test

    - name: Pack package
      run: npm pack

    - name: Upload package artifact
      uses: actions/upload-artifact@v7
      with:
        name: npm-package
        path: '*.tgz'
        retention-days: 30

  publish:
    needs: build_and_test
    if: github.event_name == 'release'
    runs-on: ubuntu-latest
    permissions:
      id-token: write
      contents: read

    steps:
    - name: Download package artifact
      uses: actions/download-artifact@v8
      with:
        name: npm-package

    - uses: actions/setup-node@v6
      with:
        node-version: '24'
        registry-url: 'https://registry.npmjs.org'

    - name: Publish to npm
      run: npm publish *.tgz --provenance --access public

