| 1 | import { JSDOM } from "jsdom"; |
| 2 | |
| 3 | export async function findFaviconPath(url: URL): Promise<string | undefined> { |
| 4 | const baseUrl = `${url.protocol}//${url.hostname}`; |
| 5 | |
| 6 | try { |
| 7 | const response = await fetch(baseUrl); |
| 8 | if (!response.ok) { |
| 9 | throw new Error(`HTTP error! status: ${response.status}`); |
| 10 | } |
| 11 | |
| 12 | const html = await response.text(); |
| 13 | const dom = new JSDOM(html); |
| 14 | const document = dom.window.document; |
| 15 | |
| 16 | // Look for favicon in <link> tags |
| 17 | const linkTags = document.querySelectorAll('link[rel*="icon"]'); |
| 18 | |
| 19 | for (const link of linkTags) { |
| 20 | const href = link.getAttribute("href"); |
| 21 | if (href) { |
| 22 | return new URL(href, baseUrl).toString(); |
| 23 | } |
| 24 | } |
| 25 | } catch (error) { |
| 26 | console.debug(`Failed to fetch favicon for ${baseUrl}: ${error}`); |
| 27 | } |
| 28 | |
| 29 | console.debug(`Failed to find favicon for ${baseUrl}`); |
| 30 | return undefined; |
| 31 | } |
| 32 | |
| 33 | export async function getFaviconBase64( |
| 34 | faviconUrl: string, |
| 35 | ): Promise<string | undefined> { |
| 36 | try { |
| 37 | const response = await fetch(faviconUrl); |
| 38 | |
| 39 | if (!response.ok) { |
| 40 | throw new Error(`HTTP error! status: ${response.status}`); |
| 41 | } |
| 42 | |
| 43 | const arrayBuffer = await response.arrayBuffer(); |
| 44 | const base64 = btoa( |
| 45 | new Uint8Array(arrayBuffer).reduce( |
| 46 | (data, byte) => data + String.fromCharCode(byte), |
| 47 | "", |
| 48 | ), |
| 49 | ); |
| 50 | const mimeType = response.headers.get("content-type") || "image/x-icon"; |
| 51 | |
| 52 | return `data:${mimeType};base64,${base64}`; |
| 53 | } catch (error) { |
| 54 | console.debug(`Failed to fetch favicon from ${faviconUrl}: ${error}`); |
| 55 | return undefined; |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | export async function fetchFavicon(url: URL): Promise<string | undefined> { |
| 60 | const faviconPath = await findFaviconPath(url); |
| 61 | if (faviconPath) { |
| 62 | return getFaviconBase64(faviconPath); |
| 63 | } |
| 64 | return undefined; |
| 65 | } |