domainforge-core 0.23.0

Rust core library implementing the SEA DSL primitives and validation engine.
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
#[cfg(feature = "wasm")]
mod wasm_tests {
    use domainforge_core::wasm::{Entity, Flow, Graph, Instance, Resource};
    use wasm_bindgen_test::wasm_bindgen_test;

    #[wasm_bindgen_test]
    fn test_entity_creation() {
        let entity = Entity::new("Warehouse".to_string(), Some("logistics".to_string()));
        assert_eq!(entity.name(), "Warehouse");
        assert_eq!(entity.namespace(), Some("logistics".to_string()));
        assert!(!entity.id().is_empty());
    }

    #[wasm_bindgen_test]
    fn test_entity_without_namespace() {
        let entity = Entity::new("Factory".to_string(), None);
        assert_eq!(entity.name(), "Factory");
        assert_eq!(entity.namespace(), None);
    }

    #[wasm_bindgen_test]
    fn test_entity_attributes() {
        let mut entity = Entity::new("Store".to_string(), None);
        let value = serde_wasm_bindgen::to_value(&serde_json::json!({"location": "NYC"})).unwrap();
        entity.set_attribute("metadata".to_string(), value).unwrap();

        let retrieved = entity.get_attribute("metadata".to_string());
        assert!(!retrieved.is_null());
    }

    #[wasm_bindgen_test]
    fn test_resource_creation() {
        let resource = Resource::new("Cameras".to_string(), "units".to_string(), None);
        assert_eq!(resource.name(), "Cameras");
        assert_eq!(resource.unit(), "units");
        assert!(!resource.id().is_empty());
    }

    #[wasm_bindgen_test]
    fn test_resource_with_namespace() {
        let resource = Resource::new(
            "Steel".to_string(),
            "kg".to_string(),
            Some("materials".to_string()),
        );
        assert_eq!(resource.name(), "Steel");
        assert_eq!(resource.unit(), "kg");
        assert_eq!(resource.namespace(), Some("materials".to_string()));
    }

    #[wasm_bindgen_test]
    fn test_flow_creation() {
        let entity1 = Entity::new("Source".to_string(), None);
        let entity2 = Entity::new("Dest".to_string(), None);
        let resource = Resource::new("Product".to_string(), "units".to_string(), None);

        let flow = Flow::new(
            resource.id(),
            entity1.id(),
            entity2.id(),
            "100".to_string(),
            None,
        );

        assert!(flow.is_ok());
        let flow = flow.unwrap();
        assert_eq!(flow.quantity(), "100");
        assert!(!flow.id().is_empty());
    }

    #[wasm_bindgen_test]
    fn test_instance_creation() {
        let instance = Instance::new("warehouse_1".to_string(), "Warehouse".to_string(), None);

        assert!(!instance.id().is_empty());
        assert_eq!(instance.name(), "warehouse_1");
        assert_eq!(instance.entity_type(), "Warehouse");
    }

    #[wasm_bindgen_test]
    fn test_graph_creation() {
        let graph = Graph::new();
        assert!(graph.is_empty());
        assert_eq!(graph.entity_count(), 0);
        assert_eq!(graph.resource_count(), 0);
        assert_eq!(graph.flow_count(), 0);
    }

    #[wasm_bindgen_test]
    fn test_graph_add_entity() {
        let mut graph = Graph::new();
        let entity = Entity::new("Factory".to_string(), None);

        let result = graph.add_entity(&entity);
        assert!(result.is_ok());
        assert_eq!(graph.entity_count(), 1);
        assert!(!graph.is_empty());
    }

    #[wasm_bindgen_test]
    fn test_graph_get_entity() {
        let mut graph = Graph::new();
        let entity = Entity::new("Office".to_string(), None);
        let id = entity.id();

        graph.add_entity(&entity).unwrap();
        let retrieved = graph.get_entity(id).unwrap();

        assert!(retrieved.is_some());
        let retrieved = retrieved.unwrap();
        assert_eq!(retrieved.name(), "Office");
    }

    #[wasm_bindgen_test]
    fn test_graph_find_entity_by_name() {
        let mut graph = Graph::new();
        let entity = Entity::new("Distribution Center".to_string(), None);

        graph.add_entity(&entity).unwrap();
        let found_id = graph.find_entity_by_name("Distribution Center".to_string());

        assert!(found_id.is_some());
    }

    #[wasm_bindgen_test]
    fn test_graph_add_resource() {
        let mut graph = Graph::new();
        let resource = Resource::new("Materials".to_string(), "kg".to_string(), None);

        let result = graph.add_resource(&resource);
        assert!(result.is_ok());
        assert_eq!(graph.resource_count(), 1);
    }

    #[wasm_bindgen_test]
    fn test_graph_add_flow_with_validation() {
        let mut graph = Graph::new();
        let entity1 = Entity::new("Source".to_string(), None);
        let entity2 = Entity::new("Target".to_string(), None);
        let resource = Resource::new("Goods".to_string(), "units".to_string(), None);

        graph.add_entity(&entity1).unwrap();
        graph.add_entity(&entity2).unwrap();
        graph.add_resource(&resource).unwrap();

        let flow = Flow::new(
            resource.id(),
            entity1.id(),
            entity2.id(),
            "50".to_string(),
            None,
        )
        .unwrap();

        let result = graph.add_flow(&flow);
        assert!(result.is_ok());
        assert_eq!(graph.flow_count(), 1);
    }

