formatjs_cli 0.1.11

Command-line interface for FormatJS - A Rust-based CLI for internationalization
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
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
use anyhow::{Context, Result};
use formatjs_icu_messageformat_parser::{
    Parser as IcuParser, ParserOptions, print_ast, try_hoist_selectors,
};
use oxc::ast_visit::{Visit, walk};
use oxc_allocator::Allocator;
use oxc_ast::ast::*;
use oxc_parser::{Parser, ParserReturn};
use oxc_span::SourceType;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;
use std::path::Path;

/// Message descriptor extracted from source code
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct MessageDescriptor {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub default_message: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub file: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub start: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub end: Option<u32>,
}

/// Convert byte offset to (line, column) - both 1-indexed
fn get_line_col(source: &str, offset: usize) -> (usize, usize) {
    let mut line = 1;
    let mut col = 1;
    for (i, ch) in source.chars().enumerate() {
        if i >= offset {
            break;
        }
        if ch == '\n' {
            line += 1;
            col = 1;
        } else {
            col += 1;
        }
    }
    (line, col)
}

/// Extract messages from a single source file
pub fn extract_messages_from_source(
    source_text: &str,
    file_path: &Path,
    source_type: SourceType,
    extract_source_location: bool,
    component_names: &[String],
    function_names: &[String],
    pragma_meta: HashMap<String, String>,
    preserve_whitespace: bool,
    flatten: bool,
    throws: bool,
) -> Result<Vec<MessageDescriptor>> {
    // Parse the file
    let allocator = Allocator::default();
    let ParserReturn {
        program, errors, ..
    } = Parser::new(&allocator, source_text, source_type).parse();

    if !errors.is_empty() {
        let error_messages: Vec<String> = errors.iter().map(|e| format!("{:?}", e)).collect();
        anyhow::bail!("Parse errors:\n{}", error_messages.join("\n"));
    }

    // Visit the AST to extract messages
    let mut visitor = MessageExtractor::new(
        file_path,
        extract_source_location,
        component_names,
        function_names,
        pragma_meta,
        preserve_whitespace,
        throws,
    );

    visitor.visit_program(&program);

    // Apply selector hoisting if flatten is enabled
    let messages = if flatten {
        visitor
            .messages
            .into_iter()
            .map(|mut msg| {
                if let Some(ref default_message) = msg.default_message {
                    // Parse the ICU message
                    let parser = IcuParser::new(
                        default_message,
                        ParserOptions {
                            ignore_tag: false,
                            ..Default::default()
                        },
                    );

                    match parser.parse() {
                        Ok(ast) => {
                            // Apply selector hoisting
                            match try_hoist_selectors(ast) {
                                Ok(hoisted_ast) => {
                                    // Print back to string
                                    msg.default_message = Some(print_ast(&hoisted_ast));
                                }
                                Err(e) => {
                                    // Get line and column from start position if available
                                    let location_str = if let Some(start) = msg.start {
                                        let line_col = get_line_col(source_text, start as usize);
                                        format!(" at line {}, column {}", line_col.0, line_col.1)
                                    } else {
                                        String::new()
                                    };
                                    let id_str = msg
                                        .id
                                        .as_ref()
                                        .map(|id| format!(" with id \"{}\"", id))
                                        .unwrap_or_default();
                                    anyhow::bail!(
                                        "[formatjs] Cannot flatten message in file \"{}\"{}{}: {}\nMessage: {}",
                                        file_path.display(),
                                        location_str,
                                        id_str,
                                        e,
                                        default_message
                                    );
                                }
                            }
                        }
                        Err(_) => {
                            // If parsing fails, keep the original message
                        }
                    }
                }
                Ok(msg)
            })
            .collect::<Result<Vec<_>>>()?
    } else {
        visitor.messages
    };

    Ok(messages)
}

/// Determine oxc SourceType from file extension
pub fn determine_source_type(path: &Path) -> Result<SourceType> {
    let ext = path
        .extension()
        .and_then(|e| e.to_str())
        .context("File has no extension")?;

    let source_type: SourceType = match ext {
        "tsx" => SourceType::default().with_jsx(true).with_typescript(true),
        "jsx" => SourceType::default().with_jsx(true),
        "ts" | "mts" | "cts" => SourceType::default().with_typescript(true),
        "js" | "mjs" | "cjs" => SourceType::default(),
        _ => anyhow::bail!("Unsupported file extension: {}", ext),
    };

    Ok(source_type)
}

/// AST visitor to extract message descriptors
struct MessageExtractor<'a> {
    file_path: &'a Path,
    extract_source_location: bool,
    component_names: &'a [String],
    function_names: &'a [String],
    _pragma_meta: HashMap<String, String>,
    preserve_whitespace: bool,
    throws: bool,
    messages: Vec<MessageDescriptor>,
}

impl<'a> MessageExtractor<'a> {
    fn new(
        file_path: &'a Path,
        extract_source_location: bool,
        component_names: &'a [String],
        function_names: &'a [String],
        pragma_meta: HashMap<String, String>,
        preserve_whitespace: bool,
        throws: bool,
    ) -> Self {
        Self {
            file_path,
            extract_source_location,
            component_names,
            function_names,
            _pragma_meta: pragma_meta,
            preserve_whitespace,
            throws,
            messages: Vec::new(),
        }
    }

