rong_console 0.1.1

Console module for RongJS
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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
use rong::{function::*, *};
use std::cell::RefCell;
use std::collections::HashSet;
use std::fmt;
use std::hash::{DefaultHasher, Hash, Hasher};
use std::io::{self, IsTerminal, Write};

thread_local! {
    static CONSOLE_WRITER: RefCell<Option<Box<dyn ConsoleWriter>>> = RefCell::new(None);
}

#[derive(Debug)]
pub enum LogLevel {
    Verbose,
    Error,
    Warn,
    Info,
    Debug,
}

pub trait ConsoleWriter: Send + Sync + fmt::Debug {
    fn write(&self, level: LogLevel, message: String);
    fn is_tty(&self) -> bool;
}

#[derive(Debug)]
struct DefaultWriter;

impl ConsoleWriter for DefaultWriter {
    fn write(&self, level: LogLevel, message: String) {
        match level {
            LogLevel::Verbose | LogLevel::Info => {
                println!("{}", message);
            }
            LogLevel::Debug => {
                println!("DEBUG: {}", message);
            }
            LogLevel::Error => {
                eprintln!("ERROR: {}", message);
            }
            LogLevel::Warn => {
                eprintln!("WARN: {}", message);
            }
        }
    }

    fn is_tty(&self) -> bool {
        io::stdout().is_terminal()
    }
}

/// Set a custom console writer for the current thread.
pub fn set_writer(writer: Box<dyn ConsoleWriter>) {
    CONSOLE_WRITER.with(|w| {
        *w.borrow_mut() = Some(writer);
    });
}

/// Write a message using the thread-local console writer
fn write_console(level: LogLevel, message: String) {
    CONSOLE_WRITER.with(|w| {
        let mut writer = w.borrow_mut();
        if writer.is_none() {
            *writer = Some(Box::new(DefaultWriter));
        }
        if let Some(writer) = writer.as_ref() {
            writer.write(level, message);
        }
    });
}

/// Check if the console writer is a TTY
fn console_writer_is_tty() -> bool {
    CONSOLE_WRITER.with(|w| {
        let mut writer = w.borrow_mut();
        if writer.is_none() {
            *writer = Some(Box::new(DefaultWriter));
        }
        writer.as_ref().is_some_and(|writer| writer.is_tty())
    })
}

/// Initialize the console module
pub fn init(ctx: &JSContext) -> JSResult<()> {
    let console = JSObject::new(ctx);

    console
        .set("clear", JSFunc::new(ctx, clear)?)?
        .set("log", JSFunc::new(ctx, verbose)?)?
        .set("error", JSFunc::new(ctx, error)?)?
        .set("warn", JSFunc::new(ctx, warn)?)?
        .set("info", JSFunc::new(ctx, info)?)?
        .set("debug", JSFunc::new(ctx, debug)?)?;

    ctx.register_class::<Console>()?;
    ctx.global().set("console", console)?;
    Ok(())
}

fn log_message(level: LogLevel, message: String) {
    write_console(level, message);
}

fn clear() {
    if console_writer_is_tty() {
        // ANSI clear screen sequence
        print!("\x1B[2J\x1B[1;1H");
        // Ensure immediate output flush
        let _ = io::stdout().flush();
    } else {
        // In non-terminal environment, print a newline
        println!();
    }
}

fn verbose(ctx: JSContext, args: Rest<JSValue>) {
    let message = format_args(&ctx, args);
    log_message(LogLevel::Info, message);
}

fn error(ctx: JSContext, args: Rest<JSValue>) {
    let message = format_args(&ctx, args);
    log_message(LogLevel::Error, message);
}

fn warn(ctx: JSContext, args: Rest<JSValue>) {
    let message = format_args(&ctx, args);
    log_message(LogLevel::Warn, message);
}

fn info(ctx: JSContext, args: Rest<JSValue>) {
    let message = format_args(&ctx, args);
    log_message(LogLevel::Info, message);
}

fn debug(ctx: JSContext, args: Rest<JSValue>) {
    let message = format_args(&ctx, args);
    log_message(LogLevel::Debug, message);
}

