name: Setup and cache
description: Setup for node, pnpm and cache for browser testing binaries
inputs:
  node-version:
    required: false
    description: Node version for setup-node
    default: 20.x

runs:
  using: composite

  steps:
    - name: Install pnpm
      uses: pnpm/action-setup@a7487c7e89a18df4991f7f222e4898a00d66ddda # v4.1.0

    - name: Set node version to ${{ inputs.node-version }}
      uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
      with:
        node-version: ${{ inputs.node-version }}

    - name: Resolve package versions
      id: resolve-package-versions
      shell: bash
      run: >
        echo "$(
          node -e "
            const fs = require('fs');
            const lockfile = fs.readFileSync('./pnpm-lock.yaml', 'utf8');
            const pattern = (name) => new RegExp(name + ':\\\s+specifier: [\\\s\\\w\\\.^]+version: (\\\d+\\\.\\\d+\\\.\\\d+)');
            const playwrightVersion = lockfile.match(pattern('playwright'))[1];
            console.log('PLAYWRIGHT_VERSION=' + playwrightVersion);
          "
        )" >> $GITHUB_OUTPUT

    - name: Check resolved package versions
      shell: bash
      if: |
        contains(fromJSON('[null, "", "undefined"]'), steps.resolve-package-versions.outputs.PLAYWRIGHT_VERSION)
      run: echo "Failed to resolve package versions. See log above." && exit 1

    - name: Cache Playwright v${{ steps.resolve-package-versions.outputs.PLAYWRIGHT_VERSION }}
      uses: actions/cache@0400d5f644dc74513175e3cd8d07132dd4860809 # v4.2.4
      id: playwright-cache
      with:
        path: ${{ env.PLAYWRIGHT_BROWSERS_PATH }}
        key: ${{ runner.os }}-playwright-${{ steps.resolve-package-versions.outputs.PLAYWRIGHT_VERSION }}
        restore-keys: |
          ${{ runner.os }}-playwright-
