code-search-cli 0.3.3

Intelligent code search tool for tracing text (UI text, function names, variables) to implementation code
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
use crate::error::{Result, SearchError};
use crate::parse::translation::TranslationEntry;
use std::collections::HashMap;
use std::fs;
use std::path::Path;

/// Parser for JavaScript translation files
///
/// Supports both ES6 exports and CommonJS formats:
/// - `export default { ... }`
/// - `module.exports = { ... }`
pub struct JsParser;

impl JsParser {
    /// Parse a JavaScript file and extract translation entries
    pub fn parse_file(file_path: &Path) -> Result<Vec<TranslationEntry>> {
        let content = fs::read_to_string(file_path).map_err(SearchError::Io)?;

        Self::parse_content(&content, file_path)
    }

    /// Parse JavaScript content and extract translation entries
    pub fn parse_content(content: &str, file_path: &Path) -> Result<Vec<TranslationEntry>> {
        // Extract the object literal from the JavaScript file
        let object_content = Self::extract_object_literal(content)?;

        // Parse the object literal as JSON-like structure
        let parsed_object = Self::parse_object_literal(&object_content)?;

        // Convert to translation entries
        let mut entries = Vec::new();
        Self::flatten_object(&parsed_object, String::new(), file_path, &mut entries);

        Ok(entries)
    }

    /// Extract the main object literal from JavaScript export
    fn extract_object_literal(content: &str) -> Result<String> {
        let content = content.trim();

        // Look for export default { ... } or module.exports = { ... }
        let start_patterns = ["export default", "module.exports =", "exports ="];

        let mut object_start = None;
        for pattern in &start_patterns {
            if let Some(pos) = content.find(pattern) {
                // Find the opening brace after the pattern
                let after_pattern = &content[pos + pattern.len()..];
                if let Some(brace_pos) = after_pattern.find('{') {
                    object_start = Some(pos + pattern.len() + brace_pos);
                    break;
                }
            }
        }

        let start = object_start
            .ok_or_else(|| SearchError::Generic("No JavaScript object export found".to_string()))?;

        // Find the matching closing brace
        let mut brace_count = 0;
        let mut end = start;
        let chars: Vec<char> = content.chars().collect();

        for (i, &ch) in chars.iter().enumerate().skip(start) {
            match ch {
                '{' => brace_count += 1,
                '}' => {
                    brace_count -= 1;
                    if brace_count == 0 {
                        end = i + 1;
                        break;
                    }
                }
                _ => {}
            }
        }

        if brace_count != 0 {
            return Err(SearchError::Generic(
                "Unmatched braces in JavaScript object".to_string(),
            ));
        }

        Ok(content[start..end].to_string())
    }

    /// Parse a JavaScript object literal into a nested HashMap
    fn parse_object_literal(content: &str) -> Result<HashMap<String, serde_json::Value>> {
        // Convert JavaScript object syntax to JSON
        let json_content = Self::js_to_json(content)?;

        // Parse as JSON
        serde_json::from_str(&json_content)
            .map_err(|e| SearchError::Generic(format!("Failed to parse JavaScript object: {}", e)))
    }

    /// Convert JavaScript object syntax to valid JSON
    fn js_to_json(js_content: &str) -> Result<String> {
        let mut result = String::new();
        let chars: Vec<char> = js_content.chars().collect();
        let mut i = 0;
        let mut in_string = false;
        let mut string_char = '"';

        while i < chars.len() {
            let ch = chars[i];

            match ch {
                '"' | '\'' => {
                    if !in_string {
                        in_string = true;
                        string_char = ch;
                        result.push('"'); // Always use double quotes in JSON
                    } else if ch == string_char {
                        in_string = false;
                        result.push('"');
                    } else {
                        result.push(ch);
                    }
                }
                _ if in_string => {
                    // Inside string, copy as-is (except quote handling above)
                    result.push(ch);
                }
                _ if (ch.is_alphabetic() || ch == '_') && !in_string => {
                    // Check if this looks like a property name (followed by colon)
                    let mut j = i;
                    let mut prop_name = String::new();

                    // Collect the identifier
                    while j < chars.len() && (chars[j].is_alphanumeric() || chars[j] == '_') {
                        prop_name.push(chars[j]);
                        j += 1;
                    }

                    // Skip whitespace after identifier
                    while j < chars.len() && chars[j].is_whitespace() {
                        j += 1;
                    }

                    // Check if followed by colon (property name)
                    if j < chars.len() && chars[j] == ':' {
                        // This is a property name, quote it
                        result.push('"');
                        result.push_str(&prop_name);
                        result.push('"');
                        i = j - 1; // Position before the colon
                    } else {
                        // Not a property name, copy as-is
                        result.push(ch);
                    }
                }
                _ => {
                    result.push(ch);
                }
            }

            i += 1;
        }

        Ok(result)
    }

