Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

feat(cli): split response waits into literal and regex modes

ldm08441f9a7d822
diff --git a/moli-core/src/page/mod.rs b/moli-core/src/page/mod.rs
index 42fda63e0..79d3b7294 100644
--- a/moli-core/src/page/mod.rs
+++ b/moli-core/src/page/mod.rs
@@ -155,12 +155,13 @@ pub use protocol_support::{
ScriptObservableOutputItem, SubresourceAuthChallenge, SubresourceAuthCredentials,
SubresourceAuthScheme, SubresourceAuthTarget, SubresourceBodyFinished,
SubresourceBodyFinishedResult, SubresourceDataReceived, SubresourceEventSourceMessageReceived,
- SubresourceJsonPathEquals, SubresourceNetworkOutcome, SubresourceNetworkRecord,
- SubresourceNetworkRequestHandle, SubresourceRequestInitiatorType, SubresourceRequestStarted,
- SubresourceResourceType, SubresourceResponseBody, SubresourceResponseStarted,
- SubresourceResponseWaitCriteria, ViewportSurface, WebSocketFrameDirection,
- WebSocketFrameOpcode, WebSocketLifecycleEvent, WebSocketLifecycleKind, WebSocketNetworkEvent,
- extract_subresource_auth_challenge, subresource_auth_credentials_for_challenge,
+ SubresourceJsonPathEquals, SubresourceJsonPathRegex, SubresourceNetworkOutcome,
+ SubresourceNetworkRecord, SubresourceNetworkRequestHandle, SubresourceRequestInitiatorType,
+ SubresourceRequestStarted, SubresourceResourceType, SubresourceResponseBody,
+ SubresourceResponseStarted, SubresourceResponseWaitCriteria, ViewportSurface,
+ WebSocketFrameDirection, WebSocketFrameOpcode, WebSocketLifecycleEvent, WebSocketLifecycleKind,
+ WebSocketNetworkEvent, extract_subresource_auth_challenge,
+ subresource_auth_credentials_for_challenge,
};
pub use renderer_command_support::DocumentNodeClientRectResolution;
pub use renderer_command_support::{
diff --git a/moli-core/src/page/protocol_support.rs b/moli-core/src/page/protocol_support.rs
index f758026c0..88d7ead42 100644
--- a/moli-core/src/page/protocol_support.rs
+++ b/moli-core/src/page/protocol_support.rs
@@ -14,10 +14,11 @@ pub use crate::protocol_types::{
ScriptObservableOutputItem, SubresourceAuthChallenge, SubresourceAuthCredentials,
SubresourceAuthScheme, SubresourceAuthTarget, SubresourceBodyFinished,
SubresourceBodyFinishedResult, SubresourceDataReceived, SubresourceEventSourceMessageReceived,
- SubresourceJsonPathEquals, SubresourceNetworkOutcome, SubresourceNetworkRecord,
- SubresourceNetworkRequestHandle, SubresourceRequestInitiatorType, SubresourceRequestStarted,
- SubresourceResourceType, SubresourceResponseBody, SubresourceResponseStarted,
- SubresourceResponseWaitCriteria, ViewportSurface, WebSocketFrameDirection,
- WebSocketFrameOpcode, WebSocketLifecycleEvent, WebSocketLifecycleKind, WebSocketNetworkEvent,
- extract_subresource_auth_challenge, subresource_auth_credentials_for_challenge,
+ SubresourceJsonPathEquals, SubresourceJsonPathRegex, SubresourceNetworkOutcome,
+ SubresourceNetworkRecord, SubresourceNetworkRequestHandle, SubresourceRequestInitiatorType,
+ SubresourceRequestStarted, SubresourceResourceType, SubresourceResponseBody,
+ SubresourceResponseStarted, SubresourceResponseWaitCriteria, ViewportSurface,
+ WebSocketFrameDirection, WebSocketFrameOpcode, WebSocketLifecycleEvent, WebSocketLifecycleKind,
+ WebSocketNetworkEvent, extract_subresource_auth_challenge,
+ subresource_auth_credentials_for_challenge,
};
diff --git a/moli-page-types/src/lib.rs b/moli-page-types/src/lib.rs
index 556f877ab..9b272fccc 100644
--- a/moli-page-types/src/lib.rs
+++ b/moli-page-types/src/lib.rs
@@ -1927,13 +1927,16 @@ fn configure_secure_subresource_response_body_spool_file_options(_options: &mut
#[derive(Debug, Clone, Default)]
pub struct SubresourceResponseWaitCriteria {
pub url_contains: Option<String>,
+ pub url_regex: Option<Regex>,
+ pub body_contains: Option<String>,
pub body_regex: Option<Regex>,
pub json_path_equals: Option<SubresourceJsonPathEquals>,
+ pub json_path_regex: Option<SubresourceJsonPathRegex>,
}
impl SubresourceResponseWaitCriteria {
pub fn is_empty(&self) -> bool {
- self.url_contains.is_none() && self.body_regex.is_none() && self.json_path_equals.is_none()
+ self.url_contains.is_none() && self.url_regex.is_none() && !self.requires_response_body()
}
/// Compatibility matcher for diagnostic surfaces that prefer best-effort
@@ -1962,21 +1965,41 @@ impl SubresourceResponseWaitCriteria {
return Ok(false);
}
+ if let Some(regex) = self.url_regex.as_ref()
+ && !regex.is_match(record.url().as_str())
+ && !matches!(
+ record.outcome(),
+ SubresourceNetworkOutcome::Success { final_url, .. }
+ if regex.is_match(final_url.as_str())
+ )
+ {
+ return Ok(false);
+ }
+
let SubresourceNetworkOutcome::Success {
response_headers,
response_body,
..
} = record.outcome()
else {
- return Ok(self.body_regex.is_none() && self.json_path_equals.is_none());
+ return Ok(!self.requires_response_body());
};
- let response_body_text = if self.body_regex.is_some() || self.json_path_equals.is_some() {
+ let response_body_text = if self.requires_response_body() {
Some(response_body.try_text()?)
} else {
None
};
+ if let Some(needle) = self.body_contains.as_deref()
+ && !response_body_text
+ .as_deref()
+ .unwrap_or_default()
+ .contains(needle)
+ {
+ return Ok(false);
+ }
+
if let Some(regex) = self.body_regex.as_ref()
&& !regex.is_match(response_body_text.as_deref().unwrap_or_default())
{
@@ -1993,8 +2016,25 @@ impl SubresourceResponseWaitCriteria {
return Ok(false);
}
+ if let Some(expectation) = self.json_path_regex.as_ref()
+ && !json_path_matches_regex(
+ response_headers,
+ response_body_text.as_deref().unwrap_or_default(),
+ expectation,
+ )
+ {
+ return Ok(false);
+ }
+
Ok(true)
}
+
+ fn requires_response_body(&self) -> bool {
+ self.body_contains.is_some()
+ || self.body_regex.is_some()
+ || self.json_path_equals.is_some()
+ || self.json_path_regex.is_some()
+ }
}
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -2003,10 +2043,37 @@ pub struct SubresourceJsonPathEquals {
pub expected: String,
}
+#[derive(Debug, Clone)]
+pub struct SubresourceJsonPathRegex {
+ pub path: Vec<String>,
+ pub regex: Regex,
+}
+
fn json_path_equals(
headers: &[(String, String)],
body: &str,
expectation: &SubresourceJsonPathEquals,
+) -> bool {
+ json_path_satisfies(headers, body, &expectation.path, |value| {
+ json_value_equals_string(value, &expectation.expected)
+ })
+}
+
+fn json_path_matches_regex(
+ headers: &[(String, String)],
+ body: &str,
+ expectation: &SubresourceJsonPathRegex,
+) -> bool {
+ json_path_satisfies(headers, body, &expectation.path, |value| {
+ json_value_matches_regex(value, &expectation.regex)
+ })
+}
+
+fn json_path_satisfies(
+ headers: &[(String, String)],
+ body: &str,
+ path: &[String],
+ predicate: impl FnOnce(&Value) -> bool,
) -> bool {
let Some(content_type) = header_value(headers, "content-type") else {
return false;
@@ -2018,10 +2085,10 @@ fn json_path_equals(
let Ok(parsed) = serde_json::from_str::<Value>(body) else {
return false;
};
- let Some(value) = json_path_value(&parsed, &expectation.path) else {
+ let Some(value) = json_path_value(&parsed, path) else {
return false;
};
- json_value_equals_string(value, &expectation.expected)
+ predicate(value)
}
fn json_path_value<'a>(mut value: &'a Value, path: &[String]) -> Option<&'a Value> {
@@ -2045,6 +2112,16 @@ fn json_value_equals_string(value: &Value, expected: &str) -> bool {
}
}
+fn json_value_matches_regex(value: &Value, regex: &Regex) -> bool {
+ match value {
+ Value::String(actual) => regex.is_match(actual),
+ Value::Bool(actual) => regex.is_match(if *actual { "true" } else { "false" }),
+ Value::Number(actual) => regex.is_match(&actual.to_string()),
+ Value::Null => regex.is_match("null"),
+ Value::Array(_) | Value::Object(_) => false,
+ }
+}
+
fn header_value<'a>(headers: &'a [(String, String)], name: &str) -> Option<&'a str> {
headers
.iter()
@@ -4063,9 +4140,8 @@ mod tests {
Vec::new(),
);
let criteria = SubresourceResponseWaitCriteria {
- url_contains: None,
body_regex: Some(Regex::new("missing").unwrap()),
- json_path_equals: None,
+ ..SubresourceResponseWaitCriteria::default()
};
assert!(
criteria.try_matches(&record).is_err(),
@@ -4078,7 +4154,45 @@ mod tests {
}
#[test]
- fn body_wait_criteria_matches_response_body_as_regex() {
+ fn url_wait_criteria_matches_original_and_final_urls_as_regex() {
+ let record = SubresourceNetworkRecord::success(
+ None,
+ Url::parse("https://example.test/page").unwrap(),
+ Url::parse("https://api.example.test/v1/orders/42").unwrap(),
+ "GET".to_owned(),
+ Vec::new(),
+ None,
+ SubresourceResourceType::Fetch,
+ None,
+ Vec::new(),
+ Url::parse("https://api.example.test/v2/orders/42").unwrap(),
+ 200,
+ Vec::new(),
+ String::new(),
+ Vec::new(),
+ );
+
+ for regex in [r"/v1/orders/\d+$", r"/v2/orders/\d+$"] {
+ let criteria = SubresourceResponseWaitCriteria {
+ url_regex: Some(Regex::new(regex).unwrap()),
+ ..SubresourceResponseWaitCriteria::default()
+ };
+ assert!(criteria.try_matches(&record).is_ok_and(|matches| matches));
+ }
+
+ let non_matching = SubresourceResponseWaitCriteria {
+ url_regex: Some(Regex::new(r"/v3/orders/\d+$").unwrap()),
+ ..SubresourceResponseWaitCriteria::default()
+ };
+ assert!(
+ non_matching
+ .try_matches(&record)
+ .is_ok_and(|matches| !matches)
+ );
+ }
+
+ #[test]
+ fn body_wait_criteria_supports_literal_and_regex_matching() {
let record = SubresourceNetworkRecord::success_with_body(
None,
Url::parse("https://example.test/page").unwrap(),
@@ -4099,17 +4213,31 @@ mod tests {
Vec::new(),
);
+ let literal = SubresourceResponseWaitCriteria {
+ body_contains: Some("order #42 ready".to_owned()),
+ ..SubresourceResponseWaitCriteria::default()
+ };
+ assert!(literal.try_matches(&record).is_ok_and(|matches| matches));
+
+ let regex_syntax_is_literal = SubresourceResponseWaitCriteria {
+ body_contains: Some(r"order #\d+ ready".to_owned()),
+ ..SubresourceResponseWaitCriteria::default()
+ };
+ assert!(
+ regex_syntax_is_literal
+ .try_matches(&record)
+ .is_ok_and(|matches| !matches)
+ );
+
let criteria = SubresourceResponseWaitCriteria {
- url_contains: None,
body_regex: Some(Regex::new(r"order #\d+ ready").unwrap()),
- json_path_equals: None,
+ ..SubresourceResponseWaitCriteria::default()
};
assert!(criteria.try_matches(&record).is_ok_and(|matches| matches));
let non_matching = SubresourceResponseWaitCriteria {
- url_contains: None,
body_regex: Some(Regex::new(r"^order #\d{3} ready$").unwrap()),
- json_path_equals: None,
+ ..SubresourceResponseWaitCriteria::default()
};
assert!(
non_matching
@@ -4119,7 +4247,7 @@ mod tests {
}
#[test]
- fn json_path_wait_criteria_uses_shared_json_mime_parser() {
+ fn json_path_wait_criteria_supports_equals_and_regex_with_shared_mime_parser() {
let expectation = SubresourceJsonPathEquals {
path: vec!["ok".to_owned()],
expected: "true".to_owned(),
@@ -4145,6 +4273,24 @@ mod tests {
r#"{"ok":true}"#,
&expectation,
));
+
+ let regex_expectation = SubresourceJsonPathRegex {
+ path: vec!["data".to_owned(), "url".to_owned()],
+ regex: Regex::new(r"^/item/\d+$").unwrap(),
+ };
+ assert!(json_path_matches_regex(
+ &[(
+ "content-type".to_owned(),
+ "application/json; charset=utf-8".to_owned(),
+ )],
+ r#"{"data":{"url":"/item/42"}}"#,
+ &regex_expectation,
+ ));
+ assert!(!json_path_matches_regex(
+ &[("content-type".to_owned(), "application/json".to_owned())],
+ r#"{"data":{"url":"/orders/42"}}"#,
+ &regex_expectation,
+ ));
}
#[test]
diff --git a/moli-renderer-v8/src/types.rs b/moli-renderer-v8/src/types.rs
index bcdadf924..ff0aac1c8 100644
--- a/moli-renderer-v8/src/types.rs
+++ b/moli-renderer-v8/src/types.rs
@@ -55,12 +55,12 @@ pub use crate::protocol_types::{
ScriptRunOutcome, ScriptSkipReason, ScriptSourceKind, SubresourceAuthChallenge,
SubresourceAuthCredentials, SubresourceAuthScheme, SubresourceAuthTarget,
SubresourceBodyFinished, SubresourceBodyFinishedResult, SubresourceDataReceived,
- SubresourceEventSourceMessageReceived, SubresourceJsonPathEquals, SubresourceNetworkOutcome,
- SubresourceNetworkRecord, SubresourceNetworkRequestHandle, SubresourceRequestInitiatorType,
- SubresourceRequestStarted, SubresourceResourceType, SubresourceResponseBody,
- SubresourceResponseBodyWriter, SubresourceResponseStarted, SubresourceResponseWaitCriteria,
- WebSocketFrameDirection, WebSocketFrameOpcode, WebSocketLifecycleEvent, WebSocketLifecycleKind,
- WebSocketNetworkEvent,
+ SubresourceEventSourceMessageReceived, SubresourceJsonPathEquals, SubresourceJsonPathRegex,
+ SubresourceNetworkOutcome, SubresourceNetworkRecord, SubresourceNetworkRequestHandle,
+ SubresourceRequestInitiatorType, SubresourceRequestStarted, SubresourceResourceType,
+ SubresourceResponseBody, SubresourceResponseBodyWriter, SubresourceResponseStarted,
+ SubresourceResponseWaitCriteria, WebSocketFrameDirection, WebSocketFrameOpcode,
+ WebSocketLifecycleEvent, WebSocketLifecycleKind, WebSocketNetworkEvent,
};
pub(super) enum PendingSubresourceContinuation {
diff --git a/moli/src/cli.rs b/moli/src/cli.rs
index 83163bf9a..2409ee686 100644
--- a/moli/src/cli.rs
+++ b/moli/src/cli.rs
@@ -91,21 +91,60 @@ pub struct FetchArgs {
#[arg(long, default_value_t = 0)]
pub delay_ms: u64,
- #[arg(long)]
+ /// Wait for a response whose original or final URL contains this literal
+ /// substring.
+ #[arg(
+ long,
+ value_name = "SUBSTRING",
+ conflicts_with = "wait_response_url_regex"
+ )]
pub wait_response_url: Option<String>,
- /// Wait for a response whose body matches this regex. An invalid regex
- /// fails the fetch command immediately.
+ /// Wait for a response whose original or final URL matches this regex.
#[arg(
long,
value_name = "REGEX",
- value_parser = parse_response_body_regex
+ value_parser = parse_response_url_regex,
+ conflicts_with = "wait_response_url"
)]
- pub wait_response_body: Option<ResponseBodyRegexArg>,
+ pub wait_response_url_regex: Option<ResponseRegexArg>,
- #[arg(long, value_parser = parse_response_json_path_arg)]
+ /// Wait for a response whose body contains this literal substring.
+ #[arg(
+ long,
+ value_name = "SUBSTRING",
+ conflicts_with = "wait_response_body_regex"
+ )]
+ pub wait_response_body: Option<String>,
+
+ /// Wait for a response whose body matches this regex.
+ #[arg(
+ long,
+ value_name = "REGEX",
+ value_parser = parse_response_body_regex,
+ conflicts_with = "wait_response_body"
+ )]
+ pub wait_response_body_regex: Option<ResponseRegexArg>,
+
+ /// Wait for a response whose JSON field equals this literal value.
+ #[arg(
+ long,
+ value_name = "PATH=VALUE",
+ value_parser = parse_response_json_path_arg,
+ conflicts_with = "wait_response_json_regex"
+ )]
pub wait_response_json: Option<ResponseJsonPathArg>,
+ /// Wait for a response whose JSON scalar field's textual value matches
+ /// this regex.
+ #[arg(
+ long,
+ value_name = "PATH=REGEX",
+ value_parser = parse_response_json_path_regex_arg,
+ conflicts_with = "wait_response_json"
+ )]
+ pub wait_response_json_regex: Option<ResponseJsonPathRegexArg>,
+
/// Maximum total readiness time in milliseconds. Initial and HTTP-error
/// replacement navigations, the selected lifecycle stage, response match,
/// selector, and script waits share one absolute deadline. Network-idle and
@@ -152,8 +191,21 @@ pub struct ResponseJsonPathArg {
}
fn parse_response_json_path_arg(raw: &str) -> Result<ResponseJsonPathArg, String> {
+ let (path, expected) = split_response_json_path_arg(raw, "path=value")?;
+ Ok(ResponseJsonPathArg {
+ path,
+ expected: expected.to_owned(),
+ })
+}
+
+fn split_response_json_path_arg<'a>(
+ raw: &'a str,
+ expected_form: &str,
+) -> Result<(Vec<String>, &'a str), String> {
let Some(separator) = raw.find('=') else {
- return Err("response JSON wait must be in 'path=value' form".to_owned());
+ return Err(format!(
+ "response JSON wait must be in '{expected_form}' form"
+ ));
};
let path = raw[..separator].trim();
if path.is_empty() {
@@ -167,18 +219,39 @@ fn parse_response_json_path_arg(raw: &str) -> Result<ResponseJsonPathArg, String
if segments.iter().any(String::is_empty) {
return Err("response JSON wait path must not contain empty segments".to_owned());
}
- Ok(ResponseJsonPathArg {
- path: segments,
- expected: raw[separator + 1..].to_owned(),
+ Ok((segments, &raw[separator + 1..]))
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct ResponseJsonPathRegexArg {
+ pub path: Vec<String>,
+ regex: ResponseRegexArg,
+}
+
+impl ResponseJsonPathRegexArg {
+ pub(crate) fn regex(&self) -> &Regex {
+ self.regex.regex()
+ }
+
+ pub fn pattern(&self) -> &str {
+ self.regex.pattern()
+ }
+}
+
+fn parse_response_json_path_regex_arg(raw: &str) -> Result<ResponseJsonPathRegexArg, String> {
+ let (path, pattern) = split_response_json_path_arg(raw, "path=regex")?;
+ Ok(ResponseJsonPathRegexArg {
+ path,
+ regex: parse_response_regex(pattern, "--wait-response-json-regex")?,
})
}
#[derive(Debug, Clone)]
-pub struct ResponseBodyRegexArg {
+pub struct ResponseRegexArg {
regex: Regex,
}
-impl ResponseBodyRegexArg {
+impl ResponseRegexArg {
pub(crate) fn regex(&self) -> &Regex {
&self.regex
}
@@ -188,18 +261,26 @@ impl ResponseBodyRegexArg {
}
}
-impl PartialEq for ResponseBodyRegexArg {
+impl PartialEq for ResponseRegexArg {
fn eq(&self, other: &Self) -> bool {
self.regex.as_str() == other.regex.as_str()
}
}
-impl Eq for ResponseBodyRegexArg {}
+impl Eq for ResponseRegexArg {}
+
+fn parse_response_url_regex(raw: &str) -> Result<ResponseRegexArg, String> {
+ parse_response_regex(raw, "--wait-response-url-regex")
+}
+
+fn parse_response_body_regex(raw: &str) -> Result<ResponseRegexArg, String> {
+ parse_response_regex(raw, "--wait-response-body-regex")
+}
-fn parse_response_body_regex(raw: &str) -> Result<ResponseBodyRegexArg, String> {
+fn parse_response_regex(raw: &str, option: &str) -> Result<ResponseRegexArg, String> {
Regex::new(raw)
- .map(|regex| ResponseBodyRegexArg { regex })
- .map_err(|error| format!("invalid --wait-response-body regex: {error}"))
+ .map(|regex| ResponseRegexArg { regex })
+ .map_err(|error| format!("invalid {option} regex: {error}"))
}
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -601,12 +682,17 @@ mod tests {
}
#[test]
- fn fetch_help_labels_response_body_pattern_as_regex() {
+ fn fetch_help_labels_literal_and_regex_response_waits() {
let help = Cli::try_parse_from(["moli", "fetch", "--help"])
.unwrap_err()
.to_string();
- assert!(help.contains("--wait-response-body <REGEX>"));
+ assert!(help.contains("--wait-response-url <SUBSTRING>"));
+ assert!(help.contains("--wait-response-url-regex <REGEX>"));
+ assert!(help.contains("--wait-response-body <SUBSTRING>"));
+ assert!(help.contains("--wait-response-body-regex <REGEX>"));
+ assert!(help.contains("--wait-response-json <PATH=VALUE>"));
+ assert!(help.contains("--wait-response-json-regex <PATH=REGEX>"));
}
#[test]
diff --git a/moli/src/config.rs b/moli/src/config.rs
index e95dd7628..3d3016822 100644
--- a/moli/src/config.rs
+++ b/moli/src/config.rs
@@ -3,7 +3,7 @@ use cidr::AnyIpCidr;
use moli_browser_profile::BrowserProfilePaths;
use moli_core::{
LayoutPolicy, OptionalResourceFetchMask,
- page::{SubresourceJsonPathEquals, SubresourceResponseWaitCriteria},
+ page::{SubresourceJsonPathEquals, SubresourceJsonPathRegex, SubresourceResponseWaitCriteria},
runtime::BrowserConfig,
};
use moli_fetch::{FetchConfig, WebBotAuthProfile, WebBotAuthSigner};
@@ -299,8 +299,13 @@ pub fn response_wait_criteria_from_args(
) -> SubresourceResponseWaitCriteria {
SubresourceResponseWaitCriteria {
url_contains: args.wait_response_url.clone(),
+ url_regex: args
+ .wait_response_url_regex
+ .as_ref()
+ .map(|arg| arg.regex().clone()),
+ body_contains: args.wait_response_body.clone(),
body_regex: args
- .wait_response_body
+ .wait_response_body_regex
.as_ref()
.map(|arg| arg.regex().clone()),
json_path_equals: args
@@ -310,5 +315,11 @@ pub fn response_wait_criteria_from_args(
path: json.path.clone(),
expected: json.expected.clone(),
}),
+ json_path_regex: args.wait_response_json_regex.as_ref().map(|json| {
+ SubresourceJsonPathRegex {
+ path: json.path.clone(),
+ regex: json.regex().clone(),
+ }
+ }),
}
}
diff --git a/moli/tests/cli.rs b/moli/tests/cli.rs
index 941a14dfd..40523ba4e 100644
--- a/moli/tests/cli.rs
+++ b/moli/tests/cli.rs
@@ -9,7 +9,7 @@ use std::{
use moli::cli::{
Cli, Commands, CommonArgs, DumpFormat, FetchArgs, FetchWaitUntil, LogFormat, LogLevel,
- RequestHeaderArg, ResponseBodyRegexArg, ResponseJsonPathArg, ServeArgs, StripModeChoice,
+ RequestHeaderArg, ResponseJsonPathArg, ResponseRegexArg, ServeArgs, StripModeChoice,
StripOptions, WebBotAuthProfileChoice, normalize_args_for_compat,
};
use moli::config::AppConfig;
@@ -99,8 +99,11 @@ fn parses_explicit_fetch_command_with_compatibility_flags() {
wait_script_file: None,
delay_ms: 0,
wait_response_url: None,
+ wait_response_url_regex: None,
wait_response_body: None,
+ wait_response_body_regex: None,
wait_response_json: None,
+ wait_response_json_regex: None,
timeout: 25_000,
common: CommonArgs {
insecure_disable_tls_host_verification: false,
@@ -393,8 +396,11 @@ fn infers_fetch_mode_from_bare_url() {
wait_script_file: None,
delay_ms: 0,
wait_response_url: None,
+ wait_response_url_regex: None,
wait_response_body: None,
+ wait_response_body_regex: None,
wait_response_json: None,
+ wait_response_json_regex: None,
timeout: 25_000,
common: CommonArgs::default(),
url: "https://example.com".to_owned(),
@@ -430,8 +436,11 @@ fn parses_bare_dump_with_explicit_fetch_command_and_defaults_to_html() {
wait_script_file: None,
delay_ms: 0,
wait_response_url: None,
+ wait_response_url_regex: None,
wait_response_body: None,
+ wait_response_body_regex: None,
wait_response_json: None,
+ wait_response_json_regex: None,
timeout: 25_000,
common: CommonArgs::default(),
url: "https://example.com".to_owned(),
@@ -471,8 +480,11 @@ fn parses_header_flag_with_explicit_fetch_command() {
wait_script_file: None,
delay_ms: 0,
wait_response_url: None,
+ wait_response_url_regex: None,
wait_response_body: None,
+ wait_response_body_regex: None,
wait_response_json: None,
+ wait_response_json_regex: None,
timeout: 25_000,
common: CommonArgs::default(),
url: "https://example.com".to_owned(),
@@ -847,7 +859,7 @@ fn parses_dcl_fetch_wait_until_alias() {
}
#[test]
-fn parses_fetch_response_wait_flags() {
+fn parses_fetch_literal_response_wait_flags() {
let cli = Cli::try_parse_from(normalize_args_for_compat([
"moli",
"fetch",
@@ -869,12 +881,7 @@ fn parses_fetch_response_wait_flags() {
args.wait_response_url.as_deref(),
Some("mtop.taobao.idle.pc.detail")
);
- assert_eq!(
- args.wait_response_body
- .as_ref()
- .map(ResponseBodyRegexArg::pattern),
- Some("SUCCESS")
- );
+ assert_eq!(args.wait_response_body.as_deref(), Some("SUCCESS"));
assert_eq!(
args.wait_response_json,
Some(ResponseJsonPathArg {
@@ -882,25 +889,125 @@ fn parses_fetch_response_wait_flags() {
expected: "/item/42".to_owned(),
})
);
+ assert!(args.wait_response_url_regex.is_none());
+ assert!(args.wait_response_body_regex.is_none());
+ assert!(args.wait_response_json_regex.is_none());
}
#[test]
-fn rejects_invalid_wait_response_body_regex() {
- let error = Cli::try_parse_from(normalize_args_for_compat([
+fn parses_fetch_regex_response_wait_flags() {
+ let cli = Cli::try_parse_from(normalize_args_for_compat([
"moli",
"fetch",
- "--wait-response-body",
- "[",
+ "--wait-response-url-regex",
+ r"mtop\.taobao\..*\.detail",
+ "--wait-response-body-regex",
+ "SUCC[A-Z]+",
+ "--wait-response-json-regex",
+ r"data.url=^/item/\d+$",
"https://example.com",
]))
- .unwrap_err();
+ .unwrap();
- assert_eq!(error.kind(), clap::error::ErrorKind::ValueValidation);
- assert!(
- error
- .to_string()
- .contains("invalid --wait-response-body regex")
+ let Commands::Fetch(args) = cli.command else {
+ panic!("expected fetch command");
+ };
+
+ assert_eq!(
+ args.wait_response_url_regex
+ .as_ref()
+ .map(ResponseRegexArg::pattern),
+ Some(r"mtop\.taobao\..*\.detail")
+ );
+ assert_eq!(
+ args.wait_response_body_regex
+ .as_ref()
+ .map(ResponseRegexArg::pattern),
+ Some("SUCC[A-Z]+")
);
+ let json = args
+ .wait_response_json_regex
+ .as_ref()
+ .expect("JSON regex wait argument");
+ assert_eq!(json.path, ["data".to_owned(), "url".to_owned()]);
+ assert_eq!(json.pattern(), r"^/item/\d+$");
+ assert!(args.wait_response_url.is_none());
+ assert!(args.wait_response_body.is_none());
+ assert!(args.wait_response_json.is_none());
+}
+
+#[test]
+fn rejects_invalid_response_wait_regexes() {
+ let cases = [
+ (
+ "--wait-response-url-regex",
+ "[",
+ "invalid --wait-response-url-regex regex",
+ ),
+ (
+ "--wait-response-body-regex",
+ "[",
+ "invalid --wait-response-body-regex regex",
+ ),
+ (
+ "--wait-response-json-regex",
+ "data.url=[",
+ "invalid --wait-response-json-regex regex",
+ ),
+ ];
+
+ for (flag, value, expected) in cases {
+ let error = Cli::try_parse_from(normalize_args_for_compat([
+ "moli",
+ "fetch",
+ flag,
+ value,
+ "https://example.com",
+ ]))
+ .unwrap_err();
+
+ assert_eq!(error.kind(), clap::error::ErrorKind::ValueValidation);
+ assert!(error.to_string().contains(expected), "{error}");
+ }
+}
+
+#[test]
+fn literal_and_regex_response_wait_flags_conflict_per_dimension() {
+ let cases = [
+ (
+ "--wait-response-url",
+ "/api/items",
+ "--wait-response-url-regex",
+ "/api/.*",
+ ),
+ (
+ "--wait-response-body",
+ "ready",
+ "--wait-response-body-regex",
+ "ready|done",
+ ),
+ (
+ "--wait-response-json",
+ "data.state=ready",
+ "--wait-response-json-regex",
+ "data.state=ready|done",
+ ),
+ ];
+
+ for (literal_flag, literal, regex_flag, regex) in cases {
+ let error = Cli::try_parse_from(normalize_args_for_compat([
+ "moli",
+ "fetch",
+ literal_flag,
+ literal,
+ regex_flag,
+ regex,
+ "https://example.com",
+ ]))
+ .unwrap_err();
+
+ assert_eq!(error.kind(), clap::error::ErrorKind::ArgumentConflict);
+ }
}
#[test]
diff --git a/moli/tests/fetch_cli.rs b/moli/tests/fetch_cli.rs
index 4f7a07430..adec9a378 100644
--- a/moli/tests/fetch_cli.rs
+++ b/moli/tests/fetch_cli.rs
@@ -1641,7 +1641,7 @@ fn cli_dump_json_trace_network_includes_subresource_summary() -> Result<()> {
}
#[test]
-fn cli_wait_response_matches_url_body_and_json_without_networkidle() -> Result<()> {
+fn cli_wait_response_regexes_match_url_body_and_json_without_networkidle() -> Result<()> {
let runtime = tokio::runtime::Runtime::new()?;
let server = runtime.block_on(FixtureServer::spawn())?;
let url = server.url("/wait-until-delayed-json-fetch");
@@ -1654,12 +1654,12 @@ fn cli_wait_response_matches_url_body_and_json_without_networkidle() -> Result<(
"*",
"--wait-until",
"load",
- "--wait-response-url",
- "/wait-until-json-data",
- "--wait-response-body",
+ "--wait-response-url-regex",
+ r"/wait-until-(json|xml)-data$",
+ "--wait-response-body-regex",
"SUCC[A-Z]+",
- "--wait-response-json",
- "data.url=/item/42",
+ "--wait-response-json-regex",
+ r"data.url=^/item/\d+$",
"--dump",
"json",
"--trace-network",
@@ -1729,7 +1729,7 @@ fn cli_readiness_plan_combines_early_response_selector_and_script() -> Result<()
"--wait-response-url",
"/wait-until-json-data",
"--wait-response-body",
- "SUCCESS",
+ r#""ret":["SUCCESS"]"#,
"--wait-response-json",
"data.url=/item/42",
"--wait-selector",
diff --git a/skills/moli-webfetch/references/fetch-recipes.md b/skills/moli-webfetch/references/fetch-recipes.md
index 32340878e..6bb83f085 100644
--- a/skills/moli-webfetch/references/fetch-recipes.md
+++ b/skills/moli-webfetch/references/fetch-recipes.md
@@ -45,10 +45,14 @@ a better completion signal:
truthy.
- `--wait-script-file <path>`: use a reusable or multiline condition. It is
mutually exclusive with `--wait-script`.
-- `--wait-response-url <substring>`: wait for an application request by URL.
-- `--wait-response-body <regex>`: require text matching the regex in that response.
-- `--wait-response-json <path=value>`: require a JSON field value. All supplied
- response criteria must match one response.
+- `--wait-response-url <substring>`: wait for an application request whose URL
+ contains literal text; use `--wait-response-url-regex <regex>` for a pattern.
+- `--wait-response-body <substring>`: require literal text in that response;
+ use `--wait-response-body-regex <regex>` for a pattern.
+- `--wait-response-json <path=value>`: require an exact JSON field value; use
+ `--wait-response-json-regex <path=regex>` for a patterned scalar value. All
+ supplied response criteria must match one response. Literal and regex forms
+ of the same criterion are mutually exclusive.
- `--delay-ms <ms>`: use only when the site has no observable readiness signal.
- `--timeout <ms>`: bound navigation and explicit waits; the default is 10000.
@@ -63,8 +67,8 @@ moli fetch \
moli fetch \
--dump json \
--trace-network \
- --wait-response-url "/api/search" \
- --wait-response-json "data.ready=true" \
+ --wait-response-url-regex "/api/(search|results)$" \
+ --wait-response-json-regex "data.requestId=^req-[0-9]+$" \
"https://example.com/search"
```