Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

projectFaviconRoute.ts

171 lines5.1 KB

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