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