nu_plugin_nw_ulid 0.2.0

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

use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand};
use nu_protocol::{
    Category, Example, LabeledError, PipelineData, Signature, Span, SyntaxShape, Type, Value,
};

use crate::{SecurityWarnings, UlidEngine, UlidPlugin};

/// Generates new ULIDs with optional count and timestamp.
pub struct UlidGenerateCommand;

impl PluginCommand for UlidGenerateCommand {
    type Plugin = UlidPlugin;

    fn name(&self) -> &str {
        "ulid generate"
    }

    fn description(&self) -> &str {
        "Generate a new ULID (Universally Unique Lexicographically Sortable Identifier)"
    }

    fn signature(&self) -> Signature {
        Signature::build(self.name())
            .named(
                "count",
                SyntaxShape::Int,
                "Number of ULIDs to generate (max 10,000)",
                Some('c'),
            )
            .named(
                "timestamp",
                SyntaxShape::Int,
                "Custom timestamp in milliseconds",
                Some('t'),
            )
            .input_output_types(vec![
                (Type::Nothing, Type::String),
                (Type::Nothing, Type::List(Box::new(Type::String))),
            ])
            .category(Category::Generators)
    }

    fn examples(&self) -> Vec<Example<'_>> {
        vec![
            Example {
                example: "ulid generate",
                description: "Generate a single ULID",
                result: None,
            },
            Example {
                example: "ulid generate --count 5",
                description: "Generate 5 ULIDs",
                result: None,
            },
            Example {
                example: "ulid generate --timestamp 1640995200000",
                description: "Generate a ULID with specific timestamp",
                result: None,
            },
        ]
    }

    fn run(
        &self,
        _plugin: &Self::Plugin,
        _engine: &EngineInterface,
        call: &EvaluatedCall,
        _input: PipelineData,
    ) -> Result<PipelineData, LabeledError> {
        let count: Option<i64> = call.get_flag("count")?;
        let timestamp: Option<i64> = call.get_flag("timestamp")?;

        match count {
            Some(c) => generate_bulk_ulids(c, timestamp, call.head),
            None => generate_single_ulid(timestamp, call.head),
        }
    }
}

/// Validates whether a string is a valid ULID.
pub struct UlidValidateCommand;

impl PluginCommand for UlidValidateCommand {
    type Plugin = UlidPlugin;

    fn name(&self) -> &str {
        "ulid validate"
    }

    fn description(&self) -> &str {
        "Validate if a string is a valid ULID"
    }

    fn signature(&self) -> Signature {
        Signature::build(self.name())
            .required("ulid", SyntaxShape::String, "The ULID string to validate")
            .input_output_types(vec![(Type::Nothing, Type::Bool)])
            .category(Category::Strings)
    }

    fn examples(&self) -> Vec<Example<'_>> {
        vec![
            Example {
                example: "ulid validate '01AN4Z07BY79KA1307SR9X4MV3'",
                description: "Validate a ULID string",
                result: Some(Value::bool(true, Span::test_data())),
            },
            Example {
                example: "ulid validate 'invalid-ulid'",
                description: "Validate an invalid ULID string",
                result: Some(Value::bool(false, Span::test_data())),
            },
        ]
    }

    fn run(
        &self,
        _plugin: &Self::Plugin,
        _engine: &EngineInterface,
        call: &EvaluatedCall,
        _input: PipelineData,
    ) -> Result<PipelineData, LabeledError> {
        let ulid_str: String = call.req(0)?;
        let is_valid = UlidEngine::validate(&ulid_str);
        Ok(PipelineData::Value(Value::bool(is_valid, call.head), None))
    }
}

/// Parses a ULID string and extracts its timestamp and randomness components.
pub struct UlidParseCommand;

impl PluginCommand for UlidParseCommand {
    type Plugin = UlidPlugin;

    fn name(&self) -> &str {
        "ulid parse"
    }

    fn description(&self) -> &str {
        "Parse a ULID string and extract its components"
    }

    fn signature(&self) -> Signature {
        Signature::build(self.name())
            .required("ulid", SyntaxShape::String, "The ULID string to parse")
            .input_output_types(vec![(Type::Nothing, Type::Record(vec![].into()))])
            .category(Category::Strings)
    }