    /// Flatten nested object into dot-notation translation entries
    fn flatten_object(
        obj: &HashMap<String, serde_json::Value>,
        prefix: String,
        file_path: &Path,
        entries: &mut Vec<TranslationEntry>,
    ) {
        for (key, value) in obj {
            let full_key = if prefix.is_empty() {
                key.clone()
            } else {
                format!("{}.{}", prefix, key)
            };

            match value {
                serde_json::Value::String(s) => {
                    entries.push(TranslationEntry {
                        key: full_key,
                        value: s.clone(),
                        file: file_path.to_path_buf(),
                        line: 1, // JavaScript files don't have reliable line numbers for nested objects
                    });
                }
                serde_json::Value::Object(nested_obj) => {
                    let nested_map: HashMap<String, serde_json::Value> = nested_obj
                        .iter()
                        .map(|(k, v)| (k.clone(), v.clone()))
                        .collect();
                    Self::flatten_object(&nested_map, full_key, file_path, entries);
                }
                serde_json::Value::Array(arr) => {
                    for (i, v) in arr.iter().enumerate() {
                        let item_key = format!("{}.{}", full_key, i);

                        if let serde_json::Value::String(s) = v {
                            entries.push(TranslationEntry {
                                key: item_key,
                                value: s.clone(),
                                file: file_path.to_path_buf(),
                                line: 1,
                            });
                        } else if let serde_json::Value::Object(nested_obj) = v {
                            let nested_map: HashMap<String, serde_json::Value> = nested_obj
                                .iter()
                                .map(|(k, v)| (k.clone(), v.clone()))
                                .collect();
                            Self::flatten_object(&nested_map, item_key, file_path, entries);
                        }
                    }
                }
                _ => {
                    // Skip other types
                }
            }
        }
    }

    /// Check if a file contains the query and if it's in a translation structure
    pub fn contains_query(file_path: &Path, query: &str) -> Result<bool> {
        use grep_matcher::Matcher;
        use grep_regex::RegexMatcherBuilder;
        use grep_searcher::{sinks::UTF8, SearcherBuilder};

        // Build the regex matcher with fixed string (literal) matching
        // We use the grep crates directly to avoid spawning external processes
        let matcher = RegexMatcherBuilder::new()
            .case_insensitive(true)
            .fixed_strings(true)
            .build(query)
            .map_err(|e| SearchError::Generic(format!("Failed to build matcher: {}", e)))?;

        let mut searcher = SearcherBuilder::new().line_number(true).build();

        let mut found = false;

        // Search the file
        let _ = searcher.search_path(
            &matcher,
            file_path,
            UTF8(|line_num, line| {
                let mut stop = false;
                // Iterate over all matches in the line to find the column number
                // We use the same matcher to find the position within the line
                let _ = matcher.find_iter(line.as_bytes(), |m| {
                    // m.start() is 0-based byte offset, but we need 1-based column for is_translation_value
                    let col_num = m.start() + 1;

                    // Check if this match is a translation value
                    // We catch potential errors and treat them as false (not found in this context)
                    if let Ok(true) =
                        Self::is_translation_value(file_path, line_num as usize, col_num, query)
                    {
                        found = true;
                        stop = true;
                        return false; // Stop match iteration
                    }
                    true // Continue match iteration
                });

                if stop {
                    Ok(false) // Stop file search
                } else {
                    Ok(true) // Continue file search
                }
            }),
        );

        Ok(found)
    }

