bnto-core 0.1.2

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

use serde::Serialize;

// --- ParamCondition — Conditional Visibility / Requirement Rules ---
//
// Declares when a parameter should be shown/required based on other param values.
// `Single` = one condition, `Any` = OR logic across multiple conditions.

/// A single condition entry: "when `param` has the value `equals`".
///
/// Used both standalone (in `ParamCondition::Single`) and as entries
/// in the `ParamCondition::Any` array.
#[derive(Debug, Clone, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ParamConditionEntry {
    /// The name of the parameter to check against.
    /// Example: `"operation"` — check the value of the "operation" parameter.
    pub param: String,

    /// The value that triggers visibility/requirement.
    /// Example: `"resize"` — only show this param when operation is "resize".
    pub equals: String,
}

/// Conditional visibility/requirement rule for a parameter.
///
/// Tells the UI when to show a parameter or when to make it required.
/// Uses `#[serde(untagged)]` so Single serializes as a plain object and
/// Any serializes as an array — no type discriminator field needed.
#[derive(Debug, Clone, Serialize, PartialEq)]
#[serde(untagged)]
pub enum ParamCondition {
    /// Show/require when a single parameter matches a value.
    /// Serializes as: `{"param": "operation", "equals": "resize"}`
    Single(ParamConditionEntry),

    /// Show/require when ANY of multiple conditions match (OR logic).
    /// Serializes as: `[{"param": "...", "equals": "..."}, ...]`
    Any(Vec<ParamConditionEntry>),
}

// --- InputCardinality ---

/// Declares how a processor expects to receive files for smart iteration.
/// Used by the auto-iteration executor to partition flat node sequences
/// into implicit per-file loops.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Default)]
#[serde(rename_all = "camelCase")]
pub enum InputCardinality {
    /// Processes one file at a time. Contiguous perFile nodes get wrapped
    /// in an implicit per-file loop in auto mode.
    #[default]
    PerFile,
    /// Needs the full batch of files at once (e.g., zip, concat, merge).
    /// Acts as an iteration barrier in auto mode.
    Batch,
    /// Processor generates output from its parameters — no input files.
    /// Runs exactly once, ignoring the file pipeline.
    Source,
}

// --- NodeCategory ---

/// The broad category a node belongs to. Used for UI grouping and filtering.
/// Serialized as kebab-case to match `@bnto/nodes` convention.
#[derive(Debug, Clone, Serialize, PartialEq)]
#[serde(rename_all = "kebab-case")]
pub enum NodeCategory {
    /// Image processing — compress, resize, convert formats
    Image,
    /// Spreadsheet/CSV operations — clean, rename columns
    Spreadsheet,
    /// File system operations — rename files
    File,
    /// Data transformation (future) — JSON, XML, text
    Data,
    /// Network operations (future) — HTTP requests, API calls
    Network,
    /// Control flow (future) — loops, conditionals, groups
    Control,
    /// System operations (future) — shell commands, environment
    System,
    /// Video operations — download, transcode (CLI/desktop only)
    Video,
    /// Input/output nodes — file input, file output
    Io,
}

// --- ParameterType ---

/// The type of a node parameter. Determines what UI control to render.
/// Tagged with `"type"` in JSON (e.g., `{"type": "number"}`).
#[derive(Debug, Clone, Serialize, PartialEq, Default)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum ParameterType {
    /// A numeric value (integer or float). Used for quality, width, height.
    Number,
    /// A text string. Used for find/replace patterns, prefixes, suffixes.
    #[default]
    String,
    /// A true/false toggle. Used for trimWhitespace, removeEmptyRows.
    Boolean,
    /// A choice from a fixed set of options (like a dropdown/select).
    /// The `options` field lists all valid values.
    Enum {
        /// The list of valid values for this enum parameter.
        /// Example: `["jpeg", "png", "webp"]` for image format selection.
        options: Vec<std::string::String>,
    },
    /// A structured object (key-value map). Used for column rename mappings.
    Object,
    /// A file upload parameter (base64-encoded). Used for overlay images, etc.
    /// The `accept` field lists allowed MIME types for the file picker.
    File {
        /// Accepted MIME types (e.g., `["image/png", "image/jpeg"]`).
        accept: Vec<std::string::String>,
    },
}

// --- Constraints ---

