#!/usr/bin/env bash
#
# End-to-end SeaLights flow for a Next.js SSR project:
# 1. Build the app (Next.js produces `.next/`)
# 2. Open a SeaLights build session
# 3. Scan client bundles (`.next/static/`)
# 4. Scan server bundles (the rest of `.next/`)
# 5. Mark the build session as complete
# 6. Start the server with the runtime preload so coverage is collected
set -euo pipefail
if [ ! -f sltoken.txt ]; then
echo "ERROR: sltoken.txt not found in $(pwd)." >&2
echo " Copy sltoken.txt.example, paste your SeaLights agent token, then re-run." >&2
exit 1
fi
# 1. Clean previous builds
rm -rf .next sl-dist
# 2. Build the Next.js app (production mode, source maps enabled in next.config.mjs)
npm install
npm run build
# 3. Open a build session
# In CI, replace the timestamp with your commit SHA or build system ID.
BUILD_ID="$(date +%s)"
npx slnodejs config \
--appname "<YOUR_APP>" \
--branch main \
--build "$BUILD_ID"
# 4. Client scan — instruments browser bundles into sl-dist/
# and registers them as the "client" sub-module in the build session.
npx slnodejs scan \
--workspacepath .next/static \
--es6Modules \
--scm none \
--instrumentForBrowsers \
--outputpath sl-dist \
--useRelativeSlMapping \
--newInstrumenter \
--uniqueModuleId client
# Remove the un-instrumented client output so it is not re-scanned
# by the server pass. The instrumented copy in sl-dist/ is restored below.
rm -rf .next/static
# 5. Server scan — walks the rest of .next/ (server bundles only)
npx slnodejs scan \
--workspacepath .next \
--es6Modules \
--scm none \
--uniqueModuleId server
# 6. Finalise the build session (signals all sub-modules have been submitted)
npx slnodejs scanned --buildsessionidfile buildSessionId --ok
# 7. Restore the instrumented client bundles so Next.js serves them at runtime
mv sl-dist .next/static
# 8. Start the server with the SeaLights Node preload
# This script does NOT open or close a test session — see Step 5.
NODE_DEBUG=sl \
SL_LOG_LEVEL=debug \
NODE_OPTIONS='-r ./node_modules/slnodejs/lib/preload.js' \
npm run start