node-js 0.1.5

JavaScript as a fusevm frontend: a lexer/parser and compiler to fusevm::Chunk on a JsHost object heap, with no bespoke VM or JIT
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
//! Node `stream` module: native base classes + module helper functions.
//!
//! The base classes (`Readable`/`Writable`/`Duplex`/`Transform`/`PassThrough`/
//! `Stream`) are EventEmitter-backed objects (same `@@native`/`@@on`/`@@once`
//! shape as `net` sockets) exposing the surface higher layers touch today:
//! `on`/`once`/`emit`, `write`/`end`, `push`/`read`, and a best-effort `pipe`.
//! `http`'s `req`/`res` are their own native objects (see `http.rs`); this module
//! exists so `require('stream')` yields the base constructors and the module
//! helper functions (`finished`, `pipeline`, `isReadable`, …).
//!
//! Lifecycle state is tracked with hidden boolean props set as terminal events
//! fire: `@@ended` (readable end), `@@finished` (writable finish), `@@destroyed`
//! (close/destroy), `@@errored` (error value), `@@disturbed` (read/resume/pipe).
//! `finished(stream, cb)` callbacks live in a `@@finished` array drained on the
//! first terminal event so the callback fires exactly once.

use crate::host::{with_host, JsObj};
use fusevm::Value;
use indexmap::IndexMap;
use std::cell::Cell;

// Module-state default high-water marks (byte mode / object mode). Node v26
// defaults: 65536 bytes, 16 objects; `setDefaultHighWaterMark` mutates these.
thread_local! {
    static DEFAULT_HWM_BYTES: Cell<f64> = const { Cell::new(65536.0) };
    static DEFAULT_HWM_OBJ: Cell<f64> = const { Cell::new(16.0) };
}

/// The base classes exported by `require('stream')`.
pub const CLASSES: &[&str] = &[
    "Readable",
    "Writable",
    "Duplex",
    "Transform",
    "PassThrough",
    "Stream",
];

/// The module free-functions exported by `require('stream')`.
pub const METHODS: &[&str] = &[
    "finished",
    "pipeline",
    "addAbortSignal",
    "destroy",
    "isReadable",
    "isWritable",
    "isErrored",
    "isDestroyed",
    "isDisturbed",
    "getDefaultHighWaterMark",
    "setDefaultHighWaterMark",
];

/// True if `name` is one of the stream base-class constructors.
pub fn is_class(name: &str) -> bool {
    CLASSES.contains(&name)
}

/// `stream.<Class>` property (a constructor value), reachable via
/// `namespace_property` → `stdlib::constant`.
pub fn constant(name: &str) -> Option<Value> {
    if is_class(name) {
        Some(with_host(|h| h.alloc(JsObj::Builtin(name.to_string()))))
    } else {
        None
    }
}

/// `new Readable()` / `Writable` / `Duplex` / `Transform` / `PassThrough` /
/// `Stream`.
pub fn construct(name: &str, args: &[Value]) -> Value {
    // A `push`ed-data queue lives on the object as an array for `read`.
    let mut extra = IndexMap::new();
    let queue = with_host(|h| h.new_array(Vec::new()));
    extra.insert("@@queue".into(), queue);
    // `new Writable({ write(chunk, enc, cb) {…} })` supplies the implementation
    // the stream is supposed to run — that option is the whole point of
    // constructing one directly, and it was DISCARDED: `construct` took only the
    // class name, so a custom sink silently swallowed every chunk. Keep the
    // callbacks the write path uses.
    if let Some(opts) = args.first() {
        for (opt, key) in [("write", "@@writeImpl"), ("final", "@@finalImpl")] {
            if let Some(f) = opt_callable(opts, opt) {
                extra.insert(key.into(), f);
            }
        }
    }
    super::net::new_emitter_object(name, extra)
}

/// An own property of `v` that is callable, else `None`.
fn opt_callable(v: &Value, key: &str) -> Option<Value> {
    let f = with_host(|h| match h.get(v) {
        Some(JsObj::Object(m)) => m.get(key).cloned(),
        _ => None,
    })?;
    with_host(|h| crate::host::is_callable(h, &f)).then_some(f)
}