    fn examples(&self) -> Vec<Example<'_>> {
        vec![Example {
            example: "ulid parse '01AN4Z07BY79KA1307SR9X4MV3'",
            description: "Parse a ULID and show its components",
            result: None,
        }]
    }

    fn run(
        &self,
        _plugin: &Self::Plugin,
        _engine: &EngineInterface,
        call: &EvaluatedCall,
        _input: PipelineData,
    ) -> Result<PipelineData, LabeledError> {
        let ulid_str: String = call.req(0)?;

        match UlidEngine::parse(&ulid_str) {
            Ok(components) => {
                let value = UlidEngine::components_to_value(&components, call.head);
                Ok(PipelineData::Value(value, None))
            }
            Err(e) => Err(LabeledError::new("Parse failed").with_label(e.to_string(), call.head)),
        }
    }
}

/// Displays comprehensive security guidance for ULID usage contexts.
pub struct UlidSecurityAdviceCommand;

impl PluginCommand for UlidSecurityAdviceCommand {
    type Plugin = UlidPlugin;

    fn name(&self) -> &str {
        "ulid security-advice"
    }

    fn description(&self) -> &str {
        "Show comprehensive security advice for ULID usage"
    }

    fn signature(&self) -> Signature {
        Signature::build(self.name())
            .input_output_types(vec![(Type::Nothing, Type::Record(vec![].into()))])
            .category(Category::Misc)
    }

    fn examples(&self) -> Vec<Example<'_>> {
        vec![Example {
            example: "ulid security-advice",
            description: "Display security guidance for ULID usage",
            result: None,
        }]
    }

    fn run(
        &self,
        _plugin: &Self::Plugin,
        _engine: &EngineInterface,
        call: &EvaluatedCall,
        _input: PipelineData,
    ) -> Result<PipelineData, LabeledError> {
        let advice = SecurityWarnings::get_security_advice(call.head);
        Ok(PipelineData::Value(advice, None))
    }
}

fn generate_single_ulid(
    timestamp: Option<i64>,
    span: nu_protocol::Span,
) -> Result<PipelineData, LabeledError> {
    let ulid = match timestamp {
        Some(ts) => UlidEngine::generate_with_timestamp(ts as u64),
        None => UlidEngine::generate(),
    }
    .map_err(|e| LabeledError::new("Generation failed").with_label(e.to_string(), span))?;

    Ok(PipelineData::Value(
        Value::string(ulid.to_string(), span),
        None,
    ))
}

fn generate_bulk_ulids(
    count: i64,
    timestamp: Option<i64>,
    span: nu_protocol::Span,
) -> Result<PipelineData, LabeledError> {
    let count_usize = if count < 0 {
        return Err(LabeledError::new("Invalid count").with_label("Count must be positive", span));
    } else if count > crate::MAX_BULK_GENERATION as i64 {
        return Err(LabeledError::new("Count too large").with_label(
            format!("Maximum count is {}", crate::MAX_BULK_GENERATION),
            span,
        ));
    } else {
        count as usize
    };

    let ulids = match timestamp {
        Some(ts) => {
            let mut result = Vec::new();
            for _ in 0..count_usize {
                let ulid = UlidEngine::generate_with_timestamp(ts as u64).map_err(|e| {
                    LabeledError::new("Generation failed").with_label(e.to_string(), span)
                })?;
                result.push(ulid);
            }
            result
        }
        None => UlidEngine::generate_bulk(count_usize).map_err(|e| {
            LabeledError::new("Bulk generation failed").with_label(e.to_string(), span)
        })?,
    };

    let values: Vec<Value> = ulids
        .iter()
        .map(|ulid| Value::string(ulid.to_string(), span))
        .collect();

    Ok(PipelineData::Value(Value::list(values, span), None))
}

#[cfg(test)]
mod tests {
    use super::*;
    use nu_protocol::{Span, Value};

    fn create_test_span() -> Span {
        Span::test_data()
    }

    mod ulid_generate_command {
        use super::*;

