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 fn dev(&self) -> bool;
23}
24
25#[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 #[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}")]
51pub enum Command {
53 Build(BuildArgs),
55 Prebuild(PreBuildArgs),
57 Postbuild(PostBuildArgs),
59 New(NewArgs),
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 BuildArgs {
94 pub wasm: Vec<WasmPath>,
101
102 #[arg(short, long)]
104 package: Option<WasmPath>,
105
106 #[arg(long)]
108 pub manifest_path: Option<Utf8PathBuf>,
109
110 #[arg(long)]
112 wasm_memory_hint: Vec<isize>,
113
114 #[arg(long = "wasm-unwind")]
116 pub wasm_unwind: Vec<bool>,
117
118 #[arg(long, default_value = "./dist")]
120 pub out_dir: Utf8PathBuf,
121
122 #[arg(short, long)]
125 pub target_memory_type: Option<TargetMemoryType>,
126
127 #[command(flatten)]
130 pub transpile_opts: TranspileOpts,
131
132 #[arg(long)]
135 pub threads: Option<bool>,
136
137 #[arg(long)]
141 pub dwarf: Option<bool>,
142
143 #[arg(long, default_value = "false")]
146 pub adjust_abi: bool,
147
148 #[arg(long, default_value = "false")]
150 pub keep_build_artifacts: bool,
151
152 #[arg(long, default_value = "false")]
154 pub dev: bool,
155
156 #[command(flatten)]
158 pub vfs_build_opts: VfsBuildOptions,
159
160 #[arg(skip)]
162 pub target_vfs_build_opts: Option<Box<[VfsBuildOptions]>>,
163}
164
165impl BuildArgs {
166 pub fn get_wasm_memory_hints(&self) -> Box<[Option<usize>]> {
168 self.wasm_memory_hint
169 .iter()
170 .map(|&hint| if hint < 0 { None } else { Some(hint as usize) })
171 .chain(std::iter::repeat(None))
172 .take(self.wasm.len())
173 .collect::<Box<_>>()
174 }
175
176 pub fn get_wasm_unwinds(&self) -> Box<[bool]> {
178 self.wasm_unwind
179 .iter()
180 .copied()
181 .chain(std::iter::repeat(false))
182 .take(self.wasm.len())
183 .collect::<Box<_>>()
184 }
185
186 pub fn get_package(&self) -> eyre::Result<WasmPath> {
188 let mut p = Ok(self.package.clone()).transpose().unwrap_or_else(|| {
189 if let Some(ref manifest) = self.manifest_path {
190 WasmPath::with_maybe_only_manifest(manifest.clone())
191 } else {
192 WasmPath::with_maybe_none()
193 }
194 })?;
195 if let Some(ref manifest) = self.manifest_path {
196 if let WasmPath::Maybe { manifest_path, .. } = &mut p {
197 *manifest_path = manifest.clone();
198 }
199 }
200 Ok(p)
201 }
202
203 pub fn get_wasm_paths(&self) -> Box<[WasmPath]> {
205 let mut paths = self.wasm.clone();
206 if let Some(ref manifest) = self.manifest_path {
207 for p in &mut paths {
208 if let WasmPath::Maybe { manifest_path, .. } = p {
209 *manifest_path = manifest.clone();
210 }
211 }
212 }
213 paths.into_boxed_slice()
214 }
215}
216
217impl PostBuildContext for BuildArgs {
218 fn out_dir(&self) -> &Utf8PathBuf {
219 &self.out_dir
220 }
221
222 fn keep_build_artifacts(&self) -> bool {
223 self.keep_build_artifacts
224 }
225
226 fn adjust_abi(&self) -> bool {
227 self.adjust_abi
228 }
229
230 fn transpile_to_js(
231 &self,
232 component: &[u8],
233 name: impl AsRef<str>,
234 ) -> Result<js_component_bindgen::Transpiled, eyre::Error> {
235 self.transpile_opts.transpile_to_js(component, name)
236 }
237
238 fn dev(&self) -> bool {
239 self.dev
240 }
241}
242
243#[derive(Parser, Debug)]
244#[clap(author, version, about, long_about = None, help_template = "
245{name} {version}
246{author}
247{about}
248
249{usage-heading} {usage}
250
251{all-args}")]
252pub struct PreBuildArgs {
254 pub wasm: Vec<WasmPath>,
261
262 #[arg(short, long)]
264 package: Option<WasmPath>,
265
266 #[arg(long)]
268 pub manifest_path: Option<Utf8PathBuf>,
269
270 #[arg(long)]
272 wasm_memory_hint: Vec<isize>,
273
274 #[arg(long = "wasm-unwind")]
276 pub wasm_unwind: Vec<bool>,
277
278 #[arg(long, default_value = "./dist")]
280 pub out_dir: Utf8PathBuf,
281
282 #[arg(short, long)]
285 pub target_memory_type: Option<TargetMemoryType>,
286
287 #[arg(long)]
290 pub threads: Option<bool>,
291
292 #[arg(long)]
296 pub dwarf: Option<bool>,
297
298 #[arg(long, default_value = "false")]
301 pub adjust_abi: bool,
302
303 #[arg(long, default_value = "false")]
305 pub keep_build_artifacts: bool,
306
307 #[arg(long, default_value = "false")]
309 pub dev: bool,
310
311 #[command(flatten)]
313 pub vfs_build_opts: VfsBuildOptions,
314
315 #[arg(skip)]
317 pub target_vfs_build_opts: Option<Box<[VfsBuildOptions]>>,
318}
319
320impl PreBuildArgs {
321 pub fn get_wasm_memory_hints(&self) -> Box<[Option<usize>]> {
323 self.wasm_memory_hint
324 .iter()
325 .map(|&hint| if hint < 0 { None } else { Some(hint as usize) })
326 .chain(std::iter::repeat(None))
327 .take(self.wasm.len())
328 .collect::<Box<_>>()
329 }
330
331 pub fn get_wasm_unwinds(&self) -> Box<[bool]> {
333 self.wasm_unwind
334 .iter()
335 .copied()
336 .chain(std::iter::repeat(false))
337 .take(self.wasm.len())
338 .collect::<Box<_>>()
339 }
340
341 pub fn get_package(&self) -> eyre::Result<WasmPath> {
343 let mut p = Ok(self.package.clone()).transpose().unwrap_or_else(|| {
344 if let Some(ref manifest) = self.manifest_path {
345 WasmPath::with_maybe_only_manifest(manifest.clone())
346 } else {
347 WasmPath::with_maybe_none()
348 }
349 })?;
350 if let Some(ref manifest) = self.manifest_path {
351 if let WasmPath::Maybe { manifest_path, .. } = &mut p {
352 *manifest_path = manifest.clone();
353 }
354 }
355 Ok(p)
356 }
357
358 pub fn get_wasm_paths(&self) -> Box<[WasmPath]> {
360 let mut paths = self.wasm.clone();
361 if let Some(ref manifest) = self.manifest_path {
362 for p in &mut paths {
363 if let WasmPath::Maybe { manifest_path, .. } = p {
364 *manifest_path = manifest.clone();
365 }
366 }
367 }
368 paths.into_boxed_slice()
369 }
370}
371
372#[derive(Parser, Debug)]
373#[clap(author, version, about, long_about = None, help_template = "
374{name} {version}
375{author}
376{about}
377
378{usage-heading} {usage}
379
380{all-args}")]
381pub struct PostBuildArgs {
383 #[arg(short, long)]
385 pub package: WasmPath,
386
387 #[arg(long, default_value = "./dist")]
389 pub out_dir: Utf8PathBuf,
390
391 #[command(flatten)]
393 pub transpile_opts: TranspileOpts,
394
395 #[arg(long)]
397 pub dwarf: Option<bool>,
398
399 #[arg(long, default_value = "false")]
402 pub adjust_abi: bool,
403
404 #[arg(long, default_value = "false")]
406 pub keep_build_artifacts: bool,
407
408 #[arg(long, default_value = "false")]
410 pub dev: bool,
411}
412
413impl PostBuildContext for PostBuildArgs {
414 fn out_dir(&self) -> &Utf8PathBuf {
415 &self.out_dir
416 }
417
418 fn keep_build_artifacts(&self) -> bool {
419 self.keep_build_artifacts
420 }
421
422 fn adjust_abi(&self) -> bool {
423 self.adjust_abi
424 }
425
426 fn transpile_to_js(
427 &self,
428 component: &[u8],
429 name: impl AsRef<str>,
430 ) -> Result<js_component_bindgen::Transpiled, eyre::Error> {
431 self.transpile_opts.transpile_to_js(component, name)
432 }
433
434 fn dev(&self) -> bool {
435 self.dev
436 }
437}
438
439#[derive(Parser, Debug)]
441#[clap(author, version, about, long_about = None, help_template = "
442{name} {version}
443{author}
444{about}
445
446{usage-heading} {usage}
447
448{all-args}")]
449pub struct TranspileOpts {
450 #[arg(long, default_value = "false")]
452 no_typescript: bool,
453
454 #[arg(long, value_parser = analysis::analysis_instantiation, default_value = "CustomInstantiationMode(None)")]
457 instantiation: CustomInstantiationMode,
458
459 #[arg(long, value_parser = analysis::analysis_import_bindings)]
461 import_bindings: Option<js_component_bindgen::BindingsMode>,
462
463 #[arg(long, value_delimiter = ',', value_parser = analysis::parse_mapping, action = clap::ArgAction::Append)]
465 map: Vec<(String, String)>,
466
467 #[arg(long, default_value = "false")]
469 no_nodejs_compat: bool,
470
471 #[arg(long, default_value = "0")]
473 base64_cutoff: usize,
474
475 #[arg(long, default_value = "false")]
477 tla_compat: bool,
478
479 #[arg(long, default_value = "false")]
481 valid_lifting_optimization: bool,
482
483 #[arg(long, default_value = "false")]
485 tracing: bool,
486
487 #[arg(long, default_value = "false")]
489 no_namespaced_exports: bool,
490
491 #[arg(long, default_value = "false")]
493 pub guest: bool,
494}
495
496impl TranspileOpts {
497 pub fn transpile_to_js(
499 &self,
500 component: &[u8],
501 name: impl AsRef<str>,
502 ) -> Result<js_component_bindgen::Transpiled, eyre::Error> {
503 js_component_bindgen::transpile(
504 component,
505 js_component_bindgen::TranspileOpts {
506 name: name.as_ref().to_string(),
507 no_typescript: self.no_typescript,
508 instantiation_mode: self.instantiation.clone().0,
509 import_bindings: self.import_bindings.clone(),
510 map: if !self.map.is_empty() {
511 Some(self.map.iter().cloned().collect())
512 } else {
513 None
514 },
515 nodejs_compat_disabled: self.no_nodejs_compat,
516 base64_cutoff: self.base64_cutoff,
517 tla_compat: self.tla_compat,
518 valid_lifting_optimization: self.valid_lifting_optimization,
519 tracing: self.tracing,
520 no_namespaced_exports: self.no_namespaced_exports,
521 multi_memory: true,
522 guest: self.guest,
523 async_mode: None,
524 strict: false,
525 asmjs: false,
526 },
527 )
528 .to_eyre()
529 .wrap_err("Failed to transpile to JS.")
530 }
531}
532
533#[derive(Clone, Debug)]
535pub struct CustomInstantiationMode(Option<js_component_bindgen::InstantiationMode>);
536
537pub(super) mod analysis {
538 use js_component_bindgen::{BindingsMode, InstantiationMode};
539
540 use super::CustomInstantiationMode;
541
542 pub fn analysis_instantiation(s: &str) -> Result<CustomInstantiationMode, clap::Error> {
543 match s {
544 "Sync" => Ok(CustomInstantiationMode(Some(InstantiationMode::Sync))),
545 "Async" => Ok(CustomInstantiationMode(Some(InstantiationMode::Async))),
546 "Normal" => Ok(CustomInstantiationMode(None)),
547 _ => Ok(CustomInstantiationMode(Some(InstantiationMode::Async))),
548 }
549 }
550
551 pub fn analysis_import_bindings(s: &str) -> Result<Option<BindingsMode>, clap::Error> {
552 match s {
553 "Hybrid" => Ok(Some(BindingsMode::Hybrid)),
554 "Js" => Ok(Some(BindingsMode::Js)),
555 "Optimized" => Ok(Some(BindingsMode::Optimized)),
556 "DirectOptimized" => Ok(Some(BindingsMode::DirectOptimized)),
557 _ => Ok(None),
558 }
559 }
560
561 pub fn parse_mapping(s: &str) -> Result<(String, String), String> {
562 let parts: Vec<&str> = s.splitn(2, '=').collect();
563 if parts.len() != 2 {
564 return Err(format!("Invalid mapping format: '{}'", s));
565 }
566 Ok((parts[0].to_string(), parts[1].to_string()))
567 }
568}
569
570#[derive(
572 Debug,
573 Clone,
574 Copy,
575 PartialEq,
576 strum::EnumString,
577 strum::Display,
578 serde::Serialize,
579 serde::Deserialize,
580)]
581pub enum TargetMemoryType {
582 #[strum(ascii_case_insensitive)]
584 Single,
585 #[strum(ascii_case_insensitive)]
587 Multi,
588}
589
590impl TargetMemoryType {
591 pub fn is_multi(&self) -> bool {
593 matches!(self, TargetMemoryType::Multi)
594 }
595
596 pub fn is_single(&self) -> bool {
598 matches!(self, TargetMemoryType::Single)
599 }
600}
601
602#[derive(Parser, Debug, Clone, Default)]
604pub struct VfsBuildOptions {
605 #[arg(long, action = clap::ArgAction::Append)]
607 pub features: Vec<String>,
608
609 #[arg(long, action = clap::ArgAction::Count)]
611 pub no_default_features: u8,
612
613 #[arg(long = "vfs-unwind", default_value = "false")]
615 pub unwind: bool,
616
617 #[arg(long, action = clap::ArgAction::Count)]
619 pub no_opt: u8,
620
621 #[arg(long, action = clap::ArgAction::Count)]
623 pub no_opt_all: u8,
624}