Skip to content

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

fix(branding): Improve Logo Detection (#2749)

Abimael Martell87976f390e67
diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS
index 56851bde8..0d6900b00 100644
--- a/.github/CODEOWNERS
+++ b/.github/CODEOWNERS
@@ -114,7 +114,7 @@
# Branding
**/branding* @abimaelmartell
-**/brandingScript* @abimaelmartell
+**/branding-script* @abimaelmartell
# Examples
/examples/* @ericciarla @nickscamara
diff --git a/apps/api/.gitignore b/apps/api/.gitignore
index 7efd97aed..1cc479f83 100644
--- a/apps/api/.gitignore
+++ b/apps/api/.gitignore
@@ -15,3 +15,7 @@ dump.rdb
firecrawl.log
test-results/
+
+# Branding script build artifacts (dev-only, generated at runtime)
+branding-script.pasteable.js
+bundle.generated.ts
diff --git a/apps/api/knip.config.ts b/apps/api/knip.config.ts
index ada00cb16..94f57cd5f 100644
--- a/apps/api/knip.config.ts
+++ b/apps/api/knip.config.ts
@@ -9,14 +9,9 @@ const config: KnipConfig = {
},
ignore: [
"native/**",
- "src/services/search-index-db.ts", // WIP
- "src/lib/search-index-client.ts", // WIP
- ],
- ignoreDependencies: [
- "openai",
- "undici-types",
- "@pinecone-database/pinecone", // WIP
+ "src/scraper/scrapeURL/engines/fire-engine/branding-script/**",
],
+ ignoreDependencies: ["openai", "undici-types"],
};
export default config;
diff --git a/apps/api/package.json b/apps/api/package.json
index 159a948a5..cd84ed401 100644
--- a/apps/api/package.json
+++ b/apps/api/package.json
@@ -13,6 +13,7 @@
"flyio": "node dist/src/index.js",
"start:dev": "tsc-watch --onSuccess \"node dist/src/index.js\"",
"build": "tsc",
+ "branding:print": "node src/scraper/scrapeURL/engines/fire-engine/branding-script/print-script.js",
"build:nosentry": "tsc",
"test": "jest --testPathIgnorePatterns=\"src/__tests__/e2e_noAuth/*\"",
"test:local-no-auth": "jest --testPathIgnorePatterns=\"src/__tests__/e2e_withAuth/*\"",
@@ -101,6 +102,7 @@
"cors": "^2.8.5",
"culori": "^4.0.2",
"dotenv": "^16.3.1",
+ "esbuild": "^0.27.2",
"escape-html": "^1.0.3",
"express": "4.22.0",
"express-ws": "^5.0.2",
diff --git a/apps/api/pnpm-lock.yaml b/apps/api/pnpm-lock.yaml
index 26c94717b..9a0e402fb 100644
--- a/apps/api/pnpm-lock.yaml
+++ b/apps/api/pnpm-lock.yaml
@@ -112,6 +112,9 @@ importers:
dotenv:
specifier: ^16.3.1
version: 16.4.5
+ esbuild:
+ specifier: ^0.27.2
+ version: 0.27.2
escape-html:
specifier: ^1.0.3
version: 1.0.3
@@ -292,7 +295,7 @@ importers:
version: 6.3.4
ts-jest:
specifier: ^29.4.5
ts-node:
specifier: ^10.9.1
version: 10.9.2(@types/[email protected])([email protected])
@@ -717,156 +720,312 @@ packages:
cpu: [ppc64]
os: [aix]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-GZMB+a0mOMZs4MpDbj8RJp4cw+w1WV5NYD6xzgvzUJ5Ek2jerwfO2eADyI6ExDSUED+1X8aMbegahsJi+8mgpw==}
+ engines: {node: '>=18'}
+ cpu: [ppc64]
+ os: [aix]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-OD3p7LYzWpLhZEyATcTSJ67qB5D+20vbtr6vHlHWSQYhKtzUYrETuWThmzFpZtFsBIxRvhO07+UgVA9m0i/O1w==}
engines: {node: '>=18'}
cpu: [arm64]
os: [android]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-pvz8ZZ7ot/RBphf8fv60ljmaoydPU12VuXHImtAs0XhLLw+EXBi2BLe3OYSBslR4rryHvweW5gmkKFwTiFy6KA==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [android]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-RONsAvGCz5oWyePVnLdZY/HHwA++nxYWIX1atInlaW6SEkwq6XkP3+cb825EUcRs5Vss/lGh/2YxAb5xqc07Uw==}
engines: {node: '>=18'}
cpu: [arm]
os: [android]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-DVNI8jlPa7Ujbr1yjU2PfUSRtAUZPG9I1RwW4F4xFB1Imiu2on0ADiI/c3td+KmDtVKNbi+nffGDQMfcIMkwIA==}
+ engines: {node: '>=18'}
+ cpu: [arm]
+ os: [android]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-yJAVPklM5+4+9dTeKwHOaA+LQkmrKFX96BM0A/2zQrbS6ENCmxc4OVoBs5dPkCCak2roAD+jKCdnmOqKszPkjA==}
engines: {node: '>=18'}
cpu: [x64]
os: [android]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-z8Ank4Byh4TJJOh4wpz8g2vDy75zFL0TlZlkUkEwYXuPSgX8yzep596n6mT7905kA9uHZsf/o2OJZubl2l3M7A==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [android]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-Jw0mxgIaYX6R8ODrdkLLPwBqHTtYHJSmzzd+QeytSugzQ0Vg4c5rDky5VgkoowbZQahCbsv1rT1KW72MPIkevw==}
engines: {node: '>=18'}
cpu: [arm64]
os: [darwin]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-davCD2Zc80nzDVRwXTcQP/28fiJbcOwvdolL0sOiOsbwBa72kegmVU0Wrh1MYrbuCL98Omp5dVhQFWRKR2ZAlg==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [darwin]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-Vh2gLxxHnuoQ+GjPNvDSDRpoBCUzY4Pu0kBqMBDlK4fuWbKgGtmDIeEC081xi26PPjn+1tct+Bh8FjyLlw1Zlg==}
engines: {node: '>=18'}
cpu: [x64]
os: [darwin]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-ZxtijOmlQCBWGwbVmwOF/UCzuGIbUkqB1faQRf5akQmxRJ1ujusWsb3CVfk/9iZKr2L5SMU5wPBi1UWbvL+VQA==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [darwin]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-YPJ7hDQ9DnNe5vxOm6jaie9QsTwcKedPvizTVlqWG9GBSq+BuyWEDazlGaDTC5NGU4QJd666V0yqCBL2oWKPfA==}
engines: {node: '>=18'}
cpu: [arm64]
os: [freebsd]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-lS/9CN+rgqQ9czogxlMcBMGd+l8Q3Nj1MFQwBZJyoEKI50XGxwuzznYdwcav6lpOGv5BqaZXqvBSiB/kJ5op+g==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [freebsd]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-MmaEXxQRdXNFsRN/KcIimLnSJrk2r5H8v+WVafRWz5xdSVmWLoITZQXcgehI2ZE6gioE6HirAEToM/RvFBeuhw==}
engines: {node: '>=18'}
cpu: [x64]
os: [freebsd]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-tAfqtNYb4YgPnJlEFu4c212HYjQWSO/w/h/lQaBK7RbwGIkBOuNKQI9tqWzx7Wtp7bTPaGC6MJvWI608P3wXYA==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [freebsd]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-WIgg00ARWv/uYLU7lsuDK00d/hHSfES5BzdWAdAig1ioV5kaFNrtK8EqGcUBJhYqotlUByUKz5Qo6u8tt7iD/w==}
engines: {node: '>=18'}
cpu: [arm64]
os: [linux]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-hYxN8pr66NsCCiRFkHUAsxylNOcAQaxSSkHMMjcpx0si13t1LHFphxJZUiGwojB1a/Hd5OiPIqDdXONia6bhTw==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [linux]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-FuzEP9BixzZohl1kLf76KEVOsxtIBFwCaLupVuk4eFVnOZfU+Wsn+x5Ryam7nILV2pkq2TqQM9EZPsOBuMC+kg==}
engines: {node: '>=18'}
cpu: [arm]
os: [linux]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-vWfq4GaIMP9AIe4yj1ZUW18RDhx6EPQKjwe7n8BbIecFtCQG4CfHGaHuh7fdfq+y3LIA2vGS/o9ZBGVxIDi9hw==}
+ engines: {node: '>=18'}
+ cpu: [arm]
+ os: [linux]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-A1D9YzRX1i+1AJZuFFUMP1E9fMaYY+GnSQil9Tlw05utlE86EKTUA7RjwHDkEitmLYiFsRd9HwKBPEftNdBfjg==}
engines: {node: '>=18'}
cpu: [ia32]
os: [linux]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-MJt5BRRSScPDwG2hLelYhAAKh9imjHK5+NE/tvnRLbIqUWa+0E9N4WNMjmp/kXXPHZGqPLxggwVhz7QP8CTR8w==}
+ engines: {node: '>=18'}
+ cpu: [ia32]
+ os: [linux]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-O7k1J/dwHkY1RMVvglFHl1HzutGEFFZ3kNiDMSOyUrB7WcoHGf96Sh+64nTRT26l3GMbCW01Ekh/ThKM5iI7hQ==}
engines: {node: '>=18'}
cpu: [loong64]
os: [linux]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-lugyF1atnAT463aO6KPshVCJK5NgRnU4yb3FUumyVz+cGvZbontBgzeGFO1nF+dPueHD367a2ZXe1NtUkAjOtg==}
+ engines: {node: '>=18'}
+ cpu: [loong64]
+ os: [linux]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-uv+dqfRazte3BzfMp8PAQXmdGHQt2oC/y2ovwpTteqrMx2lwaksiFZ/bdkXJC19ttTvNXBuWH53zy/aTj1FgGw==}
engines: {node: '>=18'}
cpu: [mips64el]
os: [linux]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-nlP2I6ArEBewvJ2gjrrkESEZkB5mIoaTswuqNFRv/WYd+ATtUpe9Y09RnJvgvdag7he0OWgEZWhviS1OTOKixw==}
+ engines: {node: '>=18'}
+ cpu: [mips64el]
+ os: [linux]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-GyG0KcMi1GBavP5JgAkkstMGyMholMDybAf8wF5A70CALlDM2p/f7YFE7H92eDeH/VBtFJA5MT4nRPDGg4JuzQ==}
engines: {node: '>=18'}
cpu: [ppc64]
os: [linux]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-C92gnpey7tUQONqg1n6dKVbx3vphKtTHJaNG2Ok9lGwbZil6DrfyecMsp9CrmXGQJmZ7iiVXvvZH6Ml5hL6XdQ==}
+ engines: {node: '>=18'}
+ cpu: [ppc64]
+ os: [linux]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-rAqDYFv3yzMrq7GIcen3XP7TUEG/4LK86LUPMIz6RT8A6pRIDn0sDcvjudVZBiiTcZCY9y2SgYX2lgK3AF+1eg==}
engines: {node: '>=18'}
cpu: [riscv64]
os: [linux]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-B5BOmojNtUyN8AXlK0QJyvjEZkWwy/FKvakkTDCziX95AowLZKR6aCDhG7LeF7uMCXEJqwa8Bejz5LTPYm8AvA==}
+ engines: {node: '>=18'}
+ cpu: [riscv64]
+ os: [linux]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-Xutvh6VjlbcHpsIIbwY8GVRbwoviWT19tFhgdA7DlenLGC/mbc3lBoVb7jxj9Z+eyGqvcnSyIltYUrkKzWqSvg==}
engines: {node: '>=18'}
cpu: [s390x]
os: [linux]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-p4bm9+wsPwup5Z8f4EpfN63qNagQ47Ua2znaqGH6bqLlmJ4bx97Y9JdqxgGZ6Y8xVTixUnEkoKSHcpRlDnNr5w==}
+ engines: {node: '>=18'}
+ cpu: [s390x]
+ os: [linux]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-ASFQhgY4ElXh3nDcOMTkQero4b1lgubskNlhIfJrsH5OKZXDpUAKBlNS0Kx81jwOBp+HCeZqmoJuihTv57/jvQ==}
engines: {node: '>=18'}
cpu: [x64]
os: [linux]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-uwp2Tip5aPmH+NRUwTcfLb+W32WXjpFejTIOWZFw/v7/KnpCDKG66u4DLcurQpiYTiYwQ9B7KOeMJvLCu/OvbA==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [linux]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-d1KfruIeohqAi6SA+gENMuObDbEjn22olAR7egqnkCD9DGBG0wsEARotkLgXDu6c4ncgWTZJtN5vcgxzWRMzcw==}
engines: {node: '>=18'}
cpu: [arm64]
os: [netbsd]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-Kj6DiBlwXrPsCRDeRvGAUb/LNrBASrfqAIok+xB0LxK8CHqxZ037viF13ugfsIpePH93mX7xfJp97cyDuTZ3cw==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [netbsd]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-nVDCkrvx2ua+XQNyfrujIG38+YGyuy2Ru9kKVNyh5jAys6n+l44tTtToqHjino2My8VAY6Lw9H7RI73XFi66Cg==}
engines: {node: '>=18'}
cpu: [x64]
os: [netbsd]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-HwGDZ0VLVBY3Y+Nw0JexZy9o/nUAWq9MlV7cahpaXKW6TOzfVno3y3/M8Ga8u8Yr7GldLOov27xiCnqRZf0tCA==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [netbsd]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-j8HgrDuSJFAujkivSMSfPQSAa5Fxbvk4rgNAS5i3K+r8s1X0p1uOO2Hl2xNsGFppOeHOLAVgYwDVlmxhq5h+SQ==}
engines: {node: '>=18'}
cpu: [arm64]
os: [openbsd]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-DNIHH2BPQ5551A7oSHD0CKbwIA/Ox7+78/AWkbS5QoRzaqlev2uFayfSxq68EkonB+IKjiuxBFoV8ESJy8bOHA==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [openbsd]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-1h8MUAwa0VhNCDp6Af0HToI2TJFAn1uqT9Al6DJVzdIBAd21m/G0Yfc77KDM3uF3T/YaOgQq3qTJHPbTOInaIQ==}
engines: {node: '>=18'}
cpu: [x64]
os: [openbsd]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-/it7w9Nb7+0KFIzjalNJVR5bOzA9Vay+yIPLVHfIQYG/j+j9VTH84aNB8ExGKPU4AzfaEvN9/V4HV+F+vo8OEg==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [openbsd]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-r2nVa5SIK9tSWd0kJd9HCffnDHKchTGikb//9c7HX+r+wHYCpQrSgxhlY6KWV1nFo1l4KFbsMlHk+L6fekLsUg==}
engines: {node: '>=18'}
cpu: [arm64]
os: [openharmony]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-LRBbCmiU51IXfeXk59csuX/aSaToeG7w48nMwA6049Y4J4+VbWALAuXcs+qcD04rHDuSCSRKdmY63sruDS5qag==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [openharmony]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-zUlaP2S12YhQ2UzUfcCuMDHQFJyKABkAjvO5YSndMiIkMimPmxA+BYSBikWgsRpvyxuRnow4nS5NPnf9fpv41w==}
engines: {node: '>=18'}
cpu: [x64]
os: [sunos]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-kMtx1yqJHTmqaqHPAzKCAkDaKsffmXkPHThSfRwZGyuqyIeBvf08KSsYXl+abf5HDAPMJIPnbBfXvP2ZC2TfHg==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [sunos]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-YEGFFWESlPva8hGL+zvj2z/SaK+pH0SwOM0Nc/d+rVnW7GSTFlLBGzZkuSU9kFIGIo8q9X3ucpZhu8PDN5A2sQ==}
engines: {node: '>=18'}
cpu: [arm64]
os: [win32]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-Yaf78O/B3Kkh+nKABUF++bvJv5Ijoy9AN1ww904rOXZFLWVc5OLOfL56W+C8F9xn5JQZa3UX6m+IktJnIb1Jjg==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [win32]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-hiGgGC6KZ5LZz58OL/+qVVoZiuZlUYlYHNAmczOm7bs2oE1XriPFi5ZHHrS8ACpV5EjySrnoCKmcbQMN+ojnHg==}
engines: {node: '>=18'}
cpu: [ia32]
os: [win32]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-Iuws0kxo4yusk7sw70Xa2E2imZU5HoixzxfGCdxwBdhiDgt9vX9VUCBhqcwY7/uh//78A1hMkkROMJq9l27oLQ==}
+ engines: {node: '>=18'}
+ cpu: [ia32]
+ os: [win32]
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-cn3Yr7+OaaZq1c+2pe+8yxC8E144SReCQjN6/2ynubzYjvyqZjTXfQJpAcQpsdJq3My7XADANiYGHoFC69pLQw==}
engines: {node: '>=18'}
cpu: [x64]
os: [win32]
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-sRdU18mcKf7F+YgheI/zGf5alZatMUTKj/jNS6l744f9u3WFu4v7twcUI9vu4mknF4Y9aDlblIie0IM+5xxaqQ==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [win32]
+
'@ethereumjs/[email protected]':
resolution: {integrity: sha512-pksvzI0VyLgmuEF2FA/JR/4/y6hcPq8OUail3/AvycBaW1d5VSauOZzqGvJ3RTmR4MU35lWE8KseKOsEhrFRBA==}
@@ -3842,6 +4001,11 @@ packages:
engines: {node: '>=18'}
hasBin: true
+ resolution: {integrity: sha512-HyNQImnsOC7X9PMNaCIeAm4ISCQXs5a5YasTXVliKv4uuBo1dKrG0A+uQS8M5eXjVMnLg3WgXaKvprHlFJQffw==}
+ engines: {node: '>=18'}
+ hasBin: true
+
resolution: {integrity: sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==}
engines: {node: '>=6'}
@@ -7064,81 +7228,159 @@ snapshots:
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@esbuild/[email protected]':
optional: true
+ '@esbuild/[email protected]':
+ optional: true
+
'@ethereumjs/[email protected]':
dependencies:
'@ethereumjs/util': 8.1.0
@@ -11155,6 +11397,35 @@ snapshots:
'@esbuild/win32-ia32': 0.25.8
'@esbuild/win32-x64': 0.25.8
+ optionalDependencies:
+ '@esbuild/aix-ppc64': 0.27.2
+ '@esbuild/android-arm': 0.27.2
+ '@esbuild/android-arm64': 0.27.2
+ '@esbuild/android-x64': 0.27.2
+ '@esbuild/darwin-arm64': 0.27.2
+ '@esbuild/darwin-x64': 0.27.2
+ '@esbuild/freebsd-arm64': 0.27.2
+ '@esbuild/freebsd-x64': 0.27.2
+ '@esbuild/linux-arm': 0.27.2
+ '@esbuild/linux-arm64': 0.27.2
+ '@esbuild/linux-ia32': 0.27.2
+ '@esbuild/linux-loong64': 0.27.2
+ '@esbuild/linux-mips64el': 0.27.2
+ '@esbuild/linux-ppc64': 0.27.2
+ '@esbuild/linux-riscv64': 0.27.2
+ '@esbuild/linux-s390x': 0.27.2
+ '@esbuild/linux-x64': 0.27.2
+ '@esbuild/netbsd-arm64': 0.27.2
+ '@esbuild/netbsd-x64': 0.27.2
+ '@esbuild/openbsd-arm64': 0.27.2
+ '@esbuild/openbsd-x64': 0.27.2
+ '@esbuild/openharmony-arm64': 0.27.2
+ '@esbuild/sunos-x64': 0.27.2
+ '@esbuild/win32-arm64': 0.27.2
+ '@esbuild/win32-ia32': 0.27.2
+ '@esbuild/win32-x64': 0.27.2
+
@@ -13701,7 +13972,7 @@ snapshots:
dependencies:
bs-logger: 0.2.6
fast-json-stable-stringify: 2.1.0
@@ -13719,6 +13990,7 @@ snapshots:
'@jest/transform': 30.2.0
'@jest/types': 30.2.0
babel-jest: 30.2.0(@babel/[email protected])
+ esbuild: 0.27.2
jest-util: 30.2.0
diff --git a/apps/api/src/controllers/v1/types.ts b/apps/api/src/controllers/v1/types.ts
index dc7156407..0ab6df618 100644
--- a/apps/api/src/controllers/v1/types.ts
+++ b/apps/api/src/controllers/v1/types.ts
@@ -1268,6 +1268,7 @@ export type TeamFlags = {
extractV3Beta?: boolean;
agentBeta?: boolean;
bypassCreditChecks?: boolean;
+ debugBranding?: boolean;
} | null;
export type AuthCreditUsageChunkFromTeam = Omit<
diff --git a/apps/api/src/controllers/v2/types.ts b/apps/api/src/controllers/v2/types.ts
index 0393a080c..2712b40e4 100644
--- a/apps/api/src/controllers/v2/types.ts
+++ b/apps/api/src/controllers/v2/types.ts
@@ -1256,6 +1256,7 @@ export type TeamFlags = {
crawlTtlHours?: number;
ipWhitelist?: boolean;
bypassCreditChecks?: boolean;
+ debugBranding?: boolean;
} | null;
interface RequestWithMaybeACUC<
diff --git a/apps/api/src/lib/branding/extractHeaderHtmlChunk.ts b/apps/api/src/lib/branding/extractHeaderHtmlChunk.ts
new file mode 100644
index 000000000..132b03fbc
--- /dev/null
+++ b/apps/api/src/lib/branding/extractHeaderHtmlChunk.ts
@@ -0,0 +1,50 @@
+/**
+ * Extract a small chunk of HTML from the top/header area for LLM context when
+ * no logo candidates were found. Helps the LLM infer brand name and note that
+ * a logo may exist but wasn't captured (e.g. inline SVG, shadow DOM).
+ *
+ * Strategy: strip noise, find header/nav/body start, take first N chars.
+ */
+
+const MAX_HEADER_CHUNK_CHARS = 5500;
+
+/**
+ * Remove script and style tags and their content, and HTML comments.
+ * Uses regex; safe for typical page header content.
+ */
+function stripNoise(html: string): string {
+ let out = html;
+ // Comments
+ out = out.replace(/<!--[\s\S]*?-->/g, "");
+ // Scripts (non-greedy to first </script>)
+ out = out.replace(/<script\b[\s\S]*?<\/script>/gi, "");
+ // Styles
+ out = out.replace(/<style\b[\s\S]*?<\/style>/gi, "");
+ return out;
+}
+
+/**
+ * Find the earliest start of header-like content: <header, <nav, or <body.
+ * Returns index into html, or 0 if not found.
+ */
+function findHeaderStart(html: string): number {
+ const lower = html.toLowerCase();
+ const header = lower.indexOf("<header");
+ const nav = lower.indexOf("<nav");
+ const body = lower.indexOf("<body");
+ const indices = [header, nav, body].filter(i => i >= 0);
+ return indices.length > 0 ? Math.min(...indices) : 0;
+}
+
+/**
+ * Extract a single chunk of HTML useful for logo/brand context: header/nav
+ * area, stripped of scripts/styles/comments, length-limited.
+ * Use only when there are no logo candidates so the LLM has fallback context.
+ */
+export function extractHeaderHtmlChunk(html: string): string {
+ if (!html || typeof html !== "string") return "";
+ const stripped = stripNoise(html);
+ const start = findHeaderStart(stripped);
+ const chunk = stripped.slice(start, start + MAX_HEADER_CHUNK_CHARS);
+ return chunk.replace(/\s+/g, " ").trim();
+}
diff --git a/apps/api/src/lib/branding/llm.ts b/apps/api/src/lib/branding/llm.ts
index 35d3f0dc3..4add8852f 100644
--- a/apps/api/src/lib/branding/llm.ts
+++ b/apps/api/src/lib/branding/llm.ts
@@ -2,11 +2,17 @@ import { generateObject } from "ai";
import * as Sentry from "@sentry/node";
import { logger } from "../logger";
import { config } from "../../config";
-import { BrandingEnhancement, brandingEnhancementSchema } from "./schema";
+import { BrandingEnhancement, getBrandingEnhancementSchema } from "./schema";
import { buildBrandingPrompt } from "./prompt";
import { BrandingLLMInput } from "./types";
import { getModel } from "../generic-ai";
+function isDebugBrandingEnabled(input: BrandingLLMInput): boolean {
+ return (
+ config.DEBUG_BRANDING === true || input.teamFlags?.debugBranding === true
+ );
+}
+
export async function enhanceBrandingWithLLM(
input: BrandingLLMInput,
): Promise<BrandingEnhancement> {
@@ -19,21 +25,33 @@ export async function enhanceBrandingWithLLM(
const logoCandidatesCount = input.logoCandidates?.length || 0;
const promptLength = prompt.length;
- // Use gpt-4o for complex cases:
- // - Many buttons (>8)
- // - Many logo candidates (>5)
+ // Use gpt-4o for complex/visual cases (better vision and reasoning):
+ // - Has screenshot (vision task – gpt-4o has strong visual capabilities)
+ // - Many buttons (>8) or logo candidates (>5)
// - Long prompt (>8000 chars)
- // - Has screenshot (adds complexity)
const isComplexCase =
+ !!input.screenshot ||
buttonsCount > 8 ||
logoCandidatesCount > 5 ||
- promptLength > 8000 ||
- !!input.screenshot;
+ promptLength > 8000;
const modelName = isComplexCase ? "gpt-4o" : "gpt-4o-mini";
const model = getModel(modelName);
- if (config.DEBUG_BRANDING === true) {
+ if (isDebugBrandingEnabled(input)) {
+ const logoCandidates = input.logoCandidates || [];
+ const logoCandidateFiles = logoCandidates.map(candidate => ({
+ src: candidate.src,
+ href: candidate.href,
+ alt: candidate.alt,
+ location: candidate.location,
+ width: Math.round(candidate.position?.width || 0),
+ height: Math.round(candidate.position?.height || 0),
+ isSvg: candidate.isSvg,
+ indicators: candidate.indicators,
+ }));
+ const screenshotLength = input.screenshot ? input.screenshot.length : 0;
+
logger.info("LLM model selection", {
model: modelName,
buttonsCount,
@@ -43,6 +61,16 @@ export async function enhanceBrandingWithLLM(
isComplexCase,
});
+ logger.info("LLM branding prompt (full)", { prompt });
+ logger.info("LLM branding input files", {
+ logoCandidates: logoCandidateFiles,
+ screenshot: {
+ provided: !!input.screenshot,
+ length: screenshotLength,
+ preview: input.screenshot ? input.screenshot.slice(0, 48) + "..." : "",
+ },
+ });
+
logger.debug("LLM branding prompt preview", {
promptStart: prompt.substring(0, 500),
promptEnd: prompt.substring(prompt.length - 500),
@@ -54,12 +82,20 @@ export async function enhanceBrandingWithLLM(
}
try {
+ // Use schema with logoSelection only if logo candidates are provided
+ const hasLogoCandidates = !!(
+ input.logoCandidates && input.logoCandidates.length > 0
+ );
+ const schema = getBrandingEnhancementSchema(hasLogoCandidates);
+
const result = await generateObject({
model,
- schema: brandingEnhancementSchema,
+ schema,
providerOptions: {
openai: {
- strictJsonSchema: true,
+ // Prefer loose schema so we use whatever the LLM returns (avoids validation
+ // failures on minor schema drift or when model omits optional fields).
+ strictJsonSchema: false,
},
},
messages: [
@@ -88,13 +124,16 @@ export async function enhanceBrandingWithLLM(
},
});
- if (config.DEBUG_BRANDING === true) {
+ if (isDebugBrandingEnabled(input)) {
const reasoningPreview = result.reasoning
? result.reasoning.length > 1000
? result.reasoning.substring(0, 1000) + "..."
: result.reasoning
: undefined;
+ // Type assertion to handle optional logoSelection
+ const resultObject = result.object as BrandingEnhancement;
+
logger.info("LLM branding response", {
model: modelName,
buttonsCount,
@@ -106,12 +145,12 @@ export async function enhanceBrandingWithLLM(
reasoning: reasoningPreview,
reasoningLength: result.reasoning?.length || 0,
warnings: result.warnings,
- hasObject: !!result.object,
- objectKeys: result.object ? Object.keys(result.object) : [],
- buttonClassification: result.object?.buttonClassification,
- colorRoles: result.object?.colorRoles,
- cleanedFontsLength: result.object?.cleanedFonts?.length || 0,
- logoSelection: result.object?.logoSelection,
+ hasObject: !!resultObject,
+ objectKeys: resultObject ? Object.keys(resultObject) : [],
+ buttonClassification: resultObject?.buttonClassification,
+ colorRoles: resultObject?.colorRoles,
+ cleanedFontsLength: resultObject?.cleanedFonts?.length || 0,
+ logoSelection: resultObject?.logoSelection,
});
if (result.reasoning && result.reasoning.length > 1000) {
@@ -121,15 +160,53 @@ export async function enhanceBrandingWithLLM(
}
}
- return result.object;
+ // When there are no logo candidates, do not pass logoSelection so downstream treats it as "none"
+ const resultObject = result.object as BrandingEnhancement;
+ if (!hasLogoCandidates && resultObject?.logoSelection != null) {
+ const { logoSelection: _, ...rest } = resultObject;
+ return rest as BrandingEnhancement;
+ }
+ return resultObject;
} catch (error) {
- Sentry.captureException(error);
+ // Refusal: API returned content type "refusal" (e.g. "I can't assist with that") but the SDK
+ // expects "output_text", so it throws before we get a result. Treat as soft failure, not a bug.
+ const message = error instanceof Error ? error.message : String(error);
+ const causeMessage =
+ error instanceof Error && error.cause instanceof Error
+ ? (error.cause as Error).message
+ : "";
+ const isRefusalOrOutputValidation =
+ /output_text|refusal|Invalid input: expected/i.test(message) ||
+ /output_text|refusal|Invalid input: expected/i.test(causeMessage);
- logger.error("LLM branding enhancement failed", {
- error,
- buttonsCount: input.buttons?.length || 0,
- promptLength: prompt.length,
- });
+ if (isRefusalOrOutputValidation) {
+ logger.info(
+ "LLM branding: model refused or returned invalid format, using fallback",
+ {
+ reason: "refusal_or_invalid_output",
+ buttonsCount: input.buttons?.length || 0,
+ promptLength: prompt.length,
+ },
+ );
+ } else {
+ Sentry.withScope(scope => {
+ scope.setTag("feature", "branding-llm");
+ scope.setTag("model", modelName);
+ scope.setContext("branding_llm", {
+ url: input.url,
+ buttonsCount: input.buttons?.length || 0,
+ logoCandidatesCount: input.logoCandidates?.length || 0,
+ promptLength: prompt.length,
+ hasScreenshot: !!input.screenshot,
+ });
+ Sentry.captureException(error);
+ });
+ logger.error("LLM branding enhancement failed", {
+ error,
+ buttonsCount: input.buttons?.length || 0,
+ promptLength: prompt.length,
+ });
+ }
return {
cleanedFonts: [],
@@ -141,6 +218,24 @@ export async function enhanceBrandingWithLLM(
confidence: 0,
},
colorRoles: {
+ primaryColor: "",
+ accentColor: "",
+ backgroundColor: "",
+ textPrimary: "",
+ confidence: 0,
+ },
+ personality: {
+ tone: "professional",
+ energy: "medium",
+ targetAudience: "unknown",
+ },
+ designSystem: {
+ framework: "unknown",
+ componentLibrary: "",
+ },
+ logoSelection: {
+ selectedLogoIndex: -1,
+ selectedLogoReasoning: "LLM failed",
confidence: 0,
},
};
diff --git a/apps/api/src/lib/branding/logo-selector.ts b/apps/api/src/lib/branding/logo-selector.ts
index 7b33f59f1..cae15f7d7 100644
--- a/apps/api/src/lib/branding/logo-selector.ts
+++ b/apps/api/src/lib/branding/logo-selector.ts
@@ -1,7 +1,7 @@
import { logger } from "../logger";
import { calculateLogoArea } from "./types";
-interface LogoCandidate {
+export interface LogoCandidate {
src: string;
alt: string;
isSvg: boolean;
@@ -36,7 +36,6 @@ const CONFIDENCE_THRESHOLDS = {
GOOD_CONFIDENCE: 0.75,
MODERATE_CONFIDENCE: 0.6,
WEAK_CONFIDENCE: 0.4,
- LLM_THRESHOLD: 0.85,
} as const;
/**
@@ -179,8 +178,7 @@ function detectRepeatedLogos(candidates: LogoCandidate[]): Set<number> {
candidates.forEach((candidate, index) => {
const srcKey =
- candidate.src.split("?")[0].split("/").pop()?.toLowerCase() ||
- candidate.src;
+ extractFilename(candidate.src)?.toLowerCase() || candidate.src;
if (!srcGroups.has(srcKey)) {
srcGroups.set(srcKey, []);
}
@@ -281,6 +279,9 @@ export function selectLogoWithConfidence(
if (candidate.isVisible) {
score += 15;
reasons.push("visible");
+ } else {
+ score -= 25;
+ reasons.push("invisible (hidden/minimized variant, heavy penalty)");
}
if (candidate.position.top < 100 && candidate.position.left < 300) {
@@ -373,11 +374,6 @@ export function selectLogoWithConfidence(
reasons.push("body location without header (penalty)");
}
- if (!candidate.isVisible) {
- score -= 10;
- reasons.push("not visible (penalty)");
- }
-
return {
index,
score,
@@ -444,13 +440,6 @@ export function selectLogoWithConfidence(
};
}
-/**
- * Determine if LLM validation is needed based on heuristic confidence
- */
-export function shouldUseLLMForLogoSelection(confidence: number): boolean {
- return confidence < CONFIDENCE_THRESHOLDS.LLM_THRESHOLD;
-}
-
/**
* Get top N candidates for LLM validation (when needed)
* Returns the highest-scoring candidates to reduce token usage
@@ -485,6 +474,9 @@ export function getTopCandidatesForLLM(
if (candidate.indicators.srcMatch) score += 10;
if (candidate.indicators.altMatch) score += 5;
+ // Main document images are often the primary brand logo
+ if (candidate.source === "document.images") score += 15;
+
return { originalIndex, score, candidate };
});
diff --git a/apps/api/src/lib/branding/merge.ts b/apps/api/src/lib/branding/merge.ts
index 5234a5eb4..f454763af 100644
--- a/apps/api/src/lib/branding/merge.ts
+++ b/apps/api/src/lib/branding/merge.ts
@@ -1,37 +1,30 @@
import { BrandingProfile } from "../../types/branding";
+import { LogoCandidate } from "./logo-selector";
import { BrandingEnhancement } from "./schema";
import { ButtonSnapshot, calculateLogoArea } from "./types";
+import { logger } from "../logger";
export function mergeBrandingResults(
js: BrandingProfile,
llm: BrandingEnhancement,
buttonSnapshots: ButtonSnapshot[],
- logoCandidates?: Array<{
- src: string;
- alt: string;
- isSvg: boolean;
- isVisible: boolean;
- location: "header" | "body" | "footer";
- position: { top: number; left: number; width: number; height: number };
- indicators: {
- inHeader: boolean;
- altMatch: boolean;
- srcMatch: boolean;
- classMatch: boolean;
- hrefMatch: boolean;
- };
- href?: string;
- source: string;
- }>,
+ logoCandidates?: LogoCandidate[],
): BrandingProfile {
const merged: BrandingProfile = { ...js };
- // Handle logo selection: if LLM says no logo (-1), clear it
- if (llm.logoSelection && llm.logoSelection.selectedLogoIndex !== undefined) {
+ // Handle logo selection only when we had logo candidates; ignore logoSelection when there were none
+ const hasLogoCandidates = !!(logoCandidates && logoCandidates.length > 0);
+ if (
+ hasLogoCandidates &&
+ llm.logoSelection &&
+ llm.logoSelection.selectedLogoIndex !== undefined
+ ) {
// If LLM explicitly says no logo (returns -1), remove any logo that was set
if (llm.logoSelection.selectedLogoIndex === -1) {
if (merged.images) {
delete merged.images.logo;
+ delete merged.images.logoHref;
+ delete merged.images.logoAlt;
}
(merged as any).__llm_logo_reasoning = {
selectedIndex: -1,
@@ -39,6 +32,7 @@ export function mergeBrandingResults(
llm.logoSelection.selectedLogoReasoning || "No valid logo found",
confidence: llm.logoSelection.confidence || 0,
rejected: true,
+ source: "llm",
};
}
// If LLM selected a valid logo index
@@ -108,18 +102,15 @@ export function mergeBrandingResults(
const height = selectedLogo.position?.height || 0;
const isSmallSquareIcon =
Math.abs(width - height) < 5 && width < 40 && width > 0;
-
- const hasRedFlags =
- isLanguageWord ||
- isCommonMenuWord ||
- isUIIcon ||
- isSmallSquareIcon ||
- isExternalLink;
+ const trustLLMForLogo = confidence >= 0.7;
+ const smallSquareIconLikelyUi =
+ isSmallSquareIcon &&
+ !(trustLLMForLogo && selectedLogo.indicators?.inHeader);
// Only set logo if:
// 1. Confidence is good (>= 0.5) OR
// 2. Logo has very strong indicators (inHeader + hrefMatch + reasonable size)
- // AND no red flags
+ // AND no red flags (small square icons are allowed only with strong indicators)
const area = calculateLogoArea(selectedLogo.position);
const hasReasonableSize = area >= 500 && area <= 100000;
const hasStrongIndicators =
@@ -127,35 +118,70 @@ export function mergeBrandingResults(
selectedLogo.indicators?.hrefMatch &&
hasReasonableSize;
- const shouldIncludeLogo =
- !hasRedFlags &&
+ const reasoning = llm.logoSelection.selectedLogoReasoning ?? "";
+ const isHeuristicOrFallback =
+ reasoning.includes("Heuristic") ||
+ reasoning.includes("heuristic") ||
+ reasoning === "LLM failed" ||
+ reasoning.includes("invalid index");
+
+ // Trust LLM logo choice: don't reject for "small square icon" when LLM selected it
+ const smallSquareRedFlag =
+ smallSquareIconLikelyUi &&
+ !hasStrongIndicators &&
+ isHeuristicOrFallback;
+ const hasRedFlagsWithLLMTrust =
+ isLanguageWord ||
+ isCommonMenuWord ||
+ isUIIcon ||
+ smallSquareRedFlag ||
+ isExternalLink;
+ const shouldIncludeLogoWithLLMTrust =
+ !hasRedFlagsWithLLMTrust &&
(confidence >= 0.5 || (hasStrongIndicators && confidence >= 0.4));
- if (shouldIncludeLogo) {
+ if (shouldIncludeLogoWithLLMTrust) {
// Initialize images object if it doesn't exist
if (!merged.images) {
merged.images = {};
}
merged.images.logo = selectedLogo.src;
+ if (selectedLogo.href) {
+ merged.images.logoHref = selectedLogo.href;
+ } else {
+ delete merged.images.logoHref;
+ }
+ if (selectedLogo.alt) {
+ merged.images.logoAlt = selectedLogo.alt;
+ } else {
+ delete merged.images.logoAlt;
+ }
(merged as any).__llm_logo_reasoning = {
selectedIndex: llm.logoSelection.selectedLogoIndex,
reasoning: llm.logoSelection.selectedLogoReasoning,
confidence: llm.logoSelection.confidence,
+ source: isHeuristicOrFallback ? "heuristic" : "llm",
};
+ logger.debug("[branding merge] Logo included", {
+ result: "included",
+ selectedIndex: llm.logoSelection.selectedLogoIndex,
+ source: isHeuristicOrFallback ? "heuristic" : "llm",
+ confidence,
+ reasoning: (reasoning || "").slice(0, 120),
+ });
} else {
// Log why we're not including the logo
let rejectionReason = "Low confidence";
- if (hasRedFlags) {
- const redFlagReasons: string[] = [];
+ const redFlagReasons: string[] = [];
+ if (hasRedFlagsWithLLMTrust) {
if (isLanguageWord) redFlagReasons.push("language word");
if (isCommonMenuWord) redFlagReasons.push("menu word");
if (isUIIcon) redFlagReasons.push("UI icon");
- if (isSmallSquareIcon) redFlagReasons.push("small square icon");
+ if (smallSquareRedFlag) redFlagReasons.push("small square icon");
if (isExternalLink) redFlagReasons.push("external link");
rejectionReason = `Red flags detected (${redFlagReasons.join(", ")})`;
}
- const selectedLogoReasoning =
- llm.logoSelection.selectedLogoReasoning?.trim() || "";
+ const selectedLogoReasoning = reasoning.trim();
(merged as any).__llm_logo_reasoning = {
selectedIndex: llm.logoSelection.selectedLogoIndex,
reasoning: selectedLogoReasoning
@@ -163,7 +189,21 @@ export function mergeBrandingResults(
: `Logo rejected: ${rejectionReason}.`,
confidence: llm.logoSelection.confidence,
rejected: true,
+ source: isHeuristicOrFallback ? "heuristic" : "llm",
};
+ logger.debug("[branding merge] Logo rejected (override)", {
+ result: "rejected",
+ selectedIndex: llm.logoSelection.selectedLogoIndex,
+ source: isHeuristicOrFallback ? "heuristic" : "llm",
+ confidence,
+ hasRedFlags: hasRedFlagsWithLLMTrust,
+ redFlagReasons: redFlagReasons.length ? redFlagReasons : undefined,
+ confidenceOk:
+ confidence >= 0.5 || (hasStrongIndicators && confidence >= 0.4),
+ isHeuristicOrFallback,
+ smallSquareRedFlag,
+ reasoning: (reasoning || "").slice(0, 120),
+ });
}
}
}
diff --git a/apps/api/src/lib/branding/processor.ts b/apps/api/src/lib/branding/processor.ts
index b64a00312..3df7eb2f5 100644
--- a/apps/api/src/lib/branding/processor.ts
+++ b/apps/api/src/lib/branding/processor.ts
@@ -515,6 +515,7 @@ export function processRawBranding(raw: BrandingScriptReturn): BrandingProfile {
__button_snapshots: buttonSnapshots as any,
__input_snapshots: inputSnapshots as any,
__framework_hints: raw.frameworkHints as any,
+ __logo_candidates: raw.logoCandidates as any,
};
}
diff --git a/apps/api/src/lib/branding/prompt.ts b/apps/api/src/lib/branding/prompt.ts
index 44c7c417c..64ca9347e 100644
--- a/apps/api/src/lib/branding/prompt.ts
+++ b/apps/api/src/lib/branding/prompt.ts
@@ -8,11 +8,45 @@ export function buildBrandingPrompt(input: BrandingLLMInput): string {
buttons,
logoCandidates,
brandName,
+ pageTitle,
+ pageUrl,
backgroundCandidates,
url,
+ headerHtmlChunk,
+ favicon,
+ ogImage,
+ heuristicLogoPick,
} = input;
+ const normalizedBrandName = (brandName || "")
+ .toLowerCase()
+ .replace(/\s+/g, "");
+ const displayUrl = pageUrl || url;
+ const hasPageContext = !!(pageTitle || displayUrl);
+
+ let prompt = `Analyze the branding of this website`;
+ if (displayUrl) prompt += `: ${displayUrl}`;
+ prompt += `\n\n`;
+ if (hasPageContext) {
+ prompt += `## Page context (use to infer the site's brand)\n`;
+ if (displayUrl)
+ prompt += `- **URL** (final after redirects): ${displayUrl}\n`;
+ if (pageTitle) prompt += `- **Page title**: "${pageTitle}"\n`;
+ prompt += `Use the full page title and URL to infer the site's brand. Many sites use "Page Name | Brand" or "Brand - Page Name" — the brand is often the **second part** (e.g. "AI Innovation Workspace | Miro" → brand is Miro) or the **domain** from the URL. Pick the logo that matches the **actual brand** (from title/URL), not necessarily the first phrase in the title. Our heuristic brand name below is a hint; prefer your inference from title/URL when it makes more sense.\n\n`;
+ }
- let prompt = `Analyze the branding of this website: ${url}\n\n`;
+ const hasLogoCandidates = !!(logoCandidates && logoCandidates.length > 0);
+ if (!hasLogoCandidates) {
+ prompt += `## Logo candidates: None\n`;
+ prompt += `No logo candidates were extracted from this page. Do not return or attempt to select a logo. The response schema does not include logoSelection when there are no candidates.\n\n`;
+
+ if (headerHtmlChunk && headerHtmlChunk.length > 0) {
+ prompt += `## Page HTML (header/nav snippet)\n`;
+ prompt += `Below is a simplified snippet of the page header/nav area. Use it only for context:\n`;
+ prompt += `- **Brand name**: Infer from link text, aria-labels, or title attributes (e.g. \`<a aria-label="X logo">\`, \`<title>X</title>\`).\n`;
+ prompt += `- **Logo note**: If you see a logo-like element (e.g. \`<a aria-label*="logo">\`, \`<img>\` in header, inline \`<svg>\`) that wasn't captured as a candidate, you may note it in reasoning—but do NOT return a logo URL or index from this HTML. Only logo candidates (none here) can be selected.\n`;
+ prompt += `\n\`\`\`html\n${headerHtmlChunk}\n\`\`\`\n\n`;
+ }
+ }
// Add JS analysis context
prompt += `## JavaScript Analysis (Baseline):\n`;
@@ -94,6 +128,95 @@ export function buildBrandingPrompt(input: BrandingLLMInput): string {
};
};
+ const baseHostname = (() => {
+ try {
+ return new URL(displayUrl).hostname.toLowerCase();
+ } catch {
+ return "";
+ }
+ })();
+
+ const extractFilename = (src: string) => {
+ if (!src) return "";
+ const withoutQuery = src.split("?")[0].split("#")[0];
+ const parts = withoutQuery.split("/");
+ return parts.pop() || "";
+ };
+
+ const classifyHref = (href?: string, hrefMatch?: boolean) => {
+ if (!href || !href.trim()) return "none";
+ if (hrefMatch) return "home";
+ try {
+ const resolved = new URL(href, displayUrl);
+ if (!resolved.hostname || !baseHostname) return "internal";
+ return resolved.hostname.toLowerCase() === baseHostname
+ ? "internal"
+ : "external";
+ } catch {
+ return "unknown";
+ }
+ };
+
+ const getLogoCandidateMeta = (
+ candidate: NonNullable<BrandingLLMInput["logoCandidates"]>[number],
+ ) => {
+ const width = Math.max(0, Math.round(candidate.position?.width || 0));
+ const height = Math.max(0, Math.round(candidate.position?.height || 0));
+ const top = Math.max(0, Math.round(candidate.position?.top || 0));
+ const left = Math.max(0, Math.round(candidate.position?.left || 0));
+ const area = Math.max(0, Math.round(width * height));
+ const aspectRatio =
+ width && height ? Math.max(width / height, height / width) : 0;
+ const maxSide = Math.max(width, height);
+
+ let sizeLabel = "unknown";
+ if (maxSide <= 24 || area <= 400) sizeLabel = "tiny";
+ else if (maxSide <= 48 || area <= 1800) sizeLabel = "small";
+ else if (maxSide <= 140 || area <= 12000) sizeLabel = "medium";
+ else if (maxSide <= 320 || area <= 50000) sizeLabel = "large";
+ else sizeLabel = "hero";
+
+ const hrefType = classifyHref(
+ candidate.href,
+ candidate.indicators?.hrefMatch,
+ );
+ const srcFilename = extractFilename(candidate.src);
+ const filenameHasLogo = /logo|brand/i.test(srcFilename || "");
+ const srcHasLogo = /logo|brand/i.test(candidate.src);
+
+ const hints: string[] = [];
+ if (filenameHasLogo || srcHasLogo) hints.push("filename=logo");
+ if (sizeLabel === "tiny" || sizeLabel === "small") hints.push("icon-sized");
+ if (sizeLabel === "hero") hints.push("hero-sized");
+ if (aspectRatio >= 3 && width >= 80) hints.push("wordmark-shaped");
+ if (hrefType === "external") hints.push("external-link");
+ if (
+ normalizedBrandName &&
+ candidate.alt &&
+ candidate.alt
+ .toLowerCase()
+ .replace(/\s+/g, "")
+ .includes(normalizedBrandName)
+ ) {
+ hints.push("alt~=brand");
+ }
+ if (candidate.isSvg && candidate.logoSvgScore !== undefined) {
+ hints.push(`svgScore:${Math.round(candidate.logoSvgScore)}`);
+ }
+
+ return {
+ width,
+ height,
+ top,
+ left,
+ area,
+ aspectRatio,
+ sizeLabel,
+ hrefType,
+ hints,
+ };
+ };
+
// Collect class patterns for framework detection
const allClasses = new Set<string>();
if (buttons && buttons.length > 0) {
@@ -171,6 +294,14 @@ export function buildBrandingPrompt(input: BrandingLLMInput): string {
// Add logo candidates section (optimized - compact format)
if (logoCandidates && logoCandidates.length > 0) {
prompt += `\n## Logo Candidates (${logoCandidates.length}):\n`;
+ if (
+ heuristicLogoPick != null &&
+ heuristicLogoPick.selectedIndexInFilteredList >= 0 &&
+ heuristicLogoPick.selectedIndexInFilteredList < logoCandidates.length
+ ) {
+ prompt += `**Heuristic suggestion**: Our heuristic selected **Candidate #${heuristicLogoPick.selectedIndexInFilteredList}** (confidence: ${(heuristicLogoPick.confidence * 100).toFixed(0)}%). Reason: ${heuristicLogoPick.reasoning}\n\n`;
+ prompt += `**Your task**: Confirm this choice OR pick a different index. If you pick a different logo, you MUST explain why the heuristic was wrong and why your choice is better.\n\n`;
+ }
if (input.screenshot) {
prompt += `**IMPORTANT**: Look at the screenshot provided. The brand logo is almost always in the TOP/HEADER area of the page.\n`;
prompt += `Find the logo in the header area of the screenshot, then match it to one of the candidates below.\n\n`;
@@ -178,12 +309,25 @@ export function buildBrandingPrompt(input: BrandingLLMInput): string {
prompt += `**IMPORTANT**: The brand logo is almost always in the TOP/HEADER area of the page.\n`;
prompt += `Find the logo in the header area (usually the top of the page), then match it to one of the candidates below.\n\n`;
}
+ if (favicon) {
+ const faviconPreview =
+ favicon.length > 100 ? favicon.substring(0, 100) + "..." : favicon;
+ prompt += `**Favicon**: The site's favicon is: ${faviconPreview}\n`;
+ prompt += `The main logo is often the favicon image or favicon + wordmark. Prefer a candidate whose src matches or resembles the favicon (same domain/filename, or "Logo.svg"/wordmark in header with href=home). Do NOT pick a random header SVG that does not link to home and does not match the favicon/brand.\n\n`;
+ }
- if (brandName) {
- prompt += `Brand Name: "${brandName}" - The logo should visually represent or contain this name.\n\n`;
+ if (brandName || hasPageContext) {
+ if (hasPageContext) {
+ prompt += `**Brand**: Infer from page title/URL above (e.g. "X | Miro" → brand Miro). The logo should match that brand.\n`;
+ }
+ if (brandName) {
+ prompt += `Heuristic brand hint: "${brandName}" (from page meta/title — use only if it aligns with your inference from title/URL).\n\n`;
+ } else if (hasPageContext) {
+ prompt += `\n`;
+ }
}
- // Compact format: index, location, visible, alt, indicators, href, truncated URL
+ // Pass everything we get from the browser so the LLM can use all metadata (alt, aria-label, title, position, indicators, etc.)
logoCandidates.forEach((candidate, idx) => {
const indicators: string[] = [];
if (candidate.indicators.inHeader) indicators.push("header");
@@ -192,38 +336,75 @@ export function buildBrandingPrompt(input: BrandingLLMInput): string {
if (candidate.indicators.classMatch) indicators.push("class=logo");
if (candidate.indicators.hrefMatch) indicators.push("href=home");
+ const meta = getLogoCandidateMeta(candidate);
const urlPreview =
candidate.src.length > 80
? candidate.src.substring(0, 80) + "..."
: candidate.src;
- const hrefInfo = candidate.href ? ` | href:${candidate.href}` : "";
const typeLabel = candidate.isSvg ? "SVG" : "IMG";
-
- prompt += `#${idx}: ${candidate.location} | ${candidate.isVisible ? "visible" : "hidden"} | ${typeLabel} | alt:"${candidate.alt || ""}" | [${indicators.join(", ")}]${hrefInfo} | ${urlPreview}\n`;
+ const aspectLabel = meta.aspectRatio
+ ? meta.aspectRatio.toFixed(1)
+ : "n/a";
+ const hintLabel = meta.hints.length > 0 ? meta.hints.join(", ") : "none";
+ const sourceLabel = candidate.source ? `source:${candidate.source}` : "";
+ const svgScoreLabel =
+ candidate.logoSvgScore !== undefined
+ ? `logoSvgScore:${Math.round(candidate.logoSvgScore)}`
+ : "";
+
+ const pos = candidate.position;
+ const positionLabel =
+ pos != null
+ ? `top:${Math.round(pos.top ?? 0)} left:${Math.round(pos.left ?? 0)} width:${Math.round(pos.width ?? 0)} height:${Math.round(pos.height ?? 0)}`
+ : "n/a";
+
+ prompt += `\n**Logo Candidate #${idx}**\n`;
+ prompt += ` Metadata: alt:"${(candidate.alt || "").replace(/"/g, '\\"')}" | ariaLabel:"${(candidate.ariaLabel || "").replace(/"/g, '\\"')}" | title:"${(candidate.title || "").replace(/"/g, '\\"')}" | source:${candidate.source ?? "n/a"} | location:${candidate.location} | isVisible:${candidate.isVisible} | position:${positionLabel} | indicators:${JSON.stringify(candidate.indicators)}${svgScoreLabel ? ` | ${svgScoreLabel}` : ""}\n`;
+ prompt += ` Size: ${meta.width}x${meta.height} (${meta.sizeLabel}, area:${meta.area}, aspect:${aspectLabel}) | href:${meta.hrefType}${candidate.href ? ` | hrefUrl:${candidate.href.length > 60 ? candidate.href.substring(0, 60) + "..." : candidate.href}` : ""} | hints:[${hintLabel}]\n`;
+ prompt += ` Source URL: ${urlPreview}\n`;
});
- prompt += `\n**LOGO SELECTION - SIMPLE APPROACH:**\n`;
+ prompt += `\n**Candidate Hints (how to use them):**\n`;
+ prompt += `- alt, ariaLabel, title = text from the image/link (often the brand or "X logo"); use these to match the brand name\n`;
+ prompt += `- size labels: tiny/small are usually UI icons; hero-sized are usually hero images/banners\n`;
+ prompt += `- wordmark-shaped is OK if it is in header and links to homepage\n`;
+ prompt += `- **href=home (or "/" or "#") in header is a strong brand signal** — the main logo almost always links to home; avoid picking header candidates that link to product/docs/other pages unless they clearly match the favicon or "Logo" in src\n`;
+ prompt += `- href:external is usually NOT the brand logo\n`;
+ prompt += `- source: document.images = main page images (often the primary brand logo)\n`;
+ prompt += `- If a favicon was provided above, prefer candidates whose src matches or resembles it (same domain, or Logo.svg/wordmark)\n`;
+ prompt += `- logoSvgScore/svgScore: higher = more logo-like (SVG or image)\n\n`;
+
+ prompt += `\n**LOGO SELECTION - CRITICAL RULES (follow in order):**\n`;
+ prompt += `1. **NEVER pick invisible or tiny UI icons:** If a candidate has isVisible:false, do NOT pick it unless it is the ONLY header candidate. Prefer isVisible:true.\n`;
+ prompt += `2. **Prefer href=home in header:** The main brand logo almost always links to home ("/", "#", or homepage URL). Do NOT pick a header candidate that links to a product/docs/other page if another candidate has href=home or matches the favicon/Logo.svg.\n`;
+ prompt += `3. **NEVER pick "tiny" or "small" when a proper logo exists:** If any candidate has size "medium" or "large" and is in header with href=home (or matches favicon), do NOT pick a "tiny" or "small" candidate (those are usually menu/hamburger/icons).\n`;
+ prompt += `4. **REJECT by alt text:** Do NOT pick candidates whose alt/ariaLabel contains: "menu", "hamburger", "toggle", "mobile menu", "menu open", "menu close", "close-mobile". Those are UI icons, not the brand logo.\n`;
+ prompt += `5. **Prefer the main visible logo:** When multiple candidates share the same href (e.g. homepage), pick the one with LARGER width×height and isVisible:true — that is the primary logo; the smaller/hidden one is often a collapsed-nav variant.\n`;
+ prompt += `6. **Prefer favicon match or clear Logo:** If favicon was provided, prefer a candidate whose src matches or resembles it, or a clear "Logo.svg"/wordmark in header with href=home. Prefer alt matching brand (e.g. "X Home") over generic or empty alt.\n\n`;
+ prompt += `**LOGO SELECTION - SIMPLE APPROACH:**\n`;
if (input.screenshot) {
- prompt += `Look at the screenshot and select the MOST PROMINENT primary brand logo.\n\n`;
+ prompt += `Look at the screenshot and select the MOST PROMINENT primary brand logo (the one users actually see in the header).\n\n`;
} else {
- prompt += `Select the MOST PROMINENT primary brand logo.\n\n`;
+ prompt += `Select the MOST PROMINENT primary brand logo (largest visible header logo that represents the brand).\n\n`;
}
prompt += `**Simple Rules:**\n`;
prompt += `1. **Look at the TOP of the page** - The main logo is almost always in the header/navbar at the very top\n`;
- prompt += `2. **Primary logo** - Choose the largest, most visible logo that represents "${brandName || "the website's brand"}"\n`;
+ prompt += `2. **Primary logo** - Choose the largest, most visible logo that represents "${brandName || "the website's brand"}" (prefer medium/large size, isVisible:true)\n`;
prompt += `3. **Prefer header logos** - Logos in the header/navbar area are the brand logo (highest priority)\n`;
prompt += `4. **Ignore partner/client logos** - Skip smaller logos in "customers", "partners", or footer sections\n`;
if (input.screenshot) {
- prompt += `5. **Use the screenshot** - Visually identify which logo is THE main brand logo users see first\n\n`;
+ prompt += `5. **Use the screenshot** - Visually identify which logo is THE main brand logo users see first (not a tiny icon or hidden variant)\n\n`;
} else {
- prompt += `5. **Use visual indicators** - Identify which logo is THE main brand logo based on position, size, and indicators\n\n`;
+ prompt += `5. **Use position + size + isVisible** - Prefer header, larger dimensions, and isVisible:true; reject tiny or invisible candidates\n\n`;
}
prompt += `**What to avoid:**\n`;
+ prompt += `- Tiny or small icons (menu, hamburger, close, toggle) — check alt text and size\n`;
+ prompt += `- Candidates with isVisible:false when a visible header logo exists\n`;
prompt += `- Customer/client logos (usually smaller, in groups, different brand names)\n`;
prompt += `- Social media icons\n`;
prompt += `- Footer logos (unless no header logo exists)\n\n`;
- prompt += `Just pick the obvious main brand logo at the top of the page that users see first.\n\n`;
+ prompt += `Just pick the obvious main brand logo at the top of the page that users see first (visible, medium/large, alt like brand name or "X Home").\n\n`;
}
// Add background color candidates section
@@ -292,64 +473,64 @@ 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 += ` - 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\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 += `${buttons && buttons.length > 0 ? "4" : "2"}. **Brand Personality**: Overall tone and energy\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`;
prompt += `${buttons && buttons.length > 0 ? "5" : "3"}. **Design System**: Based on the class patterns shown above:\n`;
prompt += ` - **Framework**: Identify the CSS framework (tailwind/bootstrap/material/chakra/custom/unknown)\n`;
prompt += ` - **Component Library**: Look for prefixes like \`radix-\`, \`shadcn-\`, \`headlessui-\`, or \`react-aria-\` in classes\n`;
- prompt += ` - If using Tailwind + a component library, identify both (e.g., framework: tailwind, componentLibrary: "radix-ui")\n\n`;
+ prompt += ` - If using Tailwind + a component library, identify both (e.g., framework: tailwind, componentLibrary: "radix-ui")\n`;
+ prompt += ` - If no component library is detected, return an empty string ""\n\n`;
prompt += `${buttons && buttons.length > 0 ? "6" : "4"}. **Clean Fonts**: Return up to 5 cleaned, human-readable font names\n`;
prompt += ` - Remove framework obfuscation (Next.js hashes, etc.)\n`;
prompt += ` - Filter out generics and CSS variables\n`;
prompt += ` - Prioritize by frequency (shown in usage count)\n`;
- prompt += ` - Assign appropriate roles (heading, body, monospace, display)\n\n`;
+ prompt += ` - Assign appropriate roles (heading, body, monospace, display) or "unknown"\n\n`;
if (logoCandidates && logoCandidates.length > 0) {
const logoTaskNumber = buttons && buttons.length > 0 ? "7" : "5";
prompt += `${logoTaskNumber}. **Logo Selection**: Identify the best brand logo from the ${logoCandidates.length} candidates provided above.\n`;
+ if (
+ heuristicLogoPick != null &&
+ heuristicLogoPick.selectedIndexInFilteredList >= 0
+ ) {
+ prompt += ` - **Heuristic suggested #${heuristicLogoPick.selectedIndexInFilteredList}.** Confirm it (return the same index with reasoning) OR pick a different index; if you pick differently, explain why the heuristic was wrong and why your choice is better.\n`;
+ }
prompt += ` - **YOU MUST RETURN**: selectedLogoIndex (number), selectedLogoReasoning (string), and confidence (0-1)\n`;
- prompt += ` - **CRITICAL**: The logo MUST match the brand name "${brandName || "unknown"}" and look like a brand logo\n`;
+ prompt += ` - **CRITICAL**: NEVER pick a tiny/invisible/UI icon. Prefer the MAIN visible header logo (medium/large size, isVisible:true, alt like "${brandName || "Brand"} Home").\n`;
prompt += ` - **IT'S OK TO RETURN -1**: If no candidate is a good brand logo, return -1 with low confidence\n`;
prompt += ` - **DECISION PROCESS**:\n`;
if (input.screenshot) {
- prompt += ` 1. Look at the screenshot - find the logo in the HEADER/TOP area\n`;
- prompt += ` 2. Check which candidate matches that visual position and appearance\n`;
+ prompt += ` 1. Look at the screenshot - find the MAIN logo in the HEADER (the one users see, not a tiny icon)\n`;
+ prompt += ` 2. Match that visual to a candidate; prefer isVisible:true and larger size\n`;
} else {
- prompt += ` 1. Find the logo in the HEADER/TOP area based on candidate indicators\n`;
- prompt += ` 2. Check which candidate matches the expected position and appearance\n`;
+ prompt += ` 1. Filter by isVisible:true and size (prefer medium/large over tiny/small)\n`;
+ prompt += ` 2. Prefer candidates with alt matching brand (e.g. "${brandName || "Brand"} Home"), href=home, in header\n`;
}
- prompt += ` 3. Verify the candidate has indicators: "header", "href=home", or "alt=logo"\n`;
- prompt += ` 4. Verify it's NOT a UI icon (search, menu, cart, user, settings, etc.)\n`;
- prompt += ` 5. If multiple candidates look similar, prefer the one with href="/" (homepage link)\n`;
- prompt += ` 6. If you're unsure or none look like brand logos, return -1\n`;
+ prompt += ` 3. Reject any candidate with alt containing "menu", "hamburger", "toggle", "mobile menu", "close"\n`;
+ prompt += ` 4. If multiple candidates share the same href, pick the LARGER one (primary logo), not the smaller/hidden variant\n`;
+ prompt += ` 5. If you're unsure or only tiny/invisible candidates remain, return -1\n`;
prompt += ` - **STRONG INDICATORS** (prioritize candidates with these):\n`;
- prompt += ` * "href:/" or "hrefMatch" → Logo links to homepage (VERY STRONG indicator of brand logo)\n`;
- prompt += ` * Internal links only → Logo should NOT link to external websites\n`;
- prompt += ` * Has a link → Brand logos are usually clickable, not inside buttons\n`;
- prompt += ` * "header" location → Logo in header/navbar area (STRONG indicator)\n`;
- prompt += ` * "visible" → Logo is currently visible (preferred)\n`;
- prompt += ` * "alt=logo" or alt text matching "${brandName || "brand name"}" → Likely the brand logo\n`;
- prompt += ` * Reasonable size (not tiny like icons, not huge like hero images)\n`;
- prompt += ` - **AVOID** (return -1 if ALL candidates are these):\n`;
- prompt += ` * Very large images (likely og:image, hero images, or banners - not logos)\n`;
- prompt += ` * Images with NO LINK or inside buttons (brand logos link to homepage via <a> tag)\n`;
- prompt += ` * Images that link to EXTERNAL websites (brand logos link to homepage, not external sites)\n`;
- prompt += ` * UI icons: search icons, menu hamburgers, cart icons, user icons, settings icons\n`;
- prompt += ` * Very small square icons (< 40x40px)\n`;
- prompt += ` * Language switcher flags or text\n`;
- prompt += ` * Customer/client logos (different brand names than "${brandName || "unknown"}")\n`;
- prompt += ` * Partner/testimonial logos (usually in body, not header)\n`;
- prompt += ` * Footer logos (unless no header logo exists)\n`;
- prompt += ` * GitHub stars, social media icons, badges, external service badges\n`;
- prompt += ` * Logos in "customers", "partners", "case studies" sections\n`;
+ prompt += ` * isVisible:true AND size medium/large (not tiny) → The main logo users see\n`;
+ prompt += ` * "href:/" or "hrefMatch" → Logo links to homepage (VERY STRONG)\n`;
+ prompt += ` * "header" + alt like "${brandName || "brand name"} Home" → Primary brand logo\n`;
+ prompt += ` * Larger width×height when same href as other candidates → Primary; smaller = collapsed/mini variant\n`;
+ prompt += ` - **AVOID** (do NOT pick these; return -1 if only these remain):\n`;
+ prompt += ` * isVisible:false when another candidate has isVisible:true\n`;
+ prompt += ` * Size "tiny" or "small" when a "medium"/"large" header logo exists\n`;
+ prompt += ` * Alt/ariaLabel containing: menu, hamburger, toggle, "mobile menu", "menu open", "menu close"\n`;
+ prompt += ` * Very large images (og:image, hero, banners)\n`;
+ prompt += ` * UI icons (search, hamburger, cart, user, settings)\n`;
+ prompt += ` * Customer/client/footer logos\n`;
prompt += ` - **RETURN FORMAT**:\n`;
- prompt += ` * selectedLogoIndex: The INDEX number (0-${logoCandidates.length - 1}) of the best logo, or -1 if none are good brand logos\n`;
- prompt += ` * selectedLogoReasoning: "Selected #X because [it has href:/, in header, matches brand name, etc.]" OR "No valid brand logo found - candidates are UI icons/customer logos"\n`;
+ prompt += ` * selectedLogoIndex: The INDEX (0-${logoCandidates.length - 1}) of the best logo, or -1 if none are good\n`;
+ prompt += ` * selectedLogoReasoning: "Selected #X because [isVisible, medium/large, header, href=home, alt=brand]." OR "No valid brand logo - only tiny/invisible/UI icons."\n`;
prompt += ` * confidence: 0.8-1.0 if sure, 0.5-0.7 if uncertain, 0.0-0.4 if no good match or returning -1\n`;
- prompt += ` - **PREFER -1 OVER BAD LOGOS**: Better to return no logo than a search icon or customer logo\n\n`;
+ prompt += ` - **PREFER -1 OVER BAD LOGOS**: Better to return no logo than a menu/hamburger icon or tiny hidden variant.\n\n`;
}
if (buttons && buttons.length > 0) {
@@ -380,9 +561,11 @@ export function buildBrandingPrompt(input: BrandingLLMInput): string {
prompt += `${fieldNumber}. colorRoles: { primaryColor, accentColor, backgroundColor, textPrimary, confidence }\n`;
fieldNumber++;
prompt += `${fieldNumber}. cleanedFonts: [] (array, can be empty but must be present)\n`;
- if (logoCandidates && logoCandidates.length > 0) {
+ if (hasLogoCandidates) {
fieldNumber++;
prompt += `${fieldNumber}. logoSelection: { selectedLogoIndex, selectedLogoReasoning, confidence }\n`;
+ } else {
+ prompt += `(No logoSelection required — there are no logo candidates.)\n`;
}
prompt += `\n**DO NOT** return empty objects {}. Fill in ALL fields with actual values or -1/null as appropriate.\n`;
diff --git a/apps/api/src/lib/branding/schema.ts b/apps/api/src/lib/branding/schema.ts
index 1be3cc1da..0d0b721c4 100644
--- a/apps/api/src/lib/branding/schema.ts
+++ b/apps/api/src/lib/branding/schema.ts
@@ -1,7 +1,7 @@
import { z } from "zod";
-// Schema for LLM output
-export const brandingEnhancementSchema = z.object({
+// Base schema without logoSelection
+const baseBrandingEnhancementSchema = z.object({
// Button classification - LLM picks which buttons are primary/secondary
buttonClassification: z
.object({
@@ -42,65 +42,46 @@ export const brandingEnhancementSchema = z.object({
}),
// Color role clarification
- colorRoles: z
- .object({
- primaryColor: z.string().nullish().describe("Main brand color (hex)"),
- accentColor: z.string().nullish().describe("Accent/CTA color (hex)"),
- backgroundColor: z
- .string()
- .nullish()
- .describe("Main background color (hex)"),
- textPrimary: z.string().nullish().describe("Primary text color (hex)"),
- confidence: z.number().min(0).max(1),
- })
- .default({
- primaryColor: null,
- accentColor: null,
- backgroundColor: null,
- textPrimary: null,
- confidence: 0,
- }),
+ colorRoles: z.object({
+ primaryColor: z.string().describe("Main brand color (hex)"),
+ accentColor: z.string().describe("Accent/CTA color (hex)"),
+ backgroundColor: z.string().describe("Main background color (hex)"),
+ textPrimary: z.string().describe("Primary text color (hex)"),
+ confidence: z.number().min(0).max(1),
+ }),
// Brand personality
- personality: z
- .object({
- tone: z
- .enum([
- "professional",
- "playful",
- "modern",
- "traditional",
- "minimalist",
- "bold",
- ])
- .describe("Overall brand tone"),
- energy: z.enum(["low", "medium", "high"]).describe("Visual energy level"),
- targetAudience: z
- .string()
- .optional()
- .describe("Perceived target audience"),
- })
- .optional(),
+ personality: z.object({
+ tone: z
+ .enum([
+ "professional",
+ "playful",
+ "modern",
+ "traditional",
+ "minimalist",
+ "bold",
+ ])
+ .describe("Overall brand tone"),
+ energy: z.enum(["low", "medium", "high"]).describe("Visual energy level"),
+ targetAudience: z.string().describe("Perceived target audience"),
+ }),
// Design system insights
- designSystem: z
- .object({
- framework: z
- .enum([
- "tailwind",
- "bootstrap",
- "material",
- "chakra",
- "custom",
- "unknown",
- ])
- .describe("Detected CSS framework"),
- componentLibrary: z
- .string()
- .nullish()
- .describe("Detected component library (e.g., radix-ui, shadcn)"),
- })
- .optional(),
+ designSystem: z.object({
+ framework: z
+ .enum([
+ "tailwind",
+ "bootstrap",
+ "material",
+ "chakra",
+ "custom",
+ "unknown",
+ ])
+ .describe("Detected CSS framework"),
+ componentLibrary: z
+ .string()
+ .describe("Detected component library (e.g., radix-ui, shadcn)"),
+ }),
// Font cleaning - LLM cleans and filters font names
cleanedFonts: z
@@ -108,8 +89,7 @@ export const brandingEnhancementSchema = z.object({
z.object({
family: z.string().describe("Cleaned, human-readable font name"),
role: z
- .enum(["heading", "body", "monospace", "display"])
- .nullish()
+ .enum(["heading", "body", "monospace", "display", "unknown"])
.describe("Font role/usage"),
}),
)
@@ -118,29 +98,45 @@ export const brandingEnhancementSchema = z.object({
"Top 5 cleaned fonts (remove obfuscation, fallbacks, generics, CSS vars)",
)
.default([]),
+});
+// Schema with logoSelection (when logo candidates are provided)
+const brandingEnhancementSchemaWithLogo = baseBrandingEnhancementSchema.extend({
// Logo selection - LLM picks the best logo from candidates
- logoSelection: z
- .object({
- selectedLogoIndex: z
- .number()
- .describe(
- "REQUIRED: Index of the selected logo in the provided candidates list (0-based), or -1 if NONE of the candidates match the brand name. YOU MUST RETURN A NUMBER.",
- ),
- selectedLogoReasoning: z
- .string()
- .describe(
- "REQUIRED: Detailed explanation of why this logo was selected, or why none were suitable if returning -1. YOU MUST PROVIDE REASONING.",
- ),
- confidence: z
- .number()
- .min(0)
- .max(1)
- .describe(
- "REQUIRED: Confidence in logo selection (0-1). Return 0 if no suitable logo found.",
- ),
- })
- .optional(), // Still optional at top level so it's only required when logo candidates are provided
+ logoSelection: z.object({
+ selectedLogoIndex: z
+ .number()
+ .describe(
+ "REQUIRED: Index of the selected logo in the provided candidates list (0-based), or -1 if NONE of the candidates match the site's brand. Infer the brand from page title/URL when provided (e.g. 'X | Miro' → brand Miro). YOU MUST RETURN A NUMBER.",
+ ),
+ selectedLogoReasoning: z
+ .string()
+ .describe(
+ "REQUIRED: Detailed explanation of why this logo was selected, or why none were suitable if returning -1. YOU MUST PROVIDE REASONING.",
+ ),
+ confidence: z
+ .number()
+ .min(0)
+ .max(1)
+ .describe(
+ "REQUIRED: Confidence in logo selection (0-1). Return 0 if no suitable logo found.",
+ ),
+ }),
});
-export type BrandingEnhancement = z.infer<typeof brandingEnhancementSchema>;
+// Export function to get the appropriate schema based on whether logo candidates exist
+export function getBrandingEnhancementSchema(hasLogoCandidates: boolean) {
+ return hasLogoCandidates
+ ? brandingEnhancementSchemaWithLogo
+ : baseBrandingEnhancementSchema;
+}
+
+// Type - logoSelection is optional in the type even though it's required in schema when candidates exist
+export type BrandingEnhancement = Omit<
+ z.infer<typeof brandingEnhancementSchemaWithLogo>,
+ "logoSelection"
+> & {
+ logoSelection?: z.infer<
+ typeof brandingEnhancementSchemaWithLogo
+ >["logoSelection"];
+};
diff --git a/apps/api/src/lib/branding/transformer.ts b/apps/api/src/lib/branding/transformer.ts
index 66b390fcd..61ca63d8b 100644
--- a/apps/api/src/lib/branding/transformer.ts
+++ b/apps/api/src/lib/branding/transformer.ts
@@ -8,10 +8,16 @@ import { BrandingScriptReturn, ButtonSnapshot } from "./types";
import { mergeBrandingResults } from "./merge";
import {
selectLogoWithConfidence,
- shouldUseLLMForLogoSelection,
getTopCandidatesForLLM,
} from "./logo-selector";
-import { calculateLogoArea } from "./types";
+import { extractHeaderHtmlChunk } from "./extractHeaderHtmlChunk";
+
+function isDebugBrandingEnabled(meta: Meta): boolean {
+ return (
+ config.DEBUG_BRANDING === true ||
+ meta.internalOptions.teamFlags?.debugBranding === true
+ );
+}
export async function brandingTransformer(
meta: Meta,
@@ -26,17 +32,26 @@ export async function brandingTransformer(
let brandingProfile: BrandingProfile = jsBranding;
- try {
- const buttonSnapshots: ButtonSnapshot[] =
- (jsBranding as any).__button_snapshots || [];
- const inputSnapshots = (jsBranding as any).__input_snapshots || [];
+ // Declare variables outside try block for catch block access
+ const buttonSnapshots: ButtonSnapshot[] =
+ (jsBranding as any).__button_snapshots || [];
+ const inputSnapshots = (jsBranding as any).__input_snapshots || [];
+ const logoCandidates = rawBranding.logoCandidates || [];
+ const brandName = rawBranding.brandName;
+ const backgroundCandidates = rawBranding.backgroundCandidates || [];
+
+ // Initialize metadata tracking variables
+ let llmButtonClassificationSucceeded = false;
+ let llmLogoSelectionSucceeded = false;
+ let logoSelectionFinalSource: "llm" | "heuristic" | "fallback" | "none" =
+ "none";
+ let logoSelectionError: string | undefined = undefined;
+ let heuristicResult: ReturnType<typeof selectLogoWithConfidence> | null =
+ null;
- const logoCandidates = rawBranding.logoCandidates || [];
- const brandName = rawBranding.brandName;
- const backgroundCandidates = rawBranding.backgroundCandidates || [];
-
- // TIER 1: Use smart heuristics to get initial selection
- const heuristicResult =
+ try {
+ // TIER 1: Use smart heuristics to get initial selection (passed to LLM for confirm/override)
+ heuristicResult =
logoCandidates.length > 0
? selectLogoWithConfidence(logoCandidates, brandName)
: null;
@@ -52,17 +67,38 @@ export async function brandingTransformer(
});
}
- // TIER 2: Decide if we need LLM validation
- const needsLLMValidation = heuristicResult
- ? shouldUseLLMForLogoSelection(heuristicResult.confidence)
- : false;
-
- // Filter to top 10 candidates for LLM (reduces token cost)
+ // Always send logo candidates to the LLM when we have any (confirm or override heuristic)
+ // Filter to top 20 candidates for LLM (keeps strong body candidates like alt="X logo" + document.images)
const { filteredCandidates, indexMap } =
- needsLLMValidation && logoCandidates.length > 0
- ? getTopCandidatesForLLM(logoCandidates, 10)
+ logoCandidates.length > 0
+ ? getTopCandidatesForLLM(logoCandidates, 20)
: { filteredCandidates: [], indexMap: new Map<number, number>() };
+ // Heuristic's pick in filtered-list index space (so prompt can say "heuristic picked #N")
+ let heuristicLogoPick:
+ | {
+ selectedIndexInFilteredList: number;
+ confidence: number;
+ reasoning: string;
+ }
+ | undefined;
+ if (heuristicResult && filteredCandidates.length > 0) {
+ let heuristicFilteredIndex = -1;
+ for (const [filteredIdx, originalIdx] of indexMap) {
+ if (originalIdx === heuristicResult.selectedIndex) {
+ heuristicFilteredIndex = filteredIdx;
+ break;
+ }
+ }
+ if (heuristicFilteredIndex >= 0) {
+ heuristicLogoPick = {
+ selectedIndexInFilteredList: heuristicFilteredIndex,
+ confidence: heuristicResult.confidence,
+ reasoning: heuristicResult.reasoning,
+ };
+ }
+ }
+
// Limit buttons to top 12 most relevant ones to reduce prompt size
// Prioritize buttons with CTA indicators, vibrant colors, or common CTA text
let limitedButtons = buttonSnapshots;
@@ -129,32 +165,78 @@ export async function brandingTransformer(
limitedButtons: limitedButtons.length,
});
- // TIER 2: Only call LLM if heuristics are uncertain
+ // When no logo candidates, pass a header/nav HTML chunk so the LLM has fallback context (brand name, "logo exists but not captured")
+ const headerHtmlChunk =
+ logoCandidates.length === 0 &&
+ document.html &&
+ typeof document.html === "string"
+ ? extractHeaderHtmlChunk(document.html)
+ : undefined;
+
+ const sendingLogoCandidates = filteredCandidates.length > 0;
+
+ // TIER 2: Call LLM (always with logo candidates when we have any; heuristic suggestion passed for confirm/override)
+ const finalUrl = rawBranding.pageUrl || document.url || meta.url;
const llmEnhancement = await enhanceBrandingWithLLM({
jsAnalysis: jsBranding,
buttons: limitedButtons,
- logoCandidates:
- needsLLMValidation && filteredCandidates.length > 0
- ? filteredCandidates
- : undefined, // Don't send logo candidates if heuristics are confident
+ logoCandidates: sendingLogoCandidates ? filteredCandidates : undefined,
brandName,
+ pageTitle: rawBranding.pageTitle,
+ pageUrl: rawBranding.pageUrl,
backgroundCandidates:
backgroundCandidates.length > 0 ? backgroundCandidates : undefined,
screenshot: document.screenshot,
- url: document.url || meta.url,
+ url: finalUrl || "",
+ headerHtmlChunk: headerHtmlChunk || undefined,
+ favicon: brandingProfile.images?.favicon ?? undefined,
+ ogImage: brandingProfile.images?.ogImage ?? undefined,
+ heuristicLogoPick,
teamId: meta.internalOptions.teamId,
+ teamFlags: meta.internalOptions.teamFlags,
});
- // Map LLM's filtered index back to original index for logos
- if (needsLLMValidation && llmEnhancement.logoSelection) {
+ // Track LLM success/failure status (will be updated after all processing)
+ llmButtonClassificationSucceeded =
+ llmEnhancement.buttonClassification.primaryButtonReasoning !==
+ "LLM failed" && llmEnhancement.buttonClassification.confidence > 0;
+
+ // Capture raw AI response for logoSelection (before any mapping/heuristic overwrite) for debugging
+ const rawLogoSelectionFromLLM =
+ llmEnhancement.logoSelection != null
+ ? {
+ selectedLogoIndex: llmEnhancement.logoSelection.selectedLogoIndex,
+ selectedLogoReasoning:
+ llmEnhancement.logoSelection.selectedLogoReasoning ?? undefined,
+ confidence: llmEnhancement.logoSelection.confidence,
+ }
+ : undefined;
+
+ // When there are no logo candidates, ignore any logoSelection from the LLM so result is consistent
+ if (logoCandidates.length === 0 && llmEnhancement.logoSelection != null) {
+ delete (llmEnhancement as { logoSelection?: unknown }).logoSelection;
+ }
+
+ // Map LLM's filtered index back to original index for logos (when we sent candidates)
+ if (llmEnhancement.logoSelection && indexMap.size > 0) {
const llmFilteredIndex = llmEnhancement.logoSelection.selectedLogoIndex;
const llmOriginalIndex = indexMap.get(llmFilteredIndex);
if (llmOriginalIndex !== undefined) {
// Update the selection with the original index
llmEnhancement.logoSelection.selectedLogoIndex = llmOriginalIndex;
- } else {
- // LLM returned invalid index - fallback to heuristic
+ meta.logger.info("Logo index mapped (LLM saw filtered list)", {
+ llmFilteredIndex: llmFilteredIndex,
+ originalIndex: llmOriginalIndex,
+ note:
+ "LLM said #" +
+ llmFilteredIndex +
+ " in filtered list → same logo at index " +
+ llmOriginalIndex +
+ " in full candidates",
+ });
+ } else if (llmFilteredIndex >= 0) {
+ // LLM returned index not in our filtered list - fallback to heuristic
meta.logger.warn(
"LLM returned invalid logo index, falling back to heuristic",
{
@@ -164,18 +246,22 @@ export async function brandingTransformer(
heuristicIndex: heuristicResult?.selectedIndex,
},
);
- // Use heuristic result if available, otherwise clear LLM selection
if (heuristicResult) {
llmEnhancement.logoSelection = {
selectedLogoIndex: heuristicResult.selectedIndex,
selectedLogoReasoning: `Heuristic fallback (LLM returned invalid index): ${heuristicResult.reasoning}`,
- confidence: Math.max(heuristicResult.confidence - 0.1, 0.3), // Slightly lower confidence
+ confidence: Math.max(heuristicResult.confidence - 0.1, 0.3),
};
} else {
- // No heuristic result available - clear LLM selection
- llmEnhancement.logoSelection = undefined;
+ llmEnhancement.logoSelection = {
+ selectedLogoIndex: -1,
+ selectedLogoReasoning:
+ "No valid logo found - LLM returned invalid index and no heuristic result available",
+ confidence: 0,
+ };
}
}
+ // llmFilteredIndex === -1: LLM said "no good logo", keep selectedLogoIndex -1
}
// Map LLM's button indices back to original indices
@@ -202,104 +288,63 @@ export async function brandingTransformer(
}
}
- // TIER 3: Merge heuristic and LLM results
- if (heuristicResult && logoCandidates.length > 0) {
- if (needsLLMValidation && llmEnhancement.logoSelection) {
- // LLM validation was used - validate it against heuristic
- const llmOriginalIndex = llmEnhancement.logoSelection.selectedLogoIndex;
- const heuristicSelectedIndex = heuristicResult.selectedIndex;
-
- // If LLM picked a different logo, validate it's not worse
- if (
- llmOriginalIndex !== undefined &&
- llmOriginalIndex !== heuristicSelectedIndex &&
- llmOriginalIndex >= 0 &&
- llmOriginalIndex < logoCandidates.length
- ) {
- const llmCandidate = logoCandidates[llmOriginalIndex];
- const heuristicCandidate = logoCandidates[heuristicSelectedIndex];
-
- // Calculate logo sizes
- const llmArea = calculateLogoArea(llmCandidate.position);
- const heuristicArea = calculateLogoArea(heuristicCandidate.position);
-
- // Red flags: LLM picked a logo that's objectively worse
- const llmIsWorse =
- // LLM picked non-header logo when heuristic picked header logo
- (!llmCandidate.indicators?.inHeader &&
- heuristicCandidate.indicators?.inHeader) ||
- // LLM picked non-visible logo when heuristic picked visible logo
- (!llmCandidate.isVisible && heuristicCandidate.isVisible) ||
- // LLM picked logo without href="/" when heuristic has it
- (!llmCandidate.indicators?.hrefMatch &&
- heuristicCandidate.indicators?.hrefMatch) ||
- // LLM picked logo from body/footer when heuristic picked from header
- (llmCandidate.location !== "header" &&
- heuristicCandidate.location === "header") ||
- // LLM picked much smaller logo (less than 50% of heuristic area) AND heuristic is in header
- (llmArea < heuristicArea * 0.5 &&
- heuristicCandidate.indicators?.inHeader) ||
- // LLM picked very small logo (<500px²) when heuristic picked reasonable size
- (llmArea < 500 && heuristicArea > 1000);
-
- if (llmIsWorse) {
- meta.logger.warn(
- "LLM picked objectively worse logo - using heuristic instead",
- {
- llmOriginalIndex: llmOriginalIndex,
- llmLocation: llmCandidate.location,
- llmVisible: llmCandidate.isVisible,
- llmInHeader: llmCandidate.indicators?.inHeader,
- llmHrefMatch: llmCandidate.indicators?.hrefMatch,
- llmArea: Math.round(llmArea),
- llmSrc: llmCandidate.src.substring(0, 100),
- heuristicIndex: heuristicSelectedIndex,
- heuristicLocation: heuristicCandidate.location,
- heuristicVisible: heuristicCandidate.isVisible,
- heuristicInHeader: heuristicCandidate.indicators?.inHeader,
- heuristicHrefMatch: heuristicCandidate.indicators?.hrefMatch,
- heuristicArea: Math.round(heuristicArea),
- heuristicSrc: heuristicCandidate.src.substring(0, 100),
- },
- );
-
- // Override LLM with heuristic
- llmEnhancement.logoSelection = {
- selectedLogoIndex: heuristicResult.selectedIndex,
- selectedLogoReasoning: `Heuristic preferred over LLM (LLM picked worse logo): ${heuristicResult.reasoning}`,
- confidence: heuristicResult.confidence,
- };
- } else {
- // LLM picked something different but not objectively worse - trust it
- meta.logger.info(
- "Using LLM-validated logo selection (different from heuristic but valid)",
- );
- }
- } else {
- // LLM agreed with heuristic or picked invalid index
- meta.logger.info("Using LLM-validated logo selection");
+ // Trust LLM logo selection when valid; no override from heuristic.
+ if (
+ heuristicResult &&
+ logoCandidates.length > 0 &&
+ !llmEnhancement.logoSelection
+ ) {
+ // LLM didn't return logo selection - fallback to heuristic
+ meta.logger.warn("LLM didn't return logo selection, using heuristic");
+ llmEnhancement.logoSelection = {
+ selectedLogoIndex: heuristicResult.selectedIndex,
+ selectedLogoReasoning: `Heuristic fallback: ${heuristicResult.reasoning}`,
+ confidence: Math.max(heuristicResult.confidence - 0.1, 0.3),
+ };
+ }
+
+ // Determine final logo selection source after all processing (trust LLM when it picked a logo)
+ if (llmEnhancement.logoSelection) {
+ const reasoning =
+ llmEnhancement.logoSelection.selectedLogoReasoning ?? "";
+ const trustLLMChoice =
+ reasoning.includes("LLM picked worse logo") ||
+ reasoning.includes("Heuristic preferred over LLM");
+ const isInvalidIndexFallback =
+ reasoning.includes("LLM returned invalid index") ||
+ reasoning.includes("invalid index");
+ const isHeuristicFallback =
+ reasoning.includes("Heuristic fallback") ||
+ reasoning.includes("Heuristic preferred") ||
+ isInvalidIndexFallback;
+ if (
+ trustLLMChoice ||
+ (reasoning !== "LLM failed" && !isHeuristicFallback)
+ ) {
+ llmLogoSelectionSucceeded = true;
+ logoSelectionFinalSource = "llm";
+ } else if (
+ (reasoning.includes("Heuristic") || reasoning.includes("heuristic")) &&
+ !(
+ isInvalidIndexFallback &&
+ llmEnhancement.logoSelection?.selectedLogoIndex === -1
+ )
+ ) {
+ logoSelectionFinalSource = "heuristic";
+ if (isInvalidIndexFallback) {
+ logoSelectionError = "LLM returned invalid logo index";
}
- } else if (!needsLLMValidation) {
- // Heuristics were confident - use them directly
- meta.logger.info(
- "Using heuristic logo selection (high confidence, skipped LLM)",
- );
- llmEnhancement.logoSelection = {
- selectedLogoIndex: heuristicResult.selectedIndex,
- selectedLogoReasoning: heuristicResult.reasoning,
- confidence: heuristicResult.confidence,
- };
- } else if (!llmEnhancement.logoSelection) {
- // LLM was called but didn't return selection - fallback to heuristic
- meta.logger.warn(
- "LLM validation requested but didn't return selection, using heuristic",
- );
- llmEnhancement.logoSelection = {
- selectedLogoIndex: heuristicResult.selectedIndex,
- selectedLogoReasoning: `Heuristic fallback: ${heuristicResult.reasoning}`,
- confidence: Math.max(heuristicResult.confidence - 0.1, 0.3), // Slightly lower confidence
- };
+ } else {
+ logoSelectionFinalSource = "fallback";
+ logoSelectionError = isInvalidIndexFallback
+ ? "LLM returned invalid logo index"
+ : reasoning;
}
+ } else if (logoCandidates.length === 0) {
+ logoSelectionFinalSource = "none";
+ } else {
+ logoSelectionFinalSource = "fallback";
+ logoSelectionError = "LLM did not return logo selection";
}
meta.logger.info("Branding enhancement complete", {
@@ -310,12 +355,13 @@ export async function brandingTransformer(
color_confidence: llmEnhancement.colorRoles.confidence,
logo_selected_index: llmEnhancement.logoSelection?.selectedLogoIndex,
logo_confidence: llmEnhancement.logoSelection?.confidence,
- logo_selection_method: needsLLMValidation
- ? llmEnhancement.logoSelection
- ? "llm-validated"
- : "heuristic-fallback"
- : "heuristic-only",
- llm_called_for_logo: needsLLMValidation,
+ logo_selection_method:
+ logoCandidates.length > 0
+ ? llmEnhancement.logoSelection
+ ? "llm-validated"
+ : "heuristic-fallback"
+ : "none",
+ llm_called_for_logo: sendingLogoCandidates,
});
brandingProfile = mergeBrandingResults(
@@ -325,6 +371,27 @@ export async function brandingTransformer(
logoCandidates.length > 0 ? logoCandidates : undefined,
);
+ // Add LLM metadata for evals (rawLogoSelection = exact AI response for debugging)
+ (brandingProfile as any).__llm_metadata = {
+ logoSelection: {
+ llmCalled: sendingLogoCandidates,
+ llmSucceeded: llmLogoSelectionSucceeded,
+ finalSource: logoSelectionFinalSource,
+ error: logoSelectionError,
+ rawLogoSelection: rawLogoSelectionFromLLM,
+ },
+ buttonClassification: {
+ llmCalled: buttonSnapshots.length > 0,
+ llmSucceeded: llmButtonClassificationSucceeded,
+ error:
+ !llmButtonClassificationSucceeded &&
+ llmEnhancement.buttonClassification.primaryButtonReasoning ===
+ "LLM failed"
+ ? "LLM call failed or returned fallback values"
+ : undefined,
+ },
+ };
+
meta.logger.info("Input fields detected", {
count: inputSnapshots.length,
types: inputSnapshots.map((i: any) => i.type).slice(0, 10),
@@ -335,11 +402,27 @@ export async function brandingTransformer(
{ error },
);
brandingProfile = jsBranding;
+
+ // Add error metadata
+ (brandingProfile as any).__llm_metadata = {
+ logoSelection: {
+ llmCalled: logoCandidates.length > 0,
+ llmSucceeded: false,
+ finalSource: heuristicResult ? "heuristic" : "none",
+ error: error instanceof Error ? error.message : String(error),
+ },
+ buttonClassification: {
+ llmCalled: buttonSnapshots.length > 0,
+ llmSucceeded: false,
+ error: error instanceof Error ? error.message : String(error),
+ },
+ };
}
- if (config.DEBUG_BRANDING !== true) {
+ if (!isDebugBrandingEnabled(meta)) {
delete (brandingProfile as any).__button_snapshots;
delete (brandingProfile as any).__input_snapshots;
+ delete (brandingProfile as any).__logo_candidates;
}
return brandingProfile;
diff --git a/apps/api/src/lib/branding/types.ts b/apps/api/src/lib/branding/types.ts
index 720c60ef8..ef7ad7aa4 100644
--- a/apps/api/src/lib/branding/types.ts
+++ b/apps/api/src/lib/branding/types.ts
@@ -48,6 +48,8 @@ export interface BrandingLLMInput {
logoCandidates?: Array<{
src: string;
alt: string;
+ ariaLabel?: string;
+ title?: string;
isSvg: boolean;
isVisible: boolean;
location: "header" | "body" | "footer";
@@ -61,8 +63,13 @@ export interface BrandingLLMInput {
};
href?: string;
source: string;
+ logoSvgScore?: number;
}>;
brandName?: string;
+ /** Full page title (e.g. "AI Innovation Workspace | Miro") — LLM infers brand from this. */
+ pageTitle?: string;
+ /** Final page URL after redirects — prefer over document.url when available. */
+ pageUrl?: string;
backgroundCandidates?: Array<{
color: string;
source: string;
@@ -71,7 +78,20 @@ export interface BrandingLLMInput {
}>;
screenshot?: string;
url: string;
+ /** Optional header/nav HTML chunk for LLM when no logo candidates (fallback context). */
+ headerHtmlChunk?: string;
+ /** Favicon URL when available (from page meta/link). */
+ favicon?: string | null;
+ /** OG image URL when available (meta og:image). */
+ ogImage?: string | null;
+ /** Heuristic's logo pick (index in the filtered candidate list we send). Ask LLM to confirm or override and explain. */
+ heuristicLogoPick?: {
+ selectedIndexInFilteredList: number;
+ confidence: number;
+ reasoning: string;
+ };
teamId?: string;
+ teamFlags?: { debugBranding?: boolean } | null;
}
/**
@@ -135,6 +155,8 @@ export interface BrandingScriptReturn {
logoCandidates?: Array<{
src: string;
alt: string;
+ ariaLabel?: string;
+ title?: string;
isSvg: boolean;
isVisible: boolean;
location: "header" | "body" | "footer";
@@ -148,8 +170,13 @@ export interface BrandingScriptReturn {
};
href?: string;
source: string;
+ logoSvgScore?: number;
}>;
brandName?: string;
+ /** Full page title (e.g. "AI Innovation Workspace | Miro") — LLM can infer brand from this. */
+ pageTitle?: string;
+ /** Final page URL after redirects (from window.location.href in the script). */
+ pageUrl?: string;
typography: {
stacks: {
body: string[];
diff --git a/apps/api/src/scraper/scrapeURL/engines/fire-engine/branding-script/brand-utils.ts b/apps/api/src/scraper/scrapeURL/engines/fire-engine/branding-script/brand-utils.ts
new file mode 100644
index 000000000..0e3e1505f
--- /dev/null
+++ b/apps/api/src/scraper/scrapeURL/engines/fire-engine/branding-script/brand-utils.ts
@@ -0,0 +1,411 @@
+import { CONSTANTS } from "./constants";
+import { getComputedStyleCached } from "./helpers";
+
+export interface Typography {
+ stacks: {
+ body: string[];
+ heading: string[];
+ paragraph: string[];
+ };
+ sizes: {
+ h1: string;
+ h2: string;
+ body: string;
+ };
+}
+
+export const getTypography = (): Typography => {
+ const pickFontStack = (el: Element): string[] => {
+ return (
+ getComputedStyleCached(el)
+ .fontFamily?.split(",")
+ .map(f => f.replace(/["']/g, "").trim())
+ .filter(Boolean) || []
+ );
+ };
+
+ // Fallback to documentElement when body is null (e.g. incomplete or non-HTML doc)
+ const bodyOrRoot =
+ document.body ?? (document.documentElement as unknown as Element);
+ const h1 = document.querySelector("h1") ?? bodyOrRoot;
+ const h2 = document.querySelector("h2") ?? h1;
+ const p = document.querySelector("p") ?? bodyOrRoot;
+ const body = bodyOrRoot;
+
+ return {
+ stacks: {
+ body: pickFontStack(body),
+ heading: pickFontStack(h1),
+ paragraph: pickFontStack(p),
+ },
+ sizes: {
+ h1: getComputedStyleCached(h1).fontSize || "32px",
+ h2: getComputedStyleCached(h2).fontSize || "24px",
+ body: getComputedStyleCached(p).fontSize || "16px",
+ },
+ };
+};
+
+export const detectFrameworkHints = (): string[] => {
+ const hints: string[] = [];
+
+ const generator = document.querySelector('meta[name="generator"]');
+ if (generator) hints.push(generator.getAttribute("content") || "");
+
+ const scripts = Array.from(document.querySelectorAll("script[src]"))
+ .map(s => s.getAttribute("src") || "")
+ .filter(Boolean);
+
+ if (
+ scripts.some(s => s.includes("tailwind") || s.includes("cdn.tailwindcss"))
+ ) {
+ hints.push("tailwind");
+ }
+ if (scripts.some(s => s.includes("bootstrap"))) {
+ hints.push("bootstrap");
+ }
+ if (scripts.some(s => s.includes("mui") || s.includes("material-ui"))) {
+ hints.push("material-ui");
+ }
+
+ return hints.filter(Boolean);
+};
+
+export const detectColorScheme = (): "dark" | "light" => {
+ const body = document.body;
+ const html = document.documentElement;
+
+ const hasDarkIndicator =
+ html.classList.contains("dark") ||
+ body.classList.contains("dark") ||
+ html.classList.contains("dark-mode") ||
+ body.classList.contains("dark-mode") ||
+ html.getAttribute("data-theme") === "dark" ||
+ body.getAttribute("data-theme") === "dark" ||
+ html.getAttribute("data-bs-theme") === "dark";
+
+ const hasLightIndicator =
+ html.classList.contains("light") ||
+ body.classList.contains("light") ||
+ html.classList.contains("light-mode") ||
+ body.classList.contains("light-mode") ||
+ html.getAttribute("data-theme") === "light" ||
+ body.getAttribute("data-theme") === "light" ||
+ html.getAttribute("data-bs-theme") === "light";
+
+ let prefersDark = false;
+ try {
+ prefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
+ } catch (e) {
+ // matchMedia not available
+ }
+
+ if (hasDarkIndicator) return "dark";
+ if (hasLightIndicator) return "light";
+
+ const getEffectiveBackground = (
+ el: Element,
+ ): { r: number; g: number; b: number; alpha: number } | null => {
+ let current: Element | null = el;
+ let depth = 0;
+ while (current && depth < 10) {
+ const bg = getComputedStyleCached(current).backgroundColor;
+ const match = bg.match(
+ /rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/,
+ );
+ if (match) {
+ const r = parseInt(match[1], 10);
+ const g = parseInt(match[2], 10);
+ const b = parseInt(match[3], 10);
+ const alpha = match[4] ? parseFloat(match[4]) : 1;
+
+ if (alpha > CONSTANTS.MIN_ALPHA_THRESHOLD) {
+ return { r, g, b, alpha };
+ }
+ }
+ current = current.parentElement;
+ depth++;
+ }
+ return null;
+ };
+
+ const bodyBg = getEffectiveBackground(body);
+ const htmlBg = getEffectiveBackground(html);
+ const effectiveBg = bodyBg || htmlBg;
+
+ if (effectiveBg) {
+ const { r, g, b } = effectiveBg;
+ const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
+
+ if (luminance < 0.4) return "dark";
+ if (luminance > 0.6) return "light";
+
+ return prefersDark ? "dark" : "light";
+ }
+
+ return prefersDark ? "dark" : "light";
+};
+
+export const extractBrandName = (): string => {
+ const ogSiteName = document
+ .querySelector('meta[property="og:site_name"]')
+ ?.getAttribute("content");
+ const title = document.title;
+ const h1 = document.querySelector("h1")?.textContent?.trim();
+
+ let domainName = "";
+ try {
+ const hostname = window.location.hostname;
+ domainName = hostname.replace(/^www\./, "").split(".")[0];
+ domainName = domainName.charAt(0).toUpperCase() + domainName.slice(1);
+ } catch (e) {
+ // location not available
+ }
+
+ let titleBrand = "";
+ if (title) {
+ titleBrand = title
+ .replace(/\s*[-|–|—]\s*.*$/, "")
+ .replace(/\s*:\s*.*$/, "")
+ .replace(/\s*\|.*$/, "")
+ .trim();
+ }
+
+ return ogSiteName || titleBrand || h1 || domainName || "";
+};
+
+export const normalizeColor = (
+ color: string | null | undefined,
+): string | null => {
+ if (!color || typeof color !== "string") return null;
+ const normalized = color.toLowerCase().trim();
+
+ if (normalized === "transparent" || normalized === "rgba(0, 0, 0, 0)") {
+ return null;
+ }
+
+ if (
+ normalized === "#ffffff" ||
+ normalized === "#fff" ||
+ normalized === "white" ||
+ normalized === "rgb(255, 255, 255)" ||
+ /^rgba\(255,\s*255,\s*255(,\s*1(\.0)?)?\)$/.test(normalized)
+ ) {
+ return "rgb(255, 255, 255)";
+ }
+
+ if (
+ normalized === "#000000" ||
+ normalized === "#000" ||
+ normalized === "black" ||
+ normalized === "rgb(0, 0, 0)" ||
+ /^rgba\(0,\s*0,\s*0(,\s*1(\.0)?)?\)$/.test(normalized)
+ ) {
+ return "rgb(0, 0, 0)";
+ }
+
+ if (normalized.startsWith("#")) {
+ return normalized;
+ }
+
+ if (normalized.startsWith("rgb")) {
+ return normalized.replace(/\s+/g, "");
+ }
+
+ return normalized;
+};
+
+export const isValidBackgroundColor = (
+ color: string | null | undefined,
+): boolean => {
+ if (!color || typeof color !== "string") return false;
+ const normalized = color.toLowerCase().trim();
+ if (normalized === "transparent" || normalized === "rgba(0, 0, 0, 0)") {
+ return false;
+ }
+ const rgbaMatch = normalized.match(
+ /rgba\(\s*0\s*,\s*0\s*,\s*0\s*,\s*([\d.]+)\s*\)/,
+ );
+ if (rgbaMatch) {
+ const alpha = parseFloat(rgbaMatch[1]);
+ if (alpha < CONSTANTS.MAX_TRANSPARENT_ALPHA) {
+ return false;
+ }
+ return true;
+ }
+ const colorMatch = normalized.match(/color\([^)]+\)/);
+ if (colorMatch) {
+ return true;
+ }
+ return normalized.length > 0;
+};
+
+export interface BackgroundCandidate {
+ color: string;
+ source: string;
+ priority: number;
+ area?: number;
+}
+
+export const getBackgroundCandidates = (): BackgroundCandidate[] => {
+ const candidates: BackgroundCandidate[] = [];
+
+ const colorFrequency = new Map<string, number>();
+ const allSampleElements = document.querySelectorAll(
+ "body, html, main, article, [role='main'], div, section",
+ );
+ const sampleEls = Array.from(allSampleElements).slice(
+ 0,
+ CONSTANTS.MAX_BACKGROUND_SAMPLES,
+ );
+
+ sampleEls.forEach(el => {
+ try {
+ const bg = getComputedStyleCached(el).backgroundColor;
+ if (isValidBackgroundColor(bg)) {
+ const rect = el.getBoundingClientRect();
+ const area = rect.width * rect.height;
+ if (area > CONSTANTS.MIN_SIGNIFICANT_AREA) {
+ const normalized = normalizeColor(bg);
+ if (normalized) {
+ const currentCount = colorFrequency.get(normalized) || 0;
+ colorFrequency.set(normalized, currentCount + area);
+ }
+ }
+ }
+ } catch (e) {
+ // Ignore element errors
+ }
+ });
+
+ let mostCommonColor: string | null = null;
+ let maxArea = 0;
+ Array.from(colorFrequency.entries()).forEach(([color, area]) => {
+ if (area > maxArea) {
+ maxArea = area;
+ mostCommonColor = color;
+ }
+ });
+
+ const bodyBg = getComputedStyleCached(document.body).backgroundColor;
+ const htmlBg = getComputedStyleCached(
+ document.documentElement,
+ ).backgroundColor;
+
+ if (isValidBackgroundColor(bodyBg)) {
+ const normalized = normalizeColor(bodyBg);
+ const priority = normalized === mostCommonColor ? 15 : 10;
+ if (normalized) {
+ candidates.push({
+ color: normalized,
+ source: "body",
+ priority: priority,
+ });
+ }
+ }
+
+ if (isValidBackgroundColor(htmlBg)) {
+ const normalized = normalizeColor(htmlBg);
+ const priority = normalized === mostCommonColor ? 14 : 9;
+ if (normalized) {
+ candidates.push({
+ color: normalized,
+ source: "html",
+ priority: priority,
+ });
+ }
+ }
+
+ const normalizedBodyBg = normalizeColor(bodyBg);
+ const normalizedHtmlBg = normalizeColor(htmlBg);
+ if (
+ mostCommonColor &&
+ mostCommonColor !== normalizedBodyBg &&
+ mostCommonColor !== normalizedHtmlBg
+ ) {
+ candidates.push({
+ color: mostCommonColor,
+ source: "most-common-visible",
+ priority: 12,
+ area: maxArea,
+ });
+ }
+
+ try {
+ const rootStyle = getComputedStyleCached(document.documentElement);
+
+ const cssVars = [
+ "--background",
+ "--background-light",
+ "--background-dark",
+ "--bg-background",
+ "--bg-background-light",
+ "--bg-background-dark",
+ "--color-background",
+ "--color-background-light",
+ "--color-background-dark",
+ ];
+
+ cssVars.forEach(varName => {
+ try {
+ const rawValue = rootStyle.getPropertyValue(varName).trim();
+
+ if (rawValue && isValidBackgroundColor(rawValue)) {
+ candidates.push({
+ color: rawValue,
+ source: "css-var:" + varName,
+ priority: 8,
+ });
+ }
+ } catch (e) {
+ // Ignore CSS var errors
+ }
+ });
+ } catch (e) {
+ // Ignore root style errors
+ }
+
+ try {
+ const allContainers = document.querySelectorAll(
+ "main, article, [role='main'], header, .main, .container",
+ );
+ const mainContainers = Array.from(allContainers).slice(0, 5);
+ mainContainers.forEach(el => {
+ try {
+ const bg = getComputedStyleCached(el).backgroundColor;
+ if (isValidBackgroundColor(bg)) {
+ const rect = el.getBoundingClientRect();
+ const area = rect.width * rect.height;
+ if (area > CONSTANTS.MIN_LARGE_CONTAINER_AREA) {
+ const normalized = normalizeColor(bg);
+ if (normalized) {
+ candidates.push({
+ color: normalized,
+ source: el.tagName.toLowerCase() + "-container",
+ priority: 5,
+ area: area,
+ });
+ }
+ }
+ }
+ } catch (e) {
+ // Ignore container errors
+ }
+ });
+ } catch (e) {
+ // Ignore container query errors
+ }
+
+ const seen = new Set<string>();
+ const unique = candidates.filter(c => {
+ if (!c || !c.color) return false;
+ const key = normalizeColor(c.color);
+ if (!key || seen.has(key)) return false;
+ seen.add(key);
+ return true;
+ });
+
+ unique.sort((a, b) => (b.priority || 0) - (a.priority || 0));
+
+ return unique;
+};
diff --git a/apps/api/src/scraper/scrapeURL/engines/fire-engine/branding-script/buttons.ts b/apps/api/src/scraper/scrapeURL/engines/fire-engine/branding-script/buttons.ts
new file mode 100644
index 000000000..9b4c4e914
--- /dev/null
+++ b/apps/api/src/scraper/scrapeURL/engines/fire-engine/branding-script/buttons.ts
@@ -0,0 +1,66 @@
+import { CONSTANTS } from "./constants";
+import {
+ getClassNameString,
+ getComputedStyleCached,
+ recordError,
+} from "./helpers";
+
+export const checkButtonLikeElement = (
+ el: Element,
+ cs: CSSStyleDeclaration,
+ rect: DOMRect,
+ classNames: string,
+): boolean => {
+ const hasButtonClasses = CONSTANTS.BUTTON_CLASS_PATTERN.test(classNames);
+
+ if (
+ hasButtonClasses &&
+ rect.width > CONSTANTS.BUTTON_MIN_WIDTH &&
+ rect.height > CONSTANTS.BUTTON_MIN_HEIGHT
+ ) {
+ return true;
+ }
+
+ const paddingTop = parseFloat(cs.paddingTop) || 0;
+ const paddingBottom = parseFloat(cs.paddingBottom) || 0;
+ const paddingLeft = parseFloat(cs.paddingLeft) || 0;
+ const paddingRight = parseFloat(cs.paddingRight) || 0;
+ const hasPadding =
+ paddingTop > CONSTANTS.BUTTON_MIN_PADDING_VERTICAL ||
+ paddingBottom > CONSTANTS.BUTTON_MIN_PADDING_VERTICAL ||
+ paddingLeft > CONSTANTS.BUTTON_MIN_PADDING_HORIZONTAL ||
+ paddingRight > CONSTANTS.BUTTON_MIN_PADDING_HORIZONTAL;
+ const hasMinSize =
+ rect.width > CONSTANTS.BUTTON_MIN_WIDTH &&
+ rect.height > CONSTANTS.BUTTON_MIN_HEIGHT;
+ const hasRounded = parseFloat(cs.borderRadius) > 0;
+ const hasBorder =
+ parseFloat(cs.borderTopWidth) > 0 ||
+ parseFloat(cs.borderBottomWidth) > 0 ||
+ parseFloat(cs.borderLeftWidth) > 0 ||
+ parseFloat(cs.borderRightWidth) > 0;
+
+ return hasPadding && hasMinSize && (hasRounded || hasBorder);
+};
+
+export const isButtonElement = (el: Element | null): boolean => {
+ if (!el || typeof el.matches !== "function") return false;
+
+ if (el.matches(CONSTANTS.BUTTON_SELECTOR)) {
+ return true;
+ }
+
+ if (el.tagName.toLowerCase() === "a") {
+ try {
+ const classNames = getClassNameString(el).toLowerCase();
+ const cs = getComputedStyleCached(el);
+ const rect = el.getBoundingClientRect();
+ return checkButtonLikeElement(el, cs, rect, classNames);
+ } catch (e) {
+ recordError("isButtonElement", e);
+ return false;
+ }
+ }
+
+ return false;
+};
diff --git a/apps/api/src/scraper/scrapeURL/engines/fire-engine/branding-script/constants.ts b/apps/api/src/scraper/scrapeURL/engines/fire-engine/branding-script/constants.ts
new file mode 100644
index 000000000..66e4983d6
--- /dev/null
+++ b/apps/api/src/scraper/scrapeURL/engines/fire-engine/branding-script/constants.ts
@@ -0,0 +1,27 @@
+export const CONSTANTS = {
+ BUTTON_MIN_WIDTH: 50,
+ BUTTON_MIN_HEIGHT: 25,
+ BUTTON_MIN_PADDING_VERTICAL: 3,
+ BUTTON_MIN_PADDING_HORIZONTAL: 6,
+ MAX_PARENT_TRAVERSAL: 5,
+ MAX_BACKGROUND_SAMPLES: 100,
+ MIN_SIGNIFICANT_AREA: 1000,
+ MIN_LARGE_CONTAINER_AREA: 10000,
+ DUPLICATE_POSITION_THRESHOLD: 1,
+ MIN_LOGO_SIZE: 25,
+ MIN_ALPHA_THRESHOLD: 0.1,
+ MAX_TRANSPARENT_ALPHA: 0.01,
+ BUTTON_SELECTOR:
+ 'button,input[type="submit"],input[type="button"],[role=button],[data-primary-button],[data-secondary-button],[data-cta],a.button,a.btn,[class*="btn"],[class*="button"],a[class*="bg-brand"],a[class*="bg-primary"],a[class*="bg-accent"]',
+ // Logo detection thresholds
+ TASKBAR_TOP_THRESHOLD: 80,
+ CONTAINER_TOP_THRESHOLD: 50,
+ TASKBAR_LOGO_MAX_TOP: 120,
+ TASKBAR_LOGO_MAX_LEFT: 450,
+ TASKBAR_LOGO_MIN_WIDTH: 24,
+ TASKBAR_LOGO_MIN_HEIGHT: 12,
+ TOP_PAGE_THRESHOLD_PX: 500,
+ // Button-like element class pattern
+ BUTTON_CLASS_PATTERN:
+ /rounded(-md|-lg|-xl|-full)?|p[xy]?-\d+|border.*rounded|inline-flex.*items-center.*justify-center/,
+};
diff --git a/apps/api/src/scraper/scrapeURL/engines/fire-engine/branding-script/css-data.ts b/apps/api/src/scraper/scrapeURL/engines/fire-engine/branding-script/css-data.ts
new file mode 100644
index 000000000..1529afabf
--- /dev/null
+++ b/apps/api/src/scraper/scrapeURL/engines/fire-engine/branding-script/css-data.ts
@@ -0,0 +1,79 @@
+import { toPx } from "./helpers";
+
+export interface CSSData {
+ colors: string[];
+ spacings: number[];
+ radii: number[];
+}
+
+export const collectCSSData = (): CSSData => {
+ const data: CSSData = {
+ colors: [],
+ spacings: [],
+ radii: [],
+ };
+
+ for (const sheet of Array.from(document.styleSheets)) {
+ let rules: CSSRuleList | null;
+ try {
+ rules = sheet.cssRules;
+ } catch {
+ // CORS stylesheets throw SecurityError when accessing cssRules - this is expected
+ continue;
+ }
+ if (!rules) continue;
+
+ for (const rule of Array.from(rules)) {
+ try {
+ if (rule.type === CSSRule.STYLE_RULE) {
+ const s = (rule as CSSStyleRule).style;
+
+ [
+ "color",
+ "background-color",
+ "border-color",
+ "fill",
+ "stroke",
+ ].forEach(prop => {
+ const val = s.getPropertyValue(prop);
+ if (val) data.colors.push(val);
+ });
+
+ [
+ "border-radius",
+ "border-top-left-radius",
+ "border-top-right-radius",
+ "border-bottom-left-radius",
+ "border-bottom-right-radius",
+ ].forEach(p => {
+ const v = toPx(s.getPropertyValue(p));
+ if (v) data.radii.push(v);
+ });
+
+ [
+ "margin",
+ "margin-top",
+ "margin-right",
+ "margin-bottom",
+ "margin-left",
+ "padding",
+ "padding-top",
+ "padding-right",
+ "padding-bottom",
+ "padding-left",
+ "gap",
+ "row-gap",
+ "column-gap",
+ ].forEach(p => {
+ const v = toPx(s.getPropertyValue(p));
+ if (v) data.spacings.push(v);
+ });
+ }
+ } catch {
+ // Ignore individual rule errors
+ }
+ }
+ }
+
+ return data;
+};
diff --git a/apps/api/src/scraper/scrapeURL/engines/fire-engine/branding-script/elements.ts b/apps/api/src/scraper/scrapeURL/engines/fire-engine/branding-script/elements.ts
new file mode 100644
index 000000000..c25dcd2d3
--- /dev/null
+++ b/apps/api/src/scraper/scrapeURL/engines/fire-engine/branding-script/elements.ts
@@ -0,0 +1,319 @@
+import { CONSTANTS } from "./constants";
+import {
+ getClassNameString,
+ getComputedStyleCached,
+ recordError,
+ toPx,
+} from "./helpers";
+import { isButtonElement } from "./buttons";
+
+export const sampleElements = (): Element[] => {
+ const picksSet = new Set<Element>();
+
+ const pushQ = (q: string, limit = 10) => {
+ const elements = Array.from(document.querySelectorAll(q));
+ let count = 0;
+ for (const el of elements) {
+ if (count >= limit) break;
+ picksSet.add(el);
+ count++;
+ }
+ };
+
+ pushQ('header img, .site-logo img, img[alt*=logo i], img[src*="logo"]', 5);
+
+ pushQ(
+ 'button, input[type="submit"], input[type="button"], [role=button], [data-primary-button], [data-secondary-button], [data-cta], a.button, a.btn, [class*="btn"], [class*="button"], a[class*="bg-brand"], a[class*="bg-primary"], a[class*="bg-accent"]',
+ 100,
+ );
+
+ const allLinks = Array.from(document.querySelectorAll("a")).slice(0, 100);
+ for (const link of allLinks) {
+ if (!picksSet.has(link) && isButtonElement(link)) {
+ picksSet.add(link);
+ }
+ }
+
+ pushQ('input, select, textarea, [class*="form-control"]', 25);
+ pushQ("h1, h2, h3, p, a", 50);
+
+ // Avoid Array.from on Set - old mootools overwrites Array.from and breaks Set iteration
+ const result: Element[] = [];
+ picksSet.forEach(el => result.push(el));
+
+ return result.filter(Boolean);
+};
+
+export interface StyleSnapshot {
+ tag: string;
+ classes: string;
+ text: string;
+ rect: { w: number; h: number };
+ colors: {
+ text: string;
+ background: string;
+ border: string;
+ borderWidth: number | null;
+ borderTop: string;
+ borderTopWidth: number | null;
+ borderRight: string;
+ borderRightWidth: number | null;
+ borderBottom: string;
+ borderBottomWidth: number | null;
+ borderLeft: string;
+ borderLeftWidth: number | null;
+ };
+ typography: {
+ fontStack: string[];
+ size: string | null;
+ weight: number | null;
+ };
+ radius: number | null;
+ borderRadius: {
+ topLeft: number | null;
+ topRight: number | null;
+ bottomRight: number | null;
+ bottomLeft: number | null;
+ };
+ shadow: string | null;
+ isButton: boolean;
+ isNavigation: boolean;
+ hasCTAIndicator: boolean;
+ isInput: boolean;
+ inputMetadata: InputMetadata | null;
+ isLink: boolean;
+}
+
+interface InputMetadata {
+ type: string;
+ placeholder: string;
+ value: string;
+ required: boolean;
+ disabled: boolean;
+ name: string;
+ id: string;
+ label: string;
+}
+
+export const getStyleSnapshot = (el: Element): StyleSnapshot => {
+ const cs = getComputedStyleCached(el);
+ const rect = el.getBoundingClientRect();
+
+ const fontStack =
+ cs
+ .getPropertyValue("font-family")
+ ?.split(",")
+ .map(f => f.replace(/["']/g, "").trim())
+ .filter(Boolean) || [];
+
+ let classNames = "";
+ try {
+ if (el.getAttribute) {
+ const attrClass = el.getAttribute("class");
+ if (attrClass) classNames = attrClass.toLowerCase();
+ }
+ if (!classNames) {
+ classNames = getClassNameString(el).toLowerCase();
+ }
+ } catch (e) {
+ try {
+ classNames = getClassNameString(el).toLowerCase();
+ } catch (e2) {
+ classNames = "";
+ }
+ }
+
+ let bgColor = cs.getPropertyValue("background-color");
+ const textColor = cs.getPropertyValue("color");
+
+ const isTransparent =
+ bgColor === "transparent" || bgColor === "rgba(0, 0, 0, 0)";
+ const alphaMatch = bgColor.match(/rgba?\([^,]*,[^,]*,[^,]*,\s*([\d.]+)\)/);
+ const hasZeroAlpha = alphaMatch && parseFloat(alphaMatch[1]) === 0;
+
+ const isInputElement =
+ el.tagName.toLowerCase() === "input" ||
+ el.tagName.toLowerCase() === "select" ||
+ el.tagName.toLowerCase() === "textarea";
+
+ if ((isTransparent || hasZeroAlpha) && !isInputElement) {
+ let parent = el.parentElement;
+ let depth = 0;
+ while (parent && depth < CONSTANTS.MAX_PARENT_TRAVERSAL) {
+ const parentBg =
+ getComputedStyleCached(parent).getPropertyValue("background-color");
+ if (
+ parentBg &&
+ parentBg !== "transparent" &&
+ parentBg !== "rgba(0, 0, 0, 0)"
+ ) {
+ const parentAlphaMatch = parentBg.match(
+ /rgba?\([^,]*,[^,]*,[^,]*,\s*([\d.]+)\)/,
+ );
+ const parentAlpha = parentAlphaMatch
+ ? parseFloat(parentAlphaMatch[1])
+ : 1;
+ if (parentAlpha > CONSTANTS.MIN_ALPHA_THRESHOLD) {
+ bgColor = parentBg;
+ break;
+ }
+ }
+ parent = parent.parentElement;
+ depth++;
+ }
+ }
+
+ const isButton = isButtonElement(el);
+
+ let isNavigation = false;
+ let hasCTAIndicator = false;
+
+ try {
+ hasCTAIndicator =
+ el.matches(
+ '[data-primary-button],[data-secondary-button],[data-cta],[class*="cta"],[class*="hero"]',
+ ) ||
+ el.getAttribute("data-primary-button") === "true" ||
+ el.getAttribute("data-secondary-button") === "true";
+
+ if (!hasCTAIndicator) {
+ const hasNavClass =
+ classNames.includes("nav-") ||
+ classNames.includes("-nav") ||
+ classNames.includes("nav-anchor") ||
+ classNames.includes("nav-link") ||
+ classNames.includes("sidebar-") ||
+ classNames.includes("-sidebar") ||
+ classNames.includes("menu-") ||
+ classNames.includes("-menu") ||
+ classNames.includes("toggle") ||
+ classNames.includes("trigger");
+
+ const hasNavRole = el.matches(
+ '[role="tab"],[role="menuitem"],[role="menuitemcheckbox"],[aria-haspopup],[aria-expanded]',
+ );
+
+ const inNavContext = !!el.closest(
+ 'nav, [role="navigation"], [role="menu"], [role="menubar"], [class*="navigation"], [class*="dropdown"], [class*="sidebar"], [id*="sidebar"], [id*="navigation"], [id*="nav-"], aside[class*="nav"], aside[id*="nav"]',
+ );
+
+ let isNavLink = false;
+ if (el.tagName.toLowerCase() === "a" && el.parentElement) {
+ if (el.parentElement.tagName.toLowerCase() === "li") {
+ const listEl = el.closest("ul, ol");
+ if (
+ listEl &&
+ listEl.closest(
+ '[class*="nav"], [id*="nav"], [class*="sidebar"], [id*="sidebar"]',
+ )
+ ) {
+ isNavLink = true;
+ }
+ }
+ }
+
+ isNavigation = hasNavClass || hasNavRole || inNavContext || isNavLink;
+ }
+ } catch (e) {
+ recordError("getStyleSnapshot-navigation-detection", e);
+ }
+
+ let text = "";
+ const inputEl = el as HTMLInputElement;
+ if (
+ el.tagName.toLowerCase() === "input" &&
+ (inputEl.type === "submit" || inputEl.type === "button")
+ ) {
+ text = (inputEl.value && inputEl.value.trim().substring(0, 100)) || "";
+ } else {
+ text = (el.textContent && el.textContent.trim().substring(0, 100)) || "";
+ }
+
+ const isInputField = el.matches(
+ 'input:not([type="submit"]):not([type="button"]),select,textarea,[class*="form-control"]',
+ );
+ let inputMetadata: InputMetadata | null = null;
+ if (isInputField) {
+ const tagName = el.tagName.toLowerCase();
+ const inp = el as HTMLInputElement;
+ inputMetadata = {
+ type: tagName === "input" ? inp.type || "text" : tagName,
+ placeholder: inp.placeholder || "",
+ value: tagName === "input" ? inp.value || "" : "",
+ required: inp.required || false,
+ disabled: inp.disabled || false,
+ name: inp.name || "",
+ id: el.id || "",
+ label: (() => {
+ if (el.id) {
+ const label = document.querySelector(
+ 'label[for="' + CSS.escape(el.id) + '"]',
+ );
+ if (label) return (label.textContent || "").trim().substring(0, 100);
+ }
+ const parentLabel = el.closest("label");
+ if (parentLabel) {
+ const clone = parentLabel.cloneNode(true) as HTMLElement;
+ const inputInClone = clone.querySelector("input,select,textarea");
+ if (inputInClone) inputInClone.remove();
+ return (clone.textContent || "").trim().substring(0, 100);
+ }
+ return "";
+ })(),
+ };
+ }
+
+ return {
+ tag: el.tagName.toLowerCase(),
+ classes: classNames,
+ text: text,
+ rect: { w: rect.width, h: rect.height },
+ colors: {
+ text: textColor,
+ background: bgColor,
+ border: (() => {
+ const top = cs.getPropertyValue("border-top-color");
+ const right = cs.getPropertyValue("border-right-color");
+ const bottom = cs.getPropertyValue("border-bottom-color");
+ const left = cs.getPropertyValue("border-left-color");
+ if (top === right && top === bottom && top === left) return top;
+ return top;
+ })(),
+ borderWidth: (() => {
+ const top = toPx(cs.getPropertyValue("border-top-width"));
+ const right = toPx(cs.getPropertyValue("border-right-width"));
+ const bottom = toPx(cs.getPropertyValue("border-bottom-width"));
+ const left = toPx(cs.getPropertyValue("border-left-width"));
+ if (top === right && top === bottom && top === left) return top;
+ return top;
+ })(),
+ borderTop: cs.getPropertyValue("border-top-color"),
+ borderTopWidth: toPx(cs.getPropertyValue("border-top-width")),
+ borderRight: cs.getPropertyValue("border-right-color"),
+ borderRightWidth: toPx(cs.getPropertyValue("border-right-width")),
+ borderBottom: cs.getPropertyValue("border-bottom-color"),
+ borderBottomWidth: toPx(cs.getPropertyValue("border-bottom-width")),
+ borderLeft: cs.getPropertyValue("border-left-color"),
+ borderLeftWidth: toPx(cs.getPropertyValue("border-left-width")),
+ },
+ typography: {
+ fontStack,
+ size: cs.getPropertyValue("font-size") || null,
+ weight: parseInt(cs.getPropertyValue("font-weight"), 10) || null,
+ },
+ radius: toPx(cs.getPropertyValue("border-radius")),
+ borderRadius: {
+ topLeft: toPx(cs.getPropertyValue("border-top-left-radius")),
+ topRight: toPx(cs.getPropertyValue("border-top-right-radius")),
+ bottomRight: toPx(cs.getPropertyValue("border-bottom-right-radius")),
+ bottomLeft: toPx(cs.getPropertyValue("border-bottom-left-radius")),
+ },
+ shadow: cs.getPropertyValue("box-shadow") || null,
+ isButton: isButton && !isNavigation,
+ isNavigation: isNavigation,
+ hasCTAIndicator: hasCTAIndicator,
+ isInput: isInputField,
+ inputMetadata: inputMetadata,
+ isLink: el.matches("a"),
+ };
+};
diff --git a/apps/api/src/scraper/scrapeURL/engines/fire-engine/branding-script/helpers.ts b/apps/api/src/scraper/scrapeURL/engines/fire-engine/branding-script/helpers.ts
new file mode 100644
index 000000000..a629afe7c
--- /dev/null
+++ b/apps/api/src/scraper/scrapeURL/engines/fire-engine/branding-script/helpers.ts
@@ -0,0 +1,127 @@
+// Error tracking
+export const errors: Array<{
+ context: string;
+ message: string;
+ timestamp: number;
+}> = [];
+
+export const recordError = (context: string, error: unknown) => {
+ errors.push({
+ context: context,
+ message:
+ error && (error as Error).message
+ ? (error as Error).message
+ : String(error),
+ timestamp: Date.now(),
+ });
+};
+
+// Use native getComputedStyle so page scripts (e.g. MooTools) overwriting
+// window.getComputedStyle don't break us. Guard so we never call .bind on undefined.
+let nativeGetComputedStyle: (el: Element) => CSSStyleDeclaration;
+try {
+ const gcs =
+ typeof Window !== "undefined" &&
+ Window.prototype &&
+ (
+ Window.prototype as {
+ getComputedStyle?: (el: Element) => CSSStyleDeclaration;
+ }
+ ).getComputedStyle;
+ if (gcs && typeof gcs.bind === "function" && typeof window !== "undefined") {
+ nativeGetComputedStyle = gcs.bind(window);
+ } else if (
+ typeof window !== "undefined" &&
+ typeof window.getComputedStyle === "function"
+ ) {
+ nativeGetComputedStyle = window.getComputedStyle.bind(window);
+ } else {
+ nativeGetComputedStyle = () => ({}) as CSSStyleDeclaration;
+ }
+} catch {
+ nativeGetComputedStyle = () => ({}) as CSSStyleDeclaration;
+}
+
+// Style caching
+const styleCache = new WeakMap<Element, CSSStyleDeclaration>();
+
+function getComputedStyleSafe(el: Element): CSSStyleDeclaration {
+ try {
+ return nativeGetComputedStyle(el);
+ } catch (e) {
+ recordError("getComputedStyle", e);
+ recordError(
+ "getComputedStyle:diagnostic",
+ String(
+ JSON.stringify({
+ nodeType: el?.nodeType,
+ constructor: el?.constructor?.name,
+ isElement: el instanceof Element,
+ hasOwnerDocument: !!(el as Node & { ownerDocument?: Document })
+ ?.ownerDocument,
+ }),
+ ),
+ );
+ return nativeGetComputedStyle(document.documentElement);
+ }
+}
+
+export const getComputedStyleCached = (el: Element): CSSStyleDeclaration => {
+ if (!el || typeof el !== "object" || !(el instanceof Element)) {
+ return getComputedStyleSafe(document.documentElement);
+ }
+ if (styleCache.has(el)) {
+ return styleCache.get(el)!;
+ }
+ const style = getComputedStyleSafe(el);
+ styleCache.set(el, style);
+ return style;
+};
+
+// Unit conversion
+export const toPx = (v: string | null | undefined): number | null => {
+ if (!v || v === "auto") return null;
+ if (v.endsWith("px")) return parseFloat(v);
+ if (v.endsWith("rem"))
+ return (
+ parseFloat(v) *
+ parseFloat(
+ getComputedStyleSafe(document.documentElement).fontSize || "16",
+ )
+ );
+ if (v.endsWith("em"))
+ return (
+ parseFloat(v) *
+ parseFloat(
+ getComputedStyleSafe(
+ document.body ?? (document.documentElement as unknown as Element),
+ ).fontSize || "16",
+ )
+ );
+ if (v.endsWith("%")) return null;
+ const num = parseFloat(v);
+ return Number.isFinite(num) ? num : null;
+};
+
+// Class name extraction (handles SVG elements)
+export const getClassNameString = (el: Element): string => {
+ if (!el || !el.className) return "";
+ try {
+ const className = el.className as unknown;
+ if (className && typeof className === "object" && "baseVal" in className) {
+ return String((className as { baseVal: string }).baseVal || "");
+ }
+ if (typeof className === "string") {
+ return className;
+ }
+ if (
+ className &&
+ typeof (className as { toString?: unknown }).toString === "function"
+ ) {
+ return String(className);
+ }
+ return String(className || "");
+ } catch (e) {
+ return "";
+ }
+};
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
new file mode 100644
index 000000000..b50f9aecf
--- /dev/null
+++ b/apps/api/src/scraper/scrapeURL/engines/fire-engine/branding-script/images.ts
@@ -0,0 +1,1354 @@
+import { CONSTANTS } from "./constants";
+import {
+ getClassNameString,
+ getComputedStyleCached,
+ recordError,
+} from "./helpers";
+import { resolveSvgStyles } from "./svg-utils";
+
+interface LogoCandidate {
+ src: string;
+ alt: string;
+ ariaLabel?: string;
+ title?: string;
+ isSvg: boolean;
+ isVisible: boolean;
+ location: "header" | "body";
+ position: { top: number; left: number; width: number; height: number };
+ indicators: {
+ inHeader: boolean;
+ altMatch: boolean;
+ srcMatch: boolean;
+ classMatch: boolean;
+ hrefMatch: boolean;
+ };
+ href?: string;
+ source: string;
+ logoSvgScore: number;
+}
+
+interface ImageData {
+ type: string;
+ src: string;
+}
+
+export interface FindImagesResult {
+ images: ImageData[];
+ logoCandidates: LogoCandidate[];
+}
+
+export const findImages = (): FindImagesResult => {
+ const imgs: ImageData[] = [];
+ const logoCandidates: LogoCandidate[] = [];
+
+ const push = (src: string | undefined | null, type: string): void => {
+ if (src) imgs.push({ type, src });
+ };
+
+ const querySelectorAllIncludingShadowRoots = (
+ selector: string,
+ ): Element[] => {
+ const results: Element[] = [];
+ const seenRoots = new Set<Document | ShadowRoot>();
+ function walk(root: Document | ShadowRoot): void {
+ if (!root || seenRoots.has(root)) return;
+ seenRoots.add(root);
+ try {
+ const list = root.querySelectorAll(selector);
+ list.forEach(el => results.push(el));
+ root.querySelectorAll("*").forEach(el => {
+ if ((el as Element & { shadowRoot?: ShadowRoot }).shadowRoot) {
+ walk((el as Element & { shadowRoot: ShadowRoot }).shadowRoot);
+ }
+ });
+ } catch (_) {
+ // Ignore errors
+ }
+ }
+ walk(document);
+ return results;
+ };
+
+ push(
+ (document.querySelector('link[rel*="icon" i]') as HTMLLinkElement | null)
+ ?.href,
+ "favicon",
+ );
+ push(
+ (
+ document.querySelector(
+ 'meta[property="og:image" i]',
+ ) as HTMLMetaElement | null
+ )?.content,
+ "og",
+ );
+ push(
+ (
+ document.querySelector(
+ 'meta[name="twitter:image" i]',
+ ) as HTMLMetaElement | null
+ )?.content,
+ "twitter",
+ );
+
+ const ensureSvgEncoded = (
+ url: string | null | undefined,
+ ): string | null | undefined => {
+ if (!url || !url.startsWith("data:image/svg+xml")) return url;
+
+ const isAlreadyEncoded =
+ url.includes("charset=utf-8") ||
+ (url.includes("data:image/svg+xml,") &&
+ url.split("data:image/svg+xml,")[1]?.startsWith("%"));
+
+ if (isAlreadyEncoded) return url;
+
+ let svgContent = "";
+ if (url.includes("charset=utf-8,")) {
+ svgContent = url.split("charset=utf-8,")[1];
+ } else if (url.includes("data:image/svg+xml,")) {
+ svgContent = url.split("data:image/svg+xml,")[1];
+ }
+
+ if (!svgContent) return url;
+
+ const cleanSvg = svgContent.replace(/\\"/g, '"').replace(/\\'/g, "'");
+ try {
+ return "data:image/svg+xml;charset=utf-8," + encodeURIComponent(cleanSvg);
+ } catch (e) {
+ return (
+ "data:image/svg+xml;charset=utf-8," +
+ cleanSvg.replace(/"/g, "%22").replace(/'/g, "%27")
+ );
+ }
+ };
+
+ const extractBackgroundImageUrl = (bgImage: string | null): string | null => {
+ if (!bgImage || bgImage === "none") return null;
+
+ const decodeHtmlEntities = (url: string): string => {
+ if (
+ url.includes("&quot;") ||
+ url.includes("&lt;") ||
+ url.includes("&gt;")
+ ) {
+ return url
+ .replace(/&quot;/g, '"')
+ .replace(/&lt;/g, "<")
+ .replace(/&gt;/g, ">");
+ }
+ return url;
+ };
+
+ const quotedMatch = bgImage.match(/url\((["'])(.*?)\1\)/);
+ if (quotedMatch) {
+ const url = decodeHtmlEntities(quotedMatch[2]);
+ return ensureSvgEncoded(url) || null;
+ }
+
+ const unquotedMatch = bgImage.match(/url\((data:[^)]+)\)/);
+ if (unquotedMatch) {
+ const url = decodeHtmlEntities(unquotedMatch[1]);
+ return ensureSvgEncoded(url) || null;
+ }
+
+ const simpleMatch = bgImage.match(/url\(([^)]+?)\)/);
+ if (simpleMatch) {
+ let url = simpleMatch[1].trim().replace(/^["']|["']$/g, "");
+ url = ensureSvgEncoded(url) || url;
+ return url;
+ }
+
+ return null;
+ };
+
+ const isSameBrandHost = (
+ currentHostname: string,
+ linkHostname: string,
+ ): boolean => {
+ if (currentHostname === linkHostname) return true;
+ const currentLabel = currentHostname.split(".")[0] || "";
+ const linkLabel = linkHostname.split(".")[0] || "";
+ return (
+ currentLabel.length > 1 &&
+ linkLabel.length > 1 &&
+ currentLabel === linkLabel
+ );
+ };
+
+ const isHomeHref = (href: string | null): boolean => {
+ if (!href) return false;
+
+ const normalizedHref = href.trim();
+
+ if (
+ normalizedHref === "./" ||
+ normalizedHref === "/" ||
+ normalizedHref === "/home" ||
+ normalizedHref === "/index" ||
+ normalizedHref === ""
+ ) {
+ return true;
+ }
+
+ if (normalizedHref.startsWith("#") || normalizedHref.startsWith("?")) {
+ return true;
+ }
+
+ if (
+ normalizedHref.startsWith("http://") ||
+ normalizedHref.startsWith("https://") ||
+ normalizedHref.startsWith("//")
+ ) {
+ try {
+ const currentHostname = window.location.hostname.toLowerCase();
+ const linkUrl = new URL(href, window.location.origin);
+ const linkHostname = linkUrl.hostname.toLowerCase();
+
+ if (!isSameBrandHost(currentHostname, linkHostname)) return false;
+
+ const path = linkUrl.pathname.replace(/\/$/, "") || "/";
+ if (
+ path === "/" ||
+ path === "/home" ||
+ path === "/index" ||
+ path === "/index.html"
+ )
+ return true;
+ const segments = path.split("/").filter(Boolean);
+ if (segments.length === 1) return true;
+
+ return false;
+ } catch (e) {
+ return false;
+ }
+ }
+
+ const segments = normalizedHref.split("/").filter(Boolean);
+ if (segments.length === 1 && !normalizedHref.includes(".")) return true;
+
+ return false;
+ };
+
+ const collectLogoCandidate = (el: Element, source: string): void => {
+ const rect = el.getBoundingClientRect();
+ const style = getComputedStyleCached(el);
+ const parentLink = el.closest("a");
+
+ const isVisible =
+ rect.width > 0 &&
+ rect.height > 0 &&
+ style.display !== "none" &&
+ style.visibility !== "hidden" &&
+ style.opacity !== "0";
+
+ const bgImage = style.getPropertyValue("background-image");
+ const bgImageUrl = extractBackgroundImageUrl(bgImage);
+
+ const parentAriaLabel = parentLink?.getAttribute("aria-label") || "";
+ const hasLogoAriaLabel = /logo|home|brand/i.test(parentAriaLabel);
+ const hasLogoDataAttr =
+ el.getAttribute("data-framer-name")?.toLowerCase().includes("logo") ||
+ el.getAttribute("data-name")?.toLowerCase().includes("logo");
+ const inHeaderNav = el.closest('header, nav, [role="banner"]') !== null;
+ const hasHomeHref =
+ parentLink && isHomeHref(parentLink.getAttribute("href") || "");
+
+ const elClass = (el.getAttribute("class") || "").toLowerCase();
+ if (/minimized/.test(elClass) && inHeaderNav) {
+ return;
+ }
+
+ const hasBackgroundLogo =
+ bgImageUrl &&
+ (/logo/i.test(bgImageUrl) ||
+ el.closest('[class*="logo" i], [id*="logo" i]') !== null ||
+ (el.tagName.toLowerCase() === "a" && inHeaderNav) ||
+ (parentLink && inHeaderNav && hasHomeHref) ||
+ hasLogoAriaLabel ||
+ hasLogoDataAttr ||
+ (parentLink && inHeaderNav && /home/i.test(parentAriaLabel)));
+
+ const imgSrc = (el as HTMLImageElement).src || "";
+ if (imgSrc) {
+ const ogImageSrc =
+ document
+ .querySelector('meta[property="og:image"]')
+ ?.getAttribute("content") || "";
+ const twitterImageSrc =
+ document
+ .querySelector('meta[name="twitter:image"]')
+ ?.getAttribute("content") || "";
+
+ const matchesOgOrTwitter =
+ (ogImageSrc && imgSrc.includes(ogImageSrc)) ||
+ (twitterImageSrc && imgSrc.includes(twitterImageSrc)) ||
+ (ogImageSrc && ogImageSrc.includes(imgSrc)) ||
+ (twitterImageSrc && twitterImageSrc.includes(imgSrc));
+
+ if (matchesOgOrTwitter) {
+ // Don't skip header/nav logos that are also og:image (many sites use logo as og:image)
+ const headerNavSelector =
+ 'header, nav, [role="banner"], #navbar, [id*="navbar" i], #taskbar, [id*="taskbar" i], [role="menubar"]';
+ const inHeaderOrNav = el.closest(headerNavSelector) !== null;
+ const hasStrongLogoContext =
+ (inHeaderOrNav && hasHomeHref) ||
+ (inHeaderOrNav && /logo/i.test(imgSrc)) ||
+ (inHeaderOrNav &&
+ el.closest('[class*="logo" i], [id*="logo" i]') !== null) ||
+ /logo/i.test(
+ (el.getAttribute("class") || "") + (el.getAttribute("alt") || ""),
+ );
+ if (!hasStrongLogoContext) {
+ return;
+ }
+ }
+ }
+
+ const headerNavSelector =
+ 'header, nav, [role="banner"], #navbar, [id*="navbar" i], #taskbar, [id*="taskbar" i], [role="menubar"]';
+ const inHeader = el.closest(headerNavSelector) !== null;
+ const parentInHeader =
+ parentLink && parentLink.closest(headerNavSelector) !== null;
+
+ let inTopLevelNav = false;
+ if (!inHeader && !parentInHeader) {
+ const taskbarOrMenubar = el.closest(
+ '#taskbar, [id*="taskbar" i], [role="menubar"]',
+ );
+ if (taskbarOrMenubar) {
+ const barRect = taskbarOrMenubar.getBoundingClientRect();
+ if (
+ barRect.top <= CONSTANTS.TASKBAR_TOP_THRESHOLD &&
+ barRect.width > 0 &&
+ barRect.height > 0
+ ) {
+ inTopLevelNav = true;
+ }
+ }
+
+ const topLevelContainer = el.closest(
+ '[class*="sticky" i], [class*="fixed" i], [style*="position: sticky" i], [style*="position:fixed" i]',
+ );
+ if (!inTopLevelNav && topLevelContainer) {
+ const containerRect = topLevelContainer.getBoundingClientRect();
+ const containerStyle = getComputedStyleCached(topLevelContainer);
+ const isAtTop = containerRect.top <= CONSTANTS.CONTAINER_TOP_THRESHOLD;
+ const hasNavLikeContent =
+ topLevelContainer.querySelector('nav, a[href="/"], a[href="./"]') !==
+ null;
+ const hasStickyOrFixed =
+ /sticky|fixed/i.test(containerStyle.position) ||
+ /top-0|top:0|top:\s*0/i.test(containerStyle.cssText);
+
+ if (isAtTop && (hasNavLikeContent || hasStickyOrFixed)) {
+ inTopLevelNav = true;
+ }
+ }
+ }
+
+ const finalInHeader = inHeader || parentInHeader || inTopLevelNav;
+
+ const isSmallFlagImage =
+ rect.width <= 20 &&
+ rect.height <= 20 &&
+ (el as HTMLImageElement).src &&
+ /flag|lang|country/i.test((el as HTMLImageElement).src.toLowerCase());
+
+ const langSwitcherParent = el.closest(
+ 'ul[class*="lang"], li[class*="lang"], div[class*="lang"], nav[class*="lang"], [id*="lang"], [id*="language"]',
+ );
+
+ if (isSmallFlagImage) {
+ return;
+ }
+
+ if (langSwitcherParent) {
+ const parentClasses =
+ getClassNameString(langSwitcherParent).toLowerCase();
+ const parentTagName = langSwitcherParent.tagName;
+
+ const isLanguageList =
+ parentTagName === "UL" && /lang|language/i.test(parentClasses);
+ const isLanguageItem =
+ parentTagName === "LI" && /lang|language/i.test(parentClasses);
+ const isLanguageContainer =
+ (parentTagName === "DIV" || parentTagName === "NAV") &&
+ /header-lang|lang-switch|language-switch|lang-select|language-select|language-list/i.test(
+ parentClasses,
+ );
+ const hasExplicitLangIndicator =
+ /lang-item|language-list|lang-switch|language-switch|lang-select|language-select/i.test(
+ parentClasses,
+ );
+
+ if (
+ isLanguageList ||
+ isLanguageItem ||
+ isLanguageContainer ||
+ hasExplicitLangIndicator
+ ) {
+ return;
+ }
+ }
+
+ const insideButton = el.closest(
+ 'button, [role="button"], input[type="button"], input[type="submit"]',
+ );
+ if (insideButton) {
+ const isLogoInNavContext =
+ finalInHeader && (hasHomeHref || hasLogoAriaLabel || hasLogoDataAttr);
+
+ const inTaskbarOrMenubar = el.closest(
+ '#taskbar, [id*="taskbar" i], [role="menubar"]',
+ );
+ const isLogoInTopBar =
+ inTaskbarOrMenubar &&
+ rect.top <= CONSTANTS.TASKBAR_LOGO_MAX_TOP &&
+ rect.left <= CONSTANTS.TASKBAR_LOGO_MAX_LEFT &&
+ rect.width >= CONSTANTS.TASKBAR_LOGO_MIN_WIDTH &&
+ rect.height >= CONSTANTS.TASKBAR_LOGO_MIN_HEIGHT;
+
+ const buttonHasLogoIndicators =
+ insideButton &&
+ (/logo|brand/i.test(getClassNameString(insideButton)) ||
+ /logo|brand/i.test(
+ insideButton.getAttribute("data-framer-name") || "",
+ ) ||
+ /logo|brand/i.test(insideButton.getAttribute("data-name") || "") ||
+ /logo|home|brand/i.test(
+ insideButton.getAttribute("aria-label") || "",
+ ));
+
+ const elementHasLogoIndicators =
+ /logo|brand/i.test(el.getAttribute("alt") || "") ||
+ /logo|brand/i.test(el.getAttribute("aria-label") || "");
+
+ if (
+ !isLogoInNavContext &&
+ !isLogoInTopBar &&
+ !buttonHasLogoIndicators &&
+ !elementHasLogoIndicators
+ ) {
+ return;
+ }
+ }
+
+ const elementClasses = getClassNameString(el).toLowerCase();
+ const elementId = (el.id || "").toLowerCase();
+ const ariaLabel = (el.getAttribute?.("aria-label") || "").toLowerCase();
+
+ const hasSearchClass = /search|magnif/i.test(elementClasses);
+ const hasSearchId = /search|magnif/i.test(elementId);
+ const hasSearchAriaLabel = /search/i.test(ariaLabel);
+
+ const parent = el.parentElement;
+ const isInSearchForm =
+ parent &&
+ ((parent.tagName === "FORM" &&
+ /search/i.test(getClassNameString(parent) + (parent.id || ""))) ||
+ (parent.matches &&
+ parent.matches(
+ 'form[class*="search"], form[id*="search"], button[class*="search"], button[id*="search"], [role="search"]',
+ )));
+
+ const inSearchButton = el.closest(
+ 'button[class*="search"], button[id*="search"], a[class*="search"], a[id*="search"]',
+ );
+
+ const isSearchIcon =
+ hasSearchClass ||
+ hasSearchId ||
+ hasSearchAriaLabel ||
+ isInSearchForm ||
+ !!inSearchButton;
+
+ if (isSearchIcon) {
+ return;
+ }
+
+ const isUIIcon =
+ /icon|menu|hamburger|bars|close|times|cart|user|account|profile|settings|notification|bell|chevron|arrow|caret|dropdown/i.test(
+ elementClasses,
+ ) ||
+ /icon|menu|hamburger|cart|user|bell/i.test(elementId) ||
+ /menu|close|cart|user|settings/i.test(ariaLabel);
+
+ if (isUIIcon) {
+ const parentLinkForLogo = el.closest("a");
+ const parentDataNav = parentLinkForLogo?.getAttribute("data-nav") || "";
+ const parentDataGaName =
+ parentLinkForLogo?.getAttribute("data-ga-name") || "";
+ const parentLinkAriaLabel =
+ parentLinkForLogo?.getAttribute("aria-label") || "";
+ const parentLinkHref = parentLinkForLogo?.getAttribute("href") || "";
+
+ const hasExplicitLogoIndicator =
+ /logo|brand|site-name|site-title/i.test(elementClasses) ||
+ /logo|brand/i.test(elementId) ||
+ /logo|brand/i.test(parentDataNav) ||
+ /logo|brand/i.test(parentDataGaName) ||
+ /\bhome\b/i.test(parentLinkAriaLabel) ||
+ isHomeHref(parentLinkHref);
+
+ if (!hasExplicitLogoIndicator) {
+ return;
+ }
+ }
+
+ const elAlt = (
+ el.getAttribute?.("alt") ||
+ (el as HTMLImageElement).alt ||
+ ""
+ ).toLowerCase();
+ if (
+ /mobile menu|hamburger|toggle navigation|menu open|menu close|close-mobile|hamburger-img/i.test(
+ elAlt,
+ )
+ ) {
+ return;
+ }
+
+ const anchorParent = el.closest("a");
+ const href = anchorParent ? anchorParent.getAttribute("href") || "" : "";
+ const anchorAriaLabel = (
+ anchorParent?.getAttribute("aria-label") || ""
+ ).toLowerCase();
+ const ariaLabelHomeMatch =
+ /\bhome(page)?\b/.test(ariaLabel) ||
+ /\bhome(page)?\b/.test(anchorAriaLabel);
+ const candidateAriaLabel = ariaLabel || anchorAriaLabel || "";
+
+ if (href && href.trim()) {
+ const hrefLower = href.toLowerCase().trim();
+
+ const isExternalLink =
+ hrefLower.startsWith("http://") ||
+ hrefLower.startsWith("https://") ||
+ hrefLower.startsWith("//");
+
+ if (isExternalLink) {
+ const externalServiceDomains = [
+ "github.com",
+ "twitter.com",
+ "x.com",
+ "facebook.com",
+ "linkedin.com",
+ "instagram.com",
+ "youtube.com",
+ "discord.com",
+ "slack.com",
+ "npmjs.com",
+ "pypi.org",
+ "crates.io",
+ "packagist.org",
+ "badge.fury.io",
+ "shields.io",
+ "img.shields.io",
+ "badgen.net",
+ "codecov.io",
+ "coveralls.io",
+ "circleci.com",
+ "travis-ci.org",
+ "app.netlify.com",
+ "vercel.com",
+ ];
+
+ try {
+ const currentHostname = window.location.hostname.toLowerCase();
+ const linkUrl = new URL(href, window.location.origin);
+ const linkHostname = linkUrl.hostname.toLowerCase();
+ const isSameSite = isSameBrandHost(currentHostname, linkHostname);
+ if (
+ !isSameSite &&
+ externalServiceDomains.some(domain => hrefLower.includes(domain))
+ ) {
+ return;
+ }
+
+ if (!isSameSite) {
+ return;
+ }
+ } catch (e) {
+ return;
+ }
+ }
+ }
+
+ const isSvg = el.tagName.toLowerCase() === "svg";
+
+ let logoSvgScore = 0;
+ if (isSvg) {
+ const svgWidth =
+ rect.width || parseFloat(el.getAttribute("width") || "0") || 0;
+ const svgHeight =
+ rect.height || parseFloat(el.getAttribute("height") || "0") || 0;
+
+ const hasTextElements = el.querySelector("text") !== null;
+ if (hasTextElements) {
+ logoSvgScore -= 50;
+ }
+
+ const hasAnimations =
+ el.querySelector("animate, animateTransform, animateMotion") !== null;
+ if (hasAnimations) {
+ logoSvgScore += 30;
+ }
+
+ const pathCount = el.querySelectorAll("path").length;
+ const groupCount = el.querySelectorAll("g").length;
+ logoSvgScore += Math.min(pathCount * 2, 40);
+ logoSvgScore += Math.min(groupCount, 20);
+
+ const area = svgWidth * svgHeight;
+ if (area > 10000) logoSvgScore += 20;
+ else if (area > 5000) logoSvgScore += 10;
+ else if (area < 1000) logoSvgScore -= 20;
+
+ if (svgWidth > 0 && svgHeight > 0) {
+ const aspectRatio =
+ Math.max(svgWidth, svgHeight) / Math.min(svgWidth, svgHeight);
+ if (aspectRatio < 1.5) logoSvgScore += 10;
+ else if (aspectRatio > 5) logoSvgScore -= 15;
+ }
+
+ if (
+ pathCount > 0 &&
+ pathCount < 20 &&
+ groupCount === 0 &&
+ !hasAnimations
+ ) {
+ logoSvgScore -= 30;
+ }
+ }
+
+ let alt = "";
+ let srcMatch = false;
+ let altMatch = false;
+ let classMatch = false;
+ let hrefMatch = false;
+
+ if (isSvg) {
+ const svgId = el.id || "";
+ const svgClass = getClassNameString(el);
+ const svgAriaLabel = el.getAttribute("aria-label") || "";
+ const svgTitle = el.querySelector("title")?.textContent || "";
+ const svgText = el.textContent?.trim() || "";
+
+ alt = svgAriaLabel || svgTitle || svgText || svgId || "";
+ altMatch =
+ /logo/i.test(svgId) ||
+ /logo/i.test(svgAriaLabel) ||
+ /logo/i.test(svgTitle);
+ classMatch = /logo/i.test(svgClass);
+ srcMatch = el.closest('[class*="logo" i], [id*="logo" i]') !== null;
+ } else {
+ const imgId = el.id || "";
+ const parentLinkForAlt = el.closest("a");
+ alt =
+ ((el as HTMLImageElement).alt && (el as HTMLImageElement).alt.trim()) ||
+ (parentLinkForAlt?.getAttribute("aria-label") || "").trim() ||
+ "";
+
+ const idMatch = /logo/i.test(imgId);
+ srcMatch =
+ ((el as HTMLImageElement).src
+ ? /logo/i.test((el as HTMLImageElement).src)
+ : false) || idMatch;
+ altMatch = /logo/i.test(alt);
+
+ const imgClass = getClassNameString(el);
+ classMatch =
+ /logo/i.test(imgClass) ||
+ el.closest('[class*="logo" i], [id*="logo" i]') !== null ||
+ idMatch;
+ }
+
+ let src = "";
+
+ if (isSvg) {
+ const imageEl = el.querySelector("image");
+ const imageHref =
+ imageEl?.getAttribute("href") ||
+ imageEl?.getAttribute("xlink:href") ||
+ "";
+ if (imageHref) {
+ try {
+ src = new URL(imageHref, window.location.origin).href;
+ } catch (e) {
+ src = imageHref;
+ }
+ if (!srcMatch) srcMatch = /logo/i.test(imageHref);
+ }
+
+ if (!src) {
+ try {
+ const resolvedSvg = resolveSvgStyles(el as SVGSVGElement);
+ const serializer = new XMLSerializer();
+ src =
+ "data:image/svg+xml;utf8," +
+ encodeURIComponent(serializer.serializeToString(resolvedSvg));
+ } catch (e) {
+ recordError("resolveSvgStyles", e);
+ try {
+ const serializer = new XMLSerializer();
+ src =
+ "data:image/svg+xml;utf8," +
+ encodeURIComponent(serializer.serializeToString(el));
+ } catch (e2) {
+ recordError("XMLSerializer fallback", e2);
+ const parentLinkForSvg = el.closest("a");
+ const parentAria = (
+ parentLinkForSvg?.getAttribute("aria-label") || ""
+ ).toLowerCase();
+ const inHeaderNavForSvg =
+ el.closest(
+ 'header, nav, [role="banner"], #navbar, [id*="navbar" i], #taskbar, [id*="taskbar" i], [role="menubar"]',
+ ) !== null;
+ const strongLogoCandidate =
+ inHeaderNavForSvg &&
+ parentLinkForSvg &&
+ /logo|homepage|home\s*page/i.test(parentAria);
+ if (strongLogoCandidate) {
+ try {
+ const raw = el.cloneNode(true);
+ const serializer = new XMLSerializer();
+ src =
+ "data:image/svg+xml;utf8," +
+ encodeURIComponent(serializer.serializeToString(raw));
+ } catch (e3) {
+ recordError("svg-strong-candidate-serialize", e3);
+ return;
+ }
+ } else {
+ return;
+ }
+ }
+ }
+ }
+ } else {
+ src = (el as HTMLImageElement).src || "";
+
+ if (!src && bgImageUrl) {
+ const shouldTreatAsLogo =
+ hasBackgroundLogo ||
+ hasLogoDataAttr ||
+ hasLogoAriaLabel ||
+ hasHomeHref ||
+ (parentLink && inHeaderNav);
+
+ if (shouldTreatAsLogo) {
+ if (bgImageUrl.startsWith("data:")) {
+ src = bgImageUrl;
+ } else {
+ try {
+ const url = new URL(bgImageUrl, window.location.origin);
+ src = url.href;
+ } catch (e) {
+ if (bgImageUrl.startsWith("/")) {
+ src = window.location.origin + bgImageUrl;
+ } else if (
+ bgImageUrl.startsWith("http://") ||
+ bgImageUrl.startsWith("https://")
+ ) {
+ src = bgImageUrl;
+ } else {
+ src = window.location.origin + "/" + bgImageUrl;
+ }
+ }
+ }
+
+ if (!srcMatch)
+ srcMatch = /logo/i.test(bgImageUrl) || !!hasLogoDataAttr;
+ if (!classMatch)
+ classMatch =
+ el.closest('[class*="logo" i], [id*="logo" i]') !== null ||
+ !!hasLogoDataAttr;
+ if (!altMatch && hasLogoAriaLabel) {
+ altMatch = true;
+ alt = parentAriaLabel;
+ }
+ }
+ }
+ }
+
+ if (href) {
+ const normalizedHref = href.toLowerCase().trim();
+
+ hrefMatch =
+ normalizedHref === "/" ||
+ normalizedHref === "/home" ||
+ normalizedHref === "/index" ||
+ normalizedHref === "" ||
+ normalizedHref === "./";
+
+ if (
+ !hrefMatch &&
+ (normalizedHref.startsWith("http://") ||
+ normalizedHref.startsWith("https://") ||
+ normalizedHref.startsWith("//"))
+ ) {
+ try {
+ const currentHostname = window.location.hostname.toLowerCase();
+ const linkUrl = new URL(href, window.location.origin);
+ const linkHostname = linkUrl.hostname.toLowerCase();
+
+ if (
+ isSameBrandHost(currentHostname, linkHostname) &&
+ (linkUrl.pathname === "/" ||
+ linkUrl.pathname === "/home" ||
+ linkUrl.pathname === "/index.html")
+ ) {
+ hrefMatch = true;
+ }
+ } catch (e) {
+ // Ignore
+ }
+ }
+ }
+ if (!hrefMatch && ariaLabelHomeMatch) {
+ hrefMatch = true;
+ }
+ if (!hrefMatch && hasHomeHref && (hasLogoDataAttr || hasLogoAriaLabel)) {
+ hrefMatch = true;
+ }
+
+ if (src) {
+ const isSvgDataUri = src.startsWith("data:image/svg+xml");
+ const finalIsSvg = isSvg || isSvgDataUri;
+
+ const title = finalIsSvg
+ ? el.querySelector?.("title")?.textContent?.trim() || undefined
+ : el.getAttribute?.("title") ||
+ ((el as HTMLImageElement).title !== undefined &&
+ (el as HTMLImageElement).title !== ""
+ ? (el as HTMLImageElement).title
+ : undefined);
+
+ let posWidth = rect.width;
+ let posHeight = rect.height;
+ if (posWidth <= 0 || posHeight <= 0) {
+ const attrW = el.getAttribute?.("width");
+ const attrH = el.getAttribute?.("height");
+ const w = attrW != null ? parseFloat(attrW) : NaN;
+ const h = attrH != null ? parseFloat(attrH) : NaN;
+ if (w > 0) posWidth = w;
+ if (h > 0) posHeight = h;
+ if (
+ (posWidth <= 0 || posHeight <= 0) &&
+ finalIsSvg &&
+ el.getAttribute?.("viewBox")
+ ) {
+ const vb = el
+ .getAttribute("viewBox")!
+ .trim()
+ .split(/[\s,]+/);
+ if (vb.length >= 4) {
+ const vw = parseFloat(vb[2]);
+ const vh = parseFloat(vb[3]);
+ if (vw > 0 && !Number.isNaN(vw))
+ posWidth = posWidth <= 0 ? vw : posWidth;
+ if (vh > 0 && !Number.isNaN(vh))
+ posHeight = posHeight <= 0 ? vh : posHeight;
+ }
+ }
+ }
+
+ const actuallyVisible = isVisible && rect.width > 0 && rect.height > 0;
+ const positionTop = rect.width > 0 && rect.height > 0 ? rect.top : 0;
+ const positionLeft = rect.width > 0 && rect.height > 0 ? rect.left : 0;
+
+ const logoCandidate: LogoCandidate = {
+ src,
+ alt,
+ ariaLabel: candidateAriaLabel || undefined,
+ title: title || undefined,
+ isSvg: finalIsSvg,
+ isVisible: actuallyVisible,
+ location: finalInHeader ? "header" : "body",
+ position: {
+ top: positionTop,
+ left: positionLeft,
+ width: posWidth,
+ height: posHeight,
+ },
+ indicators: {
+ inHeader: !!finalInHeader,
+ altMatch,
+ srcMatch,
+ classMatch,
+ hrefMatch,
+ },
+ href: href || undefined,
+ source,
+ logoSvgScore: finalIsSvg ? (isSvgDataUri ? 80 : logoSvgScore) : 100,
+ };
+
+ logoCandidates.push(logoCandidate);
+ }
+ };
+
+ const allLogoSelectors = [
+ "header a img, header a svg, header img, header svg",
+ "[class*='theme-site-logo' i] img, [class*='elementor-widget-theme-site-logo' i] img",
+ "header a > svg, nav a > svg",
+ '[class*="header" i] a img, [class*="header" i] a svg, [class*="header" i] img, [class*="header" i] svg',
+ '[id*="header" i] a img, [id*="header" i] a svg, [id*="header" i] img, [id*="header" i] svg',
+ "nav a img, nav a svg, nav img, nav svg",
+ '[role="banner"] a img, [role="banner"] a svg, [role="banner"] img, [role="banner"] svg',
+ 'a[aria-label*="logo" i] > svg, a[aria-label*="homepage" i] > svg',
+ "#navbar a img, #navbar a svg, #navbar img, #navbar svg",
+ '[id*="navbar" i] a img, [id*="navbar" i] a svg, [id*="navbar" i] img, [id*="navbar" i] svg',
+ '[id*="navigation" i] a img, [id*="navigation" i] a svg, [id*="navigation" i] img, [id*="navigation" i] svg',
+ '[class*="navbar" i] a img, [class*="navbar" i] a svg, [class*="navbar" i] img, [class*="navbar" i] svg',
+ '[class*="globalnav" i] a img, [class*="globalnav" i] a svg, [class*="globalnav" i] img, [class*="globalnav" i] svg',
+ '[class*="nav-wrapper" i] a img, [class*="nav-wrapper" i] a svg, [class*="nav-wrapper" i] img, [class*="nav-wrapper" i] svg',
+ 'a[data-nav*="logo" i] img, a[data-nav*="logo" i] svg',
+ 'a[data-tracking-type*="logo" i] img, a[data-tracking-type*="logo" i] svg',
+ 'a[data-ga-name*="logo" i] img, a[data-ga-name*="logo" i] svg',
+ 'a[class*="logo" i] img, a[class*="logo" i] svg',
+ 'a[data-qa*="logo" i] img, a[data-qa*="logo" i] svg',
+ 'a[aria-label*="logo" i] img, a[aria-label*="logo" i] svg',
+ '[class*="header-logo" i] img, [class*="header-logo" i] svg',
+ '[class*="container-logo" i] a img, [class*="container-logo" i] a svg',
+ '[class*="logo" i] img, [class*="logo" i] svg',
+ '[id*="logo" i] img, [id*="logo" i] svg',
+ 'img[class*="nav-logo" i], svg[class*="nav-logo" i]',
+ 'img[class*="logo" i], svg[class*="logo" i]',
+ 'a[href="/"] svg, a[href="./"] svg',
+ 'a[href="/"] img, a[href="./"] img',
+ "#taskbar svg, #taskbar img",
+ '[id*="taskbar" i] svg, [id*="taskbar" i] img',
+ '[role="menubar"] svg, [role="menubar"] img',
+ ];
+
+ allLogoSelectors.forEach(selector => {
+ const matches = querySelectorAllIncludingShadowRoots(selector);
+ matches.forEach(el => {
+ collectLogoCandidate(el, selector);
+ });
+ });
+
+ const logoContainerSelectors = [
+ '[class*="logo" i] a',
+ '[id*="logo" i] a',
+ 'header a[class*="logo" i]',
+ 'header [class*="logo" i] a',
+ 'nav a[class*="logo" i]',
+ 'nav [class*="logo" i] a',
+ "header a > div",
+ "header a > span",
+ "nav a > div",
+ "nav a > span",
+ '[role="banner"] a > div',
+ '[role="banner"] a > span',
+ 'a[aria-label*="logo" i] > div',
+ 'a[aria-label*="logo" i] > span',
+ 'a[aria-label*="home" i] > div',
+ 'a[aria-label*="home" i] > span',
+ 'a[href="./"] > div',
+ 'a[href="./"] > span',
+ 'a[href="/"] > div',
+ 'a[href="/"] > span',
+ 'a[href="/home"] > div',
+ 'a[href="/home"] > span',
+ 'a[aria-label*="home" i] div[data-framer-name*="logo" i]',
+ 'a[aria-label*="home" i] span[data-framer-name*="logo" i]',
+ 'a[href="./"] div[data-framer-name*="logo" i]',
+ 'a[href="./"] span[data-framer-name*="logo" i]',
+ 'a[href="/"] div[data-framer-name*="logo" i]',
+ 'a[href="/"] span[data-framer-name*="logo" i]',
+ 'div[data-framer-name*="logo" i]',
+ 'span[data-framer-name*="logo" i]',
+ 'div[data-name*="logo" i]',
+ 'span[data-name*="logo" i]',
+ '[class*="logo" i][class*="shape" i]',
+ '[class*="logo" i][class*="icon" i]',
+ 'nav [class*="logo" i]',
+ 'header [class*="logo" i]',
+ '[role="banner"] [class*="logo" i]',
+ ];
+
+ logoContainerSelectors.forEach(selector => {
+ const matches = querySelectorAllIncludingShadowRoots(selector);
+ matches.forEach(el => {
+ const style = getComputedStyleCached(el);
+ const bgImage = style.getPropertyValue("background-image");
+ const bgImageUrl = extractBackgroundImageUrl(bgImage);
+
+ const elClassName =
+ (typeof el.className === "string"
+ ? el.className
+ : el.getAttribute("class")) || "";
+ const elHasLogoClass = /logo/i.test(elClassName);
+
+ if (bgImageUrl) {
+ const rect = el.getBoundingClientRect();
+ const isVisible =
+ rect.width > 0 &&
+ rect.height > 0 &&
+ style.display !== "none" &&
+ style.visibility !== "hidden" &&
+ style.opacity !== "0";
+ const hasReasonableSize =
+ rect.width >= CONSTANTS.MIN_LOGO_SIZE &&
+ rect.height >= CONSTANTS.MIN_LOGO_SIZE;
+ const inLogoContext =
+ el.closest(
+ '[class*="logo" i], [id*="logo" i], header, nav, [role="banner"]',
+ ) !== null;
+
+ const parentLink = el.closest("a");
+ const hasLogoDataAttr =
+ el.getAttribute("data-framer-name")?.toLowerCase().includes("logo") ||
+ el.getAttribute("data-name")?.toLowerCase().includes("logo");
+ const hasLogoAriaLabel =
+ parentLink &&
+ /logo|home|brand/i.test(parentLink.getAttribute("aria-label") || "");
+ const hasHomeHrefCheck =
+ parentLink && isHomeHref(parentLink.getAttribute("href") || "");
+
+ const hasStrongLogoIndicators =
+ elHasLogoClass ||
+ hasLogoDataAttr ||
+ hasLogoAriaLabel ||
+ hasHomeHrefCheck;
+ const sizeRequirement = hasStrongLogoIndicators
+ ? rect.width > 0 && rect.height > 0
+ : hasReasonableSize;
+
+ if (
+ isVisible &&
+ sizeRequirement &&
+ (inLogoContext || hasStrongLogoIndicators)
+ ) {
+ collectLogoCandidate(el, "background-image-logo");
+ }
+ }
+ });
+ });
+
+ const allElementsWithBg = Array.from(document.querySelectorAll("div, span"));
+
+ const allDivsWithBgImage = allElementsWithBg.filter(el => {
+ const style = getComputedStyleCached(el);
+ const bgImage = style.getPropertyValue("background-image");
+ const bgImageUrl = extractBackgroundImageUrl(bgImage);
+
+ if (!bgImageUrl) return false;
+
+ const className = el.className || "";
+ const parentLink = el.closest("a");
+
+ const hasLogoDataAttr =
+ el.getAttribute("data-framer-name")?.toLowerCase().includes("logo") ||
+ el.getAttribute("data-name")?.toLowerCase().includes("logo");
+ const hasLogoClass = (typeof className === "string" ? className : "")
+ .toLowerCase()
+ .includes("logo");
+ const hasLogoAriaLabel =
+ parentLink &&
+ /logo|home|brand/i.test(parentLink.getAttribute("aria-label") || "");
+ const hasHomeHrefCheck =
+ parentLink && isHomeHref(parentLink.getAttribute("href") || "");
+ const inHeaderNavCheck =
+ el.closest('header, nav, [role="banner"]') !== null;
+
+ return (
+ hasLogoDataAttr ||
+ hasLogoClass ||
+ (hasLogoAriaLabel && hasHomeHrefCheck) ||
+ (hasLogoAriaLabel && inHeaderNavCheck) ||
+ (hasHomeHrefCheck && inHeaderNavCheck)
+ );
+ });
+
+ allDivsWithBgImage.forEach(el => {
+ const rect = el.getBoundingClientRect();
+ const alreadyCollected = logoCandidates.some(c => {
+ return (
+ Math.abs(c.position.top - rect.top) < 1 &&
+ Math.abs(c.position.left - rect.left) < 1 &&
+ Math.abs(c.position.width - rect.width) < 1 &&
+ Math.abs(c.position.height - rect.height) < 1
+ );
+ });
+ if (!alreadyCollected) {
+ collectLogoCandidate(el, "background-image-logo-indicators");
+ }
+ });
+
+ const excludeSelectors =
+ '[class*="testimonial"], [class*="client"], [class*="partner"], [class*="customer"], [class*="case-study"], [id*="testimonial"], [id*="client"], [id*="partner"], [id*="customer"], [id*="case-study"], footer, [class*="footer"]';
+
+ const allImages = querySelectorAllIncludingShadowRoots("img");
+ allImages.forEach(img => {
+ if (
+ /logo/i.test((img as HTMLImageElement).alt || "") ||
+ /logo/i.test((img as HTMLImageElement).src) ||
+ img.closest('[class*="logo" i]')
+ ) {
+ if (!img.closest(excludeSelectors)) {
+ collectLogoCandidate(img, "document.images");
+ }
+ }
+ });
+
+ const allSvgs = querySelectorAllIncludingShadowRoots("svg");
+ allSvgs.forEach(svg => {
+ const svgRect = svg.getBoundingClientRect();
+ const alreadyCollected = logoCandidates.some(c => {
+ if (!c.isSvg) return false;
+ return (
+ Math.abs(c.position.top - svgRect.top) < 1 &&
+ Math.abs(c.position.left - svgRect.left) < 1 &&
+ Math.abs(c.position.width - svgRect.width) < 1 &&
+ Math.abs(c.position.height - svgRect.height) < 1
+ );
+ });
+ if (alreadyCollected) {
+ return;
+ }
+
+ const insideButton = svg.closest(
+ 'button, [role="button"], input[type="button"], input[type="submit"]',
+ );
+ if (insideButton) {
+ const inTaskbarOrMenubar = svg.closest(
+ '#taskbar, [id*="taskbar" i], [role="menubar"]',
+ );
+ const isTopBarLogo =
+ inTaskbarOrMenubar &&
+ svgRect.top <= CONSTANTS.TASKBAR_LOGO_MAX_TOP &&
+ svgRect.left <= CONSTANTS.TASKBAR_LOGO_MAX_LEFT &&
+ svgRect.width >= CONSTANTS.TASKBAR_LOGO_MIN_WIDTH &&
+ svgRect.height >= CONSTANTS.TASKBAR_LOGO_MIN_HEIGHT;
+ if (!isTopBarLogo) {
+ return;
+ }
+ }
+
+ const svgId = svg.id || "";
+ const svgClass = getClassNameString(svg);
+ const svgAriaLabel = svg.getAttribute("aria-label") || "";
+ const svgTitle = svg.querySelector("title")?.textContent || "";
+
+ const hasSearchId = /search|magnif/i.test(svgId);
+ const hasSearchClass = /search|magnif/i.test(svgClass);
+ const hasSearchAriaLabel = /search/i.test(svgAriaLabel);
+ const hasSearchTitle = /search/i.test(svgTitle);
+
+ const parent = svg.parentElement;
+ const isInSearchForm =
+ parent &&
+ ((parent.tagName === "FORM" &&
+ /search/i.test(getClassNameString(parent) + (parent.id || ""))) ||
+ (parent.matches &&
+ parent.matches(
+ 'form[class*="search"], form[id*="search"], button[class*="search"], button[id*="search"], [role="search"]',
+ )));
+
+ const inSearchButton = svg.closest(
+ 'button[class*="search"], button[id*="search"], a[class*="search"], a[id*="search"]',
+ );
+
+ const isSearchIcon =
+ hasSearchId ||
+ hasSearchClass ||
+ hasSearchAriaLabel ||
+ hasSearchTitle ||
+ isInSearchForm ||
+ !!inSearchButton;
+
+ if (isSearchIcon) {
+ return;
+ }
+
+ const isUIIcon =
+ /icon|menu|hamburger|bars|close|times|cart|user|account|profile|settings|notification|bell|chevron|arrow|caret|dropdown/i.test(
+ svgClass,
+ ) ||
+ /icon|menu|hamburger|cart|user|bell/i.test(svgId) ||
+ /menu|close|cart|user|settings/i.test(svgAriaLabel);
+
+ const hasLogoId = /logo/i.test(svgId);
+ const hasLogoClass = /logo/i.test(svgClass);
+ const hasLogoAriaLabel = /logo/i.test(svgAriaLabel);
+ const hasLogoTitle = /logo/i.test(svgTitle);
+ const inHeaderNav = svg.closest(
+ 'header, nav, [role="banner"], #navbar, [id*="navbar" i], #taskbar, [id*="taskbar" i], [role="menubar"]',
+ );
+ const inLogoContainer = svg.closest('[class*="logo" i], [id*="logo" i]');
+ const inHeaderNavArea = !!inHeaderNav;
+ const inAnchorInHeader = svg.closest("a") && inHeaderNav;
+
+ if (isUIIcon) {
+ const hasExplicitLogoIndicator =
+ hasLogoId ||
+ hasLogoClass ||
+ hasLogoAriaLabel ||
+ hasLogoTitle ||
+ inLogoContainer;
+ if (!hasExplicitLogoIndicator) {
+ return;
+ }
+ }
+
+ const shouldCollect =
+ hasLogoId ||
+ hasLogoClass ||
+ hasLogoAriaLabel ||
+ hasLogoTitle ||
+ inLogoContainer ||
+ inHeaderNavArea ||
+ inAnchorInHeader;
+
+ if (shouldCollect) {
+ if (!svg.closest(excludeSelectors)) {
+ collectLogoCandidate(svg, "document.querySelectorAll(svg)");
+ }
+ }
+ });
+
+ const homeLinks = querySelectorAllIncludingShadowRoots("a[href]").filter(a =>
+ isHomeHref(a.getAttribute("href") || ""),
+ );
+ const fallbackCandidates: Array<{ el: Element; top: number; left: number }> =
+ [];
+ homeLinks.forEach(link => {
+ const imgs = link.querySelectorAll("img, svg");
+ imgs.forEach(el => {
+ const rect = el.getBoundingClientRect();
+ const inTop = rect.top >= 0 && rect.top < CONSTANTS.TOP_PAGE_THRESHOLD_PX;
+ const hasSize = rect.width > 0 && rect.height > 0;
+ if (inTop && hasSize)
+ fallbackCandidates.push({ el, top: rect.top, left: rect.left });
+ });
+ });
+ fallbackCandidates.sort((a, b) => a.top - b.top || a.left - b.left);
+ fallbackCandidates.forEach(({ el }) =>
+ collectLogoCandidate(el, "fallback-top-home-link"),
+ );
+
+ const isHomeLinkSource = (c: LogoCandidate): boolean =>
+ typeof c.source === "string" &&
+ (c.source.indexOf('href="/"') !== -1 ||
+ c.source.indexOf('href="./"') !== -1 ||
+ c.source === "fallback-top-home-link");
+
+ const bySrc = new Map<string, LogoCandidate>();
+ logoCandidates.forEach(candidate => {
+ const existing = bySrc.get(candidate.src);
+ if (!existing) {
+ bySrc.set(candidate.src, candidate);
+ return;
+ }
+ const candidateFromHomeLink = isHomeLinkSource(candidate);
+ const existingFromHomeLink = isHomeLinkSource(existing);
+ if (candidateFromHomeLink && !existingFromHomeLink) {
+ bySrc.set(candidate.src, candidate);
+ return;
+ }
+ if (!candidateFromHomeLink && existingFromHomeLink) {
+ return;
+ }
+ const candidateVisible = !!candidate.isVisible;
+ const existingVisible = !!existing.isVisible;
+ if (candidateVisible && !existingVisible) {
+ bySrc.set(candidate.src, candidate);
+ return;
+ }
+ if (!candidateVisible && existingVisible) {
+ return;
+ }
+ const area =
+ (candidate.position.width || 0) * (candidate.position.height || 0);
+ const existingArea =
+ (existing.position.width || 0) * (existing.position.height || 0);
+ if (area > existingArea) {
+ bySrc.set(candidate.src, candidate);
+ }
+ });
+ const uniqueCandidates = Array.from(bySrc.values());
+
+ let candidatesToPick = uniqueCandidates.filter(c => c.isVisible);
+ if (candidatesToPick.length === 0 && uniqueCandidates.length > 0) {
+ candidatesToPick = uniqueCandidates;
+ }
+
+ if (candidatesToPick.length > 0) {
+ const best = candidatesToPick.reduce<LogoCandidate | null>(
+ (best, candidate) => {
+ if (!best) return candidate;
+
+ const candidateHomeLinkImg =
+ !candidate.isSvg &&
+ !!candidate.indicators.hrefMatch &&
+ (candidate.indicators.inHeader || isHomeLinkSource(candidate));
+ const bestHomeLinkImg =
+ !best.isSvg &&
+ !!best.indicators.hrefMatch &&
+ (best.indicators.inHeader || isHomeLinkSource(best));
+ if (candidateHomeLinkImg && !bestHomeLinkImg) return candidate;
+ if (!candidateHomeLinkImg && bestHomeLinkImg) return best;
+
+ const candidateArea =
+ candidate.position.width * candidate.position.height;
+ const bestArea = best.position.width * best.position.height;
+ const candidateIsTiny = candidateArea < CONSTANTS.MIN_SIGNIFICANT_AREA;
+ const bestIsTiny = bestArea < CONSTANTS.MIN_SIGNIFICANT_AREA;
+
+ if (candidateIsTiny && !bestIsTiny) return best;
+ if (!candidateIsTiny && bestIsTiny) return candidate;
+
+ if (!candidate.isSvg && best.isSvg) return candidate;
+ if (candidate.isSvg && !best.isSvg) return best;
+
+ if (candidate.isSvg && best.isSvg) {
+ const candidateScore = candidate.logoSvgScore || 0;
+ const bestScore = best.logoSvgScore || 0;
+ if (candidateScore > bestScore) return candidate;
+ if (candidateScore < bestScore) return best;
+ }
+
+ if (candidate.indicators.inHeader && !best.indicators.inHeader)
+ return candidate;
+ if (!candidate.indicators.inHeader && best.indicators.inHeader)
+ return best;
+
+ if (candidate.indicators.hrefMatch && !best.indicators.hrefMatch)
+ return candidate;
+ if (!candidate.indicators.hrefMatch && best.indicators.hrefMatch)
+ return best;
+
+ if (candidate.indicators.classMatch && !best.indicators.classMatch)
+ return candidate;
+ if (!candidate.indicators.classMatch && best.indicators.classMatch)
+ return best;
+
+ const candidateTooSmall =
+ candidate.position.width < CONSTANTS.MIN_LOGO_SIZE ||
+ candidate.position.height < CONSTANTS.MIN_LOGO_SIZE;
+ const bestTooSmall =
+ best.position.width < CONSTANTS.MIN_LOGO_SIZE ||
+ best.position.height < CONSTANTS.MIN_LOGO_SIZE;
+
+ if (candidateTooSmall && !bestTooSmall) return best;
+ if (!candidateTooSmall && bestTooSmall) return candidate;
+
+ return candidate.position.top < best.position.top ? candidate : best;
+ },
+ null,
+ );
+
+ if (best) {
+ if (best.isSvg) {
+ push(best.src, "logo-svg");
+ } else {
+ push(best.src, "logo");
+ }
+ }
+ }
+
+ return { images: imgs, logoCandidates: uniqueCandidates };
+};
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
new file mode 100644
index 000000000..8a59cc9bd
--- /dev/null
+++ b/apps/api/src/scraper/scrapeURL/engines/fire-engine/branding-script/index.ts
@@ -0,0 +1,72 @@
+import { errors } from "./helpers";
+import { collectCSSData } from "./css-data";
+import { sampleElements, getStyleSnapshot } from "./elements";
+import { findImages } from "./images";
+import {
+ getTypography,
+ detectFrameworkHints,
+ detectColorScheme,
+ extractBrandName,
+ getBackgroundCandidates,
+} from "./brand-utils";
+
+interface BrandingResult {
+ branding: {
+ cssData: ReturnType<typeof collectCSSData>;
+ snapshots: ReturnType<typeof getStyleSnapshot>[];
+ images: ReturnType<typeof findImages>["images"];
+ logoCandidates: ReturnType<typeof findImages>["logoCandidates"];
+ brandName: string;
+ pageTitle: string;
+ pageUrl: string;
+ typography: ReturnType<typeof getTypography>;
+ frameworkHints: string[];
+ colorScheme: "dark" | "light";
+ pageBackground: string | null;
+ backgroundCandidates: ReturnType<typeof getBackgroundCandidates>;
+ errors?: Array<{ context: string; message: string; timestamp: number }>;
+ };
+}
+
+export const extractBrandDesign = (): BrandingResult => {
+ const cssData = collectCSSData();
+ const elements = sampleElements();
+ const snapshots = elements.map(getStyleSnapshot);
+ const imageData = findImages();
+ const typography = getTypography();
+ const frameworkHints = detectFrameworkHints();
+ const colorScheme = detectColorScheme();
+ const brandName = extractBrandName();
+ const backgroundCandidates = getBackgroundCandidates();
+
+ const pageBackground =
+ backgroundCandidates.length > 0 ? backgroundCandidates[0].color : null;
+ const pageTitle = document.title || "";
+ const pageUrl =
+ typeof window !== "undefined" && window.location
+ ? window.location.href
+ : "";
+
+ return {
+ branding: {
+ cssData,
+ snapshots,
+ images: imageData.images,
+ logoCandidates: imageData.logoCandidates,
+ brandName,
+ pageTitle,
+ pageUrl,
+ typography,
+ frameworkHints,
+ colorScheme,
+ pageBackground,
+ backgroundCandidates,
+ errors: errors.length > 0 ? errors : undefined,
+ },
+ };
+};
+
+// Auto-execute when loaded in browser context (IIFE pattern)
+(function __extractBrandDesign() {
+ return extractBrandDesign();
+})();
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
new file mode 100644
index 000000000..03c98cef8
--- /dev/null
+++ b/apps/api/src/scraper/scrapeURL/engines/fire-engine/branding-script/print-script.js
@@ -0,0 +1,27 @@
+#!/usr/bin/env node
+// Outputs the branding script to stdout for pasting into browser console
+// Usage: node print-script.js | pbcopy
+const esbuild = require("esbuild");
+const path = require("path");
+
+const entryPoint = path.join(__dirname, "index.ts");
+
+const result = esbuild.buildSync({
+ entryPoints: [entryPoint],
+ bundle: true,
+ minify: false, // Don't minify for readability when debugging
+ format: "iife",
+ globalName: "__extractBrandDesign",
+ target: ["es2020"],
+ write: false,
+});
+
+const bundledCode = result.outputFiles[0].text;
+
+// Wrap in a self-executing function that returns the result
+const script = `(function __extractBrandDesign() {
+${bundledCode}
+return __extractBrandDesign.extractBrandDesign();
+})();`;
+
+process.stdout.write(script);
diff --git a/apps/api/src/scraper/scrapeURL/engines/fire-engine/branding-script/svg-utils.ts b/apps/api/src/scraper/scrapeURL/engines/fire-engine/branding-script/svg-utils.ts
new file mode 100644
index 000000000..14af51e6f
--- /dev/null
+++ b/apps/api/src/scraper/scrapeURL/engines/fire-engine/branding-script/svg-utils.ts
@@ -0,0 +1,177 @@
+import { getComputedStyleCached } from "./helpers";
+
+const FC_IDX = "data-fc-idx";
+
+export const resolveSvgUseElements = (
+ svgClone: SVGSVGElement,
+ originalSvg: SVGSVGElement,
+): SVGSVGElement => {
+ const useElements = Array.from(svgClone.querySelectorAll("use"));
+
+ for (const useEl of useElements) {
+ const href = useEl.getAttribute("href") || useEl.getAttribute("xlink:href");
+ if (!href) continue;
+
+ const idMatch = href.match(/#([^)]+)/);
+ if (!idMatch) continue;
+
+ const targetId = idMatch[1];
+
+ let referencedEl: Element | null = originalSvg.querySelector(
+ "#" + CSS.escape(targetId),
+ );
+
+ if (!referencedEl) {
+ let parent = originalSvg.parentElement;
+ while (parent && !referencedEl) {
+ if (parent.tagName === "svg" || parent.tagName === "SVG") {
+ referencedEl = parent.querySelector("#" + CSS.escape(targetId));
+ }
+ parent = parent.parentElement;
+ }
+ }
+
+ if (!referencedEl) {
+ referencedEl = document.getElementById(targetId);
+ }
+
+ if (referencedEl && useEl.parentNode) {
+ const clonedRef = referencedEl.cloneNode(true) as Element;
+ const useIdx = useEl.getAttribute(FC_IDX);
+
+ if (clonedRef.tagName === "symbol" || clonedRef.tagName === "SYMBOL") {
+ const wrapper = document.createElementNS(
+ "http://www.w3.org/2000/svg",
+ "svg",
+ );
+
+ const viewBox = clonedRef.getAttribute("viewBox");
+ if (viewBox) wrapper.setAttribute("viewBox", viewBox);
+ const preserveAspectRatio = clonedRef.getAttribute(
+ "preserveAspectRatio",
+ );
+ if (preserveAspectRatio)
+ wrapper.setAttribute("preserveAspectRatio", preserveAspectRatio);
+
+ Array.from(useEl.attributes).forEach(attr => {
+ if (attr.name !== "href" && attr.name !== "xlink:href") {
+ wrapper.setAttribute(attr.name, attr.value);
+ }
+ });
+
+ if (useIdx != null) wrapper.setAttribute(FC_IDX, useIdx);
+
+ while (clonedRef.firstChild) {
+ wrapper.appendChild(clonedRef.firstChild);
+ }
+
+ useEl.parentNode.replaceChild(wrapper, useEl);
+ } else {
+ const clonedContent = clonedRef.cloneNode(true) as Element;
+
+ Array.from(useEl.attributes).forEach(attr => {
+ if (attr.name !== "href" && attr.name !== "xlink:href") {
+ if (clonedContent.setAttribute) {
+ clonedContent.setAttribute(attr.name, attr.value);
+ }
+ }
+ });
+
+ if (useIdx != null) clonedContent.setAttribute(FC_IDX, useIdx);
+
+ useEl.parentNode.replaceChild(clonedContent, useEl);
+ }
+ }
+ }
+
+ return svgClone;
+};
+
+export const resolveSvgStyles = (svg: SVGSVGElement): SVGSVGElement => {
+ const svgClone = svg.cloneNode(true) as SVGSVGElement;
+
+ // Build aligned element lists *before* resolving <use>, so indices stay 1:1.
+ const originalElements = [svg, ...Array.from(svg.querySelectorAll("*"))];
+ const clonedElementsPre = [
+ svgClone,
+ ...Array.from(svgClone.querySelectorAll("*")),
+ ];
+ clonedElementsPre.forEach((el, i) => el.setAttribute(FC_IDX, String(i)));
+
+ const svgWithResolvedUse = resolveSvgUseElements(svgClone, svg);
+
+ const computedStyles = originalElements.map(el => ({
+ el,
+ computed: getComputedStyleCached(el),
+ }));
+
+ const svgDefaults: Record<string, string> = {
+ fill: "rgb(0, 0, 0)",
+ stroke: "none",
+ "stroke-width": "1px",
+ opacity: "1",
+ "fill-opacity": "1",
+ "stroke-opacity": "1",
+ };
+
+ const applyResolvedStyle = (
+ clonedEl: Element,
+ originalEl: Element,
+ computed: CSSStyleDeclaration,
+ prop: string,
+ ) => {
+ const attrValue = originalEl.getAttribute(prop);
+ const value = computed.getPropertyValue(prop);
+
+ if (attrValue && attrValue.includes("var(")) {
+ clonedEl.removeAttribute(prop);
+ if (value && value.trim() && value !== "none") {
+ (clonedEl as HTMLElement).style.setProperty(prop, value, "important");
+ }
+ } else if (value && value.trim()) {
+ const isExplicit =
+ originalEl.hasAttribute(prop) ||
+ (originalEl as HTMLElement).style[prop as any];
+ const isDifferent =
+ svgDefaults[prop] !== undefined && value !== svgDefaults[prop];
+ if (isExplicit || isDifferent) {
+ (clonedEl as HTMLElement).style.setProperty(prop, value, "important");
+ }
+ }
+ };
+
+ const allProps = [
+ "fill",
+ "stroke",
+ "color",
+ "stop-color",
+ "flood-color",
+ "lighting-color",
+ "stroke-width",
+ "stroke-dasharray",
+ "stroke-dashoffset",
+ "stroke-linecap",
+ "stroke-linejoin",
+ "opacity",
+ "fill-opacity",
+ "stroke-opacity",
+ ];
+
+ const clonedWithIdx = svgWithResolvedUse.querySelectorAll(`[${FC_IDX}]`);
+ clonedWithIdx.forEach(clonedEl => {
+ const idxStr = clonedEl.getAttribute(FC_IDX);
+ clonedEl.removeAttribute(FC_IDX);
+ if (idxStr == null) return;
+ const i = parseInt(idxStr, 10);
+ if (i < 0 || i >= originalElements.length) return;
+ const originalEl = originalElements[i];
+ const computed = computedStyles[i]?.computed;
+ if (!computed) return;
+
+ for (const prop of allProps) {
+ applyResolvedStyle(clonedEl, originalEl, computed, prop);
+ }
+ });
+
+ return svgWithResolvedUse;
+};
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 7ca85b405..6f80318b4 100644
--- a/apps/api/src/scraper/scrapeURL/engines/fire-engine/brandingScript.ts
+++ b/apps/api/src/scraper/scrapeURL/engines/fire-engine/brandingScript.ts
@@ -1,1230 +1,45 @@
-export const getBrandingScript = () => String.raw`
-(function __extractBrandDesign() {
- const errors = [];
- const recordError = (context, error) => {
- errors.push({
- context: context,
- message: error && error.message ? error.message : String(error),
- timestamp: Date.now(),
- });
- };
-
- const CONSTANTS = {
- BUTTON_MIN_WIDTH: 50,
- BUTTON_MIN_HEIGHT: 25,
- BUTTON_MIN_PADDING_VERTICAL: 3,
- BUTTON_MIN_PADDING_HORIZONTAL: 6,
- MAX_PARENT_TRAVERSAL: 5,
- MAX_BACKGROUND_SAMPLES: 100,
- MIN_SIGNIFICANT_AREA: 1000,
- MIN_LARGE_CONTAINER_AREA: 10000,
- DUPLICATE_POSITION_THRESHOLD: 1,
- MIN_LOGO_SIZE: 25,
- MIN_ALPHA_THRESHOLD: 0.1,
- MAX_TRANSPARENT_ALPHA: 0.01,
- BUTTON_SELECTOR: 'button,input[type="submit"],input[type="button"],[role=button],[data-primary-button],[data-secondary-button],[data-cta],a.button,a.btn,[class*="btn"],[class*="button"],a[class*="bg-brand"],a[class*="bg-primary"],a[class*="bg-accent"]',
- };
-
- const styleCache = new WeakMap();
- const getComputedStyleCached = (el) => {
- if (styleCache.has(el)) {
- return styleCache.get(el);
- }
- const style = getComputedStyle(el);
- styleCache.set(el, style);
- return style;
- };
-
- const toPx = v => {
- if (!v || v === "auto") return null;
- if (v.endsWith("px")) return parseFloat(v);
- if (v.endsWith("rem"))
- return (
- parseFloat(v) *
- parseFloat(getComputedStyle(document.documentElement).fontSize || 16)
- );
- if (v.endsWith("em"))
- return (
- parseFloat(v) *
- parseFloat(getComputedStyle(document.body).fontSize || 16)
- );
- if (v.endsWith("%")) return null;
- const num = parseFloat(v);
- return Number.isFinite(num) ? num : null;
- };
-
- const getClassNameString = (el) => {
- if (!el || !el.className) return '';
- try {
- if (el.className.baseVal !== undefined) {
- return String(el.className.baseVal || '');
- }
- if (typeof el.className.toString === 'function') {
- return String(el.className);
- }
- if (typeof el.className === 'string') {
- return el.className;
- }
- return String(el.className || '');
- } catch (e) {
- return '';
- }
- };
-
- const resolveSvgStyles = svg => {
- const originalElements = [svg, ...svg.querySelectorAll("*")];
- const computedStyles = originalElements.map(el => ({
- el,
- computed: getComputedStyle(el),
- }));
-
- const clone = svg.cloneNode(true);
- const clonedElements = [clone, ...clone.querySelectorAll("*")];
-
- const svgDefaults = {
- fill: "rgb(0, 0, 0)",
- stroke: "none",
- "stroke-width": "1px",
- opacity: "1",
- "fill-opacity": "1",
- "stroke-opacity": "1",
- };
-
- const applyResolvedStyle = (clonedEl, originalEl, computed, prop) => {
- const attrValue = originalEl.getAttribute(prop);
- const value = computed.getPropertyValue(prop);
-
- if (attrValue && attrValue.includes("var(")) {
- clonedEl.removeAttribute(prop);
- if (value && value.trim() && value !== "none") {
- clonedEl.style.setProperty(prop, value, "important");
- }
- } else if (value && value.trim()) {
- const isExplicit =
- originalEl.hasAttribute(prop) || originalEl.style[prop];
- const isDifferent =
- svgDefaults[prop] !== undefined && value !== svgDefaults[prop];
- if (isExplicit || isDifferent) {
- clonedEl.style.setProperty(prop, value, "important");
- }
- }
- };
-
- for (let i = 0; i < clonedElements.length; i++) {
- const clonedEl = clonedElements[i];
- const originalEl = originalElements[i];
- const computed = computedStyles[i]?.computed;
- if (!computed) continue;
-
- const allProps = [
- "fill",
- "stroke",
- "color",
- "stop-color",
- "flood-color",
- "lighting-color",
- "stroke-width",
- "stroke-dasharray",
- "stroke-dashoffset",
- "stroke-linecap",
- "stroke-linejoin",
- "opacity",
- "fill-opacity",
- "stroke-opacity",
- ];
-
- for (const prop of allProps) {
- applyResolvedStyle(clonedEl, originalEl, computed, prop);
- }
- }
-
- return clone;
- };
-
- const collectCSSData = () => {
- const data = {
- colors: [],
- spacings: [],
- radii: [],
- };
-
- for (const sheet of Array.from(document.styleSheets)) {
- let rules;
- try {
- rules = sheet.cssRules;
- } catch (e) {
- recordError('collectCSSData - CORS stylesheet', e);
- continue;
- }
- if (!rules) continue;
-
- for (const rule of Array.from(rules)) {
- try {
- if (rule.type === CSSRule.STYLE_RULE) {
- const s = rule.style;
-
- [
- "color",
- "background-color",
- "border-color",
- "fill",
- "stroke",
- ].forEach(prop => {
- const val = s.getPropertyValue(prop);
- if (val) data.colors.push(val);
- });
-
- [
- "border-radius",
- "border-top-left-radius",
- "border-top-right-radius",
- "border-bottom-left-radius",
- "border-bottom-right-radius",
- ].forEach(p => {
- const v = toPx(s.getPropertyValue(p));
- if (v) data.radii.push(v);
- });
-
- [
- "margin",
- "margin-top",
- "margin-right",
- "margin-bottom",
- "margin-left",
- "padding",
- "padding-top",
- "padding-right",
- "padding-bottom",
- "padding-left",
- "gap",
- "row-gap",
- "column-gap",
- ].forEach(p => {
- const v = toPx(s.getPropertyValue(p));
- if (v) data.spacings.push(v);
- });
- }
- } catch {}
- }
- }
-
- return data;
- };
-
- const checkButtonLikeElement = (el, cs, rect, classNames) => {
- const hasButtonClasses =
- /rounded(-md|-lg|-xl|-full)?/.test(classNames) ||
- /px-\d+/.test(classNames) ||
- /py-\d+/.test(classNames) ||
- /p-\d+/.test(classNames) ||
- (/border/.test(classNames) && /rounded/.test(classNames)) ||
- (/inline-flex/.test(classNames) && /items-center/.test(classNames) && /justify-center/.test(classNames));
-
- if (hasButtonClasses && rect.width > CONSTANTS.BUTTON_MIN_WIDTH && rect.height > CONSTANTS.BUTTON_MIN_HEIGHT) {
- return true;
- }
-
- const paddingTop = parseFloat(cs.paddingTop) || 0;
- const paddingBottom = parseFloat(cs.paddingBottom) || 0;
- const paddingLeft = parseFloat(cs.paddingLeft) || 0;
- const paddingRight = parseFloat(cs.paddingRight) || 0;
- const hasPadding = paddingTop > CONSTANTS.BUTTON_MIN_PADDING_VERTICAL ||
- paddingBottom > CONSTANTS.BUTTON_MIN_PADDING_VERTICAL ||
- paddingLeft > CONSTANTS.BUTTON_MIN_PADDING_HORIZONTAL ||
- paddingRight > CONSTANTS.BUTTON_MIN_PADDING_HORIZONTAL;
- const hasMinSize = rect.width > CONSTANTS.BUTTON_MIN_WIDTH && rect.height > CONSTANTS.BUTTON_MIN_HEIGHT;
- const hasRounded = parseFloat(cs.borderRadius) > 0;
- const hasBorder = parseFloat(cs.borderTopWidth) > 0 || parseFloat(cs.borderBottomWidth) > 0 ||
- parseFloat(cs.borderLeftWidth) > 0 || parseFloat(cs.borderRightWidth) > 0;
-
- return hasPadding && hasMinSize && (hasRounded || hasBorder);
- };
-
- const isButtonElement = (el) => {
- if (!el || typeof el.matches !== 'function') return false;
-
- if (el.matches(CONSTANTS.BUTTON_SELECTOR)) {
- return true;
- }
-
- if (el.tagName.toLowerCase() === 'a') {
- try {
- const classNames = getClassNameString(el).toLowerCase();
- const cs = getComputedStyleCached(el);
- const rect = el.getBoundingClientRect();
- return checkButtonLikeElement(el, cs, rect, classNames);
- } catch (e) {
- recordError('isButtonElement', e);
- return false;
- }
- }
-
- return false;
- };
-
- const looksLikeButton = (el) => {
- return isButtonElement(el);
- };
-
- const sampleElements = () => {
- const picksSet = new Set();
-
- const pushQ = (q, limit = 10) => {
- const elements = document.querySelectorAll(q);
- let count = 0;
- for (const el of elements) {
- if (count >= limit) break;
- picksSet.add(el);
- count++;
- }
- };
-
- pushQ('header img, .site-logo img, img[alt*=logo i], img[src*="logo"]', 5);
-
- pushQ(
- 'button, input[type="submit"], input[type="button"], [role=button], [data-primary-button], [data-secondary-button], [data-cta], a.button, a.btn, [class*="btn"], [class*="button"], a[class*="bg-brand"], a[class*="bg-primary"], a[class*="bg-accent"]',
- 100,
- );
-
- const allLinks = Array.from(document.querySelectorAll('a')).slice(0, 100);
- for (const link of allLinks) {
- if (!picksSet.has(link) && looksLikeButton(link)) {
- picksSet.add(link);
- }
- }
-
- pushQ('input, select, textarea, [class*="form-control"]', 25);
- pushQ("h1, h2, h3, p, a", 50);
-
- const result = [...picksSet];
-
- return result.filter(Boolean);
- };
-
- const getStyleSnapshot = el => {
- const cs = getComputedStyleCached(el);
- const rect = el.getBoundingClientRect();
-
- const fontStack =
- cs
- .getPropertyValue("font-family")
- ?.split(",")
- .map(f => f.replace(/["']/g, "").trim())
- .filter(Boolean) || [];
-
- let classNames = "";
- try {
- if (el.getAttribute) {
- const attrClass = el.getAttribute("class");
- if (attrClass) classNames = attrClass.toLowerCase();
- }
- if (!classNames) {
- classNames = getClassNameString(el).toLowerCase();
- }
- } catch (e) {
- try {
- classNames = getClassNameString(el).toLowerCase();
- } catch (e2) {
- classNames = "";
- }
- }
-
- let bgColor = cs.getPropertyValue("background-color");
- const textColor = cs.getPropertyValue("color");
-
- const isTransparent = bgColor === "transparent" || bgColor === "rgba(0, 0, 0, 0)";
- const alphaMatch = bgColor.match(/rgba?\([^,]*,[^,]*,[^,]*,\s*([\d.]+)\)/);
- const hasZeroAlpha = alphaMatch && parseFloat(alphaMatch[1]) === 0;
-
- const isInputElement = el.tagName.toLowerCase() === 'input' ||
- el.tagName.toLowerCase() === 'select' ||
- el.tagName.toLowerCase() === 'textarea';
-
- if ((isTransparent || hasZeroAlpha) && !isInputElement) {
- let parent = el.parentElement;
- let depth = 0;
- while (parent && depth < CONSTANTS.MAX_PARENT_TRAVERSAL) {
- const parentBg = getComputedStyleCached(parent).getPropertyValue("background-color");
- if (parentBg && parentBg !== "transparent" && parentBg !== "rgba(0, 0, 0, 0)") {
- const parentAlphaMatch = parentBg.match(/rgba?\([^,]*,[^,]*,[^,]*,\s*([\d.]+)\)/);
- const parentAlpha = parentAlphaMatch ? parseFloat(parentAlphaMatch[1]) : 1;
- if (parentAlpha > CONSTANTS.MIN_ALPHA_THRESHOLD) {
- bgColor = parentBg;
- break;
- }
- }
- parent = parent.parentElement;
- depth++;
- }
- }
-
- const isButton = isButtonElement(el);
-
- let isNavigation = false;
- let hasCTAIndicator = false;
-
- try {
- hasCTAIndicator =
- el.matches(
- '[data-primary-button],[data-secondary-button],[data-cta],[class*="cta"],[class*="hero"]',
- ) ||
- el.getAttribute("data-primary-button") === "true" ||
- el.getAttribute("data-secondary-button") === "true";
-
- if (!hasCTAIndicator) {
- const hasNavClass = classNames.includes("nav-") ||
- classNames.includes("-nav") ||
- classNames.includes("nav-anchor") ||
- classNames.includes("nav-link") ||
- classNames.includes("sidebar-") ||
- classNames.includes("-sidebar") ||
- classNames.includes("menu-") ||
- classNames.includes("-menu") ||
- classNames.includes("toggle") ||
- classNames.includes("trigger");
-
- const hasNavRole = el.matches(
- '[role="tab"],[role="menuitem"],[role="menuitemcheckbox"],[aria-haspopup],[aria-expanded]',
- );
-
- const inNavContext = !!el.closest(
- 'nav, [role="navigation"], [role="menu"], [role="menubar"], [class*="navigation"], [class*="dropdown"], [class*="sidebar"], [id*="sidebar"], [id*="navigation"], [id*="nav-"], aside[class*="nav"], aside[id*="nav"]',
- );
-
- let isNavLink = false;
- if (el.tagName.toLowerCase() === "a" && el.parentElement) {
- if (el.parentElement.tagName.toLowerCase() === "li") {
- const listEl = el.closest("ul, ol");
- if (listEl && listEl.closest('[class*="nav"], [id*="nav"], [class*="sidebar"], [id*="sidebar"]')) {
- isNavLink = true;
- }
- }
- }
-
- isNavigation = hasNavClass || hasNavRole || inNavContext || isNavLink;
- }
- } catch (e) {}
-
- let text = "";
- if (el.tagName.toLowerCase() === 'input' && (el.type === 'submit' || el.type === 'button')) {
- text = (el.value && el.value.trim().substring(0, 100)) || "";
- } else {
- text = (el.textContent && el.textContent.trim().substring(0, 100)) || "";
- }
-
- const isInputField = el.matches('input:not([type="submit"]):not([type="button"]),select,textarea,[class*="form-control"]');
- let inputMetadata = null;
- if (isInputField) {
- const tagName = el.tagName.toLowerCase();
- inputMetadata = {
- type: tagName === 'input' ? (el.type || 'text') : tagName,
- placeholder: el.placeholder || "",
- value: tagName === 'input' ? (el.value || "") : "",
- required: el.required || false,
- disabled: el.disabled || false,
- name: el.name || "",
- id: el.id || "",
- label: (() => {
- if (el.id) {
- const label = document.querySelector('label[for="' + el.id + '"]');
- if (label) return (label.textContent || "").trim().substring(0, 100);
- }
- const parentLabel = el.closest('label');
- if (parentLabel) {
- const clone = parentLabel.cloneNode(true);
- const inputInClone = clone.querySelector('input,select,textarea');
- if (inputInClone) inputInClone.remove();
- return (clone.textContent || "").trim().substring(0, 100);
- }
- return "";
- })(),
- };
- }
-
- return {
- tag: el.tagName.toLowerCase(),
- classes: classNames,
- text: text,
- rect: { w: rect.width, h: rect.height },
- colors: {
- text: textColor,
- background: bgColor,
- border: (() => {
- const top = cs.getPropertyValue("border-top-color");
- const right = cs.getPropertyValue("border-right-color");
- const bottom = cs.getPropertyValue("border-bottom-color");
- const left = cs.getPropertyValue("border-left-color");
- if (top === right && top === bottom && top === left) return top;
- return top;
- })(),
- borderWidth: (() => {
- const top = toPx(cs.getPropertyValue("border-top-width"));
- const right = toPx(cs.getPropertyValue("border-right-width"));
- const bottom = toPx(cs.getPropertyValue("border-bottom-width"));
- const left = toPx(cs.getPropertyValue("border-left-width"));
- if (top === right && top === bottom && top === left) return top;
- return top;
- })(),
- borderTop: cs.getPropertyValue("border-top-color"),
- borderTopWidth: toPx(cs.getPropertyValue("border-top-width")),
- borderRight: cs.getPropertyValue("border-right-color"),
- borderRightWidth: toPx(cs.getPropertyValue("border-right-width")),
- borderBottom: cs.getPropertyValue("border-bottom-color"),
- borderBottomWidth: toPx(cs.getPropertyValue("border-bottom-width")),
- borderLeft: cs.getPropertyValue("border-left-color"),
- borderLeftWidth: toPx(cs.getPropertyValue("border-left-width")),
- },
- typography: {
- fontStack,
- size: cs.getPropertyValue("font-size") || null,
- weight: parseInt(cs.getPropertyValue("font-weight"), 10) || null,
- },
- radius: toPx(cs.getPropertyValue("border-radius")),
- borderRadius: {
- topLeft: toPx(cs.getPropertyValue("border-top-left-radius")),
- topRight: toPx(cs.getPropertyValue("border-top-right-radius")),
- bottomRight: toPx(cs.getPropertyValue("border-bottom-right-radius")),
- bottomLeft: toPx(cs.getPropertyValue("border-bottom-left-radius")),
- },
- shadow: cs.getPropertyValue("box-shadow") || null,
- isButton: isButton && !isNavigation,
- isNavigation: isNavigation,
- hasCTAIndicator: hasCTAIndicator,
- isInput: isInputField,
- inputMetadata: inputMetadata,
- isLink: el.matches("a"),
- };
- };
-
-
-
- const findImages = () => {
- const imgs = [];
- const logoCandidates = [];
- const push = (src, type) => {
- if (src) imgs.push({ type, src });
- };
-
- push(document.querySelector('link[rel*="icon" i]')?.href, "favicon");
- push(document.querySelector('meta[property="og:image" i]')?.content, "og");
- push(
- document.querySelector('meta[name="twitter:image" i]')?.content,
- "twitter",
- );
-
- const collectLogoCandidate = (el, source) => {
- const rect = el.getBoundingClientRect();
- const style = getComputedStyleCached(el);
- const isVisible = (
- rect.width > 0 &&
- rect.height > 0 &&
- style.display !== "none" &&
- style.visibility !== "hidden" &&
- style.opacity !== "0"
- );
-
- const imgSrc = el.src || '';
- if (imgSrc) {
- const ogImageSrc = document.querySelector('meta[property="og:image"]')?.getAttribute('content') || '';
- const twitterImageSrc = document.querySelector('meta[name="twitter:image"]')?.getAttribute('content') || '';
-
- if ((ogImageSrc && imgSrc.includes(ogImageSrc)) ||
- (twitterImageSrc && imgSrc.includes(twitterImageSrc)) ||
- (ogImageSrc && ogImageSrc.includes(imgSrc)) ||
- (twitterImageSrc && twitterImageSrc.includes(imgSrc))) {
- return;
- }
- }
-
- const inHeader = el.closest('header, nav, [role="banner"], #navbar, [id*="navbar"], [class*="navbar"], [class*="header"]');
-
- const langSwitcherParent = el.closest('[class*="lang"], [class*="language"], [class*="locale"], [class*="i18n"], [class*="translation"], [class*="switcher"], [id*="lang"], [id*="language"], [id*="locale"]');
- if (langSwitcherParent) {
- const parentClasses = getClassNameString(langSwitcherParent).toLowerCase();
- if (/lang|language|locale|i18n|translation|switcher|selector|dropdown/i.test(parentClasses)) {
- return;
- }
- }
-
- const insideButton = el.closest('button, [role="button"], input[type="button"], input[type="submit"]');
- if (insideButton) {
- return;
- }
-
-
- const elementClasses = getClassNameString(el).toLowerCase();
- const elementId = (el.id || '').toLowerCase();
- const ariaLabel = (el.getAttribute?.('aria-label') || '').toLowerCase();
-
- const isSearchIcon =
- /search|magnif/i.test(elementClasses) ||
- /search|magnif/i.test(elementId) ||
- /search/i.test(ariaLabel) ||
- el.closest('[class*="search"], [id*="search"], [role="search"]');
-
- if (isSearchIcon) return;
-
- const isUIIcon =
- /icon|menu|hamburger|bars|close|times|cart|user|account|profile|settings|notification|bell|chevron|arrow|caret|dropdown/i.test(elementClasses) ||
- /icon|menu|hamburger|cart|user|bell/i.test(elementId) ||
- /menu|close|cart|user|settings/i.test(ariaLabel);
-
- if (isUIIcon) {
- const hasExplicitLogoIndicator =
- /logo|brand|site-name|site-title/i.test(elementClasses) ||
- /logo|brand/i.test(elementId);
-
- if (!hasExplicitLogoIndicator) return;
- }
-
- const anchorParent = el.closest('a');
- const href = anchorParent ? (anchorParent.getAttribute('href') || '') : '';
-
- if (href && href.trim()) {
- const hrefLower = href.toLowerCase().trim();
-
- const isExternalLink =
- hrefLower.startsWith('http://') ||
- hrefLower.startsWith('https://') ||
- hrefLower.startsWith('//');
-
- if (isExternalLink) {
- const externalServiceDomains = [
- 'github.com', 'twitter.com', 'x.com', 'facebook.com', 'linkedin.com',
- 'instagram.com', 'youtube.com', 'discord.com', 'slack.com',
- 'npmjs.com', 'pypi.org', 'crates.io', 'packagist.org',
- 'badge.fury.io', 'shields.io', 'img.shields.io', 'badgen.net',
- 'codecov.io', 'coveralls.io', 'circleci.com', 'travis-ci.org',
- 'app.netlify.com', 'vercel.com'
- ];
-
- if (externalServiceDomains.some(domain => hrefLower.includes(domain))) {
- return;
- }
-
- try {
- const currentHostname = window.location.hostname.toLowerCase();
- const linkUrl = new URL(href, window.location.origin);
- const linkHostname = linkUrl.hostname.toLowerCase();
-
- if (linkHostname !== currentHostname) {
- return;
- }
- } catch (e) {
- return;
- }
- }
- }
-
- const isSvg = el.tagName.toLowerCase() === "svg";
-
- let alt = "";
- let srcMatch = false;
- let altMatch = false;
- let classMatch = false;
- let hrefMatch = false;
-
- if (isSvg) {
- const svgId = el.id || "";
- const svgClass = getClassNameString(el);
- const svgAriaLabel = el.getAttribute("aria-label") || "";
- const svgTitle = el.querySelector("title")?.textContent || "";
- const svgText = el.textContent?.trim() || "";
-
- alt = svgAriaLabel || svgTitle || svgText || svgId || "";
- altMatch = /logo/i.test(svgId) || /logo/i.test(svgAriaLabel) || /logo/i.test(svgTitle);
- classMatch = /logo/i.test(svgClass);
- srcMatch = el.closest('[class*="logo"], [id*="logo"]') !== null;
- } else {
- const imgId = el.id || "";
- alt = el.alt || "";
-
- const idMatch = /logo/i.test(imgId);
- srcMatch = (el.src ? /logo/i.test(el.src) : false) || idMatch;
- altMatch = /logo/i.test(alt);
-
- const imgClass = getClassNameString(el);
- classMatch = /logo/i.test(imgClass) || el.closest('[class*="logo"], [id*="logo"]') !== null || idMatch;
- }
-
- let src = "";
-
- if (isSvg) {
- try {
- const resolvedSvg = resolveSvgStyles(el);
- const serializer = new XMLSerializer();
- src = "data:image/svg+xml;utf8," + encodeURIComponent(serializer.serializeToString(resolvedSvg));
- } catch (e) {
- recordError('resolveSvgStyles', e);
- try {
- const serializer = new XMLSerializer();
- src = "data:image/svg+xml;utf8," + encodeURIComponent(serializer.serializeToString(el));
- } catch (e2) {
- recordError('XMLSerializer fallback', e2);
- return;
- }
- }
- } else {
- src = el.src || "";
- }
-
- if (href) {
- const normalizedHref = href.toLowerCase().trim();
-
- hrefMatch = normalizedHref === '/' ||
- normalizedHref === '/home' ||
- normalizedHref === '/index' ||
- normalizedHref === '';
-
- if (!hrefMatch && (normalizedHref.startsWith('http://') || normalizedHref.startsWith('https://') || normalizedHref.startsWith('//'))) {
- try {
- const currentHostname = window.location.hostname.toLowerCase();
- const linkUrl = new URL(href, window.location.origin);
- const linkHostname = linkUrl.hostname.toLowerCase();
-
- if (linkHostname === currentHostname && (linkUrl.pathname === '/' || linkUrl.pathname === '/home' || linkUrl.pathname === '/index.html')) {
- hrefMatch = true;
- }
- } catch (e) {}
- }
- }
-
- if (src) {
- logoCandidates.push({
- src,
- alt,
- isSvg,
- isVisible,
- location: inHeader ? "header" : "body",
- position: { top: rect.top, left: rect.left, width: rect.width, height: rect.height },
- indicators: {
- inHeader: !!inHeader,
- altMatch,
- srcMatch,
- classMatch,
- hrefMatch,
- },
- href: href || undefined,
- source,
- });
- }
- };
-
- const allLogoSelectors = [
- 'header a img, header a svg, header img, header svg',
- '[class*="header"] a img, [class*="header"] a svg, [class*="header"] img, [class*="header"] svg',
- 'nav a img, nav a svg, nav img, nav svg',
- '[role="banner"] a img, [role="banner"] a svg, [role="banner"] img, [role="banner"] svg',
- '#navbar a img, #navbar a svg, #navbar img, #navbar svg',
- '[id*="navbar"] a img, [id*="navbar"] a svg, [id*="navbar"] img, [id*="navbar"] svg',
- '[class*="navbar"] a img, [class*="navbar"] a svg, [class*="navbar"] img, [class*="navbar"] svg',
- 'a[class*="logo"] img, a[class*="logo"] svg',
- '[class*="logo"] img, [class*="logo"] svg',
- '[id*="logo"] img, [id*="logo"] svg',
- 'img[class*="nav-logo"], svg[class*="nav-logo"]',
- 'img[class*="logo"], svg[class*="logo"]',
- ];
-
- allLogoSelectors.forEach(selector => {
- Array.from(document.querySelectorAll(selector)).forEach(el => {
- collectLogoCandidate(el, selector);
- });
- });
-
- const excludeSelectors = '[class*="testimonial"], [class*="client"], [class*="partner"], [class*="customer"], [class*="case-study"], [id*="testimonial"], [id*="client"], [id*="partner"], [id*="customer"], [id*="case-study"], footer, [class*="footer"]';
-
- Array.from(document.images).forEach(img => {
- if (
- /logo/i.test(img.alt || "") ||
- /logo/i.test(img.src) ||
- img.closest('[class*="logo"]')
- ) {
- if (!img.closest(excludeSelectors)) {
- collectLogoCandidate(img, "document.images");
- }
- }
- });
-
- Array.from(document.querySelectorAll("svg")).forEach(svg => {
- const svgRect = svg.getBoundingClientRect();
- const alreadyCollected = logoCandidates.some(c => {
- if (!c.isSvg) return false;
- return Math.abs(c.position.top - svgRect.top) < 1 &&
- Math.abs(c.position.left - svgRect.left) < 1 &&
- Math.abs(c.position.width - svgRect.width) < 1 &&
- Math.abs(c.position.height - svgRect.height) < 1;
- });
- if (alreadyCollected) return;
-
- const insideButton = svg.closest('button, [role="button"], input[type="button"], input[type="submit"]');
- if (insideButton) return;
-
- // Check for UI icon indicators
- const svgId = svg.id || "";
- const svgClass = getClassNameString(svg);
- const svgAriaLabel = svg.getAttribute("aria-label") || "";
- const svgTitle = svg.querySelector("title")?.textContent || "";
-
- // Skip search icons
- const isSearchIcon =
- /search|magnif/i.test(svgId) ||
- /search|magnif/i.test(svgClass) ||
- /search/i.test(svgAriaLabel) ||
- /search/i.test(svgTitle) ||
- svg.closest('[class*="search"], [id*="search"], [role="search"]');
-
- if (isSearchIcon) return;
-
- // Skip other UI icons
- const isUIIcon =
- /icon|menu|hamburger|bars|close|times|cart|user|account|profile|settings|notification|bell|chevron|arrow|caret|dropdown/i.test(svgClass) ||
- /icon|menu|hamburger|cart|user|bell/i.test(svgId) ||
- /menu|close|cart|user|settings/i.test(svgAriaLabel);
-
- const hasLogoId = /logo/i.test(svgId);
- const hasLogoClass = /logo/i.test(svgClass);
- const hasLogoAriaLabel = /logo/i.test(svgAriaLabel);
- const hasLogoTitle = /logo/i.test(svgTitle);
- const inHeaderNav = svg.closest('header, nav, [role="banner"], #navbar, [id*="navbar"], [class*="navbar"], [class*="header"]');
- const inLogoContainer = svg.closest('[class*="logo"], [id*="logo"]');
- const inHeaderNavArea = !!inHeaderNav;
- const inAnchorInHeader = svg.closest('a') && inHeaderNav;
-
- // If it looks like a UI icon, only collect if it has explicit logo indicators
- if (isUIIcon) {
- const hasExplicitLogoIndicator = hasLogoId || hasLogoClass || hasLogoAriaLabel || hasLogoTitle || inLogoContainer;
- if (!hasExplicitLogoIndicator) return;
- }
-
- const shouldCollect =
- hasLogoId ||
- hasLogoClass ||
- hasLogoAriaLabel ||
- hasLogoTitle ||
- inLogoContainer ||
- inHeaderNavArea ||
- inAnchorInHeader;
-
- if (shouldCollect) {
- const excludeSelectors = '[class*="testimonial"], [class*="client"], [class*="partner"], [class*="customer"], [class*="case-study"], [id*="testimonial"], [id*="client"], [id*="partner"], [id*="customer"], [id*="case-study"], footer, [class*="footer"]';
- if (!svg.closest(excludeSelectors)) {
- collectLogoCandidate(svg, "document.querySelectorAll(svg)");
- }
- }
- });
-
- const seen = new Set();
- const uniqueCandidates = logoCandidates.filter(candidate => {
- if (seen.has(candidate.src)) return false;
- seen.add(candidate.src);
- return true;
- });
-
- let candidatesToPick = uniqueCandidates.filter(c => c.isVisible);
- if (candidatesToPick.length === 0 && uniqueCandidates.length > 0) {
- candidatesToPick = uniqueCandidates;
- }
-
- if (candidatesToPick.length > 0) {
- const best = candidatesToPick.reduce((best, candidate) => {
- if (!best) return candidate;
-
- if (candidate.indicators.inHeader && !best.indicators.inHeader) return candidate;
- if (!candidate.indicators.inHeader && best.indicators.inHeader) return best;
-
- if (candidate.indicators.hrefMatch && !best.indicators.hrefMatch) return candidate;
- if (!candidate.indicators.hrefMatch && best.indicators.hrefMatch) return best;
-
- if (candidate.indicators.classMatch && !best.indicators.classMatch) return candidate;
- if (!candidate.indicators.classMatch && best.indicators.classMatch) return best;
-
- const candidateArea = candidate.position.width * candidate.position.height;
- const bestArea = best.position.width * best.position.height;
- const candidateTooSmall = candidate.position.width < CONSTANTS.MIN_LOGO_SIZE || candidate.position.height < CONSTANTS.MIN_LOGO_SIZE;
- const bestTooSmall = best.position.width < CONSTANTS.MIN_LOGO_SIZE || best.position.height < CONSTANTS.MIN_LOGO_SIZE;
-
- if (candidateTooSmall && !bestTooSmall) return best;
- if (!candidateTooSmall && bestTooSmall) return candidate;
-
- return candidate.position.top < best.position.top ? candidate : best;
- }, null);
-
- if (best) {
- if (best.isSvg) {
- push(best.src, "logo-svg");
- } else {
- push(best.src, "logo");
- }
- }
- }
-
- return { images: imgs, logoCandidates: uniqueCandidates };
- };
-
- const getTypography = () => {
- const pickFontStack = el => {
- return (
- getComputedStyleCached(el)
- .fontFamily?.split(",")
- .map(f => f.replace(/["']/g, "").trim())
- .filter(Boolean) || []
- );
- };
-
- const h1 = document.querySelector("h1") || document.body;
- const h2 = document.querySelector("h2") || h1;
- const p = document.querySelector("p") || document.body;
- const body = document.body;
-
- return {
- stacks: {
- body: pickFontStack(body),
- heading: pickFontStack(h1),
- paragraph: pickFontStack(p),
- },
- sizes: {
- h1: getComputedStyleCached(h1).fontSize || "32px",
- h2: getComputedStyleCached(h2).fontSize || "24px",
- body: getComputedStyleCached(p).fontSize || "16px",
- },
- };
- };
-
- const detectFrameworkHints = () => {
- const hints = [];
-
- const generator = document.querySelector('meta[name="generator"]');
- if (generator) hints.push(generator.getAttribute("content") || "");
-
- const scripts = Array.from(document.querySelectorAll("script[src]"))
- .map(s => s.getAttribute("src") || "")
- .filter(Boolean);
-
- if (
- scripts.some(s => s.includes("tailwind") || s.includes("cdn.tailwindcss"))
- ) {
- hints.push("tailwind");
- }
- if (scripts.some(s => s.includes("bootstrap"))) {
- hints.push("bootstrap");
- }
- if (scripts.some(s => s.includes("mui") || s.includes("material-ui"))) {
- hints.push("material-ui");
- }
-
- return hints.filter(Boolean);
- };
-
- const detectColorScheme = () => {
- const body = document.body;
- const html = document.documentElement;
-
- const hasDarkIndicator =
- html.classList.contains("dark") ||
- body.classList.contains("dark") ||
- html.classList.contains("dark-mode") ||
- body.classList.contains("dark-mode") ||
- html.getAttribute("data-theme") === "dark" ||
- body.getAttribute("data-theme") === "dark" ||
- html.getAttribute("data-bs-theme") === "dark";
-
- const hasLightIndicator =
- html.classList.contains("light") ||
- body.classList.contains("light") ||
- html.classList.contains("light-mode") ||
- body.classList.contains("light-mode") ||
- html.getAttribute("data-theme") === "light" ||
- body.getAttribute("data-theme") === "light" ||
- html.getAttribute("data-bs-theme") === "light";
-
- let prefersDark = false;
- try {
- prefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
- } catch (e) {}
-
- if (hasDarkIndicator) return "dark";
- if (hasLightIndicator) return "light";
-
- const getEffectiveBackground = (el) => {
- let current = el;
- let depth = 0;
- while (current && depth < 10) {
- const bg = getComputedStyleCached(current).backgroundColor;
- const match = bg.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);
- if (match) {
- const r = parseInt(match[1], 10);
- const g = parseInt(match[2], 10);
- const b = parseInt(match[3], 10);
- const alpha = match[4] ? parseFloat(match[4]) : 1;
-
- if (alpha > CONSTANTS.MIN_ALPHA_THRESHOLD) {
- return { r, g, b, alpha };
- }
- }
- current = current.parentElement;
- depth++;
- }
- return null;
- };
-
- const bodyBg = getEffectiveBackground(body);
- const htmlBg = getEffectiveBackground(html);
- const effectiveBg = bodyBg || htmlBg;
-
- if (effectiveBg) {
- const { r, g, b } = effectiveBg;
- const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
-
- if (luminance < 0.4) return "dark";
- if (luminance > 0.6) return "light";
-
- return prefersDark ? "dark" : "light";
- }
-
- return prefersDark ? "dark" : "light";
- };
-
- const extractBrandName = () => {
- const ogSiteName = document.querySelector('meta[property="og:site_name"]')?.getAttribute("content");
- const title = document.title;
- const h1 = document.querySelector("h1")?.textContent?.trim();
-
- let domainName = "";
- try {
- const hostname = window.location.hostname;
- domainName = hostname.replace(/^www\./, "").split(".")[0];
- domainName = domainName.charAt(0).toUpperCase() + domainName.slice(1);
- } catch (e) {}
-
- let titleBrand = "";
- if (title) {
- titleBrand = title
- .replace(/\s*[-|–|—]\s*.*$/, "")
- .replace(/\s*:\s*.*$/, "")
- .replace(/\s*\|.*$/, "")
- .trim();
- }
-
- return ogSiteName || titleBrand || h1 || domainName || "";
- };
-
- const normalizeColor = (color) => {
- if (!color || typeof color !== "string") return null;
- const normalized = color.toLowerCase().trim();
-
- if (normalized === "transparent" || normalized === "rgba(0, 0, 0, 0)") {
- return null;
- }
-
- if (normalized === "#ffffff" || normalized === "#fff" ||
- normalized === "white" || normalized === "rgb(255, 255, 255)" ||
- /^rgba\(255,\s*255,\s*255(,\s*1(\.0)?)?\)$/.test(normalized)) {
- return "rgb(255, 255, 255)";
- }
-
- if (normalized === "#000000" || normalized === "#000" ||
- normalized === "black" || normalized === "rgb(0, 0, 0)" ||
- /^rgba\(0,\s*0,\s*0(,\s*1(\.0)?)?\)$/.test(normalized)) {
- return "rgb(0, 0, 0)";
- }
-
- if (normalized.startsWith("#")) {
- return normalized;
- }
-
- if (normalized.startsWith("rgb")) {
- return normalized.replace(/\s+/g, "");
- }
-
- return normalized;
- };
-
- const isValidBackgroundColor = (color) => {
- if (!color || typeof color !== "string") return false;
- const normalized = color.toLowerCase().trim();
- if (normalized === "transparent" || normalized === "rgba(0, 0, 0, 0)") {
- return false;
- }
- const rgbaMatch = normalized.match(/rgba\(\s*0\s*,\s*0\s*,\s*0\s*,\s*([\d.]+)\s*\)/);
- if (rgbaMatch) {
- const alpha = parseFloat(rgbaMatch[1]);
- if (alpha < CONSTANTS.MAX_TRANSPARENT_ALPHA) {
- return false;
- }
- return true;
- }
- const colorMatch = normalized.match(/color\([^)]+\)/);
- if (colorMatch) {
- return true;
- }
- return normalized.length > 0;
- };
-
- const getBackgroundCandidates = () => {
- const candidates = [];
-
- const colorFrequency = new Map();
- const allSampleElements = document.querySelectorAll("body, html, main, article, [role='main'], div, section");
- const sampleElements = Array.from(allSampleElements).slice(0, CONSTANTS.MAX_BACKGROUND_SAMPLES);
-
- sampleElements.forEach(el => {
- try {
- const bg = getComputedStyleCached(el).backgroundColor;
- if (isValidBackgroundColor(bg)) {
- const rect = el.getBoundingClientRect();
- const area = rect.width * rect.height;
- if (area > CONSTANTS.MIN_SIGNIFICANT_AREA) {
- const normalized = normalizeColor(bg);
- if (normalized) {
- const currentCount = colorFrequency.get(normalized) || 0;
- colorFrequency.set(normalized, currentCount + area);
- }
- }
- }
- } catch (e) {}
- });
-
- let mostCommonColor = null;
- let maxArea = 0;
- for (const [color, area] of colorFrequency.entries()) {
- if (area > maxArea) {
- maxArea = area;
- mostCommonColor = color;
- }
- }
-
- const bodyBg = getComputedStyleCached(document.body).backgroundColor;
- const htmlBg = getComputedStyleCached(document.documentElement).backgroundColor;
-
- if (isValidBackgroundColor(bodyBg)) {
- const normalized = normalizeColor(bodyBg);
- const priority = normalized === mostCommonColor ? 15 : 10;
- if (normalized) {
- candidates.push({
- color: normalized,
- source: "body",
- priority: priority,
- });
- }
- }
-
- if (isValidBackgroundColor(htmlBg)) {
- const normalized = normalizeColor(htmlBg);
- const priority = normalized === mostCommonColor ? 14 : 9;
- if (normalized) {
- candidates.push({
- color: normalized,
- source: "html",
- priority: priority,
- });
- }
- }
-
- const normalizedBodyBg = normalizeColor(bodyBg);
- const normalizedHtmlBg = normalizeColor(htmlBg);
- if (mostCommonColor && mostCommonColor !== normalizedBodyBg && mostCommonColor !== normalizedHtmlBg) {
- candidates.push({
- color: mostCommonColor,
- source: "most-common-visible",
- priority: 12,
- area: maxArea,
- });
- }
-
- try {
- const rootStyle = getComputedStyleCached(document.documentElement);
-
- const cssVars = [
- "--background",
- "--background-light",
- "--background-dark",
- "--bg-background",
- "--bg-background-light",
- "--bg-background-dark",
- "--color-background",
- "--color-background-light",
- "--color-background-dark",
- ];
-
- cssVars.forEach(varName => {
- try {
- const rawValue = rootStyle.getPropertyValue(varName).trim();
-
- if (rawValue && isValidBackgroundColor(rawValue)) {
- candidates.push({
- color: rawValue,
- source: "css-var:" + varName,
- priority: 8,
- });
- }
- } catch (e) {}
- });
- } catch (e) {}
-
- try {
- const allContainers = document.querySelectorAll("main, article, [role='main'], header, .main, .container");
- const mainContainers = Array.from(allContainers).slice(0, 5);
- mainContainers.forEach(el => {
- try {
- const bg = getComputedStyleCached(el).backgroundColor;
- if (isValidBackgroundColor(bg)) {
- const rect = el.getBoundingClientRect();
- const area = rect.width * rect.height;
- if (area > CONSTANTS.MIN_LARGE_CONTAINER_AREA) {
- const normalized = normalizeColor(bg);
- if (normalized) {
- candidates.push({
- color: normalized,
- source: el.tagName.toLowerCase() + "-container",
- priority: 5,
- area: area,
- });
- }
- }
- }
- } catch (e) {}
- });
- } catch (e) {}
-
- const seen = new Set();
- const unique = candidates.filter(c => {
- if (!c || !c.color) return false;
- const key = normalizeColor(c.color);
- if (!key || seen.has(key)) return false;
- seen.add(key);
- return true;
- });
-
- unique.sort((a, b) => (b.priority || 0) - (a.priority || 0));
-
- return unique;
- };
-
- const cssData = collectCSSData();
- const elements = sampleElements();
- const snapshots = elements.map(getStyleSnapshot);
- const imageData = findImages();
- const typography = getTypography();
- const frameworkHints = detectFrameworkHints();
- const colorScheme = detectColorScheme();
- const brandName = extractBrandName();
- const backgroundCandidates = getBackgroundCandidates();
-
- const pageBackground = backgroundCandidates.length > 0 ? backgroundCandidates[0].color : null;
-
- return {
- branding: {
- cssData,
- snapshots,
- images: imageData.images,
- logoCandidates: imageData.logoCandidates,
- brandName,
- typography,
- frameworkHints,
- colorScheme,
- pageBackground,
- backgroundCandidates,
- errors: errors.length > 0 ? errors : undefined,
- },
- };
+// Branding script for extracting brand design tokens from web pages
+// Built at runtime using esbuild
+import path from "path";
+import fs from "fs";
+
+let cachedScript: string | null = null;
+
+export const getBrandingScript = (): string => {
+ if (cachedScript) {
+ return cachedScript;
+ }
+
+ // Determine the correct path to the branding script source files
+ // Development: use .ts files directly
+ // Production (Docker): use compiled .js files in dist/
+ let entryPoint = path.join(__dirname, "branding-script", "index.ts");
+
+ if (!fs.existsSync(entryPoint)) {
+ // Fall back to compiled .js files (production Docker)
+ entryPoint = path.join(__dirname, "branding-script", "index.js");
+ }
+
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
+ const esbuild = require("esbuild");
+
+ const result = esbuild.buildSync({
+ entryPoints: [entryPoint],
+ bundle: true,
+ minify: true,
+ format: "iife",
+ globalName: "__extractBrandDesign",
+ target: ["es2020"],
+ write: false,
+ });
+
+ const bundledCode = result.outputFiles[0].text;
+
+ // Wrap in a self-executing function that returns the result
+ cachedScript = `(function __extractBrandDesign() {
+${bundledCode}
+return __extractBrandDesign.extractBrandDesign();
})();`;
+
+ return cachedScript;
+};
diff --git a/apps/api/src/scraper/scrapeURL/engines/fire-engine/index.ts b/apps/api/src/scraper/scrapeURL/engines/fire-engine/index.ts
index 340d85e79..5c93087b4 100644
--- a/apps/api/src/scraper/scrapeURL/engines/fire-engine/index.ts
+++ b/apps/api/src/scraper/scrapeURL/engines/fire-engine/index.ts
@@ -35,6 +35,9 @@ import { youtubePostprocessor } from "../../postprocessors/youtube";
import { withSpan, setSpanAttributes } from "../../../../lib/otel-tracer";
import { getBrandingScript } from "./brandingScript";
+/** Default wait (ms) before running the branding script when user did not set waitFor. Lets the page settle so DOM/images are ready and reduces JS errors. */
+const BRANDING_DEFAULT_WAIT_MS = 2000;
+
// This function does not take `Meta` on purpose. It may not access any
// meta values to construct the request -- that must be done by the
// `scrapeURLWithFireEngine*` functions.
@@ -234,14 +237,21 @@ export async function scrapeURLWithFireEngineChromeCDP(
"engine.url": meta.url,
"engine.team_id": meta.internalOptions.teamId,
});
+ const hasBranding = hasFormatOfType(meta.options.formats, "branding");
+ const defaultWait = hasBranding ? BRANDING_DEFAULT_WAIT_MS : 0;
+ const effectiveWait =
+ meta.options.waitFor != null && meta.options.waitFor !== 0
+ ? meta.options.waitFor
+ : defaultWait;
+
const actions: InternalAction[] = [
- // Transform waitFor option into an action (unsupported by chrome-cdp)
- ...(meta.options.waitFor !== 0
+ // Transform waitFor option into an action (unsupported by chrome-cdp).
+ // When branding is requested and user didn't set waitFor, use a default wait so the page is ready and we avoid JS errors.
+ ...(effectiveWait > 0
? [
{
type: "wait" as const,
- milliseconds:
- meta.options.waitFor > 30000 ? 30000 : meta.options.waitFor,
+ milliseconds: effectiveWait > 30000 ? 30000 : effectiveWait,
},
]
: []),
@@ -567,13 +577,20 @@ export function fireEngineMaxReasonableTime(
meta: Meta,
engine: "chrome-cdp" | "playwright" | "tlsclient",
): number {
+ const hasBranding = hasFormatOfType(meta.options.formats, "branding");
+ const defaultWait = hasBranding ? BRANDING_DEFAULT_WAIT_MS : 0;
+ const effectiveWait =
+ meta.options.waitFor != null && meta.options.waitFor !== 0
+ ? meta.options.waitFor
+ : defaultWait;
+
if (engine === "tlsclient") {
return 15000;
} else if (engine === "playwright") {
return (meta.options.waitFor ?? 0) + 30000;
} else {
return (
- (meta.options.waitFor ?? 0) +
+ effectiveWait +
(meta.options.actions?.reduce(
(a, x) => (x.type === "wait" ? (x.milliseconds ?? 2500) + a : 250 + a),
0,
diff --git a/apps/api/src/types/branding.ts b/apps/api/src/types/branding.ts
index 9161ed5ad..cc7e8f367 100644
--- a/apps/api/src/types/branding.ts
+++ b/apps/api/src/types/branding.ts
@@ -114,6 +114,10 @@ export interface BrandingProfile {
};
images?: {
logo?: string | null;
+ /** Logo link URL (parent <a href>) when logo is inside a link, e.g. homepage. */
+ logoHref?: string | null;
+ /** Logo alt text from <img alt> or parent <a aria-label>. */
+ logoAlt?: string | null;
favicon?: string | null;
ogImage?: string | null;
[key: string]: string | null | undefined;
@@ -167,5 +171,49 @@ export interface BrandingProfile {
};
confidence: number;
};
+ __llm_logo_reasoning?: {
+ selectedIndex: number;
+ reasoning: string;
+ confidence: number;
+ rejected?: boolean;
+ };
+ __llm_metadata?: {
+ logoSelection: {
+ llmCalled: boolean;
+ llmSucceeded: boolean;
+ finalSource: "llm" | "heuristic" | "fallback" | "none";
+ error?: string;
+ /** Exact AI response for logoSelection (before index mapping/heuristic), for debugging */
+ rawLogoSelection?: {
+ selectedLogoIndex: number;
+ selectedLogoReasoning?: string;
+ confidence: number;
+ };
+ };
+ buttonClassification: {
+ llmCalled: boolean;
+ llmSucceeded: boolean;
+ error?: string;
+ };
+ };
+ __logo_candidates?: Array<{
+ src: string;
+ alt: string;
+ ariaLabel?: string;
+ isSvg: boolean;
+ isVisible: boolean;
+ location: "header" | "body" | "footer";
+ position: { top: number; left: number; width: number; height: number };
+ indicators: {
+ inHeader: boolean;
+ altMatch: boolean;
+ srcMatch: boolean;
+ classMatch: boolean;
+ hrefMatch: boolean;
+ };
+ href?: string;
+ source: string;
+ logoSvgScore?: number;
+ }>;
[key: string]: unknown;
}