Skip to content

Commit

Permalink
Move json_module to Module::from_value_as_default
Browse files Browse the repository at this point in the history
  • Loading branch information
hansl committed Apr 10, 2024
1 parent 72dc002 commit 9cccd30
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 19 deletions.
19 changes: 19 additions & 0 deletions core/engine/src/module/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ use std::hash::Hash;
use std::path::{Path, PathBuf};
use std::rc::Rc;

use boa_engine::js_string;
use rustc_hash::FxHashSet;

use boa_gc::{Finalize, Gc, GcRefCell, Trace};
Expand Down Expand Up @@ -204,6 +205,24 @@ impl Module {
}
}

/// Create a [`Module`] from a `JsValue`, exporting that value as the default export.
/// This will clone the module everytime it is initialized.
pub fn from_value_as_default(value: JsValue, context: &mut Context) -> Self {
Module::synthetic(
&[js_string!("default")],
SyntheticModuleInitializer::from_copy_closure_with_captures(
move |m, value, _ctx| {
m.set_export(&js_string!("default"), value.clone())?;
Ok(())
},
value,
),
None,
None,
context,
)
}

/// Gets the realm of this `Module`.
#[inline]
#[must_use]
Expand Down
20 changes: 1 addition & 19 deletions core/interop/src/modules/json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,8 @@
//! as the default export.
#![allow(clippy::module_name_repetitions)]

use boa_engine::module::SyntheticModuleInitializer;
use boa_engine::{js_string, Context, JsValue, Module};

Check failure on line 5 in core/interop/src/modules/json.rs

View workflow job for this annotation

GitHub Actions / Coverage

unused imports: `Context`, `JsValue`, `Module`, `js_string`

/// Create a module that exports a single JSON value as the default export.
pub fn json_module(value: JsValue, context: &mut Context) -> Module {
Module::synthetic(
&[js_string!("default")],
SyntheticModuleInitializer::from_copy_closure_with_captures(
move |m, s, _ctx| {
m.set_export(&js_string!("default"), s.clone())?;
Ok(())
},
value,
),
None,
None,
context,
)
}

/// Create a module that exports a single JSON value as the default export, from its
/// JSON string. This required the `json` feature to be enabled.
///
Expand All @@ -33,7 +15,7 @@ pub fn json_string_module(json: &str, context: &mut Context) -> boa_engine::JsRe
boa_engine::JsError::from_opaque(js_string!(format!("Failed to parse JSON: {}", e)).into())
})?;
let value: JsValue = JsValue::from_json(&json_value, context)?;
Ok(json_module(value, context))
Ok(Module::from_value_as_default(value, context))
}

#[cfg(feature = "json")]
Expand Down

0 comments on commit 9cccd30

Please sign in to comment.