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, default_value = "./dist")]
116 pub out_dir: Utf8PathBuf,
117
118 #[arg(short, long)]
121 pub target_memory_type: Option<TargetMemoryType>,
122
123 #[command(flatten)]
126 pub transpile_opts: TranspileOpts,
127
128 #[arg(long)]
131 pub threads: Option<bool>,
132
133 #[arg(long)]
137 pub dwarf: Option<bool>,
138
139 #[arg(long, default_value = "false")]
142 pub adjust_abi: bool,
143
144 #[arg(long, default_value = "false")]
146 pub keep_build_artifacts: bool,
147
148 #[arg(long, default_value = "false")]
150 pub dev: bool,
151
152 #[command(flatten)]
154 pub vfs_build_opts: VfsBuildOptions,
155
156 #[arg(skip)]
158 pub target_vfs_build_opts: Option<Box<[VfsBuildOptions]>>,
159}
160
161impl BuildArgs {
162 pub fn get_wasm_memory_hints(&self) -> Box<[Option<usize>]> {
164 self.wasm_memory_hint
165 .iter()
166 .map(|&hint| if hint < 0 { None } else { Some(hint as usize) })
167 .chain(std::iter::repeat(None))
168 .take(self.wasm.len())
169 .collect::<Box<_>>()
170 }
171
172 pub fn get_package(&self) -> eyre::Result<WasmPath> {
174 let mut p = Ok(self.package.clone()).transpose().unwrap_or_else(|| {
175 if let Some(ref manifest) = self.manifest_path {
176 WasmPath::with_maybe_only_manifest(manifest.clone())
177 } else {
178 WasmPath::with_maybe_none()
179 }
180 })?;
181 if let Some(ref manifest) = self.manifest_path {
182 if let WasmPath::Maybe { manifest_path, .. } = &mut p {
183 *manifest_path = manifest.clone();
184 }
185 }
186 Ok(p)
187 }
188
189 pub fn get_wasm_paths(&self) -> Box<[WasmPath]> {
191 let mut paths = self.wasm.clone();
192 if let Some(ref manifest) = self.manifest_path {
193 for p in &mut paths {
194 if let WasmPath::Maybe { manifest_path, .. } = p {
195 *manifest_path = manifest.clone();
196 }
197 }
198 }
199 paths.into_boxed_slice()
200 }
201}
202
203impl PostBuildContext for BuildArgs {
204 fn out_dir(&self) -> &Utf8PathBuf {
205 &self.out_dir
206 }
207
208 fn keep_build_artifacts(&self) -> bool {
209 self.keep_build_artifacts
210 }
211
212 fn adjust_abi(&self) -> bool {
213 self.adjust_abi
214 }
215
216 fn transpile_to_js(
217 &self,
218 component: &[u8],
219 name: impl AsRef<str>,
220 ) -> Result<js_component_bindgen::Transpiled, eyre::Error> {
221 self.transpile_opts.transpile_to_js(component, name)
222 }
223
224 fn dev(&self) -> bool {
225 self.dev
226 }
227}
228
229#[derive(Parser, Debug)]
230#[clap(author, version, about, long_about = None, help_template = "
231{name} {version}
232{author}
233{about}
234
235{usage-heading} {usage}
236
237{all-args}")]
238pub struct PreBuildArgs {
240 pub wasm: Vec<WasmPath>,
247
248 #[arg(short, long)]
250 package: Option<WasmPath>,
251
252 #[arg(long)]
254 pub manifest_path: Option<Utf8PathBuf>,
255
256 #[arg(long)]
258 wasm_memory_hint: Vec<isize>,
259
260 #[arg(long, default_value = "./dist")]
262 pub out_dir: Utf8PathBuf,
263
264 #[arg(short, long)]
267 pub target_memory_type: Option<TargetMemoryType>,
268
269 #[arg(long)]
272 pub threads: Option<bool>,
273
274 #[arg(long)]
278 pub dwarf: Option<bool>,
279
280 #[arg(long, default_value = "false")]
283 pub adjust_abi: bool,
284
285 #[arg(long, default_value = "false")]
287 pub keep_build_artifacts: bool,
288
289 #[arg(long, default_value = "false")]
291 pub dev: bool,
292
293 #[command(flatten)]
295 pub vfs_build_opts: VfsBuildOptions,
296
297 #[arg(skip)]
299 pub target_vfs_build_opts: Option<Box<[VfsBuildOptions]>>,
300}
301
302impl PreBuildArgs {
303 pub fn get_wasm_memory_hints(&self) -> Box<[Option<usize>]> {
305 self.wasm_memory_hint
306 .iter()
307 .map(|&hint| if hint < 0 { None } else { Some(hint as usize) })
308 .chain(std::iter::repeat(None))
309 .take(self.wasm.len())
310 .collect::<Box<_>>()
311 }
312
313 pub fn get_package(&self) -> eyre::Result<WasmPath> {
315 let mut p = Ok(self.package.clone()).transpose().unwrap_or_else(|| {
316 if let Some(ref manifest) = self.manifest_path {
317 WasmPath::with_maybe_only_manifest(manifest.clone())
318 } else {
319 WasmPath::with_maybe_none()
320 }
321 })?;
322 if let Some(ref manifest) = self.manifest_path {
323 if let WasmPath::Maybe { manifest_path, .. } = &mut p {
324 *manifest_path = manifest.clone();
325 }
326 }
327 Ok(p)
328 }
329
330 pub fn get_wasm_paths(&self) -> Box<[WasmPath]> {
332 let mut paths = self.wasm.clone();
333 if let Some(ref manifest) = self.manifest_path {
334 for p in &mut paths {
335 if let WasmPath::Maybe { manifest_path, .. } = p {
336 *manifest_path = manifest.clone();
337 }
338 }
339 }
340 paths.into_boxed_slice()
341 }
342}
343
344#[derive(Parser, Debug)]
345#[clap(author, version, about, long_about = None, help_template = "
346{name} {version}
347{author}
348{about}
349
350{usage-heading} {usage}
351
352{all-args}")]
353pub struct PostBuildArgs {
355 #[arg(short, long)]
357 pub package: WasmPath,
358
359 #[arg(long, default_value = "./dist")]
361 pub out_dir: Utf8PathBuf,
362
363 #[command(flatten)]
365 pub transpile_opts: TranspileOpts,
366
367 #[arg(long)]
369 pub dwarf: Option<bool>,
370
371 #[arg(long, default_value = "false")]
374 pub adjust_abi: bool,
375
376 #[arg(long, default_value = "false")]
378 pub keep_build_artifacts: bool,
379
380 #[arg(long, default_value = "false")]
382 pub dev: bool,
383}
384
385impl PostBuildContext for PostBuildArgs {
386 fn out_dir(&self) -> &Utf8PathBuf {
387 &self.out_dir
388 }
389
390 fn keep_build_artifacts(&self) -> bool {
391 self.keep_build_artifacts
392 }
393
394 fn adjust_abi(&self) -> bool {
395 self.adjust_abi
396 }
397
398 fn transpile_to_js(
399 &self,
400 component: &[u8],
401 name: impl AsRef<str>,
402 ) -> Result<js_component_bindgen::Transpiled, eyre::Error> {
403 self.transpile_opts.transpile_to_js(component, name)
404 }
405
406 fn dev(&self) -> bool {
407 self.dev
408 }
409}
410
411#[derive(Parser, Debug)]
413#[clap(author, version, about, long_about = None, help_template = "
414{name} {version}
415{author}
416{about}
417
418{usage-heading} {usage}
419
420{all-args}")]
421pub struct TranspileOpts {
422 #[arg(long, default_value = "false")]
424 no_typescript: bool,
425
426 #[arg(long, value_parser = analysis::analysis_instantiation, default_value = "CustomInstantiationMode(None)")]
429 instantiation: CustomInstantiationMode,
430
431 #[arg(long, value_parser = analysis::analysis_import_bindings)]
433 import_bindings: Option<js_component_bindgen::BindingsMode>,
434
435 #[arg(long, value_delimiter = ',', value_parser = analysis::parse_mapping, action = clap::ArgAction::Append)]
437 map: Vec<(String, String)>,
438
439 #[arg(long, default_value = "false")]
441 no_nodejs_compat: bool,
442
443 #[arg(long, default_value = "0")]
445 base64_cutoff: usize,
446
447 #[arg(long, default_value = "false")]
449 tla_compat: bool,
450
451 #[arg(long, default_value = "false")]
453 valid_lifting_optimization: bool,
454
455 #[arg(long, default_value = "false")]
457 tracing: bool,
458
459 #[arg(long, default_value = "false")]
461 no_namespaced_exports: bool,
462
463 #[arg(long, default_value = "false")]
465 pub guest: bool,
466}
467
468impl TranspileOpts {
469 pub fn transpile_to_js(
471 &self,
472 component: &[u8],
473 name: impl AsRef<str>,
474 ) -> Result<js_component_bindgen::Transpiled, eyre::Error> {
475 js_component_bindgen::transpile(
476 component,
477 js_component_bindgen::TranspileOpts {
478 name: name.as_ref().to_string(),
479 no_typescript: self.no_typescript,
480 instantiation_mode: self.instantiation.clone().0,
481 import_bindings: self.import_bindings.clone(),
482 map: if !self.map.is_empty() {
483 Some(self.map.iter().cloned().collect())
484 } else {
485 None
486 },
487 nodejs_compat_disabled: self.no_nodejs_compat,
488 base64_cutoff: self.base64_cutoff,
489 tla_compat: self.tla_compat,
490 valid_lifting_optimization: self.valid_lifting_optimization,
491 tracing: self.tracing,
492 no_namespaced_exports: self.no_namespaced_exports,
493 multi_memory: true,
494 guest: self.guest,
495 async_mode: None,
496 strict: false,
497 asmjs: false,
498 },
499 )
500 .to_eyre()
501 .wrap_err("Failed to transpile to JS.")
502 }
503}
504
505#[derive(Clone, Debug)]
507pub struct CustomInstantiationMode(Option<js_component_bindgen::InstantiationMode>);
508
509pub(super) mod analysis {
510 use js_component_bindgen::{BindingsMode, InstantiationMode};
511
512 use super::CustomInstantiationMode;
513
514 pub fn analysis_instantiation(s: &str) -> Result<CustomInstantiationMode, clap::Error> {
515 match s {
516 "Sync" => Ok(CustomInstantiationMode(Some(InstantiationMode::Sync))),
517 "Async" => Ok(CustomInstantiationMode(Some(InstantiationMode::Async))),
518 "Normal" => Ok(CustomInstantiationMode(None)),
519 _ => Ok(CustomInstantiationMode(Some(InstantiationMode::Async))),
520 }
521 }
522
523 pub fn analysis_import_bindings(s: &str) -> Result<Option<BindingsMode>, clap::Error> {
524 match s {
525 "Hybrid" => Ok(Some(BindingsMode::Hybrid)),
526 "Js" => Ok(Some(BindingsMode::Js)),
527 "Optimized" => Ok(Some(BindingsMode::Optimized)),
528 "DirectOptimized" => Ok(Some(BindingsMode::DirectOptimized)),
529 _ => Ok(None),
530 }
531 }
532
533 pub fn parse_mapping(s: &str) -> Result<(String, String), String> {
534 let parts: Vec<&str> = s.splitn(2, '=').collect();
535 if parts.len() != 2 {
536 return Err(format!("Invalid mapping format: '{}'", s));
537 }
538 Ok((parts[0].to_string(), parts[1].to_string()))
539 }
540}
541
542#[derive(
544 Debug,
545 Clone,
546 Copy,
547 PartialEq,
548 strum::EnumString,
549 strum::Display,
550 serde::Serialize,
551 serde::Deserialize,
552)]
553pub enum TargetMemoryType {
554 #[strum(ascii_case_insensitive)]
556 Single,
557 #[strum(ascii_case_insensitive)]
559 Multi,
560}
561
562impl TargetMemoryType {
563 pub fn is_multi(&self) -> bool {
565 matches!(self, TargetMemoryType::Multi)
566 }
567
568 pub fn is_single(&self) -> bool {
570 matches!(self, TargetMemoryType::Single)
571 }
572}
573
574#[derive(Parser, Debug, Clone, Default)]
576pub struct VfsBuildOptions {
577 #[arg(long, action = clap::ArgAction::Append)]
579 pub features: Vec<String>,
580
581 #[arg(long, action = clap::ArgAction::Count)]
583 pub no_default_features: u8,
584
585 #[arg(long, action = clap::ArgAction::Count)]
587 pub no_opt: u8,
588
589 #[arg(long, action = clap::ArgAction::Count)]
591 pub no_opt_all: u8,
592}