    /// Check if a match at a specific position is a translation value
    fn is_translation_value(
        file_path: &Path,
        line_num: usize,
        col_num: usize,
        _query: &str,
    ) -> Result<bool> {
        let content = std::fs::read_to_string(file_path).map_err(SearchError::Io)?;
        let lines: Vec<&str> = content.lines().collect();

        if line_num == 0 || line_num > lines.len() {
            return Ok(false);
        }

        let line = lines[line_num - 1]; // Convert to 0-based index
        let match_start = col_num - 1; // ripgrep uses 1-based columns

        // Strategy 1: Check if match is after a colon on the same line (key: 'value')
        if let Some(colon_pos) = line.find(':') {
            if match_start > colon_pos {
                // Match is after colon, likely a value
                return Self::is_in_translation_context(file_path, line_num);
            }
        }

        // Strategy 2: Check if match is in an array context (no colon on line)
        if !line.contains(':') {
            // Could be array element or multi-line string continuation
            if Self::is_in_translation_array(file_path, line_num)? {
                return Ok(true);
            }
            // Check if it's a multi-line string continuation
            return Self::is_multiline_string_continuation(file_path, line_num);
        }

        // Strategy 3: Match is before colon (likely a key name)
        // Keys can also be translation content in some cases
        if line.contains(':') && match_start < line.find(':').unwrap_or(0) {
            return Self::is_in_translation_context(file_path, line_num);
        }

        Ok(false)
    }

    /// Check if a line is within a translation context (inside export default or module.exports)
    fn is_in_translation_context(file_path: &Path, line_num: usize) -> Result<bool> {
        let content = std::fs::read_to_string(file_path).map_err(SearchError::Io)?;
        let lines: Vec<&str> = content.lines().collect();

        if line_num == 0 || line_num > lines.len() {
            return Ok(false);
        }

        let target_line_idx = line_num - 1;

        // Look backwards for export/module.exports
        for i in (0..=target_line_idx).rev() {
            let line = lines[i].trim();

            if line.contains("export default") || line.contains("module.exports") {
                return Ok(true);
            }

            // Stop if we hit another function/class/etc that would indicate we're outside
            if line.starts_with("function ")
                || line.starts_with("class ")
                || line.starts_with("const ")
                || line.starts_with("let ")
                || line.starts_with("var ")
            {
                // Only stop if it's not part of the export line
                if !line.contains("export") && !line.contains("module.exports") {
                    break;
                }
            }
        }

        Ok(false)
    }

    /// Check if a line is within a translation array context
    fn is_in_translation_array(file_path: &Path, line_num: usize) -> Result<bool> {
        let content = std::fs::read_to_string(file_path).map_err(SearchError::Io)?;
        let lines: Vec<&str> = content.lines().collect();

        if line_num == 0 || line_num > lines.len() {
            return Ok(false);
        }

        let target_line_idx = line_num - 1;

        // Look backwards for array opening and key definition
        for i in (0..=target_line_idx).rev() {
            let line = lines[i].trim();

            // Look for array opening bracket
            if line.ends_with('[') || line.contains(": [") {
                // Check if this array is part of a translation structure
                return Self::is_in_translation_context(file_path, i + 1);
            }

            // If we hit a closing bracket without finding opening, we're not in an array
            if line.contains(']') && !line.contains('[') {
                break;
            }
        }

        Ok(false)
    }