    #[wasm_bindgen_test]
    fn test_graph_flows_from() {
        let mut graph = Graph::new();
        let entity1 = Entity::new("Warehouse".to_string(), None);
        let entity2 = Entity::new("Store".to_string(), None);
        let resource = Resource::new("Items".to_string(), "units".to_string(), None);

        graph.add_entity(&entity1).unwrap();
        graph.add_entity(&entity2).unwrap();
        graph.add_resource(&resource).unwrap();

        let flow = Flow::new(
            resource.id(),
            entity1.id(),
            entity2.id(),
            "100".to_string(),
            None,
        )
        .unwrap();
        graph.add_flow(&flow).unwrap();

        let flows = graph.flows_from(entity1.id());
        assert!(flows.is_ok());
    }

    #[wasm_bindgen_test]
    fn test_graph_parse_simple() {
        let source = r#"
Entity "Warehouse" in logistics
Resource "Cameras" units
"#;

        let result = Graph::parse(source.to_string());
        assert!(result.is_ok());

        let graph = result.unwrap();
        assert_eq!(graph.entity_count(), 1);
        assert_eq!(graph.resource_count(), 1);
    }

    #[wasm_bindgen_test]
    fn test_graph_parse_with_flow() {
        let source = r#"
Entity "Warehouse" in logistics
Entity "Factory" in manufacturing
Resource "Materials" kg
Flow "Materials" from "Warehouse" to "Factory" quantity 500
"#;

        let result = Graph::parse(source.to_string());
        assert!(result.is_ok());

        let graph = result.unwrap();
        assert_eq!(graph.entity_count(), 2);
        assert_eq!(graph.resource_count(), 1);
        assert_eq!(graph.flow_count(), 1);
    }

    #[wasm_bindgen_test]
    fn test_graph_serialization() {
        let mut graph = Graph::new();
        let entity = Entity::new("TestEntity".to_string(), None);
        graph.add_entity(&entity).unwrap();

        let json_result = graph.to_json();
        assert!(json_result.is_ok());
    }

    #[wasm_bindgen_test]
    fn test_graph_exposes_parsed_declarations_in_source_order() {
        let source = r#"
@namespace "accessors"
Dimension "Length"
Unit "m" of "Length" factor 1 base "m"
Entity "Warehouse"
Pattern "WarehouseCode" matches "^[A-Z]+$"
ConceptChange "warehouse_v2" @from_version v1.0.0 @to_version v2.0.0 @migration_policy mandatory @breaking_change true
instance warehouse_1 of "Warehouse" { code: "WH" }
Policy stock_positive per Constraint Obligation priority 3 as: 1 > 0
Metric "stock_count" as: 1 @unit "items"
Mapping "warehouse_calm" for calm { Entity "Warehouse" -> component { name: "warehouse" } }
Projection "warehouse_kg" for kg { Entity "Warehouse" { label: "Warehouse" } }
"#;

        fn names(value: wasm_bindgen::JsValue) -> Vec<String> {
            let json: serde_json::Value =
                serde_wasm_bindgen::from_value(value).expect("accessor output is JSON");
            json.as_array()
                .expect("accessor output is an array")
                .iter()
                .map(|item| {
                    item["name"]
                        .as_str()
                        .expect("declaration has a name")
                        .to_string()
                })
                .collect()
        }

        let graph = Graph::parse(source.to_string()).unwrap();
        assert_eq!(names(graph.all_policies().unwrap()), vec!["stock_positive"]);
        assert_eq!(names(graph.all_metrics().unwrap()), vec!["stock_count"]);
        assert_eq!(names(graph.all_mappings().unwrap()), vec!["warehouse_calm"]);
        assert_eq!(
            names(graph.all_projections().unwrap()),
            vec!["warehouse_kg"]
        );
        assert_eq!(names(graph.all_dimensions().unwrap()), vec!["Length"]);
        assert_eq!(names(graph.all_units().unwrap()), vec!["m"]);
        assert_eq!(names(graph.all_patterns().unwrap()), vec!["WarehouseCode"]);
        assert_eq!(
            names(graph.all_concept_changes().unwrap()),
            vec!["warehouse_v2"]
        );
        assert_eq!(
            names(graph.all_entity_instances().unwrap()),
            vec!["warehouse_1"]
        );

        // Two parses of the same source must give identical output.
        let again = Graph::parse(source.to_string()).unwrap();
        let snapshot = |graph: &Graph| -> String {
            serde_json::json!({
                "policies": names(graph.all_policies().unwrap()),
                "metrics": names(graph.all_metrics().unwrap()),
                "mappings": names(graph.all_mappings().unwrap()),
                "projections": names(graph.all_projections().unwrap()),
                "dimensions": names(graph.all_dimensions().unwrap()),
                "units": names(graph.all_units().unwrap()),
                "patterns": names(graph.all_patterns().unwrap()),
                "concept_changes": names(graph.all_concept_changes().unwrap()),
                "entity_instances": names(graph.all_entity_instances().unwrap()),
            })
            .to_string()
        };
        assert_eq!(snapshot(&graph), snapshot(&again));
    }
}

