File size: 7,125 Bytes
db2b64c
 
 
06e320b
 
 
 
 
 
 
 
 
 
 
7c96e38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47fce1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db2b64c
7c96e38
db2b64c
47fce1d
db2b64c
 
 
 
47fce1d
db2b64c
 
 
 
 
 
 
47fce1d
db2b64c
 
 
 
 
 
 
06e320b
db2b64c
 
 
06e320b
db2b64c
 
 
 
 
 
47fce1d
 
 
db2b64c
 
 
 
 
 
06e320b
db2b64c
 
 
 
 
 
 
 
 
7c96e38
db2b64c
 
 
7c96e38
 
06e320b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36b3bb0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
06e320b
 
36b3bb0
 
 
 
 
 
 
06e320b
 
 
 
 
 
 
 
 
 
7c96e38
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
import webConfig from "@/constants/common-env";
import { getStoredAuthKey } from "@/store/auth";

type ImageBlobCacheEntry = {
  promise: Promise<Blob>;
  size: number;
  lastUsedAt: number;
};

const imageBlobCache = new Map<string, ImageBlobCacheEntry>();
const MAX_IMAGE_BLOB_CACHE_ITEMS = 8;
const MAX_IMAGE_BLOB_CACHE_BYTES = 64 * 1024 * 1024;
let imageBlobCacheBytes = 0;

function isBrowserHttps() {
  return typeof window !== "undefined" && window.location.protocol === "https:";
}

export function normalizeImageUrl(value: string) {
  const trimmed = String(value || "").trim();
  if (!trimmed) {
    return "";
  }

  try {
    const url = new URL(trimmed, typeof window !== "undefined" ? window.location.href : undefined);
    if (url.protocol === "http:" && (url.hostname.endsWith(".hf.space") || isBrowserHttps())) {
      url.protocol = "https:";
    }
    return url.toString();
  } catch {
    return trimmed;
  }
}

function isHuggingFaceHost(hostname: string) {
  const host = hostname.toLowerCase();
  return host === "huggingface.co" || host.endsWith(".hf.space") || host.endsWith(".hf.co");
}

function unproxyHuggingFaceUrl(value: string) {
  try {
    const url = new URL(value, typeof window !== "undefined" ? window.location.href : undefined);
    const marker = "/redirect_to_";
    const markerIndex = url.pathname.indexOf(marker);
    if (markerIndex < 0) {
      return "";
    }
    const target = url.pathname.slice(markerIndex + marker.length);
    const slashIndex = target.indexOf("/");
    if (slashIndex <= 0) {
      return "";
    }
    const hostname = target.slice(0, slashIndex);
    if (!isHuggingFaceHost(hostname)) {
      return "";
    }
    return `https://${hostname}${target.slice(slashIndex)}${url.search}`;
  } catch {
    return "";
  }
}

function imageFetchCandidates(src: string) {
  const normalizedSrc = normalizeImageUrl(src);
  const candidates = [normalizedSrc];
  const fallbackSrc = unproxyHuggingFaceUrl(normalizedSrc);
  if (fallbackSrc && fallbackSrc !== normalizedSrc) {
    candidates.push(fallbackSrc);
  }

  try {
    const url = new URL(normalizedSrc, typeof window !== "undefined" ? window.location.href : undefined);
    if (url.hostname === "localhost") {
      url.hostname = "127.0.0.1";
      candidates.push(url.toString());
    } else if (url.hostname === "127.0.0.1") {
      url.hostname = "localhost";
      candidates.push(url.toString());
    }
  } catch {
    // Keep the original candidate list for non-URL values.
  }

  return Array.from(new Set(candidates.filter(Boolean)));
}

async function fetchImageBlobUncached(src: string) {
  let lastError: unknown = null;
  for (const candidate of imageFetchCandidates(src)) {
    try {
      const response = await fetch(candidate, { cache: "force-cache" });
      if (response.ok) {
        return response.blob();
      }
      lastError = new Error(`HTTP ${response.status}`);
    } catch (error) {
      lastError = error;
    }
  }

  try {
    const parsed = new URL(normalizeImageUrl(src), typeof window !== "undefined" ? window.location.href : undefined);
    if (parsed.protocol === "http:" || parsed.protocol === "https:") {
      const apiBase = webConfig.apiUrl.replace(/\/$/, "");
      const authKey = await getStoredAuthKey();
      const response = await fetch(`${apiBase}/api/images/proxy?url=${encodeURIComponent(parsed.toString())}`, {
        cache: "force-cache",
        headers: authKey ? { Authorization: `Bearer ${authKey}` } : undefined,
      });
      if (response.ok) {
        return response.blob();
      }
      lastError = new Error(`HTTP ${response.status}`);
    }
  } catch (error) {
    lastError = error;
  }

  const detail = lastError instanceof Error && lastError.message ? `:${lastError.message}` : "";
  throw new Error(`读取图片失败${detail}`);
}

