use v8::PinScope;
use crate::JsRuntime;
pub const HOST_DEFINED_OPTIONS_KIND_INDEX: usize = 0;
pub const HOST_DEFINED_OPTIONS_KEY_INDEX: usize = 1;
pub mod host_defined_options_kind {
pub const VM_DYNAMIC_IMPORT_MISSING: u32 = 1;
pub const VM_DYNAMIC_IMPORT_CALLBACK: u32 = 2;
}
pub fn create_host_defined_options_with_kind<'s>(
scope: &mut PinScope<'s, '_>,
kind: u32,
) -> v8::Local<'s, v8::Data> {
let arr = v8::PrimitiveArray::new(scope, 1);
let value = v8::Integer::new_from_unsigned(scope, kind);
arr.set(scope, HOST_DEFINED_OPTIONS_KIND_INDEX, value.into());
arr.into()
}
pub fn create_host_defined_options_with_kind_and_key<'s>(
scope: &mut PinScope<'s, '_>,
kind: u32,
key: u32,
) -> v8::Local<'s, v8::Data> {
let arr = v8::PrimitiveArray::new(scope, 2);
let kind_value = v8::Integer::new_from_unsigned(scope, kind);
arr.set(scope, HOST_DEFINED_OPTIONS_KIND_INDEX, kind_value.into());
let key_value = v8::Integer::new_from_unsigned(scope, key);
arr.set(scope, HOST_DEFINED_OPTIONS_KEY_INDEX, key_value.into());
arr.into()
}
pub fn read_host_defined_options_kind(
scope: &mut PinScope<'_, '_>,
host_defined_options: v8::Local<v8::Data>,
) -> Option<u32> {
let arr: v8::Local<v8::PrimitiveArray> = unsafe {
std::mem::transmute::<v8::Local<v8::Data>, v8::Local<v8::PrimitiveArray>>(
host_defined_options,
)
};
if arr.length() == HOST_DEFINED_OPTIONS_KIND_INDEX {
return None;
}
let primitive = arr.get(scope, HOST_DEFINED_OPTIONS_KIND_INDEX);
let value: v8::Local<v8::Value> = primitive.into();
let int = v8::Local::<v8::Uint32>::try_from(value).ok()?;
Some(int.value())
}
pub fn read_host_defined_options_key(
scope: &mut PinScope<'_, '_>,
host_defined_options: v8::Local<v8::Data>,
) -> Option<u32> {
let arr: v8::Local<v8::PrimitiveArray> = unsafe {
std::mem::transmute::<v8::Local<v8::Data>, v8::Local<v8::PrimitiveArray>>(
host_defined_options,
)
};
if arr.length() <= HOST_DEFINED_OPTIONS_KEY_INDEX {
return None;
}
let primitive = arr.get(scope, HOST_DEFINED_OPTIONS_KEY_INDEX);
let value: v8::Local<v8::Value> = primitive.into();
let int = v8::Local::<v8::Uint32>::try_from(value).ok()?;
Some(int.value())
}
pub fn register_vm_dynamic_import_callback(
scope: &mut PinScope<'_, '_>,
callback: v8::Local<v8::Function>,
) -> u32 {
let state = JsRuntime::state_from(scope);
let id = state.next_vm_dynamic_import_callback_id.get();
state
.next_vm_dynamic_import_callback_id
.set(id.checked_add(1).unwrap_or(1));
state
.vm_dynamic_import_callbacks
.borrow_mut()
.insert(id, v8::Global::new(scope, callback));
id
}
pub fn register_external_module_import_meta_cb(
scope: &mut PinScope<'_, '_>,
callback: crate::runtime::ExternalModuleImportMetaCb,
) {
let state = JsRuntime::state_from(scope);
state.external_module_import_meta_cb.set(Some(callback));
}