        #[test]
        fn test_command_signature() {
            let cmd = UlidGenerateCommand;
            let signature = cmd.signature();

            assert_eq!(signature.name, "ulid generate");
            assert!(signature.named.iter().any(|flag| flag.long == "count"));
            assert!(signature.named.iter().any(|flag| flag.long == "timestamp"));
            // Verify no --format flag exists (removed in favour of pipeline commands)
            assert!(
                !signature.named.iter().any(|flag| flag.long == "format"),
                "The --format flag should not exist"
            );
        }

        #[test]
        fn test_command_name() {
            let cmd = UlidGenerateCommand;
            assert_eq!(cmd.name(), "ulid generate");
        }

        #[test]
        fn test_command_description() {
            let cmd = UlidGenerateCommand;
            let desc = cmd.description();
            assert!(desc.contains("Generate"));
            assert!(desc.contains("ULID"));
        }

        #[test]
        fn test_command_examples() {
            let cmd = UlidGenerateCommand;
            let examples = cmd.examples();

            assert!(!examples.is_empty());
            assert!(
                examples
                    .iter()
                    .any(|ex| ex.example.contains("ulid generate"))
            );
        }

        #[test]
        fn test_count_validation_logic() {
            // Test count validation without full command execution
            let test_cases = vec![
                (-1, false, "negative count"),
                (0, true, "zero count"),
                (1, true, "normal count"),
                (5000, true, "medium count"),
                (crate::MAX_BULK_GENERATION as i64, true, "max count"),
                (
                    crate::MAX_BULK_GENERATION as i64 + 1,
                    false,
                    "over max count",
                ),
            ];

            for (count, should_be_valid, description) in test_cases {
                let is_valid = (0..=crate::MAX_BULK_GENERATION as i64).contains(&count);

                assert_eq!(
                    is_valid, should_be_valid,
                    "Failed for {}: {}",
                    count, description
                );
            }
        }
    }

    mod ulid_validate_command {
        use super::*;

        #[test]
        fn test_command_signature() {
            let cmd = UlidValidateCommand;
            let signature = cmd.signature();

            assert_eq!(signature.name, "ulid validate");
            assert_eq!(signature.required_positional.len(), 1);
            assert_eq!(signature.required_positional[0].name, "ulid");
            // Verify no --detailed flag exists (removed for type-consistency)
            assert!(
                !signature.named.iter().any(|flag| flag.long == "detailed"),
                "The --detailed flag should not exist"
            );
            // Verify output type is exclusively Bool
            assert_eq!(signature.input_output_types.len(), 1);
            assert_eq!(signature.input_output_types[0], (Type::Nothing, Type::Bool));
        }

        #[test]
        fn test_command_name() {
            let cmd = UlidValidateCommand;
            assert_eq!(cmd.name(), "ulid validate");
        }

        #[test]
        fn test_command_description() {
            let cmd = UlidValidateCommand;
            let desc = cmd.description();
            assert!(desc.contains("Validate"));
            assert!(desc.contains("ULID"));
        }

        #[test]
        fn test_command_examples() {
            let cmd = UlidValidateCommand;
            let examples = cmd.examples();

            assert_eq!(examples.len(), 2);

            // Check that examples include both valid and invalid cases
            assert!(examples[0].example.contains("01AN4Z07BY79KA1307SR9X4MV3"));
            assert!(examples[0].result.is_some());
            assert!(examples[1].example.contains("invalid-ulid"));
            assert!(examples[1].result.is_some());

            // Verify no --detailed example exists
            assert!(
                !examples.iter().any(|ex| ex.example.contains("--detailed")),
                "No example should reference --detailed"
            );
        }

        #[test]
        fn test_validation_logic_integration() {
            // Test validation against known patterns
            let test_cases = vec![
                ("01AN4Z07BY79KA1307SR9X4MV3", true, "standard example ULID"),
                ("01BX5ZZKBKACTAV9WEVGEMMVRY", true, "another valid ULID"),
                ("", false, "empty string"),
                ("too_short", false, "too short"),
                ("01AN4Z07BY79KA1307SR9X4MV3X", false, "too long"),
                ("invalid-chars!", false, "invalid characters"),
                (
                    "lowercase123456789012345678",
                    false,
                    "lowercase not allowed",
                ),
            ];

            for (ulid_str, expected_valid, description) in test_cases {
                let is_valid = UlidEngine::validate(ulid_str);
                assert_eq!(
                    is_valid, expected_valid,
                    "Failed for '{}': {}",
                    ulid_str, description
                );
            }
        }
    }

