bun_runtime 0.5.4

Bao runtime integration — JS engine + Bun API + event loop
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
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
// @trace REQ-ENG-007
use ::std::ptr::NonNull;
use bun_core::ZBox;

use mozjs::conversions::jsstr_to_string;
use mozjs::jsapi::*;
use mozjs::jsval::{BooleanValue, Int32Value, JSVal, ObjectValue, UndefinedValue};
use mozjs::rooted;
use mozjs::rust::wrappers2 as w2;

use crate::require::cache_builtin;

pub fn install(cx: &mut mozjs::context::JSContext) {
    rooted!(&in(cx) let tty_obj = unsafe { w2::JS_NewPlainObject(cx) });
    if tty_obj.get().is_null() {
        return;
    }

    unsafe {
        w2::JS_DefineFunction(
            cx,
            tty_obj.handle(),
            c"isatty".as_ptr(),
            Some(tty_isatty),
            1,
            0,
        );

        // ReadStream constructor
        let rs_fn = JS_NewFunction(
            cx.raw_cx(),
            Some(tty_read_stream_ctor),
            1,
            JSFUN_CONSTRUCTOR,
            c"ReadStream".as_ptr(),
        );
        if !rs_fn.is_null() {
            let rs_obj = JS_GetFunctionObject(rs_fn);
            rooted!(&in(cx) let rs_val = ObjectValue(rs_obj));
            JS_DefineProperty(
                cx.raw_cx(),
                tty_obj.handle().into(),
                c"ReadStream".as_ptr(),
                rs_val.handle().into(),
                JSPROP_ENUMERATE as u32,
            );
        }

        // WriteStream constructor
        let ws_fn = JS_NewFunction(
            cx.raw_cx(),
            Some(tty_write_stream_ctor),
            1,
            JSFUN_CONSTRUCTOR,
            c"WriteStream".as_ptr(),
        );
        if !ws_fn.is_null() {
            let ws_obj = JS_GetFunctionObject(ws_fn);
            rooted!(&in(cx) let ws_val = ObjectValue(ws_obj));
            JS_DefineProperty(
                cx.raw_cx(),
                tty_obj.handle().into(),
                c"WriteStream".as_ptr(),
                ws_val.handle().into(),
                JSPROP_ENUMERATE as u32,
            );
        }
    }

    cache_builtin(cx, "tty", tty_obj.get());
}

#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn tty_isatty(_cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    let fd = if argc > 0 {
        let v = *args.get(0).ptr;
        if v.is_int32() { v.to_int32() } else { -1 }
    } else {
        -1
    };
    // windows: the console-handle probe (GetStdHandle + GetConsoleMode) is
    // the platform isatty — Node's libuv `uv_guess_handle` classifies by the
    // OS handle type, not the CRT fd table, whose FDEV bit marks UNATTACHED
    // std fds as devices (a piped/closed stdin then disagrees with the
    // console truth). One detection source per platform: this is the same
    // probe `console_is_tty` uses for the WriteStream/ReadStream isTTY.
    #[cfg(unix)]
    let result = if fd >= 0 { libc::isatty(fd) } else { 0 };
    #[cfg(windows)]
    let result = if fd >= 0 && console_is_tty(fd) { 1 } else { 0 };
    args.rval().set(BooleanValue(result == 1));
    true
}

