From c37c6230e9d23361d339b2ff4957b574df6fda97 Mon Sep 17 00:00:00 2001 From: rouzwelt Date: Thu, 25 Apr 2024 03:15:28 +0000 Subject: [PATCH] init --- src/error.rs | 3 +++ src/module.rs | 4 ++-- src/worker.rs | 27 +++++++++++++++++++++++++++ 3 files changed, 32 insertions(+), 2 deletions(-) diff --git a/src/error.rs b/src/error.rs index 6e487ed..e87b335 100644 --- a/src/error.rs +++ b/src/error.rs @@ -21,4 +21,7 @@ pub enum Error { #[error("failed to get js value")] FailedToGetV8Value, + + #[error("undefined export")] + UndefinedExport, } diff --git a/src/module.rs b/src/module.rs index 3ca386a..8b5eed7 100644 --- a/src/module.rs +++ b/src/module.rs @@ -19,8 +19,8 @@ pub struct JsModule { } impl JsModule { - pub fn export_exists(&self, key: &String) -> bool { - self.exports.contains(key) + pub fn export_exists(&self, key: &str) -> bool { + self.exports.contains(&key.to_string()) } } diff --git a/src/worker.rs b/src/worker.rs index fb0a178..99eaa07 100644 --- a/src/worker.rs +++ b/src/worker.rs @@ -152,6 +152,33 @@ globalThis.require = __internalCreateRequire____("{}");"#, }, }) } + + /// get module object instance + pub fn get_main_module_instance(&mut self) -> Result, Error> { + let mod_namespace = self + .main_worker + .js_runtime + .get_module_namespace(self.main_module.id)?; + Ok(mod_namespace) + } + + /// get the export value + pub fn get_export(&mut self, name: &str) -> Result, Error> { + if !self.main_module.export_exists(name) { + return Err(Error::UndefinedExport); + } + + let module = self.get_main_module_instance()?; + let mut scope = self.main_worker.js_runtime.handle_scope(); + let module = module.open(&mut scope); + + let key = v8::String::new(&mut scope, name).ok_or(Error::FailedToGetV8Value)?; + let value = module + .get(&mut scope, key.into()) + .ok_or(Error::FailedToGetV8Value)?; + + Ok(v8::Global::new(&mut scope, value)) + } } #[cfg(test)]