cviz 2.0.3

A CLI tool to visualize WebAssembly component composition structure.
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
use crate::model::{
    ComponentNode, CompositionGraph, FuncSignature, InstanceInterface, InterfaceConnection,
    InterfaceType, TypeArena, ValueType, ValueTypeId, SYNTHETIC_COMPONENT,
};
use anyhow::Result;
use std::collections::HashMap;
use wirm::ir::component::concrete::{ConcreteFuncType, ConcreteType, ConcreteValType};
use wirm::ir::component::refs::{GetCompRefs, GetItemRef};
use wirm::ir::component::visitor::{
    walk_structural, ComponentVisitor, ItemKind, ResolvedItem, VisitCtx,
};
use wirm::wasmparser::{
    ComponentAlias, ComponentExport, ComponentExternalKind, ComponentInstance, ComponentTypeRef,
    PrimitiveValType,
};
use wirm::Component;

/// Parse the top-level interface (instance-kind) imports of a plain Wasm component.
///
/// Returns one `(interface_name, fingerprint)` pair for every `instance`-kind import
/// found in the component's import section.  The fingerprint is derived from the
/// concrete type of the import and can be used for structural type-compatibility checks.
/// `fingerprint` is `None` when the type cannot be concretised (rare).
///
/// Other import kinds (functions, modules, types) are ignored.
///
/// This is the counterpart to [`parse_component`] for extracting the *import* surface of
/// a component that has not yet been composed with its dependencies.
pub fn parse_component_imports(buff: &[u8]) -> Result<Vec<(String, Option<String>)>> {
    use wirm::wasmparser::ComponentTypeRef;

    let component = Component::parse(buff, false, false).expect("Unable to parse");
    let mut arena = crate::model::TypeArena::default();
    let mut imports = Vec::new();

    for import in component.imports.iter() {
        if let ComponentTypeRef::Instance(_) = import.ty {
            let name = import.name.0.to_string();
            let fingerprint = component
                .concretize_import(&name)
                .and_then(|ct| concrete_to_interface_type(ct, &mut arena))
                .map(|it| it.fingerprint(&arena));
            imports.push((name, fingerprint));
        }
    }

    Ok(imports)
}

