joeylib2/scripts/lib/webGate.sh

62 lines
1.9 KiB
Bash

# shellcheck shell=bash
# Part of JoeyLib, Copyright (c) 2026 Scott Duensing, under the MIT License.
# See LICENSE.md for license information.
# SPDX-License-Identifier: MIT
#
# Shared by the web gates (scripts/bench-web.sh, scripts/verify-web-*.sh) and
# joey-run: serve a web program's folder (make web: bin/NAME/NAME.html and
# its files) over HTTP on this machine and drive it in headless Chromium with
# scripts/lib/webDriver.mjs. Source after joeyEnv.sh.
#
# webNeed exit 2 unless Chromium and Node (emsdk's) are here
# webServe DIR serve DIR; sets WEB_PORT and WEB_SERVER_PID
# webDrive PAGE ARGS... run webDriver.mjs on http://127.0.0.1:WEB_PORT/PAGE
# webStop stop the server
WEB_PORT=""
WEB_SERVER_PID=""
WEB_PORT_MIN=20000
WEB_PORT_SPAN=20000
webNeed() {
WEB_CHROME="$(command -v chromium || command -v chromium-browser || command -v google-chrome || true)"
if [ -z "$WEB_CHROME" ]; then
echo "$(basename "$0"): no Chromium or Chrome to run web programs in" >&2
exit 2
fi
WEB_NODE="$(ls -d "${EMSDK_DIR:-}"/node/*/bin/node 2>/dev/null | head -1)"
if [ -z "$WEB_NODE" ]; then
echo "$(basename "$0"): emsdk's node is not installed; run: ./install.sh install toolchain:web" >&2
exit 2
fi
}
webServe() {
local tries
for ((tries = 0; tries < 10; tries++)); do
WEB_PORT=$((WEB_PORT_MIN + RANDOM % WEB_PORT_SPAN))
python3 -m http.server "$WEB_PORT" --bind 127.0.0.1 --directory "$1" > /dev/null 2>&1 &
WEB_SERVER_PID=$!
sleep 0.5
if joeyAlive "$WEB_SERVER_PID"; then
return 0
fi
done
echo "$(basename "$0"): could not start a web server" >&2
exit 1
}
webDrive() {
local page="$1"
shift
"$WEB_NODE" "$JOEY_REPO/scripts/lib/webDriver.mjs" --chrome "$WEB_CHROME" --url "http://127.0.0.1:$WEB_PORT/$page" "$@"
}
webStop() {
joeyStop "$WEB_SERVER_PID"
WEB_SERVER_PID=""
}