wasi_virt_layer-cli 0.10.0

CLI for the wasi_virt_layer crate
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
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
use std::{collections::HashMap, fs, io::Read as _, str::FromStr};

use camino::Utf8PathBuf;
use compact_str::{CompactString, ToCompactString as _};
use eyre::{Context as _, ContextCompat};
use itertools::Itertools;

use crate::{
    args::{self, TargetMemoryType},
    compile,
    config_checker::TomlRestorers,
    unique_name::{MemoryUniqueName, UniqueName},
    util::{CaminoUtilModule as _, WasmName, WasmNameHolder},
};

/// Represents the generation context, holding configuration arguments and targeted module info.
#[derive(Debug, Clone)]
pub struct GeneratorCtx {
    /// The name of the VFS module.
    pub vfs_name: WasmName,
    /// The names of the target modules.
    pub target_names: Box<[WasmName]>,
    /// Including one's own WASI ABI
    pub target_names_with_self: Box<[WasmName]>,

    /// The memory type of the target modules (Single or Multi).
    pub target_memory_type: TargetMemoryType,
    /// Whether to print unstable debug information.
    pub unstable_print_debug: bool,
    /// Whether to include DWARF debug information.
    pub dwarf: bool,
    /// Whether to enable multi-threading support.
    pub threads: bool,
    /// Whether to adjust the ABI for standard environments.
    pub adjust_abi: bool,
    /// Whether to keep intermediate build artifacts.
    pub keep_build_artifacts: bool,
    /// Whether the VFS module is a library (has no start section / `_start` export).
    /// Detected during `pre_vfs`; when `true`, the VFS start slot in the
    /// combined start chain is skipped entirely.
    pub vfs_is_library: bool,
    pub wrap_unreachable_targets: std::collections::HashSet<String>,
    pub main_void_synthesized_targets: Option<std::collections::HashSet<String>>,
    /// Whether own-memory mode is enabled.
    pub own_memory: bool,
    /// Whether atomic wait deadlock detection is enabled.
    pub detect_deadlock: bool,
    /// Export-stack isolation configuration keyed by module name.
    pub stack_config: StackConfig,
    /// Whether to validate generated Wasm modules.
    pub validate: bool,
}

/// Normalized export-stack isolation configuration.
#[derive(Debug, Clone, Default)]
pub struct StackConfig {
    /// Stack sizes in bytes. The `vfs` key aliases the actual VFS module name.
    pub sizes: HashMap<String, u32>,
    /// Fixed slot counts for multi-memory target modules.
    pub slots: HashMap<String, u32>,
}

impl StackConfig {
    fn from_options(options: args::StackOptions) -> eyre::Result<Self> {
        let mut config = Self::default();
        for size in options.sizes {
            if config
                .sizes
                .insert(size.module.clone(), size.bytes)
                .is_some()
            {
                eyre::bail!("duplicate --stack-size for module `{}`", size.module);
            }
        }
        for slots in options.slots {
            if config
                .slots
                .insert(slots.module.clone(), slots.slots)
                .is_some()
            {
                eyre::bail!("duplicate --stack-slots for module `{}`", slots.module);
            }
        }
        Ok(config)
    }

    /// Returns the configured VFS stack size.
    pub fn vfs_size(&self, vfs_name: &str) -> Option<u32> {
        self.sizes
            .get(vfs_name)
            .or_else(|| self.sizes.get("vfs"))
            .copied()
    }

    /// Returns the configured stack size for a target.
    pub fn target_size(&self, target_name: &str) -> Option<u32> {
        self.sizes.get(target_name).copied()
    }
}

/// Sub-context for extracting and storing component variables during execution.
#[derive(Debug, Default)]
pub struct ComponentCtx {
    /// Optional name of the VFS module.
    pub vfs_name: Option<compact_str::CompactString>,
    /// Optional names of the target modules.
    pub target_names: Option<Box<[compact_str::CompactString]>>,
    /// Optional memory type of the target modules.
    pub target_memory_type: Option<args::TargetMemoryType>,
    /// Optional flag for unstable debug printing.
    pub unstable_print_debug: Option<bool>,
    /// Flag for including DWARF debug information.
    pub dwarf: bool,
    /// Optional flag for multi-threading support.
    pub threads: Option<bool>,
    /// Flag for ABI adjustment.
    pub adjust_abi: bool,
    /// Flag for own-memory mode.
    pub own_memory: bool,
    /// Whether atomic wait deadlock detection is enabled.
    pub detect_deadlock: bool,
}

impl ComponentCtx {
    /// Creates a new `ComponentCtx` with the specified context parameters.
    pub fn new(
        vfs_name: compact_str::CompactString,
        target_names: Box<[compact_str::CompactString]>,
        target_memory_type: TargetMemoryType,
        unstable_print_debug: bool,
        dwarf: bool,
        threads: bool,
        adjust_abi: bool,
        own_memory: bool,
        detect_deadlock: bool,
    ) -> Self {
        Self {
            vfs_name: Some(vfs_name),
            target_names: Some(target_names),
            target_memory_type: Some(target_memory_type),
            unstable_print_debug: Some(unstable_print_debug),
            dwarf,
            threads: Some(threads),
            adjust_abi,
            own_memory,
            detect_deadlock,
        }
    }

    /// Returns the name of the VFS module.
    pub fn vfs_name(&self) -> &compact_str::CompactString {
        self.vfs_name.as_ref().unwrap()
    }

    /// Returns the names of the target modules.
    pub fn target_names(&self) -> &Box<[compact_str::CompactString]> {
        self.target_names.as_ref().unwrap()
    }

    /// Returns the memory type of the target modules.
    pub fn target_memory_type(&self) -> TargetMemoryType {
        self.target_memory_type.unwrap()
    }

    /// Returns whether to print unstable debug information.
    pub fn unstable_print_debug(&self) -> bool {
        self.unstable_print_debug.unwrap()
    }

    /// Returns whether to include DWARF debug information.
    pub fn dwarf(&self) -> bool {
        self.dwarf
    }

    /// Returns whether to enable multi-threading support.
    pub fn threads(&self) -> bool {
        self.threads.unwrap()
    }
}

/// Coordinates iterating over registered generators and merging external module logic into the VFS.
#[derive(Debug)]
pub struct GeneratorRunner {
    /// The context used during generation.
    pub ctx: GeneratorCtx,
    /// The path to the WASM module.
    pub path: WasmPath,
    /// The paths to the target WASM modules.
    pub targets: Box<[WasmPath]>,
    /// Options for building the VFS module.
    pub vfs_build_opts: args::VfsBuildOptions,
    /// Options for building the target WASM modules.
    pub target_vfs_build_opts: Box<[args::VfsBuildOptions]>,
    /// The TOML restorers used to reset configuration files.
    pub toml_restorers: Option<TomlRestorers>,
    /// Memory hints for the target modules.
    pub memory_hint: HashMap<WasmName, usize>,
    /// Holder for the names of the WASM modules.
    pub wasm_name_holder: WasmNameHolder,
}