/// Run the `write(chunk, encoding, callback)` implementation the constructor was
/// given, if any. The callback is required by the contract, so a no-op function
/// is supplied when the implementation asks for one.
fn run_write_impl(recv: &Value, chunk: &Value) -> Result<(), String> {
    let Some(f) = hidden_prop(recv, "@@writeImpl") else {
        return Ok(());
    };
    let enc = with_host(|h| h.new_str("utf8".to_string()));
    // `_write` is handed a `callback` it is contractually required to call.
    // Nothing here waits on backpressure, so it only has to BE callable —
    // a `write(c, e, cb) { …; cb(); }` implementation throws without it.
    let cb = with_host(|h| h.alloc(JsObj::Builtin("@@streamWriteCallback".into())));
    crate::host::invoke(&f, vec![chunk.clone(), enc, cb], None)?;
    Ok(())
}

fn hidden_prop(recv: &Value, key: &str) -> Option<Value> {
    with_host(|h| match h.get(recv) {
        Some(JsObj::Object(m)) => m.get(key).cloned(),
        _ => None,
    })
}

/// Module free-function dispatch (`stream.finished`, `stream.isReadable`, …).
pub fn call(method: &str, args: &[Value]) -> Option<Result<Value, String>> {
    let s0 = || args.first().cloned().unwrap_or(Value::Undef);
    Some(match method {
        "getDefaultHighWaterMark" => Ok(get_default_hwm(args)),
        "setDefaultHighWaterMark" => Ok(set_default_hwm(args)),
        "isReadable" => Ok(Value::Bool(is_readable(&s0()))),
        "isWritable" => Ok(Value::Bool(is_writable(&s0()))),
        "isErrored" => Ok(Value::Bool(flag(&s0(), "@@errored"))),
        "isDestroyed" => Ok(Value::Bool(flag(&s0(), "@@destroyed"))),
        "isDisturbed" => Ok(Value::Bool(flag(&s0(), "@@disturbed"))),
        "destroy" => Ok(destroy_stream(args)),
        "finished" => Ok(finished(args)),
        "pipeline" => pipeline(args),
        "addAbortSignal" => Ok(add_abort_signal(args)),
        _ => return None,
    })
}

fn get_default_hwm(args: &[Value]) -> Value {
    let obj = args
        .first()
        .map(|v| with_host(|h| h.truthy(v)))
        .unwrap_or(false);
    let n = if obj {
        DEFAULT_HWM_OBJ.with(|c| c.get())
    } else {
        DEFAULT_HWM_BYTES.with(|c| c.get())
    };
    Value::Float(n)
}

fn set_default_hwm(args: &[Value]) -> Value {
    let obj = args
        .first()
        .map(|v| with_host(|h| h.truthy(v)))
        .unwrap_or(false);
    let val = super::arg_num(args, 1);
    if obj {
        DEFAULT_HWM_OBJ.with(|c| c.set(val));
    } else {
        DEFAULT_HWM_BYTES.with(|c| c.set(val));
    }
    Value::Undef
}

// ── lifecycle-flag helpers ──────────────────────────────────────────────────

fn tag_of(recv: &Value) -> Option<String> {
    with_host(|h| match h.get(recv) {
        Some(JsObj::Object(p)) => p.get("@@native").map(|v| h.str_of(v)),
        _ => None,
    })
}

fn flag(recv: &Value, key: &str) -> bool {
    with_host(|h| match h.get(recv) {
        Some(JsObj::Object(p)) => p.get(key).map(|v| h.truthy(v)).unwrap_or(false),
        _ => false,
    })
}

fn set_flag(recv: &Value, key: &str, v: Value) {
    with_host(|h| {
        if let Some(JsObj::Object(p)) = h.get_mut(recv) {
            p.insert(key.to_string(), v);
        }
    });
}

fn is_readable(s: &Value) -> bool {
    let Some(t) = tag_of(s) else { return false };
    matches!(
        t.as_str(),
        "Readable" | "Duplex" | "Transform" | "PassThrough"
    ) && !flag(s, "@@destroyed")
        && !flag(s, "@@ended")
}

fn is_writable(s: &Value) -> bool {
    let Some(t) = tag_of(s) else { return false };
    matches!(
        t.as_str(),
        "Writable" | "Duplex" | "Transform" | "PassThrough"
    ) && !flag(s, "@@destroyed")
        && !flag(s, "@@finished")
}

// ── `finished` callback registry ────────────────────────────────────────────

fn add_finished(recv: &Value, cb: Value) {
    with_host(|h| {
        let existing = match h.get(recv) {
            Some(JsObj::Object(p)) => p.get("@@finished").cloned(),
            _ => None,
        };
        let arr = match existing {
            Some(a) if matches!(h.get(&a), Some(JsObj::Array(_))) => a,
            _ => {
                let a = h.new_array(Vec::new());
                if let Some(JsObj::Object(p)) = h.get_mut(recv) {
                    p.insert("@@finished".into(), a.clone());
                }
                a
            }
        };
        if let Some(JsObj::Array(items)) = h.get_mut(&arr) {
            items.push(cb);
        }
    });
}

