Open History to see the last commit
1import fs from "node:fs";
2import http from "node:http";
3import path from "node:path";
4
5const FAVICON_MIME_TYPES: Record<string, string> = {
6 ".png": "image/png",
7 ".jpg": "image/jpeg",
8 ".svg": "image/svg+xml",
9 ".ico": "image/x-icon",
10};
11
12// Well-known favicon paths checked in order.
13const FAVICON_CANDIDATES = [
14 "favicon.svg",
15 "favicon.ico",
16 "favicon.png",
17 "public/favicon.svg",
18 "public/favicon.ico",
19 "public/favicon.png",
20 "app/favicon.ico",
21 "app/favicon.png",
22 "app/icon.svg",
23 "app/icon.png",
24 "app/icon.ico",
25 "src/favicon.ico",
26 "src/favicon.svg",
27 "src/app/favicon.ico",
28 "src/app/icon.svg",
29 "src/app/icon.png",
30 "assets/icon.svg",
31 "assets/icon.png",
32 "assets/logo.svg",
33 "assets/logo.png",
34];
35
36// Files that may contain a <link rel="icon"> or icon metadata declaration.
37const ICON_SOURCE_FILES = [
38 "index.html",
39 "public/index.html",
40 "app/routes/__root.tsx",
41 "src/routes/__root.tsx",
42 "app/root.tsx",
43 "src/root.tsx",
44 "src/index.html",
45];
46
47// Matches <link ...> tags or object-like icon metadata where rel/href can appear in any order.
48const LINK_ICON_HTML_RE =
49 /<link\b(?=[^>]*\brel=["'](?:icon|shortcut icon)["'])(?=[^>]*\bhref=["']([^"'?]+))[^>]*>/i;
50const LINK_ICON_OBJ_RE =
51 /(?=[^}]*\brel\s*:\s*["'](?:icon|shortcut icon)["'])(?=[^}]*\bhref\s*:\s*["']([^"'?]+))[^}]*/i;
52
53function extractIconHref(source: string): string | null {
54 const htmlMatch = source.match(LINK_ICON_HTML_RE);
55 if (htmlMatch?.[1]) return htmlMatch[1];
56 const objMatch = source.match(LINK_ICON_OBJ_RE);
57 if (objMatch?.[1]) return objMatch[1];
58 return null;
59}
60
61function resolveIconHref(projectCwd: string, href: string): string[] {
62 const clean = href.replace(/^\//, "");
63 return [path.join(projectCwd, "public", clean), path.join(projectCwd, clean)];
64}
65
66function isPathWithinProject(projectCwd: string, candidatePath: string): boolean {
67 const relative = path.relative(path.resolve(projectCwd), path.resolve(candidatePath));
68 return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
69}
70
71function serveFaviconFile(filePath: string, res: http.ServerResponse): void {
72 const ext = path.extname(filePath).toLowerCase();
73 const contentType = FAVICON_MIME_TYPES[ext] ?? "application/octet-stream";
74 fs.readFile(filePath, (readErr, data) => {
75 if (readErr) {
76 res.writeHead(500, { "Content-Type": "text/plain" });
77 res.end("Read error");
78 return;
79 }
80 res.writeHead(200, {
81 "Content-Type": contentType,
82 "Cache-Control": "public, max-age=3600",
83 });
84 res.end(data);
85 });
86}
87
88export function tryHandleProjectFaviconRequest(url: URL, res: http.ServerResponse): boolean {
89 if (url.pathname !== "/api/project-favicon") {
90 return false;
91 }
92
93 const projectCwd = url.searchParams.get("cwd");
94 if (!projectCwd) {
95 res.writeHead(400, { "Content-Type": "text/plain" });
96 res.end("Missing cwd parameter");
97 return true;
98 }
99
100 const tryResolvedPaths = (paths: string[], index: number, onExhausted: () => void): void => {
101 if (index >= paths.length) {
102 onExhausted();
103 return;
104 }
105 const candidate = paths[index]!;
106 if (!isPathWithinProject(projectCwd, candidate)) {
107 tryResolvedPaths(paths, index + 1, onExhausted);
108 return;
109 }
110 fs.stat(candidate, (err, stats) => {
111 if (err || !stats?.isFile()) {
112 tryResolvedPaths(paths, index + 1, onExhausted);
113 return;
114 }
115 serveFaviconFile(candidate, res);
116 });
117 };
118
119 const trySourceFiles = (index: number): void => {
120 if (index >= ICON_SOURCE_FILES.length) {
121 res.writeHead(404, { "Content-Type": "text/plain" });
122 res.end("No favicon found");
123 return;
124 }
125 const sourceFile = path.join(projectCwd, ICON_SOURCE_FILES[index]!);
126 fs.readFile(sourceFile, "utf8", (err, content) => {
127 if (err) {
128 trySourceFiles(index + 1);
129 return;
130 }
131 const href = extractIconHref(content);
132 if (!href) {
133 trySourceFiles(index + 1);
134 return;
135 }
136 const candidates = resolveIconHref(projectCwd, href);
137 tryResolvedPaths(candidates, 0, () => trySourceFiles(index + 1));
138 });
139 };
140
141 const tryCandidates = (index: number): void => {
142 if (index >= FAVICON_CANDIDATES.length) {
143 trySourceFiles(0);
144 return;
145 }
146 const candidate = path.join(projectCwd, FAVICON_CANDIDATES[index]!);
147 if (!isPathWithinProject(projectCwd, candidate)) {
148 tryCandidates(index + 1);
149 return;
150 }
151 fs.stat(candidate, (err, stats) => {
152 if (err || !stats?.isFile()) {
153 tryCandidates(index + 1);
154 return;
155 }
156 serveFaviconFile(candidate, res);
157 });
158 };
159
160 tryCandidates(0);
161 return true;
162}