/// A runner that coordinates the generation of a WebAssembly component.
#[derive(Debug)]
pub struct ComponentRunner {
    /// Encapsulates contextual settings across all generator components during transpilation.
    pub ctx: Option<ComponentCtx>,
    /// Specifies the target active WASM module destination.
    pub path: WasmPath,
    /// Manages dynamically generated and globally referenced named functions.
    pub wasm_name_holder: Option<WasmNameHolder>,
}

pub(crate) trait WrapRunner<T> {
    #[allow(unused_variables)]
    fn wrap_run(
        self,
        path: &mut WasmPath,
        dwarf: bool,
        keep_build_artifacts: bool,
        stream_pipeline: Option<crate::wasm_stream::pipeline::Pipeline>,
        validate: bool,
    ) -> eyre::Result<T>
    where
        Self: Sized;
}

impl<T, F: FnOnce() -> eyre::Result<T>> WrapRunner<T> for F {
    fn wrap_run(
        self,
        path: &mut WasmPath,
        _dwarf: bool,
        keep_build_artifacts: bool,
        mut stream_pipeline: Option<crate::wasm_stream::pipeline::Pipeline>,
        validate: bool,
    ) -> eyre::Result<T> {
        let old_path = path.path()?.clone();

        let result = (self)()?;

        if let Some(pipeline) = &mut stream_pipeline {
            let input_wasm = fs::read(&old_path).wrap_err("Failed to read Wasm file")?;
            let output_wasm = pipeline
                .run(&input_wasm)
                .wrap_err("Failed to run StreamPipeline pre-walrus")?;

            let new_path = old_path.with_extension("adjusted.wasm");

            if fs::metadata(&new_path).is_ok() {
                fs::remove_file(&new_path)
                    .wrap_err_with(|| format!("Failed to remove existing file {new_path}"))?;
            }

            std::fs::write(&new_path, &output_wasm)
                .wrap_err_with(|| format!("Failed to write adjusted Wasm to {new_path}"))?;

            if validate {
                wasmparser::Validator::new_with_features(wasmparser::WasmFeatures::all())
                    .validate_all(&output_wasm)
                    .wrap_err_with(|| format!("Wasm validation failed for {}", new_path))?;
            }

            if !keep_build_artifacts && !path.is_original(&old_path) {
                std::fs::remove_file(&old_path).unwrap_or_else(|e| {
                    log::warn!("Failed to remove intermediate file {old_path}: {e}")
                });
            }

            path.set_path(new_path)?;
        }

        Ok(result)
    }
}

pub(crate) trait EndWithOpt<T> {
    #[allow(unused_variables)]
    fn with_opt(
        self,
        path: &mut WasmPath,
        dwarf: bool,
        keep_build_artifacts: bool,
        skip_opt: bool,
        validate: bool,
    ) -> eyre::Result<T>
    where
        Self: Sized;

    #[allow(dead_code)]
    fn with_opt_args(
        self,
        path: &mut WasmPath,
        args: &[&str],
        require_update: bool,
        dwarf: bool,
        keep_build_artifacts: bool,
        skip_opt: bool,
        validate: bool,
    ) -> eyre::Result<T>
    where
        Self: Sized;
}

impl<T, F: FnOnce(&mut WasmPath) -> eyre::Result<T>> EndWithOpt<T> for F {
    fn with_opt(
        self,
        path: &mut WasmPath,
        dwarf: bool,
        keep_build_artifacts: bool,
        skip_opt: bool,
        validate: bool,
    ) -> eyre::Result<T>
    where
        Self: Sized,
    {
        let result = (self)(path).wrap_err("Failed to run with with_opt")?;

        if skip_opt {
            println!("Skipping Wasm optimization...");
            return Ok(result);
        }

        println!("Optimizing Wasm...");
        let old_path = path.path()?.clone();
        let new_path = compile::optimize_wasm(&old_path, &[], false, dwarf)
            .wrap_err("Failed to optimize Wasm")?;

        if validate {
            let optimized_wasm = std::fs::read(&new_path)
                .wrap_err_with(|| format!("Failed to read optimized Wasm from {new_path}"))?;
            wasmparser::Validator::new_with_features(wasmparser::WasmFeatures::all())
                .validate_all(&optimized_wasm)
                .wrap_err_with(|| format!("Wasm validation failed for {}", new_path))?;
        }

        if !keep_build_artifacts && old_path != new_path && !path.is_original(&old_path) {
            std::fs::remove_file(&old_path)
                .wrap_err_with(|| format!("Failed to remove existing file {old_path}"))?;
        }

        path.set_path(new_path)?;

        Ok(result)
    }

    fn with_opt_args(
        self,
        path: &mut WasmPath,
        args: &[&str],
        require_update: bool,
        dwarf: bool,
        keep_build_artifacts: bool,
        skip_opt: bool,
        validate: bool,
    ) -> eyre::Result<T>
    where
        Self: Sized,
    {
        let result = (self)(path).wrap_err("Failed to run with with_opt_args")?;

        if skip_opt {
            println!("Skipping Wasm optimization...");
            return Ok(result);
        }

        println!("Optimizing Wasm... with args: {}", args.iter().join(" "));
        let old_path = path.path()?.clone();
        let new_path = compile::optimize_wasm(&old_path, args, require_update, dwarf)
            .wrap_err("Failed to optimize Wasm")?;

        if validate {
            let optimized_wasm = std::fs::read(&new_path)
                .wrap_err_with(|| format!("Failed to read optimized Wasm from {new_path}"))?;
            wasmparser::Validator::new_with_features(wasmparser::WasmFeatures::all())
                .validate_all(&optimized_wasm)
                .wrap_err_with(|| format!("Wasm validation failed for {}", new_path))?;
        }

        if !keep_build_artifacts && old_path != new_path && !path.is_original(&old_path) {
            std::fs::remove_file(&old_path)
                .wrap_err_with(|| format!("Failed to remove existing file {old_path}"))?;
        }

        path.set_path(new_path)?;

        Ok(result)
    }
}

