afterburner 0.1.2

Afterburner - JS ~> WASM Sandboxed Execution VM
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
// SPDX-License-Identifier: BUSL-1.1
// Copyright (c) 2026 vertexclique
// Licensed under the Business Source License 1.1.
// Change Date: 4 years after this version's release. Change License: Apache-2.0.

//! Terminal styling + animation for the `burn` CLI.
//!
//! Colors come straight from the afterburner.sh design system - the *sunburst
//! flame* gradient (pink-red → orange → gold) plus the supporting teal / violet
//! / green. Everything degrades gracefully: when `NO_COLOR` is set, the stream
//! isn't a TTY, or `TERM=dumb`, styling and animation are skipped and plain
//! text is emitted, so pipes and CI logs stay clean.

use crossterm::style::{Color, Stylize};
use std::io::{IsTerminal, Write};
use std::sync::Arc;
use std::sync::OnceLock;
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread::JoinHandle;
use std::time::Duration;

// ── brand palette (afterburner.sh) ──────────────────────────────────────────

/// Sunburst gradient start - `rgb(255,46,84)` (`#ff2e54`).
pub const FLAME_RED: Color = Color::Rgb {
    r: 255,
    g: 46,
    b: 84,
};
/// Primary accent - vibrant orange `#ff6118`.
pub const ACCENT: Color = Color::Rgb {
    r: 255,
    g: 97,
    b: 24,
};
/// Sunburst gradient end - gold `#ffcf5e`.
pub const GOLD: Color = Color::Rgb {
    r: 255,
    g: 207,
    b: 94,
};
/// Logo green `#5ec34c` - success.
pub const SUCCESS: Color = Color::Rgb {
    r: 94,
    g: 195,
    b: 76,
};
/// Logo teal `#27c7c7` - values / identifiers.
pub const TEAL: Color = Color::Rgb {
    r: 39,
    g: 199,
    b: 199,
};
/// Ghost gray `#64748d` - muted / secondary text.
pub const MUTED: Color = Color::Rgb {
    r: 100,
    g: 116,
    b: 141,
};

/// The three sunburst stops, for gradient interpolation.
const SUNBURST: [(u8, u8, u8); 3] = [(255, 46, 84), (255, 122, 0), (255, 207, 94)];

/// Whether to emit ANSI styling at all. Cached: `NO_COLOR` off, `FORCE_COLOR`
/// on, `TERM != dumb`, and at least one of stdout/stderr is a TTY.
pub fn colors_enabled() -> bool {
    static ENABLED: OnceLock<bool> = OnceLock::new();
    *ENABLED.get_or_init(|| {
        if std::env::var_os("NO_COLOR").is_some() {
            return false;
        }
        if std::env::var_os("FORCE_COLOR").is_some() {
            return true;
        }
        if matches!(std::env::var("TERM").as_deref(), Ok("dumb")) {
            return false;
        }
        std::io::stdout().is_terminal() || std::io::stderr().is_terminal()
    })
}

pub fn animations_enabled() -> bool {
    colors_enabled() && std::io::stderr().is_terminal()
}

fn paint(s: &str, c: Color) -> String {
    if colors_enabled() {
        s.with(c).to_string()
    } else {
        s.to_string()
    }
}

fn paint_bold(s: &str, c: Color) -> String {
    if colors_enabled() {
        s.with(c).bold().to_string()
    } else {
        s.to_string()
    }
}

// ── semantic text helpers ───────────────────────────────────────────────────

/// Primary accent, bold (headings, brand words).
pub fn accent(s: &str) -> String {
    paint_bold(s, ACCENT)
}
/// A value / identifier (digests, URLs, coordinates).
pub fn value(s: &str) -> String {
    paint(s, TEAL)
}
/// Muted secondary text (labels, hints).
pub fn muted(s: &str) -> String {
    paint(s, MUTED)
}
/// Gold highlight.
pub fn gold(s: &str) -> String {
    paint(s, GOLD)
}

/// `✓ <msg>` - glyph AND message in success green (cargo-style: the whole
/// status line carries color, never a colored glyph next to default text).
/// Pass a PLAIN `msg`: embedding a differently-colored span emits an inner
/// reset that drops the green for the remainder - print such identifiers as
/// separate styled args after the `ok(...)`.
pub fn ok(msg: &str) -> String {
    format!("{} {}", paint_bold("", SUCCESS), paint(msg, SUCCESS))
}
/// `✗ <msg>` - glyph and message in alert red.
pub fn fail(msg: &str) -> String {
    format!("{} {}", paint_bold("", FLAME_RED), paint(msg, FLAME_RED))
}
/// `! <msg>` - glyph and message in gold.
pub fn warn(msg: &str) -> String {
    format!("{} {}", paint_bold("!", GOLD), paint(msg, GOLD))
}
/// A `→` step bullet in accent.
pub fn bullet() -> String {
    paint("", ACCENT)
}

