bnto-core 0.1.3

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
// Document-shape types for `.bnto.json` files -- the authoring view.
//
// These mirror the TypeScript `Definition` types in
// `packages/@bnto/nodes/src/definition.ts`. They represent the full document
// users author and the editor displays: position, metadata, ports, edges.
//
// The execution-pruned view (what the pipeline executor receives) lives in
// `pipeline.rs` (`PipelineDefinition` / `PipelineNode`). That view strips
// presentation fields and flattens `nodes` -> `children` for runtime walks.
//
// JSON conventions preserved from the TS source of truth:
// - camelCase keys
// - Optional fields omitted when `None` (never emitted as `null`)
// - Empty port arrays emitted (not omitted) so the shape is regular
// - `nodes` and `edges` omitted on leaves, present on containers

use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
#[cfg(feature = "ts")]
use ts_rs::TS;

use crate::pipeline::PipelineSettings;

// --- ts-rs export path ---
//
// The `ts` feature emits TypeScript interfaces into
// `packages/@bnto/nodes/src/generated/definitionTypes/<StructName>.ts`.
// Paths are relative to `bnto-core/`'s CARGO_MANIFEST_DIR.
// Run: `cargo test -p bnto-core --features ts export_bindings_`

/// Full document shape for a node in a `.bnto.json` file.
///
/// This is the authoring view -- richer than `PipelineNode` (which is the
/// execution-pruned view). The `settings` field is only meaningful at the
/// root of a recipe document; nested nodes typically omit it.
#[cfg_attr(feature = "ts", derive(TS))]
#[cfg_attr(
    feature = "ts",
    ts(
        export,
        export_to = "../../../../packages/@bnto/nodes/src/generated/definitionTypes/"
    )
)]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Definition {
    pub id: String,
    #[serde(rename = "type")]
    #[cfg_attr(feature = "ts", ts(rename = "type"))]
    pub node_type: String,
    pub version: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "ts", ts(optional))]
    pub parent_id: Option<String>,
    pub name: String,
    pub position: Position,
    pub metadata: Metadata,
    #[serde(default = "default_parameters")]
    #[cfg_attr(feature = "ts", ts(type = "Record<string, unknown>"))]
    pub parameters: serde_json::Value,
    pub input_ports: Vec<Port>,
    pub output_ports: Vec<Port>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "ts", ts(optional))]
    pub nodes: Option<Vec<Definition>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "ts", ts(optional))]
    pub edges: Option<Vec<Edge>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "ts", ts(optional))]
    pub settings: Option<PipelineSettings>,
    /// Recipe-level dependencies — external tools needed at runtime.
    /// Only meaningful at the root of a recipe document; nested nodes omit it.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub requires: Vec<crate::Dependency>,
    /// User-facing field declarations for recipe-level controls.
    /// When present, the TUI/editor renders these instead of raw processor params.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub fields: BTreeMap<String, crate::FieldDef>,
}

/// 2D coordinate for a node on the editor canvas.
#[cfg_attr(feature = "ts", derive(TS))]
#[cfg_attr(
    feature = "ts",
    ts(
        export,
        export_to = "../../../../packages/@bnto/nodes/src/generated/definitionTypes/"
    )
)]
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
pub struct Position {
    pub x: f64,
    pub y: f64,
}

/// Authoring metadata attached to every node (description, timestamps, tags).
/// All fields are optional; an empty `Metadata` serializes to `{}`.
#[cfg_attr(feature = "ts", derive(TS))]
#[cfg_attr(
    feature = "ts",
    ts(
        export,
        export_to = "../../../../packages/@bnto/nodes/src/generated/definitionTypes/"
    )
)]
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Metadata {
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "ts", ts(optional))]
    pub description: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "ts", ts(optional))]
    pub created_at: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "ts", ts(optional))]
    pub updated_at: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "ts", ts(optional))]
    pub category: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "ts", ts(optional))]
    pub tags: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "ts", ts(optional, type = "Record<string, string>"))]
    pub custom_data: Option<BTreeMap<String, String>>,
}

/// An input or output port on a node. `handle` is used when a node exposes
/// multiple logical slots (e.g. an `if` node with `then` / `else` outputs).
#[cfg_attr(feature = "ts", derive(TS))]
#[cfg_attr(
    feature = "ts",
    ts(
        export,
        export_to = "../../../../packages/@bnto/nodes/src/generated/definitionTypes/"
    )
)]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Port {
    pub id: String,
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "ts", ts(optional))]
    pub handle: Option<String>,
}

