semver-analyzer-ts 0.0.3

TypeScript/JavaScript support for the semver-analyzer
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
//! Children slot tracing through JSX return trees.
//!
//! Traces where `{children}` or `{props.children}` appears in a component's
//! JSX return tree, recording the chain of wrapper components/elements from
//! the root of the return expression down to the children slot.
//!
//! This tells us what internal structure the component wraps around
//! consumer-provided children.
//!
//! Example for Dropdown:
//! ```tsx
//! return (
//!     <Popper popper={
//!         <Menu>
//!             <MenuContent>
//!                 {children}        ← children slot
//!             </MenuContent>
//!         </Menu>
//!     } />
//! );
//! ```
//! Result: children_slot_path = ["Popper", "Menu", "MenuContent"]

use std::collections::HashMap;

use oxc_allocator::Allocator;
use oxc_ast::ast::*;
use oxc_parser::Parser;
use oxc_span::SourceType;

/// Trace the path from JSX root to `{children}` in a component's source.
///
/// Returns the chain of component/element names that wrap the children slot.
/// Returns an empty vec if `{children}` is not found in the JSX tree.
pub fn trace_children_slot(source: &str) -> Vec<String> {
    let allocator = Allocator::default();
    let source_type = SourceType::tsx();
    let parsed = Parser::new(&allocator, source, source_type).parse();

    // Build a map of dynamic component variable aliases, e.g.:
    //   component = 'td'                       → component → "td"
    //   component: MergedComponent = component  → MergedComponent → "td"
    // This lets us resolve <MergedComponent> back to <td> in JSX.
    let aliases = collect_component_aliases(&parsed.program.body);

    let mut path = Vec::new();
    for stmt in &parsed.program.body {
        if find_children_in_statement(stmt, source, &mut path, &aliases) {
            return path;
        }
    }

    path
}

// ── Dynamic component alias resolution ──────────────────────────────────
//
// Design systems commonly use a "polymorphic component" pattern where the
// rendered HTML element comes from a prop with a string default:
//
//   const TdBase = ({ component = 'td', ... }) => {
//     const { component: MergedComponent = component, ... } = merged;
//     return <MergedComponent>{children}</MergedComponent>;
//   };
//
// The JSX AST sees `MergedComponent` (PascalCase), not `td`. We resolve
// these aliases by scanning destructuring patterns for string literal
// defaults, then following identifier-to-identifier chains.

/// Collect a map of variable names to their resolved HTML element defaults.
///
/// Scans all destructuring patterns in the source for assignments like:
///   `component = 'td'`              →  component → "td"
///   `component: Alias = component`  →  Alias → resolve("component") → "td"
///   `const Tag = 'section'`         →  Tag → "section"
fn collect_component_aliases<'a>(body: &'a [Statement<'a>]) -> HashMap<String, String> {
    let mut raw: HashMap<String, AliasValue> = HashMap::new();

    for stmt in body {
        collect_aliases_from_statement(stmt, &mut raw);
    }

    // Resolve chains: if a value is an Ident pointing to another entry, follow it
    resolve_alias_chains(&raw)
}

/// Intermediate representation for alias values before resolution.
#[derive(Clone)]
enum AliasValue {
    /// A resolved string literal like `'td'`
    Literal(String),
    /// An identifier reference like `component` (needs chain resolution)
    Ident(String),
}

fn resolve_alias_chains(raw: &HashMap<String, AliasValue>) -> HashMap<String, String> {
    let mut resolved = HashMap::new();
    for (name, value) in raw {
        if let Some(lit) = resolve_one(value, raw, 0) {
            resolved.insert(name.clone(), lit);
        }
    }
    resolved
}

fn resolve_one(value: &AliasValue, raw: &HashMap<String, AliasValue>, depth: u8) -> Option<String> {
    if depth > 5 {
        return None; // prevent infinite loops
    }
    match value {
        AliasValue::Literal(s) => Some(s.clone()),
        AliasValue::Ident(name) => raw.get(name).and_then(|v| resolve_one(v, raw, depth + 1)),
    }
}