function evictImageBlobCache(protectedKey = "") {
  while (
    imageBlobCache.size > MAX_IMAGE_BLOB_CACHE_ITEMS ||
    imageBlobCacheBytes > MAX_IMAGE_BLOB_CACHE_BYTES
  ) {
    const candidate = [...imageBlobCache.entries()]
      .filter(([key]) => key !== protectedKey)
      .sort(([, left], [, right]) => left.lastUsedAt - right.lastUsedAt)[0];
    if (!candidate) return;
    imageBlobCache.delete(candidate[0]);
    imageBlobCacheBytes = Math.max(0, imageBlobCacheBytes - candidate[1].size);
  }
}

export async function fetchImageBlob(src: string) {
  const key = normalizeImageUrl(src);
  const cached = imageBlobCache.get(key);
  if (cached) {
    cached.lastUsedAt = Date.now();
    return cached.promise;
  }

  const entry: ImageBlobCacheEntry = {
    promise: Promise.resolve(new Blob()),
    size: 0,
    lastUsedAt: Date.now(),
  };
  entry.promise = fetchImageBlobUncached(key)
    .then((blob) => {
      if (imageBlobCache.get(key) === entry) {
        entry.size = blob.size;
        entry.lastUsedAt = Date.now();
        imageBlobCacheBytes += blob.size;
        evictImageBlobCache(key);
      }
      return blob;
    })
    .catch((error) => {
      if (imageBlobCache.get(key) === entry) {
        imageBlobCache.delete(key);
      }
      throw error;
    });
  imageBlobCache.set(key, entry);
  evictImageBlobCache(key);
  return entry.promise;
}

/**
 * 预取图片为 Blob,供「下载 / 加入参考」等需要字节流的操作用。
 *
 * ⚠️⚠️ **绝对不要在图片列表的渲染 / onLoad 路径里批量调用它**(2026-10-16 事故)。
 * 结果图是 ChatGPT 官网签名直链(跨域),`<img>` 本来就要完整下载一遍;这里再 fetch
 * 一次,跨域被 CORS 拦下后会回落到后端 `/api/images/proxy`,让只有 2 核的容器替**每个
 * 访客**把整张图(1~3MB)重下一遍;同时这些无用请求会占满浏览器对同域名仅有的 6 条
 * 并发连接,`<img>` 反而要排队——症状就是「画图页图片加载慢,右键新标签页打开却很快」。
 * 下载/加入参考都是用户主动点击,届时 fetchImageBlob 自己会取并缓存,无需预热。
 *
 * 保留在飞上限作为兜底:万一将来又被挂到批量路径上,最多只并行 2 个,不会雪崩。
 */
const MAX_INFLIGHT_WARMS = 2;
let inflightWarms = 0;

export function warmImageBlob(src: string) {
  if (!String(src || "").trim()) return;
  if (inflightWarms >= MAX_INFLIGHT_WARMS) return;
  inflightWarms += 1;
  void fetchImageBlob(src)
    .catch(() => undefined)
    .finally(() => {
      inflightWarms = Math.max(0, inflightWarms - 1);
    });
}

export function releaseImageBlob(src: string) {
  const key = normalizeImageUrl(src);
  const cached = imageBlobCache.get(key);
  if (!cached) return;
  imageBlobCache.delete(key);
  imageBlobCacheBytes = Math.max(0, imageBlobCacheBytes - cached.size);
}

export async function downloadImageSrc(src: string, filename: string) {
  const blob = await fetchImageBlob(src);
  const objectUrl = URL.createObjectURL(blob);
  const link = document.createElement("a");
  link.href = objectUrl;
  link.download = filename;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  URL.revokeObjectURL(objectUrl);
}