    fn extract_string_literal(
        &self,
        expr: &Expression,
        preserve_whitespace: Option<bool>,
    ) -> Option<String> {
        match expr {
            Expression::StringLiteral(lit) => {
                let value = lit.value.to_string();
                if preserve_whitespace.unwrap_or(self.preserve_whitespace) {
                    Some(value)
                } else {
                    Some(value.trim().to_string())
                }
            }
            Expression::TemplateLiteral(tpl)
                if tpl.quasis.len() == 1 && tpl.expressions.is_empty() =>
            {
                let value = tpl.quasis[0].value.cooked.as_ref()?.to_string();
                if preserve_whitespace.unwrap_or(self.preserve_whitespace) {
                    Some(value)
                } else {
                    Some(value.trim().to_string())
                }
            }
            // Handle string concatenation (e.g., 'Hello' + ' ' + 'World')
            Expression::BinaryExpression(bin) if bin.operator == BinaryOperator::Addition => {
                let left = self.extract_string_literal(&bin.left, Some(true))?;
                let right = self.extract_string_literal(&bin.right, Some(true))?;
                Some(format!("{}{}", left, right))
            }
            _ => None,
        }
    }

    fn extract_description(&self, expr: &Expression) -> Option<Value> {
        if let Some(string_val) = self.extract_string_literal(expr, None) {
            return Some(Value::String(string_val));
        }

        // Handle object literal descriptions
        if let Expression::ObjectExpression(obj) = expr {
            let mut map = serde_json::Map::new();
            for prop in &obj.properties {
                if let ObjectPropertyKind::ObjectProperty(p) = prop {
                    if let PropertyKey::StaticIdentifier(key) = &p.key {
                        // Try to extract string value
                        if let Some(val) = self.extract_string_literal(&p.value, None) {
                            map.insert(key.name.to_string(), Value::String(val));
                        }
                        // Try to extract numeric value
                        else if let Expression::NumericLiteral(num) = &p.value {
                            // Convert to JSON number (from_f64 returns Option)
                            if let Some(num_val) = serde_json::Number::from_f64(num.value) {
                                map.insert(key.name.to_string(), Value::Number(num_val));
                            }
                        }
                    }
                }
            }
            if !map.is_empty() {
                return Some(Value::Object(map));
            }
        }

        None
    }

