Skip to content

Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. πŸ”₯

fix(branding): return brandName and pick brand colors over header chrome (#4310)

Abimael Martellc9594bfecee9
diff --git a/apps/api/knip.config.ts b/apps/api/knip.config.ts
index e73777ef8..fba35467d 100644
--- a/apps/api/knip.config.ts
+++ b/apps/api/knip.config.ts
@@ -4,6 +4,8 @@ const config: KnipConfig = {
workspaces: {
".": {
entry: [
+ "src/index.ts",
+ "src/harness.ts",
"src/services/worker/**/*.ts",
"src/services/**/*-worker.ts",
"src/**/*.test.ts",
diff --git a/apps/api/src/__tests__/lib/branding/color-roles.test.ts b/apps/api/src/__tests__/lib/branding/color-roles.test.ts
new file mode 100644
index 000000000..7bea2d974
--- /dev/null
+++ b/apps/api/src/__tests__/lib/branding/color-roles.test.ts
@@ -0,0 +1,253 @@
+import { describe, it, expect } from "vitest";
+import { mergeBrandingResults } from "../../../lib/branding/merge";
+import { processRawBranding } from "../../../lib/branding/processor";
+import {
+ isNearBlack,
+ normalizeRoleHex,
+ pickBrandPrimary,
+ shouldApplyLlmColorRoles,
+} from "../../../lib/branding/color-roles";
+import type { BrandingScriptReturn } from "../../../lib/branding/types";
+
+const emptyLlm = {
+ cleanedFonts: [] as [],
+ buttonClassification: {
+ primaryButtonIndex: -1,
+ primaryButtonReasoning: "n/a",
+ secondaryButtonIndex: -1,
+ secondaryButtonReasoning: "n/a",
+ confidence: 0,
+ },
+};
+
+describe("pickBrandPrimary", () => {
+ it("skips navy header chrome on a light page", () => {
+ expect(
+ pickBrandPrimary(["#061B31", "#635BFF", "#FFFFFF"], {
+ background: "#FFFFFF",
+ textPrimary: "#0A2540",
+ colorScheme: "light",
+ }),
+ ).toBe("#635BFF");
+ });
+
+ it("keeps a dark chromatic color on a dark page", () => {
+ expect(
+ pickBrandPrimary(["#0A0A0A", "#22C55E"], {
+ background: "#0A0A0A",
+ colorScheme: "dark",
+ }),
+ ).toBe("#22C55E");
+ });
+
+ it("does not treat saturated blue as near-black chrome", () => {
+ expect(isNearBlack("#0000FF")).toBe(false);
+ expect(isNearBlack("#061B31")).toBe(true);
+ expect(isNearBlack("#000080")).toBe(true);
+ expect(
+ pickBrandPrimary(["#061B31", "#0000FF"], {
+ background: "#FFFFFF",
+ colorScheme: "light",
+ }),
+ ).toBe("#0000FF");
+ expect(
+ pickBrandPrimary(["#000080", "#635BFF"], {
+ background: "#FFFFFF",
+ colorScheme: "light",
+ }),
+ ).toBe("#635BFF");
+ });
+});
+
+describe("normalizeRoleHex / LLM gate", () => {
+ it("rejects color names", () => {
+ expect(normalizeRoleHex("navy")).toBeUndefined();
+ expect(normalizeRoleHex("#635BFF")).toBe("#635BFF");
+ expect(normalizeRoleHex("#63f")).toBe("#6633FF");
+ });
+
+ it("applies LLM colors at 0.5+ and rescues chrome at 0.4+", () => {
+ expect(shouldApplyLlmColorRoles(0.6, "#635BFF", "#061B31", "light")).toBe(
+ true,
+ );
+ expect(shouldApplyLlmColorRoles(0.5, "#635BFF", "#FF4C00", "light")).toBe(
+ true,
+ );
+ expect(shouldApplyLlmColorRoles(0.45, "#635BFF", "#061B31", "light")).toBe(
+ true,
+ );
+ expect(shouldApplyLlmColorRoles(0.45, "#635BFF", "#635BFF", "light")).toBe(
+ false,
+ );
+ expect(shouldApplyLlmColorRoles(0.2, "#635BFF", "#061B31", "light")).toBe(
+ false,
+ );
+ });
+});
+
+describe("merge color roles", () => {
+ it("applies a valid LLM primary at confidence 0.6", () => {
+ const merged = mergeBrandingResults(
+ { colorScheme: "light", colors: { primary: "#061B31" } },
+ {
+ ...emptyLlm,
+ colorRoles: {
+ primaryColor: "#635BFF",
+ accentColor: "#635BFF",
+ backgroundColor: "#FFFFFF",
+ textPrimary: "#0A2540",
+ confidence: 0.6,
+ },
+ },
+ [],
+ );
+ expect(merged.colors?.primary).toBe("#635BFF");
+ });
+
+ it("does not let a color name overwrite the heuristic", () => {
+ const merged = mergeBrandingResults(
+ { colorScheme: "light", colors: { primary: "#FF4C00" } },
+ {
+ ...emptyLlm,
+ colorRoles: {
+ primaryColor: "orange",
+ accentColor: "",
+ backgroundColor: "",
+ textPrimary: "",
+ confidence: 0.9,
+ },
+ },
+ [],
+ );
+ expect(merged.colors?.primary).toBe("#FF4C00");
+ });
+
+ it("does not let a high-confidence navy LLM primary overwrite a brand color", () => {
+ const merged = mergeBrandingResults(
+ { colorScheme: "light", colors: { primary: "#635BFF" } },
+ {
+ ...emptyLlm,
+ colorRoles: {
+ primaryColor: "#061B31",
+ accentColor: "#635BFF",
+ backgroundColor: "#FFFFFF",
+ textPrimary: "#0A2540",
+ confidence: 0.9,
+ },
+ },
+ [],
+ );
+ expect(merged.colors?.primary).toBe("#635BFF");
+ expect(merged.colors?.background).toBe("#FFFFFF");
+ });
+
+ it("keeps heuristic secondary when the LLM returns a non-hex secondary", () => {
+ const merged = mergeBrandingResults(
+ {
+ colorScheme: "light",
+ colors: { primary: "#635BFF", secondary: "#00D4FF" },
+ },
+ {
+ ...emptyLlm,
+ colorRoles: {
+ primaryColor: "#635BFF",
+ secondaryColor: "navy",
+ accentColor: "#635BFF",
+ backgroundColor: "#FFFFFF",
+ textPrimary: "#0A2540",
+ confidence: 0.9,
+ },
+ },
+ [],
+ );
+ expect(merged.colors?.secondary).toBe("#00D4FF");
+ });
+
+ it("drops heuristic secondary when the LLM omits secondaryColor", () => {
+ const merged = mergeBrandingResults(
+ {
+ colorScheme: "light",
+ colors: { primary: "#635BFF", secondary: "#00D4FF" },
+ },
+ {
+ ...emptyLlm,
+ colorRoles: {
+ primaryColor: "#635BFF",
+ accentColor: "#635BFF",
+ backgroundColor: "#FFFFFF",
+ textPrimary: "#0A2540",
+ confidence: 0.9,
+ },
+ },
+ [],
+ );
+ expect(merged.colors?.secondary).toBeUndefined();
+ });
+});
+
+type Snapshot = BrandingScriptReturn["snapshots"][number];
+
+function snap(
+ partial: Omit<Partial<Snapshot>, "colors"> & {
+ colors?: Partial<Snapshot["colors"]>;
+ },
+): Snapshot {
+ const { colors, ...rest } = partial;
+ return {
+ tag: "div",
+ classes: "",
+ text: "",
+ rect: { w: 100, h: 40 },
+ typography: { fontStack: ["Inter"], size: "16px", weight: 400 },
+ radius: 0,
+ borderRadius: { topLeft: 0, topRight: 0, bottomRight: 0, bottomLeft: 0 },
+ shadow: null,
+ isButton: false,
+ isInput: false,
+ isLink: false,
+ ...rest,
+ colors: {
+ text: "rgb(0, 0, 0)",
+ background: "rgb(255, 255, 255)",
+ border: "transparent",
+ borderWidth: 0,
+ ...colors,
+ },
+ };
+}
+
+describe("processRawBranding primary", () => {
+ it("prefers a CTA button color over a large navy header", () => {
+ const profile = processRawBranding({
+ cssData: { colors: [], spacings: [], radii: [] },
+ snapshots: [
+ snap({
+ tag: "header",
+ rect: { w: 1400, h: 80 },
+ colors: { background: "rgb(6, 27, 49)", text: "rgb(255, 255, 255)" },
+ }),
+ snap({
+ tag: "button",
+ text: "Get started",
+ isButton: true,
+ hasCTAIndicator: true,
+ rect: { w: 140, h: 44 },
+ colors: {
+ background: "rgb(99, 91, 255)",
+ text: "rgb(255, 255, 255)",
+ },
+ }),
+ ],
+ images: [],
+ typography: {
+ stacks: { body: ["Inter"], heading: ["Inter"], paragraph: ["Inter"] },
+ sizes: { h1: "32px", h2: "24px", body: "16px" },
+ },
+ frameworkHints: [],
+ colorScheme: "light",
+ pageBackground: "rgb(255, 255, 255)",
+ });
+
+ expect(profile.colors?.primary).toBe("#635BFF");
+ });
+});
diff --git a/apps/api/src/__tests__/lib/branding/declared-logo.test.ts b/apps/api/src/__tests__/lib/branding/declared-logo.test.ts
index 40b4fe5d0..0e1db1b5a 100644
--- a/apps/api/src/__tests__/lib/branding/declared-logo.test.ts
+++ b/apps/api/src/__tests__/lib/branding/declared-logo.test.ts
@@ -1,5 +1,9 @@
import { describe, it, expect } from "vitest";
-import { pickDeclaredLogo } from "../../../lib/branding/declared-logo";
+import {
+ declaredLogoCandidate,
+ pickDeclaredLogo,
+ shouldAddDeclaredLogoCandidate,
+} from "../../../lib/branding/declared-logo";
describe("pickDeclaredLogo", () => {
it("prefers JSON-LD declared logo over apple-touch icon", () => {
@@ -31,4 +35,131 @@ describe("pickDeclaredLogo", () => {
expect(pickDeclaredLogo(undefined)).toBeNull();
expect(pickDeclaredLogo([])).toBeNull();
});
+
+ it("builds a selectable candidate from a declared mark", () => {
+ const candidate = declaredLogoCandidate(
+ "https://x.com/logo.svg",
+ "logo-jsonld",
+ "Example",
+ );
+ expect(candidate).toMatchObject({
+ src: "https://x.com/logo.svg",
+ alt: "Example",
+ isSvg: true,
+ isVisible: true,
+ source: "logo-jsonld",
+ indicators: { inHeader: true, srcMatch: true, hrefMatch: true },
+ });
+ expect(candidate.href).toBeUndefined();
+ });
+
+ it("does not inject a declared mark when a visible header logo exists", () => {
+ expect(
+ shouldAddDeclaredLogoCandidate(
+ [
+ {
+ src: "https://x.com/header.svg",
+ isVisible: true,
+ location: "header",
+ indicators: {
+ inHeader: true,
+ altMatch: true,
+ srcMatch: true,
+ classMatch: false,
+ hrefMatch: true,
+ },
+ },
+ ],
+ "https://x.com/jsonld.png",
+ ),
+ ).toBe(false);
+ });
+
+ it("injects a declared mark when the header image has no logo indicators", () => {
+ expect(
+ shouldAddDeclaredLogoCandidate(
+ [
+ {
+ src: "https://x.com/hero.png",
+ isVisible: true,
+ location: "header",
+ indicators: {
+ inHeader: true,
+ altMatch: false,
+ srcMatch: false,
+ classMatch: false,
+ hrefMatch: false,
+ },
+ },
+ ],
+ "https://x.com/jsonld.png",
+ ),
+ ).toBe(true);
+ });
+
+ it("injects a declared mark when the same URL exists only as a hidden candidate", () => {
+ expect(
+ shouldAddDeclaredLogoCandidate(
+ [
+ {
+ src: "https://x.com/jsonld.png",
+ isVisible: false,
+ location: "body",
+ indicators: {
+ inHeader: false,
+ altMatch: false,
+ srcMatch: true,
+ classMatch: false,
+ hrefMatch: false,
+ },
+ },
+ ],
+ "https://x.com/jsonld.png",
+ ),
+ ).toBe(true);
+ });
+
+ it("does not inject a declared mark when the same URL is already visible", () => {
+ expect(
+ shouldAddDeclaredLogoCandidate(
+ [
+ {
+ src: "https://x.com/jsonld.png",
+ isVisible: true,
+ location: "body",
+ indicators: {
+ inHeader: false,
+ altMatch: false,
+ srcMatch: true,
+ classMatch: false,
+ hrefMatch: false,
+ },
+ },
+ ],
+ "https://x.com/jsonld.png",
+ ),
+ ).toBe(false);
+ });
+
+ it("injects a declared mark when nothing rendered is in the header", () => {
+ expect(
+ shouldAddDeclaredLogoCandidate(
+ [
+ {
+ src: "https://x.com/og.png",
+ isVisible: false,
+ location: "body",
+ indicators: {
+ inHeader: false,
+ altMatch: false,
+ srcMatch: false,
+ classMatch: false,
+ hrefMatch: false,
+ },
+ },
+ ],
+ "https://x.com/jsonld.png",
+ ),
+ ).toBe(true);
+ });
});
diff --git a/apps/api/src/lib/branding/color-roles.ts b/apps/api/src/lib/branding/color-roles.ts
new file mode 100644
index 000000000..044fd2911
--- /dev/null
+++ b/apps/api/src/lib/branding/color-roles.ts
@@ -0,0 +1,106 @@
+/** CIE-ish luma used to tell chrome (near-black / near-white) from brand color. */
+export function contrastYIQ(hex: string): number {
+ if (!hex) return 0;
+ const h = hex.replace("#", "");
+ if (h.length < 6) return 0;
+ const r = parseInt(h.slice(0, 2), 16);
+ const g = parseInt(h.slice(2, 4), 16);
+ const b = parseInt(h.slice(4, 6), 16);
+ return (r * 299 + g * 587 + b * 114) / 1000;
+}
+
+export function isGrayish(hex: string): boolean {
+ const h = hex.replace("#", "");
+ if (h.length < 6) return true;
+ const r = parseInt(h.slice(0, 2), 16);
+ const g = parseInt(h.slice(2, 4), 16);
+ const b = parseInt(h.slice(4, 6), 16);
+ return Math.max(r, g, b) - Math.min(r, g, b) < 15;
+}
+
+export function isNearBlack(hex: string): boolean {
+ const h = hex.replace("#", "");
+ if (h.length < 6) return contrastYIQ(hex) < 40;
+ const max = Math.max(
+ parseInt(h.slice(0, 2), 16),
+ parseInt(h.slice(2, 4), 16),
+ parseInt(h.slice(4, 6), 16),
+ );
+ // YIQ alone treats saturated blue (#0000FF) as near-black. Require a dark
+ // channel max so navy chrome (#000080 max 128, #061B31 max 49) matches
+ // and full-bright brand blues do not.
+ return contrastYIQ(hex) < 40 && max < 140;
+}
+
+/** Chromatic brand color β€” not gray chrome, and not a near-black nav on light pages. */
+export function isUsableBrandPrimary(
+ hex: string,
+ colorScheme?: "light" | "dark",
+): boolean {
+ if (isGrayish(hex)) return false;
+ if (colorScheme !== "dark" && isNearBlack(hex)) return false;
+ return true;
+}
+
+const HEX = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i;
+
+/** Accept #RGB / #RRGGBB; reject names like "navy" so they cannot overwrite heuristics. */
+export function normalizeRoleHex(value?: string | null): string | undefined {
+ if (!value) return undefined;
+ const raw = value.trim();
+ if (!HEX.test(raw)) return undefined;
+ const h = raw.slice(1);
+ const full =
+ h.length === 3 ? `#${h[0]}${h[0]}${h[1]}${h[1]}${h[2]}${h[2]}` : raw;
+ return full.toUpperCase();
+}
+
+/**
+ * Brand primary is a chromatic color β€” not page chrome.
+ * On light pages, skip near-black (navy headers, dark nav bars).
+ */
+export function pickBrandPrimary(
+ ranked: string[],
+ opts: {
+ background?: string;
+ textPrimary?: string;
+ colorScheme?: "light" | "dark";
+ },
+): string {
+ const skip = new Set(
+ [opts.background, opts.textPrimary].filter((h): h is string => !!h),
+ );
+ const lightPage = opts.colorScheme !== "dark";
+
+ const chromatic = ranked.find(h => {
+ if (skip.has(h) || isGrayish(h)) return false;
+ if (lightPage && isNearBlack(h)) return false;
+ return true;
+ });
+ if (chromatic) return chromatic;
+
+ return (
+ ranked.find(h => !isGrayish(h) && !skip.has(h)) ||
+ (lightPage ? "#000000" : "#FFFFFF")
+ );
+}
+
+/** Inclusive 0.5 bar β€” models often return exactly 0.5 when uncertain. Rescue header chrome down to 0.4. */
+const LLM_COLOR_CONFIDENCE = 0.5;
+
+export function shouldApplyLlmColorRoles(
+ confidence: number,
+ llmPrimary?: string,
+ heuristicPrimary?: string,
+ colorScheme?: "light" | "dark",
+): boolean {
+ if (confidence >= LLM_COLOR_CONFIDENCE) return true;
+ if (confidence < 0.4) return false;
+ const llm = normalizeRoleHex(llmPrimary);
+ if (!llm || isGrayish(llm) || isNearBlack(llm)) return false;
+ return (
+ colorScheme !== "dark" &&
+ !!heuristicPrimary &&
+ isNearBlack(heuristicPrimary)
+ );
+}
diff --git a/apps/api/src/lib/branding/declared-logo.ts b/apps/api/src/lib/branding/declared-logo.ts
index 396ce7e19..63e5e94f0 100644
--- a/apps/api/src/lib/branding/declared-logo.ts
+++ b/apps/api/src/lib/branding/declared-logo.ts
@@ -1,3 +1,5 @@
+import { LogoCandidate } from "./logo-selector";
+
/**
* Fallback logo from site-declared brand marks, used only when the normal
* candidate β†’ heuristic β†’ LLM pipeline produced no logo. JSON-LD `logo` is
@@ -14,3 +16,51 @@ export function pickDeclaredLogo(
if (touch) return { src: touch.src, source: "apple-touch-icon" };
return null;
}
+
+type DeclaredRaceCandidate = Pick<
+ LogoCandidate,
+ "src" | "isVisible" | "location" | "indicators"
+>;
+
+function hasStrongVisibleHeaderLogo(c: DeclaredRaceCandidate): boolean {
+ if (!c.isVisible) return false;
+ if (!(c.location === "header" || c.indicators.inHeader)) return false;
+ const { altMatch, srcMatch, classMatch, hrefMatch } = c.indicators;
+ return altMatch || srcMatch || classMatch || hrefMatch;
+}
+
+/** Inject declared marks only when no strong rendered header logo is already in the race. */
+export function shouldAddDeclaredLogoCandidate(
+ existing: DeclaredRaceCandidate[],
+ declaredSrc: string,
+): boolean {
+ if (existing.some(c => c.src === declaredSrc && c.isVisible)) return false;
+ return !existing.some(hasStrongVisibleHeaderLogo);
+}
+
+/** Turn a declared mark into a logo candidate so it can win selection, not only last-resort fallback. */
+export function declaredLogoCandidate(
+ src: string,
+ source: "logo-jsonld" | "apple-touch-icon",
+ brandName?: string,
+): LogoCandidate {
+ const isSvg =
+ /\.svg(\?|#|$)/i.test(src) ||
+ src.toLowerCase().startsWith("data:image/svg");
+ return {
+ src,
+ alt: brandName?.trim() || "",
+ isSvg,
+ isVisible: true,
+ location: "header",
+ position: { top: 0, left: 0, width: 180, height: 180 },
+ indicators: {
+ inHeader: true,
+ altMatch: false,
+ srcMatch: true,
+ classMatch: false,
+ hrefMatch: true,
+ },
+ source,
+ };
+}
diff --git a/apps/api/src/lib/branding/merge.ts b/apps/api/src/lib/branding/merge.ts
index 59ac5854c..fa9e3ced5 100644
--- a/apps/api/src/lib/branding/merge.ts
+++ b/apps/api/src/lib/branding/merge.ts
@@ -1,4 +1,9 @@
import { BrandingProfile } from "../../types/branding";
+import {
+ isUsableBrandPrimary,
+ normalizeRoleHex,
+ shouldApplyLlmColorRoles,
+} from "./color-roles";
import { LogoCandidate } from "./logo-selector";
import { BrandingEnhancement } from "./schema";
import { ButtonSnapshot, calculateLogoArea } from "./types";
@@ -263,21 +268,40 @@ export function mergeBrandingResults(
}
}
- if (llm.colorRoles.confidence > 0.7) {
+ if (
+ shouldApplyLlmColorRoles(
+ llm.colorRoles.confidence,
+ llm.colorRoles.primaryColor,
+ merged.colors?.primary,
+ merged.colorScheme,
+ )
+ ) {
+ const llmPrimary = normalizeRoleHex(llm.colorRoles.primaryColor);
+ const llmSecondary = normalizeRoleHex(llm.colorRoles.secondaryColor);
+ const llmAccent = normalizeRoleHex(llm.colorRoles.accentColor);
+ const llmBackground = normalizeRoleHex(llm.colorRoles.backgroundColor);
+ const llmText = normalizeRoleHex(llm.colorRoles.textPrimary);
+ const usablePrimary =
+ llmPrimary && isUsableBrandPrimary(llmPrimary, merged.colorScheme)
+ ? llmPrimary
+ : undefined;
+ const rawSecondary = llm.colorRoles.secondaryColor;
+ const omittedSecondary =
+ rawSecondary == null || String(rawSecondary).trim() === "";
+
merged.colors = {
...merged.colors,
- primary: llm.colorRoles.primaryColor || merged.colors?.primary,
- ...(llm.colorRoles.secondaryColor
- ? { secondary: llm.colorRoles.secondaryColor }
- : {}),
- accent: llm.colorRoles.accentColor || merged.colors?.accent,
- background: llm.colorRoles.backgroundColor || merged.colors?.background,
- textPrimary: llm.colorRoles.textPrimary || merged.colors?.textPrimary,
+ primary: usablePrimary || merged.colors?.primary,
+ ...(llmSecondary ? { secondary: llmSecondary } : {}),
+ accent: llmAccent || merged.colors?.accent,
+ background: llmBackground || merged.colors?.background,
+ textPrimary: llmText || merged.colors?.textPrimary,
};
// When the LLM omits secondaryColor, remove the JS-heuristic secondary
- // to avoid propagating spurious colors from CSS presets (e.g. WordPress themes)
- if (!llm.colorRoles.secondaryColor && merged.colors?.secondary) {
+ // to avoid propagating spurious colors from CSS presets (e.g. WordPress themes).
+ // Invalid values (color names) must not look like an omission.
+ if (omittedSecondary && merged.colors?.secondary) {
delete merged.colors.secondary;
}
diff --git a/apps/api/src/lib/branding/processor.ts b/apps/api/src/lib/branding/processor.ts
index 9044520ee..7dd760b69 100644
--- a/apps/api/src/lib/branding/processor.ts
+++ b/apps/api/src/lib/branding/processor.ts
@@ -1,4 +1,10 @@
import { BrandingProfile } from "../../types/branding";
+import {
+ contrastYIQ,
+ isGrayish,
+ isNearBlack,
+ pickBrandPrimary,
+} from "./color-roles";
import { BrandingScriptReturn, InputSnapshot } from "./types";
import { parse, rgb, formatHex } from "culori";
@@ -102,17 +108,6 @@ function calculateRepresentativeBorderRadius(borderRadius?: {
return maxCorner > 0 ? `${maxCorner}px` : "0px";
}
-// Calculate contrast for text readability
-function contrastYIQ(hex: string): number {
- if (!hex) return 0;
- const h = hex.replace("#", "");
- if (h.length < 6) return 0;
- const r = parseInt(h.slice(0, 2), 16),
- g = parseInt(h.slice(2, 4), 16),
- b = parseInt(h.slice(4, 6), 16);
- return (r * 299 + g * 587 + b * 114) / 1000;
-}
-
// Infer color palette from snapshots
function inferPalette(
snapshots: BrandingScriptReturn["snapshots"],
@@ -143,6 +138,12 @@ function inferPalette(
);
bump(hexify(s.colors.text, pageBackground), 1.0);
bump(hexify(s.colors.border, pageBackground), 0.3);
+ if (s.isButton) {
+ const buttonBg = hexify(s.colors.background, pageBackground);
+ if (buttonBg && !isGrayish(buttonBg)) {
+ bump(buttonBg, s.hasCTAIndicator ? 80 : 25);
+ }
+ }
}
for (const c of cssColors) bump(hexify(c, pageBackground), 0.5);
@@ -151,17 +152,6 @@ function inferPalette(
.sort((a, b) => b[1] - a[1])
.map(([h]) => h);
- const isGrayish = (hex: string) => {
- const h = hex.replace("#", "");
- if (h.length < 6) return true;
- const r = parseInt(h.slice(0, 2), 16),
- g = parseInt(h.slice(2, 4), 16),
- b = parseInt(h.slice(4, 6), 16);
- const max = Math.max(r, g, b),
- min = Math.min(r, g, b);
- return max - min < 15;
- };
-
// Improved background detection that considers color scheme
let background = "#FFFFFF"; // Default fallback
@@ -189,13 +179,21 @@ function inferPalette(
}
}
+ const primary = pickBrandPrimary(ranked, {
+ background,
+ colorScheme,
+ });
const textPrimary =
- ranked.find(h => !/^#FFFFFF$/i.test(h) && contrastYIQ(h) < 160) ||
- (colorScheme === "dark" ? "#FFFFFF" : "#111111");
- const primary =
- ranked.find(h => !isGrayish(h) && h !== textPrimary && h !== background) ||
- (colorScheme === "dark" ? "#FFFFFF" : "#000000");
- const accent = ranked.find(h => h !== primary && !isGrayish(h)) || primary;
+ ranked.find(
+ h => h !== primary && !/^#FFFFFF$/i.test(h) && contrastYIQ(h) < 160,
+ ) || (colorScheme === "dark" ? "#FFFFFF" : "#111111");
+ const accent =
+ ranked.find(
+ h =>
+ h !== primary &&
+ !isGrayish(h) &&
+ !(colorScheme !== "dark" && isNearBlack(h)),
+ ) || primary;
// Collect all detected colors with their frequencies for debugging
const allDetectedColors = Array.from(freq.entries())
diff --git a/apps/api/src/lib/branding/prompt.ts b/apps/api/src/lib/branding/prompt.ts
index b5a30df02..e8b1f3d39 100644
--- a/apps/api/src/lib/branding/prompt.ts
+++ b/apps/api/src/lib/branding/prompt.ts
@@ -486,11 +486,11 @@ export function buildBrandingPrompt(input: BrandingLLMInput): string {
}
prompt += `${buttons && buttons.length > 0 ? "3" : "1"}. **Color Roles**: Based on ${buttons && buttons.length > 0 ? "button colors and " : ""}page context:\n`;
- prompt += ` - PRIMARY brand color (usually logo/heading color)\n`;
+ prompt += ` - PRIMARY brand color: the saturated brand/CTA color (logo fill, primary button). NOT the header/nav chrome, NOT near-black navy on a light page, NOT the page background.\n`;
prompt += ` - SECONDARY brand color (a complementary color distinct from primary, often used for secondary headings, supporting UI elements, or alternate brand visuals. Return "" if no clear secondary color exists)\n`;
prompt += ` - ACCENT color (${buttons && buttons.length > 0 ? "usually the vibrant CTA button background - green, blue, etc." : "vibrant accent color from the page"})\n`;
prompt += ` - Background and text colors\n`;
- prompt += ` - If unsure about any color, return an empty string "" for that field (NOT null)\n\n`;
+ prompt += ` - Return hex only (#RRGGBB). If unsure about any color, return an empty string "" for that field (NOT null)\n\n`;
prompt += `${buttons && buttons.length > 0 ? "4" : "2"}. **Brand Personality**: Overall tone, energy, and target audience\n`;
prompt += ` - If unsure about target audience, return "unknown"\n\n`;
diff --git a/apps/api/src/lib/branding/transformer.ts b/apps/api/src/lib/branding/transformer.ts
index ba2d21c71..0a0bc0db6 100644
--- a/apps/api/src/lib/branding/transformer.ts
+++ b/apps/api/src/lib/branding/transformer.ts
@@ -11,7 +11,11 @@ import {
getTopCandidatesForLLM,
} from "./logo-selector";
import { extractHeaderHtmlChunk } from "./extractHeaderHtmlChunk";
-import { pickDeclaredLogo } from "./declared-logo";
+import {
+ declaredLogoCandidate,
+ pickDeclaredLogo,
+ shouldAddDeclaredLogoCandidate,
+} from "./declared-logo";
function isDebugBrandingEnabled(meta: Meta): boolean {
return (
@@ -37,8 +41,17 @@ export async function brandingTransformer(
const buttonSnapshots: ButtonSnapshot[] =
(jsBranding as any).__button_snapshots || [];
const inputSnapshots = (jsBranding as any).__input_snapshots || [];
- const logoCandidates = rawBranding.logoCandidates || [];
- const brandName = rawBranding.brandName;
+ const logoCandidates = [...(rawBranding.logoCandidates || [])];
+ const brandName = rawBranding.brandName?.trim() || undefined;
+ const declared = pickDeclaredLogo(rawBranding.images);
+ if (
+ declared &&
+ shouldAddDeclaredLogoCandidate(logoCandidates, declared.src)
+ ) {
+ logoCandidates.push(
+ declaredLogoCandidate(declared.src, declared.source, brandName),
+ );
+ }
const backgroundCandidates = rawBranding.backgroundCandidates || [];
// Initialize metadata tracking variables
@@ -426,17 +439,14 @@ export async function brandingTransformer(
// Last-resort fallback: when the candidate β†’ heuristic β†’ LLM pipeline ended
// with no logo (no candidates, LLM rejection, or LLM failure), use the
// site-declared brand mark. Never overrides a selected logo.
- if (!brandingProfile.images?.logo) {
- const declared = pickDeclaredLogo(rawBranding.images);
- if (declared) {
- brandingProfile.images = {
- ...(brandingProfile.images ?? {}),
- logo: declared.src,
- };
- meta.logger.info("Using declared logo fallback", {
- source: declared.source,
- });
- }
+ if (!brandingProfile.images?.logo && declared) {
+ brandingProfile.images = {
+ ...(brandingProfile.images ?? {}),
+ logo: declared.src,
+ };
+ meta.logger.info("Using declared logo fallback", {
+ source: declared.source,
+ });
}
if (!isDebugBrandingEnabled(meta)) {
@@ -446,5 +456,12 @@ export async function brandingTransformer(
delete (brandingProfile as any).__framework_hints;
}
+ if (brandName) {
+ brandingProfile.brandName = brandName;
+ }
+ if (brandingProfile.images?.logo) {
+ brandingProfile.logo = brandingProfile.images.logo;
+ }
+
return brandingProfile;
}
diff --git a/apps/api/src/types/branding.ts b/apps/api/src/types/branding.ts
index cc7e8f367..1054a9665 100644
--- a/apps/api/src/types/branding.ts
+++ b/apps/api/src/types/branding.ts
@@ -1,5 +1,7 @@
export interface BrandingProfile {
colorScheme?: "light" | "dark";
+ /** Site name from og:site_name / title / h1 / domain, collected in-page. */
+ brandName?: string;
logo?: string | null;
fonts?: Array<{
family: string;
diff --git a/apps/js-sdk/firecrawl/package.json b/apps/js-sdk/firecrawl/package.json
index ac1296803..139368a82 100644
--- a/apps/js-sdk/firecrawl/package.json
+++ b/apps/js-sdk/firecrawl/package.json
@@ -1,6 +1,6 @@
{
"name": "@mendable/firecrawl-js",
- "version": "4.32.1",
+ "version": "4.32.2",
"description": "JavaScript SDK for the Firecrawl API: web scraping, crawling, web search, and scientific literature search over a research paper index of PubMed, bioRxiv, medRxiv and arXiv abstracts",
"main": "dist/index.js",
"types": "dist/index.d.ts",
diff --git a/apps/js-sdk/firecrawl/src/v2/types.ts b/apps/js-sdk/firecrawl/src/v2/types.ts
index 1f99c6232..128f99bb3 100644
--- a/apps/js-sdk/firecrawl/src/v2/types.ts
+++ b/apps/js-sdk/firecrawl/src/v2/types.ts
@@ -328,6 +328,7 @@ export interface AgentWebhookConfig {
export interface BrandingProfile {
colorScheme?: "light" | "dark";
+ brandName?: string;
logo?: string | null;
fonts?: Array<{
family: string;
diff --git a/apps/python-sdk/firecrawl/__init__.py b/apps/python-sdk/firecrawl/__init__.py
index 908e06d0d..b58024270 100644
--- a/apps/python-sdk/firecrawl/__init__.py
+++ b/apps/python-sdk/firecrawl/__init__.py
@@ -18,7 +18,7 @@ from .v1 import (
V1ChangeTrackingOptions,
)
-__version__ = "4.35.0"
+__version__ = "4.35.1"
# Define the logger for the Firecrawl project
logger: logging.Logger = logging.getLogger("firecrawl")
diff --git a/apps/python-sdk/firecrawl/v2/types.py b/apps/python-sdk/firecrawl/v2/types.py
index 8039d3395..096cecd1b 100644
--- a/apps/python-sdk/firecrawl/v2/types.py
+++ b/apps/python-sdk/firecrawl/v2/types.py
@@ -258,9 +258,10 @@ class AttributeResult(BaseModel):
class BrandingProfile(BaseModel):
"""Branding information extracted from a website."""
- model_config = {"extra": "allow"}
+ model_config = {"extra": "allow", "populate_by_name": True}
color_scheme: Optional[Literal["light", "dark"]] = None
+ brand_name: Optional[str] = Field(default=None, alias="brandName")
logo: Optional[str] = None
fonts: Optional[List[Dict[str, Any]]] = None
colors: Optional[Dict[str, str]] = None