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

ProjectFaviconResolver.ts

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