    /// Extract function name from callee expression, handling:
    /// - Simple identifiers: formatMessage
    /// - Member expressions: intl.formatMessage
    /// - Deep chains: props.intl.formatMessage, this.props.intl.formatMessage
    /// - Optional chaining: intl.formatMessage?.(), something?.intl?.formatMessage?.()
    /// - ChainExpression wrapper
    fn extract_function_name<'b>(&self, callee: &'b Expression) -> Option<&'b str> {
        match callee {
            // Direct function call: formatMessage(...)
            Expression::Identifier(id) => Some(id.name.as_str()),

            // Member expression: intl.formatMessage, props.intl.formatMessage
            Expression::StaticMemberExpression(member) => {
                self.extract_function_name_from_member(member)
            }

            // Optional chaining wrapper: formatMessage?.()
            Expression::ChainExpression(chain) => {
                self.extract_function_name_from_chain(&chain.expression)
            }

            // TypeScript generic instantiation: formatMessage<T>, intl.formatMessage<HTMLElement>
            Expression::TSInstantiationExpression(instantiation) => {
                // The actual expression is inside the instantiation
                self.extract_function_name(&instantiation.expression)
            }

            _ => None,
        }
    }

    /// Extract function name from ChainElement (used in optional chaining)
    fn extract_function_name_from_chain<'b>(
        &self,
        chain_elem: &'b ChainElement,
    ) -> Option<&'b str> {
        match chain_elem {
            ChainElement::CallExpression(_) => None,
            ChainElement::StaticMemberExpression(member) => {
                self.extract_function_name_from_member(member)
            }
            _ => None,
        }
    }

    /// Extract function name from member expression, checking if it's a valid intl call
    fn extract_function_name_from_member<'b>(
        &self,
        member: &'b StaticMemberExpression,
    ) -> Option<&'b str> {
        let property_name = member.property.name.as_str();

        // Check if the object is 'intl' or ends with '.intl'
        if self.is_intl_object(&member.object) {
            return Some(property_name);
        }

        None
    }

    /// Check if an expression is or ends with 'intl'
    /// Matches: intl, props.intl, this.props.intl, something?.intl
    fn is_intl_object(&self, expr: &Expression) -> bool {
        match expr {
            // Direct 'intl' identifier
            Expression::Identifier(id) => id.name.as_str() == "intl",

            // props.intl, this.props.intl
            Expression::StaticMemberExpression(member) => {
                if member.property.name.as_str() == "intl" {
                    return true;
                }
                // Recursively check parent (for this.props.intl)
                self.is_intl_object(&member.object)
            }

            // Optional chaining: something?.intl
            Expression::ChainExpression(chain) => self.is_intl_object_from_chain(&chain.expression),

            // this.props
            Expression::ThisExpression(_) => false, // 'this' alone is not intl, but this.props.intl will be caught above

            _ => false,
        }
    }

    /// Check if a ChainElement is or ends with 'intl'
    fn is_intl_object_from_chain(&self, chain_elem: &ChainElement) -> bool {
        match chain_elem {
            ChainElement::StaticMemberExpression(member) => {
                if member.property.name.as_str() == "intl" {
                    return true;
                }
                self.is_intl_object(&member.object)
            }
            _ => false,
        }
    }

    fn extract_jsx_message(&mut self, opening_element: &JSXOpeningElement) {
        // Check if this is a FormattedMessage or custom component
        let component_name = match &opening_element.name {
            JSXElementName::Identifier(id) => id.name.as_str(),
            JSXElementName::IdentifierReference(id) => id.name.as_str(),
            _ => return,
        };

        if !self.component_names.iter().any(|n| n == component_name) {
            return;
        }

        let mut descriptor = MessageDescriptor {
            id: None,
            default_message: None,
            description: None,
            file: None,
            start: None,
            end: None,
        };

        // Extract source location if requested
        if self.extract_source_location {
            descriptor.file = Some(self.file_path.to_string_lossy().to_string());
            descriptor.start = Some(opening_element.span.start);
            descriptor.end = Some(opening_element.span.end);
        }

        // Extract attributes
        for attr in &opening_element.attributes {
            if let JSXAttributeItem::Attribute(jsx_attr) = attr {
                if let JSXAttributeName::Identifier(name) = &jsx_attr.name {
                    let attr_name = name.name.as_str();

                    if let Some(value) = &jsx_attr.value {
                        match value {
                            JSXAttributeValue::StringLiteral(lit) => {
                                let val = lit.value.to_string();
                                // Apply whitespace trimming based on preserve_whitespace flag
                                let val = if self.preserve_whitespace {
                                    val
                                } else {
                                    val.trim().to_string()
                                };
                                match attr_name {
                                    "id" => descriptor.id = Some(val),
                                    "defaultMessage" => descriptor.default_message = Some(val),
                                    "description" => {
                                        descriptor.description = Some(Value::String(val))
                                    }
                                    _ => {}
                                }
                            }
                            JSXAttributeValue::ExpressionContainer(container) => {
                                // JSXExpression contains all Expression variants directly
                                if let Some(expr) = container.expression.as_expression() {
                                    match attr_name {
                                        "id" => {
                                            descriptor.id = self.extract_string_literal(expr, None);
                                            // Validate id is static if throws is enabled
                                            if self.throws && descriptor.id.is_none() {
                                                panic!(
                                                    "defaultMessage must be a string literal to be extracted."
                                                );
                                            }
                                        }
                                        "defaultMessage" => {
                                            descriptor.default_message =
                                                self.extract_string_literal(expr, None);
                                            // Validate defaultMessage is static if throws is enabled
                                            if self.throws && descriptor.default_message.is_none() {
                                                panic!(
                                                    "defaultMessage must be a string literal to be extracted."
                                                );
                                            }
                                        }
                                        "description" => {
                                            descriptor.description = self.extract_description(expr);
                                        }
                                        _ => {}
                                    }
                                }
                            }
                            _ => {}
                        }
                    }
                }
            }
        }

        // Only add if we have at least a defaultMessage
        if descriptor.default_message.is_some() {
            self.messages.push(descriptor);
        }
    }

    fn extract_call_expression_message(&mut self, call: &CallExpression) {
        // Check if this is defineMessages, defineMessage, or formatMessage
        let function_name = self.extract_function_name(&call.callee);

        if function_name.is_none() {
            return;
        }

        let function_name = function_name.unwrap();

        if !self.function_names.iter().any(|n| n == function_name) {
            return;
        }

        // Get first argument
        if call.arguments.is_empty() {
            return;
        }

        let arg = &call.arguments[0];
        // Argument enum contains all Expression variants directly
        let mut arg_expr = match arg.as_expression() {
            Some(expr) => expr,
            None => return,
        };

        // Unwrap TSAsExpression (e.g., `{...} as const`)
        while let Expression::TSAsExpression(ts_as) = arg_expr {
            arg_expr = &ts_as.expression;
        }

        // For defineMessages, the argument is an object with message descriptors
        if function_name == "defineMessages" {
            if let Expression::ObjectExpression(obj) = arg_expr {
                for prop in &obj.properties {
                    if let ObjectPropertyKind::ObjectProperty(p) = prop {
                        if let Expression::ObjectExpression(msg_obj) = &p.value {
                            if let Some(descriptor) =
                                self.extract_object_descriptor(&msg_obj, call.span.start)
                            {
                                self.messages.push(descriptor);
                            }
                        }
                    }
                }
            }
        } else {
            // For defineMessage and formatMessage, the argument is the descriptor
            if let Expression::ObjectExpression(obj) = arg_expr {
                if let Some(descriptor) = self.extract_object_descriptor(&obj, call.span.start) {
                    self.messages.push(descriptor);
                }
            }
        }
    }

    fn extract_object_descriptor(
        &self,
        obj: &ObjectExpression,
        span_start: u32,
    ) -> Option<MessageDescriptor> {
        let mut descriptor = MessageDescriptor {
            id: None,
            default_message: None,
            description: None,
            file: None,
            start: None,
            end: None,
        };

        if self.extract_source_location {
            descriptor.file = Some(self.file_path.to_string_lossy().to_string());
            descriptor.start = Some(span_start);
        }

        for prop in &obj.properties {
            if let ObjectPropertyKind::ObjectProperty(p) = prop {
                if let PropertyKey::StaticIdentifier(key) = &p.key {
                    match key.name.as_str() {
                        "id" => {
                            descriptor.id = self.extract_string_literal(&p.value, None);
                            // Validate id is static if throws is enabled
                            if self.throws && descriptor.id.is_none() {
                                panic!("defaultMessage must be a string literal to be extracted.");
                            }
                        }
                        "defaultMessage" => {
                            descriptor.default_message =
                                self.extract_string_literal(&p.value, None);
                            // Validate defaultMessage is static if throws is enabled
                            if self.throws && descriptor.default_message.is_none() {
                                panic!("defaultMessage must be a string literal to be extracted.");
                            }
                        }
                        "description" => {
                            descriptor.description = self.extract_description(&p.value);
                        }
                        _ => {}
                    }
                }
            }
        }

        // Only return if we have at least defaultMessage
        if descriptor.default_message.is_some() {
            Some(descriptor)
        } else {
            None
        }
    }
}