impl GeneratorRunner {
    /// Initializes a `GeneratorRunner` capturing all parameters needed for complete application-level transpilation mapping.
    pub fn new(
        path: WasmPath,
        targets: Box<[WasmPath]>,
        threads: bool,
        dwarf: bool,
        unstable_print_debug: bool,
        adjust_abi: bool,
        keep_build_artifacts: bool,
        memory_type: TargetMemoryType,
        vfs_build_opts: args::VfsBuildOptions,
        target_vfs_build_opts: Box<[args::VfsBuildOptions]>,
        toml_restorers: TomlRestorers,
        memory_hint: Box<[Option<usize>]>,
        own_memory: bool,
        detect_deadlock: bool,
        stack_options: args::StackOptions,
        validate: bool,
    ) -> eyre::Result<Self> {
        let target_names_with_self = core::iter::once(Ok(path.name()?.to_compact_string()))
            .chain(targets.iter().map(|t| Ok(t.name()?.to_compact_string())))
            .collect::<eyre::Result<Box<_>>>()?;

        let wasm_name_holder = WasmNameHolder::new(target_names_with_self);
        let mut wasm_name_holder_iter = wasm_name_holder.iter();
        let vfs_name = wasm_name_holder_iter
            .next()
            .ok_or_else(|| eyre::eyre!("Failed to get VFS name"))?;

        let target_names = wasm_name_holder_iter.collect::<Box<_>>();

        // log targeting info
        for name in target_names.iter() {
            log::info!("Targeting module: {name}");
        }
        log::info!("VFS module: {vfs_name}");

        let target_names_with_self = target_names
            .iter()
            .cloned()
            .chain(core::iter::once(vfs_name.clone()))
            .collect::<Box<_>>();

        let memory_hint = memory_hint
            .into_iter()
            .zip(target_names.iter().cloned())
            .filter_map(|(hint, name)| hint.map(|h| (name, h)))
            .collect::<HashMap<_, _>>();
        let stack_config = StackConfig::from_options(stack_options)?;

        if stack_config.slots.contains_key("vfs")
            || stack_config.slots.contains_key(vfs_name.as_ref())
        {
            eyre::bail!("--stack-slots is not valid for the VFS module");
        }
        if memory_type == TargetMemoryType::Single && !stack_config.slots.is_empty() {
            eyre::bail!("--stack-slots is only valid with multi-memory targets");
        }
        if memory_type == TargetMemoryType::Single
            && target_names
                .iter()
                .any(|name| stack_config.target_size(name.as_ref()).is_some())
            && stack_config.vfs_size(vfs_name.as_ref()).is_none()
        {
            eyre::bail!("single-memory target stack isolation requires --stack-size vfs=SIZE");
        }
        for module in stack_config.sizes.keys().chain(stack_config.slots.keys()) {
            if module != "vfs"
                && module != vfs_name.as_ref()
                && !target_names.iter().any(|name| name.as_ref() == module)
            {
                eyre::bail!("stack configuration names unknown module `{module}`");
            }
        }

        Ok(Self {
            ctx: GeneratorCtx {
                vfs_name,
                target_names,
                target_names_with_self,
                target_memory_type: memory_type,
                unstable_print_debug,
                dwarf,
                threads,
                adjust_abi,
                keep_build_artifacts,

                vfs_is_library: false,

                wrap_unreachable_targets: std::collections::HashSet::new(),
                main_void_synthesized_targets: None,
                own_memory,
                detect_deadlock,
                stack_config,
                validate,
            },
            path,
            targets,
            vfs_build_opts,
            target_vfs_build_opts,
            toml_restorers: Some(toml_restorers),
            memory_hint,
            wasm_name_holder,
        })
    }