fn format_args(_ctx: &JSContext, args: Rest<JSValue>) -> String {
    let mut result = String::new();
    format_values_internal(&mut result, args);
    result
}

fn format_values_internal(result: &mut String, args: Rest<JSValue>) {
    let size = args.len();
    let mut iter = args.0.into_iter().enumerate().peekable();

    while let Some((index, arg)) = iter.next() {
        // Handle formatted strings
        if index == 0
            && size > 1
            && let Ok(format_str) = arg.clone().try_into::<String>()
        {
            let mut chars = format_str.chars().peekable();
            while let Some(c) = chars.next() {
                if c == '%' {
                    match chars.next() {
                        Some('s') => {
                            if let Some((_, next_arg)) = iter.next() {
                                if let Ok(str) = next_arg.clone().try_into::<String>() {
                                    result.push_str(&str);
                                } else {
                                    format_raw_inner(result, next_arg, &mut HashSet::default(), 0);
                                }
                            } else {
                                result.push_str("%s");
                            }
                            continue;
                        }
                        Some('d') | Some('i') => {
                            if let Some((_, next_arg)) = iter.next() {
                                if let Ok(num) = next_arg.clone().try_into::<f64>() {
                                    result.push_str(&num.trunc().to_string());
                                } else {
                                    format_raw_inner(result, next_arg, &mut HashSet::default(), 0);
                                }
                            } else {
                                result.push_str("%d");
                            }
                            continue;
                        }
                        Some('f') => {
                            if let Some((_, next_arg)) = iter.next() {
                                if let Ok(num) = next_arg.clone().try_into::<f64>() {
                                    result.push_str(&num.to_string());
                                } else {
                                    format_raw_inner(result, next_arg, &mut HashSet::default(), 0);
                                }
                            } else {
                                result.push_str("%f");
                            }
                            continue;
                        }
                        Some('o') | Some('O') => {
                            if let Some((_, next_arg)) = iter.next() {
                                format_raw_inner(result, next_arg, &mut HashSet::default(), 0);
                            } else {
                                result.push_str("%o");
                            }
                            continue;
                        }
                        Some('%') => {
                            result.push('%');
                            continue;
                        }
                        Some(other) => {
                            result.push('%');
                            result.push(other);
                            continue;
                        }
                        None => {
                            result.push('%');
                            continue;
                        }
                    }
                }
                result.push(c);
            }

            for (_, extra) in iter.by_ref() {
                result.push(' ');
                format_raw_inner(result, extra, &mut HashSet::default(), 0);
            }
            continue;
        }

        // Non-formatted string regular argument
        if index != 0 {
            result.push(' ');
        }

        // handle next arg
        format_raw_inner(result, arg, &mut HashSet::default(), 0);
    }
}