/// Parse a WebAssembly component file and extract its composition graph
pub fn parse_component(buff: &[u8]) -> Result<CompositionGraph> {
    let component = Component::parse(buff, false, false).expect("Unable to parse");
    let mut visitor = Visitor::new();

    walk_structural(&component, &mut visitor);
    visitor.postprocess();

    // Post-process: fill in fingerprints for top-level instance exports that the visitor
    // couldn't resolve during the walk (e.g. shim-component pattern from wit-component,
    // or middleware that directly re-exports an imported instance).  Now that wirm's
    // concretize_export handles CompInst::Instantiate and Import re-exports, calling it
    // on the root component resolves the correct type.
    for export in component.exports.iter() {
        if export.kind != ComponentExternalKind::Instance {
            continue;
        }
        let name = export.name.0;
        // Always try to fill/refill — later visits (outer components) may
        // produce more complete type information than earlier visits (nested).
        {
            if let Some(ct) = component.concretize_export(name) {
                if let Some(it) = concrete_to_interface_type(ct, &mut visitor.graph.arena) {
                    let source = visitor
                        .graph
                        .component_exports
                        .get(name)
                        .map_or(SYNTHETIC_COMPONENT, |e| e.source_instance);
                    visitor.graph.add_export(name.to_string(), source, Some(it));
                }
            }
        }
    }

    Ok(visitor.graph)
}
struct Visitor {
    curr_comp_num: u32,
    comp_id_to_num: Vec<HashMap<u32, u32>>,
    graph: CompositionGraph,
    /// Sequential graph ID counter — each visited `Instantiate` gets the next value.
    next_graph_id: u32,
    /// Maps the raw pointer address of a `ComponentInstance` to its sequential graph ID.
    ///
    /// wirm gives us a stable `&ComponentInstance` reference both when visiting an
    /// instance (`visit_comp_instance`) and when resolving a reference to it later
    /// (`cx.resolve → ResolvedItem::CompInst(_, inst)`).  Using the pointer as a
    /// scope-independent identity lets us correctly correlate inner-scope shim
    /// instances across scope boundaries.
    inst_ptr_to_graph_id: HashMap<usize, u32>,
}
impl Visitor {
    pub fn new() -> Self {
        Self {
            curr_comp_num: 0,
            comp_id_to_num: Vec::new(),
            graph: CompositionGraph::new(),
            next_graph_id: 0,
            inst_ptr_to_graph_id: HashMap::new(),
        }
    }
    pub fn postprocess(&mut self) {
        // Mark host imports on the connections.
        // Any import whose source_instance is not a known graph node (or is None)
        // is provided by the host rather than another composed instance.
        let all_node_inst_ids: std::collections::HashSet<u32> =
            self.graph.nodes.keys().copied().collect();
        for node in self.graph.nodes.values_mut() {
            for import in &mut node.imports {
                if !import
                    .source_instance
                    .is_some_and(|id| all_node_inst_ids.contains(&id))
                {
                    import.is_host_import = true;
                    import.source_instance = None;
                }
            }
        }
    }
}
impl ComponentVisitor<'_> for Visitor {
    fn enter_root_component(&mut self, _cx: &VisitCtx<'_>, _component: &Component<'_>) {
        self.comp_id_to_num.push(HashMap::new());
    }
    fn exit_root_component(&mut self, _cx: &VisitCtx<'_>, _component: &Component<'_>) {
        self.comp_id_to_num.pop();
    }
    fn enter_component(&mut self, _cx: &VisitCtx, id: u32, _component: &Component) {
        if let Some(outer) = self.comp_id_to_num.last_mut() {
            outer.insert(id, self.curr_comp_num);
        }
        self.curr_comp_num += 1;
        self.comp_id_to_num.push(HashMap::new());
    }

    fn exit_component(&mut self, _: &VisitCtx, _: u32, _component: &Component) {
        self.comp_id_to_num.pop();
    }

    // Process component instances - ** this is where the composition wiring lives **
    fn visit_comp_instance(&mut self, cx: &VisitCtx, id: u32, instance: &ComponentInstance) {
        let name = cx
            .lookup_comp_inst_name(id)
            .map(|n| n.to_string())
            .unwrap_or_else(|| format!("instance_{}", id));
        match instance {
            ComponentInstance::Instantiate {
                component_index,
                args,
            } => {
                let instantiated_comp = if let ResolvedItem::Component(_, comp) =
                    cx.resolve(&instance.get_comp_refs().first().unwrap().ref_)
                {
                    Some(comp)
                } else {
                    None
                };

                let comp_num = self.comp_id_to_num.last().unwrap()[component_index];
                let mut node = ComponentNode::new(name, *component_index, comp_num);

                // Assign a sequential graph ID and register the ptr→id mapping so
                // that later cx.resolve() calls returning this instance can find it.
                let graph_id = self.next_graph_id;
                self.next_graph_id += 1;
                self.inst_ptr_to_graph_id
                    .insert(instance as *const ComponentInstance as usize, graph_id);

                // Process the "with" arguments - these are the interface connections
                for arg in args.iter() {
                    let interface_name = arg.name.to_string();
                    let interface_type =
                        pull_type_info(&interface_name, &instantiated_comp, &mut self.graph);

                    // The arg.index is the instance providing this interface
                    // It might be an alias, so resolve it to the actual source instance
                    let item = cx.resolve(&arg.get_item_ref().ref_);
                    match item {
                        ResolvedItem::CompInst(_, inst) => {
                            let source = self
                                .inst_ptr_to_graph_id
                                .get(&(inst as *const ComponentInstance as usize))
                                .copied();
                            let connection = InterfaceConnection::from_instance(
                                interface_name,
                                source,
                                interface_type,
                                &self.graph.arena,
                            );
                            node.add_import(connection);
                        }
                        ResolvedItem::Import(_id, imp) => {
                            // This arg is satisfied by the host (component import section),
                            // not by another composed instance — always a host import.
                            if let ComponentTypeRef::Instance(_) = imp.ty {
                                let connection = InterfaceConnection::from_instance(
                                    interface_name,
                                    None,
                                    interface_type,
                                    &self.graph.arena,
                                );
                                node.add_import(connection);
                            }
                        }
                        ResolvedItem::Alias(_, alias) => {
                            resolve_inst_alias(
                                cx,
                                alias,
                                &interface_name,
                                interface_type,
                                &mut node,
                                &self.inst_ptr_to_graph_id,
                                &self.graph.arena,
                            );
                        }
                        _ => {}
                    }
                }

                self.graph.add_node(graph_id, node);
            }
            ComponentInstance::FromExports(_) => {
                // This is a synthetic instance created from exports
                // These often wrap host imports - we don't track them as nodes
                // since they're just interface bundles, not actual components
            }
        }
    }
    fn visit_comp_export(&mut self, cx: &VisitCtx, _: ItemKind, _: u32, export: &ComponentExport) {
        // `component_exports` is documented as the root component's
        // public surface, so only record exports emitted at the root
        // level. `comp_id_to_num` is a stack: len == 1 inside the root
        // component, >= 2 inside any nested component.
        if self.comp_id_to_num.len() != 1 {
            return;
        }

        let export_name = export.name.0.to_string();
        let item = cx.resolve(&export.get_item_ref().ref_);

        // Only track instance exports
        match item {
            ResolvedItem::CompInst(_, inst) => {
                let ptr = inst as *const ComponentInstance as usize;
                if let Some(&graph_id) = self.inst_ptr_to_graph_id.get(&ptr) {
                    let iface_type =
                        pull_export_type_from_instance(&export_name, inst, &mut self.graph, cx);
                    self.graph.add_export(export_name, graph_id, iface_type);
                }
            }
            ResolvedItem::Alias(_, alias) => {
                let graph = &mut self.graph;
                let ptr_map = &self.inst_ptr_to_graph_id;
                let outer_comp = cx.curr_component();
                resolve_imp_alias(cx, alias, &export_name, graph, ptr_map, outer_comp);
            }
            _ => {}
        }
    }
}

