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