# Reproduce upstream's git-checkout build (scripts/build/package.sh) with the
# tools available in Debian. The npm-published tarball ships a prebuilt, flat
# lib/ (index.js/index.cjs/*.d.ts/*.d.cts ...); we regenerate it from src/.
#
# Skipped compared to upstream: the CDN bundle (needs bun) and the prettier
# beautify pass (cosmetic). The only build tool missing from Debian,
# babel-plugin-replace-import-extension, is provided locally (see
# debian/babel-plugin-replace-import-extension.js).

set -e

dir="$(pwd)/lib"
export PACKAGE_OUTPUT_PATH="$dir"
rm -rf "$dir"
mkdir -p "$dir"

# Provide the babel plugin that is not packaged in Debian.
mkdir -p node_modules/babel-plugin-replace-import-extension
cp debian/babel-plugin-replace-import-extension.js \
    node_modules/babel-plugin-replace-import-extension/index.js
printf '{"name":"babel-plugin-replace-import-extension","version":"1.6.0","main":"index.js"}\n' \
    > node_modules/babel-plugin-replace-import-extension/package.json

# Transpile ESM versions of the files (src/**/*.ts -> lib/**/*.js).
env BABEL_ENV=esm babeljs src \
    --config-file ./babel.config.json \
    --source-root src \
    --out-dir "$dir" \
    --extensions .js,.ts \
    --out-file-extension .js \
    --quiet

# Add fallback for Next.js and other tools that modularize imports.
tsx scripts/build/modularized.ts

# Transpile CommonJS versions of the files (src/**/*.ts -> lib/**/*.cjs).
env BABEL_ENV=cjs babeljs src \
    --config-file ./babel.config.json \
    --source-root src \
    --out-dir "$dir" \
    --extensions .js,.ts \
    --out-file-extension .cjs \
    --quiet

# Generate the TypeScript declarations (lib/**/*.d.ts). src/_lib/test is a unit
# test helper (it imports vitest and sinon) that is not part of the shipped
# library; tolerate the resulting "cannot find module" errors — tsc still emits
# the declarations for every other file — and drop the helper afterwards.
tsc --project tsconfig.lib.json --outDir "$dir" || true
rm -rf "$dir/_lib/test"

# Flatten the nested structure (lib/addDays/index.js -> lib/addDays.js, etc.).
tsx scripts/build/flatten.ts

# Generate the .d.cts declarations for the CommonJS entry points.
tsx scripts/build/cts.ts