fn collect_aliases_from_statement<'a>(
    stmt: &'a Statement<'a>,
    map: &mut HashMap<String, AliasValue>,
) {
    match stmt {
        Statement::FunctionDeclaration(f) => {
            collect_aliases_from_params(&f.params, map);
            if let Some(body) = &f.body {
                for inner in &body.statements {
                    collect_aliases_from_statement(inner, map);
                }
            }
        }
        Statement::VariableDeclaration(decl) => {
            for declarator in &decl.declarations {
                collect_aliases_from_binding(&declarator.id, map);
                // Handle `const Tag = 'section'`
                if let Some(init) = &declarator.init {
                    if let BindingPattern::BindingIdentifier(id) = &declarator.id {
                        match init {
                            Expression::StringLiteral(s) => {
                                map.insert(
                                    id.name.to_string(),
                                    AliasValue::Literal(s.value.to_string()),
                                );
                            }
                            Expression::Identifier(ident) => {
                                map.insert(
                                    id.name.to_string(),
                                    AliasValue::Ident(ident.name.to_string()),
                                );
                            }
                            _ => {
                                // Recurse into call expressions (forwardRef, memo, etc.)
                                collect_aliases_from_expression(init, map);
                            }
                        }
                    } else {
                        // Destructuring: `const { component: X = y } = expr`
                        collect_aliases_from_binding(&declarator.id, map);
                        collect_aliases_from_expression(init, map);
                    }
                }
            }
        }
        Statement::ExportNamedDeclaration(export) => {
            if let Some(decl) = &export.declaration {
                collect_aliases_from_declaration(decl, map);
            }
        }
        Statement::ExportDefaultDeclaration(export) => {
            if let Some(expr) = export.declaration.as_expression() {
                collect_aliases_from_expression(expr, map);
            }
        }
        Statement::BlockStatement(block) => {
            for inner in &block.body {
                collect_aliases_from_statement(inner, map);
            }
        }
        Statement::ReturnStatement(_) | Statement::ExpressionStatement(_) => {
            // These don't introduce bindings
        }
        _ => {}
    }
}

fn collect_aliases_from_declaration<'a>(
    decl: &'a Declaration<'a>,
    map: &mut HashMap<String, AliasValue>,
) {
    match decl {
        Declaration::FunctionDeclaration(f) => {
            collect_aliases_from_params(&f.params, map);
            if let Some(body) = &f.body {
                for stmt in &body.statements {
                    collect_aliases_from_statement(stmt, map);
                }
            }
        }
        Declaration::VariableDeclaration(var_decl) => {
            for declarator in &var_decl.declarations {
                collect_aliases_from_binding(&declarator.id, map);
                if let Some(init) = &declarator.init {
                    collect_aliases_from_expression(init, map);
                }
            }
        }
        _ => {}
    }
}

fn collect_aliases_from_expression<'a>(
    expr: &'a Expression<'a>,
    map: &mut HashMap<String, AliasValue>,
) {
    match expr {
        Expression::ArrowFunctionExpression(arrow) => {
            collect_aliases_from_params(&arrow.params, map);
            for stmt in &arrow.body.statements {
                collect_aliases_from_statement(stmt, map);
            }
        }
        Expression::FunctionExpression(func) => {
            collect_aliases_from_params(&func.params, map);
            if let Some(body) = &func.body {
                for stmt in &body.statements {
                    collect_aliases_from_statement(stmt, map);
                }
            }
        }
        Expression::CallExpression(call) => {
            // Handle forwardRef((props) => ...), memo((...) => ...), etc.
            for arg in &call.arguments {
                if let Some(expr) = arg.as_expression() {
                    collect_aliases_from_expression(expr, map);
                }
            }
        }
        Expression::ParenthesizedExpression(paren) => {
            collect_aliases_from_expression(&paren.expression, map);
        }
        _ => {}
    }
}

fn collect_aliases_from_params<'a>(
    params: &'a FormalParameters<'a>,
    map: &mut HashMap<String, AliasValue>,
) {
    for param in &params.items {
        collect_aliases_from_binding(&param.pattern, map);
    }
}