    #[deprecated(
        note = "Ensure this function is self-contained. This is a temporary measure for debugging purposes."
    )]
    /// Provides direct immutable access tracking the primary target structural path configuration.
    pub const fn path(&self) -> &WasmPath {
        &self.path
    }

    #[deprecated(
        note = "Ensure this function is self-contained. This is a temporary measure for debugging purposes."
    )]
    /// Directly evaluates currently linked ancillary wasm dependencies.
    pub const fn targets(&self) -> &Box<[WasmPath]> {
        &self.targets
    }

    /// Securely uncovers operational variables tracking internal generational properties dynamically.
    pub const fn ctx(&self) -> &GeneratorCtx {
        &self.ctx
    }

    /// Confirms mapping configurations and statically evaluates lazy initializations strictly allocating paths.
    pub fn definitely(&mut self) -> eyre::Result<()> {
        self.path
            .definitely(self.ctx.threads, &self.vfs_build_opts)?;
        for (i, target) in self.targets.iter_mut().enumerate() {
            target.definitely(self.ctx.threads, &self.target_vfs_build_opts[i])?;
        }
        Ok(())
    }

    /// Primary operation chaining logic seamlessly running structural modifiers across all layered stages sequentially terminating out into WebAssembly components.
    pub fn run_layers_to_component(
        mut self,
        out_dir: &Utf8PathBuf,
        keep_build_artifacts: bool,
    ) -> eyre::Result<ComponentRunner> {
        self.definitely()?;

        let toml_restorers = self
            .toml_restorers
            .take()
            .ok_or_else(|| eyre::eyre!("TomlRestorers already taken"))?;

        toml_restorers
            .restore()
            .wrap_err("Failed to restore toml files")?;

        let dwarf = self.ctx.dwarf;
        let validate = self.ctx.validate;

        println!("Remove existing output directory...");
        if std::fs::metadata(&out_dir).is_ok() {
            std::fs::remove_dir_all(&out_dir).expect("Failed to remove existing directory");
        }
        std::fs::create_dir_all(&out_dir).expect("Failed to create output directory");

        println!("Adjusting VFS Wasm...");
        let skip_vfs_opt = self.vfs_build_opts.no_opt > 0 || self.vfs_build_opts.no_opt_all > 0;
        (|path: &mut WasmPath| {
            let wasm_bytes = std::fs::read(&path.path()?).unwrap();
            let mut vfs_is_library = true;
            let mut wrap_unreachable_targets = std::collections::HashSet::new();
            let mut detected_own_memory = self.ctx.own_memory;
            for payload in wasmparser::Parser::new(0).parse_all(&wasm_bytes) {
                if let Ok(wasmparser::Payload::StartSection { .. }) = payload {
                    vfs_is_library = false;
                }
                if let Ok(wasmparser::Payload::ExportSection(s)) = payload {
                    for e in s {
                        if let Ok(e) = e {
                            if e.name == "_start" {
                                vfs_is_library = false;
                            }
                            if crate::wasm_stream::own_memory_abi::is_own_memory_mode_export(e.name)
                            {
                                detected_own_memory = true;
                            }
                            for target in self.ctx.target_names.iter() {
                                let marker = format!(
                                    "__wasip1_virt_layer_{}_wrap_unreachable",
                                    target.as_ref()
                                );
                                if e.name == marker {
                                    wrap_unreachable_targets.insert(target.as_ref().to_string());
                                }
                            }
                        }
                    }
                }
            }
            self.ctx.vfs_is_library = vfs_is_library;
            self.ctx.wrap_unreachable_targets = wrap_unreachable_targets;
            self.ctx.own_memory = detected_own_memory;
            let pipeline_is_library = vfs_is_library;
            let cloned_ctx = self.ctx.clone();

            (|| {
                // Detect VFS library mode: if the VFS module has no start section,
                // it is a library and has no initialization entry point.
                if pipeline_is_library {
                    log::info!(
                        "VFS module `{}` has no start section — treating as a library.",
                        self.ctx.vfs_name
                    );
                }

                Ok(())
            })
            .wrap_run(
                path,
                dwarf,
                keep_build_artifacts,
                {
                    let mut pipeline = crate::wasm_stream::pipeline::Pipeline::new();
                    use crate::wasm_stream::passes::{
                        abi_connect::{
                            ConnectWasip1ABIPreVfsStreamPass, NonRecursiveWasiABIPreVfsStreamPass,
                        },
                        anonymous::AnonymousStreamPass,
                        check::CheckUseWasiVirtLayerChecker,
                        dummy_injector::DummyInjectorStreamPass,
                        export_stack::ExportStackPreVfsStreamPass,
                        patch_component::PatchComponentStreamPass,
                        pre_vfs_memory_refuge::TemporaryRefugeMemoryStreamPass,
                        starts_pre::StartsPreStreamPass,
                    };

                    let check_pass = crate::wasm_stream::pipeline::ParallelCheckStreamPass::new(
                        vec![Box::new(CheckUseWasiVirtLayerChecker::new())],
                    );
                    pipeline.add_pass(Box::new(check_pass));
                    pipeline.add_pass(Box::new(AnonymousStreamPass::new(cloned_ctx.clone())));
                    pipeline.add_pass(Box::new(ConnectWasip1ABIPreVfsStreamPass::new()));
                    pipeline.add_pass(Box::new(
                    crate::wasm_stream::passes::threads_spawn::ThreadsSpawnPreVfsStreamPass::new(
                        cloned_ctx.threads,
                    ),
                ));
                    pipeline.add_pass(Box::new(NonRecursiveWasiABIPreVfsStreamPass::new()));
                    pipeline.add_pass(Box::new(PatchComponentStreamPass::new()));

                    let fn_in_starts =
                        crate::wasm_stream::passes::fn_in_starts::FnInStarts::new::<String>(&[]);
                    pipeline.add_pass(Box::new(
                        StartsPreStreamPass::new(
                            true,
                            pipeline_is_library,
                            fn_in_starts.flesh_vfs_start.clone(),
                        )
                        .with_reactor_folding(cloned_ctx.threads),
                    ));
                    pipeline.add_pass(Box::new(ExportStackPreVfsStreamPass::new(
                        cloned_ctx
                            .stack_config
                            .vfs_size(cloned_ctx.vfs_name.as_ref()),
                    )));
                    pipeline.add_pass(Box::new(DummyInjectorStreamPass::new(vec![
                        fn_in_starts.init_offset_global.clone(),
                        fn_in_starts.save_target_memory.clone(),
                        fn_in_starts.simple_debug_pre_init.clone(),
                    ])));
                    pipeline.add_pass(Box::new(TemporaryRefugeMemoryStreamPass::new(None)));
                    Some(pipeline)
                },
                cloned_ctx.validate,
            )
        })
        .with_opt(
            &mut self.path,
            dwarf,
            keep_build_artifacts,
            skip_vfs_opt,
            validate,
        )?;

        println!("Adjusting target Wasm...");

        for (i, (target, target_name)) in self
            .targets
            .iter_mut()
            .zip(self.ctx.target_names.clone())
            .enumerate()
        {
            let skip_target_opt = self.vfs_build_opts.no_opt_all > 0
                || self.target_vfs_build_opts[i].no_opt > 0
                || self.target_vfs_build_opts[i].no_opt_all > 0;
            let _cloned_ctx = self.ctx.clone();
            let is_synthesized = std::sync::Arc::new(std::sync::Mutex::new(false));
            (|path: &mut WasmPath| {
                (|| {
                    Ok(())
                })
                .wrap_run(path, dwarf, keep_build_artifacts, {
                    let mut pipeline = crate::wasm_stream::pipeline::Pipeline::new();
                    use crate::wasm_stream::passes::{
                        abi_connect::{
                            ConnectWasip1ABIPreTargetStreamPass,
                            ConnectWasip1ThreadsABIPreTargetStreamPass,
                        },
                        check::IsRustWasmChecker,
                        dummy_injector::DummyInjectorStreamPass,
                        pre_vfs_memory_refuge::TemporaryRefugeMemoryStreamPass,
                        producer::ProducerStreamPass,
                        starts_pre::StartsPreStreamPass,
                        special_func::SpecialFuncPreTargetStreamPass,
                        wrap_unreachable::WrapUnreachablePreTargetStreamPass,
                        atomic_patch::AtomicPatchStreamPass,
                        export_stack::ExportStackPreTargetStreamPass,
                    };

                    pipeline.add_pass(Box::new(ProducerStreamPass::new()));
                    pipeline.add_pass(Box::new(SpecialFuncPreTargetStreamPass::new(
                        target_name.to_string(),
                        is_synthesized.clone(),
                    )));

                    let is_opted_in = _cloned_ctx.wrap_unreachable_targets.contains(&target_name.to_string());
                    pipeline.add_pass(Box::new(WrapUnreachablePreTargetStreamPass::new(
                        target_name.to_string(),
                        is_opted_in,
                    )));
                    pipeline.add_pass(Box::new(
                        crate::wasm_stream::passes::deadlock_thread_id::DeadlockThreadIdPreTargetStreamPass::for_target(
                            _cloned_ctx.detect_deadlock,
                            target_name.to_string(),
                        ),
                    ));

                    if _cloned_ctx.target_memory_type == TargetMemoryType::Single {
                        pipeline.add_pass(Box::new(ExportStackPreTargetStreamPass::new(
                            target_name.to_string(),
                            crate::unique_name::UniqueName::WASIP1_ABI_MODULE.to_string(),
                            i as u32,
                            _cloned_ctx.stack_config.target_size(target_name.as_ref()),
                        )));
                    } else if let (Some(size), Some(slots)) = (
                        _cloned_ctx.stack_config.target_size(target_name.as_ref()),
                        _cloned_ctx.stack_config.slots.get(target_name.as_ref()).copied(),
                    ) {
                        if slots > 0 {
                            let arena_pass = crate::wasm_stream::passes::export_stack_arena::ExportStackArenaStreamPass::new(size, slots);
                            let arena_size = arena_pass.arena_offset() as u32;
                            pipeline.add_pass(Box::new(arena_pass));
                            pipeline.add_pass(Box::new(
                                crate::wasm_stream::passes::export_stack_multi_memory_target::ExportStackMultiMemoryTargetStreamPass::new(
                                    target_name.to_string(),
                                    crate::unique_name::UniqueName::WASIP1_ABI_MODULE.to_string(),
                                    arena_size,
                                    size,
                                ),
                            ));
                        }
                    }

                    pipeline.add_pass(Box::new(ConnectWasip1ABIPreTargetStreamPass::new(
                        target_name.to_string(),
                    )));
                    pipeline.add_pass(Box::new(ConnectWasip1ThreadsABIPreTargetStreamPass::new(
                        target_name.to_string(),
                    )));
                    pipeline.add_pass(Box::new(crate::wasm_stream::passes::threads_spawn::ThreadsSpawnPreTargetStreamPass::new(
                        _cloned_ctx.threads,
                        target_name.to_string(),
                    )));
                    pipeline.add_pass(Box::new(AtomicPatchStreamPass::new(
                        _cloned_ctx.threads,
                        i as u32,
                        _cloned_ctx.detect_deadlock,
                    )));

                    let check_pass = crate::wasm_stream::pipeline::ParallelCheckStreamPass::new(
                        vec![Box::new(IsRustWasmChecker::new())],
                    );
                    pipeline.add_pass(Box::new(check_pass));

                    let export_name = format!("__flesh_{}_start", target_name);
                    let thread_start_export_name =
                        format!("__wasip1_vfs_{}__thread_start", target_name);
                    pipeline.add_pass(Box::new(
                        StartsPreStreamPass::new(false, false, export_name.clone())
                            .with_thread_start_export_name(thread_start_export_name),
                    ));
                    pipeline.add_pass(Box::new(DummyInjectorStreamPass::new(vec![export_name])));
                    let new_memory_name =
                        crate::generator::UniqueName::Memory(&MemoryUniqueName::Memory(
                            &target_name,
                        ))
                        .to_string();
                    pipeline.add_pass(Box::new(TemporaryRefugeMemoryStreamPass::new(Some(
                        new_memory_name,
                    ))));

                    Some(pipeline)
                }, _cloned_ctx.validate)
            })
            .with_opt(target, dwarf, keep_build_artifacts, skip_target_opt, validate)?;

            if *is_synthesized.lock().unwrap() {
                self.ctx
                    .main_void_synthesized_targets
                    .get_or_insert_default()
                    .insert(target_name.to_string());
            }
        }

        let skip_all_opt = self.vfs_build_opts.no_opt_all > 0
            || self
                .target_vfs_build_opts
                .iter()
                .any(|opts| opts.no_opt_all > 0);

        println!("Combining Wasm modules...");

        let output = format!("{out_dir}/merged.wasm");
        let mut defined_funcs_counts = Vec::new();
        (|path: &mut WasmPath| {
            let old_path = path.path()?.clone();
            defined_funcs_counts.push(count_defined_funcs(&old_path)?);
            for target in self.targets.iter() {
                defined_funcs_counts.push(count_defined_funcs(target.path()?)?);
            }
            merge(
                &old_path,
                &self
                    .targets
                    .iter()
                    .map(|t| t.path())
                    .collect::<eyre::Result<Vec<_>>>()?,
                &output,
                self.ctx.threads,
                dwarf,
            )
            .wrap_err("Failed to combine Wasm modules")?;

            if !keep_build_artifacts {
                std::fs::remove_file(&old_path)
                    .wrap_err_with(|| format!("Failed to remove existing file {old_path}"))?;
                for target in self.targets.iter() {
                    if let Ok(target_path) = target.path() {
                        if !target.is_original(target_path) {
                            std::fs::remove_file(target_path).unwrap_or_else(|e| {
                                log::warn!(
                                    "Failed to remove intermediate target file {target_path}: {e}"
                                );
                            });
                        }
                    }
                }
            }

            path.set_path(output.into())
        })
        .with_opt(
            &mut self.path,
            dwarf,
            keep_build_artifacts,
            skip_all_opt,
            validate,
        )?;

        println!("Adjusting Merged Wasm (streaming pipeline)...");

        (|path: &mut WasmPath| {
            let old_path = path.path()?.clone();
            let input_wasm = std::fs::read(&old_path).wrap_err("Failed to read Wasm file")?;

            let mut pipeline = crate::wasm_stream::pipeline::Pipeline::new();
            let target_names: Vec<String> = self.ctx.target_names.iter().map(|n| n.as_ref().to_string()).collect();

            let vfs_name = self.ctx.vfs_name.as_ref().to_string();
            pipeline.add_pass(Box::new(
                crate::wasm_stream::passes::post_combine::PostCombineStreamPass::new(
                    vfs_name,
                    target_names.clone(),
                    defined_funcs_counts.clone(),
                    self.ctx.threads,
                )
            ));

            if self.ctx.target_memory_type == TargetMemoryType::Single {
                println!("Generating single memory Merged Wasm (streaming lowering)...");
                pipeline.add_pass(Box::new(
                    crate::wasm_stream::passes::multi_memory_lowering::MultiMemoryLoweringStreamPass::new(self.ctx.threads, self.ctx.own_memory, target_names.clone(), true)
                ));
                pipeline.add_pass(Box::new(
                    crate::wasm_stream::passes::shared_global::SharedGlobalStreamPass::new(self.ctx.threads, self.ctx.own_memory, target_names)
                ));
            } else if self.ctx.own_memory {
                println!("Adjusting own memory for Multi Memory Merged Wasm (streaming lowering)...");
                pipeline.add_pass(Box::new(
                    crate::wasm_stream::passes::multi_memory_lowering::MultiMemoryLoweringStreamPass::new(self.ctx.threads, self.ctx.own_memory, target_names.clone(), false)
                ));
            }

            let output_wasm = pipeline
                .run(&input_wasm)
                .wrap_err("Failed to run StreamPipeline")?;

            let new_path = old_path.with_extension("lowered.wasm");
            std::fs::write(&new_path, &output_wasm).wrap_err("Failed to write lowered Wasm file")?;

            if self.ctx.validate {
                wasmparser::Validator::new_with_features(wasmparser::WasmFeatures::all())
                    .validate_all(&output_wasm)
                    .wrap_err_with(|| format!("Wasm validation failed for {}", new_path))?;
            }

            if !keep_build_artifacts {
                std::fs::remove_file(&old_path).wrap_err_with(|| format!("Failed to remove existing file {old_path}"))?;
            }

            path.set_path(new_path)?;
            Ok(())
        }).with_opt(&mut self.path, dwarf, keep_build_artifacts, skip_all_opt, validate)?;

        println!("Translating Wasm to Component...");
        let old_path = self.path.path()?.clone();
        let component = compile::wasm_to_component(&old_path, &self.ctx.target_names)
            .wrap_err("Failed to translate Wasm to Component")?;
        let new_component = format!("{out_dir}/{}.component.wasm", self.ctx.vfs_name);
        let component_bytes = std::fs::read(&component)?;
        let component_bytes_with_ctx =
            crate::wasm_stream::passes::component_ctx::append_component_ctx(
                &component_bytes,
                &self.ctx,
            )?;
        std::fs::write(&new_component, &component_bytes_with_ctx)?;

        if self.ctx.validate {
            wasmparser::Validator::new_with_features(wasmparser::WasmFeatures::all())
                .validate_all(&component_bytes_with_ctx)
                .wrap_err_with(|| format!("Wasm validation failed for {}", new_component))?;
        }

        if !keep_build_artifacts {
            std::fs::remove_file(&component)
                .wrap_err_with(|| format!("Failed to remove existing file {component}"))?;
            std::fs::remove_file(&old_path)
                .wrap_err_with(|| format!("Failed to remove existing file {old_path}"))?;
        }

        self.path.set_path(Utf8PathBuf::from(new_component))?;

        Ok(ComponentRunner {
            ctx: None,
            path: self.path,
            wasm_name_holder: None,
        })
    }
}

