#!/bin/sh
# Make the Babel 8 sources parseable by the Babel 7 from the archive, which is
# used to bootstrap the build. Only the throwaway first build goes through this
# script: once a Babel 8 package is available, debian/rules skips it and the
# sources are compiled as-is.
#
# Every rewrite is reversible: debian/bootstrap-babel7-restore.sh undoes them
# before the TypeScript declarations are generated, and
# debian/fix-import-attributes.sh puts the import attributes back into the
# compiled output.
set -e

SOURCES="packages/*/src eslint/*/src codemods/*/src"

# Import attributes (ES2025) are not understood by the Babel 7 parser. Record
# the specifiers that carry one, then strip the attribute.
grep -rho 'from "[^"]*" with { type: "json" }' $SOURCES 2>/dev/null \
	| sed -e 's/^from "//' -e 's/" with .*$//' \
	| cat - debian/json-imports.list 2>/dev/null \
	| sort -u > debian/json-imports.list.new
mv debian/json-imports.list.new debian/json-imports.list

grep -rl 'with { type: "json" }' $SOURCES 2>/dev/null \
	| xargs -r sed -i 's/ with { type: "json" }//'

# "const" type parameter modifiers (TypeScript 5.0): comment the keyword out,
# the Babel 7 parser skips comments.
grep -rl '<const [A-Za-z]' $SOURCES 2>/dev/null \
	| xargs -r sed -i 's|<const \([A-Za-z]\)|</*const*/ \1|g'

# "export type * from" (TypeScript 5.0) is not understood either. These
# re-exports are type-only, so hiding them is a no-op for the emitted code.
grep -rl '^ *export type \* from' $SOURCES 2>/dev/null \
	| xargs -r sed -i 's|^\( *\)export type \* from|\1//BABEL7// export type * from|'

# The Babel 7 TypeScript parser refuses a rest element without a label in a
# tuple whose other members are labelled. Labelling it is valid TypeScript.
sed -i 's/^  \.\.\.TryLocs,$/  ...tryLocs: TryLocs, \/\/BABEL7\//' \
	packages/babel-helpers/src/helpers/regenerator.ts