fn take_finished(recv: &Value) -> Vec<Value> {
    with_host(|h| {
        let arr = match h.get_mut(recv) {
            Some(JsObj::Object(p)) => p.shift_remove("@@finished"),
            _ => None,
        };
        match arr {
            Some(av) => match h.get(&av) {
                Some(JsObj::Array(items)) => items.clone(),
                _ => Vec::new(),
            },
            None => Vec::new(),
        }
    })
}

/// Emit `name` (with `extra` args), set the matching lifecycle flag, and drain
/// `finished` callbacks on the first terminal event so each fires once.
fn emit_event(recv: &Value, name: &str, extra: Vec<Value>) -> Result<Value, String> {
    let mut a = vec![with_host(|h| h.new_str(name))];
    a.extend(extra.iter().cloned());
    let r = super::events::instance_call(recv, "emit", a)?;
    match name {
        "end" => set_flag(recv, "@@ended", Value::Bool(true)),
        "finish" => set_flag(recv, "@@finished", Value::Bool(true)),
        "close" => set_flag(recv, "@@destroyed", Value::Bool(true)),
        "error" => set_flag(
            recv,
            "@@errored",
            extra.first().cloned().unwrap_or(Value::Bool(true)),
        ),
        _ => {}
    }
    if matches!(name, "end" | "finish" | "close" | "error") {
        let cbs = take_finished(recv);
        let arg = if name == "error" {
            extra.first().cloned().unwrap_or(Value::Undef)
        } else {
            Value::Undef
        };
        for cb in cbs {
            crate::host::invoke(&cb, vec![arg.clone()], None)?;
        }
    }
    Ok(r)
}

// ── module free functions ───────────────────────────────────────────────────

/// `stream.finished(stream[, options], callback)` — invoke `callback(err)` once
/// when the stream ends/finishes/closes/errors. Fires immediately if the stream
/// has already reached a terminal state. Returns `undefined` (Node returns a
/// cleanup fn; not tracked — best-effort).
fn finished(args: &[Value]) -> Value {
    let stream = args.first().cloned().unwrap_or(Value::Undef);
    let cb = args
        .iter()
        .rev()
        .find(|v| with_host(|h| crate::host::is_callable(h, v)))
        .cloned()
        .unwrap_or(Value::Undef);
    if flag(&stream, "@@ended") || flag(&stream, "@@finished") || flag(&stream, "@@destroyed") {
        let _ = crate::host::invoke(&cb, vec![Value::Undef], None);
    } else {
        add_finished(&stream, cb);
    }
    Value::Undef
}

/// `stream.pipeline(source, ...transforms, dest[, callback])` — chain via
/// `.pipe()` and register `callback` on the destination's completion. Returns
/// the destination stream.
fn pipeline(args: &[Value]) -> Result<Value, String> {
    if args.is_empty() {
        // Node validates the LAST argument (the callback slot) first, so an
        // empty call reports that property, not a bespoke arity sentence.
        return Err(crate::host::invalid_arg_type(
            "streams[stream.length - 1]",
            "property",
            "function",
            &Value::Undef,
        ));
    }
    let cb_idx = args
        .iter()
        .rposition(|v| with_host(|h| crate::host::is_callable(h, v)));
    let (streams, cb) = match cb_idx {
        Some(i) if i == args.len() - 1 => (&args[..i], Some(args[i].clone())),
        _ => (args, None),
    };
    for w in streams.windows(2) {
        crate::host::call_method(&w[0], "pipe", vec![w[1].clone()])?;
    }
    let last = streams.last().cloned().unwrap_or(Value::Undef);
    if let Some(cb) = cb {
        add_finished(&last, cb);
    }
    Ok(last)
}

/// `stream.destroy(stream[, err])` — emit `error` (if `err` given) then `close`
/// and mark the stream destroyed.
fn destroy_stream(args: &[Value]) -> Value {
    let stream = args.first().cloned().unwrap_or(Value::Undef);
    if flag(&stream, "@@destroyed") {
        return stream;
    }
    if let Some(e) = args.get(1).cloned() {
        if !with_host(|h| h.is_nullish(&e)) {
            let _ = emit_event(&stream, "error", vec![e]);
        }
    }
    let _ = emit_event(&stream, "close", vec![]);
    set_flag(&stream, "@@destroyed", Value::Bool(true));
    stream
}

