bun_runtime 0.1.2

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
// @trace REQ-ENG-007
use ::std::ptr::NonNull;
use bun_core::ZBox;

use mozjs::jsapi::*;
use mozjs::jsval::{BooleanValue, JSVal, ObjectValue, StringValue, 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 rl_mod = unsafe { w2::JS_NewPlainObject(cx) });
    if rl_mod.get().is_null() {
        return;
    }

    unsafe {
        w2::JS_DefineFunction(
            cx,
            rl_mod.handle(),
            c"createInterface".as_ptr(),
            Some(rl_create_interface),
            1,
            JSPROP_ENUMERATE as u32,
        );
        w2::JS_DefineFunction(
            cx,
            rl_mod.handle(),
            c"clearLine".as_ptr(),
            Some(rl_clear_line),
            1,
            JSPROP_ENUMERATE as u32,
        );
        w2::JS_DefineFunction(
            cx,
            rl_mod.handle(),
            c"clearScreenDown".as_ptr(),
            Some(rl_clear_screen),
            1,
            JSPROP_ENUMERATE as u32,
        );
        w2::JS_DefineFunction(
            cx,
            rl_mod.handle(),
            c"cursorTo".as_ptr(),
            Some(rl_cursor_to),
            2,
            JSPROP_ENUMERATE as u32,
        );
        w2::JS_DefineFunction(
            cx,
            rl_mod.handle(),
            c"moveCursor".as_ptr(),
            Some(rl_move_cursor),
            3,
            JSPROP_ENUMERATE as u32,
        );
        w2::JS_DefineFunction(
            cx,
            rl_mod.handle(),
            c"emitKeypressEvents".as_ptr(),
            Some(rl_emit_keypress),
            1,
            JSPROP_ENUMERATE as u32,
        );

        // Create the readline.promises namespace with a Promise-based
        // createInterface and an Interface class that supports .question()
        // returning a Promise (matching Bun's readline.promises shape).
        rooted!(&in(cx) let promises_obj = w2::JS_NewPlainObject(cx));
        if !promises_obj.get().is_null() {
            w2::JS_DefineFunction(
                cx,
                promises_obj.handle(),
                c"createInterface".as_ptr(),
                Some(rl_promises_create_interface),
                1,
                JSPROP_ENUMERATE as u32,
            );
            w2::JS_DefineFunction(
                cx,
                promises_obj.handle(),
                c"Interface".as_ptr(),
                Some(rl_promises_interface_ctor),
                1,
                JSPROP_ENUMERATE as u32,
            );

            rooted!(&in(cx) let prom_val = ObjectValue(promises_obj.get()));
            JS_DefineProperty(
                cx.raw_cx(),
                rl_mod.handle().into(),
                c"promises".as_ptr(),
                prom_val.handle().into(),
                JSPROP_ENUMERATE as u32,
            );
        }
    }

    cache_builtin(cx, "readline", rl_mod.get());

    // Cache the promises sub-object as a standalone module so
    // require("readline/promises") works via node_subpath_aliases.
    let rl_cached = crate::gc_store::gc_store_get(unsafe { cx.raw_cx() }, "builtin:readline");
    if let Some(rl_obj) = rl_cached {
        if !rl_obj.is_null() {
            unsafe {
                let raw_cx = cx.raw_cx();
                rooted!(&in(cx) let rl_root = rl_obj);
                let mut prom_val = UndefinedValue();
                JS_GetProperty(
                    raw_cx,
                    rl_root.handle().into(),
                    c"promises".as_ptr(),
                    MutableHandle::<Value> {
                        _phantom_0: ::std::marker::PhantomData,
                        ptr: &mut prom_val,
                    },
                );
                if prom_val.is_object() {
                    cache_builtin(cx, "readline/promises", prom_val.to_object());
                }
            }
        }
    }
}