#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn tty_read_stream_ctor(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    let fd = if argc > 0 {
        let v = *args.get(0).ptr;
        if v.is_int32() { v.to_int32() } else { 0 }
    } else {
        0
    };

    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;

    rooted!(&in(cx_ref) let obj = w2::JS_NewPlainObject(cx_ref));
    if obj.get().is_null() {
        args.rval().set(UndefinedValue());
        return false;
    }

    // fd
    rooted!(&in(cx_ref) let fv = Int32Value(fd));
    JS_DefineProperty(
        cx,
        obj.handle().into(),
        c"fd".as_ptr(),
        fv.handle().into(),
        JSPROP_ENUMERATE as u32,
    );

    // isTTY — same platform probe as tty.isatty (console-handle semantics on
    // windows; CRT isatty on unix).
    #[cfg(unix)]
    let rs_is_tty = libc::isatty(fd) == 1;
    #[cfg(windows)]
    let rs_is_tty = fd >= 0 && console_is_tty(fd);
    rooted!(&in(cx_ref) let tv = BooleanValue(rs_is_tty));
    JS_DefineProperty(
        cx,
        obj.handle().into(),
        c"isTTY".as_ptr(),
        tv.handle().into(),
        JSPROP_ENUMERATE as u32,
    );

    // isRaw
    rooted!(&in(cx_ref) let rv = BooleanValue(false));
    JS_DefineProperty(
        cx,
        obj.handle().into(),
        c"isRaw".as_ptr(),
        rv.handle().into(),
        JSPROP_ENUMERATE as u32,
    );

    // readable
    rooted!(&in(cx_ref) let readable_v = BooleanValue(true));
    JS_DefineProperty(
        cx,
        obj.handle().into(),
        c"readable".as_ptr(),
        readable_v.handle().into(),
        JSPROP_ENUMERATE as u32,
    );

    w2::JS_DefineFunction(
        cx_ref,
        obj.handle(),
        c"setRawMode".as_ptr(),
        Some(tty_set_raw_mode),
        1,
        JSPROP_ENUMERATE as u32,
    );
    w2::JS_DefineFunction(cx_ref, obj.handle(), c"ref".as_ptr(), Some(tty_ref), 0, 0);
    w2::JS_DefineFunction(
        cx_ref,
        obj.handle(),
        c"unref".as_ptr(),
        Some(tty_unref),
        0,
        0,
    );
    w2::JS_DefineFunction(
        cx_ref,
        obj.handle(),
        c"on".as_ptr(),
        Some(crate::node_events::ee_on),
        1,
        0,
    );
    w2::JS_DefineFunction(
        cx_ref,
        obj.handle(),
        c"emit".as_ptr(),
        Some(crate::node_events::ee_emit),
        1,
        0,
    );
    w2::JS_DefineFunction(
        cx_ref,
        obj.handle(),
        c"resume".as_ptr(),
        Some(tty_resume),
        0,
        0,
    );
    w2::JS_DefineFunction(
        cx_ref,
        obj.handle(),
        c"pause".as_ptr(),
        Some(tty_pause),
        0,
        0,
    );
    w2::JS_DefineFunction(
        cx_ref,
        obj.handle(),
        c"destroy".as_ptr(),
        Some(tty_destroy),
        0,
        0,
    );

    args.rval().set(ObjectValue(obj.get()));
    true
}

