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

projectFaviconRoute.ts

76 lines2.3 KB

1import http from "node:http";
2import path from "node:path";
3import { Effect, FileSystem } from "effect";
4​
5import { ProjectFaviconResolver } from "./project/Services/ProjectFaviconResolver.ts";
6​
7const FAVICON_MIME_TYPES: Record<string, string> = {
8 ".png": "image/png",
9 ".jpg": "image/jpeg",
10 ".svg": "image/svg+xml",
11 ".ico": "image/x-icon",
12};
13​
14const 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>`;
15​
16export const tryHandleProjectFaviconRequest = Effect.fn("tryHandleProjectFaviconRequest")(
17 function* (
18 url: URL,
19 res: http.ServerResponse,
20 ): Effect.fn.Return<boolean, never, ProjectFaviconResolver | FileSystem.FileSystem> {
21 const respond = (
22 statusCode: number,
23 headers: Record<string, string>,
24 body: string | Uint8Array,
25 ) => {
26 res.writeHead(statusCode, headers);
27 res.end(body);
28 };
29​
30 if (url.pathname !== "/api/project-favicon") {
31 return false;
32 }
33​
34 const projectCwd = url.searchParams.get("cwd");
35 if (!projectCwd) {
36 respond(400, { "Content-Type": "text/plain" }, "Missing cwd parameter");
37 return true;
38 }
39​
40 const fileSystem = yield* FileSystem.FileSystem;
41 const faviconResolver = yield* ProjectFaviconResolver;
42 const resolvedPath = yield* faviconResolver.resolvePath(projectCwd);
43​
44 if (!resolvedPath) {
45 respond(
46 200,
47 {
48 "Content-Type": "image/svg+xml",
49 "Cache-Control": "public, max-age=3600",
50 },
51 FALLBACK_FAVICON_SVG,
52 );
53 return true;
54 }
55​
56 const data = yield* fileSystem
57 .readFile(resolvedPath)
58 .pipe(Effect.catch(() => Effect.succeed(null)));
59 if (!data) {
60 respond(500, { "Content-Type": "text/plain" }, "Read error");
61 return true;
62 }
63​
64 const ext = path.extname(resolvedPath).toLowerCase();
65 const contentType = FAVICON_MIME_TYPES[ext] ?? "application/octet-stream";
66 respond(
67 200,
68 {
69 "Content-Type": contentType,
70 "Cache-Control": "public, max-age=3600",
71 },
72 data,
73 );
74 return true;
75 },
76);