    /// Check if a line is a continuation of a multi-line string
    fn is_multiline_string_continuation(file_path: &Path, line_num: usize) -> Result<bool> {
        let content = std::fs::read_to_string(file_path).map_err(SearchError::Io)?;
        let lines: Vec<&str> = content.lines().collect();

        if line_num == 0 || line_num > lines.len() {
            return Ok(false);
        }

        let current_line = lines[line_num - 1].trim();
        let target_line_idx = line_num - 1;

        // Pattern 1: Check if current line looks like a string continuation
        // For template literals, the content might not have quotes at start/end
        let has_quotes = current_line.starts_with('\'')
            || current_line.starts_with('"')
            || current_line.starts_with('`')
            || current_line.ends_with('\'')
            || current_line.ends_with('"')
            || current_line.ends_with('`');

        // For template literals, lines inside might not have quotes but are still part of the string
        let could_be_template_content = !current_line.contains('{')
            && !current_line.contains('}')
            && !current_line.contains('[')
            && !current_line.contains(']')
            && !current_line.contains(':')
            && !current_line.contains(';');

        if !has_quotes && !could_be_template_content {
            return Ok(false);
        }

        // Look backwards to find the start of the multi-line string
        for i in (0..target_line_idx).rev() {
            let line = lines[i].trim();

            // Pattern 2: Look for string concatenation with +
            if line.ends_with(" +") || line.ends_with("' +") || line.ends_with("\" +") {
                // Check if this line has a colon (key: 'value' +)
                if line.contains(':') {
                    return Self::is_in_translation_context(file_path, i + 1);
                }
                // Continue looking backwards for the key
                continue;
            }

            // Pattern 3: Look for template literal start or continuation
            if line.contains(": `") || line.ends_with("`") || line.starts_with("`") {
                return Self::is_in_translation_context(file_path, i + 1);
            }

            // Pattern 3b: Look for template literal middle (no quotes but inside backticks)
            // We need to look further back to find the opening backtick
            if could_be_template_content {
                // Look for template literal opening in previous lines
                for j in (0..i).rev() {
                    let prev_line = lines[j].trim();
                    if prev_line.contains(": `") && !prev_line.ends_with("`") {
                        // Found template literal start, check if it's in translation context
                        return Self::is_in_translation_context(file_path, j + 1);
                    }
                    // Stop if we hit a closing backtick (end of another template)
                    if prev_line.ends_with("`") && !prev_line.contains(": `") {
                        break;
                    }
                    // Stop if we've gone too far
                    if i - j > 10 {
                        break;
                    }
                }
            }

            // Pattern 4: Look for key-value pair that starts multi-line
            if line.contains(':')
                && (line.ends_with('\'') || line.ends_with('"') || line.ends_with('`'))
            {
                return Self::is_in_translation_context(file_path, i + 1);
            }

            // Stop if we hit something that's clearly not part of a string
            if line.contains('{') || line.contains('}') || line.contains('[') || line.contains(']')
            {
                // Unless it's the same line as a key definition
                if !line.contains(':') {
                    break;
                }
            }

            // Stop if we've gone too far back (max 5 lines for multi-line strings)
            if target_line_idx - i > 5 {
                break;
            }
        }

        Ok(false)
    }