/// Extract alias mappings from destructuring patterns.
///
/// Handles:
///   `{ component = 'td' }`           → component → Literal("td")
///   `{ component: Alias = 'td' }`    → Alias → Literal("td")
///   `{ component: Alias = component }` → Alias → Ident("component")
fn collect_aliases_from_binding<'a>(
    pattern: &'a BindingPattern<'a>,
    map: &mut HashMap<String, AliasValue>,
) {
    if let BindingPattern::ObjectPattern(obj) = pattern {
        for prop in &obj.properties {
            // `{ component = 'td' }` — simple destructuring with default
            if let BindingPattern::AssignmentPattern(assign) = &prop.value {
                let binding_name = binding_pattern_name(&assign.left);
                if let Some(name) = binding_name {
                    match &assign.right {
                        Expression::StringLiteral(s) => {
                            map.insert(name, AliasValue::Literal(s.value.to_string()));
                        }
                        Expression::Identifier(ident) => {
                            map.insert(name, AliasValue::Ident(ident.name.to_string()));
                        }
                        _ => {}
                    }
                }
            }
        }
    } else if let BindingPattern::AssignmentPattern(assign) = pattern {
        let binding_name = binding_pattern_name(&assign.left);
        if let Some(name) = binding_name {
            match &assign.right {
                Expression::StringLiteral(s) => {
                    map.insert(name, AliasValue::Literal(s.value.to_string()));
                }
                Expression::Identifier(ident) => {
                    map.insert(name, AliasValue::Ident(ident.name.to_string()));
                }
                _ => {}
            }
        }
    }
}

fn binding_pattern_name(pattern: &BindingPattern) -> Option<String> {
    match pattern {
        BindingPattern::BindingIdentifier(id) => Some(id.name.to_string()),
        _ => None,
    }
}

/// Check if the source file accepts `children` as a prop at all.
///
/// Looks for `children` in destructuring patterns of function parameters.
pub fn has_children_prop(source: &str) -> bool {
    // Check destructured `children` in function/arrow params (functional components)
    let allocator = Allocator::default();
    let source_type = SourceType::tsx();
    let parsed = Parser::new(&allocator, source, source_type).parse();

    for stmt in &parsed.program.body {
        if check_children_in_statement(stmt) {
            return true;
        }
    }

    // Fallback: check for `children` in the Props interface definition
    // or `this.props.children` / `props.children` usage in class components.
    // This covers class components (e.g., Menu) that access children via
    // this.props.children in their render() method.
    source.contains("children?: React.ReactNode")
        || source.contains("children: React.ReactNode")
        || source.contains("this.props.children")
        || source.contains("props.children")
}

// ── Statement walking ───────────────────────────────────────────────────

fn find_children_in_statement<'a>(
    stmt: &'a Statement<'a>,
    source: &str,
    path: &mut Vec<String>,
    aliases: &HashMap<String, String>,
) -> bool {
    match stmt {
        Statement::FunctionDeclaration(f) => {
            if let Some(body) = &f.body {
                for inner in &body.statements {
                    if find_children_in_statement(inner, source, path, aliases) {
                        return true;
                    }
                }
            }
        }
        Statement::ReturnStatement(ret) => {
            if let Some(expr) = &ret.argument {
                return find_children_in_expression(expr, source, path, aliases);
            }
        }
        Statement::VariableDeclaration(decl) => {
            for declarator in &decl.declarations {
                if let Some(init) = &declarator.init {
                    if find_children_in_expression(init, source, path, aliases) {
                        return true;
                    }
                }
            }
        }
        Statement::ExpressionStatement(expr_stmt) => {
            return find_children_in_expression(&expr_stmt.expression, source, path, aliases);
        }
        Statement::ExportNamedDeclaration(export) => {
            if let Some(decl) = &export.declaration {
                return find_children_in_declaration(decl, source, path, aliases);
            }
        }
        Statement::ExportDefaultDeclaration(export) => {
            if let Some(expr) = export.declaration.as_expression() {
                return find_children_in_expression(expr, source, path, aliases);
            }
        }
        Statement::BlockStatement(block) => {
            for inner in &block.body {
                if find_children_in_statement(inner, source, path, aliases) {
                    return true;
                }
            }
        }
        Statement::IfStatement(if_stmt) => {
            if find_children_in_statement(&if_stmt.consequent, source, path, aliases) {
                return true;
            }
            if let Some(alt) = &if_stmt.alternate {
                if find_children_in_statement(alt, source, path, aliases) {
                    return true;
                }
            }
        }
        Statement::ClassDeclaration(class) => {
            if find_children_in_class_body(&class.body, source, path, aliases) {
                return true;
            }
        }
        _ => {}
    }
    false
}

