Open History to see the last commit
1import { EnvironmentId } from "@t3tools/contracts";
2import { mediaMimeType } from "@t3tools/shared/filePreview";
3import {
4 getProjectFaviconCacheKey,
5 getProjectFaviconResourceKey,
6 isProjectFaviconFallbackUrl,
7} from "@t3tools/shared/projectFavicon";
8import * as Base64 from "effect/encoding/Base64";
9import * as Option from "effect/Option";
10import * as Schema from "effect/Schema";
11
12export const PROJECT_FAVICON_THUMBNAIL_SIZE = 96;
13export const PROJECT_FAVICON_MAX_DATA_URL_LENGTH = 32 * 1024;
14export const PROJECT_FAVICON_MAX_SOURCE_BYTES = 4 * 1024 * 1024;
15export const PROJECT_FAVICON_CACHE_MAX_BYTES = 1024 * 1024;
16export const PROJECT_FAVICON_CACHE_MAX_ENTRIES = 128;
17
18export interface ProjectFaviconTarget {
19 readonly environmentId: EnvironmentId;
20 readonly cwd: string;
21 readonly faviconPath?: string | null | undefined;
22}
23
24const ImageDataUrl = Schema.String.check(
25 Schema.isMaxLength(PROJECT_FAVICON_MAX_DATA_URL_LENGTH),
26 Schema.isPattern(
27 /^data:image\/(?:png|jpeg|gif|webp|avif|svg\+xml|x-icon|vnd\.microsoft\.icon);base64,[A-Za-z0-9+/]+={0,2}$/,
28 ),
29);
30const Entry = Schema.Struct({
31 environmentId: EnvironmentId,
32 cwd: Schema.String,
33 faviconPath: Schema.NullOr(Schema.String),
34 revision: Schema.String,
35 dataUrl: ImageDataUrl,
36});
37export type ProjectFaviconEntry = typeof Entry.Type;
38const decodeEntry = Schema.decodeUnknownOption(Entry);
39const isImageDataUrl = Schema.is(ImageDataUrl);
40
41function keyFor(target: ProjectFaviconTarget) {
42 return getProjectFaviconResourceKey(target.environmentId, target.cwd, target.faviconPath);
43}
44
45export interface ProjectFaviconStorage {
46 readonly list: () => Promise<ReadonlyArray<unknown>>;
47 readonly put: (key: string, entry: ProjectFaviconEntry) => Promise<void>;
48 readonly remove: (key: string, entry: ProjectFaviconEntry) => Promise<void>;
49}
50
51async function readBounded(response: Response, maxBytes: number) {
52 const declared = Number(response.headers.get("content-length"));
53 if (declared > maxBytes) throw new Error("Project icon is too large to decode.");
54 if (!response.body) {
55 const bytes = new Uint8Array<ArrayBuffer>(await response.arrayBuffer());
56 if (bytes.byteLength > maxBytes) throw new Error("Project icon is too large to decode.");
57 return bytes;
58 }
59 const reader = response.body.getReader();
60 const chunks: Array<Uint8Array> = [];
61 let total = 0;
62 try {
63 for (;;) {
64 const { done, value } = await reader.read();
65 if (done) break;
66 total += value.byteLength;
67 if (total > maxBytes) throw new Error("Project icon is too large to decode.");
68 chunks.push(value);
69 }
70 } finally {
71 reader.cancel().catch(() => {});
72 }
73 const bytes = new Uint8Array<ArrayBuffer>(new ArrayBuffer(total));
74 let offset = 0;
75 for (const chunk of chunks) {
76 bytes.set(chunk, offset);
77 offset += chunk.byteLength;
78 }
79 return bytes;
80}
81
82/**
83 * Larger bitmaps go through the platform downscaler; larger SVGs stay remote because rasterizing
84 * them without intrinsic dimensions is unreliable.
85 */
86export function createProjectFaviconImageLoader(input: {
87 readonly fetch?: typeof fetch;
88 readonly downscale: (
89 image: {
90 readonly url: string;
91 readonly mimeType: string;
92 readonly bytes: Uint8Array<ArrayBuffer>;
93 },
94 signal: AbortSignal,
95 ) => Promise<string>;
96}) {
97 const fetchImpl = input.fetch ?? globalThis.fetch;
98 return async (url: string, signal: AbortSignal): Promise<string> => {
99 const response = await fetchImpl(url, { signal });
100 if (!response.ok) throw new Error(`Project icon request failed with ${response.status}.`);
101 const contentType = response.headers
102 .get("content-type")
103 ?.split(";", 1)[0]
104 ?.trim()
105 .toLowerCase();
106 const mimeType = contentType?.startsWith("image/") ? contentType : mediaMimeType(url);
107 if (!mimeType) throw new Error("Project icon has no image type.");
108 const bytes = await readBounded(response, PROJECT_FAVICON_MAX_SOURCE_BYTES);
109 signal.throwIfAborted();
110 const dataUrl = `data:${mimeType};base64,${Base64.encode(bytes)}`;
111 if (isImageDataUrl(dataUrl)) return dataUrl;
112 if (mimeType === "image/svg+xml") throw new Error("Project icon exceeds the cache limit.");
113 return input.downscale({ url, mimeType, bytes }, signal);
114 };
115}
116
117export function createProjectFaviconCache(input: {
118 readonly storage: ProjectFaviconStorage;
119 readonly load: (url: string, signal: AbortSignal) => Promise<string>;
120}) {
121 const entries = new Map<string, ProjectFaviconEntry>();
122 const environmentRevisions = new Map<EnvironmentId, number>();
123 let generation = 0;
124 let hydration: Promise<void> | undefined;
125 let clearing: Promise<void> | undefined;
126 const pending = new Set<Promise<void>>();
127
128 const persist = (operation: () => Promise<void>) => {
129 const task: Promise<void> = operation()
130 .catch(() => {})
131 .finally(() => pending.delete(task));
132 pending.add(task);
133 };
134
135 const remove = (key: string) => {
136 const entry = entries.get(key);
137 if (!entry) return;
138 entries.delete(key);
139 persist(() => input.storage.remove(key, entry));
140 };
141
142 const trim = () => {
143 let bytes = 0;
144 for (const entry of entries.values()) bytes += entry.dataUrl.length;
145 while (
146 entries.size > PROJECT_FAVICON_CACHE_MAX_ENTRIES ||
147 bytes > PROJECT_FAVICON_CACHE_MAX_BYTES
148 ) {
149 const oldest = entries.entries().next().value;
150 if (!oldest) break;
151 bytes -= oldest[1].dataUrl.length;
152 remove(oldest[0]);
153 }
154 };
155
156 const hydrate = () =>
157 (hydration ??= (async () => {
158 try {
159 for (const record of await input.storage.list()) {
160 const entry = decodeEntry(record);
161 if (Option.isSome(entry)) entries.set(keyFor(entry.value), entry.value);
162 }
163 trim();
164 } catch {}
165 })());
166
167 const peek = (target: ProjectFaviconTarget) => entries.get(keyFor(target))?.dataUrl ?? null;
168
169 const resolve = async (
170 target: ProjectFaviconTarget,
171 url: string | null,
172 signal: AbortSignal,
173 ): Promise<string | null> => {
174 await clearing;
175 const startGeneration = generation;
176 const startRevision = environmentRevisions.get(target.environmentId) ?? 0;
177 await hydrate();
178 if (signal.aborted || url === null) return peek(target);
179 const key = keyFor(target);
180 if (isProjectFaviconFallbackUrl(url)) {
181 remove(key);
182 return null;
183 }
184 const revision = getProjectFaviconCacheKey(target.environmentId, target.cwd, url);
185 const cached = entries.get(key);
186 if (cached) {
187 entries.delete(key);
188 entries.set(key, cached);
189 if (cached.revision === revision) return cached.dataUrl;
190 }
191 try {
192 const dataUrl = await input.load(url, signal);
193 if (
194 signal.aborted ||
195 startGeneration !== generation ||
196 startRevision !== (environmentRevisions.get(target.environmentId) ?? 0)
197 ) {
198 return peek(target);
199 }
200 if (isImageDataUrl(dataUrl)) {
201 const entry = {
202 environmentId: target.environmentId,
203 cwd: target.cwd,
204 faviconPath: target.faviconPath || null,
205 revision,
206 dataUrl,
207 };
208 entries.set(key, entry);
209 persist(() => input.storage.put(key, entry));
210 trim();
211 return dataUrl;
212 }
213 } catch {}
214 return peek(target) ?? url;
215 };
216
217 const flush = async () => {
218 await Promise.all(pending);
219 };
220
221 // A download that started before the clear sees the revision change and is discarded;
222 // one that starts during the clear waits for it, so it cannot repopulate storage.
223 const clear = async (environmentId?: EnvironmentId) => {
224 if (environmentId === undefined) generation += 1;
225 else
226 environmentRevisions.set(environmentId, (environmentRevisions.get(environmentId) ?? 0) + 1);
227 const previous = clearing;
228 const task = (async () => {
229 await previous;
230 await hydrate();
231 for (const [key, entry] of entries) {
232 if (environmentId === undefined || entry.environmentId === environmentId) remove(key);
233 }
234 await flush();
235 })().finally(() => {
236 if (clearing === task) clearing = undefined;
237 });
238 clearing = task;
239 await task;
240 };
241
242 return {
243 hydrate,
244 peek,
245 resolve,
246 clearEnvironment: (environmentId: EnvironmentId) => clear(environmentId),
247 clearAll: () => clear(),
248 flush,
249 };
250}
251
252export type ProjectFaviconCache = ReturnType<typeof createProjectFaviconCache>;