Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.
TypeScript 3dagent-skillsai-agentsai-videobevyclaude-codegame-enginegpulinuxmacosmotion-designmotion-graphicsreactrusttypescriptvideo-editingvideo-renderingwgpuwindows
raea run prints its console, its answer and a throw's message (#168)
shinyobjectz3a98e0a52d98
diff --git a/apps/engines/src/blender_ts.rs b/apps/engines/src/blender_ts.rsindex a076bced..b8dd31a8 100644--- a/apps/engines/src/blender_ts.rs+++ b/apps/engines/src/blender_ts.rs@@ -33,7 +33,7 @@ pub(crate) fn session(entry: &str, file: Option<&Path>, rest: &[String], secs: flet bridge = blender_bridge::start(&bin, file, rest)?;*BRIDGE.lock().map_err(|e| e.to_string())? = Some((bridge.port, bridge.token.clone()));let out = std::env::temp_dir().join(format!("raea-blender-{}.js", std::process::id()));- let ran = raea_runtime_bundle::bundle_entry(entry, &out, &[]).and_then(|_| raea_runtime_export::run_bundle(&out, secs));+ let ran = raea_runtime_bundle::bundle_entry(entry, &out, &[]).and_then(|_| raea_runtime_export::run_bundle_to_terminal(&out, secs));let _ = std::fs::remove_file(&out);let _ = post(&json!({ "sid": "raea", "ops": [{ "o": "quit" }] }));*BRIDGE.lock().map_err(|e| e.to_string())? = None;diff --git a/docs/manual/reference/cli/run.md b/docs/manual/reference/cli/run.mdindex c85615b1..2b8c81fb 100644--- a/docs/manual/reference/cli/run.md+++ b/docs/manual/reference/cli/run.md@@ -5,10 +5,20 @@ order: 8sources: ["engine/cli/src/cli.rs"]----`raea run` bundles a TypeScript file and runs it on the engine's own V8, with no window and no composition. If the-file's default export is a function, it's called. What the program prints is the answer; a throw ends the run with-exit code 1. It's how checks such as a room's `checkLayout` run, and it reaches the engine's native calls (solids,-ECS worlds) the way a composition does.+`raea run` bundles a TypeScript file and runs it on the engine's JavaScript, with no window and no composition. If+the file's default export is a function, it's called and awaited, and what it returns is printed: a string as it is,+anything else as JSON. The program's console goes to the terminal as node's does: `console.log` and `console.info`+to stdout, `console.warn` and `console.error` to stderr. A throw prints the error's name, message and stack, and ends+the run with exit code 1. It's how checks such as a room's `checkLayout` run, and it reaches the engine's native+calls (solids, ECS worlds) the way a composition does.++```ts+// count.ts: a line on stderr while it works, then its answer as JSON on stdout+export default async function () {+ console.error("counting")+ return { rooms: 3, errors: 0 }+}+``````shraea run checks/layout.tsdiff --git a/engine/cli/src/cli.rs b/engine/cli/src/cli.rsindex 2d1865a3..eb052ef4 100644--- a/engine/cli/src/cli.rs+++ b/engine/cli/src/cli.rs@@ -108,14 +108,14 @@ fn notes_run(project: &Path, rules: &[raea_app_notes::check::Rule], args: &[Stri}/// `raea run SCRIPT.ts`: a TypeScript program against the engine, headless (the native calls: solids, ECS-/// worlds, print). The script's default export, if a function, is called; what it prints goes to stdout; a throw-/// ends the run with exit 1.+/// worlds, print). Its default export, if a function, is called and its answer printed (JSON unless a string); its+/// console goes to the terminal (warn and error to stderr); a throw prints its message and stack, exit 1 (#168).pub fn run_script(args: &[String]) -> R<i32> {let ts = dunce::canonicalize(&PathBuf::from(&args[1])).map_err(|e| format!("{}: {e}", args[1]))?;let out = std::env::temp_dir().join(format!("raea-cli-{}.js", std::process::id()));bundle_script(&ts, &out)?;let secs: f64 = flag(args, "--timeout").and_then(|t| t.parse().ok()).unwrap_or(120.0);- let (code, _) = run_bundle(&out, secs)?;+ let (code, _) = run_bundle_to_terminal(&out, secs)?;let _ = std::fs::remove_file(&out);Ok(code)}@@ -351,7 +351,7 @@ pub fn run(args: &[String]) -> R<String> {let out = std::env::temp_dir().join(format!("raea-cli-t{}.js", std::process::id()));bundle_tests(&files, &out, flag(args, "--filter").as_deref(), &extra)?;let secs: f64 = flag(args, "--timeout").and_then(|t| t.parse().ok()).unwrap_or(300.0);- let (code, _) = run_bundle(&out, secs)?;+ let (code, _) = run_bundle_to_terminal(&out, secs)?;let _ = std::fs::remove_file(&out);if code != 0 {return Err(format!("{} test file(s): some failed", files.len()));diff --git a/runtime/bundle/src/fresh.rs b/runtime/bundle/src/fresh.rsindex b92d3be3..d94b053e 100644--- a/runtime/bundle/src/fresh.rs+++ b/runtime/bundle/src/fresh.rs@@ -4,9 +4,12 @@ use super::*;/// resolution on top (raea-bundle's script.rs: the SDK from its source, the test API, raea-runtime-react's node_modules as the/// fallback); its default export, if a function, is called and awaited, then the run ends.pub fn bundle_script(ts: &Path, out: &Path) -> R<()> {- bundle_module(ts, out, "Promise.resolve().then(() => (typeof (M as any).default === \"function\" ? (M as any).default() : undefined)).then(() => call(\"done\", JSON.stringify({ code: 0 })), (e: any) => { call(\"print\", JSON.stringify({ text: \"error: \" + (e && e.stack ? e.stack : String(e)) })); call(\"done\", JSON.stringify({ code: 1 })); });")+ bundle_module(ts, out, SCRIPT_ENTRY)}+/// bundle_script's entry: the answer printed, a throw on stderr with its message (#168)+const SCRIPT_ENTRY: &str = include_str!("script_entry.ts");+/// What a spec's run does (brief.ts, script.ts, taste.ts, a controller: docs/projects.feature PJ0), for bundle_module:/// it prints the module's default export as one line of JSON and ends, or prints the error and exits 1. The reader is/// engine/cli spec.rs.diff --git a/runtime/bundle/src/script_entry.ts b/runtime/bundle/src/script_entry.tsnew file mode 100644index 00000000..f710a960--- /dev/null+++ b/runtime/bundle/src/script_entry.ts@@ -0,0 +1,6 @@+// bundle_script's entry (fresh.rs): the default export called and awaited; what it returns printed (a string as it+// is, anything else as JSON), and a throw printed as its name and message, then its stack, on stderr. A script's answer+// was dropped and a throw printed its stack alone, which on JavaScriptCore is only the frames, without the message (#168).+const show = (v: any): string => { if (typeof v === "string") return v; try { return JSON.stringify(v, null, 2) ?? String(v); } catch { return String(v); } };+const said = (e: any): string => { const head = e && typeof e === "object" && "message" in e ? (e.name || "Error") + ": " + e.message : String(e); const stack = e && e.stack ? String(e.stack) : ""; return stack.startsWith(head) ? stack : stack ? head + "\n" + stack : head; };+Promise.resolve().then(() => (typeof (M as any).default === "function" ? (M as any).default() : undefined)).then((v: any) => { if (v !== undefined) call("print", JSON.stringify({ text: show(v) })); call("done", JSON.stringify({ code: 0 })); }, (e: any) => { call("print", JSON.stringify({ text: "error: " + said(e), err: true })); call("done", JSON.stringify({ code: 1 })); });diff --git a/runtime/calls/src/lib.rs b/runtime/calls/src/lib.rsindex 1e78e18b..d4eb5c8e 100644--- a/runtime/calls/src/lib.rs+++ b/runtime/calls/src/lib.rs@@ -122,6 +122,11 @@ pub static DONE: std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::ne/// Whether print also writes to stdout (the CLI; not an app).pub static ECHO: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true);+/// Whether a script's console goes to the terminal, while ECHO is on: a headless program's (`raea run`, `raea test`,+/// `raea blender run`), whose App has no log to take it, so every console line was dropped (#168). raea-runtime-react's+/// `__raea_log` reads it.+pub static CONSOLE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);+/// What a headless run printed (an app shows it; the CLI also writes it to stdout as it comes).pub static PRINTED: std::sync::Mutex<String> = std::sync::Mutex::new(String::new());@@ -162,10 +167,15 @@ pub fn call(name: &str, v: &Value) -> R<Value> {p.push_str(text);p.push('\n');}+ // `err`: a line for stderr (a script's throw, #168), where its console goes to the terminalif ECHO.load(std::sync::atomic::Ordering::Relaxed) {- let mut o = std::io::stdout().lock();- let _ = writeln!(o, "{text}");- let _ = o.flush();+ if v.get("err").and_then(Value::as_bool) == Some(true) && CONSOLE.load(std::sync::atomic::Ordering::Relaxed) {+ let _ = writeln!(std::io::stderr().lock(), "{text}");+ } else {+ let mut o = std::io::stdout().lock();+ let _ = writeln!(o, "{text}");+ let _ = o.flush();+ }}Ok(Value::Null)}@@ -207,7 +217,7 @@ pub fn register() {const SECTION: &str = "{ polygons: [number, number][][]; area: number; contours: number; bounds: { min: [number, number]; max: [number, number] } }";let calls: &[(&str, &str, &str, &str)] = &[("done", "{ code: number }", "null", "a headless run ends with this exit code"),- ("print", "{ text: string }", "null", "one line of a headless run's output"),+ ("print", "{ text: string; err?: boolean }", "null", "one line of a headless run's output (err: for stderr, on a terminal)"),("blender.post", "{ sid: string; ops: unknown[] }", "{ r: Record<string, unknown>; n: number; err?: { i: number; type: string; msg: string; trace: string } }", "a batch of raea/blender's operations run by the Blender `raea blender run SCRIPT.ts` started (sdk/blender)"),("solid.make", "{ fn: \"box\" | \"rounded_box\" | \"sphere\" | \"cylinder\" | \"cone\" | \"torus\" | \"text3d\"; args: (number | string)[] }", SOLID, "a Manifold solid from a primitive"),("solid.expr", "{ expr: string }", SOLID, "a Manifold solid from an expression (raea-render's mesh shape language)"),diff --git a/runtime/export/src/run.rs b/runtime/export/src/run.rsindex 3c1ad90f..ec26f1de 100644--- a/runtime/export/src/run.rs+++ b/runtime/export/src/run.rs@@ -26,6 +26,16 @@ pub fn run_bundle(bundle: &Path, secs: f64) -> R<(i32, String)> {}}+/// `run_bundle` for a program whose output is the terminal (`raea run`, `raea test`, `raea blender run`): its console+/// goes there too, log and info to stdout, warn and error to stderr (#168). raea check's asks and a spec's read keep+/// theirs out of stdout, which is their answer.+pub fn run_bundle_to_terminal(bundle: &Path, secs: f64) -> R<(i32, String)> {+ let was = raea_runtime_react::native::CONSOLE.swap(true, std::sync::atomic::Ordering::SeqCst);+ let ran = run_bundle(bundle, secs);+ raea_runtime_react::native::CONSOLE.store(was, std::sync::atomic::Ordering::SeqCst);+ ran+}+/// The composition's sound alone, mixed and mastered as a render's is (its <Mix>'s loudness and ceiling through raea-render's/// master row): React is stepped through every frame for its sounds, with no page painted and no video decoded. Live/// play hands this to the mixer, so a timeline sounds as its render does.diff --git a/runtime/react/src/thread.rs b/runtime/react/src/thread.rsindex 8161804e..9ed84c31 100644--- a/runtime/react/src/thread.rs+++ b/runtime/react/src/thread.rs@@ -26,6 +26,22 @@ fn flush(a: &[String]) -> Result<Ret, String> {/// `__raea_log(level, text)`: to Bevy's logfn log(a: &[String]) -> Result<Ret, String> {let text = arg(a, 1);+ // a headless program's console to the terminal, as node's: log and info to stdout, warn and error to stderr (#168)+ let (on, echo) = (native::CONSOLE.load(std::sync::atomic::Ordering::Relaxed), native::ECHO.load(std::sync::atomic::Ordering::Relaxed));+ if on && echo {+ use std::io::Write;+ match arg(a, 0) {+ "1" | "2" => {+ let _ = writeln!(std::io::stderr().lock(), "{text}");+ }+ _ => {+ let mut o = std::io::stdout().lock();+ let _ = writeln!(o, "{text}");+ let _ = o.flush();+ }+ }+ return Ok(Ret::Undefined);+ }match arg(a, 0) {"2" => error!("[js] {text}"),"1" => warn!("[js] {text}"),diff --git a/sdk/raea/src/native-calls.ts b/sdk/raea/src/native-calls.tsindex cb4b6c86..f7da1154 100644--- a/sdk/raea/src/native-calls.ts+++ b/sdk/raea/src/native-calls.ts@@ -220,8 +220,8 @@ export interface NativeCalls {"physics.part": { args: { src: string; nodes: string[]; material?: { missing?: boolean; color?: string; emissive?: string; opacity?: number; roughness?: number; unlit?: boolean } }; answer: { file: string; centre: [number, number, number]; lo: [number, number, number]; hi: [number, number, number]; tris: number } };/** boxes placed by relations (on, against, beside, near, apart, facing, align, clear), what can't hold found */"place.solve": { args: { objects: { id: string; size: [number, number, number]; at?: [number, number, number]; yaw?: number; fixed?: boolean }[]; rules: Record<string, string | number>[]; room?: { min: [number, number]; max: [number, number] } }; answer: { objects: { id: string; at: [number, number, number]; yaw: number; size: [number, number, number] }[]; found: { part: string; check: string; level: string; says: string }[]; errors: number } };- /** one line of a headless run's output */- "print": { args: { text: string }; answer: null };+ /** one line of a headless run's output (err: for stderr, on a terminal) */+ "print": { args: { text: string; err?: boolean }; answer: null };/** the window settings set so far */"raea.window.get": { args: {}; answer: Record<string, unknown> | null };/** the live game's window settings changed (merged over the ones set before); the window's host applies them */