impl ComponentRunner {
    /// Instantiates a fresh `ComponentRunner` targeting a specific underlying WebAssembly structure.
    pub fn new(path: WasmPath) -> Self {
        Self {
            ctx: None,
            path,
            wasm_name_holder: None,
        }
    }

    /// return is_threads, core_name, mem_size
    pub fn component_to_files(
        &mut self,
        parsed_args: &(impl args::PostBuildContext + ?Sized),
        dwarf: bool,
        only_core: bool,
    ) -> eyre::Result<(bool, CompactString, HashMap<CompactString, (u64, u64)>)> {
        let out_dir = parsed_args.out_dir();

        let name = self.path.name()?;

        println!("Translating Component to JS...");
        let component_bytes = std::fs::read(&self.path.path()?)?;
        self.ctx =
            Some(crate::wasm_stream::passes::component_ctx::read_component_ctx(&component_bytes)?);

        let core_wasm_path = (|path: &mut WasmPath| {
            let old_path = path.path()?.clone();
            let binary = std::fs::read(&old_path).wrap_err("Failed to read component")?;
            let transpiled = parsed_args
                .transpile_to_js(&binary, &name)
                .wrap_err("Failed to transpile to JS")?;

            let mut core_wasm = None;
            for (name, data) in transpiled.files.iter() {
                let name = camino::Utf8PathBuf::from(name);
                let file_name = out_dir.join(&name);
                if std::fs::metadata(&file_name).is_ok() {
                    std::fs::remove_file(&file_name).wrap_err_with(|| {
                        eyre::eyre!("Failed to remove existing file: {file_name}")
                    })?;
                }
                if name.as_str().ends_with(".core.wasm") {
                    let file_name = camino::Utf8PathBuf::from(file_name);
                    std::fs::write(&file_name, &data).wrap_err_with(|| {
                        eyre::eyre!("Failed to write core wasm file: {file_name}")
                    })?;
                    core_wasm = Some(file_name);
                } else {
                    if let Some(parent) = name.parent() {
                        if !parent.as_str().is_empty() {
                            let dir = name.ancestors().nth(1).wrap_err_with(|| {
                                eyre::eyre!("Failed to get parent directory: {}", name)
                            })?;
                            let joined_dir = out_dir.join(dir);
                            if !std::fs::metadata(&joined_dir).is_ok() {
                                if dir.as_str() != "interfaces" {
                                    log::warn!("Creating directory: {joined_dir}");
                                }
                                if only_core {
                                    continue;
                                }
                                std::fs::create_dir_all(&joined_dir).wrap_err_with(|| {
                                    eyre::eyre!("Failed to create directory: {joined_dir}")
                                })?;
                            }
                        }
                    }
                    if only_core {
                        continue;
                    }
                    std::fs::write(&file_name, &data).wrap_err_with(|| {
                        eyre::eyre!("Failed to write transpiled file: {file_name}")
                    })?;
                }
            }

            let core_wasm = core_wasm
                .as_ref()
                .ok_or_else(|| eyre::eyre!("Failed to find core wasm"))?;

            if !parsed_args.keep_build_artifacts() {
                std::fs::remove_file(&old_path)
                    .wrap_err_with(|| format!("Failed to remove existing file {old_path}"))?;
            }
            path.set_path(core_wasm.clone())?;

            Ok(core_wasm.clone())
        })
        .with_opt(
            &mut self.path,
            dwarf,
            parsed_args.keep_build_artifacts(),
            parsed_args.dev(),
            parsed_args.validate(),
        )?;

        let mem_sizes = {
            let wasm_bytes =
                std::fs::read(&self.path.path()?).wrap_err("Failed to read core wasm")?;
            crate::wasm_stream::passes::extract_mem_sizes::extract_memory_sizes(&wasm_bytes)?
        };

        println!("Adjusting component Merged Wasm...");
        (|path: &mut WasmPath| {
            let old_path = path.path()?.clone();
            let input_wasm = std::fs::read(&old_path).wrap_err("Failed to read Wasm file")?;

            let mut pipeline = crate::wasm_stream::pipeline::Pipeline::new();

            pipeline.add_pass(Box::new(
                crate::wasm_stream::passes::memory_post_components::PostComponentsMemoryFixStreamPass::new(self.ctx.as_ref().unwrap().threads.unwrap_or(false))
            ));

            let output_wasm = pipeline
                .run(&input_wasm)
                .wrap_err("Failed to run StreamPipeline")?;
            let new_path = old_path.with_extension("post-comp-stream.wasm");
            std::fs::write(&new_path, &output_wasm).wrap_err("Failed to write Wasm file")?;

            if parsed_args.validate() {
                wasmparser::Validator::new_with_features(wasmparser::WasmFeatures::all())
                    .validate_all(&output_wasm)
                    .wrap_err_with(|| format!("Wasm validation failed for {}", new_path))?;
            }

            if !parsed_args.keep_build_artifacts() {
                std::fs::remove_file(&old_path).unwrap_or_default();
            }
            path.set_path(new_path)?;

            Ok(())
        })
        .with_opt(
            &mut self.path,
            dwarf,
            parsed_args.keep_build_artifacts(),
            parsed_args.dev(),
            parsed_args.validate(),
        )?;

        let _dwarf = {
            let new_dwarf = self.ctx.as_ref().unwrap().dwarf;
            if dwarf && !new_dwarf {
                log::warn!(
                    "Dwarf was disabled in component processing, you should re-run with --dwarf"
                );
            }
            new_dwarf
        };

        // Keep the optimizer anchor through componentization and every core
        // optimization, then remove only its export from the published core.
        let final_core =
            crate::wasm_stream::passes::reactor_opt::finish(&std::fs::read(self.path.path()?)?)?;
        std::fs::write(self.path.path()?, final_core)?;
        std::fs::rename(self.path.path()?, &core_wasm_path).wrap_err_with(|| {
            eyre::eyre!(
                "Failed to rename final wasm from {} to {}",
                self.path.path().unwrap(),
                core_wasm_path
            )
        })?;

        Ok((
            self.ctx.as_ref().unwrap().threads.unwrap_or(false),
            core_wasm_path
                .get_file_main_name()
                .ok_or_else(|| eyre::eyre!("Failed to get file name"))?,
            mem_sizes,
        ))
    }
}

