postscriptum 0.1.0

Multi-interpreted-language scripting engine for Rust with Rhai and Python backends
Documentation
use std::sync::Arc;

use js_sys::Function;
use wasm_bindgen::prelude::*;
use web_sys::{console, window};

use crate::wasm_utils::{JsConvert, RUST_FUNCTIONS, call_rust_function};
use wasm_bindgen::JsCast;

/// A trait for Python-callable functions that abstracts over different function arities.
/// For WASM, we represent functions differently since we now use a global registry approach
pub trait PythonFunction: Send + Sync + 'static {
    fn name(&self) -> &str;
    fn register_in_global_scope(&self) -> Result<(), JsValue>; // Register in JavaScript global scope
}

/// Python-specific function bundle for WASM using the global registry approach
#[derive(Clone)]
pub struct PythonFunctionBundle {
    pub functions: Vec<String>, // Store function names that were registered in the global registry
}

impl PythonFunctionBundle {
    pub fn new() -> Self {
        Self {
            functions: Vec::new(),
        }
    }

    pub fn add_fn0<F, R>(&mut self, name: &str, f: F)
    where
        F: Fn() -> R + Send + Sync + 'static,
        R: JsConvert,
    {
        let closure = Arc::new(move |_js_arg: JsValue| -> JsValue {
            let result = f();
            result.into_js()
        });

        RUST_FUNCTIONS
            .lock()
            .unwrap()
            .insert(name.to_string(), closure);
        self.functions.push(name.to_string());
    }

    pub fn add_fn1<F, A, R>(&mut self, name: &str, f: F)
    where
        F: Fn(A) -> R + Send + Sync + 'static,
        A: JsConvert,
        R: JsConvert,
    {
        let closure = Arc::new(move |js_arg: JsValue| -> JsValue {
            let arg = A::from_js(js_arg);
            let result = f(arg);
            result.into_js()
        });

        RUST_FUNCTIONS
            .lock()
            .unwrap()
            .insert(name.to_string(), closure);
        self.functions.push(name.to_string());
    }

    pub fn add_fn2<F, A, B, R>(&mut self, name: &str, f: F)
    where
        F: Fn(A, B) -> R + Send + Sync + 'static,
        A: JsConvert,
        B: JsConvert,
        R: JsConvert,
    {
        let closure = Arc::new(move |js_arg: JsValue| -> JsValue {
            // For 2-argument functions, the js_arg should be an array of arguments
            // when called from our registry bridge in the main module
            let args = js_sys::Array::from(&js_arg);
            if args.length() >= 2 {
                let arg1 = A::from_js(args.get(0));
                let arg2 = B::from_js(args.get(1));
                let result = f(arg1, arg2);
                result.into_js()
            } else {
                // If there aren't enough arguments, return null
                JsValue::NULL
            }
        });

        RUST_FUNCTIONS
            .lock()
            .unwrap()
            .insert(name.to_string(), closure);
        self.functions.push(name.to_string());
    }

    pub fn add_fn3<F, A, B, C, R>(&mut self, name: &str, f: F)
    where
        F: Fn(A, B, C) -> R + Send + Sync + 'static,
        A: JsConvert,
        B: JsConvert,
        C: JsConvert,
        R: JsConvert,
    {
        let closure = Arc::new(move |js_arg: JsValue| -> JsValue {
            let args = js_sys::Array::from(&js_arg);
            if args.length() >= 3 {
                let arg1 = A::from_js(args.get(0));
                let arg2 = B::from_js(args.get(1));
                let arg3 = C::from_js(args.get(2));
                let result = f(arg1, arg2, arg3);
                result.into_js()
            } else {
                JsValue::NULL
            }
        });

        RUST_FUNCTIONS
            .lock()
            .unwrap()
            .insert(name.to_string(), closure);
        self.functions.push(name.to_string());
    }

    pub fn add_fn4<F, A, B, C, D, R>(&mut self, name: &str, f: F)
    where
        F: Fn(A, B, C, D) -> R + Send + Sync + 'static,
        A: JsConvert,
        B: JsConvert,
        C: JsConvert,
        D: JsConvert,
        R: JsConvert,
    {
        let closure = Arc::new(move |js_arg: JsValue| -> JsValue {
            let args = js_sys::Array::from(&js_arg);
            if args.length() >= 4 {
                let arg1 = A::from_js(args.get(0));
                let arg2 = B::from_js(args.get(1));
                let arg3 = C::from_js(args.get(2));
                let arg4 = D::from_js(args.get(3));
                let result = f(arg1, arg2, arg3, arg4);
                result.into_js()
            } else {
                JsValue::NULL
            }
        });

        RUST_FUNCTIONS
            .lock()
            .unwrap()
            .insert(name.to_string(), closure);
        self.functions.push(name.to_string());
    }

    /// Register all functions in the bundle in the JavaScript global scope
    pub fn register(&self) -> Result<(), JsValue> {
        // Create JavaScript function wrappers using closures that will be called with arguments
        for name in &self.functions {
            // Create a closure that can handle variable arguments by using the JavaScript arguments object
            let closure = {
                let name_string = name.clone();
                Closure::wrap(Box::new(move |arg1: JsValue, arg2: JsValue| -> JsValue {
                    // Create an array to hold the arguments
                    let args_array = js_sys::Array::new();
                    args_array.push(&arg1);
                    if !arg2.is_undefined() && !arg2.is_null() {
                        args_array.push(&arg2);
                    }

                    // Call the registry function with the arguments array
                    call_rust_function(&name_string, args_array.into())
                })
                    as Box<dyn FnMut(JsValue, JsValue) -> JsValue>)
            };

            // Register the closure as a JavaScript function
            let window = window().ok_or_else(|| JsValue::from_str("No global window object"))?;
            js_sys::Reflect::set(&window, &name.clone().into(), &closure.as_ref().as_ref())?;

            // Keep the closure alive
            std::mem::forget(closure);
        }
        Ok(())
    }
}

// Function to register all the functions with Pyodide globals
pub fn register_all_functions_with_pyodide(bundle: &crate::FunctionBundle) -> Result<(), JsValue> {
    let window = window().ok_or_else(|| JsValue::from_str("No global window object"))?;
    let pyodide = js_sys::Reflect::get(&window, &"pyodide".into())
        .map_err(|_| JsValue::from_str("Pyodide not loaded"))?;

    if pyodide.is_undefined() {
        return Err(JsValue::from_str("Pyodide is undefined"));
    }

    // Get the Pyodide globals object
    let pyodide_globals = js_sys::Reflect::get(&pyodide, &"globals".into())
        .map_err(|_| JsValue::from_str("Could not get Pyodide globals"))?;

    // If the bundle is a Python bundle, we need to get the function names and register them
    if let crate::FunctionBundle::Python(bundle) = bundle {
        // For each registered function, get it from the JavaScript global scope
        for func_name in &bundle.functions {
            // Get the function from the global JavaScript scope
            let js_func = js_sys::Reflect::get(&window, &func_name.clone().into())?;

            // Add it to Pyodide's global scope
            js_sys::Reflect::set(&pyodide_globals, &func_name.clone().into(), &js_func)?;
        }
    }

    Ok(())
}