Open History to see the last commit
1import {
2 scopedProjectKey,
3 scopedThreadKey,
4 scopeProjectRef,
5} from "@t3tools/client-runtime/environment";
6import type { DesktopPreviewFavicon, ScopedProjectRef, ScopedThreadRef } from "@t3tools/contracts";
7import * as Option from "effect/Option";
8import { useMemo } from "react";
9import { create } from "zustand";
10import { createJSONStorage, persist } from "zustand/middleware";
11
12import { normalizeHostname } from "~/browser/browserTargetResolver";
13import { useThreadShell } from "~/state/entities";
14import { usePreparedConnection } from "~/state/session";
15
16import {
17 BROWSER_FAVICON_MAX_ALIASES_PER_ENTRY,
18 type BrowserFaviconEntry,
19 canCanonicalizeFaviconWithoutEnvironment,
20 evictExcessFavicons,
21 faviconKey,
22 faviconStorageLocation,
23 isStorableFaviconDataUrl,
24 isValidFaviconCapturedAt,
25 migratePersistedBrowserFaviconState,
26} from "./browserFaviconLogic";
27import { createMemoryStorage, type StateStorage } from "./lib/storage";
28
29const BROWSER_FAVICON_STORAGE_KEY = "t3code:browser-favicons:v1";
30const MAX_PENDING_ORIGINS_PER_THREAD = 10;
31const MAX_PENDING_THREADS = 20;
32const MAX_REGISTERED_THREADS = 100;
33
34type PendingFavicon = DesktopPreviewFavicon;
35type PendingFaviconsByOrigin = Record<string, PendingFavicon>;
36
37export interface BrowserFaviconStoreState {
38 byKey: Record<string, BrowserFaviconEntry>;
39 pendingByThreadKey: Record<string, PendingFaviconsByOrigin>;
40 projectRefByThreadKey: Record<string, ScopedProjectRef>;
41 recordFavicon: (
42 key: string,
43 dataUrl: string,
44 capturedAt: number,
45 aliases?: ReadonlyArray<string>,
46 ) => void;
47}
48
49function pendingOriginKey(pageUrl: string): string | null {
50 return faviconKey("pending", pageUrl, null)?.slice("pending ".length) ?? null;
51}
52
53function addPendingFavicon(
54 pendingByThreadKey: Record<string, PendingFaviconsByOrigin>,
55 threadKey: string,
56 favicon: PendingFavicon,
57): Record<string, PendingFaviconsByOrigin> {
58 const originKey = pendingOriginKey(favicon.pageUrl);
59 if (!originKey) return pendingByThreadKey;
60 const current = pendingByThreadKey[threadKey] ?? {};
61 const existing = current[originKey];
62 if (existing && existing.capturedAt >= favicon.capturedAt) return pendingByThreadKey;
63 const nextForThread = {
64 ...current,
65 [originKey]: favicon,
66 };
67 const boundedForThread = Object.fromEntries(
68 Object.entries(nextForThread)
69 .toSorted(([, left], [, right]) => right.capturedAt - left.capturedAt)
70 .slice(0, MAX_PENDING_ORIGINS_PER_THREAD),
71 );
72
73 const withoutThread = { ...pendingByThreadKey };
74 delete withoutThread[threadKey];
75 return Object.fromEntries(
76 [...Object.entries(withoutThread), [threadKey, boundedForThread]].slice(-MAX_PENDING_THREADS),
77 );
78}
79
80export function resolveBrowserFaviconStorage(): StateStorage {
81 const fallback = createMemoryStorage();
82 const shadowedNames = new Set<string>();
83 let primary: Storage;
84 try {
85 if (typeof window === "undefined") return fallback;
86 primary = window.localStorage;
87 } catch {
88 return fallback;
89 }
90 return {
91 getItem: (name) => {
92 if (shadowedNames.has(name)) return fallback.getItem(name);
93 try {
94 return primary.getItem(name);
95 } catch {
96 return fallback.getItem(name);
97 }
98 },
99 setItem: (name, value) => {
100 fallback.setItem(name, value);
101 try {
102 primary.setItem(name, value);
103 shadowedNames.delete(name);
104 } catch {
105 shadowedNames.add(name);
106 }
107 },
108 removeItem: (name) => {
109 fallback.removeItem(name);
110 try {
111 primary.removeItem(name);
112 shadowedNames.delete(name);
113 } catch {
114 shadowedNames.add(name);
115 }
116 },
117 };
118}
119
120export const useBrowserFaviconStore = create<BrowserFaviconStoreState>()(
121 persist(
122 (set) => ({
123 byKey: {},
124 pendingByThreadKey: {},
125 projectRefByThreadKey: {},
126 recordFavicon: (key, dataUrl, capturedAt, aliases = []) =>
127 set((state) => {
128 if (!isStorableFaviconDataUrl(dataUrl)) return state;
129 if (!isValidFaviconCapturedAt(capturedAt)) return state;
130 const existing = state.byKey[key];
131 const aliasCandidates =
132 capturedAt > (existing?.capturedAt ?? -1)
133 ? [...aliases, ...(existing?.aliases ?? [])]
134 : [...(existing?.aliases ?? []), ...aliases];
135 const nextAliases = [...new Set(aliasCandidates)].slice(
136 0,
137 BROWSER_FAVICON_MAX_ALIASES_PER_ENTRY,
138 );
139 const aliasesUnchanged =
140 nextAliases.length === (existing?.aliases?.length ?? 0) &&
141 nextAliases.every((alias, index) => alias === existing?.aliases?.[index]);
142 if (existing && capturedAt <= existing.capturedAt && aliasesUnchanged) return state;
143 return {
144 byKey: evictExcessFavicons({
145 ...state.byKey,
146 [key]: {
147 dataUrl: capturedAt > (existing?.capturedAt ?? -1) ? dataUrl : existing!.dataUrl,
148 capturedAt: Math.max(capturedAt, existing?.capturedAt ?? -1),
149 ...(nextAliases.length > 0 ? { aliases: nextAliases } : {}),
150 },
151 }),
152 };
153 }),
154 }),
155 {
156 name: BROWSER_FAVICON_STORAGE_KEY,
157 version: 1,
158 storage: createJSONStorage(resolveBrowserFaviconStorage),
159 partialize: (state) => ({ byKey: state.byKey }),
160 migrate: migratePersistedBrowserFaviconState,
161 merge: mergeBrowserFaviconState,
162 },
163 ),
164);
165
166export function mergeBrowserFaviconState(
167 persistedState: unknown,
168 currentState: BrowserFaviconStoreState,
169): BrowserFaviconStoreState {
170 return {
171 ...currentState,
172 ...migratePersistedBrowserFaviconState(persistedState),
173 };
174}
175
176export function registerFaviconProjectForThread(
177 threadRef: ScopedThreadRef,
178 projectRef: ScopedProjectRef,
179): void {
180 const threadKey = scopedThreadKey(threadRef);
181 const state = useBrowserFaviconStore.getState();
182 const current = state.projectRefByThreadKey[threadKey];
183 if (
184 current?.environmentId === projectRef.environmentId &&
185 current.projectId === projectRef.projectId
186 ) {
187 return;
188 }
189 useBrowserFaviconStore.setState({
190 projectRefByThreadKey: Object.fromEntries(
191 [
192 ...Object.entries(state.projectRefByThreadKey).filter(([key]) => key !== threadKey),
193 [threadKey, projectRef],
194 ].slice(-MAX_REGISTERED_THREADS),
195 ),
196 });
197}
198
199export function useFaviconProjectRefForThread(threadRef: ScopedThreadRef): ScopedProjectRef | null {
200 const shell = useThreadShell(threadRef);
201 const shellProjectId = shell?.projectId ?? null;
202 const shellProjectRef = useMemo(
203 () => (shellProjectId ? scopeProjectRef(threadRef.environmentId, shellProjectId) : null),
204 [shellProjectId, threadRef.environmentId],
205 );
206 const registered = useBrowserFaviconStore(
207 (state) => state.projectRefByThreadKey[scopedThreadKey(threadRef)] ?? null,
208 );
209 return shellProjectRef ?? registered;
210}
211
212export function recordFaviconForProject(
213 projectRef: ScopedProjectRef,
214 favicon: DesktopPreviewFavicon,
215 environmentHostname: string | null,
216): boolean {
217 if (!isStorableFaviconDataUrl(favicon.dataUrl) || !isValidFaviconCapturedAt(favicon.capturedAt)) {
218 return false;
219 }
220 const location = faviconStorageLocation(
221 scopedProjectKey(projectRef),
222 favicon.pageUrl,
223 environmentHostname,
224 );
225 if (!location) return false;
226 const state = useBrowserFaviconStore.getState();
227 const existing = state.byKey[location.key];
228 if (
229 existing &&
230 existing.capturedAt >= favicon.capturedAt &&
231 location.aliases.every((alias) => existing.aliases?.includes(alias))
232 )
233 return true;
234 state.recordFavicon(location.key, favicon.dataUrl, favicon.capturedAt, location.aliases);
235 return true;
236}
237
238export function recordFaviconForThread(
239 threadRef: ScopedThreadRef,
240 favicon: DesktopPreviewFavicon,
241 projectRef: ScopedProjectRef | null,
242 environmentHostname: string | undefined,
243): boolean {
244 if (
245 !isStorableFaviconDataUrl(favicon.dataUrl) ||
246 !isValidFaviconCapturedAt(favicon.capturedAt) ||
247 !pendingOriginKey(favicon.pageUrl)
248 )
249 return false;
250 const hostname =
251 environmentHostname !== undefined
252 ? environmentHostname
253 : canCanonicalizeFaviconWithoutEnvironment(favicon.pageUrl)
254 ? null
255 : undefined;
256 if (
257 projectRef &&
258 hostname !== undefined &&
259 recordFaviconForProject(projectRef, favicon, hostname)
260 ) {
261 return true;
262 }
263 const threadKey = scopedThreadKey(threadRef);
264 const state = useBrowserFaviconStore.getState();
265 const pendingByThreadKey = addPendingFavicon(state.pendingByThreadKey, threadKey, favicon);
266 if (pendingByThreadKey !== state.pendingByThreadKey) {
267 useBrowserFaviconStore.setState({ pendingByThreadKey });
268 }
269 return false;
270}
271
272export function flushPendingFaviconsForThread(
273 threadRef: ScopedThreadRef,
274 projectRef: ScopedProjectRef,
275 environmentHostname: string | undefined,
276): boolean {
277 const threadKey = scopedThreadKey(threadRef);
278 const pending = useBrowserFaviconStore.getState().pendingByThreadKey[threadKey];
279 if (!pending) return true;
280 const remaining = Object.fromEntries(
281 Object.entries(pending).filter(([, favicon]) => {
282 const hostname =
283 environmentHostname !== undefined
284 ? environmentHostname
285 : canCanonicalizeFaviconWithoutEnvironment(favicon.pageUrl)
286 ? null
287 : undefined;
288 return hostname === undefined || !recordFaviconForProject(projectRef, favicon, hostname);
289 }),
290 );
291 useBrowserFaviconStore.setState((state) => {
292 const pendingByThreadKey = { ...state.pendingByThreadKey };
293 if (Object.keys(remaining).length === 0) delete pendingByThreadKey[threadKey];
294 else pendingByThreadKey[threadKey] = remaining;
295 return { pendingByThreadKey };
296 });
297 return Object.keys(remaining).length === 0;
298}
299
300export function useFaviconForThreadUrl(threadRef: ScopedThreadRef, url: string): string | null {
301 const projectRef = useFaviconProjectRefForThread(threadRef);
302 const preparedConnection = usePreparedConnection(threadRef.environmentId);
303 const environmentHostname = Option.isSome(preparedConnection)
304 ? new URL(preparedConnection.value.httpBaseUrl).hostname
305 : null;
306 return useBrowserFaviconStore((state) =>
307 lookupFavicon(state.byKey, projectRef, url, environmentHostname),
308 );
309}
310
311export function lookupFavicon(
312 byKey: Record<string, BrowserFaviconEntry>,
313 projectRef: ScopedProjectRef | null,
314 url: string,
315 environmentHostname: string | null,
316): string | null {
317 const key = projectRef
318 ? faviconKey(scopedProjectKey(projectRef), url, environmentHostname)
319 : null;
320 if (!key) return null;
321 const direct = byKey[key];
322 if (direct) return direct.dataUrl;
323 try {
324 const requestedHost = normalizeHostname(new URL(url).hostname);
325 const localKey = faviconKey(scopedProjectKey(projectRef!), url, requestedHost);
326 const localEntry = localKey ? byKey[localKey] : null;
327 return localEntry?.aliases?.includes(requestedHost) ? localEntry.dataUrl : null;
328 } catch {
329 return null;
330 }
331}
332
333export function resetBrowserFaviconsForTests(): void {
334 useBrowserFaviconStore.setState({
335 byKey: {},
336 pendingByThreadKey: {},
337 projectRefByThreadKey: {},
338 });
339 useBrowserFaviconStore.persist.clearStorage();
340}