impl<'a> Visit<'a> for MessageExtractor<'a> {
    fn visit_jsx_opening_element(&mut self, it: &JSXOpeningElement<'a>) {
        self.extract_jsx_message(it);
        // Continue walking to visit nested elements
        walk::walk_jsx_opening_element(self, it);
    }

    fn visit_call_expression(&mut self, it: &CallExpression<'a>) {
        self.extract_call_expression_message(it);
        // Continue walking to visit nested expressions
        walk::walk_call_expression(self, it);
    }

    fn visit_chain_expression(&mut self, it: &oxc_ast::ast::ChainExpression<'a>) {
        // Handle optional chaining like: intl.formatMessage?.()
        // The ChainExpression wraps a ChainElement which can be a CallExpression
        match &it.expression {
            oxc_ast::ast::ChainElement::CallExpression(call) => {
                // Extract the message from this call expression
                self.extract_call_expression_message(call);
                // Don't walk - this prevents double extraction since walk would
                // visit the arguments which may contain nested chains
                // Instead, manually walk just the arguments to find nested messages
                for arg in &call.arguments {
                    if let Some(expr) = arg.as_expression() {
                        walk::walk_expression(self, expr);
                    }
                }
            }
            oxc_ast::ast::ChainElement::StaticMemberExpression(_) => {
                // For member expressions in chains, walk normally to find nested patterns
                walk::walk_chain_expression(self, it);
            }
            _ => {
                // For other chain elements, walk normally
                walk::walk_chain_expression(self, it);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use std::path::PathBuf;

    // Helper function to get the fixtures directory
    fn fixtures_dir() -> PathBuf {
        // In Bazel, test data is available in the runfiles
        // The fixtures are from //packages/ts-transformer:test_fixtures
        if let Ok(runfiles) = std::env::var("RUNFILES_DIR") {
            // Running under Bazel
            PathBuf::from(runfiles)
                .join("_main")
                .join("packages")
                .join("ts-transformer")
                .join("tests")
                .join("fixtures")
        } else {
            // Fallback for cargo test
            let manifest_dir = env!("CARGO_MANIFEST_DIR");
            PathBuf::from(manifest_dir)
                .parent()
                .unwrap()
                .parent()
                .unwrap()
                .join("packages")
                .join("ts-transformer")
                .join("tests")
                .join("fixtures")
        }
    }

    // Helper function to read and extract from a fixture file
    fn extract_from_fixture(
        fixture_name: &str,
        component_names: &[String],
        function_names: &[String],
        pragma: Option<&str>,
    ) -> Result<Vec<MessageDescriptor>> {
        let fixture_path = fixtures_dir().join(fixture_name);
        let source_text = fs::read_to_string(&fixture_path)
            .with_context(|| format!("Failed to read fixture {}", fixture_name))?;

        let source_type = determine_source_type(&fixture_path)?;
        let pragma_meta = if let Some(p) = pragma {
            extract_pragma(&source_text, p)
        } else {
            HashMap::new()
        };

        extract_messages_from_source(
            &source_text,
            &fixture_path,
            source_type,
            false,
            component_names,
            function_names,
            pragma_meta,
            false,
            false,
            false,
        )
    }

    // Helper for pragma extraction (imported from extract module)
    fn extract_pragma(source: &str, pragma: &str) -> HashMap<String, String> {
        let mut meta = HashMap::new();
        let pragma_pattern = format!("// {}", pragma);

        for line in source.lines() {
            let trimmed = line.trim();
            if let Some(rest) = trimmed.strip_prefix(&pragma_pattern) {
                for pair in rest.split_whitespace() {
                    if let Some((key, value)) = pair.split_once(':') {
                        meta.insert(key.to_string(), value.to_string());
                    }
                }
            }
        }
        meta
    }

    #[test]
    fn test_extract_formatted_message_jsx() {
        let source = r#"
            import { FormattedMessage } from 'react-intl';
            <FormattedMessage id="greeting" defaultMessage="Hello {name}!" description="Greeting message" />
        "#;

        let file_path = PathBuf::from("test.tsx");
        let source_type = SourceType::default().with_typescript(true).with_jsx(true);
        let component_names = vec!["FormattedMessage".to_string()];
        let function_names = vec!["formatMessage".to_string()];

        let messages = extract_messages_from_source(
            source,
            &file_path,
            source_type,
            false,
            &component_names,
            &function_names,
            HashMap::new(),
            false,
            false,
            false,
        )
        .unwrap();

        assert_eq!(messages.len(), 1);
        assert_eq!(messages[0].id, Some("greeting".to_string()));
        assert_eq!(
            messages[0].default_message,
            Some("Hello {name}!".to_string())
        );
        assert_eq!(
            messages[0].description,
            Some(Value::String("Greeting message".to_string()))
        );
    }

    #[test]
    fn test_extract_define_messages() {
        let source = r#"
            import { defineMessages } from 'react-intl';
            const messages = defineMessages({
                greeting: {
                    id: 'greeting',
                    defaultMessage: 'Hello!',
                    description: 'Simple greeting'
                },
                farewell: {
                    id: 'farewell',
                    defaultMessage: 'Goodbye!',
                    description: 'Simple farewell'
                }
            });
        "#;

        let file_path = PathBuf::from("test.ts");
        let source_type = SourceType::default().with_typescript(true);
        let component_names = vec!["FormattedMessage".to_string()];
        let function_names = vec!["defineMessages".to_string()];

        let messages = extract_messages_from_source(
            source,
            &file_path,
            source_type,
            false,
            &component_names,
            &function_names,
            HashMap::new(),
            false,
            false,
            false,
        )
        .unwrap();

        assert_eq!(messages.len(), 2);
        assert_eq!(messages[0].id, Some("greeting".to_string()));
        assert_eq!(messages[0].default_message, Some("Hello!".to_string()));
        assert_eq!(messages[1].id, Some("farewell".to_string()));
        assert_eq!(messages[1].default_message, Some("Goodbye!".to_string()));
    }

    #[test]
    fn test_extract_format_message_call() {
        let source = r#"
            intl.formatMessage({
                id: 'welcome',
                defaultMessage: 'Welcome to our app!',
                description: 'Welcome message'
            });
        "#;

        let file_path = PathBuf::from("test.js");
        let source_type = SourceType::default();
        let component_names = vec!["FormattedMessage".to_string()];
        let function_names = vec!["formatMessage".to_string()];

        let messages = extract_messages_from_source(
            source,
            &file_path,
            source_type,
            false,
            &component_names,
            &function_names,
            HashMap::new(),
            false,
            false,
            false,
        )
        .unwrap();

        assert_eq!(messages.len(), 1);
        assert_eq!(messages[0].id, Some("welcome".to_string()));
        assert_eq!(
            messages[0].default_message,
            Some("Welcome to our app!".to_string())
        );
    }

    #[test]
    fn test_extract_with_source_location() {
        let source = r#"
            <FormattedMessage defaultMessage="Test message" />
        "#;

        let file_path = PathBuf::from("/path/to/test.tsx");
        let source_type = SourceType::default().with_typescript(true).with_jsx(true);
        let component_names = vec!["FormattedMessage".to_string()];
        let function_names = vec![];

        let messages = extract_messages_from_source(
            source,
            &file_path,
            source_type,
            true, // extract_source_location
            &component_names,
            &function_names,
            HashMap::new(),
            false,
            false,
            false,
        )
        .unwrap();

        assert_eq!(messages.len(), 1);
        assert_eq!(messages[0].file, Some("/path/to/test.tsx".to_string()));
        assert!(messages[0].start.is_some());
        assert!(messages[0].end.is_some());
    }

    #[test]
    fn test_extract_object_description() {
        let source = r#"
            <FormattedMessage
                defaultMessage="Test"
                description={{ context: "button", importance: "high" }}
            />
        "#;

        let file_path = PathBuf::from("test.tsx");
        let source_type = SourceType::default().with_typescript(true).with_jsx(true);
        let component_names = vec!["FormattedMessage".to_string()];
        let function_names = vec![];

        let messages = extract_messages_from_source(
            source,
            &file_path,
            source_type,
            false,
            &component_names,
            &function_names,
            HashMap::new(),
            false,
            false,
            false,
        )
        .unwrap();

        assert_eq!(messages.len(), 1);
        match &messages[0].description {
            Some(Value::Object(map)) => {
                assert_eq!(
                    map.get("context"),
                    Some(&Value::String("button".to_string()))
                );
                assert_eq!(
                    map.get("importance"),
                    Some(&Value::String("high".to_string()))
                );
            }
            _ => panic!("Expected object description"),
        }
    }

    #[test]
    fn test_whitespace_preservation() {
        let source = r#"
            <FormattedMessage defaultMessage="  Hello World  " />
        "#;

        let file_path = PathBuf::from("test.tsx");
        let source_type = SourceType::default().with_typescript(true).with_jsx(true);
        let component_names = vec!["FormattedMessage".to_string()];
        let function_names = vec![];

        // Without whitespace preservation
        let messages = extract_messages_from_source(
            source,
            &file_path,
            source_type,
            false,
            &component_names,
            &function_names,
            HashMap::new(),
            false, // preserve_whitespace = false
            false,
            false,
        )
        .unwrap();

        assert_eq!(messages[0].default_message, Some("Hello World".to_string()));

        // With whitespace preservation
        let messages_preserved = extract_messages_from_source(
            source,
            &file_path,
            source_type,
            false,
            &component_names,
            &function_names,
            HashMap::new(),
            true, // preserve_whitespace = true
            false,
            false,
        )
        .unwrap();

        assert_eq!(
            messages_preserved[0].default_message,
            Some("  Hello World  ".to_string())
        );
    }

    #[test]
    fn test_custom_component_names() {
        let source = r#"
            <CustomMessage id="custom" defaultMessage="Custom!" />
        "#;

        let file_path = PathBuf::from("test.tsx");
        let source_type = SourceType::default().with_typescript(true).with_jsx(true);
        let component_names = vec!["CustomMessage".to_string()];
        let function_names = vec![];

        let messages = extract_messages_from_source(
            source,
            &file_path,
            source_type,
            false,
            &component_names,
            &function_names,
            HashMap::new(),
            false,
            false,
            false,
        )
        .unwrap();

        assert_eq!(messages.len(), 1);
        assert_eq!(messages[0].id, Some("custom".to_string()));
        assert_eq!(messages[0].default_message, Some("Custom!".to_string()));
    }

    #[test]
    fn test_custom_function_names() {
        let source = r#"
            $t({
                id: 'translated',
                defaultMessage: 'Translated text'
            });
        "#;

        let file_path = PathBuf::from("test.js");
        let source_type = SourceType::default();
        let component_names = vec![];
        let function_names = vec!["$t".to_string()];

        let messages = extract_messages_from_source(
            source,
            &file_path,
            source_type,
            false,
            &component_names,
            &function_names,
            HashMap::new(),
            false,
            false,
            false,
        )
        .unwrap();

        assert_eq!(messages.len(), 1);
        assert_eq!(messages[0].id, Some("translated".to_string()));
        assert_eq!(
            messages[0].default_message,
            Some("Translated text".to_string())
        );
    }

    #[test]
    fn test_no_defaultmessage_skips() {
        let source = r#"
            <FormattedMessage id="no-default" description="Has no default message" />
        "#;

        let file_path = PathBuf::from("test.tsx");
        let source_type = SourceType::default().with_typescript(true).with_jsx(true);
        let component_names = vec!["FormattedMessage".to_string()];
        let function_names = vec![];

        let messages = extract_messages_from_source(
            source,
            &file_path,
            source_type,
            false,
            &component_names,
            &function_names,
            HashMap::new(),
            false,
            false,
            false,
        )
        .unwrap();

        // Should not extract messages without defaultMessage
        assert_eq!(messages.len(), 0);
    }

    // Fixture-based tests (matching ts-transformer test suite)

    #[test]
    fn test_fixture_formatted_message() {
        let component_names = vec!["FormattedMessage".to_string()];
        let function_names = vec!["formatMessage".to_string()];

        let messages = extract_from_fixture(
            "FormattedMessage.tsx",
            &component_names,
            &function_names,
            None,
        )
        .expect("Failed to extract from FormattedMessage.tsx");

        // Should extract 3 identical messages (string, template literal, and expression)
        assert_eq!(messages.len(), 3);
        for msg in &messages {
            assert_eq!(msg.id, Some("foo.bar.baz".to_string()));
            assert_eq!(
                msg.default_message,
                Some("Hello World! {foo, number}".to_string())
            );
            assert_eq!(
                msg.description,
                Some(Value::String("The default message.".to_string()))
            );
        }
    }

    #[test]
    fn test_fixture_define_messages() {
        let component_names = vec!["FormattedMessage".to_string()];
        let function_names = vec!["defineMessages".to_string()];

        let messages = extract_from_fixture(
            "defineMessages.tsx",
            &component_names,
            &function_names,
            Some("@react-intl"),
        )
        .expect("Failed to extract from defineMessages.tsx");

        // Should extract 7 messages from defineMessages + 1 inline FormattedMessage
        assert!(messages.len() >= 7);

        // Check first message
        let header = messages
            .iter()
            .find(|m| m.id == Some("foo.bar.baz".to_string()));
        assert!(header.is_some());
        let header = header.unwrap();
        assert_eq!(header.default_message, Some("Hello World!".to_string()));
        assert_eq!(
            header.description,
            Some(Value::String("The default message".to_string()))
        );

        // Check kittens message with ICU plural
        let kittens = messages
            .iter()
            .find(|m| m.id == Some("app.home.kittens".to_string()));
        assert!(kittens.is_some());
        let kittens = kittens.unwrap();
        assert_eq!(
            kittens.default_message,
            Some("{count, plural, =0 {😭} one {# kitten} other {# kittens}}".to_string())
        );
    }

    #[test]
    fn test_fixture_additional_component_names() {
        let component_names = vec!["CustomMessage".to_string()];
        let function_names = vec![];

        let messages = extract_from_fixture(
            "additionalComponentNames.tsx",
            &component_names,
            &function_names,
            Some("@react-intl"),
        )
        .expect("Failed to extract from additionalComponentNames.tsx");

        assert_eq!(messages.len(), 1);
        assert_eq!(messages[0].id, Some("greeting-world".to_string()));
        assert_eq!(
            messages[0].default_message,
            Some("Hello World!".to_string())
        );
        assert_eq!(
            messages[0].description,
            Some(Value::String("Greeting to the world".to_string()))
        );
    }

    #[test]
    fn test_fixture_additional_function_names() {
        let component_names = vec![];
        let function_names = vec!["formatMessage".to_string(), "$formatMessage".to_string()];

        let messages = extract_from_fixture(
            "additionalFunctionNames.tsx",
            &component_names,
            &function_names,
            Some("@react-intl"),
        )
        .expect("Failed to extract from additionalFunctionNames.tsx");

        // Should extract 2 messages (1 formatMessage + 1 $formatMessage)
        assert_eq!(messages.len(), 2);
        for msg in &messages {
            assert_eq!(msg.default_message, Some("foo".to_string()));
        }
    }

    #[test]
    fn test_fixture_descriptions_as_objects() {
        let component_names = vec!["FormattedMessage".to_string()];
        let function_names = vec![];

        let messages = extract_from_fixture(
            "descriptionsAsObjects.tsx",
            &component_names,
            &function_names,
            None,
        )
        .expect("Failed to extract from descriptionsAsObjects.tsx");

        assert!(messages.len() >= 1);

        // Find message with object description
        let msg_with_obj = messages.iter().find(|m| m.description.is_some());
        assert!(msg_with_obj.is_some());

        if let Some(Value::Object(desc)) = &msg_with_obj.unwrap().description {
            assert!(desc.contains_key("text") || desc.contains_key("metadata"));
        }
    }

    #[test]
    fn test_fixture_extract_from_format_message() {
        let component_names = vec![];
        let function_names = vec!["formatMessage".to_string()];

        let messages = extract_from_fixture(
            "extractFromFormatMessage.tsx",
            &component_names,
            &function_names,
            None,
        )
        .expect("Failed to extract from extractFromFormatMessage.tsx");

        // Should extract messages from formatMessage calls
        assert!(messages.len() >= 1);
        assert!(messages.iter().any(|m| m.default_message.is_some()));
    }

    #[test]
    fn test_fixture_format_message_call() {
        let component_names = vec![];
        let function_names = vec!["formatMessage".to_string()];

        let messages = extract_from_fixture(
            "formatMessageCall.tsx",
            &component_names,
            &function_names,
            None,
        )
        .expect("Failed to extract from formatMessageCall.tsx");

        // Should extract messages from intl.formatMessage calls
        assert!(messages.len() >= 1);
    }

    #[test]
    fn test_fixture_nested() {
        let component_names = vec![];
        let function_names = vec!["formatMessage".to_string()];

        let messages = extract_from_fixture("nested.tsx", &component_names, &function_names, None)
            .expect("Failed to extract from nested.tsx");

        // Should extract nested formatMessage calls (layer1 and layer2)
        assert!(messages.len() >= 2);
    }

    #[test]
    fn test_fixture_string_concat() {
        let component_names = vec!["FormattedMessage".to_string()];
        let function_names = vec![];

        let messages =
            extract_from_fixture("stringConcat.tsx", &component_names, &function_names, None)
                .expect("Failed to extract from stringConcat.tsx");

        // Should extract messages with string concatenation
        assert!(messages.len() >= 1);
    }

    #[test]
    fn test_fixture_template_literal() {
        let component_names = vec!["FormattedMessage".to_string()];
        let function_names = vec![];

        let messages = extract_from_fixture(
            "templateLiteral.tsx",
            &component_names,
            &function_names,
            None,
        )
        .expect("Failed to extract from templateLiteral.tsx");

        // Should extract messages from template literals
        assert!(messages.len() >= 1);
    }

    #[test]
    fn test_fixture_inline() {
        let component_names = vec!["FormattedMessage".to_string()];
        let function_names = vec!["defineMessage".to_string()];

        let messages = extract_from_fixture("inline.tsx", &component_names, &function_names, None)
            .expect("Failed to extract from inline.tsx");

        // Should extract 1 FormattedMessage + 2 defineMessage calls
        assert_eq!(messages.len(), 3);

        // Check the FormattedMessage
        let fm = messages
            .iter()
            .find(|m| m.id == Some("foo.bar.baz".to_string()));
        assert!(fm.is_some());

        // Check the defineMessage calls
        let dm1 = messages.iter().find(|m| m.id == Some("header".to_string()));
        assert!(dm1.is_some());
        let dm2 = messages
            .iter()
            .find(|m| m.id == Some("header2".to_string()));
        assert!(dm2.is_some());
    }

    #[test]
    fn test_fixture_define_messages_preserve_whitespace() {
        let fixture_path = fixtures_dir().join("defineMessagesPreserveWhitespace.tsx");
        let source_text = fs::read_to_string(&fixture_path)
            .expect("Failed to read defineMessagesPreserveWhitespace.tsx");

        let source_type = determine_source_type(&fixture_path).unwrap();
        let component_names = vec!["FormattedMessage".to_string()];
        let function_names = vec!["defineMessages".to_string()];
        let pragma_meta = extract_pragma(&source_text, "@react-intl");

        // With whitespace preservation
        let messages = extract_messages_from_source(
            &source_text,
            &fixture_path,
            source_type,
            false,
            &component_names,
            &function_names,
            pragma_meta,
            true, // preserve_whitespace = true
            false,
            false,
        )
        .unwrap();

        // Should extract multiple messages including one with trailing whitespace
        assert!(messages.len() >= 7);

        // Find the message with trailing whitespace
        let ws_msg = messages
            .iter()
            .find(|m| m.id == Some("trailing.ws".to_string()));
        assert!(ws_msg.is_some());
        let ws_msg = ws_msg.unwrap();

        // Should preserve whitespace
        assert_eq!(
            ws_msg.default_message,
            Some("   Some whitespace   ".to_string())
        );
    }

    #[test]
    fn test_fixture_optional_chaining() {
        let component_names = vec![];
        let function_names = vec!["formatMessage".to_string()];

        let messages = extract_from_fixture(
            "optionalChaining.tsx",
            &component_names,
            &function_names,
            None,
        )
        .expect("Failed to extract from optionalChaining.tsx");

        // Expected messages match the TypeScript transformer test expectations
        let expected = vec![
            MessageDescriptor {
                id: None,
                default_message: Some("Normal call".to_string()),
                description: Some(Value::String("Test normal formatMessage call".to_string())),
                file: None,
                start: None,
                end: None,
            },
            MessageDescriptor {
                id: None,
                default_message: Some("With generics".to_string()),
                description: Some(Value::String(
                    "Test formatMessage with generic type".to_string(),
                )),
                file: None,
                start: None,
                end: None,
            },
            MessageDescriptor {
                id: None,
                default_message: Some("With optional chaining".to_string()),
                description: Some(Value::String(
                    "Test formatMessage with optional chaining".to_string(),
                )),
                file: None,
                start: None,
                end: None,
            },
            MessageDescriptor {
                id: None,
                default_message: Some("With both generics and optional chaining".to_string()),
                description: Some(Value::String(
                    "Test formatMessage with both generic type and optional chaining".to_string(),
                )),
                file: None,
                start: None,
                end: None,
            },
            MessageDescriptor {
                id: None,
                default_message: Some("Nested optional chaining".to_string()),
                description: Some(Value::String("Test nested optional chaining".to_string())),
                file: None,
                start: None,
                end: None,
            },
        ];

        assert_eq!(messages, expected);
    }

    #[test]
    fn test_fixture_no_import() {
        let component_names = vec![];
        let function_names = vec!["formatMessage".to_string()];

        let messages =
            extract_from_fixture("noImport.tsx", &component_names, &function_names, None)
                .expect("Failed to extract from noImport.tsx");

        // Expected messages match the TypeScript transformer test expectations
        // These include props.intl.formatMessage, this.props.intl.formatMessage patterns
        let mut obj_desc_1 = serde_json::Map::new();
        obj_desc_1.insert(
            "obj1".to_string(),
            Value::Number(serde_json::Number::from_f64(1.0).unwrap()),
        );
        obj_desc_1.insert("obj2".to_string(), Value::String("123".to_string()));

        let mut obj_desc_2 = serde_json::Map::new();
        obj_desc_2.insert("obj2".to_string(), Value::String("123".to_string()));

        let expected = vec![
            MessageDescriptor {
                id: None,
                default_message: Some("props {intl}".to_string()),
                description: Some(Value::String("bar".to_string())),
                file: None,
                start: None,
                end: None,
            },
            MessageDescriptor {
                id: None,
                default_message: Some("this props {intl}".to_string()),
                description: Some(Value::String("bar".to_string())),
                file: None,
                start: None,
                end: None,
            },
            MessageDescriptor {
                id: None,
                default_message: Some("this props {intl}".to_string()),
                description: Some(Value::Object(obj_desc_1.clone())),
                file: None,
                start: None,
                end: None,
            },
            MessageDescriptor {
                id: None,
                default_message: Some("this props {intl}".to_string()),
                description: Some(Value::Object(obj_desc_1.clone())),
                file: None,
                start: None,
                end: None,
            },
            MessageDescriptor {
                id: None,
                default_message: Some("this props {intl}".to_string()),
                description: Some(Value::Object(obj_desc_2)),
                file: None,
                start: None,
                end: None,
            },
            MessageDescriptor {
                id: None,
                default_message: Some("foo {bar}".to_string()),
                description: Some(Value::String("bar".to_string())),
                file: None,
                start: None,
                end: None,
            },
        ];

        assert_eq!(messages, expected);
    }

    #[test]
    fn test_fixture_extract_source_location() {
        let fixture_path = fixtures_dir().join("extractSourceLocation.tsx");
        let source_text =
            fs::read_to_string(&fixture_path).expect("Failed to read extractSourceLocation.tsx");

        let source_type = determine_source_type(&fixture_path).unwrap();
        let component_names = vec!["FormattedMessage".to_string()];
        let function_names = vec![];

        // With extractSourceLocation enabled
        let messages = extract_messages_from_source(
            &source_text,
            &fixture_path,
            source_type,
            true, // extract_source_location = true
            &component_names,
            &function_names,
            HashMap::new(),
            false,
            false,
            false,
        )
        .unwrap();

        assert!(messages.len() >= 1);
        // Should have file, start, and end fields
        assert!(messages[0].file.is_some());
        assert!(messages[0].start.is_some());
        assert!(messages[0].end.is_some());
    }

    #[test]
    fn test_string_concatenation() {
        let source = r#"
            import { defineMessages } from 'react-intl';
            defineMessages({
                greeting: {
                    id: 'greeting',
                    defaultMessage: 'foo ' + 'bar',
                    description: 'Test string concatenation'
                }
            });
        "#;

        let file_path = PathBuf::from("test.js");
        let source_type = SourceType::default();
        let component_names = vec!["FormattedMessage".to_string()];
        let function_names = vec!["defineMessages".to_string()];

        let messages = extract_messages_from_source(
            source,
            &file_path,
            source_type,
            false,
            &component_names,
            &function_names,
            HashMap::new(),
            false,
            false,
            false,
        )
        .unwrap();

        assert_eq!(messages.len(), 1);
        assert_eq!(messages[0].id, Some("greeting".to_string()));
        assert_eq!(messages[0].default_message, Some("foo bar".to_string()));
    }

    #[test]
    fn test_non_breaking_space_in_message() {
        let source = r#"
            import { defineMessages } from 'react-intl';
            defineMessages({
                spacing: {
                    id: 'spacing',
                    defaultMessage: 'foo\xa0bar baz',
                    description: 'Test non-breaking space'
                }
            });
        "#;

        let file_path = PathBuf::from("test.js");
        let source_type = SourceType::default();
        let component_names = vec!["FormattedMessage".to_string()];
        let function_names = vec!["defineMessages".to_string()];

        let messages = extract_messages_from_source(
            source,
            &file_path,
            source_type,
            false,
            &component_names,
            &function_names,
            HashMap::new(),
            false,
            false,
            false,
        )
        .unwrap();

        assert_eq!(messages.len(), 1);
        assert_eq!(messages[0].id, Some("spacing".to_string()));
        // \xa0 is a non-breaking space (U+00A0)
        assert_eq!(
            messages[0].default_message,
            Some("foo\u{00a0}bar baz".to_string())
        );
    }

    #[test]
    fn test_typescript_type_guard_no_crash() {
        // Test that TypeScript type guards don't crash the parser
        let source = r#"
            import { defineMessages } from 'react-intl';

            const nonEmpty = <T>(a: T | void | undefined): a is T => !!a;

            defineMessages({
                test: {
                    id: 'test',
                    defaultMessage: 'Hello world',
                    description: 'Test message'
                }
            });
        "#;

        let file_path = PathBuf::from("test.ts");
        let source_type = SourceType::default().with_typescript(true);
        let component_names = vec!["FormattedMessage".to_string()];
        let function_names = vec!["defineMessages".to_string()];

        // Should not crash and should extract the message
        let result = extract_messages_from_source(
            source,
            &file_path,
            source_type,
            false,
            &component_names,
            &function_names,
            HashMap::new(),
            false,
            false,
            false,
        );

        assert!(result.is_ok(), "Should not crash on TypeScript type guard");
        let messages = result.unwrap();
        assert_eq!(messages.len(), 1);
        assert_eq!(messages[0].id, Some("test".to_string()));
        assert_eq!(messages[0].default_message, Some("Hello world".to_string()));
    }

    #[test]
    fn test_flatten_error_includes_location_info() {
        // GH #4161 - Test that flatten errors include file path, line, and column
        let source = r#"
import { FormattedMessage } from 'react-intl';
export default function Test() {
  return (
    <FormattedMessage
      id="test.message"
      defaultMessage="Hello <b>{count, plural, one {# item} other {# items}}</b>"
    />
  );
}
"#;

        let file_path = PathBuf::from("test.tsx");
        let source_type = SourceType::default().with_typescript(true).with_jsx(true);
        let component_names = vec!["FormattedMessage".to_string()];
        let function_names = vec!["formatMessage".to_string()];

        // Should fail with detailed error message including file, line, column, and id
        let result = extract_messages_from_source(
            source,
            &file_path,
            source_type,
            true, // extract_source_location = true
            &component_names,
            &function_names,
            HashMap::new(),
            false,
            true, // flatten = true
            false,
        );

        assert!(result.is_err(), "Should fail when trying to flatten plural within tag");
        let error = result.unwrap_err().to_string();

        // Verify error message contains all expected information
        assert!(error.contains("[formatjs]"), "Error should include [formatjs] prefix");
        assert!(error.contains("test.tsx"), "Error should include file name");
        assert!(error.contains("line"), "Error should include line number");
        assert!(error.contains("column"), "Error should include column number");
        assert!(error.contains("test.message"), "Error should include message ID");
        assert!(error.contains("Cannot hoist plural/select within a tag element"), "Error should include original error message");
        assert!(error.contains("<b>{count"), "Error should include problematic message");
    }
}