/// Optional constraints on a parameter's value (min/max range, required flag).
/// Used for validation and UI hints (slider bounds, required markers).
#[derive(Debug, Clone, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Constraints {
    /// Minimum allowed value (for numeric parameters).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min: Option<f64>,

    /// Maximum allowed value (for numeric parameters).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max: Option<f64>,

    /// Whether this parameter must be provided.
    pub required: bool,
}

// --- ParameterDef ---

/// A complete definition of one parameter a node accepts. Provides
/// everything the engine (validation) and UI (control rendering) need.
#[derive(Debug, Clone, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ParameterDef {
    /// The parameter's key name in config JSON (e.g., `"quality"`).
    pub name: std::string::String,

    /// Human-readable label for the UI.
    pub label: std::string::String,

    /// Description shown as tooltip or help text.
    pub description: std::string::String,

    /// Value type — determines what UI control to render.
    pub param_type: ParameterType,

    /// Default value (heterogeneous type via `serde_json::Value`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub default: Option<serde_json::Value>,

    /// Optional validation constraints (min/max range, required flag).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub constraints: Option<Constraints>,

    // --- UI Metadata Fields ---
    /// Placeholder text for input controls.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub placeholder: Option<String>,

    /// Show this parameter only when another parameter matches a value.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub visible_when: Option<ParamCondition>,

    /// Require this parameter only when another parameter matches a value.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub required_when: Option<ParamCondition>,

    /// Whether this param can be surfaced in container config panels.
    /// Defaults to `true`. Set `false` for internal wiring params.
    #[serde(default = "default_true")]
    pub surfaceable: bool,
}

/// Serde default for `surfaceable` field during deserialization.
#[allow(dead_code)]
fn default_true() -> bool {
    true
}

/// Manual Default because `surfaceable` must default to `true`, not `false`.
impl Default for ParameterDef {
    fn default() -> Self {
        Self {
            name: String::default(),
            label: String::default(),
            description: String::default(),
            param_type: ParameterType::default(),
            default: None,
            constraints: None,
            placeholder: None,
            visible_when: None,
            required_when: None,
            surfaceable: true,
        }
    }
}

// --- NodeTypeInfo — Node-type-level metadata (all 15 types) ---
//
// Separate from NodeMetadata because NodeMetadata describes a PROCESSOR
// (e.g., "image-compress") while NodeTypeInfo describes a NODE TYPE
// (e.g., "image-compress") — one per node type.
// Includes types the engine doesn't have processors for yet (http-request,
// shell-command). Codegen generates TS `NODE_TYPE_INFO` from this.

/// Everything the UI needs to know about a node type, independent of any
/// specific processor/operation. The engine's authoritative type registry.
#[derive(Debug, Clone, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct NodeTypeInfo {
    /// Type name as used in `.bnto.json` (e.g., `"image-compress"`, `"file-rename"`).
    pub name: String,
    /// Human-readable display label.
    pub label: String,
    /// One-sentence description.
    pub description: String,
    /// Category for UI grouping/filtering.
    pub category: NodeCategory,
    /// Whether this node can contain child nodes.
    pub is_container: bool,
    /// Platforms this type runs on (e.g., `["browser"]`, `["server"]`).
    pub platforms: Vec<String>,
    /// Lucide icon name — consumers resolve to their own icon component.
    pub icon: String,
}

/// Constructs a `NodeTypeInfo` from positional fields. Reduces per-entry
/// boilerplate in `all_node_types()` — keeps the table scannable.
macro_rules! node_type {
    ($name:expr, $label:expr, $desc:expr, $cat:expr, $container:expr, $platform:expr, $icon:expr) => {
        NodeTypeInfo {
            name: $name.to_string(),
            label: $label.to_string(),
            description: $desc.to_string(),
            category: $cat,
            is_container: $container,
            platforms: vec![$platform.to_string()],
            icon: $icon.to_string(),
        }
    };
}

/// Return metadata for all 20 registered node types.
///
/// Single source of truth for the engine's node type registry.
/// Composed from per-category helpers, then sorted alphabetically for stable output.
pub fn all_node_types() -> Vec<NodeTypeInfo> {
    let mut types = Vec::with_capacity(20);
    types.extend(control_node_types());
    types.extend(data_node_types());
    types.extend(file_node_types());
    types.extend(image_node_types());
    types.extend(io_node_types());
    types.extend(network_node_types());
    types.extend(spreadsheet_node_types());
    types.extend(system_node_types());
    types.extend(video_node_types());
    types.sort_by(|a, b| a.name.cmp(&b.name));
    types
}

