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    /// Enable development mode (skips Wasm optimization).
173    #[arg(long, default_value = "false")]
174    pub dev: bool,
175
176    /// Options for building the VFS module.
177    #[command(flatten)]
178    pub vfs_build_opts: VfsBuildOptions,
179
180    /// Options for building target Wasm modules.
181    #[arg(skip)]
182    pub target_vfs_build_opts: Option<Box<[VfsBuildOptions]>>,
183}
184
185impl BuildArgs {
186    /// Returns the memory hints for each target module.
187    pub fn get_wasm_memory_hints(&self) -> Box<[Option<usize>]> {
188        self.wasm_memory_hint
189            .iter()
190            .map(|&hint| if hint < 0 { None } else { Some(hint as usize) })
191            .chain(std::iter::repeat(None))
192            .take(self.wasm.len())
193            .collect::<Box<_>>()
194    }
195
196    /// Resolves and returns the path to the WASM package.
197    pub fn get_package(&self) -> eyre::Result<WasmPath> {
198        let mut p = Ok(self.package.clone()).transpose().unwrap_or_else(|| {
199            if let Some(ref manifest) = self.manifest_path {
200                WasmPath::with_maybe_only_manifest(manifest.clone())
201            } else {
202                WasmPath::with_maybe_none()
203            }
204        })?;
205        if let Some(ref manifest) = self.manifest_path {
206            if let WasmPath::Maybe { manifest_path, .. } = &mut p {
207                *manifest_path = manifest.clone();
208            }
209        }
210        Ok(p)
211    }
212
213    /// Gets the list of wasm targets, applying the manifest path if specified.
214    pub fn get_wasm_paths(&self) -> Box<[WasmPath]> {
215        let mut paths = self.wasm.clone();
216        if let Some(ref manifest) = self.manifest_path {
217            for p in &mut paths {
218                if let WasmPath::Maybe { manifest_path, .. } = p {
219                    *manifest_path = manifest.clone();
220                }
221            }
222        }
223        paths.into_boxed_slice()
224    }
225}
226
227impl PostBuildContext for BuildArgs {
228    fn out_dir(&self) -> &Utf8PathBuf {
229        &self.out_dir
230    }
231
232    fn keep_build_artifacts(&self) -> bool {
233        self.keep_build_artifacts
234    }
235
236    fn adjust_abi(&self) -> bool {
237        self.adjust_abi
238    }
239
240    fn transpile_to_js(
241        &self,
242        component: &[u8],
243        name: impl AsRef<str>,
244    ) -> Result<js_component_bindgen::Transpiled, eyre::Error> {
245        self.transpile_opts.transpile_to_js(component, name)
246    }
247}
248
249#[derive(Parser, Debug)]
250#[clap(author, version, about, long_about = None, help_template = "
251{name} {version}
252{author}
253{about}
254
255{usage-heading} {usage}
256
257{all-args}")]
258/// Arguments for the `prebuild` command.
259pub struct PreBuildArgs {
260    /// Path to the wasip1 wasm file
261    /// This allow 4 patterns:
262    /// 1. only manifest path, like `./Cargo.toml` or `./some/dir/Cargo.toml`
263    /// 2. only package name, like `my_package`
264    /// 3. manifest path and package name, like `./Cargo.toml::my_package` or `./some/dir/Cargo.toml::my_package`
265    /// 4. direct path to wasm file, like `./target/wasm32-wasi/release/my_crate.wasm`
266    pub wasm: Vec<WasmPath>,
267
268    /// Path to the primary package.
269    #[arg(short, long)]
270    package: Option<WasmPath>,
271
272    /// Path to Cargo.toml
273    #[arg(long)]
274    pub manifest_path: Option<Utf8PathBuf>,
275
276    /// Memory hints for the WASM files, used if automatic detection fails.
277    #[arg(long)]
278    wasm_memory_hint: Vec<isize>,
279
280    /// Output directory for the generated Component WASM
281    #[arg(long, default_value = "./dist")]
282    pub out_dir: Utf8PathBuf,
283
284    /// Target memory type
285    /// Change crate feature flags based on the target memory type
286    #[arg(short, long)]
287    pub target_memory_type: Option<TargetMemoryType>,
288
289    /// If wasm run on multiple threads, enable thread support
290    /// This will change the crate feature flags to enable multi-threading.
291    #[arg(long)]
292    pub threads: Option<bool>,
293
294    /// Enable dwarf
295    /// This is broken currently.
296    /// See https://github.com/wasm-bindgen/walrus/issues/258
297    #[arg(long)]
298    pub dwarf: Option<bool>,
299
300    /// Finally, align the ABI with wasip1-threads.
301    /// Only WASM will be generated.
302    #[arg(long, default_value = "false")]
303    pub adjust_abi: bool,
304
305    /// Keep all intermediate build artifacts instead of deleting them.
306    #[arg(long, default_value = "false")]
307    pub keep_build_artifacts: bool,
308
309    /// Enable development mode (skips Wasm optimization).
310    #[arg(long, default_value = "false")]
311    pub dev: bool,
312
313    /// Options for building the VFS module.
314    #[command(flatten)]
315    pub vfs_build_opts: VfsBuildOptions,
316
317    /// Options for building target Wasm modules.
318    #[arg(skip)]
319    pub target_vfs_build_opts: Option<Box<[VfsBuildOptions]>>,
320}
321
322impl PreBuildArgs {
323    /// Returns the memory hints for each target module.
324    pub fn get_wasm_memory_hints(&self) -> Box<[Option<usize>]> {
325        self.wasm_memory_hint
326            .iter()
327            .map(|&hint| if hint < 0 { None } else { Some(hint as usize) })
328            .chain(std::iter::repeat(None))
329            .take(self.wasm.len())
330            .collect::<Box<_>>()
331    }
332
333    /// Resolves and returns the path to the WASM package.
334    pub fn get_package(&self) -> eyre::Result<WasmPath> {
335        let mut p = Ok(self.package.clone()).transpose().unwrap_or_else(|| {
336            if let Some(ref manifest) = self.manifest_path {
337                WasmPath::with_maybe_only_manifest(manifest.clone())
338            } else {
339                WasmPath::with_maybe_none()
340            }
341        })?;
342        if let Some(ref manifest) = self.manifest_path {
343            if let WasmPath::Maybe { manifest_path, .. } = &mut p {
344                *manifest_path = manifest.clone();
345            }
346        }
347        Ok(p)
348    }
349
350    /// Gets the list of wasm targets, applying the manifest path if specified.
351    pub fn get_wasm_paths(&self) -> Box<[WasmPath]> {
352        let mut paths = self.wasm.clone();
353        if let Some(ref manifest) = self.manifest_path {
354            for p in &mut paths {
355                if let WasmPath::Maybe { manifest_path, .. } = p {
356                    *manifest_path = manifest.clone();
357                }
358            }
359        }
360        paths.into_boxed_slice()
361    }
362}
363
364#[derive(Parser, Debug)]
365#[clap(author, version, about, long_about = None, help_template = "
366{name} {version}
367{author}
368{about}
369
370{usage-heading} {usage}
371
372{all-args}")]
373/// Arguments for the `postbuild` command.
374pub struct PostBuildArgs {
375    /// Path to the Component WASM file to transpile.
376    #[arg(short, long)]
377    pub package: WasmPath,
378
379    /// Output directory for the generated files
380    #[arg(long, default_value = "./dist")]
381    pub out_dir: Utf8PathBuf,
382
383    /// Options for transpiling to JavaScript.
384    #[command(flatten)]
385    pub transpile_opts: TranspileOpts,
386
387    /// Enable dwarf
388    #[arg(long)]
389    pub dwarf: Option<bool>,
390
391    /// Finally, align the ABI with wasip1-threads.
392    /// Only WASM will be generated.
393    #[arg(long, default_value = "false")]
394    pub adjust_abi: bool,
395
396    /// Keep all intermediate build artifacts instead of deleting them.
397    #[arg(long, default_value = "false")]
398    pub keep_build_artifacts: bool,
399}
400
401impl PostBuildContext for PostBuildArgs {
402    fn out_dir(&self) -> &Utf8PathBuf {
403        &self.out_dir
404    }
405
406    fn keep_build_artifacts(&self) -> bool {
407        self.keep_build_artifacts
408    }
409
410    fn adjust_abi(&self) -> bool {
411        self.adjust_abi
412    }
413
414    fn transpile_to_js(
415        &self,
416        component: &[u8],
417        name: impl AsRef<str>,
418    ) -> Result<js_component_bindgen::Transpiled, eyre::Error> {
419        self.transpile_opts.transpile_to_js(component, name)
420    }
421}
422
423/// Options for transpiling WebAssembly components into JavaScript.
424#[derive(Parser, Debug)]
425#[clap(author, version, about, long_about = None, help_template = "
426{name} {version}
427{author}
428{about}
429
430{usage-heading} {usage}
431
432{all-args}")]
433pub struct TranspileOpts {
434    /// Disables generation of *.d.ts files and instead only generates *.js source files.
435    #[arg(long, default_value = "false")]
436    no_typescript: bool,
437
438    /// Provide a custom JS instantiation API for the component instead of the direct importable native ESM output.
439    /// Sync, Async, Normal, Default is Async.
440    #[arg(long, value_parser = analysis::analysis_instantiation, default_value = "CustomInstantiationMode(None)")]
441    instantiation: CustomInstantiationMode,
442
443    /// Configure how import bindings are provided, as high-level JS bindings, or as hybrid optimized bindings.
444    #[arg(long, value_parser = analysis::analysis_import_bindings)]
445    import_bindings: Option<js_component_bindgen::BindingsMode>,
446
447    /// Comma-separated list of "from-specifier=./to-specifier.js" mappings of component import specifiers to JS import specifiers.
448    #[arg(long, value_delimiter = ',', value_parser = analysis::parse_mapping, action = clap::ArgAction::Append)]
449    map: Vec<(String, String)>,
450
451    /// Disables compatibility in Node.js without a fetch global.
452    #[arg(long, default_value = "false")]
453    no_nodejs_compat: bool,
454
455    /// Set the cutoff byte size for base64 inlining core Wasm in instantiation mode (set to 0 to disable all base64 inlining)
456    #[arg(long, default_value = "0")]
457    base64_cutoff: usize,
458
459    /// Enables compatibility for JS environments without top-level await support via an async $init promise export to wait for instead.
460    #[arg(long, default_value = "false")]
461    tla_compat: bool,
462
463    /// Disable verification of component Wasm data structures when lifting as a production optimization
464    #[arg(long, default_value = "false")]
465    valid_lifting_optimization: bool,
466
467    /// Whether or not to emit tracing calls on function entry/exit.
468    #[arg(long, default_value = "false")]
469    tracing: bool,
470
471    /// Whether to generate namespaced exports like foo as "local:package/foo ". These exports can break typescript builds.
472    #[arg(long, default_value = "false")]
473    no_namespaced_exports: bool,
474
475    /// Whether to generate types for a guest module using module declarations.
476    #[arg(long, default_value = "false")]
477    pub guest: bool,
478}
479
480impl TranspileOpts {
481    /// Transpiles the given WebAssembly component into JavaScript source files.
482    pub fn transpile_to_js(
483        &self,
484        component: &[u8],
485        name: impl AsRef<str>,
486    ) -> Result<js_component_bindgen::Transpiled, eyre::Error> {
487        js_component_bindgen::transpile(
488            component,
489            js_component_bindgen::TranspileOpts {
490                name: name.as_ref().to_string(),
491                no_typescript: self.no_typescript,
492                instantiation: self.instantiation.clone().0,
493                import_bindings: self.import_bindings.clone(),
494                map: if !self.map.is_empty() {
495                    Some(self.map.iter().cloned().collect())
496                } else {
497                    None
498                },
499                no_nodejs_compat: self.no_nodejs_compat,
500                base64_cutoff: self.base64_cutoff,
501                tla_compat: self.tla_compat,
502                valid_lifting_optimization: self.valid_lifting_optimization,
503                tracing: self.tracing,
504                no_namespaced_exports: self.no_namespaced_exports,
505                multi_memory: true,
506                guest: self.guest,
507                async_mode: None,
508                strict: false,
509                asmjs: false,
510            },
511        )
512        .to_eyre()
513        .wrap_err("Failed to transpile to JS.")
514    }
515}
516
517/// Represents a custom instantiation mode for the generated JavaScript.
518#[derive(Clone, Debug)]
519pub struct CustomInstantiationMode(Option<js_component_bindgen::InstantiationMode>);
520
521pub(super) mod analysis {
522    use js_component_bindgen::{BindingsMode, InstantiationMode};
523
524    use super::CustomInstantiationMode;
525
526    pub fn analysis_instantiation(s: &str) -> Result<CustomInstantiationMode, clap::Error> {
527        match s {
528            "Sync" => Ok(CustomInstantiationMode(Some(InstantiationMode::Sync))),
529            "Async" => Ok(CustomInstantiationMode(Some(InstantiationMode::Async))),
530            "Normal" => Ok(CustomInstantiationMode(None)),
531            _ => Ok(CustomInstantiationMode(Some(InstantiationMode::Async))),
532        }
533    }
534
535    pub fn analysis_import_bindings(s: &str) -> Result<Option<BindingsMode>, clap::Error> {
536        match s {
537            "Hybrid" => Ok(Some(BindingsMode::Hybrid)),
538            "Js" => Ok(Some(BindingsMode::Js)),
539            "Optimized" => Ok(Some(BindingsMode::Optimized)),
540            "DirectOptimized" => Ok(Some(BindingsMode::DirectOptimized)),
541            _ => Ok(None),
542        }
543    }
544
545    pub fn parse_mapping(s: &str) -> Result<(String, String), String> {
546        let parts: Vec<&str> = s.splitn(2, '=').collect();
547        if parts.len() != 2 {
548            return Err(format!("Invalid mapping format: '{}'", s));
549        }
550        Ok((parts[0].to_string(), parts[1].to_string()))
551    }
552}
553
554/// Specifies the memory architecture of the target WebAssembly module.
555#[derive(Debug, Clone, Copy, PartialEq, strum::EnumString, strum::Display)]
556pub enum TargetMemoryType {
557    /// Traditional single memory environment.
558    #[strum(ascii_case_insensitive)]
559    Single,
560    /// Multi-memory environment where modules have their own address spaces.
561    #[strum(ascii_case_insensitive)]
562    Multi,
563}
564
565impl TargetMemoryType {
566    /// Returns `true` if this memory type is `Multi`.
567    pub fn is_multi(&self) -> bool {
568        matches!(self, TargetMemoryType::Multi)
569    }
570
571    /// Returns `true` if this memory type is `Single`.
572    pub fn is_single(&self) -> bool {
573        matches!(self, TargetMemoryType::Single)
574    }
575}
576
577/// Options for building the VFS module.
578#[derive(Parser, Debug, Clone, Default)]
579pub struct VfsBuildOptions {
580    /// Space or comma separated list of features to activate for the VFS module.
581    #[arg(long, action = clap::ArgAction::Append)]
582    pub features: Vec<String>,
583
584    /// Do not activate the `default` feature of the VFS module.
585    #[arg(long, action = clap::ArgAction::Count)]
586    pub no_default_features: u8,
587
588    /// Disable optimization for this specific module.
589    #[arg(long, action = clap::ArgAction::Count)]
590    pub no_opt: u8,
591
592    /// Disable all optimizations for this module and subsequent merged modules.
593    #[arg(long, action = clap::ArgAction::Count)]
594    pub no_opt_all: u8,
595}