/// `stream.addAbortSignal(signal, stream)` — best-effort: `AbortSignal` is not
/// modeled in this runtime, so this returns `stream` unchanged.
fn add_abort_signal(args: &[Value]) -> Value {
    args.get(1).cloned().unwrap_or(Value::Undef)
}

/// Instance dispatch for a stream base class. EventEmitter methods are delegated
/// to `events`; `emit` routes through `emit_event` for lifecycle tracking.
pub fn instance_call(
    tag: &str,
    recv: &Value,
    method: &str,
    args: Vec<Value>,
) -> Result<Value, String> {
    let _ = tag;
    if method == "emit" {
        let name = args
            .first()
            .map(|v| with_host(|h| h.str_of(v)))
            .unwrap_or_default();
        let extra = args.get(1..).map(|s| s.to_vec()).unwrap_or_default();
        return emit_event(recv, &name, extra);
    }
    // `emit` is intercepted above (lifecycle tracking); every other name in
    // `events::METHODS` delegates. Reading the set from `events` rather than
    // re-listing it is what puts `listeners`/`setMaxListeners`/`getMaxListeners`
    // on a stream — the local copy was missing all three.
    if super::events::METHODS.contains(&method) {
        return super::events::instance_call(recv, method, args);
    }
    match method {
        "write" => {
            let chunk = args.first().cloned().unwrap_or(Value::Undef);
            run_write_impl(recv, &chunk)?;
            emit_event(recv, "data", vec![chunk])?;
            Ok(Value::Bool(true))
        }
        "end" => {
            if let Some(chunk) = args.first().filter(|v| !matches!(v, Value::Undef)) {
                run_write_impl(recv, chunk)?;
                emit_event(recv, "data", vec![chunk.clone()])?;
            }
            emit_event(recv, "finish", vec![])?;
            emit_event(recv, "end", vec![])?;
            Ok(recv.clone())
        }
        "push" => {
            let chunk = args.first().cloned().unwrap_or(Value::Undef);
            if with_host(|h| h.is_nullish(&chunk)) {
                emit_event(recv, "end", vec![])?;
                return Ok(Value::Bool(false));
            }
            if let Some(q) = queue_of(recv) {
                with_host(|h| {
                    if let Some(JsObj::Array(items)) = h.get_mut(&q) {
                        items.push(chunk.clone());
                    }
                });
            }
            emit_event(recv, "data", vec![chunk])?;
            Ok(Value::Bool(true))
        }
        "read" => {
            set_flag(recv, "@@disturbed", Value::Bool(true));
            if let Some(q) = queue_of(recv) {
                let next = with_host(|h| match h.get_mut(&q) {
                    Some(JsObj::Array(items)) if !items.is_empty() => Some(items.remove(0)),
                    _ => None,
                });
                if let Some(v) = next {
                    return Ok(v);
                }
            }
            Ok(with_host(|h| h.null()))
        }
        "pipe" => {
            set_flag(recv, "@@disturbed", Value::Bool(true));
            let dest = args.first().cloned().unwrap_or(Value::Undef);
            if let Some(q) = queue_of(recv) {
                let items = with_host(|h| match h.get(&q) {
                    Some(JsObj::Array(items)) => items.clone(),
                    _ => Vec::new(),
                });
                for chunk in items {
                    crate::host::call_method(&dest, "write", vec![chunk])?;
                }
            }
            Ok(dest)
        }
        "destroy" => {
            if !flag(recv, "@@destroyed") {
                if let Some(e) = args.first().filter(|v| !matches!(v, Value::Undef)) {
                    let _ = emit_event(recv, "error", vec![e.clone()]);
                }
                let _ = emit_event(recv, "close", vec![]);
                set_flag(recv, "@@destroyed", Value::Bool(true));
            }
            Ok(recv.clone())
        }
        "resume" => {
            set_flag(recv, "@@disturbed", Value::Bool(true));
            Ok(recv.clone())
        }
        "setEncoding" | "pause" | "cork" | "uncork" => Ok(recv.clone()),
        _ => Err(crate::host::type_error(&format!(
            "stream.{method} is not a function"
        ))),
    }
}

fn queue_of(recv: &Value) -> Option<Value> {
    with_host(|h| match h.get(recv) {
        Some(JsObj::Object(p)) => p.get("@@queue").cloned(),
        _ => None,
    })
}