fn control_node_types() -> Vec<NodeTypeInfo> {
    vec![
        node_type!(
            "group",
            "Group",
            "Container for child nodes. Orchestrates sequential or parallel execution.",
            NodeCategory::Control,
            true,
            "browser",
            "box"
        ),
        node_type!(
            "loop",
            "Loop",
            "Iterate over arrays (forEach), repeat N times, or loop while condition.",
            NodeCategory::Control,
            true,
            "browser",
            "repeat"
        ),
        node_type!(
            "parallel",
            "Parallel",
            "Execute tasks concurrently with configurable worker pool and error strategy.",
            NodeCategory::Control,
            true,
            "browser",
            "git-fork"
        ),
    ]
}

fn data_node_types() -> Vec<NodeTypeInfo> {
    vec![
        node_type!(
            "edit-fields",
            "Edit Fields",
            "Set field values from static values or template expressions.",
            NodeCategory::Data,
            false,
            "browser",
            "pen-line"
        ),
        node_type!(
            "transform",
            "Transform",
            "Transform data using expressions (single value) or field mappings.",
            NodeCategory::Data,
            false,
            "browser",
            "arrow-left-right"
        ),
    ]
}

fn file_node_types() -> Vec<NodeTypeInfo> {
    vec![node_type!(
        "file-rename",
        "Rename Files",
        "Transform filenames using patterns, find/replace, and case rules.",
        NodeCategory::File,
        false,
        "browser",
        "folder-open"
    )]
}

fn image_node_types() -> Vec<NodeTypeInfo> {
    vec![
        node_type!(
            "image-compress",
            "Compress Images",
            "Reduce image file size while maintaining quality.",
            NodeCategory::Image,
            false,
            "browser",
            "image"
        ),
        node_type!(
            "image-convert",
            "Convert Image Format",
            "Convert images between JPEG, PNG, and WebP formats.",
            NodeCategory::Image,
            false,
            "browser",
            "image"
        ),
        node_type!(
            "image-resize",
            "Resize Images",
            "Change image dimensions while maintaining quality.",
            NodeCategory::Image,
            false,
            "browser",
            "image"
        ),
        node_type!(
            "image-strip-exif",
            "Strip EXIF",
            "Remove all EXIF metadata from images (GPS, camera info, timestamps).",
            NodeCategory::Image,
            false,
            "browser",
            "image"
        ),
        node_type!(
            "image-overlay",
            "Overlay Image",
            "Overlay an image onto source images at a configurable position, size, and opacity.",
            NodeCategory::Image,
            false,
            "browser",
            "stamp"
        ),
    ]
}

fn io_node_types() -> Vec<NodeTypeInfo> {
    vec![
        node_type!(
            "input",
            "Input",
            "Declares how data enters the recipe.",
            NodeCategory::Io,
            false,
            "browser",
            "file-up"
        ),
        node_type!(
            "output",
            "Output",
            "Declares how results are delivered.",
            NodeCategory::Io,
            false,
            "browser",
            "download"
        ),
    ]
}

fn network_node_types() -> Vec<NodeTypeInfo> {
    vec![node_type!(
        "http-request",
        "HTTP Request",
        "Make HTTP requests to APIs (GET, POST, PUT, DELETE, etc.).",
        NodeCategory::Network,
        false,
        "server",
        "globe"
    )]
}

fn spreadsheet_node_types() -> Vec<NodeTypeInfo> {
    vec![
        node_type!(
            "spreadsheet-clean",
            "Clean CSV",
            "Remove empty rows, trim whitespace, and deduplicate CSV data.",
            NodeCategory::Spreadsheet,
            false,
            "browser",
            "sheet"
        ),
        node_type!(
            "spreadsheet-convert",
            "CSV to JSON",
            "Convert CSV data to JSON format with configurable delimiters.",
            NodeCategory::Spreadsheet,
            false,
            "browser",
            "sheet"
        ),
        node_type!(
            "spreadsheet-merge",
            "Merge CSV",
            "Combine multiple CSV files into one with header reconciliation and deduplication.",
            NodeCategory::Spreadsheet,
            false,
            "browser",
            "sheet"
        ),
        node_type!(
            "spreadsheet-rename",
            "Rename CSV Columns",
            "Rename column headers in a CSV file.",
            NodeCategory::Spreadsheet,
            false,
            "browser",
            "sheet"
        ),
    ]
}

