1use camino::Utf8PathBuf;
2use clap::{Parser, Subcommand};
3use compact_str::CompactString;
4use eyre::Context as _;
5
6use crate::{generator::WasmPath, util::ResultUtil as _};
7
8pub trait PostBuildContext {
10 fn out_dir(&self) -> &Utf8PathBuf;
12 fn keep_build_artifacts(&self) -> bool;
14 fn adjust_abi(&self) -> bool;
16 fn transpile_to_js(
18 &self,
19 component: &[u8],
20 name: impl AsRef<str>,
21 ) -> Result<js_component_bindgen::Transpiled, eyre::Error>;
22}
23
24#[derive(Parser, Debug)]
26#[clap(author, version, about, long_about = None)]
27#[clap(propagate_version = true)]
28pub struct Cli {
29 #[clap(subcommand)]
31 pub command: Command,
32}
33
34#[derive(Subcommand, Debug)]
35pub enum Command {
37 Build(BuildArgs),
39 Prebuild(PreBuildArgs),
41 Postbuild(PostBuildArgs),
43 New(NewArgs),
45}
46
47#[derive(Parser, Debug)]
48pub struct NewArgs {
50 #[arg(value_name = "PATH")]
52 pub path: Utf8PathBuf,
53
54 #[arg(long, default_value = "false")]
56 pub threads: bool,
57}
58
59#[derive(Parser, Debug)]
60pub struct BuildArgs {
62 pub wasm: Vec<WasmPath>,
69
70 #[arg(short, long)]
72 package: Option<WasmPath>,
73
74 #[arg(long)]
76 wasm_memory_hint: Vec<isize>,
77
78 #[arg(long, default_value = "./dist")]
80 pub out_dir: Utf8PathBuf,
81
82 #[arg(short, long)]
85 pub target_memory_type: Option<TargetMemoryType>,
86
87 #[command(flatten)]
90 pub transpile_opts: TranspileOpts,
91
92 #[arg(long)]
95 pub threads: Option<bool>,
96
97 #[arg(long)]
101 pub dwarf: Option<bool>,
102
103 #[arg(long, default_value = "false")]
106 pub adjust_abi: bool,
107
108 #[arg(long, default_value = "false")]
110 pub keep_build_artifacts: bool,
111}
112
113impl BuildArgs {
114 pub fn get_wasm_memory_hints(&self) -> Box<[Option<usize>]> {
116 self.wasm_memory_hint
117 .iter()
118 .map(|&hint| if hint < 0 { None } else { Some(hint as usize) })
119 .chain(std::iter::repeat(None))
120 .take(self.wasm.len())
121 .collect::<Box<_>>()
122 }
123
124 pub fn get_package(&self) -> eyre::Result<WasmPath> {
126 Ok(self.package.clone())
127 .transpose()
128 .unwrap_or_else(|| WasmPath::with_maybe_none())
129 }
130
131 pub fn get_manifest_path(&self) -> Option<&Utf8PathBuf> {
133 self.package.as_ref().and_then(|p| p.manifest_path())
134 }
135
136 pub fn get_package_name(&self) -> Option<CompactString> {
138 self.package.clone().and_then(|p| p.name().ok())
139 }
140}
141
142impl PostBuildContext for BuildArgs {
143 fn out_dir(&self) -> &Utf8PathBuf {
144 &self.out_dir
145 }
146
147 fn keep_build_artifacts(&self) -> bool {
148 self.keep_build_artifacts
149 }
150
151 fn adjust_abi(&self) -> bool {
152 self.adjust_abi
153 }
154
155 fn transpile_to_js(
156 &self,
157 component: &[u8],
158 name: impl AsRef<str>,
159 ) -> Result<js_component_bindgen::Transpiled, eyre::Error> {
160 self.transpile_opts.transpile_to_js(component, name)
161 }
162}
163
164#[derive(Parser, Debug)]
165pub struct PreBuildArgs {
167 pub wasm: Vec<WasmPath>,
174
175 #[arg(short, long)]
177 package: Option<WasmPath>,
178
179 #[arg(long)]
181 wasm_memory_hint: Vec<isize>,
182
183 #[arg(long, default_value = "./dist")]
185 pub out_dir: Utf8PathBuf,
186
187 #[arg(short, long)]
190 pub target_memory_type: Option<TargetMemoryType>,
191
192 #[arg(long)]
195 pub threads: Option<bool>,
196
197 #[arg(long)]
201 pub dwarf: Option<bool>,
202
203 #[arg(long, default_value = "false")]
206 pub adjust_abi: bool,
207
208 #[arg(long, default_value = "false")]
210 pub keep_build_artifacts: bool,
211}
212
213impl PreBuildArgs {
214 pub fn get_wasm_memory_hints(&self) -> Box<[Option<usize>]> {
216 self.wasm_memory_hint
217 .iter()
218 .map(|&hint| if hint < 0 { None } else { Some(hint as usize) })
219 .chain(std::iter::repeat(None))
220 .take(self.wasm.len())
221 .collect::<Box<_>>()
222 }
223
224 pub fn get_package(&self) -> eyre::Result<WasmPath> {
226 Ok(self.package.clone())
227 .transpose()
228 .unwrap_or_else(|| WasmPath::with_maybe_none())
229 }
230}
231
232#[derive(Parser, Debug)]
233pub struct PostBuildArgs {
235 #[arg(short, long)]
237 pub package: WasmPath,
238
239 #[arg(long, default_value = "./dist")]
241 pub out_dir: Utf8PathBuf,
242
243 #[command(flatten)]
245 pub transpile_opts: TranspileOpts,
246
247 #[arg(long)]
249 pub dwarf: Option<bool>,
250
251 #[arg(long, default_value = "false")]
254 pub adjust_abi: bool,
255
256 #[arg(long, default_value = "false")]
258 pub keep_build_artifacts: bool,
259}
260
261impl PostBuildContext for PostBuildArgs {
262 fn out_dir(&self) -> &Utf8PathBuf {
263 &self.out_dir
264 }
265
266 fn keep_build_artifacts(&self) -> bool {
267 self.keep_build_artifacts
268 }
269
270 fn adjust_abi(&self) -> bool {
271 self.adjust_abi
272 }
273
274 fn transpile_to_js(
275 &self,
276 component: &[u8],
277 name: impl AsRef<str>,
278 ) -> Result<js_component_bindgen::Transpiled, eyre::Error> {
279 self.transpile_opts.transpile_to_js(component, name)
280 }
281}
282
283#[derive(Parser, Debug)]
285pub struct TranspileOpts {
286 #[arg(long, default_value = "false")]
288 no_typescript: bool,
289
290 #[arg(long, value_parser = analysis::analysis_instantiation, default_value = "CustomInstantiationMode(None)")]
293 instantiation: CustomInstantiationMode,
294
295 #[arg(long, value_parser = analysis::analysis_import_bindings)]
297 import_bindings: Option<js_component_bindgen::BindingsMode>,
298
299 #[arg(long, value_delimiter = ',', value_parser = analysis::parse_mapping, action = clap::ArgAction::Append)]
301 map: Vec<(String, String)>,
302
303 #[arg(long, default_value = "false")]
305 no_nodejs_compat: bool,
306
307 #[arg(long, default_value = "0")]
309 base64_cutoff: usize,
310
311 #[arg(long, default_value = "false")]
313 tla_compat: bool,
314
315 #[arg(long, default_value = "false")]
317 valid_lifting_optimization: bool,
318
319 #[arg(long, default_value = "false")]
321 tracing: bool,
322
323 #[arg(long, default_value = "false")]
325 no_namespaced_exports: bool,
326
327 #[arg(long, default_value = "false")]
329 pub guest: bool,
330}
331
332impl TranspileOpts {
333 pub fn transpile_to_js(
335 &self,
336 component: &[u8],
337 name: impl AsRef<str>,
338 ) -> Result<js_component_bindgen::Transpiled, eyre::Error> {
339 js_component_bindgen::transpile(
340 component,
341 js_component_bindgen::TranspileOpts {
342 name: name.as_ref().to_string(),
343 no_typescript: self.no_typescript,
344 instantiation: self.instantiation.clone().0,
345 import_bindings: self.import_bindings.clone(),
346 map: if !self.map.is_empty() {
347 Some(self.map.iter().cloned().collect())
348 } else {
349 None
350 },
351 no_nodejs_compat: self.no_nodejs_compat,
352 base64_cutoff: self.base64_cutoff,
353 tla_compat: self.tla_compat,
354 valid_lifting_optimization: self.valid_lifting_optimization,
355 tracing: self.tracing,
356 no_namespaced_exports: self.no_namespaced_exports,
357 multi_memory: true,
358 guest: self.guest,
359 async_mode: None,
360 strict: false,
361 asmjs: false,
362 },
363 )
364 .to_eyre()
365 .wrap_err("Failed to transpile to JS.")
366 }
367}
368
369#[derive(Clone, Debug)]
371pub struct CustomInstantiationMode(Option<js_component_bindgen::InstantiationMode>);
372
373pub(super) mod analysis {
374 use js_component_bindgen::{BindingsMode, InstantiationMode};
375
376 use super::CustomInstantiationMode;
377
378 pub fn analysis_instantiation(s: &str) -> Result<CustomInstantiationMode, clap::Error> {
379 match s {
380 "Sync" => Ok(CustomInstantiationMode(Some(InstantiationMode::Sync))),
381 "Async" => Ok(CustomInstantiationMode(Some(InstantiationMode::Async))),
382 "Normal" => Ok(CustomInstantiationMode(None)),
383 _ => Ok(CustomInstantiationMode(Some(InstantiationMode::Async))),
384 }
385 }
386
387 pub fn analysis_import_bindings(s: &str) -> Result<Option<BindingsMode>, clap::Error> {
388 match s {
389 "Hybrid" => Ok(Some(BindingsMode::Hybrid)),
390 "Js" => Ok(Some(BindingsMode::Js)),
391 "Optimized" => Ok(Some(BindingsMode::Optimized)),
392 "DirectOptimized" => Ok(Some(BindingsMode::DirectOptimized)),
393 _ => Ok(None),
394 }
395 }
396
397 pub fn parse_mapping(s: &str) -> Result<(String, String), String> {
398 let parts: Vec<&str> = s.splitn(2, '=').collect();
399 if parts.len() != 2 {
400 return Err(format!("Invalid mapping format: '{}'", s));
401 }
402 Ok((parts[0].to_string(), parts[1].to_string()))
403 }
404}
405
406#[derive(Debug, Clone, Copy, PartialEq, strum::EnumString, strum::Display)]
408pub enum TargetMemoryType {
409 #[strum(ascii_case_insensitive)]
411 Single,
412 #[strum(ascii_case_insensitive)]
414 Multi,
415}
416
417impl TargetMemoryType {
418 pub fn is_multi(&self) -> bool {
420 matches!(self, TargetMemoryType::Multi)
421 }
422
423 pub fn is_single(&self) -> bool {
425 matches!(self, TargetMemoryType::Single)
426 }
427}