#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn tty_write_stream_ctor(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    let fd = if argc > 0 {
        let v = *args.get(0).ptr;
        if v.is_int32() { v.to_int32() } else { 1 }
    } else {
        1
    };

    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;

    rooted!(&in(cx_ref) let obj = w2::JS_NewPlainObject(cx_ref));
    if obj.get().is_null() {
        args.rval().set(UndefinedValue());
        return false;
    }

    // fd
    rooted!(&in(cx_ref) let fv = Int32Value(fd));
    JS_DefineProperty(
        cx,
        obj.handle().into(),
        c"fd".as_ptr(),
        fv.handle().into(),
        JSPROP_ENUMERATE as u32,
    );

    #[cfg(unix)]
    let is_tty = libc::isatty(fd) == 1;
    #[cfg(windows)]
    let is_tty = console_is_tty(fd);

    // isTTY
    rooted!(&in(cx_ref) let tv = BooleanValue(is_tty));
    JS_DefineProperty(
        cx,
        obj.handle().into(),
        c"isTTY".as_ptr(),
        tv.handle().into(),
        JSPROP_ENUMERATE as u32,
    );

    // columns / rows from ioctl TIOCGWINSZ (unix) / the visible console
    // window extents (windows).
    #[cfg(unix)]
    let mut ws: libc::winsize = libc::winsize {
        ws_row: 0,
        ws_col: 0,
        ws_xpixel: 0,
        ws_ypixel: 0,
    };
    #[cfg(unix)]
    let has_size = is_tty && libc::ioctl(fd, libc::TIOCGWINSZ, &mut ws) == 0;
    #[cfg(unix)]
    let ws_col = ws.ws_col as i32;
    #[cfg(unix)]
    let ws_row = ws.ws_row as i32;
    #[cfg(windows)]
    let (has_size, ws_col, ws_row) = match (is_tty, console_window_size(fd)) {
        (true, Some((cols, rows))) => (true, cols, rows),
        _ => (false, 0, 0),
    };
    if has_size {
        rooted!(&in(cx_ref) let cols = Int32Value(ws_col));
        JS_DefineProperty(
            cx,
            obj.handle().into(),
            c"columns".as_ptr(),
            cols.handle().into(),
            JSPROP_ENUMERATE as u32,
        );
        rooted!(&in(cx_ref) let rows = Int32Value(ws_row));
        JS_DefineProperty(
            cx,
            obj.handle().into(),
            c"rows".as_ptr(),
            rows.handle().into(),
            JSPROP_ENUMERATE as u32,
        );
        w2::JS_DefineFunction(
            cx_ref,
            obj.handle(),
            c"getWindowSize".as_ptr(),
            Some(tty_get_window_size),
            0,
            JSPROP_ENUMERATE as u32,
        );
    } else {
        let undef = UndefinedValue();
        rooted!(&in(cx_ref) let cols = undef);
        JS_DefineProperty(
            cx,
            obj.handle().into(),
            c"columns".as_ptr(),
            cols.handle().into(),
            JSPROP_ENUMERATE as u32,
        );
        rooted!(&in(cx_ref) let rows = undef);
        JS_DefineProperty(
            cx,
            obj.handle().into(),
            c"rows".as_ptr(),
            rows.handle().into(),
            JSPROP_ENUMERATE as u32,
        );
    }

    w2::JS_DefineFunction(
        cx_ref,
        obj.handle(),
        c"clearLine".as_ptr(),
        Some(tty_clear_line),
        2,
        0,
    );
    w2::JS_DefineFunction(
        cx_ref,
        obj.handle(),
        c"clearScreenDown".as_ptr(),
        Some(tty_clear_screen_down),
        1,
        0,
    );
    w2::JS_DefineFunction(
        cx_ref,
        obj.handle(),
        c"cursorTo".as_ptr(),
        Some(tty_cursor_to),
        3,
        0,
    );
    w2::JS_DefineFunction(
        cx_ref,
        obj.handle(),
        c"moveCursor".as_ptr(),
        Some(tty_move_cursor),
        3,
        0,
    );
    w2::JS_DefineFunction(
        cx_ref,
        obj.handle(),
        c"write".as_ptr(),
        Some(tty_write_stream_write),
        1,
        JSPROP_ENUMERATE as u32,
    );

    args.rval().set(ObjectValue(obj.get()));
    true
}

