Open History to see the last commit
1import * as Cache from "effect/Cache";
2import * as Context from "effect/Context";
3import * as Duration from "effect/Duration";
4import * as Effect from "effect/Effect";
5import * as Exit from "effect/Exit";
6import * as Fiber from "effect/Fiber";
7import * as FileSystem from "effect/FileSystem";
8import * as Layer from "effect/Layer";
9import * as Option from "effect/Option";
10import * as Path from "effect/Path";
11import * as PlatformError from "effect/PlatformError";
12import * as Schema from "effect/Schema";
13
14import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
15import * as T3ProjectFileLoader from "./T3ProjectFileLoader.ts";
16
17const FAVICON_CACHE_CAPACITY = 512;
18const FAVICON_POSITIVE_CACHE_TTL = Duration.minutes(10);
19const FAVICON_NEGATIVE_CACHE_TTL = Duration.minutes(1);
20
21function faviconCacheKey(cwd: string, faviconPath?: string): string {
22 return `${faviconPath ?? ""}\0${cwd}`;
23}
24
25function parseFaviconCacheKey(key: string): {
26 readonly cwd: string;
27 readonly faviconPath?: string;
28} {
29 const separatorIndex = key.indexOf("\0");
30 if (separatorIndex === -1) {
31 return { cwd: key };
32 }
33 const faviconPath = key.slice(0, separatorIndex);
34 const cwd = key.slice(separatorIndex + 1);
35 return faviconPath.length === 0 ? { cwd } : { cwd, faviconPath };
36}
37
38const FAVICON_CANDIDATES = [
39 "favicon.svg",
40 "favicon.ico",
41 "favicon.png",
42 "public/favicon.svg",
43 "public/favicon.ico",
44 "public/favicon.png",
45 "app/favicon.ico",
46 "app/favicon.png",
47 "app/icon.svg",
48 "app/icon.png",
49 "app/icon.ico",
50 "src/favicon.ico",
51 "src/favicon.svg",
52 "src/app/favicon.ico",
53 "src/app/icon.svg",
54 "src/app/icon.png",
55 "assets/icon.svg",
56 "assets/icon.png",
57 "assets/logo.svg",
58 "assets/logo.png",
59 ".idea/icon.svg",
60 "Resources/AppIcon.icns",
61 "AppIcon.icns",
62] as const;
63
64const ICON_SOURCE_FILES = [
65 "index.html",
66 "public/index.html",
67 "app/routes/__root.tsx",
68 "src/routes/__root.tsx",
69 "app/root.tsx",
70 "src/root.tsx",
71 "src/index.html",
72] as const;
73
74// The tag pattern is anchored on `<link`, so it only starts at real candidates. Object metadata
75// is matched by scanning brace-free runs instead of by one combined pattern: an unanchored
76// pattern restarts at every offset and rescans forward, which is quadratic on large sources.
77const LINK_ICON_HTML_RE =
78 /<link\b(?=[^>]*\brel=["'](?:icon|shortcut icon)["'])(?=[^>]*\bhref=["']([^"'?]+))[^>]*>/i;
79const ICON_REL_RE = /\brel\s*:\s*["'](?:icon|shortcut icon)["']/i;
80const ICON_HREF_RE = /\bhref\s*:\s*["']([^"'?]+)/i;
81
82export class ProjectFaviconResolutionError extends Schema.TaggedError<ProjectFaviconResolutionError>()(
83 "ProjectFaviconResolutionError",
84 {
85 operation: Schema.Literals([
86 "normalize-workspace",
87 "resolve-path",
88 "stat-candidate",
89 "read-source",
90 ]),
91 workspaceRoot: Schema.String,
92 relativePath: Schema.optional(Schema.String),
93 absolutePath: Schema.optional(Schema.String),
94 cause: Schema.Defect(),
95 },
96) {
97 override get message(): string {
98 return `Failed to resolve project favicon during ${this.operation} for workspace ${this.workspaceRoot}.`;
99 }
100}
101
102const isWorkspaceRootNotExistsError = Schema.is(WorkspacePaths.WorkspaceRootNotExistsError);
103
104export const isMissingWorkspaceRoot = (error: ProjectFaviconResolutionError): boolean =>
105 error.operation === "normalize-workspace" && isWorkspaceRootNotExistsError(error.cause);
106
107export class ProjectFaviconResolver extends Context.Service<
108 ProjectFaviconResolver,
109 {
110 readonly resolvePath: (
111 cwd: string,
112 faviconPath?: string,
113 ) => Effect.Effect<string | null, ProjectFaviconResolutionError>;
114 /** Forgets cached lookups for a workspace whose files changed, such as a finished clone. */
115 readonly invalidate: (cwd: string) => Effect.Effect<void>;
116 }
117>()("t3/project/ProjectFaviconResolver") {}
118
119function extractIconHref(source: string): string | null {
120 const htmlMatch = source.match(LINK_ICON_HTML_RE);
121 if (htmlMatch?.[1]) return htmlMatch[1];
122 for (const run of source.split("}")) {
123 if (!ICON_REL_RE.test(run)) continue;
124 const hrefMatch = run.match(ICON_HREF_RE);
125 if (hrefMatch?.[1]) return hrefMatch[1];
126 }
127 return null;
128}
129
130const optionOnNotFound = <A, R>(
131 effect: Effect.Effect<A, PlatformError.PlatformError, R>,
132): Effect.Effect<Option.Option<A>, PlatformError.PlatformError, R> =>
133 effect.pipe(
134 Effect.asSome,
135 Effect.catchTags({
136 PlatformError: (error) =>
137 error.reason._tag === "NotFound" ? Effect.succeed(Option.none<A>()) : Effect.fail(error),
138 }),
139 );
140
141export const make = Effect.gen(function* () {
142 const fileSystem = yield* FileSystem.FileSystem;
143 const path = yield* Path.Path;
144 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
145 const projectFileLoader = yield* T3ProjectFileLoader.T3ProjectFileLoader;
146
147 const resolveIconHref = (href: string): ReadonlyArray<string> => {
148 const clean = href.replace(/^\//, "");
149 return [path.join("public", clean), clean];
150 };
151
152 const findExistingFile = Effect.fn("ProjectFaviconResolver.findExistingFile")(function* (
153 projectCwd: string,
154 relativeCandidates: ReadonlyArray<string>,
155 candidateScope: "workspace" | "filesystem",
156 ): Effect.fn.Return<string | null, ProjectFaviconResolutionError> {
157 for (const relativePath of relativeCandidates) {
158 const candidate = yield* (
159 candidateScope === "filesystem" && path.isAbsolute(relativePath)
160 ? Effect.succeed({ absolutePath: relativePath, relativePath })
161 : workspacePaths.resolveRelativePathWithinRoot({
162 workspaceRoot: projectCwd,
163 relativePath,
164 })
165 ).pipe(
166 Effect.asSome,
167 Effect.catchTags({
168 WorkspacePathOutsideRootError: () =>
169 Effect.succeed(
170 Option.none<{ readonly absolutePath: string; readonly relativePath: string }>(),
171 ),
172 }),
173 );
174 if (Option.isNone(candidate)) {
175 continue;
176 }
177 const stats = yield* optionOnNotFound(fileSystem.stat(candidate.value.absolutePath)).pipe(
178 Effect.mapError(
179 (cause) =>
180 new ProjectFaviconResolutionError({
181 operation: "stat-candidate",
182 workspaceRoot: projectCwd,
183 relativePath,
184 absolutePath: candidate.value.absolutePath,
185 cause,
186 }),
187 ),
188 );
189 if (Option.isSome(stats) && stats.value.type === "File") {
190 return candidate.value.absolutePath;
191 }
192 }
193 return null;
194 });
195
196 const findIconFromSource = Effect.fn("ProjectFaviconResolver.findIconFromSource")(function* (
197 projectCwd: string,
198 sourceFile: string,
199 ): Effect.fn.Return<string | null, ProjectFaviconResolutionError> {
200 const sourcePath = yield* workspacePaths
201 .resolveRelativePathWithinRoot({
202 workspaceRoot: projectCwd,
203 relativePath: sourceFile,
204 })
205 .pipe(
206 Effect.mapError(
207 (cause) =>
208 new ProjectFaviconResolutionError({
209 operation: "resolve-path",
210 workspaceRoot: projectCwd,
211 relativePath: sourceFile,
212 cause,
213 }),
214 ),
215 );
216 const source = yield* optionOnNotFound(fileSystem.readFileString(sourcePath.absolutePath)).pipe(
217 Effect.mapError(
218 (cause) =>
219 new ProjectFaviconResolutionError({
220 operation: "read-source",
221 workspaceRoot: projectCwd,
222 relativePath: sourceFile,
223 absolutePath: sourcePath.absolutePath,
224 cause,
225 }),
226 ),
227 );
228 if (Option.isNone(source)) {
229 return null;
230 }
231 const href = extractIconHref(source.value);
232 if (!href) {
233 return null;
234 }
235 return yield* findExistingFile(projectCwd, resolveIconHref(href), "workspace");
236 });
237
238 // Starts every probe at once and returns the first hit in list order. A miss
239 // costs one round of filesystem latency instead of one per probe, which
240 // matters when the disk is slow. Fibers are joined in order, so a hit returns
241 // without waiting for lower-ranked probes (the scope interrupts them), and a
242 // failure surfaces only when no earlier probe found a file.
243 const firstInOrder = Effect.fn("ProjectFaviconResolver.firstInOrder")(function* <A>(
244 items: ReadonlyArray<A>,
245 probe: (item: A) => Effect.Effect<string | null, ProjectFaviconResolutionError>,
246 ) {
247 const fibers = yield* Effect.forEach(items, (item) => Effect.forkScoped(probe(item)));
248 for (const fiber of fibers) {
249 const found = yield* Fiber.join(fiber);
250 if (found) {
251 return found;
252 }
253 }
254 return null;
255 }, Effect.scoped);
256
257 const resolvePathUncached = Effect.fn("ProjectFaviconResolver.resolvePathUncached")(function* (
258 cwd: string,
259 faviconPath?: string,
260 ): Effect.fn.Return<string | null, ProjectFaviconResolutionError> {
261 const projectCwd = yield* workspacePaths.normalizeWorkspaceRoot(cwd).pipe(
262 Effect.mapError(
263 (cause) =>
264 new ProjectFaviconResolutionError({
265 operation: "normalize-workspace",
266 workspaceRoot: cwd,
267 cause,
268 }),
269 ),
270 );
271 if (faviconPath !== undefined) {
272 const existing = yield* findExistingFile(projectCwd, [faviconPath], "filesystem");
273 if (existing) {
274 return existing;
275 }
276 }
277
278 const projectFile = yield* projectFileLoader.load(projectCwd);
279 if (Option.isSome(projectFile) && projectFile.value.iconPath !== undefined) {
280 const existing = yield* findExistingFile(
281 projectCwd,
282 [projectFile.value.iconPath],
283 "workspace",
284 );
285 if (existing) {
286 return existing;
287 }
288 }
289
290 const wellKnown = yield* firstInOrder(FAVICON_CANDIDATES, (candidate) =>
291 findExistingFile(projectCwd, [candidate], "workspace"),
292 );
293 if (wellKnown) {
294 return wellKnown;
295 }
296
297 return yield* firstInOrder(ICON_SOURCE_FILES, (sourceFile) =>
298 findIconFromSource(projectCwd, sourceFile),
299 );
300 });
301
302 const faviconCache = yield* Cache.makeWith<string, string | null, ProjectFaviconResolutionError>(
303 (key) => {
304 const { cwd, faviconPath } = parseFaviconCacheKey(key);
305 return resolvePathUncached(cwd, faviconPath);
306 },
307 {
308 capacity: FAVICON_CACHE_CAPACITY,
309 timeToLive: Exit.match({
310 onSuccess: (value: string | null) =>
311 value === null ? FAVICON_NEGATIVE_CACHE_TTL : FAVICON_POSITIVE_CACHE_TTL,
312 onFailure: () => Duration.zero,
313 }),
314 },
315 );
316
317 const resolvePath: ProjectFaviconResolver["Service"]["resolvePath"] = Effect.fn(
318 "ProjectFaviconResolver.resolvePath",
319 )(function* (cwd, faviconPath) {
320 const key = faviconCacheKey(cwd, faviconPath);
321 const cached = yield* Cache.get(faviconCache, key);
322 if (cached === null) {
323 return null;
324 }
325
326 const stats = yield* optionOnNotFound(fileSystem.stat(cached)).pipe(
327 Effect.mapError(
328 (cause) =>
329 new ProjectFaviconResolutionError({
330 operation: "stat-candidate",
331 workspaceRoot: cwd,
332 absolutePath: cached,
333 cause,
334 }),
335 ),
336 );
337 if (Option.isSome(stats) && stats.value.type === "File") {
338 return cached;
339 }
340
341 yield* Cache.invalidate(faviconCache, key);
342 return yield* Cache.get(faviconCache, key);
343 });
344
345 const invalidate: ProjectFaviconResolver["Service"]["invalidate"] = (cwd) =>
346 Cache.keys(faviconCache).pipe(
347 Effect.flatMap((keys) =>
348 Effect.forEach(
349 Array.from(keys).filter((key) => parseFaviconCacheKey(key).cwd === cwd),
350 (key) => Cache.invalidate(faviconCache, key),
351 { discard: true },
352 ),
353 ),
354 );
355
356 return ProjectFaviconResolver.of({ resolvePath, invalidate });
357});
358
359export const layer = Layer.effect(ProjectFaviconResolver, make);