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
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
//! Integration tests for import resolution across engine bindings.
//!
//! These tests verify:
//! - WASI import buffer serialization/deserialization
//! - Component registry integration with imports
//! - Recursive import support (imports that reference other imports)
//! - Circular import detection
//! - Engine rendering with pre-registered imported components

mod common;

use common::*;
use hypen_engine::ir::{ast_to_ir_node, Component, Element};
use hypen_engine::lifecycle::{Module, ModuleInstance};
use hypen_engine::reconcile::Patch;
use hypen_engine::Engine;
use hypen_parser::{parse_document, ImportClause, ImportSource, ImportStatement};
use serde_json::json;
use std::sync::{Arc, Mutex};

// ============================================================================
// A. WASI Import Buffer Serialization (4 tests)
// ============================================================================

#[test]
fn test_import_buffer_serialization_single_local() {
    // GIVEN: A single local import
    let imports = [ImportStatement::new(
        ImportClause::Named(vec!["Button".to_string(), "Card".to_string()]),
        ImportSource::Local("./components/ui".to_string()),
    )];

    // WHEN: Serialize to the WASI buffer format (same as store_pending_imports)
    let import_infos: Vec<serde_json::Value> = imports
        .iter()
        .map(|imp| {
            let (source_path, source_type) = match &imp.source {
                ImportSource::Local(p) => (p.as_str(), "local"),
                ImportSource::Url(u) => (u.as_str(), "url"),
            };
            json!({
                "names": imp.imported_names(),
                "source_path": source_path,
                "source_type": source_type,
            })
        })
        .collect();

    let json_bytes = serde_json::to_vec(&import_infos).unwrap();
    let json_str = String::from_utf8(json_bytes).unwrap();

    // THEN: JSON contains the correct structure
    let parsed: Vec<serde_json::Value> = serde_json::from_str(&json_str).unwrap();
    assert_eq!(parsed.len(), 1);
    assert_eq!(parsed[0]["names"], json!(["Button", "Card"]));
    assert_eq!(parsed[0]["source_path"], json!("./components/ui"));
    assert_eq!(parsed[0]["source_type"], json!("local"));
}

#[test]
fn test_import_buffer_serialization_url() {
    // GIVEN: A URL import
    let imports = [ImportStatement::new(
        ImportClause::Default("Widget".to_string()),
        ImportSource::Url("https://cdn.example.com/widgets".to_string()),
    )];

    // WHEN: Serialize
    let import_infos: Vec<serde_json::Value> = imports
        .iter()
        .map(|imp| {
            let (source_path, source_type) = match &imp.source {
                ImportSource::Local(p) => (p.as_str(), "local"),
                ImportSource::Url(u) => (u.as_str(), "url"),
            };
            json!({
                "names": imp.imported_names(),
                "source_path": source_path,
                "source_type": source_type,
            })
        })
        .collect();

    let json_str = serde_json::to_string(&import_infos).unwrap();
    let parsed: Vec<serde_json::Value> = serde_json::from_str(&json_str).unwrap();

    // THEN: URL import is correctly serialized
    assert_eq!(parsed[0]["names"], json!(["Widget"]));
    assert_eq!(
        parsed[0]["source_path"],
        json!("https://cdn.example.com/widgets")
    );
    assert_eq!(parsed[0]["source_type"], json!("url"));
}

