Skip to main content

wasi_virt_layer_cli/
args.rs

1use std::collections::HashMap;
2
3use camino::Utf8PathBuf;
4use clap::{Parser, Subcommand};
5use compact_str::CompactString;
6use eyre::Context as _;
7
8use crate::{generator::WasmPath, util::ResultUtil as _};
9
10/// Common interface for post-build (transpilation) arguments.
11pub trait PostBuildContext {
12    /// Returns the output directory path.
13    fn out_dir(&self) -> &Utf8PathBuf;
14    /// Returns whether to keep intermediate build artifacts.
15    fn keep_build_artifacts(&self) -> bool;
16    /// Returns whether to adjust the ABI.
17    fn adjust_abi(&self) -> bool;
18    /// Transpiles the given WebAssembly component into JavaScript source files.
19    fn transpile_to_js(
20        &self,
21        component: &[u8],
22        name: impl AsRef<str>,
23    ) -> Result<js_component_bindgen::Transpiled, eyre::Error>;
24}
25
26/// The main command-line interface for `wasi_virt_layer-cli`.
27#[derive(Parser, Debug)]
28#[clap(author, version, about, long_about = None)]
29#[clap(propagate_version = true)]
30pub struct Cli {
31    /// The command to execute.
32    #[clap(subcommand)]
33    pub command: Command,
34}
35
36#[derive(Subcommand, Debug)]
37/// Supported subcommands for the CLI.
38pub enum Command {
39    /// Builds a virtualized WASM module (prebuild + postbuild combined).
40    Build(BuildArgs),
41    /// Generates a Component WASM from VFS and target WASM modules.
42    Prebuild(PreBuildArgs),
43    /// Transpiles a Component WASM into JavaScript files.
44    Postbuild(PostBuildArgs),
45    /// Initializes a new WASI Virt Layer project.
46    New(NewArgs),
47}
48
49#[derive(Parser, Debug)]
50/// Arguments for the `new` command.
51pub struct NewArgs {
52    /// The path where the new project will be created.
53    #[arg(value_name = "PATH")]
54    pub path: Utf8PathBuf,
55
56    /// Whether to enable multi-threading support in the new project.
57    #[arg(long, default_value = "false")]
58    pub threads: bool,
59}
60
61#[derive(Parser, Debug)]
62/// Arguments for the `build` command.
63pub struct BuildArgs {
64    /// Path to the wasip1 wasm file
65    /// This allow 4 patterns:
66    /// 1. only manifest path, like `./Cargo.toml` or `./some/dir/Cargo.toml`
67    /// 2. only package name, like `my_package`
68    /// 3. manifest path and package name, like `./Cargo.toml::my_package` or `./some/dir/Cargo.toml::my_package`
69    /// 4. direct path to wasm file, like `./target/wasm32-wasi/release/my_crate.wasm`
70    pub wasm: Vec<WasmPath>,
71
72    /// Path to the primary package; used for single-package mode or component translation.
73    #[arg(short, long)]
74    package: Option<WasmPath>,
75
76    /// Memory hints for the WASM files, used if automatic detection fails.
77    #[arg(long)]
78    wasm_memory_hint: Vec<isize>,
79
80    /// Output directory for the generated files
81    #[arg(long, default_value = "./dist")]
82    pub out_dir: Utf8PathBuf,
83
84    /// Target memory type
85    /// Change crate feature flags based on the target memory type
86    #[arg(short, long)]
87    pub target_memory_type: Option<TargetMemoryType>,
88
89    // transpile options
90    /// Options for transpiling to JavaScript.
91    #[command(flatten)]
92    pub transpile_opts: TranspileOpts,
93
94    /// If wasm run on multiple threads, enable thread support
95    /// This will change the crate feature flags to enable multi-threading.
96    #[arg(long)]
97    pub threads: Option<bool>,
98
99    /// Enable dwarf
100    /// This is broken currently.
101    /// See https://github.com/wasm-bindgen/walrus/issues/258
102    #[arg(long)]
103    pub dwarf: Option<bool>,
104
105    /// Finally, align the ABI with wasip1-threads.
106    /// Only WASM will be generated.
107    #[arg(long, default_value = "false")]
108    pub adjust_abi: bool,
109
110    /// Keep all intermediate build artifacts instead of deleting them.
111    #[arg(long, default_value = "false")]
112    pub keep_build_artifacts: bool,
113}
114
115impl BuildArgs {
116    /// Returns the memory hints for each target module.
117    pub fn get_wasm_memory_hints(&self) -> Box<[Option<usize>]> {
118        self.wasm_memory_hint
119            .iter()
120            .map(|&hint| if hint < 0 { None } else { Some(hint as usize) })
121            .chain(std::iter::repeat(None))
122            .take(self.wasm.len())
123            .collect::<Box<_>>()
124    }
125
126    /// Resolves and returns the path to the WASM package.
127    pub fn get_package(&self) -> eyre::Result<WasmPath> {
128        Ok(self.package.clone())
129            .transpose()
130            .unwrap_or_else(|| WasmPath::with_maybe_none())
131    }
132
133    /// Returns the manifest path if specified.
134    pub fn get_manifest_path(&self) -> Option<&Utf8PathBuf> {
135        self.package.as_ref().and_then(|p| p.manifest_path())
136    }
137
138    /// Retrieves the name of the package if available.
139    pub fn get_package_name(&self) -> Option<CompactString> {
140        self.package.clone().and_then(|p| p.name().ok())
141    }
142}
143
144impl PostBuildContext for BuildArgs {
145    fn out_dir(&self) -> &Utf8PathBuf {
146        &self.out_dir
147    }
148
149    fn keep_build_artifacts(&self) -> bool {
150        self.keep_build_artifacts
151    }
152
153    fn adjust_abi(&self) -> bool {
154        self.adjust_abi
155    }
156
157    fn transpile_to_js(
158        &self,
159        component: &[u8],
160        name: impl AsRef<str>,
161    ) -> Result<js_component_bindgen::Transpiled, eyre::Error> {
162        self.transpile_opts.transpile_to_js(component, name)
163    }
164}
165
166#[derive(Parser, Debug)]
167/// Arguments for the `prebuild` command.
168pub struct PreBuildArgs {
169    /// Path to the wasip1 wasm file
170    /// This allow 4 patterns:
171    /// 1. only manifest path, like `./Cargo.toml` or `./some/dir/Cargo.toml`
172    /// 2. only package name, like `my_package`
173    /// 3. manifest path and package name, like `./Cargo.toml::my_package` or `./some/dir/Cargo.toml::my_package`
174    /// 4. direct path to wasm file, like `./target/wasm32-wasi/release/my_crate.wasm`
175    pub wasm: Vec<WasmPath>,
176
177    /// Path to the primary package.
178    #[arg(short, long)]
179    package: Option<WasmPath>,
180
181    /// Memory hints for the WASM files, used if automatic detection fails.
182    #[arg(long)]
183    wasm_memory_hint: Vec<isize>,
184
185    /// Output directory for the generated Component WASM
186    #[arg(long, default_value = "./dist")]
187    pub out_dir: Utf8PathBuf,
188
189    /// Target memory type
190    /// Change crate feature flags based on the target memory type
191    #[arg(short, long)]
192    pub target_memory_type: Option<TargetMemoryType>,
193
194    /// If wasm run on multiple threads, enable thread support
195    /// This will change the crate feature flags to enable multi-threading.
196    #[arg(long)]
197    pub threads: Option<bool>,
198
199    /// Enable dwarf
200    /// This is broken currently.
201    /// See https://github.com/wasm-bindgen/walrus/issues/258
202    #[arg(long)]
203    pub dwarf: Option<bool>,
204
205    /// Finally, align the ABI with wasip1-threads.
206    /// Only WASM will be generated.
207    #[arg(long, default_value = "false")]
208    pub adjust_abi: bool,
209
210    /// Keep all intermediate build artifacts instead of deleting them.
211    #[arg(long, default_value = "false")]
212    pub keep_build_artifacts: bool,
213}
214
215impl PreBuildArgs {
216    /// Returns the memory hints for each target module.
217    pub fn get_wasm_memory_hints(&self) -> Box<[Option<usize>]> {
218        self.wasm_memory_hint
219            .iter()
220            .map(|&hint| if hint < 0 { None } else { Some(hint as usize) })
221            .chain(std::iter::repeat(None))
222            .take(self.wasm.len())
223            .collect::<Box<_>>()
224    }
225
226    /// Resolves and returns the path to the WASM package.
227    pub fn get_package(&self) -> eyre::Result<WasmPath> {
228        Ok(self.package.clone())
229            .transpose()
230            .unwrap_or_else(|| WasmPath::with_maybe_none())
231    }
232}
233
234#[derive(Parser, Debug)]
235/// Arguments for the `postbuild` command.
236pub struct PostBuildArgs {
237    /// Path to the Component WASM file to transpile.
238    #[arg(short, long)]
239    pub package: WasmPath,
240
241    /// Output directory for the generated files
242    #[arg(long, default_value = "./dist")]
243    pub out_dir: Utf8PathBuf,
244
245    /// Options for transpiling to JavaScript.
246    #[command(flatten)]
247    pub transpile_opts: TranspileOpts,
248
249    /// Enable dwarf
250    #[arg(long)]
251    pub dwarf: Option<bool>,
252
253    /// Finally, align the ABI with wasip1-threads.
254    /// Only WASM will be generated.
255    #[arg(long, default_value = "false")]
256    pub adjust_abi: bool,
257
258    /// Keep all intermediate build artifacts instead of deleting them.
259    #[arg(long, default_value = "false")]
260    pub keep_build_artifacts: bool,
261}
262
263impl PostBuildContext for PostBuildArgs {
264    fn out_dir(&self) -> &Utf8PathBuf {
265        &self.out_dir
266    }
267
268    fn keep_build_artifacts(&self) -> bool {
269        self.keep_build_artifacts
270    }
271
272    fn adjust_abi(&self) -> bool {
273        self.adjust_abi
274    }
275
276    fn transpile_to_js(
277        &self,
278        component: &[u8],
279        name: impl AsRef<str>,
280    ) -> Result<js_component_bindgen::Transpiled, eyre::Error> {
281        self.transpile_opts.transpile_to_js(component, name)
282    }
283}
284
285/// Options for transpiling WebAssembly components into JavaScript.
286#[derive(Parser, Debug)]
287pub struct TranspileOpts {
288    /// Disables generation of *.d.ts files and instead only generates *.js source files.
289    #[arg(long, default_value = "false")]
290    no_typescript: bool,
291
292    /// Provide a custom JS instantiation API for the component instead of the direct importable native ESM output.
293    /// Sync, Async, Normal, Default is Async.
294    #[arg(long, value_parser = analysis::analysis_instantiation, default_value = "CustomInstantiationMode(None)")]
295    instantiation: CustomInstantiationMode,
296
297    /// Configure how import bindings are provided, as high-level JS bindings, or as hybrid optimized bindings.
298    #[arg(long, value_parser = analysis::analysis_import_bindings)]
299    import_bindings: Option<js_component_bindgen::BindingsMode>,
300
301    /// Comma-separated list of "from-specifier=./to-specifier.js" mappings of component import specifiers to JS import specifiers.
302    #[arg(long, value_delimiter = ',', value_parser = analysis::parse_mapping, num_args = 0.., action = clap::ArgAction::Append)]
303    map: Option<HashMap<String, String>>,
304
305    /// Disables compatibility in Node.js without a fetch global.
306    #[arg(long, default_value = "false")]
307    no_nodejs_compat: bool,
308
309    /// Set the cutoff byte size for base64 inlining core Wasm in instantiation mode (set to 0 to disable all base64 inlining)
310    #[arg(long, default_value = "0")]
311    base64_cutoff: usize,
312
313    /// Enables compatibility for JS environments without top-level await support via an async $init promise export to wait for instead.
314    #[arg(long, default_value = "false")]
315    tla_compat: bool,
316
317    /// Disable verification of component Wasm data structures when lifting as a production optimization
318    #[arg(long, default_value = "false")]
319    valid_lifting_optimization: bool,
320
321    /// Whether or not to emit tracing calls on function entry/exit.
322    #[arg(long, default_value = "false")]
323    tracing: bool,
324
325    /// Whether to generate namespaced exports like foo as "local:package/foo ". These exports can break typescript builds.
326    #[arg(long, default_value = "false")]
327    no_namespaced_exports: bool,
328
329    /// Whether to generate types for a guest module using module declarations.
330    #[arg(long, default_value = "false")]
331    pub guest: bool,
332}
333
334impl TranspileOpts {
335    /// Transpiles the given WebAssembly component into JavaScript source files.
336    pub fn transpile_to_js(
337        &self,
338        component: &[u8],
339        name: impl AsRef<str>,
340    ) -> Result<js_component_bindgen::Transpiled, eyre::Error> {
341        js_component_bindgen::transpile(
342            component,
343            js_component_bindgen::TranspileOpts {
344                name: name.as_ref().to_string(),
345                no_typescript: self.no_typescript,
346                instantiation: self.instantiation.clone().0,
347                import_bindings: self.import_bindings.clone(),
348                map: {
349                    if let Some(opts_map) = &self.map {
350                        let mut map = HashMap::new();
351                        for (k, v) in opts_map.iter() {
352                            map.insert(k.clone(), v.clone());
353                        }
354                        Some(map)
355                    } else {
356                        None
357                    }
358                },
359                no_nodejs_compat: self.no_nodejs_compat,
360                base64_cutoff: self.base64_cutoff,
361                tla_compat: self.tla_compat,
362                valid_lifting_optimization: self.valid_lifting_optimization,
363                tracing: self.tracing,
364                no_namespaced_exports: self.no_namespaced_exports,
365                multi_memory: true,
366                guest: self.guest,
367                async_mode: None,
368                strict: false,
369                asmjs: false,
370            },
371        )
372        .to_eyre()
373        .wrap_err("Failed to transpile to JS.")
374    }
375}
376
377/// Represents a custom instantiation mode for the generated JavaScript.
378#[derive(Clone, Debug)]
379pub struct CustomInstantiationMode(Option<js_component_bindgen::InstantiationMode>);
380
381pub(super) mod analysis {
382    use js_component_bindgen::{BindingsMode, InstantiationMode};
383
384    use super::CustomInstantiationMode;
385
386    pub fn analysis_instantiation(s: &str) -> Result<CustomInstantiationMode, clap::Error> {
387        match s {
388            "Sync" => Ok(CustomInstantiationMode(Some(InstantiationMode::Sync))),
389            "Async" => Ok(CustomInstantiationMode(Some(InstantiationMode::Async))),
390            "Normal" => Ok(CustomInstantiationMode(None)),
391            _ => Ok(CustomInstantiationMode(Some(InstantiationMode::Async))),
392        }
393    }
394
395    pub fn analysis_import_bindings(s: &str) -> Result<Option<BindingsMode>, clap::Error> {
396        match s {
397            "Hybrid" => Ok(Some(BindingsMode::Hybrid)),
398            "Js" => Ok(Some(BindingsMode::Js)),
399            "Optimized" => Ok(Some(BindingsMode::Optimized)),
400            "DirectOptimized" => Ok(Some(BindingsMode::DirectOptimized)),
401            _ => Ok(None),
402        }
403    }
404
405    pub fn parse_mapping(s: &str) -> Result<(String, String), String> {
406        let parts: Vec<&str> = s.splitn(2, '=').collect();
407        if parts.len() != 2 {
408            return Err(format!("Invalid mapping format: '{}'", s));
409        }
410        Ok((parts[0].to_string(), parts[1].to_string()))
411    }
412}
413
414/// Specifies the memory architecture of the target WebAssembly module.
415#[derive(Debug, Clone, Copy, PartialEq, strum::EnumString, strum::Display)]
416pub enum TargetMemoryType {
417    /// Traditional single memory environment.
418    #[strum(ascii_case_insensitive)]
419    Single,
420    /// Multi-memory environment where modules have their own address spaces.
421    #[strum(ascii_case_insensitive)]
422    Multi,
423}
424
425impl TargetMemoryType {
426    /// Returns `true` if this memory type is `Multi`.
427    pub fn is_multi(&self) -> bool {
428        matches!(self, TargetMemoryType::Multi)
429    }
430
431    /// Returns `true` if this memory type is `Single`.
432    pub fn is_single(&self) -> bool {
433        matches!(self, TargetMemoryType::Single)
434    }
435}