    mod ulid_parse_command {
        use super::*;

        #[test]
        fn test_command_signature() {
            let cmd = UlidParseCommand;
            let signature = cmd.signature();

            assert_eq!(signature.name, "ulid parse");
            assert_eq!(signature.required_positional.len(), 1);
            assert_eq!(signature.required_positional[0].name, "ulid");
        }

        #[test]
        fn test_command_name() {
            let cmd = UlidParseCommand;
            assert_eq!(cmd.name(), "ulid parse");
        }

        #[test]
        fn test_command_description() {
            let cmd = UlidParseCommand;
            let desc = cmd.description();
            assert!(desc.contains("Parse"));
            assert!(desc.contains("ULID"));
            assert!(desc.contains("components"));
        }

        #[test]
        fn test_command_examples() {
            let cmd = UlidParseCommand;
            let examples = cmd.examples();

            assert!(!examples.is_empty());
            assert!(examples.iter().any(|ex| ex.example.contains("ulid parse")));
        }

        #[test]
        fn test_parsing_logic_integration() {
            // Generate a known ULID and test parsing
            if let Ok(generated_ulid) = UlidEngine::generate() {
                let ulid_str = generated_ulid.to_string();
                match UlidEngine::parse(&ulid_str) {
                    Ok(components) => {
                        assert_eq!(components.ulid, ulid_str);
                        assert!(components.valid);
                        assert!(components.timestamp_ms > 0);
                        assert!(!components.randomness_hex.is_empty());
                    }
                    Err(_) => panic!("Should be able to parse generated ULID"),
                }
            }

            // Test parsing invalid ULID
            match UlidEngine::parse("invalid-ulid") {
                Ok(_) => panic!("Should not be able to parse invalid ULID"),
                Err(e) => {
                    assert!(e.to_string().contains("Invalid") || e.to_string().contains("Error"));
                }
            }
        }
    }

    mod ulid_security_advice_command {
        use super::*;

        #[test]
        fn test_command_signature() {
            let cmd = UlidSecurityAdviceCommand;
            let signature = cmd.signature();

            assert_eq!(signature.name, "ulid security-advice");
            assert_eq!(signature.required_positional.len(), 0);
        }

        #[test]
        fn test_command_name() {
            let cmd = UlidSecurityAdviceCommand;
            assert_eq!(cmd.name(), "ulid security-advice");
        }

        #[test]
        fn test_command_description() {
            let cmd = UlidSecurityAdviceCommand;
            let desc = cmd.description();
            assert!(desc.contains("security"));
            assert!(desc.contains("advice") || desc.contains("guidance"));
        }

        #[test]
        fn test_command_examples() {
            let cmd = UlidSecurityAdviceCommand;
            let examples = cmd.examples();

            assert!(!examples.is_empty());
            assert!(
                examples
                    .iter()
                    .any(|ex| ex.example.contains("ulid security-advice"))
            );
        }
    }

    mod input_validation {

        #[test]
        fn test_count_parameter_bounds() {
            // Test count validation boundaries
            let max = crate::MAX_BULK_GENERATION as i64;
            let valid_counts = [0, 1, max];
            let invalid_counts = [max + 1, -1];

            for count in valid_counts {
                assert!(
                    (0..=max).contains(&count),
                    "Count {} should be valid",
                    count
                );
            }

            for count in invalid_counts {
                assert!(
                    !(0..=max).contains(&count),
                    "Count {} should be invalid",
                    count
                );
            }
        }

        #[test]
        fn test_timestamp_parameter_validation() {
            // Test timestamp validation
            let valid_timestamps = vec![
                0u64,             // Unix epoch
                1640995200000u64, // 2022-01-01 00:00:00 UTC
                1000000000000u64, // Some large valid timestamp
            ];

            for ts in valid_timestamps {
                // Basic sanity check - timestamp should be usable for ULID generation
                assert!(ts < u64::MAX, "Timestamp {} should be valid", ts);
            }
        }