#[test]
fn test_import_buffer_serialization_multiple_mixed() {
    // GIVEN: Multiple imports of different types
    let imports = [
        ImportStatement::new(
            ImportClause::Named(vec!["Button".to_string()]),
            ImportSource::Local("./ui".to_string()),
        ),
        ImportStatement::new(
            ImportClause::Default("Dashboard".to_string()),
            ImportSource::Url("https://cdn.example.com/dashboard".to_string()),
        ),
        ImportStatement::new(
            ImportClause::Named(vec!["A".to_string(), "B".to_string(), "C".to_string()]),
            ImportSource::Local("../shared/components".to_string()),
        ),
    ];

    // WHEN: Serialize
    let import_infos: Vec<serde_json::Value> = imports
        .iter()
        .map(|imp| {
            let (source_path, source_type) = match &imp.source {
                ImportSource::Local(p) => (p.as_str(), "local"),
                ImportSource::Url(u) => (u.as_str(), "url"),
            };
            json!({
                "names": imp.imported_names(),
                "source_path": source_path,
                "source_type": source_type,
            })
        })
        .collect();

    let json_str = serde_json::to_string(&import_infos).unwrap();
    let parsed: Vec<serde_json::Value> = serde_json::from_str(&json_str).unwrap();

    // THEN: All three imports are serialized correctly
    assert_eq!(parsed.len(), 3);
    assert_eq!(parsed[0]["source_type"], json!("local"));
    assert_eq!(parsed[1]["source_type"], json!("url"));
    assert_eq!(parsed[2]["names"], json!(["A", "B", "C"]));
}

#[test]
fn test_import_buffer_serialization_empty() {
    // GIVEN: No imports
    let imports: Vec<ImportStatement> = vec![];

    // WHEN: Serialize
    let import_infos: Vec<serde_json::Value> = imports
        .iter()
        .map(|imp| {
            let (source_path, source_type) = match &imp.source {
                ImportSource::Local(p) => (p.as_str(), "local"),
                ImportSource::Url(u) => (u.as_str(), "url"),
            };
            json!({
                "names": imp.imported_names(),
                "source_path": source_path,
                "source_type": source_type,
            })
        })
        .collect();

    let json_str = serde_json::to_string(&import_infos).unwrap();

    // THEN: Empty array
    assert_eq!(json_str, "[]");
}

// ============================================================================
// B. Component Registry + Imports (3 tests)
// ============================================================================

#[test]
fn test_render_document_with_pre_registered_import() {
    // GIVEN: An engine with a pre-registered component (simulating resolved import)
    let mut engine = Engine::new();
    let patches = Arc::new(Mutex::new(Vec::new()));
    let patches_clone = patches.clone();

    engine.set_render_callback(move |p: &[Patch]| {
        patches_clone.lock().unwrap().extend(p.iter().cloned());
    });

    // Register a "Badge" component (simulating import resolution)
    let badge_component = Component::new("Badge", |_props| text_element("badge"));
    engine.register_component(badge_component);

    // WHEN: Parse a document that uses the imported component and render
    let input = r#"
import { Badge } from "./ui"

Column {
  Text("Hello")
  Badge()
}
    "#;
    let doc = parse_document(input).unwrap();
    let ir_node = ast_to_ir_node(&doc.components[0]);
    engine.render_ir_node(&ir_node);

    // THEN: Patches are generated including the Badge
    let patches = patches.lock().unwrap();
    let create_types: Vec<&str> = patches
        .iter()
        .filter_map(|p| match p {
            Patch::Create { element_type, .. } => Some(element_type.as_str()),
            _ => None,
        })
        .collect();

    assert!(
        create_types.contains(&"Column"),
        "Expected Column in creates: {:?}",
        create_types
    );
    assert!(
        create_types.contains(&"Text"),
        "Expected Text in creates: {:?}",
        create_types
    );
}

#[test]
fn test_document_imports_are_accessible_after_parsing() {
    // GIVEN: A document with various import types
    let input = r#"
import { Button, Card } from "./components/ui"
import Header from "./layout/header"
import { Widget } from "https://cdn.example.com/widgets"

Column {
  Header()
  Button(text: "Click")
  Card()
  Widget()
}
    "#;

    // WHEN: Parse the document
    let doc = parse_document(input).unwrap();

    // THEN: All imports are accessible for resolution
    assert_eq!(doc.imports.len(), 3);

    // First import: named, local
    assert_eq!(doc.imports[0].imported_names(), vec!["Button", "Card"]);
    assert_eq!(doc.imports[0].source_path(), "./components/ui");

    // Second import: default, local
    assert_eq!(doc.imports[1].imported_names(), vec!["Header"]);
    assert_eq!(doc.imports[1].source_path(), "./layout/header");

    // Third import: named, URL
    assert_eq!(doc.imports[2].imported_names(), vec!["Widget"]);
    assert_eq!(
        doc.imports[2].source_path(),
        "https://cdn.example.com/widgets"
    );
}

