Skip to main content

componentize_qjs_cli/
cli.rs

1use componentize_qjs::{ComponentizeOpts, Runtime, componentize};
2
3use anyhow::{Context, Result};
4use clap::Parser;
5use oxc_allocator::Allocator;
6use oxc_codegen::Codegen;
7use oxc_minifier::{
8    CompressOptions, CompressOptionsKeepNames, CompressOptionsUnused, MangleOptions, Minifier,
9    MinifierOptions,
10};
11use oxc_parser::Parser as OxcParser;
12use oxc_span::SourceType;
13
14use std::fs;
15
16#[derive(Parser)]
17#[command(name = "componentize-qjs")]
18#[command(about = "Convert JavaScript to WebAssembly components using QuickJS")]
19pub struct CliArgs {
20    /// Path to the WIT file or directory
21    #[arg(short, long)]
22    pub wit: std::path::PathBuf,
23
24    /// Path to the JavaScript source file
25    #[arg(short, long)]
26    pub js: std::path::PathBuf,
27
28    /// Root directory exposed during Wizer for resolving JavaScript imports
29    #[arg(long, value_name = "PATH")]
30    pub module_root: Option<std::path::PathBuf>,
31
32    /// Output path for the component
33    #[arg(short, long, default_value = "output.wasm")]
34    pub output: std::path::PathBuf,
35
36    /// World name to use from the WIT
37    #[arg(short = 'n', long)]
38    pub world: Option<String>,
39
40    /// Stub all WASI imports with traps
41    #[arg(long)]
42    pub stub_wasi: bool,
43
44    /// Minify the JS source via oxc before componentizing
45    #[arg(short = 'm', long)]
46    pub minify: bool,
47
48    /// Disable automatic garbage collection in the QuickJS runtime
49    #[arg(long)]
50    pub disable_gc: bool,
51
52    /// Use the built-in runtime optimized for smaller generated components
53    #[arg(long, conflicts_with = "runtime")]
54    pub opt_size: bool,
55
56    /// Use the built-in non-async runtime, producing components that do not use
57    /// the component-model async ABI
58    #[arg(long, conflicts_with = "runtime")]
59    pub sync: bool,
60
61    /// Path to a custom QuickJS runtime Wasm module
62    #[arg(long, value_name = "PATH")]
63    pub runtime: Option<std::path::PathBuf>,
64}
65
66/// Run the componentize-qjs CLI with the given arguments.
67pub async fn run(args: Vec<String>) -> Result<()> {
68    let args =
69        CliArgs::try_parse_from(std::iter::once("componentize-qjs".to_string()).chain(args))?;
70
71    if !args.wit.exists() {
72        anyhow::bail!("WIT file/directory not found: {}", args.wit.display());
73    }
74    if !args.js.exists() {
75        anyhow::bail!("JavaScript file not found: {}", args.js.display());
76    }
77    if let Some(runtime_file) = &args.runtime
78        && !runtime_file.exists()
79    {
80        anyhow::bail!("Runtime file not found: {}", runtime_file.display());
81    }
82    if let Some(module_root) = &args.module_root
83        && !module_root.exists()
84    {
85        anyhow::bail!("Module root not found: {}", module_root.display());
86    }
87
88    let js_source = fs::read_to_string(&args.js)
89        .with_context(|| format!("failed to read JS file: {}", args.js.display()))?;
90
91    let js_source = if args.minify {
92        let allocator = Allocator::default();
93        let source_type = SourceType::mjs();
94        let ret = OxcParser::new(&allocator, &js_source, source_type).parse();
95
96        if let Some(diagnostic) = ret.diagnostics.first() {
97            anyhow::bail!("failed to parse JavaScript before minification: {diagnostic}");
98        }
99
100        let mut program = ret.program;
101        let options = MinifierOptions {
102            mangle: Some(MangleOptions {
103                top_level: Some(false),
104                ..Default::default()
105            }),
106            mangle_properties: None,
107            compress: Some(CompressOptions {
108                unused: CompressOptionsUnused::Keep,
109                keep_names: CompressOptionsKeepNames::all_false(),
110                ..CompressOptions::default()
111            }),
112        };
113
114        let ret = Minifier::new(options).minify(&allocator, &mut program);
115        Codegen::new()
116            .with_scoping(ret.scoping)
117            .build(&program)
118            .code
119    } else {
120        js_source
121    };
122
123    println!("componentize-qjs");
124    println!("  WIT:    {}", args.wit.display());
125    println!("  JS:     {}", args.js.display());
126    println!("  Output: {}", args.output.display());
127
128    let custom_runtime = args
129        .runtime
130        .as_ref()
131        .map(|file| fs::read(file).context("failed to read runtime file"))
132        .transpose()?;
133
134    let runtime = match custom_runtime.as_deref() {
135        Some(wasm) => Runtime::Custom(wasm),
136        None => Runtime::builtin(args.sync, args.opt_size),
137    };
138
139    if args.stub_wasi {
140        println!("Stubbing WASI imports...");
141    }
142
143    let component = componentize(&ComponentizeOpts {
144        wit_path: &args.wit,
145        js_source: &js_source,
146        js_path: Some(&args.js),
147        module_root: args.module_root.as_deref(),
148        world_name: args.world.as_deref(),
149        stub_wasi: args.stub_wasi,
150        disable_gc: args.disable_gc,
151        runtime,
152    })
153    .await?;
154
155    fs::write(&args.output, &component)
156        .with_context(|| format!("failed to write output to {}", args.output.display()))?;
157
158    println!("Component written to {}", args.output.display());
159    println!("  Size: {} bytes", component.len());
160
161    Ok(())
162}