fn pull_export_type_from_instance(
    export_name: &str,
    inst: &ComponentInstance,
    graph: &mut CompositionGraph,
    cx: &VisitCtx,
) -> Option<InterfaceType> {
    let comp_ref = inst.get_comp_refs().into_iter().next()?;
    let comp = match cx.resolve(&comp_ref.ref_) {
        ResolvedItem::Component(_, c) => c,
        _ => return None,
    };
    // Try the export path first, then fall back to the import path.
    // The import path often produces better type information for
    // wac-composed components where exports are pass-throughs.
    let from_export = comp
        .concretize_export(export_name)
        .and_then(|ct| concrete_to_interface_type(ct, &mut graph.arena));

    // If the export path produced an interface with no type_exports
    // (unnamed resources), try the import path which resolves through
    // alias outer declarations and can name them.
    let has_type_exports = from_export.as_ref().is_some_and(|it| match it {
        InterfaceType::Instance(inst) => !inst.type_exports.is_empty(),
        _ => true,
    });

    if has_type_exports {
        from_export
    } else {
        comp.concretize_import(export_name)
            .and_then(|ct| concrete_to_interface_type(ct, &mut graph.arena))
            .or(from_export)
    }
}

fn pull_type_info(
    interface_name: &str,
    instantiated_comp: &Option<&Component>,
    graph: &mut CompositionGraph,
) -> Option<InterfaceType> {
    let comp = (*instantiated_comp)?;
    // Try the import path first (normal case), then check if the result
    // has complete type information.  If not, try the export path which
    // may produce better results for interfaces with resource types.
    let from_import = comp
        .concretize_import(interface_name)
        .and_then(|ct| concrete_to_interface_type(ct, &mut graph.arena));

    let has_type_exports = from_import.as_ref().is_some_and(|it| match it {
        InterfaceType::Instance(inst) => !inst.type_exports.is_empty(),
        _ => true,
    });

    if has_type_exports {
        from_import
    } else {
        comp.concretize_export(interface_name)
            .and_then(|ct| concrete_to_interface_type(ct, &mut graph.arena))
            .or(from_import)
    }
}

fn concrete_to_interface_type<'a>(
    ty: ConcreteType<'a>,
    arena: &mut TypeArena,
) -> Option<InterfaceType> {
    match ty {
        ConcreteType::Instance {
            funcs,
            type_exports: te,
        } => {
            let functions = funcs
                .into_iter()
                .map(|(name, ft)| (name.to_string(), concrete_to_func_sig(ft, arena)))
                .collect();
            let type_exports = te
                .into_iter()
                .map(|(name, cvt)| (name.to_string(), intern(cvt, arena)))
                .collect();
            Some(InterfaceType::Instance(InstanceInterface {
                functions,
                type_exports,
            }))
        }
        ConcreteType::Func(ft) => Some(InterfaceType::Func(concrete_to_func_sig(ft, arena))),
        ConcreteType::Resource => None,
    }
}

fn intern<'a>(ty: ConcreteValType<'a>, arena: &mut TypeArena) -> ValueTypeId {
    let vt = concrete_to_val_type(ty, arena);
    arena.intern_val(vt)
}

fn concrete_to_func_sig<'a>(ft: ConcreteFuncType<'a>, arena: &mut TypeArena) -> FuncSignature {
    let is_async = ft.is_async;
    let param_names = ft.params.iter().map(|(name, _)| name.to_string()).collect();
    let params = ft
        .params
        .into_iter()
        .map(|(_, ty)| intern(ty, arena))
        .collect();
    let results = ft.result.map(|ty| intern(ty, arena)).into_iter().collect();
    FuncSignature {
        is_async,
        param_names,
        params,
        results,
    }
}

