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

ProjectFaviconResolver.ts

497 lines17.1 KB

1import { safeDecodeURIComponent } from "@t3tools/shared/markdownLinks";
2import { characterEntities } from "character-entities";
3import { characterEntitiesLegacy } from "character-entities-legacy";
4import * as Cache from "effect/Cache";
5import * as Cause from "effect/Cause";
6import * as Context from "effect/Context";
7import * as Duration from "effect/Duration";
8import * as Effect from "effect/Effect";
9import * as Exit from "effect/Exit";
10import * as Fiber from "effect/Fiber";
11import * as FileSystem from "effect/FileSystem";
12import * as Layer from "effect/Layer";
13import * as Option from "effect/Option";
14import * as Path from "effect/Path";
15import * as PlatformError from "effect/PlatformError";
16import * as Schema from "effect/Schema";
17​
18import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
19import * as T3ProjectFileLoader from "./T3ProjectFileLoader.ts";
20​
21const FAVICON_CACHE_CAPACITY = 512;
22const ICON_SOURCE_SCAN_BYTES = 128 * 1024;
23const FAVICON_POSITIVE_CACHE_TTL = Duration.minutes(10);
24const FAVICON_NEGATIVE_CACHE_TTL = Duration.minutes(1);
25​
26function faviconCacheKey(cwd: string, faviconPath?: string): string {
27 return `${faviconPath ?? ""}\0${cwd}`;
29​
30function parseFaviconCacheKey(key: string): {
31 readonly cwd: string;
32 readonly faviconPath?: string;
33} {
34 const separatorIndex = key.indexOf("\0");
35 if (separatorIndex === -1) {
36 return { cwd: key };
37 }
38 const faviconPath = key.slice(0, separatorIndex);
39 const cwd = key.slice(separatorIndex + 1);
40 return faviconPath.length === 0 ? { cwd } : { cwd, faviconPath };
42​
43const FAVICON_CANDIDATES = [
44 "favicon.svg",
45 "favicon.ico",
46 "favicon.png",
47 "public/favicon.svg",
48 "public/favicon.ico",
49 "public/favicon.png",
50 "app/favicon.ico",
51 "app/favicon.png",
52 "app/icon.svg",
53 "app/icon.png",
54 "app/icon.ico",
55 "src/favicon.ico",
56 "src/favicon.svg",
57 "src/app/favicon.ico",
58 "src/app/icon.svg",
59 "src/app/icon.png",
60 "assets/icon.svg",
61 "assets/icon.png",
62 "assets/logo.svg",
63 "assets/logo.png",
64 ".idea/icon.svg",
65 "Resources/AppIcon.icns",
66 "AppIcon.icns",
67] as const;
68​
69// Flutter's default favicon ranks below icons a project declares in its source.
70const FALLBACK_FAVICON_CANDIDATES = ["web/favicon.png"] as const;
71​
72const ICON_SOURCE_FILES = [
73 "index.html",
74 "public/index.html",
75 "app/routes/__root.tsx",
76 "src/routes/__root.tsx",
77 "app/root.tsx",
78 "src/root.tsx",
79 "src/index.html",
80] as const;
81​
82// A quote opens a value only right after `=`; the lookahead+backreference keeps it atomic so
83// backtracking cannot re-read the value as plain text.
84// A comment (to `-->`, `--!>` or the end) hides the links inside it, as in a browser.
85const HTML_LINK_RE =
86 /<!--(?:-?>|[\s\S]*?--!?>|[\s\S]*)|<link\b(?:[^<>=]|=(?=([\t\n\f\r ]*(?:"[^"]*"|'[^']*')|))\1)*>/gi;
87// `rel` is an unordered, whitespace-separated token list; any `icon` token marks an icon link.
88const ICON_REL_VALUE = String.raw`(?:"(?:[^"]*[\t\n\f\r ])?icon(?=[\t\n\f\r "])|'(?:[^']*[\t\n\f\r ])?icon(?=[\t\n\f\r ']))`;
89// HTML attribute syntax: a name, then an optional double-quoted, single-quoted, or unquoted value.
90const HTML_ATTRIBUTE_RE =
91 /([^\t\n\f\r "'<>/=]+)(?:[\t\n\f\r ]*=[\t\n\f\r ]*(?:"([^"]*)"|'([^']*)'|([^\t\n\f\r >]+)))?/g;
92const ICON_REL_RE = new RegExp(
93 String.raw`(?:^|[\s,{]|\*\/)(?:"rel"|'rel'|rel)\s*:\s*${ICON_REL_VALUE}`,
94 "i",
95);
96const ICON_HREF_RE = /(?:^|[\s,{]|\*\/)(?:"href"|'href'|href)\s*:\s*(?:"([^"?#]+)|'([^'?#]+))/i;
97// https://html.spec.whatwg.org/multipage/parsing.html#numeric-character-reference-end-state
98const HTML_C1_REPLACEMENTS: Readonly<Partial<Record<number, number>>> = {
99 0x80: 0x20ac,
100 0x82: 0x201a,
101 0x83: 0x0192,
102 0x84: 0x201e,
103 0x85: 0x2026,
104 0x86: 0x2020,
105 0x87: 0x2021,
106 0x88: 0x02c6,
107 0x89: 0x2030,
108 0x8a: 0x0160,
109 0x8b: 0x2039,
110 0x8c: 0x0152,
111 0x8e: 0x017d,
112 0x91: 0x2018,
113 0x92: 0x2019,
114 0x93: 0x201c,
115 0x94: 0x201d,
116 0x95: 0x2022,
117 0x96: 0x2013,
118 0x97: 0x2014,
119 0x98: 0x02dc,
120 0x99: 0x2122,
121 0x9a: 0x0161,
122 0x9b: 0x203a,
123 0x9c: 0x0153,
124 0x9e: 0x017e,
125 0x9f: 0x0178,
126};
127​
128export class ProjectFaviconResolutionError extends Schema.TaggedError<ProjectFaviconResolutionError>()(
129 "ProjectFaviconResolutionError",
130 {
131 operation: Schema.Literals([
132 "normalize-workspace",
133 "resolve-path",
134 "stat-candidate",
135 "read-source",
136 ]),
137 workspaceRoot: Schema.String,
138 relativePath: Schema.optional(Schema.String),
139 absolutePath: Schema.optional(Schema.String),
140 cause: Schema.Defect(),
141 },
142) {
143 override get message(): string {
144 return `Failed to resolve project favicon during ${this.operation} for workspace ${this.workspaceRoot}.`;
145 }
147​
148const isWorkspaceRootNotExistsError = Schema.is(WorkspacePaths.WorkspaceRootNotExistsError);
149​
150export const isMissingWorkspaceRoot = (error: ProjectFaviconResolutionError): boolean =>
151 error.operation === "normalize-workspace" && isWorkspaceRootNotExistsError(error.cause);
152​
153export class ProjectFaviconResolver extends Context.Service<
154 ProjectFaviconResolver,
155 {
156 readonly resolvePath: (
157 cwd: string,
158 faviconPath?: string,
159 ) => Effect.Effect<string | null, ProjectFaviconResolutionError>;
160 /** Forgets cached lookups for a workspace whose files changed, such as a finished clone. */
161 readonly invalidate: (cwd: string) => Effect.Effect<void>;
162 }
163>()("t3/project/ProjectFaviconResolver") {}
164​
165function decodeHtmlAttribute(value: string, html: boolean): string {
166 return value.replace(
167 /&(?:([a-z][a-z\d]*)([;=]?)|#(?:(\d+)|x([a-f\d]+));?)/gi,
168 (reference, name?: string, terminator?: string, decimal?: string, hex?: string) => {
169 if (name !== undefined) {
170 // HTML attributes, unlike JSX, decode legacy names without `;` unless `=` or an alphanumeric follows.
171 const decoded =
172 terminator === ";"
173 ? Object.hasOwn(characterEntities, name)
174 : terminator === "" && html && characterEntitiesLegacy.includes(name);
175 return decoded ? characterEntities[name]! : reference;
176 }
177 const codePoint = hex === undefined ? Number(decimal) : Number.parseInt(hex, 16);
178 if (codePoint === 0 || codePoint > 0x10ffff || (codePoint >= 0xd800 && codePoint <= 0xdfff)) {
179 return "\uFFFD";
180 }
181 return String.fromCodePoint(HTML_C1_REPLACEMENTS[codePoint] ?? codePoint);
182 },
183 );
185​
186function* extractIconHrefs(source: string, html: boolean): Generator<string> {
187 for (const [tag] of source.matchAll(HTML_LINK_RE)) {
188 if (tag.startsWith("<!--")) continue;
189 const attributes = new Map<string, { value: string; quoted: boolean }>();
190 for (const [, name, doubleQuoted, singleQuoted, unquoted] of tag
191 .slice("<link".length)
192 .matchAll(HTML_ATTRIBUTE_RE)) {
193 const key = name!.toLowerCase();
194 if (attributes.has(key)) continue;
195 const quotedValue = doubleQuoted ?? singleQuoted;
196 attributes.set(key, {
197 value: quotedValue ?? unquoted ?? "",
198 quoted: quotedValue !== undefined,
199 });
200 }
201 const rawRel = attributes.get("rel")?.value;
202 if (rawRel === undefined) continue;
203 const rel = (html ? decodeHtmlAttribute(rawRel, true) : rawRel)
204 .toLowerCase()
205 .split(/[\t\n\f\r ]+/);
206 if (!rel.includes("icon")) continue;
207 const href = attributes.get("href");
208 // An unquoted `{...}` is a JSX expression, not a path.
209 if (!href || (!href.quoted && href.value.startsWith("{"))) continue;
210 const path = decodeHtmlAttribute(href.value, html).split(/[?#]/, 1)[0];
211 if (path) yield path;
212 }
213 for (const run of source.split("}")) {
214 if (!ICON_REL_RE.test(run)) continue;
215 const hrefMatch = run.match(ICON_HREF_RE);
216 const href = hrefMatch?.[1] ?? hrefMatch?.[2];
217 if (href) yield href;
218 }
220​
221export const optionOnNotFound = <A, R>(
222 effect: Effect.Effect<A, PlatformError.PlatformError, R>,
223): Effect.Effect<Option.Option<A>, PlatformError.PlatformError, R> =>
224 effect.pipe(
225 Effect.asSome,
226 Effect.catchTags({
227 PlatformError: (error) =>
228 error.reason._tag === "NotFound" ? Effect.succeed(Option.none<A>()) : Effect.fail(error),
229 }),
230 );
231​
232// A path through a file (ENOTDIR) or a symlink loop names no file either.
233const optionOnMissing = <A, R>(
234 effect: Effect.Effect<A, PlatformError.PlatformError, R>,
235): Effect.Effect<Option.Option<A>, PlatformError.PlatformError, R> =>
236 optionOnNotFound(effect).pipe(
237 Effect.catchIf(
238 (error) => error.reason._tag === "BadResource",
239 () => Effect.succeedNone,
240 ),
241 );
242​
243export const make = Effect.gen(function* () {
244 const fileSystem = yield* FileSystem.FileSystem;
245 const path = yield* Path.Path;
246 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
247 const projectFileLoader = yield* T3ProjectFileLoader.T3ProjectFileLoader;
248​
249 const resolveIconHref = (href: string, sourceFile: string): ReadonlyArray<string> => {
250 // `data:`, `https:` and `//host` icons name no project file, and a long data URL fails `stat`.
251 if (/^(?:[a-z][a-z\d+.-]*:|\/\/)/i.test(href.trim())) return [];
252 // Browsers strip surrounding whitespace from URL attributes; file paths keep theirs.
253 const clean = safeDecodeURIComponent(href.trim().replace(/^\//, ""));
254 // A decoded NUL fails `stat` instead of missing.
255 if (clean.includes("\0")) return [];
256 const candidates = [path.join("public", clean), clean];
257 // A relative href in HTML resolves against that file's directory (e.g. Vite `root: "src"`).
258 const htmlDir = sourceFile.endsWith(".html") ? path.dirname(sourceFile) : ".";
259 if (htmlDir !== "." && !href.trim().startsWith("/")) {
260 candidates.push(path.join(htmlDir, clean));
261 }
262 return candidates;
263 };
264​
265 const findExistingFile = Effect.fn("ProjectFaviconResolver.findExistingFile")(function* (
266 projectCwd: string,
267 relativeCandidates: ReadonlyArray<string>,
268 candidateScope: "workspace" | "filesystem",
269 ): Effect.fn.Return<string | null, ProjectFaviconResolutionError> {
270 for (const relativePath of relativeCandidates) {
271 const candidate = yield* (
272 candidateScope === "filesystem" && path.isAbsolute(relativePath)
273 ? Effect.succeed({ absolutePath: relativePath, relativePath })
274 : workspacePaths.resolveRelativePathWithinRoot({
275 workspaceRoot: projectCwd,
276 relativePath,
277 })
278 ).pipe(
279 Effect.asSome,
280 Effect.catchTags({
281 WorkspacePathOutsideRootError: () =>
282 Effect.succeed(
283 Option.none<{ readonly absolutePath: string; readonly relativePath: string }>(),
284 ),
285 }),
286 );
287 if (Option.isNone(candidate)) {
288 continue;
289 }
290 const stats = yield* optionOnMissing(fileSystem.stat(candidate.value.absolutePath)).pipe(
291 Effect.mapError(
292 (cause) =>
293 new ProjectFaviconResolutionError({
294 operation: "stat-candidate",
295 workspaceRoot: projectCwd,
296 relativePath,
297 absolutePath: candidate.value.absolutePath,
298 cause,
299 }),
300 ),
301 );
302 if (Option.isSome(stats) && stats.value.type === "File") {
303 return candidate.value.absolutePath;
304 }
305 }
306 return null;
307 });
308​
309 const findIconFromSource = Effect.fn("ProjectFaviconResolver.findIconFromSource")(function* (
310 projectCwd: string,
311 sourceFile: string,
312 ): Effect.fn.Return<string | null, ProjectFaviconResolutionError> {
313 const sourcePath = yield* workspacePaths
314 .resolveRelativePathWithinRoot({
315 workspaceRoot: projectCwd,
316 relativePath: sourceFile,
317 })
318 .pipe(
319 Effect.mapError(
320 (cause) =>
321 new ProjectFaviconResolutionError({
322 operation: "resolve-path",
323 workspaceRoot: projectCwd,
324 relativePath: sourceFile,
325 cause,
326 }),
327 ),
328 );
329 const stats = yield* optionOnMissing(fileSystem.stat(sourcePath.absolutePath)).pipe(
330 Effect.mapError(
331 (cause) =>
332 new ProjectFaviconResolutionError({
333 operation: "stat-candidate",
334 workspaceRoot: projectCwd,
335 relativePath: sourceFile,
336 absolutePath: sourcePath.absolutePath,
337 cause,
338 }),
339 ),
340 );
341 if (Option.isNone(stats) || stats.value.type !== "File") {
342 return null;
343 }
344 const source = yield* optionOnMissing(
345 fileSystem.open(sourcePath.absolutePath, { flag: "r" }).pipe(
346 Effect.flatMap((file) => file.readAlloc(ICON_SOURCE_SCAN_BYTES)),
347 Effect.scoped,
348 ),
349 ).pipe(
350 Effect.mapError(
351 (cause) =>
352 new ProjectFaviconResolutionError({
353 operation: "read-source",
354 workspaceRoot: projectCwd,
355 relativePath: sourceFile,
356 absolutePath: sourcePath.absolutePath,
357 cause,
358 }),
359 ),
360 );
361 if (Option.isNone(source) || Option.isNone(source.value)) {
362 return null;
363 }
364 const hrefs = Array.from(
365 extractIconHrefs(new TextDecoder().decode(source.value.value), sourceFile.endsWith(".html")),
366 );
367 const candidates = hrefs.flatMap((href) => resolveIconHref(href, sourceFile));
368 return yield* findExistingFile(projectCwd, candidates, "workspace");
369 });
370​
371 // Probe concurrently but join in list order so lower-ranked probes cannot delay a hit.
372 // A failure surfaces only if no earlier probe found a file; scope exit interrupts remaining probes.
373 const firstInOrder = Effect.fn("ProjectFaviconResolver.firstInOrder")(function* <A>(
374 items: ReadonlyArray<A>,
375 probe: (item: A) => Effect.Effect<string | null, ProjectFaviconResolutionError>,
376 ) {
377 const fibers = yield* Effect.forEach(items, (item) => Effect.forkScoped(probe(item)));
378 for (const fiber of fibers) {
379 const found = yield* Fiber.join(fiber);
380 if (found) {
381 return found;
382 }
383 }
384 return null;
385 }, Effect.scoped);
386​
387 const resolvePathUncached = Effect.fn("ProjectFaviconResolver.resolvePathUncached")(function* (
388 cwd: string,
389 faviconPath?: string,
390 ): Effect.fn.Return<string | null, ProjectFaviconResolutionError> {
391 const projectCwd = yield* workspacePaths.normalizeWorkspaceRoot(cwd).pipe(
392 Effect.mapError(
393 (cause) =>
394 new ProjectFaviconResolutionError({
395 operation: "normalize-workspace",
396 workspaceRoot: cwd,
397 cause,
398 }),
399 ),
400 );
401 if (faviconPath !== undefined) {
402 const existing = yield* findExistingFile(projectCwd, [faviconPath], "filesystem");
403 if (existing) {
404 return existing;
405 }
406 }
407​
408 const projectFile = yield* projectFileLoader.load(projectCwd);
409 if (Option.isSome(projectFile) && projectFile.value.iconPath !== undefined) {
410 const existing = yield* findExistingFile(
411 projectCwd,
412 [projectFile.value.iconPath],
413 "workspace",
414 );
415 if (existing) {
416 return existing;
417 }
418 }
419​
420 const wellKnown = yield* firstInOrder(FAVICON_CANDIDATES, (candidate) =>
421 findExistingFile(projectCwd, [candidate], "workspace"),
422 );
423 if (wellKnown) {
424 return wellKnown;
425 }
426​
427 const sourceDeclared = yield* firstInOrder(ICON_SOURCE_FILES, (sourceFile) =>
428 findIconFromSource(projectCwd, sourceFile),
429 );
430 if (sourceDeclared) {
431 return sourceDeclared;
432 }
433​
434 return yield* findExistingFile(projectCwd, FALLBACK_FAVICON_CANDIDATES, "workspace");
435 });
436​
437 const faviconCache = yield* Cache.makeWith<string, string | null, ProjectFaviconResolutionError>(
438 (key) => {
439 const { cwd, faviconPath } = parseFaviconCacheKey(key);
440 return resolvePathUncached(cwd, faviconPath);
441 },
442 {
443 capacity: FAVICON_CACHE_CAPACITY,
444 timeToLive: Exit.match({
445 onSuccess: (value: string | null) =>
446 value === null ? FAVICON_NEGATIVE_CACHE_TTL : FAVICON_POSITIVE_CACHE_TTL,
447 onFailure: (cause) =>
448 Option.exists(Cause.findErrorOption(cause), isMissingWorkspaceRoot)
449 ? FAVICON_NEGATIVE_CACHE_TTL
450 : Duration.zero,
451 }),
452 },
453 );
454​
455 const resolvePath: ProjectFaviconResolver["Service"]["resolvePath"] = Effect.fn(
456 "ProjectFaviconResolver.resolvePath",
457 )(function* (cwd, faviconPath) {
458 const key = faviconCacheKey(cwd, faviconPath);
459 const cached = yield* Cache.get(faviconCache, key);
460 if (cached === null) {
461 return null;
462 }
463​
464 const stats = yield* optionOnMissing(fileSystem.stat(cached)).pipe(
465 Effect.mapError(
466 (cause) =>
467 new ProjectFaviconResolutionError({
468 operation: "stat-candidate",
469 workspaceRoot: cwd,
470 absolutePath: cached,
471 cause,
472 }),
473 ),
474 );
475 if (Option.isSome(stats) && stats.value.type === "File") {
476 return cached;
477 }
478​
479 yield* Cache.invalidate(faviconCache, key);
480 return yield* Cache.get(faviconCache, key);
481 });
482​
483 const invalidate: ProjectFaviconResolver["Service"]["invalidate"] = (cwd) =>
484 Cache.keys(faviconCache).pipe(
485 Effect.flatMap((keys) =>
486 Effect.forEach(
487 Array.from(keys).filter((key) => parseFaviconCacheKey(key).cwd === cwd),
488 (key) => Cache.invalidate(faviconCache, key),
489 { discard: true },
490 ),
491 ),
492 );
493​
494 return ProjectFaviconResolver.of({ resolvePath, invalidate });
495});
496​
497export const layer = Layer.effect(ProjectFaviconResolver, make);