#!/bin/bash # Build the shared rules (core/) for the browser: a release WebAssembly module # plus its wasm-bindgen ES module glue and TypeScript declarations. # # Usage: core/wasm/build.sh [OUT_DIR] (default: core/wasm/pkg) # # Requires Rust 1.88+ with the wasm32-unknown-unknown target and # wasm-bindgen-cli at exactly the version Cargo.lock pins for wasm-bindgen. # Reads CARGO_HOME (default ~/.cargo) only to remap its paths; it replaces # any RUSTFLAGS for this build. OUT_DIR is replaced only after both steps pass. set -euo pipefail [ $# -le 1 ] || { sed -n '2,/^set -e/p' "$0" | sed '$d;s/^# \{0,1\}//' >&2; exit 2; } HERE=$(cd "$(dirname "$0")" && pwd) OUT=$(realpath -m "${1:-$HERE/pkg}") command -v cargo >/dev/null || { echo "core/wasm/build.sh: cargo is required (Rust 1.88+)" >&2; exit 2; } command -v wasm-bindgen >/dev/null || { echo "core/wasm/build.sh: wasm-bindgen-cli is required: cargo install wasm-bindgen-cli --version VERSION --locked" >&2 exit 2 } want=$(sed -n '/^name = "wasm-bindgen"$/{n;s/^version = "\(.*\)"$/\1/p;}' "$HERE/Cargo.lock") have=$(wasm-bindgen --version | cut -d' ' -f2) [ "$want" = "$have" ] || { echo "core/wasm/build.sh: wasm-bindgen-cli $have does not match the locked crate $want" >&2 exit 2 } rustup target list --installed 2>/dev/null | grep -qx wasm32-unknown-unknown || [ ! -x "$(command -v rustup)" ] || { echo "core/wasm/build.sh: run: rustup target add wasm32-unknown-unknown" >&2 exit 2 } # Remap the checkout, Cargo registry and toolchain paths that panic locations # would embed, so the same commit builds the same bytes on any machine and no # build-machine path ships in the app. Symbols are stripped (Cargo.toml). # Builds of one checkout run one at a time where flock(1) exists. mkdir -p "$HERE/target" "$(dirname "$OUT")" if command -v flock >/dev/null; then exec 9>"$HERE/target/.build.lock" flock 9 fi ROOT=$(dirname "$(dirname "$HERE")") REGISTRY=${CARGO_HOME:-$HOME/.cargo}/registry/src SYSROOT=$(rustc --print sysroot) FLAGS=() for map in "$ROOT=/tokenling" "$(realpath -m "$ROOT")=/tokenling" "$REGISTRY=/cargo" \ "$(realpath -m "$REGISTRY")=/cargo" "$SYSROOT=/rust" "$(realpath -m "$SYSROOT")=/rust"; do FLAGS+=("--remap-path-prefix=$map") done CARGO_ENCODED_RUSTFLAGS=$(IFS=$'\x1f'; echo "${FLAGS[*]}") \ cargo build --release --locked --quiet --manifest-path "$HERE/Cargo.toml" --target wasm32-unknown-unknown # Stage beside OUT, so the final swap is a rename on one filesystem. STAGE=$(mktemp -d "$(dirname "$OUT")/.$(basename "$OUT").XXXXXX") trap 'rm -rf "$STAGE"' EXIT wasm-bindgen "$HERE/target/wasm32-unknown-unknown/release/tokenling_core.wasm" \ --target web --out-dir "$STAGE" chmod 755 "$STAGE" rm -rf "$OUT" mv "$STAGE" "$OUT" trap - EXIT