fn format_raw_inner(
    result: &mut String,
    value: JSValue,
    visited: &mut HashSet<usize>,
    depth: usize,
) {
    const MAX_DEPTH: usize = 8;
    const MAX_ARRAY_ITEMS: usize = 100;
    const MAX_OBJECT_KEYS: usize = 100;

    if depth > MAX_DEPTH {
        result.push_str("[Maximum recursion depth exceeded]");
        return;
    }

    match value.type_of() {
        JSValueType::Undefined => result.push_str("undefined"),
        JSValueType::Null => result.push_str("null"),

        JSValueType::Boolean => {
            if let Ok(b) = value.try_into::<bool>() {
                result.push_str(if b { "true" } else { "false" });
            }
        }

        JSValueType::Number => {
            if let Ok(n) = value.try_into::<f64>() {
                result.push_str(&n.to_string());
            }
        }

        JSValueType::BigInt => {
            if let Ok(s) = value.try_into::<String>() {
                result.push_str(&s);
            }
        }

        JSValueType::String => {
            if let Ok(s) = value.try_into::<String>() {
                if depth > 0 {
                    result.push('"');
                    result.push_str(&escape_string(&s));
                    result.push('"');
                } else {
                    result.push_str(&s);
                }
            }
        }

        JSValueType::Date => {
            if let Ok(s) = value.try_into::<String>() {
                result.push_str(&s);
            }
        }

        JSValueType::Object | JSValueType::Array => {
            let obj: JSObject = value.clone().into();
            let hash = default_hash(&value);
            if visited.contains(&hash) {
                result.push_str("[Circular]");
                return;
            }
            visited.insert(hash);

            if let Some(array) = JSArray::from_object(obj.clone()) {
                format_array(result, array, visited, depth, MAX_ARRAY_ITEMS);
            } else {
                format_object(result, obj, visited, depth, MAX_OBJECT_KEYS);
            }
            visited.remove(&hash);
        }

        JSValueType::Function => {
            let obj: JSObject = value.into();
            let mut fn_info = Vec::new();

            if let Ok(name) = obj.get::<_, String>("name") {
                if !name.is_empty() {
                    fn_info.push(format!("Function: {}", name));
                } else {
                    fn_info.push("anonymous".to_string());
                }
            } else {
                fn_info.push("anonymous".to_string());
            }

            if let Ok(length) = obj.get::<_, f64>("length") {
                fn_info.push(format!("length: {}", length as usize));
            }

            result.push('[');
            result.push_str(&fn_info.join(", "));
            result.push(']');
        }

        JSValueType::Symbol => {
            let obj: JSObject = value.into();
            if let Some(symbol) = JSSymbol::from_object(obj) {
                if let Ok(description) = symbol.descripiton() {
                    if !description.is_empty() {
                        result.push_str(&format!("Symbol({})", description));
                    } else {
                        result.push_str("Symbol()");
                    }
                } else {
                    result.push_str("Symbol()");
                }
            } else {
                result.push_str("Symbol()");
            }
        }

        JSValueType::Promise => {
            let obj: JSObject = value.into();
            if let Ok(state) = obj.get::<_, String>("state") {
                result.push_str(&format!("Promise <{}>", state));
            }
        }

        JSValueType::Constructor => {
            let obj: JSObject = value.into();
            if let Ok(name) = obj.get::<_, String>("name")
                && !name.is_empty()
            {
                result.push_str(&format!("[class {}]", name));
                return;
            }

            if let Ok(prototype) = obj.get::<_, JSObject>("prototype")
                && let Ok(constructor_name) = prototype.get::<_, String>("constructor")
                && !constructor_name.is_empty()
            {
                result.push_str(&format!("[class {}]", constructor_name));
            }
        }

        JSValueType::Error | JSValueType::Exception => {
            let obj: JSObject = value.into();
            let mut error_parts = Vec::new();

            if let Ok(name) = obj.get::<_, String>("name") {
                error_parts.push(name);
            } else {
                error_parts.push("Error".to_string());
            }

            if let Ok(message) = obj.get::<_, String>("message")
                && !message.is_empty()
            {
                error_parts.push(message);
            }

            result.push_str(&error_parts.join(": "));

            if depth == 0
                && let Ok(stack) = obj.get::<_, String>("stack")
                && !stack.is_empty()
            {
                result.push('\n');
                result.push_str(&stack);
            }
        }

        JSValueType::ArrayBuffer => {
            let obj: JSObject = value.into();
            format_array_buffer(result, obj);
        }

        JSValueType::Unknown => {
            result.push_str("[Unknown]");
        }
    }
}

fn format_array(
    result: &mut String,
    array: JSArray,
    visited: &mut HashSet<usize>,
    depth: usize,
    max_items: usize,
) {
    let total = array.len() as usize;
    let mut written = 0usize;
    result.push_str("[ ");
    for item in array.iter::<JSValue>().flatten() {
        if written >= max_items {
            break;
        }
        if written > 0 {
            result.push_str(", ");
        }
        format_raw_inner(result, item, visited, depth + 1);
        written += 1;
    }
    if total > written {
        result.push_str(", ... ");
        result.push_str(&(total - written).to_string());
        result.push_str(" more");
    }
    result.push_str(" ]");
}

