jiq 2.21.1

Interactive JSON query tool with real-time output
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
//! Fast character-based parser for computing stats without full JSON parsing

use crate::stats::types::{ElementType, ResultStats};

/// Fast stats parser without full JSON parsing
pub struct StatsParser;

impl StatsParser {
    /// Parse result string and compute stats
    ///
    /// Uses character-based detection to identify JSON type from the first
    /// non-whitespace character, avoiding full JSON parsing for performance.
    pub fn parse(result: &str) -> ResultStats {
        let trimmed = result.trim();

        if trimmed.is_empty() {
            return ResultStats::Null;
        }

        // Check for stream (multiple JSON values) first
        if let Some(count) = Self::is_stream(trimmed) {
            return ResultStats::Stream { count };
        }

        // Detect type from first character
        match trimmed.chars().next() {
            Some('[') => {
                let count = Self::count_array_items(trimmed);
                let element_type = if count == 0 {
                    ElementType::Empty
                } else {
                    Self::detect_element_type(trimmed)
                };
                ResultStats::Array {
                    count,
                    element_type,
                }
            }
            Some('{') => ResultStats::Object,
            Some('"') => ResultStats::String,
            Some('t') | Some('f') => ResultStats::Boolean,
            Some('n') => ResultStats::Null,
            Some(c) if c.is_ascii_digit() || c == '-' => ResultStats::Number,
            _ => ResultStats::Null, // Fallback for unexpected input
        }
    }

    /// Count top-level array items using depth tracking
    ///
    /// Counts commas at depth 1 (inside the array but not nested).
    /// Items = commas + 1 for non-empty arrays.
    fn count_array_items(result: &str) -> usize {
        let mut depth = 0;
        let mut comma_count = 0;
        let mut in_string = false;
        let mut escape_next = false;
        let mut has_content = false;

        for ch in result.chars() {
            if escape_next {
                escape_next = false;
                continue;
            }

            if ch == '\\' && in_string {
                escape_next = true;
                continue;
            }

            if ch == '"' {
                in_string = !in_string;
                if depth == 1 {
                    has_content = true;
                }
                continue;
            }

            if in_string {
                continue;
            }

            match ch {
                '[' | '{' => {
                    if depth == 1 {
                        has_content = true;
                    }
                    depth += 1;
                }
                ']' | '}' => {
                    depth -= 1;
                }
                ',' => {
                    if depth == 1 {
                        comma_count += 1;
                    }
                }
                c if !c.is_whitespace() && depth == 1 => {
                    has_content = true;
                }
                _ => {}
            }
        }

        // Items = commas + 1 for non-empty arrays, 0 for empty arrays
        if has_content { comma_count + 1 } else { 0 }
    }

    /// Detect element type from first few array elements
    ///
    /// Peeks at array elements to determine if they are homogeneous
    /// (all same type) or mixed.
    fn detect_element_type(result: &str) -> ElementType {
        let mut depth = 0;
        let mut in_string = false;
        let mut escape_next = false;
        let mut first_type: Option<ElementType> = None;
        let mut elements_checked = 0;
        const MAX_ELEMENTS_TO_CHECK: usize = 10;

        let chars: Vec<char> = result.chars().collect();
        let mut i = 0;

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

            if escape_next {
                escape_next = false;
                i += 1;
                continue;
            }

            if ch == '\\' && in_string {
                escape_next = true;
                i += 1;
                continue;
            }

            if ch == '"' {
                if depth == 1 && !in_string {
                    // Starting a string element at depth 1
                    let element_type = ElementType::Strings;
                    match &first_type {
                        None => first_type = Some(element_type),
                        Some(t) if *t != ElementType::Strings => return ElementType::Mixed,
                        _ => {}
                    }
                    elements_checked += 1;
                }
                in_string = !in_string;
                i += 1;
                continue;
            }

            if in_string {
                i += 1;
                continue;
            }

            match ch {
                '[' => {
                    if depth == 1 {
                        // Starting an array element
                        let element_type = ElementType::Arrays;
                        match &first_type {
                            None => first_type = Some(element_type),
                            Some(t) if *t != ElementType::Arrays => return ElementType::Mixed,
                            _ => {}
                        }
                        elements_checked += 1;
                    }
                    depth += 1;
                }
                '{' => {
                    if depth == 1 {
                        // Starting an object element
                        let element_type = ElementType::Objects;
                        match &first_type {
                            None => first_type = Some(element_type),
                            Some(t) if *t != ElementType::Objects => return ElementType::Mixed,
                            _ => {}
                        }
                        elements_checked += 1;
                    }
                    depth += 1;
                }
                ']' | '}' => {
                    depth -= 1;
                }
                't' | 'f' if depth == 1 => {
                    // Boolean (true/false)
                    let element_type = ElementType::Booleans;
                    match &first_type {
                        None => first_type = Some(element_type),
                        Some(t) if *t != ElementType::Booleans => return ElementType::Mixed,
                        _ => {}
                    }
                    elements_checked += 1;
                }
                'n' if depth == 1 => {
                    // null
                    let element_type = ElementType::Nulls;
                    match &first_type {
                        None => first_type = Some(element_type),
                        Some(t) if *t != ElementType::Nulls => return ElementType::Mixed,
                        _ => {}
                    }
                    elements_checked += 1;
                }
                c if (c.is_ascii_digit() || c == '-') && depth == 1 => {
                    // Number
                    let element_type = ElementType::Numbers;
                    match &first_type {
                        None => first_type = Some(element_type),
                        Some(t) if *t != ElementType::Numbers => return ElementType::Mixed,
                        _ => {}
                    }
                    elements_checked += 1;
                }
                _ => {}
            }

            i += 1;
        }

