Skip to content

Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. 🔥

feat(branding): read logo colors in newer color formats, gradients and cross-origin images (#5288)

Abimael Martell646fe5a4b844
diff --git a/apps/api/src/scraper/scrapeURL/engines/fire-engine/branding-script/images.ts b/apps/api/src/scraper/scrapeURL/engines/fire-engine/branding-script/images.ts
index 8b324b215..f5520fa6f 100644
--- a/apps/api/src/scraper/scrapeURL/engines/fire-engine/branding-script/images.ts
+++ b/apps/api/src/scraper/scrapeURL/engines/fire-engine/branding-script/images.ts
@@ -1420,7 +1420,9 @@ export const findImages = (): FindImagesResult => {
.slice(0, LOGO_COLOR_CANDIDATES)
.forEach(candidate => {
const el = candidateElements.get(candidate);
- const colors = el ? getLogoColors(el) : [];
+ const colors = el
+ ? getLogoColors(el, later => (candidate.colors = later))
+ : [];
if (colors.length > 0) candidate.colors = colors;
});
diff --git a/apps/api/src/scraper/scrapeURL/engines/fire-engine/branding-script/index.ts b/apps/api/src/scraper/scrapeURL/engines/fire-engine/branding-script/index.ts
index 870bee47a..0eca05dc5 100644
--- a/apps/api/src/scraper/scrapeURL/engines/fire-engine/branding-script/index.ts
+++ b/apps/api/src/scraper/scrapeURL/engines/fire-engine/branding-script/index.ts
@@ -2,6 +2,20 @@ import { errors } from "./helpers";
import { collectCSSData } from "./css-data";
import { sampleElements, getStyleSnapshot } from "./elements";
import { findImages } from "./images";
+import { readCrossOriginLogoColors } from "./logo-colors";
+
+// Cross-origin logo images are read again with CORS after the scan; waits
+// at most this long, only on pages that have them.
+const CROSS_ORIGIN_LOGO_WAIT_MS = 1000;
+
+/** The scan's result, or a promise of it when logo images are still loading. */
+export const extractBrandDesignWithLogoColors = ():
+ | BrandingResult
+ | Promise<BrandingResult> => {
+ const result = extractBrandDesign();
+ const pending = readCrossOriginLogoColors(CROSS_ORIGIN_LOGO_WAIT_MS);
+ return pending ? pending.then(() => result) : result;
+};
import {
getTypography,
detectFrameworkHints,
diff --git a/apps/api/src/scraper/scrapeURL/engines/fire-engine/branding-script/logo-colors.ts b/apps/api/src/scraper/scrapeURL/engines/fire-engine/branding-script/logo-colors.ts
index a08d378ec..84925b59a 100644
--- a/apps/api/src/scraper/scrapeURL/engines/fire-engine/branding-script/logo-colors.ts
+++ b/apps/api/src/scraper/scrapeURL/engines/fire-engine/branding-script/logo-colors.ts
@@ -18,10 +18,44 @@ const toHex = (r: number, g: number, b: number): string =>
.join("")
.toUpperCase();
-/** rgb()/rgba() as the browser computes paint, or null if not a solid color. */
+// Paint the browser computes in a newer color syntax (lab(), oklch(),
+// color(display-p3 ...): Tailwind v4 and many design systems) is converted to
+// sRGB by drawing it on a 1x1 canvas and reading the pixel back.
+let paintCtx: CanvasRenderingContext2D | null | undefined;
+const canvasColorCache = new Map<string, [number, number, number] | null>();
+const viaCanvas = (paint: string): [number, number, number] | null => {
+ if (canvasColorCache.has(paint)) return canvasColorCache.get(paint)!;
+ let rgb: [number, number, number] | null = null;
+ try {
+ if (typeof CSS !== "undefined" && CSS.supports?.("color", paint)) {
+ if (paintCtx === undefined) {
+ const canvas = document.createElement("canvas");
+ canvas.width = canvas.height = 1;
+ paintCtx = canvas.getContext("2d", { willReadFrequently: true });
+ }
+ if (paintCtx) {
+ paintCtx.clearRect(0, 0, 1, 1);
+ paintCtx.fillStyle = paint;
+ paintCtx.fillRect(0, 0, 1, 1);
+ const d = paintCtx.getImageData(0, 0, 1, 1).data;
+ rgb = d[3] >= 128 ? [d[0], d[1], d[2]] : null;
+ }
+ }
+ } catch {
+ rgb = null;
+ }
+ canvasColorCache.set(paint, rgb);
+ return rgb;
+};
+
+/** A solid paint as the browser computes it, as RGB, or null if not one. */
const parsePaint = (paint: string): [number, number, number] | null => {
const m = paint.match(/^rgba?\(([^)]+)\)$/);
- if (!m) return null;
+ if (!m) {
+ return /^(lab|lch|oklab|oklch|color|hsla?|hwb)\(/.test(paint)
+ ? viaCanvas(paint)
+ : null;
+ }
const parts = m[1]
.split(/[\s,/]+/)
.filter(Boolean)
@@ -85,6 +119,39 @@ const isUnpainted = (shape: Element, svg: Element): boolean => {
return false;
};
+/**
+ * The stop colors of a gradient paint (`url(#id)`), following one `href` to
+ * a gradient that holds the stops; null when the paint isn't a gradient.
+ */
+const gradientStops = (paint: string, svg: Element): string[] | null => {
+ const id = paint.match(/^url\(["']?#([^"')]+)["']?\)/)?.[1];
+ if (!id) return null;
+ // The SVG's own root: a logo inside a shadow root defines its gradients
+ // there, out of the document's sight.
+ const root = svg.getRootNode() as Document | ShadowRoot;
+ const byId = (ref: string) =>
+ root.getElementById?.(ref) ?? svg.ownerDocument.getElementById(ref);
+ let gradient: Element | null = byId(id);
+ for (let hop = 0; gradient && hop < 2; hop++) {
+ if (!/gradient$/i.test(gradient.localName)) return null;
+ const stops = [...gradient.querySelectorAll("stop")];
+ if (stops.length > 0) {
+ return stops
+ .filter(
+ stop => parseFloat(getComputedStyleCached(stop).stopOpacity) >= 0.5,
+ )
+ .map(stop => getComputedStyleCached(stop).stopColor);
+ }
+ const ref = (
+ gradient.getAttribute("href") ??
+ gradient.getAttribute("xlink:href") ??
+ ""
+ ).replace(/^#/, "");
+ gradient = ref ? byId(ref) : null;
+ }
+ return null;
+};
+
/** Fill and stroke colors of an inline SVG's shapes, weighted by their area. */
const svgColors = (svg: SVGSVGElement): LogoColor[] => {
const weights = new Map<string, number>();
@@ -104,6 +171,11 @@ const svgColors = (svg: SVGSVGElement): LogoColor[] => {
// Not rendered: count it once.
}
const add = (paint: string, weight: number) => {
+ const stops = gradientStops(paint, svg);
+ if (stops) {
+ stops.forEach(stop => add(stop, weight / stops.length));
+ return;
+ }
const rgb = parsePaint(paint);
if (!rgb) return;
const hex = toHex(...rgb);
@@ -120,14 +192,19 @@ const svgColors = (svg: SVGSVGElement): LogoColor[] => {
* Colors of a loaded image, from a small copy on a canvas. Images from
* another origin without CORS can't be read and return nothing.
*/
-const imageColors = (img: HTMLImageElement): LogoColor[] => {
- if (!img.complete || !img.naturalWidth || !img.naturalHeight) return [];
- const scale = Math.min(
- 1,
- SAMPLE_PX / Math.max(img.naturalWidth, img.naturalHeight),
- );
- const w = Math.max(1, Math.round(img.naturalWidth * scale));
- const h = Math.max(1, Math.round(img.naturalHeight * scale));
+const imageColors = (
+ img: HTMLImageElement,
+ readLater?: () => void,
+): LogoColor[] => {
+ if (!img.complete) return [];
+ // An SVG file without a size of its own still draws at any size.
+ const natW =
+ img.naturalWidth || (/\.svg(\?|#|$)/i.test(img.src) ? SAMPLE_PX : 0);
+ const natH = img.naturalHeight || (natW ? natW : 0);
+ if (!natW || !natH) return [];
+ const scale = Math.min(1, SAMPLE_PX / Math.max(natW, natH));
+ const w = Math.max(1, Math.round(natW * scale));
+ const h = Math.max(1, Math.round(natH * scale));
const canvas = document.createElement("canvas");
canvas.width = w;
canvas.height = h;
@@ -138,7 +215,8 @@ const imageColors = (img: HTMLImageElement): LogoColor[] => {
ctx.drawImage(img, 0, 0, w, h);
data = ctx.getImageData(0, 0, w, h).data;
} catch {
- return []; // cross-origin
+ readLater?.(); // another origin, read without CORS
+ return [];
}
// Group pixels into 4-bit-per-channel buckets; report each bucket's average.
const buckets = new Map<
@@ -164,11 +242,28 @@ const imageColors = (img: HTMLImageElement): LogoColor[] => {
return ranked(weights);
};
-/** The colors a logo is drawn in, most used first, when they can be read. */
-export const getLogoColors = (el: Element): LogoColor[] => {
+// Logo images from another origin can't be read as loaded, but most CDNs
+// allow a CORS read: they're loaded again with crossOrigin after the scan and
+// their colors filled in then (see readCrossOriginLogoColors).
+const crossOrigin: Array<{ url: string; set: (colors: LogoColor[]) => void }> =
+ [];
+
+/**
+ * The colors a logo is drawn in, most used first, when they can be read.
+ * `set` receives colors read later from a cross-origin image.
+ */
+export const getLogoColors = (
+ el: Element,
+ set?: (colors: LogoColor[]) => void,
+): LogoColor[] => {
try {
if (el instanceof SVGSVGElement) return svgColors(el);
- if (el instanceof HTMLImageElement) return imageColors(el);
+ if (el instanceof HTMLImageElement) {
+ return imageColors(el, () => {
+ const url = el.currentSrc || el.src;
+ if (set && url) crossOrigin.push({ url, set });
+ });
+ }
// A logo drawn as a CSS background: read the image when the browser
// already has it (an image it still has to load reads as nothing).
const url = getComputedStyleCached(el).backgroundImage.match(
@@ -177,10 +272,53 @@ export const getLogoColors = (el: Element): LogoColor[] => {
if (url) {
const img = new Image();
img.src = url;
- return imageColors(img);
+ const readLater = () => {
+ if (set) crossOrigin.push({ url: img.src, set });
+ };
+ // The browser may not have the background image ready yet: read it
+ // after the scan, like a cross-origin one.
+ if (!img.complete) {
+ readLater();
+ return [];
+ }
+ return imageColors(img, readLater);
}
} catch (e) {
recordError("getLogoColors", e);
}
return [];
};
+
+/**
+ * Loads the cross-origin logo images found during the scan again with CORS
+ * and fills in their colors, waiting at most `timeoutMs`. Null when there are
+ * none, so the scan stays synchronous on most pages.
+ */
+export const readCrossOriginLogoColors = (
+ timeoutMs: number,
+): Promise<void> | null => {
+ if (crossOrigin.length === 0) return null;
+ const pending = crossOrigin.splice(0);
+ const loads = pending.map(
+ ({ url, set }) =>
+ new Promise<void>(resolve => {
+ const img = new Image();
+ img.crossOrigin = "anonymous";
+ img.onload = () => {
+ try {
+ const colors = imageColors(img);
+ if (colors.length > 0) set(colors);
+ } catch (e) {
+ recordError("readCrossOriginLogoColors", e);
+ }
+ resolve();
+ };
+ img.onerror = () => resolve();
+ img.src = url;
+ }),
+ );
+ return Promise.race([
+ Promise.all(loads).then(() => undefined),
+ new Promise<void>(resolve => setTimeout(resolve, timeoutMs)),
+ ]);
+};
diff --git a/apps/api/src/scraper/scrapeURL/engines/fire-engine/branding-script/print-script.js b/apps/api/src/scraper/scrapeURL/engines/fire-engine/branding-script/print-script.js
index 03c98cef8..ba4f37d70 100644
--- a/apps/api/src/scraper/scrapeURL/engines/fire-engine/branding-script/print-script.js
+++ b/apps/api/src/scraper/scrapeURL/engines/fire-engine/branding-script/print-script.js
@@ -21,7 +21,7 @@ const bundledCode = result.outputFiles[0].text;
// Wrap in a self-executing function that returns the result
const script = `(function __extractBrandDesign() {
${bundledCode}
-return __extractBrandDesign.extractBrandDesign();
+return __extractBrandDesign.extractBrandDesignWithLogoColors();
})();`;
process.stdout.write(script);
diff --git a/apps/api/src/scraper/scrapeURL/engines/fire-engine/brandingScript.ts b/apps/api/src/scraper/scrapeURL/engines/fire-engine/brandingScript.ts
index 6f80318b4..3881b4312 100644
--- a/apps/api/src/scraper/scrapeURL/engines/fire-engine/brandingScript.ts
+++ b/apps/api/src/scraper/scrapeURL/engines/fire-engine/brandingScript.ts
@@ -38,7 +38,7 @@ export const getBrandingScript = (): string => {
// Wrap in a self-executing function that returns the result
cachedScript = `(function __extractBrandDesign() {
${bundledCode}
-return __extractBrandDesign.extractBrandDesign();
+return __extractBrandDesign.extractBrandDesignWithLogoColors();
})();`;
return cachedScript;