/// A directed connection between two nodes in a container.
/// `source_handle` / `target_handle` disambiguate when ports have handles.
#[cfg_attr(feature = "ts", derive(TS))]
#[cfg_attr(
    feature = "ts",
    ts(
        export,
        export_to = "../../../../packages/@bnto/nodes/src/generated/definitionTypes/"
    )
)]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Edge {
    pub id: String,
    pub source: String,
    pub target: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "ts", ts(optional))]
    pub source_handle: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "ts", ts(optional))]
    pub target_handle: Option<String>,
}

/// Default for `parameters` when the key is missing entirely. Produces `{}`,
/// matching the TS convention that parameters is always an object.
pub(crate) fn default_parameters() -> serde_json::Value {
    serde_json::Value::Object(serde_json::Map::new())
}

// =============================================================================
// Tests
// =============================================================================

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

    fn minimal_leaf(id: &str, node_type: &str) -> Definition {
        Definition {
            id: id.to_string(),
            node_type: node_type.to_string(),
            version: "1.0.0".to_string(),
            parent_id: None,
            name: "Test".to_string(),
            position: Position { x: 0.0, y: 0.0 },
            metadata: Metadata::default(),
            parameters: default_parameters(),
            input_ports: vec![],
            output_ports: vec![],
            nodes: None,
            edges: None,
            settings: None,
            requires: Vec::new(),
            fields: BTreeMap::new(),
        }
    }

    // --- Shape tests: verify JSON key casing and None omission ---

    #[test]
    fn serializes_keys_in_camel_case() {
        let def = Definition {
            parent_id: Some("parent".to_string()),
            ..minimal_leaf("n1", "image-compress")
        };
        let json = serde_json::to_value(&def).unwrap();
        assert!(json.get("parentId").is_some(), "parent_id -> parentId");
        assert!(
            json.get("inputPorts").is_some(),
            "input_ports -> inputPorts"
        );
        assert!(
            json.get("outputPorts").is_some(),
            "output_ports -> outputPorts"
        );
        assert!(json.get("type").is_some(), "node_type -> type");
    }

    #[test]
    fn omits_none_fields_on_serialization() {
        let def = minimal_leaf("n1", "image-compress");
        let json = serde_json::to_value(&def).unwrap();
        assert!(json.get("parentId").is_none());
        assert!(json.get("nodes").is_none());
        assert!(json.get("edges").is_none());
        assert!(json.get("settings").is_none());
    }

    #[test]
    fn emits_empty_port_arrays_rather_than_omitting() {
        let def = minimal_leaf("n1", "image-compress");
        let json = serde_json::to_value(&def).unwrap();
        assert_eq!(json["inputPorts"], json!([]));
        assert_eq!(json["outputPorts"], json!([]));
    }

    #[test]
    fn empty_metadata_serializes_to_empty_object() {
        let meta = Metadata::default();
        let json = serde_json::to_value(&meta).unwrap();
        assert_eq!(json, json!({}));
    }

    #[test]
    fn metadata_omits_none_fields() {
        let meta = Metadata {
            description: Some("hello".to_string()),
            ..Default::default()
        };
        let json = serde_json::to_value(&meta).unwrap();
        assert_eq!(json, json!({ "description": "hello" }));
    }

    #[test]
    fn metadata_custom_data_serializes_as_nested_object() {
        let mut custom = BTreeMap::new();
        custom.insert("author".to_string(), "ryan".to_string());
        let meta = Metadata {
            custom_data: Some(custom),
            ..Default::default()
        };
        let json = serde_json::to_value(&meta).unwrap();
        assert_eq!(json, json!({ "customData": { "author": "ryan" } }));
    }

    #[test]
    fn position_round_trips() {
        let pos = Position { x: 12.5, y: -4.0 };
        let json = serde_json::to_string(&pos).unwrap();
        let back: Position = serde_json::from_str(&json).unwrap();
        assert_eq!(pos, back);
    }

    #[test]
    fn edge_with_handles_uses_camel_case() {
        let edge = Edge {
            id: "e1".to_string(),
            source: "a".to_string(),
            target: "b".to_string(),
            source_handle: Some("out".to_string()),
            target_handle: Some("in".to_string()),
        };
        let json = serde_json::to_value(&edge).unwrap();
        assert_eq!(
            json,
            json!({
                "id": "e1",
                "source": "a",
                "target": "b",
                "sourceHandle": "out",
                "targetHandle": "in",
            })
        );
    }

    #[test]
    fn edge_without_handles_omits_them() {
        let edge = Edge {
            id: "e1".to_string(),
            source: "a".to_string(),
            target: "b".to_string(),
            source_handle: None,
            target_handle: None,
        };
        let json = serde_json::to_value(&edge).unwrap();
        assert!(json.get("sourceHandle").is_none());
        assert!(json.get("targetHandle").is_none());
    }

    #[test]
    fn port_with_handle_round_trips() {
        let port = Port {
            id: "p1".to_string(),
            name: "data".to_string(),
            handle: Some("then".to_string()),
        };
        let json = serde_json::to_string(&port).unwrap();
        let back: Port = serde_json::from_str(&json).unwrap();
        assert_eq!(port, back);
    }

    // --- Round-trip tests against real fixtures ---

    #[test]
    fn deserializes_real_compress_images_recipe() {
        let raw = include_str!("../../bnto/tests/fixtures/explicit/compress-images.bnto.json");
        let def: Definition = serde_json::from_str(raw).expect("deserialization");

        assert_eq!(def.id, "compress-images");
        assert_eq!(def.node_type, "group");
        assert_eq!(def.name, "Compress Images");
        assert_eq!(
            def.metadata.description.as_deref(),
            Some("Accepts image files and compresses each one.")
        );

        let children = def.nodes.as_ref().expect("group has nodes");
        assert_eq!(children.len(), 3);

        let edges = def.edges.as_ref().expect("group has edges");
        assert_eq!(edges.len(), 2);
        assert_eq!(edges[0].source, "input");
        assert_eq!(edges[0].target, "compress-loop");
    }

    #[test]
    fn round_trip_preserves_shape_for_all_recipe_fixtures() {
        // Explicit-mode recipes exercise containers, I/O nodes, nested loops.
        // We verify the Rust representation is stable across serialize ->
        // deserialize, not that the emitted JSON is byte-identical to the
        // source. Fixtures store coordinates as JSON integers (e.g. `"x": 0`);
        // Position is `f64`, so re-serialization emits `0.0`. That's an
        // encoding artifact -- the Definition value itself is lossless.
        let fixtures = [
            include_str!("../../bnto/tests/fixtures/explicit/compress-images.bnto.json"),
            include_str!("../../bnto/tests/fixtures/explicit/optimize-images-for-web.bnto.json"),
            include_str!("../../bnto/tests/fixtures/explicit/merge-csv.bnto.json"),
            include_str!("../../bnto/tests/fixtures/explicit/rename-csv-columns.bnto.json"),
            include_str!("../../bnto/tests/fixtures/explicit/rename-files.bnto.json"),
            include_str!("../../bnto/tests/fixtures/explicit/strip-exif.bnto.json"),
            include_str!("../../bnto/tests/fixtures/explicit/svg-to-png.bnto.json"),
            include_str!("../../bnto/tests/fixtures/explicit/watermark-images.bnto.json"),
        ];

        for (i, raw) in fixtures.iter().enumerate() {
            let first: Definition =
                serde_json::from_str(raw).expect("fixture parses into Definition");
            let reemitted = serde_json::to_string(&first).expect("serializes back");
            let second: Definition =
                serde_json::from_str(&reemitted).expect("re-emitted JSON parses");
            assert_eq!(first, second, "fixture {} lost data through round-trip", i);
        }
    }

    #[test]
    fn container_node_preserves_nested_children() {
        let child = minimal_leaf("child", "image-compress");
        let container = Definition {
            nodes: Some(vec![child.clone()]),
            edges: Some(vec![]),
            ..minimal_leaf("parent", "loop")
        };

        let json = serde_json::to_string(&container).unwrap();
        let back: Definition = serde_json::from_str(&json).unwrap();
        assert_eq!(back.nodes.as_ref().unwrap().len(), 1);
        assert_eq!(back.nodes.as_ref().unwrap()[0], child);
        assert_eq!(back.edges.as_ref().unwrap().len(), 0);
    }

    #[test]
    fn missing_parameters_defaults_to_empty_object() {
        // `parameters` is required in TS but this guards against recipes
        // authored by older tooling that may omit it entirely.
        let raw = r#"{
            "id": "n1",
            "type": "image-compress",
            "version": "1.0.0",
            "name": "Test",
            "position": { "x": 0, "y": 0 },
            "metadata": {},
            "inputPorts": [],
            "outputPorts": []
        }"#;
        let def: Definition = serde_json::from_str(raw).expect("accepts missing parameters");
        assert_eq!(def.parameters, json!({}));
    }
}