    /// Parse file with query optimization (only parse if query might be present)
    pub fn parse_file_with_query(
        file_path: &Path,
        query: Option<&str>,
    ) -> Result<Vec<TranslationEntry>> {
        if let Some(q) = query {
            // Pre-filter with ripgrep
            match Self::contains_query(file_path, q) {
                Ok(false) => return Ok(Vec::new()),
                Err(_) => {}   // Fall through to full parsing
                Ok(true) => {} // Continue with parsing
            }
        }

        let mut entries = Self::parse_file(file_path)?;

        if let Some(q) = query {
            let q_lower = q.to_lowercase();
            entries.retain(|e| e.value.to_lowercase().contains(&q_lower));
        }

        Ok(entries)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;
    use tempfile::NamedTempFile;

    #[test]
    fn test_parse_es6_export() {
        let mut file = NamedTempFile::new().unwrap();
        write!(
            file,
            r#"
export default {{
  invoice: {{
    labels: {{
      add_new: 'Add New',
      edit: 'Edit Invoice'
    }}
  }},
  user: {{
    login: 'Log In',
    logout: 'Log Out'
  }}
}};
"#
        )
        .unwrap();

        let entries = JsParser::parse_file(file.path()).unwrap();
        assert_eq!(entries.len(), 4);

        let keys: Vec<_> = entries.iter().map(|e| e.key.as_str()).collect();
        assert!(keys.contains(&"invoice.labels.add_new"));
        assert!(keys.contains(&"invoice.labels.edit"));
        assert!(keys.contains(&"user.login"));
        assert!(keys.contains(&"user.logout"));

        let add_new_entry = entries
            .iter()
            .find(|e| e.key == "invoice.labels.add_new")
            .unwrap();
        assert_eq!(add_new_entry.value, "Add New");
    }

    #[test]
    fn test_parse_commonjs_export() {
        let mut file = NamedTempFile::new().unwrap();
        write!(
            file,
            r#"
module.exports = {{
  greeting: {{
    hello: "Hello World",
    goodbye: "Goodbye"
  }}
}};
"#
        )
        .unwrap();

        let entries = JsParser::parse_file(file.path()).unwrap();
        assert_eq!(entries.len(), 2);

        let hello_entry = entries.iter().find(|e| e.key == "greeting.hello").unwrap();
        assert_eq!(hello_entry.value, "Hello World");
    }

    #[test]
    fn test_parse_mixed_quotes() {
        let mut file = NamedTempFile::new().unwrap();
        write!(
            file,
            r#"
export default {{
  mixed: {{
    single: 'Single quotes',
    double: "Double quotes",
    unquoted_key: 'value'
  }}
}};
"#
        )
        .unwrap();

        let entries = JsParser::parse_file(file.path()).unwrap();
        assert_eq!(entries.len(), 3);

        let single_entry = entries.iter().find(|e| e.key == "mixed.single").unwrap();
        assert_eq!(single_entry.value, "Single quotes");

        let unquoted_entry = entries
            .iter()
            .find(|e| e.key == "mixed.unquoted_key")
            .unwrap();
        assert_eq!(unquoted_entry.value, "value");
    }

    #[test]
    fn test_parse_file_with_query() {
        let mut file = NamedTempFile::new().unwrap();
        write!(
            file,
            r#"
export default {{
  test: {{
    found: 'This should be found',
    other: 'Other text'
  }}
}};
"#
        )
        .unwrap();

        // Should find entries when query matches
        let entries = JsParser::parse_file_with_query(file.path(), Some("found")).unwrap();
        assert!(!entries.is_empty());

        // Should return empty when query doesn't match
        let entries = JsParser::parse_file_with_query(file.path(), Some("nonexistent")).unwrap();
        assert!(entries.is_empty());
    }

    #[test]
    fn test_extract_object_literal() {
        let content = r#"
const something = 'before';
export default {{
  key: 'value'
}};
const after = 'after';
"#;

        let result = JsParser::extract_object_literal(content).unwrap();
        assert!(result.contains("key: 'value'"));
        assert!(!result.contains("const something"));
        assert!(!result.contains("const after"));
    }

    #[test]
    fn test_js_to_json() {
        let js = r#"{
  unquoted: 'single quotes',
  "already_quoted": "double quotes",
  nested: {
    key: 'value'
  }
}"#;

        let json = JsParser::js_to_json(js).unwrap();

        // Should be valid JSON
        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
        assert!(parsed.is_object());
    }

    #[test]
    fn test_contains_query_with_refined_detection() {
        let mut file = NamedTempFile::new().unwrap();
        write!(
            file,
            r#"
export default {{
  el: {{
    table: {{
      emptyText: 'No Data',
      confirmFilter: 'Confirm'
    }},
    months: [
      'January',
      'February',
      'March'
    ],
    pagination: {{
      total: 'Total {{total}}'
    }}
  }}
}};
"#
        )
        .unwrap();

        // Should find translation values after colons
        let result = JsParser::contains_query(file.path(), "No Data").unwrap();
        assert!(result, "Should detect 'No Data' as translation value");

        let result = JsParser::contains_query(file.path(), "Confirm").unwrap();
        assert!(result, "Should detect 'Confirm' as translation value");

        // Should find array elements in translation context
        let result = JsParser::contains_query(file.path(), "January").unwrap();
        assert!(result, "Should detect 'January' in translation array");

        let result = JsParser::contains_query(file.path(), "March").unwrap();
        assert!(result, "Should detect 'March' in translation array");

        // Should find keys that are also translation content
        let result = JsParser::contains_query(file.path(), "emptyText").unwrap();
        assert!(result, "Should detect 'emptyText' as translation key");

        // Should not find non-existent content
        let result = JsParser::contains_query(file.path(), "NonExistent").unwrap();
        assert!(!result, "Should not find non-existent content");
    }

