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