#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn tty_set_raw_mode(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;

    rooted!(&in(cx_ref) let this = args.thisv().to_object());

    // Get fd from this object
    let mut fd_val = UndefinedValue();
    JS_GetProperty(
        cx,
        this.handle().into(),
        c"fd".as_ptr(),
        MutableHandle::<JSVal> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut fd_val,
        },
    );
    let fd = if fd_val.is_int32() {
        fd_val.to_int32()
    } else {
        -1
    };

    let raw_flag = if argc > 0 {
        let v = *args.get(0).ptr;
        v.to_boolean()
    } else {
        true
    };

    if fd < 0 {
        JS_ReportErrorUTF8(cx, c"setRawMode: invalid fd".as_ptr());
        return false;
    }

    #[cfg(unix)]
    {
        let mut term: libc::termios = ::std::mem::zeroed();
        if libc::tcgetattr(fd, &mut term) != 0 {
            JS_ReportErrorUTF8(cx, c"setRawMode: tcgetattr failed".as_ptr());
            return false;
        }

        if raw_flag {
            libc::cfmakeraw(&mut term);
        } else {
            libc::cfmakeraw(&mut term);
            term.c_iflag |= libc::ICRNL;
            term.c_oflag |= libc::OPOST | libc::ONLCR;
            term.c_lflag |= libc::ICANON | libc::ECHO | libc::ECHOE | libc::ECHOK | libc::ISIG;
        }

        if libc::tcsetattr(fd, libc::TCSANOW, &term) != 0 {
            JS_ReportErrorUTF8(cx, c"setRawMode: tcsetattr failed".as_ptr());
            return false;
        }
    }

    // windows: the console has no termios — Get/SetConsoleMode is the
    // platform equivalent of the cfmakeraw/tcsetattr pair above.
    #[cfg(windows)]
    if !console_set_raw_mode(fd, raw_flag) {
        JS_ReportErrorUTF8(cx, c"setRawMode: SetConsoleMode failed".as_ptr());
        return false;
    }

    // Update isRaw on the object
    rooted!(&in(cx_ref) let rv = BooleanValue(raw_flag));
    JS_DefineProperty(
        cx,
        this.handle().into(),
        c"isRaw".as_ptr(),
        rv.handle().into(),
        JSPROP_ENUMERATE as u32,
    );

    args.rval().set(ObjectValue(this.get()));
    true
}

#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn tty_get_window_size(cx: *mut JSContext, _argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, _argc);
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;

    rooted!(&in(cx_ref) let this = args.thisv().to_object());

    let mut fd_val = UndefinedValue();
    JS_GetProperty(
        cx,
        this.handle().into(),
        c"fd".as_ptr(),
        MutableHandle::<JSVal> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut fd_val,
        },
    );
    let fd = if fd_val.is_int32() {
        fd_val.to_int32()
    } else {
        -1
    };

    #[cfg(unix)]
    let mut ws: libc::winsize = libc::winsize {
        ws_row: 0,
        ws_col: 0,
        ws_xpixel: 0,
        ws_ypixel: 0,
    };
    #[cfg(unix)]
    let ws_col = ws.ws_col as i32;
    #[cfg(unix)]
    let ws_row = ws.ws_row as i32;
    #[cfg(windows)]
    let (ws_col, ws_row) = console_window_size(fd).unwrap_or((0, 0));
    let has_size = fd >= 0 && ws_col > 0;
    if has_size {
        rooted!(&in(cx_ref) let arr = w2::NewArrayObject1(cx_ref, 2));
        if !arr.get().is_null() {
            rooted!(&in(cx_ref) let cv = Int32Value(ws_col));
            JS_DefineElement(
                cx,
                arr.handle().into(),
                0,
                cv.handle().into(),
                JSPROP_ENUMERATE as u32,
            );
            rooted!(&in(cx_ref) let rv = Int32Value(ws_row));
            JS_DefineElement(
                cx,
                arr.handle().into(),
                1,
                rv.handle().into(),
                JSPROP_ENUMERATE as u32,
            );
            args.rval().set(ObjectValue(arr.get()));
            return true;
        }
    }
    args.rval().set(UndefinedValue());
    true
}

#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn tty_write_stream_write(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;

    rooted!(&in(cx_ref) let this = args.thisv().to_object());

    let mut fd_val = UndefinedValue();
    JS_GetProperty(
        cx,
        this.handle().into(),
        c"fd".as_ptr(),
        MutableHandle::<JSVal> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut fd_val,
        },
    );
    let fd = if fd_val.is_int32() {
        fd_val.to_int32()
    } else {
        1
    };

    if argc > 0 {
        let v = *args.get(0).ptr;
        if v.is_string() {
            let s = jsstr_to_string(&mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx)), NonNull::new_unchecked(v.to_string()));
            let bytes = s.as_bytes();
            libc::write(
                fd,
                bytes.as_ptr() as *const ::std::os::raw::c_void,
                bytes.len() as _,
            );
        }
    }
    args.rval().set(BooleanValue(true));
    true
}

