use crate::pulse::render::project::ProjectWriter;
use anyhow::{Context, Result, bail};
use std::io::{BufRead, BufReader};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};
pub mod template {
include!(concat!(env!("OUT_DIR"), "/pulse_template.rs"));
}
pub const MIN_NODE: (u32, u32, u32) = (22, 12, 0);
pub fn pulse_home() -> PathBuf {
if let Ok(h) = std::env::var("REFLEX_PULSE_HOME") {
return PathBuf::from(h);
}
dirs::home_dir()
.unwrap_or_else(|| PathBuf::from("."))
.join(".reflex")
.join("pulse")
}
#[derive(Debug, Clone)]
pub struct Node {
pub path: PathBuf,
pub version: (u32, u32, u32),
}
pub fn parse_node_version(s: &str) -> Option<(u32, u32, u32)> {
let v = s.trim().trim_start_matches('v');
let mut it = v.split('.').map(|p| p.parse::<u32>().ok());
Some((it.next()??, it.next()??, it.next().flatten().unwrap_or(0)))
}
pub fn find_node() -> Result<Node> {
let path = std::env::var("REFLEX_PULSE_NODE")
.map(PathBuf::from)
.unwrap_or_else(|_| PathBuf::from("node"));
let out = Command::new(&path)
.arg("--version")
.output()
.with_context(|| {
format!(
"Node.js {}.{}+ is needed to build the site and `{}` was not found.\n \
Install Node (https://nodejs.org), or set REFLEX_PULSE_NODE, or run with --no-build \
to write the site project without building it.",
MIN_NODE.0,
MIN_NODE.1,
path.display()
)
})?;
let version = parse_node_version(&String::from_utf8_lossy(&out.stdout))
.context("could not read `node --version`")?;
if version < MIN_NODE {
bail!(
"Node {}.{}.{} is too old to build the site; {}.{}+ is needed (set REFLEX_PULSE_NODE to another node).",
version.0,
version.1,
version.2,
MIN_NODE.0,
MIN_NODE.1
);
}
Ok(Node { path, version })
}
#[derive(Debug, Clone)]
pub struct Runtime {
pub root: PathBuf,
pub node: Node,
}
impl Runtime {
pub fn astro_entry(&self) -> PathBuf {
self.root.join("node_modules/astro/bin/astro.mjs")
}
pub fn site_dir(&self, workspace: &Path) -> PathBuf {
let canon = std::fs::canonicalize(workspace).unwrap_or_else(|_| workspace.to_path_buf());
let key = blake3::hash(canon.to_string_lossy().as_bytes()).to_hex()[..12].to_string();
let name = canon
.file_name()
.map(|n| crate::pulse::model::ids::slugify(&n.to_string_lossy()))
.unwrap_or_else(|| "site".into());
self.root.join("sites").join(format!("{name}-{key}"))
}
}
const COMPLETE: &str = ".pulse-runtime-complete";
pub fn ensure(offline: bool) -> Result<Runtime> {
let node = find_node()?;
if let Ok(dir) = std::env::var("REFLEX_PULSE_RUNTIME") {
let root = PathBuf::from(dir);
if !root.join("node_modules/astro").exists() {
bail!(
"REFLEX_PULSE_RUNTIME={} has no node_modules/astro",
root.display()
);
}
return Ok(Runtime { root, node });
}
let root = pulse_home().join("runtime").join(template::DEPS_HASH);
if root.join(COMPLETE).exists() {
return Ok(Runtime { root, node });
}
if offline {
bail!(
"The site runtime is not installed ({}) and --offline forbids installing it.\n \
Run once without --offline, or use --no-build.",
root.display()
);
}
match install_prebuilt(&root) {
Ok(true) => {}
Ok(false) => install(&root, &node)?,
Err(e) => {
eprintln!(" prebuilt runtime unavailable ({e:#}); installing with npm instead");
install(&root, &node)?;
}
}
Ok(Runtime { root, node })
}
pub fn key() -> &'static str {
template::DEPS_HASH
}
pub fn status() -> String {
let mut out = String::new();
match find_node() {
Ok(n) => out.push_str(&format!(
"node: {} ({}.{}.{})\n",
n.path.display(),
n.version.0,
n.version.1,
n.version.2
)),
Err(e) => out.push_str(&format!("node: not usable: {e:#}\n")),
}
let root = pulse_home().join("runtime").join(key());
let state = if root.join(COMPLETE).exists() {
"installed"
} else {
"not installed"
};
out.push_str(&format!("runtime: {} ({state})\n", root.display()));
let lock = RuntimeLock::embedded();
let platform = platform_id().unwrap_or("unsupported");
let prebuilt = match lock.asset_for(platform) {
Some(a) => format!("{} ({:.1} MB)", lock.url(a), a.size as f64 / 1_048_576.0),
None => "none published; falls back to npm ci".to_string(),
};
out.push_str(&format!("platform: {platform}\nprebuilt: {prebuilt}\n"));
out
}
pub fn platform_id() -> Option<&'static str> {
Some(match (std::env::consts::OS, std::env::consts::ARCH) {
("linux", "x86_64") => "linux-x64",
("linux", "aarch64") => "linux-arm64",
("macos", "x86_64") => "darwin-x64",
("macos", "aarch64") => "darwin-arm64",
("windows", "x86_64") => "win32-x64",
("windows", "aarch64") => "win32-arm64",
_ => return None,
})
}
#[derive(Debug, Clone, serde::Deserialize)]
pub struct Asset {
pub name: String,
pub sha256: String,
#[serde(default)]
pub size: u64,
}
#[derive(Debug, Clone, Default, serde::Deserialize)]
pub struct RuntimeLock {
#[serde(default)]
pub deps_hash: String,
#[serde(default)]
pub release_base: String,
#[serde(default)]
pub assets: std::collections::BTreeMap<String, Asset>,
}
impl RuntimeLock {
pub fn embedded() -> Self {
serde_json::from_str(template::RUNTIME_LOCK).unwrap_or_default()
}
pub fn asset_for(&self, platform: &str) -> Option<&Asset> {
(self.deps_hash == template::DEPS_HASH)
.then(|| self.assets.get(platform))
.flatten()
}
pub fn url(&self, asset: &Asset) -> String {
let base =
std::env::var("REFLEX_PULSE_MIRROR").unwrap_or_else(|_| self.release_base.clone());
format!(
"{}/pulse-runtime-{}/{}",
base.trim_end_matches('/'),
self.deps_hash,
asset.name
)
}
}
pub fn sha256_hex(bytes: &[u8]) -> String {
use sha2::{Digest, Sha256};
let mut h = Sha256::new();
h.update(bytes);
h.finalize().iter().map(|b| format!("{b:02x}")).collect()
}
fn install_prebuilt(root: &Path) -> Result<bool> {
let lock = RuntimeLock::embedded();
let Some(asset) = platform_id().and_then(|p| lock.asset_for(p)) else {
return Ok(false);
};
std::fs::create_dir_all(root)?;
let guard =
crate::atomic_write::IndexLock::acquire_with_timeout(root, Duration::from_secs(900))
.context("waiting for another rfx process that is installing the site runtime")?;
if root.join(COMPLETE).exists() {
drop(guard);
return Ok(true);
}
let url = lock.url(asset);
eprintln!("Downloading the Pulse site runtime ({})…", asset.name);
let start = Instant::now();
let bytes = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()?
.block_on(async {
let resp = reqwest::get(&url).await?.error_for_status()?;
resp.bytes().await
})
.with_context(|| format!("downloading {url}"))?;
let got = sha256_hex(&bytes);
if !got.eq_ignore_ascii_case(&asset.sha256) {
bail!(
"checksum mismatch for {}: expected {}, got {got}",
asset.name,
asset.sha256
);
}
let tmp = root.join(format!("node_modules.tmp-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&tmp);
std::fs::create_dir_all(&tmp)?;
let decoder = zstd::stream::read::Decoder::new(&bytes[..])?;
let mut archive = tar::Archive::new(decoder);
for entry in archive.entries()? {
let mut entry = entry?;
entry.unpack_in(&tmp)?;
}
let nm = tmp.join("node_modules");
if !nm.join("astro").exists() {
bail!("{} does not contain node_modules/astro", asset.name);
}
let _ = std::fs::remove_dir_all(root.join("node_modules"));
std::fs::rename(&nm, root.join("node_modules"))?;
let _ = std::fs::remove_dir_all(&tmp);
std::fs::write(root.join(COMPLETE), template::DEPS_HASH)?;
eprintln!(
" runtime ready in {:.0}s ({:.1} MB)",
start.elapsed().as_secs_f64(),
bytes.len() as f64 / 1_048_576.0
);
drop(guard);
Ok(true)
}
fn npm_for(node: &Node) -> PathBuf {
if let Some(dir) = node.path.parent().filter(|d| !d.as_os_str().is_empty()) {
for name in ["npm", "npm.cmd"] {
let p = dir.join(name);
if p.exists() {
return p;
}
}
}
PathBuf::from(if cfg!(windows) { "npm.cmd" } else { "npm" })
}
fn install(root: &Path, node: &Node) -> Result<()> {
std::fs::create_dir_all(root)?;
let lock = crate::atomic_write::IndexLock::acquire_with_timeout(root, Duration::from_secs(900))
.context("waiting for another rfx process that is installing the site runtime")?;
if root.join(COMPLETE).exists() {
drop(lock);
return Ok(());
}
for (rel, bytes) in template::FILES {
if *rel == "package.json" || *rel == "package-lock.json" {
std::fs::write(root.join(rel), bytes)?;
}
}
eprintln!(
"Installing the Pulse site runtime (Astro + Starlight) into {} — once per template version…",
root.display()
);
let start = Instant::now();
let status = Command::new(npm_for(node))
.args([
"ci",
"--ignore-scripts",
"--omit=dev",
"--no-audit",
"--no-fund",
"--loglevel=error",
])
.current_dir(root)
.status()
.context("running `npm ci` (npm must be installed alongside node)")?;
if !status.success() {
bail!("`npm ci` failed in {} ({status})", root.display());
}
std::fs::write(root.join(COMPLETE), template::DEPS_HASH)?;
eprintln!(" runtime ready in {:.0}s", start.elapsed().as_secs_f64());
drop(lock);
Ok(())
}
pub fn stage_template(site_dir: &Path) -> Result<()> {
let mut w = ProjectWriter::open(site_dir)?;
for (rel, bytes) in template::FILES {
if *rel == "package-lock.json" {
continue; }
w.put(rel, bytes)?;
}
w.finish("\0")?;
Ok(())
}
#[derive(Debug, Clone)]
pub struct BuildOutcome {
pub dist: PathBuf,
pub elapsed: Duration,
}
pub fn astro_build(rt: &Runtime, site_dir: &Path, verbose: bool) -> Result<BuildOutcome> {
let start = Instant::now();
let log_path = site_dir.join("build.log");
let mut child = Command::new(&rt.node.path)
.arg(rt.astro_entry())
.args(["build", "--root"])
.arg(site_dir)
.current_dir(site_dir)
.env("ASTRO_TELEMETRY_DISABLED", "1")
.env("NODE_ENV", "production")
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.context("starting astro build")?;
let stderr = child.stderr.take().expect("piped stderr");
let err_thread = std::thread::spawn(move || {
BufReader::new(stderr)
.lines()
.map_while(Result::ok)
.collect::<Vec<_>>()
});
let mut log: Vec<String> = Vec::new();
let stdout = child.stdout.take().expect("piped stdout");
for line in BufReader::new(stdout).lines().map_while(Result::ok) {
if verbose {
eprintln!(" {line}");
} else if line.contains("Complete!")
|| line.contains("pages built in")
|| line.contains("[build] ") && line.contains("page(s) built")
{
eprintln!(" {}", strip_ansi(&line));
}
log.push(line);
}
let status = child.wait()?;
log.extend(err_thread.join().unwrap_or_default());
let _ = std::fs::write(&log_path, log.join("\n"));
if !status.success() {
let tail: Vec<String> = log
.iter()
.rev()
.take(40)
.rev()
.map(|l| strip_ansi(l))
.collect();
bail!(
"astro build failed ({status}). Last lines of {}:\n{}",
log_path.display(),
tail.join("\n")
);
}
Ok(BuildOutcome {
dist: site_dir.join("dist"),
elapsed: start.elapsed(),
})
}
fn strip_ansi(s: &str) -> String {
let mut out = String::with_capacity(s.len());
let mut chars = s.chars().peekable();
while let Some(c) = chars.next() {
if c == '\u{1b}' {
for n in chars.by_ref() {
if n.is_ascii_alphabetic() {
break;
}
}
} else {
out.push(c);
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn node_versions() {
assert_eq!(parse_node_version("v24.15.0\n"), Some((24, 15, 0)));
assert_eq!(parse_node_version("22.12"), Some((22, 12, 0)));
assert!(parse_node_version("v22.11.0").unwrap() < MIN_NODE);
assert!(parse_node_version("v22.12.0").unwrap() >= MIN_NODE);
assert_eq!(parse_node_version("nope"), None);
}
#[test]
fn template_is_embedded() {
let names: Vec<&str> = template::FILES.iter().map(|(n, _)| *n).collect();
for want in [
"astro.config.mjs",
"package.json",
"package-lock.json",
"src/layouts/PulsePage.astro",
] {
assert!(names.contains(&want), "{want} missing from {names:?}");
}
assert!(
!names
.iter()
.any(|n| n.starts_with("node_modules/") || n.starts_with("scripts/"))
);
assert_eq!(template::DEPS_HASH.len(), 12);
}
#[test]
fn staging_writes_template_without_dependencies() {
let dir = tempfile::TempDir::new().unwrap();
stage_template(dir.path()).unwrap();
assert!(dir.path().join("astro.config.mjs").exists());
assert!(!dir.path().join("package-lock.json").exists());
assert!(
dir.path().join("package.json").exists(),
"declares \"type\": \"module\""
);
}
#[test]
fn runtime_lock_matching() {
let json = format!(
r#"{{"deps_hash": "{}", "release_base": "https://example.test/dl",
"assets": {{"linux-x64": {{"name": "a.tar.zst", "sha256": "ab", "size": 1}}}}}}"#,
template::DEPS_HASH
);
let lock: RuntimeLock = serde_json::from_str(&json).unwrap();
assert!(lock.asset_for("linux-x64").is_some());
assert!(lock.asset_for("darwin-arm64").is_none());
assert_eq!(
lock.url(lock.asset_for("linux-x64").unwrap()),
format!(
"https://example.test/dl/pulse-runtime-{}/a.tar.zst",
template::DEPS_HASH
)
);
let stale: RuntimeLock =
serde_json::from_str(r#"{"deps_hash": "000000000000", "assets": {"linux-x64": {"name": "a", "sha256": "b"}}}"#).unwrap();
assert!(
stale.asset_for("linux-x64").is_none(),
"a stale manifest is ignored"
);
let _ = RuntimeLock::embedded();
assert_eq!(
sha256_hex(b"abc"),
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
);
}
#[test]
fn ansi_is_stripped() {
assert_eq!(strip_ansi("\u{1b}[32m✓ Complete!\u{1b}[39m"), "✓ Complete!");
}
}