#!/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 - Don't write a package-lock.json as
#   we don't use it and it can cause issues with `npm ls`,
#   which is run by subsequent tasks in CI:
#   https://github.com/npm/npm/issues/19393
#
# --no-save - Don't update package.json - as we don't use
#   package-lock.json, we use the checksum of package.json
#   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{} npm install --no-package-lock --no-save "{}"

fi
