@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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