#[cfg(feature = "wasm")]
mod application_contract_wasm_tests {
    use domainforge_core::wasm::Graph;
    use wasm_bindgen_test::wasm_bindgen_test;

    fn flagship_sources_json() -> String {
        serde_json::json!({
            "flagship/command-write.sea": include_str!(
                "../../fixtures/application_generation/flagship/command-write.sea"),
            "flagship/query-read.sea": include_str!(
                "../../fixtures/application_generation/flagship/query-read.sea"),
        })
        .to_string()
    }

    #[wasm_bindgen_test]
    fn resolve_application_contract_json_is_canonical() {
        let sources = flagship_sources_json();
        let raw = Graph::resolve_application_contract_json(
            "flagship/query-read.sea".into(),
            sources.clone(),
        )
        .unwrap();
        let again =
            Graph::resolve_application_contract_json("flagship/query-read.sea".into(), sources)
                .unwrap();
        assert_eq!(raw, again);
        let doc: serde_json::Value = serde_json::from_str(&raw).unwrap();
        assert_eq!(doc["schema_version"], "domainforge-application-contract/v1");
    }

    #[wasm_bindgen_test]
    fn resolve_application_contract_json_rejects_bad_source_map() {
        let err =
            Graph::resolve_application_contract_json("a.sea".into(), "[]".into()).unwrap_err();
        let message = err.as_string().unwrap_or_default();
        assert!(message.contains("APP"));
    }

    #[wasm_bindgen_test]
    fn graph_exposes_typed_entity_contract_json() {
        let graph = Graph::parse(
            "@namespace \"binding\"\nentity \"Item\" { key item_id: string value: int }".into(),
        )
        .unwrap();
        let entity_id = graph.find_entity_by_name("Item".into()).unwrap();
        let raw = graph.entity_contract_json(entity_id).unwrap().unwrap();
        let contract: serde_json::Value = serde_json::from_str(&raw).unwrap();
        assert_eq!(contract["key_field"], "item_id");
        assert_eq!(contract["fields"].as_array().unwrap().len(), 2);
    }

    /// Cross-binding byte parity (M0 gate finding 2): WASM must hash to the
    /// same golden as Rust, Python, and TypeScript. See
    /// `application_cross_binding_golden_tests.rs` for the canonical
    /// constants. The golden pins the full bytes at the current release
    /// version and must be regenerated with every version bump; the stamp
    /// itself is asserted against the running crate version.
    #[wasm_bindgen_test]
    fn cross_binding_golden_hashes() {
        use sha2::{Digest, Sha256};
        const CONTRACT_GOLDEN_SHA256: &str =
            "sha256:6875648973c33641b01ea9869aa14a1981d31cec29ce7c160d48712a8e9ad89c";
        let raw = Graph::resolve_application_contract_json(
            "flagship/query-read.sea".into(),
            flagship_sources_json(),
        )
        .unwrap();
        let doc: serde_json::Value = serde_json::from_str(&raw).expect("canonical document parses");
        assert_eq!(
            doc["producer"]["version"].as_str(),
            Some(env!("CARGO_PKG_VERSION")),
            "producer.version must stamp the running crate version"
        );
        let mut hasher = Sha256::new();
        hasher.update(raw.as_bytes());
        let digest = hasher.finalize();
        let hex: String = {
            let mut s = String::with_capacity(digest.len() * 2);
            for b in digest {
                s.push_str(&format!("{b:02x}"));
            }
            s
        };
        assert_eq!(
            format!("sha256:{hex}"),
            CONTRACT_GOLDEN_SHA256,
            "WASM binding bytes drifted from the Rust golden"
        );
    }

    #[wasm_bindgen_test]
    fn test_world_ref_binding_round_trip_and_tamper_detection() {
        let sources = serde_json::json!({
            "main.sea": "@namespace \"t\"\nentity \"Tank\" { key id: uuid }\n"
        })
        .to_string();
        let identity = Graph::domain_model_identity_json("main.sea".to_string(), sources, None)
            .expect("identity resolves");
        let world = Graph::world_ref_from_identity_json("t".to_string(), identity.clone())
            .expect("world_ref mints");
        assert!(world.starts_with("world:t@sha256:"));
        assert_eq!(Graph::parse_world_ref(world.clone()).unwrap(), world);
        Graph::verify_world_ref(world.clone(), identity.clone()).expect("verifies");

        let mut forged: serde_json::Value = serde_json::from_str(&identity).unwrap();
        forged["semantic_closure_hash"] = serde_json::json!(format!("sha256:{}", "0".repeat(64)));
        assert!(Graph::verify_world_ref(world, forged.to_string()).is_err());
        assert!(Graph::parse_world_ref("world:corp".to_string()).is_err());
    }
}