Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
feat(fetch): evaluate expressions from files
ldm09da8ac5092c5
diff --git a/moli/src/app.rs b/moli/src/app.rsindex 3aa5c4bf9..ee248588d 100644--- a/moli/src/app.rs+++ b/moli/src/app.rs@@ -41,7 +41,15 @@ pub async fn run_cli_with_config<W: Write>(stdout: &mut W,) -> Result<()> {match cli.command {- Commands::Fetch(args) => {+ Commands::Fetch(mut args) => {+ let eval_expression =+ if let Some(path) = args.eval_file.as_deref() {+ Some(std::fs::read_to_string(path).with_context(|| {+ format!("failed to read --eval-file `{}`", path.display())+ })?)+ } else {+ args.eval.take()+ };let request = build_fetch_request(&args.url, &config)?;if config.browser.fetch().obey_robots() {// Checked before the browser starts so a refused fetch costs@@ -66,10 +74,12 @@ pub async fn run_cli_with_config<W: Write>(let mut page = match fetched_document {FetchedDocument::Page(page) => page,FetchedDocument::Raw(raw_document) => {- if args.eval.is_some() {+ if eval_expression.is_some() {finalize_fetch_browser(browser);return Err(with_fetch_context(- anyhow!("raw non-HTML document fetch does not support --eval"),+ anyhow!(+ "raw non-HTML document fetch does not support --eval or --eval-file"+ ),&args.url,));}@@ -114,7 +124,7 @@ pub async fn run_cli_with_config<W: Write>(.map_err(|error| with_fetch_context(error, &args.url))?;}- let rendered = if let Some(expression) = args.eval.as_deref() {+ let rendered = if let Some(expression) = eval_expression.as_deref() {eval_output::evaluate(&mut page, expression).await} else {fetch_dump::render_page_output_async(&mut page, &config.fetch).awaitdiff --git a/moli/src/cli.rs b/moli/src/cli.rsindex dd4b3f984..f6a698c16 100644--- a/moli/src/cli.rs+++ b/moli/src/cli.rs@@ -1,4 +1,4 @@-use std::{ffi::OsString, num::NonZeroU32};+use std::{ffi::OsString, num::NonZeroU32, path::PathBuf};use clap::{Args, Parser, Subcommand, ValueEnum};use regex::Regex;@@ -50,10 +50,25 @@ pub struct FetchArgs {#[arg(long,value_name = "EXPRESSION",- conflicts_with_all = ["dump", "with_base", "with_frames", "strip_mode"]+ conflicts_with_all = [+ "eval_file",+ "dump",+ "with_base",+ "with_frames",+ "strip_mode"+ ])]pub eval: Option<String>,+ /// Read the JavaScript expression from a UTF-8 file. This avoids command-line+ /// argument length limits for large or multiline scripts. Promises are awaited.+ #[arg(+ long,+ value_name = "PATH",+ conflicts_with_all = ["eval", "dump", "with_base", "with_frames", "strip_mode"]+ )]+ pub eval_file: Option<PathBuf>,+#[arg(short = 'H', long = "header", value_name = "HEADER", value_parser = parse_request_header_arg)]pub headers: Vec<RequestHeaderArg>,diff --git a/moli/tests/cli.rs b/moli/tests/cli.rsindex df6fb8e74..853887077 100644--- a/moli/tests/cli.rs+++ b/moli/tests/cli.rs@@ -75,6 +75,7 @@ fn parses_explicit_fetch_command_with_compatibility_flags() {Commands::Fetch(Box::new(FetchArgs {dump: Some(DumpFormat::SemanticTree),eval: None,+ eval_file: None,headers: vec![RequestHeaderArg {name: "X-Test".to_owned(),@@ -418,6 +419,7 @@ fn infers_fetch_mode_from_bare_url() {Commands::Fetch(Box::new(FetchArgs {dump: None,eval: None,+ eval_file: None,headers: vec![],disable_js: false,with_base: false,@@ -459,6 +461,7 @@ fn parses_bare_dump_with_explicit_fetch_command_and_defaults_to_html() {Commands::Fetch(Box::new(FetchArgs {dump: Some(DumpFormat::Html),eval: None,+ eval_file: None,headers: vec![],disable_js: false,with_base: false,@@ -501,6 +504,7 @@ fn parses_header_flag_with_explicit_fetch_command() {Commands::Fetch(Box::new(FetchArgs {dump: None,eval: None,+ eval_file: None,headers: vec![RequestHeaderArg {name: "X-Test".to_owned(),value: "one".to_owned(),@@ -908,21 +912,65 @@ fn parses_fetch_eval_expression() {panic!("expected fetch command");};assert_eq!(args.eval.as_deref(), Some("document.title"));+ assert!(args.eval_file.is_none());+}++#[test]+fn parses_fetch_eval_file() {+ let cli = Cli::try_parse_from(normalize_args_for_compat([+ "moli",+ "fetch",+ "--eval-file",+ "extract.js",+ "https://example.com",+ ]))+ .unwrap();++ let Commands::Fetch(args) = cli.command else {+ panic!("expected fetch command");+ };+ assert!(args.eval.is_none());+ assert_eq!(+ args.eval_file.as_deref(),+ Some(std::path::Path::new("extract.js"))+ );+}++#[test]+fn fetch_eval_sources_are_mutually_exclusive() {+ let error = Cli::try_parse_from(normalize_args_for_compat([+ "moli",+ "fetch",+ "--eval",+ "document.title",+ "--eval-file",+ "extract.js",+ "https://example.com",+ ]))+ .unwrap_err();++ assert_eq!(error.kind(), clap::error::ErrorKind::ArgumentConflict);}#[test]fn fetch_eval_rejects_page_dump_output_options() {- for conflicting_args in [- &["--dump", "json"][..],- &["--with-base"][..],- &["--with-frames"][..],- &["--strip-mode", "js"][..],+ for eval_args in [+ &["--eval", "document.title"][..],+ &["--eval-file", "extract.js"][..],] {- let mut args = vec!["moli", "fetch", "--eval", "document.title"];- args.extend_from_slice(conflicting_args);- args.push("https://example.com");- let error = Cli::try_parse_from(normalize_args_for_compat(args)).unwrap_err();- assert_eq!(error.kind(), clap::error::ErrorKind::ArgumentConflict);+ for conflicting_args in [+ &["--dump", "json"][..],+ &["--with-base"][..],+ &["--with-frames"][..],+ &["--strip-mode", "js"][..],+ ] {+ let mut args = vec!["moli", "fetch"];+ args.extend_from_slice(eval_args);+ args.extend_from_slice(conflicting_args);+ args.push("https://example.com");+ let error = Cli::try_parse_from(normalize_args_for_compat(args)).unwrap_err();+ assert_eq!(error.kind(), clap::error::ErrorKind::ArgumentConflict);+ }}}diff --git a/moli/tests/fetch_cli/eval.rs b/moli/tests/fetch_cli/eval.rsindex 311b9830d..4a7b6e23f 100644--- a/moli/tests/fetch_cli/eval.rs+++ b/moli/tests/fetch_cli/eval.rs@@ -1,22 +1,39 @@-use super::{BinaryDocumentFixtureServer, clean_output, run_moli};+use super::{BinaryDocumentFixtureServer, clean_output, run_moli, unique_temp_file_path};use anyhow::Result;use moli_test_support::FixtureServer;+use std::{+ ffi::{OsStr, OsString},+ path::Path,+};fn run_eval(url: &str, expression: &str, extra_args: &[&str]) -> Result<super::Output> {+ run_eval_source(url, "--eval", OsStr::new(expression), extra_args)+}++fn run_eval_file(url: &str, path: &Path, extra_args: &[&str]) -> Result<super::Output> {+ run_eval_source(url, "--eval-file", path.as_os_str(), extra_args)+}++fn run_eval_source(+ url: &str,+ source_flag: &str,+ source: &OsStr,+ extra_args: &[&str],+) -> Result<super::Output> {let mut args = vec![- "moli",- "fetch",- "--log-level",- "error",- "--http-no-proxy",- "*",- "--wait-until",- "load",- "--eval",- expression,+ OsString::from("moli"),+ OsString::from("fetch"),+ OsString::from("--log-level"),+ OsString::from("error"),+ OsString::from("--http-no-proxy"),+ OsString::from("*"),+ OsString::from("--wait-until"),+ OsString::from("load"),+ OsString::from(source_flag),+ source.to_owned(),];- args.extend_from_slice(extra_args);- args.push(url);+ args.extend(extra_args.iter().map(|arg| OsString::from(*arg)));+ args.push(OsString::from(url));run_moli(args)}@@ -91,6 +108,64 @@ fn eval_awaits_a_promise_result() -> Result<()> {Ok(())}+#[test]+fn eval_file_executes_large_multiline_scripts() -> Result<()> {+ let runtime = tokio::runtime::Runtime::new()?;+ let server = runtime.block_on(FixtureServer::spawn())?;+ let url = server.url("/static");+ let script_file = unique_temp_file_path("eval-file-large", "extract.js")?;+ let script = format!(+ "/*{}*/\n\+ const main = document.querySelector('main');\n\+ const text = main.textContent.trim();\n\+ ({{ tag: main.tagName.toLowerCase(), text }})",+ "padding".repeat(24 * 1024),+ );+ assert!(script.len() > 128 * 1024);+ std::fs::write(&script_file, script)?;++ let output = run_eval_file(&url, &script_file, &[])?;+ runtime.block_on(server.shutdown());+ if let Some(directory) = script_file.parent() {+ let _ = std::fs::remove_dir_all(directory);+ }++ assert!(+ output.status.success(),+ "stderr={}",+ clean_output(&output.stderr)+ );+ let value: serde_json::Value = serde_json::from_slice(&output.stdout)?;+ assert_eq!(+ value,+ serde_json::json!({ "tag": "main", "text": "fixture static" })+ );+ Ok(())+}++#[test]+fn eval_file_reports_read_errors_before_fetching() -> Result<()> {+ let script_file = unique_temp_file_path("eval-file-missing", "missing.js")?;+ let output = run_eval_file(+ "https://eval-file-must-not-fetch.invalid/",+ &script_file,+ &[],+ )?;+ if let Some(directory) = script_file.parent() {+ let _ = std::fs::remove_dir_all(directory);+ }++ let stdout = clean_output(&output.stdout);+ let stderr = clean_output(&output.stderr);+ assert!(!output.status.success(), "stdout={stdout}\nstderr={stderr}");+ assert!(stdout.is_empty(), "stdout={stdout}");+ assert!(+ stderr.contains("failed to read --eval-file") && stderr.contains("missing.js"),+ "stderr={stderr}"+ );+ Ok(())+}+#[test]fn eval_remains_available_when_page_javascript_is_disabled() -> Result<()> {let runtime = tokio::runtime::Runtime::new()?;