The design language that makes your AI harness better at design.
JavaScript
Fix: broken-image reads multi-line tags, Svelte bind:src and backslashes in attributes
Paul Bakaus88e7152c7735
diff --git a/crates/detect/src/detect_text.rs b/crates/detect/src/detect_text.rsindex 161c7bb91..52f850f57 100644--- a/crates/detect/src/detect_text.rs+++ b/crates/detect/src/detect_text.rs@@ -1892,8 +1892,10 @@ pub fn run_regex_matchers() -> Vec<Finding> {let mut findings = Vec::new();let ext = ext_from_file_path(file_path);- // Only the image rule consumes this view: other rules intentionally- // inspect strings (copy, CSS-in-JS, design tokens).+ // The image rule reads tags that may span lines, so it walks one joined+ // text from each line's start, with JS/TS literals masked. Only it uses+ // this view: other rules intentionally inspect strings (copy, CSS-in-JS,+ // design tokens).let image_source = once_cell::unsync::OnceCell::new();// The joined text the side-tab scope reader walks, built once per file,// and the stylesheet index over it, built on the first accent it gates.@@ -1903,18 +1905,33 @@ pub fn run_regex_matchers(for matcher in REGEX_MATCHERS.iter() {let run = || {let mut matches = Vec::new();- let image_lines;- let match_lines = if matcher.id == "broken-image" && JS_SOURCE_EXTS.contains(&ext.as_str()) {- let masked = image_source.get_or_init(|| mask_js_literals(- &lines.join("\n"), matches!(ext.as_str(), ".js" | ".jsx" | ".tsx"),- ));- image_lines = masked.split('\n').collect::<Vec<_>>();- &image_lines- } else {- lines- };- for (i, line) in match_lines.iter().enumerate() {- let ctxs: Vec<MatchCtx> = (matcher.find_all)(line);+ let image = matcher.id == "broken-image";+ if image && !lines.iter().any(|l| l.as_bytes().windows(4).any(|w| w.eq_ignore_ascii_case(b"<img"))) {+ return matches;+ }+ for (i, line) in lines.iter().enumerate() {+ let (line, ctxs): (&str, Vec<MatchCtx>) = if image {+ let (text, starts) = image_source.get_or_init(|| {+ let joined = lines.join("\n");+ let mut starts = Vec::with_capacity(lines.len());+ let mut at = 0;+ for l in lines {+ starts.push(at);+ at += l.len() + 1;+ }+ // Masking keeps every byte offset and newline.+ let text = if JS_SOURCE_EXTS.contains(&ext.as_str()) {+ mask_js_literals(&joined, matches!(ext.as_str(), ".js" | ".jsx" | ".tsx"))+ } else {+ joined+ };+ (text, starts)+ });+ let rest = &text[starts[i]..];+ (&rest[..line.len()], crate::regex_matchers::find_broken_images(rest))+ } else {+ (line, (matcher.find_all)(line))+ };if ctxs.is_empty() {continue;}diff --git a/crates/detect/src/regex_matchers.rs b/crates/detect/src/regex_matchers.rsindex 4777c3d6b..68a585890 100644--- a/crates/detect/src/regex_matchers.rs+++ b/crates/detect/src/regex_matchers.rs@@ -1760,7 +1760,6 @@ pub(crate) fn image_source_is_missing(tag: &str, ext: &str) -> bool {let vue = ext == ".vue";let b = tag.as_bytes();let mut p = 4; // <img- let mut missing = true;while p < b.len() {while p < b.len() && (b[p].is_ascii_whitespace() || b[p] == b'/') { p += 1; }if p >= b.len() || b[p] == b'>' { break; }@@ -1781,11 +1780,17 @@ pub(crate) fn image_source_is_missing(tag: &str, ext: &str) -> bool {while p < b.len() && !b[p].is_ascii_whitespace() && !matches!(b[p], b'=' | b'>' | b'/') { p += 1; }let name = &tag[start..p];while p < b.len() && b[p].is_ascii_whitespace() { p += 1; }- if vue && (name == ":src" || name == "v-bind:src" || name == "v-bind"- || name.starts_with(":src.") || name.starts_with("v-bind:src.")) {+ let source = names_image_source(name);+ let directive = name.contains(':');+ if vue && ((source && directive) || name == "v-bind") {return false;}- if p >= b.len() || b[p] != b'=' { continue; }+ if p >= b.len() || b[p] != b'=' {+ // Svelte `bind:src` alone is shorthand for `bind:src={src}`;+ // a bare `src` is still empty.+ if source && directive { return false; }+ continue;+ }p += 1;while p < b.len() && b[p].is_ascii_whitespace() { p += 1; }let value_start = p;@@ -1804,40 +1809,131 @@ pub(crate) fn image_source_is_missing(tag: &str, ext: &str) -> bool {while p < b.len() && !b[p].is_ascii_whitespace() && b[p] != b'>' { p += 1; }Some(&tag[value_start..p])};- // Preserve existing support for bound sources even outside Vue.- if name.eq_ignore_ascii_case("src") || name == ":src" || name == "v-bind:src" {- missing = value.is_some_and(|v| v.trim().is_empty() || v.trim() == "#");+ // Any source with a value, or bound to an expression, is present.+ let empty = value.is_some_and(|v| v.trim().is_empty() || v.trim() == "#");+ if source && !empty {+ return false;+ }+ }+ true+}++/// `src`, a binding of it (`:src`, `v-bind:src`, Svelte `bind:src`, Vue+/// modifiers), or an alias such as lazy loading's `data-src`, all of which+/// the original `\bsrc\s*=` matcher accepted.+fn names_image_source(name: &str) -> bool {+ let base = name.split('.').next().unwrap_or(name);+ base.eq_ignore_ascii_case("src")+ || base+ .rsplit_once(|c| c == ':' || c == '-')+ .is_some_and(|(_, last)| last.eq_ignore_ascii_case("src"))+}++/// How far a tag may run past its `<img`, so an unclosed one costs little.+const MAX_IMG_TAG_BYTES: usize = 8 * 1024;++enum TagScan {+ /// The tag's closing `>`.+ End(usize),+ /// The probe sits in a quoted attribute value or an expression's string.+ Hidden,+ /// The probe sits in an expression as code (nested JSX).+ Visible,+ NotATag,+}++/// Walk the markup tag opened at `start`. Attribute quotes close at the next+/// matching quote with no escapes (HTML, Svelte, Vue and JSX strings alike),+/// `{...}` expressions follow JS rules, and a top-level `<` means the text+/// was never a tag.+fn scan_markup_tag(b: &[u8], start: usize, probe: Option<usize>) -> TagScan {+ let inside = |open: usize, close: usize| probe.filter(|x| *x > open && *x < close);+ let mut p = start + 1;+ while p < b.len() {+ match b[p] {+ b'>' => return TagScan::End(p),+ b'<' => return TagScan::NotATag,+ quote @ (b'"' | b'\'') => {+ let Some(close) = b[p + 1..].iter().position(|c| *c == quote) else {+ return TagScan::NotATag;+ };+ let close = p + 1 + close;+ if inside(p, close).is_some() {+ return TagScan::Hidden;+ }+ p = close + 1;+ }+ b'{' => {+ let Some(close) = matching_close(b, p) else { return TagScan::NotATag; };+ if let Some(x) = inside(p, close) {+ return if in_js_string(&b[p..x]) { TagScan::Hidden } else { TagScan::Visible };+ }+ p = close + 1;+ }+ _ => p += 1,+ }+ }+ TagScan::NotATag+}++fn in_js_string(b: &[u8]) -> bool {+ let mut quote = None;+ let mut p = 0;+ while p < b.len() {+ match (quote, b[p]) {+ (Some(_), b'\\') => p += 1,+ (Some(q), c) if c == q => quote = None,+ (None, c @ (b'"' | b'\'' | b'`')) => quote = Some(c),+ _ => {}+ }+ p += 1;+ }+ quote.is_some()+}++/// A candidate inside an earlier tag's quoted attribute on its line is text;+/// one in a JSX attribute expression is a real nested element.+fn hidden_in_parent_tag(line: &[u8], at: usize) -> bool {+ let mut i = 0;+ while i < at {+ if line[i] == b'<' && line.get(i + 1).is_some_and(|c| c.is_ascii_alphabetic()) {+ match scan_markup_tag(line, i, Some(at)) {+ TagScan::Hidden => return true,+ TagScan::Visible => return false,+ TagScan::End(end) => {+ i = end + 1;+ continue;+ }+ TagScan::NotATag => {}+ }}+ i += 1;}- missing+ false}-fn find_broken_images(line: &str) -> Vec<MatchCtx> {+/// `text` runs from the start of a line to the end of the file: candidates+/// start on that line, and a tag may continue on the lines after it.+pub(crate) fn find_broken_images(text: &str) -> Vec<MatchCtx> {+ let line = &text[..text.find('\n').unwrap_or(text.len())];+ let b = text.as_bytes();let mut out = Vec::new();let mut pos = 0;while let Some(m) = IMG_OPEN_RE.find_at(line, pos) {pos = m.end();- // A candidate inside a quoted attribute is text; a candidate in a- // JSX attribute expression is a real nested element.- if let Some((parent, _)) = markup_tag_span(line, m.start()) {- let mut visible = false;- scan_js(line, parent + 1, |ch, offset, _, _, _| {- if offset == m.start() { visible = ch == '<'; return true; }- offset > m.start()- });- if parent != m.start() && !visible { continue; }- }- let mut end = None;- scan_js(line, m.end(), |ch, offset, _, _, depth| {- if ch == '>' && depth.brace == 0 { end = Some(offset); return true; }- false- });- let Some(end) = end else { continue; };- let tag = &line[m.start()..end + 1];- pos = end + 1;+ if hidden_in_parent_tag(line.as_bytes(), m.start()) { continue; }+ let window = &b[..b.len().min(m.start() + MAX_IMG_TAG_BYTES)];+ let TagScan::End(end) = scan_markup_tag(window, m.start(), None) else { continue; };+ pos = (end + 1).min(line.len());+ let tag = &text[m.start()..end + 1];if image_source_is_missing(tag, "") {+ let tag = if tag.contains('\n') {+ tag.lines().map(str::trim).filter(|l| !l.is_empty()).collect::<Vec<_>>().join(" ")+ } else {+ tag.to_string()+ };out.push(MatchCtx {- groups: vec![Some(tag.to_string())],+ groups: vec![Some(tag)],index: m.start(),});}diff --git a/crates/detect/tests/broken_image_source.rs b/crates/detect/tests/broken_image_source.rsindex 7196fb02c..cf6d6d08d 100644--- a/crates/detect/tests/broken_image_source.rs+++ b/crates/detect/tests/broken_image_source.rs@@ -6,16 +6,16 @@ use impeccable_detect::detect_text::{detect_text, TextOptions};#[test]fn source_images_distinguish_markup_from_bindings_and_code_literals() {let cases: &[(&str, &str, &[usize])] = &[- ("View.svelte", include_str!("fixtures/broken-image/shorthand.svelte"), &[5, 6, 7]),+ ("View.svelte", include_str!("fixtures/broken-image/shorthand.svelte"), &[5, 6, 7, 11, 12]),("View.astro", include_str!("fixtures/broken-image/shorthand.astro"), &[4]),("View.vue", include_str!("fixtures/broken-image/bindings.vue"), &[7, 8]),- ("index.html", include_str!("fixtures/broken-image/missing.html"), &[1, 2, 3, 4, 5, 7]),+ ("index.html", include_str!("fixtures/broken-image/missing.html"), &[1, 2, 3, 4, 5, 7, 9, 11, 18]),("markers.ts", include_str!("fixtures/broken-image/literals.js"), &[]),("markers.js", include_str!("fixtures/broken-image/literals.js"), &[]),("markers.mjs", include_str!("fixtures/broken-image/literals.js"), &[]),("markers.cjs", include_str!("fixtures/broken-image/literals.js"), &[]),- ("View.jsx", include_str!("fixtures/broken-image/elements.jsx"), &[5, 6, 11, 14, 18, 19, 21]),- ("View.tsx", include_str!("fixtures/broken-image/elements.jsx"), &[5, 6, 11, 14, 18, 19, 21]),+ ("View.jsx", include_str!("fixtures/broken-image/elements.jsx"), &[5, 6, 11, 14, 18, 19, 21, 29]),+ ("View.tsx", include_str!("fixtures/broken-image/elements.jsx"), &[5, 6, 11, 14, 18, 19, 21, 29]),];for &(path, source, expected) in cases {let findings = detect_text(source, path, &TextOptions::default());diff --git a/crates/detect/tests/fixtures/broken-image/bindings.vue b/crates/detect/tests/fixtures/broken-image/bindings.vueindex beada8b0c..35c566a60 100644--- a/crates/detect/tests/fixtures/broken-image/bindings.vue+++ b/crates/detect/tests/fixtures/broken-image/bindings.vue@@ -6,4 +6,7 @@<img v-bind="props" alt=""><img alt=":src" data-note="v-bind:src"><img src="#" alt="">+ <img+ :src="src"+ alt=""></template>diff --git a/crates/detect/tests/fixtures/broken-image/elements.jsx b/crates/detect/tests/fixtures/broken-image/elements.jsxindex 165fd770e..67a23cc98 100644--- a/crates/detect/tests/fixtures/broken-image/elements.jsx+++ b/crates/detect/tests/fixtures/broken-image/elements.jsx@@ -19,3 +19,14 @@ export const Nested = () => <div>Don't forget <img /></div>;export const Attribute = () => <Box icon={<img src="#" />} label="Portrait" />;if (ready) /<img [^>]*badges[^>]*>/.test(text);export const AfterCondition = () => <img />;+export const Multi = () => (+ <img+ src={src}+ alt=""+ />+);+export const MultiMissing = () => (+ <img+ alt=""+ />+);diff --git a/crates/detect/tests/fixtures/broken-image/missing.html b/crates/detect/tests/fixtures/broken-image/missing.htmlindex bbf18a775..6713b78ae 100644--- a/crates/detect/tests/fixtures/broken-image/missing.html+++ b/crates/detect/tests/fixtures/broken-image/missing.html@@ -6,3 +6,13 @@<img src="/real.png" alt=""><img data-note="src=/real.png" alt=""><img alt="<img>" src="/real.png">+<img src=""+ alt="Portrait" />+<img+ alt="no source"+>+<img+ src="/real.png"+ alt="">+<img data-src="/lazy.png" class="lazyload" alt="">+<p title="C:\"><img src="" alt=""></p>diff --git a/crates/detect/tests/fixtures/broken-image/shorthand.svelte b/crates/detect/tests/fixtures/broken-image/shorthand.svelteindex 96fe30d1f..ef9c2ec94 100644--- a/crates/detect/tests/fixtures/broken-image/shorthand.svelte+++ b/crates/detect/tests/fixtures/broken-image/shorthand.svelte@@ -6,3 +6,9 @@<img {alt}><img src="#" alt=""><img src={src} alt="">+<img bind:src={src} alt="">+<img bind:src alt="">+<img data-path="C:\" src="">+<img+ src=""+ alt="Portrait" />