fn format_object(
    result: &mut String,
    obj: JSObject,
    visited: &mut HashSet<usize>,
    depth: usize,
    max_keys: usize,
) {
    result.push('{');
    let mut first = true;

    if let Ok(entries) = obj.entries() {
        let total = entries.len();
        for (idx, entry) in entries.into_iter().enumerate() {
            if idx >= max_keys {
                break;
            }
            if !first {
                result.push_str(", ");
            }
            first = false;

            if let Ok(key_str) = entry.key().clone().try_into::<String>() {
                if needs_quotes(&key_str) {
                    result.push('"');
                    result.push_str(&escape_string(&key_str));
                    result.push('"');
                } else {
                    result.push_str(&key_str);
                }
                result.push_str(": ");

                format_raw_inner(result, entry.value().clone(), visited, depth + 1);
            }
        }
        if total > max_keys {
            if !first {
                result.push_str(", ");
            }
            result.push_str("... ");
            result.push_str(&(total - max_keys).to_string());
            result.push_str(" more");
        }
    }

    result.push('}');
}

fn format_array_buffer(result: &mut String, obj: JSObject) {
    if let Some(buffer) = JSArrayBuffer::<u8>::from_object(obj.clone()) {
        let len = buffer.len();

        // For small ArrayBuffer, display its content
        if len <= 50 && len > 0 {
            result.push_str("ArrayBuffer { ");
            result.push_str(&format!("byteLength: {}", len));

            // Try to get and display the byte content
            if let Some(bytes) = buffer.as_bytes() {
                result.push_str(", bytes: [");

                for (i, byte) in bytes.iter().enumerate() {
                    if i > 0 {
                        result.push_str(", ");
                    }
                    result.push_str(&format!("0x{:02x}", byte));
                }

                result.push(']');
            }

            result.push_str(" }");
        } else {
            // For large ArrayBuffer, only display the length
            result.push_str(&format!("ArrayBuffer {{ byteLength: {} }}", len));
        }
    }
}

fn needs_quotes(s: &str) -> bool {
    if s.is_empty() {
        return true;
    }

    let first_char = s.chars().next().unwrap();
    if !first_char.is_ascii_alphabetic() && first_char != '_' && first_char != '$' {
        return true;
    }

    !s.chars()
        .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$')
}

fn escape_string(s: &str) -> String {
    let mut result = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            '"' => result.push_str("\\\""),
            '\\' => result.push_str("\\\\"),
            '\n' => result.push_str("\\n"),
            '\r' => result.push_str("\\r"),
            '\t' => result.push_str("\\t"),
            '\x08' => result.push_str("\\b"),
            '\x0c' => result.push_str("\\f"),
            c if c.is_ascii_control() => {
                result.push_str(&format!("\\u{:04x}", c as u32));
            }
            c => result.push(c),
        }
    }
    result
}

#[js_export]
pub struct Console {}

#[js_class]
impl Console {
    #[js_method(constructor)]
    fn new() -> Self {
        Self {}
    }

    #[js_method]
    pub fn log(&self, ctx: JSContext, args: Rest<JSValue>) {
        verbose(ctx, args);
    }

    #[js_method]
    pub fn error(&self, ctx: JSContext, args: Rest<JSValue>) {
        error(ctx, args);
    }

    #[js_method]
    pub fn warn(&self, ctx: JSContext, args: Rest<JSValue>) {
        warn(ctx, args);
    }

    #[js_method]
    pub fn info(&self, ctx: JSContext, args: Rest<JSValue>) {
        info(ctx, args);
    }

    #[js_method]
    pub fn debug(&self, ctx: JSContext, args: Rest<JSValue>) {
        debug(ctx, args);
    }

    #[js_method]
    pub fn clear() {
        clear();
    }
}

