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

ProjectFaviconResolver.ts

425 lines14.3 KB

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