        #[test]
        fn test_ulid_string_validation_patterns() {
            let valid_patterns = vec![
                ("26 character length", "01AN4Z07BY79KA1307SR9X4MV3"),
                ("all valid chars", "7ZZZZZZZZZZZZZZZZZZZZZZZZZ"),
                ("mixed case valid", "01BX5ZZKBKACTAV9WEVGEMMVRY"),
            ];

            for (description, ulid_str) in valid_patterns {
                assert_eq!(
                    ulid_str.len(),
                    crate::ULID_STRING_LENGTH,
                    "Length check failed for {}",
                    description
                );
                assert!(
                    ulid_str
                        .chars()
                        .all(|c| crate::CROCKFORD_BASE32_CHARSET.contains(c)),
                    "Character set check failed for {}",
                    description
                );
            }
        }
    }

    mod error_handling {
        use super::*;

        #[test]
        fn test_error_message_construction() {
            // Test that error messages are properly constructed
            let test_cases = vec![
                ("Invalid count", "Count must be positive"),
                ("Count too large", "Maximum count is 10,000"),
                ("Generation failed", "ULID generation"),
                ("Parse failed", "parsing"),
            ];

            for (error_type, expected_content) in test_cases {
                let error = LabeledError::new(error_type);
                assert_eq!(error.msg, error_type);

                // Test error with label
                let error_with_label = error.with_label(expected_content, create_test_span());
                assert_eq!(error_with_label.msg, error_type);
            }
        }
    }

    mod execution_logic_tests {
        use super::*;

        #[test]
        fn test_ulid_generate_execution() {
            // Test the core ULID generation logic from the run method

            // Test single ULID generation
            let generated_ulid = UlidEngine::generate().expect("Should generate ULID");
            let ulid_str = generated_ulid.to_string();

            assert_eq!(
                ulid_str.len(),
                crate::ULID_STRING_LENGTH,
                "ULID should be 26 characters"
            );
            assert!(
                UlidEngine::validate(&ulid_str),
                "Generated ULID should be valid"
            );

            // Test bulk generation logic
            let bulk_ulids = UlidEngine::generate_bulk(5).expect("Should generate bulk ULIDs");
            assert_eq!(bulk_ulids.len(), 5, "Should generate exactly 5 ULIDs");

            // All should be unique
            let unique_count = bulk_ulids
                .iter()
                .map(|u| u.to_string())
                .collect::<std::collections::HashSet<_>>()
                .len();
            assert_eq!(unique_count, 5, "All generated ULIDs should be unique");
        }

        #[test]
        fn test_ulid_generate_with_timestamp_execution() {
            // Test timestamp-based generation logic
            let custom_timestamp = 1640995200000u64; // 2022-01-01 00:00:00 UTC

            let ulid = UlidEngine::generate_with_timestamp(custom_timestamp)
                .expect("Should generate ULID with timestamp");

            let parsed = UlidEngine::parse(&ulid.to_string()).expect("Should parse generated ULID");

            assert_eq!(parsed.timestamp_ms, custom_timestamp);
            assert!(parsed.valid);
        }

        #[test]
        fn test_count_validation_execution() {
            // Test count validation logic used in run method
            let test_cases = vec![
                (-1, false, "negative count"),
                (0, true, "zero count"), // Zero is valid, returns empty vec
                (1, true, "single count"),
                (crate::MAX_BULK_GENERATION as i64, true, "max count"),
                (
                    crate::MAX_BULK_GENERATION as i64 + 1,
                    false,
                    "over max count",
                ),
            ];

            for (count, should_be_valid, description) in test_cases {
                if count < 0 {
                    // Negative counts should be caught by validation
                    assert!(
                        !should_be_valid,
                        "Negative count should be invalid: {}",
                        description
                    );
                } else if count > crate::MAX_BULK_GENERATION as i64 {
                    // Test the actual bulk generation limit
                    let result = UlidEngine::generate_bulk(count as usize);
                    assert!(
                        result.is_err(),
                        "Over-limit count should fail: {}",
                        description
                    );
                } else {
                    // Valid counts should work
                    let result = UlidEngine::generate_bulk(count as usize);
                    assert!(
                        result.is_ok(),
                        "Valid count should succeed: {}",
                        description
                    );
                    assert_eq!(result.unwrap().len(), count as usize);
                }
            }
        }

