-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathwasm2es6js.rs
73 lines (65 loc) · 2.35 KB
/
wasm2es6js.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
use anyhow::{Context, Error};
use clap::Parser;
use std::fs;
use std::path::PathBuf;
#[derive(Parser, Debug)]
#[command(
name = "wasm2es6js",
version,
about,
long_about = None,
after_help = "Note that this is not intended to produce a production-ready output module but rather\n\
is intended purely as a temporary \"hack\" until it's standard in\n\
bundlers for working with wasm. Use this program with care!",
)]
struct Args {
#[arg(long, short, value_name = "FILE", help = "File to place output in")]
output: Option<PathBuf>,
#[arg(long, value_name = "DIR", help = "Directory to place output in")]
out_dir: Option<PathBuf>,
#[arg(long, help = "Output a `*.d.ts` file next to the JS output")]
typescript: bool,
#[arg(long, help = "Inline the Wasm module using base64 encoding")]
base64: bool,
#[arg(
long,
value_name = "PATH",
help = "Load module by passing the PATH argument to `fetch()`"
)]
fetch: Option<String>,
input: PathBuf,
}
fn main() -> anyhow::Result<()> {
let args = Args::parse();
let wasm = fs::read(&args.input)
.with_context(|| format!("failed to read `{}`", args.input.display()))?;
let object = wasm_bindgen_cli_support::wasm2es6js::Config::new()
.base64(args.base64)
.fetch(args.fetch.clone())
.generate(&wasm)?;
if args.typescript {
let ts = object.typescript()?;
write(&args, "d.ts", ts.as_bytes(), false)?;
}
let (js, wasm) = object.js_and_wasm()?;
write(&args, "js", js.as_bytes(), false)?;
if let Some(wasm) = wasm {
write(&args, "wasm", &wasm, false)?;
}
Ok(())
}
fn write(args: &Args, extension: &str, contents: &[u8], print_fallback: bool) -> Result<(), Error> {
if let Some(p) = &args.output {
let dst = p.with_extension(extension);
fs::write(&dst, contents)
.with_context(|| format!("failed to write `{}`", dst.display()))?;
} else if let Some(p) = &args.out_dir {
let filename = args.input.file_name().unwrap();
let dst = p.join(filename).with_extension(extension);
fs::write(&dst, contents)
.with_context(|| format!("failed to write `{}`", dst.display()))?;
} else if print_fallback {
println!("{}", String::from_utf8_lossy(contents))
}
Ok(())
}