hypen-engine 0.5.2

A Rust implementation of the Hypen 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
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
/// WASM Integration Tests
///
/// These tests verify the WASM interface works correctly with the engine.
/// While they run natively (not in WASM), they test the same code paths
/// that WASM would use.
use hypen_engine::{
    dispatch::Action,
    ir::{ast_to_ir_node, ComponentRegistry, Element, IRNode, Value},
    lifecycle::{Module, ModuleInstance},
    reactive::{DependencyGraph, Scheduler},
    reconcile::{reconcile_ir, InstanceTree, Patch},
};
use serde_json::json;
use std::collections::HashMap;

/// Mock render callback to capture patches
struct MockRenderer {
    patches: Vec<Patch>,
}

#[allow(dead_code)]
impl MockRenderer {
    fn new() -> Self {
        Self {
            patches: Vec::new(),
        }
    }

    fn capture_patch(&mut self, patch: Patch) {
        self.patches.push(patch);
    }

    fn clear(&mut self) {
        self.patches.clear();
    }

    fn patch_count(&self) -> usize {
        self.patches.len()
    }

    fn has_create_patch(&self, element_type: &str) -> bool {
        self.patches.iter().any(|p| match p {
            Patch::Create {
                element_type: et, ..
            } => et == element_type,
            _ => false,
        })
    }

    fn has_set_prop_patch(&self, prop_name: &str) -> bool {
        self.patches.iter().any(|p| match p {
            Patch::SetProp { name, .. } => name == prop_name,
            _ => false,
        })
    }
}

#[test]
fn test_wasm_render_simple_component() {
    // Simulates: WasmEngine.renderSource("Text('Hello')")
    let source = r#"Text("Hello")"#;
    let component = hypen_parser::parse_component(source).unwrap();
    let ir_node = ast_to_ir_node(&component);
    let element = match &ir_node {
        IRNode::Element(e) => e.clone(),
        _ => panic!("Expected Element"),
    };

    let mut tree = InstanceTree::new();
    let mut dependencies = DependencyGraph::new();
    let mut renderer = MockRenderer::new();

    let state_json = serde_json::to_value(HashMap::<String, serde_json::Value>::new()).unwrap();
    let patches = reconcile_ir(
        &mut tree,
        &IRNode::Element(element.clone()),
        None,
        &state_json,
        &mut dependencies,
    );

    for patch in patches {
        renderer.capture_patch(patch);
    }

    assert!(renderer.has_create_patch("Text"));
    assert!(renderer.patch_count() > 0);
}

#[test]
fn test_wasm_state_update_flow() {
    // Simulates: module with state, then updateState() call
    let source = r#"Text("Count: @{state.count}")"#;
    let component = hypen_parser::parse_component(source).unwrap();
    let ir_node = ast_to_ir_node(&component);
    let element = match &ir_node {
        IRNode::Element(e) => e.clone(),
        _ => panic!("Expected Element"),
    };

    let mut tree = InstanceTree::new();
    let mut dependencies = DependencyGraph::new();
    let initial_state = HashMap::from([("count".to_string(), json!(0))]);

    // Initial render
    let state_json = serde_json::to_value(&initial_state).unwrap();
    let patches = reconcile_ir(
        &mut tree,
        &IRNode::Element(element.clone()),
        None,
        &state_json,
        &mut dependencies,
    );
    assert!(!patches.is_empty());

    // Update state
    let _new_state = HashMap::from([("count".to_string(), json!(1))]);
    let changed_paths = vec!["count".to_string()];

    let mut scheduler = Scheduler::new();
    // Get affected nodes for each changed path
    for path in &changed_paths {
        let affected = dependencies.get_affected_nodes(path);
        for node_id in affected {
            scheduler.mark_dirty(node_id);
        }
    }

    // Reconcile affected nodes
    let dirty_nodes = scheduler.take_dirty();
    assert!(
        !dirty_nodes.is_empty(),
        "Should have dirty nodes after state change"
    );
}

#[test]
fn test_wasm_action_dispatch() {
    // Simulates: dispatchAction("increment", payload)
    let action = Action {
        name: "increment".to_string(),
        payload: Some(json!(1)),
        sender: None,
    };

    // Verify action structure is valid
    assert_eq!(action.name, "increment");
    assert_eq!(action.payload, Some(json!(1)));
    assert!(action.sender.is_none());
}

#[test]
fn test_wasm_component_registry() {
    // Simulates: registerComponent() calls
    use hypen_engine::ir::Component;
    let mut registry = ComponentRegistry::new();

    let component = Component::new("Button", |_props| Element::new("Text"));

    registry.register(component);

    assert!(registry.get("Button", None).is_some());
    assert!(registry.get("NonExistent", None).is_none());
}