/// ref() — no-op for TTY streams (Node.js compatible: stream.ref() returns this)
unsafe extern "C" fn tty_ref(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    let this = args.thisv();
    if this.is_object() {
        let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
        let cx_ref = &mut wrapped_cx;
        rooted!(&in(cx_ref) let obj = this.to_object());
        args.rval().set(ObjectValue(obj.get()));
    } else {
        args.rval().set(UndefinedValue());
    }
    true
}

/// unref() — no-op for TTY streams (Node.js compatible: stream.unref() returns this)
unsafe extern "C" fn tty_unref(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    let this = args.thisv();
    if this.is_object() {
        let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
        let cx_ref = &mut wrapped_cx;
        rooted!(&in(cx_ref) let obj = this.to_object());
        args.rval().set(ObjectValue(obj.get()));
    } else {
        args.rval().set(UndefinedValue());
    }
    true
}

/// resume() — mark stream as readable and emit 'resume' event
unsafe extern "C" fn tty_resume(cx: *mut JSContext, _argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, _argc);
    let this = args.thisv();
    if !this.is_object() {
        args.rval().set(UndefinedValue());
        return true;
    }
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;
    rooted!(&in(cx_ref) let this_obj = this.to_object());
    rooted!(&in(cx_ref) let readable_v = BooleanValue(true));
    JS_DefineProperty(
        cx,
        this_obj.handle().into(),
        c"readable".as_ptr(),
        readable_v.handle().into(),
        JSPROP_ENUMERATE as u32,
    );
    args.rval().set(ObjectValue(this_obj.get()));
    true
}

/// pause() — mark stream as not readable
unsafe extern "C" fn tty_pause(cx: *mut JSContext, _argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, _argc);
    let this = args.thisv();
    if !this.is_object() {
        args.rval().set(UndefinedValue());
        return true;
    }
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;
    rooted!(&in(cx_ref) let this_obj = this.to_object());
    rooted!(&in(cx_ref) let readable_v = BooleanValue(false));
    JS_DefineProperty(
        cx,
        this_obj.handle().into(),
        c"readable".as_ptr(),
        readable_v.handle().into(),
        JSPROP_ENUMERATE as u32,
    );
    args.rval().set(ObjectValue(this_obj.get()));
    true
}

/// destroy() — mark stream as destroyed
unsafe extern "C" fn tty_destroy(cx: *mut JSContext, _argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, _argc);
    let this = args.thisv();
    if !this.is_object() {
        args.rval().set(UndefinedValue());
        return true;
    }
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;
    rooted!(&in(cx_ref) let this_obj = this.to_object());
    rooted!(&in(cx_ref) let destroyed_v = BooleanValue(true));
    JS_DefineProperty(
        cx,
        this_obj.handle().into(),
        c"destroyed".as_ptr(),
        destroyed_v.handle().into(),
        JSPROP_ENUMERATE as u32,
    );
    args.rval().set(ObjectValue(this_obj.get()));
    true
}

/// clearLine(dir) — write ANSI escape to clear line. dir: -1=left, 1=right, 0=entire line
unsafe extern "C" fn tty_clear_line(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    let this = args.thisv();
    if !this.is_object() {
        args.rval().set(UndefinedValue());
        return true;
    }
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;
    rooted!(&in(cx_ref) let this_obj = this.to_object());

    let dir = if argc > 0 {
        (*args.get(0).ptr).to_int32()
    } else {
        0
    };
    let esc = match dir {
        -1 => "\x1b[1K",
        1 => "\x1b[0K",
        _ => "\x1b[2K",
    };

    let mut fd_val = UndefinedValue();
    JS_GetProperty(
        cx,
        this_obj.handle().into(),
        c"fd".as_ptr(),
        MutableHandle::<JSVal> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut fd_val,
        },
    );
    let fd = if fd_val.is_int32() {
        fd_val.to_int32()
    } else {
        1
    };

    libc::write(fd, esc.as_ptr() as *const ::std::os::raw::c_void, esc.len() as _);
    args.rval().set(ObjectValue(this_obj.get()));
    true
}

