Skip to main content

nodejs/stdlib/
util.rs

1//! Node `util` module: `format`, `inspect`, and a subset of `util.types`.
2
3use crate::host::{with_host, JsObj};
4use fusevm::Value;
5use indexmap::IndexMap;
6
7pub const METHODS: &[&str] = &[
8    "format",
9    "formatWithOptions",
10    "inspect",
11    "deprecate",
12    "inherits",
13    "types",
14    "types.isMap",
15    "types.isSet",
16    "types.isPromise",
17    "types.isDate",
18    "types.isRegExp",
19    "types.isNativeError",
20    "types.isAsyncFunction",
21    "isDeepStrictEqual",
22    "isArray",
23    "debuglog",
24    "stripVTControlCharacters",
25    "toUSVString",
26    "getSystemErrorName",
27    "getSystemErrorMessage",
28    "getSystemErrorMap",
29    "styleText",
30    "parseArgs",
31    "promisify",
32    "aborted",
33    "callbackify",
34    "parseEnv",
35    "debug",
36];
37
38/// Non-function `util` exports (`require('util').TextEncoder`, `.MIMEType`, …).
39/// Each resolves to a `Builtin("<name>")` the parent `construct`s via `new`.
40pub fn constant(name: &str) -> Option<Value> {
41    match name {
42        "types" => Some(with_host(|h| h.alloc(JsObj::Builtin("util/types".into())))),
43        "TextEncoder" | "TextDecoder" | "MIMEType" | "MIMEParams" => {
44            Some(with_host(|h| h.alloc(JsObj::Builtin(name.into()))))
45        }
46        _ => None,
47    }
48}
49
50pub fn call(method: &str, args: &[Value]) -> Option<Result<Value, String>> {
51    if let Some(pred) = method.strip_prefix("types.") {
52        return Some(Ok(Value::Bool(type_predicate(pred, args.first()))));
53    }
54    Some(match method {
55        "format" => {
56            // `format` re-enters `with_host` internally, so build the string first
57            // and only then allocate — never nest the borrow.
58            match format(args) {
59                Ok(s) => Ok(with_host(|h| h.new_str(s))),
60                Err(e) => Err(e),
61            }
62        }
63        // `formatWithOptions(inspectOptions, fmt, ...args)`: `format`, with
64        // the options bag applied to every value it inspects. A non-object
65        // bag is node's `validateObject` rejection.
66        "formatWithOptions" => {
67            let opts = args.first().cloned().unwrap_or(Value::Undef);
68            let is_object = with_host(|h| {
69                matches!(opts, Value::Obj(_)) && h.type_of(&opts) == "object" && !h.is_null(&opts)
70            });
71            if !is_object {
72                return Some(Err(crate::host::invalid_arg_type(
73                    "inspectOptions",
74                    "argument",
75                    "object",
76                    &opts,
77                )));
78            }
79            apply_inspect_options(&opts);
80            let out = format(args.get(1..).unwrap_or(&[]));
81            reset_inspect_options();
82            out.map(|s| with_host(|h| h.new_str(s)))
83        }
84        "inspect" => {
85            if let Some(v) = args.first() {
86                crate::builtins::materialize_stack(v);
87            }
88            apply_inspect_options(&args.get(1).cloned().unwrap_or(Value::Undef));
89            let rendered = crate::host::inspect_js(&args.first().cloned().unwrap_or(Value::Undef));
90            reset_inspect_options();
91            rendered.map(|s| with_host(|h| h.new_str(s)))
92        }
93        // `deprecate(fn, msg)`: return a callable that behaves like `fn`. The
94        // house rule is no deprecation nags, so no warning is emitted — the
95        // original function is handed back unchanged.
96        "deprecate" => Ok(args.first().cloned().unwrap_or(Value::Undef)),
97        // `inherits(ctor, superCtor)`: modern Node semantics — set `ctor.super_`
98        // and re-link `ctor.prototype`'s `[[Prototype]]` to `superCtor.prototype`
99        // (methods already on `ctor.prototype` are preserved).
100        "inherits" => Ok(inherits(args)),
101        // Bare `util.types` accessed then called is not meaningful; return the
102        // namespace value so a stray call is a harmless undefined.
103        "types" => Ok(Value::Undef),
104        "isDeepStrictEqual" => Ok(Value::Bool(super::assert::deep_equal(
105            &args.first().cloned().unwrap_or(Value::Undef),
106            &args.get(1).cloned().unwrap_or(Value::Undef),
107            true,
108        ))),
109        // `util.isArray === Array.isArray` (a legacy alias Node still ships).
110        "isArray" => Ok(Value::Bool(with_host(|h| {
111            matches!(
112                h.get(&args.first().cloned().unwrap_or(Value::Undef)),
113                Some(JsObj::Array(_))
114            )
115        }))),
116        // `stripVTControlCharacters(str)`: remove ANSI/VT escape sequences.
117        "stripVTControlCharacters" => {
118            let stripped = strip_vt(&super::arg_str(args, 0));
119            Ok(with_host(|h| h.new_str(stripped)))
120        }
121        // `toUSVString(str)`: replace unpaired surrogates with U+FFFD. Strings are
122        // already well-formed UTF-8 here (no lone surrogates survive), so the input
123        // round-trips unchanged.
124        "toUSVString" => Ok(with_host(|h| {
125            let s = h.str_of(&args.first().cloned().unwrap_or(Value::Undef));
126            h.new_str(s)
127        })),
128        "getSystemErrorName" => {
129            let e = errno_of(super::arg_num(args, 0));
130            let name = errno_name(e)
131                .map(str::to_string)
132                .unwrap_or_else(|| format!("Unknown system error {e}"));
133            Ok(with_host(|h| h.new_str(name)))
134        }
135        "getSystemErrorMessage" => {
136            let e = errno_of(super::arg_num(args, 0));
137            let msg = errno_message(e)
138                .map(str::to_string)
139                .unwrap_or_else(|| format!("Unknown system error {e}"));
140            Ok(with_host(|h| h.new_str(msg)))
141        }
142        "getSystemErrorMap" => Ok(system_error_map()),
143        "styleText" => return Some(style_text(args)),
144        "parseArgs" => return Some(parse_args(args)),
145        "@@nodeError" => return Some(node_error(args)),
146        // `getPromiseDetails(p)[0]` for the web-streams port's
147        // `isPromisePending`: 0 pending, 1 fulfilled, 2 rejected.
148        // The web-streams port's `readableStreamCancel(stream, reason)`, for
149        // `FileHandle.readableWebStream`.
150        "@@readableStreamCancel" => return Some(super::stream_web::readable_stream_cancel(args)),
151        "@@promiseState" => {
152            let p = args.first().cloned().unwrap_or(Value::Undef);
153            let state = with_host(|h| h.promise_id(&p).map(|id| h.promise_state(id)));
154            Ok(Value::Int(match state {
155                Some(crate::host::PromiseState::Fulfilled) => 1,
156                Some(crate::host::PromiseState::Rejected) => 2,
157                _ => 0,
158            }))
159        }
160        "debuglog" => return Some(debuglog(args)),
161        "promisify" => return Some(promisify(args)),
162        // `util.aborted(signal, resource)` — a promise that settles when the
163        // signal aborts. It did not exist, so the documented way to await an
164        // abort threw.
165        "aborted" => {
166            let signal = args.first().cloned().unwrap_or(Value::Undef);
167            let resource = args.get(1).cloned().unwrap_or(Value::Undef);
168            return Some(aborted(&signal, &resource));
169        }
170        "callbackify" => return Some(callbackify(args)),
171        // `util.parseEnv(content)` → an object of the parsed dotenv assignments.
172        "parseEnv" => Ok(parse_env(&super::arg_str(args, 0))),
173        // `util.debug === util.debuglog` (a documented alias).
174        "debug" => return Some(debuglog(args)),
175        _ => return None,
176    })
177}
178
179/// Set every `util.inspect` option `options` names for the next render;
180/// [`reset_inspect_options`] puts the defaults back. Shared by `inspect` and
181/// `formatWithOptions`, which hands the same bag to every `inspect` it makes.
182fn apply_inspect_options(options: &Value) {
183    // Honor an options `{ depth: N | null }` (default 2; null = unlimited).
184    let depth = match Some(options).filter(|o| !matches!(o, Value::Undef)) {
185        Some(opts) => match crate::builtins::get_property(opts, "depth") {
186            Ok(Value::Undef) => 2,
187            Ok(v) if with_host(|h| h.is_null(&v)) => i64::MAX,
188            Ok(v) => {
189                let n = with_host(|h| h.to_number(&v));
190                // A NEGATIVE depth is legal and means "already past the
191                // limit"; only `null` and a non-finite depth mean
192                // unlimited. Treating anything below zero as unlimited
193                // made `{ depth: -1 }` print the whole object.
194                match n {
195                    _ if n.is_nan() || n == f64::INFINITY => i64::MAX,
196                    _ if n == f64::NEG_INFINITY => i64::MIN,
197                    _ => n.trunc().clamp(i64::MIN as f64, i64::MAX as f64) as i64,
198                }
199            }
200            Err(_) => 2,
201        },
202        None => 2,
203    };
204    crate::host::set_inspect_max_depth(depth);
205    // `compact` (default 3) decides how deep a subtree may be and still
206    // print on one line; `false` means never. `breakLength` (80 here) is
207    // the column budget for that line.
208    let opts = options.clone();
209    let read = |k: &str| crate::builtins::get_property(&opts, k).unwrap_or(Value::Undef);
210    let compact = match read("compact") {
211        Value::Undef => 3,
212        Value::Bool(false) => 0,
213        // `compact: true` is node's legacy "always join" mode; no depth
214        // gate applies, which a very large number expresses exactly.
215        Value::Bool(true) => i64::MAX,
216        v => with_host(|h| h.to_number(&v)).max(0.0) as i64,
217    };
218    let break_length = match read("breakLength") {
219        Value::Undef => 80,
220        v => {
221            let n = with_host(|h| h.to_number(&v));
222            if n.is_finite() {
223                n.max(0.0) as usize
224            } else {
225                usize::MAX
226            }
227        }
228    };
229    // `sorted` accepts a comparator function in node; only the boolean
230    // form is honored here, and any truthy value turns plain sorting on.
231    // Read the option OUT of the host before borrowing it: `read` borrows
232    // the host itself, so `with_host(|h| h.truthy(&read("sorted")))` is a
233    // nested borrow and aborts the process with "RefCell already
234    // borrowed", which no script can catch.
235    let sorted_opt = read("sorted");
236    let sorted = with_host(|h| h.truthy(&sorted_opt));
237    // `customInspect` defaults to TRUE, so only an explicit `false`
238    // turns a value's own `[util.inspect.custom]` rendering off.
239    let custom_inspect = match read("customInspect") {
240        Value::Undef => true,
241        v => with_host(|h| h.truthy(&v)),
242    };
243    let show_hidden_opt = read("showHidden");
244    let show_hidden = with_host(|h| h.truthy(&show_hidden_opt));
245    // `maxArrayLength: null | Infinity` means "no limit". Node also
246    // accepts 0 (show none but the tail count), which falls out of the
247    // clamp below without a special case.
248    let max_array_length = match read("maxArrayLength") {
249        Value::Undef => crate::host::DEFAULT_MAX_ARRAY_LENGTH,
250        v if with_host(|h| h.is_null(&v)) => usize::MAX,
251        v => {
252            let n = with_host(|h| h.to_number(&v));
253            if n.is_finite() {
254                n.max(0.0) as usize
255            } else {
256                usize::MAX
257            }
258        }
259    };
260    let numeric_separator_opt = read("numericSeparator");
261    let numeric_separator = with_host(|h| h.truthy(&numeric_separator_opt));
262    let show_proxy_opt = read("showProxy");
263    let show_proxy = with_host(|h| h.truthy(&show_proxy_opt));
264    // `maxStringLength: null | Infinity` means "no limit", as for arrays.
265    let max_string_length = match read("maxStringLength") {
266        Value::Undef => crate::host::DEFAULT_MAX_STRING_LENGTH,
267        v if with_host(|h| h.is_null(&v)) => usize::MAX,
268        v => {
269            let n = with_host(|h| h.to_number(&v));
270            if n.is_finite() {
271                n.max(0.0) as usize
272            } else {
273                usize::MAX
274            }
275        }
276    };
277    // `getters: true | 'get' | 'set'`.
278    let getters_opt = read("getters");
279    let getters = with_host(|h| match h.as_str(&getters_opt).as_deref() {
280        Some("get") => 2,
281        Some("set") => 3,
282        _ if h.truthy(&getters_opt) => 1,
283        _ => 0,
284    });
285    crate::host::set_inspect_getters(getters);
286    crate::host::set_inspect_numeric_separator(numeric_separator);
287    crate::host::set_inspect_show_proxy(show_proxy);
288    crate::host::set_inspect_max_string_length(max_string_length);
289    crate::host::set_inspect_compact(compact);
290    crate::host::set_inspect_break_length(break_length);
291    crate::host::set_inspect_sorted(sorted);
292    crate::host::set_inspect_max_array_length(max_array_length);
293    crate::host::set_inspect_custom(custom_inspect);
294    crate::host::set_inspect_show_hidden(show_hidden);
295}
296
297/// The `util.inspect` defaults, restored after every render.
298fn reset_inspect_options() {
299    crate::host::set_inspect_max_depth(2);
300    crate::host::set_inspect_compact(3);
301    crate::host::set_inspect_break_length(80);
302    crate::host::set_inspect_sorted(false);
303    crate::host::set_inspect_max_array_length(crate::host::DEFAULT_MAX_ARRAY_LENGTH);
304    crate::host::set_inspect_custom(true);
305    crate::host::set_inspect_getters(0);
306    crate::host::set_inspect_numeric_separator(false);
307    crate::host::set_inspect_show_proxy(false);
308    crate::host::set_inspect_max_string_length(crate::host::DEFAULT_MAX_STRING_LENGTH);
309    crate::host::set_inspect_show_hidden(false);
310}
311
312/// `util.inherits(ctor, superCtor)`.
313fn inherits(args: &[Value]) -> Value {
314    let ctor = args.first().cloned().unwrap_or(Value::Undef);
315    let sup = args.get(1).cloned().unwrap_or(Value::Undef);
316    with_host(|h| {
317        // Get-or-create `superCtor.prototype` and store it, so a later
318        // `superCtor.prototype` read returns the same object identity (`===`).
319        let sup_proto = h.fn_prop(&sup, "prototype").unwrap_or_else(|| {
320            let mut props = indexmap::IndexMap::new();
321            props.insert("constructor".to_string(), sup.clone());
322            let p = h.new_object(props);
323            h.set_fn_prop(&sup, "prototype", p.clone());
324            p
325        });
326        // Get-or-create `ctor.prototype` (with a `constructor` back-link).
327        let ctor_proto = h.fn_prop(&ctor, "prototype").unwrap_or_else(|| {
328            let mut props = indexmap::IndexMap::new();
329            props.insert("constructor".to_string(), ctor.clone());
330            let p = h.new_object(props);
331            h.set_fn_prop(&ctor, "prototype", p.clone());
332            p
333        });
334        h.set_proto(&ctor_proto, sup_proto);
335        h.set_fn_prop(&ctor, "super_", sup);
336    });
337    Value::Undef
338}
339
340fn type_predicate(pred: &str, v: Option<&Value>) -> bool {
341    let Some(v) = v else { return false };
342    with_host(|h| match pred {
343        "isMap" => matches!(h.get(v), Some(JsObj::Map { weak: false, .. })),
344        "isSet" => matches!(h.get(v), Some(JsObj::Set { weak: false, .. })),
345        "isPromise" => matches!(h.get(v), Some(JsObj::Promise { .. })),
346        _ => false,
347    })
348}
349
350/// Node's `formatNumber` for the `%d`/`%i`/`%f` directives: the ordinary number
351/// rendering, except that negative zero prints as `-0` (plain string coercion
352/// would flatten it to `0`, so `console.log("%d", -0)` would lose the sign).
353fn fmt_directive_number(n: f64) -> String {
354    if n == 0.0 && n.is_sign_negative() {
355        return "-0".into();
356    }
357    crate::host::fmt_number(n)
358}
359
360/// Run one of the global numeric parsers over a directive argument. `%i` is
361/// `parseInt` and `%f` is `parseFloat` — string-prefix parses, NOT `Number()`,
362/// which is why `"3.9abc"` yields `3`/`3.9` rather than `NaN`.
363fn coerce_via(parser: &str, arg: &Value) -> Result<f64, String> {
364    // The parse itself cannot fail, but coercing the ARGUMENT to a string can:
365    // `parseInt([Symbol()])` joins the array, and a Symbol has no string form.
366    // Node lets that TypeError out of `util.format`; swallowing it turned a
367    // throwing program into one that printed `NaN`.
368    let v = crate::builtins::call_builtin_function(parser, vec![arg.clone()])?;
369    Ok(with_host(|h| h.to_number(&v)))
370}
371
372/// `util.format(fmt, ...args)` — printf-style substitution (`%s %d %i %f %j %o %O
373/// %c %%`) with any leftover arguments appended space-separated.
374/// Fallible because three of the directives can throw and node lets those
375/// throws out: `%j` on a BigInt is `TypeError: Do not know how to serialize a
376/// BigInt`, and `%d`/`%i`/`%f` on a value whose coercion reaches a Symbol is
377/// `TypeError: Cannot convert a Symbol value to a string`. Returning a bare
378/// `String` meant each of those printed `undefined` or `NaN` instead.
379pub fn format(args: &[Value]) -> Result<String, String> {
380    // Node's inspect reads `err.stack`, and that read is what FORMATS the header
381    // and freezes it. Doing it here, before the inspect borrow, keeps
382    // `console.log(err)` showing the error's current `name` — the inspect walk
383    // itself runs under an immutable host borrow and cannot re-format anything.
384    for a in args {
385        crate::builtins::materialize_stack(a);
386    }
387    if args.is_empty() {
388        return Ok(String::new());
389    }
390    // Node: a single argument is returned as-is (no specifier processing) —
391    // `util.format("100%% done")` === "100%% done".
392    if args.len() == 1 {
393        return crate::host::console_format_js(&args[0]);
394    }
395    let fmt = with_host(|h| h.str_of(&args[0]));
396    // A non-string first argument: inspect everything, space-joined.
397    if !matches!(args[0], Value::Str(_))
398        && !with_host(|h| matches!(h.get(&args[0]), Some(JsObj::Str(_))))
399    {
400        return Ok(args
401            .iter()
402            .map(crate::host::console_format_js)
403            .collect::<Result<Vec<_>, _>>()?
404            .join(" "));
405    }
406
407    let mut out = String::new();
408    let mut ai = 1usize;
409    let mut chars = fmt.chars().peekable();
410    while let Some(c) = chars.next() {
411        if c != '%' {
412            out.push(c);
413            continue;
414        }
415        let Some(&spec) = chars.peek() else {
416            out.push('%');
417            break;
418        };
419        if spec == '%' {
420            out.push('%');
421            chars.next();
422            continue;
423        }
424        if !matches!(spec, 's' | 'd' | 'i' | 'f' | 'j' | 'o' | 'O' | 'c') || ai >= args.len() {
425            out.push('%');
426            continue;
427        }
428        chars.next();
429        let arg = &args[ai];
430        ai += 1;
431        match spec {
432            // Node's %s renders a BigInt with the trailing `n` (unlike String()).
433            // `%s` is NOT `String(x)` for objects. Node stringifies an object
434            // only when its `toString` is one the SCRIPT wrote; an object that
435            // would merely inherit the built-in is inspected instead, at
436            // `depth: 0`. So `%s` on `{a:{b:1}}` is `{ a: [Object] }`, on a Date
437            // the ISO form, and on a Map `Map(1) { 'a' => 1 }` — where plain
438            // `String()` would flatten all three to `[object Object]`, which is
439            // what this printed for every object, Map, Set, Date and boxed
440            // primitive. A class that defines `toString` (or `Symbol
441            // .toPrimitive`) still wins, at any depth of its prototype chain.
442            's' => {
443                // A NUMBER goes through node's number formatter, not `String()`:
444                // that is the only path that distinguishes `-0` from `0`, and
445                // `util.format('%s', -0)` is `-0` where `String(-0)` is `0`.
446                if let Value::Float(n) = arg {
447                    out.push_str(&fmt_directive_number(*n));
448                    continue;
449                }
450                let (bigint, use_inspect) = with_host(|h| match h.get(arg) {
451                    Some(JsObj::BigInt(b)) => (Some(format!("{b}n")), false),
452                    _ => {
453                        let is_obj = h.type_of(arg) == "object" && !h.is_null(arg);
454                        // Only a SCRIPT-DEFINED conversion counts. A boxed
455                        // primitive carries a real `toString` on its prototype,
456                        // but it is the built-in one, so node still inspects it
457                        // (`new String('b')` under `%s` is `[String: 'b']`, not
458                        // `b`) — testing merely for the property's presence put
459                        // every boxed primitive on the stringifying path.
460                        // A Buffer is the one core type whose `toString` node
461                        // does NOT count as built-in: `lib/buffer.js` is ordinary
462                        // JavaScript, so `%s` decodes the bytes
463                        // (`util.format('%s', Buffer.from('hi'))` is `hi`) rather
464                        // than inspecting them. Its `toString` is native here and
465                        // would otherwise be classified the other way. Read from
466                        // the ALREADY-BORROWED host: `stdlib::native_tag` opens
467                        // its own borrow and would abort the process from here.
468                        // The same applies to every BYTE VIEW: node stringifies
469                        // a `Uint8Array` under `%s` as `1,2`, where a plain Array
470                        // is inspected as `[ 1, 2 ]`. An ArrayBuffer is NOT one of
471                        // these — it has no `toString` of its own and is inspected.
472                        let stringifies = matches!(h.get(arg), Some(JsObj::Object(p))
473                        if matches!(
474                            p.get("@@native").map(|t| h.str_of(t)).as_deref(),
475                            Some("Buffer") | Some("TypedArray")
476                        ));
477                        if stringifies {
478                            return (None, false);
479                        }
480                        let scripted = ["toString", "@@toPrimitive"].iter().any(|k| {
481                            crate::host::lookup_chain(h, arg, k).is_some_and(|f| {
482                                matches!(
483                                    h.get(&f),
484                                    Some(JsObj::Func(_))
485                                        | Some(JsObj::Class(_))
486                                        | Some(JsObj::BoundFunc { .. })
487                                )
488                            })
489                        });
490                        (None, is_obj && !scripted)
491                    }
492                });
493                if let Some(b) = bigint {
494                    out.push_str(&b);
495                } else if use_inspect {
496                    // `{ ...inspectOptions, depth: 0, colors: false, compact: 3 }`.
497                    let (depth, compact) = (
498                        crate::host::inspect_max_depth(),
499                        crate::host::inspect_compact(),
500                    );
501                    crate::host::set_inspect_max_depth(0);
502                    crate::host::set_inspect_compact(3);
503                    let s = crate::host::inspect_js(arg);
504                    crate::host::set_inspect_max_depth(depth);
505                    crate::host::set_inspect_compact(compact);
506                    let s = s?;
507                    out.push_str(&s);
508                } else {
509                    // Full `ToPrimitive`, so a scripted `toString` actually runs;
510                    // `str_of` reads the object's brand and would answer
511                    // `[object Object]` without calling anything.
512                    let s = crate::host::to_string_value(arg)
513                        .map(|v| with_host(|h| h.str_of(&v)))
514                        .unwrap_or_else(|_| with_host(|h| h.str_of(arg)));
515                    out.push_str(&s);
516                }
517            }
518            // The three numeric directives use three DIFFERENT conversions, and
519            // collapsing them to one truncating `to_number` got all three wrong:
520            //   %d -> Number(x)      ("%d", 1.7)      is 1.7,      not 1
521            //   %i -> parseInt(x,10) ("%i", "3.9abc") is 3,        not NaN
522            //   %f -> parseFloat(x)  ("%f", "1.5x")   is 1.5,      not NaN
523            // and `n.trunc() as i64` additionally saturated every non-finite and
524            // out-of-i64-range value to 9223372036854775807 (`Infinity`, `1e21`).
525            // BigInt keeps its `n` suffix under %d/%i (Node prints `10n`).
526            'd' | 'i' => {
527                let big = with_host(|h| match h.get(arg) {
528                    Some(JsObj::BigInt(b)) => Some(format!("{b}n")),
529                    _ => None,
530                });
531                // A bare Symbol is `NaN` under %d rather than a throw — node
532                // tests `typeof === 'symbol'` before it ever coerces. Only a
533                // Symbol reached THROUGH a coercion (inside an array, say) throws.
534                let is_symbol = with_host(|h| h.type_of(arg) == "symbol");
535                match big {
536                    Some(s) => out.push_str(&s),
537                    None if is_symbol => out.push_str("NaN"),
538                    None if spec == 'd' => {
539                        out.push_str(&fmt_directive_number(crate::host::to_number_value(arg)?))
540                    }
541                    None => out.push_str(&fmt_directive_number(coerce_via("parseInt", arg)?)),
542                }
543            }
544            'f' => {
545                let is_symbol = with_host(|h| h.type_of(arg) == "symbol");
546                if is_symbol {
547                    out.push_str("NaN");
548                } else {
549                    out.push_str(&fmt_directive_number(coerce_via("parseFloat", arg)?));
550                }
551            }
552            'j' => {
553                // A CIRCULAR structure is the one JSON failure node absorbs,
554                // rendering it as `[Circular]`; every other failure — a BigInt
555                // above all — propagates.
556                match crate::builtins::call_builtin_function("JSON.stringify", vec![arg.clone()]) {
557                    Ok(v) => out.push_str(&with_host(|h| h.str_of(&v))),
558                    Err(e) if e.contains("circular structure") => out.push_str("[Circular]"),
559                    Err(e) => return Err(e),
560                }
561            }
562            // `%o` and `%O` are NOT the same directive. `%O` is a plain
563            // `inspect` at the default depth; `%o` is `inspect(v, { showHidden:
564            // true, showProxy: true, depth: 4 })`, so it reveals an array's
565            // `[length]`, a typed array's window onto its buffer, and four levels
566            // instead of two. Rendering both as the default inspect made `%o` a
567            // silent alias of `%O`.
568            'O' => out.push_str(&crate::host::inspect_js(arg)?),
569            // Both spread over `formatWithOptions`'s bag, so the previous
570            // settings are restored rather than reset.
571            'o' => {
572                let saved = (
573                    crate::host::inspect_show_proxy(),
574                    crate::host::inspect_show_hidden(),
575                    crate::host::inspect_max_depth(),
576                );
577                crate::host::set_inspect_show_proxy(true);
578                crate::host::set_inspect_show_hidden(true);
579                crate::host::set_inspect_max_depth(4);
580                let s = crate::host::inspect_js(arg);
581                crate::host::set_inspect_show_proxy(saved.0);
582                crate::host::set_inspect_show_hidden(saved.1);
583                crate::host::set_inspect_max_depth(saved.2);
584                out.push_str(&s?);
585            }
586            'c' => {} // CSS directive: consumes the arg, emits nothing.
587            _ => {}
588        }
589    }
590    // Append remaining arguments.
591    for a in &args[ai..] {
592        out.push(' ');
593        out.push_str(&crate::host::console_format_js(a)?);
594    }
595    Ok(out)
596}
597
598// ── promisify / callbackify ──────────────────────────────────────────────────
599// These build a REAL JS closure by compiling a factory expression and invoking it
600// with the wrapped function — the same re-entrant nested-run path `vm.runInThisContext`
601// uses — so the returned value is an ordinary user function (`typeof === "function"`).
602
603/// Compile a single JS expression and run it on the LIVE host, returning its
604/// completion value. Delegates to the frontend's ONE runtime-source evaluator
605/// (`crate::eval_in_global_scope`), which runs the factory in the program's
606/// module scope rather than in the calling function's frame.
607fn run_completion(src: &str) -> Result<Value, String> {
608    crate::eval_internal(src)
609}
610
611/// A port of `lib/internal/util.js` `promisify`. `custom` is the builtin's own
612/// promisified form (node's `kCustomPromisifiedSymbol` on `setTimeout`,
613/// `fs.exists`, …) and `argNames` its `kCustomPromisifyArgsSymbol` — the names a
614/// multi-value callback resolves into (`{bytesRead, buffer}`); both are supplied
615/// from Rust because those symbols are internal. A user function's own
616/// `[util.promisify.custom]` is honoured, the result carries the original's
617/// prototype and own properties (`name`, `length`), and it is its own custom
618/// form, so promisifying it again is the identity.
619/// A non-function custom form is returned boxed (`[c]`) for the caller to
620/// reject with node's `ERR_INVALID_ARG_TYPE`.
621const PROMISIFY_SRC: &str = "(function(original, custom, argNames, sym){\n\
622  var c = custom || original[sym];\n\
623  if (c) {\n\
624    if (typeof c !== 'function') return [c];\n\
625    try { Object.defineProperty(c, sym, { value: c, enumerable: false, writable: false, configurable: true }); } catch (_) {}\n\
626    return c;\n\
627  }\n\
628  function fn(...args) {\n\
629    var self = this;\n\
630    return new Promise(function(resolve, reject){\n\
631      args.push(function(err, ...values){\n\
632        if (err) return reject(err);\n\
633        if (argNames !== undefined && values.length > 1) {\n\
634          var obj = {};\n\
635          for (var i = 0; i < argNames.length; i++) obj[argNames[i]] = values[i];\n\
636          resolve(obj);\n\
637        } else {\n\
638          resolve(values[0]);\n\
639        }\n\
640      });\n\
641      Reflect.apply(original, self, args);\n\
642    });\n\
643  }\n\
644  Object.setPrototypeOf(fn, Object.getPrototypeOf(original));\n\
645  Object.defineProperty(fn, sym, { value: fn, enumerable: false, writable: false, configurable: true });\n\
646  return Object.defineProperties(fn, Object.getOwnPropertyDescriptors(original));\n\
647})";
648
649/// `fs.exists`'s custom promisified form: it resolves with the boolean its
650/// one-argument callback receives, never rejects.
651const EXISTS_PROMISIFIED_SRC: &str = "(function exists(path){\n\
652  return new Promise(function(resolve){ require('fs').exists(path, resolve); });\n\
653})";
654
655/// `child_process`'s `customPromiseExecFunction(orig)`: resolves
656/// `{ stdout, stderr }`, or rejects with the error carrying both, and exposes
657/// the child as `promise.child`.
658const CUSTOM_EXEC_SRC: &str = "(function(orig, name){\n\
659  const f = function(...args) {\n\
660    const { promise, resolve, reject } = Promise.withResolvers();\n\
661    promise.child = orig(...args, (err, stdout, stderr) => {\n\
662      if (err !== null) {\n\
663        err.stdout = stdout;\n\
664        err.stderr = stderr;\n\
665        reject(err);\n\
666      } else {\n\
667        resolve({ stdout, stderr });\n\
668      }\n\
669    });\n\
670    return promise;\n\
671  };\n\
672  Object.defineProperty(f, 'name', { value: name });\n\
673  return f;\n\
674})";
675
676/// The function node keeps under `[util.promisify.custom]` on one of its own
677/// builtins (`kCustomPromisifiedSymbol`), keyed by the builtin's name here,
678/// or `None` for a builtin that has none. It is ONE value per builtin, so a
679/// read of `setTimeout[util.promisify.custom]`, `util.promisify(setTimeout)`
680/// and `require('timers/promises').setTimeout` are the same function.
681pub(crate) fn custom_promisified(builtin: &str) -> Option<Result<Value, String>> {
682    let alias = |target: &str| Some(Ok(with_host(|h| h.alloc(JsObj::Builtin(target.into())))));
683    match builtin {
684        "setTimeout" => return alias("timers/promises.setTimeout"),
685        "setImmediate" => return alias("timers/promises.setImmediate"),
686        "stream.pipeline" | "Stream.pipeline" => return alias("stream/promises.pipeline"),
687        "stream.finished" | "Stream.finished" => return alias("stream/promises.finished"),
688        "fs.exists" | "child_process.exec" | "child_process.execFile" => {}
689        _ => return None,
690    }
691    thread_local! {
692        static MADE: std::cell::RefCell<std::collections::HashMap<String, Value>> =
693            std::cell::RefCell::new(std::collections::HashMap::new());
694    }
695    if let Some(v) = MADE.with(|m| m.borrow().get(builtin).cloned()) {
696        return Some(Ok(v));
697    }
698    let made = (|| {
699        if builtin == "fs.exists" {
700            return run_completion(EXISTS_PROMISIFIED_SRC);
701        }
702        let factory = run_completion(CUSTOM_EXEC_SRC)?;
703        let (orig, name) = with_host(|h| {
704            let short = builtin.trim_start_matches("child_process.");
705            (h.alloc(JsObj::Builtin(builtin.into())), h.new_str(short))
706        });
707        crate::host::invoke(&factory, vec![orig, name], None)
708    })();
709    if let Ok(v) = &made {
710        MADE.with(|m| m.borrow_mut().insert(builtin.to_string(), v.clone()));
711    }
712    Some(made)
713}
714
715const CALLBACKIFY_SRC: &str = "(function(original){\n\
716  return function(){\n\
717    var self = this;\n\
718    var args = Array.prototype.slice.call(arguments);\n\
719    var cb = args.pop();\n\
720    Promise.resolve(original.apply(self, args)).then(\n\
721      function(value){ cb.call(self, null, value); },\n\
722      function(err){ cb.call(self, err || new Error('Promise was rejected with a falsy value')); }\n\
723    );\n\
724  };\n\
725})";
726
727/// `util.promisify(fn)` → a function returning a Promise that resolves with the
728/// callback's value (rejecting on its error argument).
729/// `util.aborted(signal, resource)`.
730///
731/// Resolves when `signal` aborts — immediately if it already has. The
732/// `resource` argument is REQUIRED to be an object (node validates it before
733/// looking at the signal); it only ties the promise to an async resource for
734/// tracking, which this runtime does not model, so a valid one is then ignored.
735fn aborted(signal: &Value, resource: &Value) -> Result<Value, String> {
736    if !with_host(|h| {
737        matches!(
738            h.get(resource),
739            Some(crate::host::JsObj::Object(_)) | Some(crate::host::JsObj::Array(_))
740        ) || crate::host::is_callable(h, resource)
741    }) {
742        return Err(crate::host::invalid_arg_type(
743            "resource", "argument", "object", resource,
744        ));
745    }
746    let already = crate::builtins::get_property(signal, "aborted").unwrap_or(Value::Undef);
747    if with_host(|h| h.truthy(&already)) {
748        return crate::builtins::promise_resolve_pub(Value::Undef);
749    }
750    // The listener is an ordinary `abort` handler, so it goes through the same
751    // path a script's own `signal.addEventListener('abort', …)` would — and,
752    // as in node (`signal.addEventListener('abort', resolve)`), the promise
753    // resolves WITH the abort `Event` the listener receives.
754    let (promise, resolve) = crate::builtins::pending_promise_with_resolver();
755    crate::host::call_method(
756        signal,
757        "addEventListener",
758        vec![with_host(|h| h.new_str("abort")), resolve],
759    )?;
760    Ok(promise)
761}
762
763fn promisify(args: &[Value]) -> Result<Value, String> {
764    let orig = args.first().cloned().unwrap_or(Value::Undef);
765    if !with_host(|h| crate::host::is_callable(h, &orig)) {
766        return Err(std::format!(
767            "TypeError [ERR_INVALID_ARG_TYPE]: The \"original\" argument must be of \
768             type function. Received {}",
769            super::received_desc(&orig)
770        ));
771    }
772    // The builtins node gives a custom promisified form or callback-argument
773    // names. `promisify(setTimeout)` used to wrap it as callback-last, so the
774    // `sleep = promisify(setTimeout)` idiom passed the delay as the callback.
775    let builtin = with_host(|h| match h.get(&orig) {
776        Some(JsObj::Builtin(name)) => Some(name.clone()),
777        _ => None,
778    });
779    let custom = match builtin.as_deref() {
780        Some(name) => custom_promisified(name).transpose()?,
781        None => None,
782    };
783    let arg_names: Option<&[&str]> = match builtin.as_deref() {
784        Some("fs.read") | Some("fs.readv") => Some(&["bytesRead", "buffer"]),
785        Some("fs.write") => Some(&["bytesWritten", "buffer"]),
786        Some("fs.writev") => Some(&["bytesWritten", "buffers"]),
787        Some("dns.lookup") => Some(&["address", "family"]),
788        Some("dns.lookupService") => Some(&["hostname", "service"]),
789        _ => None,
790    };
791    let (custom, names, sym) = with_host(|h| {
792        let names = match arg_names {
793            Some(list) => {
794                let items = list.iter().map(|n| h.new_str(*n)).collect();
795                h.new_array(items)
796            }
797            None => Value::Undef,
798        };
799        let sym = h.symbol_for("nodejs.util.promisify.custom");
800        (custom.unwrap_or(Value::Undef), names, sym)
801    });
802    let factory = run_completion(PROMISIFY_SRC)?;
803    let out = crate::host::invoke(&factory, vec![orig, custom, names, sym], None)?;
804    // A non-function `[util.promisify.custom]` comes back boxed in a
805    // one-element array, so the rejection can name it as node does.
806    if with_host(|h| crate::host::is_callable(h, &out)) {
807        return Ok(out);
808    }
809    let bad = crate::builtins::get_property(&out, "0")?;
810    Err(crate::host::invalid_arg_type(
811        "util.promisify.custom",
812        "property",
813        "function",
814        &bad,
815    ))
816}
817
818/// `util.callbackify(fn)` → a function taking a trailing `(err, value)` callback,
819/// invoked from the async function's resolved/rejected result.
820fn callbackify(args: &[Value]) -> Result<Value, String> {
821    let orig = args.first().cloned().unwrap_or(Value::Undef);
822    if !with_host(|h| crate::host::is_callable(h, &orig)) {
823        return Err(std::format!(
824            "TypeError [ERR_INVALID_ARG_TYPE]: The \"original\" argument must be of \
825             type function. Received {}",
826            super::received_desc(&orig)
827        ));
828    }
829    let factory = run_completion(CALLBACKIFY_SRC)?;
830    crate::host::invoke(&factory, vec![orig], None)
831}
832
833// ── debuglog ─────────────────────────────────────────────────────────────────
834
835const DEBUGLOG_ENABLED_SRC: &str = "(function(prefix){\n\
836  var util = require('util');\n\
837  return function(){\n\
838    console.error(prefix + ' ' + util.format.apply(null, arguments));\n\
839  };\n\
840})";
841
842/// `util.debuglog(section)` → a logging function gated by the `NODE_DEBUG` env var.
843/// When the section is not enabled, a no-op function is returned (Node's contract).
844fn debuglog(args: &[Value]) -> Result<Value, String> {
845    let section = super::arg_str(args, 0);
846    if debuglog_enabled(&section) {
847        let prefix = format!("{} {}:", section.to_uppercase(), std::process::id());
848        let factory = run_completion(DEBUGLOG_ENABLED_SRC)?;
849        let pfx = with_host(|h| h.new_str(prefix));
850        crate::host::invoke(&factory, vec![pfx], None)
851    } else {
852        run_completion("(function(){})")
853    }
854}
855
856/// Whether `NODE_DEBUG` enables `section` (comma/space-separated, case-insensitive,
857/// `*` wildcards allowed — matching Node's env parsing).
858fn debuglog_enabled(section: &str) -> bool {
859    let Ok(env) = std::env::var("NODE_DEBUG") else {
860        return false;
861    };
862    let sec = section.to_uppercase();
863    env.split(|c: char| c == ',' || c.is_whitespace())
864        .filter(|s| !s.is_empty())
865        .any(|pat| {
866            let pat = pat.to_uppercase();
867            if pat.contains('*') {
868                wildcard_match(&pat, &sec)
869            } else {
870                pat == sec
871            }
872        })
873}
874
875/// Minimal glob match (`*` = any run) for `NODE_DEBUG` section patterns.
876fn wildcard_match(pat: &str, s: &str) -> bool {
877    let parts: Vec<&str> = pat.split('*').collect();
878    if parts.len() == 1 {
879        return pat == s;
880    }
881    let mut pos = 0usize;
882    for (i, part) in parts.iter().enumerate() {
883        if part.is_empty() {
884            continue;
885        }
886        if i == 0 {
887            if !s[pos..].starts_with(part) {
888                return false;
889            }
890            pos += part.len();
891        } else if i == parts.len() - 1 {
892            return s[pos..].ends_with(part);
893        } else if let Some(idx) = s[pos..].find(part) {
894            pos += idx + part.len();
895        } else {
896            return false;
897        }
898    }
899    true
900}
901
902// ── stripVTControlCharacters ─────────────────────────────────────────────────
903
904/// Remove ANSI/VT escape sequences: two-char escapes, CSI (`ESC [ … final`),
905/// and OSC (`ESC ] … BEL|ST`), including the C1 CSI introducer `›`.
906pub(crate) fn strip_vt(s: &str) -> String {
907    let mut out = String::with_capacity(s.len());
908    let mut chars = s.chars().peekable();
909    while let Some(c) = chars.next() {
910        if c == '\u{9b}' {
911            // C1 CSI: consume params/intermediates until a final byte.
912            while let Some(&n) = chars.peek() {
913                chars.next();
914                if ('\u{40}'..='\u{7e}').contains(&n) {
915                    break;
916                }
917            }
918            continue;
919        }
920        if c != '\u{1b}' {
921            out.push(c);
922            continue;
923        }
924        match chars.peek() {
925            Some('[') => {
926                chars.next();
927                while let Some(&n) = chars.peek() {
928                    chars.next();
929                    if ('\u{40}'..='\u{7e}').contains(&n) {
930                        break;
931                    }
932                }
933            }
934            Some(']') => {
935                chars.next();
936                while let Some(&n) = chars.peek() {
937                    if n == '\u{7}' {
938                        chars.next();
939                        break;
940                    }
941                    if n == '\u{1b}' {
942                        chars.next();
943                        if chars.peek() == Some(&'\\') {
944                            chars.next();
945                        }
946                        break;
947                    }
948                    chars.next();
949                }
950            }
951            Some(_) => {
952                chars.next();
953            }
954            None => {}
955        }
956    }
957    out
958}
959
960// ── styleText ────────────────────────────────────────────────────────────────
961
962/// The format name(s) passed to `styleText` (a string or an array of strings).
963fn style_names(v: &Value) -> Vec<String> {
964    with_host(|h| match h.get(v) {
965        Some(JsObj::Array(items)) => items.iter().map(|x| h.str_of(x)).collect(),
966        _ => vec![h.str_of(v)],
967    })
968}
969
970/// `(open, close)` SGR parameter numbers for a `util.inspect.colors` name.
971/// `util.inspect.colors`: every SGR style name Node accepts, as
972/// `(name, open, close)`, in `Object.keys(util.inspect.colors)` order.
973///
974/// One table rather than a `match`, because `styleText`'s rejection message
975/// ENUMERATES these names and the enumeration has to come from the same source
976/// the lookup does. The old code had a `match` for the lookup and a
977/// hand-written sentence for the message, so the sentence could not go stale
978/// visibly — and it had: it said "must be a valid util.inspect.colors key",
979/// a wording no Node emits.
980pub(crate) const STYLES: &[(&str, u16, u16)] = &[
981    ("reset", 0, 0),
982    ("bold", 1, 22),
983    ("dim", 2, 22),
984    ("italic", 3, 23),
985    ("underline", 4, 24),
986    ("blink", 5, 25),
987    ("inverse", 7, 27),
988    ("hidden", 8, 28),
989    ("strikethrough", 9, 29),
990    ("doubleunderline", 21, 24),
991    ("black", 30, 39),
992    ("red", 31, 39),
993    ("green", 32, 39),
994    ("yellow", 33, 39),
995    ("blue", 34, 39),
996    ("magenta", 35, 39),
997    ("cyan", 36, 39),
998    ("white", 37, 39),
999    ("bgBlack", 40, 49),
1000    ("bgRed", 41, 49),
1001    ("bgGreen", 42, 49),
1002    ("bgYellow", 43, 49),
1003    ("bgBlue", 44, 49),
1004    ("bgMagenta", 45, 49),
1005    ("bgCyan", 46, 49),
1006    ("bgWhite", 47, 49),
1007    ("framed", 51, 54),
1008    ("overlined", 53, 55),
1009    ("gray", 90, 39),
1010    ("redBright", 91, 39),
1011    ("greenBright", 92, 39),
1012    ("yellowBright", 93, 39),
1013    ("blueBright", 94, 39),
1014    ("magentaBright", 95, 39),
1015    ("cyanBright", 96, 39),
1016    ("whiteBright", 97, 39),
1017    ("bgGray", 100, 49),
1018    ("bgRedBright", 101, 49),
1019    ("bgGreenBright", 102, 49),
1020    ("bgYellowBright", 103, 49),
1021    ("bgBlueBright", 104, 49),
1022    ("bgMagentaBright", 105, 49),
1023    ("bgCyanBright", 106, 49),
1024    ("bgWhiteBright", 107, 49),
1025];
1026
1027/// The aliases Node accepts but does not list in `inspect.colors`' own keys. It
1028/// still names them in the rejection message, after the listed keys.
1029pub(crate) const STYLE_ALIASES: &[(&str, u16, u16)] = &[
1030    ("grey", 90, 39),
1031    ("blackBright", 90, 39),
1032    ("bgGrey", 100, 49),
1033    ("bgBlackBright", 100, 49),
1034    ("faint", 2, 22),
1035    ("crossedout", 9, 29),
1036    ("strikeThrough", 9, 29),
1037    ("crossedOut", 9, 29),
1038    ("conceal", 8, 28),
1039    ("swapColors", 7, 27),
1040    ("swapcolors", 7, 27),
1041    ("doubleUnderline", 21, 24),
1042];
1043
1044/// The `(open, close)` SGR pair for a style name, or `None` if unknown.
1045fn style_codes(name: &str) -> Option<(u16, u16)> {
1046    STYLES
1047        .iter()
1048        .chain(STYLE_ALIASES.iter())
1049        .find(|(n, _, _)| *n == name)
1050        .map(|(_, o, c)| (*o, *c))
1051}
1052
1053/// `util.styleText(format, text[, { validateStream = true, stream = process.stdout }])`,
1054/// a port of `lib/util.js`. Each format's opening code goes on the left in order
1055/// and its closing code on the right in reverse, so the first is outermost; a
1056/// format's closing code inside the text is replaced by its opening code (for
1057/// the codes `bold`/`dim` share, the close is kept and the open re-applied), so
1058/// a nested `styleText` does not end the outer style early. `#RGB`/`#RRGGBB` is
1059/// a 24-bit color. With `validateStream` the stream must be a stream, and when
1060/// it would not colorize — not a TTY, or `FORCE_COLOR` disabling it — the text
1061/// comes back unstyled: piped output used to carry raw escape codes.
1062fn style_text(args: &[Value]) -> Result<Value, String> {
1063    let fmt = args.first().cloned().unwrap_or(Value::Undef);
1064    let text_v = args.get(1).cloned().unwrap_or(Value::Undef);
1065    let Some(text) = with_host(|h| h.as_str(&text_v)) else {
1066        return Err(crate::host::invalid_arg_type(
1067            "text", "argument", "string", &text_v,
1068        ));
1069    };
1070    let options = args.get(2).cloned().unwrap_or(Value::Undef);
1071    let has_options = !matches!(options, Value::Undef);
1072    if has_options && !is_plain_object_arg(&options) {
1073        return Err(crate::host::invalid_arg_type(
1074            "options", "argument", "object", &options,
1075        ));
1076    }
1077    let opt = |k: &str| -> Result<Value, String> {
1078        if has_options {
1079            crate::builtins::get_property(&options, k)
1080        } else {
1081            Ok(Value::Undef)
1082        }
1083    };
1084    let validate_stream = match opt("validateStream")? {
1085        Value::Undef => true,
1086        Value::Bool(b) => b,
1087        v => {
1088            return Err(crate::host::invalid_arg_type(
1089                "options.validateStream",
1090                "property",
1091                "boolean",
1092                &v,
1093            ))
1094        }
1095    };
1096    let mut skip_colorize = false;
1097    if validate_stream {
1098        let stream = match opt("stream")? {
1099            Value::Undef => crate::builtins::namespace_property("process", "stdout"),
1100            s => s,
1101        };
1102        if !is_stream_like(&stream)? {
1103            return Err(crate::host::coded_error(
1104                "TypeError",
1105                "ERR_INVALID_ARG_TYPE",
1106                &format!(
1107                    "The \"stream\" argument must be an instance of ReadableStream, WritableStream, or Stream. Received {}",
1108                    super::received_desc(&stream)
1109                ),
1110            ));
1111        }
1112        skip_colorize = !should_colorize(&stream)?;
1113    }
1114    let (mut open_codes, mut close_codes, mut processed) =
1115        (String::new(), String::new(), text.clone());
1116    for name in style_names(&fmt) {
1117        if name == "none" {
1118            continue;
1119        }
1120        let (open, close, keep_close) = if let Some(hex) = name.strip_prefix('#') {
1121            let Some((r, g, b)) = hex_rgb(hex) else {
1122                return Err(crate::host::coded_error(
1123                    "TypeError",
1124                    "ERR_INVALID_ARG_VALUE",
1125                    &format!(
1126                        "The argument 'format' must be a valid hex color (#RGB or #RRGGBB). Received '{name}'"
1127                    ),
1128                ));
1129            };
1130            if skip_colorize {
1131                continue;
1132            }
1133            (
1134                format!("\u{1b}[38;2;{r};{g};{b}m"),
1135                "\u{1b}[39m".to_string(),
1136                false,
1137            )
1138        } else {
1139            let (open, close) = style_codes(&name).ok_or_else(|| {
1140                // Node spells out every accepted name. Generated from the same
1141                // table the lookup reads, so a style can never be
1142                // accepted-but-unlisted.
1143                let listed: Vec<String> = STYLES
1144                    .iter()
1145                    .chain(STYLE_ALIASES.iter())
1146                    .map(|(n, _, _)| format!("'{n}'"))
1147                    .collect();
1148                crate::host::coded_error(
1149                    "TypeError",
1150                    "ERR_INVALID_ARG_VALUE",
1151                    &format!(
1152                        "The argument 'format' must be one of: {}. Received '{name}'",
1153                        listed.join(", ")
1154                    ),
1155                )
1156            })?;
1157            (
1158                format!("\u{1b}[{open}m"),
1159                format!("\u{1b}[{close}m"),
1160                close == 22,
1161            )
1162        };
1163        open_codes.push_str(&open);
1164        close_codes.insert_str(0, &close);
1165        let replacement = if keep_close {
1166            format!("{close}{open}")
1167        } else {
1168            open
1169        };
1170        processed = processed.replace(&close, &replacement);
1171    }
1172    let out = if skip_colorize {
1173        text
1174    } else {
1175        format!("{open_codes}{processed}{close_codes}")
1176    };
1177    Ok(with_host(|h| h.new_str(out)))
1178}
1179
1180/// `#RGB` / `#RRGGBB` (the part after `#`) as its three channels.
1181fn hex_rgb(hex: &str) -> Option<(u8, u8, u8)> {
1182    if !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
1183        return None;
1184    }
1185    let channel = |s: &str| u8::from_str_radix(s, 16).ok();
1186    match hex.len() {
1187        3 => {
1188            let d = |i: usize| channel(&hex[i..i + 1].repeat(2));
1189            Some((d(0)?, d(1)?, d(2)?))
1190        }
1191        6 => Some((
1192            channel(&hex[0..2])?,
1193            channel(&hex[2..4])?,
1194            channel(&hex[4..6])?,
1195        )),
1196        _ => None,
1197    }
1198}
1199
1200/// `validateObject(options, 'options')`: an object, not `null`, not an array.
1201fn is_plain_object_arg(v: &Value) -> bool {
1202    with_host(|h| {
1203        h.type_of(v) == "object" && !h.is_null(v) && !matches!(h.get(v), Some(JsObj::Array(_)))
1204    })
1205}
1206
1207/// node's `isReadableStream || isWritableStream || isNodeStream`.
1208fn is_stream_like(v: &Value) -> Result<bool, String> {
1209    if super::stream_web::is_readable_stream(v)? || super::stream_web::is_writable_stream(v)? {
1210        return Ok(true);
1211    }
1212    if !with_host(|h| matches!(h.type_of(v), "object" | "function") && !h.is_null(v)) {
1213        return Ok(false);
1214    }
1215    let get = |k: &str| crate::builtins::get_property(v, k);
1216    let truthy = |x: &Value| with_host(|h| h.truthy(x));
1217    let callable = |x: &Value| with_host(|h| crate::host::is_callable(h, x));
1218    if truthy(&get("_readableState")?) || truthy(&get("_writableState")?) {
1219        return Ok(true);
1220    }
1221    let on = callable(&get("on")?);
1222    Ok(on && (callable(&get("write")?) || callable(&get("pipe")?)))
1223}
1224
1225/// `utilColors.shouldColorize(stream)`: with `FORCE_COLOR` set, whether its
1226/// color depth exceeds 2 (`''`, `1`, `true`, `2`, `3` do); otherwise whether the
1227/// stream is a TTY whose `getColorDepth()` (when it has one) exceeds 2.
1228fn should_colorize(stream: &Value) -> Result<bool, String> {
1229    if let Ok(fc) = std::env::var("FORCE_COLOR") {
1230        return Ok(matches!(fc.as_str(), "" | "1" | "true" | "2" | "3"));
1231    }
1232    let is_tty = crate::builtins::get_property(stream, "isTTY")?;
1233    if !with_host(|h| h.truthy(&is_tty)) {
1234        return Ok(false);
1235    }
1236    let depth = crate::builtins::get_property(stream, "getColorDepth")?;
1237    if !with_host(|h| crate::host::is_callable(h, &depth)) {
1238        return Ok(true);
1239    }
1240    let d = crate::host::invoke(&depth, Vec::new(), Some(stream.clone()))?;
1241    Ok(with_host(|h| h.to_number(&d)) > 2.0)
1242}
1243
1244// ── getSystemError{Name,Message,Map} ─────────────────────────────────────────
1245// Node's system error numbers are negative libuv errnos. We resolve them through
1246// the platform's own `libc` constants so macOS/Linux each report their native
1247// numbering, and pair each with libuv's canonical (lowercase) message string.
1248
1249/// `(name, platform errno, libuv message)` for the common POSIX errors. Only
1250/// constants present on every supported Unix target are listed (cross-platform).
1251const ERRNO_TABLE: &[(&str, i32, &str)] = &[
1252    ("E2BIG", libc::E2BIG, "argument list too long"),
1253    ("EACCES", libc::EACCES, "permission denied"),
1254    ("EADDRINUSE", libc::EADDRINUSE, "address already in use"),
1255    (
1256        "EADDRNOTAVAIL",
1257        libc::EADDRNOTAVAIL,
1258        "address not available",
1259    ),
1260    (
1261        "EAFNOSUPPORT",
1262        libc::EAFNOSUPPORT,
1263        "address family not supported",
1264    ),
1265    ("EAGAIN", libc::EAGAIN, "resource temporarily unavailable"),
1266    ("EALREADY", libc::EALREADY, "connection already in progress"),
1267    ("EBADF", libc::EBADF, "bad file descriptor"),
1268    ("EBUSY", libc::EBUSY, "resource busy or locked"),
1269    ("ECANCELED", libc::ECANCELED, "operation canceled"),
1270    (
1271        "ECONNABORTED",
1272        libc::ECONNABORTED,
1273        "software caused connection abort",
1274    ),
1275    ("ECONNREFUSED", libc::ECONNREFUSED, "connection refused"),
1276    ("ECONNRESET", libc::ECONNRESET, "connection reset by peer"),
1277    (
1278        "EDESTADDRREQ",
1279        libc::EDESTADDRREQ,
1280        "destination address required",
1281    ),
1282    ("EEXIST", libc::EEXIST, "file already exists"),
1283    (
1284        "EFAULT",
1285        libc::EFAULT,
1286        "bad address in system call argument",
1287    ),
1288    ("EFBIG", libc::EFBIG, "file too large"),
1289    ("EHOSTDOWN", libc::EHOSTDOWN, "host is down"),
1290    ("EHOSTUNREACH", libc::EHOSTUNREACH, "host is unreachable"),
1291    ("EINTR", libc::EINTR, "interrupted system call"),
1292    ("EINVAL", libc::EINVAL, "invalid argument"),
1293    ("EIO", libc::EIO, "i/o error"),
1294    ("EISCONN", libc::EISCONN, "socket is already connected"),
1295    ("EISDIR", libc::EISDIR, "illegal operation on a directory"),
1296    ("ELOOP", libc::ELOOP, "too many symbolic links encountered"),
1297    ("EMFILE", libc::EMFILE, "too many open files"),
1298    ("EMLINK", libc::EMLINK, "too many links"),
1299    ("EMSGSIZE", libc::EMSGSIZE, "message too long"),
1300    ("ENAMETOOLONG", libc::ENAMETOOLONG, "name too long"),
1301    ("ENETDOWN", libc::ENETDOWN, "network is down"),
1302    ("ENETUNREACH", libc::ENETUNREACH, "network is unreachable"),
1303    ("ENFILE", libc::ENFILE, "file table overflow"),
1304    ("ENOBUFS", libc::ENOBUFS, "no buffer space available"),
1305    ("ENODEV", libc::ENODEV, "no such device"),
1306    ("ENOENT", libc::ENOENT, "no such file or directory"),
1307    ("ENOMEM", libc::ENOMEM, "not enough memory"),
1308    ("ENOPROTOOPT", libc::ENOPROTOOPT, "protocol not available"),
1309    ("ENOSPC", libc::ENOSPC, "no space left on device"),
1310    ("ENOSYS", libc::ENOSYS, "function not implemented"),
1311    ("ENOTCONN", libc::ENOTCONN, "socket is not connected"),
1312    ("ENOTDIR", libc::ENOTDIR, "not a directory"),
1313    ("ENOTEMPTY", libc::ENOTEMPTY, "directory not empty"),
1314    ("ENOTSOCK", libc::ENOTSOCK, "socket operation on non-socket"),
1315    ("ENXIO", libc::ENXIO, "no such device or address"),
1316    (
1317        "EOPNOTSUPP",
1318        libc::EOPNOTSUPP,
1319        "operation not supported on socket",
1320    ),
1321    (
1322        "EOVERFLOW",
1323        libc::EOVERFLOW,
1324        "value too large for defined data type",
1325    ),
1326    ("EPERM", libc::EPERM, "operation not permitted"),
1327    ("EPIPE", libc::EPIPE, "broken pipe"),
1328    ("EPROTO", libc::EPROTO, "protocol error"),
1329    (
1330        "EPROTONOSUPPORT",
1331        libc::EPROTONOSUPPORT,
1332        "protocol not supported",
1333    ),
1334    (
1335        "EPROTOTYPE",
1336        libc::EPROTOTYPE,
1337        "protocol wrong type for socket",
1338    ),
1339    ("ERANGE", libc::ERANGE, "result too large"),
1340    ("EROFS", libc::EROFS, "read-only file system"),
1341    (
1342        "ESHUTDOWN",
1343        libc::ESHUTDOWN,
1344        "cannot send after transport endpoint shutdown",
1345    ),
1346    ("ESPIPE", libc::ESPIPE, "invalid seek"),
1347    ("ESRCH", libc::ESRCH, "no such process"),
1348    ("ETIMEDOUT", libc::ETIMEDOUT, "connection timed out"),
1349    ("ETXTBSY", libc::ETXTBSY, "text file is busy"),
1350    ("EXDEV", libc::EXDEV, "cross-device link not permitted"),
1351];
1352
1353/// Normalize a `getSystemError*` argument (a negative libuv errno) to a positive
1354/// platform errno for table lookup.
1355fn errno_of(err: f64) -> i32 {
1356    if err < 0.0 {
1357        (-err) as i32
1358    } else {
1359        err as i32
1360    }
1361}
1362
1363pub(crate) fn errno_name(e: i32) -> Option<&'static str> {
1364    ERRNO_TABLE
1365        .iter()
1366        .find(|(_, code, _)| *code == e)
1367        .map(|(n, _, _)| *n)
1368}
1369
1370fn errno_message(e: i32) -> Option<&'static str> {
1371    ERRNO_TABLE
1372        .iter()
1373        .find(|(_, code, _)| *code == e)
1374        .map(|(_, _, m)| *m)
1375}
1376
1377/// The platform errno number and libuv message for an error CODE (`EBADF` →
1378/// `(9, "bad file descriptor")`), from the same table `util.getSystemErrorMap`
1379/// reports.
1380pub(crate) fn errno_by_name(name: &str) -> Option<(i32, &'static str)> {
1381    ERRNO_TABLE
1382        .iter()
1383        .find(|(n, _, _)| *n == name)
1384        .map(|(_, code, m)| (*code, *m))
1385}
1386
1387/// `util.getSystemErrorMap()` → a `Map` of negative errno → `[name, message]`.
1388fn system_error_map() -> Value {
1389    with_host(|h| {
1390        let mut entries = indexmap::IndexMap::new();
1391        for (name, code, msg) in ERRNO_TABLE {
1392            let key_val = Value::Float(-(*code as f64));
1393            let name_v = h.new_str(*name);
1394            let msg_v = h.new_str(*msg);
1395            let pair = h.new_array(vec![name_v, msg_v]);
1396            let key = crate::host::map_key(h, &key_val);
1397            entries.insert(key, (key_val, pair));
1398        }
1399        h.alloc(JsObj::Map {
1400            entries,
1401            weak: false,
1402        })
1403    })
1404}
1405
1406// ── parseArgs ────────────────────────────────────────────────────────────────
1407
1408/// A port of node's `lib/internal/util/parse_args/parse_args.js` and
1409/// `utils.js` (v26.12.0), with the primordials spelled as ordinary method
1410/// calls. It runs as JavaScript because it IS JavaScript in node: the token
1411/// stream (`tokens: true`), the order every validation and usage check runs
1412/// in, and the `__proto__`/null-prototype handling all fall out of the same
1413/// code. The errors node's `internal/errors` would construct are raised by
1414/// `fail` (`util.@@nodeError`, below), so they carry node's codes and
1415/// wording.
1416const PARSE_ARGS_SRC: &str = r#"(function (fail, evalMode) {
1417'use strict';
1418const ObjectHasOwn = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
1419const uncurry = (f) => (self, ...args) => Reflect.apply(f, self, args);
1420const StringPrototypeCharAt = uncurry(String.prototype.charAt);
1421const StringPrototypeIncludes = uncurry(String.prototype.includes);
1422const StringPrototypeIndexOf = uncurry(String.prototype.indexOf);
1423const StringPrototypeSlice = uncurry(String.prototype.slice);
1424const StringPrototypeStartsWith = uncurry(String.prototype.startsWith);
1425function ERR_INVALID_ARG_TYPE(name, expected, value) { fail('type', name, expected, value); }
1426function ERR_INVALID_ARG_VALUE(name, value, reason) { fail('value', name, value, reason); }
1427function ERR_PARSE_ARGS_INVALID_OPTION_VALUE(message) { fail('code', 'ERR_PARSE_ARGS_INVALID_OPTION_VALUE', message); }
1428function ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL(value) {
1429  fail('code', 'ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL', `Unexpected argument '${value}'. This command does not take positional arguments`);
1430}
1431function ERR_PARSE_ARGS_UNKNOWN_OPTION(option, allowPositionals) {
1432  const suggestDashDash = allowPositionals ? '. To specify a positional ' +
1433    "argument starting with a '-', place it at the end of the command after " +
1434    `'--', as in '-- ${JSON.stringify(option)}` : '';
1435  fail('code', 'ERR_PARSE_ARGS_UNKNOWN_OPTION', `Unknown option '${option}'${suggestDashDash}`);
1436}
1437
1438// internal/validators
1439function validateObject(value, name) {
1440  if (value === null || Array.isArray(value)) throw new ERR_INVALID_ARG_TYPE(name, 'Object', value);
1441  if (typeof value !== 'object') throw new ERR_INVALID_ARG_TYPE(name, 'Object', value);
1442}
1443function validateArray(value, name, minLength = 0) {
1444  if (!Array.isArray(value)) throw new ERR_INVALID_ARG_TYPE(name, 'Array', value);
1445  if (value.length < minLength) throw new ERR_INVALID_ARG_VALUE(name, value, `must be longer than ${minLength}`);
1446}
1447function validateString(value, name) {
1448  if (typeof value !== 'string') throw new ERR_INVALID_ARG_TYPE(name, 'string', value);
1449}
1450function validateBoolean(value, name) {
1451  if (typeof value !== 'boolean') throw new ERR_INVALID_ARG_TYPE(name, 'boolean', value);
1452}
1453function validateStringArray(value, name) {
1454  validateArray(value, name);
1455  for (let i = 0; i < value.length; ++i) validateString(value[i], `${name}[${i}]`);
1456}
1457function validateBooleanArray(value, name) {
1458  validateArray(value, name);
1459  for (let i = 0; i < value.length; ++i) validateBoolean(value[i], `${name}[${i}]`);
1460}
1461function validateUnion(value, name, union) {
1462  if (!union.includes(value)) throw new ERR_INVALID_ARG_TYPE(name, `('${union.join('|')}')`, value);
1463}
1464
1465// internal/util/parse_args/utils
1466function objectGetOwn(obj, prop) {
1467  if (ObjectHasOwn(obj, prop))
1468    return obj[prop];
1469}
1470function optionsGetOwn(options, longOption, prop) {
1471  if (ObjectHasOwn(options, longOption))
1472    return objectGetOwn(options[longOption], prop);
1473}
1474function isOptionValue(value) {
1475  if (value == null) return false;
1476  return true; // greedy!
1477}
1478function isOptionLikeValue(value) {
1479  if (value == null) return false;
1480  return value.length > 1 && StringPrototypeCharAt(value, 0) === '-';
1481}
1482function isLoneShortOption(arg) {
1483  return arg.length === 2 && StringPrototypeCharAt(arg, 0) === '-' && StringPrototypeCharAt(arg, 1) !== '-';
1484}
1485function isLoneLongOption(arg) {
1486  return arg.length > 2 && StringPrototypeStartsWith(arg, '--') && !StringPrototypeIncludes(arg, '=', 3);
1487}
1488function isLongOptionAndValue(arg) {
1489  return arg.length > 2 && StringPrototypeStartsWith(arg, '--') && StringPrototypeIncludes(arg, '=', 3);
1490}
1491function isShortOptionGroup(arg, options) {
1492  if (arg.length <= 2) return false;
1493  if (StringPrototypeCharAt(arg, 0) !== '-') return false;
1494  if (StringPrototypeCharAt(arg, 1) === '-') return false;
1495  const firstShort = StringPrototypeCharAt(arg, 1);
1496  const longOption = findLongOptionForShort(firstShort, options);
1497  return optionsGetOwn(options, longOption, 'type') !== 'string';
1498}
1499function isShortOptionAndValue(arg, options) {
1500  validateObject(options, 'options');
1501  if (arg.length <= 2) return false;
1502  if (StringPrototypeCharAt(arg, 0) !== '-') return false;
1503  if (StringPrototypeCharAt(arg, 1) === '-') return false;
1504  const shortOption = StringPrototypeCharAt(arg, 1);
1505  const longOption = findLongOptionForShort(shortOption, options);
1506  return optionsGetOwn(options, longOption, 'type') === 'string';
1507}
1508function findLongOptionForShort(shortOption, options) {
1509  validateObject(options, 'options');
1510  const longOptionEntry = Object.entries(options).find(
1511    ({ 1: optionConfig }) => objectGetOwn(optionConfig, 'short') === shortOption,
1512  );
1513  return longOptionEntry?.[0] ?? shortOption;
1514}
1515function useDefaultValueOption(longOption, optionConfig, values) {
1516  return objectGetOwn(optionConfig, 'default') !== undefined &&
1517    values[longOption] === undefined;
1518}
1519
1520// internal/util/parse_args/parse_args
1521function getMainArgs() {
1522  if (evalMode) return process.argv.slice(1);
1523  return process.argv.slice(2);
1524}
1525function checkOptionLikeValue(token) {
1526  if (!token.inlineValue && isOptionLikeValue(token.value)) {
1527    const example = StringPrototypeStartsWith(token.rawName, '--') ?
1528      `'${token.rawName}=-XYZ'` :
1529      `'--${token.name}=-XYZ' or '${token.rawName}-XYZ'`;
1530    const errorMessage = `Option '${token.rawName}' argument is ambiguous.
1531Did you forget to specify the option argument for '${token.rawName}'?
1532To specify an option argument starting with a dash use ${example}.`;
1533    throw new ERR_PARSE_ARGS_INVALID_OPTION_VALUE(errorMessage);
1534  }
1535}
1536function checkOptionUsage(config, token) {
1537  let tokenName = token.name;
1538  if (!ObjectHasOwn(config.options, tokenName)) {
1539    if (config.allowNegative && StringPrototypeStartsWith(tokenName, 'no-')) {
1540      tokenName = StringPrototypeSlice(tokenName, 3);
1541      if (!ObjectHasOwn(config.options, tokenName) || optionsGetOwn(config.options, tokenName, 'type') !== 'boolean') {
1542        throw new ERR_PARSE_ARGS_UNKNOWN_OPTION(token.rawName, config.allowPositionals);
1543      }
1544    } else {
1545      throw new ERR_PARSE_ARGS_UNKNOWN_OPTION(token.rawName, config.allowPositionals);
1546    }
1547  }
1548  const short = optionsGetOwn(config.options, tokenName, 'short');
1549  const shortAndLong = `${short ? `-${short}, ` : ''}--${tokenName}`;
1550  const type = optionsGetOwn(config.options, tokenName, 'type');
1551  if (type === 'string' && typeof token.value !== 'string') {
1552    throw new ERR_PARSE_ARGS_INVALID_OPTION_VALUE(`Option '${shortAndLong} <value>' argument missing`);
1553  }
1554  if (type === 'boolean' && token.value != null) {
1555    throw new ERR_PARSE_ARGS_INVALID_OPTION_VALUE(`Option '${shortAndLong}' does not take an argument`);
1556  }
1557}
1558function storeOption(token, options, values, allowNegative) {
1559  let longOption = token.name;
1560  let optionValue = token.value;
1561  if (longOption === '__proto__') {
1562    return;
1563  }
1564  if (allowNegative && StringPrototypeStartsWith(longOption, 'no-') && optionValue === undefined) {
1565    longOption = StringPrototypeSlice(longOption, 3);
1566    token.name = longOption;
1567    optionValue = false;
1568  }
1569  const newValue = optionValue ?? true;
1570  if (optionsGetOwn(options, longOption, 'multiple')) {
1571    if (values[longOption]) {
1572      values[longOption].push(newValue);
1573    } else {
1574      values[longOption] = [newValue];
1575    }
1576  } else {
1577    values[longOption] = newValue;
1578  }
1579}
1580function storeDefaultOption(longOption, optionValue, values) {
1581  if (longOption === '__proto__') {
1582    return;
1583  }
1584  values[longOption] = optionValue;
1585}
1586function argsToTokens(args, options) {
1587  const tokens = [];
1588  let index = -1;
1589  let groupCount = 0;
1590  const remainingArgs = args.slice();
1591  while (remainingArgs.length > 0) {
1592    const arg = remainingArgs.shift();
1593    const nextArg = remainingArgs[0];
1594    if (groupCount > 0)
1595      groupCount--;
1596    else
1597      index++;
1598    if (arg === '--') {
1599      tokens.push({ kind: 'option-terminator', index });
1600      tokens.push(...remainingArgs.map((arg) => {
1601        return { kind: 'positional', index: ++index, value: arg };
1602      }));
1603      break;
1604    }
1605    if (isLoneShortOption(arg)) {
1606      const shortOption = StringPrototypeCharAt(arg, 1);
1607      const longOption = findLongOptionForShort(shortOption, options);
1608      let value;
1609      let inlineValue;
1610      if (optionsGetOwn(options, longOption, 'type') === 'string' &&
1611          isOptionValue(nextArg)) {
1612        value = remainingArgs.shift();
1613        inlineValue = false;
1614      }
1615      tokens.push({ kind: 'option', name: longOption, rawName: arg, index, value, inlineValue });
1616      if (value != null) ++index;
1617      continue;
1618    }
1619    if (isShortOptionGroup(arg, options)) {
1620      const expanded = [];
1621      for (let index = 1; index < arg.length; index++) {
1622        const shortOption = StringPrototypeCharAt(arg, index);
1623        const longOption = findLongOptionForShort(shortOption, options);
1624        if (optionsGetOwn(options, longOption, 'type') !== 'string' ||
1625          index === arg.length - 1) {
1626          expanded.push(`-${shortOption}`);
1627        } else {
1628          expanded.push(`-${StringPrototypeSlice(arg, index)}`);
1629          break;
1630        }
1631      }
1632      remainingArgs.unshift(...expanded);
1633      groupCount = expanded.length;
1634      continue;
1635    }
1636    if (isShortOptionAndValue(arg, options)) {
1637      const shortOption = StringPrototypeCharAt(arg, 1);
1638      const longOption = findLongOptionForShort(shortOption, options);
1639      const value = StringPrototypeSlice(arg, 2);
1640      tokens.push({ kind: 'option', name: longOption, rawName: `-${shortOption}`, index, value, inlineValue: true });
1641      continue;
1642    }
1643    if (isLoneLongOption(arg)) {
1644      const longOption = StringPrototypeSlice(arg, 2);
1645      let value;
1646      let inlineValue;
1647      if (optionsGetOwn(options, longOption, 'type') === 'string' &&
1648          isOptionValue(nextArg)) {
1649        value = remainingArgs.shift();
1650        inlineValue = false;
1651      }
1652      tokens.push({ kind: 'option', name: longOption, rawName: arg, index, value, inlineValue });
1653      if (value != null) ++index;
1654      continue;
1655    }
1656    if (isLongOptionAndValue(arg)) {
1657      const equalIndex = StringPrototypeIndexOf(arg, '=');
1658      const longOption = StringPrototypeSlice(arg, 2, equalIndex);
1659      const value = StringPrototypeSlice(arg, equalIndex + 1);
1660      tokens.push({ kind: 'option', name: longOption, rawName: `--${longOption}`, index, value, inlineValue: true });
1661      continue;
1662    }
1663    tokens.push({ kind: 'positional', index, value: arg });
1664  }
1665  return tokens;
1666}
1667const parseArgs = (config = {}) => {
1668  const args = objectGetOwn(config, 'args') ?? getMainArgs();
1669  const strict = objectGetOwn(config, 'strict') ?? true;
1670  const allowPositionals = objectGetOwn(config, 'allowPositionals') ?? !strict;
1671  const returnTokens = objectGetOwn(config, 'tokens') ?? false;
1672  const allowNegative = objectGetOwn(config, 'allowNegative') ?? false;
1673  const options = objectGetOwn(config, 'options') ?? { __proto__: null };
1674  const parseConfig = { args, strict, options, allowPositionals, allowNegative };
1675  validateArray(args, 'args');
1676  validateBoolean(strict, 'strict');
1677  validateBoolean(allowPositionals, 'allowPositionals');
1678  validateBoolean(returnTokens, 'tokens');
1679  validateBoolean(allowNegative, 'allowNegative');
1680  validateObject(options, 'options');
1681  Object.entries(options).forEach(
1682    ({ 0: longOption, 1: optionConfig }) => {
1683      validateObject(optionConfig, `options.${longOption}`);
1684      const optionType = objectGetOwn(optionConfig, 'type');
1685      validateUnion(optionType, `options.${longOption}.type`, ['string', 'boolean']);
1686      if (ObjectHasOwn(optionConfig, 'short')) {
1687        const shortOption = optionConfig.short;
1688        validateString(shortOption, `options.${longOption}.short`);
1689        if (shortOption.length !== 1) {
1690          throw new ERR_INVALID_ARG_VALUE(
1691            `options.${longOption}.short`,
1692            shortOption,
1693            'must be a single character',
1694          );
1695        }
1696      }
1697      const multipleOption = objectGetOwn(optionConfig, 'multiple');
1698      if (ObjectHasOwn(optionConfig, 'multiple')) {
1699        validateBoolean(multipleOption, `options.${longOption}.multiple`);
1700      }
1701      const defaultValue = objectGetOwn(optionConfig, 'default');
1702      if (defaultValue !== undefined) {
1703        let validator;
1704        switch (optionType) {
1705          case 'string':
1706            validator = multipleOption ? validateStringArray : validateString;
1707            break;
1708          case 'boolean':
1709            validator = multipleOption ? validateBooleanArray : validateBoolean;
1710            break;
1711        }
1712        validator(defaultValue, `options.${longOption}.default`);
1713      }
1714    },
1715  );
1716  const tokens = argsToTokens(args, options);
1717  const result = {
1718    values: { __proto__: null },
1719    positionals: [],
1720  };
1721  if (returnTokens) {
1722    result.tokens = tokens;
1723  }
1724  tokens.forEach((token) => {
1725    if (token.kind === 'option') {
1726      if (strict) {
1727        checkOptionUsage(parseConfig, token);
1728        checkOptionLikeValue(token);
1729      }
1730      storeOption(token, options, result.values, parseConfig.allowNegative);
1731    } else if (token.kind === 'positional') {
1732      if (!allowPositionals) {
1733        throw new ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL(token.value);
1734      }
1735      result.positionals.push(token.value);
1736    }
1737  });
1738  Object.entries(options).forEach(({ 0: longOption, 1: optionConfig }) => {
1739    const mustSetDefault = useDefaultValueOption(longOption, optionConfig, result.values);
1740    if (mustSetDefault) {
1741      storeDefaultOption(longOption, objectGetOwn(optionConfig, 'default'), result.values);
1742    }
1743  });
1744  return result;
1745};
1746return parseArgs;
1747})"#;
1748
1749/// `util.parseArgs(config)`: the cached port above, called with `config`.
1750fn parse_args(args: &[Value]) -> Result<Value, String> {
1751    thread_local! {
1752        static PARSER: std::cell::RefCell<Option<Value>> = const { std::cell::RefCell::new(None) };
1753    }
1754    let parser = match PARSER.with(|p| p.borrow().clone()) {
1755        Some(p) => p,
1756        None => {
1757            let factory = run_completion(PARSE_ARGS_SRC)?;
1758            let fail = with_host(|h| h.alloc(JsObj::Builtin("util.@@nodeError".into())));
1759            let eval_mode = Value::Bool(super::process::eval_entry());
1760            let made = crate::host::invoke(&factory, vec![fail, eval_mode], None)?;
1761            PARSER.with(|p| *p.borrow_mut() = Some(made.clone()));
1762            made
1763        }
1764    };
1765    let config = args.first().cloned().unwrap_or(Value::Undef);
1766    crate::host::invoke(&parser, vec![config], None)
1767}
1768
1769/// `util.@@nodeError(kind, …)`: the errors node's `internal/errors` builds,
1770/// for the JavaScript ports (`parseArgs`, `FileHandle`) to throw. `kind` is
1771/// `type` (`ERR_INVALID_ARG_TYPE`, given the validator's expected-type
1772/// spelling), `value` (`ERR_INVALID_ARG_VALUE`) or `code` (any code, as a
1773/// `TypeError`, with its finished message) or `range` (`ERR_OUT_OF_RANGE`). Always
1774/// throws. A `:<Class>` suffix on `value`, `code` or `error` names the error
1775/// class, as node's `ERR_INVALID_ARG_VALUE.RangeError` does
1776/// (`value:RangeError`, `code:RangeError`).
1777fn node_error(args: &[Value]) -> Result<Value, String> {
1778    let arg = |i: usize| args.get(i).cloned().unwrap_or(Value::Undef);
1779    let kind_arg = super::arg_str(args, 0);
1780    let (kind, class) = kind_arg.split_once(':').unwrap_or((kind_arg.as_str(), ""));
1781    let class_or = |default: &str| {
1782        if class.is_empty() {
1783            default.to_string()
1784        } else {
1785            class.to_string()
1786        }
1787    };
1788    let name = super::arg_str(args, 1);
1789    // `ERR_INVALID_ARG_TYPE` / `ERR_INVALID_ARG_VALUE` call a dotted name a
1790    // property and anything else an argument.
1791    let noun = if name.contains('.') {
1792        "property"
1793    } else {
1794        "argument"
1795    };
1796    Err(match kind {
1797        "type" => {
1798            let spec = super::arg_str(args, 2);
1799            let expected = match spec.as_str() {
1800                "Array" => "an instance of Array".to_string(),
1801                "Object" => "of type object".to_string(),
1802                // A finished phrase (`('a|b')`, `an instance of Buffer, …`).
1803                s if s.starts_with('(') || s.contains(' ') => s.to_string(),
1804                s => format!("of type {s}"),
1805            };
1806            crate::host::coded_error(
1807                "TypeError",
1808                "ERR_INVALID_ARG_TYPE",
1809                &format!(
1810                    "The \"{name}\" {noun} must be {expected}. Received {}",
1811                    super::received_desc(&arg(3))
1812                ),
1813            )
1814        }
1815        "value" => {
1816            let mut shown = crate::host::inspect_js(&arg(2))?;
1817            if shown.chars().count() > 128 {
1818                shown = format!("{}...", shown.chars().take(128).collect::<String>());
1819            }
1820            let reason = match arg(3) {
1821                Value::Undef => "is invalid".to_string(),
1822                v => with_host(|h| h.str_of(&v)),
1823            };
1824            crate::host::coded_error(
1825                &class_or("TypeError"),
1826                "ERR_INVALID_ARG_VALUE",
1827                &format!("The {noun} '{name}' {reason}. Received {shown}"),
1828            )
1829        }
1830        // `ERR_OUT_OF_RANGE(name, must, value)` for a numeric value.
1831        "range" => {
1832            let n = with_host(|h| h.to_number(&arg(3)));
1833            super::out_of_range(&name, &super::arg_str(args, 2), n)
1834        }
1835        // A code node raises as a plain `Error` (`ERR_INVALID_STATE`).
1836        "error" => crate::host::coded_error(&class_or("Error"), &name, &super::arg_str(args, 2)),
1837        _ => crate::host::coded_error(&class_or("TypeError"), &name, &super::arg_str(args, 2)),
1838    })
1839}
1840
1841// ── parseEnv ─────────────────────────────────────────────────────────────────
1842// Faithful port of Node's C++ `Dotenv::ParseContent` (src/node_dotenv.cc): CRLF
1843// normalization, `#`/blank-line skipping, `export ` prefix stripping, single /
1844// double / backtick quotes (`\n` expanded only inside double quotes), unquoted
1845// inline `#` comments, unterminated quotes, and last-wins on duplicate keys.
1846// Node emits the keys sorted, so we `sort_keys` before materializing.
1847
1848/// Trim ASCII whitespace (space, tab, newline) from both ends, matching Node's
1849/// `trim_spaces` (which trims only `" \t\n"`).
1850fn env_trim(s: &str) -> &str {
1851    s.trim_matches(|c: char| c == ' ' || c == '\t' || c == '\n')
1852}
1853
1854/// `util.parseEnv(content)` → an object of parsed `KEY=VALUE` assignments.
1855fn parse_env(input: &str) -> Value {
1856    let lines = input.replace('\r', "");
1857    let mut pairs: IndexMap<String, String> = IndexMap::new();
1858    let mut content: &str = env_trim(&lines);
1859
1860    while !content.is_empty() {
1861        let first = content.as_bytes()[0];
1862        // Skip blank lines and full-line comments.
1863        if first == b'\n' || first == b'#' {
1864            match content.find('\n') {
1865                Some(nl) => content = &content[nl + 1..],
1866                None => content = "",
1867            }
1868            continue;
1869        }
1870        // Next `=` or newline: a newline first means the line has no assignment.
1871        let Some(eq_or_nl) = content.find(['=', '\n']) else {
1872            break;
1873        };
1874        if content.as_bytes()[eq_or_nl] == b'\n' {
1875            content = env_trim(&content[eq_or_nl + 1..]);
1876            continue;
1877        }
1878        // Key up to `=`.
1879        let mut key = env_trim(&content[..eq_or_nl]);
1880        content = &content[eq_or_nl + 1..];
1881        // `KEY=` (empty value).
1882        if content.is_empty() || content.as_bytes()[0] == b'\n' {
1883            pairs.insert(key.to_string(), String::new());
1884            continue;
1885        }
1886        content = env_trim(content);
1887        // Skip empty keys (`=value`, `"   "=value`).
1888        if key.is_empty() {
1889            continue;
1890        }
1891        // `export ` prefix.
1892        if let Some(rest) = key.strip_prefix("export ") {
1893            key = env_trim(rest);
1894        }
1895        if content.is_empty() {
1896            pairs.insert(key.to_string(), String::new());
1897            break;
1898        }
1899        let vfirst = content.as_bytes()[0];
1900        // Double-quoted value: expand literal `\n`, may span raw newlines.
1901        if vfirst == b'"' {
1902            if let Some(rel) = content[1..].find('"') {
1903                let closing = rel + 1;
1904                let value = content[1..closing].replace("\\n", "\n");
1905                pairs.insert(key.to_string(), value);
1906                match content[closing + 1..].find('\n') {
1907                    Some(nl) => content = &content[closing + 1 + nl + 1..],
1908                    None => content = "",
1909                }
1910                continue;
1911            }
1912            // No closing quote — fall through to the generic quote handler.
1913        }
1914        // Single / double / backtick quoted value (no escape expansion).
1915        if vfirst == b'\'' || vfirst == b'"' || vfirst == b'`' {
1916            match content[1..].find(vfirst as char) {
1917                None => match content.find('\n') {
1918                    Some(nl) => {
1919                        pairs.insert(key.to_string(), content[..nl].to_string());
1920                        content = &content[nl + 1..];
1921                    }
1922                    None => {
1923                        pairs.insert(key.to_string(), content.to_string());
1924                        break;
1925                    }
1926                },
1927                Some(rel) => {
1928                    let closing = rel + 1;
1929                    pairs.insert(key.to_string(), content[1..closing].to_string());
1930                    match content[closing + 1..].find('\n') {
1931                        Some(nl) => content = &content[closing + 1 + nl + 1..],
1932                        None => content = "",
1933                    }
1934                    continue;
1935                }
1936            }
1937        } else {
1938            // Unquoted value: up to the newline, `#` starts an inline comment, trim.
1939            let (raw, next) = match content.find('\n') {
1940                Some(nl) => (&content[..nl], &content[nl + 1..]),
1941                None => (content, ""),
1942            };
1943            let value = match raw.find('#') {
1944                Some(h) => &raw[..h],
1945                None => raw,
1946            };
1947            pairs.insert(key.to_string(), env_trim(value).to_string());
1948            content = next;
1949        }
1950        content = env_trim(content);
1951    }
1952
1953    pairs.sort_keys();
1954    with_host(|h| {
1955        let mut m = IndexMap::new();
1956        for (k, v) in pairs {
1957            let val = h.new_str(v);
1958            m.insert(k, val);
1959        }
1960        h.new_object(m)
1961    })
1962}
1963
1964// ── MIMEType / MIMEParams ────────────────────────────────────────────────────
1965// Faithful port of Node's `lib/internal/mime.js`. A `MIMEType` is a native object
1966// tagged `@@native = "MIMEType"` with `type`/`subtype`/`essence` data properties
1967// and a `params` `MIMEParams` instance; a `MIMEParams` is tagged `@@native =
1968// "MIMEParams"` with its ordered unique `(name, value)` pairs in a hidden
1969// `@@pairs` array (mirrors the URLSearchParams representation).
1970
1971/// An HTTP token code point (`NOT_HTTP_TOKEN_CODE_POINT` inverse).
1972fn is_token_char(c: char) -> bool {
1973    c.is_ascii_alphanumeric()
1974        || matches!(
1975            c,
1976            '!' | '#'
1977                | '$'
1978                | '%'
1979                | '&'
1980                | '\''
1981                | '*'
1982                | '+'
1983                | '-'
1984                | '.'
1985                | '^'
1986                | '_'
1987                | '`'
1988                | '|'
1989                | '~'
1990        )
1991}
1992
1993/// An HTTP quoted-string code point (`NOT_HTTP_QUOTED_STRING_CODE_POINT` inverse):
1994/// tab, printable ASCII, and Latin-1 supplement.
1995fn is_quoted_string_char(c: char) -> bool {
1996    c == '\t' || ('\u{20}'..='\u{7e}').contains(&c) || ('\u{80}'..='\u{ff}').contains(&c)
1997}
1998
1999/// HTTP whitespace (`\r \n \t space`).
2000fn is_http_ws(c: char) -> bool {
2001    matches!(c, '\r' | '\n' | '\t' | ' ')
2002}
2003
2004/// Lowercase only ASCII `A-Z`, leaving other code points intact (Node's
2005/// `toASCIILower`).
2006fn ascii_lower(s: &str) -> String {
2007    s.to_ascii_lowercase()
2008}
2009
2010/// Build the `TypeError [ERR_INVALID_MIME_SYNTAX]` message (with the offending
2011/// index when known).
2012fn mime_syntax_err(part: &str, s: &str, index: Option<usize>) -> String {
2013    match index {
2014        Some(i) => format!(
2015            "TypeError [ERR_INVALID_MIME_SYNTAX]: The MIME syntax for a {part} in \"{s}\" is invalid at {i}"
2016        ),
2017        None => format!(
2018            "TypeError [ERR_INVALID_MIME_SYNTAX]: The MIME syntax for a {part} in \"{s}\" is invalid"
2019        ),
2020    }
2021}
2022
2023/// Parse `type/subtype` off the front of a MIME string; returns
2024/// `(type, subtype, remaining-params-string)`.
2025fn parse_type_and_subtype(s: &str) -> Result<(String, String, String), String> {
2026    let chars: Vec<char> = s.chars().collect();
2027    let n = chars.len();
2028    // Skip leading HTTP whitespace.
2029    let mut pos = 0;
2030    while pos < n && is_http_ws(chars[pos]) {
2031        pos += 1;
2032    }
2033    // Read the type up to `/`.
2034    let type_end = (pos..n).find(|&i| chars[i] == '/');
2035    let trimmed_type: String = match type_end {
2036        Some(e) => chars[pos..e].iter().collect(),
2037        None => chars[pos..].iter().collect(),
2038    };
2039    let type_invalid = trimmed_type.chars().position(|c| !is_token_char(c));
2040    if trimmed_type.is_empty() || type_invalid.is_some() || type_end.is_none() {
2041        return Err(mime_syntax_err("type", s, type_invalid));
2042    }
2043    let type_end = type_end.unwrap();
2044    pos = type_end + 1;
2045    let mime_type = ascii_lower(&trimmed_type);
2046    // Read the subtype up to `;`.
2047    let sub_end = (pos..n).find(|&i| chars[i] == ';');
2048    let raw_subtype: &[char] = match sub_end {
2049        Some(e) => &chars[pos..e],
2050        None => &chars[pos..],
2051    };
2052    let mut new_pos = pos + raw_subtype.len();
2053    if sub_end.is_some() {
2054        new_pos += 1;
2055    }
2056    // Trim trailing HTTP whitespace from the subtype only.
2057    let mut end = raw_subtype.len();
2058    while end > 0 && is_http_ws(raw_subtype[end - 1]) {
2059        end -= 1;
2060    }
2061    let trimmed_subtype: String = raw_subtype[..end].iter().collect();
2062    let sub_invalid = trimmed_subtype.chars().position(|c| !is_token_char(c));
2063    if trimmed_subtype.is_empty() || sub_invalid.is_some() {
2064        return Err(mime_syntax_err("subtype", s, sub_invalid));
2065    }
2066    let subtype = ascii_lower(&trimmed_subtype);
2067    let params: String = chars[new_pos.min(n)..].iter().collect();
2068    Ok((mime_type, subtype, params))
2069}
2070
2071/// Scan a quoted parameter value starting just after the opening `"` (Node's
2072/// `QUOTED_VALUE_PATTERN`). Returns `(matched_len, lone_backslash, closing_quote)`.
2073fn scan_quoted(chars: &[char], start: usize) -> (usize, bool, bool) {
2074    let n = chars.len();
2075    let mut i = start;
2076    let mut lone_backslash = false;
2077    let mut closing_quote = false;
2078    while i < n {
2079        match chars[i] {
2080            '\\' => {
2081                if i + 1 >= n {
2082                    lone_backslash = true;
2083                    i += 1;
2084                    break;
2085                }
2086                i += 2;
2087            }
2088            '"' => {
2089                closing_quote = true;
2090                i += 1;
2091                break;
2092            }
2093            _ => i += 1,
2094        }
2095    }
2096    (i - start, lone_backslash, closing_quote)
2097}
2098
2099/// Remove single `\` escapes (Node's `removeBackslashes`).
2100fn remove_backslashes(s: &[char]) -> String {
2101    let n = s.len();
2102    if n == 0 {
2103        return String::new();
2104    }
2105    let mut ret = String::new();
2106    let mut i = 0usize;
2107    while i < n - 1 {
2108        if s[i] == '\\' {
2109            i += 1;
2110            ret.push(s[i]);
2111        } else {
2112            ret.push(s[i]);
2113        }
2114        i += 1;
2115    }
2116    if i == n - 1 {
2117        ret.push(s[i]);
2118    }
2119    ret
2120}
2121
2122/// Parse a MIME parameter string into ordered, unique `(name, value)` pairs.
2123fn parse_mime_params(s: &str) -> Vec<(String, String)> {
2124    let chars: Vec<char> = s.chars().collect();
2125    let n = chars.len();
2126    // The source ends where trailing whitespace begins.
2127    let mut end_of_source = n;
2128    while end_of_source > 0 && is_http_ws(chars[end_of_source - 1]) {
2129        end_of_source -= 1;
2130    }
2131    let mut out: Vec<(String, String)> = Vec::new();
2132    let mut position = 0usize;
2133    while position < end_of_source {
2134        // Skip whitespace before the parameter name.
2135        while position < n && is_http_ws(chars[position]) {
2136            position += 1;
2137        }
2138        // Read the name up to `;`, `=`, or end.
2139        let mut after = position;
2140        while after < n && chars[after] != ';' && chars[after] != '=' {
2141            after += 1;
2142        }
2143        let name = ascii_lower(&chars[position..after].iter().collect::<String>());
2144        position = after;
2145        if position < end_of_source {
2146            let ch = chars[position];
2147            position += 1;
2148            // A `;` terminator means a value-less parameter — ignore it.
2149            if ch == ';' {
2150                continue;
2151            }
2152        }
2153        if position >= end_of_source {
2154            break;
2155        }
2156        let value = if chars[position] == '"' {
2157            // Quoted-string value.
2158            position += 1;
2159            let (matched_len, lone_backslash, closing_quote) = scan_quoted(&chars, position);
2160            let matched = &chars[position..position + matched_len];
2161            position += matched_len;
2162            let inside: &[char] = if lone_backslash || closing_quote {
2163                &matched[..matched.len().saturating_sub(1)]
2164            } else {
2165                matched
2166            };
2167            let mut v = remove_backslashes(inside);
2168            if lone_backslash {
2169                v.push('\\');
2170            }
2171            v
2172        } else {
2173            // Bare value up to `;`, trailing whitespace trimmed.
2174            let value_end = (position..n).find(|&i| chars[i] == ';').unwrap_or(n);
2175            let raw = &chars[position..value_end];
2176            position += raw.len();
2177            let mut end = raw.len();
2178            while end > 0 && is_http_ws(raw[end - 1]) {
2179                end -= 1;
2180            }
2181            let trimmed: String = raw[..end].iter().collect();
2182            if trimmed.is_empty() {
2183                // Node `continue`s here without the trailing `position++`, leaving
2184                // `position` on the `;` so the next iteration consumes it.
2185                continue;
2186            }
2187            trimmed
2188        };
2189        // Keep only valid, non-duplicate parameters (first value wins).
2190        let name_ok = !name.is_empty() && name.chars().all(is_token_char);
2191        let value_ok = value.chars().all(is_quoted_string_char);
2192        if name_ok && value_ok && !out.iter().any(|(k, _)| *k == name) {
2193            out.push((name, value));
2194        }
2195        position += 1;
2196    }
2197    out
2198}
2199
2200/// Serialize a parameter value: bare if it is a valid token, else a quoted string
2201/// with `"`/`\` escaped (Node's `encode`).
2202fn encode_param_value(value: &str) -> String {
2203    if value.is_empty() {
2204        return "\"\"".to_string();
2205    }
2206    if value.chars().all(is_token_char) {
2207        return value.to_string();
2208    }
2209    let mut escaped = String::with_capacity(value.len() + 2);
2210    for c in value.chars() {
2211        if c == '"' || c == '\\' {
2212            escaped.push('\\');
2213        }
2214        escaped.push(c);
2215    }
2216    format!("\"{escaped}\"")
2217}
2218
2219/// Serialize ordered pairs as `name=value;name2=value2` (MIMEParams `toString`).
2220fn serialize_mime_params(pairs: &[(String, String)]) -> String {
2221    let mut ret = String::new();
2222    for (k, v) in pairs {
2223        if !ret.is_empty() {
2224            ret.push(';');
2225        }
2226        ret.push_str(k);
2227        ret.push('=');
2228        ret.push_str(&encode_param_value(v));
2229    }
2230    ret
2231}
2232
2233/// Method names dispatched through `mime_params_instance_call` (for
2234/// `instance_has_method` wiring; `@@iterator` powers `for..of` / spread).
2235pub const MIME_PARAMS_METHODS: &[&str] = &[
2236    "get",
2237    "set",
2238    "has",
2239    "delete",
2240    "entries",
2241    "keys",
2242    "values",
2243    "toString",
2244    "toJSON",
2245    "@@iterator",
2246];
2247
2248/// Method names dispatched through `mime_type_instance_call`.
2249pub const MIME_TYPE_METHODS: &[&str] = &["toString", "toJSON"];
2250
2251/// Build a `MIMEParams` native object from ordered pairs.
2252fn make_mime_params(pairs: &[(String, String)]) -> Value {
2253    with_host(|h| {
2254        let items: Vec<Value> = pairs
2255            .iter()
2256            .map(|(k, v)| {
2257                let kv = vec![h.new_str(k.clone()), h.new_str(v.clone())];
2258                h.new_array(kv)
2259            })
2260            .collect();
2261        let arr = h.new_array(items);
2262        let mut m = IndexMap::new();
2263        m.insert("@@native".into(), h.new_str("MIMEParams"));
2264        m.insert("@@pairs".into(), arr);
2265        h.new_object(m)
2266    })
2267}
2268
2269/// Read the ordered `(name, value)` pairs out of a `MIMEParams`.
2270fn mime_pairs_of(recv: &Value) -> Vec<(String, String)> {
2271    with_host(|h| {
2272        let items: Vec<Value> = match h.get(recv) {
2273            Some(JsObj::Object(p)) => match p.get("@@pairs").and_then(|a| h.get(a)) {
2274                Some(JsObj::Array(items)) => items.clone(),
2275                _ => Vec::new(),
2276            },
2277            _ => Vec::new(),
2278        };
2279        items
2280            .iter()
2281            .map(|it| match h.get(it) {
2282                Some(JsObj::Array(kv)) => {
2283                    let kv = kv.clone();
2284                    let k = kv.first().map(|x| h.str_of(x)).unwrap_or_default();
2285                    let v = kv.get(1).map(|x| h.str_of(x)).unwrap_or_default();
2286                    (k, v)
2287                }
2288                _ => (h.str_of(it), String::new()),
2289            })
2290            .collect()
2291    })
2292}
2293
2294/// Overwrite a `MIMEParams`' backing `@@pairs` array.
2295fn set_mime_pairs(recv: &Value, pairs: &[(String, String)]) {
2296    with_host(|h| {
2297        let items: Vec<Value> = pairs
2298            .iter()
2299            .map(|(k, v)| {
2300                let kv = vec![h.new_str(k.clone()), h.new_str(v.clone())];
2301                h.new_array(kv)
2302            })
2303            .collect();
2304        let arr = h.new_array(items);
2305        if let Some(JsObj::Object(p)) = h.get_mut(recv) {
2306            p.insert("@@pairs".into(), arr);
2307        }
2308    });
2309}
2310
2311/// `new util.MIMEParams()` — an empty parameter set (Node's constructor takes no
2312/// arguments).
2313pub fn construct_mime_params(_args: &[Value]) -> Result<Value, String> {
2314    Ok(make_mime_params(&[]))
2315}
2316
2317/// `MIMEParams` instance methods.
2318pub fn mime_params_instance_call(
2319    recv: &Value,
2320    method: &str,
2321    args: &[Value],
2322) -> Result<Value, String> {
2323    match method {
2324        "get" => {
2325            let name = super::arg_str(args, 0);
2326            match mime_pairs_of(recv).into_iter().find(|(k, _)| *k == name) {
2327                Some((_, v)) => Ok(with_host(|h| h.new_str(v))),
2328                None => Ok(with_host(|h| h.null())),
2329            }
2330        }
2331        "has" => {
2332            let name = super::arg_str(args, 0);
2333            Ok(Value::Bool(
2334                mime_pairs_of(recv).iter().any(|(k, _)| *k == name),
2335            ))
2336        }
2337        "set" => {
2338            let name = super::arg_str(args, 0);
2339            let value = super::arg_str(args, 1);
2340            if let Some(i) = name.chars().position(|c| !is_token_char(c)) {
2341                return Err(mime_syntax_err("parameter name", &name, Some(i)));
2342            }
2343            if name.is_empty() {
2344                return Err(mime_syntax_err("parameter name", &name, None));
2345            }
2346            if let Some(i) = value.chars().position(|c| !is_quoted_string_char(c)) {
2347                return Err(mime_syntax_err("parameter value", &value, Some(i)));
2348            }
2349            let mut pairs = mime_pairs_of(recv);
2350            match pairs.iter_mut().find(|(k, _)| *k == name) {
2351                Some(slot) => slot.1 = value,
2352                None => pairs.push((name, value)),
2353            }
2354            set_mime_pairs(recv, &pairs);
2355            Ok(Value::Undef)
2356        }
2357        "delete" => {
2358            let name = super::arg_str(args, 0);
2359            let mut pairs = mime_pairs_of(recv);
2360            pairs.retain(|(k, _)| *k != name);
2361            set_mime_pairs(recv, &pairs);
2362            Ok(Value::Undef)
2363        }
2364        "keys" => {
2365            let pairs = mime_pairs_of(recv);
2366            Ok(with_host(|h| {
2367                let items = pairs.into_iter().map(|(k, _)| h.new_str(k)).collect();
2368                h.alloc(JsObj::Iter {
2369                    items,
2370                    idx: 0,
2371                    array: None,
2372                    brand: Some("Generator"),
2373                })
2374            }))
2375        }
2376        "values" => {
2377            let pairs = mime_pairs_of(recv);
2378            Ok(with_host(|h| {
2379                let items = pairs.into_iter().map(|(_, v)| h.new_str(v)).collect();
2380                h.alloc(JsObj::Iter {
2381                    items,
2382                    idx: 0,
2383                    array: None,
2384                    brand: Some("Generator"),
2385                })
2386            }))
2387        }
2388        "entries" | "@@iterator" => {
2389            let pairs = mime_pairs_of(recv);
2390            Ok(with_host(|h| {
2391                let items = pairs
2392                    .into_iter()
2393                    .map(|(k, v)| {
2394                        let kv = vec![h.new_str(k), h.new_str(v)];
2395                        h.new_array(kv)
2396                    })
2397                    .collect();
2398                h.alloc(JsObj::Iter {
2399                    items,
2400                    idx: 0,
2401                    array: None,
2402                    brand: Some("Generator"),
2403                })
2404            }))
2405        }
2406        "toString" | "toJSON" => {
2407            let s = serialize_mime_params(&mime_pairs_of(recv));
2408            Ok(with_host(|h| h.new_str(s)))
2409        }
2410        _ => Err(crate::host::type_error(&format!(
2411            "mimeParams.{method} is not a function"
2412        ))),
2413    }
2414}
2415
2416/// `new util.MIMEType(input)` — parse into `type`/`subtype`/`essence`/`params`.
2417pub fn construct_mime_type(args: &[Value]) -> Result<Value, String> {
2418    // Node coerces the argument to a string first (`${string}`), so a missing
2419    // argument parses as the literal `"undefined"` (which then throws).
2420    let input = with_host(|h| h.str_of(&args.first().cloned().unwrap_or(Value::Undef)));
2421    let (mime_type, subtype, params_str) = parse_type_and_subtype(&input)?;
2422    let essence = format!("{mime_type}/{subtype}");
2423    // Build the `MIMEParams` instance BEFORE the allocating `with_host` (never nest).
2424    let params = make_mime_params(&parse_mime_params(&params_str));
2425    Ok(with_host(|h| {
2426        let mut m = IndexMap::new();
2427        m.insert("@@native".into(), h.new_str("MIMEType"));
2428        m.insert("type".into(), h.new_str(mime_type));
2429        m.insert("subtype".into(), h.new_str(subtype));
2430        m.insert("essence".into(), h.new_str(essence));
2431        m.insert("params".into(), params);
2432        h.new_object(m)
2433    }))
2434}
2435
2436/// `MIMEType` instance methods. `type`/`subtype`/`essence`/`params` are data
2437/// properties read directly; `toString`/`toJSON` serialize live (reflecting any
2438/// `params` mutation).
2439pub fn mime_type_instance_call(
2440    recv: &Value,
2441    method: &str,
2442    _args: &[Value],
2443) -> Result<Value, String> {
2444    match method {
2445        "toString" | "toJSON" => {
2446            // Read the essence and the live params object under one borrow.
2447            let (essence, params) = with_host(|h| match h.get(recv) {
2448                Some(JsObj::Object(p)) => (
2449                    p.get("essence").map(|x| h.str_of(x)).unwrap_or_default(),
2450                    p.get("params").cloned().unwrap_or(Value::Undef),
2451                ),
2452                _ => (String::new(), Value::Undef),
2453            });
2454            let param_str = serialize_mime_params(&mime_pairs_of(&params));
2455            let out = if param_str.is_empty() {
2456                essence
2457            } else {
2458                format!("{essence};{param_str}")
2459            };
2460            Ok(with_host(|h| h.new_str(out)))
2461        }
2462        _ => Err(crate::host::type_error(&format!(
2463            "mimeType.{method} is not a function"
2464        ))),
2465    }
2466}