        first_type.unwrap_or(ElementType::Empty)
    }

    /// Check if result contains a stream of JSON values
    ///
    /// Returns Some(count) if multiple separate JSON values are detected,
    /// None if it's a single value.
    fn is_stream(result: &str) -> Option<usize> {
        let mut count = 0;
        let mut depth = 0;
        let mut in_string = false;
        let mut escape_next = false;
        let mut in_value = false;

        for ch in result.chars() {
            if escape_next {
                escape_next = false;
                continue;
            }

            if ch == '\\' && in_string {
                escape_next = true;
                continue;
            }

            if ch == '"' {
                if !in_string && depth == 0 {
                    // Starting a new string value at top level
                    if !in_value {
                        count += 1;
                        in_value = true;
                    }
                }
                in_string = !in_string;
                continue;
            }

            if in_string {
                continue;
            }

            match ch {
                '[' | '{' => {
                    if depth == 0 && !in_value {
                        // Starting a new container at top level
                        count += 1;
                        in_value = true;
                    }
                    depth += 1;
                }
                ']' | '}' => {
                    depth -= 1;
                    if depth == 0 {
                        in_value = false;
                    }
                }
                't' | 'f' | 'n' if depth == 0 && !in_value => {
                    // Starting a boolean or null at top level
                    count += 1;
                    in_value = true;
                }
                c if (c.is_ascii_digit() || c == '-') && depth == 0 && !in_value => {
                    // Starting a number at top level
                    count += 1;
                    in_value = true;
                }
                c if c.is_whitespace() && depth == 0 => {
                    // Whitespace at top level ends the current value
                    in_value = false;
                }
                _ => {}
            }
        }

        if count > 1 { Some(count) } else { None }
    }
}

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

    // =========================================================================
    // Unit Tests for count_array_items
    // =========================================================================

    #[test]
    fn test_count_empty_array() {
        assert_eq!(StatsParser::count_array_items("[]"), 0);
        assert_eq!(StatsParser::count_array_items("[  ]"), 0);
        assert_eq!(StatsParser::count_array_items("[\n\t]"), 0);
    }

    #[test]
    fn test_count_simple_arrays() {
        assert_eq!(StatsParser::count_array_items("[1]"), 1);
        assert_eq!(StatsParser::count_array_items("[1, 2]"), 2);
        assert_eq!(StatsParser::count_array_items("[1, 2, 3]"), 3);
        assert_eq!(StatsParser::count_array_items(r#"["a", "b", "c"]"#), 3);
    }

    #[test]
    fn test_count_nested_arrays() {
        // Nested arrays should not count inner commas
        assert_eq!(StatsParser::count_array_items("[[1, 2], [3, 4]]"), 2);
        assert_eq!(StatsParser::count_array_items("[[1, 2, 3]]"), 1);
        assert_eq!(StatsParser::count_array_items("[[[1]], [[2]]]"), 2);
    }

    #[test]
    fn test_count_nested_objects() {
        // Nested objects should not count inner commas
        assert_eq!(StatsParser::count_array_items(r#"[{"a": 1, "b": 2}]"#), 1);
        assert_eq!(StatsParser::count_array_items(r#"[{"a": 1}, {"b": 2}]"#), 2);
    }

    #[test]
    fn test_count_strings_with_special_chars() {
        // Commas inside strings should not be counted
        assert_eq!(StatsParser::count_array_items(r#"["a,b", "c,d"]"#), 2);
        // Escaped quotes inside strings
        assert_eq!(StatsParser::count_array_items(r#"["a\"b", "c"]"#), 2);
        // Brackets inside strings
        assert_eq!(StatsParser::count_array_items(r#"["[1,2]", "{a,b}"]"#), 2);
    }

    // =========================================================================
    // Property-Based Tests
    // =========================================================================

    /// Strategy to generate a simple JSON value (non-container)
    fn arb_simple_json_value() -> impl Strategy<Value = String> {
        prop_oneof![
            // Numbers
            (-1000i64..1000).prop_map(|n| n.to_string()),
            // Strings (simple, no special chars for now)
            "[a-zA-Z0-9]{0,10}".prop_map(|s| format!(r#""{}""#, s)),
            // Booleans
            Just("true".to_string()),
            Just("false".to_string()),
            // Null
            Just("null".to_string()),
        ]
    }

    /// Strategy to generate a JSON array with known element count
    fn arb_json_array_with_count() -> impl Strategy<Value = (String, usize)> {
        prop::collection::vec(arb_simple_json_value(), 0..20).prop_map(|elements| {
            let count = elements.len();
            let json = format!("[{}]", elements.join(", "));
            (json, count)
        })
    }

    /// Strategy to generate nested JSON arrays
    fn arb_nested_json_array() -> impl Strategy<Value = (String, usize)> {
        prop::collection::vec(
            prop::collection::vec(arb_simple_json_value(), 0..5)
                .prop_map(|inner| format!("[{}]", inner.join(", "))),
            0..10,
        )
        .prop_map(|elements| {
            let count = elements.len();
            let json = format!("[{}]", elements.join(", "));
            (json, count)
        })
    }

    // Feature: stats-bar, Property 3: Array count accuracy
    // *For any* JSON array, the count displayed in stats SHALL equal the number
    // of top-level elements in the array, regardless of nesting depth within elements.
    // **Validates: Requirements 2.1, 2.7, 3.3**
    proptest! {
        #![proptest_config(ProptestConfig::with_cases(100))]

        #[test]
        fn prop_array_count_matches_element_count((json, expected_count) in arb_json_array_with_count()) {
            let actual_count = StatsParser::count_array_items(&json);
            prop_assert_eq!(
                actual_count, expected_count,
                "Array count mismatch for '{}': expected {}, got {}",
                json, expected_count, actual_count
            );
        }

        #[test]
        fn prop_nested_array_count_is_top_level_only((json, expected_count) in arb_nested_json_array()) {
            let actual_count = StatsParser::count_array_items(&json);
            prop_assert_eq!(
                actual_count, expected_count,
                "Nested array count mismatch for '{}': expected {}, got {}",
                json, expected_count, actual_count
            );
        }

        #[test]
        fn prop_array_count_ignores_commas_in_strings(
            elements in prop::collection::vec("[a-zA-Z]{1,5}".prop_map(|s| format!(r#""{},{}""#, s, s)), 1..10)
        ) {
            // Each element is a string containing a comma
            let expected_count = elements.len();
            let json = format!("[{}]", elements.join(", "));
            let actual_count = StatsParser::count_array_items(&json);
            prop_assert_eq!(
                actual_count, expected_count,
                "Count should ignore commas inside strings: '{}', expected {}, got {}",
                json, expected_count, actual_count
            );
        }
    }

    // =========================================================================
    // Unit Tests for detect_element_type
    // =========================================================================

    #[test]
    fn test_detect_empty_array() {
        assert_eq!(StatsParser::detect_element_type("[]"), ElementType::Empty);
        assert_eq!(StatsParser::detect_element_type("[  ]"), ElementType::Empty);
    }

    #[test]
    fn test_detect_objects() {
        assert_eq!(
            StatsParser::detect_element_type(r#"[{}]"#),
            ElementType::Objects
        );
        assert_eq!(
            StatsParser::detect_element_type(r#"[{"a": 1}, {"b": 2}]"#),
            ElementType::Objects
        );
    }

    #[test]
    fn test_detect_arrays() {
        assert_eq!(
            StatsParser::detect_element_type("[[]]"),
            ElementType::Arrays
        );
        assert_eq!(
            StatsParser::detect_element_type("[[1], [2, 3]]"),
            ElementType::Arrays
        );
    }

    #[test]
    fn test_detect_strings() {
        assert_eq!(
            StatsParser::detect_element_type(r#"["a"]"#),
            ElementType::Strings
        );
        assert_eq!(
            StatsParser::detect_element_type(r#"["hello", "world"]"#),
            ElementType::Strings
        );
    }

    #[test]
    fn test_detect_numbers() {
        assert_eq!(
            StatsParser::detect_element_type("[1]"),
            ElementType::Numbers
        );
        assert_eq!(
            StatsParser::detect_element_type("[1, 2, 3]"),
            ElementType::Numbers
        );
        assert_eq!(
            StatsParser::detect_element_type("[-1, 0, 100]"),
            ElementType::Numbers
        );
    }

    #[test]
    fn test_detect_booleans() {
        assert_eq!(
            StatsParser::detect_element_type("[true]"),
            ElementType::Booleans
        );
        assert_eq!(
            StatsParser::detect_element_type("[true, false]"),
            ElementType::Booleans
        );
    }

    #[test]
    fn test_detect_nulls() {
        assert_eq!(
            StatsParser::detect_element_type("[null]"),
            ElementType::Nulls
        );
        assert_eq!(
            StatsParser::detect_element_type("[null, null]"),
            ElementType::Nulls
        );
    }

    #[test]
    fn test_detect_mixed() {
        assert_eq!(
            StatsParser::detect_element_type("[1, \"a\"]"),
            ElementType::Mixed
        );
        assert_eq!(
            StatsParser::detect_element_type("[{}, []]"),
            ElementType::Mixed
        );
        assert_eq!(
            StatsParser::detect_element_type("[true, null]"),
            ElementType::Mixed
        );
    }

    // =========================================================================
    // Property-Based Tests for Element Type Detection
    // =========================================================================

    /// Strategy to generate homogeneous arrays of objects
    fn arb_array_of_objects() -> impl Strategy<Value = String> {
        prop::collection::vec(
            prop::collection::vec(("[a-z]{1,5}", arb_simple_json_value()), 0..3).prop_map(
                |pairs| {
                    let fields: Vec<String> = pairs
                        .iter()
                        .map(|(k, v)| format!(r#""{}": {}"#, k, v))
                        .collect();
                    format!("{{{}}}", fields.join(", "))
                },
            ),
            1..10,
        )
        .prop_map(|objects| format!("[{}]", objects.join(", ")))
    }

    /// Strategy to generate homogeneous arrays of arrays
    fn arb_array_of_arrays() -> impl Strategy<Value = String> {
        prop::collection::vec(
            prop::collection::vec((-100i64..100).prop_map(|n| n.to_string()), 0..5)
                .prop_map(|inner| format!("[{}]", inner.join(", "))),
            1..10,
        )
        .prop_map(|arrays| format!("[{}]", arrays.join(", ")))
    }

    /// Strategy to generate homogeneous arrays of strings
    fn arb_array_of_strings() -> impl Strategy<Value = String> {
        prop::collection::vec(
            "[a-zA-Z0-9]{0,10}".prop_map(|s| format!(r#""{}""#, s)),
            1..10,
        )
        .prop_map(|strings| format!("[{}]", strings.join(", ")))
    }

    /// Strategy to generate homogeneous arrays of numbers
    fn arb_array_of_numbers() -> impl Strategy<Value = String> {
        prop::collection::vec((-1000i64..1000).prop_map(|n| n.to_string()), 1..10)
            .prop_map(|numbers| format!("[{}]", numbers.join(", ")))
    }

    /// Strategy to generate homogeneous arrays of booleans
    fn arb_array_of_booleans() -> impl Strategy<Value = String> {
        prop::collection::vec(
            prop::bool::ANY.prop_map(|b| if b { "true" } else { "false" }.to_string()),
            1..10,
        )
        .prop_map(|bools| format!("[{}]", bools.join(", ")))
    }

    /// Strategy to generate homogeneous arrays of nulls
    fn arb_array_of_nulls() -> impl Strategy<Value = String> {
        (1usize..10).prop_map(|count| {
            let nulls: Vec<&str> = (0..count).map(|_| "null").collect();
            format!("[{}]", nulls.join(", "))
        })
    }

    // Feature: stats-bar, Property 2: Array element type detection
    // *For any* JSON array with homogeneous elements, the stats display SHALL correctly
    // identify the element type (objects, arrays, strings, numbers, booleans, nulls).
    // For arrays with heterogeneous elements, the stats SHALL display "mixed".
    // **Validates: Requirements 2.1, 2.2, 2.3, 2.4, 2.5, 2.6**
    proptest! {
        #![proptest_config(ProptestConfig::with_cases(100))]

        #[test]
        fn prop_detect_array_of_objects(json in arb_array_of_objects()) {
            let element_type = StatsParser::detect_element_type(&json);
            prop_assert_eq!(
                element_type, ElementType::Objects,
                "Array of objects should detect as Objects: {}",
                json
            );
        }

        #[test]
        fn prop_detect_array_of_arrays(json in arb_array_of_arrays()) {
            let element_type = StatsParser::detect_element_type(&json);
            prop_assert_eq!(
                element_type, ElementType::Arrays,
                "Array of arrays should detect as Arrays: {}",
                json
            );
        }

        #[test]
        fn prop_detect_array_of_strings(json in arb_array_of_strings()) {
            let element_type = StatsParser::detect_element_type(&json);
            prop_assert_eq!(
                element_type, ElementType::Strings,
                "Array of strings should detect as Strings: {}",
                json
            );
        }

        #[test]
        fn prop_detect_array_of_numbers(json in arb_array_of_numbers()) {
            let element_type = StatsParser::detect_element_type(&json);
            prop_assert_eq!(
                element_type, ElementType::Numbers,
                "Array of numbers should detect as Numbers: {}",
                json
            );
        }

        #[test]
        fn prop_detect_array_of_booleans(json in arb_array_of_booleans()) {
            let element_type = StatsParser::detect_element_type(&json);
            prop_assert_eq!(
                element_type, ElementType::Booleans,
                "Array of booleans should detect as Booleans: {}",
                json
            );
        }

        #[test]
        fn prop_detect_array_of_nulls(json in arb_array_of_nulls()) {
            let element_type = StatsParser::detect_element_type(&json);
            prop_assert_eq!(
                element_type, ElementType::Nulls,
                "Array of nulls should detect as Nulls: {}",
                json
            );
        }
    }

    // =========================================================================
    // Unit Tests for is_stream
    // =========================================================================

    #[test]
    fn test_single_value_not_stream() {
        assert_eq!(StatsParser::is_stream("{}"), None);
        assert_eq!(StatsParser::is_stream("[]"), None);
        assert_eq!(StatsParser::is_stream(r#""hello""#), None);
        assert_eq!(StatsParser::is_stream("123"), None);
        assert_eq!(StatsParser::is_stream("true"), None);
        assert_eq!(StatsParser::is_stream("null"), None);
    }

    #[test]
    fn test_multiple_values_is_stream() {
        assert_eq!(StatsParser::is_stream("{} {}"), Some(2));
        assert_eq!(StatsParser::is_stream("[] []"), Some(2));
        assert_eq!(StatsParser::is_stream("1 2 3"), Some(3));
        assert_eq!(StatsParser::is_stream(r#""a" "b""#), Some(2));
        assert_eq!(StatsParser::is_stream("true false"), Some(2));
        assert_eq!(StatsParser::is_stream("null null null"), Some(3));
    }

    #[test]
    fn test_mixed_stream() {
        assert_eq!(StatsParser::is_stream(r#"{} [] "a" 1 true null"#), Some(6));
        assert_eq!(StatsParser::is_stream(r#"{"a": 1} [1, 2]"#), Some(2));
    }

    #[test]
    fn test_stream_with_newlines() {
        assert_eq!(StatsParser::is_stream("{}\n{}"), Some(2));
        assert_eq!(StatsParser::is_stream("1\n2\n3"), Some(3));
    }

    // =========================================================================
    // Property-Based Tests for Stream Detection
    // =========================================================================

    /// Strategy to generate a stream of JSON values with known count
    fn arb_json_stream() -> impl Strategy<Value = (String, usize)> {
        prop::collection::vec(
            prop_oneof![
                Just("{}".to_string()),
                Just("[]".to_string()),
                (-100i64..100).prop_map(|n| n.to_string()),
                "[a-zA-Z]{1,5}".prop_map(|s| format!(r#""{}""#, s)),
                Just("true".to_string()),
                Just("false".to_string()),
                Just("null".to_string()),
            ],
            2..10, // At least 2 values to be a stream
        )
        .prop_map(|values| {
            let count = values.len();
            let stream = values.join("\n");
            (stream, count)
        })
    }

    /// Strategy to generate a single JSON value (not a stream)
    fn arb_single_json_value() -> impl Strategy<Value = String> {
        prop_oneof![
            // Simple object
            prop::collection::vec(
                ("[a-z]{1,3}", (-100i64..100).prop_map(|n| n.to_string())),
                0..3
            )
            .prop_map(|pairs| {
                let fields: Vec<String> = pairs
                    .iter()
                    .map(|(k, v)| format!(r#""{}": {}"#, k, v))
                    .collect();
                format!("{{{}}}", fields.join(", "))
            }),
            // Simple array
            prop::collection::vec((-100i64..100).prop_map(|n| n.to_string()), 0..5)
                .prop_map(|nums| format!("[{}]", nums.join(", "))),
            // String
            "[a-zA-Z0-9]{0,10}".prop_map(|s| format!(r#""{}""#, s)),
            // Number
            (-1000i64..1000).prop_map(|n| n.to_string()),
            // Boolean
            Just("true".to_string()),
            Just("false".to_string()),
            // Null
            Just("null".to_string()),
        ]
    }

    // Feature: stats-bar, Property 4: Stream detection
    // *For any* jq output containing multiple separate JSON values, the stats SHALL
    // display "Stream [N]" where N equals the count of separate values. For single-value
    // outputs, the stats SHALL NOT display "Stream" format.
    // **Validates: Requirements 1.7, 5.1, 5.2**
    proptest! {
        #![proptest_config(ProptestConfig::with_cases(100))]

        #[test]
        fn prop_stream_detection_counts_correctly((stream, expected_count) in arb_json_stream()) {
            let result = StatsParser::is_stream(&stream);
            prop_assert_eq!(
                result, Some(expected_count),
                "Stream should be detected with count {}: '{}'",
                expected_count, stream
            );
        }

        #[test]
        fn prop_single_value_not_detected_as_stream(json in arb_single_json_value()) {
            let result = StatsParser::is_stream(&json);
            prop_assert_eq!(
                result, None,
                "Single value should not be detected as stream: '{}'",
                json
            );
        }
    }

    // =========================================================================
    // Unit Tests for parse (integration)
    // =========================================================================

    #[test]
    fn test_parse_array() {
        let result = StatsParser::parse("[1, 2, 3]");
        assert_eq!(
            result,
            ResultStats::Array {
                count: 3,
                element_type: ElementType::Numbers
            }
        );
    }

    #[test]
    fn test_parse_object() {
        let result = StatsParser::parse(r#"{"a": 1}"#);
        assert_eq!(result, ResultStats::Object);
    }

    #[test]
    fn test_parse_string() {
        let result = StatsParser::parse(r#""hello""#);
        assert_eq!(result, ResultStats::String);
    }

    #[test]
    fn test_parse_number() {
        let result = StatsParser::parse("42");
        assert_eq!(result, ResultStats::Number);
    }

    #[test]
    fn test_parse_boolean() {
        let result = StatsParser::parse("true");
        assert_eq!(result, ResultStats::Boolean);
    }

    #[test]
    fn test_parse_null() {
        let result = StatsParser::parse("null");
        assert_eq!(result, ResultStats::Null);
    }

    #[test]
    fn test_parse_stream() {
        let result = StatsParser::parse("{}\n{}\n{}");
        assert_eq!(result, ResultStats::Stream { count: 3 });
    }
}