#[test]
fn test_wasm_component_resolution() {
    // Simulates: component resolution with context path
    use hypen_engine::ir::Component;
    let mut registry = ComponentRegistry::new();

    let button = Component::new("Button", |_props| Element::new("Text"));

    registry.register(button);

    // Get component
    let resolved = registry.get("Button", None);
    assert!(resolved.is_some());
}

#[test]
fn test_wasm_parse_error_handling() {
    // Simulates: renderSource() with invalid syntax
    let invalid_sources = vec![
        "Text(",           // Incomplete
        "Text('unclosed)", // Unclosed string
        "123Invalid",      // Invalid start
        "",                // Empty
    ];

    for source in invalid_sources {
        let result = hypen_parser::parse_component(source);
        assert!(
            result.is_err(),
            "Should fail to parse invalid source: {}",
            source
        );
    }
}

#[test]
fn test_wasm_nested_component_expansion() {
    // Simulates: Component with nested children
    let source = r#"
        Column {
            Text("Title")
            Text("Subtitle")
        }
    "#;

    let component = hypen_parser::parse_component(source).unwrap();
    let element = match ast_to_ir_node(&component) {
        IRNode::Element(e) => e,
        _ => panic!("Expected Element"),
    };

    assert_eq!(element.element_type, "Column");
    assert_eq!(element.ir_children.len(), 2);
    match &element.ir_children[0] {
        IRNode::Element(e) => assert_eq!(e.element_type, "Text"),
        _ => panic!("Expected Element"),
    };
    match &element.ir_children[1] {
        IRNode::Element(e) => assert_eq!(e.element_type, "Text"),
        _ => panic!("Expected Element"),
    };
}

#[test]
fn test_wasm_state_binding_extraction() {
    // Simulates: State bindings in templates
    let source = r#"Text("User: @{state.user.name}, Age: @{state.user.age}")"#;

    let component = hypen_parser::parse_component(source).unwrap();
    let ir_node = ast_to_ir_node(&component);
    let element = match &ir_node {
        IRNode::Element(e) => e.clone(),
        _ => panic!("Expected Element"),
    };

    let mut tree = InstanceTree::new();
    let mut dependencies = DependencyGraph::new();
    let state = HashMap::from([
        ("user.name".to_string(), json!("Alice")),
        ("user.age".to_string(), json!(30)),
    ]);

    let state_json = serde_json::to_value(&state).unwrap();
    let _ = reconcile_ir(
        &mut tree,
        &IRNode::Element(element.clone()),
        None,
        &state_json,
        &mut dependencies,
    );

    // Verify dependencies were tracked
    let affected = dependencies.get_affected_nodes("user.name");
    assert!(!affected.is_empty(), "Should track user.name dependency");
}

#[test]
fn test_wasm_module_lifecycle() {
    // Simulates: Module registration and lifecycle
    let module = Module {
        name: "TestModule".to_string(),
        actions: vec!["increment".to_string()],
        state_keys: vec!["count".to_string()],
        persist: false,
        version: Some(1),
    };

    let initial_state = json!({ "count": 0 });
    let instance = ModuleInstance::new(module.clone(), initial_state.clone());

    assert_eq!(instance.module.name, "TestModule");
    assert_eq!(instance.get_state(), &initial_state);
}

#[test]
fn test_wasm_state_merging() {
    // Simulates: Deep state merging in modules
    let base_state = json!({
        "user": {
            "name": "Alice",
            "age": 30
        },
        "settings": {
            "theme": "dark"
        }
    });

    let updates = json!({
        "user": {
            "age": 31
        },
        "settings": {
            "notifications": true
        }
    });

    // Test that merge logic preserves nested structure
    // (This would be the actual merge implementation)
    assert!(base_state.is_object());
    assert!(updates.is_object());
}