/// Represents the resolution state and file format targeting for manipulating WebAssembly modules intelligently.
#[derive(Debug, Clone, Hash)]
pub enum WasmPath {
    /// Indicates the target still needs compilation through standard cargo dependencies.
    Maybe {
        /// Fully resolved physical path to the corresponding Cargo.toml manifest definition.
        manifest_path: Utf8PathBuf,
        /// Specified internal crate package identifier.
        package: String,
    },
    /// A strictly resolved raw WebAssembly binary file ready for patching operations.
    Definitely(Utf8PathBuf),
    /// A completed explicitly transpiled WebAssembly Component standard architecture module.
    Component(Utf8PathBuf),
    /// A user-provided raw WebAssembly binary file that should never be deleted.
    /// The inner path tracks the original file location.
    Original {
        /// The current working path (may change as transformations produce new files).
        current: Utf8PathBuf,
        /// The original user-provided path that must be preserved.
        original: Utf8PathBuf,
    },
}

impl FromStr for WasmPath {
    type Err = eyre::Error;

    /// manifest_path :: package
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        fn parse_path_and_package(s: &str) -> eyre::Result<Option<WasmPath>> {
            let split = s.split("::").collect::<Vec<_>>();
            if split.len() == 2 {
                let manifest_path = Utf8PathBuf::from_str(split[0])
                    .wrap_err_with(|| format!("Failed to parse manifest path: {}", split[0]))?;
                let package = split[1].to_string();
                return Ok(Some(WasmPath::Maybe {
                    manifest_path,
                    package,
                }));
            }
            Ok(None)
        }

