#!/usr/bin/env bash
set -euo pipefail

# Derived from .github/workflows/build.yml and .github/workflows/release.yml
# Publishes the js artifact to npm only (other languages ignored).

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")"/.. && pwd)"
cd "$ROOT_DIR"

# Configurable inputs (env overrides)
REGISTRY_HOST="${NPM_REGISTRY:-registry.npmjs.org}"
DIST_TAG="${NPM_DIST_TAG:-latest}"
DRY_RUN="${NPM_PUBLISH_DRY_RUN:-false}"

die() { echo "error: $*" >&2; exit 1; }

# Optional auth via NPM_TOKEN (or ensure you are already logged in with `npm login`)
if [[ -n "${NPM_TOKEN:-}" ]]; then
  npm config set "//${REGISTRY_HOST}/:_authToken" "${NPM_TOKEN}"
fi

# Install deps
yarn install --check-files --frozen-lockfile

# Build js artifact
npx projen package:js

# Locate tarball
TARBALL=""
if compgen -G "dist/js/*.tgz" > /dev/null; then
  # pick the most recent tgz
  TARBALL=$(ls -t dist/js/*.tgz | head -n 1)
fi
[[ -n "$TARBALL" && -f "$TARBALL" ]] || die "JS package tarball not found under dist/js/*.tgz"

# Publish
PUBLISH_ARGS=("$TARBALL" "--access" "public" "--tag" "${DIST_TAG}" "--registry" "https://${REGISTRY_HOST}")
if [[ "$DRY_RUN" == "true" ]]; then
  PUBLISH_ARGS+=("--dry-run")
fi

npm publish "${PUBLISH_ARGS[@]}"

echo "Published: ${TARBALL} (tag=${DIST_TAG})"