fn concrete_to_val_type<'a>(ty: ConcreteValType<'a>, arena: &mut TypeArena) -> ValueType {
    match ty {
        ConcreteValType::Primitive(p) => prim_to_val_type(p),
        ConcreteValType::Record(fields) => ValueType::Record(
            fields
                .into_iter()
                .map(|(name, ty)| (name.to_string(), intern(*ty, arena)))
                .collect(),
        ),
        ConcreteValType::Variant(cases) => ValueType::Variant(
            cases
                .into_iter()
                .map(|(name, ty)| (name.to_string(), ty.map(|t| intern(*t, arena))))
                .collect(),
        ),
        ConcreteValType::List(ty) => ValueType::List(intern(*ty, arena)),
        ConcreteValType::FixedLengthList(ty, size) => {
            ValueType::FixedSizeList(intern(*ty, arena), size)
        }
        ConcreteValType::Tuple(types) => {
            ValueType::Tuple(types.into_iter().map(|ty| intern(ty, arena)).collect())
        }
        ConcreteValType::Option(ty) => ValueType::Option(intern(*ty, arena)),
        ConcreteValType::Result { ok, err } => ValueType::Result {
            ok: ok.map(|t| intern(*t, arena)),
            err: err.map(|t| intern(*t, arena)),
        },
        ConcreteValType::Flags(names) => {
            ValueType::Flags(names.iter().map(|s| s.to_string()).collect())
        }
        ConcreteValType::Enum(names) => {
            ValueType::Enum(names.iter().map(|s| s.to_string()).collect())
        }
        ConcreteValType::Map(key, val) => ValueType::Map(intern(*key, arena), intern(*val, arena)),
        ConcreteValType::NamedResource(name) => ValueType::Resource(name.to_string()),
        ConcreteValType::AsyncHandle => ValueType::AsyncHandle,
    }
}

fn prim_to_val_type(p: PrimitiveValType) -> ValueType {
    match p {
        PrimitiveValType::Bool => ValueType::Bool,
        PrimitiveValType::S8 => ValueType::S8,
        PrimitiveValType::U8 => ValueType::U8,
        PrimitiveValType::S16 => ValueType::S16,
        PrimitiveValType::U16 => ValueType::U16,
        PrimitiveValType::S32 => ValueType::S32,
        PrimitiveValType::U32 => ValueType::U32,
        PrimitiveValType::S64 => ValueType::S64,
        PrimitiveValType::U64 => ValueType::U64,
        PrimitiveValType::F32 => ValueType::F32,
        PrimitiveValType::F64 => ValueType::F64,
        PrimitiveValType::Char => ValueType::Char,
        PrimitiveValType::String => ValueType::String,
        PrimitiveValType::ErrorContext => ValueType::ErrorContext,
    }
}