#[test]
fn test_document_without_imports_has_empty_imports_vec() {
    // GIVEN: A document without any imports
    let input = r#"
Column {
  Text("No imports here")
}
    "#;

    // WHEN: Parse the document
    let doc = parse_document(input).unwrap();

    // THEN: Imports vec is empty
    assert!(doc.imports.is_empty());

    // AND: Component is still parsed normally
    assert_eq!(doc.components.len(), 1);
    assert_eq!(doc.components[0].name, "Column");
}

// ============================================================================
// C. Recursive Import Scenarios (4 tests)
// ============================================================================

#[test]
fn test_nested_import_chain_a_imports_b() {
    // Simulates: App.hypen imports Header, Header.hypen imports Logo
    // All components pre-registered (simulating the resolver loop)

    let mut engine = Engine::new();
    let patches = Arc::new(Mutex::new(Vec::new()));
    let patches_clone = patches.clone();

    engine.set_render_callback(move |p: &[Patch]| {
        patches_clone.lock().unwrap().extend(p.iter().cloned());
    });

    // Register Logo (leaf dependency)
    let logo = Component::new("Logo", |_props| Element::new("Image"));
    engine.register_component(logo);

    // Register Header (depends on Logo)
    let header = Component::new("Header", |_props| {
        let mut row = Element::new("Row");
        row.ir_children
            .push(hypen_engine::ir::IRNode::Element(Element::new("Logo")));
        row.ir_children
            .push(hypen_engine::ir::IRNode::Element(text_element("App Title")));
        row
    });
    engine.register_component(header);

    // WHEN: Render App (depends on Header)
    let app_input = r#"
import { Header } from "./layout"

Column {
  Header()
  Text("Content")
}
    "#;
    let doc = parse_document(app_input).unwrap();
    let ir_node = ast_to_ir_node(&doc.components[0]);
    engine.render_ir_node(&ir_node);

    // THEN: Patches include nested components
    let patches = patches.lock().unwrap();
    let create_types: Vec<&str> = patches
        .iter()
        .filter_map(|p| match p {
            Patch::Create { element_type, .. } => Some(element_type.as_str()),
            _ => None,
        })
        .collect();

    assert!(
        create_types.contains(&"Column"),
        "Missing Column: {:?}",
        create_types
    );
    assert!(
        create_types.contains(&"Row"),
        "Missing Row (from Header): {:?}",
        create_types
    );
}

#[test]
fn test_circular_import_detection_via_visited_set() {
    // Simulates circular detection: A imports B, B imports A
    use std::collections::HashSet;

    let mut visited = HashSet::new();

    // First visit: A -> ok
    assert!(visited.insert("./components/a".to_string()));

    // Second visit: B -> ok
    assert!(visited.insert("./components/b".to_string()));

    // Third visit: A again -> circular!
    assert!(
        !visited.insert("./components/a".to_string()),
        "Should detect circular import"
    );
}

#[test]
fn test_import_visited_set_uses_name_and_path() {
    // Verifies the import_key format used in js.rs: "source_path:name"
    use std::collections::HashSet;

    let mut visited = HashSet::new();

    // Button from ./ui
    let key1 = format!("{}:{}", "./ui", "Button");
    assert!(visited.insert(key1));

    // Card from ./ui (different component, same path)
    let key2 = format!("{}:{}", "./ui", "Card");
    assert!(visited.insert(key2));

    // Button from ./other (same component, different path)
    let key3 = format!("{}:{}", "./other", "Button");
    assert!(visited.insert(key3));

    // Button from ./ui again (duplicate)
    let key4 = format!("{}:{}", "./ui", "Button");
    assert!(!visited.insert(key4), "Should detect duplicate import key");
}