        #[test]
        fn test_ulid_validate_execution() {
            // Test validation logic from UlidValidateCommand run method
            let valid_ulids = vec!["01AN4Z07BY79KA1307SR9X4MV3", "01BX5ZZKBKACTAV9WEVGEMMVRY"];

            let invalid_ulids = vec![
                "invalid",
                "too_short",
                "01AN4Z07BY79KA1307SR9X4MV3X", // too long
                "",                            // empty
                "01AN4Z07BY79KA1307SR9X4MV!",  // invalid character
            ];

            // Test basic validation
            for ulid_str in &valid_ulids {
                assert!(
                    UlidEngine::validate(ulid_str),
                    "Should validate: {}",
                    ulid_str
                );
            }

            for ulid_str in &invalid_ulids {
                assert!(
                    !UlidEngine::validate(ulid_str),
                    "Should not validate: {}",
                    ulid_str
                );
            }
        }

        #[test]
        fn test_ulid_parse_execution() {
            // Test parsing logic from UlidParseCommand run method
            let test_ulid = UlidEngine::generate().expect("Should generate test ULID");
            let ulid_str = test_ulid.to_string();

            // Test successful parsing
            let components = UlidEngine::parse(&ulid_str).expect("Should parse valid ULID");

            assert_eq!(components.ulid, ulid_str);
            assert!(components.valid);
            assert!(components.timestamp_ms > 0);
            assert!(!components.randomness_hex.is_empty());

            // Test components to value conversion
            let span = create_test_span();
            let value = UlidEngine::components_to_value(&components, span);

            match value {
                Value::Record { val, .. } => {
                    let record = val.into_owned();
                    assert!(record.contains("ulid"));
                    assert!(record.contains("timestamp"));
                    assert!(record.contains("randomness"));
                    assert!(record.contains("valid"));
                }
                _ => panic!("Components should convert to Record value"),
            }

            // Test parsing invalid ULID
            let invalid_result = UlidEngine::parse("invalid-ulid");
            assert!(invalid_result.is_err(), "Should fail to parse invalid ULID");
        }

        #[test]
        fn test_timestamp_boundary_conditions() {
            // Test timestamp handling edge cases
            let test_timestamps = vec![
                0u64,             // Unix epoch
                1640995200000u64, // 2022-01-01 00:00:00 UTC
                u64::MAX - 1000,  // Near max value
            ];

            for timestamp in test_timestamps {
                // Test timestamp-based generation
                let result = UlidEngine::generate_with_timestamp(timestamp);

                if timestamp < u64::MAX - 1000 {
                    assert!(
                        result.is_ok(),
                        "Should generate ULID with timestamp {}",
                        timestamp
                    );

                    let ulid = result.unwrap();
                    let parsed = UlidEngine::parse(&ulid.to_string()).unwrap();
                    assert_eq!(parsed.timestamp_ms, timestamp);
                }
            }
        }

        #[test]
        fn test_ulid_uniqueness_and_sorting() {
            // Test ULID uniqueness and lexicographic sorting properties
            let mut ulids = Vec::new();

            // Generate multiple ULIDs
            for _ in 0..10 {
                let ulid = UlidEngine::generate().expect("Should generate ULID");
                ulids.push(ulid.to_string());
            }

            // All should be unique
            let unique_count = ulids.iter().collect::<std::collections::HashSet<_>>().len();
            assert_eq!(unique_count, 10, "All ULIDs should be unique");

            // Test lexicographic ordering (ULIDs should be roughly sortable by generation time)
            let sorted_ulids = {
                let mut sorted = ulids.clone();
                sorted.sort();
                sorted
            };

            // Due to timestamp precision, consecutive ULIDs should have some ordering correlation
            // We'll just verify they can be sorted without panicking
            assert_eq!(sorted_ulids.len(), ulids.len());
        }

