The design language that makes your AI harness better at design.
JavaScript
Fix: broken-image skips attribute shorthand and markup inside JS/TS literals
Paul Bakaus76b5f1e1592a
diff --git a/crates/detect/src/detect_text.rs b/crates/detect/src/detect_text.rsindex 7edc31a2c..161c7bb91 100644--- a/crates/detect/src/detect_text.rs+++ b/crates/detect/src/detect_text.rs@@ -622,6 +622,152 @@ pub fn strip_js_comments(content: &str, jsx: bool) -> String {output}+/// A markup-only view using the comment scanner's literal and JSX parsers.+/// Code literals are blanked; JSX attributes/text and template expressions+/// containing real elements remain visible. Other rules keep their original view.+fn mask_js_literals(content: &str, jsx: bool) -> String {+ struct Mask<'a> {+ chars: &'a [char],+ hidden: Vec<bool>,+ jsx: bool,+ }+ impl Mask<'_> {+ fn hide(&mut self, start: usize, end: usize) {+ self.hidden[start..end].fill(true);+ }+ fn template(&mut self, start: usize) -> usize {+ let mut p = start + 1;+ let mut text = start;+ while p < self.chars.len() {+ match self.chars[p] {+ '\\' => p = (p + 2).min(self.chars.len()),+ '`' => {+ self.hide(text, p + 1);+ return p + 1;+ }+ '$' if self.chars.get(p + 1) == Some(&'{') => {+ self.hide(text, p + 2);+ p = self.code(p + 2, true);+ text = p;+ }+ _ => p += 1,+ }+ }+ self.hide(text, p);+ p+ }+ fn element(&mut self, start: usize, tag: ParsedJsxTag) -> usize {+ let mut p = start + 1;+ // Literal attributes belong to markup. Expressions can contain+ // code strings, regexes, or nested JSX and need the code scanner.+ while p < tag.end {+ match self.chars[p] {+ '\'' | '"' => p = find_quoted_string_end(self.chars, p, self.chars[p])+ .map(|end| end + 1).unwrap_or(tag.end),+ '{' => p = self.code(p + 1, true),+ _ => p += 1,+ }+ }+ p = tag.end + 1;+ if tag.self_closing || tag.closing { return p; }+ while p < self.chars.len() {+ if self.chars[p] == '<' {+ if let Some(child) = parse_jsx_tag(self.chars, p) {+ if child.closing && child.name == tag.name { return child.end + 1; }+ p = self.element(p, child);+ continue;+ }+ } else if self.chars[p] == '{' {+ p = self.code(p + 1, true);+ continue;+ }+ p += 1;+ }+ p+ }+ fn code(&mut self, start: usize, expression: bool) -> usize {+ let mut p = start;+ let mut sig = Significant::default();+ let mut braces = Vec::new();+ let mut parens = Vec::new();+ let mut last_brace = "";+ while p < self.chars.len() {+ let ch = self.chars[p];+ let next = self.chars.get(p + 1).copied();+ if ch == '/' && matches!(next, Some('/') | Some('*')) {+ let end = if next == Some('/') {+ self.chars[p..].iter().position(|c| *c == '\n')+ .map(|end| p + end).unwrap_or(self.chars.len())+ } else {+ find_sub(self.chars, p + 2, &['*', '/'])+ .map(|end| end + 2).unwrap_or(self.chars.len())+ };+ self.hide(p, end);+ p = end;+ continue;+ }+ if matches!(ch, '\'' | '"') {+ let end = find_quoted_string_end(self.chars, p, ch)+ .map(|end| end + 1).unwrap_or(self.chars.len());+ self.hide(p, end);+ p = end;+ sig.record(')');+ continue;+ }+ if ch == '`' {+ p = self.template(p);+ sig.record(')');+ continue;+ }+ if ch == '/' && sig.regex_can_start(last_brace) {+ if let Some(end) = find_regex_literal_end(self.chars, p) {+ self.hide(p, end + 1);+ p = end + 1;+ sig.record(')');+ continue;+ }+ }+ if self.jsx && ch == '<' && sig.regex_can_start(last_brace) {+ if let Some(tag) = parse_jsx_tag(self.chars, p) {+ p = self.element(p, tag);+ sig.record(')');+ continue;+ }+ }+ if ch == '{' {+ braces.push(sig.brace_kind(false, true));+ } else if ch == '}' {+ if expression && braces.is_empty() { return p + 1; }+ last_brace = braces.pop().unwrap_or("");+ } else if ch == '(' {+ parens.push(matches!(sig.current_word.as_str(), "if" | "while" | "for" | "with" | "switch" | "catch"));+ } else if ch == ')' && parens.pop() == Some(true) {+ // A control condition is followed by a statement, where+ // `/.../` is a regex, unlike division after a function call.+ sig.record(';');+ p += 1;+ continue;+ }+ sig.record(ch);+ p += 1;+ }+ p+ }+ }+ let chars: Vec<char> = content.chars().collect();+ let mut mask = Mask { chars: &chars, hidden: vec![false; chars.len()], jsx };+ mask.code(0, false);+ let mut out = String::with_capacity(content.len());+ for (ch, hidden) in chars.iter().zip(mask.hidden) {+ if hidden && !matches!(ch, '\n' | '\r') {+ out.extend(std::iter::repeat(' ').take(ch.len_utf8()));+ } else {+ out.push(*ch);+ }+ }+ out+}+re!(CSS_COMMENT_RE, format!("/\\*{ANY}*?\\*/"));/// JS `stripCssComments`: blank comment bodies (each UTF-16 unit that is not@@ -1745,6 +1891,10 @@ pub fn run_regex_matchers(sheet: Option<&FileSheet>,) -> 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).+ 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.let source = once_cell::unsync::OnceCell::new();@@ -1753,7 +1903,17 @@ pub fn run_regex_matchers(for matcher in REGEX_MATCHERS.iter() {let run = || {let mut matches = Vec::new();- for (i, line) in lines.iter().enumerate() {+ 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);if ctxs.is_empty() {continue;@@ -1782,6 +1942,8 @@ pub fn run_regex_matchers(// declarations around the match read square, and in// stylesheet text the stylesheet agrees.if (matcher.test)(&m, &scope)+ && (matcher.id != "broken-image"+ || crate::regex_matchers::image_source_is_missing(m.whole(), &ext))&& (matcher.id != "side-tab" || is_stripe_child_match(&m) || {let source = source.get_or_init(|| SourceText::new(lines));side_tab_rounded_in_scope(&m, source, i, sass)diff --git a/crates/detect/src/regex_matchers.rs b/crates/detect/src/regex_matchers.rsindex 2ecef5f5e..4777c3d6b 100644--- a/crates/detect/src/regex_matchers.rs+++ b/crates/detect/src/regex_matchers.rs@@ -1751,43 +1751,95 @@ re!(CUBIC_BEZIER_RE,format!("cubic-bezier\\({WS}*([0-9.-]+){WS}*,{WS}*([0-9.-]+){WS}*,{WS}*([0-9.-]+){WS}*,{WS}*([0-9.-]+){WS}*\\)"));-re!(- BROKEN_IMG_SRC_RE,- format!(- "<{img}{B}[^>]*?{B}{src}{WS}*={WS}*(?:\"\"|''|\"{WS}+\"|'{WS}+'|\"#\"|'#')",- img = ci("img"),- src = ci("src")- )-);re!(IMG_OPEN_RE, format!("<{}{B}", ci("img")));-re!(SRC_ATTR_RE, format!("{B}{}{WS}*=", ci("src")));-/// Hand-written port of `/<img\b(?:(?!\bsrc\s*=)[^>])*>/gi`.-fn find_img_without_src(line: &str) -> Vec<MatchCtx> {+/// Read attributes, not substrings of an attribute value or expression.+/// Dynamic bindings/spreads cannot establish a missing source statically.+pub(crate) fn image_source_is_missing(tag: &str, ext: &str) -> bool {+ let shorthand = matches!(ext, ".svelte" | ".astro");+ 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; }+ if b[p] == b'{' {+ let Some(close) = matching_close(b, p) else { return false; };+ let expression = tag[p + 1..close].trim();+ if shorthand && (expression == "src" || expression.starts_with("...")) {+ return false;+ }+ // JSX spreads also leave the source unknown.+ if matches!(ext, ".jsx" | ".tsx" | ".js") && expression.starts_with("...") {+ return false;+ }+ p = close + 1;+ continue;+ }+ let start = p;+ 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.")) {+ return false;+ }+ if p >= b.len() || b[p] != b'=' { continue; }+ p += 1;+ while p < b.len() && b[p].is_ascii_whitespace() { p += 1; }+ let value_start = p;+ let value = if p < b.len() && matches!(b[p], b'\'' | b'"') {+ let quote = b[p];+ p += 1;+ let start = p;+ while p < b.len() && b[p] != quote { p += 1; }+ let value = &tag[start..p];+ p = (p + 1).min(b.len());+ Some(value)+ } else if p < b.len() && b[p] == b'{' {+ p = matching_close(b, p).map(|close| close + 1).unwrap_or(b.len());+ None+ } else {+ 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() == "#");+ }+ }+ missing+}++fn find_broken_images(line: &str) -> Vec<MatchCtx> {let mut out = Vec::new();let mut pos = 0;while let Some(m) = IMG_OPEN_RE.find_at(line, pos) {- let run_start = m.end();- let gt = line[run_start..].find('>').map(|i| i + run_start);- match gt {- Some(gt) => {- let has_src = SRC_ATTR_RE- .find_at(line, run_start)- .map(|s| s.start() < gt)- .unwrap_or(false);- if has_src {- pos = m.end();- continue;- }- out.push(MatchCtx {- groups: vec![Some(line[m.start()..gt + 1].to_string())],- index: m.start(),- });- pos = gt + 1;- }- None => {- pos = m.end();- }+ 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 image_source_is_missing(tag, "") {+ out.push(MatchCtx {+ groups: vec![Some(tag.to_string())],+ index: m.start(),+ });}}out@@ -1993,16 +2045,10 @@ pub static REGEX_MATCHERS: Lazy<Vec<Matcher>> = Lazy::new(|| {},Matcher {id: "broken-image",- find_all: |l| all(&BROKEN_IMG_SRC_RE, l),+ find_all: find_broken_images,test: |_, _| true,fmt: |m, _| slice_utf16_start(m.whole(), 100),},- Matcher {- id: "broken-image",- find_all: find_img_without_src,- test: |m, _| !SRC_ATTR_RE.is_match(m.whole()),- fmt: |m, _| slice_utf16_start(m.whole(), 100),- },]});diff --git a/crates/detect/tests/broken_image_source.rs b/crates/detect/tests/broken_image_source.rsnew file mode 100644index 000000000..7196fb02c--- /dev/null+++ b/crates/detect/tests/broken_image_source.rs@@ -0,0 +1,27 @@+//! The source scan's `broken-image` rule: an `<img>` with no source is+//! markup, not Svelte/Astro/Vue attribute shorthand or a binding, and `<img`+//! inside a JS/TS string, template or regex literal is not markup at all.+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.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]),+ ("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]),+ ];+ for &(path, source, expected) in cases {+ let findings = detect_text(source, path, &TextOptions::default());+ let mut lines = findings.iter().filter(|f| f.antipattern == "broken-image")+ .map(|f| f.line as usize).collect::<Vec<_>>();+ lines.sort_unstable();+ assert_eq!(lines, expected, "{path}");+ }+}diff --git a/crates/detect/tests/fixtures/broken-image/bindings.vue b/crates/detect/tests/fixtures/broken-image/bindings.vuenew file mode 100644index 000000000..beada8b0c--- /dev/null+++ b/crates/detect/tests/fixtures/broken-image/bindings.vue@@ -0,0 +1,9 @@+<template>+ <img :src="src" alt="">+ <img v-bind:src="src" alt="">+ <img :src="" alt="">+ <img v-bind:src.prop="src" alt="">+ <img v-bind="props" alt="">+ <img alt=":src" data-note="v-bind:src">+ <img src="#" alt="">+</template>diff --git a/crates/detect/tests/fixtures/broken-image/elements.jsx b/crates/detect/tests/fixtures/broken-image/elements.jsxnew file mode 100644index 000000000..165fd770e--- /dev/null+++ b/crates/detect/tests/fixtures/broken-image/elements.jsx@@ -0,0 +1,21 @@+const markers = ['<img', '<button>'];+const pattern = /<img [^>]*badges[^>]*>/;+const text = `picture <img>${'<img>'}`;+export const View = () => <>+ <img alt="" />+ <img src="#" alt="" />+ <img src="/real.png" alt="" />+ <img src={src} alt="" />+ <img {...props} alt="" />+ <div>{'<img src="">'}{/<img [^>]*>/g.test(text)}</div>+ <img alt="after literals" />+</>;+const ratio = width / height;+export const AfterDivision = () => <img />;+const unfinished = '<img';+const literalAfter = '<img src="">';+export const AfterUnfinished = () => <img src="/real.png" />;+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 />;diff --git a/crates/detect/tests/fixtures/broken-image/literals.js b/crates/detect/tests/fixtures/broken-image/literals.jsnew file mode 100644index 000000000..7574bae71--- /dev/null+++ b/crates/detect/tests/fixtures/broken-image/literals.js@@ -0,0 +1,14 @@+const markers = ['<img', '<a', '<button'];+const pattern = /<img [^>]*badges[^>]*>/gi;+const single = '<img alt="">';+const double = "<img src='#'>";+const escaped = 'it\'s <img alt="">';+const multiline = `+ <img>+ ${'<img src="">'}+ ${`nested <img>`}+`;+const classes = /[<img >\/]+/;+const tagged = html`<img src="#">`;+// <img>+/* <img src=""> */diff --git a/crates/detect/tests/fixtures/broken-image/missing.html b/crates/detect/tests/fixtures/broken-image/missing.htmlnew file mode 100644index 000000000..bbf18a775--- /dev/null+++ b/crates/detect/tests/fixtures/broken-image/missing.html@@ -0,0 +1,8 @@+<img alt="">+<img src="#" alt="">+<img src="" alt="">+<img src=' ' alt="">+<IMG SRC="#" ALT="">+<img src="/real.png" alt="">+<img data-note="src=/real.png" alt="">+<img alt="<img>" src="/real.png">diff --git a/crates/detect/tests/fixtures/broken-image/shorthand.astro b/crates/detect/tests/fixtures/broken-image/shorthand.astronew file mode 100644index 000000000..490714f6e--- /dev/null+++ b/crates/detect/tests/fixtures/broken-image/shorthand.astro@@ -0,0 +1,5 @@+<img {src} alt="">+<img {...props} alt="">+<img { src } alt="Portrait">+<img alt="{src}">+<img src="/portrait.png" alt="">diff --git a/crates/detect/tests/fixtures/broken-image/shorthand.svelte b/crates/detect/tests/fixtures/broken-image/shorthand.sveltenew file mode 100644index 000000000..96fe30d1f--- /dev/null+++ b/crates/detect/tests/fixtures/broken-image/shorthand.svelte@@ -0,0 +1,8 @@+<img {src} alt="">+<img { src } alt="Portrait">+<img {...props} alt="">+<img {...props} src="#" alt="">+<img alt="{src}" data-note="{...props}">+<img {alt}>+<img src="#" alt="">+<img src={src} alt="">