#[test]
fn test_three_level_component_chain() {
    // Simulates: App -> Page -> Section -> Widget

    let mut engine = Engine::new();
    let patches = Arc::new(Mutex::new(Vec::new()));
    let patches_clone = patches.clone();

    engine.set_render_callback(move |p: &[Patch]| {
        patches_clone.lock().unwrap().extend(p.iter().cloned());
    });

    // Widget (leaf)
    let widget = Component::new("Widget", |_props| text_element("widget"));
    engine.register_component(widget);

    // Section (uses Widget)
    let section = Component::new("Section", |_props| {
        let mut col = Element::new("Column");
        col.ir_children
            .push(hypen_engine::ir::IRNode::Element(Element::new("Widget")));
        col.ir_children
            .push(hypen_engine::ir::IRNode::Element(text_element("section")));
        col
    });
    engine.register_component(section);

    // Page (uses Section)
    let page = Component::new("Page", |_props| {
        let mut col = Element::new("Column");
        col.ir_children
            .push(hypen_engine::ir::IRNode::Element(Element::new("Section")));
        col.ir_children
            .push(hypen_engine::ir::IRNode::Element(text_element("page")));
        col
    });
    engine.register_component(page);

    // Render App
    let app_input = r#"
import { Page } from "./pages"

Column {
  Page()
  Text("footer")
}
    "#;
    let doc = parse_document(app_input).unwrap();
    let ir_node = ast_to_ir_node(&doc.components[0]);
    engine.render_ir_node(&ir_node);

    // THEN: All levels render
    let patches = patches.lock().unwrap();
    assert!(
        patches.len() >= 5,
        "Expected many patches for 4-level component tree, got {}",
        patches.len()
    );
}

// ============================================================================
// D. State Bindings with Documents (3 tests)
// ============================================================================

#[test]
fn test_state_binding_in_document() {
    // GIVEN: Engine with state
    let mut engine = Engine::new();
    let patches = Arc::new(Mutex::new(Vec::new()));
    let patches_clone = patches.clone();

    engine.set_render_callback(move |p: &[Patch]| {
        patches_clone.lock().unwrap().extend(p.iter().cloned());
    });

    let module_meta = Module::new("App");
    let module = ModuleInstance::new(module_meta, json!({"title": "My App"}));
    engine.set_module(module);

    // WHEN: Render document with state binding
    let input = r#"
import { AppHeader } from "./header"

Column {
  Text("@{state.title}")
}
    "#;
    let doc = parse_document(input).unwrap();
    engine.render_ir_node(&ast_to_ir_node(&doc.components[0]));

    // THEN: State binding resolves
    let patches = patches.lock().unwrap();
    let has_title = patches.iter().any(|p| {
        if let Patch::Create { props, .. } = p {
            props
                .get("0")
                .map(|v| v == &json!("My App"))
                .unwrap_or(false)
        } else {
            false
        }
    });
    assert!(has_title, "Expected 'My App' in initial render");
}

