javy_plugin_api/
javy_plugin.rs

1/// Provides default implementations for required methods a Javy plugin.
2///
3/// # Arguments
4///
5/// * `namespace` - The name of the module that will be used for function
6///   imports in dynamically linked modules generated with this plugin.
7/// * `component` - A struct.
8/// * `config` - A function that will return a [`javy::Config`] to configure
9///   the [`javy::Runtime`].
10/// * `modify_runtime` - A function that can add modify the [`javy::Runtime`].
11///   For example, by adding additional methods for use by JavaScript.
12///
13/// # Examples
14///
15/// ```ignore
16/// use javy_plugin_api::{javy::{Config, Runtime}, javy_plugin};
17///
18/// struct Component;
19///
20/// javy_plugin!("my-import-namespace", Component, config, modify_runtime);
21///
22/// fn config() -> Config {
23///     Config::default()
24/// }
25///
26/// fn modify_runtime(runtime: Runtime) -> Runtime {
27///     runtime
28/// }
29/// ```
30#[macro_export]
31macro_rules! javy_plugin {
32    ($namespace:literal, $component:ident, $config:expr, $modify_runtime:expr) => {
33        javy_plugin_api::import_namespace!($namespace);
34
35        impl Guest for $component {
36            fn compile_src(src: Vec<u8>) -> Result<Vec<u8>, String> {
37                javy_plugin_api::compile_src(&src).map_err(|e| e.to_string())
38            }
39
40            fn initialize_runtime() -> () {
41                javy_plugin_api::initialize_runtime($config, $modify_runtime).unwrap();
42            }
43
44            fn invoke(bytecode: Vec<u8>, function: Option<String>) -> () {
45                javy_plugin_api::invoke(&bytecode, function.as_deref()).unwrap_or_else(|e| {
46                    eprintln!("{e}");
47                    std::process::abort();
48                });
49            }
50        }
51    };
52}