        if let Some(wasm_path) =
            parse_path_and_package(s).wrap_err("Failed to parse path and package")?
        {
            return Ok(wasm_path);
        }

        if s.ends_with(".wasm") {
            let path = Utf8PathBuf::from_str(s)
                .wrap_err_with(|| format!("Failed to parse wasm path: {s}"))?;
            return WasmPath::with_wasm(path);
        }

        if s.ends_with("Cargo.toml") {
            let manifest_path = Utf8PathBuf::from_str(s)
                .wrap_err_with(|| format!("Failed to parse manifest path: {s}"))?;
            return WasmPath::with_maybe_only_manifest(manifest_path);
        }

        WasmPath::with_maybe_only_package(s.to_string())
            .wrap_err_with(|| format!("Failed to parse package name: {s}"))
    }
}

impl WasmPath {
    /// Computes the unique short name used during module linking and identification.
    pub fn name(&self) -> eyre::Result<CompactString> {
        match self {
            WasmPath::Maybe { package, .. } => {
                // Normalize package name by replacing hyphens with underscores
                // This is necessary because Rust package names can have hyphens (e.g., "test-package")
                // but they are converted to underscores in module identifiers (e.g., "test_package")
                let normalized = package.replace('-', "_");
                Ok(normalized.to_compact_string())
            }
            WasmPath::Definitely(path)
            | WasmPath::Component(path)
            | WasmPath::Original { current: path, .. } => path
                .get_file_main_name()
                .ok_or_else(|| eyre::eyre!("Failed to get file name from {path}")),
        }
    }

    /// Exposes the manifest path conditionally if the dependency is unresolved logically.
    pub fn manifest_path(&self) -> Option<&Utf8PathBuf> {
        match self {
            WasmPath::Maybe { manifest_path, .. } => Some(manifest_path),
            WasmPath::Definitely(_) | WasmPath::Component(_) | WasmPath::Original { .. } => None,
        }
    }

    /// Calculates the overarching workspace root via dependency graphing context implicitly.
    pub fn root_manifest_path(&self) -> Option<Utf8PathBuf> {
        match self {
            WasmPath::Maybe { manifest_path, .. } => {
                let cargo_metadata = {
                    let mut metadata_command = cargo_metadata::MetadataCommand::new();
                    metadata_command.manifest_path(&manifest_path);
                    metadata_command.exec().unwrap()
                };
                Some(cargo_metadata.workspace_root.join("Cargo.toml"))
            }
            WasmPath::Definitely(_) | WasmPath::Component(_) | WasmPath::Original { .. } => None,
        }
    }

    /// Statically assigns an unresolved target using defined package specifications.
    pub const fn with_maybe(manifest_path: Utf8PathBuf, package: String) -> Self {
        Self::Maybe {
            manifest_path,
            package,
        }
    }

    /// Constructs an unresolved dependency resolving package tracking inherently from a file manifest dynamically.
    pub fn with_maybe_only_manifest(manifest_path: Utf8PathBuf) -> eyre::Result<Self> {
        let cargo_metadata = {
            let mut metadata_command = cargo_metadata::MetadataCommand::new();
            metadata_command.manifest_path(&manifest_path);
            metadata_command.exec().unwrap()
        };
        let building_crate = compile::get_building_crate(&cargo_metadata, &None)?;

        Ok(Self::Maybe {
            manifest_path,
            package: building_crate.name.to_string(),
        })
    }

