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

ProjectFaviconResolver.ts

258 lines8.0 KB

1/**
2 * ProjectFaviconResolver - Effect service contract for project icon discovery.
3 *
4 * Resolves a representative favicon or app icon file for a workspace by
5 * checking common file locations and project source metadata.
6 *
7 * @module ProjectFaviconResolver
8 */
9import * as Context from "effect/Context";
10import * as Effect from "effect/Effect";
11import * as FileSystem from "effect/FileSystem";
12import * as Layer from "effect/Layer";
13import * as Option from "effect/Option";
14import * as Path from "effect/Path";
15import * as PlatformError from "effect/PlatformError";
16import * as Schema from "effect/Schema";
17​
18import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
19import * as T3ProjectFileLoader from "./T3ProjectFileLoader.ts";
20​
21// Well-known favicon paths checked in order.
22const FAVICON_CANDIDATES = [
23 "favicon.svg",
24 "favicon.ico",
25 "favicon.png",
26 "public/favicon.svg",
27 "public/favicon.ico",
28 "public/favicon.png",
29 "app/favicon.ico",
30 "app/favicon.png",
31 "app/icon.svg",
32 "app/icon.png",
33 "app/icon.ico",
34 "src/favicon.ico",
35 "src/favicon.svg",
36 "src/app/favicon.ico",
37 "src/app/icon.svg",
38 "src/app/icon.png",
39 "assets/icon.svg",
40 "assets/icon.png",
41 "assets/logo.svg",
42 "assets/logo.png",
43 ".idea/icon.svg",
44] as const;
45​
46// Files that may contain a <link rel="icon"> or icon metadata declaration.
47const ICON_SOURCE_FILES = [
48 "index.html",
49 "public/index.html",
50 "app/routes/__root.tsx",
51 "src/routes/__root.tsx",
52 "app/root.tsx",
53 "src/root.tsx",
54 "src/index.html",
55] as const;
56​
57// Matches <link ...> tags or object-like icon metadata where rel/href can appear in any order.
58const LINK_ICON_HTML_RE =
59 /<link\b(?=[^>]*\brel=["'](?:icon|shortcut icon)["'])(?=[^>]*\bhref=["']([^"'?]+))[^>]*>/i;
60const LINK_ICON_OBJ_RE =
61 /(?=[^}]*\brel\s*:\s*["'](?:icon|shortcut icon)["'])(?=[^}]*\bhref\s*:\s*["']([^"'?]+))[^}]*/i;
62​
63export class ProjectFaviconResolutionError extends Schema.TaggedErrorClass<ProjectFaviconResolutionError>()(
64 "ProjectFaviconResolutionError",
65 {
66 operation: Schema.Literals([
67 "normalize-workspace",
68 "resolve-path",
69 "stat-candidate",
70 "read-source",
71 ]),
72 workspaceRoot: Schema.String,
73 relativePath: Schema.optional(Schema.String),
74 absolutePath: Schema.optional(Schema.String),
75 cause: Schema.Defect(),
76 },
77) {
78 override get message(): string {
79 return `Failed to resolve project favicon during ${this.operation} for workspace ${this.workspaceRoot}.`;
80 }
82​
83/** Service tag for project favicon resolution. */
84export class ProjectFaviconResolver extends Context.Service<
85 ProjectFaviconResolver,
86 {
87 /**
88 * Resolve a favicon or icon file path for the provided workspace root.
89 *
90 * Returns `null` when no candidate icon file can be found.
91 */
92 readonly resolvePath: (
93 cwd: string,
94 faviconPath?: string,
95 ) => Effect.Effect<string | null, ProjectFaviconResolutionError>;
96 }
97>()("t3/project/ProjectFaviconResolver") {}
98​
99function extractIconHref(source: string): string | null {
100 const htmlMatch = source.match(LINK_ICON_HTML_RE);
101 if (htmlMatch?.[1]) return htmlMatch[1];
102 const objMatch = source.match(LINK_ICON_OBJ_RE);
103 if (objMatch?.[1]) return objMatch[1];
104 return null;
106​
107const optionOnNotFound = <A, R>(
108 effect: Effect.Effect<A, PlatformError.PlatformError, R>,
109): Effect.Effect<Option.Option<A>, PlatformError.PlatformError, R> =>
110 effect.pipe(
111 Effect.map(Option.some),
112 Effect.catchTags({
113 PlatformError: (error) =>
114 error.reason._tag === "NotFound" ? Effect.succeed(Option.none<A>()) : Effect.fail(error),
115 }),
116 );
117​
118export const make = Effect.gen(function* () {
119 const fileSystem = yield* FileSystem.FileSystem;
120 const path = yield* Path.Path;
121 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
122 const projectFileLoader = yield* T3ProjectFileLoader.T3ProjectFileLoader;
123​
124 const resolveIconHref = (href: string): ReadonlyArray<string> => {
125 const clean = href.replace(/^\//, "");
126 return [path.join("public", clean), clean];
127 };
128​
129 const findExistingFile = Effect.fn("ProjectFaviconResolver.findExistingFile")(function* (
130 projectCwd: string,
131 relativeCandidates: ReadonlyArray<string>,
132 ): Effect.fn.Return<string | null, ProjectFaviconResolutionError> {
133 for (const relativePath of relativeCandidates) {
134 const candidate = yield* workspacePaths
135 .resolveRelativePathWithinRoot({
136 workspaceRoot: projectCwd,
137 relativePath,
138 })
139 .pipe(
140 Effect.map(Option.some),
141 Effect.catchTags({
142 WorkspacePathOutsideRootError: () =>
143 Effect.succeed(
144 Option.none<{ readonly absolutePath: string; readonly relativePath: string }>(),
145 ),
146 }),
147 );
148 if (Option.isNone(candidate)) {
149 continue;
150 }
151 const stats = yield* optionOnNotFound(fileSystem.stat(candidate.value.absolutePath)).pipe(
152 Effect.mapError(
153 (cause) =>
154 new ProjectFaviconResolutionError({
155 operation: "stat-candidate",
156 workspaceRoot: projectCwd,
157 relativePath,
158 absolutePath: candidate.value.absolutePath,
159 cause,
160 }),
161 ),
162 );
163 if (Option.isSome(stats) && stats.value.type === "File") {
164 return candidate.value.absolutePath;
165 }
166 }
167 return null;
168 });
169​
170 const resolvePath: ProjectFaviconResolver["Service"]["resolvePath"] = Effect.fn(
171 "ProjectFaviconResolver.resolvePath",
172 )(function* (cwd, faviconPath) {
173 const projectCwd = yield* workspacePaths.normalizeWorkspaceRoot(cwd).pipe(
174 Effect.mapError(
175 (cause) =>
176 new ProjectFaviconResolutionError({
177 operation: "normalize-workspace",
178 workspaceRoot: cwd,
179 cause,
180 }),
181 ),
182 );
183 // A grouped project's saved path can be absent from one checkout. Use it
184 // where it exists and retain automatic discovery for the other checkouts.
185 if (faviconPath !== undefined) {
186 const existing = yield* findExistingFile(projectCwd, [faviconPath]);
187 if (existing) {
188 return existing;
189 }
190 }
191​
192 // A t3.json iconPath takes precedence over the well-known locations.
193 const projectFile = yield* projectFileLoader.load(projectCwd);
194 if (Option.isSome(projectFile) && projectFile.value.iconPath !== undefined) {
195 const existing = yield* findExistingFile(projectCwd, [projectFile.value.iconPath]);
196 if (existing) {
197 return existing;
198 }
199 }
200​
201 for (const candidate of FAVICON_CANDIDATES) {
202 const existing = yield* findExistingFile(projectCwd, [candidate]);
203 if (existing) {
204 return existing;
205 }
206 }
207​
208 for (const sourceFile of ICON_SOURCE_FILES) {
209 const sourcePath = yield* workspacePaths
210 .resolveRelativePathWithinRoot({
211 workspaceRoot: projectCwd,
212 relativePath: sourceFile,
213 })
214 .pipe(
215 Effect.mapError(
216 (cause) =>
217 new ProjectFaviconResolutionError({
218 operation: "resolve-path",
219 workspaceRoot: projectCwd,
220 relativePath: sourceFile,
221 cause,
222 }),
223 ),
224 );
225 const source = yield* optionOnNotFound(
226 fileSystem.readFileString(sourcePath.absolutePath),
227 ).pipe(
228 Effect.mapError(
229 (cause) =>
230 new ProjectFaviconResolutionError({
231 operation: "read-source",
232 workspaceRoot: projectCwd,
233 relativePath: sourceFile,
234 absolutePath: sourcePath.absolutePath,
235 cause,
236 }),
237 ),
238 );
239 if (Option.isNone(source)) {
240 continue;
241 }
242 const href = extractIconHref(source.value);
243 if (!href) {
244 continue;
245 }
246 const existing = yield* findExistingFile(projectCwd, resolveIconHref(href));
247 if (existing) {
248 return existing;
249 }
250 }
251​
252 return null;
253 });
254​
255 return ProjectFaviconResolver.of({ resolvePath });
256});
257​
258export const layer = Layer.effect(ProjectFaviconResolver, make);