Skip to main content

wasi_virt_layer_cli/
args.rs

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