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

ProjectFaviconResolver.ts

347 lines11.1 KB

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