#[inline]
pub fn default_hash<T: Hash + ?Sized>(v: &T) -> usize {
    let mut state = DefaultHasher::default();
    v.hash(&mut state);
    state.finish() as usize
}

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

    // Use thread-local buffer to avoid cross-test interleaving when tests run in parallel
    thread_local! {
        static TEST_OUTPUT: std::cell::RefCell<String> = const { std::cell::RefCell::new(String::new()) };
    }

    fn clear_test_output() {
        TEST_OUTPUT.with(|s| s.borrow_mut().clear());
    }

    fn get_test_output() -> String {
        TEST_OUTPUT.with(|s| s.borrow().clone())
    }

    fn append_test_output(message: &str) {
        TEST_OUTPUT.with(|s| {
            let mut buf = s.borrow_mut();
            buf.push_str(message);
            buf.push('\n');
        });
    }

    #[derive(Debug)]
    struct TestConsoleWriter;

    impl ConsoleWriter for TestConsoleWriter {
        fn write(&self, _level: LogLevel, message: String) {
            append_test_output(&message);
        }

        fn is_tty(&self) -> bool {
            false
        }
    }

    #[test]
    fn test_console_log_formatted_string() {
        run(|ctx| {
            clear_test_output();
            // Reset thread-local storage
            CONSOLE_WRITER.with(|w| {
                *w.borrow_mut() = None;
            });
            init(ctx)?;
            set_writer(Box::new(TestConsoleWriter));

            let js_code = r#"console.log("Name: %s, Age: %d", "Alice", 30);"#;
            ctx.eval::<()>(Source::from_bytes(js_code))?;

            let output = get_test_output().trim().to_string();
            assert_eq!(
                output, "Name: Alice, Age: 30",
                "Output should match formatted string"
            );
            Ok(())
        });
    }

    #[test]
    fn test_console_log_unknown_formatter_keeps_literal_and_appends_args() {
        run(|ctx| {
            clear_test_output();
            CONSOLE_WRITER.with(|w| {
                *w.borrow_mut() = None;
            });
            init(ctx)?;
            set_writer(Box::new(TestConsoleWriter));

            let js_code = r#"console.log("Hello %x", 42);"#;
            ctx.eval::<()>(Source::from_bytes(js_code))?;

            let output = get_test_output().trim().to_string();
            assert_eq!(output, "Hello %x 42");
            Ok(())
        });
    }

    #[test]
    fn test_console_log_formatter_fallback_on_type_mismatch() {
        run(|ctx| {
            clear_test_output();
            CONSOLE_WRITER.with(|w| {
                *w.borrow_mut() = None;
            });
            init(ctx)?;
            set_writer(Box::new(TestConsoleWriter));

            // If number formatting fails, fall back to raw formatting for that arg.
            let js_code = r#"console.log("Value=%d", { a: 1 });"#;
            ctx.eval::<()>(Source::from_bytes(js_code))?;

            let output = get_test_output().trim().to_string();
            assert!(output.starts_with("Value="));
            assert!(output.contains("{"));
            Ok(())
        });
    }

    #[test]
    fn test_console_log_circular_reference() {
        run(|ctx| {
            clear_test_output();
            // Reset thread-local storage
            CONSOLE_WRITER.with(|w| {
                *w.borrow_mut() = None;
            });
            init(ctx)?;
            set_writer(Box::new(TestConsoleWriter));

            let js_code = r#"
                // Create an object with circular reference
                const obj = { name: "Circular Object" };
                obj.self = obj;

                console.log("Circular object:", obj);
            "#;
            ctx.eval::<()>(Source::from_bytes(js_code))?;

            let output = get_test_output().trim().to_string();
            assert!(
                output.contains("[Circular]"),
                "Output '{}' should contain circular reference marker",
                output
            );
            Ok(())
        });
    }

    #[test]
    fn test_console_log_max_depth() {
        run(|ctx| {
            clear_test_output();
            // Reset thread-local storage
            CONSOLE_WRITER.with(|w| {
                *w.borrow_mut() = None;
            });
            init(ctx)?;
            set_writer(Box::new(TestConsoleWriter));

            let js_code = r#"
                // Function to create a deeply nested object
                function createDeepObject(depth) {
                    if (depth <= 0) return {};
                    return { child: createDeepObject(depth - 1) };
                }

                // Create an object that exceeds maximum recursion depth
                const deepObj = createDeepObject(15);

                console.log("Deep object:", deepObj);
            "#;
            ctx.eval::<()>(Source::from_bytes(js_code))?;

            let output = get_test_output().trim().to_string();
            assert!(
                output.contains("[Maximum recursion depth exceeded]"),
                "Output '{}' should contain recursion depth warning",
                output
            );
            Ok(())
        });
    }
}