    /// Assesses global cargo metadata configuring definitions matching solely the provided string identifier.
    pub fn with_maybe_only_package(package: String) -> eyre::Result<Self> {
        let cargo_metadata = {
            let metadata_command = cargo_metadata::MetadataCommand::new();
            metadata_command.exec().unwrap()
        };
        let building_crate = compile::get_building_crate(&cargo_metadata, &Some(package.clone()))?;

        Ok(Self::Maybe {
            manifest_path: building_crate.manifest_path,
            package: building_crate.name.to_string(),
        })
    }

    /// Loads an unresolved dependency using current environment cargo bounds natively.
    pub fn with_maybe_none() -> eyre::Result<Self> {
        let cargo_metadata = {
            let metadata_command = cargo_metadata::MetadataCommand::new();
            metadata_command.exec().unwrap()
        };
        let building_crate = compile::get_building_crate(&cargo_metadata, &None)?;

        Ok(Self::Maybe {
            manifest_path: building_crate.manifest_path,
            package: building_crate.name.to_string(),
        })
    }

    /// Scans an exact provided `.wasm` artifact verifying magic byte signatures correctly to assign a resolution state.
    /// User-provided `.wasm` files are wrapped in `Original` to prevent deletion of the original file.
    pub fn with_wasm(path: Utf8PathBuf) -> eyre::Result<Self> {
        if path.extension() != Some("wasm") {
            eyre::bail!("Wasm file does not have .wasm extension: {path}");
        }
        if !fs::metadata(&path).is_ok() {
            // Assume it's an original Wasm file even if it doesn't exist yet
            return Ok(Self::Original {
                current: path.clone(),
                original: path,
            });
        }

        let mut file =
            fs::File::open(&path).wrap_err_with(|| format!("Failed to open wasm file: {path}"))?;
        let mut magic = [0u8; 8];
        file.read_exact(&mut magic)
            .wrap_err_with(|| format!("Failed to read magic number from wasm file: {path}"))?;
        if !magic.starts_with(b"\0asm") {
            eyre::bail!("Wasm file does not have valid magic number: {path}");
        }
        let version = &magic[4..8];
        // https://github.com/WebAssembly/component-model/blob/main/design/mvp/Binary.md#component-definitions
        if version == [0x0D, 0x00, 0x01, 0x00] {
            return Ok(Self::Component(path));
        }
        // https://webassembly.github.io/spec/core/binary/modules.html#binary-module
        if version != [0x01, 0x00, 0x00, 0x00] {
            eyre::bail!("Wasm file does not have valid version: {path}");
        }

        Ok(Self::Original {
            current: path.clone(),
            original: path,
        })
    }

    /// Forcefully invokes internal compiling mechanisms translating a declarative specification down into an executable binary structurally.
    pub fn definitely(
        &mut self,
        threads: bool,
        vfs_build_opts: &args::VfsBuildOptions,
    ) -> eyre::Result<()> {
        if let WasmPath::Maybe {
            manifest_path,
            package,
        } = self
        {
            let cargo_metadata = {
                let mut metadata_command = cargo_metadata::MetadataCommand::new();
                metadata_command.manifest_path(&manifest_path);
                metadata_command.exec().unwrap()
            };
            let building_crate =
                compile::get_building_crate(&cargo_metadata, &Some(package.clone()))?;
            let vfs_name = building_crate.name.to_string();

            let path = compile::build_vfs(
                Some(&manifest_path.to_string()),
                &building_crate,
                threads,
                vfs_build_opts,
            )
            .wrap_err_with(|| eyre::eyre!("Failed to build VFS: {vfs_name}"))?;
            *self = WasmPath::Definitely(path);
        }

        // Original variant is already resolved, no action needed.

        Ok(())
    }

    /// Returns the path to the WASM module.
    pub fn path(&self) -> eyre::Result<&Utf8PathBuf> {
        match self {
            WasmPath::Maybe { .. } => {
                return Err(eyre::eyre!("WasmPath is not definitely set: {self:?}"));
            }
            WasmPath::Definitely(p)
            | WasmPath::Component(p)
            | WasmPath::Original { current: p, .. } => Ok(p),
        }
    }

    /// Returns `true` if the given path is the original user-provided file that should be preserved.
    pub fn is_original(&self, path: &Utf8PathBuf) -> bool {
        matches!(self, WasmPath::Original { original, .. } if original == path)
    }

    /// Forcefully overrides the explicitly resolved file path for definite path targets.
    /// For `Original` variants, preserves the original path tracking.
    pub fn set_path(&mut self, path: Utf8PathBuf) -> eyre::Result<()> {
        match self {
            WasmPath::Maybe { .. } => {
                return Err(eyre::eyre!("WasmPath is not definitely set: {path}"));
            }
            WasmPath::Original { current, .. } => {
                // Keep the original path, only update current
                *current = path;
            }
            _ => {
                *self = WasmPath::Definitely(path);
            }
        }
        Ok(())
    }
}

/// Combines prepared VFS and target modules into one core Wasm module.
fn count_defined_funcs(wasm_path: &camino::Utf8PathBuf) -> eyre::Result<u32> {
    let wasm = std::fs::read(wasm_path)?;
    for payload in wasmparser::Parser::new(0).parse_all(&wasm) {
        let payload = payload.map_err(|e| eyre::eyre!("Parse error: {}", e))?;
        if let wasmparser::Payload::FunctionSection(s) = payload {
            return Ok(s.count());
        }
    }
    Ok(0)
}

pub fn merge(
    vfs: &Utf8PathBuf,
    wasm: &[impl AsRef<std::path::Path>],
    output: impl AsRef<std::path::Path>,
    _threads: bool,
    dwarf: bool,
) -> eyre::Result<()> {
    let mut inputs = Vec::with_capacity(wasm.len() + 1);
    inputs.push(crate::wasm_stream::merge::MergeInput {
        alias: UniqueName::WASIP1_ABI_MODULE.to_string(),
        path: vfs.as_std_path(),
    });
    for wasm in wasm {
        inputs.push(crate::wasm_stream::merge::MergeInput {
            alias: format!(
                "wasip1_vfs_{}",
                wasm.as_ref()
                    .get_file_main_name()
                    .ok_or_else(|| eyre::eyre!("Failed to get Wasm module name"))?
            ),
            path: wasm.as_ref(),
        });
    }
    crate::wasm_stream::merge::merge_modules(&inputs, output, dwarf)
}

macro_rules! _add_generators_by_type {
    ($runner:expr, $($ty:ty),* $(,)?) => {
        $(
            if let Some(_) = $runner.get_generator_ref::<$ty>().ok() {
                panic!("Generator of type {} already exists", std::any::type_name::<$ty>());
            }
            $runner.add_generator(<$ty>::default());
        )*
    };
}