use js_sys::Function;
use wasm_bindgen::JsValue;
use wasm_bindgen::prelude::*;
use crate::{EngineType, Error, FunctionBundle, Result, python::PythonEngine};
use crate::python::wasm_function_bundle::register_all_functions_with_pyodide;
pub fn register_bundle(engine: &mut PythonEngine, bundle: &FunctionBundle) -> Result<()> {
match bundle {
FunctionBundle::Python(_) => {
println!("Registering Python function bundle with Pyodide...");
web_sys::console::log_1(&"Registering Python function bundle...".to_string().into());
if let FunctionBundle::Python(py_bundle) = bundle {
if let Err(e) = py_bundle.register() {
eprintln!("Failed to register functions in global scope: {:?}", e);
}
}
match register_all_functions_with_pyodide(bundle) {
Ok(_) => {
println!("Successfully registered Python function bundle with Pyodide");
engine._initialized = true;
}
Err(e) => {
eprintln!(
"Failed to register Python function bundle with Pyodide, will try again: {:?}",
e
);
}
}
}
_ => {
}
}
Ok(())
}
pub fn eval(engine: &mut PythonEngine, code: &str) -> Result<String> {
if !engine._initialized {
}
let result = call_run_python(code)?;
let result_str = if result.is_string() {
result
.as_string()
.unwrap_or_else(|| "<no result>".to_string())
} else if result.is_object() {
let obj = result.dyn_ref::<js_sys::Object>().unwrap();
let to_string_result = js_sys::Reflect::get(obj, &"toString".into()).ok();
if let Some(to_string_fn) = to_string_result {
if let Some(to_string_fn) = to_string_fn.dyn_ref::<Function>() {
match to_string_fn.call0(obj) {
Ok(str_result) => str_result
.as_string()
.unwrap_or_else(|| "<toString failed>".to_string()),
Err(_) => "<object>".to_string(),
}
} else {
format!("{:?}", result)
}
} else {
format!("{:?}", result)
}
} else {
use js_sys::JSON;
match JSON::stringify(&result) {
Ok(json_str) => json_str
.as_string()
.unwrap_or_else(|| format!("{:?}", result)),
Err(_) => format!("{:?}", result), }
};
Ok(result_str)
}
fn call_run_python(code: &str) -> Result<JsValue> {
use js_sys::JsString;
use web_sys::window;
let window = window().ok_or_else(|| Error::Python("No window object available".into()))?;
let pyodide_obj = js_sys::Reflect::get(&window.into(), &"pyodide".into()).map_err(|_| {
console_error_panic_hook::set_once();
eprintln!("Pyodide not found in global scope");
Error::Python(
"Pyodide not available. Make sure Pyodide is loaded before running Python code."
.to_string(),
)
})?;
if pyodide_obj.is_undefined() {
return Err(Error::Python(
"Pyodide is undefined. The Pyodide library may not be fully loaded yet.".to_string(),
));
}
let run_python_fn = js_sys::Reflect::get(&pyodide_obj, &"runPython".into()).map_err(|e| {
eprintln!("Failed to get runPython function: {:?}", e);
Error::Python("Failed to get runPython function from Pyodide object".to_string())
})?;
if run_python_fn.is_undefined() {
return Err(Error::Python(
"runPython function is undefined. Pyodide may not be fully initialized.".to_string(),
));
}
let run_python_fn = run_python_fn
.dyn_into::<Function>()
.map_err(|_| Error::Python("runPython is not a function".into()))?;
run_python_fn
.call1(&pyodide_obj, &JsString::from(code).into())
.map_err(|e| {
eprintln!("JS error calling runPython: {:?}", e);
let error_str = format!("{:?}", e);
Error::Python(format!(
"JavaScript error when executing Python code: {error_str}"
))
})
}
pub fn set_var(_engine: &PythonEngine, name: &str, value: &serde_json::Value) -> Result<()> {
let payload = super::py_string_literal(&serde_json::to_string(value).map_err(|_| {
Error::UnconvertibleValue {
backend: EngineType::Python,
}
})?);
call_run_python("import json").map(|_| ())?;
call_run_python(&format!("{name} = json.loads({payload})")).map(|_| ())?;
{
let mut bound = _engine.bound_names.borrow_mut();
if !bound.iter().any(|n| n == name) {
bound.push(name.to_string());
}
}
Ok(())
}
fn js_to_json(value: &JsValue) -> Result<serde_json::Value> {
if value.is_undefined() || value.is_null() {
return Ok(serde_json::Value::Null);
}
let unconvertible = || Error::UnconvertibleValue {
backend: EngineType::Python,
};
let text = js_sys::JSON::stringify(value).map_err(|_| unconvertible())?;
let text = String::from(text);
serde_json::from_str(&text).map_err(|_| unconvertible())
}
pub fn eval_json(_engine: &mut PythonEngine, code: &str) -> Result<serde_json::Value> {
let result = call_run_python(code.trim())?;
js_to_json(&result)
}
pub fn compile_py(src: &str) -> Result<super::PyCodeHandle> {
let lit = super::py_string_literal(src.trim());
let probe = format!("compile({lit}, '<postscriptum>', 'exec')");
call_run_python(&probe)?;
Ok(super::PyCodeHandle {
src: src.trim().to_string(),
})
}
pub fn eval_compiled(
engine: &mut PythonEngine,
handle: &super::PyCodeHandle,
) -> Result<serde_json::Value> {
eval_json(engine, &handle.src)
}
pub fn fork(engine: &PythonEngine) -> Result<PythonEngine> {
Ok(PythonEngine {
_initialized: engine._initialized,
bound_names: std::cell::RefCell::new(engine.bound_names.borrow().clone()),
})
}
pub fn clear(engine: &PythonEngine) -> Result<()> {
let names: Vec<String> = std::mem::take(&mut *engine.bound_names.borrow_mut());
if names.is_empty() {
return Ok(());
}
let pops = names
.iter()
.map(|n| format!("globals().pop('{n}', None)"))
.collect::<Vec<_>>()
.join(", ");
call_run_python(&format!("[{pops}]")).map(|_| ())?;
Ok(())
}