#!/usr/bin/env bash
# Rebuild the MIT viewer bundle; source maps include upstream sources.
set -euo pipefail
VERSION="${1:-0.186.1}"
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
WORK="$(mktemp -d)"
trap 'rm -rf "$WORK"' EXIT
cd "$WORK"
npm init -y > /dev/null
npm install --no-audit --no-fund "three@$VERSION" esbuild@0.25 > /dev/null
cat > entry.mjs <<'EOF'
export { WebGLRenderer, Scene, BufferGeometry, Float32BufferAttribute, Mesh, MeshStandardMaterial,
  PerspectiveCamera, HemisphereLight, DirectionalLight, GridHelper, Vector2, Vector3, Raycaster, Color, DoubleSide,
  SphereGeometry, MeshBasicMaterial } from 'three';
export { OrbitControls } from 'three/addons/controls/OrbitControls.js';
EOF
OUT="$ROOT/js/vendor/three-$VERSION"
mkdir -p "$OUT"
npx esbuild entry.mjs --bundle --format=esm --minify --sourcemap --sources-content=true --legal-comments=linked --target=es2020 --outfile="$OUT/three.mjs"
cp node_modules/three/LICENSE "$OUT/LICENSE.txt"