fn find_children_in_declaration<'a>(
    decl: &'a Declaration<'a>,
    source: &str,
    path: &mut Vec<String>,
    aliases: &HashMap<String, String>,
) -> bool {
    match decl {
        Declaration::FunctionDeclaration(f) => {
            if let Some(body) = &f.body {
                for stmt in &body.statements {
                    if find_children_in_statement(stmt, source, path, aliases) {
                        return true;
                    }
                }
            }
        }
        Declaration::VariableDeclaration(var_decl) => {
            for declarator in &var_decl.declarations {
                if let Some(init) = &declarator.init {
                    if find_children_in_expression(init, source, path, aliases) {
                        return true;
                    }
                }
            }
        }
        Declaration::ClassDeclaration(class) => {
            if find_children_in_class_body(&class.body, source, path, aliases) {
                return true;
            }
        }
        _ => {}
    }
    false
}

/// Walk a class body looking for a `render()` method and trace its return
/// for `{children}` or `{this.props.children}`.
fn find_children_in_class_body<'a>(
    body: &'a ClassBody<'a>,
    source: &str,
    path: &mut Vec<String>,
    aliases: &HashMap<String, String>,
) -> bool {
    for element in &body.body {
        if let ClassElement::MethodDefinition(method) = element {
            // Match render() method by name
            let is_render = match &method.key {
                PropertyKey::StaticIdentifier(id) => id.name == "render",
                _ => false,
            };
            if is_render {
                if let Some(body) = &method.value.body {
                    for stmt in &body.statements {
                        if find_children_in_statement(stmt, source, path, aliases) {
                            return true;
                        }
                    }
                }
            }
        }
    }
    false
}

fn find_children_in_expression<'a>(
    expr: &'a Expression<'a>,
    source: &str,
    path: &mut Vec<String>,
    aliases: &HashMap<String, String>,
) -> bool {
    match expr {
        Expression::JSXElement(el) => find_children_in_jsx_element(el, source, path, aliases),
        Expression::JSXFragment(frag) => {
            for child in &frag.children {
                if find_children_in_jsx_child(child, source, path, aliases) {
                    return true;
                }
            }
            false
        }
        Expression::ParenthesizedExpression(paren) => {
            find_children_in_expression(&paren.expression, source, path, aliases)
        }
        Expression::ConditionalExpression(cond) => {
            // Check both branches
            find_children_in_expression(&cond.consequent, source, path, aliases)
                || find_children_in_expression(&cond.alternate, source, path, aliases)
        }
        Expression::LogicalExpression(logical) => {
            find_children_in_expression(&logical.right, source, path, aliases)
        }
        Expression::CallExpression(call) => {
            // Handle forwardRef((...) => ...) etc.
            for arg in &call.arguments {
                if let Some(expr) = arg.as_expression() {
                    if find_children_in_expression(expr, source, path, aliases) {
                        return true;
                    }
                }
            }
            false
        }
        Expression::ArrowFunctionExpression(arrow) => {
            for stmt in &arrow.body.statements {
                if find_children_in_statement(stmt, source, path, aliases) {
                    return true;
                }
            }
            false
        }
        Expression::FunctionExpression(func) => {
            if let Some(body) = &func.body {
                for stmt in &body.statements {
                    if find_children_in_statement(stmt, source, path, aliases) {
                        return true;
                    }
                }
            }
            false
        }
        _ => false,
    }
}

// ── JSX-specific walking ────────────────────────────────────────────────