#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn rl_create_interface(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    let wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    rooted!(&in(wrapped_cx) let iface = mozjs_sys::jsapi::JS_NewPlainObject(cx));
    if iface.get().is_null() {
        args.rval().set(UndefinedValue());
        return true;
    }

    let mut input_val = UndefinedValue();
    if argc > 0 && (*args.get(0).ptr).is_object() {
        let opts = (*args.get(0).ptr).to_object();
        rooted!(&in(wrapped_cx) let opts_root = opts);
        JS_GetProperty(
            cx,
            opts_root.handle().into(),
            c"input".as_ptr(),
            MutableHandle::<Value> {
                _phantom_0: ::std::marker::PhantomData,
                ptr: &mut input_val,
            },
        );
    }
    rooted!(&in(wrapped_cx) let input_val_root = input_val);
    JS_DefineProperty(
        cx,
        iface.handle().into(),
        c"input".as_ptr(),
        input_val_root.handle().into(),
        JSPROP_ENUMERATE as u32,
    );

    rooted!(&in(wrapped_cx) let closed_val = mozjs::jsval::BooleanValue(false));
    JS_DefineProperty(
        cx,
        iface.handle().into(),
        c"closed".as_ptr(),
        closed_val.handle().into(),
        JSPROP_ENUMERATE as u32,
    );

    rooted!(&in(wrapped_cx) let paused_val = mozjs::jsval::BooleanValue(false));
    JS_DefineProperty(
        cx,
        iface.handle().into(),
        c"paused".as_ptr(),
        paused_val.handle().into(),
        JSPROP_ENUMERATE as u32,
    );

    // on — delegate to EventEmitter
    JS_DefineFunction(
        cx,
        iface.handle().into(),
        c"on".as_ptr(),
        Some(crate::node_events::ee_on),
        2,
        JSPROP_ENUMERATE as u32,
    );
    // close — mark as closed
    JS_DefineFunction(
        cx,
        iface.handle().into(),
        c"close".as_ptr(),
        Some(rl_close),
        0,
        JSPROP_ENUMERATE as u32,
    );
    // pause/resume — toggle paused flag
    JS_DefineFunction(
        cx,
        iface.handle().into(),
        c"pause".as_ptr(),
        Some(rl_pause),
        0,
        JSPROP_ENUMERATE as u32,
    );
    JS_DefineFunction(
        cx,
        iface.handle().into(),
        c"resume".as_ptr(),
        Some(rl_resume),
        0,
        JSPROP_ENUMERATE as u32,
    );
    // write/prompt/setPrompt — return this for chaining. question is NOT in
    // this list: it has real stdin-reading semantics (see rl_question).
    for name in &["write", "prompt", "setPrompt"] {
        let c_name = ZBox::from_bytes(name.as_bytes());
        JS_DefineFunction(
            cx,
            iface.handle().into(),
            c_name.as_ptr(),
            Some(rl_chain),
            0,
            JSPROP_ENUMERATE as u32,
        );
    }
    // question(query, callback) — writes the prompt, reads one real line
    // from stdin, invokes callback(answer).
    JS_DefineFunction(
        cx,
        iface.handle().into(),
        c"question".as_ptr(),
        Some(rl_question),
        2,
        JSPROP_ENUMERATE as u32,
    );

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

#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn rl_close(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 wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    rooted!(&in(wrapped_cx) let this_obj = this.to_object());
    rooted!(&in(wrapped_cx) let closed_v = BooleanValue(true));
    JS_DefineProperty(
        cx,
        this_obj.handle().into(),
        c"closed".as_ptr(),
        closed_v.handle().into(),
        JSPROP_ENUMERATE as u32,
    );
    args.rval().set(ObjectValue(this_obj.get()));
    true
}

#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn rl_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 wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    rooted!(&in(wrapped_cx) let this_obj = this.to_object());
    rooted!(&in(wrapped_cx) let paused_v = BooleanValue(true));
    JS_DefineProperty(
        cx,
        this_obj.handle().into(),
        c"paused".as_ptr(),
        paused_v.handle().into(),
        JSPROP_ENUMERATE as u32,
    );
    args.rval().set(ObjectValue(this_obj.get()));
    true
}

#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn rl_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 wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    rooted!(&in(wrapped_cx) let this_obj = this.to_object());
    rooted!(&in(wrapped_cx) let paused_v = BooleanValue(false));
    JS_DefineProperty(
        cx,
        this_obj.handle().into(),
        c"paused".as_ptr(),
        paused_v.handle().into(),
        JSPROP_ENUMERATE as u32,
    );
    args.rval().set(ObjectValue(this_obj.get()));
    true
}

