# Common build tool setup steps
# Used by both official-release build and PR checks
# Installs Node.js, authenticates npm, and installs build tools

steps:
  - task: UseNode@1
    displayName: "Use Node.js 22"
    inputs:
      version: "22.x"

    # Force usage of Azure Artifacts npm registry
  - task: npmAuthenticate@0
    inputs:
      workingFile: .npmrc

  - task: Bash@3
    displayName: "Bootstrap yarn"
    env:
      NPM_CONFIG_USERCONFIG: $(Build.SourcesDirectory)/.npmrc
    inputs:
      targetType: inline
      script: |
        set -euo pipefail
        BOOTSTRAP_DIR=".yarn-bin"
        rm -rf "$BOOTSTRAP_DIR"
        echo "Installing yarn@1.22.22 into $BOOTSTRAP_DIR (tool-only)"
        npm install \
          --loglevel info \
          --no-save \
          --no-audit \
          --no-fund \
          --ignore-scripts \
          --prefix "$BOOTSTRAP_DIR" \
          yarn@1.22.22
        echo "##vso[task.setvariable variable=YARN_BOOTSTRAP_DIR]$PWD/$BOOTSTRAP_DIR"
        echo "##vso[task.setvariable variable=YARN_BIN]$PWD/$BOOTSTRAP_DIR/node_modules/.bin/yarn"
        echo "Yarn bootstrap dir: $PWD/$BOOTSTRAP_DIR"
        "$BOOTSTRAP_DIR/node_modules/.bin/yarn" --version

  - task: Bash@3
    displayName: "Install project dependencies (yarn)"
    inputs:
      targetType: inline
      script: |
        set -euo pipefail
        cd $(Build.SourcesDirectory)

        #################################################################################
        # TODO: this is temporary until we have a GitHub PR validator pipeline that can
        # also authenticate to the private npm registry.
        # When resolved, we should just run:
        # npx yarn --frozen-lockfile
        #################################################################################

        rm -rf node_modules
        mv yarn.lock yarn.lock_bak
        mv yarn.lock_cfs yarn.lock

        # #################################################################################
        echo "=== Installing dependencies ==="
        "$YARN_BOOTSTRAP_DIR/node_modules/.bin/yarn" install --frozen-lockfile --verbose

        # Expose project-local vsce binary as a pipeline variable for downstream steps (manifest gen, publish)
        if [ -x "node_modules/.bin/vsce" ]; then
          echo "##vso[task.setvariable variable=VSCE_BIN]$PWD/node_modules/.bin/vsce"
          echo "VSCE_BIN set to $PWD/node_modules/.bin/vsce"
        else
          echo "ERROR: vsce not found in node_modules/.bin (is it a devDependency?)." >&2
          exit 1
        fi