fn find_children_in_jsx_element<'a>(
    el: &'a JSXElement<'a>,
    source: &str,
    path: &mut Vec<String>,
    aliases: &HashMap<String, String>,
) -> bool {
    let raw_tag = jsx_element_name(&el.opening_element.name);

    // Resolve dynamic component variables to their default HTML element.
    // e.g., <MergedComponent> where MergedComponent defaults to 'td'
    let tag_name = if raw_tag.starts_with(|c: char| c.is_uppercase()) {
        aliases.get(&raw_tag).cloned().unwrap_or(raw_tag)
    } else {
        raw_tag
    };

    // Check JSX props/attributes for children passed as props
    // e.g., <Popper popper={<Menu>{children}</Menu>} />
    for attr_item in &el.opening_element.attributes {
        if let JSXAttributeItem::Attribute(attr) = attr_item {
            if let Some(JSXAttributeValue::ExpressionContainer(container)) = &attr.value {
                if let Some(inner_expr) = container.expression.as_expression() {
                    path.push(tag_name.clone());
                    if find_children_in_expression(inner_expr, source, path, aliases) {
                        return true;
                    }
                    path.pop();
                }
            }
        }
    }

    // Check direct JSX children
    // We push our tag name first, then recurse. If recursion fails, we pop.
    path.push(tag_name.clone());

    for child in &el.children {
        match child {
            JSXChild::ExpressionContainer(container) => {
                if is_children_expression(&container.expression, source) {
                    return true;
                }
                // Could be a more complex expression containing children
                if let Some(expr) = container.expression.as_expression() {
                    if find_children_in_expression(expr, source, path, aliases) {
                        return true;
                    }
                }
            }
            JSXChild::Element(child_el) => {
                if find_children_in_jsx_element(child_el, source, path, aliases) {
                    return true;
                }
            }
            JSXChild::Fragment(frag) => {
                for frag_child in &frag.children {
                    if find_children_in_jsx_child(frag_child, source, path, aliases) {
                        return true;
                    }
                }
            }
            _ => {}
        }
    }

    // Children not found in this subtree, remove our tag
    path.pop();
    false
}

fn find_children_in_jsx_child<'a>(
    child: &'a JSXChild<'a>,
    source: &str,
    path: &mut Vec<String>,
    aliases: &HashMap<String, String>,
) -> bool {
    match child {
        JSXChild::Element(el) => find_children_in_jsx_element(el, source, path, aliases),
        JSXChild::ExpressionContainer(container) => {
            if is_children_expression(&container.expression, source) {
                return true;
            }
            if let Some(expr) = container.expression.as_expression() {
                return find_children_in_expression(expr, source, path, aliases);
            }
            false
        }
        JSXChild::Fragment(frag) => {
            for c in &frag.children {
                if find_children_in_jsx_child(c, source, path, aliases) {
                    return true;
                }
            }
            false
        }
        _ => false,
    }
}

/// Check if a JSX expression container holds `{children}` or `{props.children}`.
///
/// Also handles common patterns like `{mergedChildren || children}` and
/// `{someVar ?? children}` where children appears in a logical expression.
fn is_children_expression(expr: &JSXExpression, _source: &str) -> bool {
    match expr {
        JSXExpression::Identifier(id) if id.name == "children" => true,
        _ => {
            if let Some(inner) = expr.as_expression() {
                is_children_expr_inner(inner)
            } else {
                false
            }
        }
    }
}

fn is_children_expr_inner(expr: &Expression) -> bool {
    match expr {
        Expression::Identifier(id) => id.name == "children",
        Expression::StaticMemberExpression(member) => {
            if member.property.name != "children" {
                return false;
            }
            // Match props.children
            if matches!(&member.object, Expression::Identifier(id) if id.name == "props") {
                return true;
            }
            // Match this.props.children (class components)
            if let Expression::StaticMemberExpression(inner) = &member.object {
                return inner.property.name == "props"
                    && matches!(&inner.object, Expression::ThisExpression(_));
            }
            false
        }
        // Handle {mergedChildren || children}, {x ?? children}, {x && children}
        Expression::LogicalExpression(logical) => {
            is_children_expr_inner(&logical.left) || is_children_expr_inner(&logical.right)
        }
        // Handle {condition ? children : null} or {condition ? null : children}
        Expression::ConditionalExpression(cond) => {
            is_children_expr_inner(&cond.consequent) || is_children_expr_inner(&cond.alternate)
        }
        // Handle {(children)}
        Expression::ParenthesizedExpression(paren) => is_children_expr_inner(&paren.expression),
        _ => false,
    }
}