/// Read one line (up to and including `\n`) from a raw file descriptor.
/// Returns the line without the trailing `\n`/`\r\n`, `None` on EOF before
/// any byte was read, or `Err` on a read error.
///
/// Byte-wise reads on purpose: wrapping fd 0 in a `File` would close the fd
/// on drop, and a line of interactive input is far below syscall overhead
/// thresholds.
fn read_line_from_fd(fd: i32) -> ::std::result::Result<Option<String>, ::std::io::Error> {
    let mut out: Vec<u8> = Vec::new();
    let mut byte = [0u8; 1];
    loop {
        // SAFETY: plain read(2) on a valid fd; buffer is a valid 1-byte ptr.
        let n = unsafe { libc::read(fd, byte.as_mut_ptr() as *mut libc::c_void, 1) };
        if n < 0 {
            return Err(::std::io::Error::last_os_error());
        }
        if n == 0 {
            // EOF — no data at all means "stdin closed", a partial line
            // without trailing newline is still returned as an answer.
            return Ok(if out.is_empty() {
                None
            } else {
                Some(trim_line_ending(out))
            });
        }
        if byte[0] == b'\n' {
            return Ok(Some(trim_line_ending(out)));
        }
        out.push(byte[0]);
    }
}

/// Strip a single trailing `\r` (CRLF input), if present.
fn trim_line_ending(mut line: Vec<u8>) -> String {
    if line.last() == Some(&b'\r') {
        line.pop();
    }
    String::from_utf8(line).unwrap_or_default()
}

/// Write the `question()` prompt (args[`idx`], when a string) to stdout
/// without a trailing newline. Prompt display is best-effort: a closed
/// stdout must not prevent reading the answer.
fn print_question_prompt(cx: *mut JSContext, args: &CallArgs, idx: u32) {
    if idx >= args.argc_ {
        return;
    }
    // SAFETY: reading an argv slot handed to us by SpiderMonkey; no GC can
    // run between the read and the string conversion.
    let v = unsafe { *args.get(idx).ptr };
    if !v.is_string() {
        return;
    }
    // SAFETY: v is a JS string value on a live cx.
    let s = unsafe { crate::js_to_rust_string(cx, v) };
    if s.is_empty() {
        return;
    }
    use ::std::io::Write;
    let mut out = ::std::io::stdout();
    let _ = out.write_all(s.as_bytes());
    let _ = out.flush();
}

/// readline Interface .question(query, callback) — writes the prompt, reads
/// one real line from stdin, then invokes `callback(answer)`.
///
/// Fails closed: EOF or a read error throws instead of fabricating an empty
/// answer (silent-fake eradication group D — this previously resolved
/// with `''` via a no-op chain method).
#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn rl_question(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);

    if argc < 2 || !(*args.get(1).ptr).is_object() {
        JS_ReportErrorUTF8(
            cx,
            c"readline.question(query, callback): callback must be a function".as_ptr(),
        );
        return false;
    }

    print_question_prompt(cx, &args, 0);

    match read_line_from_fd(0) {
        Ok(Some(line)) => {
            let wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
            rooted!(&in(wrapped_cx) let callback = (*args.get(1).ptr).to_object());
            let js_str = JS_NewStringCopyN(
                cx,
                line.as_ptr() as *const libc::c_char,
                line.len(),
            );
            if js_str.is_null() {
                JS_ReportErrorUTF8(cx, c"readline.question: failed to allocate answer string".as_ptr());
                return false;
            }
            rooted!(&in(wrapped_cx) let str_val = StringValue(&*js_str));
            let elems = [str_val.get()];
            let call_args = HandleValueArray {
                length_: 1,
                elements_: elems.as_ptr(),
            };
            rooted!(&in(wrapped_cx) let cb_val = ObjectValue(callback.get()));
            rooted!(&in(wrapped_cx) let global = CurrentGlobalOrNull(cx));
            rooted!(&in(wrapped_cx) let mut call_rval = UndefinedValue());
            if !JS_CallFunctionValue(
                cx,
                global.handle().into(),
                cb_val.handle().into(),
                &call_args,
                call_rval.handle_mut().into(),
            ) {
                return false;
            }
            let this = args.thisv();
            if this.is_object() {
                args.rval().set(*this.ptr);
            } else {
                args.rval().set(UndefinedValue());
            }
            true
        }
        Ok(None) => {
            JS_ReportErrorUTF8(
                cx,
                c"readline.question: stdin closed before an answer was read (EOF)".as_ptr(),
            );
            false
        }
        Err(e) => {
            let msg = format!("readline.question: failed to read from stdin: {}", e);
            if let Ok(c_msg) = ::std::ffi::CString::new(msg) {
                JS_ReportErrorUTF8(cx, c"%s".as_ptr(), c_msg.as_ptr());
            }
            false
        }
    }
}