        #[test]
        fn test_error_handling_paths() {
            // Test various error conditions in ULID operations

            // Test invalid ULID string patterns
            let invalid_inputs = vec![
                ("", "empty string"),
                ("invalid", "too short"),
                ("01AN4Z07BY79KA1307SR9X4MV3EXTRA", "too long"),
                ("01AN4Z07BY79KA1307SR9X4MV!", "invalid character"),
                ("not-a-ulid-at-all", "completely invalid"),
            ];

            for (input, description) in invalid_inputs {
                // Test validation
                assert!(
                    !UlidEngine::validate(input),
                    "Should reject {}: {}",
                    input,
                    description
                );

                // Test parsing fails appropriately
                let parse_result = UlidEngine::parse(input);
                assert!(
                    parse_result.is_err(),
                    "Parsing should fail for {}",
                    description
                );
            }

            // Test bulk generation limits
            let over_limit_result = UlidEngine::generate_bulk(10_001);
            assert!(
                over_limit_result.is_err(),
                "Should reject over-limit bulk generation"
            );
        }

        #[test]
        fn test_output_value_creation() {
            // Test the various Value creation paths used in run methods
            let test_ulid = UlidEngine::generate().expect("Should generate test ULID");
            let span = create_test_span();

            // Test single ULID value creation
            let single_value = Value::string(test_ulid.to_string(), span);
            match single_value {
                Value::String { val, .. } => {
                    assert_eq!(val, test_ulid.to_string());
                }
                _ => panic!("Single ULID should create String value"),
            }

            // Test list value creation (for bulk generation)
            let bulk_ulids = [test_ulid];
            let list_values: Vec<Value> = bulk_ulids
                .iter()
                .map(|ulid| Value::string(ulid.to_string(), span))
                .collect();

            assert_eq!(list_values.len(), 1);
            match &list_values[0] {
                Value::String { val, .. } => {
                    assert_eq!(val, &test_ulid.to_string());
                }
                _ => panic!("Bulk ULID should create String values"),
            }

            // Test PipelineData creation
            let pipeline_data = PipelineData::Value(Value::list(list_values, span), None);

            match pipeline_data {
                PipelineData::Value(Value::List { vals, .. }, None) => {
                    assert_eq!(vals.len(), 1);
                }
                _ => panic!("Should create proper PipelineData"),
            }
        }
    }

    mod generate_single_ulid_tests {
        use super::*;

        #[test]
        fn test_generates_without_timestamp() {
            let span = create_test_span();
            let result = generate_single_ulid(None, span).unwrap();
            match result {
                PipelineData::Value(Value::String { val, .. }, _) => {
                    assert_eq!(val.len(), crate::ULID_STRING_LENGTH);
                }
                _ => panic!("Expected string pipeline value"),
            }
        }

        #[test]
        fn test_generates_with_timestamp() {
            let span = create_test_span();
            let result = generate_single_ulid(Some(1704067200000), span).unwrap();
            match result {
                PipelineData::Value(Value::String { val, .. }, _) => {
                    assert_eq!(val.len(), crate::ULID_STRING_LENGTH);
                }
                _ => panic!("Expected string pipeline value"),
            }
        }
    }

    mod generate_bulk_ulids_tests {
        use super::*;

        #[test]
        fn test_generates_correct_count() {
            let span = create_test_span();
            let result = generate_bulk_ulids(5, None, span).unwrap();
            match result {
                PipelineData::Value(Value::List { vals, .. }, _) => {
                    assert_eq!(vals.len(), 5);
                }
                _ => panic!("Expected list pipeline value"),
            }
        }

        #[test]
        fn test_negative_count_errors() {
            let span = create_test_span();
            assert!(generate_bulk_ulids(-1, None, span).is_err());
        }

        #[test]
        fn test_over_max_count_errors() {
            let span = create_test_span();
            assert!(generate_bulk_ulids(10_001, None, span).is_err());
        }

        #[test]
        fn test_with_timestamp() {
            let span = create_test_span();
            let result = generate_bulk_ulids(3, Some(1704067200000), span).unwrap();
            match result {
                PipelineData::Value(Value::List { vals, .. }, _) => {
                    assert_eq!(vals.len(), 3);
                }
                _ => panic!("Expected list pipeline value"),
            }
        }
    }
}