#[test]
fn test_state_update_propagates_through_document() {
    let mut engine = Engine::new();
    let patches = Arc::new(Mutex::new(Vec::new()));
    let patches_clone = patches.clone();

    engine.set_render_callback(move |p: &[Patch]| {
        patches_clone.lock().unwrap().extend(p.iter().cloned());
    });

    let module_meta = Module::new("App");
    let module = ModuleInstance::new(module_meta, json!({"count": 0}));
    engine.set_module(module);

    let input = r#"
import { Counter } from "./counter"

Column {
  Text("@{state.count}")
}
    "#;
    let doc = parse_document(input).unwrap();
    engine.render_ir_node(&ast_to_ir_node(&doc.components[0]));

    patches.lock().unwrap().clear();

    // WHEN: Update state
    engine.update_state(None, json!({"count": 99}));

    // THEN: SetProp emitted
    let patches = patches.lock().unwrap();
    let has_update = patches.iter().any(|p| match p {
        Patch::SetProp { name, value, .. } => name == "0" && value == &json!(99),
        _ => false,
    });
    assert!(
        has_update,
        "Expected SetProp with count=99. Got: {:?}",
        *patches
    );
}

#[test]
fn test_document_full_lifecycle() {
    let mut engine = Engine::new();
    let all_patches = Arc::new(Mutex::new(Vec::new()));
    let patches_clone = all_patches.clone();

    engine.set_render_callback(move |p: &[Patch]| {
        patches_clone.lock().unwrap().extend(p.iter().cloned());
    });

    let module_meta = Module::new("Chat");
    let module = ModuleInstance::new(module_meta, json!({"message": "Hello"}));
    engine.set_module(module);

    let input = r#"
import { MessageView } from "./chat"

Column {
  Text("@{state.message}")
}
    "#;
    let doc = parse_document(input).unwrap();
    engine.render_ir_node(&ast_to_ir_node(&doc.components[0]));

    // Check initial render
    {
        let patches = all_patches.lock().unwrap();
        let has_hello = patches.iter().any(|p| {
            if let Patch::Create { props, .. } = p {
                props
                    .get("0")
                    .map(|v| v == &json!("Hello"))
                    .unwrap_or(false)
            } else {
                false
            }
        });
        assert!(has_hello, "Expected 'Hello' in initial render");
    }

    // Update state
    all_patches.lock().unwrap().clear();
    engine.update_state(None, json!({"message": "World"}));

    // Check update
    {
        let patches = all_patches.lock().unwrap();
        let has_world = patches.iter().any(|p| match p {
            Patch::SetProp { name, value, .. } => name == "0" && value == &json!("World"),
            _ => false,
        });
        assert!(
            has_world,
            "Expected 'World' after state update. Got: {:?}",
            *patches
        );
    }
}

// ============================================================================
// E. Router + Import Parsing (2 tests)
// ============================================================================

#[test]
fn test_document_with_router_and_imports() {
    let input = r#"
import { HomePage } from "./pages/home"
import { AboutPage } from "./pages/about"

Router {
  Route(path: "/") {
    HomePage()
  }
  Route(path: "/about") {
    AboutPage()
  }
}
    "#;

    let doc = parse_document(input).unwrap();

    assert_eq!(doc.imports.len(), 2);
    assert_eq!(doc.imports[0].imported_names(), vec!["HomePage"]);
    assert_eq!(doc.imports[1].imported_names(), vec!["AboutPage"]);

    assert_eq!(doc.components.len(), 1);
    assert_eq!(doc.components[0].name, "Router");
}

#[test]
fn test_document_with_nested_layouts_and_imports() {
    let input = r#"
import { Header } from "./layout/header"
import { Footer } from "./layout/footer"
import { Sidebar } from "./layout/sidebar"
import { MainContent } from "./pages/main"

Column {
  Header()
  Row {
    Sidebar()
    MainContent()
  }
  Footer()
}
    "#;

    let doc = parse_document(input).unwrap();

    assert_eq!(doc.imports.len(), 4);
    assert_eq!(doc.imports[0].source_path(), "./layout/header");
    assert_eq!(doc.imports[1].source_path(), "./layout/footer");
    assert_eq!(doc.imports[2].source_path(), "./layout/sidebar");
    assert_eq!(doc.imports[3].source_path(), "./pages/main");

    assert_eq!(doc.components.len(), 1);
    assert_eq!(doc.components[0].name, "Column");
}