fn system_node_types() -> Vec<NodeTypeInfo> {
    vec![node_type!(
        "shell-command",
        "Shell Command",
        "Execute shell commands with stall detection, retry, and streaming output.",
        NodeCategory::System,
        false,
        "server",
        "terminal"
    )]
}

fn video_node_types() -> Vec<NodeTypeInfo> {
    vec![node_type!(
        "video-download",
        "Download Video",
        "Download video from URLs using yt-dlp (CLI/desktop only).",
        NodeCategory::Video,
        false,
        "server",
        "video"
    )]
}

// --- Dependency ---

/// An external binary that a processor requires at runtime.
///
/// Pure-Rust processors (image, csv, file) have no dependencies.
/// Processors wrapping CLI tools (yt-dlp, ffmpeg) declare their
/// requirements here. The dependency checker verifies these before
/// pipeline execution; `bnto doctor` reports missing deps with install hints.
#[derive(Debug, Clone, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Dependency {
    /// Binary name to look up on PATH (e.g., `"yt-dlp"`, `"ffmpeg"`).
    pub binary: String,
    /// Semver version constraint (e.g., `">=2023.0.0"`). Empty = any version.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub version: String,
    /// Human-readable install instructions (e.g., `"brew install yt-dlp"`).
    pub install_hint: String,
    /// Homepage URL for the tool.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub homepage: String,
}

// --- NodeMetadata ---