#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn rl_chain(_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 wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(_cx));
        rooted!(&in(wrapped_cx) let this_obj = this.to_object());
        args.rval().set(ObjectValue(this_obj.get()));
    } else {
        args.rval().set(UndefinedValue());
    }
    true
}

#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn rl_clear_line(_cx: *mut JSContext, _argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, _argc);
    args.rval().set(mozjs::jsval::BooleanValue(true));
    true
}

#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn rl_clear_screen(_cx: *mut JSContext, _argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, _argc);
    args.rval().set(mozjs::jsval::BooleanValue(true));
    true
}

#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn rl_cursor_to(_cx: *mut JSContext, _argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, _argc);
    args.rval().set(mozjs::jsval::BooleanValue(true));
    true
}

#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn rl_move_cursor(_cx: *mut JSContext, _argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, _argc);
    args.rval().set(mozjs::jsval::BooleanValue(true));
    true
}

#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn rl_emit_keypress(_cx: *mut JSContext, _argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, _argc);
    args.rval().set(UndefinedValue());
    true
}

/// readline.promises.createInterface — returns the Interface synchronously;
/// its question() returns a Promise (see rl_promises_question).
#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn rl_promises_create_interface(
    cx: *mut JSContext,
    argc: u32,
    vp: *mut JSVal,
) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    let wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));

    // Create an Interface object the same way rl_create_interface does
    rooted!(&in(wrapped_cx) let iface = mozjs_sys::jsapi::JS_NewPlainObject(cx));
    if iface.get().is_null() {
        args.rval().set(UndefinedValue());
        return true;
    }

    let mut input_val = UndefinedValue();
    if argc > 0 && (*args.get(0).ptr).is_object() {
        let opts = (*args.get(0).ptr).to_object();
        rooted!(&in(wrapped_cx) let opts_root = opts);
        JS_GetProperty(
            cx,
            opts_root.handle().into(),
            c"input".as_ptr(),
            MutableHandle::<Value> {
                _phantom_0: ::std::marker::PhantomData,
                ptr: &mut input_val,
            },
        );
    }
    rooted!(&in(wrapped_cx) let input_val_root = input_val);
    JS_DefineProperty(
        cx,
        iface.handle().into(),
        c"input".as_ptr(),
        input_val_root.handle().into(),
        JSPROP_ENUMERATE as u32,
    );

    rooted!(&in(wrapped_cx) let closed_val = mozjs::jsval::BooleanValue(false));
    JS_DefineProperty(
        cx,
        iface.handle().into(),
        c"closed".as_ptr(),
        closed_val.handle().into(),
        JSPROP_ENUMERATE as u32,
    );

    rooted!(&in(wrapped_cx) let paused_val = mozjs::jsval::BooleanValue(false));
    JS_DefineProperty(
        cx,
        iface.handle().into(),
        c"paused".as_ptr(),
        paused_val.handle().into(),
        JSPROP_ENUMERATE as u32,
    );

    JS_DefineFunction(
        cx,
        iface.handle().into(),
        c"on".as_ptr(),
        Some(crate::node_events::ee_on),
        2,
        JSPROP_ENUMERATE as u32,
    );
    JS_DefineFunction(
        cx,
        iface.handle().into(),
        c"close".as_ptr(),
        Some(rl_close),
        0,
        JSPROP_ENUMERATE as u32,
    );
    JS_DefineFunction(
        cx,
        iface.handle().into(),
        c"pause".as_ptr(),
        Some(rl_pause),
        0,
        JSPROP_ENUMERATE as u32,
    );
    JS_DefineFunction(
        cx,
        iface.handle().into(),
        c"resume".as_ptr(),
        Some(rl_resume),
        0,
        JSPROP_ENUMERATE as u32,
    );

    // question() returns a Promise (readline/promises spec)
    JS_DefineFunction(
        cx,
        iface.handle().into(),
        c"question".as_ptr(),
        Some(rl_promises_question),
        1,
        JSPROP_ENUMERATE as u32,
    );

    for name in &["write", "prompt", "setPrompt"] {
        let c_name = ZBox::from_bytes(name.as_bytes());
        JS_DefineFunction(
            cx,
            iface.handle().into(),
            c_name.as_ptr(),
            Some(rl_chain),
            0,
            JSPROP_ENUMERATE as u32,
        );
    }

    // Return the Interface synchronously (node:readline/promises semantics:
    // createInterface() yields the Interface directly — only question()
    // returns a Promise). The previous Promise.resolve(iface) wrapper broke
    // the standard `const rl = createInterface(...); rl.question(...)` shape.
    args.rval().set(ObjectValue(iface.get()));
    true
}

