1use crate::host::{is_callable, with_host, JsObj};
27use fusevm::Value;
28use indexmap::IndexMap;
29use std::collections::{HashMap, VecDeque};
30
31pub const METHODS: &[&str] = &[
32 "createInterface",
33 "clearLine",
34 "clearScreenDown",
35 "cursorTo",
36 "moveCursor",
37 "emitKeypressEvents",
38];
39
40pub const INTERFACE_METHODS: &[&str] = &[
43 "question",
44 "write",
45 "close",
46 "pause",
47 "resume",
48 "prompt",
49 "setPrompt",
50 "getPrompt",
51 "on",
52 "once",
53 "addListener",
54 "prependListener",
55 "removeListener",
56 "off",
57 "removeAllListeners",
58 "@@asyncIterator",
59];
60
61pub const PROMISES_METHODS: &[&str] = &["createInterface"];
64
65pub fn call(method: &str, args: &[Value]) -> Option<Result<Value, String>> {
66 if method.starts_with("@@") {
67 return internal_call(method, args);
68 }
69 Some(match method {
70 "createInterface" => Ok(create_interface(args, false)),
71 "cursorTo" => {
75 let x = super::arg_num(args, 1);
76 let y = args.get(2).filter(|v| !matches!(v, Value::Undef));
77 let seq = match y {
78 Some(yv) => format!(
79 "\x1b[{};{}H",
80 with_host(|h| h.to_number(yv)) as i64 + 1,
81 x as i64 + 1
82 ),
83 None => format!("\x1b[{}G", x as i64 + 1),
84 };
85 write_stdout(&seq);
86 Ok(Value::Bool(true))
87 }
88 "moveCursor" => {
89 let dx = super::arg_num(args, 1) as i64;
90 let dy = super::arg_num(args, 2) as i64;
91 let mut seq = String::new();
92 if dx > 0 {
93 seq.push_str(&format!("\x1b[{dx}C"));
94 } else if dx < 0 {
95 seq.push_str(&format!("\x1b[{}D", -dx));
96 }
97 if dy > 0 {
98 seq.push_str(&format!("\x1b[{dy}B"));
99 } else if dy < 0 {
100 seq.push_str(&format!("\x1b[{}A", -dy));
101 }
102 write_stdout(&seq);
103 Ok(Value::Bool(true))
104 }
105 "clearLine" => {
106 let dir = super::arg_num(args, 1);
107 let seq = if dir < 0.0 {
109 "\x1b[1K"
110 } else if dir > 0.0 {
111 "\x1b[0K"
112 } else {
113 "\x1b[2K"
114 };
115 write_stdout(seq);
116 Ok(Value::Bool(true))
117 }
118 "clearScreenDown" => {
119 write_stdout("\x1b[0J");
120 Ok(Value::Bool(true))
121 }
122 "emitKeypressEvents" => Ok(Value::Undef),
127 _ => return None,
128 })
129}
130
131pub fn construct(args: &[Value]) -> Result<Value, String> {
135 Ok(create_interface(args, false))
136}
137
138pub fn constant(name: &str) -> Option<Value> {
142 match name {
143 "Interface" => Some(with_host(|h| h.alloc(JsObj::Builtin("Interface".into())))),
144 _ => None,
145 }
146}
147
148pub fn promises_call(method: &str, args: &[Value]) -> Option<Result<Value, String>> {
151 match method {
152 "createInterface" => Some(Ok(create_interface(args, true))),
153 _ => None,
154 }
155}
156
157fn create_interface(args: &[Value], promises: bool) -> Value {
158 let id = NEXT_ID.with(|n| {
159 let id = n.get();
160 n.set(id + 1);
161 id
162 });
163 let (input, output) = match args.first() {
165 Some(o) if opt_prop(o, "input").is_some() => (
166 opt_prop(o, "input").unwrap_or(Value::Undef),
167 opt_prop(o, "output").unwrap_or(Value::Undef),
168 ),
169 _ => (
170 args.first().cloned().unwrap_or(Value::Undef),
171 args.get(1).cloned().unwrap_or(Value::Undef),
172 ),
173 };
174 let terminal = match args.first().and_then(|o| opt_prop(o, "terminal")) {
176 Some(t) if !matches!(t, Value::Undef) => with_host(|h| h.truthy(&t)),
177 _ => {
178 matches!(output, Value::Obj(_))
179 && crate::builtins::get_property(&output, "isTTY")
180 .map(|v| with_host(|h| h.truthy(&v)))
181 .unwrap_or(false)
182 }
183 };
184 let iface = with_host(|h| {
185 let listeners = h.new_object(IndexMap::new());
186 let prompt = h.new_str("> ");
187 let mut m = IndexMap::new();
188 m.insert("@@native".into(), h.new_str("Interface"));
189 m.insert("@@input".into(), input.clone());
190 m.insert("@@output".into(), output.clone());
191 m.insert(
192 "@@terminal".into(),
193 h.new_str(if terminal { "1" } else { "0" }),
194 );
195 m.insert("line".into(), h.new_str(""));
197 m.insert("output".into(), output);
198 m.insert("input".into(), input.clone());
199 m.insert("terminal".into(), Value::Bool(terminal));
200 m.insert("@@prompt".into(), prompt);
201 m.insert("@@listeners".into(), listeners);
202 m.insert("@@rlid".into(), Value::Float(id as f64));
203 if promises {
204 let flag = h.new_str("1");
205 m.insert("@@promises".into(), flag);
206 }
207 h.new_object(m)
208 });
209 if matches!(input, Value::Obj(_)) && !is_stdin(&input) {
210 attach_stream(&iface, &input);
211 }
212 iface
213}
214
215pub fn instance_call(recv: &Value, method: &str, args: Vec<Value>) -> Result<Value, String> {
217 match method {
218 "question" => {
221 let query = with_host(|h| args.first().map(|v| h.str_of(v)).unwrap_or_default());
222 write_output(recv, &query);
223 if with_state(recv, |s| s.flowing) {
226 if read_hidden(recv, "@@promises") == "1" {
227 let (promise, id) = with_host(|h| {
228 let p = h.new_promise();
229 let id = h.promise_id(&p).unwrap_or(0);
230 (p, id)
231 });
232 with_state(recv, |s| s.question = Some(QuestionReply::Promise(id)));
233 return Ok(promise);
234 }
235 let cb = args
236 .iter()
237 .rev()
238 .find(|v| with_host(|h| is_callable(h, v)))
239 .cloned();
240 if let Some(cb) = cb {
241 with_state(recv, |s| s.question = Some(QuestionReply::Callback(cb)));
242 }
243 return Ok(Value::Undef);
244 }
245 let line = read_line();
246 if read_hidden(recv, "@@promises") == "1" {
250 let line_val = with_host(|h| h.new_str(line));
251 return crate::builtins::promise_resolve_pub(line_val);
252 }
253 let cb = args
258 .iter()
259 .rev()
260 .find(|v| with_host(|h| is_callable(h, v)))
261 .cloned();
262 if let Some(cb) = cb {
263 let line_val = with_host(|h| h.new_str(line));
264 crate::host::invoke(&cb, vec![line_val], None)?;
265 }
266 Ok(Value::Undef)
267 }
268 "write" => {
272 let data = with_host(|h| args.first().map(|v| h.str_of(v)).unwrap_or_default());
273 if read_hidden(recv, "@@terminal") == "1" {
274 write_output(recv, &data);
275 } else {
276 on_data(recv, data.as_bytes())?;
277 }
278 Ok(Value::Undef)
279 }
280 "prompt" => {
281 let p = read_hidden(recv, "@@prompt");
282 write_output(recv, &p);
283 Ok(Value::Undef)
284 }
285 "setPrompt" => {
286 let p = with_host(|h| args.first().map(|v| h.str_of(v)).unwrap_or_default());
287 with_host(|h| {
288 let pv = h.new_str(p);
289 if let Some(JsObj::Object(m)) = h.get_mut(recv) {
290 m.insert("@@prompt".into(), pv);
291 }
292 });
293 Ok(Value::Undef)
294 }
295 "getPrompt" => {
299 let prompt = read_hidden(recv, "@@prompt");
300 Ok(with_host(|h| h.new_str(prompt)))
301 }
302 "on" | "once" | "addListener" | "prependListener" => {
305 if let (Some(ev), Some(cb)) = (args.first(), args.get(1)) {
306 let event = with_host(|h| h.str_of(ev));
307 store_listener(
308 recv,
309 &event,
310 cb.clone(),
311 method == "once",
312 method == "prependListener",
313 );
314 if event == "line" || event == "close" {
315 ensure_flowing(recv);
316 }
317 }
318 Ok(recv.clone())
319 }
320 "removeListener" | "off" => {
321 if let (Some(ev), Some(cb)) = (args.first(), args.get(1)) {
322 let event = with_host(|h| h.str_of(ev));
323 remove_listener(recv, &event, cb);
324 }
325 Ok(recv.clone())
326 }
327 "removeAllListeners" => {
328 let event = args
329 .first()
330 .filter(|v| !matches!(v, Value::Undef))
331 .map(|v| with_host(|h| h.str_of(v)));
332 clear_listeners(recv, event.as_deref());
333 Ok(recv.clone())
334 }
335 "close" => {
336 close(recv)?;
337 Ok(Value::Undef)
338 }
339 "@@asyncIterator" => Ok(async_iterator(recv)),
340 "pause" | "resume" => Ok(recv.clone()),
343 _ => Err(crate::host::type_error(&format!(
344 "{method} is not a function"
345 ))),
346 }
347}
348
349fn read_hidden(recv: &Value, key: &str) -> String {
351 with_host(|h| match h.get(recv) {
352 Some(JsObj::Object(p)) => p.get(key).map(|v| h.str_of(v)).unwrap_or_default(),
353 _ => String::new(),
354 })
355}
356
357fn listeners_obj(recv: &Value) -> Option<Value> {
359 opt_prop(recv, "@@listeners")
360}
361
362fn store_listener(recv: &Value, event: &str, cb: Value, once: bool, prepend: bool) {
365 let Some(listeners) = listeners_obj(recv) else {
366 return;
367 };
368 with_host(|h| {
369 let entry = h.new_array(vec![cb, Value::Bool(once)]);
370 let arr = match h.get(&listeners) {
371 Some(JsObj::Object(p)) => p.get(event).cloned(),
372 _ => None,
373 };
374 let arr = arr.filter(|a| matches!(h.get(a), Some(JsObj::Array(_))));
375 match arr {
376 Some(a) => {
377 if let Some(JsObj::Array(items)) = h.get_mut(&a) {
378 if prepend {
379 items.insert(0, entry);
380 } else {
381 items.push(entry);
382 }
383 }
384 }
385 None => {
386 let a = h.new_array(vec![entry]);
387 if let Some(JsObj::Object(p)) = h.get_mut(&listeners) {
388 p.insert(event.to_string(), a);
389 }
390 }
391 }
392 });
393}
394
395fn listener_entries(recv: &Value, event: &str) -> Vec<(Value, bool)> {
397 let Some(listeners) = listeners_obj(recv) else {
398 return Vec::new();
399 };
400 with_host(|h| {
401 let arr = match h.get(&listeners) {
402 Some(JsObj::Object(p)) => p.get(event).cloned(),
403 _ => None,
404 };
405 let Some(Some(JsObj::Array(items))) = arr.map(|a| h.get(&a).cloned()) else {
406 return Vec::new();
407 };
408 items
409 .iter()
410 .filter_map(|e| match h.get(e) {
411 Some(JsObj::Array(pair)) if pair.len() == 2 => {
412 Some((pair[0].clone(), h.truthy(&pair[1])))
413 }
414 _ => None,
415 })
416 .collect()
417 })
418}
419
420fn remove_listener(recv: &Value, event: &str, cb: &Value) {
422 let Some(listeners) = listeners_obj(recv) else {
423 return;
424 };
425 with_host(|h| {
426 let arr = match h.get(&listeners) {
427 Some(JsObj::Object(p)) => p.get(event).cloned(),
428 _ => None,
429 };
430 let Some(arr) = arr else { return };
431 let pos = match h.get(&arr) {
432 Some(JsObj::Array(items)) => items.iter().position(|e| match h.get(e) {
433 Some(JsObj::Array(pair)) => pair.first().is_some_and(|f| h.strict_eq(f, cb)),
434 _ => false,
435 }),
436 _ => None,
437 };
438 if let (Some(i), Some(JsObj::Array(items))) = (pos, h.get_mut(&arr)) {
439 items.remove(i);
440 }
441 });
442}
443
444fn clear_listeners(recv: &Value, event: Option<&str>) {
446 let Some(listeners) = listeners_obj(recv) else {
447 return;
448 };
449 with_host(|h| {
450 if let Some(JsObj::Object(p)) = h.get_mut(&listeners) {
451 match event {
452 Some(e) => {
453 p.shift_remove(e);
454 }
455 None => p.clear(),
456 }
457 }
458 });
459}
460
461fn read_line() -> String {
463 let mut line = String::new();
464 let _ = crate::host::with_stdin_reader(|r| r.read_line(&mut line));
465 while line.ends_with('\n') || line.ends_with('\r') {
466 line.pop();
467 }
468 line
469}
470
471fn write_stdout(s: &str) {
474 with_host(|h| h.write_out(s, false));
475}
476
477fn write_output(recv: &Value, s: &str) {
490 let out = opt_prop(recv, "@@output").unwrap_or(Value::Undef);
491 if matches!(out, Value::Obj(_)) && !with_host(|h| h.is_null(&out)) {
492 let payload = with_host(|h| h.new_str(s.to_string()));
493 let _ = crate::host::call_method(&out, "write", vec![payload]);
494 }
495}
496
497fn opt_prop(v: &Value, key: &str) -> Option<Value> {
499 with_host(|h| match h.get(v) {
500 Some(JsObj::Object(p)) => p.get(key).cloned(),
501 _ => None,
502 })
503}
504
505#[derive(Default)]
515struct LineState {
516 pending: Vec<u8>,
518 after_cr: bool,
521 to_emit: VecDeque<String>,
523 emitting: bool,
525 ended: bool,
527 closed: bool,
528 flowing: bool,
531 iterating: bool,
534 buffered: VecDeque<String>,
535 waiters: VecDeque<u32>,
536 question: Option<QuestionReply>,
539}
540
541enum QuestionReply {
542 Callback(Value),
543 Promise(u32),
544}
545
546thread_local! {
547 static LINES: std::cell::RefCell<HashMap<u64, LineState>> =
548 std::cell::RefCell::new(HashMap::new());
549 static NEXT_ID: std::cell::Cell<u64> = const { std::cell::Cell::new(1) };
550}
551
552fn rl_id(recv: &Value) -> u64 {
553 opt_prop(recv, "@@rlid")
554 .map(|v| with_host(|h| h.to_number(&v)) as u64)
555 .unwrap_or(0)
556}
557
558fn with_state<R>(recv: &Value, f: impl FnOnce(&mut LineState) -> R) -> R {
559 let id = rl_id(recv);
560 LINES.with(|m| f(m.borrow_mut().entry(id).or_default()))
561}
562
563fn is_stdin(input: &Value) -> bool {
565 with_host(|h| match h.get(input) {
566 Some(JsObj::Object(p)) => {
567 p.get("@@native").map(|v| h.str_of(v)).as_deref() == Some("WriteStream")
568 && p.get("fd").map(|v| h.to_number(v)) == Some(0.0)
569 }
570 _ => false,
571 })
572}
573
574fn ensure_flowing(recv: &Value) {
576 let input = opt_prop(recv, "@@input").unwrap_or(Value::Undef);
577 if !is_stdin(&input) {
578 return;
579 }
580 let start = with_state(recv, |s| {
581 !std::mem::replace(&mut s.flowing, true) && !s.closed
582 });
583 if start {
584 attach_stream(recv, &input);
585 }
586}
587
588fn on_data(recv: &Value, bytes: &[u8]) -> Result<(), String> {
591 if with_state(recv, |s| s.closed) {
593 return Ok(());
594 }
595 let start = with_state(recv, |s| {
596 let mut i = 0;
597 if s.after_cr && bytes.first() == Some(&b'\n') {
598 i = 1;
599 }
600 s.after_cr = false;
601 while i < bytes.len() {
602 match bytes[i] {
603 b'\n' => {
604 let line = String::from_utf8_lossy(&s.pending).into_owned();
605 s.pending.clear();
606 s.to_emit.push_back(line);
607 }
608 b'\r' => {
609 let line = String::from_utf8_lossy(&s.pending).into_owned();
610 s.pending.clear();
611 s.to_emit.push_back(line);
612 match bytes.get(i + 1) {
613 Some(b'\n') => i += 1,
614 None => s.after_cr = true,
615 _ => {}
616 }
617 }
618 b => s.pending.push(b),
619 }
620 i += 1;
621 }
622 !s.to_emit.is_empty() && !std::mem::replace(&mut s.emitting, true)
623 });
624 if start {
625 emit_lines(recv)?;
626 }
627 Ok(())
628}
629
630fn on_end(recv: &Value) -> Result<(), String> {
632 let (start, close_now) = with_state(recv, |s| {
633 s.ended = true;
634 if !s.pending.is_empty() {
635 let line = String::from_utf8_lossy(&s.pending).into_owned();
636 s.pending.clear();
637 s.to_emit.push_back(line);
638 }
639 let start = !s.to_emit.is_empty() && !std::mem::replace(&mut s.emitting, true);
640 (start, s.to_emit.is_empty() && !s.emitting)
641 });
642 if start {
643 emit_lines(recv)?;
644 } else if close_now {
645 close(recv)?;
646 }
647 Ok(())
648}
649
650fn emit_lines(recv: &Value) -> Result<(), String> {
655 while let Some(line) = with_state(recv, |s| s.to_emit.pop_front()) {
656 if let Err(e) = deliver(recv, line) {
657 with_state(recv, |s| s.emitting = false);
658 return Err(e);
659 }
660 }
661 let close_now = with_state(recv, |s| {
662 s.emitting = false;
663 s.ended
664 });
665 if close_now {
666 close(recv)?;
667 }
668 Ok(())
669}
670
671fn deliver(recv: &Value, line: String) -> Result<(), String> {
674 match with_state(recv, |s| s.question.take()) {
675 Some(QuestionReply::Callback(cb)) => {
676 let v = with_host(|h| h.new_str(line));
677 crate::host::invoke(&cb, vec![v], None)?;
678 return Ok(());
679 }
680 Some(QuestionReply::Promise(id)) => {
681 let v = with_host(|h| h.new_str(line));
682 crate::host::resolve_promise_val(id, v);
683 return Ok(());
684 }
685 None => {}
686 }
687 let v = with_host(|h| h.new_str(line.clone()));
688 emit(recv, "line", vec![v.clone()])?;
689 let waiter = with_state(recv, |s| {
690 if !s.iterating {
691 return None;
692 }
693 let w = s.waiters.pop_front();
694 if w.is_none() {
695 s.buffered.push_back(line);
696 }
697 w
698 });
699 if let Some(id) = waiter {
700 crate::host::resolve_promise_val(id, iter_result(v, false));
701 }
702 Ok(())
703}
704
705fn close(recv: &Value) -> Result<(), String> {
708 let waiters = with_state(recv, |s| {
709 if std::mem::replace(&mut s.closed, true) {
710 return None;
711 }
712 Some(std::mem::take(&mut s.waiters))
713 });
714 let Some(waiters) = waiters else {
715 return Ok(());
716 };
717 with_host(|h| {
719 if let Some(JsObj::Object(p)) = h.get_mut(recv) {
720 p.insert("closed".into(), Value::Bool(true));
721 }
722 });
723 let input = opt_prop(recv, "@@input").unwrap_or(Value::Undef);
726 if is_stdin(&input) {
727 crate::host::call_method(&input, "pause", Vec::new())?;
728 }
729 emit(recv, "close", Vec::new())?;
730 for id in waiters {
731 crate::host::resolve_promise_val(id, iter_result(Value::Undef, true));
732 }
733 Ok(())
734}
735
736fn emit(recv: &Value, event: &str, args: Vec<Value>) -> Result<(), String> {
738 let entries = listener_entries(recv, event);
739 for (cb, once) in entries {
740 if once {
741 remove_listener(recv, event, &cb);
742 }
743 crate::host::invoke(&cb, args.clone(), Some(recv.clone()))?;
744 }
745 Ok(())
746}
747
748fn iter_result(value: Value, done: bool) -> Value {
750 with_host(|h| {
751 let mut m = IndexMap::new();
752 m.insert("value".into(), value);
753 m.insert("done".into(), Value::Bool(done));
754 h.new_object(m)
755 })
756}
757
758fn internal_call(method: &str, args: &[Value]) -> Option<Result<Value, String>> {
761 let recv = args.first().cloned().unwrap_or(Value::Undef);
762 let r = match method {
763 "@@feed" => {
764 let chunk = args.get(1).cloned().unwrap_or(Value::Undef);
765 let bytes = super::buffer::view_bytes(&chunk)
766 .unwrap_or_else(|| with_host(|h| h.str_of(&chunk)).into_bytes());
767 on_data(&recv, &bytes)
768 }
769 "@@end" => on_end(&recv),
770 "@@close" => close(&recv),
771 _ => return None,
772 };
773 Some(r.map(|_| Value::Undef))
774}
775
776fn attach_stream(recv: &Value, input: &Value) {
779 with_state(recv, |s| s.flowing = true);
780 let has_on = crate::builtins::get_property(input, "on")
781 .map(|f| with_host(|h| is_callable(h, &f)))
782 .unwrap_or(false);
783 if !has_on {
784 return;
785 }
786 for (event, internal) in [("data", "readline.@@feed"), ("end", "readline.@@end")] {
787 let (name, cb) = with_host(|h| {
788 let target = h.alloc(JsObj::Builtin(internal.into()));
789 let undef = Value::Undef;
790 let cb = h.alloc(JsObj::BoundFunc {
791 target,
792 this: undef,
793 args: vec![recv.clone()],
794 });
795 (h.new_str(event), cb)
796 });
797 let _ = crate::host::call_method(input, "on", vec![name, cb]);
798 }
799}
800
801pub const ITERATOR_METHODS: &[&str] = &["next", "return", "@@asyncIterator"];
805
806fn async_iterator(recv: &Value) -> Value {
807 with_state(recv, |s| s.iterating = true);
808 ensure_flowing(recv);
809 with_host(|h| {
810 let mut m = IndexMap::new();
811 m.insert("@@native".into(), h.new_str("ReadlineIterator"));
812 m.insert("@@iface".into(), recv.clone());
813 h.new_object(m)
814 })
815}
816
817pub fn iterator_call(recv: &Value, method: &str) -> Result<Value, String> {
818 let iface = opt_prop(recv, "@@iface").unwrap_or(Value::Undef);
819 match method {
820 "@@asyncIterator" => Ok(recv.clone()),
821 "next" => {
822 let ready = with_state(&iface, |s| match s.buffered.pop_front() {
823 Some(line) => Some(Some(line)),
824 None if s.closed => Some(None),
825 None => None,
826 });
827 match ready {
828 Some(Some(line)) => {
829 let v = with_host(|h| h.new_str(line));
830 crate::builtins::promise_resolve_pub(iter_result(v, false))
831 }
832 Some(None) => crate::builtins::promise_resolve_pub(iter_result(Value::Undef, true)),
833 None => {
834 let (promise, id) = with_host(|h| {
835 let p = h.new_promise();
836 let id = h.promise_id(&p).unwrap_or(0);
837 (p, id)
838 });
839 with_state(&iface, |s| s.waiters.push_back(id));
840 Ok(promise)
841 }
842 }
843 }
844 "return" => {
847 with_host(|h| {
848 let cb = h.alloc(JsObj::Builtin("readline.@@close".into()));
849 h.queue_nexttick(cb, vec![iface.clone()]);
850 });
851 crate::builtins::promise_resolve_pub(iter_result(Value::Undef, true))
852 }
853 _ => Err(crate::host::type_error(&format!(
854 "{method} is not a function"
855 ))),
856 }
857}