#!/bin/sh
# Type-check paywall.js with the TypeScript compiler in checkJs mode.
#
# Exits 77 ("skipped" for meson and for the GNU test convention) when no
# TypeScript compiler is available locally.  We never fall back to a
# plain `npx --package typescript', which would download a compiler:
# running the test suite must not reach out to the network.  To run it
# by hand without installing anything:
#
#   npx --package typescript tsc --allowJs --checkJs --noEmit \
#     --target esnext --lib esnext,esnext.bigint,dom,dom.iterable \
#     src/frontend/paywall.js src/frontend/global.d.ts
#
# dom.iterable is not optional: without it `for (const x of
# el.getElementsByClassName(...))' is an error, because plain `dom'
# declares HTMLCollectionOf without a [Symbol.iterator].

set -eu

srcdir=${SRCDIR:-$(dirname "$0")}

# `tsc' on npm is NOT the TypeScript compiler -- it is a squatted
# package whose entire content is a message telling you so, and it
# exits 0 for --version.  A bare `npx --no-install tsc --version'
# probe therefore succeeds against it and we then run it for real,
# which fails the test with that message and nothing to do with this
# code.  Insist the probe looks like a version.
if command -v tsc >/dev/null 2>&1; then
  set -- tsc
elif npx --no-install tsc --version 2>/dev/null | grep -Eq '[0-9]+\.[0-9]+'; then
  set -- npx --no-install tsc
else
  echo "no local TypeScript compiler found, skipping type check" >&2
  exit 77
fi

exec "$@" \
  --allowJs \
  --checkJs \
  --noEmit \
  --target esnext \
  --lib esnext,esnext.bigint,dom,dom.iterable \
  "$srcdir/paywall.js" \
  "$srcdir/global.d.ts"