/// clearScreenDown() — write ANSI escape to clear from cursor to end of screen
unsafe extern "C" fn tty_clear_screen_down(cx: *mut JSContext, _argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, _argc);
    let this = args.thisv();
    if !this.is_object() {
        args.rval().set(UndefinedValue());
        return true;
    }
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;
    rooted!(&in(cx_ref) let this_obj = this.to_object());

    let esc = "\x1b[J";
    let mut fd_val = UndefinedValue();
    JS_GetProperty(
        cx,
        this_obj.handle().into(),
        c"fd".as_ptr(),
        MutableHandle::<JSVal> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut fd_val,
        },
    );
    let fd = if fd_val.is_int32() {
        fd_val.to_int32()
    } else {
        1
    };

    libc::write(fd, esc.as_ptr() as *const ::std::os::raw::c_void, esc.len() as _);
    args.rval().set(ObjectValue(this_obj.get()));
    true
}

/// cursorTo(x, y) — write ANSI escape to move cursor
unsafe extern "C" fn tty_cursor_to(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    let this = args.thisv();
    if !this.is_object() {
        args.rval().set(UndefinedValue());
        return true;
    }
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;
    rooted!(&in(cx_ref) let this_obj = this.to_object());

    let col = if argc > 0 {
        (*args.get(0).ptr).to_int32().max(0) as u32
    } else {
        0
    };
    let row = if argc > 1 {
        (*args.get(1).ptr).to_int32().max(0) as u32
    } else {
        0
    };
    let esc = format!("\x1b[{};{}H", row + 1, col + 1);

    let mut fd_val = UndefinedValue();
    JS_GetProperty(
        cx,
        this_obj.handle().into(),
        c"fd".as_ptr(),
        MutableHandle::<JSVal> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut fd_val,
        },
    );
    let fd = if fd_val.is_int32() {
        fd_val.to_int32()
    } else {
        1
    };

    libc::write(fd, esc.as_ptr() as *const ::std::os::raw::c_void, esc.len() as _);
    args.rval().set(ObjectValue(this_obj.get()));
    true
}

/// moveCursor(dx, dy) — write ANSI escape to move cursor relative
unsafe extern "C" fn tty_move_cursor(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    let this = args.thisv();
    if !this.is_object() {
        args.rval().set(UndefinedValue());
        return true;
    }
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;
    rooted!(&in(cx_ref) let this_obj = this.to_object());

    let dx = if argc > 0 {
        (*args.get(0).ptr).to_int32()
    } else {
        0
    };
    let dy = if argc > 1 {
        (*args.get(1).ptr).to_int32()
    } else {
        0
    };

    let mut esc = String::new();
    if dy > 0 {
        esc.push_str(&format!("\x1b[{}A", dy));
    }
    if dy < 0 {
        esc.push_str(&format!("\x1b[{}B", -dy));
    }
    if dx > 0 {
        esc.push_str(&format!("\x1b[{}C", dx));
    }
    if dx < 0 {
        esc.push_str(&format!("\x1b[{}D", -dx));
    }

    if !esc.is_empty() {
        let mut fd_val = UndefinedValue();
        JS_GetProperty(
            cx,
            this_obj.handle().into(),
            c"fd".as_ptr(),
            MutableHandle::<JSVal> {
                _phantom_0: ::std::marker::PhantomData,
                ptr: &mut fd_val,
            },
        );
        let fd = if fd_val.is_int32() {
            fd_val.to_int32()
        } else {
            1
        };
        libc::write(fd, esc.as_ptr() as *const ::std::os::raw::c_void, esc.len() as _);
    }
    args.rval().set(ObjectValue(this_obj.get()));
    true
}

// ─── windows console helpers (win-cross, #18) ──────────────────────────────
// CRT fd → console handle (0=stdin, 1=stdout, 2=stderr; other fds have no
// console mapping and fall back to stdout — matching Node's windows tty,
// which only ever attaches to the three standard streams).
#[cfg(windows)]
fn console_handle_for_fd(fd: core::ffi::c_int) -> bun_windows_sys::HANDLE {
    let std_id = match fd {
        0 => bun_windows_sys::STD_INPUT_HANDLE,
        2 => bun_windows_sys::STD_ERROR_HANDLE,
        _ => bun_windows_sys::STD_OUTPUT_HANDLE,
    };
    // SAFETY: GetStdHandle has no preconditions (returns INVALID_HANDLE_VALUE
    // for an unknown slot).
    unsafe { bun_windows_sys::kernel32::GetStdHandle(std_id) }
}