/// The `burn:` error prefix in the brand alert color.
pub fn error_prefix() -> String {
    paint_bold("burn:", FLAME_RED)
}

/// Sanitize an error message for display: never surface the JS engine's name,
/// and collapse a doubled `compile failed:` prefix.
pub fn humanize_error(msg: &str) -> String {
    let mut s = msg.replace("Exception generated by QuickJS", "uncaught exception");
    // The JS/WASM engine names are implementation details users must never see.
    // `rquickjs` first so it does not become "rthe engine".
    for needle in ["rquickjs", "QuickJS", "quickjs", "Wasmtime", "wasmtime"] {
        if s.contains(needle) {
            s = s.replace(needle, "the engine");
        }
    }
    while s.contains("compile failed: compile failed:") {
        s = s.replace("compile failed: compile failed:", "compile failed:");
    }
    s
}

/// Color a REPL prompt for rustyline's `Highlighter`. `None` when styling is
/// off. rustyline measures width on the plain prompt and only *displays* this,
/// so no readline width markers (`\x01`/`\x02`) are needed - using them here is
/// what corrupted cursor positioning.
pub fn highlight_prompt(prompt: &str) -> Option<String> {
    if !colors_enabled() {
        return None;
    }
    Some(prompt.with(ACCENT).bold().to_string())
}

// ── flame gradient ──────────────────────────────────────────────────────────

fn lerp_sunburst(t: f32) -> (u8, u8, u8) {
    let t = t.clamp(0.0, 1.0);
    let (a, b, local) = if t < 0.5 {
        (SUNBURST[0], SUNBURST[1], t / 0.5)
    } else {
        (SUNBURST[1], SUNBURST[2], (t - 0.5) / 0.5)
    };
    let mix = |x: u8, y: u8| (x as f32 + (y as f32 - x as f32) * local).round() as u8;
    (mix(a.0, b.0), mix(a.1, b.1), mix(a.2, b.2))
}

/// Color each character of `s` along the sunburst flame gradient (bold).
pub fn flame(s: &str) -> String {
    if !colors_enabled() {
        return s.to_string();
    }
    let chars: Vec<char> = s.chars().collect();
    let n = chars.len().max(1);
    let mut out = String::new();
    for (i, ch) in chars.iter().enumerate() {
        let t = if n == 1 {
            0.0
        } else {
            i as f32 / (n - 1) as f32
        };
        let (r, g, b) = lerp_sunburst(t);
        out.push_str(
            &ch.to_string()
                .with(Color::Rgb { r, g, b })
                .bold()
                .to_string(),
        );
    }
    out
}

// ── spinner (animation for network ops) ─────────────────────────────────────

const FRAMES: [&str; 10] = ["", "", "", "", "", "", "", "", "", ""];

/// The spinner glyph at frame `i`, shimmered along the flame gradient.
pub fn spinner_frame(i: usize) -> String {
    let frame = FRAMES[i % FRAMES.len()];
    if !colors_enabled() {
        return frame.to_string();
    }
    let (r, g, b) = lerp_sunburst((i % 20) as f32 / 19.0);
    frame.with(Color::Rgb { r, g, b }).bold().to_string()
}

/// A gradient-filled progress bar of `width` cells, `ratio` in `[0,1]`. Filled
/// cells run along the sunburst gradient (shimmered by `phase`); the rest are
/// muted. Degrades to `[##--]` when colors are off.
pub fn flame_bar(ratio: f32, width: usize, phase: f32) -> String {
    let filled = ((ratio.clamp(0.0, 1.0) * width as f32).round() as usize).min(width);
    if !colors_enabled() {
        let mut s = String::with_capacity(width + 2);
        s.push('[');
        for i in 0..width {
            s.push(if i < filled { '#' } else { '-' });
        }
        s.push(']');
        return s;
    }
    let mut s = String::from("[");
    for i in 0..width {
        if i < filled {
            let t = ((i as f32 / width.max(1) as f32) + phase).rem_euclid(1.0);
            let (r, g, b) = lerp_sunburst(t);
            s.push_str(&"".with(Color::Rgb { r, g, b }).to_string());
        } else {
            s.push_str(&"".with(MUTED).to_string());
        }
    }
    s.push(']');
    s
}

/// A background-thread spinner. Animates on an interactive stderr; a no-op
/// otherwise. Cleared on drop.
pub struct Spinner {
    stop: Arc<AtomicBool>,
    handle: Option<JoinHandle<()>>,
}

