Skip to content

Commit bf638a7

Browse files
committed
refactor(tauri): enhance script execution logic in execute function
- Updated the `execute` function to improve the handling of scripts with and without arguments. - Scripts with arguments are now wrapped in an IIFE and executed as functions, while scripts without arguments are evaluated directly. - Enhanced comments for clarity on the script evaluation process, ensuring better understanding of callable detection and execution flow.
1 parent dd8b8a4 commit bf638a7

1 file changed

Lines changed: 14 additions & 6 deletions

File tree

packages/tauri-plugin/src/commands.rs

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -60,14 +60,17 @@ pub(crate) async fn execute<R: Runtime>(
6060
let tx = Arc::new(Mutex::new(Some(tx)));
6161

6262
// Build the script with args if offered
63-
// Note: TypeScript sends scripts as-is (not JSON.stringify'd), so we serialize here
63+
// For args: evaluate the script as a callable and pass args
64+
// For no-args: evaluate the script expression directly (callable detection happens in JS wrapper)
6465
let script = if !request.args.is_empty() {
6566
let args_json = serde_json::to_string(&request.args)
6667
.map_err(|e| crate::Error::SerializationError(format!("Failed to serialize args: {}", e)))?;
67-
let script_json = serde_json::to_string(&request.script)
68-
.map_err(|e| crate::Error::SerializationError(format!("Failed to serialize script: {}", e)))?;
69-
format!("(function() {{ const __wdio_args = {}; return ({}); }})()", args_json, script_json)
68+
format!(
69+
"(function() {{ const __wdio_fn = ({}); const __wdio_args = {}; return __wdio_fn(...__wdio_args); }})()",
70+
request.script, args_json
71+
)
7072
} else {
73+
// No args - preserve the script expression and evaluate it below
7174
request.script.clone()
7275
};
7376

@@ -125,8 +128,13 @@ pub(crate) async fn execute<R: Runtime>(
125128
throw new Error('window.__TAURI__.core.invoke not available after timeout');
126129
}}
127130
128-
// Execute the user's script
129-
const result = await ({});
131+
// Execute the user's script.
132+
// If expression resolves to a function, call it with Tauri APIs.
133+
// Otherwise, await the value directly.
134+
const __wdio_script = ({});
135+
const result = typeof __wdio_script === 'function'
136+
? await __wdio_script({{ core: window.__TAURI__?.core, event: window.__TAURI__?.event }})
137+
: await __wdio_script;
130138
131139
// Emit the result using the current window's event emitter
132140
// This ensures the event goes to the same window where we're listening

0 commit comments

Comments
 (0)