Skip to main content

strata_js/engine/
eval.rs

1//! JavaScript Statement, Expression, and Function Evaluator.
2
3use super::ast::*;
4use super::dom::*;
5use super::scope::*;
6use super::{JsEngine, MAX_EVAL_DEPTH};
7use crate::json::{parse_json, stringify_json};
8use crate::promise::{drain_microtasks, JsPromise, PromiseState};
9use crate::{ClosureHandle, JsValue, SymbolId};
10use std::collections::{BTreeMap, HashMap, HashSet};
11
12/// Maximum loop iterations before triggering execution timeout guard to prevent infinite loop DoS.
13pub const MAX_LOOP_ITERATIONS: usize = 1_000_000;
14
15impl JsEngine {
16    pub fn execute_statement(&mut self, stmt: &Stmt) -> Result<JsValue, String> {
17        match self.execute_stmt_flow(stmt)? {
18            StatementFlow::Normal(v) | StatementFlow::Return(v) | StatementFlow::Yield(v) => Ok(v),
19            StatementFlow::Throw(err) => Err(format!("Uncaught exception: {err}")),
20            StatementFlow::Break(_) => Err("SyntaxError: Illegal break statement".to_string()),
21            StatementFlow::Continue(_) => {
22                Err("SyntaxError: Illegal continue statement".to_string())
23            }
24        }
25    }
26
27    fn execute_block_flow(&mut self, stmts: &[Stmt]) -> Result<StatementFlow, String> {
28        let mut res = JsValue::Undefined;
29        for s in stmts {
30            match self.execute_stmt_flow(s)? {
31                StatementFlow::Normal(v) => res = v,
32                early => return Ok(early),
33            }
34        }
35        Ok(StatementFlow::Normal(res))
36    }
37
38    pub fn execute_stmt_flow(&mut self, stmt: &Stmt) -> Result<StatementFlow, String> {
39        match stmt {
40            Stmt::Directive(ref d) => {
41                if d == "use strict" {
42                    self.is_strict = true;
43                }
44                Ok(StatementFlow::Normal(JsValue::String(d.clone())))
45            }
46            Stmt::VarDecl { name, init } => {
47                let val = match init {
48                    Some(expr) => self.eval_expr(expr)?,
49                    None => JsValue::Undefined,
50                };
51                if let Some(err) = self.pending_throw.take() {
52                    return Ok(StatementFlow::Throw(err));
53                }
54                self.current_scope.borrow_mut().declare(name, val.clone());
55                if self.current_scope.borrow().parent.is_none() {
56                    self.globals.insert(name.clone(), val);
57                }
58                Ok(StatementFlow::Normal(JsValue::Undefined))
59            }
60            Stmt::DestructureDecl { pattern, init } => {
61                let val = self.eval_expr(init)?;
62                if let Some(err) = self.pending_throw.take() {
63                    return Ok(StatementFlow::Throw(err));
64                }
65                match pattern {
66                    DestructurePattern::Object { properties, rest } => {
67                        let mut matched_keys = HashSet::new();
68                        for prop in properties {
69                            matched_keys.insert(prop.source_key.clone());
70                            let mut prop_val = match &val {
71                                JsValue::Object(cell) => cell
72                                    .borrow()
73                                    .get(&prop.source_key)
74                                    .cloned()
75                                    .unwrap_or(JsValue::Undefined),
76                                _ => JsValue::Undefined,
77                            };
78                            if matches!(prop_val, JsValue::Undefined) {
79                                if let Some(ref def_expr) = prop.default_value {
80                                    prop_val = self.eval_expr(def_expr)?;
81                                }
82                            }
83                            self.current_scope
84                                .borrow_mut()
85                                .declare(&prop.target_name, prop_val.clone());
86                            if self.current_scope.borrow().parent.is_none() {
87                                self.globals.insert(prop.target_name.clone(), prop_val);
88                            }
89                        }
90                        if let Some(rest_name) = rest {
91                            let mut rest_map = BTreeMap::new();
92                            if let JsValue::Object(cell) = &val {
93                                for (k, v) in cell.borrow().iter() {
94                                    if !matched_keys.contains(k) && k != "__proto__" {
95                                        rest_map.insert(k.clone(), v.clone());
96                                    }
97                                }
98                            }
99                            let rest_val = JsValue::new_object(rest_map);
100                            self.current_scope
101                                .borrow_mut()
102                                .declare(rest_name, rest_val.clone());
103                            if self.current_scope.borrow().parent.is_none() {
104                                self.globals.insert(rest_name.clone(), rest_val);
105                            }
106                        }
107                    }
108                    DestructurePattern::Array { elements, rest } => {
109                        let mut idx = 0;
110                        for elem_opt in elements {
111                            if let Some(elem) = elem_opt {
112                                let mut elem_val = match &val {
113                                    JsValue::Array(cell) => cell
114                                        .borrow()
115                                        .get(idx)
116                                        .cloned()
117                                        .unwrap_or(JsValue::Undefined),
118                                    JsValue::String(s) => s
119                                        .chars()
120                                        .nth(idx)
121                                        .map(|c| JsValue::String(c.to_string()))
122                                        .unwrap_or(JsValue::Undefined),
123                                    _ => JsValue::Undefined,
124                                };
125                                if matches!(elem_val, JsValue::Undefined) {
126                                    if let Some(ref def_expr) = elem.default_value {
127                                        elem_val = self.eval_expr(def_expr)?;
128                                    }
129                                }
130                                self.current_scope
131                                    .borrow_mut()
132                                    .declare(&elem.target_name, elem_val.clone());
133                                if self.current_scope.borrow().parent.is_none() {
134                                    self.globals.insert(elem.target_name.clone(), elem_val);
135                                }
136                            }
137                            idx += 1;
138                        }
139                        if let Some(rest_name) = rest {
140                            let rest_items = match &val {
141                                JsValue::Array(cell) => {
142                                    let b = cell.borrow();
143                                    if idx < b.len() {
144                                        b[idx..].to_vec()
145                                    } else {
146                                        Vec::new()
147                                    }
148                                }
149                                _ => Vec::new(),
150                            };
151                            let rest_val = JsValue::new_array(rest_items);
152                            self.current_scope
153                                .borrow_mut()
154                                .declare(rest_name, rest_val.clone());
155                            if self.current_scope.borrow().parent.is_none() {
156                                self.globals.insert(rest_name.clone(), rest_val);
157                            }
158                        }
159                    }
160                }
161                Ok(StatementFlow::Normal(JsValue::Undefined))
162            }
163            Stmt::Assign { target, value } => {
164                let val = self.eval_expr(value)?;
165                if let Some(err) = self.pending_throw.take() {
166                    return Ok(StatementFlow::Throw(err));
167                }
168                self.assign_target(target, val.clone())?;
169                Ok(StatementFlow::Normal(val))
170            }
171            Stmt::Expr(expr) => {
172                let val = self.eval_expr(expr)?;
173                if let Some(err) = self.pending_throw.take() {
174                    return Ok(StatementFlow::Throw(err));
175                }
176                Ok(StatementFlow::Normal(val))
177            }
178            Stmt::Block(stmts) => self.execute_block_flow(stmts),
179            Stmt::If {
180                cond,
181                then_branch,
182                else_branch,
183            } => {
184                let c = self.eval_expr(cond)?;
185                if c.is_truthy() {
186                    self.execute_stmt_flow(then_branch)
187                } else if let Some(e) = else_branch {
188                    self.execute_stmt_flow(e)
189                } else {
190                    Ok(StatementFlow::Normal(JsValue::Undefined))
191                }
192            }
193            Stmt::While { cond, body } => {
194                let mut res = JsValue::Undefined;
195                let mut iterations = 0;
196                while self.eval_expr(cond)?.is_truthy() {
197                    iterations += 1;
198                    if iterations > MAX_LOOP_ITERATIONS {
199                        return Err("RangeError: Maximum loop iteration limit exceeded (execution timed out)".to_string());
200                    }
201                    match self.execute_stmt_flow(body)? {
202                        StatementFlow::Normal(v) => res = v,
203                        StatementFlow::Continue(_) => continue,
204                        StatementFlow::Break(_) => break,
205                        early => return Ok(early),
206                    }
207                }
208                Ok(StatementFlow::Normal(res))
209            }
210            Stmt::For {
211                init,
212                cond,
213                step,
214                body,
215            } => {
216                if let Some(i) = init {
217                    match self.execute_stmt_flow(i)? {
218                        StatementFlow::Normal(_) => {}
219                        early => return Ok(early),
220                    }
221                }
222                let mut res = JsValue::Undefined;
223                let mut iterations = 0;
224                loop {
225                    iterations += 1;
226                    if iterations > MAX_LOOP_ITERATIONS {
227                        return Err("RangeError: Maximum loop iteration limit exceeded (execution timed out)".to_string());
228                    }
229                    if let Some(c) = cond {
230                        if !self.eval_expr(c)?.is_truthy() {
231                            break;
232                        }
233                    }
234                    match self.execute_stmt_flow(body)? {
235                        StatementFlow::Normal(v) => res = v,
236                        StatementFlow::Continue(_) => {
237                            if let Some(s) = step {
238                                self.eval_expr(s)?;
239                            }
240                            continue;
241                        }
242                        StatementFlow::Break(_) => break,
243                        early => return Ok(early),
244                    }
245                    if let Some(s) = step {
246                        self.eval_expr(s)?;
247                    }
248                    self.maybe_prune_closures();
249                }
250                Ok(StatementFlow::Normal(res))
251            }
252            Stmt::FunctionDecl {
253                name,
254                params,
255                body,
256                is_async,
257                is_generator,
258            } => {
259                let closure_id = self.next_closure_id;
260                self.next_closure_id += 1;
261                let closure = JsClosure {
262                    id: closure_id,
263                    name: Some(name.clone()),
264                    params: params.clone(),
265                    body: body.clone(),
266                    env: self.current_scope.clone(),
267                    is_async: *is_async,
268                    is_generator: *is_generator,
269                };
270                let fn_val = JsValue::Function(ClosureHandle::new(closure_id, Some(name.clone())));
271                self.closures.insert(closure_id, closure.clone());
272                self.current_scope
273                    .borrow_mut()
274                    .declare(name, fn_val.clone());
275                if self.current_scope.borrow().parent.is_none() {
276                    self.globals.insert(name.clone(), fn_val);
277                    self.user_functions.insert(name.clone(), closure);
278                }
279                Ok(StatementFlow::Normal(JsValue::Undefined))
280            }
281            Stmt::ClassDecl {
282                name,
283                super_class,
284                constructor,
285                methods,
286            } => {
287                let mut methods_map = HashMap::new();
288                for (m_name, params, body) in methods {
289                    methods_map.insert(m_name.clone(), (params.clone(), body.clone()));
290                }
291                self.classes.insert(
292                    name.clone(),
293                    ClassDef {
294                        name: name.clone(),
295                        super_class: super_class.clone(),
296                        constructor: constructor.clone(),
297                        methods: methods_map,
298                    },
299                );
300                let mut class_meta = BTreeMap::new();
301                class_meta.insert("__class_name__".to_string(), JsValue::String(name.clone()));
302                class_meta.insert("__is_class__".to_string(), JsValue::Bool(true));
303                let class_val = JsValue::new_object(class_meta);
304                self.current_scope
305                    .borrow_mut()
306                    .declare(name, class_val.clone());
307                if self.current_scope.borrow().parent.is_none() {
308                    self.globals.insert(name.clone(), class_val);
309                }
310                Ok(StatementFlow::Normal(JsValue::Undefined))
311            }
312            Stmt::Return(expr_opt) => {
313                let val = match expr_opt {
314                    Some(e) => self.eval_expr(e)?,
315                    None => JsValue::Undefined,
316                };
317                if let Some(err) = self.pending_throw.take() {
318                    return Ok(StatementFlow::Throw(err));
319                }
320                Ok(StatementFlow::Return(val))
321            }
322            Stmt::Throw(expr) => {
323                let val = self.eval_expr(expr)?;
324                Ok(StatementFlow::Throw(val))
325            }
326            Stmt::TryCatch {
327                try_block,
328                catch_param,
329                catch_block,
330                finally_block,
331            } => {
332                let mut flow = match self.execute_block_flow(try_block) {
333                    Ok(f) => f,
334                    Err(e) => {
335                        let err_obj = self.create_error_from_string(&e);
336                        StatementFlow::Throw(err_obj)
337                    }
338                };
339                if let StatementFlow::Throw(ref thrown_val) = flow {
340                    let thrown_val = thrown_val.clone();
341                    if let Some(catch_stmts) = catch_block {
342                        let catch_scope = Scope::new_child(self.current_scope.clone());
343                        if let Some(ref param_name) = catch_param {
344                            catch_scope.borrow_mut().declare(param_name, thrown_val);
345                        }
346                        let saved_scope = self.current_scope.clone();
347                        self.current_scope = catch_scope;
348                        let catch_flow = self.execute_block_flow(catch_stmts);
349                        self.current_scope = saved_scope;
350                        flow = catch_flow?;
351                    }
352                }
353                if let Some(finally_stmts) = finally_block {
354                    let finally_flow = self.execute_block_flow(finally_stmts)?;
355                    if let StatementFlow::Return(_) | StatementFlow::Throw(_) = finally_flow {
356                        flow = finally_flow;
357                    }
358                }
359                Ok(flow)
360            }
361            Stmt::Break(label) => Ok(StatementFlow::Break(label.clone())),
362            Stmt::Continue(label) => Ok(StatementFlow::Continue(label.clone())),
363            Stmt::Switch {
364                discriminant,
365                cases,
366            } => {
367                let disc_val = self.eval_expr(discriminant)?;
368                let mut matched_index = None;
369                let mut default_index = None;
370
371                for (i, case) in cases.iter().enumerate() {
372                    if let Some(test_expr) = &case.test {
373                        let test_val = self.eval_expr(test_expr)?;
374                        if disc_val.strict_eq(&test_val) {
375                            matched_index = Some(i);
376                            break;
377                        }
378                    } else if default_index.is_none() {
379                        default_index = Some(i);
380                    }
381                }
382
383                let start_index = matched_index.or(default_index);
384                let mut res = JsValue::Undefined;
385
386                if let Some(start) = start_index {
387                    for case in &cases[start..] {
388                        for stmt in &case.consequent {
389                            match self.execute_stmt_flow(stmt)? {
390                                StatementFlow::Normal(v) => res = v,
391                                StatementFlow::Break(_) => return Ok(StatementFlow::Normal(res)),
392                                StatementFlow::Continue(lbl) => {
393                                    return Ok(StatementFlow::Continue(lbl))
394                                }
395                                StatementFlow::Return(v) => return Ok(StatementFlow::Return(v)),
396                                StatementFlow::Throw(v) => return Ok(StatementFlow::Throw(v)),
397                                StatementFlow::Yield(v) => return Ok(StatementFlow::Yield(v)),
398                            }
399                        }
400                    }
401                }
402
403                Ok(StatementFlow::Normal(res))
404            }
405        }
406    }
407
408    fn assign_target(&mut self, target: &Expr, val: JsValue) -> Result<(), String> {
409        match target {
410            Expr::Identifier(name) => {
411                if self.is_strict && !self.current_scope.borrow().has(name) {
412                    return Err(format!("ReferenceError: {name} is not defined"));
413                }
414                if !self.current_scope.borrow_mut().set(name, val.clone()) {
415                    self.current_scope.borrow_mut().declare(name, val.clone());
416                }
417                if self.current_scope.borrow().parent.is_none() {
418                    self.globals.insert(name.clone(), val);
419                }
420                Ok(())
421            }
422            Expr::Member {
423                object,
424                property,
425                computed,
426            } => {
427                let key = if let Some(comp_expr) = computed {
428                    let prop_val = self.eval_expr(comp_expr)?;
429                    match prop_val {
430                        JsValue::String(s) => s,
431                        JsValue::Number(n) => format!("{n}"),
432                        JsValue::BigInt(bi) => bi.to_decimal_string(),
433                        other => other.to_string(),
434                    }
435                } else {
436                    property.clone()
437                };
438
439                // Check built-in prototype mutation guard
440                if let Expr::Member {
441                    object: ref base,
442                    property: ref base_prop,
443                    ..
444                } = &**object
445                {
446                    if let Expr::Identifier(ref ctor_id) = &**base {
447                        if base_prop == "prototype" {
448                            if self.freeze_prototypes {
449                                return Err(format!(
450                                    "TypeError: Cannot modify frozen prototype {ctor_id}.prototype"
451                                ));
452                            }
453                            if !self.allow_prototype_mutation
454                                && matches!(
455                                    ctor_id.as_str(),
456                                    "Object" | "Array" | "Function" | "String" | "Error"
457                                )
458                            {
459                                return Err(format!(
460                                    "TypeError: Cannot modify sealed prototype {ctor_id}.prototype"
461                                ));
462                            }
463                            match ctor_id.as_str() {
464                                "Array" => {
465                                    self.array_prototype.insert(key.clone(), val.clone());
466                                }
467                                "Object" => {
468                                    self.object_prototype.insert(key.clone(), val.clone());
469                                }
470                                "Function" => {
471                                    self.function_prototype.insert(key.clone(), val.clone());
472                                }
473                                "String" => {
474                                    self.string_prototype.insert(key.clone(), val.clone());
475                                }
476                                "Error" => {
477                                    self.error_prototype.insert(key.clone(), val.clone());
478                                }
479                                _ => {}
480                            }
481                        }
482                    }
483                }
484
485                // Document / DOM element shortcuts
486                if let Expr::Identifier(id) = &**object {
487                    if id == "document" && key == "title" {
488                        if let Some(s) = val.as_str() {
489                            *self.document.title.borrow_mut() = s.to_string();
490                            self.document.mark_mutated();
491                        }
492                        return Ok(());
493                    }
494                }
495                if let Expr::Member {
496                    object: parent_obj,
497                    property: parent_prop,
498                    ..
499                } = &**object
500                {
501                    if let Expr::Identifier(id) = &**parent_obj {
502                        if id == "document" && parent_prop == "body" {
503                            if key == "innerHTML" {
504                                if let Some(s) = val.as_str() {
505                                    self.document.body.set_inner_html(s);
506                                    self.document.mark_mutated();
507                                }
508                                return Ok(());
509                            } else if key == "textContent" {
510                                if let Some(s) = val.as_str() {
511                                    self.document.body.set_text_content(s);
512                                    self.document.mark_mutated();
513                                }
514                                return Ok(());
515                            }
516                        }
517                    }
518                }
519
520                let obj = self.eval_expr(object)?;
521
522                // Check DOM node on object
523                if let JsValue::Object(ref cell) = obj {
524                    if let Some(node) = self.resolve_dom_node(&cell.borrow()) {
525                        if key == "innerHTML" {
526                            if let Some(s) = val.as_str() {
527                                node.set_inner_html(s);
528                                self.document.mark_mutated();
529                            }
530                            return Ok(());
531                        } else if key == "textContent" {
532                            if let Some(s) = val.as_str() {
533                                node.set_text_content(s);
534                                self.document.mark_mutated();
535                            }
536                            return Ok(());
537                        } else if key == "className" {
538                            if let Some(s) = val.as_str() {
539                                node.set_class_name(s);
540                                self.document.mark_mutated();
541                            }
542                            return Ok(());
543                        } else if key == "id" {
544                            if let Some(s) = val.as_str() {
545                                node.set_attribute("id", s);
546                                self.document.mark_mutated();
547                            }
548                            return Ok(());
549                        } else if key == "value" {
550                            if let Some(s) = val.as_str() {
551                                node.set_attribute("value", s);
552                                self.document.mark_mutated();
553                            }
554                            return Ok(());
555                        } else if key.starts_with("on") && key.len() > 2 {
556                            let ev_name = key[2..].to_ascii_lowercase();
557                            node.add_event_listener(&ev_name, val);
558                            return Ok(());
559                        }
560                    }
561                }
562
563                if key == "__proto__" && (self.freeze_prototypes || !self.allow_prototype_mutation)
564                {
565                    return Err("TypeError: Cannot modify prototype in sealed mode".to_string());
566                }
567
568                // Check Proxy set trap
569                if let JsValue::Object(ref cell) = obj {
570                    let proxy_info = {
571                        let b = cell.borrow();
572                        if b.get("__is_proxy__") == Some(&JsValue::Bool(true)) {
573                            let target = b.get("__proxy_target__").cloned();
574                            let handler = b.get("__proxy_handler__").cloned();
575                            Some((target, handler))
576                        } else {
577                            None
578                        }
579                    };
580                    if let Some((Some(target), Some(handler))) = proxy_info {
581                        if let Some(set_trap) = handler.get_prop("set") {
582                            if set_trap.is_function() {
583                                let receiver = obj.clone();
584                                let trap_args =
585                                    vec![target.clone(), JsValue::String(key), val, receiver];
586                                let _ =
587                                    self.call_value_with_this(&set_trap, trap_args, Some(handler))?;
588                                return Ok(());
589                            }
590                        }
591                        target.set_prop(key, val);
592                        return Ok(());
593                    }
594                }
595
596                // Mutate Object
597                if let JsValue::Object(ref cell) = obj {
598                    cell.borrow_mut().insert(key, val);
599                    return Ok(());
600                }
601
602                // Mutate Array
603                if let JsValue::Array(ref cell) = obj {
604                    if key == "length" {
605                        if let Some(new_len) = val.as_f64() {
606                            let mut b = cell.borrow_mut();
607                            b.resize(new_len as usize, JsValue::Undefined);
608                        }
609                        return Ok(());
610                    }
611                    if let Ok(idx) = key.parse::<usize>() {
612                        let mut b = cell.borrow_mut();
613                        if idx >= b.len() {
614                            b.resize(idx + 1, JsValue::Undefined);
615                        }
616                        b[idx] = val;
617                        return Ok(());
618                    }
619                    return Ok(());
620                }
621
622                if matches!(obj, JsValue::Null | JsValue::Undefined) {
623                    return Err(format!(
624                        "TypeError: Cannot set properties of {} (setting '{}')",
625                        obj.js_typeof(),
626                        key
627                    ));
628                }
629
630                Ok(())
631            }
632            Expr::Array(items) => {
633                let mut idx = 0;
634                for item in items {
635                    if matches!(item, Expr::Literal(JsValue::Undefined)) {
636                        idx += 1;
637                        continue;
638                    }
639                    if let Expr::Spread(inner) = item {
640                        let rest_items = match &val {
641                            JsValue::Array(cell) => {
642                                let b = cell.borrow();
643                                if idx < b.len() {
644                                    b[idx..].to_vec()
645                                } else {
646                                    Vec::new()
647                                }
648                            }
649                            _ => Vec::new(),
650                        };
651                        self.assign_target(inner, JsValue::new_array(rest_items))?;
652                        break;
653                    } else {
654                        let item_val = match &val {
655                            JsValue::Array(cell) => cell
656                                .borrow()
657                                .get(idx)
658                                .cloned()
659                                .unwrap_or(JsValue::Undefined),
660                            _ => JsValue::Undefined,
661                        };
662                        self.assign_target(item, item_val)?;
663                        idx += 1;
664                    }
665                }
666                Ok(())
667            }
668            Expr::Object(pairs) => {
669                let mut matched_keys = HashSet::new();
670                for (k, target_expr) in pairs {
671                    if let Expr::Spread(inner) = target_expr {
672                        let mut rest_map = BTreeMap::new();
673                        if let JsValue::Object(cell) = &val {
674                            for (mk, mv) in cell.borrow().iter() {
675                                if !matched_keys.contains(mk) && mk != "__proto__" {
676                                    rest_map.insert(mk.clone(), mv.clone());
677                                }
678                            }
679                        }
680                        self.assign_target(inner, JsValue::new_object(rest_map))?;
681                    } else {
682                        matched_keys.insert(k.clone());
683                        let item_val = match &val {
684                            JsValue::Object(cell) => {
685                                cell.borrow().get(k).cloned().unwrap_or(JsValue::Undefined)
686                            }
687                            _ => JsValue::Undefined,
688                        };
689                        self.assign_target(target_expr, item_val)?;
690                    }
691                }
692                Ok(())
693            }
694            _ => Err("Invalid assignment target".to_string()),
695        }
696    }
697
698    pub fn call_value(&mut self, callee: &JsValue, args: Vec<JsValue>) -> Result<JsValue, String> {
699        self.call_value_with_this(callee, args, None)
700    }
701
702    pub fn call_value_with_this(
703        &mut self,
704        callee: &JsValue,
705        args: Vec<JsValue>,
706        this_val: Option<JsValue>,
707    ) -> Result<JsValue, String> {
708        match callee {
709            JsValue::Function(handle) => {
710                if let Some(closure) = self.closures.get(&handle.id).cloned() {
711                    return self.call_closure_with_this(&closure, args, this_val);
712                }
713                if let Some(ref name) = handle.name {
714                    if let Some(closure) = self.user_functions.get(name).cloned() {
715                        return self.call_closure_with_this(&closure, args, this_val);
716                    }
717                    return self.call_function(name, args);
718                }
719                Err(format!(
720                    "TypeError: Function #{} is not callable",
721                    handle.id
722                ))
723            }
724            JsValue::String(name) => self.call_function(name, args),
725            JsValue::Object(map) => {
726                let (cid, fn_name) = {
727                    let b = map.borrow();
728                    let cid = b
729                        .get("__closure_id__")
730                        .and_then(|v| v.as_f64())
731                        .map(|n| n as u64);
732                    let fn_name = b
733                        .get("__fn__")
734                        .and_then(|v| v.as_str())
735                        .map(|s| s.to_string());
736                    (cid, fn_name)
737                };
738                if let Some(id) = cid {
739                    if let Some(closure) = self.closures.get(&id).cloned() {
740                        return self.call_closure_with_this(&closure, args, this_val);
741                    }
742                }
743                if let Some(name) = fn_name {
744                    self.call_function(&name, args)
745                } else {
746                    Ok(JsValue::Undefined)
747                }
748            }
749            _ => Ok(JsValue::Undefined),
750        }
751    }
752
753    pub fn eval_expr(&mut self, expr: &Expr) -> Result<JsValue, String> {
754        if self.eval_depth >= MAX_EVAL_DEPTH {
755            return Err(
756                "RangeError: Maximum call stack size exceeded (eval recursion limit)".to_string(),
757            );
758        }
759        self.eval_depth += 1;
760        let res = self.eval_expr_inner(expr);
761        self.eval_depth -= 1;
762        res
763    }
764
765    fn eval_expr_inner(&mut self, expr: &Expr) -> Result<JsValue, String> {
766        match expr {
767            Expr::Literal(val) => Ok(val.clone()),
768            Expr::Assign { target, value } => {
769                let val = self.eval_expr(value)?;
770                self.assign_target(target, val.clone())?;
771                Ok(val)
772            }
773            Expr::Update { op, target, prefix } => {
774                let cur_val = self.eval_expr(target)?;
775                let num = cur_val.as_f64().unwrap_or(0.0);
776                let new_num = if *op == UpdateOp::Increment {
777                    num + 1.0
778                } else {
779                    num - 1.0
780                };
781                self.assign_target(target, JsValue::Number(new_num))?;
782                if *prefix {
783                    Ok(JsValue::Number(new_num))
784                } else {
785                    Ok(JsValue::Number(num))
786                }
787            }
788            Expr::Identifier(name) => {
789                if let Some(val) = self.current_scope.borrow().get(name) {
790                    return Ok(val);
791                }
792                if let Some(val) = self.globals.get(name) {
793                    return Ok(val.clone());
794                }
795                match name.as_str() {
796                    "undefined" => Ok(JsValue::Undefined),
797                    "null" => Ok(JsValue::Null),
798                    "document" => Ok(JsValue::empty_object()),
799                    "window" => Ok(JsValue::empty_object()),
800                    _ => Err(format!("ReferenceError: {name} is not defined")),
801                }
802            }
803            Expr::Binary { op, left, right } => match op {
804                BinaryOp::Or => {
805                    let l_val = self.eval_expr(left)?;
806                    if l_val.is_truthy() {
807                        return Ok(l_val);
808                    }
809                    self.eval_expr(right)
810                }
811                BinaryOp::And => {
812                    let l_val = self.eval_expr(left)?;
813                    if !l_val.is_truthy() {
814                        return Ok(l_val);
815                    }
816                    self.eval_expr(right)
817                }
818                BinaryOp::NullishCoalescing => {
819                    let l_val = self.eval_expr(left)?;
820                    if !matches!(l_val, JsValue::Null | JsValue::Undefined) {
821                        return Ok(l_val);
822                    }
823                    self.eval_expr(right)
824                }
825                BinaryOp::InstanceOf => {
826                    let l_val = self.eval_expr(left)?;
827                    let class_name = match &**right {
828                        Expr::Identifier(ref id) => id.clone(),
829                        Expr::Literal(JsValue::String(ref s)) => s.clone(),
830                        other => {
831                            let rv = self.eval_expr(other)?;
832                            if let JsValue::Object(map) = rv {
833                                map.borrow()
834                                    .get("__class_name__")
835                                    .and_then(|v| v.as_str())
836                                    .unwrap_or("")
837                                    .to_string()
838                            } else {
839                                String::new()
840                            }
841                        }
842                    };
843                    Ok(JsValue::Bool(self.is_instance_of(&l_val, &class_name)))
844                }
845                _ => {
846                    let l_val = self.eval_expr(left)?;
847                    let r_val = self.eval_expr(right)?;
848                    self.eval_binary(op, &l_val, &r_val)
849                }
850            },
851            Expr::Unary { op, expr } => {
852                if *op == UnaryOp::Typeof {
853                    if let Expr::Identifier(ref name) = &**expr {
854                        if let Some(val) = self.current_scope.borrow().get(name) {
855                            return Ok(JsValue::String(val.js_typeof().to_string()));
856                        }
857                        if let Some(val) = self.globals.get(name) {
858                            return Ok(JsValue::String(val.js_typeof().to_string()));
859                        }
860                        return Ok(JsValue::String("undefined".to_string()));
861                    }
862                }
863                let val = self.eval_expr(expr)?;
864                match op {
865                    UnaryOp::Not => Ok(JsValue::Bool(!val.is_truthy())),
866                    UnaryOp::Neg => match val {
867                        JsValue::BigInt(bi) => Ok(JsValue::BigInt(bi.neg())),
868                        _ => {
869                            let n = val.as_f64().unwrap_or(0.0);
870                            Ok(JsValue::Number(-n))
871                        }
872                    },
873                    UnaryOp::Pos => match val {
874                        JsValue::BigInt(_) => {
875                            Err("TypeError: Cannot convert a BigInt value to a number".to_string())
876                        }
877                        _ => {
878                            let n = val.as_f64().unwrap_or(0.0);
879                            Ok(JsValue::Number(n))
880                        }
881                    },
882                    UnaryOp::BitNot => match val {
883                        JsValue::BigInt(bi) => Ok(JsValue::BigInt(bi.bit_not())),
884                        _ => {
885                            let n = val.as_f64().unwrap_or(0.0) as i64 as i32;
886                            Ok(JsValue::Number((!n) as f64))
887                        }
888                    },
889                    UnaryOp::Typeof => Ok(JsValue::String(val.js_typeof().to_string())),
890                }
891            }
892            Expr::TemplateLiteral(parts) => {
893                let mut out = String::new();
894                for part in parts {
895                    match part {
896                        TemplatePart::Literal(s) => out.push_str(s),
897                        TemplatePart::Expr(e) => {
898                            let v = self.eval_expr(e)?;
899                            match v {
900                                JsValue::String(s) => out.push_str(&s),
901                                JsValue::Number(n) => out.push_str(&format!("{n}")),
902                                JsValue::BigInt(bi) => out.push_str(&bi.to_decimal_string()),
903                                JsValue::Bool(b) => out.push_str(&format!("{b}")),
904                                JsValue::Null => out.push_str("null"),
905                                JsValue::Undefined => out.push_str("undefined"),
906                                other => out.push_str(
907                                    &stringify_json(&other)
908                                        .unwrap_or_else(|_| "[object Object]".to_string()),
909                                ),
910                            }
911                        }
912                    }
913                }
914                Ok(JsValue::String(out))
915            }
916            Expr::ArrowFunction {
917                params,
918                body,
919                is_async,
920            } => {
921                let closure_id = self.next_closure_id;
922                self.next_closure_id += 1;
923                self.anon_counter += 1;
924                let fn_name = format!("__anon_fn_{closure_id}");
925                let stmts = match body {
926                    ArrowBody::Expr(e) => vec![Stmt::Return(Some((**e).clone()))],
927                    ArrowBody::Block(s) => s.clone(),
928                };
929                let closure = JsClosure {
930                    id: closure_id,
931                    name: None,
932                    params: params.clone(),
933                    body: stmts,
934                    env: self.current_scope.clone(),
935                    is_async: *is_async,
936                    is_generator: false,
937                };
938                self.closures.insert(closure_id, closure);
939                Ok(JsValue::Function(ClosureHandle::new(
940                    closure_id,
941                    Some(fn_name),
942                )))
943            }
944            Expr::Await(inner) => {
945                let val = self.eval_expr(inner)?;
946                drain_microtasks();
947
948                let promise_opt = match &val {
949                    JsValue::Promise(p) => Some(p.clone()),
950                    _ => None,
951                };
952
953                if let Some(promise) = promise_opt {
954                    // Cooperative event loop progression until promise settles or progress halts
955                    let max_wait = std::time::Duration::from_secs(5);
956                    let start = std::time::Instant::now();
957                    loop {
958                        match promise.state() {
959                            PromiseState::Fulfilled(res) => return Ok(res),
960                            PromiseState::Rejected(err) => {
961                                self.pending_throw = Some(err);
962                                return Ok(JsValue::Undefined);
963                            }
964                            PromiseState::Pending => {
965                                let drained = drain_microtasks();
966                                let fired = self.tick_engine_timers();
967                                if drained > 0 || fired > 0 {
968                                    continue;
969                                }
970                                if let Some(wait_dur) = crate::web::time_until_next_timer() {
971                                    if start.elapsed() > max_wait {
972                                        break;
973                                    }
974                                    let sleep_chunk =
975                                        wait_dur.min(std::time::Duration::from_millis(5));
976                                    if sleep_chunk > std::time::Duration::ZERO {
977                                        std::thread::sleep(sleep_chunk);
978                                    } else {
979                                        std::thread::yield_now();
980                                    }
981                                } else {
982                                    if start.elapsed().as_millis() > 50 {
983                                        break;
984                                    }
985                                    std::thread::sleep(std::time::Duration::from_millis(1));
986                                }
987                            }
988                        }
989                    }
990
991                    match promise.state() {
992                        PromiseState::Fulfilled(res) => Ok(res),
993                        PromiseState::Rejected(err) => {
994                            self.pending_throw = Some(err);
995                            Ok(JsValue::Undefined)
996                        }
997                        PromiseState::Pending => {
998                            Err("AsyncError: Awaited Promise remained pending after event loop exhaustion".to_string())
999                        }
1000                    }
1001                } else {
1002                    Ok(val)
1003                }
1004            }
1005            Expr::Member {
1006                object,
1007                property,
1008                computed,
1009            } => {
1010                let obj_val = self.eval_expr(object)?;
1011                self.eval_member_access(object, &obj_val, property, computed.as_deref())
1012            }
1013            Expr::OptionalMember {
1014                object,
1015                property,
1016                computed,
1017            } => {
1018                let obj_val = self.eval_expr(object)?;
1019                if matches!(obj_val, JsValue::Null | JsValue::Undefined) {
1020                    return Ok(JsValue::Undefined);
1021                }
1022                self.eval_member_access(object, &obj_val, property, computed.as_deref())
1023            }
1024            Expr::Call { callee, args } => {
1025                if let Expr::OptionalMember { object, .. } = &**callee {
1026                    let base = self.eval_expr(object)?;
1027                    if matches!(base, JsValue::Null | JsValue::Undefined) {
1028                        return Ok(JsValue::Undefined);
1029                    }
1030                }
1031
1032                let mut evaluated_args = Vec::new();
1033                for a in args {
1034                    if let Expr::Spread(inner) = a {
1035                        let spread_val = self.eval_expr(inner)?;
1036                        match spread_val {
1037                            JsValue::Array(items) => evaluated_args.extend(items.borrow().clone()),
1038                            JsValue::String(s) => {
1039                                for ch in s.chars() {
1040                                    evaluated_args.push(JsValue::String(ch.to_string()));
1041                                }
1042                            }
1043                            other => evaluated_args.push(other),
1044                        }
1045                    } else {
1046                        evaluated_args.push(self.eval_expr(a)?);
1047                    }
1048                }
1049
1050                if let Expr::Identifier(id) = &**callee {
1051                    if id == "super" {
1052                        let super_class_opt = self.current_scope.borrow().get("__super_class__");
1053                        if let Some(JsValue::String(super_name)) = super_class_opt {
1054                            let super_ctor = self.resolve_constructor(&super_name);
1055                            if let Some((params, body, next_super)) = super_ctor {
1056                                let current_this = self
1057                                    .current_scope
1058                                    .borrow()
1059                                    .get("this")
1060                                    .unwrap_or(JsValue::Undefined);
1061                                let super_scope = Scope::new_child(self.current_scope.clone());
1062                                super_scope.borrow_mut().declare("this", current_this);
1063                                if let Some(ns) = next_super {
1064                                    super_scope
1065                                        .borrow_mut()
1066                                        .declare("__super_class__", JsValue::String(ns));
1067                                }
1068                                super_scope
1069                                    .borrow_mut()
1070                                    .declare("__current_class__", JsValue::String(super_name));
1071
1072                                bind_parameters(&params, evaluated_args, &super_scope);
1073
1074                                let saved_scope = self.current_scope.clone();
1075                                self.current_scope = super_scope.clone();
1076
1077                                let mut err = None;
1078                                for stmt in &body {
1079                                    match self.execute_stmt_flow(stmt) {
1080                                        Ok(StatementFlow::Normal(_)) => {}
1081                                        Ok(StatementFlow::Return(_)) => break,
1082                                        Ok(StatementFlow::Throw(v)) => {
1083                                            err = Some(format!("Uncaught exception: {v}"));
1084                                            break;
1085                                        }
1086                                        Ok(StatementFlow::Break(_)) => {
1087                                            err = Some(
1088                                                "SyntaxError: Illegal break statement".to_string(),
1089                                            );
1090                                            break;
1091                                        }
1092                                        Ok(StatementFlow::Continue(_)) => {
1093                                            err = Some(
1094                                                "SyntaxError: Illegal continue statement"
1095                                                    .to_string(),
1096                                            );
1097                                            break;
1098                                        }
1099                                        Ok(StatementFlow::Yield(_)) => break,
1100                                        Err(e) => {
1101                                            err = Some(e);
1102                                            break;
1103                                        }
1104                                    }
1105                                }
1106
1107                                self.current_scope = saved_scope;
1108                                if let Some(e) = err {
1109                                    return Err(e);
1110                                }
1111
1112                                if let Some(updated_this) = super_scope.borrow().get("this") {
1113                                    self.current_scope.borrow_mut().set("this", updated_this);
1114                                }
1115                                return Ok(JsValue::Undefined);
1116                            }
1117                        }
1118                    }
1119                }
1120
1121                if let Expr::Member {
1122                    object,
1123                    property,
1124                    computed,
1125                }
1126                | Expr::OptionalMember {
1127                    object,
1128                    property,
1129                    computed,
1130                } = &**callee
1131                {
1132                    if computed.is_none() {
1133                        if let Expr::Identifier(id) = &**object {
1134                            if id == "super" {
1135                                let current_class_opt =
1136                                    self.current_scope.borrow().get("__current_class__");
1137                                if let Some(JsValue::String(curr_cls)) = current_class_opt {
1138                                    let super_class_opt = self
1139                                        .classes
1140                                        .get(&curr_cls)
1141                                        .and_then(|c| c.super_class.clone());
1142                                    if let Some(super_name) = super_class_opt {
1143                                        if let Some((params, body, _)) =
1144                                            self.resolve_method(&super_name, property)
1145                                        {
1146                                            let current_this = self
1147                                                .current_scope
1148                                                .borrow()
1149                                                .get("this")
1150                                                .unwrap_or(JsValue::Undefined);
1151                                            let super_scope =
1152                                                Scope::new_child(self.current_scope.clone());
1153                                            super_scope.borrow_mut().declare("this", current_this);
1154                                            super_scope.borrow_mut().declare(
1155                                                "__current_class__",
1156                                                JsValue::String(super_name),
1157                                            );
1158
1159                                            bind_parameters(&params, evaluated_args, &super_scope);
1160
1161                                            let saved_scope = self.current_scope.clone();
1162                                            self.current_scope = super_scope.clone();
1163
1164                                            let mut ret = JsValue::Undefined;
1165                                            let mut err = None;
1166                                            for stmt in &body {
1167                                                match self.execute_stmt_flow(stmt) {
1168                                                    Ok(StatementFlow::Normal(v)) => ret = v,
1169                                                    Ok(StatementFlow::Return(v)) => {
1170                                                        ret = v;
1171                                                        break;
1172                                                    }
1173                                                    Ok(StatementFlow::Throw(v)) => {
1174                                                        err = Some(format!(
1175                                                            "Uncaught exception: {v}"
1176                                                        ));
1177                                                        break;
1178                                                    }
1179                                                    Ok(StatementFlow::Break(_)) => {
1180                                                        err = Some(
1181                                                            "SyntaxError: Illegal break statement"
1182                                                                .to_string(),
1183                                                        );
1184                                                        break;
1185                                                    }
1186                                                    Ok(StatementFlow::Continue(_)) => {
1187                                                        err = Some("SyntaxError: Illegal continue statement".to_string());
1188                                                        break;
1189                                                    }
1190                                                    Ok(StatementFlow::Yield(v)) => {
1191                                                        ret = v;
1192                                                        break;
1193                                                    }
1194                                                    Err(e) => {
1195                                                        err = Some(e);
1196                                                        break;
1197                                                    }
1198                                                }
1199                                            }
1200
1201                                            self.current_scope = saved_scope;
1202                                            if let Some(e) = err {
1203                                                return Err(e);
1204                                            }
1205
1206                                            if let Some(updated_this) =
1207                                                super_scope.borrow().get("this")
1208                                            {
1209                                                self.current_scope
1210                                                    .borrow_mut()
1211                                                    .set("this", updated_this);
1212                                            }
1213                                            return Ok(ret);
1214                                        }
1215                                    }
1216                                }
1217                            }
1218                        }
1219                    }
1220
1221                    if let Expr::Identifier(id) = &**object {
1222                        if id == "document" {
1223                            match property.as_str() {
1224                                "getElementById" => {
1225                                    if let Some(target_id) =
1226                                        evaluated_args.first().and_then(|v| v.as_str())
1227                                    {
1228                                        if let Some(elem) =
1229                                            self.document.get_element_by_id(target_id)
1230                                        {
1231                                            return Ok(self.dom_node_to_js(&elem));
1232                                        }
1233                                    }
1234                                    return Ok(JsValue::Null);
1235                                }
1236                                "querySelector" => {
1237                                    if let Some(sel) =
1238                                        evaluated_args.first().and_then(|v| v.as_str())
1239                                    {
1240                                        if let Some(elem) = self.document.query_selector(sel) {
1241                                            return Ok(self.dom_node_to_js(&elem));
1242                                        }
1243                                    }
1244                                    return Ok(JsValue::Null);
1245                                }
1246                                "querySelectorAll" => {
1247                                    if let Some(sel) =
1248                                        evaluated_args.first().and_then(|v| v.as_str())
1249                                    {
1250                                        let all = self.document.query_selector_all(sel);
1251                                        let list: Vec<JsValue> =
1252                                            all.iter().map(|n| self.dom_node_to_js(n)).collect();
1253                                        return Ok(JsValue::new_array(list));
1254                                    }
1255                                    return Ok(JsValue::empty_array());
1256                                }
1257                                "createElement" => {
1258                                    if let Some(tag) =
1259                                        evaluated_args.first().and_then(|v| v.as_str())
1260                                    {
1261                                        let elem = self.document.create_element(tag);
1262                                        return Ok(self.dom_node_to_js(&elem));
1263                                    }
1264                                    return Ok(JsValue::Null);
1265                                }
1266                                "createTextNode" => {
1267                                    if let Some(text) =
1268                                        evaluated_args.first().and_then(|v| v.as_str())
1269                                    {
1270                                        let elem = self.document.create_text_node(text);
1271                                        return Ok(self.dom_node_to_js(&elem));
1272                                    }
1273                                    return Ok(JsValue::Null);
1274                                }
1275                                "createComment" => {
1276                                    if let Some(text) =
1277                                        evaluated_args.first().and_then(|v| v.as_str())
1278                                    {
1279                                        let elem = self.document.create_comment(text);
1280                                        return Ok(self.dom_node_to_js(&elem));
1281                                    }
1282                                    return Ok(JsValue::Null);
1283                                }
1284                                _ => {}
1285                            }
1286                        } else if id == "console" {
1287                            let msg = evaluated_args
1288                                .iter()
1289                                .map(|v| match v {
1290                                    JsValue::String(s) => s.clone(),
1291                                    JsValue::Number(n) => n.to_string(),
1292                                    JsValue::Bool(b) => b.to_string(),
1293                                    JsValue::Null => "null".to_string(),
1294                                    JsValue::Undefined => "undefined".to_string(),
1295                                    other => stringify_json(other)
1296                                        .unwrap_or_else(|_| "[object Object]".to_string()),
1297                                })
1298                                .collect::<Vec<_>>()
1299                                .join(" ");
1300                            self.console_logs.push(msg);
1301                            return Ok(JsValue::Undefined);
1302                        } else if id == "JSON" {
1303                            if property == "stringify" {
1304                                if let Some(first) = evaluated_args.first() {
1305                                    return stringify_json(first).map(JsValue::String);
1306                                }
1307                            } else if property == "parse" {
1308                                if let Some(first) = evaluated_args.first().and_then(|v| v.as_str())
1309                                {
1310                                    return parse_json(first);
1311                                }
1312                            }
1313                        } else if id == "Math" {
1314                            match property.as_str() {
1315                                "floor" => {
1316                                    let n = evaluated_args
1317                                        .first()
1318                                        .and_then(|v| v.as_f64())
1319                                        .unwrap_or(0.0);
1320                                    return Ok(JsValue::Number(n.floor()));
1321                                }
1322                                "ceil" => {
1323                                    let n = evaluated_args
1324                                        .first()
1325                                        .and_then(|v| v.as_f64())
1326                                        .unwrap_or(0.0);
1327                                    return Ok(JsValue::Number(n.ceil()));
1328                                }
1329                                "round" => {
1330                                    let n = evaluated_args
1331                                        .first()
1332                                        .and_then(|v| v.as_f64())
1333                                        .unwrap_or(0.0);
1334                                    return Ok(JsValue::Number(n.round()));
1335                                }
1336                                "abs" => {
1337                                    let n = evaluated_args
1338                                        .first()
1339                                        .and_then(|v| v.as_f64())
1340                                        .unwrap_or(0.0);
1341                                    return Ok(JsValue::Number(n.abs()));
1342                                }
1343                                "min" => {
1344                                    let mut m = f64::INFINITY;
1345                                    for a in &evaluated_args {
1346                                        if let Some(n) = a.as_f64() {
1347                                            if n < m {
1348                                                m = n;
1349                                            }
1350                                        }
1351                                    }
1352                                    return Ok(JsValue::Number(m));
1353                                }
1354                                "max" => {
1355                                    let mut m = f64::NEG_INFINITY;
1356                                    for a in &evaluated_args {
1357                                        if let Some(n) = a.as_f64() {
1358                                            if n > m {
1359                                                m = n;
1360                                            }
1361                                        }
1362                                    }
1363                                    return Ok(JsValue::Number(m));
1364                                }
1365                                "sqrt" => {
1366                                    let n = evaluated_args
1367                                        .first()
1368                                        .and_then(|v| v.as_f64())
1369                                        .unwrap_or(0.0);
1370                                    return Ok(JsValue::Number(n.sqrt()));
1371                                }
1372                                _ => {}
1373                            }
1374                        } else if id == "Promise" {
1375                            match property.as_str() {
1376                                "resolve" => {
1377                                    let v = evaluated_args
1378                                        .first()
1379                                        .cloned()
1380                                        .unwrap_or(JsValue::Undefined);
1381                                    let p = JsPromise::resolve(v);
1382                                    return Ok(self.create_promise_value(p));
1383                                }
1384                                "reject" => {
1385                                    let v = evaluated_args
1386                                        .first()
1387                                        .cloned()
1388                                        .unwrap_or(JsValue::Undefined);
1389                                    let p = JsPromise::reject(v);
1390                                    return Ok(self.create_promise_value(p));
1391                                }
1392                                "all" => {
1393                                    let first = evaluated_args
1394                                        .first()
1395                                        .cloned()
1396                                        .unwrap_or_else(JsValue::empty_array);
1397                                    if let JsValue::Array(items) = first {
1398                                        let mut promise_list = Vec::new();
1399                                        for item in items.borrow().iter() {
1400                                            match item {
1401                                                JsValue::Promise(p) => {
1402                                                    promise_list.push(p.clone());
1403                                                }
1404                                                _ => {
1405                                                    promise_list
1406                                                        .push(JsPromise::resolve(item.clone()));
1407                                                }
1408                                            }
1409                                        }
1410                                        let all_p = JsPromise::all(promise_list);
1411                                        drain_microtasks();
1412                                        let mapped_p = all_p.then(JsValue::new_array);
1413                                        drain_microtasks();
1414                                        return Ok(self.create_promise_value(mapped_p));
1415                                    }
1416                                    let p = JsPromise::resolve(JsValue::empty_array());
1417                                    return Ok(self.create_promise_value(p));
1418                                }
1419                                _ => {}
1420                            }
1421                        } else if id == "Object" {
1422                            match property.as_str() {
1423                                "create" => {
1424                                    let proto =
1425                                        evaluated_args.first().cloned().unwrap_or(JsValue::Null);
1426                                    let mut new_obj = BTreeMap::new();
1427                                    if !matches!(proto, JsValue::Null) {
1428                                        new_obj.insert("__proto__".to_string(), proto);
1429                                    }
1430                                    return Ok(JsValue::new_object(new_obj));
1431                                }
1432                                "getPrototypeOf" => {
1433                                    if let Some(JsValue::Object(m)) = evaluated_args.first() {
1434                                        if let Some(p) = m.borrow().get("__proto__") {
1435                                            return Ok(p.clone());
1436                                        }
1437                                        return Ok(JsValue::new_object(
1438                                            self.object_prototype.clone(),
1439                                        ));
1440                                    }
1441                                    return Ok(JsValue::Null);
1442                                }
1443                                "setPrototypeOf" => {
1444                                    if self.freeze_prototypes || !self.allow_prototype_mutation {
1445                                        return Err(
1446                                            "TypeError: Cannot modify prototype in sealed mode"
1447                                                .to_string(),
1448                                        );
1449                                    }
1450                                    let proto =
1451                                        evaluated_args.get(1).cloned().unwrap_or(JsValue::Null);
1452                                    if let Some(JsValue::Object(m)) = evaluated_args.first() {
1453                                        m.borrow_mut().insert("__proto__".to_string(), proto);
1454                                        return Ok(JsValue::Object(m.clone()));
1455                                    }
1456                                    return Ok(JsValue::Undefined);
1457                                }
1458                                "keys" => {
1459                                    if let Some(JsValue::Object(m)) = evaluated_args.first() {
1460                                        let keys: Vec<JsValue> = m
1461                                            .borrow()
1462                                            .keys()
1463                                            .filter(|k| !k.starts_with("__"))
1464                                            .map(|k| JsValue::String(k.clone()))
1465                                            .collect();
1466                                        return Ok(JsValue::new_array(keys));
1467                                    }
1468                                    return Ok(JsValue::empty_array());
1469                                }
1470                                "values" => {
1471                                    if let Some(JsValue::Object(m)) = evaluated_args.first() {
1472                                        let vals: Vec<JsValue> = m
1473                                            .borrow()
1474                                            .iter()
1475                                            .filter(|(k, _)| !k.starts_with("__"))
1476                                            .map(|(_, v)| v.clone())
1477                                            .collect();
1478                                        return Ok(JsValue::new_array(vals));
1479                                    }
1480                                    return Ok(JsValue::empty_array());
1481                                }
1482                                "entries" => {
1483                                    if let Some(JsValue::Object(m)) = evaluated_args.first() {
1484                                        let entries: Vec<JsValue> = m
1485                                            .borrow()
1486                                            .iter()
1487                                            .filter(|(k, _)| !k.starts_with("__"))
1488                                            .map(|(k, v)| {
1489                                                JsValue::new_array(vec![
1490                                                    JsValue::String(k.clone()),
1491                                                    v.clone(),
1492                                                ])
1493                                            })
1494                                            .collect();
1495                                        return Ok(JsValue::new_array(entries));
1496                                    }
1497                                    return Ok(JsValue::empty_array());
1498                                }
1499                                "assign" => {
1500                                    if let Some(JsValue::Object(target)) = evaluated_args.first() {
1501                                        for src in evaluated_args.iter().skip(1) {
1502                                            if let JsValue::Object(s_map) = src {
1503                                                for (k, v) in s_map.borrow().iter() {
1504                                                    if (k == "__proto__"
1505                                                        || k == "constructor"
1506                                                        || k == "prototype")
1507                                                        && !self.allow_prototype_mutation
1508                                                    {
1509                                                        continue;
1510                                                    }
1511                                                    target
1512                                                        .borrow_mut()
1513                                                        .insert(k.clone(), v.clone());
1514                                                }
1515                                            }
1516                                        }
1517                                        return Ok(JsValue::Object(target.clone()));
1518                                    }
1519                                    return Ok(JsValue::Undefined);
1520                                }
1521                                "fromEntries" => {
1522                                    let mut map = BTreeMap::new();
1523                                    if let Some(JsValue::Array(items)) = evaluated_args.first() {
1524                                        for item in items.borrow().iter() {
1525                                            if let JsValue::Array(pair) = item {
1526                                                let p = pair.borrow();
1527                                                if let (Some(k), Some(v)) = (p.first(), p.get(1)) {
1528                                                    map.insert(k.to_string(), v.clone());
1529                                                }
1530                                            }
1531                                        }
1532                                    }
1533                                    return Ok(JsValue::new_object(map));
1534                                }
1535                                _ => {}
1536                            }
1537                        } else if id == "Reflect" {
1538                            match property.as_str() {
1539                                "get" => {
1540                                    let target = evaluated_args
1541                                        .first()
1542                                        .cloned()
1543                                        .unwrap_or(JsValue::Undefined);
1544                                    let prop_key = evaluated_args
1545                                        .get(1)
1546                                        .map(|v| v.to_string())
1547                                        .unwrap_or_default();
1548                                    return Ok(target
1549                                        .get_prop(&prop_key)
1550                                        .unwrap_or(JsValue::Undefined));
1551                                }
1552                                "set" => {
1553                                    if evaluated_args.len() >= 3 {
1554                                        let target = &evaluated_args[0];
1555                                        let prop_key = evaluated_args[1].to_string();
1556                                        let val = evaluated_args[2].clone();
1557                                        target.set_prop(prop_key, val);
1558                                        return Ok(JsValue::Bool(true));
1559                                    }
1560                                    return Ok(JsValue::Bool(false));
1561                                }
1562                                "has" => {
1563                                    let target = evaluated_args
1564                                        .first()
1565                                        .cloned()
1566                                        .unwrap_or(JsValue::Undefined);
1567                                    let prop_key = evaluated_args
1568                                        .get(1)
1569                                        .map(|v| v.to_string())
1570                                        .unwrap_or_default();
1571                                    return Ok(JsValue::Bool(target.has_prop(&prop_key)));
1572                                }
1573                                "deleteProperty" => {
1574                                    if let Some(JsValue::Object(c)) = evaluated_args.first() {
1575                                        let prop_key = evaluated_args
1576                                            .get(1)
1577                                            .map(|v| v.to_string())
1578                                            .unwrap_or_default();
1579                                        return Ok(JsValue::Bool(
1580                                            c.borrow_mut().remove(&prop_key).is_some(),
1581                                        ));
1582                                    }
1583                                    return Ok(JsValue::Bool(false));
1584                                }
1585                                "ownKeys" => {
1586                                    if let Some(JsValue::Object(c)) = evaluated_args.first() {
1587                                        let keys: Vec<JsValue> = c
1588                                            .borrow()
1589                                            .keys()
1590                                            .filter(|k| !k.starts_with("__"))
1591                                            .map(|k| JsValue::String(k.clone()))
1592                                            .collect();
1593                                        return Ok(JsValue::new_array(keys));
1594                                    }
1595                                    return Ok(JsValue::empty_array());
1596                                }
1597                                _ => {}
1598                            }
1599                        } else if id == "Date" {
1600                            match property.as_str() {
1601                                "now" => {
1602                                    let now = std::time::SystemTime::now()
1603                                        .duration_since(std::time::UNIX_EPOCH)
1604                                        .map(|d| d.as_millis() as f64)
1605                                        .unwrap_or(0.0);
1606                                    return Ok(JsValue::Number(now));
1607                                }
1608                                "parse" => {
1609                                    if let Some(date_str) =
1610                                        evaluated_args.first().and_then(|v| v.as_str())
1611                                    {
1612                                        if let Ok(ts) = date_str.parse::<f64>() {
1613                                            return Ok(JsValue::Number(ts));
1614                                        }
1615                                    }
1616                                    return Ok(JsValue::Number(f64::NAN));
1617                                }
1618                                _ => {}
1619                            }
1620                        } else if id == "BigInt" {
1621                            if let Some(val) = evaluated_args.first() {
1622                                return self.to_bigint(val);
1623                            }
1624                            return Err(
1625                                "TypeError: Cannot convert undefined to a BigInt".to_string()
1626                            );
1627                        } else if id == "Symbol" {
1628                            match property.as_str() {
1629                                "for" => {
1630                                    let key = evaluated_args
1631                                        .first()
1632                                        .map(|v| v.to_string())
1633                                        .unwrap_or_default();
1634                                    if let Some(sym_id) = self.symbol_registry.get(&key) {
1635                                        return Ok(JsValue::Symbol(sym_id.clone()));
1636                                    }
1637                                    let id = self.next_symbol_id;
1638                                    self.next_symbol_id += 1;
1639                                    let sym = SymbolId::new(id, Some(key.clone()));
1640                                    self.symbol_registry.insert(key, sym.clone());
1641                                    return Ok(JsValue::Symbol(sym));
1642                                }
1643                                "keyFor" => {
1644                                    if let Some(JsValue::Symbol(sym)) = evaluated_args.first() {
1645                                        for (k, v) in &self.symbol_registry {
1646                                            if v == sym {
1647                                                return Ok(JsValue::String(k.clone()));
1648                                            }
1649                                        }
1650                                    }
1651                                    return Ok(JsValue::Undefined);
1652                                }
1653                                _ => {}
1654                            }
1655                        }
1656                    }
1657
1658                    // Array prototype method calls: arr.push, arr.map, arr.filter, arr.join, etc.
1659                    let obj_val = self.eval_expr(object)?;
1660                    let _obj_ident: Option<String> = if let Expr::Identifier(ref id) = &**object {
1661                        Some(id.clone())
1662                    } else {
1663                        None
1664                    };
1665
1666                    if let JsValue::Array(ref arr) = obj_val {
1667                        match property.as_str() {
1668                            "push" => {
1669                                self.allocate_bytes(evaluated_args.len().saturating_mul(16))?;
1670                                let mut b = arr.borrow_mut();
1671                                b.extend(evaluated_args);
1672                                return Ok(JsValue::Number(b.len() as f64));
1673                            }
1674                            "pop" => {
1675                                let popped = arr.borrow_mut().pop().unwrap_or(JsValue::Undefined);
1676                                return Ok(popped);
1677                            }
1678                            "map" => {
1679                                if let Some(cb) = evaluated_args.first().cloned() {
1680                                    let mut out = Vec::new();
1681                                    let b = arr.borrow();
1682                                    for (i, item) in b.iter().enumerate() {
1683                                        let res = self.call_value(
1684                                            &cb,
1685                                            vec![
1686                                                item.clone(),
1687                                                JsValue::Number(i as f64),
1688                                                obj_val.clone(),
1689                                            ],
1690                                        )?;
1691                                        out.push(res);
1692                                    }
1693                                    return Ok(JsValue::new_array(out));
1694                                }
1695                                return Ok(JsValue::empty_array());
1696                            }
1697                            "filter" => {
1698                                if let Some(cb) = evaluated_args.first().cloned() {
1699                                    let mut out = Vec::new();
1700                                    let b = arr.borrow();
1701                                    for (i, item) in b.iter().enumerate() {
1702                                        let res = self.call_value(
1703                                            &cb,
1704                                            vec![
1705                                                item.clone(),
1706                                                JsValue::Number(i as f64),
1707                                                obj_val.clone(),
1708                                            ],
1709                                        )?;
1710                                        if res.is_truthy() {
1711                                            out.push(item.clone());
1712                                        }
1713                                    }
1714                                    return Ok(JsValue::new_array(out));
1715                                }
1716                                return Ok(JsValue::empty_array());
1717                            }
1718                            "find" => {
1719                                if let Some(cb) = evaluated_args.first().cloned() {
1720                                    let b = arr.borrow();
1721                                    for (i, item) in b.iter().enumerate() {
1722                                        let res = self.call_value(
1723                                            &cb,
1724                                            vec![
1725                                                item.clone(),
1726                                                JsValue::Number(i as f64),
1727                                                obj_val.clone(),
1728                                            ],
1729                                        )?;
1730                                        if res.is_truthy() {
1731                                            return Ok(item.clone());
1732                                        }
1733                                    }
1734                                }
1735                                return Ok(JsValue::Undefined);
1736                            }
1737                            "findIndex" => {
1738                                if let Some(cb) = evaluated_args.first().cloned() {
1739                                    let b = arr.borrow();
1740                                    for (i, item) in b.iter().enumerate() {
1741                                        let res = self.call_value(
1742                                            &cb,
1743                                            vec![
1744                                                item.clone(),
1745                                                JsValue::Number(i as f64),
1746                                                obj_val.clone(),
1747                                            ],
1748                                        )?;
1749                                        if res.is_truthy() {
1750                                            return Ok(JsValue::Number(i as f64));
1751                                        }
1752                                    }
1753                                }
1754                                return Ok(JsValue::Number(-1.0));
1755                            }
1756                            "some" => {
1757                                if let Some(cb) = evaluated_args.first().cloned() {
1758                                    for (i, item) in arr.borrow().iter().enumerate() {
1759                                        let res = self.call_value(
1760                                            &cb,
1761                                            vec![
1762                                                item.clone(),
1763                                                JsValue::Number(i as f64),
1764                                                obj_val.clone(),
1765                                            ],
1766                                        )?;
1767                                        if res.is_truthy() {
1768                                            return Ok(JsValue::Bool(true));
1769                                        }
1770                                    }
1771                                }
1772                                return Ok(JsValue::Bool(false));
1773                            }
1774                            "every" => {
1775                                if let Some(cb) = evaluated_args.first().cloned() {
1776                                    for (i, item) in arr.borrow().iter().enumerate() {
1777                                        let res = self.call_value(
1778                                            &cb,
1779                                            vec![
1780                                                item.clone(),
1781                                                JsValue::Number(i as f64),
1782                                                obj_val.clone(),
1783                                            ],
1784                                        )?;
1785                                        if !res.is_truthy() {
1786                                            return Ok(JsValue::Bool(false));
1787                                        }
1788                                    }
1789                                    return Ok(JsValue::Bool(true));
1790                                }
1791                                return Ok(JsValue::Bool(true));
1792                            }
1793                            "reduce" => {
1794                                if let Some(cb) = evaluated_args.first().cloned() {
1795                                    let b = arr.borrow();
1796                                    let mut iter = b.iter();
1797                                    let mut accum = if evaluated_args.len() >= 2 {
1798                                        evaluated_args[1].clone()
1799                                    } else if let Some(first) = iter.next() {
1800                                        first.clone()
1801                                    } else {
1802                                        return Err("TypeError: Reduce of empty array with no initial value".to_string());
1803                                    };
1804                                    for (i, item) in iter.enumerate() {
1805                                        accum = self.call_value(
1806                                            &cb,
1807                                            vec![
1808                                                accum,
1809                                                item.clone(),
1810                                                JsValue::Number(i as f64),
1811                                                obj_val.clone(),
1812                                            ],
1813                                        )?;
1814                                    }
1815                                    return Ok(accum);
1816                                }
1817                                return Ok(JsValue::Undefined);
1818                            }
1819                            "reduceRight" => {
1820                                if let Some(cb) = evaluated_args.first().cloned() {
1821                                    let b = arr.borrow();
1822                                    let mut iter = b.iter().rev();
1823                                    let mut accum = if evaluated_args.len() >= 2 {
1824                                        evaluated_args[1].clone()
1825                                    } else if let Some(first) = iter.next() {
1826                                        first.clone()
1827                                    } else {
1828                                        return Err("TypeError: Reduce of empty array with no initial value".to_string());
1829                                    };
1830                                    let len = b.len();
1831                                    for (i, item) in iter.enumerate() {
1832                                        let actual_idx = len - 1 - (i + 1);
1833                                        accum = self.call_value(
1834                                            &cb,
1835                                            vec![
1836                                                accum,
1837                                                item.clone(),
1838                                                JsValue::Number(actual_idx as f64),
1839                                                obj_val.clone(),
1840                                            ],
1841                                        )?;
1842                                    }
1843                                    return Ok(accum);
1844                                }
1845                                return Ok(JsValue::Undefined);
1846                            }
1847                            "join" => {
1848                                let sep = evaluated_args
1849                                    .first()
1850                                    .and_then(|v| v.as_str())
1851                                    .unwrap_or(",");
1852                                return Ok(JsValue::String(obj_val.join(sep)));
1853                            }
1854                            "slice" => {
1855                                let start = evaluated_args
1856                                    .first()
1857                                    .and_then(|v| v.as_f64())
1858                                    .unwrap_or(0.0)
1859                                    as isize;
1860                                let end = evaluated_args
1861                                    .get(1)
1862                                    .and_then(|v| v.as_f64())
1863                                    .map(|n| n as isize);
1864                                return Ok(obj_val.slice(start, end));
1865                            }
1866                            "concat" => {
1867                                let mut result = arr.borrow().clone();
1868                                for arg in evaluated_args {
1869                                    match arg {
1870                                        JsValue::Array(items) => {
1871                                            result.extend(items.borrow().clone())
1872                                        }
1873                                        other => result.push(other),
1874                                    }
1875                                }
1876                                return Ok(JsValue::new_array(result));
1877                            }
1878                            "includes" => {
1879                                if let Some(item) = evaluated_args.first() {
1880                                    return Ok(JsValue::Bool(obj_val.includes(item)));
1881                                }
1882                                return Ok(JsValue::Bool(false));
1883                            }
1884                            "indexOf" => {
1885                                if let Some(target) = evaluated_args.first() {
1886                                    for (i, item) in arr.borrow().iter().enumerate() {
1887                                        if item.strict_eq(target) {
1888                                            return Ok(JsValue::Number(i as f64));
1889                                        }
1890                                    }
1891                                }
1892                                return Ok(JsValue::Number(-1.0));
1893                            }
1894                            "reverse" => {
1895                                arr.borrow_mut().reverse();
1896                                return Ok(obj_val.clone());
1897                            }
1898                            "flat" => {
1899                                let depth = evaluated_args
1900                                    .first()
1901                                    .and_then(|v| v.as_f64())
1902                                    .unwrap_or(1.0)
1903                                    as usize;
1904                                return Ok(obj_val.flat(depth));
1905                            }
1906                            "flatMap" => {
1907                                if let Some(cb) = evaluated_args.first().cloned() {
1908                                    let mut out = Vec::new();
1909                                    let b = arr.borrow();
1910                                    for (i, item) in b.iter().enumerate() {
1911                                        let res = self.call_value(
1912                                            &cb,
1913                                            vec![
1914                                                item.clone(),
1915                                                JsValue::Number(i as f64),
1916                                                obj_val.clone(),
1917                                            ],
1918                                        )?;
1919                                        if let JsValue::Array(inner) = res {
1920                                            out.extend(inner.borrow().clone());
1921                                        } else {
1922                                            out.push(res);
1923                                        }
1924                                    }
1925                                    return Ok(JsValue::new_array(out));
1926                                }
1927                                return Ok(JsValue::empty_array());
1928                            }
1929                            "at" => {
1930                                let b = arr.borrow();
1931                                let idx_f = evaluated_args
1932                                    .first()
1933                                    .and_then(|v| v.as_f64())
1934                                    .unwrap_or(0.0);
1935                                let idx = if idx_f < 0.0 {
1936                                    (b.len() as f64 + idx_f) as isize
1937                                } else {
1938                                    idx_f as isize
1939                                };
1940                                if idx >= 0 && (idx as usize) < b.len() {
1941                                    return Ok(b[idx as usize].clone());
1942                                }
1943                                return Ok(JsValue::Undefined);
1944                            }
1945                            "sort" => {
1946                                if let Some(cb) = evaluated_args.first().cloned() {
1947                                    let mut sort_err = None;
1948                                    let mut cloned = arr.borrow().clone();
1949                                    cloned.sort_by(|a, b| {
1950                                        if sort_err.is_some() {
1951                                            return std::cmp::Ordering::Equal;
1952                                        }
1953                                        match self.call_value(&cb, vec![a.clone(), b.clone()]) {
1954                                            Ok(JsValue::Number(n)) => {
1955                                                if n < 0.0 {
1956                                                    std::cmp::Ordering::Less
1957                                                } else if n > 0.0 {
1958                                                    std::cmp::Ordering::Greater
1959                                                } else {
1960                                                    std::cmp::Ordering::Equal
1961                                                }
1962                                            }
1963                                            Ok(_) => std::cmp::Ordering::Equal,
1964                                            Err(e) => {
1965                                                sort_err = Some(e);
1966                                                std::cmp::Ordering::Equal
1967                                            }
1968                                        }
1969                                    });
1970                                    if let Some(err) = sort_err {
1971                                        return Err(err);
1972                                    }
1973                                    *arr.borrow_mut() = cloned;
1974                                } else {
1975                                    arr.borrow_mut().sort_by_key(|a| a.to_string());
1976                                }
1977                                return Ok(obj_val.clone());
1978                            }
1979                            _ => {}
1980                        }
1981                    }
1982
1983                    // RegExp method calls: re.test, re.exec, re.toString
1984                    if let JsValue::Object(ref map) = obj_val {
1985                        let is_re = {
1986                            let b = map.borrow();
1987                            b.get("__is_regex__") == Some(&JsValue::Bool(true))
1988                        };
1989                        if is_re {
1990                            let (source, flags) = {
1991                                let b = map.borrow();
1992                                let s = b
1993                                    .get("source")
1994                                    .and_then(|s| s.as_str())
1995                                    .unwrap_or("")
1996                                    .to_string();
1997                                let f = b
1998                                    .get("flags")
1999                                    .and_then(|s| s.as_str())
2000                                    .unwrap_or("")
2001                                    .to_string();
2002                                (s, f)
2003                            };
2004                            let re = self.compile_regex(&source, &flags)?;
2005
2006                            match property.as_str() {
2007                                "test" => {
2008                                    let input = evaluated_args
2009                                        .first()
2010                                        .map(|v| match v {
2011                                            JsValue::String(s) => s.clone(),
2012                                            other => self.to_display_string(other),
2013                                        })
2014                                        .unwrap_or_default();
2015                                    return Ok(JsValue::Bool(re.is_match(&input)));
2016                                }
2017                                "exec" => {
2018                                    let input = evaluated_args
2019                                        .first()
2020                                        .map(|v| match v {
2021                                            JsValue::String(s) => s.clone(),
2022                                            other => self.to_display_string(other),
2023                                        })
2024                                        .unwrap_or_default();
2025                                    if let Some(caps) = re.captures(&input) {
2026                                        let mut elems = Vec::new();
2027                                        for cap_opt in caps.iter() {
2028                                            match cap_opt {
2029                                                Some(m) => elems
2030                                                    .push(JsValue::String(m.as_str().to_string())),
2031                                                None => elems.push(JsValue::Undefined),
2032                                            }
2033                                        }
2034                                        if let Some(m0) = caps.get(0) {
2035                                            let last_idx = (m0.start() + m0.as_str().len()) as f64;
2036                                            map.borrow_mut().insert(
2037                                                "lastIndex".to_string(),
2038                                                JsValue::Number(last_idx),
2039                                            );
2040                                        }
2041                                        return Ok(JsValue::new_array(elems));
2042                                    } else {
2043                                        return Ok(JsValue::Null);
2044                                    }
2045                                }
2046                                "toString" => {
2047                                    return Ok(JsValue::String(format!("/{source}/{flags}")));
2048                                }
2049                                _ => {}
2050                            }
2051                        }
2052                    }
2053
2054                    // String prototype method calls: str.match, str.replace, str.replaceAll, str.search, str.split, etc.
2055                    if let JsValue::String(ref s) = obj_val {
2056                        match property.as_str() {
2057                            "match" => {
2058                                if let Some(arg) = evaluated_args.first() {
2059                                    let (pat, flags) = match arg {
2060                                        JsValue::Object(m) => {
2061                                            let b = m.borrow();
2062                                            if b.get("__is_regex__") == Some(&JsValue::Bool(true)) {
2063                                                let p = b
2064                                                    .get("source")
2065                                                    .and_then(|v| v.as_str())
2066                                                    .unwrap_or("")
2067                                                    .to_string();
2068                                                let f = b
2069                                                    .get("flags")
2070                                                    .and_then(|v| v.as_str())
2071                                                    .unwrap_or("")
2072                                                    .to_string();
2073                                                (p, f)
2074                                            } else {
2075                                                (regex::escape(&arg.to_string()), String::new())
2076                                            }
2077                                        }
2078                                        other => (regex::escape(&other.to_string()), String::new()),
2079                                    };
2080                                    let re = self.compile_regex(&pat, &flags)?;
2081                                    if flags.contains('g') {
2082                                        let matches: Vec<JsValue> = re
2083                                            .find_iter(s)
2084                                            .map(|m| JsValue::String(m.as_str().to_string()))
2085                                            .collect();
2086                                        if matches.is_empty() {
2087                                            return Ok(JsValue::Null);
2088                                        }
2089                                        return Ok(JsValue::new_array(matches));
2090                                    } else if let Some(caps) = re.captures(s) {
2091                                        let mut elems = Vec::new();
2092                                        for cap_opt in caps.iter() {
2093                                            match cap_opt {
2094                                                Some(m) => elems
2095                                                    .push(JsValue::String(m.as_str().to_string())),
2096                                                None => elems.push(JsValue::Undefined),
2097                                            }
2098                                        }
2099                                        return Ok(JsValue::new_array(elems));
2100                                    } else {
2101                                        return Ok(JsValue::Null);
2102                                    }
2103                                }
2104                                return Ok(JsValue::Null);
2105                            }
2106                            "search" => {
2107                                if let Some(arg) = evaluated_args.first() {
2108                                    let (pat, flags) = match arg {
2109                                        JsValue::Object(m) => {
2110                                            let b = m.borrow();
2111                                            if b.get("__is_regex__") == Some(&JsValue::Bool(true)) {
2112                                                let p = b
2113                                                    .get("source")
2114                                                    .and_then(|v| v.as_str())
2115                                                    .unwrap_or("")
2116                                                    .to_string();
2117                                                let f = b
2118                                                    .get("flags")
2119                                                    .and_then(|v| v.as_str())
2120                                                    .unwrap_or("")
2121                                                    .to_string();
2122                                                (p, f)
2123                                            } else {
2124                                                (regex::escape(&arg.to_string()), String::new())
2125                                            }
2126                                        }
2127                                        other => (regex::escape(&other.to_string()), String::new()),
2128                                    };
2129                                    let re = self.compile_regex(&pat, &flags)?;
2130                                    if let Some(m) = re.find(s) {
2131                                        return Ok(JsValue::Number(m.start() as f64));
2132                                    }
2133                                }
2134                                return Ok(JsValue::Number(-1.0));
2135                            }
2136                            "replace" => {
2137                                if evaluated_args.len() >= 2 {
2138                                    let target_arg = &evaluated_args[0];
2139                                    let replacement = match &evaluated_args[1] {
2140                                        JsValue::String(rs) => rs.clone(),
2141                                        other => self.to_display_string(other),
2142                                    };
2143
2144                                    let re_info = match target_arg {
2145                                        JsValue::Object(m) => {
2146                                            let b = m.borrow();
2147                                            if b.get("__is_regex__") == Some(&JsValue::Bool(true)) {
2148                                                let p = b
2149                                                    .get("source")
2150                                                    .and_then(|v| v.as_str())
2151                                                    .unwrap_or("")
2152                                                    .to_string();
2153                                                let f = b
2154                                                    .get("flags")
2155                                                    .and_then(|v| v.as_str())
2156                                                    .unwrap_or("")
2157                                                    .to_string();
2158                                                Some((p, f))
2159                                            } else {
2160                                                None
2161                                            }
2162                                        }
2163                                        _ => None,
2164                                    };
2165                                    if let Some((p, f)) = re_info {
2166                                        let re = self.compile_regex(&p, &f)?;
2167                                        if f.contains('g') {
2168                                            let res = re.replace_all(s, replacement.as_str());
2169                                            return Ok(JsValue::String(res.to_string()));
2170                                        } else {
2171                                            let res = re.replace(s, replacement.as_str());
2172                                            return Ok(JsValue::String(res.to_string()));
2173                                        }
2174                                    } else {
2175                                        let search_str = target_arg.to_string();
2176                                        let res = s.replacen(&search_str, &replacement, 1);
2177                                        return Ok(JsValue::String(res));
2178                                    }
2179                                }
2180                                return Ok(JsValue::String(s.clone()));
2181                            }
2182                            "replaceAll" => {
2183                                if evaluated_args.len() >= 2 {
2184                                    let target_arg = &evaluated_args[0];
2185                                    let replacement = match &evaluated_args[1] {
2186                                        JsValue::String(rs) => rs.clone(),
2187                                        other => self.to_display_string(other),
2188                                    };
2189
2190                                    let re_info = match target_arg {
2191                                        JsValue::Object(m) => {
2192                                            let b = m.borrow();
2193                                            if b.get("__is_regex__") == Some(&JsValue::Bool(true)) {
2194                                                let p = b
2195                                                    .get("source")
2196                                                    .and_then(|v| v.as_str())
2197                                                    .unwrap_or("")
2198                                                    .to_string();
2199                                                let f = b
2200                                                    .get("flags")
2201                                                    .and_then(|v| v.as_str())
2202                                                    .unwrap_or("")
2203                                                    .to_string();
2204                                                Some((p, f))
2205                                            } else {
2206                                                None
2207                                            }
2208                                        }
2209                                        _ => None,
2210                                    };
2211                                    if let Some((p, f)) = re_info {
2212                                        let re = self.compile_regex(&p, &f)?;
2213                                        let res = re.replace_all(s, replacement.as_str());
2214                                        return Ok(JsValue::String(res.to_string()));
2215                                    } else {
2216                                        let search_str = target_arg.to_string();
2217                                        let res = s.replace(&search_str, &replacement);
2218                                        return Ok(JsValue::String(res));
2219                                    }
2220                                }
2221                                return Ok(JsValue::String(s.clone()));
2222                            }
2223                            "split" => {
2224                                let sep_arg = evaluated_args.first();
2225                                let re_info = match sep_arg {
2226                                    Some(JsValue::Object(m)) => {
2227                                        let b = m.borrow();
2228                                        if b.get("__is_regex__") == Some(&JsValue::Bool(true)) {
2229                                            let p = b
2230                                                .get("source")
2231                                                .and_then(|v| v.as_str())
2232                                                .unwrap_or("")
2233                                                .to_string();
2234                                            let f = b
2235                                                .get("flags")
2236                                                .and_then(|v| v.as_str())
2237                                                .unwrap_or("")
2238                                                .to_string();
2239                                            Some((p, f))
2240                                        } else {
2241                                            None
2242                                        }
2243                                    }
2244                                    _ => None,
2245                                };
2246                                if let Some((p, f)) = re_info {
2247                                    let re = self.compile_regex(&p, &f)?;
2248                                    let parts: Vec<JsValue> = re
2249                                        .split(s)
2250                                        .map(|p| JsValue::String(p.to_string()))
2251                                        .collect();
2252                                    return Ok(JsValue::new_array(parts));
2253                                } else if let Some(other) = sep_arg {
2254                                    let sep = other.to_string();
2255                                    if sep.is_empty() {
2256                                        let chars: Vec<JsValue> = s
2257                                            .chars()
2258                                            .map(|c| JsValue::String(c.to_string()))
2259                                            .collect();
2260                                        return Ok(JsValue::new_array(chars));
2261                                    }
2262                                    let parts: Vec<JsValue> = s
2263                                        .split(&sep)
2264                                        .map(|p| JsValue::String(p.to_string()))
2265                                        .collect();
2266                                    return Ok(JsValue::new_array(parts));
2267                                } else {
2268                                    return Ok(JsValue::new_array(vec![JsValue::String(
2269                                        s.clone(),
2270                                    )]));
2271                                }
2272                            }
2273                            "toLowerCase" => {
2274                                return Ok(JsValue::String(s.to_lowercase()));
2275                            }
2276                            "toUpperCase" => {
2277                                return Ok(JsValue::String(s.to_uppercase()));
2278                            }
2279                            "trim" => {
2280                                return Ok(JsValue::String(s.trim().to_string()));
2281                            }
2282                            "trimStart" | "trimLeft" => {
2283                                return Ok(JsValue::String(s.trim_start().to_string()));
2284                            }
2285                            "trimEnd" | "trimRight" => {
2286                                return Ok(JsValue::String(s.trim_end().to_string()));
2287                            }
2288                            "includes" => {
2289                                let search = evaluated_args
2290                                    .first()
2291                                    .map(|v| v.to_string())
2292                                    .unwrap_or_default();
2293                                return Ok(JsValue::Bool(s.contains(&search)));
2294                            }
2295                            "indexOf" => {
2296                                let search = evaluated_args
2297                                    .first()
2298                                    .map(|v| v.to_string())
2299                                    .unwrap_or_default();
2300                                if let Some(idx) = s.find(&search) {
2301                                    return Ok(JsValue::Number(idx as f64));
2302                                }
2303                                return Ok(JsValue::Number(-1.0));
2304                            }
2305                            "startsWith" => {
2306                                let prefix = evaluated_args
2307                                    .first()
2308                                    .map(|v| v.to_string())
2309                                    .unwrap_or_default();
2310                                return Ok(JsValue::Bool(s.starts_with(&prefix)));
2311                            }
2312                            "endsWith" => {
2313                                let suffix = evaluated_args
2314                                    .first()
2315                                    .map(|v| v.to_string())
2316                                    .unwrap_or_default();
2317                                return Ok(JsValue::Bool(s.ends_with(&suffix)));
2318                            }
2319                            "charAt" => {
2320                                let idx = evaluated_args
2321                                    .first()
2322                                    .and_then(|v| v.as_f64())
2323                                    .unwrap_or(0.0)
2324                                    as usize;
2325                                let ch = s
2326                                    .chars()
2327                                    .nth(idx)
2328                                    .map(|c| c.to_string())
2329                                    .unwrap_or_default();
2330                                return Ok(JsValue::String(ch));
2331                            }
2332                            "charCodeAt" => {
2333                                let idx = evaluated_args
2334                                    .first()
2335                                    .and_then(|v| v.as_f64())
2336                                    .unwrap_or(0.0)
2337                                    as usize;
2338                                if let Some(c) = s.chars().nth(idx) {
2339                                    return Ok(JsValue::Number(c as u32 as f64));
2340                                }
2341                                return Ok(JsValue::Number(f64::NAN));
2342                            }
2343                            "slice" | "substring" => {
2344                                let start = evaluated_args
2345                                    .first()
2346                                    .and_then(|v| v.as_f64())
2347                                    .unwrap_or(0.0)
2348                                    as isize;
2349                                let end = evaluated_args
2350                                    .get(1)
2351                                    .and_then(|v| v.as_f64())
2352                                    .map(|n| n as isize);
2353                                let len = s.chars().count() as isize;
2354                                let s_idx = if start < 0 {
2355                                    (len + start).max(0) as usize
2356                                } else {
2357                                    start.min(len) as usize
2358                                };
2359                                let e_idx = match end {
2360                                    Some(e) => {
2361                                        if e < 0 {
2362                                            (len + e).max(0) as usize
2363                                        } else {
2364                                            e.min(len) as usize
2365                                        }
2366                                    }
2367                                    None => len as usize,
2368                                };
2369                                if s_idx >= e_idx {
2370                                    return Ok(JsValue::String(String::new()));
2371                                }
2372                                let sub: String =
2373                                    s.chars().skip(s_idx).take(e_idx - s_idx).collect();
2374                                return Ok(JsValue::String(sub));
2375                            }
2376                            _ => {}
2377                        }
2378                    }
2379
2380                    // DOM Node method calls: elem.appendChild, elem.insertBefore, elem.removeChild, etc.
2381                    if let JsValue::Object(ref map) = obj_val {
2382                        if let Some(node) = self.resolve_dom_node(&map.borrow()) {
2383                            match property.as_str() {
2384                                "setAttribute" => {
2385                                    if evaluated_args.len() >= 2 {
2386                                        if let (Some(k), Some(v)) =
2387                                            (evaluated_args[0].as_str(), evaluated_args[1].as_str())
2388                                        {
2389                                            node.set_attribute(k, v);
2390                                            self.document.mark_mutated();
2391                                        }
2392                                    }
2393                                    return Ok(JsValue::Undefined);
2394                                }
2395                                "getAttribute" => {
2396                                    if let Some(k) = evaluated_args.first().and_then(|v| v.as_str())
2397                                    {
2398                                        if let Some(v) = node.get_attribute(k) {
2399                                            return Ok(JsValue::String(v));
2400                                        }
2401                                    }
2402                                    return Ok(JsValue::Null);
2403                                }
2404                                "removeAttribute" => {
2405                                    if let Some(k) = evaluated_args.first().and_then(|v| v.as_str())
2406                                    {
2407                                        node.remove_attribute(k);
2408                                        self.document.mark_mutated();
2409                                    }
2410                                    return Ok(JsValue::Undefined);
2411                                }
2412                                "hasAttribute" => {
2413                                    if let Some(k) = evaluated_args.first().and_then(|v| v.as_str())
2414                                    {
2415                                        return Ok(JsValue::Bool(node.has_attribute(k)));
2416                                    }
2417                                    return Ok(JsValue::Bool(false));
2418                                }
2419                                "appendChild" => {
2420                                    if let Some(JsValue::Object(child_map)) = evaluated_args.first()
2421                                    {
2422                                        if let Some(child_node) =
2423                                            self.resolve_dom_node(&child_map.borrow())
2424                                        {
2425                                            node.append_child(child_node.clone());
2426                                            self.document.mark_mutated();
2427                                            return Ok(self.dom_node_to_js(&child_node));
2428                                        }
2429                                    }
2430                                    return Ok(JsValue::Null);
2431                                }
2432                                "prepend" => {
2433                                    if let Some(JsValue::Object(child_map)) = evaluated_args.first()
2434                                    {
2435                                        if let Some(child_node) =
2436                                            self.resolve_dom_node(&child_map.borrow())
2437                                        {
2438                                            node.prepend_child(child_node.clone());
2439                                            self.document.mark_mutated();
2440                                            return Ok(self.dom_node_to_js(&child_node));
2441                                        }
2442                                    }
2443                                    return Ok(JsValue::Null);
2444                                }
2445                                "insertBefore" => {
2446                                    if let Some(JsValue::Object(new_map)) = evaluated_args.first() {
2447                                        if let Some(new_node) =
2448                                            self.resolve_dom_node(&new_map.borrow())
2449                                        {
2450                                            let ref_node = if evaluated_args.len() >= 2 {
2451                                                if let Some(JsValue::Object(ref_map)) =
2452                                                    evaluated_args.get(1)
2453                                                {
2454                                                    self.resolve_dom_node(&ref_map.borrow())
2455                                                } else {
2456                                                    None
2457                                                }
2458                                            } else {
2459                                                None
2460                                            };
2461                                            let inserted = node.insert_before(
2462                                                new_node.clone(),
2463                                                ref_node.as_ref(),
2464                                            )?;
2465                                            self.document.mark_mutated();
2466                                            return Ok(self.dom_node_to_js(&inserted));
2467                                        }
2468                                    }
2469                                    return Ok(JsValue::Null);
2470                                }
2471                                "replaceChild" => {
2472                                    if evaluated_args.len() >= 2 {
2473                                        if let (
2474                                            Some(JsValue::Object(new_map)),
2475                                            Some(JsValue::Object(old_map)),
2476                                        ) = (evaluated_args.first(), evaluated_args.get(1))
2477                                        {
2478                                            if let (Some(new_node), Some(old_node)) = (
2479                                                self.resolve_dom_node(&new_map.borrow()),
2480                                                self.resolve_dom_node(&old_map.borrow()),
2481                                            ) {
2482                                                let replaced =
2483                                                    node.replace_child(new_node, &old_node)?;
2484                                                self.document.mark_mutated();
2485                                                return Ok(self.dom_node_to_js(&replaced));
2486                                            }
2487                                        }
2488                                    }
2489                                    return Ok(JsValue::Null);
2490                                }
2491                                "removeChild" => {
2492                                    if let Some(JsValue::Object(child_map)) = evaluated_args.first()
2493                                    {
2494                                        if let Some(child_node) =
2495                                            self.resolve_dom_node(&child_map.borrow())
2496                                        {
2497                                            let removed = node.remove_child(&child_node);
2498                                            if removed {
2499                                                self.document.mark_mutated();
2500                                                return Ok(self.dom_node_to_js(&child_node));
2501                                            }
2502                                        }
2503                                    }
2504                                    return Ok(JsValue::Null);
2505                                }
2506                                "remove" => {
2507                                    node.remove();
2508                                    self.document.mark_mutated();
2509                                    return Ok(JsValue::Undefined);
2510                                }
2511                                "cloneNode" => {
2512                                    let deep = evaluated_args
2513                                        .first()
2514                                        .map(|v| v.is_truthy())
2515                                        .unwrap_or(false);
2516                                    let cloned = node.clone_node(deep);
2517                                    return Ok(self.dom_node_to_js(&cloned));
2518                                }
2519                                "contains" => {
2520                                    if let Some(JsValue::Object(other_map)) = evaluated_args.first()
2521                                    {
2522                                        if let Some(other_node) =
2523                                            self.resolve_dom_node(&other_map.borrow())
2524                                        {
2525                                            return Ok(JsValue::Bool(node.contains(&other_node)));
2526                                        }
2527                                    }
2528                                    return Ok(JsValue::Bool(false));
2529                                }
2530                                "querySelector" => {
2531                                    if let Some(sel) =
2532                                        evaluated_args.first().and_then(|v| v.as_str())
2533                                    {
2534                                        if let Some(found) = node.query_selector(sel) {
2535                                            return Ok(self.dom_node_to_js(&found));
2536                                        }
2537                                    }
2538                                    return Ok(JsValue::Null);
2539                                }
2540                                "querySelectorAll" => {
2541                                    if let Some(sel) =
2542                                        evaluated_args.first().and_then(|v| v.as_str())
2543                                    {
2544                                        let found = node.query_selector_all(sel);
2545                                        let list: Vec<JsValue> =
2546                                            found.iter().map(|n| self.dom_node_to_js(n)).collect();
2547                                        return Ok(JsValue::new_array(list));
2548                                    }
2549                                    return Ok(JsValue::empty_array());
2550                                }
2551                                "addEventListener" => {
2552                                    if evaluated_args.len() >= 2 {
2553                                        if let Some(event) = evaluated_args[0].as_str() {
2554                                            node.add_event_listener(
2555                                                event,
2556                                                evaluated_args[1].clone(),
2557                                            );
2558                                        }
2559                                    }
2560                                    return Ok(JsValue::Undefined);
2561                                }
2562                                _ => {}
2563                            }
2564                        }
2565                    }
2566                }
2567
2568                if let Expr::Member {
2569                    object,
2570                    property,
2571                    computed: None,
2572                }
2573                | Expr::OptionalMember {
2574                    object,
2575                    property,
2576                    computed: None,
2577                } = &**callee
2578                {
2579                    let obj_val = self.eval_expr(object)?;
2580
2581                    // Promise .then / .catch / .finally with authentic JsValue::Promise support
2582                    let promise_opt = match &obj_val {
2583                        JsValue::Promise(p) => Some(p.clone()),
2584                        _ => None,
2585                    };
2586                    if let Some(promise) = promise_opt {
2587                        match property.as_str() {
2588                            "then" => {
2589                                let cb = evaluated_args.first().cloned();
2590                                let (next_promise, resolve, reject) =
2591                                    JsPromise::<JsValue>::new_pending();
2592                                let mut next_val = JsValue::Undefined;
2593                                let mut had_err = None;
2594
2595                                match promise.state() {
2596                                    PromiseState::Fulfilled(v) => {
2597                                        if let Some(ref callback) = cb {
2598                                            match self.call_value(callback, vec![v]) {
2599                                                Ok(res) => next_val = res,
2600                                                Err(e) => had_err = Some(e),
2601                                            }
2602                                        } else {
2603                                            next_val = v;
2604                                        }
2605                                    }
2606                                    PromiseState::Rejected(err) => {
2607                                        had_err = Some(err.to_string());
2608                                    }
2609                                    PromiseState::Pending => {}
2610                                }
2611
2612                                if let Some(e) = had_err {
2613                                    reject(JsValue::String(e));
2614                                } else {
2615                                    if let JsValue::Promise(ref sub_p) = next_val {
2616                                        match sub_p.state() {
2617                                            PromiseState::Fulfilled(sv) => resolve(sv),
2618                                            PromiseState::Rejected(se) => reject(se),
2619                                            PromiseState::Pending => resolve(next_val.clone()),
2620                                        }
2621                                        drain_microtasks();
2622                                        return Ok(self.create_promise_value(next_promise));
2623                                    }
2624                                    resolve(next_val);
2625                                }
2626                                drain_microtasks();
2627                                return Ok(self.create_promise_value(next_promise));
2628                            }
2629                            "catch" => {
2630                                let cb = evaluated_args.first().cloned();
2631                                let (next_promise, resolve, reject) =
2632                                    JsPromise::<JsValue>::new_pending();
2633
2634                                match promise.state() {
2635                                    PromiseState::Rejected(err) => {
2636                                        if let Some(ref callback) = cb {
2637                                            match self.call_value(callback, vec![err]) {
2638                                                Ok(recovered) => resolve(recovered),
2639                                                Err(e) => reject(JsValue::String(e)),
2640                                            }
2641                                        } else {
2642                                            reject(err);
2643                                        }
2644                                    }
2645                                    PromiseState::Fulfilled(v) => {
2646                                        resolve(v);
2647                                    }
2648                                    PromiseState::Pending => {}
2649                                }
2650                                drain_microtasks();
2651                                return Ok(self.create_promise_value(next_promise));
2652                            }
2653                            "finally" => {
2654                                let cb = evaluated_args.first().cloned();
2655                                if let Some(ref callback) = cb {
2656                                    let _ = self.call_value(callback, Vec::new());
2657                                }
2658                                drain_microtasks();
2659                                return Ok(obj_val.clone());
2660                            }
2661                            _ => {}
2662                        }
2663                    }
2664
2665                    if let JsValue::Object(ref map) = obj_val {
2666                        // Generator .next()
2667                        let gen_id_opt = {
2668                            let b = map.borrow();
2669                            if b.get("__is_generator__") == Some(&JsValue::Bool(true)) {
2670                                b.get("__gen_id__")
2671                                    .and_then(|v| v.as_f64())
2672                                    .map(|n| n as u64)
2673                            } else {
2674                                None
2675                            }
2676                        };
2677                        if let Some(gid) = gen_id_opt {
2678                            if property == "next" {
2679                                return self.step_generator(gid, evaluated_args.first().cloned());
2680                            }
2681                        }
2682
2683                        // Date methods
2684                        let date_ms_opt = {
2685                            let b = map.borrow();
2686                            if b.get("__is_date__") == Some(&JsValue::Bool(true)) {
2687                                b.get("__date_ms__").and_then(|v| v.as_f64())
2688                            } else {
2689                                None
2690                            }
2691                        };
2692                        if let Some(ms) = date_ms_opt {
2693                            return self.eval_date_method(property, ms, &evaluated_args);
2694                        }
2695
2696                        // WeakMap methods
2697                        let weak_map_id_opt = {
2698                            let b = map.borrow();
2699                            if b.get("__is_weak_map__") == Some(&JsValue::Bool(true)) {
2700                                b.get("__weak_id__")
2701                                    .and_then(|v| v.as_f64())
2702                                    .map(|n| n as u64)
2703                            } else {
2704                                None
2705                            }
2706                        };
2707                        if let Some(wid) = weak_map_id_opt {
2708                            return self.eval_weak_map_method(wid, property, &evaluated_args);
2709                        }
2710
2711                        // WeakSet methods
2712                        let weak_set_id_opt = {
2713                            let b = map.borrow();
2714                            if b.get("__is_weak_set__") == Some(&JsValue::Bool(true)) {
2715                                b.get("__weak_id__")
2716                                    .and_then(|v| v.as_f64())
2717                                    .map(|n| n as u64)
2718                            } else {
2719                                None
2720                            }
2721                        };
2722                        if let Some(wid) = weak_set_id_opt {
2723                            return self.eval_weak_set_method(wid, property, &evaluated_args);
2724                        }
2725
2726                        // WeakRef methods
2727                        let weak_ref_id_opt = {
2728                            let b = map.borrow();
2729                            if b.get("__is_weak_ref__") == Some(&JsValue::Bool(true)) {
2730                                b.get("__weak_id__")
2731                                    .and_then(|v| v.as_f64())
2732                                    .map(|n| n as u64)
2733                            } else {
2734                                None
2735                            }
2736                        };
2737                        if let Some(wid) = weak_ref_id_opt {
2738                            if property == "deref" {
2739                                let target_opt = self
2740                                    .weak_refs
2741                                    .borrow()
2742                                    .get(&wid)
2743                                    .and_then(|w| w.upgrade())
2744                                    .map(JsValue::Object);
2745                                return Ok(target_opt.unwrap_or(JsValue::Undefined));
2746                            }
2747                        }
2748
2749                        // Response methods
2750                        let is_resp =
2751                            map.borrow().get("__is_response__") == Some(&JsValue::Bool(true));
2752                        if is_resp {
2753                            let body_str = map
2754                                .borrow()
2755                                .get("__body__")
2756                                .and_then(|v| v.as_str())
2757                                .unwrap_or("")
2758                                .to_string();
2759                            match property.as_str() {
2760                                "json" => {
2761                                    let parsed =
2762                                        crate::json::parse_json(&body_str).unwrap_or(JsValue::Null);
2763                                    let p = JsPromise::resolve(parsed);
2764                                    return Ok(self.create_promise_value(p));
2765                                }
2766                                "text" => {
2767                                    let p = JsPromise::resolve(JsValue::String(body_str));
2768                                    return Ok(self.create_promise_value(p));
2769                                }
2770                                _ => {}
2771                            }
2772                        }
2773
2774                        if property == "get" && evaluated_args.len() == 1 {
2775                            if let Some(key) = evaluated_args[0].as_str() {
2776                                let b = map.borrow();
2777                                if let Some(val) = b.get(key) {
2778                                    return Ok(val.clone());
2779                                }
2780                                let key_lower = key.to_ascii_lowercase();
2781                                if let Some(val) = b.get(&key_lower) {
2782                                    return Ok(val.clone());
2783                                }
2784                            }
2785                            return Ok(JsValue::Null);
2786                        }
2787                        if property == "hasOwnProperty" && evaluated_args.len() == 1 {
2788                            let key = match &evaluated_args[0] {
2789                                JsValue::String(s) => s.clone(),
2790                                JsValue::Number(n) => format!("{n}"),
2791                                other => other.to_string(),
2792                            };
2793                            return Ok(JsValue::Bool(map.borrow().contains_key(&key)));
2794                        }
2795                        if property == "toString" && evaluated_args.is_empty() {
2796                            return Ok(JsValue::String("[object Object]".to_string()));
2797                        }
2798
2799                        let cls_opt = map.borrow().get("__class__").and_then(|v| match v {
2800                            JsValue::String(s) => Some(s.clone()),
2801                            _ => None,
2802                        });
2803                        if let Some(cls_name) = cls_opt {
2804                            if let Some((params, body, super_class_opt)) =
2805                                self.resolve_method(&cls_name, property)
2806                            {
2807                                let method_scope = Scope::new_child(self.current_scope.clone());
2808                                method_scope.borrow_mut().declare("this", obj_val.clone());
2809                                method_scope.borrow_mut().declare(
2810                                    "__current_class__",
2811                                    JsValue::String(cls_name.clone()),
2812                                );
2813                                if let Some(s_name) = super_class_opt {
2814                                    method_scope
2815                                        .borrow_mut()
2816                                        .declare("__super_class__", JsValue::String(s_name));
2817                                }
2818
2819                                bind_parameters(&params, evaluated_args, &method_scope);
2820
2821                                let saved_scope = self.current_scope.clone();
2822                                self.current_scope = method_scope.clone();
2823
2824                                let mut ret = JsValue::Undefined;
2825                                let mut err = None;
2826                                for stmt in &body {
2827                                    match self.execute_stmt_flow(stmt) {
2828                                        Ok(StatementFlow::Normal(v)) => ret = v,
2829                                        Ok(StatementFlow::Return(v)) => {
2830                                            ret = v;
2831                                            break;
2832                                        }
2833                                        Ok(StatementFlow::Throw(v)) => {
2834                                            err = Some(format!("Uncaught exception: {v}"));
2835                                            break;
2836                                        }
2837                                        Ok(StatementFlow::Break(_)) => {
2838                                            err = Some(
2839                                                "SyntaxError: Illegal break statement".to_string(),
2840                                            );
2841                                            break;
2842                                        }
2843                                        Ok(StatementFlow::Continue(_)) => {
2844                                            err = Some(
2845                                                "SyntaxError: Illegal continue statement"
2846                                                    .to_string(),
2847                                            );
2848                                            break;
2849                                        }
2850                                        Ok(StatementFlow::Yield(v)) => {
2851                                            ret = v;
2852                                            break;
2853                                        }
2854                                        Err(e) => {
2855                                            err = Some(e);
2856                                            break;
2857                                        }
2858                                    }
2859                                }
2860
2861                                self.current_scope = saved_scope;
2862                                if let Some(e) = err {
2863                                    return Err(e);
2864                                }
2865
2866                                return Ok(ret);
2867                            }
2868                        }
2869                    }
2870                }
2871
2872                // Identifier calls: check lexical scope chain -> globals -> legacy user_functions
2873                if let Expr::Identifier(fn_name) = &**callee {
2874                    let scope_val = self.current_scope.borrow().get(fn_name);
2875                    if let Some(val) = scope_val {
2876                        return self.call_value(&val, evaluated_args);
2877                    }
2878                    if let Some(val) = self.globals.get(fn_name).cloned() {
2879                        return self.call_value(&val, evaluated_args);
2880                    }
2881                    if let Some(closure) = self.user_functions.get(fn_name).cloned() {
2882                        return self.call_closure(&closure, evaluated_args);
2883                    }
2884                }
2885
2886                let this_val = match &**callee {
2887                    Expr::Member { object, .. } | Expr::OptionalMember { object, .. } => {
2888                        self.eval_expr(object).ok()
2889                    }
2890                    _ => None,
2891                };
2892                let callee_val = self.eval_expr(callee)?;
2893                self.call_value_with_this(&callee_val, evaluated_args, this_val)
2894            }
2895            Expr::OptionalCall { callee, args } => {
2896                if let Expr::OptionalMember { object, .. } | Expr::Member { object, .. } = &**callee
2897                {
2898                    let base = self.eval_expr(object)?;
2899                    if matches!(base, JsValue::Null | JsValue::Undefined) {
2900                        return Ok(JsValue::Undefined);
2901                    }
2902                }
2903                let callee_val = self.eval_expr(callee)?;
2904                if matches!(callee_val, JsValue::Null | JsValue::Undefined) {
2905                    return Ok(JsValue::Undefined);
2906                }
2907                let temp_call = Expr::Call {
2908                    callee: callee.clone(),
2909                    args: args.clone(),
2910                };
2911                self.eval_expr(&temp_call)
2912            }
2913            Expr::New { callee, args } => {
2914                let mut evaluated_args = Vec::new();
2915                for a in args {
2916                    if let Expr::Spread(inner) = a {
2917                        let spread_val = self.eval_expr(inner)?;
2918                        match spread_val {
2919                            JsValue::Array(items) => evaluated_args.extend(items.borrow().clone()),
2920                            JsValue::String(s) => {
2921                                for ch in s.chars() {
2922                                    evaluated_args.push(JsValue::String(ch.to_string()));
2923                                }
2924                            }
2925                            other => evaluated_args.push(other),
2926                        }
2927                    } else {
2928                        evaluated_args.push(self.eval_expr(a)?);
2929                    }
2930                }
2931                match &**callee {
2932                    Expr::Identifier(name) => {
2933                        if name == "Promise" {
2934                            let pid = self.next_promise_id;
2935                            self.next_promise_id += 1;
2936                            let (promise, resolve_fn, reject_fn) =
2937                                JsPromise::<JsValue>::new_pending();
2938                            self.promises.insert(pid, promise.clone());
2939                            self.promise_controllers
2940                                .insert(pid, (resolve_fn, reject_fn));
2941
2942                            if let Some(executor) = evaluated_args.first().cloned() {
2943                                let mut res_map = BTreeMap::new();
2944                                res_map.insert(
2945                                    "__fn__".to_string(),
2946                                    JsValue::String(format!("__promise_res_{pid}")),
2947                                );
2948                                let res_val = JsValue::new_object(res_map);
2949
2950                                let mut rej_map = BTreeMap::new();
2951                                rej_map.insert(
2952                                    "__fn__".to_string(),
2953                                    JsValue::String(format!("__promise_rej_{pid}")),
2954                                );
2955                                let rej_val = JsValue::new_object(rej_map);
2956
2957                                self.call_value(&executor, vec![res_val, rej_val])?;
2958                            }
2959                            drain_microtasks();
2960
2961                            Ok(JsValue::Promise(promise))
2962                        } else if matches!(
2963                            name.as_str(),
2964                            "Error" | "TypeError" | "ReferenceError" | "SyntaxError" | "RangeError"
2965                        ) {
2966                            let msg = evaluated_args
2967                                .first()
2968                                .map(|v| v.to_string())
2969                                .unwrap_or_default();
2970                            let mut map = BTreeMap::new();
2971                            map.insert("__is_error__".to_string(), JsValue::Bool(true));
2972                            map.insert("name".to_string(), JsValue::String(name.clone()));
2973                            map.insert("message".to_string(), JsValue::String(msg.clone()));
2974                            map.insert(
2975                                "stack".to_string(),
2976                                JsValue::String(format!("{name}: {msg}\n    at strata_js")),
2977                            );
2978                            map.insert(
2979                                "__proto__".to_string(),
2980                                JsValue::new_object(self.error_prototype.clone()),
2981                            );
2982                            Ok(JsValue::new_object(map))
2983                        } else if name == "Proxy" {
2984                            if evaluated_args.len() < 2 {
2985                                return Err(
2986                                    "TypeError: Cannot create Proxy with fewer than 2 arguments"
2987                                        .to_string(),
2988                                );
2989                            }
2990                            let target = evaluated_args[0].clone();
2991                            let handler = evaluated_args[1].clone();
2992                            if !matches!(
2993                                target,
2994                                JsValue::Object(_) | JsValue::Array(_) | JsValue::Function(_)
2995                            ) {
2996                                return Err(
2997                                    "TypeError: Cannot create proxy with a non-object as target"
2998                                        .to_string(),
2999                                );
3000                            }
3001                            if !matches!(handler, JsValue::Object(_)) {
3002                                return Err(
3003                                    "TypeError: Cannot create proxy with a non-object as handler"
3004                                        .to_string(),
3005                                );
3006                            }
3007                            let mut p_map = BTreeMap::new();
3008                            p_map.insert("__is_proxy__".to_string(), JsValue::Bool(true));
3009                            p_map.insert("__proxy_target__".to_string(), target);
3010                            p_map.insert("__proxy_handler__".to_string(), handler);
3011                            Ok(JsValue::new_object(p_map))
3012                        } else if name == "Date" {
3013                            let ms = if evaluated_args.is_empty() {
3014                                std::time::SystemTime::now()
3015                                    .duration_since(std::time::UNIX_EPOCH)
3016                                    .map(|d| d.as_millis() as f64)
3017                                    .unwrap_or(0.0)
3018                            } else if evaluated_args.len() == 1 {
3019                                match &evaluated_args[0] {
3020                                    JsValue::Number(n) => *n,
3021                                    JsValue::String(s) => s.parse::<f64>().unwrap_or(f64::NAN),
3022                                    _ => f64::NAN,
3023                                }
3024                            } else {
3025                                let year = evaluated_args[0].as_f64().unwrap_or(0.0);
3026                                let month = evaluated_args
3027                                    .get(1)
3028                                    .and_then(|v| v.as_f64())
3029                                    .unwrap_or(0.0);
3030                                let day = evaluated_args
3031                                    .get(2)
3032                                    .and_then(|v| v.as_f64())
3033                                    .unwrap_or(1.0);
3034                                let hours = evaluated_args
3035                                    .get(3)
3036                                    .and_then(|v| v.as_f64())
3037                                    .unwrap_or(0.0);
3038                                let minutes = evaluated_args
3039                                    .get(4)
3040                                    .and_then(|v| v.as_f64())
3041                                    .unwrap_or(0.0);
3042                                let seconds = evaluated_args
3043                                    .get(5)
3044                                    .and_then(|v| v.as_f64())
3045                                    .unwrap_or(0.0);
3046                                let ms = evaluated_args
3047                                    .get(6)
3048                                    .and_then(|v| v.as_f64())
3049                                    .unwrap_or(0.0);
3050                                crate::engine::date_to_ms(
3051                                    year, month, day, hours, minutes, seconds, ms,
3052                                )
3053                            };
3054                            let mut d_map = BTreeMap::new();
3055                            d_map.insert("__is_date__".to_string(), JsValue::Bool(true));
3056                            d_map.insert("__date_ms__".to_string(), JsValue::Number(ms));
3057                            d_map.insert(
3058                                "__proto__".to_string(),
3059                                JsValue::new_object(self.object_prototype.clone()),
3060                            );
3061                            Ok(JsValue::new_object(d_map))
3062                        } else if name == "BigInt" {
3063                            Err("TypeError: BigInt is not a constructor".to_string())
3064                        } else if name == "WeakMap" {
3065                            let wid = self.next_weak_id;
3066                            self.next_weak_id += 1;
3067                            self.weak_maps
3068                                .borrow_mut()
3069                                .insert(wid, std::collections::HashMap::new());
3070                            let mut w_map = BTreeMap::new();
3071                            w_map.insert("__is_weak_map__".to_string(), JsValue::Bool(true));
3072                            w_map.insert("__weak_id__".to_string(), JsValue::Number(wid as f64));
3073                            w_map.insert(
3074                                "__proto__".to_string(),
3075                                JsValue::new_object(self.object_prototype.clone()),
3076                            );
3077                            Ok(JsValue::new_object(w_map))
3078                        } else if name == "WeakSet" {
3079                            let wid = self.next_weak_id;
3080                            self.next_weak_id += 1;
3081                            self.weak_sets
3082                                .borrow_mut()
3083                                .insert(wid, std::collections::HashSet::new());
3084                            let mut w_map = BTreeMap::new();
3085                            w_map.insert("__is_weak_set__".to_string(), JsValue::Bool(true));
3086                            w_map.insert("__weak_id__".to_string(), JsValue::Number(wid as f64));
3087                            w_map.insert(
3088                                "__proto__".to_string(),
3089                                JsValue::new_object(self.object_prototype.clone()),
3090                            );
3091                            Ok(JsValue::new_object(w_map))
3092                        } else if name == "WeakRef" {
3093                            let target = evaluated_args
3094                                .first()
3095                                .cloned()
3096                                .unwrap_or(JsValue::Undefined);
3097                            let target_obj = match target {
3098                                JsValue::Object(ref o) => std::rc::Rc::downgrade(o),
3099                                _ => {
3100                                    return Err(
3101                                        "TypeError: \"target\" must be an object".to_string()
3102                                    )
3103                                }
3104                            };
3105                            let wid = self.next_weak_id;
3106                            self.next_weak_id += 1;
3107                            self.weak_refs.borrow_mut().insert(wid, target_obj);
3108                            let mut w_map = BTreeMap::new();
3109                            w_map.insert("__is_weak_ref__".to_string(), JsValue::Bool(true));
3110                            w_map.insert("__weak_id__".to_string(), JsValue::Number(wid as f64));
3111                            w_map.insert(
3112                                "__proto__".to_string(),
3113                                JsValue::new_object(self.object_prototype.clone()),
3114                            );
3115                            Ok(JsValue::new_object(w_map))
3116                        } else if name == "Symbol" {
3117                            Err("TypeError: Symbol is not a constructor".to_string())
3118                        } else if name == "RegExp" {
3119                            let pat = evaluated_args
3120                                .first()
3121                                .map(|v| match v {
3122                                    JsValue::Object(m)
3123                                        if m.borrow().get("__is_regex__")
3124                                            == Some(&JsValue::Bool(true)) =>
3125                                    {
3126                                        m.borrow()
3127                                            .get("source")
3128                                            .and_then(|s| s.as_str())
3129                                            .unwrap_or("")
3130                                            .to_string()
3131                                    }
3132                                    _ => v.to_string(),
3133                                })
3134                                .unwrap_or_default();
3135                            let flg = if evaluated_args.len() > 1 {
3136                                evaluated_args[1].to_string()
3137                            } else {
3138                                String::new()
3139                            };
3140                            self.create_regex_value(&pat, &flg)
3141                        } else if name == "Array" {
3142                            let arr = if evaluated_args.len() == 1 {
3143                                if let Some(JsValue::Number(n)) = evaluated_args.first() {
3144                                    if *n >= 0.0 && n.fract() == 0.0 {
3145                                        let count = *n as usize;
3146                                        self.allocate_bytes(count.saturating_mul(16))?;
3147                                        vec![JsValue::Undefined; count]
3148                                    } else {
3149                                        return Err("RangeError: Invalid array length".to_string());
3150                                    }
3151                                } else {
3152                                    self.allocate_bytes(16)?;
3153                                    evaluated_args
3154                                }
3155                            } else {
3156                                self.allocate_bytes(evaluated_args.len().saturating_mul(16))?;
3157                                evaluated_args
3158                            };
3159                            Ok(JsValue::new_array(arr))
3160                        } else if name == "Object" {
3161                            Ok(JsValue::empty_object())
3162                        } else if self.classes.contains_key(name) {
3163                            self.instantiate_class(name, evaluated_args)
3164                        } else {
3165                            Err(format!("TypeError: {name} is not a constructor"))
3166                        }
3167                    }
3168                    other => {
3169                        let callee_val = self.eval_expr(other)?;
3170                        if let JsValue::Object(ref map) = callee_val {
3171                            let cls_opt =
3172                                map.borrow().get("__class_name__").and_then(|v| match v {
3173                                    JsValue::String(s) => Some(s.clone()),
3174                                    _ => None,
3175                                });
3176                            if let Some(cls_name) = cls_opt {
3177                                if cls_name == "Promise" {
3178                                    let pid = self.next_promise_id;
3179                                    self.next_promise_id += 1;
3180                                    let (promise, resolve_fn, reject_fn) =
3181                                        JsPromise::<JsValue>::new_pending();
3182                                    self.promises.insert(pid, promise.clone());
3183                                    self.promise_controllers
3184                                        .insert(pid, (resolve_fn, reject_fn));
3185
3186                                    if let Some(executor) = evaluated_args.first().cloned() {
3187                                        let mut res_map = BTreeMap::new();
3188                                        res_map.insert(
3189                                            "__fn__".to_string(),
3190                                            JsValue::String(format!("__promise_res_{pid}")),
3191                                        );
3192                                        let res_val = JsValue::new_object(res_map);
3193
3194                                        let mut rej_map = BTreeMap::new();
3195                                        rej_map.insert(
3196                                            "__fn__".to_string(),
3197                                            JsValue::String(format!("__promise_rej_{pid}")),
3198                                        );
3199                                        let rej_val = JsValue::new_object(rej_map);
3200
3201                                        self.call_value(&executor, vec![res_val, rej_val])?;
3202                                    }
3203                                    drain_microtasks();
3204
3205                                    return Ok(JsValue::Promise(promise));
3206                                }
3207                                if self.classes.contains_key(&cls_name) {
3208                                    return self.instantiate_class(&cls_name, evaluated_args);
3209                                }
3210                            }
3211                        }
3212                        Err("TypeError: Value is not a constructor".to_string())
3213                    }
3214                }
3215            }
3216            Expr::Spread(inner) => self.eval_expr(inner),
3217            Expr::Array(items) => {
3218                let mut vals = Vec::new();
3219                for item in items {
3220                    if let Expr::Spread(inner) = item {
3221                        let spread_val = self.eval_expr(inner)?;
3222                        match spread_val {
3223                            JsValue::Array(inner_items) => {
3224                                vals.extend(inner_items.borrow().clone())
3225                            }
3226                            JsValue::String(s) => {
3227                                for ch in s.chars() {
3228                                    vals.push(JsValue::String(ch.to_string()));
3229                                }
3230                            }
3231                            other => vals.push(other),
3232                        }
3233                    } else {
3234                        vals.push(self.eval_expr(item)?);
3235                    }
3236                }
3237                Ok(JsValue::new_array(vals))
3238            }
3239            Expr::Object(pairs) => {
3240                let mut map = BTreeMap::new();
3241                for (k, v) in pairs {
3242                    if let Expr::Spread(inner) = v {
3243                        let spread_val = self.eval_expr(inner)?;
3244                        if let JsValue::Object(inner_map) = spread_val {
3245                            for (ik, iv) in inner_map.borrow().iter() {
3246                                map.insert(ik.clone(), iv.clone());
3247                            }
3248                        }
3249                    } else {
3250                        map.insert(k.clone(), self.eval_expr(v)?);
3251                    }
3252                }
3253                Ok(JsValue::new_object(map))
3254            }
3255            Expr::RegExpLiteral { pattern, flags } => self.create_regex_value(pattern, flags),
3256            Expr::Yield(inner) => {
3257                let val = if let Some(expr) = inner {
3258                    self.eval_expr(expr)?
3259                } else {
3260                    JsValue::Undefined
3261                };
3262                self.pending_yield = Some(val.clone());
3263                Ok(val)
3264            }
3265        }
3266    }
3267
3268    fn eval_member_access(
3269        &mut self,
3270        object: &Expr,
3271        obj_val: &JsValue,
3272        property: &str,
3273        computed: Option<&Expr>,
3274    ) -> Result<JsValue, String> {
3275        if matches!(obj_val, JsValue::Null | JsValue::Undefined) {
3276            return Err(format!(
3277                "TypeError: Cannot read properties of {} (reading '{}')",
3278                obj_val.js_typeof(),
3279                property
3280            ));
3281        }
3282
3283        // Check Proxy get trap
3284        if let JsValue::Object(ref map) = obj_val {
3285            let is_proxy = {
3286                let b = map.borrow();
3287                b.get("__is_proxy__") == Some(&JsValue::Bool(true))
3288            };
3289            if is_proxy {
3290                let (target, handler) = {
3291                    let b = map.borrow();
3292                    (
3293                        b.get("__proxy_target__")
3294                            .cloned()
3295                            .unwrap_or(JsValue::Undefined),
3296                        b.get("__proxy_handler__")
3297                            .cloned()
3298                            .unwrap_or(JsValue::Undefined),
3299                    )
3300                };
3301                if let JsValue::Object(ref h_cell) = handler {
3302                    let get_trap = h_cell.borrow().get("get").cloned();
3303                    if let Some(trap_fn) = get_trap {
3304                        let prop_key = match computed {
3305                            Some(comp_expr) => self.eval_expr(comp_expr)?,
3306                            None => JsValue::String(property.to_string()),
3307                        };
3308                        return self.call_value(&trap_fn, vec![target, prop_key, obj_val.clone()]);
3309                    }
3310                }
3311                return self.eval_member_access(object, &target, property, computed);
3312            }
3313        }
3314
3315        if let JsValue::Promise(_) = obj_val {
3316            let key = match computed {
3317                Some(comp_expr) => {
3318                    let prop_val = self.eval_expr(comp_expr)?;
3319                    prop_val.to_string()
3320                }
3321                None => property.to_string(),
3322            };
3323            if matches!(key.as_str(), "then" | "catch" | "finally") {
3324                let mut fn_map = BTreeMap::new();
3325                fn_map.insert(
3326                    "__fn__".to_string(),
3327                    JsValue::String(format!("__promise_method_{key}")),
3328                );
3329                return Ok(JsValue::new_object(fn_map));
3330            }
3331            if key == "Symbol(Symbol.toStringTag)" || key == "toStringTag" {
3332                return Ok(JsValue::String("Promise".to_string()));
3333            }
3334            if let Some(proto_val) = self.object_prototype.get(&key) {
3335                return Ok(proto_val.clone());
3336            }
3337            return Ok(JsValue::Undefined);
3338        }
3339
3340        if let Some(comp_expr) = computed {
3341            let prop_val = self.eval_expr(comp_expr)?;
3342            let key = match &prop_val {
3343                JsValue::String(s) => s.clone(),
3344                JsValue::Number(n) => format!("{n}"),
3345                JsValue::Symbol(s) => format!("Symbol({})", s.description.as_deref().unwrap_or("")),
3346                other => other.to_string(),
3347            };
3348            if let JsValue::Array(ref arr) = obj_val {
3349                if let Some(idx) = prop_val.as_f64() {
3350                    return Ok(arr
3351                        .borrow()
3352                        .get(idx as usize)
3353                        .cloned()
3354                        .unwrap_or(JsValue::Undefined));
3355                }
3356                if let Some(proto_val) = self.array_prototype.get(&key) {
3357                    return Ok(proto_val.clone());
3358                }
3359                if let Some(proto_val) = self.object_prototype.get(&key) {
3360                    return Ok(proto_val.clone());
3361                }
3362            }
3363            if let JsValue::Object(ref map) = obj_val {
3364                let b = map.borrow();
3365                if let Some(v) = b.get(&key) {
3366                    return Ok(v.clone());
3367                }
3368                let mut cur_proto = b.get("__proto__").cloned();
3369                let mut depth = 0;
3370                while let Some(JsValue::Object(p_map)) = cur_proto {
3371                    depth += 1;
3372                    if depth > 64 {
3373                        break;
3374                    }
3375                    let pb = p_map.borrow();
3376                    if let Some(v) = pb.get(&key) {
3377                        return Ok(v.clone());
3378                    }
3379                    cur_proto = pb.get("__proto__").cloned();
3380                }
3381                if let Some(v) = self.object_prototype.get(&key) {
3382                    return Ok(v.clone());
3383                }
3384                return Ok(JsValue::Undefined);
3385            }
3386            if let JsValue::String(ref s) = obj_val {
3387                if let Some(idx) = prop_val.as_f64() {
3388                    return Ok(s
3389                        .chars()
3390                        .nth(idx as usize)
3391                        .map(|c| JsValue::String(c.to_string()))
3392                        .unwrap_or(JsValue::Undefined));
3393                }
3394                if let Some(proto_val) = self.string_prototype.get(&key) {
3395                    return Ok(proto_val.clone());
3396                }
3397                if let Some(proto_val) = self.object_prototype.get(&key) {
3398                    return Ok(proto_val.clone());
3399                }
3400            }
3401            return Ok(JsValue::Undefined);
3402        }
3403
3404        if let Expr::Identifier(id) = object {
3405            if id == "document" {
3406                match property {
3407                    "body" => {
3408                        let mut map = BTreeMap::new();
3409                        map.insert("__is_body__".to_string(), JsValue::Bool(true));
3410                        map.insert(
3411                            "innerHTML".to_string(),
3412                            JsValue::String(self.document.body.inner_html()),
3413                        );
3414                        map.insert(
3415                            "textContent".to_string(),
3416                            JsValue::String(self.document.body.text_content()),
3417                        );
3418                        return Ok(JsValue::new_object(map));
3419                    }
3420                    "title" => {
3421                        return Ok(JsValue::String(self.document.title.borrow().clone()));
3422                    }
3423                    _ => {}
3424                }
3425            } else if id == "Symbol" {
3426                match property {
3427                    "iterator" => return Ok(JsValue::Symbol(SymbolId::iterator())),
3428                    "toStringTag" => return Ok(JsValue::Symbol(SymbolId::to_string_tag())),
3429                    "hasInstance" => return Ok(JsValue::Symbol(SymbolId::has_instance())),
3430                    "toPrimitive" => return Ok(JsValue::Symbol(SymbolId::to_primitive())),
3431                    _ => {}
3432                }
3433            } else if id == "Object" && property == "prototype" {
3434                return Ok(JsValue::new_object(self.object_prototype.clone()));
3435            } else if id == "Array" && property == "prototype" {
3436                return Ok(JsValue::new_object(self.array_prototype.clone()));
3437            } else if id == "Function" && property == "prototype" {
3438                return Ok(JsValue::new_object(self.function_prototype.clone()));
3439            } else if id == "String" && property == "prototype" {
3440                return Ok(JsValue::new_object(self.string_prototype.clone()));
3441            } else if id == "Error" && property == "prototype" {
3442                return Ok(JsValue::new_object(self.error_prototype.clone()));
3443            }
3444        }
3445
3446        if property == "length" {
3447            match obj_val {
3448                JsValue::Array(arr) => return Ok(JsValue::Number(arr.borrow().len() as f64)),
3449                JsValue::String(s) => return Ok(JsValue::Number(s.len() as f64)),
3450                _ => {}
3451            }
3452        }
3453
3454        if let JsValue::Symbol(ref sym) = obj_val {
3455            if property == "description" {
3456                return Ok(sym
3457                    .description
3458                    .as_ref()
3459                    .map(|s| JsValue::String(s.clone()))
3460                    .unwrap_or(JsValue::Undefined));
3461            }
3462            return Ok(JsValue::Undefined);
3463        }
3464
3465        if let JsValue::Array(arr) = obj_val {
3466            if let Ok(idx) = property.parse::<usize>() {
3467                return Ok(arr.borrow().get(idx).cloned().unwrap_or(JsValue::Undefined));
3468            }
3469            if let Some(proto_val) = self.array_prototype.get(property) {
3470                return Ok(proto_val.clone());
3471            }
3472            if let Some(proto_val) = self.object_prototype.get(property) {
3473                return Ok(proto_val.clone());
3474            }
3475        }
3476
3477        if let JsValue::String(_) = obj_val {
3478            if let Some(proto_val) = self.string_prototype.get(property) {
3479                return Ok(proto_val.clone());
3480            }
3481            if let Some(proto_val) = self.object_prototype.get(property) {
3482                return Ok(proto_val.clone());
3483            }
3484        }
3485
3486        if let JsValue::Function(_) = obj_val {
3487            if let Some(proto_val) = self.function_prototype.get(property) {
3488                return Ok(proto_val.clone());
3489            }
3490            if let Some(proto_val) = self.object_prototype.get(property) {
3491                return Ok(proto_val.clone());
3492            }
3493        }
3494
3495        if let JsValue::Object(ref map) = obj_val {
3496            let b = map.borrow();
3497            if let Some(node) = self.resolve_dom_node(&b) {
3498                match property {
3499                    "parentNode" => {
3500                        return Ok(node
3501                            .parent_node()
3502                            .map(|p| self.dom_node_to_js(&p))
3503                            .unwrap_or(JsValue::Null));
3504                    }
3505                    "parentElement" => {
3506                        return Ok(node
3507                            .parent_element()
3508                            .map(|p| self.dom_node_to_js(&p))
3509                            .unwrap_or(JsValue::Null));
3510                    }
3511                    "firstChild" => {
3512                        return Ok(node
3513                            .first_child()
3514                            .map(|c| self.dom_node_to_js(&c))
3515                            .unwrap_or(JsValue::Null));
3516                    }
3517                    "lastChild" => {
3518                        return Ok(node
3519                            .last_child()
3520                            .map(|c| self.dom_node_to_js(&c))
3521                            .unwrap_or(JsValue::Null));
3522                    }
3523                    "firstElementChild" => {
3524                        return Ok(node
3525                            .first_element_child()
3526                            .map(|c| self.dom_node_to_js(&c))
3527                            .unwrap_or(JsValue::Null));
3528                    }
3529                    "lastElementChild" => {
3530                        return Ok(node
3531                            .last_element_child()
3532                            .map(|c| self.dom_node_to_js(&c))
3533                            .unwrap_or(JsValue::Null));
3534                    }
3535                    "previousSibling" => {
3536                        return Ok(node
3537                            .previous_sibling()
3538                            .map(|s| self.dom_node_to_js(&s))
3539                            .unwrap_or(JsValue::Null));
3540                    }
3541                    "nextSibling" => {
3542                        return Ok(node
3543                            .next_sibling()
3544                            .map(|s| self.dom_node_to_js(&s))
3545                            .unwrap_or(JsValue::Null));
3546                    }
3547                    "previousElementSibling" => {
3548                        return Ok(node
3549                            .previous_element_sibling()
3550                            .map(|s| self.dom_node_to_js(&s))
3551                            .unwrap_or(JsValue::Null));
3552                    }
3553                    "nextElementSibling" => {
3554                        return Ok(node
3555                            .next_element_sibling()
3556                            .map(|s| self.dom_node_to_js(&s))
3557                            .unwrap_or(JsValue::Null));
3558                    }
3559                    "childNodes" => {
3560                        let children_js = node
3561                            .children()
3562                            .iter()
3563                            .map(|c| self.dom_node_to_js(c))
3564                            .collect();
3565                        return Ok(JsValue::new_array(children_js));
3566                    }
3567                    "children" => {
3568                        let children_js = node
3569                            .children()
3570                            .iter()
3571                            .filter(|c| {
3572                                matches!(c.inner.borrow().node_type, DomNodeType::Element { .. })
3573                            })
3574                            .map(|c| self.dom_node_to_js(c))
3575                            .collect();
3576                        return Ok(JsValue::new_array(children_js));
3577                    }
3578                    "childElementCount" => {
3579                        return Ok(JsValue::Number(node.child_element_count() as f64));
3580                    }
3581                    "innerHTML" => {
3582                        return Ok(JsValue::String(node.inner_html()));
3583                    }
3584                    "outerHTML" => {
3585                        return Ok(JsValue::String(node.outer_html()));
3586                    }
3587                    "textContent" => {
3588                        return Ok(JsValue::String(node.text_content()));
3589                    }
3590                    "className" => {
3591                        return Ok(JsValue::String(node.class_name()));
3592                    }
3593                    "tagName" => {
3594                        return Ok(JsValue::String(node.tag_name().unwrap_or_default()));
3595                    }
3596                    "id" => {
3597                        return Ok(JsValue::String(node.id().unwrap_or_default()));
3598                    }
3599                    "value" => {
3600                        return Ok(JsValue::String(
3601                            node.get_attribute("value").unwrap_or_default(),
3602                        ));
3603                    }
3604                    _ => {}
3605                }
3606            }
3607
3608            if let Some(v) = b.get(property) {
3609                return Ok(v.clone());
3610            }
3611
3612            // Prototype chain traversal (__proto__)
3613            let mut cur_proto = b.get("__proto__").cloned();
3614            let mut depth = 0;
3615            while let Some(JsValue::Object(p_map)) = cur_proto {
3616                depth += 1;
3617                if depth > 64 {
3618                    break;
3619                }
3620                let pb = p_map.borrow();
3621                if let Some(v) = pb.get(property) {
3622                    return Ok(v.clone());
3623                }
3624                cur_proto = pb.get("__proto__").cloned();
3625            }
3626
3627            // Built-in Object.prototype fallback
3628            if let Some(v) = self.object_prototype.get(property) {
3629                return Ok(v.clone());
3630            }
3631
3632            return Ok(JsValue::Undefined);
3633        }
3634        Ok(JsValue::Undefined)
3635    }
3636
3637    fn resolve_dom_node(&self, map: &BTreeMap<String, JsValue>) -> Option<DomNode> {
3638        if let Some(JsValue::Number(uid)) = map.get("__uid__") {
3639            let u = *uid as u64;
3640            if let Some(node) = self.live_nodes.borrow().get(&u).cloned() {
3641                return Some(node);
3642            }
3643            if let Some(found) = self.document.get_element_by_uid(u) {
3644                self.live_nodes.borrow_mut().insert(u, found.clone());
3645                return Some(found);
3646            }
3647        }
3648        if let Some(JsValue::String(id)) = map.get("__dom_id__") {
3649            if let Some(found) = self.document.get_element_by_id(id) {
3650                self.live_nodes
3651                    .borrow_mut()
3652                    .insert(found.uid(), found.clone());
3653                return Some(found);
3654            }
3655        }
3656        None
3657    }
3658
3659    pub fn call_closure(
3660        &mut self,
3661        closure: &JsClosure,
3662        args: Vec<JsValue>,
3663    ) -> Result<JsValue, String> {
3664        self.call_closure_with_this(closure, args, None)
3665    }
3666
3667    pub fn call_closure_with_this(
3668        &mut self,
3669        closure: &JsClosure,
3670        args: Vec<JsValue>,
3671        this_val: Option<JsValue>,
3672    ) -> Result<JsValue, String> {
3673        if self.call_depth >= MAX_CALL_STACK_DEPTH {
3674            return Err("RangeError: Maximum call stack size exceeded".to_string());
3675        }
3676        self.call_depth += 1;
3677        let res = self.call_closure_inner(closure, args, this_val);
3678        self.call_depth -= 1;
3679        res
3680    }
3681
3682    fn call_closure_inner(
3683        &mut self,
3684        closure: &JsClosure,
3685        args: Vec<JsValue>,
3686        this_val: Option<JsValue>,
3687    ) -> Result<JsValue, String> {
3688        let call_scope = Scope::new_child(closure.env.clone());
3689        if let Some(t) = this_val {
3690            call_scope.borrow_mut().declare("this", t);
3691        }
3692        bind_parameters(&closure.params, args, &call_scope);
3693
3694        if closure.is_generator {
3695            let gen_id = self.next_generator_id;
3696            self.next_generator_id += 1;
3697            let instance = crate::engine::GeneratorInstance {
3698                closure: closure.clone(),
3699                scope: call_scope,
3700                pc: 0,
3701                done: false,
3702            };
3703            self.generators.borrow_mut().insert(gen_id, instance);
3704
3705            let mut gen_map = BTreeMap::new();
3706            gen_map.insert("__is_generator__".to_string(), JsValue::Bool(true));
3707            gen_map.insert("__gen_id__".to_string(), JsValue::Number(gen_id as f64));
3708            gen_map.insert(
3709                "__proto__".to_string(),
3710                JsValue::new_object(self.object_prototype.clone()),
3711            );
3712            return Ok(JsValue::new_object(gen_map));
3713        }
3714
3715        let saved_scope = self.current_scope.clone();
3716        self.current_scope = call_scope;
3717
3718        let mut ret = JsValue::Undefined;
3719        let mut thrown = None;
3720        let mut sys_err = None;
3721        for stmt in &closure.body {
3722            match self.execute_stmt_flow(stmt) {
3723                Ok(StatementFlow::Normal(v)) => ret = v,
3724                Ok(StatementFlow::Return(v)) => {
3725                    ret = v;
3726                    break;
3727                }
3728                Ok(StatementFlow::Throw(v)) => {
3729                    thrown = Some(v);
3730                    break;
3731                }
3732                Ok(StatementFlow::Break(_)) => {
3733                    sys_err = Some("SyntaxError: Illegal break statement".to_string());
3734                    break;
3735                }
3736                Ok(StatementFlow::Continue(_)) => {
3737                    sys_err = Some("SyntaxError: Illegal continue statement".to_string());
3738                    break;
3739                }
3740                Ok(StatementFlow::Yield(v)) => {
3741                    ret = v;
3742                    break;
3743                }
3744                Err(e) => {
3745                    sys_err = Some(e);
3746                    break;
3747                }
3748            }
3749        }
3750
3751        self.current_scope = saved_scope;
3752
3753        if closure.is_async {
3754            if let Some(err_val) = thrown {
3755                let p = JsPromise::reject(err_val);
3756                return Ok(self.create_promise_value(p));
3757            }
3758            if let Some(e) = sys_err {
3759                let p = JsPromise::reject(JsValue::String(e));
3760                return Ok(self.create_promise_value(p));
3761            }
3762            if let JsValue::Promise(_) = ret {
3763                return Ok(ret);
3764            }
3765            let p = JsPromise::resolve(ret);
3766            return Ok(self.create_promise_value(p));
3767        }
3768
3769        if let Some(v) = thrown {
3770            self.pending_throw = Some(v);
3771            return Ok(JsValue::Undefined);
3772        }
3773
3774        if let Some(err_res) = sys_err {
3775            return Err(err_res);
3776        }
3777
3778        Ok(ret)
3779    }
3780
3781    pub fn step_generator(
3782        &mut self,
3783        gen_id: u64,
3784        _next_arg: Option<JsValue>,
3785    ) -> Result<JsValue, String> {
3786        let (closure, scope, mut pc, done) = match self.generators.borrow().get(&gen_id) {
3787            Some(inst) => (inst.closure.clone(), inst.scope.clone(), inst.pc, inst.done),
3788            None => return Err("TypeError: Invalid generator".to_string()),
3789        };
3790
3791        if done {
3792            let mut res = BTreeMap::new();
3793            res.insert("value".to_string(), JsValue::Undefined);
3794            res.insert("done".to_string(), JsValue::Bool(true));
3795            return Ok(JsValue::new_object(res));
3796        }
3797
3798        let saved_scope = self.current_scope.clone();
3799        self.current_scope = scope.clone();
3800
3801        let stmts = closure.body.clone();
3802        let mut ret = JsValue::Undefined;
3803        let mut yielded = false;
3804        let mut thrown = None;
3805        let mut is_done = false;
3806
3807        while pc < stmts.len() {
3808            let stmt = &stmts[pc];
3809            pc += 1;
3810
3811            match self.execute_stmt_flow(stmt) {
3812                Ok(StatementFlow::Normal(v)) => {
3813                    ret = v;
3814                    if let Some(y) = self.pending_yield.take() {
3815                        ret = y;
3816                        yielded = true;
3817                        break;
3818                    }
3819                }
3820                Ok(StatementFlow::Return(v)) => {
3821                    ret = v;
3822                    is_done = true;
3823                    break;
3824                }
3825                Ok(StatementFlow::Yield(v)) => {
3826                    ret = v;
3827                    yielded = true;
3828                    break;
3829                }
3830                Ok(StatementFlow::Throw(v)) => {
3831                    thrown = Some(v);
3832                    is_done = true;
3833                    break;
3834                }
3835                Ok(StatementFlow::Break(_)) => {
3836                    thrown = Some(JsValue::String(
3837                        "SyntaxError: Illegal break statement".to_string(),
3838                    ));
3839                    is_done = true;
3840                    break;
3841                }
3842                Ok(StatementFlow::Continue(_)) => {
3843                    thrown = Some(JsValue::String(
3844                        "SyntaxError: Illegal continue statement".to_string(),
3845                    ));
3846                    is_done = true;
3847                    break;
3848                }
3849                Err(e) => {
3850                    thrown = Some(JsValue::String(e));
3851                    is_done = true;
3852                    break;
3853                }
3854            }
3855        }
3856
3857        if pc >= stmts.len() && !yielded {
3858            is_done = true;
3859        }
3860
3861        self.current_scope = saved_scope;
3862
3863        if let Some(inst) = self.generators.borrow_mut().get_mut(&gen_id) {
3864            inst.pc = pc;
3865            inst.done = is_done;
3866        }
3867
3868        if let Some(err_val) = thrown {
3869            return Err(format!("Uncaught exception: {err_val}"));
3870        }
3871
3872        let mut res = BTreeMap::new();
3873        res.insert("value".to_string(), ret);
3874        res.insert("done".to_string(), JsValue::Bool(is_done));
3875        Ok(JsValue::new_object(res))
3876    }
3877
3878    pub fn to_bigint(&self, val: &JsValue) -> Result<JsValue, String> {
3879        match val {
3880            JsValue::BigInt(b) => Ok(JsValue::BigInt(b.clone())),
3881            JsValue::Number(n) => {
3882                if n.is_nan() || n.is_infinite() || n.fract() != 0.0 {
3883                    return Err("RangeError: The number cannot be converted to a BigInt because it is not an integer".to_string());
3884                }
3885                let s = format!("{:.0}", n);
3886                crate::bigint::JsBigInt::parse(&s).map(JsValue::BigInt)
3887            }
3888            JsValue::String(s) => {
3889                let trimmed = s.trim();
3890                if trimmed.is_empty() {
3891                    return Ok(JsValue::BigInt(crate::bigint::JsBigInt::zero()));
3892                }
3893                crate::bigint::JsBigInt::parse(trimmed).map(JsValue::BigInt)
3894            }
3895            JsValue::Bool(b) => {
3896                if *b {
3897                    crate::bigint::JsBigInt::parse("1").map(JsValue::BigInt)
3898                } else {
3899                    Ok(JsValue::BigInt(crate::bigint::JsBigInt::zero()))
3900                }
3901            }
3902            JsValue::Undefined | JsValue::Null | JsValue::Symbol(_) => {
3903                Err("TypeError: Cannot convert value to a BigInt".to_string())
3904            }
3905            JsValue::Array(_) | JsValue::Object(_) | JsValue::Promise(_) => {
3906                let s = self.to_display_string(val);
3907                self.to_bigint(&JsValue::String(s))
3908            }
3909            JsValue::Function(_) => {
3910                Err("TypeError: Cannot convert function to a BigInt".to_string())
3911            }
3912        }
3913    }
3914
3915    fn eval_date_method(
3916        &self,
3917        property: &str,
3918        ms: f64,
3919        _args: &[JsValue],
3920    ) -> Result<JsValue, String> {
3921        let (y, m, d, h, min, s, milli) = crate::engine::ms_to_date(ms);
3922        match property {
3923            "getTime" | "valueOf" => Ok(JsValue::Number(ms)),
3924            "getFullYear" => Ok(JsValue::Number(y as f64)),
3925            "getMonth" => Ok(JsValue::Number(m as f64)),
3926            "getDate" => Ok(JsValue::Number(d as f64)),
3927            "getHours" => Ok(JsValue::Number(h as f64)),
3928            "getMinutes" => Ok(JsValue::Number(min as f64)),
3929            "getSeconds" => Ok(JsValue::Number(s as f64)),
3930            "getMilliseconds" => Ok(JsValue::Number(milli as f64)),
3931            "toISOString" => Ok(JsValue::String(format!(
3932                "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}.{:03}Z",
3933                y,
3934                m + 1,
3935                d,
3936                h,
3937                min,
3938                s,
3939                milli
3940            ))),
3941            "toUTCString" => Ok(JsValue::String(format!(
3942                "{:04}-{:02}-{:02} {:02}:{:02}:{:02} GMT",
3943                y,
3944                m + 1,
3945                d,
3946                h,
3947                min,
3948                s
3949            ))),
3950            "toString" => Ok(JsValue::String(format!(
3951                "{:04}-{:02}-{:02} {:02}:{:02}:{:02}",
3952                y,
3953                m + 1,
3954                d,
3955                h,
3956                min,
3957                s
3958            ))),
3959            _ => Ok(JsValue::Undefined),
3960        }
3961    }
3962
3963    fn eval_weak_map_method(
3964        &mut self,
3965        id: u64,
3966        property: &str,
3967        args: &[JsValue],
3968    ) -> Result<JsValue, String> {
3969        let key_opt = args.first().and_then(|v| match v {
3970            JsValue::Object(o) => Some(std::rc::Rc::as_ptr(o) as usize),
3971            JsValue::Array(a) => Some(std::rc::Rc::as_ptr(a) as usize),
3972            _ => None,
3973        });
3974
3975        match property {
3976            "get" => {
3977                if let Some(k) = key_opt {
3978                    let b = self.weak_maps.borrow();
3979                    if let Some(m) = b.get(&id) {
3980                        return Ok(m.get(&k).cloned().unwrap_or(JsValue::Undefined));
3981                    }
3982                }
3983                Ok(JsValue::Undefined)
3984            }
3985            "set" => {
3986                if let Some(k) = key_opt {
3987                    let val = args.get(1).cloned().unwrap_or(JsValue::Undefined);
3988                    self.weak_maps
3989                        .borrow_mut()
3990                        .entry(id)
3991                        .or_default()
3992                        .insert(k, val);
3993                    if let Some(this_obj) = self.current_scope.borrow().get("this") {
3994                        return Ok(this_obj);
3995                    }
3996                    Ok(JsValue::Undefined)
3997                } else {
3998                    Err("TypeError: Invalid value used as weak map key".to_string())
3999                }
4000            }
4001            "has" => {
4002                if let Some(k) = key_opt {
4003                    let has = self
4004                        .weak_maps
4005                        .borrow()
4006                        .get(&id)
4007                        .map(|m| m.contains_key(&k))
4008                        .unwrap_or(false);
4009                    Ok(JsValue::Bool(has))
4010                } else {
4011                    Ok(JsValue::Bool(false))
4012                }
4013            }
4014            "delete" => {
4015                if let Some(k) = key_opt {
4016                    let removed = self
4017                        .weak_maps
4018                        .borrow_mut()
4019                        .get_mut(&id)
4020                        .map(|m| m.remove(&k).is_some())
4021                        .unwrap_or(false);
4022                    Ok(JsValue::Bool(removed))
4023                } else {
4024                    Ok(JsValue::Bool(false))
4025                }
4026            }
4027            _ => Ok(JsValue::Undefined),
4028        }
4029    }
4030
4031    fn eval_weak_set_method(
4032        &mut self,
4033        id: u64,
4034        property: &str,
4035        args: &[JsValue],
4036    ) -> Result<JsValue, String> {
4037        let key_opt = args.first().and_then(|v| match v {
4038            JsValue::Object(o) => Some(std::rc::Rc::as_ptr(o) as usize),
4039            JsValue::Array(a) => Some(std::rc::Rc::as_ptr(a) as usize),
4040            _ => None,
4041        });
4042
4043        match property {
4044            "add" => {
4045                if let Some(k) = key_opt {
4046                    self.weak_sets.borrow_mut().entry(id).or_default().insert(k);
4047                    if let Some(this_obj) = self.current_scope.borrow().get("this") {
4048                        return Ok(this_obj);
4049                    }
4050                    Ok(JsValue::Undefined)
4051                } else {
4052                    Err("TypeError: Invalid value used in weak set".to_string())
4053                }
4054            }
4055            "has" => {
4056                if let Some(k) = key_opt {
4057                    let has = self
4058                        .weak_sets
4059                        .borrow()
4060                        .get(&id)
4061                        .map(|s| s.contains(&k))
4062                        .unwrap_or(false);
4063                    Ok(JsValue::Bool(has))
4064                } else {
4065                    Ok(JsValue::Bool(false))
4066                }
4067            }
4068            "delete" => {
4069                if let Some(k) = key_opt {
4070                    let removed = self
4071                        .weak_sets
4072                        .borrow_mut()
4073                        .get_mut(&id)
4074                        .map(|s| s.remove(&k))
4075                        .unwrap_or(false);
4076                    Ok(JsValue::Bool(removed))
4077                } else {
4078                    Ok(JsValue::Bool(false))
4079                }
4080            }
4081            _ => Ok(JsValue::Undefined),
4082        }
4083    }
4084
4085    pub fn call_function(&mut self, name: &str, args: Vec<JsValue>) -> Result<JsValue, String> {
4086        if let Some(pid_str) = name.strip_prefix("__promise_res_") {
4087            if let Ok(pid) = pid_str.parse::<u64>() {
4088                if let Some((res_fn, _)) = self.promise_controllers.get(&pid).cloned() {
4089                    let val = args.first().cloned().unwrap_or(JsValue::Undefined);
4090                    res_fn(val);
4091                    drain_microtasks();
4092                    return Ok(JsValue::Undefined);
4093                }
4094            }
4095        }
4096        if let Some(pid_str) = name.strip_prefix("__promise_rej_") {
4097            if let Ok(pid) = pid_str.parse::<u64>() {
4098                if let Some((_, rej_fn)) = self.promise_controllers.get(&pid).cloned() {
4099                    let val = args.first().cloned().unwrap_or(JsValue::Undefined);
4100                    rej_fn(val);
4101                    drain_microtasks();
4102                    return Ok(JsValue::Undefined);
4103                }
4104            }
4105        }
4106
4107        if name == "BigInt" {
4108            if let Some(val) = args.first() {
4109                return self.to_bigint(val);
4110            }
4111            return Err("TypeError: Cannot convert undefined to a BigInt".to_string());
4112        }
4113
4114        if name == "RegExp" {
4115            let pat = args
4116                .first()
4117                .map(|v| match v {
4118                    JsValue::Object(m)
4119                        if m.borrow().get("__is_regex__") == Some(&JsValue::Bool(true)) =>
4120                    {
4121                        m.borrow()
4122                            .get("source")
4123                            .and_then(|s| s.as_str())
4124                            .unwrap_or("")
4125                            .to_string()
4126                    }
4127                    _ => v.to_string(),
4128                })
4129                .unwrap_or_default();
4130            let flg = if args.len() > 1 {
4131                args[1].to_string()
4132            } else {
4133                String::new()
4134            };
4135            return self.create_regex_value(&pat, &flg);
4136        }
4137
4138        if name == "setTimeout" {
4139            let callback = args.first().cloned().unwrap_or(JsValue::Undefined);
4140            let delay_ms = args
4141                .get(1)
4142                .and_then(|v| v.as_f64())
4143                .map(|n| n.max(0.0) as u64)
4144                .unwrap_or(0);
4145            let extra_args = if args.len() > 2 {
4146                args[2..].to_vec()
4147            } else {
4148                Vec::new()
4149            };
4150            let timer_id = crate::web::set_timeout(
4151                move || {
4152                    crate::engine::ENGINE_TIMER_CALLBACKS.with(|q| {
4153                        q.borrow_mut().push_back((callback, extra_args));
4154                    });
4155                },
4156                delay_ms,
4157            );
4158            return Ok(JsValue::Number(timer_id as f64));
4159        }
4160
4161        if name == "clearTimeout" {
4162            if let Some(id_num) = args.first().and_then(|v| v.as_f64()) {
4163                crate::web::clear_timeout(id_num as usize);
4164            }
4165            return Ok(JsValue::Undefined);
4166        }
4167
4168        if name == "setInterval" {
4169            let callback = args.first().cloned().unwrap_or(JsValue::Undefined);
4170            let interval_ms = args
4171                .get(1)
4172                .and_then(|v| v.as_f64())
4173                .map(|n| n.max(0.0) as u64)
4174                .unwrap_or(0);
4175            let extra_args = if args.len() > 2 {
4176                args[2..].to_vec()
4177            } else {
4178                Vec::new()
4179            };
4180            let timer_id = crate::web::set_interval(
4181                move || {
4182                    crate::engine::ENGINE_TIMER_CALLBACKS.with(|q| {
4183                        q.borrow_mut()
4184                            .push_back((callback.clone(), extra_args.clone()));
4185                    });
4186                },
4187                interval_ms,
4188            );
4189            return Ok(JsValue::Number(timer_id as f64));
4190        }
4191
4192        if name == "clearInterval" {
4193            if let Some(id_num) = args.first().and_then(|v| v.as_f64()) {
4194                crate::web::clear_interval(id_num as usize);
4195            }
4196            return Ok(JsValue::Undefined);
4197        }
4198
4199        if name == "fetch" {
4200            let url = args.first().map(|v| v.to_string()).unwrap_or_default();
4201            let (method, headers_vec, body_bytes) = if args.len() > 1 {
4202                if let JsValue::Object(ref init_map) = args[1] {
4203                    let ib = init_map.borrow();
4204                    let m = ib
4205                        .get("method")
4206                        .map(|v| match v {
4207                            JsValue::String(s) => s.clone(),
4208                            other => other.to_string(),
4209                        })
4210                        .unwrap_or_else(|| "GET".to_string());
4211
4212                    let mut hdrs = Vec::new();
4213                    if let Some(JsValue::Object(ref h_map)) = ib.get("headers") {
4214                        for (k, v) in h_map.borrow().iter() {
4215                            hdrs.push((
4216                                k.clone(),
4217                                match v {
4218                                    JsValue::String(s) => s.clone(),
4219                                    other => other.to_string(),
4220                                },
4221                            ));
4222                        }
4223                    }
4224
4225                    let b = ib.get("body").map(|v| match v {
4226                        JsValue::String(s) => s.as_bytes().to_vec(),
4227                        other => other.to_string().into_bytes(),
4228                    });
4229
4230                    (m, hdrs, b)
4231                } else {
4232                    ("GET".to_string(), Vec::new(), None)
4233                }
4234            } else {
4235                ("GET".to_string(), Vec::new(), None)
4236            };
4237
4238            let (promise, resolve, reject) = JsPromise::<JsValue>::new_pending();
4239
4240            // Explicit synthetic test mock URL scheme:
4241            if url.starts_with("mock://") {
4242                let mut resp_map = BTreeMap::new();
4243                resp_map.insert("__is_response__".to_string(), JsValue::Bool(true));
4244                resp_map.insert("status".to_string(), JsValue::Number(200.0));
4245                resp_map.insert("statusText".to_string(), JsValue::String("OK".to_string()));
4246                resp_map.insert("ok".to_string(), JsValue::Bool(true));
4247                resp_map.insert("url".to_string(), JsValue::String(url));
4248                let body_str = body_bytes
4249                    .and_then(|b| String::from_utf8(b).ok())
4250                    .unwrap_or_else(|| "{\"status\":\"ok\"}".to_string());
4251                resp_map.insert("__body__".to_string(), JsValue::String(body_str));
4252                let mut headers_map = BTreeMap::new();
4253                headers_map.insert(
4254                    "content-type".to_string(),
4255                    JsValue::String("application/json".to_string()),
4256                );
4257                resp_map.insert("headers".to_string(), JsValue::new_object(headers_map));
4258                resolve(JsValue::new_object(resp_map));
4259                return Ok(self.create_promise_value(promise));
4260            }
4261
4262            // Real HTTP/HTTPS fetch via host FetchHandler hook
4263            let req = crate::web::FetchRequest {
4264                url: url.clone(),
4265                method,
4266                headers: headers_vec,
4267                body: body_bytes,
4268            };
4269
4270            match crate::web::dispatch_fetch_sync(req) {
4271                Ok(resp) => {
4272                    let mut resp_map = BTreeMap::new();
4273                    resp_map.insert("__is_response__".to_string(), JsValue::Bool(true));
4274                    resp_map.insert("status".to_string(), JsValue::Number(resp.status as f64));
4275                    resp_map.insert(
4276                        "statusText".to_string(),
4277                        JsValue::String(resp.status_text.clone()),
4278                    );
4279                    resp_map.insert("ok".to_string(), JsValue::Bool(resp.ok()));
4280                    resp_map.insert("url".to_string(), JsValue::String(url));
4281                    let body_str = String::from_utf8_lossy(&resp.body).to_string();
4282                    resp_map.insert("__body__".to_string(), JsValue::String(body_str));
4283
4284                    let mut headers_map = BTreeMap::new();
4285                    for (k, v) in resp.headers {
4286                        headers_map.insert(k.to_ascii_lowercase(), JsValue::String(v));
4287                    }
4288                    resp_map.insert("headers".to_string(), JsValue::new_object(headers_map));
4289
4290                    resolve(JsValue::new_object(resp_map));
4291                }
4292                Err(err) => {
4293                    reject(JsValue::String(format!(
4294                        "TypeError: Failed to fetch: {}",
4295                        err
4296                    )));
4297                }
4298            }
4299
4300            return Ok(self.create_promise_value(promise));
4301        }
4302
4303        if name == "Symbol" {
4304            let desc = args.first().and_then(|v| match v {
4305                JsValue::String(s) => Some(s.clone()),
4306                JsValue::Undefined => None,
4307                other => Some(other.to_string()),
4308            });
4309            let id = self.next_symbol_id;
4310            self.next_symbol_id += 1;
4311            return Ok(JsValue::Symbol(SymbolId::new(id, desc)));
4312        }
4313
4314        if matches!(
4315            name,
4316            "Error" | "TypeError" | "ReferenceError" | "SyntaxError" | "RangeError"
4317        ) {
4318            let msg = args.first().map(|v| v.to_string()).unwrap_or_default();
4319            let mut map = BTreeMap::new();
4320            map.insert("__is_error__".to_string(), JsValue::Bool(true));
4321            map.insert("name".to_string(), JsValue::String(name.to_string()));
4322            map.insert("message".to_string(), JsValue::String(msg.clone()));
4323            map.insert(
4324                "stack".to_string(),
4325                JsValue::String(format!("{name}: {msg}\n    at strata_js")),
4326            );
4327            map.insert(
4328                "__proto__".to_string(),
4329                JsValue::new_object(self.error_prototype.clone()),
4330            );
4331            return Ok(JsValue::new_object(map));
4332        }
4333
4334        if name == "Object" {
4335            let first = args.first().cloned().unwrap_or_else(JsValue::empty_object);
4336            return match first {
4337                JsValue::Undefined | JsValue::Null => Ok(JsValue::empty_object()),
4338                other => Ok(other),
4339            };
4340        }
4341
4342        if name == "Array" {
4343            return Ok(JsValue::new_array(args));
4344        }
4345
4346        let scope_val = self.current_scope.borrow().get(name);
4347        if let Some(val) = scope_val {
4348            return self.call_value(&val, args);
4349        }
4350
4351        if let Some(val) = self.globals.get(name).cloned() {
4352            return self.call_value(&val, args);
4353        }
4354
4355        if let Some(closure) = self.user_functions.get(name).cloned() {
4356            return self.call_closure(&closure, args);
4357        }
4358
4359        Err(format!("Undefined function: '{name}'"))
4360    }
4361
4362    fn eval_binary(
4363        &self,
4364        op: &BinaryOp,
4365        left: &JsValue,
4366        right: &JsValue,
4367    ) -> Result<JsValue, String> {
4368        match op {
4369            BinaryOp::Add => match (left, right) {
4370                (JsValue::BigInt(a), JsValue::BigInt(b)) => Ok(JsValue::BigInt(a.add(b))),
4371                (JsValue::BigInt(_), _) | (_, JsValue::BigInt(_)) => {
4372                    if let JsValue::String(_) = left {
4373                        Ok(JsValue::String(format!(
4374                            "{}{}",
4375                            self.to_display_string(left),
4376                            self.to_display_string(right)
4377                        )))
4378                    } else if let JsValue::String(_) = right {
4379                        Ok(JsValue::String(format!(
4380                            "{}{}",
4381                            self.to_display_string(left),
4382                            self.to_display_string(right)
4383                        )))
4384                    } else {
4385                        Err("TypeError: Cannot mix BigInt and other types, use explicit conversions".to_string())
4386                    }
4387                }
4388                (JsValue::String(a), JsValue::String(b)) => Ok(JsValue::String(format!("{a}{b}"))),
4389                (JsValue::String(a), b) => {
4390                    Ok(JsValue::String(format!("{a}{}", self.to_display_string(b))))
4391                }
4392                (a, JsValue::String(b)) => {
4393                    Ok(JsValue::String(format!("{}{b}", self.to_display_string(a))))
4394                }
4395                (JsValue::Number(a), JsValue::Number(b)) => Ok(JsValue::Number(a + b)),
4396                _ => Ok(JsValue::Number(
4397                    left.as_f64().unwrap_or(0.0) + right.as_f64().unwrap_or(0.0),
4398                )),
4399            },
4400            BinaryOp::Sub => match (left, right) {
4401                (JsValue::BigInt(a), JsValue::BigInt(b)) => Ok(JsValue::BigInt(a.sub(b))),
4402                (JsValue::BigInt(_), _) | (_, JsValue::BigInt(_)) => Err(
4403                    "TypeError: Cannot mix BigInt and other types, use explicit conversions"
4404                        .to_string(),
4405                ),
4406                _ => {
4407                    let a = left.as_f64().unwrap_or(0.0);
4408                    let b = right.as_f64().unwrap_or(0.0);
4409                    Ok(JsValue::Number(a - b))
4410                }
4411            },
4412            BinaryOp::Mul => match (left, right) {
4413                (JsValue::BigInt(a), JsValue::BigInt(b)) => Ok(JsValue::BigInt(a.mul(b))),
4414                (JsValue::BigInt(_), _) | (_, JsValue::BigInt(_)) => Err(
4415                    "TypeError: Cannot mix BigInt and other types, use explicit conversions"
4416                        .to_string(),
4417                ),
4418                _ => {
4419                    let a = left.as_f64().unwrap_or(0.0);
4420                    let b = right.as_f64().unwrap_or(0.0);
4421                    Ok(JsValue::Number(a * b))
4422                }
4423            },
4424            BinaryOp::Div => match (left, right) {
4425                (JsValue::BigInt(a), JsValue::BigInt(b)) => {
4426                    if b.is_zero() {
4427                        return Err("RangeError: Division by zero".to_string());
4428                    }
4429                    Ok(JsValue::BigInt(a.div(b)?))
4430                }
4431                (JsValue::BigInt(_), _) | (_, JsValue::BigInt(_)) => Err(
4432                    "TypeError: Cannot mix BigInt and other types, use explicit conversions"
4433                        .to_string(),
4434                ),
4435                _ => {
4436                    let a = left.as_f64().unwrap_or(0.0);
4437                    let b = right.as_f64().unwrap_or(0.0);
4438                    Ok(JsValue::Number(a / b))
4439                }
4440            },
4441            BinaryOp::Mod => match (left, right) {
4442                (JsValue::BigInt(a), JsValue::BigInt(b)) => {
4443                    if b.is_zero() {
4444                        return Err("RangeError: Division by zero".to_string());
4445                    }
4446                    Ok(JsValue::BigInt(a.rem(b)?))
4447                }
4448                (JsValue::BigInt(_), _) | (_, JsValue::BigInt(_)) => Err(
4449                    "TypeError: Cannot mix BigInt and other types, use explicit conversions"
4450                        .to_string(),
4451                ),
4452                _ => {
4453                    let a = left.as_f64().unwrap_or(0.0);
4454                    let b = right.as_f64().unwrap_or(0.0);
4455                    Ok(JsValue::Number(a % b))
4456                }
4457            },
4458            BinaryOp::Power => match (left, right) {
4459                (JsValue::BigInt(a), JsValue::BigInt(b)) => Ok(JsValue::BigInt(a.pow(b)?)),
4460                (JsValue::BigInt(_), _) | (_, JsValue::BigInt(_)) => Err(
4461                    "TypeError: Cannot mix BigInt and other types, use explicit conversions"
4462                        .to_string(),
4463                ),
4464                _ => {
4465                    let a = left.as_f64().unwrap_or(0.0);
4466                    let b = right.as_f64().unwrap_or(0.0);
4467                    Ok(JsValue::Number(a.powf(b)))
4468                }
4469            },
4470            BinaryOp::BitAnd => match (left, right) {
4471                (JsValue::BigInt(a), JsValue::BigInt(b)) => Ok(JsValue::BigInt(a.bit_and(b))),
4472                (JsValue::BigInt(_), _) | (_, JsValue::BigInt(_)) => Err(
4473                    "TypeError: Cannot mix BigInt and other types, use explicit conversions"
4474                        .to_string(),
4475                ),
4476                _ => {
4477                    let a = left.as_f64().unwrap_or(0.0) as i64;
4478                    let b = right.as_f64().unwrap_or(0.0) as i64;
4479                    Ok(JsValue::Number((a & b) as f64))
4480                }
4481            },
4482            BinaryOp::BitOr => match (left, right) {
4483                (JsValue::BigInt(a), JsValue::BigInt(b)) => Ok(JsValue::BigInt(a.bit_or(b))),
4484                (JsValue::BigInt(_), _) | (_, JsValue::BigInt(_)) => Err(
4485                    "TypeError: Cannot mix BigInt and other types, use explicit conversions"
4486                        .to_string(),
4487                ),
4488                _ => {
4489                    let a = left.as_f64().unwrap_or(0.0) as i64;
4490                    let b = right.as_f64().unwrap_or(0.0) as i64;
4491                    Ok(JsValue::Number((a | b) as f64))
4492                }
4493            },
4494            BinaryOp::BitXor => match (left, right) {
4495                (JsValue::BigInt(a), JsValue::BigInt(b)) => Ok(JsValue::BigInt(a.bit_xor(b))),
4496                (JsValue::BigInt(_), _) | (_, JsValue::BigInt(_)) => Err(
4497                    "TypeError: Cannot mix BigInt and other types, use explicit conversions"
4498                        .to_string(),
4499                ),
4500                _ => {
4501                    let a = left.as_f64().unwrap_or(0.0) as i64;
4502                    let b = right.as_f64().unwrap_or(0.0) as i64;
4503                    Ok(JsValue::Number((a ^ b) as f64))
4504                }
4505            },
4506            BinaryOp::Shl => match (left, right) {
4507                (JsValue::BigInt(a), JsValue::BigInt(b)) => {
4508                    let shift = b
4509                        .to_u64()
4510                        .ok_or_else(|| "RangeError: Invalid shift amount".to_string())?
4511                        as usize;
4512                    Ok(JsValue::BigInt(a.shl(shift)))
4513                }
4514                (JsValue::BigInt(_), _) | (_, JsValue::BigInt(_)) => Err(
4515                    "TypeError: Cannot mix BigInt and other types, use explicit conversions"
4516                        .to_string(),
4517                ),
4518                _ => {
4519                    let a = left.as_f64().unwrap_or(0.0) as i32;
4520                    let b = (right.as_f64().unwrap_or(0.0) as u32) & 31;
4521                    Ok(JsValue::Number((a << b) as f64))
4522                }
4523            },
4524            BinaryOp::Shr => match (left, right) {
4525                (JsValue::BigInt(a), JsValue::BigInt(b)) => {
4526                    let shift = b
4527                        .to_u64()
4528                        .ok_or_else(|| "RangeError: Invalid shift amount".to_string())?
4529                        as usize;
4530                    Ok(JsValue::BigInt(a.shr(shift)))
4531                }
4532                (JsValue::BigInt(_), _) | (_, JsValue::BigInt(_)) => Err(
4533                    "TypeError: Cannot mix BigInt and other types, use explicit conversions"
4534                        .to_string(),
4535                ),
4536                _ => {
4537                    let a = left.as_f64().unwrap_or(0.0) as i32;
4538                    let b = (right.as_f64().unwrap_or(0.0) as u32) & 31;
4539                    Ok(JsValue::Number((a >> b) as f64))
4540                }
4541            },
4542            BinaryOp::StrictEq => Ok(JsValue::Bool(left.strict_eq(right))),
4543            BinaryOp::StrictNotEq => Ok(JsValue::Bool(!left.strict_eq(right))),
4544            BinaryOp::Eq => Ok(JsValue::Bool(left.loose_eq(right))),
4545            BinaryOp::NotEq => Ok(JsValue::Bool(!left.loose_eq(right))),
4546            BinaryOp::Lt => match (left, right) {
4547                (JsValue::BigInt(a), JsValue::BigInt(b)) => {
4548                    Ok(JsValue::Bool(a.cmp(b) == std::cmp::Ordering::Less))
4549                }
4550                _ => {
4551                    let a = left.as_f64().unwrap_or(0.0);
4552                    let b = right.as_f64().unwrap_or(0.0);
4553                    Ok(JsValue::Bool(a < b))
4554                }
4555            },
4556            BinaryOp::Lte => match (left, right) {
4557                (JsValue::BigInt(a), JsValue::BigInt(b)) => {
4558                    Ok(JsValue::Bool(a.cmp(b) != std::cmp::Ordering::Greater))
4559                }
4560                _ => {
4561                    let a = left.as_f64().unwrap_or(0.0);
4562                    let b = right.as_f64().unwrap_or(0.0);
4563                    Ok(JsValue::Bool(a <= b))
4564                }
4565            },
4566            BinaryOp::Gt => match (left, right) {
4567                (JsValue::BigInt(a), JsValue::BigInt(b)) => {
4568                    Ok(JsValue::Bool(a.cmp(b) == std::cmp::Ordering::Greater))
4569                }
4570                _ => {
4571                    let a = left.as_f64().unwrap_or(0.0);
4572                    let b = right.as_f64().unwrap_or(0.0);
4573                    Ok(JsValue::Bool(a > b))
4574                }
4575            },
4576            BinaryOp::Gte => match (left, right) {
4577                (JsValue::BigInt(a), JsValue::BigInt(b)) => {
4578                    Ok(JsValue::Bool(a.cmp(b) != std::cmp::Ordering::Less))
4579                }
4580                _ => {
4581                    let a = left.as_f64().unwrap_or(0.0);
4582                    let b = right.as_f64().unwrap_or(0.0);
4583                    Ok(JsValue::Bool(a >= b))
4584                }
4585            },
4586            BinaryOp::And => {
4587                if !left.is_truthy() {
4588                    Ok(left.clone())
4589                } else {
4590                    Ok(right.clone())
4591                }
4592            }
4593            BinaryOp::Or => {
4594                if left.is_truthy() {
4595                    Ok(left.clone())
4596                } else {
4597                    Ok(right.clone())
4598                }
4599            }
4600            BinaryOp::NullishCoalescing => {
4601                if !matches!(left, JsValue::Null | JsValue::Undefined) {
4602                    Ok(left.clone())
4603                } else {
4604                    Ok(right.clone())
4605                }
4606            }
4607            BinaryOp::InstanceOf => {
4608                let class_name = match right {
4609                    JsValue::String(s) => s.clone(),
4610                    JsValue::Object(map) => map
4611                        .borrow()
4612                        .get("__class_name__")
4613                        .and_then(|v| v.as_str())
4614                        .unwrap_or("")
4615                        .to_string(),
4616                    _ => String::new(),
4617                };
4618                Ok(JsValue::Bool(self.is_instance_of(left, &class_name)))
4619            }
4620        }
4621    }
4622
4623    fn to_display_string(&self, val: &JsValue) -> String {
4624        match val {
4625            JsValue::String(s) => s.clone(),
4626            JsValue::Number(n) => n.to_string(),
4627            JsValue::Bool(b) => b.to_string(),
4628            JsValue::BigInt(b) => format!("{b}n"),
4629            JsValue::Null => "null".to_string(),
4630            JsValue::Undefined => "undefined".to_string(),
4631            JsValue::Object(map)
4632                if map.borrow().get("__is_regex__") == Some(&JsValue::Bool(true)) =>
4633            {
4634                let b = map.borrow();
4635                let src = b.get("source").and_then(|v| v.as_str()).unwrap_or("");
4636                let flg = b.get("flags").and_then(|v| v.as_str()).unwrap_or("");
4637                format!("/{src}/{flg}")
4638            }
4639            other => stringify_json(other).unwrap_or_else(|_| "[object Object]".to_string()),
4640        }
4641    }
4642}