/// windows `is_tty`: a console handle answers GetConsoleMode; files/pipes
/// fail it.
#[cfg(windows)]
fn console_is_tty(fd: core::ffi::c_int) -> bool {
    let h = console_handle_for_fd(fd);
    let mut mode: bun_windows_sys::DWORD = 0;
    // SAFETY: out-param is a stack DWORD; GetConsoleMode has no other
    // preconditions.
    unsafe { bun_windows_sys::kernel32::GetConsoleMode(h, &mut mode) != 0 }
}

/// windows winsize: the visible console window extents (Node parity:
/// columns = Right-Left+1, rows = Bottom-Top+1). Falls back to the
/// COLUMNS/LINES env vars (Node's documented resolution order) for the
/// pseudo-console shapes where the std handle answers GetConsoleMode but not
/// GetConsoleScreenBufferInfo (ConPTY output side) — reporting isTTY with no
/// columns/rows is the un-TTY inconsistency the deep tty probe checks.
#[cfg(windows)]
fn console_window_size(fd: core::ffi::c_int) -> Option<(i32, i32)> {
    console_window_size_console(fd).or_else(console_window_size_env)
}

#[cfg(windows)]
fn console_window_size_console(fd: core::ffi::c_int) -> Option<(i32, i32)> {
    let h = console_handle_for_fd(fd);
    let mut csbi: bun_windows_sys::CONSOLE_SCREEN_BUFFER_INFO =
        unsafe { ::std::mem::zeroed() };
    // SAFETY: out-param is a zeroed POD struct we own.
    let ok = unsafe {
        bun_windows_sys::kernel32::GetConsoleScreenBufferInfo(h, &mut csbi)
    } != 0;
    if !ok {
        return None;
    }
    let cols = (csbi.srWindow.Right - csbi.srWindow.Left + 1) as i32;
    let rows = (csbi.srWindow.Bottom - csbi.srWindow.Top + 1) as i32;
    Some((cols, rows))
}

/// COLUMNS/LINES env fallback (both must parse positive; Node treats a
/// partial pair as absent rather than inventing a zero dimension).
#[cfg(windows)]
fn console_window_size_env() -> Option<(i32, i32)> {
    let cols: i32 = ::std::env::var("COLUMNS").ok()?.trim().parse().ok()?;
    let rows: i32 = ::std::env::var("LINES").ok()?.trim().parse().ok()?;
    if cols > 0 && rows > 0 {
        Some((cols, rows))
    } else {
        None
    }
}

/// windows raw mode: clear the line/echo/processed input flags for raw,
/// restore them for cooked (Node `setRawMode` windows semantics — the
/// console has no termios; Get/SetConsoleMode is the platform equivalent).
#[cfg(windows)]
fn console_set_raw_mode(fd: core::ffi::c_int, raw: bool) -> bool {
    const ENABLE_PROCESSED_INPUT: bun_windows_sys::DWORD = 0x0001;
    const ENABLE_LINE_INPUT: bun_windows_sys::DWORD = 0x0002;
    const ENABLE_ECHO_INPUT: bun_windows_sys::DWORD = 0x0004;
    let h = console_handle_for_fd(fd);
    let mut mode: bun_windows_sys::DWORD = 0;
    // SAFETY: out-param is a stack DWORD.
    if unsafe { bun_windows_sys::kernel32::GetConsoleMode(h, &mut mode) } == 0 {
        return false;
    }
    let line_flags = ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT;
    if raw {
        mode &= !line_flags;
    } else {
        mode |= line_flags;
    }
    // SAFETY: SetConsoleMode on a console handle we just queried.
    unsafe { bun_windows_sys::kernel32::SetConsoleMode(h, mode) != 0 }
}