From 7765c7fa281853ddfb26b6b17534df95eaede804 Mon Sep 17 00:00:00 2001 From: Lucas Fernandes Nogueira Date: Sun, 27 Jun 2021 19:51:47 -0300 Subject: [PATCH] fix(core): invoke key injection on ES module, improve performance (#2094) --- .changes/fix-javascript-iife-esm-rewrite.md | 6 ++++ .changes/invoke-key-performance.md | 6 ++++ core/tauri-codegen/src/embedded_assets.rs | 32 +++++++++++++++++++++ core/tauri/src/manager.rs | 11 +++---- 4 files changed, 48 insertions(+), 7 deletions(-) create mode 100644 .changes/fix-javascript-iife-esm-rewrite.md create mode 100644 .changes/invoke-key-performance.md diff --git a/.changes/fix-javascript-iife-esm-rewrite.md b/.changes/fix-javascript-iife-esm-rewrite.md new file mode 100644 index 000000000..cfa0450ff --- /dev/null +++ b/.changes/fix-javascript-iife-esm-rewrite.md @@ -0,0 +1,6 @@ +--- +"tauri": patch +"tauri-codegen": patch +--- + +Detect ESM scripts and inject the invoke key directly instead of using an IIFE. diff --git a/.changes/invoke-key-performance.md b/.changes/invoke-key-performance.md new file mode 100644 index 000000000..6296fa582 --- /dev/null +++ b/.changes/invoke-key-performance.md @@ -0,0 +1,6 @@ +--- +"tauri": patch +"tauri-codegen": patch +--- + +Improve invoke key code injection performance time rewriting code at compile time. diff --git a/core/tauri-codegen/src/embedded_assets.rs b/core/tauri-codegen/src/embedded_assets.rs index e87fbdebc..3316bbd5e 100644 --- a/core/tauri-codegen/src/embedded_assets.rs +++ b/core/tauri-codegen/src/embedded_assets.rs @@ -177,6 +177,38 @@ impl EmbeddedAssets { .to_vec(); } } + let is_javascript = ["js", "cjs", "mjs"] + .iter() + .any(|e| path.extension() == Some(OsStr::new(e))); + if is_javascript { + let js = String::from_utf8_lossy(&input).into_owned(); + input = if [ + "import{", "import*", "import ", "export{", "export*", "export ", + ] + .iter() + .any(|t| js.contains(t)) + { + format!( + r#" + const __TAURI_INVOKE_KEY__ = __TAURI__INVOKE_KEY_TOKEN__; + {} + "#, + js + ) + .as_bytes() + .to_vec() + } else { + format!( + r#"(function () {{ + const __TAURI_INVOKE_KEY__ = __TAURI__INVOKE_KEY_TOKEN__; + {} + }})()"#, + js + ) + .as_bytes() + .to_vec() + }; + } // we must canonicalize the base of our paths to allow long paths on windows let out_dir = std::env::var("OUT_DIR") diff --git a/core/tauri/src/manager.rs b/core/tauri/src/manager.rs index 001cedd10..b61982561 100644 --- a/core/tauri/src/manager.rs +++ b/core/tauri/src/manager.rs @@ -467,13 +467,10 @@ impl WindowManager

{ if is_javascript { let js = String::from_utf8_lossy(&asset).into_owned(); Ok( - format!( - r#"(function () {{ - const __TAURI_INVOKE_KEY__ = {}; - {} - }})()"#, - manager.generate_invoke_key(), - js + js.replacen( + "__TAURI__INVOKE_KEY_TOKEN__", + &manager.generate_invoke_key().to_string(), + 1, ) .as_bytes() .to_vec(),