/// readline.promises.Interface — constructor for the promises Interface class.
/// Same as rl_promises_create_interface but callable as `new Interface(options)`.
#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn rl_promises_interface_ctor(
    cx: *mut JSContext,
    argc: u32,
    vp: *mut JSVal,
) -> bool {
    // Delegate to rl_promises_create_interface which creates an Interface
    // with question() returning Promise.
    rl_promises_create_interface(cx, argc, vp)
}

/// readline/promises Interface .question() — writes the prompt, reads one
/// real line from stdin, returns a Promise resolved with the answer string
/// (or rejected on EOF/read error — never a fabricated empty answer).
///
/// Silent-fake eradication group D: this previously resolved `''`
/// immediately without reading anything.
#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn rl_promises_question(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);

    print_question_prompt(cx, &args, 0);

    // Read the real answer, then wrap it in Promise.resolve / Promise.reject
    // via the same eval'd-thunk pattern used by rl_promises_create_interface.
    let (thunk_src, answer) = match read_line_from_fd(0) {
        Ok(Some(line)) => ("(function(v) { return Promise.resolve(v); })", Ok(line)),
        Ok(None) => (
            "(function(m) { return Promise.reject(new Error(m)); })",
            Err("readline question(): stdin closed before an answer was read (EOF)".to_string()),
        ),
        Err(e) => (
            "(function(m) { return Promise.reject(new Error(m)); })",
            Err(format!("readline question(): failed to read from stdin: {}", e)),
        ),
    };

    let wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let opts = mozjs::glue::NewCompileOptions(cx, c"<rl_question>".as_ptr(), 1);
    if opts.is_null() {
        JS_ReportErrorUTF8(cx, c"readline question(): failed to create compile options".as_ptr());
        return false;
    }
    let mut thunk = UndefinedValue();
    let ok = mozjs_sys::jsapi::JS::Evaluate2(
        cx,
        opts,
        &mut mozjs::rust::transform_str_to_source_text(thunk_src),
        MutableHandle::<Value> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut thunk,
        },
    );
    libc::free(opts as *mut _);
    if !ok || !thunk.is_object() {
        JS_ReportErrorUTF8(cx, c"readline question(): failed to build Promise wrapper".as_ptr());
        return false;
    }

    rooted!(&in(wrapped_cx) let thunk_obj = thunk.to_object());
    let payload = match &answer {
        Ok(line) => {
            let js_str = JS_NewStringCopyN(cx, line.as_ptr() as *const libc::c_char, line.len());
            if js_str.is_null() {
                JS_ReportErrorUTF8(
                    cx,
                    c"readline question(): failed to allocate answer string".as_ptr(),
                );
                return false;
            }
            StringValue(&*js_str)
        }
        Err(msg) => match ::std::ffi::CString::new(msg.as_str()) {
            Ok(c_msg) => {
                let js_str = JS_NewStringCopyN(cx, c_msg.as_ptr(), msg.len());
                if !js_str.is_null() {
                    StringValue(&*js_str)
                } else {
                    UndefinedValue()
                }
            }
            Err(_) => UndefinedValue(),
        },
    };
    rooted!(&in(wrapped_cx) let payload_root = payload);
    let elems = [payload_root.get()];
    let call_args = HandleValueArray {
        length_: 1,
        elements_: elems.as_ptr(),
    };
    rooted!(&in(wrapped_cx) let thunk_val = ObjectValue(thunk_obj.get()));
    rooted!(&in(wrapped_cx) let global = CurrentGlobalOrNull(cx));
    rooted!(&in(wrapped_cx) let mut call_rval = UndefinedValue());
    if !JS_CallFunctionValue(
        cx,
        global.handle().into(),
        thunk_val.handle().into(),
        &call_args,
        call_rval.handle_mut().into(),
    ) {
        return false;
    }
    args.rval().set(call_rval.get());
    true
}