#!/bin/sh
# Compile the TypeScript build tooling to plain ECMAScript modules.
#
# Upstream relies on Node.js' built-in TypeScript type stripping, which
# Debian's nodejs is not built with. Each file is transpiled in place (no
# bundling) so that its "import.meta.url" keeps pointing at the right
# directory, and its relative ".ts" specifiers are rewritten to ".mjs".
#
# The rewrite only touches specifiers that really point at a sibling
# TypeScript file: several of these scripts *generate* Babel sources and carry
# "import ... from '<something>.ts'" inside template literals, which must be
# left alone.
set -e

FILES=$(find Gulpfile.ts babel-worker.ts scripts packages/*/scripts \
	-name '*.ts' ! -name '*.d.ts' 2>/dev/null || true)

# Record what was generated so that debian/rules can clean it up again without
# touching the .mjs files that come from the tarball.
: > debian/tooling.list

for f in $FILES; do
	out="${f%.ts}.mjs"
	echo "$out" >> debian/tooling.list
	esbuild "$f" --platform=node --format=esm --log-level=warning \
		--outfile="$out"
	perl -i -pe '
		BEGIN { $dir = $ARGV[0]; $dir =~ s{/[^/]*$}{} or $dir = "."; }
		s{((?:from |import\(|new URL\()\s*["'"'"'])(\.{1,2}/[^"'"'"']*)\.ts(["'"'"'])}
		 { -e "$dir/$2.ts" ? "$1$2.mjs$3" : "$1$2.ts$3" }ge;
	' "$out"
done