#[test]
fn test_wasm_reconciliation_keyed_lists() {
    // Simulates: Keyed list reconciliation
    let old_source = r#"
        Column {
            Text(key: "a", "Item A")
            Text(key: "b", "Item B")
            Text(key: "c", "Item C")
        }
    "#;

    let new_source = r#"
        Column {
            Text(key: "b", "Item B")
            Text(key: "a", "Item A")
            Text(key: "d", "Item D")
        }
    "#;

    let old_component = hypen_parser::parse_component(old_source).unwrap();
    let new_component = hypen_parser::parse_component(new_source).unwrap();

    let old_ir_node = ast_to_ir_node(&old_component);
    let new_ir_node = ast_to_ir_node(&new_component);

    let mut tree = InstanceTree::new();
    let mut dependencies = DependencyGraph::new();
    let state: HashMap<String, serde_json::Value> = HashMap::new();

    // Initial render
    let state_json = serde_json::to_value(&state).unwrap();
    let _patches = reconcile_ir(
        &mut tree,
        &old_ir_node,
        None,
        &state_json,
        &mut dependencies,
    );

    // Reconcile with new tree
    let reconcile_patches = reconcile_ir(
        &mut tree,
        &new_ir_node,
        None,
        &state_json,
        &mut dependencies,
    );

    // Should generate patches for the changed children:
    // Old: [a, b, c] -> New: [b, a, d] means moves, removes, and/or creates
    // Or SetProp patches for updated text values
    assert!(
        !reconcile_patches.is_empty(),
        "Should generate patches for keyed list changes: {:?}",
        reconcile_patches
    );
}

#[test]
fn test_wasm_props_with_various_types() {
    // Simulates: Props with different value types
    let source = r#"
        Button(
            text: "Click",
            count: 42,
            enabled: true,
            data: {name: "test", value: 123},
            items: [1, 2, 3]
        )
    "#;

    let component = hypen_parser::parse_component(source).unwrap();
    let element = match ast_to_ir_node(&component) {
        IRNode::Element(e) => e,
        _ => panic!("Expected Element"),
    };

    // Verify all prop types are preserved
    assert!(element.props.contains_key("text"));
    assert!(element.props.contains_key("count"));
    assert!(element.props.contains_key("enabled"));
    assert!(element.props.contains_key("data"));
    assert!(element.props.contains_key("items"));
}

#[test]
fn test_wasm_applicators() {
    // Simulates: Applicators (style modifiers)
    let source = r#"
        Text("Styled")
            .fontSize(18)
            .color(blue)
            .padding(16)
    "#;

    let component = hypen_parser::parse_component(source).unwrap();
    let element = match ast_to_ir_node(&component) {
        IRNode::Element(e) => e,
        _ => panic!("Expected Element"),
    };

    // Applicators become props with format "applicatorName.index"
    assert!(element.props.contains_key("fontSize.0"));
    assert!(element.props.contains_key("color.0"));
    assert!(element.props.contains_key("padding.0"));
}

#[test]
fn test_wasm_action_references() {
    // Simulates: @actions.* references
    let source = r#"Button("@actions.handleClick")"#;

    let component = hypen_parser::parse_component(source).unwrap();
    let element = match ast_to_ir_node(&component) {
        IRNode::Element(e) => e,
        _ => panic!("Expected Element"),
    };

    // Positional action references are stored under the "action" key
    let action_prop = element.props.get("action");
    assert!(
        action_prop.is_some(),
        "Positional @actions.* should become props[\"action\"]"
    );

    match action_prop.unwrap() {
        Value::Action(action) => {
            assert_eq!(action, "handleClick");
        }
        _ => panic!("Expected Action"),
    }
}

#[test]
fn test_wasm_clear_tree() {
    // Simulates: clearTree() - resetting engine state
    let source = r#"Text("Hello")"#;
    let component = hypen_parser::parse_component(source).unwrap();
    let ir_node = ast_to_ir_node(&component);
    let element = match &ir_node {
        IRNode::Element(e) => e.clone(),
        _ => panic!("Expected Element"),
    };

    let mut tree = InstanceTree::new();
    let mut dependencies = DependencyGraph::new();
    let state: HashMap<String, serde_json::Value> = HashMap::new();

    let state_json = serde_json::to_value(&state).unwrap();
    let _ = reconcile_ir(
        &mut tree,
        &IRNode::Element(element.clone()),
        None,
        &state_json,
        &mut dependencies,
    );
    let root_id = tree.root().expect("Should have root");
    tree.set_root(root_id);

    // Verify tree is not empty
    assert!(tree.root().is_some());

    // Clear (simulate)
    tree = InstanceTree::new();
    let _dependencies = DependencyGraph::new();

    // Verify tree is empty
    assert!(tree.root().is_none());
}

#[test]
fn test_wasm_revision_tracking() {
    // Simulates: Revision counter for remote UI
    let mut revision: u64 = 0;

    // Each render increments revision
    revision += 1;
    assert_eq!(revision, 1);

    revision += 1;
    assert_eq!(revision, 2);

    // Verify overflow doesn't panic (will wrap)
    let mut max_revision = u64::MAX;
    max_revision = max_revision.wrapping_add(1);
    assert_eq!(max_revision, 0);
}