fn resolve_inst_alias(
    cx: &VisitCtx,
    alias: &ComponentAlias,
    interface_name: &str,
    interface_type: Option<InterfaceType>,
    node: &mut ComponentNode,
    inst_ptr_to_graph_id: &HashMap<usize, u32>,
    arena: &TypeArena,
) {
    let inst_ref = alias.get_item_ref();

    match cx.resolve(&inst_ref.ref_) {
        ResolvedItem::CompInst(_, inst) => {
            let source = inst_ptr_to_graph_id
                .get(&(inst as *const ComponentInstance as usize))
                .copied();
            let connection = InterfaceConnection::from_instance(
                interface_name.to_string(),
                source,
                interface_type,
                arena,
            );
            node.add_import(connection);
        }
        ResolvedItem::Alias(_, nested_alias) => resolve_inst_alias(
            cx,
            nested_alias,
            interface_name,
            interface_type,
            node,
            inst_ptr_to_graph_id,
            arena,
        ),
        _ => {}
    }
}
fn resolve_imp_alias(
    cx: &VisitCtx,
    alias: &ComponentAlias,
    export_name: &str,
    graph: &mut CompositionGraph,
    inst_ptr_to_graph_id: &HashMap<usize, u32>,
    outer_comp: &Component,
) {
    let inst_ref = alias.get_item_ref();
    let resolved = cx.resolve(&inst_ref.ref_);

    match resolved {
        ResolvedItem::CompInst(_, inst) => {
            let ptr = inst as *const ComponentInstance as usize;
            if let Some(&graph_id) = inst_ptr_to_graph_id.get(&ptr) {
                let mut iface_type = pull_export_type_from_instance(export_name, inst, graph, cx);

                // If the nested component produced an interface with unnamed
                // resources (no type_exports), try the outer component's own
                // concretize_export which can resolve through alias outer.
                let has_type_exports = iface_type.as_ref().is_some_and(|it| match it {
                    InterfaceType::Instance(inst) => !inst.type_exports.is_empty(),
                    _ => true,
                });
                if !has_type_exports {
                    if let Some(ct) = outer_comp.concretize_export(export_name) {
                        if let Some(better) = concrete_to_interface_type(ct, &mut graph.arena) {
                            let better_has_te = match &better {
                                InterfaceType::Instance(inst) => !inst.type_exports.is_empty(),
                                _ => false,
                            };
                            if better_has_te {
                                iface_type = Some(better);
                            }
                        }
                    }
                }

                graph.add_export(export_name.to_string(), graph_id, iface_type);
            }
        }
        ResolvedItem::Alias(_, nested_alias) => resolve_imp_alias(
            cx,
            nested_alias,
            export_name,
            graph,
            inst_ptr_to_graph_id,
            outer_comp,
        ),
        _ => {}
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{get_chain_for, is_connection_for};

    /// WAT for a composed component with two middleware instances chained via wasi:http/handler.
    ///
    /// Structure:
    ///   host(handler) → middleware-a → middleware-b → export(handler)
    fn two_middleware_chain_wat() -> &'static str {
        r#"(component
            (import "wasi:http/handler@0.3.0" (instance $host
                (export "handle" (func))
            ))

            (component $middleware-a
                (import "wasi:http/handler@0.3.0" (instance $imp
                    (export "handle" (func))
                ))
                (alias export $imp "handle" (func $f))
                (instance $out (export "handle" (func $f)))
                (export "wasi:http/handler@0.3.0" (instance $out))
            )

            (instance $a (instantiate $middleware-a
                (with "wasi:http/handler@0.3.0" (instance $host))
            ))
            (alias export $a "wasi:http/handler@0.3.0" (instance $a-out))

            (component $middleware-b
                (import "wasi:http/handler@0.3.0" (instance $imp
                    (export "handle" (func))
                ))
                (alias export $imp "handle" (func $f))
                (instance $out (export "handle" (func $f)))
                (export "wasi:http/handler@0.3.0" (instance $out))
            )

            (instance $b (instantiate $middleware-b
                (with "wasi:http/handler@0.3.0" (instance $a-out))
            ))
            (alias export $b "wasi:http/handler@0.3.0" (instance $b-out))

            (export "wasi:http/handler@0.3.0" (instance $b-out))
        )"#
    }

    #[test]
    fn test_parse_composed_component() {
        let bytes = wat::parse_str(two_middleware_chain_wat()).expect("failed to parse WAT");
        let graph = parse_component(&bytes).expect("failed to parse component");

        // Should have exactly 2 real component nodes (the two middleware instances)
        let real_nodes = graph.real_nodes();
        assert_eq!(real_nodes.len(), 2, "expected 2 real component nodes");

        // Each node should have a handler import
        let http_interface = "wasi:http/handler";
        for node in &real_nodes {
            assert!(
                node.imports
                    .iter()
                    .any(|i| is_connection_for(i, http_interface)),
                "node '{}' should have a handler import",
                node.name
            );
        }

        // Should have an export for the handler
        assert!(
            graph
                .component_exports
                .keys()
                .any(|k| k.contains("wasi:http/handler")),
            "expected handler export"
        );
    }

    #[test]
    fn test_handler_chain_detection() {
        let bytes = wat::parse_str(two_middleware_chain_wat()).expect("failed to parse WAT");
        let graph = parse_component(&bytes).expect("failed to parse component");

        let http_interface = "wasi:http/handler";
        let chain = get_chain_for(&graph, http_interface);
        assert_eq!(chain.len(), 2, "expected 2 nodes in handler chain");

        // Chain is in request-flow order: outermost (export) first, innermost last
        // First node is the export point (outermost handler)
        let first = graph.get_node(chain[0]).expect("first chain node");
        assert!(
            first
                .imports
                .iter()
                .any(|i| !i.is_host_import && is_connection_for(i, http_interface)),
            "first chain node (outermost) should import handler from another component"
        );

        // Last node imports from host (innermost handler)
        let last = graph.get_node(chain[1]).expect("last chain node");
        assert!(
            last.imports
                .iter()
                .any(|i| i.is_host_import && is_connection_for(i, http_interface)),
            "last chain node (innermost) should import handler from host"
        );

        // First node's handler source should be the last node
        let first_handler = first
            .imports
            .iter()
            .find(|i| is_connection_for(i, http_interface))
            .unwrap();
        assert_eq!(
            first_handler.source_instance.unwrap(),
            chain[1],
            "first node's handler source should be the last chain node"
        );
    }

    #[test]
    fn test_parse_composed_multiple() {
        let bytes = include_bytes!("../../../tests/fixtures/composed-multiple.wasm");
        let graph = parse_component(bytes).expect("failed to parse composed-multiple.wasm");
        assert!(
            !graph.nodes.is_empty(),
            "expected at least one component node"
        );
    }

    #[test]
    fn test_host_import_detection() {
        let bytes = wat::parse_str(two_middleware_chain_wat()).expect("failed to parse WAT");
        let graph = parse_component(&bytes).expect("failed to parse component");

        let host_interfaces = graph.host_interfaces();
        assert!(
            host_interfaces
                .iter()
                .any(|i| i.contains("wasi:http/handler")),
            "expected host handler interface, got: {:?}",
            host_interfaces
        );
    }

    // -----------------------------------------------------------------------
    // Fingerprint post-processing tests (RC-1, RC-2, RC-3 coverage)
    // -----------------------------------------------------------------------

    /// Standalone middleware using the FromExports synthetic-instance pattern.
    /// Export resolves to `CompInst::FromExports` — handled by the existing arm;
    /// the post-processing pass must not clobber the fingerprint.
    #[test]
    fn fingerprint_from_exports_instance() {
        let wat = r#"(component
            (import "wasi:http/handler@0.3.0" (instance $host
                (export "handle" (func (param "req" u32) (result u32)))
            ))
            (alias export $host "handle" (func $f))
            (instance $out (export "handle" (func $f)))
            (export "wasi:http/handler@0.3.0" (instance $out))
        )"#;
        let bytes = wat::parse_str(wat).expect("failed to parse WAT");
        let graph = parse_component(&bytes).expect("failed to parse component");

        let export = graph
            .component_exports
            .get("wasi:http/handler@0.3.0")
            .expect("expected export for wasi:http/handler@0.3.0");
        assert!(
            export.fingerprint.is_some(),
            "expected non-None fingerprint for FromExports middleware, got None"
        );
    }

    /// Standalone middleware using the shim-component (Instantiate) pattern.
    /// The outer component exports an instantiated nested shim component as the
    /// interface instance — the primary bug (RC-1/RC-2).  After the fix the
    /// post-processing pass fills in the fingerprint via `concretize_export`.
    #[test]
    fn fingerprint_from_shim_component() {
        let wat = r#"(component
            (component $shim
                (import "handle" (func $h (param "req" u32) (result u32)))
                (export "handle" (func $h))
            )
            (import "handle" (func $h (param "req" u32) (result u32)))
            (instance $shim-inst (instantiate $shim
                (with "handle" (func $h))
            ))
            (export "wasi:http/handler@0.3.0" (instance $shim-inst))
        )"#;
        let bytes = wat::parse_str(wat).expect("failed to parse WAT");
        let graph = parse_component(&bytes).expect("failed to parse component");

        let export = graph
            .component_exports
            .get("wasi:http/handler@0.3.0")
            .expect("expected export for wasi:http/handler@0.3.0");
        assert!(
            export.fingerprint.is_some(),
            "expected non-None fingerprint for shim-component middleware, got None"
        );
    }

    /// Standalone middleware that directly re-exports an imported instance (RC-3).
    /// The visitor drops this export entirely; the post-processing pass must add it
    /// with a valid fingerprint.
    #[test]
    fn fingerprint_from_import_reexport() {
        let wat = r#"(component
            (import "wasi:http/handler@0.3.0" (instance $handler
                (export "handle" (func (param "req" u32) (result u32)))
            ))
            (export "wasi:http/handler@0.3.0" (instance $handler))
        )"#;
        let bytes = wat::parse_str(wat).expect("failed to parse WAT");
        let graph = parse_component(&bytes).expect("failed to parse component");

        let export = graph
            .component_exports
            .get("wasi:http/handler@0.3.0")
            .expect("expected export for wasi:http/handler@0.3.0");
        assert!(
            export.fingerprint.is_some(),
            "expected non-None fingerprint for import-reexport middleware, got None"
        );
    }

    /// Parsing two components that export the same interface with the same function
    /// signature must produce equal fingerprints.
    #[test]
    fn fingerprint_matches_between_chain_and_mw() {
        // Both components export "handle" (func (param u32) (result u32)).
        let chain_wat = r#"(component
            (import "wasi:http/handler@0.3.0" (instance $host
                (export "handle" (func (param "req" u32) (result u32)))
            ))
            (alias export $host "handle" (func $f))
            (instance $out (export "handle" (func $f)))
            (export "wasi:http/handler@0.3.0" (instance $out))
        )"#;
        let mw_wat = r#"(component
            (import "wasi:http/handler@0.3.0" (instance $handler
                (export "handle" (func (param "req" u32) (result u32)))
            ))
            (export "wasi:http/handler@0.3.0" (instance $handler))
        )"#;
        let chain_bytes = wat::parse_str(chain_wat).expect("failed to parse chain WAT");
        let mw_bytes = wat::parse_str(mw_wat).expect("failed to parse middleware WAT");

        let chain_graph = parse_component(&chain_bytes).expect("failed to parse chain");
        let mw_graph = parse_component(&mw_bytes).expect("failed to parse middleware");

        let chain_fp = chain_graph
            .component_exports
            .get("wasi:http/handler@0.3.0")
            .and_then(|e| e.fingerprint.as_ref())
            .expect("chain should have fingerprint");
        let mw_fp = mw_graph
            .component_exports
            .get("wasi:http/handler@0.3.0")
            .and_then(|e| e.fingerprint.as_ref())
            .expect("middleware should have fingerprint");

        assert_eq!(
            chain_fp, mw_fp,
            "compatible chain/middleware should have equal fingerprints"
        );
    }

    /// Two component definitions each contain an inner `Instantiate` shim at the
    /// same wasm-local instance id (0).  Before the sequential-ID fix, the second
    /// shim would silently overwrite the first in the graph, causing both exports
    /// to point at the same node.  After the fix they must resolve to distinct nodes.
    #[test]
    fn parallel_inner_shims_get_distinct_graph_ids() {
        let wat = r#"(component
            ;; Two host-provided interfaces
            (import "test:iface/a@0.1.0" (instance $host-a
                (export "run" (func))
            ))
            (import "test:iface/b@0.1.0" (instance $host-b
                (export "run" (func))
            ))

            ;; First wrapper — inner shim gets wasm local id 0 inside this scope
            (component $comp-a
                (import "test:iface/a@0.1.0" (instance $imp
                    (export "run" (func))
                ))
                (component $shim-a
                    (import "test:iface/a@0.1.0" (instance $i
                        (export "run" (func))
                    ))
                    (alias export $i "run" (func $f))
                    (instance $out (export "run" (func $f)))
                    (export "test:iface/a@0.1.0" (instance $out))
                )
                (instance $shim-a-inst (instantiate $shim-a
                    (with "test:iface/a@0.1.0" (instance $imp))
                ))
                (alias export $shim-a-inst "test:iface/a@0.1.0" (instance $a-inner))
                (export "test:iface/a@0.1.0" (instance $a-inner))
            )

            ;; Second wrapper — inner shim also gets wasm local id 0 in its own scope
            (component $comp-b
                (import "test:iface/b@0.1.0" (instance $imp
                    (export "run" (func))
                ))
                (component $shim-b
                    (import "test:iface/b@0.1.0" (instance $i
                        (export "run" (func))
                    ))
                    (alias export $i "run" (func $f))
                    (instance $out (export "run" (func $f)))
                    (export "test:iface/b@0.1.0" (instance $out))
                )
                (instance $shim-b-inst (instantiate $shim-b
                    (with "test:iface/b@0.1.0" (instance $imp))
                ))
                (alias export $shim-b-inst "test:iface/b@0.1.0" (instance $b-inner))
                (export "test:iface/b@0.1.0" (instance $b-inner))
            )

            (instance $a (instantiate $comp-a
                (with "test:iface/a@0.1.0" (instance $host-a))
            ))
            (alias export $a "test:iface/a@0.1.0" (instance $a-out))

            (instance $b (instantiate $comp-b
                (with "test:iface/b@0.1.0" (instance $host-b))
            ))
            (alias export $b "test:iface/b@0.1.0" (instance $b-out))

            (export "test:iface/a@0.1.0" (instance $a-out))
            (export "test:iface/b@0.1.0" (instance $b-out))
        )"#;

        let bytes = wat::parse_str(wat).expect("failed to parse WAT");
        let graph = parse_component(&bytes).expect("failed to parse component");

        let export_a = graph
            .component_exports
            .get("test:iface/a@0.1.0")
            .expect("export for test:iface/a@0.1.0 missing");
        let export_b = graph
            .component_exports
            .get("test:iface/b@0.1.0")
            .expect("export for test:iface/b@0.1.0 missing");

        let src_a = export_a.source_instance;
        let src_b = export_b.source_instance;

        assert_ne!(
            src_a, src_b,
            "parallel inner shims at the same wasm local id must map to distinct graph nodes"
        );

        // Each export's source node must actually exist in the graph
        assert!(
            graph.get_node(src_a).is_some(),
            "source node for test:iface/a@0.1.0 must exist in graph"
        );
        assert!(
            graph.get_node(src_b).is_some(),
            "source node for test:iface/b@0.1.0 must exist in graph"
        );
    }

    /// Parsing two components with differing function signatures must produce
    /// different fingerprints so that `validate_contract` correctly rejects them.
    #[test]
    fn fingerprint_differs_between_chain_and_mw() {
        // Chain: (param u32) -> u32
        let chain_wat = r#"(component
            (import "wasi:http/handler@0.3.0" (instance $host
                (export "handle" (func (param "req" u32) (result u32)))
            ))
            (alias export $host "handle" (func $f))
            (instance $out (export "handle" (func $f)))
            (export "wasi:http/handler@0.3.0" (instance $out))
        )"#;
        // Incompatible middleware: different param types
        let mw_wat = r#"(component
            (import "wasi:http/handler@0.3.0" (instance $handler
                (export "handle" (func (param "req" string) (result u32)))
            ))
            (export "wasi:http/handler@0.3.0" (instance $handler))
        )"#;
        let chain_bytes = wat::parse_str(chain_wat).expect("failed to parse chain WAT");
        let mw_bytes = wat::parse_str(mw_wat).expect("failed to parse middleware WAT");

        let chain_graph = parse_component(&chain_bytes).expect("failed to parse chain");
        let mw_graph = parse_component(&mw_bytes).expect("failed to parse middleware");

        let chain_fp = chain_graph
            .component_exports
            .get("wasi:http/handler@0.3.0")
            .and_then(|e| e.fingerprint.as_ref())
            .expect("chain should have fingerprint");
        let mw_fp = mw_graph
            .component_exports
            .get("wasi:http/handler@0.3.0")
            .and_then(|e| e.fingerprint.as_ref())
            .expect("middleware should have fingerprint");

        assert_ne!(
            chain_fp, mw_fp,
            "incompatible chain/middleware should have different fingerprints"
        );
    }

    /// Regression fixture for a cross-interface type-aliasing shape
    /// surfaced by the nebula `orders` demo composition. A service
    /// interface's instance type re-exports types from a sibling
    /// types-instance import via `(alias outer …) (export … (type
    /// (eq …)))` — this is what wit-component produces for WIT that
    /// uses `use other:pkg/types.{X}`.
    ///
    /// Expected behavior: cviz surfaces those re-exported names as
    /// `type_exports` of the service interface (so downstream
    /// consumers like splicer can locate the aliased component-type
    /// indices). Current behavior: cviz returns
    /// `type_exports: []`, and splicer's tier-1 adapter generator
    /// falls through to locally-redeclared records, producing a
    /// component that fails validation with
    /// `instance not valid to be used as export`.
    #[test]
    fn cross_interface_aliased_types_populate_type_exports() {
        // Outer component instantiates an inner component. The inner
        // imports a types instance (`my:core/types`) plus a service
        // interface whose instance type `alias outer`s the types
        // instance's exports — the shape `use my:core/types.{order,
        // quote}` compiles to.
        let wat = r#"(component
            (component $inner
                (import "my:core/types" (instance $types
                    (type (record (field "order-id" string)))
                    (export "order" (type (eq 0)))
                    (type (record (field "order-id" string) (field "amount" u32)))
                    (export "quote" (type (eq 2)))
                ))
                (alias export $types "order" (type $order))
                (alias export $types "quote" (type $quote))
                (import "my:service/orders" (instance $svc
                    (alias outer 1 $order (type (;0;)))
                    (export "order" (type (eq 0)))
                    (alias outer 1 $quote (type (;2;)))
                    (export "quote" (type (eq 2)))
                    (type (;4;) (func (param "o" 0) (result 2)))
                    (export "create-order" (func (type 4)))
                ))
                (alias export $svc "create-order" (func $f))
                (instance $out (export "create-order" (func $f)))
                (export "my:service/orders" (instance $out))
            )
            (import "my:core/types" (instance $host-types
                (type (record (field "order-id" string)))
                (export "order" (type (eq 0)))
                (type (record (field "order-id" string) (field "amount" u32)))
                (export "quote" (type (eq 2)))
            ))
            (alias export $host-types "order" (type $outer-order))
            (alias export $host-types "quote" (type $outer-quote))
            (import "my:service/orders" (instance $host-svc
                (alias outer 1 $outer-order (type (;0;)))
                (export "order" (type (eq 0)))
                (alias outer 1 $outer-quote (type (;2;)))
                (export "quote" (type (eq 2)))
                (type (;4;) (func (param "o" 0) (result 2)))
                (export "create-order" (func (type 4)))
            ))
            (instance $inst (instantiate $inner
                (with "my:core/types" (instance $host-types))
                (with "my:service/orders" (instance $host-svc))
            ))
            (alias export $inst "my:service/orders" (instance $out))
            (export "my:service/orders" (instance $out))
        )"#;
        let bytes = wat::parse_str(wat).expect("failed to parse WAT");
        let graph = parse_component(&bytes).expect("failed to parse component");

        let svc_conn = graph
            .nodes
            .values()
            .flat_map(|n| n.imports.iter())
            .find(|c| c.interface_name == "my:service/orders")
            .expect("expected some node to import my:service/orders");

        let inst = match &svc_conn.interface_type {
            Some(crate::model::InterfaceType::Instance(i)) => i,
            other => panic!("expected Instance interface_type, got {other:?}"),
        };

        assert!(
            inst.type_exports.contains_key("order"),
            "type_exports should include `order` (aliased from my:core/types \
             via (alias outer) + (export (type (eq …)))), but got: {:?}",
            inst.type_exports.keys().collect::<Vec<_>>()
        );
        assert!(
            inst.type_exports.contains_key("quote"),
            "type_exports should include `quote`, but got: {:?}",
            inst.type_exports.keys().collect::<Vec<_>>()
        );
    }
}