use std::fs;
use brrrty_js::Value;
use brrrty_js::runtime::{JsResult, JsRuntime, PathPart};
use brrrty_node::{RunMode, Worker, find_node};
fn node() -> Option<brrrty_node::NodeInfo> {
match find_node(None) {
Ok(n) => Some(n),
Err(e) => {
if std::env::var_os("CI").is_some() {
panic!("CI needs Node for these tests: {e}");
}
eprintln!("skipped: {e}");
None
}
}
}
fn site(files: &[(&str, &str)]) -> tempfile::TempDir {
let t = tempfile::tempdir().unwrap();
for (rel, body) in files {
let p = t.path().join(rel);
fs::create_dir_all(p.parent().unwrap()).unwrap();
fs::write(p, body).unwrap();
}
t
}
fn get<'a>(v: &'a Value, k: &str) -> &'a Value {
match v {
Value::Object(o) => o.get(k).unwrap_or_else(|| panic!("no `{k}` in {v:?}")),
other => panic!("not an object: {other:?}"),
}
}
fn list(v: &Value) -> &[Value] {
match v {
Value::Array(a) => a,
other => panic!("not an array: {other:?}"),
}
}
fn s(v: &str) -> Value {
Value::String(v.into())
}
const CONFIG: &str = r#"module.exports = function (eleventyConfig) {
eleventyConfig.addPassthroughCopy("a").addPassthroughCopy("b");
require("./_config/filters.js")(eleventyConfig);
eleventyConfig.setTemplateFormats(["njk", "md"]);
eleventyConfig.addGlobalData("x", 1);
eleventyConfig.setSomethingNew(true);
return { dir: { input: "src" } };
};
"#;
const FILTERS: &str = r#"module.exports = (eleventyConfig) => {
eleventyConfig.addFilter("upper", function upper(s) { return String(s).toUpperCase(); });
eleventyConfig.addAsyncFilter("slow", async function slow(s) { return s; });
};
"#;
#[test]
fn the_config_loads_against_a_recorder_and_replies_with_what_it_set() {
let Some(node) = node() else { return };
let t = site(&[
("eleventy.config.js", CONFIG),
("_config/filters.js", FILTERS),
]);
let mut w = Worker::start(&node, t.path(), RunMode::Build).expect("starts");
let d = match w.load_config(&t.path().join("eleventy.config.js")) {
JsResult::Ok(d) => d,
other => panic!("{other:?}"),
};
let v = &d.value;
let values = get(v, "values");
let copies: Vec<&Value> = list(get(values, "passthroughCopy"))
.iter()
.map(|c| get(c, "input"))
.collect();
assert_eq!(copies, [&s("a"), &s("b")]);
assert_eq!(
get(values, "templateFormats"),
&Value::Array(vec![s("njk"), s("md")].into())
);
assert_eq!(get(get(values, "globalData"), "x"), &Value::Number(1.0));
let dir = get(get(v, "returned"), "dir");
assert_eq!(get(dir, "input"), &s("src"));
let funcs = list(get(v, "functions"));
let names: Vec<&Value> = funcs.iter().map(|f| get(f, "name")).collect();
assert_eq!(names, [&s("upper"), &s("slow")]);
assert_eq!(get(&funcs[0], "kind"), &s("filter"));
assert_eq!(get(&funcs[1], "async"), &Value::Bool(true));
assert_eq!(d.functions.len(), 2);
assert_eq!(
d.functions[0].0,
vec![
PathPart::Key("functions".into()),
PathPart::Index(0),
PathPart::Key("fn".into())
]
);
let un = list(get(v, "unsupported"));
assert_eq!(un.len(), 1);
assert_eq!(get(&un[0], "method"), &s("setSomethingNew"));
assert_eq!(get(&un[0], "at"), &s("eleventy.config.js:6"));
}
#[test]
fn a_config_that_throws_refuses_with_the_file_and_line() {
let Some(node) = node() else { return };
let t = site(&[(
"eleventy.config.js",
"module.exports = function (eleventyConfig) {\n eleventyConfig.addGlobalData(\"x\", 1);\n throw new Error(\"boom\");\n};\n",
)]);
let mut w = Worker::start(&node, t.path(), RunMode::Build).expect("starts");
match w.load_config(&t.path().join("eleventy.config.js")) {
JsResult::Thrown(e) => {
assert_eq!(e.message, "boom");
assert_eq!(e.line, Some(3));
assert!(
e.file
.as_ref()
.is_some_and(|f| f.ends_with("eleventy.config.js")),
"{:?}",
e.file
);
}
other => panic!("{other:?}"),
}
}
#[test]
fn plugins_see_the_merged_path_prefix() {
let Some(node) = node() else { return };
for (returned, want) in [("{}", "/"), (r#"{ pathPrefix: "/blog/" }"#, "/blog/")] {
let cfg = format!(
"module.exports = (c) => {{\n c.addPlugin((p) => {{\n if (p.pathPrefix === undefined) throw new Error(\"The `baseHref` option is required\");\n p.addGlobalData(\"seen\", p.pathPrefix);\n }});\n return {returned};\n}};\n"
);
let t = site(&[("eleventy.config.js", &cfg)]);
let mut w = Worker::start(&node, t.path(), RunMode::Build).expect("starts");
let d = match w.load_config(&t.path().join("eleventy.config.js")) {
JsResult::Ok(d) => d,
other => panic!("{other:?}"),
};
let seen = get(get(&d.value, "values"), "globalData");
assert_eq!(get(seen, "seen"), &s(want));
}
}
#[test]
fn plugins_see_the_merged_dir() {
let Some(node) = node() else { return };
for (returned, want_out, want_in) in [
("{}", "_site", "."),
(
r#"{ dir: { input: "src", output: "dist" } }"#,
"dist",
"src",
),
] {
let cfg = format!(
"module.exports = (c) => {{\n c.addPlugin((p) => {{\n p.addGlobalData(\"out\", p.dir.output);\n p.addGlobalData(\"inp\", p.dir.input);\n }});\n return {returned};\n}};\n"
);
let t = site(&[("eleventy.config.js", &cfg)]);
let mut w = Worker::start(&node, t.path(), RunMode::Build).expect("starts");
let d = match w.load_config(&t.path().join("eleventy.config.js")) {
JsResult::Ok(d) => d,
other => panic!("{other:?}"),
};
let seen = get(get(&d.value, "values"), "globalData");
assert_eq!(get(seen, "out"), &s(want_out));
assert_eq!(get(seen, "inp"), &s(want_in));
}
}
#[test]
fn set_directory_calls_do_not_leak_into_dir() {
let Some(node) = node() else { return };
let cfg = "module.exports = (c) => {\n c.setOutputDirectory(\"dist\");\n c.setLayoutsDirectory(\"lay\");\n c.addPlugin((p) => {\n p.addGlobalData(\"out\", p.dir.output);\n p.addGlobalData(\"inp\", p.dir.input);\n p.addGlobalData(\"lay\", String(p.dir.layouts));\n });\n return { dir: { input: \"src\" } };\n};\n";
let t = site(&[("eleventy.config.js", cfg)]);
let mut w = Worker::start(&node, t.path(), RunMode::Build).expect("starts");
let d = match w.load_config(&t.path().join("eleventy.config.js")) {
JsResult::Ok(d) => d,
other => panic!("{other:?}"),
};
let seen = get(get(&d.value, "values"), "globalData");
assert_eq!(get(seen, "out"), &s("_site"));
assert_eq!(get(seen, "inp"), &s("src"));
assert_eq!(get(seen, "lay"), &s("undefined"));
}
#[test]
fn plugins_see_the_directories() {
let Some(node) = node() else { return };
let plugin = "c.addPlugin((p) => {\n const d = p.directories;\n p.addGlobalData(\"seen\", [d.input, d.output, d.data, d.includes, String(d.layouts)].join(\" \"));\n });";
for (body, want) in [
("return {};", "./ ./_site/ ./_data/ ./_includes/ undefined"),
(
"return { dir: { input: \"src\", output: \"dist\" } };",
"./src/ ./dist/ ./src/_data/ ./src/_includes/ undefined",
),
(
"c.setOutputDirectory(\"out\"); return {};",
"./ ./out/ ./_data/ ./_includes/ undefined",
),
(
"c.setLayoutsDirectory(\"lay\"); return { dir: { input: \"src\" } };",
"./src/ ./_site/ ./src/_data/ ./src/_includes/ ./src/lay/",
),
(
"c.setOutputDirectory(\"dist\"); c.setInputDirectory(\"src\"); return { dir: { output: undefined, input: \"\" } };",
"./src/ ./dist/ ./src/_data/ ./src/_includes/ undefined",
),
] {
let (setup, ret) = match body.find("return") {
Some(i) => body.split_at(i),
None => (body, ""),
};
let cfg = format!("module.exports = (c) => {{\n {setup}\n {plugin}\n {ret}\n}};\n");
let t = site(&[("eleventy.config.js", &cfg)]);
let mut w = Worker::start(&node, t.path(), RunMode::Build).expect("starts");
let d = match w.load_config(&t.path().join("eleventy.config.js")) {
JsResult::Ok(d) => d,
other => panic!("{other:?}"),
};
let seen = get(get(&d.value, "values"), "globalData");
assert_eq!(get(seen, "seen"), &s(want), "{body}");
}
}
#[test]
fn html_transformer_calls_are_recorded_not_thrown() {
let Some(node) = node() else { return };
let cfg = "module.exports = (c) => {\n c.addPlugin((p) => {\n p.htmlTransformer.addUrlTransform([\"html\"], (u) => u, { priority: -1 });\n p.htmlTransformer.addPosthtmlPlugin(\"html\", () => {});\n });\n return {};\n};\n";
let t = site(&[("eleventy.config.js", cfg)]);
let mut w = Worker::start(&node, t.path(), RunMode::Build).expect("starts");
let d = match w.load_config(&t.path().join("eleventy.config.js")) {
JsResult::Ok(d) => d,
other => panic!("{other:?}"),
};
let methods: Vec<&Value> = list(get(&d.value, "unsupported"))
.iter()
.map(|u| get(u, "method"))
.collect();
assert_eq!(methods, [&s("htmlTransformer.addUrlTransform")]);
assert_eq!(list(get(&d.value, "functions")).len(), 2);
}
#[test]
fn posthtml_plugins_are_recorded_as_functions() {
let Some(node) = node() else { return };
let cfg = r#"function IdAttributePlugin(c, options = {}) {
const sel = "[id],h1,h2,h3,h4,h5,h6", checkDuplicates = 1;
c.htmlTransformer.addPosthtmlPlugin("html", () => {}, { name: "x" });
}
module.exports = (c) => {
c.htmlTransformer.addPosthtmlPlugin("html,css", function first() {}, { priority: 3, name: "first", pluginOptions: { a: 1 } });
c.addPlugin(IdAttributePlugin);
c.htmlTransformer.addPosthtmlPlugin("html", function second() {});
return {};
};
"#;
let t = site(&[("eleventy.config.js", cfg)]);
let mut w = Worker::start(&node, t.path(), RunMode::Build).expect("starts");
let d = match w.load_config(&t.path().join("eleventy.config.js")) {
JsResult::Ok(d) => d,
other => panic!("{other:?}"),
};
let fns: Vec<&Value> = list(get(&d.value, "functions"))
.iter()
.filter(|f| get(f, "kind") == &s("posthtml"))
.collect();
assert_eq!(fns.len(), 2, "{:?}", d.value);
assert!(
list(get(&d.value, "functions"))
.iter()
.any(|f| get(f, "kind") == &s("posthtmlRunner"))
);
assert_eq!(get(fns[0], "extensions"), &s("html,css"));
assert_eq!(get(fns[0], "priority"), &Value::Number(3.0));
assert_eq!(get(fns[0], "name"), &s("first"));
assert_eq!(get(get(fns[0], "options"), "a"), &Value::Number(1.0));
assert_eq!(get(fns[1], "priority"), &Value::Number(0.0));
assert!(
list(get(&d.value, "unsupported")).is_empty(),
"{:?}",
d.value
);
let native = list(get(get(&d.value, "values"), "nativeOrder"));
assert_eq!(get(&native[0], "name"), &s("idattribute"));
let seq = |v: &Value| match get(v, "seq") {
Value::Number(n) => *n,
other => panic!("{other:?}"),
};
assert!(seq(fns[0]) < seq(fns[1]) && seq(fns[1]) < seq(&native[0]));
}
#[test]
fn html_transformer_answers_the_in_check() {
let Some(node) = node() else { return };
let cfg = r#"module.exports = (c) => {
if (!("addPosthtmlPlugin" in c.htmlTransformer)) {
throw new Error("`eleventyImageTransformPlugin` is not compatible with this version of Eleventy.");
}
if ("nope" in c.htmlTransformer) throw new Error("unknown name reported present");
c.htmlTransformer.addPosthtmlPlugin("html", () => {});
return {};
};
"#;
let t = site(&[("eleventy.config.js", cfg)]);
let mut w = Worker::start(&node, t.path(), RunMode::Build).expect("starts");
let d = match w.load_config(&t.path().join("eleventy.config.js")) {
JsResult::Ok(d) => d,
other => panic!("{other:?}"),
};
let methods: Vec<&Value> = list(get(&d.value, "unsupported"))
.iter()
.map(|u| get(u, "method"))
.collect();
assert!(methods.is_empty(), "{methods:?}");
}
#[test]
fn built_in_plugins_are_recorded_by_name() {
let Some(node) = node() else { return };
let cfg = r#"const POSTHTML_PLUGIN_NAME = "11ty/eleventy/id-attribute";
function IdAttributePlugin(c, options = {}) {
const sel = "[id],h1,h2,h3,h4,h5,h6", checkDuplicates = "error";
c.htmlTransformer.addPosthtmlPlugin("html", () => {}, { name: POSTHTML_PLUGIN_NAME });
}
function eleventyHtmlBasePlugin(c, options = {}) {
c.addFilter("addPathPrefixToFullUrl", (u) => u);
c.htmlTransformer.addUrlTransform(["html"], (u) => u, { priority: -1 });
}
function TransformPlugin(c, options = {}) {
c.on("eleventy.contentMap", () => {});
c.htmlTransformer.addUrlTransform("html", () => { throw new Error("Internal error: contentMap not available for the `pathToUrl` Transform."); });
}
function Other(c) {
c.htmlTransformer.addPosthtmlPlugin("html", () => {});
}
module.exports = (c) => {
c.addPlugin(IdAttributePlugin);
c.addPlugin(eleventyHtmlBasePlugin, {});
c.addPlugin(TransformPlugin);
c.addPlugin(IdAttributePlugin, { selector: "h2" });
c.addPlugin(Other);
return {};
};
"#;
let t = site(&[("eleventy.config.js", cfg)]);
let mut w = Worker::start(&node, t.path(), RunMode::Build).expect("starts");
let d = match w.load_config(&t.path().join("eleventy.config.js")) {
JsResult::Ok(d) => d,
other => panic!("{other:?}"),
};
assert_eq!(
list(get(get(&d.value, "values"), "nativePlugins")),
[s("idattribute"), s("htmlbase"), s("inputpathtourl")]
);
let methods: Vec<&Value> = list(get(&d.value, "unsupported"))
.iter()
.map(|u| get(u, "method"))
.collect();
assert!(methods.is_empty(), "{methods:?}");
assert_eq!(list(get(&d.value, "functions")).len(), 3);
}
#[test]
fn html_base_is_native_only_for_the_default_path_prefix() {
let Some(node) = node() else { return };
let cfg = r#"function eleventyHtmlBasePlugin(c, options = {}) {
c.addFilter("addPathPrefixToFullUrl", (u) => u);
c.htmlTransformer.addUrlTransform(["html"], (u) => u, { priority: -1 });
}
module.exports = (c) => {
c.addPlugin(eleventyHtmlBasePlugin);
return { pathPrefix: "/blog/" };
};
"#;
let t = site(&[("eleventy.config.js", cfg)]);
let mut w = Worker::start(&node, t.path(), RunMode::Build).expect("starts");
let d = match w.load_config(&t.path().join("eleventy.config.js")) {
JsResult::Ok(d) => d,
other => panic!("{other:?}"),
};
match get(&d.value, "values") {
Value::Object(o) => assert!(o.get("nativePlugins").is_none(), "{o:?}"),
other => panic!("{other:?}"),
}
let methods: Vec<&Value> = list(get(&d.value, "unsupported"))
.iter()
.map(|u| get(u, "method"))
.collect();
assert_eq!(methods, [&s("htmlTransformer.addUrlTransform")]);
}
#[test]
fn get_filter_returns_added_and_built_in_filters() {
let Some(node) = node() else { return };
let cfg = r#"module.exports = function (c) {
c.addFilter("shout", (s) => String(s).toUpperCase());
c.addPlugin(function plugin(config) {
const slugify = config.getFilter("slugify");
config.addGlobalData("slug", slugify("Hello World"));
config.addGlobalData("shout", config.getFilter("shout")("hi"));
config.addGlobalData("none", config.getFilter("nope") === undefined);
});
return {};
};
"#;
let t = site(&[
("eleventy.config.js", cfg),
(
"node_modules/@11ty/eleventy/package.json",
r#"{"name":"@11ty/eleventy","version":"3.1.8","main":"./src/main.cjs"}"#,
),
(
"node_modules/@11ty/eleventy/src/main.cjs",
"module.exports = {};\n",
),
(
"node_modules/@11ty/eleventy/node_modules/@sindresorhus/slugify/package.json",
r#"{"name":"@sindresorhus/slugify","type":"module","exports":"./index.js"}"#,
),
(
"node_modules/@11ty/eleventy/node_modules/@sindresorhus/slugify/index.js",
"export default (s, o) => String(s).toLowerCase().replace(/\\W+/g, \"-\") + (o && o.decamelize === false ? \"\" : \"!\");\n",
),
]);
let mut w = Worker::start(&node, t.path(), RunMode::Build).expect("starts");
let d = match w.load_config(&t.path().join("eleventy.config.js")) {
JsResult::Ok(d) => d,
other => panic!("{other:?}"),
};
let data = get(get(&d.value, "values"), "globalData");
assert_eq!(get(data, "slug"), &s("hello-world"));
assert_eq!(get(data, "shout"), &s("HI"));
assert_eq!(get(data, "none"), &Value::Bool(true));
}
#[test]
fn js_glob_matcher_agrees_with_the_picomatch_table() {
let Some(node) = node() else { return };
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
let src = fs::read_to_string(root.join("src/worker/config.mjs")).unwrap();
let start = src.find("function compileGlob(").expect("compileGlob");
let end = start + src[start..].find("\n}\n").expect("end of compileGlob") + 3;
let rows = fs::read_to_string(root.join("../brrrty-config/src/glob_rows.tsv")).unwrap();
let dir = tempfile::tempdir().unwrap();
let script = format!(
"{}\nconst fs = require('fs');\nlet bad = [];\nlet n = 0;\nfor (const line of fs.readFileSync(process.argv[2], 'utf8').split('\\n')) {{\n if (!line) continue;\n const [p, g, want] = line.split('\\t');\n n++;\n let got;\n try {{ got = compileGlob(g)(p); }} catch (e) {{ got = 'threw: ' + e.message; }}\n if (got !== (want === 'true')) bad.push(p + ' ' + g + ' -> ' + got);\n}}\nconsole.log(JSON.stringify({{ n, bad }}));\n",
&src[start..end]
);
let script_path = dir.path().join("glob.cjs");
fs::write(&script_path, script).unwrap();
let rows_path = dir.path().join("rows.tsv");
fs::write(&rows_path, &rows).unwrap();
let out = std::process::Command::new(&node.path)
.arg(&script_path)
.arg(&rows_path)
.output()
.unwrap();
assert!(
out.status.success(),
"{}",
String::from_utf8_lossy(&out.stderr)
);
let text = String::from_utf8_lossy(&out.stdout);
let want_rows = rows.lines().filter(|l| !l.is_empty()).count();
assert!(text.contains(&format!("\"n\":{want_rows}")), "{text}");
assert!(text.contains("\"bad\":[]"), "JS matcher disagrees: {text}");
}