impl Spinner {
    fn start(msg: &str) -> Spinner {
        if !animations_enabled() {
            return Spinner {
                stop: Arc::new(AtomicBool::new(true)),
                handle: None,
            };
        }
        let stop = Arc::new(AtomicBool::new(false));
        let flag = stop.clone();
        let msg = msg.to_string();
        let handle = std::thread::spawn(move || {
            use crossterm::{cursor, execute, terminal};
            let mut err = std::io::stderr();
            let _ = execute!(err, cursor::Hide);
            let mut i = 0usize;
            while !flag.load(Ordering::Relaxed) {
                let frame = FRAMES[i % FRAMES.len()];
                // Shimmer the glyph color along the flame gradient.
                let (r, g, b) = lerp_sunburst((i % 20) as f32 / 19.0);
                let _ = execute!(
                    err,
                    cursor::MoveToColumn(0),
                    terminal::Clear(terminal::ClearType::CurrentLine)
                );
                let _ = write!(
                    err,
                    "{} {}",
                    frame.with(Color::Rgb { r, g, b }).bold(),
                    msg.as_str().with(MUTED)
                );
                let _ = err.flush();
                i += 1;
                std::thread::sleep(Duration::from_millis(80));
            }
            let _ = execute!(
                err,
                cursor::MoveToColumn(0),
                terminal::Clear(terminal::ClearType::CurrentLine),
                cursor::Show
            );
            let _ = err.flush();
        });
        Spinner {
            stop,
            handle: Some(handle),
        }
    }
}

impl Drop for Spinner {
    fn drop(&mut self) {
        self.stop.store(true, Ordering::Relaxed);
        if let Some(h) = self.handle.take() {
            let _ = h.join();
        }
    }
}

/// Run `f` while showing an animated `msg` spinner; returns `f`'s value and
/// clears the spinner first, so the caller's own output prints cleanly.
pub fn spin<T>(msg: &str, f: impl FnOnce() -> T) -> T {
    let sp = Spinner::start(msg);
    let out = f();
    drop(sp);
    out
}

// ── REPL banner (animated) ──────────────────────────────────────────────────

const WORDMARK: [&str; 5] = [
    " _                      ",
    "| |__  _   _ _ __ _ __   ",
    "| '_ \\| | | | '__| '_ \\  ",
    "| |_) | |_| | |  | | | |  ",
    "|_.__/ \\__,_|_|  |_| |_|  ",
];

fn flame_phase(line: &str, phase: f32, width: usize) -> String {
    let mut out = String::new();
    for (col, ch) in line.chars().enumerate() {
        if ch == ' ' {
            out.push(' ');
            continue;
        }
        let t = ((col as f32 / width.max(1) as f32) + phase).rem_euclid(1.0);
        let (r, g, b) = lerp_sunburst(t);
        out.push_str(
            &ch.to_string()
                .with(Color::Rgb { r, g, b })
                .bold()
                .to_string(),
        );
    }
    out
}

fn animate_wordmark() {
    use crossterm::{cursor, execute};
    let mut err = std::io::stderr();
    let width = WORDMARK
        .iter()
        .map(|l| l.chars().count())
        .max()
        .unwrap_or(1);
    let _ = execute!(err, cursor::Hide);
    for f in 0..16 {
        if f > 0 {
            let _ = execute!(err, cursor::MoveUp(WORDMARK.len() as u16));
        }
        let phase = -(f as f32) * 0.07; // sweep the gradient rightward
        for line in WORDMARK {
            let _ = execute!(err, cursor::MoveToColumn(0));
            let _ = writeln!(err, "  {}", flame_phase(line, phase, width));
        }
        let _ = err.flush();
        std::thread::sleep(Duration::from_millis(45));
    }
    let _ = execute!(err, cursor::Show);
}

fn banner_subtitle(version: &str, tail: &str) {
    eprintln!();
    eprintln!(
        "  {} {}",
        accent("Afterburner"),
        muted("· sandboxed JavaScript runtime")
    );
    eprintln!("  {}", muted(&format!("v{version}{tail}")));
    eprintln!();
}

/// Animated flame banner for top-level `burn --help`.
pub fn banner(version: &str) {
    if !animations_enabled() {
        return;
    }
    animate_wordmark();
    banner_subtitle(version, "");
}

/// REPL welcome banner - animated wordmark on a terminal, one plain line otherwise.
pub fn repl_banner(version: &str) {
    if !animations_enabled() {
        eprintln!("burn {version}: Afterburner sandbox REPL. :help for commands, :exit to quit.");
        return;
    }
    animate_wordmark();
    banner_subtitle(version, " · :help for commands · :exit to quit");
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn humanize_strips_engine_name_and_double_prefix() {
        assert_eq!(
            humanize_error("Exception generated by QuickJS"),
            "uncaught exception"
        );
        assert_eq!(
            humanize_error("compile failed: compile failed: SyntaxError: x"),
            "compile failed: SyntaxError: x"
        );
        assert!(!humanize_error("internal QuickJS detail").contains("QuickJS"));
        assert!(!humanize_error("rquickjs panic").contains("quickjs"));
        assert!(
            !humanize_error("wasmtime trap at 0x0")
                .to_lowercase()
                .contains("wasmtime")
        );
        assert_eq!(
            humanize_error("ReferenceError: a is not defined"),
            "ReferenceError: a is not defined"
        );
    }
}