Skip to content

Craft Anything: understand how any software works, and craft your own.

Rust

Copy only the scripts a web script export can write (#587)

Ole Bohmbach521947899df4
diff --git a/crates/analysis/src/web_scripts.rs b/crates/analysis/src/web_scripts.rs
index 891372c3..47b17a61 100644
--- a/crates/analysis/src/web_scripts.rs
+++ b/crates/analysis/src/web_scripts.rs
@@ -15,13 +15,60 @@ pub struct CapturedScript {
pub text: String,
}
+/// Most scripts, and most bytes of script text, an extraction keeps. Scripts past it are listed
+/// by URL only, so a large capture isn't copied in full when only part of it will be used.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct ScriptBudget {
+ pub max_scripts: usize,
+ pub max_bytes: u64,
+}
+
+impl ScriptBudget {
+ pub const UNLIMITED: ScriptBudget = ScriptBudget { max_scripts: usize::MAX, max_bytes: u64::MAX };
+}
+
+/// Scripts kept within a [`ScriptBudget`], and the URLs of those left out because of it.
+#[derive(Debug, Clone, Default, PartialEq, Eq)]
+pub struct ExtractedScripts {
+ pub scripts: Vec<CapturedScript>,
+ pub over_budget: Vec<String>,
+ pub bytes: u64,
+}
+
+impl ExtractedScripts {
+ /// Every script seen, kept or not.
+ pub fn seen(&self) -> usize {
+ self.scripts.len().saturating_add(self.over_budget.len())
+ }
+
+ /// Whether another script can be kept at all.
+ fn has_room(&self, budget: ScriptBudget) -> bool {
+ self.scripts.len() < budget.max_scripts
+ }
+
+ /// Whether a script of `len` bytes fits in what's left.
+ fn fits(&self, budget: ScriptBudget, len: usize) -> bool {
+ self.has_room(budget) && self.bytes.saturating_add(len as u64) <= budget.max_bytes
+ }
+
+ fn keep(&mut self, url: String, text: String) {
+ self.bytes = self.bytes.saturating_add(text.len() as u64);
+ self.scripts.push(CapturedScript { url, text });
+ }
+}
+
/// Scripts listed in a capture result: any object with a `url` and inline source
/// (`source`, `text`, `content` or `script_source`).
pub fn scripts_from_capture(v: &Value) -> Vec<CapturedScript> {
- let mut out = Vec::new();
+ scripts_from_capture_within(v, ScriptBudget::UNLIMITED).scripts
+}
+
+/// [`scripts_from_capture`], copying only the scripts that fit `budget`.
+pub fn scripts_from_capture_within(v: &Value, budget: ScriptBudget) -> ExtractedScripts {
+ let mut out = ExtractedScripts::default();
let mut stack = vec![(v, 0usize)];
while let Some((x, depth)) = stack.pop() {
- if depth > 10 || out.len() >= 20_000 {
+ if depth > 10 || out.seen() >= 20_000 {
break;
}
match x {
@@ -29,7 +76,11 @@ pub fn scripts_from_capture(v: &Value) -> Vec<CapturedScript> {
let text = ["source", "text", "content", "script_source"].iter().find_map(|k| m.get(*k).and_then(Value::as_str));
if let Some(text) = text {
let url = m.get("url").and_then(Value::as_str).unwrap_or("").to_string();
- out.push(CapturedScript { url, text: text.to_string() });
+ if out.fits(budget, text.len()) {
+ out.keep(url, text.to_string());
+ } else {
+ out.over_budget.push(url);
+ }
continue;
}
for y in m.values() {
@@ -49,8 +100,13 @@ pub fn scripts_from_capture(v: &Value) -> Vec<CapturedScript> {
/// JavaScript responses recorded in a HAR, when their bodies were saved.
pub fn scripts_from_har(bytes: &[u8], max_entries: usize) -> Result<Vec<CapturedScript>, String> {
+ Ok(scripts_from_har_within(bytes, max_entries, ScriptBudget::UNLIMITED)?.scripts)
+}
+
+/// [`scripts_from_har`], decoding and keeping only the scripts that fit `budget`.
+pub fn scripts_from_har_within(bytes: &[u8], max_entries: usize, budget: ScriptBudget) -> Result<ExtractedScripts, String> {
let h = har::parse(bytes, max_entries).map_err(|e| e.to_string())?;
- let mut out = Vec::new();
+ let mut out = ExtractedScripts::default();
for e in h.entries {
let mime = e.response.mime.as_deref().unwrap_or("").to_ascii_lowercase();
let path = e.request.url.split(['?', '#']).next().unwrap_or("").to_ascii_lowercase();
@@ -59,13 +115,25 @@ pub fn scripts_from_har(bytes: &[u8], max_entries: usize) -> Result<Vec<Captured
continue;
}
let Some(text) = e.response.text else { continue };
+ if text.is_empty() {
+ continue;
+ }
+ if !out.has_room(budget) {
+ out.over_budget.push(e.request.url);
+ continue;
+ }
let text = if e.response.encoding.as_deref() == Some("base64") {
base64_decode(&text).map(|b| String::from_utf8_lossy(&b).into_owned()).unwrap_or_default()
} else {
text
};
- if !text.is_empty() {
- out.push(CapturedScript { url: e.request.url, text });
+ if text.is_empty() {
+ continue;
+ }
+ if out.fits(budget, text.len()) {
+ out.keep(e.request.url, text);
+ } else {
+ out.over_budget.push(e.request.url);
}
}
Ok(out)
@@ -210,6 +278,29 @@ mod tests {
assert_eq!(s, vec![CapturedScript { url: "https://x.test/a.js".into(), text: "a()".into() }]);
}
+ #[test]
+ fn extraction_keeps_only_what_fits_the_budget() {
+ let cap = json!({"scripts": [
+ {"url": "https://ex.test/a.js", "source": "aaaa"},
+ {"url": "https://ex.test/big.js", "source": "bbbbbbbbbb"},
+ {"url": "https://ex.test/c.js", "source": "cc"},
+ {"url": "https://ex.test/d.js", "source": "d"},
+ ]});
+ let e = scripts_from_capture_within(&cap, ScriptBudget { max_scripts: 10, max_bytes: 6 });
+ let kept: Vec<&str> = e.scripts.iter().map(|s| s.url.as_str()).collect();
+ assert_eq!(kept, ["https://ex.test/a.js", "https://ex.test/c.js"]);
+ assert_eq!(e.over_budget, ["https://ex.test/big.js", "https://ex.test/d.js"]);
+ assert_eq!((e.bytes, e.seen()), (6, 4));
+ let e = scripts_from_capture_within(&cap, ScriptBudget { max_scripts: 1, max_bytes: u64::MAX });
+ assert_eq!((e.scripts.len(), e.over_budget.len()), (1, 3));
+
+ let har = br#"{"log":{"entries":[{"request":{"method":"GET","url":"https://x.test/a.js"},"response":{"status":200,"content":{"mimeType":"text/javascript","text":"YSgp","encoding":"base64"}}},
+ {"request":{"method":"GET","url":"https://x.test/b.js"},"response":{"status":200,"content":{"mimeType":"text/javascript","text":"b()"}}}]}}"#;
+ let e = scripts_from_har_within(har, 100, ScriptBudget { max_scripts: 1, max_bytes: u64::MAX }).unwrap();
+ assert_eq!(e.scripts, vec![CapturedScript { url: "https://x.test/a.js".into(), text: "a()".into() }]);
+ assert_eq!(e.over_budget, ["https://x.test/b.js"]);
+ }
+
#[test]
fn traces_with_context() {
let m = parse_map(
diff --git a/crates/engine/src/tools/web_tools.rs b/crates/engine/src/tools/web_tools.rs
index 2263bb53..c0770505 100644
--- a/crates/engine/src/tools/web_tools.rs
+++ b/crates/engine/src/tools/web_tools.rs
@@ -5,7 +5,9 @@
use super::artifact_tools::{WalkOptions, abs_path, create_absent_dir, env, read_capped, rel_to, resolve_evidence_input, walk_dir, write_new_file};
use crate::tool::{Ctx, Effects, Requires, ToolOutput, ToolSpec, Toolset, parse_params, schema_of};
use craft_anything_analysis::web_har::{HarOptions, inspect_har};
-use craft_anything_analysis::web_scripts::{CapturedScript, parse_map, plan_layout, scripts_from_capture, scripts_from_har, trace_location};
+use craft_anything_analysis::web_scripts::{
+ ExtractedScripts, ScriptBudget, parse_map, plan_layout, scripts_from_capture_within, scripts_from_har_within, trace_location,
+};
use craft_anything_evidence::{
Authority, Confidence, Coverage, CoverageStatus, ErrorCode, EvidenceBuilder, Limitation, Location, Subject, ToolError, sha256_hex,
};
@@ -96,29 +98,40 @@ fn default_max_bytes() -> u64 {
fn web_scripts_save(ctx: &mut Ctx<'_>, params: Value) -> Result<ToolOutput, ToolError> {
let p: ExportParams = parse_params(params)?;
let mut links = Vec::new();
- let (scripts, source_name): (Vec<CapturedScript>, String) = match (&p.capture, &p.capture_path) {
+ // Only the scripts that fit the export's limits are copied out of the capture and planned;
+ // the rest are listed as skipped by URL.
+ let budget = ScriptBudget { max_scripts: p.max_scripts, max_bytes: p.max_bytes };
+ let (extracted, source_name): (ExtractedScripts, String) = match (&p.capture, &p.capture_path) {
(Some(c), None) => {
let ev = resolve_evidence_input(ctx, c, &[])?;
links.push(ev.id.clone());
- (scripts_from_capture(&ev.result), ev.subject.name.clone().unwrap_or_else(|| ev.id.clone()))
+ (scripts_from_capture_within(&ev.result, budget), ev.subject.name.clone().unwrap_or_else(|| ev.id.clone()))
}
(None, Some(path)) => {
let path = abs_path(path, "capture_path")?;
let bytes = read_capped(&path, 512 * 1024 * 1024)?;
let v: Value = serde_json::from_slice(&bytes).map_err(|e| ToolError::invalid(format!("{} is not JSON: {e}", path.display())))?;
- let s = if v.pointer("/log/entries").is_some() { scripts_from_har(&bytes, 200_000).map_err(ToolError::invalid)? } else { scripts_from_capture(&v) };
+ let s = if v.pointer("/log/entries").is_some() {
+ // The HAR reader parses the bytes itself; don't hold this copy meanwhile.
+ drop(v);
+ scripts_from_har_within(&bytes, 200_000, budget).map_err(ToolError::invalid)?
+ } else {
+ scripts_from_capture_within(&v, budget)
+ };
(s, path.display().to_string())
}
_ => return Err(ToolError::invalid("pass exactly one of capture or capture_path")),
};
- if scripts.is_empty() {
+ if extracted.seen() == 0 {
return Err(ToolError::invalid("the capture holds no script sources")
.with_remediation("Captures need script text (url + source); HAR files need saved response bodies."));
}
+ let seen = extracted.seen();
+ let ExtractedScripts { scripts, over_budget, .. } = extracted;
let out = create_absent_dir(&p.output_directory)?;
let plan = plan_layout(&scripts);
let mut written = Vec::new();
- let mut skipped = Vec::new();
+ let mut skipped: Vec<Value> = over_budget.into_iter().map(|url| json!({"url": url, "reason": "count or size limit reached"})).collect();
let mut total = 0u64;
for (i, (s, f)) in scripts.iter().zip(plan.iter()).enumerate() {
if i % 64 == 0 {
@@ -147,7 +160,7 @@ fn web_scripts_save(ctx: &mut Ctx<'_>, params: Value) -> Result<ToolOutput, Tool
.result(json!({"output_directory": out, "manifest": out.join("manifest.json"), "files_folder": files_dir, "scripts": written, "skipped": skipped, "bytes": total}))
.summary(summary)
.confidence(Confidence::Derived)
- .coverage(Coverage { status: if skipped.is_empty() { CoverageStatus::Complete } else { CoverageStatus::Partial }, examined: Some(written.len() as u64), total: Some(scripts.len() as u64), next_offset: None })
+ .coverage(Coverage { status: if skipped.is_empty() { CoverageStatus::Complete } else { CoverageStatus::Partial }, examined: Some(written.len() as u64), total: Some(seen as u64), next_offset: None })
.location(Location::new("path", out.display().to_string()));
for l in links {
b = b.link(l);
@@ -663,4 +676,24 @@ mod tests {
let a = call(&e, "js_app_map", json!({"input_path": input})).unwrap();
assert!(a["result"]["endpoints"].as_array().unwrap().iter().any(|ep| ep["url"] == "/api/notes"));
}
+
+ #[test]
+ fn script_export_lists_what_the_limits_left_out() {
+ let dir = tempfile::tempdir().unwrap();
+ let cap = json!({"scripts": [
+ {"url": "https://app.test/a.js", "source": "a();"},
+ {"url": "https://app.test/b.js", "source": "b();"},
+ {"url": "https://app.test/c.js", "source": "c();"},
+ ]});
+ let cp = dir.path().join("capture.json");
+ std::fs::write(&cp, serde_json::to_vec(&cap).unwrap()).unwrap();
+ let e = Engine::new(crate::testing::session());
+ let out = dir.path().join("export");
+ let x = call(&e, "web_scripts_save", json!({"capture_path": cp, "output_directory": out, "max_scripts": 1})).unwrap();
+ assert_eq!(x["result"]["scripts"].as_array().unwrap().len(), 1);
+ let skipped: Vec<&str> = x["result"]["skipped"].as_array().unwrap().iter().map(|s| s["url"].as_str().unwrap()).collect();
+ assert_eq!(skipped, ["https://app.test/b.js", "https://app.test/c.js"]);
+ assert_eq!(x["coverage"]["total"], 3);
+ assert!(out.join("files/app.test/a.js").exists() && !out.join("files/app.test/b.js").exists());
+ }
}