Skip to content

Commit

Permalink
fix: define stringified value
Browse files Browse the repository at this point in the history
  • Loading branch information
xusd320 committed Jul 1, 2024
1 parent 57ff2c7 commit 7ba0a94
Showing 1 changed file with 26 additions and 9 deletions.
35 changes: 26 additions & 9 deletions crates/mako/src/visitors/env_replacer.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use std::collections::HashMap;
use std::str::FromStr;
use std::sync::Arc;

use anyhow::{anyhow, Result};
Expand Down Expand Up @@ -190,14 +191,15 @@ pub fn build_env_map(
fn get_env_expr(v: Value, context: &Arc<Context>) -> Result<Expr> {
match v {
Value::String(v) => {
let safe_value = if Value::from_str(&v).map_or(false, |t| t.is_object()) {
format!("({})", v)
} else {
v.clone()
};

// the string content is treat as expression, so it has to be parsed
let ast = JsAst::build(
"_mako_internal/_define_.js",
&format!("({})", v),
context.clone(),
)
.map_err(|_| anyhow!(ConfigError::InvalidateDefineConfig(v.clone())))
.unwrap();
let ast =
JsAst::build("_mako_internal/_define_.js", &safe_value, context.clone()).unwrap();
let module = ast.ast.body.first().unwrap();

match module {
Expand Down Expand Up @@ -332,7 +334,7 @@ mod tests {
"A".to_string() => json!("\"foo\"")
}
),
r#"log(("foo"));"#
r#"log("foo");"#
);
}

Expand All @@ -349,7 +351,7 @@ mod tests {
log([
1,
true,
("foo")
"foo"
]);
"#
.trim()
Expand All @@ -367,6 +369,21 @@ log([
);
}

#[test]
fn test_stringified_env() {
assert_eq!(
run(
r#"log(A)"#,
hashmap! {
"A".to_string() => json!("{\"v\": 1}")
}
),
r#"log(({
"v": 1
}));"#
);
}

fn run(js_code: &str, envs: HashMap<String, Value>) -> String {
let mut test_utils = TestUtils::gen_js_ast(js_code);
let envs = build_env_map(envs, &test_utils.context).unwrap();
Expand Down

0 comments on commit 7ba0a94

Please sign in to comment.