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

ProjectFaviconResolver.ts

391 lines12.6 KB

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 ICON_SOURCE_SCAN_BYTES = 128 * 1024;
20const FAVICON_POSITIVE_CACHE_TTL = Duration.minutes(10);
21const FAVICON_NEGATIVE_CACHE_TTL = Duration.minutes(1);
22​
23function faviconCacheKey(cwd: string, faviconPath?: string): string {
24 return `${faviconPath ?? ""}\0${cwd}`;
26​
27function parseFaviconCacheKey(key: string): {
28 readonly cwd: string;
29 readonly faviconPath?: string;
30} {
31 const separatorIndex = key.indexOf("\0");
32 if (separatorIndex === -1) {
33 return { cwd: key };
34 }
35 const faviconPath = key.slice(0, separatorIndex);
36 const cwd = key.slice(separatorIndex + 1);
37 return faviconPath.length === 0 ? { cwd } : { cwd, faviconPath };
39​
40const FAVICON_CANDIDATES = [
41 "favicon.svg",
42 "favicon.ico",
43 "favicon.png",
44 "public/favicon.svg",
45 "public/favicon.ico",
46 "public/favicon.png",
47 "app/favicon.ico",
48 "app/favicon.png",
49 "app/icon.svg",
50 "app/icon.png",
51 "app/icon.ico",
52 "src/favicon.ico",
53 "src/favicon.svg",
54 "src/app/favicon.ico",
55 "src/app/icon.svg",
56 "src/app/icon.png",
57 "assets/icon.svg",
58 "assets/icon.png",
59 "assets/logo.svg",
60 "assets/logo.png",
61 ".idea/icon.svg",
62 "Resources/AppIcon.icns",
63 "AppIcon.icns",
64] as const;
65​
66// Flutter's default favicon ranks below icons a project declares in its source.
67const FALLBACK_FAVICON_CANDIDATES = ["web/favicon.png"] as const;
68​
69const ICON_SOURCE_FILES = [
70 "index.html",
71 "public/index.html",
72 "app/routes/__root.tsx",
73 "src/routes/__root.tsx",
74 "app/root.tsx",
75 "src/root.tsx",
76 "src/index.html",
77] as const;
78​
79const HTML_LINK_RE = /<link\b[^<>]*>/gi;
80const HTML_ICON_REL_RE = /\brel=["'](?:icon|shortcut icon)["']/i;
81const HTML_ICON_HREF_RE = /\bhref=["']([^"'?]+)/i;
82const ICON_REL_RE = /\brel\s*:\s*["'](?:icon|shortcut icon)["']/i;
83const ICON_HREF_RE = /\bhref\s*:\s*["']([^"'?]+)/i;
84​
85export class ProjectFaviconResolutionError extends Schema.TaggedError<ProjectFaviconResolutionError>()(
86 "ProjectFaviconResolutionError",
87 {
88 operation: Schema.Literals([
89 "normalize-workspace",
90 "resolve-path",
91 "stat-candidate",
92 "read-source",
93 ]),
94 workspaceRoot: Schema.String,
95 relativePath: Schema.optional(Schema.String),
96 absolutePath: Schema.optional(Schema.String),
97 cause: Schema.Defect(),
98 },
99) {
100 override get message(): string {
101 return `Failed to resolve project favicon during ${this.operation} for workspace ${this.workspaceRoot}.`;
102 }
104​
105const isWorkspaceRootNotExistsError = Schema.is(WorkspacePaths.WorkspaceRootNotExistsError);
106​
107export const isMissingWorkspaceRoot = (error: ProjectFaviconResolutionError): boolean =>
108 error.operation === "normalize-workspace" && isWorkspaceRootNotExistsError(error.cause);
109​
110export class ProjectFaviconResolver extends Context.Service<
111 ProjectFaviconResolver,
112 {
113 readonly resolvePath: (
114 cwd: string,
115 faviconPath?: string,
116 ) => Effect.Effect<string | null, ProjectFaviconResolutionError>;
117 /** Forgets cached lookups for a workspace whose files changed, such as a finished clone. */
118 readonly invalidate: (cwd: string) => Effect.Effect<void>;
119 }
120>()("t3/project/ProjectFaviconResolver") {}
121​
122function extractIconHref(source: string): string | null {
123 for (const [tag] of source.matchAll(HTML_LINK_RE)) {
124 if (!HTML_ICON_REL_RE.test(tag)) continue;
125 const hrefMatch = tag.match(HTML_ICON_HREF_RE);
126 if (hrefMatch?.[1]) return hrefMatch[1];
127 }
128 for (const run of source.split("}")) {
129 if (!ICON_REL_RE.test(run)) continue;
130 const hrefMatch = run.match(ICON_HREF_RE);
131 if (hrefMatch?.[1]) return hrefMatch[1];
132 }
133 return null;
135​
136export const optionOnNotFound = <A, R>(
137 effect: Effect.Effect<A, PlatformError.PlatformError, R>,
138): Effect.Effect<Option.Option<A>, PlatformError.PlatformError, R> =>
139 effect.pipe(
140 Effect.asSome,
141 Effect.catchTags({
142 PlatformError: (error) =>
143 error.reason._tag === "NotFound" ? Effect.succeed(Option.none<A>()) : Effect.fail(error),
144 }),
145 );
146​
147export const make = Effect.gen(function* () {
148 const fileSystem = yield* FileSystem.FileSystem;
149 const path = yield* Path.Path;
150 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
151 const projectFileLoader = yield* T3ProjectFileLoader.T3ProjectFileLoader;
152​
153 const resolveIconHref = (href: string): ReadonlyArray<string> => {
154 // Browsers strip surrounding whitespace from URL attributes; file paths keep theirs.
155 const clean = href.trim().replace(/^\//, "");
156 return [path.join("public", clean), clean];
157 };
158​
159 const findExistingFile = Effect.fn("ProjectFaviconResolver.findExistingFile")(function* (
160 projectCwd: string,
161 relativeCandidates: ReadonlyArray<string>,
162 candidateScope: "workspace" | "filesystem",
163 ): Effect.fn.Return<string | null, ProjectFaviconResolutionError> {
164 for (const relativePath of relativeCandidates) {
165 const candidate = yield* (
166 candidateScope === "filesystem" && path.isAbsolute(relativePath)
167 ? Effect.succeed({ absolutePath: relativePath, relativePath })
168 : workspacePaths.resolveRelativePathWithinRoot({
169 workspaceRoot: projectCwd,
170 relativePath,
171 })
172 ).pipe(
173 Effect.asSome,
174 Effect.catchTags({
175 WorkspacePathOutsideRootError: () =>
176 Effect.succeed(
177 Option.none<{ readonly absolutePath: string; readonly relativePath: string }>(),
178 ),
179 }),
180 );
181 if (Option.isNone(candidate)) {
182 continue;
183 }
184 const stats = yield* optionOnNotFound(fileSystem.stat(candidate.value.absolutePath)).pipe(
185 Effect.mapError(
186 (cause) =>
187 new ProjectFaviconResolutionError({
188 operation: "stat-candidate",
189 workspaceRoot: projectCwd,
190 relativePath,
191 absolutePath: candidate.value.absolutePath,
192 cause,
193 }),
194 ),
195 );
196 if (Option.isSome(stats) && stats.value.type === "File") {
197 return candidate.value.absolutePath;
198 }
199 }
200 return null;
201 });
202​
203 const findIconFromSource = Effect.fn("ProjectFaviconResolver.findIconFromSource")(function* (
204 projectCwd: string,
205 sourceFile: string,
206 ): Effect.fn.Return<string | null, ProjectFaviconResolutionError> {
207 const sourcePath = yield* workspacePaths
208 .resolveRelativePathWithinRoot({
209 workspaceRoot: projectCwd,
210 relativePath: sourceFile,
211 })
212 .pipe(
213 Effect.mapError(
214 (cause) =>
215 new ProjectFaviconResolutionError({
216 operation: "resolve-path",
217 workspaceRoot: projectCwd,
218 relativePath: sourceFile,
219 cause,
220 }),
221 ),
222 );
223 const stats = yield* optionOnNotFound(fileSystem.stat(sourcePath.absolutePath)).pipe(
224 Effect.mapError(
225 (cause) =>
226 new ProjectFaviconResolutionError({
227 operation: "stat-candidate",
228 workspaceRoot: projectCwd,
229 relativePath: sourceFile,
230 absolutePath: sourcePath.absolutePath,
231 cause,
232 }),
233 ),
234 );
235 if (Option.isNone(stats) || stats.value.type !== "File") {
236 return null;
237 }
238 const source = yield* optionOnNotFound(
239 fileSystem.open(sourcePath.absolutePath, { flag: "r" }).pipe(
240 Effect.flatMap((file) => file.readAlloc(ICON_SOURCE_SCAN_BYTES)),
241 Effect.scoped,
242 ),
243 ).pipe(
244 Effect.mapError(
245 (cause) =>
246 new ProjectFaviconResolutionError({
247 operation: "read-source",
248 workspaceRoot: projectCwd,
249 relativePath: sourceFile,
250 absolutePath: sourcePath.absolutePath,
251 cause,
252 }),
253 ),
254 );
255 if (Option.isNone(source) || Option.isNone(source.value)) {
256 return null;
257 }
258 const href = extractIconHref(new TextDecoder().decode(source.value.value));
259 if (!href) {
260 return null;
261 }
262 return yield* findExistingFile(projectCwd, resolveIconHref(href), "workspace");
263 });
264​
265 // Probe concurrently but join in list order so lower-ranked probes cannot delay a hit.
266 // A failure surfaces only if no earlier probe found a file; scope exit interrupts remaining probes.
267 const firstInOrder = Effect.fn("ProjectFaviconResolver.firstInOrder")(function* <A>(
268 items: ReadonlyArray<A>,
269 probe: (item: A) => Effect.Effect<string | null, ProjectFaviconResolutionError>,
270 ) {
271 const fibers = yield* Effect.forEach(items, (item) => Effect.forkScoped(probe(item)));
272 for (const fiber of fibers) {
273 const found = yield* Fiber.join(fiber);
274 if (found) {
275 return found;
276 }
277 }
278 return null;
279 }, Effect.scoped);
280​
281 const resolvePathUncached = Effect.fn("ProjectFaviconResolver.resolvePathUncached")(function* (
282 cwd: string,
283 faviconPath?: string,
284 ): Effect.fn.Return<string | null, ProjectFaviconResolutionError> {
285 const projectCwd = yield* workspacePaths.normalizeWorkspaceRoot(cwd).pipe(
286 Effect.mapError(
287 (cause) =>
288 new ProjectFaviconResolutionError({
289 operation: "normalize-workspace",
290 workspaceRoot: cwd,
291 cause,
292 }),
293 ),
294 );
295 if (faviconPath !== undefined) {
296 const existing = yield* findExistingFile(projectCwd, [faviconPath], "filesystem");
297 if (existing) {
298 return existing;
299 }
300 }
301​
302 const projectFile = yield* projectFileLoader.load(projectCwd);
303 if (Option.isSome(projectFile) && projectFile.value.iconPath !== undefined) {
304 const existing = yield* findExistingFile(
305 projectCwd,
306 [projectFile.value.iconPath],
307 "workspace",
308 );
309 if (existing) {
310 return existing;
311 }
312 }
313​
314 const wellKnown = yield* firstInOrder(FAVICON_CANDIDATES, (candidate) =>
315 findExistingFile(projectCwd, [candidate], "workspace"),
316 );
317 if (wellKnown) {
318 return wellKnown;
319 }
320​
321 const sourceDeclared = yield* firstInOrder(ICON_SOURCE_FILES, (sourceFile) =>
322 findIconFromSource(projectCwd, sourceFile),
323 );
324 if (sourceDeclared) {
325 return sourceDeclared;
326 }
327​
328 return yield* findExistingFile(projectCwd, FALLBACK_FAVICON_CANDIDATES, "workspace");
329 });
330​
331 const faviconCache = yield* Cache.makeWith<string, string | null, ProjectFaviconResolutionError>(
332 (key) => {
333 const { cwd, faviconPath } = parseFaviconCacheKey(key);
334 return resolvePathUncached(cwd, faviconPath);
335 },
336 {
337 capacity: FAVICON_CACHE_CAPACITY,
338 timeToLive: Exit.match({
339 onSuccess: (value: string | null) =>
340 value === null ? FAVICON_NEGATIVE_CACHE_TTL : FAVICON_POSITIVE_CACHE_TTL,
341 onFailure: (cause) =>
342 Option.exists(Cause.findErrorOption(cause), isMissingWorkspaceRoot)
343 ? FAVICON_NEGATIVE_CACHE_TTL
344 : Duration.zero,
345 }),
346 },
347 );
348​
349 const resolvePath: ProjectFaviconResolver["Service"]["resolvePath"] = Effect.fn(
350 "ProjectFaviconResolver.resolvePath",
351 )(function* (cwd, faviconPath) {
352 const key = faviconCacheKey(cwd, faviconPath);
353 const cached = yield* Cache.get(faviconCache, key);
354 if (cached === null) {
355 return null;
356 }
357​
358 const stats = yield* optionOnNotFound(fileSystem.stat(cached)).pipe(
359 Effect.mapError(
360 (cause) =>
361 new ProjectFaviconResolutionError({
362 operation: "stat-candidate",
363 workspaceRoot: cwd,
364 absolutePath: cached,
365 cause,
366 }),
367 ),
368 );
369 if (Option.isSome(stats) && stats.value.type === "File") {
370 return cached;
371 }
372​
373 yield* Cache.invalidate(faviconCache, key);
374 return yield* Cache.get(faviconCache, key);
375 });
376​
377 const invalidate: ProjectFaviconResolver["Service"]["invalidate"] = (cwd) =>
378 Cache.keys(faviconCache).pipe(
379 Effect.flatMap((keys) =>
380 Effect.forEach(
381 Array.from(keys).filter((key) => parseFaviconCacheKey(key).cwd === cwd),
382 (key) => Cache.invalidate(faviconCache, key),
383 { discard: true },
384 ),
385 ),
386 );
387​
388 return ProjectFaviconResolver.of({ resolvePath, invalidate });
389});
390​
391export const layer = Layer.effect(ProjectFaviconResolver, make);