From 8daa5bb914734e7f4e57c4147f9f99a829f09c93 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BE=A1=E9=A3=8E?= <18012261618@126.com> Date: Wed, 27 Nov 2024 15:21:14 +0800 Subject: [PATCH 01/10] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8Dload=20.wasm?= =?UTF-8?q?=E6=96=87=E4=BB=B6=E5=AF=B9importObject=E7=9A=84=E5=A4=84?= =?UTF-8?q?=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Cargo.lock | 14 ++ crates/mako/Cargo.toml | 1 + crates/mako/src/plugins/wasm_runtime.rs | 91 +++++++++++- examples/import-resources/index.tsx | 5 + .../minus-wasm-pack/index.d.ts | 15 ++ .../import-resources/minus-wasm-pack/index.js | 4 + .../minus-wasm-pack/index_bg.js | 133 ++++++++++++++++++ .../minus-wasm-pack/index_bg.wasm | Bin 0 -> 17815 bytes .../minus-wasm-pack/index_bg.wasm.d.ts | 13 ++ 9 files changed, 275 insertions(+), 1 deletion(-) create mode 100644 examples/import-resources/minus-wasm-pack/index.d.ts create mode 100644 examples/import-resources/minus-wasm-pack/index.js create mode 100644 examples/import-resources/minus-wasm-pack/index_bg.js create mode 100644 examples/import-resources/minus-wasm-pack/index_bg.wasm create mode 100644 examples/import-resources/minus-wasm-pack/index_bg.wasm.d.ts diff --git a/Cargo.lock b/Cargo.lock index 0b3a7b6b8..0a21219dc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2817,6 +2817,7 @@ dependencies = [ "tungstenite", "twox-hash", "url", + "wasmparser", ] [[package]] @@ -6878,6 +6879,19 @@ version = "0.2.93" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c62a0a307cb4a311d3a07867860911ca130c3494e8c2719593806c08bc5d0484" +[[package]] +name = "wasmparser" +version = "0.207.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e19bb9f8ab07616da582ef8adb24c54f1424c7ec876720b7da9db8ec0626c92c" +dependencies = [ + "ahash 0.8.11", + "bitflags 2.6.0", + "hashbrown 0.14.5", + "indexmap 2.5.0", + "semver 1.0.23", +] + [[package]] name = "wayland-client" version = "0.29.5" diff --git a/crates/mako/Cargo.toml b/crates/mako/Cargo.toml index 4c0cc4cc2..b0835cf3f 100644 --- a/crates/mako/Cargo.toml +++ b/crates/mako/Cargo.toml @@ -27,6 +27,7 @@ percent-encoding = { version = "2.3.1" } serde = { workspace = true } serde_json = { workspace = true } url = { version = "2.5.0" } +wasmparser = "0.207.0" swc_core = { workspace = true, features = [ "base", diff --git a/crates/mako/src/plugins/wasm_runtime.rs b/crates/mako/src/plugins/wasm_runtime.rs index 9feb48973..d862c6c30 100644 --- a/crates/mako/src/plugins/wasm_runtime.rs +++ b/crates/mako/src/plugins/wasm_runtime.rs @@ -1,9 +1,14 @@ +use std::collections::HashMap; +use std::fs::File; +use std::io::Read; use std::sync::Arc; use anyhow; +use wasmparser::{Import, Parser, Payload}; +use crate::ast::file::{Content, JsContent}; use crate::compiler::Context; -use crate::plugin::Plugin; +use crate::plugin::{Plugin, PluginLoadParam}; pub struct WasmRuntimePlugin {} @@ -27,4 +32,88 @@ impl Plugin for WasmRuntimePlugin { Ok(vec![]) } } + + fn load( + &self, + param: &PluginLoadParam, + _context: &Arc, + ) -> anyhow::Result> { + let file = param.file; + if file.path.to_string_lossy().ends_with(".wasm") { + let final_file_name = format!( + "{}.{}.{}", + file.get_file_stem(), + file.get_content_hash()?, + file.extname + ); + let origin_path = file.pathname.to_string_lossy().to_string(); + _context.emit_assets(origin_path, final_file_name.clone()); + + let mut buffer = Vec::new(); + File::open(file.path.as_path())?.read_to_end(&mut buffer)?; + // Parse wasm file to get imports + let mut import_objs_map: HashMap<&str, Vec> = HashMap::new(); + for payload in Parser::new(0).parse_all(&buffer) { + if let Ok(Payload::ImportSection(imports)) = payload { + for import in imports { + match import { + Ok(Import { module, name, ty }) => { + if let Some(import_obj) = import_objs_map.get_mut(module) { + import_obj.push(name.to_string()); + } else { + import_objs_map.insert(module, vec![name.to_string()]); + } + } + Err(_) => { + println!("import error"); + } + } + } + } + } + + let mut js_imports_str = String::new(); + let mut import_objs_str = String::new(); + + for (index, (key, value)) in import_objs_map.iter().enumerate() { + js_imports_str.push_str(&format!( + "import * as module{module_idx} from \"{module}\";\n", + module_idx = index, + module = key + )); + + import_objs_str.push_str(&format!( + "\"{module}\": {{ {names} }}", + module = key, + names = value + .iter() + .map(|name| format!("{}: module{}.{}", name, index, name)) + .collect::>() + .join(", ") + )); + } + + let mut content = String::new(); + content.push_str(&js_imports_str); + + if import_objs_str.is_empty() { + content.push_str(&format!( + "module.exports = require._interopreRequireWasm(exports, \"{}\")", + final_file_name + )); + } else { + content.push_str(&format!( + "module.exports = require._interopreRequireWasm(exports, \"{}\", {{{}}})", + final_file_name, import_objs_str + )); + } + + return Ok(Some(Content::Js(JsContent { + content, + ..Default::default() + }))); + } + + Ok(None) + } } diff --git a/examples/import-resources/index.tsx b/examples/import-resources/index.tsx index f5313c77e..afdc166e2 100644 --- a/examples/import-resources/index.tsx +++ b/examples/import-resources/index.tsx @@ -7,6 +7,7 @@ import toml, { title } from './index.toml'; import xml from './index.xml'; import yaml, { pi } from './index.yaml'; import MailchimpUnsplash from './mailchimp-unsplash.jpg'; +import * as wasm from './minus-wasm-pack'; const num1 = 10; const num2 = 20; @@ -32,6 +33,10 @@ function App() {

Test import .wasm file async: {num1} + {num2} = {sum}

+

+ Test import .wasm file(generated by wasm-pack) async: {num1} - {num2} ={' '} + {wasm.minus(num1, num2)} +

Test import .toml file

{JSON.stringify(toml, null, 2)}
diff --git a/examples/import-resources/minus-wasm-pack/index.d.ts b/examples/import-resources/minus-wasm-pack/index.d.ts new file mode 100644 index 000000000..1a32e9455 --- /dev/null +++ b/examples/import-resources/minus-wasm-pack/index.d.ts @@ -0,0 +1,15 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + */ +export function greet(): void; +/** + * @param {string} name + */ +export function greet2(name: string): void; +/** + * @param {number} a + * @param {number} b + * @returns {number} + */ +export function minus(a: number, b: number): number; diff --git a/examples/import-resources/minus-wasm-pack/index.js b/examples/import-resources/minus-wasm-pack/index.js new file mode 100644 index 000000000..870892045 --- /dev/null +++ b/examples/import-resources/minus-wasm-pack/index.js @@ -0,0 +1,4 @@ +import { __wbg_set_wasm } from './index_bg.js'; +import * as wasm from './index_bg.wasm'; +__wbg_set_wasm(wasm); +export * from './index_bg.js'; diff --git a/examples/import-resources/minus-wasm-pack/index_bg.js b/examples/import-resources/minus-wasm-pack/index_bg.js new file mode 100644 index 000000000..e0cd54229 --- /dev/null +++ b/examples/import-resources/minus-wasm-pack/index_bg.js @@ -0,0 +1,133 @@ +let wasm; +export function __wbg_set_wasm(val) { + wasm = val; +} + +const lTextDecoder = + typeof TextDecoder === 'undefined' + ? (0, module.require)('util').TextDecoder + : TextDecoder; + +let cachedTextDecoder = new lTextDecoder('utf-8', { + ignoreBOM: true, + fatal: true, +}); + +cachedTextDecoder.decode(); + +let cachedUint8ArrayMemory0 = null; + +function getUint8ArrayMemory0() { + if ( + cachedUint8ArrayMemory0 === null || + cachedUint8ArrayMemory0.byteLength === 0 + ) { + cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer); + } + return cachedUint8ArrayMemory0; +} + +function getStringFromWasm0(ptr, len) { + ptr = ptr >>> 0; + return cachedTextDecoder.decode( + getUint8ArrayMemory0().subarray(ptr, ptr + len), + ); +} +/** + */ +export function greet() { + wasm.greet(); +} + +let WASM_VECTOR_LEN = 0; + +const lTextEncoder = + typeof TextEncoder === 'undefined' + ? (0, module.require)('util').TextEncoder + : TextEncoder; + +let cachedTextEncoder = new lTextEncoder('utf-8'); + +const encodeString = + typeof cachedTextEncoder.encodeInto === 'function' + ? function (arg, view) { + return cachedTextEncoder.encodeInto(arg, view); + } + : function (arg, view) { + const buf = cachedTextEncoder.encode(arg); + view.set(buf); + return { + read: arg.length, + written: buf.length, + }; + }; + +function passStringToWasm0(arg, malloc, realloc) { + if (realloc === undefined) { + const buf = cachedTextEncoder.encode(arg); + const ptr = malloc(buf.length, 1) >>> 0; + getUint8ArrayMemory0() + .subarray(ptr, ptr + buf.length) + .set(buf); + WASM_VECTOR_LEN = buf.length; + return ptr; + } + + let len = arg.length; + let ptr = malloc(len, 1) >>> 0; + + const mem = getUint8ArrayMemory0(); + + let offset = 0; + + for (; offset < len; offset++) { + const code = arg.charCodeAt(offset); + if (code > 0x7f) break; + mem[ptr + offset] = code; + } + + if (offset !== len) { + if (offset !== 0) { + arg = arg.slice(offset); + } + ptr = realloc(ptr, len, (len = offset + arg.length * 3), 1) >>> 0; + const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len); + const ret = encodeString(arg, view); + + offset += ret.written; + ptr = realloc(ptr, len, offset, 1) >>> 0; + } + + WASM_VECTOR_LEN = offset; + return ptr; +} +/** + * @param {string} name + */ +export function greet2(name) { + const ptr0 = passStringToWasm0( + name, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len0 = WASM_VECTOR_LEN; + wasm.greet2(ptr0, len0); +} + +/** + * @param {number} a + * @param {number} b + * @returns {number} + */ +export function minus(a, b) { + const ret = wasm.minus(a, b); + return ret; +} + +export function __wbg_alert_f837f172b2a24942(arg0, arg1) { + alert(getStringFromWasm0(arg0, arg1)); +} + +export function __wbg_prompt_ec584a06a1c7c28b(arg0, arg1) { + prompt(getStringFromWasm0(arg0, arg1)); +} diff --git a/examples/import-resources/minus-wasm-pack/index_bg.wasm b/examples/import-resources/minus-wasm-pack/index_bg.wasm new file mode 100644 index 0000000000000000000000000000000000000000..a50256cbd1b182aaa10be69e6c430e1e5bac4ae8 GIT binary patch literal 17815 zcmeI4UyR(>b>Hvr&-~e)S#l(AWSUD=cgA!~Rw6n3e^+tS{ShVQjm!#YgTAByz1$sA zoL!RI+2Km6ZSC5X4Y$#Q9~{626hJ@?L_zG@1=Q3{oOXjKg@DL`AA~j!elQRN^@Exy zfPyHf3ik6o_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~_TX?l64 zJu^KsGc!9gH#0x8Fta$bG_#C0OwZ2D&d$!w&d;JC=*se3dv1DeW^Q(FZf<^VVQz75 zX>NJGJwH7^Ge0{&H$OkWFuypzG{3yiUYK4$s}|-K<`)(g78jNlmKWQL{3Vga*~PiV z`Nf6B#l@w?<)!x0^wP}I?9$xQ{L;eG;?mO6@-ieYGyO6{qoOogUUr`w<8O>?++OeW zcH-*R+RbaXQTZtSM`*OGQzc;NY@E6Bd{Qzke|Y-r()8K3KQ+*H&l=~>w3pAc=T4WO zUE88r8U33+J6$(a%Kv1@gVM?6S%0d1wS8r-Gqce??H)VYU+Z1#@aIrEYiwd?Cw}zk fjobaTD_fm2*S2n5S=-uqw7PTs+RZba=lcH>GVs0Y literal 0 HcmV?d00001 diff --git a/examples/import-resources/minus-wasm-pack/index_bg.wasm.d.ts b/examples/import-resources/minus-wasm-pack/index_bg.wasm.d.ts new file mode 100644 index 000000000..183cf3457 --- /dev/null +++ b/examples/import-resources/minus-wasm-pack/index_bg.wasm.d.ts @@ -0,0 +1,13 @@ +/* tslint:disable */ +/* eslint-disable */ +export const memory: WebAssembly.Memory; +export function greet2(a: number, b: number): void; +export function minus(a: number, b: number): number; +export function greet(): void; +export function __wbindgen_malloc(a: number, b: number): number; +export function __wbindgen_realloc( + a: number, + b: number, + c: number, + d: number, +): number; From 74048e2194eb5ed5b325821841e7bf341995a852 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BE=A1=E9=A3=8E?= <18012261618@126.com> Date: Wed, 27 Nov 2024 15:31:58 +0800 Subject: [PATCH 02/10] =?UTF-8?q?fix:=20=E5=88=A0=E9=99=A4=E6=B2=A1?= =?UTF-8?q?=E5=BF=85=E8=A6=81=E7=9A=84=E8=BE=93=E5=87=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/mako/src/plugins/wasm_runtime.rs | 15 +++++---------- 1 file changed, 5 insertions(+), 10 deletions(-) diff --git a/crates/mako/src/plugins/wasm_runtime.rs b/crates/mako/src/plugins/wasm_runtime.rs index d862c6c30..b51db5821 100644 --- a/crates/mako/src/plugins/wasm_runtime.rs +++ b/crates/mako/src/plugins/wasm_runtime.rs @@ -56,16 +56,11 @@ impl Plugin for WasmRuntimePlugin { for payload in Parser::new(0).parse_all(&buffer) { if let Ok(Payload::ImportSection(imports)) = payload { for import in imports { - match import { - Ok(Import { module, name, ty }) => { - if let Some(import_obj) = import_objs_map.get_mut(module) { - import_obj.push(name.to_string()); - } else { - import_objs_map.insert(module, vec![name.to_string()]); - } - } - Err(_) => { - println!("import error"); + if let Ok(Import { module, name, ty }) = import { + if let Some(import_obj) = import_objs_map.get_mut(module) { + import_obj.push(name.to_string()); + } else { + import_objs_map.insert(module, vec![name.to_string()]); } } } From 76dc555d6f68ab15e185aa8ae94cb3389a312294 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BE=A1=E9=A3=8E?= <18012261618@126.com> Date: Wed, 27 Nov 2024 19:49:57 +0800 Subject: [PATCH 03/10] =?UTF-8?q?fix:=20=E4=BF=AE=E6=94=B9=E7=94=9F?= =?UTF-8?q?=E6=88=90=E7=9A=84=E6=88=90=E5=91=98=E8=A1=A8=E8=BE=BE=E5=BC=8F?= =?UTF-8?q?js=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/mako/src/plugins/wasm_runtime.rs | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/crates/mako/src/plugins/wasm_runtime.rs b/crates/mako/src/plugins/wasm_runtime.rs index b51db5821..e6a87f653 100644 --- a/crates/mako/src/plugins/wasm_runtime.rs +++ b/crates/mako/src/plugins/wasm_runtime.rs @@ -50,13 +50,18 @@ impl Plugin for WasmRuntimePlugin { _context.emit_assets(origin_path, final_file_name.clone()); let mut buffer = Vec::new(); - File::open(file.path.as_path())?.read_to_end(&mut buffer)?; + File::open(&file.path)?.read_to_end(&mut buffer)?; // Parse wasm file to get imports let mut import_objs_map: HashMap<&str, Vec> = HashMap::new(); for payload in Parser::new(0).parse_all(&buffer) { if let Ok(Payload::ImportSection(imports)) = payload { for import in imports { - if let Ok(Import { module, name, ty }) = import { + if let Ok(Import { + module, + name, + ty: _, + }) = import + { if let Some(import_obj) = import_objs_map.get_mut(module) { import_obj.push(name.to_string()); } else { @@ -82,7 +87,7 @@ impl Plugin for WasmRuntimePlugin { module = key, names = value .iter() - .map(|name| format!("{}: module{}.{}", name, index, name)) + .map(|name| format!("\"{}\": module{}[\"{}\"]", name, index, name)) .collect::>() .join(", ") )); From 49b470e24b9f9971b8c4a3d132ae65a609aa113e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BE=A1=E9=A3=8E?= <18012261618@126.com> Date: Fri, 29 Nov 2024 15:48:34 +0800 Subject: [PATCH 04/10] =?UTF-8?q?fix:=20=E5=8F=98=E9=87=8F=E9=87=8D?= =?UTF-8?q?=E5=91=BD=E5=90=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/mako/src/plugins/wasm_runtime.rs | 30 +++++++++++++------------ 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/crates/mako/src/plugins/wasm_runtime.rs b/crates/mako/src/plugins/wasm_runtime.rs index e6a87f653..bcc03746f 100644 --- a/crates/mako/src/plugins/wasm_runtime.rs +++ b/crates/mako/src/plugins/wasm_runtime.rs @@ -46,13 +46,15 @@ impl Plugin for WasmRuntimePlugin { file.get_content_hash()?, file.extname ); - let origin_path = file.pathname.to_string_lossy().to_string(); - _context.emit_assets(origin_path, final_file_name.clone()); + _context.emit_assets( + file.pathname.to_string_lossy().to_string(), + final_file_name.clone(), + ); let mut buffer = Vec::new(); File::open(&file.path)?.read_to_end(&mut buffer)?; // Parse wasm file to get imports - let mut import_objs_map: HashMap<&str, Vec> = HashMap::new(); + let mut wasm_import_object_map: HashMap<&str, Vec> = HashMap::new(); for payload in Parser::new(0).parse_all(&buffer) { if let Ok(Payload::ImportSection(imports)) = payload { for import in imports { @@ -62,27 +64,27 @@ impl Plugin for WasmRuntimePlugin { ty: _, }) = import { - if let Some(import_obj) = import_objs_map.get_mut(module) { - import_obj.push(name.to_string()); + if let Some(import_object) = wasm_import_object_map.get_mut(module) { + import_object.push(name.to_string()); } else { - import_objs_map.insert(module, vec![name.to_string()]); + wasm_import_object_map.insert(module, vec![name.to_string()]); } } } } } - let mut js_imports_str = String::new(); - let mut import_objs_str = String::new(); + let mut module_import_code = String::new(); + let mut wasm_import_object_code = String::new(); - for (index, (key, value)) in import_objs_map.iter().enumerate() { - js_imports_str.push_str(&format!( + for (index, (key, value)) in wasm_import_object_map.iter().enumerate() { + module_import_code.push_str(&format!( "import * as module{module_idx} from \"{module}\";\n", module_idx = index, module = key )); - import_objs_str.push_str(&format!( + wasm_import_object_code.push_str(&format!( "\"{module}\": {{ {names} }}", module = key, names = value @@ -94,9 +96,9 @@ impl Plugin for WasmRuntimePlugin { } let mut content = String::new(); - content.push_str(&js_imports_str); + content.push_str(&module_import_code); - if import_objs_str.is_empty() { + if wasm_import_object_code.is_empty() { content.push_str(&format!( "module.exports = require._interopreRequireWasm(exports, \"{}\")", final_file_name @@ -104,7 +106,7 @@ impl Plugin for WasmRuntimePlugin { } else { content.push_str(&format!( "module.exports = require._interopreRequireWasm(exports, \"{}\", {{{}}})", - final_file_name, import_objs_str + final_file_name, wasm_import_object_code )); } From d0aea670e2133c069e7c8ea5b6b6aebb9f33625f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BE=A1=E9=A3=8E?= <18012261618@126.com> Date: Fri, 29 Nov 2024 19:14:09 +0800 Subject: [PATCH 05/10] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=E4=BB=A3?= =?UTF-8?q?=E7=A0=81lint=E6=8A=A5=E9=94=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/mako/src/plugins/wasm_runtime.rs | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/crates/mako/src/plugins/wasm_runtime.rs b/crates/mako/src/plugins/wasm_runtime.rs index bcc03746f..7390c684a 100644 --- a/crates/mako/src/plugins/wasm_runtime.rs +++ b/crates/mako/src/plugins/wasm_runtime.rs @@ -55,14 +55,17 @@ impl Plugin for WasmRuntimePlugin { File::open(&file.path)?.read_to_end(&mut buffer)?; // Parse wasm file to get imports let mut wasm_import_object_map: HashMap<&str, Vec> = HashMap::new(); - for payload in Parser::new(0).parse_all(&buffer) { + Parser::new(0).parse_all(&buffer).for_each(|payload| { if let Ok(Payload::ImportSection(imports)) = payload { - for import in imports { - if let Ok(Import { - module, - name, - ty: _, - }) = import + imports.into_iter_with_offsets().for_each(|import| { + if let Ok(( + _, + Import { + module, + name, + ty: _, + }, + )) = import { if let Some(import_object) = wasm_import_object_map.get_mut(module) { import_object.push(name.to_string()); @@ -70,9 +73,9 @@ impl Plugin for WasmRuntimePlugin { wasm_import_object_map.insert(module, vec![name.to_string()]); } } - } + }); } - } + }); let mut module_import_code = String::new(); let mut wasm_import_object_code = String::new(); From 1a3106222694101f076906bc1ebb0d6022a5867b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BE=A1=E9=A3=8E?= <18012261618@126.com> Date: Fri, 29 Nov 2024 21:47:32 +0800 Subject: [PATCH 06/10] =?UTF-8?q?test:=20=E8=A1=A5=E5=85=85wasm=5Fruntime?= =?UTF-8?q?=E6=B5=8B=E8=AF=95=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/mako/src/plugins/wasm_runtime.rs | 45 +++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/crates/mako/src/plugins/wasm_runtime.rs b/crates/mako/src/plugins/wasm_runtime.rs index 7390c684a..4dd842dbf 100644 --- a/crates/mako/src/plugins/wasm_runtime.rs +++ b/crates/mako/src/plugins/wasm_runtime.rs @@ -122,3 +122,48 @@ impl Plugin for WasmRuntimePlugin { Ok(None) } } + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use super::*; + use crate::ast::file::File; + use crate::compiler::Context; + + #[test] + fn test_wasm_runtime_load_with_import_object() { + let plugin = WasmRuntimePlugin {}; + let context = Arc::new(Context { + ..Default::default() + }); + let wasm_relative_path = + std::path::Path::new("../../examples/import-resources/minus-wasm-pack/index_bg.wasm"); + let wasm_path = std::fs::canonicalize(wasm_relative_path).unwrap(); + let file = File::new(wasm_path.to_string_lossy().to_string(), context.clone()); + let param = PluginLoadParam { file: &file }; + let result: Option = plugin.load(¶m, &context).unwrap(); + + assert!(result.is_some()); + if let Some(Content::Js(js_content)) = result { + assert!(js_content.content.contains("import * as module0 from")); + } + } + + #[test] + fn test_wasm_runtime_load_without_import_object() { + let plugin = WasmRuntimePlugin {}; + let context = Arc::new(Context { + ..Default::default() + }); + let wasm_relative_path = std::path::Path::new("../../examples/import-resources/add.wasm"); + let wasm_path = std::fs::canonicalize(wasm_relative_path).unwrap(); + let file = File::new(wasm_path.to_string_lossy().to_string(), context.clone()); + let param = PluginLoadParam { file: &file }; + let result = plugin.load(¶m, &context).unwrap(); + assert!(result.is_some()); + if let Some(Content::Js(js_content)) = result { + assert!(!js_content.content.contains("import * as module0 from")) + } + } +} From f037029f7e0f8a98dbcc4420a036f83728492f06 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BE=A1=E9=A3=8E?= <18012261618@126.com> Date: Wed, 15 Jan 2025 16:52:06 +0800 Subject: [PATCH 07/10] =?UTF-8?q?chore:=20=E8=A1=A5=E5=85=85import=20js?= =?UTF-8?q?=E6=96=B9=E5=BC=8F=E7=9A=84=E7=A4=BA=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../import-js-wasm/index.d.ts | 51 +++ .../import-resources/import-js-wasm/index.js | 303 ++++++++++++++++++ .../import-js-wasm/index_bg.wasm | Bin 0 -> 18869 bytes .../import-js-wasm/index_bg.wasm.d.ts | 12 + .../defined-in-js.js | 21 ++ examples/import-resources/index.tsx | 7 + 6 files changed, 394 insertions(+) create mode 100644 examples/import-resources/import-js-wasm/index.d.ts create mode 100644 examples/import-resources/import-js-wasm/index.js create mode 100644 examples/import-resources/import-js-wasm/index_bg.wasm create mode 100644 examples/import-resources/import-js-wasm/index_bg.wasm.d.ts create mode 100644 examples/import-resources/import-js-wasm/snippets/import_js-ebef8887557a6fbe/defined-in-js.js diff --git a/examples/import-resources/import-js-wasm/index.d.ts b/examples/import-resources/import-js-wasm/index.d.ts new file mode 100644 index 000000000..9cc07fd87 --- /dev/null +++ b/examples/import-resources/import-js-wasm/index.d.ts @@ -0,0 +1,51 @@ +/* tslint:disable */ +/* eslint-disable */ +export function run(): void; + +export type InitInput = + | RequestInfo + | URL + | Response + | BufferSource + | WebAssembly.Module; + +export interface InitOutput { + readonly memory: WebAssembly.Memory; + readonly run: () => void; + readonly __wbindgen_malloc: (a: number, b: number) => number; + readonly __wbindgen_realloc: ( + a: number, + b: number, + c: number, + d: number, + ) => number; + readonly __wbindgen_start: () => void; +} + +export type SyncInitInput = BufferSource | WebAssembly.Module; +/** + * Instantiates the given `module`, which can either be bytes or + * a precompiled `WebAssembly.Module`. + * + * @param {{ module: SyncInitInput }} module - Passing `SyncInitInput` directly is deprecated. + * + * @returns {InitOutput} + */ +export function initSync( + module: { module: SyncInitInput } | SyncInitInput, +): InitOutput; + +/** + * If `module_or_path` is {RequestInfo} or {URL}, makes a request and + * for everything else, calls `WebAssembly.instantiate` directly. + * + * @param {{ module_or_path: InitInput | Promise }} module_or_path - Passing `InitInput` directly is deprecated. + * + * @returns {Promise} + */ +export default function __wbg_init( + module_or_path?: + | { module_or_path: InitInput | Promise } + | InitInput + | Promise, +): Promise; diff --git a/examples/import-resources/import-js-wasm/index.js b/examples/import-resources/import-js-wasm/index.js new file mode 100644 index 000000000..5ef2dbd46 --- /dev/null +++ b/examples/import-resources/import-js-wasm/index.js @@ -0,0 +1,303 @@ +import { + MyClass, + name, +} from './snippets/import_js-ebef8887557a6fbe/defined-in-js.js'; + +let wasm; + +const cachedTextDecoder = + typeof TextDecoder !== 'undefined' + ? new TextDecoder('utf-8', { ignoreBOM: true, fatal: true }) + : { + decode: () => { + throw Error('TextDecoder not available'); + }, + }; + +if (typeof TextDecoder !== 'undefined') { + cachedTextDecoder.decode(); +} + +let cachedUint8ArrayMemory0 = null; + +function getUint8ArrayMemory0() { + if ( + cachedUint8ArrayMemory0 === null || + cachedUint8ArrayMemory0.byteLength === 0 + ) { + cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer); + } + return cachedUint8ArrayMemory0; +} + +function getStringFromWasm0(ptr, len) { + ptr = ptr >>> 0; + return cachedTextDecoder.decode( + getUint8ArrayMemory0().subarray(ptr, ptr + len), + ); +} + +let WASM_VECTOR_LEN = 0; + +const cachedTextEncoder = + typeof TextEncoder !== 'undefined' + ? new TextEncoder('utf-8') + : { + encode: () => { + throw Error('TextEncoder not available'); + }, + }; + +const encodeString = + typeof cachedTextEncoder.encodeInto === 'function' + ? function (arg, view) { + return cachedTextEncoder.encodeInto(arg, view); + } + : function (arg, view) { + const buf = cachedTextEncoder.encode(arg); + view.set(buf); + return { + read: arg.length, + written: buf.length, + }; + }; + +function passStringToWasm0(arg, malloc, realloc) { + if (realloc === undefined) { + const buf = cachedTextEncoder.encode(arg); + const ptr = malloc(buf.length, 1) >>> 0; + getUint8ArrayMemory0() + .subarray(ptr, ptr + buf.length) + .set(buf); + WASM_VECTOR_LEN = buf.length; + return ptr; + } + + let len = arg.length; + let ptr = malloc(len, 1) >>> 0; + + const mem = getUint8ArrayMemory0(); + + let offset = 0; + + for (; offset < len; offset++) { + const code = arg.charCodeAt(offset); + if (code > 0x7f) break; + mem[ptr + offset] = code; + } + + if (offset !== len) { + if (offset !== 0) { + arg = arg.slice(offset); + } + ptr = realloc(ptr, len, (len = offset + arg.length * 3), 1) >>> 0; + const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len); + const ret = encodeString(arg, view); + + offset += ret.written; + ptr = realloc(ptr, len, offset, 1) >>> 0; + } + + WASM_VECTOR_LEN = offset; + return ptr; +} + +let cachedDataViewMemory0 = null; + +function getDataViewMemory0() { + if ( + cachedDataViewMemory0 === null || + cachedDataViewMemory0.buffer.detached === true || + (cachedDataViewMemory0.buffer.detached === undefined && + cachedDataViewMemory0.buffer !== wasm.memory.buffer) + ) { + cachedDataViewMemory0 = new DataView(wasm.memory.buffer); + } + return cachedDataViewMemory0; +} + +const heap = new Array(128).fill(undefined); + +heap.push(undefined, null, true, false); + +let heap_next = heap.length; + +function addHeapObject(obj) { + if (heap_next === heap.length) heap.push(heap.length + 1); + const idx = heap_next; + heap_next = heap[idx]; + + heap[idx] = obj; + return idx; +} + +function getObject(idx) { + return heap[idx]; +} + +function dropObject(idx) { + if (idx < 132) return; + heap[idx] = heap_next; + heap_next = idx; +} + +function takeObject(idx) { + const ret = getObject(idx); + dropObject(idx); + return ret; +} + +export function run() { + wasm.run(); +} + +async function __wbg_load(module, imports) { + if (typeof Response === 'function' && module instanceof Response) { + if (typeof WebAssembly.instantiateStreaming === 'function') { + try { + return await WebAssembly.instantiateStreaming(module, imports); + } catch (e) { + if (module.headers.get('Content-Type') != 'application/wasm') { + console.warn( + '`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n', + e, + ); + } else { + throw e; + } + } + } + + const bytes = await module.arrayBuffer(); + return await WebAssembly.instantiate(bytes, imports); + } else { + const instance = await WebAssembly.instantiate(module, imports); + + if (instance instanceof WebAssembly.Instance) { + return { instance, module }; + } else { + return instance; + } + } +} + +function __wbg_get_imports() { + const imports = {}; + imports.wbg = {}; + imports.wbg.__wbg_log_b2db2c5816f1d07e = function (arg0, arg1) { + console.log(getStringFromWasm0(arg0, arg1)); + }; + imports.wbg.__wbg_name_fca994005bad39be = function (arg0) { + const ret = name(); + const ptr1 = passStringToWasm0( + ret, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len1 = WASM_VECTOR_LEN; + getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true); + getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true); + }; + imports.wbg.__wbg_new_74968321906dc678 = function () { + const ret = new MyClass(); + return addHeapObject(ret); + }; + imports.wbg.__wbg_number_6ea25e36c02a28e3 = function (arg0) { + const ret = getObject(arg0).number; + return ret; + }; + imports.wbg.__wbg_render_40d583ad633779da = function (arg0, arg1) { + const ret = getObject(arg1).render(); + const ptr1 = passStringToWasm0( + ret, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len1 = WASM_VECTOR_LEN; + getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true); + getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true); + }; + imports.wbg.__wbg_setnumber_a86efb097c245512 = function (arg0, arg1) { + const ret = (getObject(arg0).number = arg1 >>> 0); + return addHeapObject(ret); + }; + imports.wbg.__wbindgen_object_drop_ref = function (arg0) { + takeObject(arg0); + }; + + return imports; +} + +function __wbg_init_memory(imports, memory) {} + +function __wbg_finalize_init(instance, module) { + wasm = instance.exports; + __wbg_init.__wbindgen_wasm_module = module; + cachedDataViewMemory0 = null; + cachedUint8ArrayMemory0 = null; + + wasm.__wbindgen_start(); + return wasm; +} + +function initSync(module) { + if (wasm !== undefined) return wasm; + + if (typeof module !== 'undefined') { + if (Object.getPrototypeOf(module) === Object.prototype) { + ({ module } = module); + } else { + console.warn( + 'using deprecated parameters for `initSync()`; pass a single object instead', + ); + } + } + + const imports = __wbg_get_imports(); + + __wbg_init_memory(imports); + + if (!(module instanceof WebAssembly.Module)) { + module = new WebAssembly.Module(module); + } + + const instance = new WebAssembly.Instance(module, imports); + + return __wbg_finalize_init(instance, module); +} + +async function __wbg_init(module_or_path) { + if (wasm !== undefined) return wasm; + + if (typeof module_or_path !== 'undefined') { + if (Object.getPrototypeOf(module_or_path) === Object.prototype) { + ({ module_or_path } = module_or_path); + } else { + console.warn( + 'using deprecated parameters for the initialization function; pass a single object instead', + ); + } + } + + if (typeof module_or_path === 'undefined') { + module_or_path = new URL('index_bg.wasm', import.meta.url); + } + const imports = __wbg_get_imports(); + + if ( + typeof module_or_path === 'string' || + (typeof Request === 'function' && module_or_path instanceof Request) || + (typeof URL === 'function' && module_or_path instanceof URL) + ) { + module_or_path = fetch(module_or_path); + } + + __wbg_init_memory(imports); + + const { instance, module } = await __wbg_load(await module_or_path, imports); + + return __wbg_finalize_init(instance, module); +} + +export { initSync }; +export default __wbg_init; diff --git a/examples/import-resources/import-js-wasm/index_bg.wasm b/examples/import-resources/import-js-wasm/index_bg.wasm new file mode 100644 index 0000000000000000000000000000000000000000..78c287bc3c457612aef715bd833517c773ecd5ff GIT binary patch literal 18869 zcmeI4ZH!#kdEd{ycixsWD~@C)rnr=KXQJ4o#h2N)nO!DM_Y$F`jm#)$(xN~Mki*>} zxwFe%?(A?y*{Zmf<(P$)S|3!@F8o0O1Xw|wR7u@J4HR_Ss)j!}g+3UzS_r7yD2M|% z0Sm~9&jD2bVK&&xgMInVp^oU`NF8&?A7T<}Yk^Wlvf!3}-8 z^U)1^4$?<=K2TSlR%_3xbmy(0-Ra}b7t~67_~W1$J$d2M*tv6jpIdET>72W`(4L*0 zYBZ)Vv==95FLYd_5r_PUm9G+Q%nL<1g3*SL1&LZ^4G*=bKqcP5()jfwWeOlQ*NH753BHah)PKde2|>|DIi zm~AagOifRZPdGPNYiV`yQfKwt+J$asp?_|%w|4bhuXE8uo37RCtS++FRAX^^X0pB5 zoSba6W*6H4JUx|nVIc|w$NzmnIhQLIgD41t(B%p)C`C~el!R>l@y!!oVJ;tB4aUau zQQ+<^jDYB5Yirw;i=WOHu5_-f^_~h{)VsFo?z>m}NCCXkURhaNa1Y)$)Yj|x#)qmy zjT`-TukY>~i367eX;#l118I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PJ?|}#7jg_T^j+$1`lKso^&3x6k{~uA}_Pp~Ys2xP^>5;3wwZ&@- z=+v;Z!o1hompVc2ucNeFg|3ATYH9KKg{Pvt6xqT9<0obsCmQh)wmH?BnVoLMU~B4l zqjh{@{Al6H_6oxaD7eWJla(j=nWf|DZ})seN^iWun-gHavoLXC>Zm)mpFLda^v_-F mv=NKWM)>glE7$t%3oD)DmsZv;v{yDBE^RDbT0P#m-v951_3l9c literal 0 HcmV?d00001 diff --git a/examples/import-resources/import-js-wasm/index_bg.wasm.d.ts b/examples/import-resources/import-js-wasm/index_bg.wasm.d.ts new file mode 100644 index 000000000..d8cde4a8f --- /dev/null +++ b/examples/import-resources/import-js-wasm/index_bg.wasm.d.ts @@ -0,0 +1,12 @@ +/* tslint:disable */ +/* eslint-disable */ +export const memory: WebAssembly.Memory; +export const run: () => void; +export const __wbindgen_malloc: (a: number, b: number) => number; +export const __wbindgen_realloc: ( + a: number, + b: number, + c: number, + d: number, +) => number; +export const __wbindgen_start: () => void; diff --git a/examples/import-resources/import-js-wasm/snippets/import_js-ebef8887557a6fbe/defined-in-js.js b/examples/import-resources/import-js-wasm/snippets/import_js-ebef8887557a6fbe/defined-in-js.js new file mode 100644 index 000000000..d948845cd --- /dev/null +++ b/examples/import-resources/import-js-wasm/snippets/import_js-ebef8887557a6fbe/defined-in-js.js @@ -0,0 +1,21 @@ +export function name() { + return 'Rust'; +} + +export class MyClass { + constructor() { + this._number = 42; + } + + get number() { + return this._number; + } + + set number(n) { + return (this._number = n); + } + + render() { + return `My number is: ${this.number}`; + } +} diff --git a/examples/import-resources/index.tsx b/examples/import-resources/index.tsx index afdc166e2..0b87ebb26 100644 --- a/examples/import-resources/index.tsx +++ b/examples/import-resources/index.tsx @@ -9,6 +9,13 @@ import yaml, { pi } from './index.yaml'; import MailchimpUnsplash from './mailchimp-unsplash.jpg'; import * as wasm from './minus-wasm-pack'; +// https://github.com/rustwasm/wasm-bindgen/tree/main/examples/import_js +import('./import-js-wasm') + .then((_) => { + _.default(); + }) + .catch(console.error); + const num1 = 10; const num2 = 20; From 4511ec603e0a0212835982bcd63d72144ecfc021 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BE=A1=E9=A3=8E?= <18012261618@126.com> Date: Thu, 16 Jan 2025 14:00:39 +0800 Subject: [PATCH 08/10] =?UTF-8?q?chore:=20=E4=BF=AE=E6=94=B9import=20js?= =?UTF-8?q?=E7=A4=BA=E4=BE=8Bwasm=E4=BA=A7=E7=89=A9=E6=A0=BC=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../import-js-wasm/index.d.ts | 48 --- .../import-resources/import-js-wasm/index.js | 308 +----------------- .../import-js-wasm/index_bg.js | 199 +++++++++++ .../import-js-wasm/index_bg.wasm | Bin 18869 -> 18939 bytes examples/import-resources/index.tsx | 6 +- 5 files changed, 205 insertions(+), 356 deletions(-) create mode 100644 examples/import-resources/import-js-wasm/index_bg.js diff --git a/examples/import-resources/import-js-wasm/index.d.ts b/examples/import-resources/import-js-wasm/index.d.ts index 9cc07fd87..be66165bc 100644 --- a/examples/import-resources/import-js-wasm/index.d.ts +++ b/examples/import-resources/import-js-wasm/index.d.ts @@ -1,51 +1,3 @@ /* tslint:disable */ /* eslint-disable */ export function run(): void; - -export type InitInput = - | RequestInfo - | URL - | Response - | BufferSource - | WebAssembly.Module; - -export interface InitOutput { - readonly memory: WebAssembly.Memory; - readonly run: () => void; - readonly __wbindgen_malloc: (a: number, b: number) => number; - readonly __wbindgen_realloc: ( - a: number, - b: number, - c: number, - d: number, - ) => number; - readonly __wbindgen_start: () => void; -} - -export type SyncInitInput = BufferSource | WebAssembly.Module; -/** - * Instantiates the given `module`, which can either be bytes or - * a precompiled `WebAssembly.Module`. - * - * @param {{ module: SyncInitInput }} module - Passing `SyncInitInput` directly is deprecated. - * - * @returns {InitOutput} - */ -export function initSync( - module: { module: SyncInitInput } | SyncInitInput, -): InitOutput; - -/** - * If `module_or_path` is {RequestInfo} or {URL}, makes a request and - * for everything else, calls `WebAssembly.instantiate` directly. - * - * @param {{ module_or_path: InitInput | Promise }} module_or_path - Passing `InitInput` directly is deprecated. - * - * @returns {Promise} - */ -export default function __wbg_init( - module_or_path?: - | { module_or_path: InitInput | Promise } - | InitInput - | Promise, -): Promise; diff --git a/examples/import-resources/import-js-wasm/index.js b/examples/import-resources/import-js-wasm/index.js index 5ef2dbd46..76aa1cca7 100644 --- a/examples/import-resources/import-js-wasm/index.js +++ b/examples/import-resources/import-js-wasm/index.js @@ -1,303 +1,5 @@ -import { - MyClass, - name, -} from './snippets/import_js-ebef8887557a6fbe/defined-in-js.js'; - -let wasm; - -const cachedTextDecoder = - typeof TextDecoder !== 'undefined' - ? new TextDecoder('utf-8', { ignoreBOM: true, fatal: true }) - : { - decode: () => { - throw Error('TextDecoder not available'); - }, - }; - -if (typeof TextDecoder !== 'undefined') { - cachedTextDecoder.decode(); -} - -let cachedUint8ArrayMemory0 = null; - -function getUint8ArrayMemory0() { - if ( - cachedUint8ArrayMemory0 === null || - cachedUint8ArrayMemory0.byteLength === 0 - ) { - cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer); - } - return cachedUint8ArrayMemory0; -} - -function getStringFromWasm0(ptr, len) { - ptr = ptr >>> 0; - return cachedTextDecoder.decode( - getUint8ArrayMemory0().subarray(ptr, ptr + len), - ); -} - -let WASM_VECTOR_LEN = 0; - -const cachedTextEncoder = - typeof TextEncoder !== 'undefined' - ? new TextEncoder('utf-8') - : { - encode: () => { - throw Error('TextEncoder not available'); - }, - }; - -const encodeString = - typeof cachedTextEncoder.encodeInto === 'function' - ? function (arg, view) { - return cachedTextEncoder.encodeInto(arg, view); - } - : function (arg, view) { - const buf = cachedTextEncoder.encode(arg); - view.set(buf); - return { - read: arg.length, - written: buf.length, - }; - }; - -function passStringToWasm0(arg, malloc, realloc) { - if (realloc === undefined) { - const buf = cachedTextEncoder.encode(arg); - const ptr = malloc(buf.length, 1) >>> 0; - getUint8ArrayMemory0() - .subarray(ptr, ptr + buf.length) - .set(buf); - WASM_VECTOR_LEN = buf.length; - return ptr; - } - - let len = arg.length; - let ptr = malloc(len, 1) >>> 0; - - const mem = getUint8ArrayMemory0(); - - let offset = 0; - - for (; offset < len; offset++) { - const code = arg.charCodeAt(offset); - if (code > 0x7f) break; - mem[ptr + offset] = code; - } - - if (offset !== len) { - if (offset !== 0) { - arg = arg.slice(offset); - } - ptr = realloc(ptr, len, (len = offset + arg.length * 3), 1) >>> 0; - const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len); - const ret = encodeString(arg, view); - - offset += ret.written; - ptr = realloc(ptr, len, offset, 1) >>> 0; - } - - WASM_VECTOR_LEN = offset; - return ptr; -} - -let cachedDataViewMemory0 = null; - -function getDataViewMemory0() { - if ( - cachedDataViewMemory0 === null || - cachedDataViewMemory0.buffer.detached === true || - (cachedDataViewMemory0.buffer.detached === undefined && - cachedDataViewMemory0.buffer !== wasm.memory.buffer) - ) { - cachedDataViewMemory0 = new DataView(wasm.memory.buffer); - } - return cachedDataViewMemory0; -} - -const heap = new Array(128).fill(undefined); - -heap.push(undefined, null, true, false); - -let heap_next = heap.length; - -function addHeapObject(obj) { - if (heap_next === heap.length) heap.push(heap.length + 1); - const idx = heap_next; - heap_next = heap[idx]; - - heap[idx] = obj; - return idx; -} - -function getObject(idx) { - return heap[idx]; -} - -function dropObject(idx) { - if (idx < 132) return; - heap[idx] = heap_next; - heap_next = idx; -} - -function takeObject(idx) { - const ret = getObject(idx); - dropObject(idx); - return ret; -} - -export function run() { - wasm.run(); -} - -async function __wbg_load(module, imports) { - if (typeof Response === 'function' && module instanceof Response) { - if (typeof WebAssembly.instantiateStreaming === 'function') { - try { - return await WebAssembly.instantiateStreaming(module, imports); - } catch (e) { - if (module.headers.get('Content-Type') != 'application/wasm') { - console.warn( - '`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n', - e, - ); - } else { - throw e; - } - } - } - - const bytes = await module.arrayBuffer(); - return await WebAssembly.instantiate(bytes, imports); - } else { - const instance = await WebAssembly.instantiate(module, imports); - - if (instance instanceof WebAssembly.Instance) { - return { instance, module }; - } else { - return instance; - } - } -} - -function __wbg_get_imports() { - const imports = {}; - imports.wbg = {}; - imports.wbg.__wbg_log_b2db2c5816f1d07e = function (arg0, arg1) { - console.log(getStringFromWasm0(arg0, arg1)); - }; - imports.wbg.__wbg_name_fca994005bad39be = function (arg0) { - const ret = name(); - const ptr1 = passStringToWasm0( - ret, - wasm.__wbindgen_malloc, - wasm.__wbindgen_realloc, - ); - const len1 = WASM_VECTOR_LEN; - getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true); - getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true); - }; - imports.wbg.__wbg_new_74968321906dc678 = function () { - const ret = new MyClass(); - return addHeapObject(ret); - }; - imports.wbg.__wbg_number_6ea25e36c02a28e3 = function (arg0) { - const ret = getObject(arg0).number; - return ret; - }; - imports.wbg.__wbg_render_40d583ad633779da = function (arg0, arg1) { - const ret = getObject(arg1).render(); - const ptr1 = passStringToWasm0( - ret, - wasm.__wbindgen_malloc, - wasm.__wbindgen_realloc, - ); - const len1 = WASM_VECTOR_LEN; - getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true); - getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true); - }; - imports.wbg.__wbg_setnumber_a86efb097c245512 = function (arg0, arg1) { - const ret = (getObject(arg0).number = arg1 >>> 0); - return addHeapObject(ret); - }; - imports.wbg.__wbindgen_object_drop_ref = function (arg0) { - takeObject(arg0); - }; - - return imports; -} - -function __wbg_init_memory(imports, memory) {} - -function __wbg_finalize_init(instance, module) { - wasm = instance.exports; - __wbg_init.__wbindgen_wasm_module = module; - cachedDataViewMemory0 = null; - cachedUint8ArrayMemory0 = null; - - wasm.__wbindgen_start(); - return wasm; -} - -function initSync(module) { - if (wasm !== undefined) return wasm; - - if (typeof module !== 'undefined') { - if (Object.getPrototypeOf(module) === Object.prototype) { - ({ module } = module); - } else { - console.warn( - 'using deprecated parameters for `initSync()`; pass a single object instead', - ); - } - } - - const imports = __wbg_get_imports(); - - __wbg_init_memory(imports); - - if (!(module instanceof WebAssembly.Module)) { - module = new WebAssembly.Module(module); - } - - const instance = new WebAssembly.Instance(module, imports); - - return __wbg_finalize_init(instance, module); -} - -async function __wbg_init(module_or_path) { - if (wasm !== undefined) return wasm; - - if (typeof module_or_path !== 'undefined') { - if (Object.getPrototypeOf(module_or_path) === Object.prototype) { - ({ module_or_path } = module_or_path); - } else { - console.warn( - 'using deprecated parameters for the initialization function; pass a single object instead', - ); - } - } - - if (typeof module_or_path === 'undefined') { - module_or_path = new URL('index_bg.wasm', import.meta.url); - } - const imports = __wbg_get_imports(); - - if ( - typeof module_or_path === 'string' || - (typeof Request === 'function' && module_or_path instanceof Request) || - (typeof URL === 'function' && module_or_path instanceof URL) - ) { - module_or_path = fetch(module_or_path); - } - - __wbg_init_memory(imports); - - const { instance, module } = await __wbg_load(await module_or_path, imports); - - return __wbg_finalize_init(instance, module); -} - -export { initSync }; -export default __wbg_init; +import * as wasm from './index_bg.wasm'; +export * from './index_bg.js'; +import { __wbg_set_wasm } from './index_bg.js'; +__wbg_set_wasm(wasm); +wasm.__wbindgen_start(); diff --git a/examples/import-resources/import-js-wasm/index_bg.js b/examples/import-resources/import-js-wasm/index_bg.js new file mode 100644 index 000000000..5a0246201 --- /dev/null +++ b/examples/import-resources/import-js-wasm/index_bg.js @@ -0,0 +1,199 @@ +import { + MyClass, + name, +} from './snippets/import_js-ebef8887557a6fbe/defined-in-js.js'; + +let wasm; +export function __wbg_set_wasm(val) { + wasm = val; +} + +const lTextDecoder = + typeof TextDecoder === 'undefined' + ? (0, module.require)('util').TextDecoder + : TextDecoder; + +let cachedTextDecoder = new lTextDecoder('utf-8', { + ignoreBOM: true, + fatal: true, +}); + +cachedTextDecoder.decode(); + +let cachedUint8ArrayMemory0 = null; + +function getUint8ArrayMemory0() { + if ( + cachedUint8ArrayMemory0 === null || + cachedUint8ArrayMemory0.byteLength === 0 + ) { + cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer); + } + return cachedUint8ArrayMemory0; +} + +function getStringFromWasm0(ptr, len) { + ptr = ptr >>> 0; + return cachedTextDecoder.decode( + getUint8ArrayMemory0().subarray(ptr, ptr + len), + ); +} + +let WASM_VECTOR_LEN = 0; + +const lTextEncoder = + typeof TextEncoder === 'undefined' + ? (0, module.require)('util').TextEncoder + : TextEncoder; + +let cachedTextEncoder = new lTextEncoder('utf-8'); + +const encodeString = + typeof cachedTextEncoder.encodeInto === 'function' + ? function (arg, view) { + return cachedTextEncoder.encodeInto(arg, view); + } + : function (arg, view) { + const buf = cachedTextEncoder.encode(arg); + view.set(buf); + return { + read: arg.length, + written: buf.length, + }; + }; + +function passStringToWasm0(arg, malloc, realloc) { + if (realloc === undefined) { + const buf = cachedTextEncoder.encode(arg); + const ptr = malloc(buf.length, 1) >>> 0; + getUint8ArrayMemory0() + .subarray(ptr, ptr + buf.length) + .set(buf); + WASM_VECTOR_LEN = buf.length; + return ptr; + } + + let len = arg.length; + let ptr = malloc(len, 1) >>> 0; + + const mem = getUint8ArrayMemory0(); + + let offset = 0; + + for (; offset < len; offset++) { + const code = arg.charCodeAt(offset); + if (code > 0x7f) break; + mem[ptr + offset] = code; + } + + if (offset !== len) { + if (offset !== 0) { + arg = arg.slice(offset); + } + ptr = realloc(ptr, len, (len = offset + arg.length * 3), 1) >>> 0; + const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len); + const ret = encodeString(arg, view); + + offset += ret.written; + ptr = realloc(ptr, len, offset, 1) >>> 0; + } + + WASM_VECTOR_LEN = offset; + return ptr; +} + +let cachedDataViewMemory0 = null; + +function getDataViewMemory0() { + if ( + cachedDataViewMemory0 === null || + cachedDataViewMemory0.buffer.detached === true || + (cachedDataViewMemory0.buffer.detached === undefined && + cachedDataViewMemory0.buffer !== wasm.memory.buffer) + ) { + cachedDataViewMemory0 = new DataView(wasm.memory.buffer); + } + return cachedDataViewMemory0; +} + +const heap = new Array(128).fill(undefined); + +heap.push(undefined, null, true, false); + +let heap_next = heap.length; + +function addHeapObject(obj) { + if (heap_next === heap.length) heap.push(heap.length + 1); + const idx = heap_next; + heap_next = heap[idx]; + + heap[idx] = obj; + return idx; +} + +function getObject(idx) { + return heap[idx]; +} + +function dropObject(idx) { + if (idx < 132) return; + heap[idx] = heap_next; + heap_next = idx; +} + +function takeObject(idx) { + const ret = getObject(idx); + dropObject(idx); + return ret; +} + +export function run() { + wasm.run(); +} + +export function __wbg_log_b2db2c5816f1d07e(arg0, arg1) { + console.log(getStringFromWasm0(arg0, arg1)); +} + +export function __wbg_name_fca994005bad39be(arg0) { + const ret = name(); + const ptr1 = passStringToWasm0( + ret, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len1 = WASM_VECTOR_LEN; + getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true); + getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true); +} + +export function __wbg_new_74968321906dc678() { + const ret = new MyClass(); + return addHeapObject(ret); +} + +export function __wbg_number_6ea25e36c02a28e3(arg0) { + const ret = getObject(arg0).number; + return ret; +} + +export function __wbg_render_40d583ad633779da(arg0, arg1) { + const ret = getObject(arg1).render(); + const ptr1 = passStringToWasm0( + ret, + wasm.__wbindgen_malloc, + wasm.__wbindgen_realloc, + ); + const len1 = WASM_VECTOR_LEN; + getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true); + getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true); +} + +export function __wbg_setnumber_a86efb097c245512(arg0, arg1) { + const ret = (getObject(arg0).number = arg1 >>> 0); + return addHeapObject(ret); +} + +export function __wbindgen_object_drop_ref(arg0) { + takeObject(arg0); +} diff --git a/examples/import-resources/import-js-wasm/index_bg.wasm b/examples/import-resources/import-js-wasm/index_bg.wasm index 78c287bc3c457612aef715bd833517c773ecd5ff..7b3192882b410a4a724a735077909586ed87b9b8 100644 GIT binary patch delta 140 zcmdlwneq2z#tETmS&h@V4ljr e2v)dPmIX||Pyo}D#Tb<#40lF|%;qA-P7eSF-yTE& diff --git a/examples/import-resources/index.tsx b/examples/import-resources/index.tsx index 0b87ebb26..f853d8803 100644 --- a/examples/import-resources/index.tsx +++ b/examples/import-resources/index.tsx @@ -10,11 +10,7 @@ import MailchimpUnsplash from './mailchimp-unsplash.jpg'; import * as wasm from './minus-wasm-pack'; // https://github.com/rustwasm/wasm-bindgen/tree/main/examples/import_js -import('./import-js-wasm') - .then((_) => { - _.default(); - }) - .catch(console.error); +import('./import-js-wasm').catch(console.error); const num1 = 10; const num2 = 20; From d9c513db2c542588f08a225c5ed05741280656e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BE=A1=E9=A3=8E?= <18012261618@126.com> Date: Thu, 16 Jan 2025 14:27:16 +0800 Subject: [PATCH 09/10] =?UTF-8?q?chore:=20wasmparser=E4=BE=9D=E8=B5=96?= =?UTF-8?q?=E5=8C=85=E5=9C=A8=E9=85=8D=E7=BD=AE=E6=96=87=E4=BB=B6=E7=9A=84?= =?UTF-8?q?=E4=BD=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/mako/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/mako/Cargo.toml b/crates/mako/Cargo.toml index ac6b12776..47301e37e 100644 --- a/crates/mako/Cargo.toml +++ b/crates/mako/Cargo.toml @@ -28,7 +28,6 @@ serde = { workspace = true } serde_json = { workspace = true } swc_malloc = { workspace = true } url = { version = "2.5.0" } -wasmparser = "0.207.0" swc_core = { workspace = true, features = [ "base", @@ -115,6 +114,7 @@ tracing = "0.1.37" tracing-subscriber = { version = "0.3.17", features = ["env-filter"] } tungstenite = "0.19.0" twox-hash = "1.6.3" +wasmparser = "0.207.0" [dev-dependencies] insta = { version = "1.30.0", features = ["yaml"] } From 6b37ba97e74891a72a8db5458a535dc06f5a1d20 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BE=A1=E9=A3=8E?= <18012261618@126.com> Date: Fri, 17 Jan 2025 15:41:29 +0800 Subject: [PATCH 10/10] =?UTF-8?q?chore:=20=E5=88=A0=E9=99=A4=E5=A4=9A?= =?UTF-8?q?=E4=BD=99=E7=9A=84.wasm=20load=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/mako/src/build/load.rs | 22 ---------------------- crates/mako/src/plugins/wasm_runtime.rs | 5 ++++- 2 files changed, 4 insertions(+), 23 deletions(-) diff --git a/crates/mako/src/build/load.rs b/crates/mako/src/build/load.rs index 401fd9e52..80561f24a 100644 --- a/crates/mako/src/build/load.rs +++ b/crates/mako/src/build/load.rs @@ -36,7 +36,6 @@ const CSS_EXTENSIONS: [&str; 1] = ["css"]; const JSON_EXTENSIONS: [&str; 2] = ["json", "json5"]; const YAML_EXTENSIONS: [&str; 2] = ["yaml", "yml"]; const XML_EXTENSIONS: [&str; 1] = ["xml"]; -const WASM_EXTENSIONS: [&str; 1] = ["wasm"]; const TOML_EXTENSIONS: [&str; 1] = ["toml"]; const SVG_EXTENSIONS: [&str; 1] = ["svg"]; const MD_EXTENSIONS: [&str; 2] = ["md", "mdx"]; @@ -180,27 +179,6 @@ export function moduleToDom(css) { })); } - // wasm - if WASM_EXTENSIONS.contains(&file.extname.as_str()) { - let final_file_name = format!( - "{}.{}.{}", - file.get_file_stem(), - file.get_content_hash()?, - file.extname - ); - context.emit_assets( - file.pathname.to_string_lossy().to_string(), - final_file_name.clone(), - ); - return Ok(Content::Js(JsContent { - content: format!( - "module.exports = require._interopreRequireWasm(exports, \"{}\")", - final_file_name - ), - ..Default::default() - })); - } - // xml if XML_EXTENSIONS.contains(&file.extname.as_str()) { let content = FileSystem::read_file(&file.pathname)?; diff --git a/crates/mako/src/plugins/wasm_runtime.rs b/crates/mako/src/plugins/wasm_runtime.rs index 4dd842dbf..8087bd106 100644 --- a/crates/mako/src/plugins/wasm_runtime.rs +++ b/crates/mako/src/plugins/wasm_runtime.rs @@ -12,6 +12,8 @@ use crate::plugin::{Plugin, PluginLoadParam}; pub struct WasmRuntimePlugin {} +const WASM_EXTENSIONS: [&str; 1] = ["wasm"]; + impl Plugin for WasmRuntimePlugin { fn name(&self) -> &str { "wasm_runtime" @@ -39,7 +41,8 @@ impl Plugin for WasmRuntimePlugin { _context: &Arc, ) -> anyhow::Result> { let file = param.file; - if file.path.to_string_lossy().ends_with(".wasm") { + + if WASM_EXTENSIONS.contains(&file.extname.as_str()) { let final_file_name = format!( "{}.{}.{}", file.get_file_stem(),