#[test]
fn test_wasm_dependency_tracking_complex() {
    // Simulates: Complex nested state dependencies
    let source = r#"
        Column {
            Text("@{state.user.profile.name}")
            Text("@{state.user.profile.email}")
            Text("@{state.settings.theme}")
        }
    "#;

    let component = hypen_parser::parse_component(source).unwrap();
    let ir_node = ast_to_ir_node(&component);

    let mut tree = InstanceTree::new();
    let mut dependencies = DependencyGraph::new();
    let state = HashMap::from([
        ("user.profile.name".to_string(), json!("Alice")),
        ("user.profile.email".to_string(), json!("alice@example.com")),
        ("settings.theme".to_string(), json!("dark")),
    ]);

    let state_json = serde_json::to_value(&state).unwrap();
    let _ = reconcile_ir(&mut tree, &ir_node, None, &state_json, &mut dependencies);

    // Test that changing user.profile affects both name and email nodes
    let affected = dependencies.get_affected_nodes("user.profile");
    assert!(
        affected.len() >= 2,
        "Changing user.profile should affect both name and email"
    );

    // Test that changing settings.theme only affects theme node
    let affected_theme = dependencies.get_affected_nodes("settings.theme");
    assert!(
        !affected_theme.is_empty(),
        "Changing settings.theme should affect theme node"
    );
}

#[test]
fn test_wasm_error_recovery() {
    // Simulates: Engine continues working after errors
    let mut tree = InstanceTree::new();

    // Invalid operation shouldn't crash subsequent valid operations
    let valid_source = r#"Text("Valid")"#;
    let component = hypen_parser::parse_component(valid_source).unwrap();
    let ir_node = ast_to_ir_node(&component);
    let element = match &ir_node {
        IRNode::Element(e) => e.clone(),
        _ => panic!("Expected Element"),
    };

    let mut dependencies = DependencyGraph::new();
    let state: HashMap<String, serde_json::Value> = HashMap::new();

    let state_json = serde_json::to_value(&state).unwrap();
    let patches = reconcile_ir(
        &mut tree,
        &IRNode::Element(element.clone()),
        None,
        &state_json,
        &mut dependencies,
    );
    assert!(!patches.is_empty(), "Should continue working after errors");
}

#[test]
fn test_wasm_large_tree_performance() {
    // Simulates: Rendering large component trees
    let mut source = String::from("Column {\n");
    for i in 0..100 {
        source.push_str(&format!("  Text(\"Item {}\")\n", i));
    }
    source.push('}');

    let component = hypen_parser::parse_component(&source).unwrap();
    let ir_node = ast_to_ir_node(&component);
    let element = match &ir_node {
        IRNode::Element(ref e) => e,
        _ => panic!("Expected Element"),
    };

    assert_eq!(element.element_type, "Column");
    assert_eq!(element.ir_children.len(), 100);

    let mut tree = InstanceTree::new();
    let mut dependencies = DependencyGraph::new();
    let state: HashMap<String, serde_json::Value> = HashMap::new();

    let state_json = serde_json::to_value(&state).unwrap();
    let patches = reconcile_ir(&mut tree, &ir_node, None, &state_json, &mut dependencies);

    // Should generate patches for all elements
    assert!(
        patches.len() > 100,
        "Should create patches for all elements"
    );
}

#[test]
fn test_wasm_concurrent_state_paths() {
    // Simulates: Multiple state paths updating simultaneously
    let changed_paths = vec![
        "user.name".to_string(),
        "user.email".to_string(),
        "settings.theme".to_string(),
        "settings.language".to_string(),
    ];

    let mut dependencies = DependencyGraph::new();

    // Register some fake dependencies using real NodeIds
    use hypen_engine::{ir::Element, reactive::Binding, reconcile::InstanceTree};
    let mut tree = InstanceTree::new();
    let node1 = tree.create_node(&Element::new("Text"), &serde_json::json!({}));
    let node2 = tree.create_node(&Element::new("Text"), &serde_json::json!({}));

    dependencies.add_dependency(
        node1,
        &Binding::state(vec!["user".to_string(), "name".to_string()]),
        None,
    );
    dependencies.add_dependency(
        node2,
        &Binding::state(vec!["settings".to_string(), "theme".to_string()]),
        None,
    );

    let mut affected = indexmap::IndexSet::new();
    for path in &changed_paths {
        affected.extend(dependencies.get_affected_nodes(path));
    }

    assert!(
        affected.contains(&node1),
        "Should track user.name dependency"
    );
    assert!(
        affected.contains(&node2),
        "Should track settings.theme dependency"
    );
}