wasm_bindgen_cli_support/
wasm2es6js.rs1use anyhow::{bail, Error};
2use base64::{prelude::BASE64_STANDARD, Engine as _};
3use std::collections::HashSet;
4use std::fmt::Write;
5use walrus::Module;
6
7pub struct Config {
8 base64: bool,
9 fetch_path: Option<String>,
10}
11
12pub struct Output {
13 module: Module,
14 base64: bool,
15 fetch_path: Option<String>,
16}
17
18impl Config {
19 pub fn new() -> Config {
20 Config {
21 base64: false,
22 fetch_path: None,
23 }
24 }
25
26 pub fn base64(&mut self, base64: bool) -> &mut Self {
27 self.base64 = base64;
28 self
29 }
30
31 pub fn fetch(&mut self, path: Option<String>) -> &mut Self {
32 self.fetch_path = path;
33 self
34 }
35
36 pub fn generate(&mut self, wasm: &[u8]) -> Result<Output, Error> {
37 if !self.base64 && self.fetch_path.is_none() {
38 bail!("one of --base64 or --fetch is required");
39 }
40 let module = Module::from_buffer(wasm)?;
41 Ok(Output {
42 module,
43 base64: self.base64,
44 fetch_path: self.fetch_path.clone(),
45 })
46 }
47}
48
49fn push_index_identifier(i: usize, s: &mut String) {
52 let letter = b'a' + ((i % 26) as u8);
53 s.push(letter as char);
54 if i >= 26 {
55 write!(s, "{}", i / 26).unwrap();
56 }
57}
58
59fn args_are_optional(name: &str) -> bool {
60 name == "__wbindgen_thread_destroy"
61}
62
63pub fn interface(module: &Module) -> Result<String, Error> {
64 let mut exports = String::new();
65 module_export_types(module, |name, ty| {
66 writeln!(exports, " readonly {name}: {ty};").unwrap();
67 });
68 Ok(exports)
69}
70
71pub fn typescript(module: &Module) -> Result<String, Error> {
72 let mut exports = "/* tslint:disable */\n/* eslint-disable */\n".to_string();
73 module_export_types(module, |name, ty| {
74 writeln!(exports, "export const {name}: {ty};").unwrap();
75 });
76 Ok(exports)
77}
78
79fn module_export_types(module: &Module, mut export: impl FnMut(&str, &str)) {
82 for entry in module.exports.iter() {
83 match entry.item {
84 walrus::ExportItem::Function(id) => {
85 let func = module.funcs.get(id);
86 let ty = module.types.get(func.ty());
87 let ts_type = function_type_to_ts(ty, args_are_optional(&entry.name));
88 export(&entry.name, &ts_type);
89 }
90 walrus::ExportItem::Memory(_) => export(&entry.name, "WebAssembly.Memory"),
91 walrus::ExportItem::Table(_) => export(&entry.name, "WebAssembly.Table"),
92 walrus::ExportItem::Global(_) => continue,
93 };
94 }
95}
96fn val_type_to_ts(ty: walrus::ValType) -> &'static str {
97 match ty {
100 walrus::ValType::I32 | walrus::ValType::F32 | walrus::ValType::F64 => "number",
101 walrus::ValType::I64 => "bigint",
102 walrus::ValType::Ref(_) => "any",
104 walrus::ValType::V128 => "any",
109 }
110}
111fn function_type_to_ts(function: &walrus::Type, all_args_optional: bool) -> String {
112 let mut out = String::new();
113
114 out.push('(');
116 for (i, arg_type) in function.params().iter().enumerate() {
117 if i > 0 {
118 out.push_str(", ");
119 }
120
121 push_index_identifier(i, &mut out);
122 if all_args_optional {
123 out.push('?');
124 }
125 out.push_str(": ");
126 out.push_str(val_type_to_ts(*arg_type));
127 }
128 out.push(')');
129
130 out.push_str(" => ");
132
133 let results = function.results();
135 match results.len() {
138 0 => out.push_str("void"),
139 1 => out.push_str(val_type_to_ts(results[0])),
140 _ => {
141 out.push('[');
142 for (i, result) in results.iter().enumerate() {
143 if i > 0 {
144 out.push_str(", ");
145 }
146 out.push_str(val_type_to_ts(*result));
147 }
148 out.push(']');
149 }
150 }
151
152 out
153}
154
155impl Output {
156 pub fn typescript(&self) -> Result<String, Error> {
157 let mut ts = typescript(&self.module)?;
158 if self.base64 {
159 ts.push_str("export const booted: Promise<boolean>;\n");
160 }
161 Ok(ts)
162 }
163
164 pub fn js_and_wasm(mut self) -> Result<(String, Option<Vec<u8>>), Error> {
165 let mut js_imports = String::new();
166 let mut exports = String::new();
167 let mut set_exports = String::new();
168 let mut imports = String::new();
169
170 let mut set = HashSet::new();
171 for entry in self.module.imports.iter() {
172 if !set.insert(&entry.module) {
173 continue;
174 }
175
176 let mut name = String::new();
177 push_index_identifier(set.len(), &mut name);
178
179 js_imports.push_str(&format!(
180 "import * as import_{} from '{}';\n",
181 name, entry.module
182 ));
183 imports.push_str(&format!("'{}': import_{}, ", entry.module, name));
184 }
185
186 for entry in self.module.exports.iter() {
187 exports.push_str("export let ");
188 exports.push_str(&entry.name);
189 exports.push_str(";\n");
190 set_exports.push_str(&entry.name);
191 set_exports.push_str(" = wasm.exports.");
192 set_exports.push_str(&entry.name);
193 set_exports.push_str(";\n");
194 }
195
196 if self.unstart() {
215 set_exports.push_str("wasm.exports.__wasm2es6js_start();\n");
216 }
217
218 let inst = format!(
219 "
220 WebAssembly.instantiate(bytes,{{ {imports} }})
221 .then(obj => {{
222 const wasm = obj.instance;
223 {set_exports}
224 }})
225 ",
226 );
227 let wasm = self.module.emit_wasm();
228 let (bytes, booted) = if self.base64 {
229 (
230 format!(
231 "
232 let bytes;
233 const base64 = \"{base64}\";
234 if (typeof Buffer === 'undefined') {{
235 bytes = Uint8Array.from(atob(base64), c => c.charCodeAt(0));
236 }} else {{
237 bytes = Buffer.from(base64, 'base64');
238 }}
239 ",
240 base64 = BASE64_STANDARD.encode(&wasm)
241 ),
242 inst,
243 )
244 } else if let Some(ref path) = self.fetch_path {
245 (
246 String::new(),
247 format!(
248 "
249 fetch('{path}')
250 .then(res => res.arrayBuffer())
251 .then(bytes => {inst})
252 "
253 ),
254 )
255 } else {
256 bail!("the option --base64 or --fetch is required");
257 };
258 let js = format!(
259 "\
260 {js_imports}
261 {bytes}
262 export const booted = {booted};
263 {exports}
264 ",
265 );
266 let wasm = if self.base64 { None } else { Some(wasm) };
267 Ok((js, wasm))
268 }
269
270 fn unstart(&mut self) -> bool {
274 let start = match self.module.start.take() {
275 Some(id) => id,
276 None => return false,
277 };
278 self.module.exports.add("__wasm2es6js_start", start);
279 true
280 }
281}
282
283#[cfg(test)]
284mod tests {
285 use super::*;
286
287 #[test]
288 fn test_push_index_identifier() {
289 fn index_identifier(i: usize) -> String {
290 let mut s = String::new();
291 push_index_identifier(i, &mut s);
292 s
293 }
294
295 assert_eq!(index_identifier(0), "a");
296 assert_eq!(index_identifier(1), "b");
297 assert_eq!(index_identifier(25), "z");
298 assert_eq!(index_identifier(26), "a1");
299 assert_eq!(index_identifier(27), "b1");
300 assert_eq!(index_identifier(51), "z1");
301 assert_eq!(index_identifier(52), "a2");
302 assert_eq!(index_identifier(53), "b2");
303 assert_eq!(index_identifier(260), "a10");
304 assert_eq!(index_identifier(261), "b10");
305 }
306}