1use camino::Utf8PathBuf;
2use clap::{Parser, Subcommand};
3use eyre::Context as _;
4
5use crate::{generator::WasmPath, util::ResultUtil as _};
6
7pub trait PostBuildContext {
9 fn out_dir(&self) -> &Utf8PathBuf;
11 fn keep_build_artifacts(&self) -> bool;
13 fn adjust_abi(&self) -> bool;
15 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#[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 #[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}")]
49pub enum Command {
51 Build(BuildArgs),
53 Prebuild(PreBuildArgs),
55 Postbuild(PostBuildArgs),
57 New(NewArgs),
59 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}")]
72pub struct NewArgs {
74 #[arg(value_name = "PATH")]
76 pub path: Utf8PathBuf,
77
78 #[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}")]
92pub struct PrepareTargetArgs {
94 #[arg(value_name = "TARGET_WASM")]
96 pub target_wasm: Utf8PathBuf,
97
98 #[arg(short, long, value_name = "OUTPUT")]
100 pub output: Option<Utf8PathBuf>,
101
102 #[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}")]
116pub struct BuildArgs {
118 pub wasm: Vec<WasmPath>,
125
126 #[arg(short, long)]
128 package: Option<WasmPath>,
129
130 #[arg(long)]
132 pub manifest_path: Option<Utf8PathBuf>,
133
134 #[arg(long)]
136 wasm_memory_hint: Vec<isize>,
137
138 #[arg(long, default_value = "./dist")]
140 pub out_dir: Utf8PathBuf,
141
142 #[arg(short, long)]
145 pub target_memory_type: Option<TargetMemoryType>,
146
147 #[command(flatten)]
150 pub transpile_opts: TranspileOpts,
151
152 #[arg(long)]
155 pub threads: Option<bool>,
156
157 #[arg(long)]
161 pub dwarf: Option<bool>,
162
163 #[arg(long, default_value = "false")]
166 pub adjust_abi: bool,
167
168 #[arg(long, default_value = "false")]
170 pub keep_build_artifacts: bool,
171
172 #[arg(long, default_value = "false")]
174 pub dev: bool,
175
176 #[command(flatten)]
178 pub vfs_build_opts: VfsBuildOptions,
179
180 #[arg(skip)]
182 pub target_vfs_build_opts: Option<Box<[VfsBuildOptions]>>,
183}
184
185impl BuildArgs {
186 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 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 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}")]
258pub struct PreBuildArgs {
260 pub wasm: Vec<WasmPath>,
267
268 #[arg(short, long)]
270 package: Option<WasmPath>,
271
272 #[arg(long)]
274 pub manifest_path: Option<Utf8PathBuf>,
275
276 #[arg(long)]
278 wasm_memory_hint: Vec<isize>,
279
280 #[arg(long, default_value = "./dist")]
282 pub out_dir: Utf8PathBuf,
283
284 #[arg(short, long)]
287 pub target_memory_type: Option<TargetMemoryType>,
288
289 #[arg(long)]
292 pub threads: Option<bool>,
293
294 #[arg(long)]
298 pub dwarf: Option<bool>,
299
300 #[arg(long, default_value = "false")]
303 pub adjust_abi: bool,
304
305 #[arg(long, default_value = "false")]
307 pub keep_build_artifacts: bool,
308
309 #[arg(long, default_value = "false")]
311 pub dev: bool,
312
313 #[command(flatten)]
315 pub vfs_build_opts: VfsBuildOptions,
316
317 #[arg(skip)]
319 pub target_vfs_build_opts: Option<Box<[VfsBuildOptions]>>,
320}
321
322impl PreBuildArgs {
323 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 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 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}")]
373pub struct PostBuildArgs {
375 #[arg(short, long)]
377 pub package: WasmPath,
378
379 #[arg(long, default_value = "./dist")]
381 pub out_dir: Utf8PathBuf,
382
383 #[command(flatten)]
385 pub transpile_opts: TranspileOpts,
386
387 #[arg(long)]
389 pub dwarf: Option<bool>,
390
391 #[arg(long, default_value = "false")]
394 pub adjust_abi: bool,
395
396 #[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#[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 #[arg(long, default_value = "false")]
436 no_typescript: bool,
437
438 #[arg(long, value_parser = analysis::analysis_instantiation, default_value = "CustomInstantiationMode(None)")]
441 instantiation: CustomInstantiationMode,
442
443 #[arg(long, value_parser = analysis::analysis_import_bindings)]
445 import_bindings: Option<js_component_bindgen::BindingsMode>,
446
447 #[arg(long, value_delimiter = ',', value_parser = analysis::parse_mapping, action = clap::ArgAction::Append)]
449 map: Vec<(String, String)>,
450
451 #[arg(long, default_value = "false")]
453 no_nodejs_compat: bool,
454
455 #[arg(long, default_value = "0")]
457 base64_cutoff: usize,
458
459 #[arg(long, default_value = "false")]
461 tla_compat: bool,
462
463 #[arg(long, default_value = "false")]
465 valid_lifting_optimization: bool,
466
467 #[arg(long, default_value = "false")]
469 tracing: bool,
470
471 #[arg(long, default_value = "false")]
473 no_namespaced_exports: bool,
474
475 #[arg(long, default_value = "false")]
477 pub guest: bool,
478}
479
480impl TranspileOpts {
481 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#[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#[derive(Debug, Clone, Copy, PartialEq, strum::EnumString, strum::Display)]
556pub enum TargetMemoryType {
557 #[strum(ascii_case_insensitive)]
559 Single,
560 #[strum(ascii_case_insensitive)]
562 Multi,
563}
564
565impl TargetMemoryType {
566 pub fn is_multi(&self) -> bool {
568 matches!(self, TargetMemoryType::Multi)
569 }
570
571 pub fn is_single(&self) -> bool {
573 matches!(self, TargetMemoryType::Single)
574 }
575}
576
577#[derive(Parser, Debug, Clone, Default)]
579pub struct VfsBuildOptions {
580 #[arg(long, action = clap::ArgAction::Append)]
582 pub features: Vec<String>,
583
584 #[arg(long, action = clap::ArgAction::Count)]
586 pub no_default_features: u8,
587
588 #[arg(long, action = clap::ArgAction::Count)]
590 pub no_opt: u8,
591
592 #[arg(long, action = clap::ArgAction::Count)]
594 pub no_opt_all: u8,
595}