Open History to see the last commit
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 Cache from "effect/Cache";
10import * as Context from "effect/Context";
11import * as Duration from "effect/Duration";
12import * as Effect from "effect/Effect";
13import * as Exit from "effect/Exit";
14import * as FileSystem from "effect/FileSystem";
15import * as Layer from "effect/Layer";
16import * as Option from "effect/Option";
17import * as Path from "effect/Path";
18import * as PlatformError from "effect/PlatformError";
19import * as Schema from "effect/Schema";
20
21import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
22import * as T3ProjectFileLoader from "./T3ProjectFileLoader.ts";
23
24// Resolution walks up to 12 well-known paths plus 7 source files, so a miss
25// costs ~20 filesystem probes. AssetAccess resolves on every project-favicon
26// asset URL, and a project's icon does not move, so the answer is cached.
27const FAVICON_CACHE_CAPACITY = 512;
28const FAVICON_POSITIVE_CACHE_TTL = Duration.minutes(10);
29const FAVICON_NEGATIVE_CACHE_TTL = Duration.minutes(1);
30
31function faviconCacheKey(cwd: string, faviconPath?: string): string {
32 return `${faviconPath ?? ""}\0${cwd}`;
33}
34
35function parseFaviconCacheKey(key: string): {
36 readonly cwd: string;
37 readonly faviconPath?: string;
38} {
39 const separatorIndex = key.indexOf("\0");
40 if (separatorIndex === -1) {
41 return { cwd: key };
42 }
43 const faviconPath = key.slice(0, separatorIndex);
44 const cwd = key.slice(separatorIndex + 1);
45 return faviconPath.length === 0 ? { cwd } : { cwd, faviconPath };
46}
47
48// Well-known favicon paths checked in order.
49const FAVICON_CANDIDATES = [
50 "favicon.svg",
51 "favicon.ico",
52 "favicon.png",
53 "public/favicon.svg",
54 "public/favicon.ico",
55 "public/favicon.png",
56 "app/favicon.ico",
57 "app/favicon.png",
58 "app/icon.svg",
59 "app/icon.png",
60 "app/icon.ico",
61 "src/favicon.ico",
62 "src/favicon.svg",
63 "src/app/favicon.ico",
64 "src/app/icon.svg",
65 "src/app/icon.png",
66 "assets/icon.svg",
67 "assets/icon.png",
68 "assets/logo.svg",
69 "assets/logo.png",
70 ".idea/icon.svg",
71] as const;
72
73// Files that may contain a <link rel="icon"> or icon metadata declaration.
74const ICON_SOURCE_FILES = [
75 "index.html",
76 "public/index.html",
77 "app/routes/__root.tsx",
78 "src/routes/__root.tsx",
79 "app/root.tsx",
80 "src/root.tsx",
81 "src/index.html",
82] as const;
83
84// Matches <link ...> tags or object-like icon metadata where rel/href can appear in any order.
85// The tag pattern is anchored on `<link`, so it only starts at real candidates. Object metadata
86// is matched by scanning brace-free runs instead of by one combined pattern: an unanchored
87// pattern restarts at every offset and rescans forward, which is quadratic on large sources.
88const LINK_ICON_HTML_RE =
89 /<link\b(?=[^>]*\brel=["'](?:icon|shortcut icon)["'])(?=[^>]*\bhref=["']([^"'?]+))[^>]*>/i;
90const ICON_REL_RE = /\brel\s*:\s*["'](?:icon|shortcut icon)["']/i;
91const ICON_HREF_RE = /\bhref\s*:\s*["']([^"'?]+)/i;
92
93export class ProjectFaviconResolutionError extends Schema.TaggedErrorClass<ProjectFaviconResolutionError>()(
94 "ProjectFaviconResolutionError",
95 {
96 operation: Schema.Literals([
97 "normalize-workspace",
98 "resolve-path",
99 "stat-candidate",
100 "read-source",
101 ]),
102 workspaceRoot: Schema.String,
103 relativePath: Schema.optional(Schema.String),
104 absolutePath: Schema.optional(Schema.String),
105 cause: Schema.Defect(),
106 },
107) {
108 override get message(): string {
109 return `Failed to resolve project favicon during ${this.operation} for workspace ${this.workspaceRoot}.`;
110 }
111}
112
113/** Service tag for project favicon resolution. */
114export class ProjectFaviconResolver extends Context.Service<
115 ProjectFaviconResolver,
116 {
117 /**
118 * Resolve a favicon or icon file path for the provided workspace root.
119 *
120 * Returns `null` when no candidate icon file can be found.
121 */
122 readonly resolvePath: (
123 cwd: string,
124 faviconPath?: string,
125 ) => Effect.Effect<string | null, ProjectFaviconResolutionError>;
126 }
127>()("t3/project/ProjectFaviconResolver") {}
128
129function extractIconHref(source: string): string | null {
130 const htmlMatch = source.match(LINK_ICON_HTML_RE);
131 if (htmlMatch?.[1]) return htmlMatch[1];
132 // Icon metadata counts when `rel` and `href` share a brace-free run, so a run holding `rel`
133 // but no href falls through to the next one rather than ending the search.
134 for (const run of source.split("}")) {
135 if (!ICON_REL_RE.test(run)) continue;
136 const hrefMatch = run.match(ICON_HREF_RE);
137 if (hrefMatch?.[1]) return hrefMatch[1];
138 }
139 return null;
140}
141
142const optionOnNotFound = <A, R>(
143 effect: Effect.Effect<A, PlatformError.PlatformError, R>,
144): Effect.Effect<Option.Option<A>, PlatformError.PlatformError, R> =>
145 effect.pipe(
146 Effect.map(Option.some),
147 Effect.catchTags({
148 PlatformError: (error) =>
149 error.reason._tag === "NotFound" ? Effect.succeed(Option.none<A>()) : Effect.fail(error),
150 }),
151 );
152
153export const make = Effect.gen(function* () {
154 const fileSystem = yield* FileSystem.FileSystem;
155 const path = yield* Path.Path;
156 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
157 const projectFileLoader = yield* T3ProjectFileLoader.T3ProjectFileLoader;
158
159 const resolveIconHref = (href: string): ReadonlyArray<string> => {
160 const clean = href.replace(/^\//, "");
161 return [path.join("public", clean), clean];
162 };
163
164 const findExistingFile = Effect.fn("ProjectFaviconResolver.findExistingFile")(function* (
165 projectCwd: string,
166 relativeCandidates: ReadonlyArray<string>,
167 candidateScope: "workspace" | "filesystem",
168 ): Effect.fn.Return<string | null, ProjectFaviconResolutionError> {
169 for (const relativePath of relativeCandidates) {
170 const candidate = yield* (
171 candidateScope === "filesystem" && path.isAbsolute(relativePath)
172 ? Effect.succeed({ absolutePath: relativePath, relativePath })
173 : workspacePaths.resolveRelativePathWithinRoot({
174 workspaceRoot: projectCwd,
175 relativePath,
176 })
177 ).pipe(
178 Effect.map(Option.some),
179 Effect.catchTags({
180 WorkspacePathOutsideRootError: () =>
181 Effect.succeed(
182 Option.none<{ readonly absolutePath: string; readonly relativePath: string }>(),
183 ),
184 }),
185 );
186 if (Option.isNone(candidate)) {
187 continue;
188 }
189 const stats = yield* optionOnNotFound(fileSystem.stat(candidate.value.absolutePath)).pipe(
190 Effect.mapError(
191 (cause) =>
192 new ProjectFaviconResolutionError({
193 operation: "stat-candidate",
194 workspaceRoot: projectCwd,
195 relativePath,
196 absolutePath: candidate.value.absolutePath,
197 cause,
198 }),
199 ),
200 );
201 if (Option.isSome(stats) && stats.value.type === "File") {
202 return candidate.value.absolutePath;
203 }
204 }
205 return null;
206 });
207
208 const resolvePathUncached = Effect.fn("ProjectFaviconResolver.resolvePathUncached")(function* (
209 cwd: string,
210 faviconPath?: string,
211 ): Effect.fn.Return<string | null, ProjectFaviconResolutionError> {
212 const projectCwd = yield* workspacePaths.normalizeWorkspaceRoot(cwd).pipe(
213 Effect.mapError(
214 (cause) =>
215 new ProjectFaviconResolutionError({
216 operation: "normalize-workspace",
217 workspaceRoot: cwd,
218 cause,
219 }),
220 ),
221 );
222 // A grouped project's saved path can be absent from one checkout. Use it
223 // where it exists and retain automatic discovery for the other checkouts.
224 if (faviconPath !== undefined) {
225 const existing = yield* findExistingFile(projectCwd, [faviconPath], "filesystem");
226 if (existing) {
227 return existing;
228 }
229 }
230
231 // A t3.json iconPath takes precedence over the well-known locations.
232 const projectFile = yield* projectFileLoader.load(projectCwd);
233 if (Option.isSome(projectFile) && projectFile.value.iconPath !== undefined) {
234 const existing = yield* findExistingFile(
235 projectCwd,
236 [projectFile.value.iconPath],
237 "workspace",
238 );
239 if (existing) {
240 return existing;
241 }
242 }
243
244 for (const candidate of FAVICON_CANDIDATES) {
245 const existing = yield* findExistingFile(projectCwd, [candidate], "workspace");
246 if (existing) {
247 return existing;
248 }
249 }
250
251 for (const sourceFile of ICON_SOURCE_FILES) {
252 const sourcePath = yield* workspacePaths
253 .resolveRelativePathWithinRoot({
254 workspaceRoot: projectCwd,
255 relativePath: sourceFile,
256 })
257 .pipe(
258 Effect.mapError(
259 (cause) =>
260 new ProjectFaviconResolutionError({
261 operation: "resolve-path",
262 workspaceRoot: projectCwd,
263 relativePath: sourceFile,
264 cause,
265 }),
266 ),
267 );
268 const source = yield* optionOnNotFound(
269 fileSystem.readFileString(sourcePath.absolutePath),
270 ).pipe(
271 Effect.mapError(
272 (cause) =>
273 new ProjectFaviconResolutionError({
274 operation: "read-source",
275 workspaceRoot: projectCwd,
276 relativePath: sourceFile,
277 absolutePath: sourcePath.absolutePath,
278 cause,
279 }),
280 ),
281 );
282 if (Option.isNone(source)) {
283 continue;
284 }
285 const href = extractIconHref(source.value);
286 if (!href) {
287 continue;
288 }
289 const existing = yield* findExistingFile(projectCwd, resolveIconHref(href), "workspace");
290 if (existing) {
291 return existing;
292 }
293 }
294
295 return null;
296 });
297
298 const faviconCache = yield* Cache.makeWith<string, string | null, ProjectFaviconResolutionError>(
299 (key) => {
300 const { cwd, faviconPath } = parseFaviconCacheKey(key);
301 return resolvePathUncached(cwd, faviconPath);
302 },
303 {
304 capacity: FAVICON_CACHE_CAPACITY,
305 timeToLive: Exit.match({
306 onSuccess: (value: string | null) =>
307 value === null ? FAVICON_NEGATIVE_CACHE_TTL : FAVICON_POSITIVE_CACHE_TTL,
308 onFailure: () => Duration.zero,
309 }),
310 },
311 );
312
313 const resolvePath: ProjectFaviconResolver["Service"]["resolvePath"] = Effect.fn(
314 "ProjectFaviconResolver.resolvePath",
315 )(function* (cwd, faviconPath) {
316 const key = faviconCacheKey(cwd, faviconPath);
317 const cached = yield* Cache.get(faviconCache, key);
318 if (cached === null) {
319 return null;
320 }
321
322 // A hit still confirms the file with one stat rather than the ~20 probes a
323 // full walk costs, so a deleted icon falls back at once instead of after
324 // the TTL.
325 const stats = yield* optionOnNotFound(fileSystem.stat(cached)).pipe(
326 Effect.mapError(
327 (cause) =>
328 new ProjectFaviconResolutionError({
329 operation: "stat-candidate",
330 workspaceRoot: cwd,
331 absolutePath: cached,
332 cause,
333 }),
334 ),
335 );
336 if (Option.isSome(stats) && stats.value.type === "File") {
337 return cached;
338 }
339
340 yield* Cache.invalidate(faviconCache, key);
341 return yield* Cache.get(faviconCache, key);
342 });
343
344 return ProjectFaviconResolver.of({ resolvePath });
345});
346
347export const layer = Layer.effect(ProjectFaviconResolver, make);