#!/usr/bin/env bash
#
# HELPER PURPOSE

# Workaround for a bug in npm where it doesn't correctly
# resolve conflicting peer dependencies.
#
# Parses errors for missing peer dependencies from
# the output of `npm ls` and then pipes the package
# names to `npm install`.
#
# Why we pass the flags we do to `npm install`:
#
# --no-package-lock - While we now use package-lock.json
#   in our repos, skip package-lock.json in this instance
#   as we don't want to accidentally modify the file
#   for subsequent steps in the workflow, e.g cache keys
#   and artefact generation.
#
# --no-save - We don't want to modify package.json as we
#   use its checksum for some CI tasks e.g. naming node_module caches
#

# Set error handling
#
# Do *not* set `-o pipefail` as `npm ls --production --parseable`
# will have an exit code of 1 when there are missing peer
# dependencies, but that's what we're expecting to happen
set -eu

# HELPER COMMANDS

if [ -e package.json ]; then

    npm ls --production --parseable 2>&1 >/dev/null | \
      sed -n -e 's/^npm ERR! peer dep missing: \(.*\),.*/\1/p' | \
          xargs -I{} echo -n '"{}" ' | \
            xargs npm install --no-package-lock --no-save

fi