/// Get the element name from a JSX element name node.
fn jsx_element_name(name: &JSXElementName) -> String {
    match name {
        JSXElementName::Identifier(id) => id.name.to_string(),
        JSXElementName::IdentifierReference(id) => id.name.to_string(),
        JSXElementName::NamespacedName(ns) => {
            format!("{}:{}", ns.namespace.name, ns.name.name)
        }
        JSXElementName::MemberExpression(member) => {
            format!(
                "{}.{}",
                jsx_member_object(&member.object),
                member.property.name
            )
        }
        JSXElementName::ThisExpression(_) => "this".to_string(),
    }
}

fn jsx_member_object(obj: &JSXMemberExpressionObject) -> String {
    match obj {
        JSXMemberExpressionObject::IdentifierReference(id) => id.name.to_string(),
        JSXMemberExpressionObject::MemberExpression(member) => {
            format!(
                "{}.{}",
                jsx_member_object(&member.object),
                member.property.name
            )
        }
        JSXMemberExpressionObject::ThisExpression(_) => "this".to_string(),
    }
}

/// Check if any function parameter destructures `children`.
fn check_children_in_statement<'a>(stmt: &'a Statement<'a>) -> bool {
    match stmt {
        Statement::FunctionDeclaration(f) => check_children_in_params(&f.params),
        Statement::VariableDeclaration(var_decl) => {
            for declarator in &var_decl.declarations {
                if let Some(init) = &declarator.init {
                    if check_children_in_expr(init) {
                        return true;
                    }
                }
            }
            false
        }
        Statement::ExportNamedDeclaration(export) => {
            if let Some(decl) = &export.declaration {
                return check_children_in_decl(decl);
            }
            false
        }
        Statement::ExportDefaultDeclaration(export) => {
            if let Some(expr) = export.declaration.as_expression() {
                return check_children_in_expr(expr);
            }
            false
        }
        _ => false,
    }
}

fn check_children_in_decl<'a>(decl: &'a Declaration<'a>) -> bool {
    match decl {
        Declaration::FunctionDeclaration(f) => check_children_in_params(&f.params),
        Declaration::VariableDeclaration(var_decl) => {
            for declarator in &var_decl.declarations {
                if let Some(init) = &declarator.init {
                    if check_children_in_expr(init) {
                        return true;
                    }
                }
            }
            false
        }
        _ => false,
    }
}

fn check_children_in_expr<'a>(expr: &'a Expression<'a>) -> bool {
    match expr {
        Expression::ArrowFunctionExpression(arrow) => check_children_in_params(&arrow.params),
        Expression::FunctionExpression(func) => check_children_in_params(&func.params),
        Expression::CallExpression(call) => {
            for arg in &call.arguments {
                if let Some(expr) = arg.as_expression() {
                    if check_children_in_expr(expr) {
                        return true;
                    }
                }
            }
            false
        }
        Expression::ParenthesizedExpression(paren) => check_children_in_expr(&paren.expression),
        _ => false,
    }
}

fn check_children_in_params(params: &FormalParameters) -> bool {
    for param in &params.items {
        if has_children_binding(&param.pattern) {
            return true;
        }
    }
    false
}