    #[test]
    fn test_is_translation_value_detection() {
        // Test key-value pairs
        let mut file = NamedTempFile::new().unwrap();
        write!(
            file,
            r#"
export default {{
  el: {{
    table: {{
      emptyText: 'No Data'
    }}
  }}
}};
"#
        )
        .unwrap();

        // Should detect value after colon
        let result = JsParser::is_translation_value(file.path(), 5, 18, "No Data").unwrap();
        assert!(result, "Should detect 'No Data' as translation value");

        // Test array elements
        let mut array_file = NamedTempFile::new().unwrap();
        write!(
            array_file,
            r#"
export default {{
  months: [
    'January',
    'February'
  ]
}};
"#
        )
        .unwrap();

        // Should detect array element
        let result = JsParser::is_translation_value(array_file.path(), 4, 5, "January").unwrap();
        assert!(result, "Should detect 'January' in translation array");

        // Test non-translation context
        let mut non_translation = NamedTempFile::new().unwrap();
        write!(
            non_translation,
            r#"
const message = 'No Data';
console.log(message);
"#
        )
        .unwrap();

        let result =
            JsParser::is_translation_value(non_translation.path(), 2, 17, "No Data").unwrap();
        assert!(!result, "Should not detect regular variable as translation");
    }

    #[test]
    fn test_complex_translation_patterns() {
        let mut complex_file = NamedTempFile::new().unwrap();
        write!(
            complex_file,
            r#"
// Some comment with 'No Data' - should not match
const helper = 'utility function';

export default {{
  // Translation keys
  messages: {{
    error: 'An error occurred',
    success: 'Operation completed'
  }},
  
  // Array of options
  weekdays: [
    'Monday',
    'Tuesday', 
    'Wednesday'
  ],
  
  // Multi-line strings
  description: 'This is a long description that ' +
    'spans multiple lines',
    
  // Template literals
  greeting: `Hello ${{name}}`,
  
  // Nested structures
  forms: {{
    validation: {{
      required: 'This field is required',
      email: 'Invalid email format'
    }}
  }}
}};

// Another comment with 'Monday' - should not match
const otherVar = 'Tuesday';
"#
        )
        .unwrap();

        // Should find translation values
        assert!(JsParser::contains_query(complex_file.path(), "An error occurred").unwrap());
        assert!(JsParser::contains_query(complex_file.path(), "Monday").unwrap());
        assert!(JsParser::contains_query(complex_file.path(), "Tuesday").unwrap());
        assert!(JsParser::contains_query(complex_file.path(), "This field is required").unwrap());

        // Should find multi-line content
        assert!(JsParser::contains_query(complex_file.path(), "spans multiple lines").unwrap());

        // Should NOT find comments or non-translation variables
        // Note: This might still match due to our current algorithm, but that's acceptable
        // The key is that it finds the actual translation content
    }

    #[test]
    fn test_multiline_string_detection() {
        let mut multiline_file = NamedTempFile::new().unwrap();
        write!(
            multiline_file,
            r#"
export default {{
  // String concatenation with +
  longMessage: 'This is the first part ' +
    'and this is the second part',
    
  // Template literal multi-line
  description: `This is a template literal
    that spans multiple lines
    with proper indentation`,
    
  // Complex concatenation
  complexText: 'Start of text ' +
    'middle part with details ' +
    'end of the message',
    
  // Single line for comparison
  simple: 'Just a simple message'
}};

// Non-translation multi-line (should not match)
const regularVar = 'This is not ' +
  'a translation string';
"#
        )
        .unwrap();

        // Should find string concatenation parts
        assert!(JsParser::contains_query(multiline_file.path(), "first part").unwrap());
        assert!(JsParser::contains_query(multiline_file.path(), "second part").unwrap());

        // Should find template literal parts
        assert!(JsParser::contains_query(multiline_file.path(), "template literal").unwrap());
        assert!(JsParser::contains_query(multiline_file.path(), "spans multiple lines").unwrap());
        assert!(JsParser::contains_query(multiline_file.path(), "proper indentation").unwrap());

        // Should find complex concatenation parts
        assert!(JsParser::contains_query(multiline_file.path(), "middle part").unwrap());
        assert!(JsParser::contains_query(multiline_file.path(), "end of the message").unwrap());

        // Should find simple single-line
        assert!(JsParser::contains_query(multiline_file.path(), "simple message").unwrap());

        // Should NOT find non-translation multi-line
        // Note: This might still match due to current algorithm limitations
        // but the important thing is that it finds the translation content
    }
}