#!/usr/bin/env bash

# This is quite unfortunate, but it's necessary.  preact/compat injects a `React`` type into the
# global scope, and the "@types/react" package does the same.  However, these types are
# incompatible, and TypeScript is indecisive (read, it appears indeterministic) about which global
# React type it thinks things are referring to.  Some dependencies (e.g., "react-router") depend on
# the global React types provided by "@types/react", so we _have_ to have those installed, and we
# also must have `preact/compat` installed (it's part of Preact anyway).  So the only option left is
# to just stop preact/compat from exporting a global React type.

echo "Patching Preact Types"

SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )

cd "$SCRIPT_DIR/../node_modules/.pnpm" || exit

for x in preact@*; do
  FILE="$x/node_modules/preact/compat/src/index.d.ts"
  sed -i.bak 's/export = React;/export = React_Compat;/' "$FILE"
  sed -i.bak 's/export as namespace React;/export as namespace React_Compat;/' "$FILE"
  sed -i.bak 's/declare namespace React {/declare namespace React_Compat {/' "$FILE"
  rm "$FILE.bak"
done;