fn has_children_binding(pattern: &BindingPattern) -> bool {
    match pattern {
        BindingPattern::ObjectPattern(obj) => {
            for prop in &obj.properties {
                match &prop.key {
                    PropertyKey::StaticIdentifier(id) if id.name == "children" => {
                        return true;
                    }
                    _ => {}
                }
            }
            false
        }
        BindingPattern::AssignmentPattern(assign) => has_children_binding(&assign.left),
        _ => false,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_trace_simple_children() {
        let source = r#"
            const MyComponent = ({ children }: Props) => (
                <div className="wrapper">
                    {children}
                </div>
            );
        "#;

        let path = trace_children_slot(source);
        assert_eq!(path, vec!["div"]);
    }

    #[test]
    fn test_trace_nested_children() {
        let source = r#"
            const Modal = ({ children }: Props) => {
                return (
                    <Backdrop>
                        <FocusTrap>
                            <ModalBox>
                                {children}
                            </ModalBox>
                        </FocusTrap>
                    </Backdrop>
                );
            };
        "#;

        let path = trace_children_slot(source);
        assert_eq!(path, vec!["Backdrop", "FocusTrap", "ModalBox"]);
    }

    #[test]
    fn test_trace_children_in_prop() {
        let source = r#"
            const Dropdown = ({ children }: Props) => {
                const menu = (
                    <Menu>
                        <MenuContent>
                            {children}
                        </MenuContent>
                    </Menu>
                );
                return (
                    <Popper popper={menu} />
                );
            };
        "#;

        let path = trace_children_slot(source);
        assert_eq!(path, vec!["Menu", "MenuContent"]);
    }

    #[test]
    fn test_has_children_prop_true() {
        let source = r#"
            export const Button = ({ children, variant }: ButtonProps) => (
                <button>{children}</button>
            );
        "#;
        assert!(has_children_prop(source));
    }

    #[test]
    fn test_has_children_prop_false() {
        let source = r#"
            export const Icon = ({ name, size }: IconProps) => (
                <svg><use href={name} /></svg>
            );
        "#;
        assert!(!has_children_prop(source));
    }

    #[test]
    fn test_trace_dynamic_component_simple() {
        // Simple case: component prop with string default used as JSX tag
        let source = r#"
            const MyCell = ({ children, component = 'td' }: Props) => {
                const Component = component;
                return <Component>{children}</Component>;
            };
        "#;

        let path = trace_children_slot(source);
        assert_eq!(path, vec!["td"]);
    }

    #[test]
    fn test_trace_dynamic_component_merged() {
        // PatternFly pattern: prop default + destructuring with rename
        let source = r#"
            const TdBase = ({ children, component = 'td' }: Props) => {
                const merged = mergeProps();
                const { component: MergedComponent = component } = merged;
                return <MergedComponent>{children}</MergedComponent>;
            };
        "#;

        let path = trace_children_slot(source);
        assert_eq!(path, vec!["td"]);
    }

    #[test]
    fn test_trace_dynamic_component_th() {
        let source = r#"
            const ThBase = ({
                children,
                component = 'th',
            }: ThProps) => {
                const { component: MergedComponent = component, ...rest } = merged;
                return (
                    <MergedComponent className="header">
                        {children}
                    </MergedComponent>
                );
            };
        "#;

        let path = trace_children_slot(source);
        assert_eq!(path, vec!["th"]);
    }

    #[test]
    fn test_trace_dynamic_component_no_default() {
        // When the component prop has no string default, keep the original name
        let source = r#"
            const Box = ({ children, component: Component }: Props) => (
                <Component>{children}</Component>
            );
        "#;

        let path = trace_children_slot(source);
        // Component is PascalCase but has no resolvable default
        assert_eq!(path, vec!["Component"]);
    }

    #[test]
    fn test_collect_aliases_simple() {
        let allocator = Allocator::default();
        let source = r#"
            const Foo = ({ component = 'div' }: Props) => {
                return <component>{children}</component>;
            };
        "#;
        let parsed = Parser::new(&allocator, source, SourceType::tsx()).parse();
        let aliases = collect_component_aliases(&parsed.program.body);
        assert_eq!(aliases.get("component"), Some(&"div".to_string()));
    }

    #[test]
    fn test_trace_forwardref_with_internal_component() {
        // Pattern: forwardRef wrapper that delegates to an internal component
        // The tracer must find {children} inside TrBase even though Tr
        // doesn't directly use it
        let source = r#"
            const TrBase = ({
                children,
                className,
            }: TrProps) => {
                return (
                    <>
                        <tr className={className}>
                            {children}
                        </tr>
                    </>
                );
            };

            export const Tr = forwardRef((props: TrProps, ref) => (
                <TrBase {...props} innerRef={ref} />
            ));
        "#;

        let path = trace_children_slot(source);
        // Should find children inside TrBase's <tr>
        eprintln!("Tr forwardRef path: {:?}", path);
        assert_eq!(path, vec!["tr"]);
    }

    #[test]
    fn test_collect_aliases_two_hop() {
        let allocator = Allocator::default();
        let source = r#"
            const Foo = ({ component = 'td' }: Props) => {
                const { component: MergedComponent = component } = merged;
                return null;
            };
        "#;
        let parsed = Parser::new(&allocator, source, SourceType::tsx()).parse();
        let aliases = collect_component_aliases(&parsed.program.body);
        assert_eq!(aliases.get("component"), Some(&"td".to_string()));
        assert_eq!(aliases.get("MergedComponent"), Some(&"td".to_string()));
    }
}