/// Complete self-description of a processor. Return type of
/// `NodeProcessor::metadata()`. The `node_type` is the direct dispatch
/// key (e.g., `"image-compress"`).
#[derive(Debug, Clone, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct NodeMetadata {
    /// Per-operation node type (e.g., `"image-compress"`, `"spreadsheet-clean"`).
    pub node_type: std::string::String,
    /// Human-readable processor name.
    pub name: std::string::String,
    /// Description of what this processor does.
    pub description: std::string::String,
    /// Category for UI grouping/filtering.
    pub category: NodeCategory,
    /// Accepted MIME types. Empty means "any file type".
    pub accepts: Vec<std::string::String>,
    /// Platforms this processor runs on (`"browser"`, `"server"`, `"desktop"`).
    pub platforms: Vec<std::string::String>,
    /// Parameters with types, defaults, and constraints.
    pub parameters: Vec<ParameterDef>,
    /// How this processor expects to receive files: one at a time or as a batch.
    /// Defaults to `PerFile`. Used by the auto-iteration executor.
    #[serde(default)]
    pub input_cardinality: InputCardinality,
    /// External binary dependencies. Empty for browser-only processors.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub requires: Vec<Dependency>,
}

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

    // --- InputCardinality Tests ---

    #[test]
    fn test_input_cardinality_defaults_to_per_file() {
        let cardinality = InputCardinality::default();
        assert_eq!(cardinality, InputCardinality::PerFile);
    }

    #[test]
    fn test_input_cardinality_serializes_camel_case() {
        let per_file = serde_json::to_string(&InputCardinality::PerFile).unwrap();
        assert_eq!(per_file, r#""perFile""#);

        let batch = serde_json::to_string(&InputCardinality::Batch).unwrap();
        assert_eq!(batch, r#""batch""#);

        let source = serde_json::to_string(&InputCardinality::Source).unwrap();
        assert_eq!(source, r#""source""#);
    }

    #[test]
    fn test_metadata_with_input_cardinality_round_trip() {
        let metadata = NodeMetadata {
            node_type: "image-compress".to_string(),
            name: "Compress Images".to_string(),
            description: "Reduce image file size".to_string(),
            category: NodeCategory::Image,
            accepts: vec!["image/jpeg".to_string()],
            platforms: vec!["browser".to_string()],
            parameters: vec![],
            input_cardinality: InputCardinality::PerFile,
            requires: vec![],
        };
        let json = serde_json::to_string(&metadata).unwrap();
        assert!(json.contains(r#""inputCardinality":"perFile""#));

        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed["inputCardinality"], "perFile");
    }

    #[test]
    fn test_metadata_with_batch_cardinality() {
        let metadata = NodeMetadata {
            node_type: "zip-files".to_string(),
            name: "Zip Files".to_string(),
            description: "Bundle files into a zip archive".to_string(),
            category: NodeCategory::File,
            accepts: vec![],
            platforms: vec!["browser".to_string()],
            parameters: vec![],
            input_cardinality: InputCardinality::Batch,
            requires: vec![],
        };
        let json = serde_json::to_string(&metadata).unwrap();
        assert!(json.contains(r#""inputCardinality":"batch""#));
    }

    // --- NodeTypeInfo Tests ---

    #[test]
    fn test_all_node_types_returns_20_entries() {
        // The engine defines all 20 node types.
        let types = all_node_types();
        assert_eq!(types.len(), 20, "Should have exactly 20 node types");
    }

    #[test]
    fn test_all_node_types_sorted_alphabetically() {
        // Entries should be sorted by name for deterministic output.
        let types = all_node_types();
        let names: Vec<&str> = types.iter().map(|t| t.name.as_str()).collect();
        let mut sorted = names.clone();
        sorted.sort();
        assert_eq!(names, sorted, "Node types should be alphabetically sorted");
    }

    #[test]
    fn test_all_node_types_unique_names() {
        // Every node type name should be unique.
        let types = all_node_types();
        let mut names: Vec<&str> = types.iter().map(|t| t.name.as_str()).collect();
        names.sort();
        names.dedup();
        assert_eq!(names.len(), 20, "All node type names should be unique");
    }

    #[test]
    fn test_container_types_are_group_loop_parallel() {
        // Only group, loop, and parallel should be containers.
        let types = all_node_types();
        let mut containers: Vec<&str> = types
            .iter()
            .filter(|t| t.is_container)
            .map(|t| t.name.as_str())
            .collect();
        containers.sort();
        assert_eq!(containers, vec!["group", "loop", "parallel"]);
    }

    #[test]
    fn test_io_types_are_input_output() {
        // Only input and output should have the Io category.
        let types = all_node_types();
        let mut io_types: Vec<&str> = types
            .iter()
            .filter(|t| t.category == NodeCategory::Io)
            .map(|t| t.name.as_str())
            .collect();
        io_types.sort();
        assert_eq!(io_types, vec!["input", "output"]);
    }

    #[test]
    fn test_server_only_types() {
        // http-request and shell-command should only have "server" platform.
        let types = all_node_types();
        let mut server_only: Vec<&str> = types
            .iter()
            .filter(|t| !t.platforms.contains(&"browser".to_string()))
            .map(|t| t.name.as_str())
            .collect();
        server_only.sort();
        assert_eq!(
            server_only,
            vec!["http-request", "shell-command", "video-download"]
        );
    }

    #[test]
    fn test_node_type_info_serializes_camel_case() {
        // NodeTypeInfo should serialize with camelCase keys.
        let info = NodeTypeInfo {
            name: "image".to_string(),
            label: "Image".to_string(),
            description: "Image processing".to_string(),
            category: NodeCategory::Image,
            is_container: false,
            platforms: vec!["browser".to_string()],
            icon: "image".to_string(),
        };
        let json = serde_json::to_string(&info).unwrap();
        // isContainer should be camelCase in JSON
        assert!(json.contains(r#""isContainer":false"#));
        assert!(!json.contains("is_container"));
    }

    // --- Serialization Tests ---
    // These verify that our types serialize to the expected JSON format,
    // with camelCase keys, skip_serializing_if working, etc.

    #[test]
    fn test_category_serializes_to_kebab_case() {
        // NodeCategory variants should serialize as kebab-case strings.
        let json = serde_json::to_string(&NodeCategory::Image).unwrap();
        assert_eq!(json, r#""image""#);

        let json = serde_json::to_string(&NodeCategory::Spreadsheet).unwrap();
        assert_eq!(json, r#""spreadsheet""#);

        let json = serde_json::to_string(&NodeCategory::File).unwrap();
        assert_eq!(json, r#""file""#);

        let json = serde_json::to_string(&NodeCategory::Io).unwrap();
        assert_eq!(json, r#""io""#);

        let json = serde_json::to_string(&NodeCategory::Video).unwrap();
        assert_eq!(json, r#""video""#);
    }

    #[test]
    fn test_parameter_type_number_serialization() {
        // Number type serializes with a "type" tag.
        let json = serde_json::to_string(&ParameterType::Number).unwrap();
        assert_eq!(json, r#"{"type":"number"}"#);
    }

    #[test]
    fn test_parameter_type_enum_serialization() {
        // Enum type includes the options list.
        let param = ParameterType::Enum {
            options: vec!["jpeg".to_string(), "png".to_string(), "webp".to_string()],
        };
        let json = serde_json::to_string(&param).unwrap();
        assert!(json.contains(r#""type":"enum""#));
        assert!(json.contains(r#""options":["jpeg","png","webp"]"#));
    }

    #[test]
    fn test_constraints_skips_none_fields() {
        // Fields that are None should be omitted from the JSON output.
        let constraints = Constraints {
            min: Some(1.0),
            max: None,
            required: false,
        };
        let json = serde_json::to_string(&constraints).unwrap();
        // Should have "min" but NOT "max".
        assert!(json.contains(r#""min":1.0"#));
        assert!(!json.contains("max"));
        assert!(json.contains(r#""required":false"#));
    }

    #[test]
    fn test_constraints_includes_all_fields_when_present() {
        let constraints = Constraints {
            min: Some(1.0),
            max: Some(100.0),
            required: true,
        };
        let json = serde_json::to_string(&constraints).unwrap();
        assert!(json.contains(r#""min":1.0"#));
        assert!(json.contains(r#""max":100.0"#));
        assert!(json.contains(r#""required":true"#));
    }

    #[test]
    fn test_parameter_def_serializes_camel_case() {
        // ParameterDef fields should be camelCase in JSON.
        let param = ParameterDef {
            name: "quality".to_string(),
            label: "Quality".to_string(),
            description: "Compression quality".to_string(),
            param_type: ParameterType::Number,
            default: Some(serde_json::json!(80)),
            constraints: Some(Constraints {
                min: Some(1.0),
                max: Some(100.0),
                required: false,
            }),
            ..Default::default()
        };
        let json = serde_json::to_string(&param).unwrap();
        // Should use "paramType" not "param_type".
        assert!(json.contains(r#""paramType""#));
        assert!(!json.contains("param_type"));
    }

    #[test]
    fn test_parameter_def_skips_none_default() {
        // When default is None, it should be omitted from JSON.
        let param = ParameterDef {
            name: "width".to_string(),
            label: "Width".to_string(),
            description: "Target width".to_string(),
            param_type: ParameterType::Number,
            ..Default::default()
        };
        let json = serde_json::to_string(&param).unwrap();
        assert!(!json.contains("default"));
        assert!(!json.contains("constraints"));
        // UI metadata fields should also be omitted when None.
        assert!(!json.contains("placeholder"));
        assert!(!json.contains("visibleWhen"));
        assert!(!json.contains("requiredWhen"));
    }

    #[test]
    fn test_parameter_def_surfaceable_defaults_to_true() {
        // The `surfaceable` field should default to `true` — most params are
        // user-facing controls that should appear in surfaced container views.
        let param = ParameterDef {
            name: "quality".to_string(),
            label: "Quality".to_string(),
            description: "Compression quality".to_string(),
            param_type: ParameterType::Number,
            ..Default::default()
        };
        // Default::default() should give surfaceable = true.
        assert!(param.surfaceable, "surfaceable should default to true");
        // And it should serialize with the field present.
        let json = serde_json::to_string(&param).unwrap();
        assert!(json.contains(r#""surfaceable":true"#));
    }

    #[test]
    fn test_parameter_def_surfaceable_false_serializes() {
        // Internal wiring params (like loop `items`) should be explicitly
        // marked `surfaceable: false` so the editor doesn't surface them.
        let param = ParameterDef {
            name: "items".to_string(),
            label: "Items".to_string(),
            description: "Template expression for iteration items".to_string(),
            param_type: ParameterType::String,
            surfaceable: false,
            ..Default::default()
        };
        assert!(!param.surfaceable);
        let json = serde_json::to_string(&param).unwrap();
        assert!(json.contains(r#""surfaceable":false"#));
    }

    #[test]
    fn test_node_metadata_serializes_camel_case() {
        // NodeMetadata fields should be camelCase in JSON.
        let metadata = NodeMetadata {
            node_type: "image-compress".to_string(),
            name: "Compress Images".to_string(),
            description: "Reduce image file size".to_string(),
            category: NodeCategory::Image,
            accepts: vec![
                "image/jpeg".to_string(),
                "image/png".to_string(),
                "image/webp".to_string(),
            ],
            platforms: vec!["browser".to_string()],
            parameters: vec![],
            input_cardinality: InputCardinality::PerFile,
            requires: vec![],
        };
        let json = serde_json::to_string(&metadata).unwrap();
        // Should use camelCase field names.
        assert!(json.contains(r#""nodeType":"image-compress""#));
        assert!(json.contains(r#""platforms":["browser"]"#));
        assert!(!json.contains("node_type"));
    }

    #[test]
    fn test_full_metadata_round_trip() {
        // Build a complete NodeMetadata and verify it serializes to valid JSON
        // that can be parsed back.
        let metadata = NodeMetadata {
            node_type: "image-compress".to_string(),
            name: "Compress Images".to_string(),
            description: "Reduce image file size while maintaining quality".to_string(),
            category: NodeCategory::Image,
            accepts: vec![
                "image/jpeg".to_string(),
                "image/png".to_string(),
                "image/webp".to_string(),
            ],
            platforms: vec!["browser".to_string()],
            parameters: vec![ParameterDef {
                name: "quality".to_string(),
                label: "Quality".to_string(),
                description: "Compression quality (1-100)".to_string(),
                param_type: ParameterType::Number,
                default: Some(serde_json::json!(80)),
                constraints: Some(Constraints {
                    min: Some(1.0),
                    max: Some(100.0),
                    required: false,
                }),
                ..Default::default()
            }],
            input_cardinality: InputCardinality::PerFile,
            requires: vec![],
        };

        // Serialize to JSON string.
        let json = serde_json::to_string_pretty(&metadata).unwrap();

        // Parse back to a generic JSON Value (round-trip test).
        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();

        // Verify key fields are present and correct.
        assert_eq!(parsed["nodeType"], "image-compress");
        assert_eq!(parsed["category"], "image");
        assert_eq!(parsed["platforms"][0], "browser");
        assert_eq!(parsed["accepts"].as_array().unwrap().len(), 3);
        assert_eq!(parsed["parameters"].as_array().unwrap().len(), 1);
        assert_eq!(parsed["parameters"][0]["name"], "quality");
        assert_eq!(parsed["parameters"][0]["default"], 80);
    }

    // --- ParamCondition Serialization Tests ---

    #[test]
    fn test_param_condition_single_serializes_as_object() {
        // A Single condition should serialize as a flat JSON object
        // with "param" and "equals" keys (camelCase).
        let condition = ParamCondition::Single(ParamConditionEntry {
            param: "operation".to_string(),
            equals: "resize".to_string(),
        });
        let json = serde_json::to_string(&condition).unwrap();
        // Should be a flat object, not wrapped in a type tag.
        assert_eq!(json, r#"{"param":"operation","equals":"resize"}"#);
    }

    #[test]
    fn test_param_condition_any_serializes_as_array() {
        // An Any condition should serialize as a JSON array of condition objects.
        // This represents OR logic: show when ANY condition matches.
        let condition = ParamCondition::Any(vec![
            ParamConditionEntry {
                param: "operation".to_string(),
                equals: "resize".to_string(),
            },
            ParamConditionEntry {
                param: "operation".to_string(),
                equals: "crop".to_string(),
            },
        ]);
        let json = serde_json::to_string(&condition).unwrap();
        // Should be an array of objects.
        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
        assert!(parsed.is_array(), "Any condition should be a JSON array");
        assert_eq!(parsed.as_array().unwrap().len(), 2);
        assert_eq!(parsed[0]["param"], "operation");
        assert_eq!(parsed[0]["equals"], "resize");
        assert_eq!(parsed[1]["equals"], "crop");
    }

    #[test]
    fn test_parameter_def_with_ui_fields_serializes_camel_case() {
        // When UI metadata fields are set, they should appear in JSON
        // with camelCase keys (visibleWhen, not visible_when).
        let param = ParameterDef {
            name: "width".to_string(),
            label: "Width".to_string(),
            description: "Target width in pixels".to_string(),
            param_type: ParameterType::Number,
            default: None,
            constraints: None,
            placeholder: Some("e.g. 800".to_string()),
            visible_when: Some(ParamCondition::Single(ParamConditionEntry {
                param: "operation".to_string(),
                equals: "resize".to_string(),
            })),
            ..Default::default()
        };
        let json = serde_json::to_string(&param).unwrap();
        // "visibleWhen" should be camelCase (not "visible_when").
        assert!(json.contains(r#""visibleWhen""#));
        assert!(!json.contains("visible_when"));
        // "placeholder" should be present.
        assert!(json.contains(r#""placeholder":"e.g. 800""#));
        // "requiredWhen" should be omitted (it's None).
        assert!(!json.contains("requiredWhen"));
    }

    // --- Dependency Tests ---

    #[test]
    fn test_dependency_serializes_camel_case() {
        let dep = Dependency {
            binary: "yt-dlp".to_string(),
            version: ">=2023.01.01".to_string(),
            install_hint: "brew install yt-dlp".to_string(),
            homepage: "https://github.com/yt-dlp/yt-dlp".to_string(),
        };
        let json = serde_json::to_string(&dep).unwrap();
        assert!(json.contains(r#""binary":"yt-dlp""#));
        assert!(json.contains(r#""version":">=2023.01.01""#));
        assert!(json.contains(r#""installHint":"brew install yt-dlp""#));
        assert!(json.contains(r#""homepage":"https://github.com/yt-dlp/yt-dlp""#));
        // Must NOT contain snake_case keys.
        assert!(!json.contains("install_hint"));
    }

    #[test]
    fn test_dependency_skips_empty_optional_fields() {
        let dep = Dependency {
            binary: "ffmpeg".to_string(),
            version: String::new(),
            install_hint: "brew install ffmpeg".to_string(),
            homepage: String::new(),
        };
        let json = serde_json::to_string(&dep).unwrap();
        assert!(!json.contains("version"), "empty version should be omitted");
        assert!(
            !json.contains("homepage"),
            "empty homepage should be omitted"
        );
        assert!(json.contains(r#""binary":"ffmpeg""#));
        assert!(json.contains(r#""installHint""#));
    }

    #[test]
    fn test_dependency_equality() {
        let a = Dependency {
            binary: "yt-dlp".to_string(),
            version: ">=2023.01.01".to_string(),
            install_hint: "brew install yt-dlp".to_string(),
            homepage: "https://github.com/yt-dlp/yt-dlp".to_string(),
        };
        let b = a.clone();
        assert_eq!(a, b);
    }

    #[test]
    fn test_metadata_requires_empty_skipped_in_serialization() {
        let metadata = NodeMetadata {
            node_type: "image-compress".to_string(),
            name: "Compress".to_string(),
            description: String::new(),
            category: NodeCategory::Image,
            accepts: vec![],
            platforms: vec!["browser".to_string()],
            parameters: vec![],
            input_cardinality: InputCardinality::PerFile,
            requires: vec![],
        };
        let json = serde_json::to_string(&metadata).unwrap();
        assert!(
            !json.contains("requires"),
            "empty requires should be omitted"
        );
    }

    #[test]
    fn test_metadata_requires_present_when_populated() {
        let metadata = NodeMetadata {
            node_type: "video-download".to_string(),
            name: "Download Video".to_string(),
            description: String::new(),
            category: NodeCategory::Network,
            accepts: vec![],
            platforms: vec!["server".to_string()],
            parameters: vec![],
            input_cardinality: InputCardinality::PerFile,
            requires: vec![Dependency {
                binary: "yt-dlp".to_string(),
                version: ">=2023.01.01".to_string(),
                install_hint: "brew install yt-dlp".to_string(),
                homepage: "https://github.com/yt-dlp/yt-dlp".to_string(),
            }],
        };
        let json = serde_json::to_string(&metadata).unwrap();
        assert!(json.contains(r#""requires""#));
        assert!(json.contains(r#""binary":"yt-dlp""#));
        assert!(json.contains(r#""version":">=2023.01.01""#));
    }
}