Spaces:
Running
Running
Upload 104 files
Browse files- 前端页面/components/用户体验_国际化.js +14 -0
- 前端页面/core/侧边栏数据引擎.js +764 -713
- 前端页面/core/全局配置.js +11 -0
- 前端页面/core/榜单分页状态.js +4 -3
- 前端页面/core/榜单数据来源.js +23 -1
- 前端页面/core/网络请求_基础设施.js +934 -900
- 前端页面/core/网络请求_缓存管理.js +55 -2
- 前端页面/market/Skill安装流程.js +4 -4
- 前端页面/market/发布内容_提交引擎.js +311 -311
- 前端页面/market/安装目录.js +72 -0
- 前端页面/market/资源安装引擎.js +16 -3
- 前端页面/market/资源操作生命周期.js +62 -52
前端页面/components/用户体验_国际化.js
CHANGED
|
@@ -89,6 +89,12 @@ const translations = {
|
|
| 89 |
'install.source': "来源:{source}",
|
| 90 |
'install.source_unavailable': "暂时无法核实安装来源",
|
| 91 |
'install.error_source_changed': "资源来源已变更,请刷新资源后重新安装。",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
'install.error_package_too_large': '下载包超过本地安全上限,已停止安装。',
|
| 93 |
'install.error_download': '下载多次中断。请检查网络后重试。',
|
| 94 |
'install.error_target_occupied': '旧版本文件仍被占用。关闭 ComfyUI 后再重试更新。',
|
|
@@ -867,6 +873,7 @@ const translations = {
|
|
| 867 |
'task.cached_refresh_failed': '暂时无法刷新,仍显示公开缓存内容;操作需联网确认。',
|
| 868 |
'feedback.cache_fallback': '⚠️ 网络连接失败,展示的是缓存数据',
|
| 869 |
'feedback.refresh_failed_cached': '网络刷新失败,仍显示上次结果',
|
|
|
|
| 870 |
// 🔧 新增:以下三条原为散落在各组件里的硬编码中文,现收口到词典以支持多语言
|
| 871 |
'feedback.offline_no_cache': '网络已断开,且无本地缓存',
|
| 872 |
// ☁️ 云端不可达冷却期内、且本地无缓存可兜底时抛出(详见 网络请求_基础设施.js)。
|
|
@@ -1900,6 +1907,12 @@ const translations = {
|
|
| 1900 |
'install.source': "Source: {source}",
|
| 1901 |
'install.source_unavailable': "Installation source cannot be verified",
|
| 1902 |
'install.error_source_changed': "The resource source changed. Refresh the resource before installing again.",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1903 |
'install.error_package_too_large': 'The download exceeded the local safety limit. Installation was stopped.',
|
| 1904 |
'install.error_download': 'The download failed repeatedly. Check the network before retrying.',
|
| 1905 |
'install.error_target_occupied': 'Files from the previous version are in use. Close ComfyUI before retrying the update.',
|
|
@@ -2670,6 +2683,7 @@ const translations = {
|
|
| 2670 |
'task.cached_refresh_failed': 'Refresh unavailable. Saved public content remains visible; actions require an online check.',
|
| 2671 |
'feedback.cache_fallback': '⚠️ Network failed, showing cached data',
|
| 2672 |
'feedback.refresh_failed_cached': 'Refresh failed. The previous results are still shown.',
|
|
|
|
| 2673 |
'feedback.offline_no_cache': 'Network disconnected, and no local cache available',
|
| 2674 |
'feedback.cloud_unreachable_no_cache': 'Cloud service is unreachable, and there is no local content to show',
|
| 2675 |
'feedback.search_local_result': '⚠️ Network unavailable, showing local search results',
|
|
|
|
| 89 |
'install.source': "来源:{source}",
|
| 90 |
'install.source_unavailable': "暂时无法核实安装来源",
|
| 91 |
'install.error_source_changed': "资源来源已变更,请刷新资源后重新安装。",
|
| 92 |
+
'install.open_directory': "打开安装目录",
|
| 93 |
+
'install.open_receiver': "打开接收目录",
|
| 94 |
+
'install.directory_requested': "已请求打开,请查看文件管理器。",
|
| 95 |
+
'install.directory_unavailable': "目标文件夹已移动或不存在,请手动检查。",
|
| 96 |
+
'install.directory_failed': "暂时无法打开文件夹,请手动打开。",
|
| 97 |
+
'install.directory_uncertain': "无法确认是否已打开,请先查看文件管理器。",
|
| 98 |
'install.error_package_too_large': '下载包超过本地安全上限,已停止安装。',
|
| 99 |
'install.error_download': '下载多次中断。请检查网络后重试。',
|
| 100 |
'install.error_target_occupied': '旧版本文件仍被占用。关闭 ComfyUI 后再重试更新。',
|
|
|
|
| 873 |
'task.cached_refresh_failed': '暂时无法刷新,仍显示公开缓存内容;操作需联网确认。',
|
| 874 |
'feedback.cache_fallback': '⚠️ 网络连接失败,展示的是缓存数据',
|
| 875 |
'feedback.refresh_failed_cached': '网络刷新失败,仍显示上次结果',
|
| 876 |
+
'feedback.list_changed_retry': '列表已更新,请重新加载。',
|
| 877 |
// 🔧 新增:以下三条原为散落在各组件里的硬编码中文,现收口到词典以支持多语言
|
| 878 |
'feedback.offline_no_cache': '网络已断开,且无本地缓存',
|
| 879 |
// ☁️ 云端不可达冷却期内、且本地无缓存可兜底时抛出(详见 网络请求_基础设施.js)。
|
|
|
|
| 1907 |
'install.source': "Source: {source}",
|
| 1908 |
'install.source_unavailable': "Installation source cannot be verified",
|
| 1909 |
'install.error_source_changed': "The resource source changed. Refresh the resource before installing again.",
|
| 1910 |
+
'install.open_directory': "Open installation folder",
|
| 1911 |
+
'install.open_receiver': "Open destination folder",
|
| 1912 |
+
'install.directory_requested': "Open request sent. Check your file manager.",
|
| 1913 |
+
'install.directory_unavailable': "The destination folder moved or no longer exists. Check it manually.",
|
| 1914 |
+
'install.directory_failed': "The folder could not be opened. Open it manually.",
|
| 1915 |
+
'install.directory_uncertain': "The open result is unconfirmed. Check your file manager first.",
|
| 1916 |
'install.error_package_too_large': 'The download exceeded the local safety limit. Installation was stopped.',
|
| 1917 |
'install.error_download': 'The download failed repeatedly. Check the network before retrying.',
|
| 1918 |
'install.error_target_occupied': 'Files from the previous version are in use. Close ComfyUI before retrying the update.',
|
|
|
|
| 2683 |
'task.cached_refresh_failed': 'Refresh unavailable. Saved public content remains visible; actions require an online check.',
|
| 2684 |
'feedback.cache_fallback': '⚠️ Network failed, showing cached data',
|
| 2685 |
'feedback.refresh_failed_cached': 'Refresh failed. The previous results are still shown.',
|
| 2686 |
+
'feedback.list_changed_retry': 'The list has changed. Please reload it.',
|
| 2687 |
'feedback.offline_no_cache': 'Network disconnected, and no local cache available',
|
| 2688 |
'feedback.cloud_unreachable_no_cache': 'Cloud service is unreachable, and there is no local content to show',
|
| 2689 |
'feedback.search_local_result': '⚠️ Network unavailable, showing local search results',
|
前端页面/core/侧边栏数据引擎.js
CHANGED
|
@@ -1,713 +1,764 @@
|
|
| 1 |
-
// 前端页面/core/侧边栏数据引擎.js
|
| 2 |
-
// ==========================================
|
| 3 |
-
// 📊 侧边栏数据加载引擎
|
| 4 |
-
// ==========================================
|
| 5 |
-
// 作用:负责列表数据的加载、缓存、分页、渲染
|
| 6 |
-
// 关联文件:
|
| 7 |
-
// - 网络请求API.js (数据获取)
|
| 8 |
-
// - 列表卡片组件.js (工具/应用卡片渲染)
|
| 9 |
-
// - 创作者卡片组件.js (创作者卡片渲染)
|
| 10 |
-
// - 性能优化工具.js (分页加载、骨架屏)
|
| 11 |
-
// ==========================================
|
| 12 |
-
// ⚡ P1性能优化:
|
| 13 |
-
// - 首屏仅加载 PAGE_SIZE 条数据
|
| 14 |
-
// - 滚动到底部自动加载更多
|
| 15 |
-
// - 骨架屏加载动画
|
| 16 |
-
// - 增强缓存策略
|
| 17 |
-
// ==========================================
|
| 18 |
-
|
| 19 |
-
import { fetchSidebarList, readSidebarListCache, readCreatorsSessionCache as getCreatorsFromSessionStorage,
|
| 20 |
-
writeCreatorsSessionCache as saveCreatorsToSessionStorage } from "./榜单数据来源.js";
|
| 21 |
-
import { mountSidebarDomainView } from "./榜单视图切换.js";
|
| 22 |
-
import { setupSidebarPagination as _setupPaginationLoader } from "./榜单分页控制.js";
|
| 23 |
-
import { createSidebarPaginationStore } from "./榜单分页状态.js";
|
| 24 |
-
import { sortDataLocally, filterItemsByKeyword, searchCreatorsLocally } from "./榜单本地查询.js";
|
| 25 |
-
|
| 26 |
-
import {
|
| 27 |
-
|
| 28 |
-
import {
|
| 29 |
-
import {
|
| 30 |
-
import {
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
import {
|
| 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 |
-
const
|
| 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 |
-
const
|
| 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 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
(
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
//
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
//
|
| 331 |
-
const
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
if (
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
if (
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
//
|
| 452 |
-
//
|
| 453 |
-
//
|
| 454 |
-
//
|
| 455 |
-
//
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
if (
|
| 463 |
-
|
| 464 |
-
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
|
| 473 |
-
|
| 474 |
-
|
| 475 |
-
|
| 476 |
-
//
|
| 477 |
-
|
| 478 |
-
|
| 479 |
-
|
| 480 |
-
|
| 481 |
-
|
| 482 |
-
|
| 483 |
-
|
| 484 |
-
|
| 485 |
-
|
| 486 |
-
//
|
| 487 |
-
|
| 488 |
-
|
| 489 |
-
|
| 490 |
-
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
|
| 494 |
-
|
| 495 |
-
|
| 496 |
-
|
| 497 |
-
if (
|
| 498 |
-
|
| 499 |
-
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
|
| 507 |
-
|
| 508 |
-
|
| 509 |
-
|
| 510 |
-
|
| 511 |
-
|
| 512 |
-
|
| 513 |
-
|
| 514 |
-
|
| 515 |
-
|
| 516 |
-
|
| 517 |
-
|
| 518 |
-
|
| 519 |
-
|
| 520 |
-
|
| 521 |
-
|
| 522 |
-
|
| 523 |
-
|
| 524 |
-
|
| 525 |
-
|
| 526 |
-
|
| 527 |
-
|
| 528 |
-
|
| 529 |
-
|
| 530 |
-
|
| 531 |
-
if (
|
| 532 |
-
|
| 533 |
-
|
| 534 |
-
|
| 535 |
-
|
| 536 |
-
|
| 537 |
-
|
| 538 |
-
|
| 539 |
-
|
| 540 |
-
|
| 541 |
-
|
| 542 |
-
|
| 543 |
-
// 启
|
| 544 |
-
|
| 545 |
-
|
| 546 |
-
|
| 547 |
-
|
| 548 |
-
|
| 549 |
-
|
| 550 |
-
|
| 551 |
-
|
| 552 |
-
|
| 553 |
-
|
| 554 |
-
|
| 555 |
-
|
| 556 |
-
|
| 557 |
-
|
| 558 |
-
|
| 559 |
-
|
| 560 |
-
|
| 561 |
-
|
| 562 |
-
|
| 563 |
-
|
| 564 |
-
|
| 565 |
-
|
| 566 |
-
//
|
| 567 |
-
|
| 568 |
-
|
| 569 |
-
|
| 570 |
-
return;
|
| 571 |
-
}
|
| 572 |
-
|
| 573 |
-
//
|
| 574 |
-
|
| 575 |
-
|
| 576 |
-
|
| 577 |
-
|
| 578 |
-
|
| 579 |
-
|
| 580 |
-
|
| 581 |
-
|
| 582 |
-
|
| 583 |
-
|
| 584 |
-
|
| 585 |
-
|
| 586 |
-
|
| 587 |
-
|
| 588 |
-
|
| 589 |
-
|
| 590 |
-
|
| 591 |
-
|
| 592 |
-
|
| 593 |
-
|
| 594 |
-
|
| 595 |
-
|
| 596 |
-
|
| 597 |
-
|
| 598 |
-
|
| 599 |
-
|
| 600 |
-
|
| 601 |
-
|
| 602 |
-
|
| 603 |
-
|
| 604 |
-
|
| 605 |
-
|
| 606 |
-
|
| 607 |
-
|
| 608 |
-
}
|
| 609 |
-
|
| 610 |
-
|
| 611 |
-
|
| 612 |
-
|
| 613 |
-
|
| 614 |
-
|
| 615 |
-
|
| 616 |
-
|
| 617 |
-
|
| 618 |
-
|
| 619 |
-
|
| 620 |
-
|
| 621 |
-
|
| 622 |
-
|
| 623 |
-
|
| 624 |
-
|
| 625 |
-
|
| 626 |
-
|
| 627 |
-
|
| 628 |
-
|
| 629 |
-
|
| 630 |
-
|
| 631 |
-
|
| 632 |
-
|
| 633 |
-
|
| 634 |
-
|
| 635 |
-
|
| 636 |
-
|
| 637 |
-
|
| 638 |
-
|
| 639 |
-
|
| 640 |
-
|
| 641 |
-
|
| 642 |
-
|
| 643 |
-
|
| 644 |
-
|
| 645 |
-
|
| 646 |
-
|
| 647 |
-
|
| 648 |
-
|
| 649 |
-
}
|
| 650 |
-
|
| 651 |
-
|
| 652 |
-
|
| 653 |
-
|
| 654 |
-
|
| 655 |
-
|
| 656 |
-
|
| 657 |
-
|
| 658 |
-
|
| 659 |
-
|
| 660 |
-
|
| 661 |
-
|
| 662 |
-
|
| 663 |
-
|
| 664 |
-
|
| 665 |
-
|
| 666 |
-
|
| 667 |
-
|
| 668 |
-
|
| 669 |
-
|
| 670 |
-
|
| 671 |
-
|
| 672 |
-
|
| 673 |
-
|
| 674 |
-
|
| 675 |
-
|
| 676 |
-
|
| 677 |
-
|
| 678 |
-
|
| 679 |
-
|
| 680 |
-
|
| 681 |
-
|
| 682 |
-
|
| 683 |
-
|
| 684 |
-
|
| 685 |
-
|
| 686 |
-
|
| 687 |
-
/
|
| 688 |
-
|
| 689 |
-
|
| 690 |
-
|
| 691 |
-
|
| 692 |
-
|
| 693 |
-
|
| 694 |
-
|
| 695 |
-
|
| 696 |
-
|
| 697 |
-
|
| 698 |
-
|
| 699 |
-
|
| 700 |
-
|
| 701 |
-
|
| 702 |
-
|
| 703 |
-
|
| 704 |
-
|
| 705 |
-
|
| 706 |
-
|
| 707 |
-
|
| 708 |
-
|
| 709 |
-
|
| 710 |
-
|
| 711 |
-
|
| 712 |
-
|
| 713 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// 前端页面/core/侧边栏数据引擎.js
|
| 2 |
+
// ==========================================
|
| 3 |
+
// 📊 侧边栏数据加载引擎
|
| 4 |
+
// ==========================================
|
| 5 |
+
// 作用:负责列表数据的加载、缓存、分页、渲染
|
| 6 |
+
// 关联文件:
|
| 7 |
+
// - 网络请求API.js (数据获取)
|
| 8 |
+
// - 列表卡片组件.js (工具/应用卡片渲染)
|
| 9 |
+
// - 创作者卡片组件.js (创作者卡片渲染)
|
| 10 |
+
// - 性能优化工具.js (分页加载、骨架屏)
|
| 11 |
+
// ==========================================
|
| 12 |
+
// ⚡ P1性能优化:
|
| 13 |
+
// - 首屏仅加载 PAGE_SIZE 条数据
|
| 14 |
+
// - 滚动到底部自动加载更多
|
| 15 |
+
// - 骨架屏加载动画
|
| 16 |
+
// - 增强缓存策略
|
| 17 |
+
// ==========================================
|
| 18 |
+
|
| 19 |
+
import { fetchSidebarList, getSidebarResponseCacheSource, readSidebarListCache, readCreatorsSessionCache as getCreatorsFromSessionStorage,
|
| 20 |
+
writeCreatorsSessionCache as saveCreatorsToSessionStorage } from "./榜单数据来源.js";
|
| 21 |
+
import { mountSidebarDomainView } from "./榜单视图切换.js";
|
| 22 |
+
import { setupSidebarPagination as _setupPaginationLoader } from "./榜单分页控制.js";
|
| 23 |
+
import { createSidebarPaginationStore } from "./榜单分页状态.js";
|
| 24 |
+
import { sortDataLocally, filterItemsByKeyword, searchCreatorsLocally } from "./榜单本地查询.js";
|
| 25 |
+
import { getSidebarListCacheKey } from "./全局配置.js";
|
| 26 |
+
import { captureCacheSource, captureCacheWrite } from "./网络请求_缓存管理.js";
|
| 27 |
+
|
| 28 |
+
import { api } from "./网络请求API.js";
|
| 29 |
+
import { proxyImages } from "./网络请求API.js";
|
| 30 |
+
import { createItemCard } from "../market/列表卡片组件.js";
|
| 31 |
+
import { createCreatorCard } from "../market/创作者卡片组件.js";
|
| 32 |
+
import {
|
| 33 |
+
createSkeleton,
|
| 34 |
+
setCache,
|
| 35 |
+
lazyLoadImages,
|
| 36 |
+
renderListLoadError
|
| 37 |
+
} from "../components/性能优化工具.js";
|
| 38 |
+
import { applyViewportAnimations, getAnimationTypeForTab, scrollCardIntoView, stopViewportAnimations } from "../components/动画音效引擎.js";
|
| 39 |
+
import { t } from "../components/用户体验增强.js";
|
| 40 |
+
import { showToast } from "../components/UI交互提示组件.js"; // 🔧 降级提示改走统一组件(原为手写 div)
|
| 41 |
+
|
| 42 |
+
// 💬 讨论区组件(动态导入)
|
| 43 |
+
let postsViewModule = null;
|
| 44 |
+
async function getPostsView() {
|
| 45 |
+
if (!postsViewModule) {
|
| 46 |
+
postsViewModule = await import("../post/讨论区组件.js");
|
| 47 |
+
}
|
| 48 |
+
return postsViewModule;
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
// 📝 任务榜组件(动态导入)
|
| 52 |
+
let tasksViewModule = null;
|
| 53 |
+
async function getTasksView() {
|
| 54 |
+
if (!tasksViewModule) {
|
| 55 |
+
tasksViewModule = await import("../task/任务榜组件.js");
|
| 56 |
+
}
|
| 57 |
+
return tasksViewModule;
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
// 🧩 提示词组件(动态导入)
|
| 61 |
+
let promptsViewModule = null;
|
| 62 |
+
async function getPromptsView() {
|
| 63 |
+
if (!promptsViewModule) {
|
| 64 |
+
promptsViewModule = await import("../prompt/提示词组件.js");
|
| 65 |
+
}
|
| 66 |
+
return promptsViewModule;
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
// ==========================================
|
| 71 |
+
// 🔧 配置常量
|
| 72 |
+
// ==========================================
|
| 73 |
+
const PAGE_SIZE = 20; // 每页数量
|
| 74 |
+
const CREATORS_PAGE_SIZE = 12; // 创作者每页数量(卡片更大)
|
| 75 |
+
|
| 76 |
+
/**
|
| 77 |
+
* ⏱️ 获取缓存过期时间(毫秒)
|
| 78 |
+
* 从用户设置中读取,默认2小时(7200秒)
|
| 79 |
+
* @returns {number} 缓存过期时间(毫秒)
|
| 80 |
+
*/
|
| 81 |
+
function getCacheExpireTime() {
|
| 82 |
+
try {
|
| 83 |
+
const settingsStr = localStorage.getItem('ComfyCommunity_Settings');
|
| 84 |
+
if (settingsStr) {
|
| 85 |
+
const settings = JSON.parse(settingsStr);
|
| 86 |
+
const seconds = parseInt(settings.cacheExpireSeconds);
|
| 87 |
+
if (seconds && seconds >= 60 && seconds <= 86400) {
|
| 88 |
+
return seconds * 1000; // 转为毫秒
|
| 89 |
+
}
|
| 90 |
+
}
|
| 91 |
+
} catch (e) {}
|
| 92 |
+
return 1000 * 60 * 60 * 2; // 默认2小时
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
// ==========================================
|
| 96 |
+
// 🔄 同榜单数据与创作者会话缓存
|
| 97 |
+
// ==========================================
|
| 98 |
+
/**
|
| 99 |
+
* 从同 tab 的任意排序状态中获取已有数据
|
| 100 |
+
*/
|
| 101 |
+
function findExistingTabData(tab, freshOnly = true) {
|
| 102 |
+
let source;
|
| 103 |
+
const data = paginationStore.findCompleteData(tab, (_state, sort) => {
|
| 104 |
+
const key = getSidebarListCacheKey(tab, sort);
|
| 105 |
+
const metadata = readSidebarListCache(key, { creators: tab === 'creators' });
|
| 106 |
+
if (!metadata.found || (freshOnly && metadata.expired)) return null;
|
| 107 |
+
const candidate = captureCacheSource(key);
|
| 108 |
+
if (!candidate?.isAvailable() || (freshOnly && !candidate.isFresh())) return null;
|
| 109 |
+
source = candidate;
|
| 110 |
+
return metadata.value === _state.allData ? _state.allData : proxyImages(metadata.value);
|
| 111 |
+
});
|
| 112 |
+
return data ? { data, source } : null;
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
+
function saveSidebarResponse(cacheKey, data, rawData) {
|
| 116 |
+
const cachedResponse = getSidebarResponseCacheSource(rawData);
|
| 117 |
+
if (cachedResponse) return cachedResponse.source?.copyTo(cacheKey, data) || false;
|
| 118 |
+
setCache(cacheKey, data, getCacheExpireTime(), true);
|
| 119 |
+
return true;
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
// ==========================================
|
| 123 |
+
// 📦 分页状态管理
|
| 124 |
+
// ==========================================
|
| 125 |
+
// 每个标签页独立的分页状态
|
| 126 |
+
const paginationStore = createSidebarPaginationStore();
|
| 127 |
+
const contentReadOwners = new WeakMap();
|
| 128 |
+
const ownedRenderGetters = new WeakMap();
|
| 129 |
+
const expiredRenderToken = Symbol();
|
| 130 |
+
const getPaginationState = (tab, sort) => paginationStore.get(tab, sort);
|
| 131 |
+
|
| 132 |
+
export function disposeSidebarContent(contentArea) {
|
| 133 |
+
stopViewportAnimations(contentArea);
|
| 134 |
+
try { paginationStore.stopLoaders(); }
|
| 135 |
+
catch { console.warn('Sidebar pagination cleanup failed'); }
|
| 136 |
+
for (const child of Array.from(contentArea.children)) {
|
| 137 |
+
const cleanup = child._cleanup;
|
| 138 |
+
child._cleanup = null;
|
| 139 |
+
try { cleanup?.call(child); }
|
| 140 |
+
catch { console.warn('Sidebar list view cleanup failed'); }
|
| 141 |
+
}
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
// ==========================================
|
| 146 |
+
// 🚀 主加载函数
|
| 147 |
+
// ==========================================
|
| 148 |
+
export async function loadSidebarContent({
|
| 149 |
+
tab,
|
| 150 |
+
sort,
|
| 151 |
+
keyword,
|
| 152 |
+
contentArea,
|
| 153 |
+
currentUser,
|
| 154 |
+
renderToken,
|
| 155 |
+
getRenderToken,
|
| 156 |
+
force = false,
|
| 157 |
+
expandItemId = null, // 新增:要自动展开的卡片ID
|
| 158 |
+
isNavigationCurrent = () => true
|
| 159 |
+
}) {
|
| 160 |
+
if (renderToken !== getRenderToken()) return;
|
| 161 |
+
const previousGetter = ownedRenderGetters.get(getRenderToken);
|
| 162 |
+
const getHostRenderToken = previousGetter?.area === contentArea ? previousGetter.getHost : getRenderToken;
|
| 163 |
+
const readOwner = {};
|
| 164 |
+
contentReadOwners.set(contentArea, readOwner);
|
| 165 |
+
getRenderToken = () => contentReadOwners.get(contentArea) === readOwner ? getHostRenderToken() : expiredRenderToken;
|
| 166 |
+
ownedRenderGetters.set(getRenderToken, { area: contentArea, getHost: getHostRenderToken });
|
| 167 |
+
const canNavigate = () => renderToken === getRenderToken() && isNavigationCurrent();
|
| 168 |
+
// 新榜单取得视图所有权时停止所有旧分页器,保留各榜单已加载数据。
|
| 169 |
+
paginationStore.stopLoaders();
|
| 170 |
+
|
| 171 |
+
const domainViews = {
|
| 172 |
+
posts: { loadModule: getPostsView, factory: 'createPostsView', errorKey: 'feedback.load_posts_failed',
|
| 173 |
+
afterMount: module => { if (module.loadPosts) module.loadPosts(); } },
|
| 174 |
+
tasks: { loadModule: getTasksView, factory: 'createTasksView', errorKey: 'feedback.load_tasks_failed' },
|
| 175 |
+
prompts: { loadModule: getPromptsView, factory: 'createPromptsView', errorKey: 'feedback.load_prompts_failed' },
|
| 176 |
+
};
|
| 177 |
+
if (Object.hasOwn(domainViews, tab)) {
|
| 178 |
+
await mountSidebarDomainView({ contentArea, currentUser, keyword, renderToken, getRenderToken,
|
| 179 |
+
...domainViews[tab] });
|
| 180 |
+
return;
|
| 181 |
+
}
|
| 182 |
+
|
| 183 |
+
const cacheKey = getSidebarListCacheKey(tab, sort);
|
| 184 |
+
const state = getPaginationState(tab, sort);
|
| 185 |
+
const pageSize = tab === "creators" ? CREATORS_PAGE_SIZE : PAGE_SIZE;
|
| 186 |
+
const sameCreatorSearchData = tab === "creators" && keyword && state.isSearchResult &&
|
| 187 |
+
state.searchKeyword === keyword && Array.isArray(state.allData) && state.allData.length > 0
|
| 188 |
+
? state.allData
|
| 189 |
+
: null;
|
| 190 |
+
|
| 191 |
+
// ========== 🔄 强制刷新:清除当前 tab/sort 的内存缓存 ==========
|
| 192 |
+
if (force) {
|
| 193 |
+
state.allData = [];
|
| 194 |
+
state.displayedCount = 0;
|
| 195 |
+
state.isFullyLoaded = false;
|
| 196 |
+
if (!sameCreatorSearchData) {
|
| 197 |
+
state.isSearchResult = false;
|
| 198 |
+
state.searchKeyword = "";
|
| 199 |
+
}
|
| 200 |
+
}
|
| 201 |
+
|
| 202 |
+
// 停止之前的分页加载器
|
| 203 |
+
if (state.loader) {
|
| 204 |
+
state.loader.stop();
|
| 205 |
+
state.loader = null; // 清除引用,防止旧分页器状态残留
|
| 206 |
+
}
|
| 207 |
+
|
| 208 |
+
// ========== 🔍 搜索过滤统一入口 ==========
|
| 209 |
+
// 🔧 修复:过滤职责原先分裂在三处且口径不一致 —— loadMoreData 与分页器的
|
| 210 |
+
// getTotalDataCount 都是「先过滤再切片」(正确),而各首屏分支是「先切 20 条再过滤」,
|
| 211 |
+
// renderBatch 内部又对切好的批次再过滤一次。后果不只是首屏条数偏少:首屏与分页
|
| 212 |
+
// 处于不同的数据空间(首屏在「原始前 20 条」里找匹配,分页在「过滤后全集」里按 20
|
| 213 |
+
// 步长切片),排在第 20 条之后的匹配项会永久丢失,甚至首屏直接显示「没有搜索到相关内容」。
|
| 214 |
+
// 现统一收口到本函数:所有取数路径都先过滤、再切片,renderBatch 只负责渲染。
|
| 215 |
+
// 创作者Tab的 keyword 由后端搜索接口过滤,此处不做本地过滤(与原口径一致)。
|
| 216 |
+
const _applySearchScope = (dataArray) => {
|
| 217 |
+
const scoped = !keyword || tab === "creators" ? dataArray : filterItemsByKeyword(dataArray, keyword);
|
| 218 |
+
if (!expandItemId || tab === "creators") return scoped;
|
| 219 |
+
const target = dataArray.find(item => String(item.id) === String(expandItemId));
|
| 220 |
+
if (!target) return scoped;
|
| 221 |
+
return [target, ...scoped.filter(item => String(item.id) !== String(expandItemId))];
|
| 222 |
+
};
|
| 223 |
+
|
| 224 |
+
// ========== 渲染函数:渲染一批数据(只渲染,过滤由 _applySearchScope 统一负责)==========
|
| 225 |
+
let targetLookupStarted = false;
|
| 226 |
+
const renderBatch = (dataArray, append = false) => {
|
| 227 |
+
if (renderToken !== getRenderToken()) return;
|
| 228 |
+
|
| 229 |
+
// 🔧 数据已由调用方经 _applySearchScope 过滤,本函数只负责渲染(不再二次过滤)
|
| 230 |
+
const displayData = dataArray;
|
| 231 |
+
|
| 232 |
+
// 首次渲染清空容器
|
| 233 |
+
if (!append) {
|
| 234 |
+
disposeSidebarContent(contentArea);
|
| 235 |
+
contentArea.innerHTML = "";
|
| 236 |
+
state.displayedCount = 0;
|
| 237 |
+
}
|
| 238 |
+
|
| 239 |
+
// 空数据处理
|
| 240 |
+
if (displayData.length === 0 && state.displayedCount === 0) {
|
| 241 |
+
const emptyState = document.createElement('div');
|
| 242 |
+
emptyState.className = 'sidebar-status-message';
|
| 243 |
+
emptyState.textContent = t(keyword ? 'feedback.no_search_results' : 'feedback.no_list_data');
|
| 244 |
+
emptyState.setAttribute('role', 'status');
|
| 245 |
+
contentArea.replaceChildren(emptyState);
|
| 246 |
+
if (!expandItemId) return 0;
|
| 247 |
+
}
|
| 248 |
+
|
| 249 |
+
// 渲染卡片
|
| 250 |
+
const fragment = document.createDocumentFragment();
|
| 251 |
+
const animationType = getAnimationTypeForTab(tab);
|
| 252 |
+
const cards = [];
|
| 253 |
+
let targetCard = null; // 用于保存需要展开的目标卡片
|
| 254 |
+
|
| 255 |
+
if (tab === "tools" || tab === "skills" || tab === "apps" || tab === "recommends") {
|
| 256 |
+
displayData.forEach(data => {
|
| 257 |
+
const card = createItemCard(data, currentUser);
|
| 258 |
+
cards.push(card);
|
| 259 |
+
fragment.appendChild(card);
|
| 260 |
+
// 检查是否是需要展开的卡片
|
| 261 |
+
if (expandItemId && String(data.id) === String(expandItemId)) {
|
| 262 |
+
targetCard = card;
|
| 263 |
+
}
|
| 264 |
+
});
|
| 265 |
+
} else if (tab === "creators") {
|
| 266 |
+
displayData.forEach(data => {
|
| 267 |
+
const card = createCreatorCard(data, currentUser);
|
| 268 |
+
cards.push(card);
|
| 269 |
+
fragment.appendChild(card);
|
| 270 |
+
});
|
| 271 |
+
}
|
| 272 |
+
|
| 273 |
+
contentArea.appendChild(fragment);
|
| 274 |
+
|
| 275 |
+
// ✨ 应用视口感知动画:可见卡片依次错开载入,滚动/分页进入视口的卡片自动补播动画
|
| 276 |
+
applyViewportAnimations(contentArea, cards, animationType, !append);
|
| 277 |
+
|
| 278 |
+
// 对新渲染的图片启用懒加载
|
| 279 |
+
lazyLoadImages(contentArea, "img:not(.lazy-loaded):not(.lazy-loading)");
|
| 280 |
+
|
| 281 |
+
// 🔔 自动展开目标卡片(如果有)
|
| 282 |
+
if (targetCard && !append) {
|
| 283 |
+
requestAnimationFrame(() => {
|
| 284 |
+
if (!canNavigate()) return;
|
| 285 |
+
// 滚���到卡片位置
|
| 286 |
+
scrollCardIntoView(targetCard);
|
| 287 |
+
// 模拟点击摘要区域展开卡片
|
| 288 |
+
const summary = targetCard.querySelector('.item-summary') || targetCard.firstElementChild;
|
| 289 |
+
if (summary) summary.click();
|
| 290 |
+
});
|
| 291 |
+
}
|
| 292 |
+
|
| 293 |
+
// 目标不在列表快照中时补取,仍使用原榜单卡片展开。
|
| 294 |
+
if (expandItemId && !targetCard && !append && !targetLookupStarted && canNavigate()) {
|
| 295 |
+
targetLookupStarted = true;
|
| 296 |
+
(async () => {
|
| 297 |
+
try {
|
| 298 |
+
const res = await api.getItemById(expandItemId);
|
| 299 |
+
if (!canNavigate()) return;
|
| 300 |
+
if (res?.status !== "success" || !res.data || String(res.data.id) !== String(expandItemId)) {
|
| 301 |
+
showToast(t('notif.item_not_found'), "error");
|
| 302 |
+
return;
|
| 303 |
+
}
|
| 304 |
+
const target = state.allData.find(item => String(item.id) === String(expandItemId)) || proxyImages([res.data])[0];
|
| 305 |
+
state.loader?.stop();
|
| 306 |
+
state.loader = null;
|
| 307 |
+
state.allData = [target, ...state.allData.filter(item => String(item.id) !== String(expandItemId))];
|
| 308 |
+
const scoped = _applySearchScope(state.allData);
|
| 309 |
+
renderBatch(scoped.slice(0, pageSize), false);
|
| 310 |
+
if (scoped.length > pageSize) {
|
| 311 |
+
_setupPaginationLoader(contentArea, state, pageSize, loadMoreData, keyword, tab, renderToken, getRenderToken);
|
| 312 |
+
}
|
| 313 |
+
} catch (_) {
|
| 314 |
+
if (canNavigate()) showToast(t('notif.load_item_failed'), "error");
|
| 315 |
+
}
|
| 316 |
+
})();
|
| 317 |
+
}
|
| 318 |
+
|
| 319 |
+
state.displayedCount += displayData.length;
|
| 320 |
+
return displayData.length;
|
| 321 |
+
};
|
| 322 |
+
|
| 323 |
+
// ========== 分页加载更多函数 ==========
|
| 324 |
+
const loadMoreData = async (page, size, { isCurrent = () => true } = {}) => {
|
| 325 |
+
if (!isCurrent()) return [];
|
| 326 |
+
// 计算要显示的数据范围
|
| 327 |
+
const start = (page - 1) * size;
|
| 328 |
+
const end = start + size;
|
| 329 |
+
|
| 330 |
+
// 从全量数据中截取(统一走 _applySearchScope,与首屏处于同一数据空间)
|
| 331 |
+
const dataSlice = _applySearchScope(state.allData);
|
| 332 |
+
|
| 333 |
+
const batch = dataSlice.slice(start, end);
|
| 334 |
+
|
| 335 |
+
if (batch.length > 0) {
|
| 336 |
+
renderBatch(batch, true);
|
| 337 |
+
}
|
| 338 |
+
|
| 339 |
+
return batch;
|
| 340 |
+
};
|
| 341 |
+
|
| 342 |
+
// ========== 尝试从缓存加载 ==========
|
| 343 |
+
// 📌 本处的缓存口径与 任务榜/讨论区/提示词(统一走 性能优化工具.js 的
|
| 344 |
+
// readListCache,命中后一律调 silentRefresh 后台补新)**刻意不同**,不是历史遗留,勿顺手归一:
|
| 345 |
+
// - 这里缓存的是全量数据(items 200 条 / creators 500 条),分页完全在本地做,
|
| 346 |
+
// 所以缓存命中即等于「数据完整」,只在 expired 时才值得再发一次网络请求;
|
| 347 |
+
// - 那三个列表只缓存第一页,命中后数据必然不完整,故一律后台 silentRefresh 补新。
|
| 348 |
+
// 若强行统一成「总是后台刷新」,插件榜会在每次 Tab 切换时多发一次 200 条的全量请求。
|
| 349 |
+
// 获取完整缓存信息(包含过期状态)
|
| 350 |
+
const { value: cachedData, expired: isCacheExpired, found: hasCacheData } =
|
| 351 |
+
readSidebarListCache(cacheKey, { creators: tab === 'creators' });
|
| 352 |
+
|
| 353 |
+
// 有缓存时直接渲染缓存(搜索时也使用缓存,renderBatch 会处理 keyword 过滤)
|
| 354 |
+
// 🔍 创作者Tab有keyword时不使用缓存,每次都从后端搜索
|
| 355 |
+
// 🔧 修复:原实现还把「刚清空搜索框」也列为跳过缓存的理由,但 cacheKey 不含 keyword、
|
| 356 |
+
// 搜索结果也从不写入该键(见下方 isCreatorSearch 判断),缓存里存的始终是干净的全量列表,
|
| 357 |
+
// 清空搜索框后完全可以直接用缓存上屏;强制联网只会让用户在弱网下白等一整个重试预算
|
| 358 |
+
const skipCache = tab === "creators" && !!keyword;
|
| 359 |
+
if (!force && hasCacheData && !skipCache) {
|
| 360 |
+
// 🚀 缓存数据也需要过一遍图片代理,确保新字段也被处理
|
| 361 |
+
const proxiedData = proxyImages(cachedData);
|
| 362 |
+
state.allData = proxiedData;
|
| 363 |
+
state.isFullyLoaded = true;
|
| 364 |
+
// 缓存是全量列表而非搜索结果,清除搜索标记,避免下次加载仍被当作搜索结果处理
|
| 365 |
+
if (tab === "creators" && !keyword) {
|
| 366 |
+
state.isSearchResult = false;
|
| 367 |
+
state.searchKeyword = "";
|
| 368 |
+
}
|
| 369 |
+
|
| 370 |
+
// 首屏渲染(仅第一页)—— 先过滤再切片,与 loadMoreData 同一数据空间
|
| 371 |
+
const scopedData = _applySearchScope(proxiedData);
|
| 372 |
+
renderBatch(scopedData.slice(0, pageSize), false);
|
| 373 |
+
|
| 374 |
+
// 如果有更多数据,启动分页加载器
|
| 375 |
+
if (scopedData.length > pageSize) {
|
| 376 |
+
_setupPaginationLoader(contentArea, state, pageSize, loadMoreData, keyword, tab, renderToken, getRenderToken);
|
| 377 |
+
}
|
| 378 |
+
|
| 379 |
+
// 【新增】Tab 切换后台静默刷新 —— 仅缓存过期时触发
|
| 380 |
+
if (isCacheExpired) {
|
| 381 |
+
console.log(`🔄 缓存已过期,${tab}_${sort} 启动后台静默刷新...`);
|
| 382 |
+
|
| 383 |
+
setTimeout(async () => {
|
| 384 |
+
// 保存当前上下文快照,防止网络延迟期间用户切换Tab导致竞态
|
| 385 |
+
const savedToken = renderToken;
|
| 386 |
+
const savedTab = tab;
|
| 387 |
+
const savedSort = sort;
|
| 388 |
+
|
| 389 |
+
// 防竞态检查1:回调开始执行时验证
|
| 390 |
+
if (savedToken !== getRenderToken()) return;
|
| 391 |
+
|
| 392 |
+
const isReadCurrent = captureCacheWrite(cacheKey);
|
| 393 |
+
try {
|
| 394 |
+
const rawData = await fetchSidebarList({ tab: savedTab, sort: savedSort, background: true });
|
| 395 |
+
if (savedToken !== getRenderToken() || !isReadCurrent()) return;
|
| 396 |
+
const newData = proxyImages(rawData);
|
| 397 |
+
|
| 398 |
+
// 防竞态检查2:网络请求完成后再次验证
|
| 399 |
+
if (savedToken !== getRenderToken()) return;
|
| 400 |
+
|
| 401 |
+
// 🛡️ 空响应防护:云端返回空列表时不回写缓存、也不清屏重渲染。
|
| 402 |
+
// 本分支由「缓存过期」触发,是切 Tab 时最常走到的路径,若不拦,
|
| 403 |
+
// 下方 state.allData = newData + contentArea.innerHTML = "" 会把
|
| 404 |
+
// 已上屏的本地数据连画面带缓存一起清空(见 _isEmptyOverwrite 说明)
|
| 405 |
+
if (_isEmptyOverwrite(newData, state.allData, cachedData)) {
|
| 406 |
+
console.warn(`🛡️ ${savedTab}_${savedSort} 云端返回空列表,保留本地数据,跳过缓存回写`);
|
| 407 |
+
return;
|
| 408 |
+
}
|
| 409 |
+
|
| 410 |
+
// 只有token匹配时才同时更新state.allData和setCache
|
| 411 |
+
if (_shouldUpdateData(state.allData, newData)) {
|
| 412 |
+
console.log(`✅ ${savedTab}_${savedSort} 检测到新数据,执行静默更新`);
|
| 413 |
+
state.allData = newData;
|
| 414 |
+
state.displayedCount = 0; // 重置分页计数
|
| 415 |
+
// 📴 持久化到 localStorage,保证重启后离线仍可展示
|
| 416 |
+
saveSidebarResponse(cacheKey, newData, rawData);
|
| 417 |
+
|
| 418 |
+
// 更新创作者 sessionStorage 缓存
|
| 419 |
+
if (savedTab === "creators") {
|
| 420 |
+
saveCreatorsToSessionStorage(newData);
|
| 421 |
+
}
|
| 422 |
+
|
| 423 |
+
// 完整重新渲染(替代之前只更新数字的方案)
|
| 424 |
+
// 🔧 先过滤再切片:搜索场景下静默刷新同样会触发,
|
| 425 |
+
// 原实现在 newData 前 20 条里过滤,会漏掉靠后的匹配项
|
| 426 |
+
const scopedNewData = _applySearchScope(newData);
|
| 427 |
+
renderBatch(scopedNewData.slice(0, pageSize), false);
|
| 428 |
+
|
| 429 |
+
if (scopedNewData.length > pageSize) {
|
| 430 |
+
_setupPaginationLoader(contentArea, state, pageSize, loadMoreData, keyword, savedTab, savedToken, getRenderToken);
|
| 431 |
+
}
|
| 432 |
+
} else {
|
| 433 |
+
// 关键字段无变化 → 无需重渲染。但 newData 才是刚从云端取回的权威数据,
|
| 434 |
+
// 缓存必须回写 newData:若仍回写旧的 state.allData,等于把旧数据固化并
|
| 435 |
+
// 续期(续期后 isCacheExpired 转 false,下次连静默刷新都不再触发),
|
| 436 |
+
// 导致缓存中的旧版本号被长期锁死、卡片徽章无法出现。
|
| 437 |
+
// 注意此处刻意不更新 state.allData:首屏已按旧数据渲染,保持二者一致可
|
| 438 |
+
// 避免分页加载与已渲染卡片错位;新数据在下次进入读取缓存时生效
|
| 439 |
+
saveSidebarResponse(cacheKey, newData, rawData);
|
| 440 |
+
}
|
| 441 |
+
} catch (err) {
|
| 442 |
+
if (savedToken !== getRenderToken()) return;
|
| 443 |
+
console.warn(`⚠️ ${savedTab}_${savedSort} 后台刷新失败`);
|
| 444 |
+
}
|
| 445 |
+
}, 0);
|
| 446 |
+
}
|
| 447 |
+
|
| 448 |
+
return;
|
| 449 |
+
}
|
| 450 |
+
|
| 451 |
+
// ========== 🔄 本地排序优先:同 tab 已有数据时直接排序渲染(强制刷新时跳过)==========
|
| 452 |
+
// 🔍 创作者Tab有keyword时不走本地排序优先,必须调用后端搜索API
|
| 453 |
+
// 🔍 创作者Tab清空搜索框后也不走本地排序优先,避免使用搜索时的部分结果
|
| 454 |
+
// 🔍 如果当前state是搜索结果,也不走本地排序优先
|
| 455 |
+
// 仅在"正在搜索"或"刚清空搜索但state仍是搜索结果"时跳过本地排序
|
| 456 |
+
const isCreatorSearching = tab === "creators" && keyword;
|
| 457 |
+
const isCreatorSearchCleared = tab === "creators" && !keyword && state.isSearchResult;
|
| 458 |
+
const skipLocalSort = isCreatorSearching || isCreatorSearchCleared || state.isSearchResult;
|
| 459 |
+
const existingData = findExistingTabData(tab);
|
| 460 |
+
if (!force && !skipLocalSort && existingData && existingData.data.length > 0 && existingData.source.isFresh()) {
|
| 461 |
+
const locallySorted = sortDataLocally(existingData.data, tab, sort);
|
| 462 |
+
if (existingData.source.copyTo(cacheKey, locallySorted)) {
|
| 463 |
+
state.allData = locallySorted;
|
| 464 |
+
state.isFullyLoaded = true;
|
| 465 |
+
state.displayedCount = 0; // 重置已显示计数,因为数据重新排序了
|
| 466 |
+
|
| 467 |
+
// 首屏渲染(先过滤再切片)
|
| 468 |
+
const scopedSorted = _applySearchScope(locallySorted);
|
| 469 |
+
renderBatch(scopedSorted.slice(0, pageSize), false);
|
| 470 |
+
|
| 471 |
+
// 启动分页加载器
|
| 472 |
+
if (scopedSorted.length > pageSize) {
|
| 473 |
+
_setupPaginationLoader(contentArea, state, pageSize, loadMoreData, keyword, tab, renderToken, getRenderToken);
|
| 474 |
+
}
|
| 475 |
+
|
| 476 |
+
// 存入当前排序的缓存(📴 创作者数据同样持久化到 localStorage,保证重启后离线可展示)
|
| 477 |
+
return; // 本地排序后直接返回,不需要后台刷新(数据是同一批)
|
| 478 |
+
}
|
| 479 |
+
}
|
| 480 |
+
|
| 481 |
+
// ========== 🚀 缓存先行:阻塞前先用本地已有数据上屏 ==========
|
| 482 |
+
// 走到这里说明上面两条快路径都没命中:要么是 force 强制刷新(刻意跳过缓存),
|
| 483 |
+
// 要么是本次会话还没有该 tab 的完整数据。弱网下一次列表请求最长要烧满整个重试预算,
|
| 484 |
+
// 期间用户只能盯骨架屏;此刻若本地已有可用数据,就先渲染首屏,网络请求照常往下走,
|
| 485 |
+
// 回来后按 renderToken + _shouldUpdateData 决定是否重渲染(与上方静默刷新同口径)。
|
| 486 |
+
// 🔍 新关键词的创作者搜索不参与缓存先行,避免显示其它查询结果;只有强制刷新当前同一关键词时,
|
| 487 |
+
// 才临时复用精确匹配的上一批搜索结果(state.searchKeyword),失败时继续保留它。
|
| 488 |
+
let renderedInstant = false;
|
| 489 |
+
if (!isCreatorSearching || sameCreatorSearchData) {
|
| 490 |
+
// 可立即上屏的数据:当前排序的列表缓存(force 时被跳过)→ 创作者 sessionStorage 降级副本
|
| 491 |
+
let instantData = sameCreatorSearchData ||
|
| 492 |
+
((hasCacheData && Array.isArray(cachedData) && cachedData.length > 0) ? cachedData : null);
|
| 493 |
+
if (!instantData && tab === "creators") {
|
| 494 |
+
const sessionData = getCreatorsFromSessionStorage();
|
| 495 |
+
if (Array.isArray(sessionData) && sessionData.length > 0) instantData = sessionData;
|
| 496 |
+
}
|
| 497 |
+
if (!instantData && !isCreatorSearching) instantData = findExistingTabData(tab, false)?.data || null;
|
| 498 |
+
if (instantData) {
|
| 499 |
+
console.log(`🚀 ${tab}_${sort} 缓存先行:先用本地数据渲染首屏,网络请求转后台`);
|
| 500 |
+
// 🚀 与上方缓存命中分支同口径:本地数据也过一遍图片代理(proxyImages 内部会先剥除
|
| 501 |
+
// 已有代理前缀,幂等),确保代理规则新增的字段同样被处理
|
| 502 |
+
// sessionStorage 副本的顺序不保证与当前排序一致,统一本地排一次(对已排序数据幂等)
|
| 503 |
+
const sortedData = sortDataLocally(proxyImages(instantData), tab, sort);
|
| 504 |
+
state.allData = sortedData;
|
| 505 |
+
state.isFullyLoaded = true;
|
| 506 |
+
state.isSearchResult = !!sameCreatorSearchData;
|
| 507 |
+
state.searchKeyword = sameCreatorSearchData ? keyword : "";
|
| 508 |
+
// 🔧 先过滤再切片(tools/skills/apps/recommends 带 keyword 时同样会进入本分支)
|
| 509 |
+
const scopedInstant = _applySearchScope(sortedData);
|
| 510 |
+
renderBatch(scopedInstant.slice(0, pageSize), false);
|
| 511 |
+
if (scopedInstant.length > pageSize) {
|
| 512 |
+
_setupPaginationLoader(contentArea, state, pageSize, loadMoreData, keyword, tab, renderToken, getRenderToken);
|
| 513 |
+
}
|
| 514 |
+
renderedInstant = true;
|
| 515 |
+
}
|
| 516 |
+
}
|
| 517 |
+
|
| 518 |
+
// ========== 显示加载骨架屏(已有本地数据上屏时跳过,避免闪屏)==========
|
| 519 |
+
if (!renderedInstant) {
|
| 520 |
+
disposeSidebarContent(contentArea);
|
| 521 |
+
contentArea.innerHTML = "";
|
| 522 |
+
const skeleton = createSkeleton(tab === "creators" ? "list" : "card", 3);
|
| 523 |
+
contentArea.appendChild(skeleton);
|
| 524 |
+
}
|
| 525 |
+
|
| 526 |
+
// ========== 从网络加载数据 ==========
|
| 527 |
+
try {
|
| 528 |
+
const isReadCurrent = captureCacheWrite(cacheKey);
|
| 529 |
+
const rawData = await fetchSidebarList({ tab, sort, keyword, force });
|
| 530 |
+
if (renderToken !== getRenderToken()) return;
|
| 531 |
+
if (!isReadCurrent()) {
|
| 532 |
+
const error = new Error();
|
| 533 |
+
error.name = "ListCacheChangedError";
|
| 534 |
+
throw error;
|
| 535 |
+
}
|
| 536 |
+
const realData = proxyImages(rawData);
|
| 537 |
+
if (renderToken !== getRenderToken()) return;
|
| 538 |
+
if (tab === 'creators') {
|
| 539 |
+
state.isSearchResult = !!keyword;
|
| 540 |
+
state.searchKeyword = keyword || '';
|
| 541 |
+
}
|
| 542 |
+
|
| 543 |
+
// 存入缓存(📴 创作者数据同样持久化到 localStorage,保证重启后离线仍可展示;搜索结果不存入缓存)
|
| 544 |
+
const isCreatorSearch = tab === "creators" && keyword;
|
| 545 |
+
// 🛡️ 空响应防护:创作者搜索命中 0 条是有效答案(下方要渲染「没有搜索到相关内容」),
|
| 546 |
+
// 必须排除在防护之外,否则会把空搜索结果误判成云端故障、改渲染全量列表
|
| 547 |
+
const isEmptyOverwrite = !isCreatorSearch && _isEmptyOverwrite(realData, cachedData, state.allData);
|
| 548 |
+
if (isEmptyOverwrite) {
|
| 549 |
+
console.warn(`🛡️ ${tab}_${sort} 云端返回空列表,保留本地数据,不覆盖缓存`);
|
| 550 |
+
} else if (!isCreatorSearch) {
|
| 551 |
+
saveSidebarResponse(cacheKey, realData, rawData);
|
| 552 |
+
}
|
| 553 |
+
|
| 554 |
+
// 创作者非搜索数据存入 sessionStorage(用于离线降级)
|
| 555 |
+
if (tab === "creators" && !isCreatorSearch && !isEmptyOverwrite) {
|
| 556 |
+
saveCreatorsToSessionStorage(realData);
|
| 557 |
+
}
|
| 558 |
+
|
| 559 |
+
state.isFullyLoaded = true;
|
| 560 |
+
|
| 561 |
+
// 🛡️ 空响应且本地数据已上屏:保持当前画面,不用空列表清屏(与缓存同口径不回写)
|
| 562 |
+
if (isEmptyOverwrite && renderedInstant) {
|
| 563 |
+
return;
|
| 564 |
+
}
|
| 565 |
+
|
| 566 |
+
// 🚀 缓存先行场景:网络数据与已上屏的本地数据无实质差异时不重渲染,避免清屏重画
|
| 567 |
+
// 打断用户已经滚动的阅读位置(与上方后台静默刷新同口径)。缓存已在上面回写权威新数据,
|
| 568 |
+
// 此处刻意不更新 state.allData,保持与已渲染卡片一致,防止分页加载错位
|
| 569 |
+
if (renderedInstant && !_shouldUpdateData(state.allData, realData)) {
|
| 570 |
+
return;
|
| 571 |
+
}
|
| 572 |
+
|
| 573 |
+
// 更新状态
|
| 574 |
+
state.allData = realData;
|
| 575 |
+
|
| 576 |
+
// 渲染首屏(先过滤再切片:tools/skills/apps/recommends 的 keyword 是本地搜索,
|
| 577 |
+
// realData 是未过滤的全量数据,原实现在前 20 条里过滤会漏掉靠后的匹配项)
|
| 578 |
+
const scopedReal = _applySearchScope(realData);
|
| 579 |
+
renderBatch(scopedReal.slice(0, pageSize), false);
|
| 580 |
+
|
| 581 |
+
// 启动分页加载器
|
| 582 |
+
if (scopedReal.length > pageSize) {
|
| 583 |
+
_setupPaginationLoader(contentArea, state, pageSize, loadMoreData, keyword, tab, renderToken, getRenderToken);
|
| 584 |
+
}
|
| 585 |
+
|
| 586 |
+
} catch (error) {
|
| 587 |
+
// 🔍 防竞态:本次加载已被更新的加载取代(切Tab、换排序、继续输入关键词)时直接退出。
|
| 588 |
+
// renderBatch 内部本来就有这道守卫,但它之外的降级分支会直接写 contentArea.innerHTML
|
| 589 |
+
// 并弹提示,缺少守卫会让过期结果覆盖掉新内容
|
| 590 |
+
if (renderToken !== getRenderToken()) {
|
| 591 |
+
console.warn(`⏹️ ${tab}_${sort} 请求已过期,忽略本次失败`);
|
| 592 |
+
return;
|
| 593 |
+
}
|
| 594 |
+
if (error?.name === "ListCacheChangedError") {
|
| 595 |
+
if (renderedInstant) {
|
| 596 |
+
if (force) showToast(t('feedback.list_changed_retry'), 'warning');
|
| 597 |
+
return;
|
| 598 |
+
}
|
| 599 |
+
renderListLoadError(contentArea, t('feedback.list_changed_retry'), () => loadSidebarContent({
|
| 600 |
+
tab, sort, keyword, contentArea, currentUser, renderToken, getRenderToken,
|
| 601 |
+
force: true, expandItemId, isNavigationCurrent
|
| 602 |
+
}), t);
|
| 603 |
+
return;
|
| 604 |
+
}
|
| 605 |
+
// 🔍 主动撤销(上方 cancelAll)不是网络故障:用户只是又敲了一个字,
|
| 606 |
+
// 新一次加载已经在跑了。这里必须静默退出,否则会误弹「网络不可用」提示
|
| 607 |
+
if (error && error.name === 'RequestCancelledError') {
|
| 608 |
+
console.log(`⏹️ ${tab}_${sort} 搜索请求已被新关键词取代`);
|
| 609 |
+
return;
|
| 610 |
+
}
|
| 611 |
+
console.error("数据加载失败");
|
| 612 |
+
|
| 613 |
+
// 🚀 缓存先行场景:首屏已经用本地数据上屏,网络失败时保持当前画面即可,不再走下面的
|
| 614 |
+
// 降级分支(否则会把同一批数据重渲染一遍、重播卡片动画)。与上方后台静默刷新失败一致:
|
| 615 |
+
// 只记录日志,不额外打扰用户
|
| 616 |
+
if (renderedInstant) {
|
| 617 |
+
console.warn(`📴 ${tab}_${sort} 网络刷新失败,保持已渲染的本地数据`);
|
| 618 |
+
if (force) showToast(t('feedback.refresh_failed_cached'), 'warning');
|
| 619 |
+
return;
|
| 620 |
+
}
|
| 621 |
+
|
| 622 |
+
// 🚀 回退到任何可用缓存(包括过期的)
|
| 623 |
+
// 🔍 创作者Tab搜索场景跳过此分支:renderBatch 对创作者不做本地过滤,
|
| 624 |
+
// 直接渲染全量缓存会导致搜索结果未过滤,改由下方本地搜索降级分支处理
|
| 625 |
+
if (hasCacheData && cachedData && !(tab === "creators" && keyword)) {
|
| 626 |
+
console.warn(`📴 网络失败,降级显示${isCacheExpired ? '过期' : ''}缓存`);
|
| 627 |
+
state.allData = cachedData;
|
| 628 |
+
// 🔧 先过滤再切片:本分支已排除 creators+keyword,但 tools/skills/apps/recommends
|
| 629 |
+
// 带 keyword 时会进来;renderBatch 不再自行过滤,此处必须显式过滤
|
| 630 |
+
const scopedCached = _applySearchScope(cachedData);
|
| 631 |
+
renderBatch(scopedCached.slice(0, pageSize), false);
|
| 632 |
+
|
| 633 |
+
// 如果是过期缓存,显示提示
|
| 634 |
+
// 🔧 改用统一提示组件 + 词典(原为手写 div、无动画不排队,且文案硬编码中文)
|
| 635 |
+
if (isCacheExpired) {
|
| 636 |
+
showToast(t('feedback.cache_fallback'), 'warning');
|
| 637 |
+
}
|
| 638 |
+
return;
|
| 639 |
+
}
|
| 640 |
+
|
| 641 |
+
// 🚀 创作者Tab:尝试从 sessionStorage 或内存中降级
|
| 642 |
+
if (tab === "creators") {
|
| 643 |
+
let fallbackData = null;
|
| 644 |
+
|
| 645 |
+
// 1. 优先从当前内存状态获取
|
| 646 |
+
if (keyword && state.isSearchResult && state.searchKeyword === keyword &&
|
| 647 |
+
state.allData && state.allData.length > 0) {
|
| 648 |
+
fallbackData = state.allData;
|
| 649 |
+
}
|
| 650 |
+
// 2. 从本地列表缓存获取(含过期缓存,搜索结果不入库故不会污染)
|
| 651 |
+
if (!fallbackData && hasCacheData && cachedData) {
|
| 652 |
+
fallbackData = cachedData;
|
| 653 |
+
}
|
| 654 |
+
// 3. 尝试从 sessionStorage 获取
|
| 655 |
+
if (!fallbackData) {
|
| 656 |
+
fallbackData = getCreatorsFromSessionStorage();
|
| 657 |
+
}
|
| 658 |
+
// 4. 从其他排序状态获取
|
| 659 |
+
if (!fallbackData) {
|
| 660 |
+
fallbackData = findExistingTabData("creators", false)?.data || null;
|
| 661 |
+
}
|
| 662 |
+
|
| 663 |
+
if (fallbackData && fallbackData.length > 0) {
|
| 664 |
+
let displayData = fallbackData;
|
| 665 |
+
|
| 666 |
+
// 搜索场景:执行本地搜索
|
| 667 |
+
if (keyword) {
|
| 668 |
+
displayData = searchCreatorsLocally(keyword, fallbackData);
|
| 669 |
+
if (displayData.length === 0) {
|
| 670 |
+
const emptyState = document.createElement('div');
|
| 671 |
+
emptyState.className = 'sidebar-status-message';
|
| 672 |
+
emptyState.textContent = t('feedback.no_search_results');
|
| 673 |
+
emptyState.setAttribute('role', 'status');
|
| 674 |
+
contentArea.replaceChildren(emptyState);
|
| 675 |
+
|
| 676 |
+
// 🔧 改用统一提示组件 + 词典(原为手写 div 且文案硬编码中文)
|
| 677 |
+
showToast(t('feedback.search_local_result'), 'warning');
|
| 678 |
+
return;
|
| 679 |
+
}
|
| 680 |
+
}
|
| 681 |
+
|
| 682 |
+
// 按当前排序排序
|
| 683 |
+
displayData = sortDataLocally(displayData, tab, sort);
|
| 684 |
+
state.allData = displayData;
|
| 685 |
+
state.isSearchResult = !!keyword;
|
| 686 |
+
state.searchKeyword = keyword || '';
|
| 687 |
+
// 统一走 _applySearchScope(创作者Tab恒等返回,数据已由上方
|
| 688 |
+
// searchCreatorsLocally 过滤),保证各渲染入口口径完全一致
|
| 689 |
+
const scopedFallback = _applySearchScope(displayData);
|
| 690 |
+
renderBatch(scopedFallback.slice(0, pageSize), false);
|
| 691 |
+
|
| 692 |
+
// 启动分页加载器
|
| 693 |
+
if (scopedFallback.length > pageSize) {
|
| 694 |
+
_setupPaginationLoader(contentArea, state, pageSize, loadMoreData, keyword, tab, renderToken, getRenderToken);
|
| 695 |
+
}
|
| 696 |
+
|
| 697 |
+
// 🔧 改用统一提示组件 + 词典(原为手写 div 且两条文案均硬编码中文)
|
| 698 |
+
showToast(keyword ? t('feedback.search_local_result') : t('feedback.cache_fallback'), 'warning');
|
| 699 |
+
return;
|
| 700 |
+
} else if (keyword) {
|
| 701 |
+
renderListLoadError(contentArea, t('common.network_error_retry'), () => loadSidebarContent({
|
| 702 |
+
tab, sort, keyword, contentArea, currentUser, renderToken, getRenderToken,
|
| 703 |
+
force: true, expandItemId, isNavigationCurrent
|
| 704 |
+
}), t, error);
|
| 705 |
+
return;
|
| 706 |
+
}
|
| 707 |
+
}
|
| 708 |
+
|
| 709 |
+
// 无本地数据时提供原位重试,保留当前 ComfyUI 页面与榜单上下文。
|
| 710 |
+
renderListLoadError(contentArea, t('common.network_error_retry'), () => loadSidebarContent({
|
| 711 |
+
tab, sort, keyword, contentArea, currentUser, renderToken, getRenderToken,
|
| 712 |
+
force: true, expandItemId, isNavigationCurrent
|
| 713 |
+
}), t, error);
|
| 714 |
+
}
|
| 715 |
+
}
|
| 716 |
+
|
| 717 |
+
|
| 718 |
+
/**
|
| 719 |
+
* 🛡️ 空响应防护:本次云端返回是否属于「请求成功但列表为空」,且本地已有非空数据
|
| 720 |
+
*
|
| 721 |
+
* 背景:网络失败本身从不清理本地数据(重试耗尽只置云端冷却并回退过期缓存,见技术文档
|
| 722 |
+
* 04 章 4.2.2),但云端偶发返回 HTTP 200 + data:[] 会——例如 Space 冷启动时 HF Dataset
|
| 723 |
+
* 尚未加载完。此时 realData/newData 为 [],照原样回写缓存就把断网降级的唯一数据来源清掉了。
|
| 724 |
+
*
|
| 725 |
+
* 只拦「新数据为空 且 本地已有非空数据」这一种组合:本地本来就是空的(首次使用、刚清过
|
| 726 |
+
* 缓存、云端确实一条都没有)时返回 false,照��写入,不改变任何正常流程。
|
| 727 |
+
* 调用方须自行排除搜索结果场景——搜索命中 0 条是有效答案,不是云端故障。
|
| 728 |
+
*
|
| 729 |
+
* @param {Array} newData - 本次从云端取回的数据
|
| 730 |
+
* @param {...(Array|null|undefined)} localData - 本地已有数据(缓存副本 / 内存 state.allData)
|
| 731 |
+
* @returns {boolean} true = 属于会覆盖本地好数据的空响应,应跳过回写与重渲染
|
| 732 |
+
*/
|
| 733 |
+
function _isEmptyOverwrite(newData, ...localData) {
|
| 734 |
+
if (Array.isArray(newData) && newData.length > 0) return false;
|
| 735 |
+
return localData.some(d => Array.isArray(d) && d.length > 0);
|
| 736 |
+
}
|
| 737 |
+
|
| 738 |
+
/** 判断是否需要更新数据 —— 对比ID顺序和关键字段 */
|
| 739 |
+
function _shouldUpdateData(oldData, newData) {
|
| 740 |
+
if (!oldData || !newData) return true;
|
| 741 |
+
if (oldData.length !== newData.length) return true;
|
| 742 |
+
|
| 743 |
+
// 检查ID顺序是否一致(检测排序变化、新增/删除)
|
| 744 |
+
// 比对条数覆盖首屏渲染量(PAGE_SIZE),避免首屏可见卡片(第 11~20 条)的版本/数字更新被漏检
|
| 745 |
+
const checkCount = Math.min(PAGE_SIZE, oldData.length);
|
| 746 |
+
for (let i = 0; i < checkCount; i++) {
|
| 747 |
+
const oldId = oldData[i].id || oldData[i].account;
|
| 748 |
+
const newId = newData[i].id || newData[i].account;
|
| 749 |
+
if (oldId !== newId) return true;
|
| 750 |
+
|
| 751 |
+
// 检查关键数字字段
|
| 752 |
+
const keyFields = ['likes', 'downloads', 'uses', 'views', 'daily_views', 'recent_tips', 'favorites', 'rating_avg', 'rating_count'];
|
| 753 |
+
for (const field of keyFields) {
|
| 754 |
+
if ((oldData[i][field] || 0) !== (newData[i][field] || 0)) return true;
|
| 755 |
+
}
|
| 756 |
+
|
| 757 |
+
// 检查版本号(字符串):云端扫描到插件新版本时往往只有 latest_version 变化,
|
| 758 |
+
// 点赞/下载/浏览等数字字段全不动;若不比对它,卡片上的"可更新"徽章将永远刷不出来
|
| 759 |
+
if ((oldData[i].latest_version || '') !== (newData[i].latest_version || '')) return true;
|
| 760 |
+
}
|
| 761 |
+
return false;
|
| 762 |
+
}
|
| 763 |
+
|
| 764 |
+
|
前端页面/core/全局配置.js
CHANGED
|
@@ -121,6 +121,12 @@ export const LOCAL_PERFORMANCE = Object.freeze({
|
|
| 121 |
LABELS: Object.freeze({ tools: 'nav.tools', skills: 'nav.skills', apps: 'nav.apps', recommends: 'nav.recommends', creators: 'nav.creators', tasks: 'nav.tasks', posts: 'nav.posts', prompts: 'nav.prompts' })
|
| 122 |
});
|
| 123 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 124 |
export const SKILL_INSTALL = Object.freeze({
|
| 125 |
PATH: '/community_hub/skill_install',
|
| 126 |
PREFLIGHT_TIMEOUT: 30000,
|
|
@@ -191,6 +197,11 @@ export function isAdmin(account) {
|
|
| 191 |
// ==========================================
|
| 192 |
// 💾 缓存配置
|
| 193 |
// ==========================================
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 194 |
const RESOURCE_LIST_PREFIXES = [
|
| 195 |
"ListCache_tools_", "ListCache_skills_", "ListCache_apps_", "ListCache_recommends_"
|
| 196 |
];
|
|
|
|
| 121 |
LABELS: Object.freeze({ tools: 'nav.tools', skills: 'nav.skills', apps: 'nav.apps', recommends: 'nav.recommends', creators: 'nav.creators', tasks: 'nav.tasks', posts: 'nav.posts', prompts: 'nav.prompts' })
|
| 122 |
});
|
| 123 |
|
| 124 |
+
export const LOCAL_INSTALL_DIRECTORY = Object.freeze({
|
| 125 |
+
PATH: '/community_hub/open_install_directory',
|
| 126 |
+
TIMEOUT: 25000,
|
| 127 |
+
RESPONSE_MAX_BYTES: 8192
|
| 128 |
+
});
|
| 129 |
+
|
| 130 |
export const SKILL_INSTALL = Object.freeze({
|
| 131 |
PATH: '/community_hub/skill_install',
|
| 132 |
PREFLIGHT_TIMEOUT: 30000,
|
|
|
|
| 197 |
// ==========================================
|
| 198 |
// 💾 缓存配置
|
| 199 |
// ==========================================
|
| 200 |
+
export function getSidebarListCacheKey(tab, sort) {
|
| 201 |
+
const list = tab === 'creators' ? 'creators_full' : tab;
|
| 202 |
+
return `ListCache_${list}_${sort}`;
|
| 203 |
+
}
|
| 204 |
+
|
| 205 |
const RESOURCE_LIST_PREFIXES = [
|
| 206 |
"ListCache_tools_", "ListCache_skills_", "ListCache_apps_", "ListCache_recommends_"
|
| 207 |
];
|
前端页面/core/榜单分页状态.js
CHANGED
|
@@ -16,10 +16,11 @@ export function createSidebarPaginationStore() {
|
|
| 16 |
}
|
| 17 |
return states.get(key);
|
| 18 |
},
|
| 19 |
-
findCompleteData(tab) {
|
| 20 |
for (const [key, state] of states) {
|
| 21 |
-
if (key.startsWith(`${tab}_`) && state.allData.length > 0 && state.isFullyLoaded) {
|
| 22 |
-
|
|
|
|
| 23 |
}
|
| 24 |
}
|
| 25 |
return null;
|
|
|
|
| 16 |
}
|
| 17 |
return states.get(key);
|
| 18 |
},
|
| 19 |
+
findCompleteData(tab, readData = state => state.allData) {
|
| 20 |
for (const [key, state] of states) {
|
| 21 |
+
if (key.startsWith(`${tab}_`) && state.allData.length > 0 && state.isFullyLoaded && !state.isSearchResult) {
|
| 22 |
+
const data = readData(state, key.slice(tab.length + 1));
|
| 23 |
+
if (Array.isArray(data) && data.length > 0) return data;
|
| 24 |
}
|
| 25 |
}
|
| 26 |
return null;
|
前端页面/core/榜单数据来源.js
CHANGED
|
@@ -2,6 +2,12 @@ import { api, requestCancelManager } from './网络请求API.js';
|
|
| 2 |
import { API, CACHE, PAGINATION } from './全局配置.js';
|
| 3 |
import { requireListResponseData, getCacheWithMeta, removeCache } from '../components/性能优化工具.js';
|
| 4 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
const itemTypes = Object.freeze({ tools: 'tool', skills: 'skill', apps: 'app', recommends: 'recommend' });
|
| 6 |
|
| 7 |
// 只读取与校验,不提交视图状态或缓存;提交时由调用方核查界面代次。
|
|
@@ -9,6 +15,8 @@ export async function fetchSidebarList({ tab, sort, keyword = '', force = false,
|
|
| 9 |
const options = background
|
| 10 |
? { noCache: true, timeout: API.BACKGROUND_TIMEOUT, retries: API.BACKGROUND_RETRIES }
|
| 11 |
: (force ? { noCache: true } : {});
|
|
|
|
|
|
|
| 12 |
let response;
|
| 13 |
if (Object.hasOwn(itemTypes, tab)) {
|
| 14 |
response = await api.getItems(itemTypes[tab], sort, PAGINATION.SIDEBAR_ITEM_FETCH_LIMIT, options);
|
|
@@ -22,7 +30,21 @@ export async function fetchSidebarList({ tab, sort, keyword = '', force = false,
|
|
| 22 |
} else {
|
| 23 |
throw new TypeError('Unsupported sidebar list');
|
| 24 |
}
|
| 25 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
}
|
| 27 |
|
| 28 |
function validCreatorList(data) {
|
|
|
|
| 2 |
import { API, CACHE, PAGINATION } from './全局配置.js';
|
| 3 |
import { requireListResponseData, getCacheWithMeta, removeCache } from '../components/性能优化工具.js';
|
| 4 |
|
| 5 |
+
import { captureCacheWrite } from './网络请求_缓存管理.js';
|
| 6 |
+
import { getResponseCacheSource } from './网络请求_基础设施.js';
|
| 7 |
+
|
| 8 |
+
const sidebarResponseSources = new WeakMap();
|
| 9 |
+
export const getSidebarResponseCacheSource = data => sidebarResponseSources.get(data) || null;
|
| 10 |
+
|
| 11 |
const itemTypes = Object.freeze({ tools: 'tool', skills: 'skill', apps: 'app', recommends: 'recommend' });
|
| 12 |
|
| 13 |
// 只读取与校验,不提交视图状态或缓存;提交时由调用方核查界面代次。
|
|
|
|
| 15 |
const options = background
|
| 16 |
? { noCache: true, timeout: API.BACKGROUND_TIMEOUT, retries: API.BACKGROUND_RETRIES }
|
| 17 |
: (force ? { noCache: true } : {});
|
| 18 |
+
const endpoint = Object.hasOwn(itemTypes, tab) ? "/api/items" : keyword ? "/api/creators/search" : "/api/creators";
|
| 19 |
+
const isCurrent = captureCacheWrite(`api_${endpoint}`);
|
| 20 |
let response;
|
| 21 |
if (Object.hasOwn(itemTypes, tab)) {
|
| 22 |
response = await api.getItems(itemTypes[tab], sort, PAGINATION.SIDEBAR_ITEM_FETCH_LIMIT, options);
|
|
|
|
| 30 |
} else {
|
| 31 |
throw new TypeError('Unsupported sidebar list');
|
| 32 |
}
|
| 33 |
+
if (!isCurrent()) {
|
| 34 |
+
const error = new Error();
|
| 35 |
+
error.name = "ListCacheChangedError";
|
| 36 |
+
throw error;
|
| 37 |
+
}
|
| 38 |
+
const source = getResponseCacheSource(response);
|
| 39 |
+
if (source && !source.source?.isAvailable()) {
|
| 40 |
+
const error = new Error();
|
| 41 |
+
error.name = "ListCacheChangedError";
|
| 42 |
+
throw error;
|
| 43 |
+
}
|
| 44 |
+
const data = requireListResponseData(response);
|
| 45 |
+
sidebarResponseSources.delete(data);
|
| 46 |
+
if (source) sidebarResponseSources.set(data, source);
|
| 47 |
+
return data;
|
| 48 |
}
|
| 49 |
|
| 50 |
function validCreatorList(data) {
|
前端页面/core/网络请求_基础设施.js
CHANGED
|
@@ -1,912 +1,946 @@
|
|
| 1 |
-
// 前端页面/core/网络请求_基础设施.js
|
| 2 |
-
// ==========================================
|
| 3 |
-
// 🌐 网络请求基础设施模块
|
| 4 |
-
// ==========================================
|
| 5 |
-
// 作用:提供底层网络请求能力,包括缓存、重试、错误处理、请求取消等
|
| 6 |
-
// 关联文件:
|
| 7 |
-
// - 全局配置.js (配置中心)
|
| 8 |
-
// - 网络请求_缓存管理.js (缓存管理)
|
| 9 |
-
// - 网络请求_图片代理.js (图片代理)
|
| 10 |
-
// ==========================================
|
| 11 |
-
|
| 12 |
-
import { removeCache, getCacheWithMeta } from "../components/性能优化工具.js";
|
| 13 |
import { API, CACHE } from "./全局配置.js";
|
| 14 |
-
import { beginLocalPerformanceSample } from "./本机性能统计.js";
|
| 15 |
-
import { eventBus, EVENTS, logoutAndClearUserData, isOnline, isCloudReachable, markCloudDown, markCloudUp } from "./状态管理.js";
|
| 16 |
-
import { CACHE_CONFIG, CACHE_INVALIDATION_MAP, invalidateRelatedCache, _getCacheTTL, getCache, setCache, isPrivateApiGet } from "./网络请求_缓存管理.js";
|
| 17 |
-
import { unproxyImages } from "./网络请求_图片代理.js";
|
| 18 |
-
// 🔧 直接引入 i18n 叶子模块(而非 用户体验增强.js):本文件处于依赖链最上游,
|
| 19 |
-
// 引入带 DOM 初始化副作用的增强层可能造成启动时序问题;国际化模块无副作用、零循环依赖
|
| 20 |
-
import { t } from "../components/用户体验_国际化.js";
|
| 21 |
-
|
| 22 |
-
// 🚀 动态时序导入:proxyImages 通过动态 import() 获取,避免模块初始化时序问题
|
| 23 |
-
let _proxyImages = null;
|
| 24 |
-
async function getProxyImages() {
|
| 25 |
-
if (!_proxyImages) {
|
| 26 |
-
const mod = await import("./网络请求_图片代理.js");
|
| 27 |
-
_proxyImages = mod.proxyImages;
|
| 28 |
-
}
|
| 29 |
-
return _proxyImages;
|
| 30 |
-
}
|
| 31 |
-
|
| 32 |
-
// 🏗️ P2架构优化:使用配置中心的 API 地址
|
| 33 |
-
const BASE_URL = API.BASE_URL;
|
| 34 |
-
|
| 35 |
-
// ⚡ P1性能优化:请求去重(相同GET请求只发一次)
|
| 36 |
-
const pendingRequests = new Map();
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
return
|
| 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 |
-
if (
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
//
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
return
|
| 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 |
-
if (
|
| 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 |
-
*/
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
}
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 283 |
async function request(endpoint, options = {}) {
|
| 284 |
const sample = beginLocalPerformanceSample(endpoint, options.method || 'GET');
|
| 285 |
try { return await performRequest(endpoint, options, sample); }
|
| 286 |
finally { sample?.finish(); }
|
| 287 |
}
|
| 288 |
|
| 289 |
-
async function performRequest(endpoint, options = {}, sample = null) {
|
| 290 |
-
const privateRead = (options.method || "GET").toUpperCase() === "GET" && isPrivateApiGet(endpoint);
|
| 291 |
-
if (privateRead) {
|
| 292 |
-
removeCache(`api_${endpoint}`);
|
| 293 |
-
options = { ...options, noStore: true };
|
| 294 |
-
}
|
| 295 |
-
// 私有详情显式不留存:同时绕过响应命中/回退/去重、插件写缓存和浏览器缓存。
|
| 296 |
-
if (options.noStore) options = { ...options, noCache: true, cache: "no-store" };
|
| 297 |
-
const url = `${BASE_URL}${endpoint}`;
|
| 298 |
-
const method = (options.method || "GET").toUpperCase();
|
| 299 |
-
const headers = { ...options.headers };
|
| 300 |
-
if (!(options.body instanceof FormData)) { headers["Content-Type"] = "application/json"; }
|
| 301 |
-
const token = _safeGetAuthToken();
|
| 302 |
-
const privateEntry = privateRead ? { revoked: false, controller: null, matches: () => token === _safeGetAuthToken() } : null;
|
| 303 |
-
const assertReadSession = () => {
|
| 304 |
-
if (privateRead && (privateEntry.revoked || !privateEntry.matches())) {
|
| 305 |
-
const error = new Error(t('auth.session_changed'));
|
| 306 |
-
error.name = 'SessionChangedError';
|
| 307 |
-
error.isCancelled = true;
|
| 308 |
-
throw error;
|
| 309 |
-
}
|
| 310 |
-
};
|
| 311 |
-
if (token) {
|
| 312 |
-
const tokenParts = token.split(".");
|
| 313 |
-
if (tokenParts.length === 3) {
|
| 314 |
-
// 标准 JWT 格式
|
| 315 |
-
headers["Authorization"] = `Bearer ${token}`;
|
| 316 |
-
} else {
|
| 317 |
-
// 🔒 P0同步:旧版 mock_token 已被后端明确拒绝(伪造后门已封堵),
|
| 318 |
-
// 以及其他无法识别的格式,统一清除本地旧凭证并提示重新登录。
|
| 319 |
-
// 🔧 修复:凭证既已清除,同步广播登出事件重置导航登录态/停止轮询,
|
| 320 |
-
// 并给用户明确提示(原实现仅 console.warn 静默清理)
|
| 321 |
-
console.warn("⚠️ 检测到无效/已过期的旧版 Token,已自动清除,请重新登录");
|
| 322 |
-
_safeClearAuthStorage();
|
| 323 |
-
window.dispatchEvent(new CustomEvent('comfy-ranking-auth-expired'));
|
| 324 |
-
notifyTokenExpired();
|
| 325 |
-
}
|
| 326 |
-
}
|
| 327 |
-
|
| 328 |
-
// 🚀 P4优化:组件级请求取消支持
|
| 329 |
-
const componentId = options.componentId || '_global';
|
| 330 |
-
|
| 331 |
-
// ⚡ P1性能优化:GET 请求缓存检查
|
| 332 |
-
// 🔑 P0修复:cacheKey 必须包含完整 endpoint(含查询参数),不能截断 '?' 之后的部分
|
| 333 |
-
// 例:'/api/items?type=tool&sort=time' 和 '/api/items?type=tool&sort=views' 必须产生不同的缓存 Key
|
| 334 |
-
const cacheKey = `api_${endpoint}`;
|
| 335 |
-
const
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 340 |
sample?.cacheHit();
|
| 341 |
-
return proxyFn(cached);
|
| 342 |
-
}
|
| 343 |
-
}
|
| 344 |
-
|
| 345 |
-
// 📴 本地兜底数据(含过期缓存)——一次读取,供下面三处复用:
|
| 346 |
-
// ① 离线/云端不可达时直接返回它;② 判定本次 GET 是否属于「后台补新」(走短预算);
|
| 347 |
-
// ③ 重试耗尽后的最终回退仍按原口径自行重读一次(期间可能有并发请求写入更新的数据)
|
| 348 |
-
const fallbackMeta = (method === "GET" && !options.noCache)
|
| 349 |
-
? getCacheWithMeta(cacheKey, true) // 忽略过期
|
| 350 |
-
: { value: null, expired: false, found: false };
|
| 351 |
-
const conditionalRead = method === "GET" && !options.noStore && options.credentials !== "include"
|
| 352 |
-
&& !Object.keys(headers).some(name => name.toLowerCase() === "authorization")
|
| 353 |
-
&& API.PUBLIC_CONDITIONAL_GET_PATHS.includes(endpoint.split(/[?#]/)[0]);
|
| 354 |
-
const conditionalMeta = conditionalRead ? getCacheWithMeta(cacheKey, true) : null;
|
| 355 |
-
if (conditionalRead) {
|
| 356 |
-
for (const name of Object.keys(headers)) if (name.toLowerCase() === "if-none-match") delete headers[name];
|
| 357 |
-
if (conditionalMeta?.found && conditionalMeta.etag) headers["If-None-Match"] = conditionalMeta.etag;
|
| 358 |
-
}
|
| 359 |
-
|
| 360 |
-
// 🚀 P3优化:离线模式支持(网络状态取自 状态管理.js 的 isOnline())
|
| 361 |
-
// ☁️ 云端不可达冷却与本机断网同等对待:两者的结论都是「这次联网注定拿不到东西」,
|
| 362 |
-
// 区别只在判据——前者看 navigator.onLine(本机网卡通不通),后者看上一次请求的
|
| 363 |
-
// 失败结论是否还在冷却期内。没有这层的话,HF Space 单独连不上时 isOnline() 恒为 true,
|
| 364 |
-
// 本分支永远不触
|
| 365 |
-
// 而全局并发额度只有 6 个,挂死的后台请求会把前台请求全部挤到排队
|
| 366 |
-
// noCache 只代表绕过该 endpoint 的响应缓存,不得绕过共享网络熔断;榜单强制刷新
|
| 367 |
-
// 仍由列表层先显示自己的缓存,冷却期内直接失败返回,避免切换榜单逐个重试 HF。
|
| 368 |
-
if (method === "GET" && (!isOnline() || !isCloudReachable())) {
|
| 369 |
-
if (fallbackMeta.found) {
|
| 370 |
-
console.log(`📴 ${isOnline() ? '☁️ 云端不可达' : '离线模式'}:返回${fallbackMeta.expired ? '过期' : ''}缓存`);
|
| 371 |
-
const
|
|
|
|
| 372 |
sample?.cacheHit();
|
| 373 |
-
return proxyFn2(fallbackMeta.value);
|
| 374 |
-
}
|
| 375 |
-
// 🔧 修复:原为硬编码中文,而本错误会被 12+ 处调用方直接 showToast(err.message) 弹给用户,
|
| 376 |
-
// 导致英文界面下仍弹中文提示;现改走词典。云端不可达与本机断网分开用词,
|
| 377 |
-
// 否则本机明明有网的用户会被「网络已断开」误导去查自己的路由器
|
| 378 |
-
throw new Error(isOnline() ? t('feedback.cloud_unreachable_no_cache') : t('feedback.offline_no_cache'));
|
| 379 |
-
}
|
| 380 |
-
|
| 381 |
-
// ⚡ P1性能优化:请求去重(相同GET请求只发一次)
|
| 382 |
-
if (trackPendingRequest) {
|
| 383 |
-
|
|
|
|
| 384 |
sample?.discard();
|
| 385 |
-
return
|
| 386 |
-
}
|
| 387 |
-
}
|
| 388 |
-
|
| 389 |
-
const fetchOptions = { ...options, method, headers };
|
| 390 |
-
|
| 391 |
-
// 🚀 核心修改:在将 body 转为 JSON 字符串发送前,执行无情剥离!
|
| 392 |
-
if (options.body && !(options.body instanceof FormData) && typeof options.body !== "string") {
|
| 393 |
-
fetchOptions.body = JSON.stringify(unproxyImages(options.body));
|
| 394 |
-
} else if (options.body instanceof FormData) {
|
| 395 |
-
fetchOptions.body = options.body;
|
| 396 |
-
}
|
| 397 |
-
|
| 398 |
-
// 🚀 P1优化:重试与超时预算
|
| 399 |
-
// 🔧 修复:重试次数/间隔此前硬编码在本文件(2 / 1000),使 全局配置.js 的
|
| 400 |
-
// API.MAX_RETRIES、API.RETRY_DELAY 成为死配置,现统一读取配置中心
|
| 401 |
-
// 🐢 弱网预算分级:列表/搜索类 GET 有本地缓存兜底,失败上限适当收紧,
|
| 402 |
-
// 避免弱网下用户长时间盯骨架屏;按去掉查询串的路径全匹配,
|
| 403 |
-
// 不会误伤 /api/items/{id}、/api/creators/{account}/details 等详情请求
|
| 404 |
-
const endpointPath = endpoint.split("?")[0];
|
| 405 |
-
let defaultTimeout = API.TIMEOUT;
|
| 406 |
-
let defaultRetries = method === "GET" ? API.MAX_RETRIES : 0; // 非 GET 不重试
|
| 407 |
-
if (method === "GET") {
|
| 408 |
-
if (endpointPath === "/api/creators/search") {
|
| 409 |
-
defaultTimeout = API.SEARCH_TIMEOUT;
|
| 410 |
-
defaultRetries = API.SEARCH_RETRIES;
|
| 411 |
-
} else if (endpointPath === "/api/items" || endpointPath === "/api/creators") {
|
| 412 |
-
defaultRetries = API.LIST_RETRIES;
|
| 413 |
-
}
|
| 414 |
-
}
|
| 415 |
-
// 🐢 后台补新短预算:本地已有该请求的缓存,说明列表视图已经把内容渲染上屏了
|
| 416 |
-
// (七大列表都是「本地数据先上屏 → 再发请求补新」),这次请求纯属后台行为,
|
| 417 |
-
// 失败要快——它每多挂 1 秒就多占 1 个并发额度(全局仅 6 个)。用 Math.min 只收不放,
|
| 418 |
-
// 不会把搜索类已经收紧过的 10s 预算又放宽回去。
|
| 419 |
-
// noCache 请求不参与:调用方明确要权威新数据(余额、安装前的资源详情、广告配置),
|
| 420 |
-
// 把它的超时砍短会把「慢但能成功」变成「快速失败」,违背调用方意图
|
| 421 |
-
const useCacheBudget = method === "GET" && !options.noCache && fallbackMeta.found;
|
| 422 |
-
if (useCacheBudget) {
|
| 423 |
-
defaultTimeout = Math.min(defaultTimeout, API.BACKGROUND_TIMEOUT);
|
| 424 |
-
defaultRetries = Math.min(defaultRetries, API.BACKGROUND_RETRIES);
|
| 425 |
-
}
|
| 426 |
-
const requestTimeout = options.timeout || defaultTimeout;
|
| 427 |
-
const maxRetries = options.retries ?? defaultRetries;
|
| 428 |
-
const retryDelay = options.retryDelay ?? API.RETRY_DELAY; // 指数退避基数
|
| 429 |
-
|
| 430 |
-
// ⚡ P1性能优化:封装请求 Promise(支持去重 + 重试)
|
| 431 |
-
if (privateEntry) activePrivateReads.add(privateEntry);
|
| 432 |
-
const requestPromise = (async () => {
|
| 433 |
-
let lastError = null;
|
| 434 |
-
// ☁️ 本次失败是否属于「网络层不可达」(超时 / 连不上),用于循环结束后决定是否打冷却。
|
| 435 |
-
// 5xx 不置位:服务端已经应答说明云端可达,若也打冷却会让一个坏接口把全站 GET 拖下水
|
| 436 |
-
let networkLevelFailure = false;
|
| 437 |
-
|
| 438 |
-
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
| 439 |
-
assertReadSession();
|
| 440 |
-
// 🚀 P1优化:指数退避延迟
|
| 441 |
-
if (attempt > 0) {
|
| 442 |
-
// ☁️ 冷却已生效就停止重试:另一个并发请求可能刚刚确证云端不可达,
|
| 443 |
-
// 继续重试只是白烧一轮超时预算、白占一个并发额度,直接跳去下方缓存兜底
|
| 444 |
-
if (method === "GET" && !isCloudReachable()) break;
|
| 445 |
-
const delay = retryDelay * Math.pow(2, attempt - 1); // 1s, 2s, 4s...
|
| 446 |
-
console.log(`🔄 请求重试 (${attempt}/${maxRetries})...`);
|
| 447 |
-
await new Promise(r => setTimeout(r, delay));
|
| 448 |
-
}
|
| 449 |
-
|
| 450 |
-
// 🚀 P4优化:使用请求取消管理器(支持超时 + 组件级取消)
|
| 451 |
-
const controller = requestCancelManager.create(componentId);
|
| 452 |
-
if (privateEntry) privateEntry.controller = controller;
|
| 453 |
-
const currentFetchOptions = { ...fetchOptions, signal: controller.signal };
|
| 454 |
-
let timeoutId = null;
|
| 455 |
-
let timedOut = false;
|
| 456 |
-
let fetchStarted = false;
|
| 457 |
-
let transportFailed = false;
|
| 458 |
-
const onTimeout = () => { timedOut = true; controller.abort(); };
|
| 459 |
-
// 已有缓存时排队也计入预算,避免被无缓存的慢请求无限拖住。
|
| 460 |
-
if (useCacheBudget) timeoutId = setTimeout(onTimeout, requestTimeout);
|
| 461 |
-
|
| 462 |
-
try {
|
| 463 |
-
const result = await requestQueue.add(async () => {
|
| 464 |
-
if (!useCacheBudget) timeoutId = setTimeout(onTimeout, requestTimeout);
|
| 465 |
-
// 请求可能在云端故障被另一个并发请求确认前进入队列;出队发出 fetch
|
| 466 |
-
// 前复查共享状态,避免队列继续逐个访问已知不可达的 HF endpoint。
|
| 467 |
-
if (method === "GET" && (!isOnline() || !isCloudReachable())) {
|
| 468 |
-
const unavailableError = new Error(
|
| 469 |
-
isOnline() ? t('feedback.cloud_unreachable_no_cache') : t('feedback.offline_no_cache')
|
| 470 |
-
);
|
| 471 |
-
unavailableError.name = 'CloudUnavailableError';
|
| 472 |
-
throw unavailableError;
|
| 473 |
-
}
|
| 474 |
-
assertReadSession();
|
| 475 |
-
fetchStarted = true;
|
| 476 |
-
try {
|
| 477 |
-
|
| 478 |
-
let
|
| 479 |
-
|
| 480 |
-
|
| 481 |
-
|
| 482 |
-
|
| 483 |
-
&&
|
| 484 |
-
&& currentMeta.
|
|
|
|
| 485 |
sample?.cacheHit();
|
| 486 |
-
validatedData = currentMeta.value;
|
| 487 |
-
} else {
|
| 488 |
-
// 缓存可能在等待期间被清理/写操作失效;同一预算内补取完整响应。
|
| 489 |
-
const fullHeaders = { ...currentFetchOptions.headers };
|
| 490 |
-
for (const name of Object.keys(fullHeaders)) if (name.toLowerCase() === "if-none-match") delete fullHeaders[name];
|
| 491 |
-
if (controller.signal.aborted) throw new DOMException('Aborted', 'AbortError');
|
| 492 |
-
|
| 493 |
-
|
| 494 |
-
|
| 495 |
-
|
| 496 |
-
|
| 497 |
-
let
|
| 498 |
-
|
| 499 |
-
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
|
| 507 |
-
|
| 508 |
-
|
| 509 |
-
|
| 510 |
-
|
| 511 |
-
|
| 512 |
-
|
| 513 |
-
|
| 514 |
-
|
| 515 |
-
|
| 516 |
-
|
| 517 |
-
|
| 518 |
-
|
| 519 |
-
|
| 520 |
-
|
| 521 |
-
|
| 522 |
-
|
| 523 |
-
|
| 524 |
-
|
| 525 |
-
|
| 526 |
-
|
| 527 |
-
|
| 528 |
-
|
| 529 |
-
|
| 530 |
-
//
|
| 531 |
-
//
|
| 532 |
-
//
|
| 533 |
-
//
|
| 534 |
-
//
|
| 535 |
-
|
| 536 |
-
|
| 537 |
-
|
| 538 |
-
|
| 539 |
-
|
| 540 |
-
error
|
| 541 |
-
|
| 542 |
-
if (
|
| 543 |
-
|
| 544 |
-
|
| 545 |
-
|
| 546 |
-
|
| 547 |
-
|
| 548 |
-
|
| 549 |
-
|
| 550 |
-
|
| 551 |
-
|
| 552 |
-
|
| 553 |
-
lastError
|
| 554 |
-
|
| 555 |
-
|
| 556 |
-
|
| 557 |
-
|
| 558 |
-
|
| 559 |
-
//
|
| 560 |
-
//
|
| 561 |
-
//
|
| 562 |
-
|
| 563 |
-
|
| 564 |
-
lastError
|
| 565 |
-
|
| 566 |
-
|
| 567 |
-
|
| 568 |
-
|
| 569 |
-
|
| 570 |
-
|
| 571 |
-
lastError
|
| 572 |
-
|
| 573 |
-
|
| 574 |
-
|
| 575 |
-
|
| 576 |
-
//
|
| 577 |
-
|
| 578 |
-
|
| 579 |
-
|
| 580 |
-
|
| 581 |
-
|
| 582 |
-
|
| 583 |
-
|
| 584 |
-
|
| 585 |
-
|
| 586 |
-
|
| 587 |
-
|
| 588 |
-
|
| 589 |
-
|
| 590 |
-
|
| 591 |
-
|
| 592 |
-
|
| 593 |
-
|
| 594 |
-
|
| 595 |
-
|
| 596 |
-
|
| 597 |
-
|
| 598 |
-
|
| 599 |
-
|
| 600 |
-
|
| 601 |
-
|
| 602 |
-
|
| 603 |
-
|
| 604 |
-
|
| 605 |
-
|
| 606 |
-
|
| 607 |
-
// 🔍
|
| 608 |
-
//
|
| 609 |
-
|
| 610 |
-
|
| 611 |
-
|
| 612 |
-
|
| 613 |
-
|
| 614 |
-
|
| 615 |
-
|
| 616 |
-
|
| 617 |
-
|
| 618 |
-
|
| 619 |
-
|
| 620 |
-
|
| 621 |
-
|
| 622 |
-
|
| 623 |
-
|
| 624 |
-
|
| 625 |
-
|
| 626 |
-
|
| 627 |
-
|
| 628 |
-
|
| 629 |
-
|
| 630 |
-
|
| 631 |
-
|
| 632 |
-
|
| 633 |
-
|
| 634 |
-
|
| 635 |
-
|
| 636 |
-
|
| 637 |
-
|
| 638 |
-
|
| 639 |
-
|
| 640 |
-
|
| 641 |
-
|
| 642 |
-
|
| 643 |
-
|
| 644 |
-
|
| 645 |
-
|
| 646 |
-
//
|
| 647 |
-
|
| 648 |
-
|
| 649 |
-
|
| 650 |
-
|
| 651 |
-
|
| 652 |
-
|
| 653 |
-
|
| 654 |
-
|
| 655 |
-
}
|
| 656 |
-
|
| 657 |
-
|
| 658 |
-
|
| 659 |
-
|
| 660 |
-
|
| 661 |
-
|
| 662 |
-
|
| 663 |
-
|
| 664 |
-
|
| 665 |
-
|
| 666 |
-
|
| 667 |
-
|
| 668 |
-
|
| 669 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 670 |
sample?.cacheHit();
|
| 671 |
-
return proxyFn4(fallback.value); // 返回过期缓存数据
|
| 672 |
-
}
|
| 673 |
-
}
|
| 674 |
-
// 仍无缓存,才抛异常
|
| 675 |
-
throw lastError || new Error(t('feedback.error'));
|
| 676 |
-
})();
|
| 677 |
-
|
| 678 |
-
if (privateEntry) requestPromise.finally(() => activePrivateReads.delete(privateEntry)).catch(() => {});
|
| 679 |
-
|
| 680 |
-
|
| 681 |
-
|
| 682 |
-
|
| 683 |
-
|
| 684 |
-
|
| 685 |
-
|
| 686 |
-
|
| 687 |
-
//
|
| 688 |
-
|
| 689 |
-
|
| 690 |
-
|
| 691 |
-
|
| 692 |
-
|
| 693 |
-
|
| 694 |
-
|
| 695 |
-
|
| 696 |
-
|
| 697 |
-
|
| 698 |
-
|
| 699 |
-
|
| 700 |
-
|
| 701 |
-
|
| 702 |
-
|
| 703 |
-
|
| 704 |
-
|
| 705 |
-
|
| 706 |
-
|
| 707 |
-
|
| 708 |
-
|
| 709 |
-
|
| 710 |
-
|
| 711 |
-
|
| 712 |
-
|
| 713 |
-
|
| 714 |
-
|
| 715 |
-
|
| 716 |
-
|
| 717 |
-
|
| 718 |
-
|
| 719 |
-
//
|
| 720 |
-
const
|
| 721 |
-
const
|
| 722 |
-
|
| 723 |
-
|
| 724 |
-
|
| 725 |
-
|
| 726 |
-
|
| 727 |
-
|
| 728 |
-
|
| 729 |
-
|
| 730 |
-
|
| 731 |
-
|
| 732 |
-
|
| 733 |
-
|
| 734 |
-
|
| 735 |
-
|
| 736 |
-
|
| 737 |
-
|
| 738 |
-
|
| 739 |
-
|
| 740 |
-
|
| 741 |
-
|
| 742 |
-
|
| 743 |
-
|
| 744 |
-
|
| 745 |
-
|
| 746 |
-
|
| 747 |
-
|
| 748 |
-
|
| 749 |
-
|
| 750 |
-
|
| 751 |
-
|
| 752 |
-
|
| 753 |
-
|
| 754 |
-
|
| 755 |
-
|
| 756 |
-
|
| 757 |
-
|
| 758 |
-
|
| 759 |
-
|
| 760 |
-
|
| 761 |
-
|
| 762 |
-
|
| 763 |
-
|
| 764 |
-
|
| 765 |
-
|
| 766 |
-
|
| 767 |
-
|
| 768 |
-
|
| 769 |
-
|
| 770 |
-
|
| 771 |
-
|
| 772 |
-
|
| 773 |
-
|
| 774 |
-
|
| 775 |
-
|
| 776 |
-
|
| 777 |
-
|
| 778 |
-
|
| 779 |
-
|
| 780 |
-
|
| 781 |
-
|
| 782 |
-
|
| 783 |
-
lineParts
|
| 784 |
-
|
| 785 |
-
|
| 786 |
-
|
| 787 |
-
|
| 788 |
-
|
| 789 |
-
|
| 790 |
-
|
| 791 |
-
|
| 792 |
-
|
| 793 |
-
|
| 794 |
-
|
| 795 |
-
if (
|
| 796 |
-
|
| 797 |
-
|
| 798 |
-
|
| 799 |
-
|
| 800 |
-
|
| 801 |
-
|
| 802 |
-
|
| 803 |
-
|
| 804 |
-
|
| 805 |
-
|
| 806 |
-
|
| 807 |
-
|
| 808 |
-
|
| 809 |
-
|
| 810 |
-
|
| 811 |
-
|
| 812 |
-
|
| 813 |
-
|
| 814 |
-
|
| 815 |
-
if (!
|
| 816 |
-
|
| 817 |
-
|
| 818 |
-
|
| 819 |
-
|
| 820 |
-
|
| 821 |
-
|
| 822 |
-
|
| 823 |
-
|
| 824 |
-
|
| 825 |
-
|
| 826 |
-
}
|
| 827 |
-
|
| 828 |
-
|
| 829 |
-
|
| 830 |
-
|
| 831 |
-
|
| 832 |
-
|
| 833 |
-
|
| 834 |
-
|
| 835 |
-
|
| 836 |
-
|
| 837 |
-
|
| 838 |
-
|
| 839 |
-
|
| 840 |
-
|
| 841 |
-
|
| 842 |
-
|
| 843 |
-
processSSELine(takeLine());
|
| 844 |
-
|
| 845 |
-
|
| 846 |
-
|
| 847 |
-
|
| 848 |
-
|
| 849 |
-
|
| 850 |
-
|
| 851 |
-
|
| 852 |
-
|
| 853 |
-
|
| 854 |
-
|
| 855 |
-
|
| 856 |
-
|
| 857 |
-
|
| 858 |
-
}
|
| 859 |
-
|
| 860 |
-
|
| 861 |
-
|
| 862 |
-
|
| 863 |
-
|
| 864 |
-
|
| 865 |
-
|
| 866 |
-
|
| 867 |
-
|
| 868 |
-
|
| 869 |
-
|
| 870 |
-
|
| 871 |
-
|
| 872 |
-
|
| 873 |
-
|
| 874 |
-
|
| 875 |
-
|
| 876 |
-
|
| 877 |
-
|
| 878 |
-
|
| 879 |
-
|
| 880 |
-
|
| 881 |
-
|
| 882 |
-
|
| 883 |
-
|
| 884 |
-
|
| 885 |
-
|
| 886 |
-
|
| 887 |
-
|
| 888 |
-
|
| 889 |
-
|
| 890 |
-
|
| 891 |
-
|
| 892 |
-
|
| 893 |
-
|
| 894 |
-
|
| 895 |
-
|
| 896 |
-
|
| 897 |
-
|
| 898 |
-
|
| 899 |
-
|
| 900 |
-
|
| 901 |
-
|
| 902 |
-
|
| 903 |
-
|
| 904 |
-
|
| 905 |
-
|
| 906 |
-
|
| 907 |
-
|
| 908 |
-
|
| 909 |
-
|
| 910 |
-
|
| 911 |
-
|
| 912 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// 前端页面/core/网络请求_基础设施.js
|
| 2 |
+
// ==========================================
|
| 3 |
+
// 🌐 网络请求基础设施模块
|
| 4 |
+
// ==========================================
|
| 5 |
+
// 作用:提供底层网络请求能力,包括缓存、重试、错误处理、请求取消等
|
| 6 |
+
// 关联文件:
|
| 7 |
+
// - 全局配置.js (配置中心)
|
| 8 |
+
// - 网络请求_缓存管理.js (缓存管理)
|
| 9 |
+
// - 网络请求_图片代理.js (图片代理)
|
| 10 |
+
// ==========================================
|
| 11 |
+
|
| 12 |
+
import { removeCache, getCacheWithMeta } from "../components/性能优化工具.js";
|
| 13 |
import { API, CACHE } from "./全局配置.js";
|
| 14 |
+
import { beginLocalPerformanceSample } from "./本机性能统计.js";
|
| 15 |
+
import { eventBus, EVENTS, logoutAndClearUserData, isOnline, isCloudReachable, markCloudDown, markCloudUp } from "./状态管理.js";
|
| 16 |
+
import { CACHE_CONFIG, CACHE_INVALIDATION_MAP, invalidateRelatedCache, _getCacheTTL, getCache, setCache, isPrivateApiGet, captureCacheWrite, captureCacheSource } from "./网络请求_缓存管理.js";
|
| 17 |
+
import { unproxyImages } from "./网络请求_图片代理.js";
|
| 18 |
+
// 🔧 直接引入 i18n 叶子模块(而非 用户体验增强.js):本文件处于依赖链最上游,
|
| 19 |
+
// 引入带 DOM 初始化副作用的增强层可能造成启动时序问题;国际化模块无副作用、零循环依赖
|
| 20 |
+
import { t } from "../components/用户体验_国际化.js";
|
| 21 |
+
|
| 22 |
+
// 🚀 动态时序导入:proxyImages 通过动态 import() 获取,避免模块初始化时序问题
|
| 23 |
+
let _proxyImages = null;
|
| 24 |
+
async function getProxyImages() {
|
| 25 |
+
if (!_proxyImages) {
|
| 26 |
+
const mod = await import("./网络请求_图片代理.js");
|
| 27 |
+
_proxyImages = mod.proxyImages;
|
| 28 |
+
}
|
| 29 |
+
return _proxyImages;
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
// 🏗️ P2架构优化:使用配置中心的 API 地址
|
| 33 |
+
const BASE_URL = API.BASE_URL;
|
| 34 |
+
|
| 35 |
+
// ⚡ P1性能优化:请求去重(相同GET请求只发一次)
|
| 36 |
+
const pendingRequests = new Map();
|
| 37 |
+
const cacheReadOwners = new Map();
|
| 38 |
+
const pendingRequestGuards = new WeakMap();
|
| 39 |
+
const responseCacheSources = new WeakMap();
|
| 40 |
+
|
| 41 |
+
function _cachedResponse(value, source) {
|
| 42 |
+
if (value && typeof value === 'object') responseCacheSources.set(value, { source });
|
| 43 |
+
return value;
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
export function getResponseCacheSource(value) {
|
| 47 |
+
return responseCacheSources.get(value) || null;
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
function withRequestDiagnostic(error, response, data = null) {
|
| 52 |
+
let headerId;
|
| 53 |
+
try { headerId = response.headers?.get?.(API.REQUEST_ID_HEADER); } catch {}
|
| 54 |
+
for (const value of [headerId, data?.error_id]) {
|
| 55 |
+
if (typeof value === 'string' && API.REQUEST_ID_PATTERN.test(value)) {
|
| 56 |
+
error.requestId = value;
|
| 57 |
+
break;
|
| 58 |
+
}
|
| 59 |
+
}
|
| 60 |
+
return error;
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
function httpErrorMessage(data, status) {
|
| 64 |
+
if (typeof data.detail === 'string' && Object.hasOwn(API.REQUEST_BODY_ERRORS, data.detail)) {
|
| 65 |
+
const rule = API.REQUEST_BODY_ERRORS[data.detail];
|
| 66 |
+
if (rule.status === status) return t(rule.msgKey);
|
| 67 |
+
}
|
| 68 |
+
if (Array.isArray(data.detail)) return t('feedback.invalid_request_data');
|
| 69 |
+
for (const value of [data.detail, data.message, data.error]) {
|
| 70 |
+
if (typeof value === 'string' && value.trim()) return value;
|
| 71 |
+
}
|
| 72 |
+
return t('feedback.http_request_failed', { status });
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
// 🚀 P3优化:网络状态由 状态管理.js 的 isOnline() 统一提供(见下方离线模式支持),
|
| 76 |
+
// 本模块不再自行注册 online/offline 监听。
|
| 77 |
+
|
| 78 |
+
// 🔧 修复:401(Token 过期/签名无效)统一处理——清除本地凭证并提示重新登录。
|
| 79 |
+
// 背景:服务端更换 JWT_SECRET 或 Token 过期后,旧 Token 被云端拒签,若不清除
|
| 80 |
+
// 本地凭证会导致所有登录态操作反复报「Token 签名无效」。去重窗口:并发请求
|
| 81 |
+
// 同时收到 401 时只提示一次。
|
| 82 |
+
let _authExpiredAt = 0;
|
| 83 |
+
function _safeStorageGet(storageName, key) {
|
| 84 |
+
try {
|
| 85 |
+
const storage = window[storageName];
|
| 86 |
+
return storage ? storage.getItem(key) : null;
|
| 87 |
+
} catch (_) {
|
| 88 |
+
return null;
|
| 89 |
+
}
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
function _safeGetAuthToken() {
|
| 93 |
+
return _safeStorageGet('localStorage', 'ComfyCommunity_Token')
|
| 94 |
+
|| _safeStorageGet('sessionStorage', 'ComfyCommunity_Token')
|
| 95 |
+
|| '';
|
| 96 |
+
}
|
| 97 |
+
|
| 98 |
+
/** 与实际 Authorization 使用同一存储读取;仅返回比较函数,不暴露凭证。 */
|
| 99 |
+
export function captureRequestSession() {
|
| 100 |
+
const originalToken = _safeGetAuthToken();
|
| 101 |
+
return () => originalToken === _safeGetAuthToken();
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
// 仅跟踪私有 GET;会话撤销不取消或重放已提交的业务写操作。
|
| 105 |
+
const activePrivateReads = new Set();
|
| 106 |
+
function revokePrivateReads(force = false) {
|
| 107 |
+
for (const entry of activePrivateReads) {
|
| 108 |
+
if (force || !entry.matches()) {
|
| 109 |
+
entry.revoked = true;
|
| 110 |
+
entry.controller?.abort();
|
| 111 |
+
}
|
| 112 |
+
}
|
| 113 |
+
}
|
| 114 |
+
for (const event of ['comfy-user-login', 'comfy-user-logout', 'comfy-ranking-auth-expired']) {
|
| 115 |
+
window.addEventListener(event, () => revokePrivateReads(true));
|
| 116 |
+
}
|
| 117 |
+
window.addEventListener('storage', event => {
|
| 118 |
+
if (event.key === null || event.key === CACHE.LEGACY_KEYS.USER) revokePrivateReads(true);
|
| 119 |
+
else if (event.key === CACHE.LEGACY_KEYS.TOKEN) revokePrivateReads();
|
| 120 |
+
});
|
| 121 |
+
eventBus.on(EVENTS.USER_LOGIN, () => revokePrivateReads(true));
|
| 122 |
+
eventBus.on(EVENTS.USER_LOGOUT, () => revokePrivateReads(true));
|
| 123 |
+
|
| 124 |
+
function _safeClearAuthStorage() {
|
| 125 |
+
for (const storageName of ['localStorage', 'sessionStorage']) {
|
| 126 |
+
try {
|
| 127 |
+
const storage = window[storageName];
|
| 128 |
+
storage?.removeItem('ComfyCommunity_Token');
|
| 129 |
+
storage?.removeItem('ComfyCommunity_User');
|
| 130 |
+
} catch (_) {
|
| 131 |
+
// 浏览器禁用 Storage 时仍继续完成内存登出和事件通知。
|
| 132 |
+
}
|
| 133 |
+
}
|
| 134 |
+
}
|
| 135 |
+
|
| 136 |
+
function notifyTokenExpired() {
|
| 137 |
+
const now = Date.now();
|
| 138 |
+
if (now - _authExpiredAt < 5000) return;
|
| 139 |
+
_authExpiredAt = now;
|
| 140 |
+
console.warn("⚠️ 登录凭证已失效,本地凭证已清除,请重新登录");
|
| 141 |
+
// 动态 import UI 组件,与 proxyImages 同样避免模块初始化时序问题
|
| 142 |
+
import("../components/UI交互提示组件.js").then(async ({ showToast }) => {
|
| 143 |
+
const { t } = await import("../components/用户体验_国际化.js");
|
| 144 |
+
showToast(t('auth.token_expired'), "warning", 4000);
|
| 145 |
+
}).catch(() => {});
|
| 146 |
+
}
|
| 147 |
+
|
| 148 |
+
function handleAuthExpired(failedToken) {
|
| 149 |
+
// 竞态防护:若用户在 401 返回前已重新登录(存储中的 Token 已更换),
|
| 150 |
+
// 不清理新凭证;失败请求未携带 Token 时 401 与登录态无关,同样不打扰
|
| 151 |
+
if (!failedToken) return false;
|
| 152 |
+
const currentToken = _safeGetAuthToken();
|
| 153 |
+
if (currentToken !== failedToken) return false;
|
| 154 |
+
// 清除前取出账号,用于清理账号级 Profile 缓存
|
| 155 |
+
let account = null;
|
| 156 |
+
try {
|
| 157 |
+
const userStr = _safeStorageGet('localStorage', "ComfyCommunity_User")
|
| 158 |
+
|| _safeStorageGet('sessionStorage', "ComfyCommunity_User");
|
| 159 |
+
if (userStr) account = JSON.parse(userStr)?.user?.account || null;
|
| 160 |
+
} catch (e) {}
|
| 161 |
+
// 与手动登出同深度的完整清理:Token/User、私有数据缓存、内存缓存与安装版本戳
|
| 162 |
+
logoutAndClearUserData(account);
|
| 163 |
+
notifyTokenExpired();
|
| 164 |
+
return true;
|
| 165 |
+
}
|
| 166 |
+
|
| 167 |
+
// 🚀 P4优化:请求取消管理器
|
| 168 |
+
const requestCancelManager = {
|
| 169 |
+
_controllers: new Map(), // {componentId: Set<AbortController>}
|
| 170 |
+
|
| 171 |
+
/**
|
| 172 |
+
* 创建并注册 AbortController
|
| 173 |
+
* @param {string} componentId - 组件 ID
|
| 174 |
+
* @returns {AbortController}
|
| 175 |
+
*/
|
| 176 |
+
create(componentId = '_global') {
|
| 177 |
+
if (!this._controllers.has(componentId)) {
|
| 178 |
+
this._controllers.set(componentId, new Set());
|
| 179 |
+
}
|
| 180 |
+
const controller = new AbortController();
|
| 181 |
+
this._controllers.get(componentId).add(controller);
|
| 182 |
+
return controller;
|
| 183 |
+
},
|
| 184 |
+
|
| 185 |
+
/**
|
| 186 |
+
* 移除已完成的 controller
|
| 187 |
+
*/
|
| 188 |
+
remove(componentId, controller) {
|
| 189 |
+
const controllers = this._controllers.get(componentId);
|
| 190 |
+
if (controllers) {
|
| 191 |
+
controllers.delete(controller);
|
| 192 |
+
}
|
| 193 |
+
},
|
| 194 |
+
|
| 195 |
+
/**
|
| 196 |
+
* 取消指定组件的所有请求
|
| 197 |
+
* @param {string} componentId - 组件 ID
|
| 198 |
+
*/
|
| 199 |
+
cancelAll(componentId) {
|
| 200 |
+
const controllers = this._controllers.get(componentId);
|
| 201 |
+
if (controllers) {
|
| 202 |
+
const count = controllers.size;
|
| 203 |
+
for (const controller of controllers) {
|
| 204 |
+
controller.abort();
|
| 205 |
+
}
|
| 206 |
+
controllers.clear();
|
| 207 |
+
// 🔧 仅在实际撤销了请求时打日志:本方法会被搜索框的每一次输入触发,
|
| 208 |
+
// 绝大多数时候并没有在途请求,无条件打印会刷出大量无意义日志
|
| 209 |
+
if (count > 0) {
|
| 210 |
+
console.log(`🚫 已取消组件 [${componentId}] 的 ${count} 个在途请求`);
|
| 211 |
+
}
|
| 212 |
+
}
|
| 213 |
+
},
|
| 214 |
+
|
| 215 |
+
/**
|
| 216 |
+
* 取消所有请求
|
| 217 |
+
*/
|
| 218 |
+
cancelAllGlobal() {
|
| 219 |
+
for (const [componentId, controllers] of this._controllers) {
|
| 220 |
+
for (const controller of controllers) {
|
| 221 |
+
controller.abort();
|
| 222 |
+
}
|
| 223 |
+
controllers.clear();
|
| 224 |
+
}
|
| 225 |
+
console.log('🚫 已取消所有进行中的请求');
|
| 226 |
+
},
|
| 227 |
+
|
| 228 |
+
/**
|
| 229 |
+
* 获取统计信息
|
| 230 |
+
*/
|
| 231 |
+
getStats() {
|
| 232 |
+
let total = 0;
|
| 233 |
+
for (const controllers of this._controllers.values()) {
|
| 234 |
+
total += controllers.size;
|
| 235 |
+
}
|
| 236 |
+
return { components: this._controllers.size, activeRequests: total };
|
| 237 |
+
}
|
| 238 |
+
};
|
| 239 |
+
|
| 240 |
+
// 🚀 P3优化:请求队列管理(限制并发数)
|
| 241 |
+
const requestQueue = {
|
| 242 |
+
maxConcurrent: 6, // 浏览器同域名默认限制 6 个并发
|
| 243 |
+
running: 0,
|
| 244 |
+
pending: [],
|
| 245 |
+
|
| 246 |
+
async add(fn, signal) {
|
| 247 |
+
signal.throwIfAborted();
|
| 248 |
+
// 如果还有槽位,直接执行
|
| 249 |
+
if (this.running < this.maxConcurrent) {
|
| 250 |
+
this.running++;
|
| 251 |
+
try {
|
| 252 |
+
return await fn();
|
| 253 |
+
} finally {
|
| 254 |
+
this.running--;
|
| 255 |
+
this._processNext();
|
| 256 |
+
}
|
| 257 |
+
}
|
| 258 |
+
|
| 259 |
+
// 否则加入队列等待
|
| 260 |
+
return new Promise((resolve, reject) => {
|
| 261 |
+
const onAbort = () => {
|
| 262 |
+
const index = this.pending.indexOf(run);
|
| 263 |
+
if (index !== -1) this.pending.splice(index, 1);
|
| 264 |
+
reject(signal.reason);
|
| 265 |
+
};
|
| 266 |
+
const run = async () => {
|
| 267 |
+
signal.removeEventListener('abort', onAbort);
|
| 268 |
+
try {
|
| 269 |
+
signal.throwIfAborted();
|
| 270 |
+
resolve(await fn());
|
| 271 |
+
} catch (e) {
|
| 272 |
+
reject(e);
|
| 273 |
+
}
|
| 274 |
+
};
|
| 275 |
+
this.pending.push(run);
|
| 276 |
+
signal.addEventListener('abort', onAbort, { once: true });
|
| 277 |
+
});
|
| 278 |
+
},
|
| 279 |
+
|
| 280 |
+
_processNext() {
|
| 281 |
+
if (this.pending.length > 0 && this.running < this.maxConcurrent) {
|
| 282 |
+
const next = this.pending.shift();
|
| 283 |
+
this.running++;
|
| 284 |
+
next().finally(() => {
|
| 285 |
+
this.running--;
|
| 286 |
+
this._processNext();
|
| 287 |
+
});
|
| 288 |
+
}
|
| 289 |
+
},
|
| 290 |
+
|
| 291 |
+
getStats() {
|
| 292 |
+
return { running: this.running, pending: this.pending.length };
|
| 293 |
+
}
|
| 294 |
+
};
|
| 295 |
+
|
| 296 |
async function request(endpoint, options = {}) {
|
| 297 |
const sample = beginLocalPerformanceSample(endpoint, options.method || 'GET');
|
| 298 |
try { return await performRequest(endpoint, options, sample); }
|
| 299 |
finally { sample?.finish(); }
|
| 300 |
}
|
| 301 |
|
| 302 |
+
async function performRequest(endpoint, options = {}, sample = null) {
|
| 303 |
+
const privateRead = (options.method || "GET").toUpperCase() === "GET" && isPrivateApiGet(endpoint);
|
| 304 |
+
if (privateRead) {
|
| 305 |
+
removeCache(`api_${endpoint}`);
|
| 306 |
+
options = { ...options, noStore: true };
|
| 307 |
+
}
|
| 308 |
+
// 私有详情显式不留存:同时绕过响应命中/回退/去重、插件写缓存和浏览器缓存。
|
| 309 |
+
if (options.noStore) options = { ...options, noCache: true, cache: "no-store" };
|
| 310 |
+
const url = `${BASE_URL}${endpoint}`;
|
| 311 |
+
const method = (options.method || "GET").toUpperCase();
|
| 312 |
+
const headers = { ...options.headers };
|
| 313 |
+
if (!(options.body instanceof FormData)) { headers["Content-Type"] = "application/json"; }
|
| 314 |
+
const token = _safeGetAuthToken();
|
| 315 |
+
const privateEntry = privateRead ? { revoked: false, controller: null, matches: () => token === _safeGetAuthToken() } : null;
|
| 316 |
+
const assertReadSession = () => {
|
| 317 |
+
if (privateRead && (privateEntry.revoked || !privateEntry.matches())) {
|
| 318 |
+
const error = new Error(t('auth.session_changed'));
|
| 319 |
+
error.name = 'SessionChangedError';
|
| 320 |
+
error.isCancelled = true;
|
| 321 |
+
throw error;
|
| 322 |
+
}
|
| 323 |
+
};
|
| 324 |
+
if (token) {
|
| 325 |
+
const tokenParts = token.split(".");
|
| 326 |
+
if (tokenParts.length === 3) {
|
| 327 |
+
// 标准 JWT 格式
|
| 328 |
+
headers["Authorization"] = `Bearer ${token}`;
|
| 329 |
+
} else {
|
| 330 |
+
// 🔒 P0同步:旧版 mock_token 已被后端明确拒绝(伪造后门已封堵),
|
| 331 |
+
// 以及其他无法识别的格式,统一清除本地旧凭证并提示重新登录。
|
| 332 |
+
// 🔧 修复:凭证既已清除,同步广播登出事件重置导航登录态/停止轮询,
|
| 333 |
+
// 并给用户明确提示(原实现仅 console.warn 静默清理)
|
| 334 |
+
console.warn("⚠️ 检测到无效/已过期的旧版 Token,已自动清除,请重新登录");
|
| 335 |
+
_safeClearAuthStorage();
|
| 336 |
+
window.dispatchEvent(new CustomEvent('comfy-ranking-auth-expired'));
|
| 337 |
+
notifyTokenExpired();
|
| 338 |
+
}
|
| 339 |
+
}
|
| 340 |
+
|
| 341 |
+
// 🚀 P4优化:组件级请求取消支持
|
| 342 |
+
const componentId = options.componentId || '_global';
|
| 343 |
+
|
| 344 |
+
// ⚡ P1性能优化:GET 请求缓存检查
|
| 345 |
+
// 🔑 P0修复:cacheKey 必须包含完整 endpoint(含查询参数),不能截断 '?' 之后的部分
|
| 346 |
+
// 例:'/api/items?type=tool&sort=time' 和 '/api/items?type=tool&sort=views' 必须产生不同的缓存 Key
|
| 347 |
+
const cacheKey = `api_${endpoint}`;
|
| 348 |
+
const isRequestCacheCurrent = method === "GET" && !options.noStore ? captureCacheWrite(cacheKey) : null;
|
| 349 |
+
let isCacheWriteCurrent = isRequestCacheCurrent;
|
| 350 |
+
const trackPendingRequest = method === "GET" && !options.noCache;
|
| 351 |
+
const trackCacheOwner = method === "GET" && !options.noStore;
|
| 352 |
+
if (method === "GET" && !options.noCache) {
|
| 353 |
+
const cached = getCache(cacheKey);
|
| 354 |
+
if (cached) {
|
| 355 |
+
const source = captureCacheSource(cacheKey);
|
| 356 |
+
const proxyFn = await getProxyImages();
|
| 357 |
sample?.cacheHit();
|
| 358 |
+
return _cachedResponse(proxyFn(cached), source);
|
| 359 |
+
}
|
| 360 |
+
}
|
| 361 |
+
|
| 362 |
+
// 📴 本地兜底数据(含过期缓存)——一次读取,供下面三处复用:
|
| 363 |
+
// ① 离线/云端不可达时直接返回它;② 判定本次 GET 是否属于「后台补新」(走短预算);
|
| 364 |
+
// ③ 重试耗尽后的最终回退仍按原口径自行重读一次(期间可能有并发请求写入更新的数据)
|
| 365 |
+
const fallbackMeta = (method === "GET" && !options.noCache)
|
| 366 |
+
? getCacheWithMeta(cacheKey, true) // 忽略过期
|
| 367 |
+
: { value: null, expired: false, found: false };
|
| 368 |
+
const conditionalRead = method === "GET" && !options.noStore && options.credentials !== "include"
|
| 369 |
+
&& !Object.keys(headers).some(name => name.toLowerCase() === "authorization")
|
| 370 |
+
&& API.PUBLIC_CONDITIONAL_GET_PATHS.includes(endpoint.split(/[?#]/)[0]);
|
| 371 |
+
const conditionalMeta = conditionalRead ? getCacheWithMeta(cacheKey, true) : null;
|
| 372 |
+
if (conditionalRead) {
|
| 373 |
+
for (const name of Object.keys(headers)) if (name.toLowerCase() === "if-none-match") delete headers[name];
|
| 374 |
+
if (conditionalMeta?.found && conditionalMeta.etag) headers["If-None-Match"] = conditionalMeta.etag;
|
| 375 |
+
}
|
| 376 |
+
|
| 377 |
+
// 🚀 P3优化:离线模式支持(网络状态取自 状态管理.js 的 isOnline())
|
| 378 |
+
// ☁️ 云端不可达冷却与本机断网同等对待:两者的结论都是「这次联网注定拿不到东西」,
|
| 379 |
+
// 区别只在判据——前者看 navigator.onLine(本机网卡通不通),后者看上一次请求的
|
| 380 |
+
// 失败结论是否还在冷却期内。没有这层的话,HF Space 单独连不上时 isOnline() 恒为 true,
|
| 381 |
+
// 本分支永远不触发,于是每个界面、每轮 30 秒的消息轮询都要各自烧满 61~93 秒重试预算,
|
| 382 |
+
// 而全局并发额度只有 6 个,挂死的后台请求会把前台请求全部挤到排队
|
| 383 |
+
// noCache 只代表绕过该 endpoint 的响应缓存,不得绕过共享网络熔断;榜单强制刷新
|
| 384 |
+
// 仍由列表层先显示自己的缓存,冷却期内直接失败返回,避免切换榜单逐个重试 HF。
|
| 385 |
+
if (method === "GET" && (!isOnline() || !isCloudReachable())) {
|
| 386 |
+
if (fallbackMeta.found) {
|
| 387 |
+
console.log(`📴 ${isOnline() ? '☁️ 云端不可达' : '离线模式'}:返回${fallbackMeta.expired ? '过期' : ''}缓存`);
|
| 388 |
+
const source = captureCacheSource(cacheKey);
|
| 389 |
+
const proxyFn2 = await getProxyImages();
|
| 390 |
sample?.cacheHit();
|
| 391 |
+
return _cachedResponse(proxyFn2(fallbackMeta.value), source);
|
| 392 |
+
}
|
| 393 |
+
// 🔧 修复:原为硬编码中文,而本错误会被 12+ 处调用方直接 showToast(err.message) 弹给用户,
|
| 394 |
+
// 导致英文界面下仍弹中文提示;现改走词典。云端不可达与本机断网分开用词,
|
| 395 |
+
// 否则本机明明有网的用户会被「网络已断开」误导去查自己的路由器
|
| 396 |
+
throw new Error(isOnline() ? t('feedback.cloud_unreachable_no_cache') : t('feedback.offline_no_cache'));
|
| 397 |
+
}
|
| 398 |
+
|
| 399 |
+
// ⚡ P1性能优化:请求去重(相同GET请求只发一次)
|
| 400 |
+
if (trackPendingRequest) {
|
| 401 |
+
const pending = pendingRequests.get(cacheKey);
|
| 402 |
+
if (pending && pendingRequestGuards.get(pending)?.() && cacheReadOwners.get(cacheKey) === pending) {
|
| 403 |
sample?.discard();
|
| 404 |
+
return pending;
|
| 405 |
+
}
|
| 406 |
+
}
|
| 407 |
+
|
| 408 |
+
const fetchOptions = { ...options, method, headers };
|
| 409 |
+
|
| 410 |
+
// 🚀 核心修改:在将 body 转为 JSON 字符串发送前,执行无情剥离!
|
| 411 |
+
if (options.body && !(options.body instanceof FormData) && typeof options.body !== "string") {
|
| 412 |
+
fetchOptions.body = JSON.stringify(unproxyImages(options.body));
|
| 413 |
+
} else if (options.body instanceof FormData) {
|
| 414 |
+
fetchOptions.body = options.body;
|
| 415 |
+
}
|
| 416 |
+
|
| 417 |
+
// 🚀 P1优化:重试与超时预算
|
| 418 |
+
// 🔧 修复:重试次数/间隔此前硬编码在本文件(2 / 1000),使 全局配置.js 的
|
| 419 |
+
// API.MAX_RETRIES、API.RETRY_DELAY 成为死配置,现统一读取配置中心
|
| 420 |
+
// 🐢 弱网预算分级:列表/搜索类 GET 有本地缓存兜底,失败上限适当收紧,
|
| 421 |
+
// 避免弱网下用户长时间盯骨架屏;按去掉查询串的路径全匹配,
|
| 422 |
+
// 不会误伤 /api/items/{id}、/api/creators/{account}/details 等详情请求
|
| 423 |
+
const endpointPath = endpoint.split("?")[0];
|
| 424 |
+
let defaultTimeout = API.TIMEOUT;
|
| 425 |
+
let defaultRetries = method === "GET" ? API.MAX_RETRIES : 0; // 非 GET 不重试
|
| 426 |
+
if (method === "GET") {
|
| 427 |
+
if (endpointPath === "/api/creators/search") {
|
| 428 |
+
defaultTimeout = API.SEARCH_TIMEOUT;
|
| 429 |
+
defaultRetries = API.SEARCH_RETRIES;
|
| 430 |
+
} else if (endpointPath === "/api/items" || endpointPath === "/api/creators") {
|
| 431 |
+
defaultRetries = API.LIST_RETRIES;
|
| 432 |
+
}
|
| 433 |
+
}
|
| 434 |
+
// 🐢 后台补新短预算:本地已有该请求的缓存,说明列表视图已经把内容渲染上屏了
|
| 435 |
+
// (七大列表都是「本地数据先上屏 → 再发请求补新」),这次请求纯属后台行为,
|
| 436 |
+
// 失败要快——它每多挂 1 秒就多占 1 个并发额度(全局仅 6 个)。用 Math.min 只收不放,
|
| 437 |
+
// 不会把搜索类已经收紧过的 10s 预算又放宽回去。
|
| 438 |
+
// noCache 请求不参与:调用方明确要权威新数据(余额、安装前的资源详情、广告配置),
|
| 439 |
+
// 把它的超时砍短会把「慢但能成功」变成「快速失败」,违背调用方意图
|
| 440 |
+
const useCacheBudget = method === "GET" && !options.noCache && fallbackMeta.found;
|
| 441 |
+
if (useCacheBudget) {
|
| 442 |
+
defaultTimeout = Math.min(defaultTimeout, API.BACKGROUND_TIMEOUT);
|
| 443 |
+
defaultRetries = Math.min(defaultRetries, API.BACKGROUND_RETRIES);
|
| 444 |
+
}
|
| 445 |
+
const requestTimeout = options.timeout || defaultTimeout;
|
| 446 |
+
const maxRetries = options.retries ?? defaultRetries;
|
| 447 |
+
const retryDelay = options.retryDelay ?? API.RETRY_DELAY; // 指数退避基数
|
| 448 |
+
|
| 449 |
+
// ⚡ P1性能优化:封装请求 Promise(支持去重 + 重试)
|
| 450 |
+
if (privateEntry) activePrivateReads.add(privateEntry);
|
| 451 |
+
const requestPromise = (async () => {
|
| 452 |
+
let lastError = null;
|
| 453 |
+
// ☁️ 本次失败是否属于「网络层不可达」(超时 / 连不上),用于循环结束后决定是否打冷却。
|
| 454 |
+
// 5xx 不置位:服务端已经应答说明云端可达,若也打冷却会让一个坏接口把全站 GET 拖下水
|
| 455 |
+
let networkLevelFailure = false;
|
| 456 |
+
|
| 457 |
+
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
| 458 |
+
assertReadSession();
|
| 459 |
+
// 🚀 P1优化:指数退避延迟
|
| 460 |
+
if (attempt > 0) {
|
| 461 |
+
// ☁️ 冷却已生效就停止重试:另一个并发请求可能刚刚确证云端不可达,
|
| 462 |
+
// 继续重试只是白烧一轮超时预算、白占一个并发额度,直接跳去下方缓存兜底
|
| 463 |
+
if (method === "GET" && !isCloudReachable()) break;
|
| 464 |
+
const delay = retryDelay * Math.pow(2, attempt - 1); // 1s, 2s, 4s...
|
| 465 |
+
console.log(`🔄 请求重试 (${attempt}/${maxRetries})...`);
|
| 466 |
+
await new Promise(r => setTimeout(r, delay));
|
| 467 |
+
}
|
| 468 |
+
|
| 469 |
+
// 🚀 P4优化:使用请求取消管理器(支持超时 + 组件级取消)
|
| 470 |
+
const controller = requestCancelManager.create(componentId);
|
| 471 |
+
if (privateEntry) privateEntry.controller = controller;
|
| 472 |
+
const currentFetchOptions = { ...fetchOptions, signal: controller.signal };
|
| 473 |
+
let timeoutId = null;
|
| 474 |
+
let timedOut = false;
|
| 475 |
+
let fetchStarted = false;
|
| 476 |
+
let transportFailed = false;
|
| 477 |
+
const onTimeout = () => { timedOut = true; controller.abort(); };
|
| 478 |
+
// 已有缓存时排队也计入预算,避免被无缓存的慢请求无限拖住。
|
| 479 |
+
if (useCacheBudget) timeoutId = setTimeout(onTimeout, requestTimeout);
|
| 480 |
+
|
| 481 |
+
try {
|
| 482 |
+
const result = await requestQueue.add(async () => {
|
| 483 |
+
if (!useCacheBudget) timeoutId = setTimeout(onTimeout, requestTimeout);
|
| 484 |
+
// 请求可能在云端故障被另一个并发请求确认前进入队列;出队发出 fetch
|
| 485 |
+
// 前复查共享状态,避免队列继续逐个访问已知不可达的 HF endpoint。
|
| 486 |
+
if (method === "GET" && (!isOnline() || !isCloudReachable())) {
|
| 487 |
+
const unavailableError = new Error(
|
| 488 |
+
isOnline() ? t('feedback.cloud_unreachable_no_cache') : t('feedback.offline_no_cache')
|
| 489 |
+
);
|
| 490 |
+
unavailableError.name = 'CloudUnavailableError';
|
| 491 |
+
throw unavailableError;
|
| 492 |
+
}
|
| 493 |
+
assertReadSession();
|
| 494 |
+
fetchStarted = true;
|
| 495 |
+
try {
|
| 496 |
+
if (isRequestCacheCurrent) isCacheWriteCurrent = captureCacheWrite(cacheKey);
|
| 497 |
+
let response = await fetch(url, currentFetchOptions);
|
| 498 |
+
let validatedData;
|
| 499 |
+
if (response.status === 304 && conditionalRead) {
|
| 500 |
+
const currentMeta = getCacheWithMeta(cacheKey, true);
|
| 501 |
+
if (conditionalMeta?.found && conditionalMeta.etag
|
| 502 |
+
&& response.headers?.get?.('ETag') === conditionalMeta.etag
|
| 503 |
+
&& currentMeta.found && currentMeta.etag === conditionalMeta.etag
|
| 504 |
+
&& currentMeta.value === conditionalMeta.value) {
|
| 505 |
sample?.cacheHit();
|
| 506 |
+
validatedData = currentMeta.value;
|
| 507 |
+
} else {
|
| 508 |
+
// 缓存可能在等待期间被清理/写操作失效;同一预算内补取完整响应。
|
| 509 |
+
const fullHeaders = { ...currentFetchOptions.headers };
|
| 510 |
+
for (const name of Object.keys(fullHeaders)) if (name.toLowerCase() === "if-none-match") delete fullHeaders[name];
|
| 511 |
+
if (controller.signal.aborted) throw new DOMException('Aborted', 'AbortError');
|
| 512 |
+
isCacheWriteCurrent = captureCacheWrite(cacheKey);
|
| 513 |
+
response = await fetch(url, { ...currentFetchOptions, headers: fullHeaders, cache: "no-store" });
|
| 514 |
+
if (response.status === 304) throw new SyntaxError('Unexpected not-modified response');
|
| 515 |
+
}
|
| 516 |
+
}
|
| 517 |
+
let data;
|
| 518 |
+
let bodyConfirmed = true;
|
| 519 |
+
try {
|
| 520 |
+
data = validatedData !== undefined ? validatedData
|
| 521 |
+
: response.status === 204 ? {} : await response.json();
|
| 522 |
+
} catch (error) {
|
| 523 |
+
// 错误响应的正文不可读时仍按 HTTP 状态处理,不能用缓存掩盖 401/403。
|
| 524 |
+
if (!response.ok && (error instanceof SyntaxError || error instanceof TypeError || (timedOut && error.name === 'AbortError'))) {
|
| 525 |
+
data = {};
|
| 526 |
+
bodyConfirmed = false;
|
| 527 |
+
} else {
|
| 528 |
+
throw error;
|
| 529 |
+
}
|
| 530 |
+
}
|
| 531 |
+
return { response, data, bodyConfirmed, validated: validatedData !== undefined };
|
| 532 |
+
} catch (error) {
|
| 533 |
+
transportFailed = error instanceof TypeError;
|
| 534 |
+
throw error;
|
| 535 |
+
}
|
| 536 |
+
}, controller.signal);
|
| 537 |
+
clearTimeout(timeoutId);
|
| 538 |
+
requestCancelManager.remove(componentId, controller);
|
| 539 |
+
const { response } = result;
|
| 540 |
+
let responseData = result.data;
|
| 541 |
+
assertReadSession();
|
| 542 |
+
|
| 543 |
+
if (!response.ok && !result.validated) {
|
| 544 |
+
if (!responseData || typeof responseData !== "object" || Array.isArray(responseData)) responseData = {};
|
| 545 |
+
const errorMsg = httpErrorMessage(responseData, response.status);
|
| 546 |
+
|
| 547 |
+
// 🚀 P1优化:4xx 错误不重试,5xx 错误可重试
|
| 548 |
+
if (response.status >= 400 && response.status < 500) {
|
| 549 |
+
if (response.status === 401) {
|
| 550 |
+
// 🔧 修复:清除失效凭证并提示重新登录(原实现仅广播事件,无人清理);
|
| 551 |
+
// 传入本请求实际使用的 Token 做竞态比对,避免误清重新登录后签发的新凭证。
|
| 552 |
+
// 仅当确认凭证确实失效后才广播登出事件(导航停止轮询并重置登录态),
|
| 553 |
+
// 迟到的旧 401 或匿名请求的 401 不再误触发登录态重置。
|
| 554 |
+
// 登录接口的 401 语义是「密码错误」而非凭证失效,不走全局清理,
|
| 555 |
+
// 避免与登录表单自身的错误提示重复叠加
|
| 556 |
+
if (endpoint !== "/api/users/login" && handleAuthExpired(token)) {
|
| 557 |
+
window.dispatchEvent(new CustomEvent('comfy-ranking-auth-expired'));
|
| 558 |
+
}
|
| 559 |
+
}
|
| 560 |
+
const error = withRequestDiagnostic(new Error(errorMsg), response, responseData);
|
| 561 |
+
error.status = response.status;
|
| 562 |
+
if (typeof responseData.detail === "string" && /^[a-z][a-z0-9_]{0,79}$/.test(responseData.detail)) error.code = responseData.detail;
|
| 563 |
+
if (result.bodyConfirmed && Object.hasOwn(API.REQUEST_BODY_ERRORS, error.code)
|
| 564 |
+
&& API.REQUEST_BODY_ERRORS[error.code].status === error.status) {
|
| 565 |
+
error.requestBodyRejected = true;
|
| 566 |
+
}
|
| 567 |
+
throw error;
|
| 568 |
+
}
|
| 569 |
+
|
| 570 |
+
// 应用明确标记且正文可读的503只影响当前接口,仍允许其它榜单联网。
|
| 571 |
+
if (response.status === 503 && result.bodyConfirmed &&
|
| 572 |
+
response.headers?.get?.(API.ENDPOINT_ERROR_SCOPE_HEADER) === API.ENDPOINT_ERROR_SCOPE_VALUE) {
|
| 573 |
+
lastError = withRequestDiagnostic(new Error(errorMsg), response, responseData);
|
| 574 |
+
lastError.status = response.status;
|
| 575 |
+
networkLevelFailure = false;
|
| 576 |
+
break;
|
| 577 |
+
}
|
| 578 |
+
|
| 579 |
+
// Hugging Face Space / 网关不可用通常以 502、503 或 504 响应,
|
| 580 |
+
// 这类响应证明请求到达了代理层,但云端当前无法提供服务。
|
| 581 |
+
// 与超时/连接失败一样共享冷却,避免切换榜单时每个 endpoint
|
| 582 |
+
// 都重复访问一次;普通 500 仍只视为单接口服务端错误。
|
| 583 |
+
if ([502, 503, 504].includes(response.status)) {
|
| 584 |
+
lastError = withRequestDiagnostic(new Error(errorMsg), response, responseData);
|
| 585 |
+
lastError.status = response.status;
|
| 586 |
+
networkLevelFailure = true;
|
| 587 |
+
markCloudDown(endpoint);
|
| 588 |
+
break;
|
| 589 |
+
}
|
| 590 |
+
|
| 591 |
+
lastError = withRequestDiagnostic(new Error(errorMsg), response, responseData);
|
| 592 |
+
lastError.status = response.status;
|
| 593 |
+
continue; // 5xx 错误重试
|
| 594 |
+
}
|
| 595 |
+
|
| 596 |
+
// ☁️ 拿到了正常应答即证明云端可达,立即清零冷却(不必等它自然过期)。
|
| 597 |
+
// 非 GET 的成功同样算数——写操作是冷却期内唯一还在联网的请求,天然是探针
|
| 598 |
+
markCloudUp();
|
| 599 |
+
|
| 600 |
+
// 🚀 P1优化:精确清除相关缓存(替代暴力清空)
|
| 601 |
+
if (["POST", "PUT", "DELETE"].includes(method)) {
|
| 602 |
+
invalidateRelatedCache(endpoint, method);
|
| 603 |
+
}
|
| 604 |
+
|
| 605 |
+
// ⚡ P1性能优化:GET 请求结果缓存
|
| 606 |
+
if (method === "GET" && !options.noStore && isCacheWriteCurrent() && cacheReadOwners.get(cacheKey) === requestPromise) {
|
| 607 |
+
const ttl = _getCacheTTL(endpoint);
|
| 608 |
+
if (ttl > 0) {
|
| 609 |
+
// 创作者列表不持久化到 localStorage,避免空间不足
|
| 610 |
+
const persist = !endpoint.includes('/api/creators');
|
| 611 |
+
setCache(cacheKey, responseData, ttl, persist,
|
| 612 |
+
conditionalRead ? { etag: response.headers?.get?.('ETag') } : {});
|
| 613 |
+
}
|
| 614 |
+
}
|
| 615 |
+
|
| 616 |
+
// 入口数据挂载代理
|
| 617 |
+
const proxyFn3 = await getProxyImages();
|
| 618 |
+
assertReadSession();
|
| 619 |
+
responseData = proxyFn3(responseData);
|
| 620 |
+
if (responseData && typeof responseData === "object") {
|
| 621 |
+
responseCacheSources.delete(responseData);
|
| 622 |
+
if (trackCacheOwner && (!isCacheWriteCurrent() || cacheReadOwners.get(cacheKey) !== requestPromise)) responseCacheSources.set(responseData, { source: null });
|
| 623 |
+
}
|
| 624 |
+
return responseData;
|
| 625 |
+
} catch (error) {
|
| 626 |
+
clearTimeout(timeoutId); // 清除超时计时器
|
| 627 |
+
// 🔍 失败/超时同样摘除 controller:成功路径在上方已 remove,这里不补的话,
|
| 628 |
+
// 取消分组里会堆积已失效的 controller,使 cancelAll 的在途计数虚高
|
| 629 |
+
requestCancelManager.remove(componentId, controller);
|
| 630 |
+
assertReadSession();
|
| 631 |
+
|
| 632 |
+
// 🔍 主动撤销(组件级取消)与超时都表现为 AbortError,但语义完全相反:
|
| 633 |
+
// 超时该重试;主动撤销是调用方明确表示「这次结果我不要了」,绝不能重试,
|
| 634 |
+
// 否则会白烧一轮超时预算(搜索场景下用户每敲一次键都可能触发一次撤销)。
|
| 635 |
+
// 直接抛出而不走循环后的「过期缓存兜底」,避免把作废请求的结果上屏
|
| 636 |
+
if (error.name === 'AbortError' && !timedOut) {
|
| 637 |
+
const cancelErr = new Error(t('feedback.request_cancelled'));
|
| 638 |
+
cancelErr.name = 'RequestCancelledError';
|
| 639 |
+
cancelErr.isCancelled = true;
|
| 640 |
+
throw cancelErr;
|
| 641 |
+
}
|
| 642 |
+
|
| 643 |
+
// 队列等待期间已有并发请求确证网络不可达:该请求尚未发出 fetch,
|
| 644 |
+
// 直接交给统一缓存兜底,不重试、不延长冷却,也不把队列错误当作网络探测。
|
| 645 |
+
if (error.name === 'CloudUnavailableError') {
|
| 646 |
+
lastError = error;
|
| 647 |
+
break;
|
| 648 |
+
}
|
| 649 |
+
|
| 650 |
+
// 🔧 P1优化:可重试的错误类型
|
| 651 |
+
const isRetryable = (
|
| 652 |
+
error.name === 'AbortError' ||
|
| 653 |
+
transportFailed
|
| 654 |
+
);
|
| 655 |
+
|
| 656 |
+
if (isRetryable) {
|
| 657 |
+
// 🔧 修复:重试耗尽时不再直接 throw(否则循环后的「过期缓存兜底」
|
| 658 |
+
// 分支永远不可达,断网时无法无缝切换本地数据)。记录友好错误后跳出循环,
|
| 659 |
+
// 让 GET 请求走过期缓存回退;无缓存时仍以该友好错误抛出。
|
| 660 |
+
const isTimeout = error.name === 'AbortError';
|
| 661 |
+
lastError = isTimeout
|
| 662 |
+
? new Error(t('feedback.network_timeout'))
|
| 663 |
+
: new Error(t('feedback.network_unavailable'));
|
| 664 |
+
lastError.code = isTimeout ? 'network_timeout' : 'network_unavailable';
|
| 665 |
+
if (fetchStarted) networkLevelFailure = true;
|
| 666 |
+
// ☁️ 连接层失败(被墙 / DNS 污染 / ���绝连接 / 证书错误)几乎不会是偶发抖动,
|
| 667 |
+
// 打上冷却后其它界面与轮询就不用再各自烧一遍预算。但单次失败不足以定论,
|
| 668 |
+
// 故分两种口径:已配重试时要求第二次尝试仍失败才定论(连接层失败是毫秒级的,
|
| 669 |
+
// 多等一轮只多花约 1 秒,却能挡住偶发抖动误伤 60 秒);
|
| 670 |
+
// 未配重试时(后台补新短预算,界面已用缓存上屏)误判零代价,立即定论。
|
| 671 |
+
// 超时则可能是 HF Space 冷启动(慢但能成功),不在此定论,耗尽后由下方统一处理
|
| 672 |
+
if (!isTimeout && (attempt >= 1 || maxRetries === 0)) markCloudDown(endpoint);
|
| 673 |
+
if (attempt < maxRetries) continue; // 重试
|
| 674 |
+
break; // 重试耗尽 → 跳到过期缓存兜底
|
| 675 |
+
}
|
| 676 |
+
|
| 677 |
+
// 🔧 P3优化:错误分类处理,提供更清晰的错误信息(不可重试错误直接抛出)
|
| 678 |
+
if (error instanceof SyntaxError) {
|
| 679 |
+
throw new Error(t('feedback.response_format_error'));
|
| 680 |
+
}
|
| 681 |
+
throw error;
|
| 682 |
+
}
|
| 683 |
+
}
|
| 684 |
+
|
| 685 |
+
// ☁️ 所有尝试都因网络层原因失败(超时耗尽重试也走这里)→ 打上冷却,
|
| 686 |
+
// 接下来 API.CLOUD_DOWN_COOLDOWN 内的 GET 全部就地走缓存,不再重复等待
|
| 687 |
+
if (networkLevelFailure) markCloudDown(endpoint);
|
| 688 |
+
|
| 689 |
+
// 所有重试都失败,尝试回退到过期缓存
|
| 690 |
+
if (method === "GET" && !options.noCache) {
|
| 691 |
+
const fallback = getCacheWithMeta(cacheKey, true); // true = 允许过期
|
| 692 |
+
if (fallback.found) {
|
| 693 |
+
console.warn('📴 网络请求失败,回退到本地缓存');
|
| 694 |
+
const source = captureCacheSource(cacheKey);
|
| 695 |
+
const proxyFn4 = await getProxyImages();
|
| 696 |
sample?.cacheHit();
|
| 697 |
+
return _cachedResponse(proxyFn4(fallback.value), source); // 返回过期缓存数据
|
| 698 |
+
}
|
| 699 |
+
}
|
| 700 |
+
// 仍无缓存,才抛异常
|
| 701 |
+
throw lastError || new Error(t('feedback.error'));
|
| 702 |
+
})();
|
| 703 |
+
|
| 704 |
+
if (privateEntry) requestPromise.finally(() => activePrivateReads.delete(privateEntry)).catch(() => {});
|
| 705 |
+
|
| 706 |
+
if (trackCacheOwner) {
|
| 707 |
+
cacheReadOwners.set(cacheKey, requestPromise);
|
| 708 |
+
requestPromise.finally(() => {
|
| 709 |
+
if (cacheReadOwners.get(cacheKey) === requestPromise) cacheReadOwners.delete(cacheKey);
|
| 710 |
+
}).catch(() => {});
|
| 711 |
+
}
|
| 712 |
+
|
| 713 |
+
// 记录进行中的请求
|
| 714 |
+
if (trackPendingRequest) {
|
| 715 |
+
pendingRequests.set(cacheKey, requestPromise);
|
| 716 |
+
pendingRequestGuards.set(requestPromise, isRequestCacheCurrent);
|
| 717 |
+
}
|
| 718 |
+
|
| 719 |
+
// 确保请求完成后清除去重记录
|
| 720 |
+
// 🔧 补 .catch 空处理:finally 会派生出一个新的 Promise,而它从未被返回也无人接收,
|
| 721 |
+
// 一旦请求失败(含主动撤销)就会在控制台抛 Uncaught (in promise)。
|
| 722 |
+
// 原始 requestPromise 仍在下方正常返回给调用方处理,此处只是吞掉这份重复的拒绝
|
| 723 |
+
if (trackPendingRequest) {
|
| 724 |
+
requestPromise.finally(() => {
|
| 725 |
+
if (pendingRequests.get(cacheKey) === requestPromise) pendingRequests.delete(cacheKey);
|
| 726 |
+
}).catch(() => {});
|
| 727 |
+
}
|
| 728 |
+
|
| 729 |
+
return requestPromise;
|
| 730 |
+
}
|
| 731 |
+
|
| 732 |
+
// ==========================================
|
| 733 |
+
// 📡 SSE 流式请求(用于安装进度等长时间操作)
|
| 734 |
+
// ==========================================
|
| 735 |
+
|
| 736 |
+
/**
|
| 737 |
+
* 发起 SSE 流式请求(用于安装进度等长时间操作)
|
| 738 |
+
* @param {string} endpoint - API端点路径(本地ComfyUI路径,如 /community_hub/install_tool_stream)
|
| 739 |
+
* @param {Object} body - POST请求体
|
| 740 |
+
* @param {Function} onProgress - 进度回调 ({stage, progress, message, status, data}) => void
|
| 741 |
+
* @param {Object} [options] - 可选配置 { timeout: 300000 }
|
| 742 |
+
* @returns {Promise<Object>} 最终结果事件
|
| 743 |
+
*/
|
| 744 |
+
export async function requestSSE(endpoint, body, onProgress, options = {}) {
|
| 745 |
+
const timeout = options.timeout || 1200000; // 20分钟全局超时(大型工具克隆需要较长时间)
|
| 746 |
+
const controller = new AbortController();
|
| 747 |
+
const globalTimer = setTimeout(() => controller.abort(), timeout);
|
| 748 |
+
const externalSignal = options.signal;
|
| 749 |
+
const abortFromCaller = () => controller.abort();
|
| 750 |
+
if (externalSignal?.aborted) controller.abort();
|
| 751 |
+
else externalSignal?.addEventListener("abort", abortFromCaller, { once: true });
|
| 752 |
+
|
| 753 |
+
// ���� 空闲超时检测:长时间无数据视为连接已断
|
| 754 |
+
const IDLE_TIMEOUT_DEFAULT = 30000; // 30 秒无数据视为空闲
|
| 755 |
+
const IDLE_TIMEOUT_GRACE = 5000; // 收到 finalResult 后的宽限期 5 秒
|
| 756 |
+
let currentIdleTimeout = options.idleTimeout || IDLE_TIMEOUT_DEFAULT;
|
| 757 |
+
let idleTimer = null;
|
| 758 |
+
let finalResult = null;
|
| 759 |
+
let streamReader = null;
|
| 760 |
+
|
| 761 |
+
const clearIdleTimer = () => {
|
| 762 |
+
if (idleTimer !== null) {
|
| 763 |
+
clearTimeout(idleTimer);
|
| 764 |
+
idleTimer = null;
|
| 765 |
+
}
|
| 766 |
+
};
|
| 767 |
+
|
| 768 |
+
try {
|
| 769 |
+
const response = await fetch(endpoint, {
|
| 770 |
+
method: "POST",
|
| 771 |
+
headers: { "Content-Type": "application/json" },
|
| 772 |
+
body: JSON.stringify(body),
|
| 773 |
+
signal: controller.signal
|
| 774 |
+
});
|
| 775 |
+
|
| 776 |
+
if (!response.ok) {
|
| 777 |
+
const error = withRequestDiagnostic(new Error(t('feedback.http_request_failed', { status: response.status })), response);
|
| 778 |
+
error.status = response.status;
|
| 779 |
+
// 仅当流式路由明确不存在/不接受该方法时,调用方可安全回退到旧端点。
|
| 780 |
+
// 网络错误、超时和服务端错误都可能发生在操作已开始后,不可自动重发。
|
| 781 |
+
error.fallbackSafe = response.status === 404 || response.status === 405;
|
| 782 |
+
throw error;
|
| 783 |
+
}
|
| 784 |
+
|
| 785 |
+
const reader = streamReader = response.body.getReader();
|
| 786 |
+
const decoder = new TextDecoder('utf-8', { fatal: true });
|
| 787 |
+
const decodeSSEChunk = (value, options) => {
|
| 788 |
+
try {
|
| 789 |
+
return decoder.decode(value, options);
|
| 790 |
+
} catch (_) {
|
| 791 |
+
const error = new Error(t('feedback.stream_invalid_encoding'));
|
| 792 |
+
error.code = 'invalid_stream_encoding';
|
| 793 |
+
error.outcomeUnknown = true;
|
| 794 |
+
throw error;
|
| 795 |
+
}
|
| 796 |
+
};
|
| 797 |
+
let totalBytes = 0, lineBytes = 0, lineCount = 0;
|
| 798 |
+
let workBytes = 0, workLines = 0, workChunks = 0;
|
| 799 |
+
const lineParts = [];
|
| 800 |
+
const limitError = () => {
|
| 801 |
+
const error = new Error(t('feedback.stream_limit_exceeded'));
|
| 802 |
+
error.code = 'stream_limit_exceeded';
|
| 803 |
+
error.outcomeUnknown = true;
|
| 804 |
+
return error;
|
| 805 |
+
};
|
| 806 |
+
const appendLinePart = (part) => {
|
| 807 |
+
if (!part) return;
|
| 808 |
+
let level = 0;
|
| 809 |
+
while (lineParts[level] !== undefined) {
|
| 810 |
+
part = lineParts[level] + part;
|
| 811 |
+
lineParts[level++] = undefined;
|
| 812 |
+
}
|
| 813 |
+
lineParts[level] = part;
|
| 814 |
+
};
|
| 815 |
+
const takeLine = () => {
|
| 816 |
+
const line = lineParts.slice().reverse().filter(part => part !== undefined).join('');
|
| 817 |
+
lineParts.length = 0;
|
| 818 |
+
return line;
|
| 819 |
+
};
|
| 820 |
+
const yieldIfNeeded = async () => {
|
| 821 |
+
if (workBytes >= API.SSE_YIELD_BYTES || workLines >= API.SSE_YIELD_LINES || workChunks >= API.SSE_YIELD_CHUNKS) {
|
| 822 |
+
workBytes = workLines = workChunks = 0;
|
| 823 |
+
await new Promise(resolve => setTimeout(resolve, 0));
|
| 824 |
+
}
|
| 825 |
+
if (controller.signal.aborted) throw new DOMException('Aborted', 'AbortError');
|
| 826 |
+
};
|
| 827 |
+
const checkChunkBudget = (value) => {
|
| 828 |
+
totalBytes += value.byteLength;
|
| 829 |
+
if (totalBytes > API.SSE_MAX_RESPONSE_BYTES) throw limitError();
|
| 830 |
+
let start = 0, end;
|
| 831 |
+
while ((end = value.indexOf(10, start)) !== -1) {
|
| 832 |
+
lineBytes += end - start;
|
| 833 |
+
if (lineBytes > API.SSE_MAX_LINE_BYTES) throw limitError();
|
| 834 |
+
lineBytes = 0;
|
| 835 |
+
start = end + 1;
|
| 836 |
+
}
|
| 837 |
+
lineBytes += value.byteLength - start;
|
| 838 |
+
if (lineBytes > API.SSE_MAX_LINE_BYTES) throw limitError();
|
| 839 |
+
};
|
| 840 |
+
const processSSELine = (line) => {
|
| 841 |
+
if (!line.startsWith("data: ")) return;
|
| 842 |
+
let data;
|
| 843 |
+
try {
|
| 844 |
+
data = JSON.parse(line.slice(6));
|
| 845 |
+
} catch (_) {
|
| 846 |
+
console.warn("[SSE] 解析事件失败");
|
| 847 |
+
return;
|
| 848 |
+
}
|
| 849 |
+
if (!data || typeof data !== "object" || Array.isArray(data)) {
|
| 850 |
+
console.warn("[SSE] 忽略非对象事件");
|
| 851 |
+
return;
|
| 852 |
+
}
|
| 853 |
+
if (data.status === "success" || data.status === "error") {
|
| 854 |
+
// 先保存最终结果,UI 更新回调即使异常也不能丢失服务端结果。
|
| 855 |
+
finalResult = data;
|
| 856 |
+
currentIdleTimeout = IDLE_TIMEOUT_GRACE;
|
| 857 |
+
}
|
| 858 |
+
try {
|
| 859 |
+
onProgress?.(data);
|
| 860 |
+
} catch (callbackError) {
|
| 861 |
+
console.warn("[SSE] 进度回调失败");
|
| 862 |
+
}
|
| 863 |
+
};
|
| 864 |
+
const processSSEText = async (text, flush = false) => {
|
| 865 |
+
let start = 0, end;
|
| 866 |
+
while ((end = text.indexOf("\n", start)) !== -1) {
|
| 867 |
+
if (++lineCount > API.SSE_MAX_LINES) throw limitError();
|
| 868 |
+
appendLinePart(text.slice(start, end));
|
| 869 |
+
processSSELine(takeLine());
|
| 870 |
+
start = end + 1;
|
| 871 |
+
workLines++;
|
| 872 |
+
await yieldIfNeeded();
|
| 873 |
+
}
|
| 874 |
+
appendLinePart(text.slice(start));
|
| 875 |
+
if (flush && lineParts.length) {
|
| 876 |
+
if (++lineCount > API.SSE_MAX_LINES) throw limitError();
|
| 877 |
+
processSSELine(takeLine());
|
| 878 |
+
}
|
| 879 |
+
};
|
| 880 |
+
while (true) {
|
| 881 |
+
// 使用 Promise.race 实现空闲超时:reader.read() 与空闲定时器竞争
|
| 882 |
+
const idlePromise = new Promise((_, reject) => {
|
| 883 |
+
idleTimer = setTimeout(() => reject(new Error("SSE_IDLE_TIMEOUT")), currentIdleTimeout);
|
| 884 |
+
});
|
| 885 |
+
|
| 886 |
+
let readResult;
|
| 887 |
+
try {
|
| 888 |
+
readResult = await Promise.race([
|
| 889 |
+
reader.read(),
|
| 890 |
+
idlePromise
|
| 891 |
+
]);
|
| 892 |
+
} catch (e) {
|
| 893 |
+
clearIdleTimer();
|
| 894 |
+
if (e.message === "SSE_IDLE_TIMEOUT") {
|
| 895 |
+
controller.abort();
|
| 896 |
+
// 如果已收到 finalResult,优先返回它(服务器只是没正确关闭连接)
|
| 897 |
+
if (finalResult) return finalResult;
|
| 898 |
+
// 否则返回空闲超时错误
|
| 899 |
+
return { status: "error", outcomeUnknown: true, message: t('feedback.stream_idle_timeout') };
|
| 900 |
+
}
|
| 901 |
+
throw e;
|
| 902 |
+
}
|
| 903 |
+
clearIdleTimer();
|
| 904 |
+
|
| 905 |
+
const { done, value } = readResult;
|
| 906 |
+
if (done) {
|
| 907 |
+
await processSSEText(decodeSSEChunk(), true);
|
| 908 |
+
break;
|
| 909 |
+
}
|
| 910 |
+
|
| 911 |
+
checkChunkBudget(value);
|
| 912 |
+
workBytes += value.byteLength;
|
| 913 |
+
workChunks++;
|
| 914 |
+
await processSSEText(decodeSSEChunk(value, { stream: true }));
|
| 915 |
+
await yieldIfNeeded();
|
| 916 |
+
}
|
| 917 |
+
|
| 918 |
+
return finalResult || { status: "error", outcomeUnknown: true, message: t('feedback.stream_missing_final') };
|
| 919 |
+
} catch (err) {
|
| 920 |
+
// 已收到最终事件时,后续连接关闭错误不应覆盖操作结果或触发重复提交。
|
| 921 |
+
if (finalResult) return finalResult;
|
| 922 |
+
if (err.name === "AbortError") {
|
| 923 |
+
return {
|
| 924 |
+
status: "error",
|
| 925 |
+
outcomeUnknown: true,
|
| 926 |
+
cancelRequested: !!externalSignal?.aborted,
|
| 927 |
+
message: externalSignal?.aborted ? t('feedback.request_cancelled') : t('feedback.stream_timeout_unconfirmed')
|
| 928 |
+
};
|
| 929 |
+
}
|
| 930 |
+
throw err;
|
| 931 |
+
} finally {
|
| 932 |
+
clearTimeout(globalTimer);
|
| 933 |
+
clearIdleTimer();
|
| 934 |
+
externalSignal?.removeEventListener("abort", abortFromCaller);
|
| 935 |
+
try { controller.abort(); } catch (_) {}
|
| 936 |
+
if (streamReader) {
|
| 937 |
+
try { Promise.resolve(streamReader.cancel()).catch(() => {}); } catch (_) {}
|
| 938 |
+
try { streamReader.releaseLock(); } catch (_) {}
|
| 939 |
+
streamReader = null;
|
| 940 |
+
}
|
| 941 |
+
}
|
| 942 |
+
}
|
| 943 |
+
|
| 944 |
+
// 导出给外部使用
|
| 945 |
+
export { requestCancelManager, invalidateRelatedCache, request };
|
| 946 |
+
export default request;
|
前端页面/core/网络请求_缓存管理.js
CHANGED
|
@@ -9,7 +9,7 @@
|
|
| 9 |
// - 性能优化工具.js (重导出缓存函数,保持向后兼容)
|
| 10 |
// ==========================================
|
| 11 |
|
| 12 |
-
import { API, CACHE } from "./全局配置.js";
|
| 13 |
|
| 14 |
// ==========================================
|
| 15 |
// 📦 缓存底层实现
|
|
@@ -33,6 +33,53 @@ const memoryCache = new Map();
|
|
| 33 |
const memoryCacheOrder = []; // LRU 顺序追踪
|
| 34 |
const memoryOnlyEntries = new WeakSet();
|
| 35 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
/**
|
| 37 |
* 生成完整缓存键(带前缀)
|
| 38 |
* @param {string} key - 原始键
|
|
@@ -116,8 +163,11 @@ function _safeStorageWrite(fullKey, jsonStr) {
|
|
| 116 |
* @param {{etag?: string}} metadata - 可选的正文验证器,与value一同失效
|
| 117 |
*/
|
| 118 |
export function setCache(key, value, ttl = DEFAULT_TTL, persist = true, metadata = {}) {
|
|
|
|
|
|
|
|
|
|
|
|
|
| 119 |
const fk = _fullKey(key);
|
| 120 |
-
const expireAt = Date.now() + ttl;
|
| 121 |
const cacheData = { schemaVersion: CACHE_SCHEMA_VERSION, value, expireAt, lastAccessAt: Date.now() };
|
| 122 |
memoryOnlyEntries.add(cacheData);
|
| 123 |
if (typeof metadata?.etag === "string" && API.CONDITIONAL_ETAG_PATTERN.test(metadata.etag)) cacheData.etag = metadata.etag;
|
|
@@ -378,6 +428,7 @@ function _enforceStorageBudget(protectedKey = null) {
|
|
| 378 |
* @param {string} key - 缓存键
|
| 379 |
*/
|
| 380 |
export function removeCache(key) {
|
|
|
|
| 381 |
const fk = _fullKey(key);
|
| 382 |
_deleteMemoryEntry(fk);
|
| 383 |
try {
|
|
@@ -403,6 +454,7 @@ export function removeCacheByPrefix(prefix) {
|
|
| 403 |
}
|
| 404 |
|
| 405 |
function _removeCacheByPrefixes(prefixes) {
|
|
|
|
| 406 |
const candidates = [...new Set(prefixes.flatMap(prefix =>
|
| 407 |
prefix.startsWith(CACHE_PREFIX) ? [prefix] : [_fullKey(prefix), prefix]))];
|
| 408 |
const isMatch = (key) => candidates.some(p => key.startsWith(p));
|
|
@@ -437,6 +489,7 @@ function _removeCacheByPrefixes(prefixes) {
|
|
| 437 |
* 清除所有缓存
|
| 438 |
*/
|
| 439 |
export function clearAllCache() {
|
|
|
|
| 440 |
memoryCache.clear();
|
| 441 |
memoryCacheOrder.length = 0;
|
| 442 |
storageUsageBytes = null;
|
|
|
|
| 9 |
// - 性能优化工具.js (重导出缓存函数,保持向后兼容)
|
| 10 |
// ==========================================
|
| 11 |
|
| 12 |
+
import { API, CACHE, getSidebarListCacheKey } from "./全局配置.js";
|
| 13 |
|
| 14 |
// ==========================================
|
| 15 |
// 📦 缓存底层实现
|
|
|
|
| 33 |
const memoryCacheOrder = []; // LRU 顺序追踪
|
| 34 |
const memoryOnlyEntries = new WeakSet();
|
| 35 |
|
| 36 |
+
let cacheClearToken = {};
|
| 37 |
+
const cacheWriteScopes = [
|
| 38 |
+
...[...CACHE.RESOURCE_LIST_PREFIXES, getSidebarListCacheKey('creators', '')].map(prefix =>
|
| 39 |
+
({ prefix, matches: key => key.startsWith(prefix), token: {} })),
|
| 40 |
+
...API.PUBLIC_CONDITIONAL_GET_PATHS.map(path => {
|
| 41 |
+
const prefix = `api_${path}`;
|
| 42 |
+
return { prefix, matches: key => key.split(/[?#]/)[0] === prefix, token: {} };
|
| 43 |
+
})
|
| 44 |
+
];
|
| 45 |
+
|
| 46 |
+
function _cacheScopeKey(key) {
|
| 47 |
+
return typeof key === 'string' && key.startsWith(CACHE_PREFIX) ? key.slice(CACHE_PREFIX.length) : key;
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
export function captureCacheWrite(key) {
|
| 51 |
+
const normalized = key;
|
| 52 |
+
const scope = typeof normalized === 'string' ? cacheWriteScopes.find(item => item.matches(normalized)) : null;
|
| 53 |
+
const token = scope?.token, clearToken = cacheClearToken;
|
| 54 |
+
return () => cacheClearToken === clearToken && (!scope || scope.token === token);
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
function _revokeCacheWrites(keys, prefix = false) {
|
| 58 |
+
const normalized = (prefix ? keys.map(_cacheScopeKey) : keys).filter(key => typeof key === 'string' && key.length > 0);
|
| 59 |
+
for (const scope of cacheWriteScopes) {
|
| 60 |
+
if (normalized.some(key => scope.matches(key) || (prefix && scope.prefix.startsWith(key)))) scope.token = {};
|
| 61 |
+
}
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
export function captureCacheSource(key) {
|
| 65 |
+
const fk = _fullKey(key), cached = memoryCache.get(fk);
|
| 66 |
+
if (!_isValidCacheEntry(cached)) return null;
|
| 67 |
+
const isAvailable = () => memoryCache.get(fk) === cached && _isValidCacheEntry(cached);
|
| 68 |
+
const isFresh = () => isAvailable() && !_isExpired(cached);
|
| 69 |
+
return {
|
| 70 |
+
isAvailable,
|
| 71 |
+
isFresh,
|
| 72 |
+
copyTo(targetKey, value) {
|
| 73 |
+
const normalized = targetKey;
|
| 74 |
+
if (!isFresh() || typeof normalized !== 'string' ||
|
| 75 |
+
!CACHE.RESOURCE_LIST_PREFIXES.concat(getSidebarListCacheKey('creators', '')).some(prefix => normalized.startsWith(prefix))) return false;
|
| 76 |
+
_storeCache(normalized, value, cached.expireAt, true, {});
|
| 77 |
+
return true;
|
| 78 |
+
}
|
| 79 |
+
};
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
|
| 83 |
/**
|
| 84 |
* 生成完整缓存键(带前缀)
|
| 85 |
* @param {string} key - 原始键
|
|
|
|
| 163 |
* @param {{etag?: string}} metadata - 可选的正文验证器,与value一同失效
|
| 164 |
*/
|
| 165 |
export function setCache(key, value, ttl = DEFAULT_TTL, persist = true, metadata = {}) {
|
| 166 |
+
_storeCache(key, value, Date.now() + ttl, persist, metadata);
|
| 167 |
+
}
|
| 168 |
+
|
| 169 |
+
function _storeCache(key, value, expireAt, persist, metadata) {
|
| 170 |
const fk = _fullKey(key);
|
|
|
|
| 171 |
const cacheData = { schemaVersion: CACHE_SCHEMA_VERSION, value, expireAt, lastAccessAt: Date.now() };
|
| 172 |
memoryOnlyEntries.add(cacheData);
|
| 173 |
if (typeof metadata?.etag === "string" && API.CONDITIONAL_ETAG_PATTERN.test(metadata.etag)) cacheData.etag = metadata.etag;
|
|
|
|
| 428 |
* @param {string} key - 缓存键
|
| 429 |
*/
|
| 430 |
export function removeCache(key) {
|
| 431 |
+
_revokeCacheWrites([key]);
|
| 432 |
const fk = _fullKey(key);
|
| 433 |
_deleteMemoryEntry(fk);
|
| 434 |
try {
|
|
|
|
| 454 |
}
|
| 455 |
|
| 456 |
function _removeCacheByPrefixes(prefixes) {
|
| 457 |
+
_revokeCacheWrites(prefixes, true);
|
| 458 |
const candidates = [...new Set(prefixes.flatMap(prefix =>
|
| 459 |
prefix.startsWith(CACHE_PREFIX) ? [prefix] : [_fullKey(prefix), prefix]))];
|
| 460 |
const isMatch = (key) => candidates.some(p => key.startsWith(p));
|
|
|
|
| 489 |
* 清除所有缓存
|
| 490 |
*/
|
| 491 |
export function clearAllCache() {
|
| 492 |
+
cacheClearToken = {};
|
| 493 |
memoryCache.clear();
|
| 494 |
memoryCacheOrder.length = 0;
|
| 495 |
storageUsageBytes = null;
|
前端页面/market/Skill安装流程.js
CHANGED
|
@@ -194,11 +194,11 @@ export async function runSkillInstall({ target, credentials, scope, confirm, onP
|
|
| 194 |
let result;
|
| 195 |
try { result = await stream('commit'); }
|
| 196 |
catch (error) {
|
| 197 |
-
if (error?.fallbackSafe) return { status: 'error', error_code: 'local_update_required', outcomeUnknown: false };
|
| 198 |
}
|
| 199 |
-
if (confirmed(result, ready.installed_version)) return result;
|
| 200 |
if (object(result) && result.status === 'error' && result.outcomeUnknown === false
|
| 201 |
-
&& typeof result.error_code === 'string') return result;
|
| 202 |
if (scope.isCurrent() && !signal.aborted) {
|
| 203 |
try {
|
| 204 |
onProgress?.({ stage: 'validate', progress: 99, skillAction: 'status' });
|
|
@@ -207,7 +207,7 @@ export async function runSkillInstall({ target, credentials, scope, confirm, onP
|
|
| 207 |
&& confirmed(receipt, ready.installed_version)) return receipt;
|
| 208 |
} catch {}
|
| 209 |
}
|
| 210 |
-
return { status: 'error', outcomeUnknown: true };
|
| 211 |
} catch (error) {
|
| 212 |
throw failure(error?.fallbackSafe ? 'local_update_required' : error?.code || 'install_failed');
|
| 213 |
} finally {
|
|
|
|
| 194 |
let result;
|
| 195 |
try { result = await stream('commit'); }
|
| 196 |
catch (error) {
|
| 197 |
+
if (error?.fallbackSafe) return { status: 'error', error_code: 'local_update_required', outcomeUnknown: false, plan_id: plan };
|
| 198 |
}
|
| 199 |
+
if (confirmed(result, ready.installed_version)) return { ...result, plan_id: plan };
|
| 200 |
if (object(result) && result.status === 'error' && result.outcomeUnknown === false
|
| 201 |
+
&& typeof result.error_code === 'string') return { ...result, plan_id: plan };
|
| 202 |
if (scope.isCurrent() && !signal.aborted) {
|
| 203 |
try {
|
| 204 |
onProgress?.({ stage: 'validate', progress: 99, skillAction: 'status' });
|
|
|
|
| 207 |
&& confirmed(receipt, ready.installed_version)) return receipt;
|
| 208 |
} catch {}
|
| 209 |
}
|
| 210 |
+
return { status: 'error', outcomeUnknown: true, plan_id: plan };
|
| 211 |
} catch (error) {
|
| 212 |
throw failure(error?.fallbackSafe ? 'local_update_required' : error?.code || 'install_failed');
|
| 213 |
} finally {
|
前端页面/market/发布内容_提交引擎.js
CHANGED
|
@@ -1,311 +1,311 @@
|
|
| 1 |
-
import { processImageCore as _processImageCore } from "./有界图片处理.js";
|
| 2 |
-
import { validateImageFile } from "./图片文件检查.js";
|
| 3 |
-
import { IMAGE_PROCESS, TYPE_RULES } from "../core/全局配置.js";
|
| 4 |
-
// 前端页面/market/发布内容_提交引擎.js
|
| 5 |
-
import { createPublishSubmissionScope } from "./发布提交生命周期.js";
|
| 6 |
-
import { api } from "../core/网络请求API.js";
|
| 7 |
-
import { showToast } from "../components/UI交互提示组件.js";
|
| 8 |
-
import { t } from "../components/用户体验增强.js";
|
| 9 |
-
import { removeCache, removeCacheByPrefix } from "../components/性能优化工具.js";
|
| 10 |
-
|
| 11 |
-
/**
|
| 12 |
-
* 📋 获取指定主类型的提交规则(校验与字段组装统一读取,与 UI 显隐同源)
|
| 13 |
-
* @param {string} mainType - 主类型: tool/skill/app/recommend
|
| 14 |
-
*/
|
| 15 |
-
function getSubmitRules(mainType) {
|
| 16 |
-
return TYPE_RULES[mainType] || TYPE_RULES.tool;
|
| 17 |
-
}
|
| 18 |
-
|
| 19 |
-
/**
|
| 20 |
-
* 🟢 根据发布类型清除对应缓存(精确清除,不影响其他页面)
|
| 21 |
-
* @param {string} type - 发布类型: tool/skill/app/recommend/recommend_tool/recommend_skill/recommend_app/recommend_link
|
| 22 |
-
*/
|
| 23 |
-
function clearItemCacheByType(type) {
|
| 24 |
-
// 确定当前类型对应的 tab
|
| 25 |
-
let tab = 'recommends';
|
| 26 |
-
if (type === 'tool' || type === 'recommend_tool') {
|
| 27 |
-
tab = 'tools';
|
| 28 |
-
} else if (type === 'skill' || type === 'recommend_skill') {
|
| 29 |
-
tab = 'skills';
|
| 30 |
-
} else if (type === 'app' || type === 'recommend_app') {
|
| 31 |
-
tab = 'apps';
|
| 32 |
-
}
|
| 33 |
-
|
| 34 |
-
// 清除 API 缓存
|
| 35 |
-
// 🔧 修复:API 层缓存键总是带完整查询串(api_/api/items?type=tool&sort=time&limit=200),
|
| 36 |
-
// 而 removeCache 是精确键删除,原先这几个调用一个也命中不到(no-op),发布成功后
|
| 37 |
-
// request() 仍会从缓存直接返回旧列表、看不到刚发布的内容。改用前缀删除,
|
| 38 |
-
// 一次覆盖全部 type/sort/limit 组合(原先按 type 单独删的那行已被本前缀覆盖,属冗余)
|
| 39 |
-
removeCacheByPrefix('api_/api/items');
|
| 40 |
-
removeCacheByPrefix('api_/api/creators'); // 创作者列表也需要刷新
|
| 41 |
-
|
| 42 |
-
// 清除侧边栏数据引擎缓存(只清除对应类型)
|
| 43 |
-
const sorts = ['time', 'downloads', 'likes', 'favorites', 'tips', 'views', 'daily_views', 'rating'];
|
| 44 |
-
for (const sort of sorts) {
|
| 45 |
-
removeCache(
|
| 46 |
-
removeCache(
|
| 47 |
-
}
|
| 48 |
-
|
| 49 |
-
console.log(`🗑️ 已清除 [${tab}] 类型的列表缓存`);
|
| 50 |
-
}
|
| 51 |
-
|
| 52 |
-
/**
|
| 53 |
-
* 🟢 利用 HTML5 Canvas 纯前端裁剪并压缩头像
|
| 54 |
-
* 功能:强制 1:1 比例中心裁剪,缩放到 512x512,转换为 JPG 格式。
|
| 55 |
-
*/
|
| 56 |
-
function processAvatar(file) {
|
| 57 |
-
return _processImageCore(file, {
|
| 58 |
-
cropToSquare: true,
|
| 59 |
-
maxFileSize: IMAGE_PROCESS.AVATAR_MAX_BYTES,
|
| 60 |
-
targetSize: IMAGE_PROCESS.AVATAR_SIZE,
|
| 61 |
-
quality: 0.85,
|
| 62 |
-
suffix: '_cropped.jpg'
|
| 63 |
-
}).then(processedFile => {
|
| 64 |
-
console.log(`✅ 头像处理完成:原始 ${(file.size/1024).toFixed(1)}KB -> 压缩后 ${(processedFile.size/1024).toFixed(1)}KB`);
|
| 65 |
-
return processedFile;
|
| 66 |
-
});
|
| 67 |
-
}
|
| 68 |
-
|
| 69 |
-
/**
|
| 70 |
-
* 上传前图片压缩处理
|
| 71 |
-
* - 转为 JPG 格式
|
| 72 |
-
* - 最长边至多4096并保持比例;质量压缩后仍超过5MB则拒绝
|
| 73 |
-
* @param {File} file - 原始图片文件
|
| 74 |
-
* @returns {Promise<File>} - 处理后的文件
|
| 75 |
-
*/
|
| 76 |
-
export async function compressImageForUpload(file) {
|
| 77 |
-
// 如果不是图片文件,直接返回
|
| 78 |
-
if (!file.type || !file.type.startsWith('image/')) {
|
| 79 |
-
return file;
|
| 80 |
-
}
|
| 81 |
-
|
| 82 |
-
if (!Number.isFinite(file.size) || file.size < 0 || file.size > IMAGE_PROCESS.MAX_INPUT_BYTES) {
|
| 83 |
-
throw new Error('Image exceeds upload budget');
|
| 84 |
-
}
|
| 85 |
-
// 动图保持原格式;不由Canvas变为静态图片。
|
| 86 |
-
if (file.type === 'image/gif') { await validateImageFile(file); return file; }
|
| 87 |
-
return _processImageCore(file, {
|
| 88 |
-
quality: 0.92, fillBackground: '#FFFFFF', maxFileSize: IMAGE_PROCESS.MAX_OUTPUT_BYTES,
|
| 89 |
-
skipIfSmallJpeg: true, suffix: '.jpg'
|
| 90 |
-
});
|
| 91 |
-
}
|
| 92 |
-
|
| 93 |
-
/**
|
| 94 |
-
* 🟢 新增:全局统一的文件上传包装器(供个人设置等其它组件调用)
|
| 95 |
-
* 会在上传前自动拦截并处理头像图片
|
| 96 |
-
*/
|
| 97 |
-
export async function uploadFile(file, file_type, options = {}) {
|
| 98 |
-
const current = options.isCurrent || (() => true);
|
| 99 |
-
const feedback = (message, level) => { if (!options.silent && current()) showToast(message, level); };
|
| 100 |
-
if (!current()) return null;
|
| 101 |
-
try {
|
| 102 |
-
let fileToUpload = file;
|
| 103 |
-
|
| 104 |
-
// 拦截点:如果是头像,就在纯内存中先进行裁剪、缩放、压缩
|
| 105 |
-
if (file_type === "avatar" && file.type && file.type.startsWith("image/")) {
|
| 106 |
-
feedback(`🖼️ ${t('publish.processing_avatar')}`);
|
| 107 |
-
fileToUpload = await processAvatar(file);
|
| 108 |
-
}
|
| 109 |
-
|
| 110 |
-
feedback(`🌐 ${t('publish.uploading_file', { size: (fileToUpload.size/1024).toFixed(1) })}`);
|
| 111 |
-
if (!current()) return null;
|
| 112 |
-
const res = await api.uploadFile(fileToUpload, file_type);
|
| 113 |
-
|
| 114 |
-
if (!current()) return null;
|
| 115 |
-
if (res.status === "success") {
|
| 116 |
-
feedback(`✅ ${t('publish.upload_success')}`);
|
| 117 |
-
return res.url;
|
| 118 |
-
} else {
|
| 119 |
-
feedback(t('publish.upload_failed'), 'error');
|
| 120 |
-
return null;
|
| 121 |
-
}
|
| 122 |
-
} catch (error) {
|
| 123 |
-
feedback(t('publish.upload_error'), 'error');
|
| 124 |
-
return null;
|
| 125 |
-
}
|
| 126 |
-
}
|
| 127 |
-
|
| 128 |
-
// ==========================================
|
| 129 |
-
// 发布表单提交:原会话范围与保存结果核实
|
| 130 |
-
// ==========================================
|
| 131 |
-
export async function handlePublishSubmit(params) {
|
| 132 |
-
const {
|
| 133 |
-
container, currentUser, isEditMode, editItemData,
|
| 134 |
-
imageFiles, jsonFile, onSuccessCallback, submitBtn, submitBtnText // 🖼️ imageFiles 替换 coverFile
|
| 135 |
-
} = params;
|
| 136 |
-
|
| 137 |
-
const scope = params.submissionScope || createPublishSubmissionScope(container, submitBtn, currentUser?.account);
|
| 138 |
-
if (!scope.isCurrent()) return;
|
| 139 |
-
const expectedRevision = isEditMode ? (editItemData?.edit_revision === undefined ? 0 : editItemData.edit_revision) : null;
|
| 140 |
-
if (isEditMode && (!Number.isSafeInteger(expectedRevision) || expectedRevision < 0)) {
|
| 141 |
-
showToast(t('common.operation_failed'), 'error'); return;
|
| 142 |
-
}
|
| 143 |
-
const selectedImages = Array.from(imageFiles || []);
|
| 144 |
-
const typeSelect = container.querySelector("#pub-type");
|
| 145 |
-
const recommendTypeSelect = container.querySelector("#pub-recommend-type");
|
| 146 |
-
const resTypeSelect = container.querySelector("#pub-resource-type");
|
| 147 |
-
const boxPrivateRepo = container.querySelector("#private-repo-settings");
|
| 148 |
-
const isPrivateCheck = container.querySelector("#pub-is-private");
|
| 149 |
-
const inputLink = container.querySelector("#pub-link");
|
| 150 |
-
const inputNetdiskLink = container.querySelector("#pub-netdisk-link"); // ☁️ 网盘链接
|
| 151 |
-
const inputNetdiskPassword = container.querySelector("#pub-netdisk-password"); // 🔐 网盘密码
|
| 152 |
-
|
| 153 |
-
const mainType = typeSelect.value;
|
| 154 |
-
const rules = getSubmitRules(mainType); // 📋 本次提交的声明式规则
|
| 155 |
-
let type = mainType;
|
| 156 |
-
if (mainType === "recommend") type = recommendTypeSelect.value;
|
| 157 |
-
|
| 158 |
-
const title = container.querySelector("#pub-title").value.trim();
|
| 159 |
-
const shortDesc = container.querySelector("#pub-short").value.trim();
|
| 160 |
-
const fullDesc = container.querySelector("#pub-full").value.trim();
|
| 161 |
-
const price = rules.price ? Number(container.querySelector("#pub-price").value) : 0;
|
| 162 |
-
if (!Number.isSafeInteger(price) || price < 0) return showToast(t('common.operation_failed'), "warning");
|
| 163 |
-
|
| 164 |
-
let finalLink = inputLink.value.trim();
|
| 165 |
-
let isJsonUpload = (resTypeSelect.value === "json") || (type === "recommend_app");
|
| 166 |
-
let isNetdisk = (resTypeSelect.value === "netdisk"); // ☁️ 是否网盘模式
|
| 167 |
-
|
| 168 |
-
// ☁️ 网盘模式下使用网盘链接
|
| 169 |
-
if (isNetdisk) {
|
| 170 |
-
finalLink = inputNetdiskLink.value.trim();
|
| 171 |
-
}
|
| 172 |
-
|
| 173 |
-
if (isEditMode && isJsonUpload && !jsonFile && editItemData.link) finalLink = editItemData.link;
|
| 174 |
-
|
| 175 |
-
// ☁️ 网盘密码(加密存储,仅购买后解密显示)
|
| 176 |
-
let netdisk_password = null;
|
| 177 |
-
if (isNetdisk && inputNetdiskPassword.value.trim()) {
|
| 178 |
-
netdisk_password = inputNetdiskPassword.value.trim();
|
| 179 |
-
}
|
| 180 |
-
|
| 181 |
-
let github_token = null;
|
| 182 |
-
// 📋 仅规则允许私有仓库且该区可见、已勾选时才收集 token
|
| 183 |
-
if (rules.privateRepoWhenLink && boxPrivateRepo.style.display !== "none" && isPrivateCheck.checked) {
|
| 184 |
-
github_token = container.querySelector("#pub-github-token").value.trim();
|
| 185 |
-
if (!github_token) {
|
| 186 |
-
const hasExistingToken = isEditMode && !!(editItemData?.github_token || editItemData?.has_private_token);
|
| 187 |
-
if (isEditMode && hasExistingToken) {
|
| 188 |
-
// 编辑模式下已有密钥,留空表示保留原值,不发送 github_token 字段
|
| 189 |
-
github_token = null;
|
| 190 |
-
} else {
|
| 191 |
-
return showToast(t('publish.pat_required'), "warning");
|
| 192 |
-
}
|
| 193 |
-
}
|
| 194 |
-
}
|
| 195 |
-
|
| 196 |
-
if (!title || !shortDesc) return showToast(t('publish.name_desc_required'), "warning");
|
| 197 |
-
if (type === "recommend_link" && !finalLink) return showToast(t('publish.link_required'), "warning");
|
| 198 |
-
if ((type === "tool" || type === "skill" || type === "recommend_tool" || type === "recommend_skill") && !isJsonUpload && !isNetdisk && !finalLink) return showToast(t('publish.git_required'), "warning");
|
| 199 |
-
if (isJsonUpload && !jsonFile && !finalLink) return showToast(t('publish.json_required'), "warning");
|
| 200 |
-
if (isNetdisk && !finalLink) return showToast(t('publish.netdisk_required'), "warning"); // ☁️
|
| 201 |
-
|
| 202 |
-
// 🎨 规则要求原创强制的类型必须勾选原创
|
| 203 |
-
const isOriginalCheckbox = container.querySelector("#is-original-checkbox");
|
| 204 |
-
const isOriginal = isOriginalCheckbox?.checked || false;
|
| 205 |
-
if (rules.originalRequired && !isOriginal) {
|
| 206 |
-
return showToast(t('publish.original_required_toast'), "warning");
|
| 207 |
-
}
|
| 208 |
-
|
| 209 |
-
// 💸 是否支持退款 (仅规则允许的类型提交)
|
| 210 |
-
const allowRefundCheckbox = container.querySelector("#allow-refund-checkbox");
|
| 211 |
-
const allowRefund = rules.refund ? (allowRefundCheckbox?.checked ?? true) : null;
|
| 212 |
-
|
| 213 |
-
if (!scope.begin()) return;
|
| 214 |
-
let committed = false, saveAttempted = false, outcomeUnknown = false;
|
| 215 |
-
submitBtn.innerHTML = `⏳ ${t('publish.connecting')}`;
|
| 216 |
-
submitBtn.disabled = true;
|
| 217 |
-
|
| 218 |
-
try {
|
| 219 |
-
if (isJsonUpload && jsonFile) {
|
| 220 |
-
submitBtn.innerHTML = `⏳ ${t('publish.uploading_secure')}`;
|
| 221 |
-
const uploadType = type.includes("app") ? "app" : (type.includes("tool") || type === "skill" ? "tool" : "recommend");
|
| 222 |
-
const jsonUploadRes = await api.uploadFile(jsonFile, uploadType);
|
| 223 |
-
if (!scope.isCurrent()) return;
|
| 224 |
-
if (jsonUploadRes?.status !== "success" || typeof jsonUploadRes.url !== "string" || !jsonUploadRes.url.trim()) throw new Error("Invalid upload result");
|
| 225 |
-
finalLink = jsonUploadRes.url;
|
| 226 |
-
}
|
| 227 |
-
|
| 228 |
-
// 🖼️ 上传多张效果展示图
|
| 229 |
-
let coverUrl = isEditMode ? editItemData.coverUrl : null;
|
| 230 |
-
let imageUrls = isEditMode ? (editItemData.imageUrls || []) : [];
|
| 231 |
-
|
| 232 |
-
if (selectedImages.length > 0) {
|
| 233 |
-
submitBtn.innerHTML = `⏳ ${t('publish.uploading_images', { current: 0, total: selectedImages.length })}`;
|
| 234 |
-
const uploadedUrls = [];
|
| 235 |
-
|
| 236 |
-
for (let i = 0; i < selectedImages.length; i++) {
|
| 237 |
-
submitBtn.innerHTML = `⏳ ${t('publish.uploading_images', { current: i + 1, total: selectedImages.length })}`;
|
| 238 |
-
// 上传前压缩:转JPG,超5MB压缩
|
| 239 |
-
const processedFile = await compressImageForUpload(selectedImages[i]);
|
| 240 |
-
if (!scope.isCurrent()) return;
|
| 241 |
-
const uploadRes = await api.uploadFile(processedFile, "cover");
|
| 242 |
-
if (!scope.isCurrent()) return;
|
| 243 |
-
if (uploadRes?.status === "success" && typeof uploadRes.url === "string" && uploadRes.url.trim()) {
|
| 244 |
-
uploadedUrls.push(uploadRes.url);
|
| 245 |
-
} else {
|
| 246 |
-
throw new Error("Invalid image upload result");
|
| 247 |
-
}
|
| 248 |
-
}
|
| 249 |
-
|
| 250 |
-
coverUrl = uploadedUrls[0]; // 第一张作为封面
|
| 251 |
-
imageUrls = uploadedUrls; // 全部图片URL
|
| 252 |
-
}
|
| 253 |
-
|
| 254 |
-
if (!scope.isCurrent()) return;
|
| 255 |
-
submitBtn.innerHTML = `⏳ ${t('publish.syncing')}`;
|
| 256 |
-
// 🖼️ 统一封面逻辑:第一张图片始终作为封面(兑容拖拽排序后的顺序变化)
|
| 257 |
-
if (imageUrls && imageUrls.length > 0) {
|
| 258 |
-
coverUrl = imageUrls[0];
|
| 259 |
-
}
|
| 260 |
-
const submitData = {
|
| 261 |
-
...(!isEditMode && scope.publicationId ? { request_id: scope.publicationId } : {}),
|
| 262 |
-
...(isEditMode ? { expected_revision: expectedRevision } : {}),
|
| 263 |
-
type, title, shortDesc, fullDesc, price, link: finalLink, coverUrl, imageUrls, // 🖼️ 添加 imageUrls
|
| 264 |
-
author: currentUser.account, github_token,
|
| 265 |
-
netdisk_password, // ☁️ 网盘密码(后端加密存储)
|
| 266 |
-
is_netdisk: isNetdisk, // ☁️ 标记为网盘资源
|
| 267 |
-
is_original: isOriginal // 🎨 标记为原创作品
|
| 268 |
-
};
|
| 269 |
-
|
| 270 |
-
// 💸 仅 tool/skill/app 类型提交 allow_refund 字段
|
| 271 |
-
if (allowRefund !== null) {
|
| 272 |
-
submitData.allow_refund = allowRefund;
|
| 273 |
-
}
|
| 274 |
-
|
| 275 |
-
saveAttempted = true;
|
| 276 |
-
const result = isEditMode
|
| 277 |
-
? await api.updateItem(editItemData.id, currentUser.account, submitData)
|
| 278 |
-
: await api.publishItem(submitData);
|
| 279 |
-
if (!scope.isCurrent()) return;
|
| 280 |
-
if (result?.status !== "success") throw new Error("Invalid save result");
|
| 281 |
-
committed = true;
|
| 282 |
-
showToast(isEditMode ? `✅ ${t('publish.save_success')}` : `🎉 ${t('publish.publish_success')}`, "success");
|
| 283 |
-
// 主保存已确认;派生缓存或界面回调异常不重新开放提交。
|
| 284 |
-
try { clearItemCacheByType(type); } catch (_) {}
|
| 285 |
-
if (scope.isCurrent() && onSuccessCallback) {
|
| 286 |
-
try { await onSuccessCallback(); } catch (_) {}
|
| 287 |
-
}
|
| 288 |
-
} catch (err) {
|
| 289 |
-
if (!scope.isCurrent() || committed) return;
|
| 290 |
-
if (isEditMode && err?.status === 409 && err?.code === 'resource_revision_conflict') {
|
| 291 |
-
outcomeUnknown = true; // 保持入口锁,要求重开取得新版本;不自动覆盖。
|
| 292 |
-
showToast(t('publish.edit_conflict'), 'warning');
|
| 293 |
-
submitBtn.disabled = true; submitBtn.innerHTML = t('publish.edit_reopen');
|
| 294 |
-
return;
|
| 295 |
-
}
|
| 296 |
-
// 已发出的保存可能在服务端提交;仅已知前置拒绝允许原表单重试。
|
| 297 |
-
const rejected = (err?.requestBodyRejected === true || [400, 401, 403, 404, 409, 422, 429].includes(err?.status));
|
| 298 |
-
outcomeUnknown = saveAttempted && !rejected;
|
| 299 |
-
if (outcomeUnknown) {
|
| 300 |
-
showToast(t('publish.save_unconfirmed'), "warning");
|
| 301 |
-
submitBtn.disabled = true;
|
| 302 |
-
submitBtn.innerHTML = t('publish.result_pending');
|
| 303 |
-
return;
|
| 304 |
-
}
|
| 305 |
-
showToast(t('common.operation_failed'), "error");
|
| 306 |
-
submitBtn.disabled = false;
|
| 307 |
-
submitBtn.innerHTML = submitBtnText;
|
| 308 |
-
} finally {
|
| 309 |
-
scope.finish(committed, outcomeUnknown);
|
| 310 |
-
}
|
| 311 |
-
}
|
|
|
|
| 1 |
+
import { processImageCore as _processImageCore } from "./有界图片处理.js";
|
| 2 |
+
import { validateImageFile } from "./图片文件检查.js";
|
| 3 |
+
import { IMAGE_PROCESS, TYPE_RULES, getSidebarListCacheKey } from "../core/全局配置.js";
|
| 4 |
+
// 前端页面/market/发布内容_提交引擎.js
|
| 5 |
+
import { createPublishSubmissionScope } from "./发布提交生命周期.js";
|
| 6 |
+
import { api } from "../core/网络请求API.js";
|
| 7 |
+
import { showToast } from "../components/UI交互提示组件.js";
|
| 8 |
+
import { t } from "../components/用户体验增强.js";
|
| 9 |
+
import { removeCache, removeCacheByPrefix } from "../components/性能优化工具.js";
|
| 10 |
+
|
| 11 |
+
/**
|
| 12 |
+
* 📋 获取指定主类型的提交规则(校验与字段组装统一读取,与 UI 显隐同源)
|
| 13 |
+
* @param {string} mainType - 主类型: tool/skill/app/recommend
|
| 14 |
+
*/
|
| 15 |
+
function getSubmitRules(mainType) {
|
| 16 |
+
return TYPE_RULES[mainType] || TYPE_RULES.tool;
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
/**
|
| 20 |
+
* 🟢 根据发布类型清除对应缓存(精确清除,不影响其他页面)
|
| 21 |
+
* @param {string} type - 发布类型: tool/skill/app/recommend/recommend_tool/recommend_skill/recommend_app/recommend_link
|
| 22 |
+
*/
|
| 23 |
+
function clearItemCacheByType(type) {
|
| 24 |
+
// 确定当前类型对应的 tab
|
| 25 |
+
let tab = 'recommends';
|
| 26 |
+
if (type === 'tool' || type === 'recommend_tool') {
|
| 27 |
+
tab = 'tools';
|
| 28 |
+
} else if (type === 'skill' || type === 'recommend_skill') {
|
| 29 |
+
tab = 'skills';
|
| 30 |
+
} else if (type === 'app' || type === 'recommend_app') {
|
| 31 |
+
tab = 'apps';
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
// 清除 API 缓存
|
| 35 |
+
// 🔧 修复:API 层缓存键总是带完整查询串(api_/api/items?type=tool&sort=time&limit=200),
|
| 36 |
+
// 而 removeCache 是精确键删除,原先这几个调用一个也命中不到(no-op),发布成功后
|
| 37 |
+
// request() 仍会从缓存直接返回旧列表、看不到刚发布的内容。改用前缀删除,
|
| 38 |
+
// 一次覆盖全部 type/sort/limit 组合(原先按 type 单独删的那行已被本前缀覆盖,属冗余)
|
| 39 |
+
removeCacheByPrefix('api_/api/items');
|
| 40 |
+
removeCacheByPrefix('api_/api/creators'); // 创作者列表也需要刷新
|
| 41 |
+
|
| 42 |
+
// 清除侧边栏数据引擎缓存(只清除对应类型)
|
| 43 |
+
const sorts = ['time', 'downloads', 'likes', 'favorites', 'tips', 'views', 'daily_views', 'rating'];
|
| 44 |
+
for (const sort of sorts) {
|
| 45 |
+
removeCache(getSidebarListCacheKey(tab, sort));
|
| 46 |
+
removeCache(getSidebarListCacheKey('creators', sort)); // 创作者列表
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
console.log(`🗑️ 已清除 [${tab}] 类型的列表缓存`);
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
/**
|
| 53 |
+
* 🟢 利用 HTML5 Canvas 纯前端裁剪并压缩头像
|
| 54 |
+
* 功能:强制 1:1 比例中心裁剪,缩放到 512x512,转换为 JPG 格式。
|
| 55 |
+
*/
|
| 56 |
+
function processAvatar(file) {
|
| 57 |
+
return _processImageCore(file, {
|
| 58 |
+
cropToSquare: true,
|
| 59 |
+
maxFileSize: IMAGE_PROCESS.AVATAR_MAX_BYTES,
|
| 60 |
+
targetSize: IMAGE_PROCESS.AVATAR_SIZE,
|
| 61 |
+
quality: 0.85,
|
| 62 |
+
suffix: '_cropped.jpg'
|
| 63 |
+
}).then(processedFile => {
|
| 64 |
+
console.log(`✅ 头像处理完成:原始 ${(file.size/1024).toFixed(1)}KB -> 压缩后 ${(processedFile.size/1024).toFixed(1)}KB`);
|
| 65 |
+
return processedFile;
|
| 66 |
+
});
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
/**
|
| 70 |
+
* 上传前图片压缩处理
|
| 71 |
+
* - 转为 JPG 格式
|
| 72 |
+
* - 最长边至多4096并保持比例;质量压缩后仍超过5MB则拒绝
|
| 73 |
+
* @param {File} file - 原始图片文件
|
| 74 |
+
* @returns {Promise<File>} - 处理后的文件
|
| 75 |
+
*/
|
| 76 |
+
export async function compressImageForUpload(file) {
|
| 77 |
+
// 如果不是图片文件,直接返回
|
| 78 |
+
if (!file.type || !file.type.startsWith('image/')) {
|
| 79 |
+
return file;
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
if (!Number.isFinite(file.size) || file.size < 0 || file.size > IMAGE_PROCESS.MAX_INPUT_BYTES) {
|
| 83 |
+
throw new Error('Image exceeds upload budget');
|
| 84 |
+
}
|
| 85 |
+
// 动图保持原格式;不由Canvas变为静态图片。
|
| 86 |
+
if (file.type === 'image/gif') { await validateImageFile(file); return file; }
|
| 87 |
+
return _processImageCore(file, {
|
| 88 |
+
quality: 0.92, fillBackground: '#FFFFFF', maxFileSize: IMAGE_PROCESS.MAX_OUTPUT_BYTES,
|
| 89 |
+
skipIfSmallJpeg: true, suffix: '.jpg'
|
| 90 |
+
});
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
/**
|
| 94 |
+
* 🟢 新增:全局统一的文件上传包装器(供个人设置等其它组件调用)
|
| 95 |
+
* 会在上传前自动拦截并处理头像图片
|
| 96 |
+
*/
|
| 97 |
+
export async function uploadFile(file, file_type, options = {}) {
|
| 98 |
+
const current = options.isCurrent || (() => true);
|
| 99 |
+
const feedback = (message, level) => { if (!options.silent && current()) showToast(message, level); };
|
| 100 |
+
if (!current()) return null;
|
| 101 |
+
try {
|
| 102 |
+
let fileToUpload = file;
|
| 103 |
+
|
| 104 |
+
// 拦截点:如果是头像,就在纯内存中先进行裁剪、缩放、压缩
|
| 105 |
+
if (file_type === "avatar" && file.type && file.type.startsWith("image/")) {
|
| 106 |
+
feedback(`🖼️ ${t('publish.processing_avatar')}`);
|
| 107 |
+
fileToUpload = await processAvatar(file);
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
feedback(`🌐 ${t('publish.uploading_file', { size: (fileToUpload.size/1024).toFixed(1) })}`);
|
| 111 |
+
if (!current()) return null;
|
| 112 |
+
const res = await api.uploadFile(fileToUpload, file_type);
|
| 113 |
+
|
| 114 |
+
if (!current()) return null;
|
| 115 |
+
if (res.status === "success") {
|
| 116 |
+
feedback(`✅ ${t('publish.upload_success')}`);
|
| 117 |
+
return res.url;
|
| 118 |
+
} else {
|
| 119 |
+
feedback(t('publish.upload_failed'), 'error');
|
| 120 |
+
return null;
|
| 121 |
+
}
|
| 122 |
+
} catch (error) {
|
| 123 |
+
feedback(t('publish.upload_error'), 'error');
|
| 124 |
+
return null;
|
| 125 |
+
}
|
| 126 |
+
}
|
| 127 |
+
|
| 128 |
+
// ==========================================
|
| 129 |
+
// 发布表单提交:原会话范围与保存结果核实
|
| 130 |
+
// ==========================================
|
| 131 |
+
export async function handlePublishSubmit(params) {
|
| 132 |
+
const {
|
| 133 |
+
container, currentUser, isEditMode, editItemData,
|
| 134 |
+
imageFiles, jsonFile, onSuccessCallback, submitBtn, submitBtnText // 🖼️ imageFiles 替换 coverFile
|
| 135 |
+
} = params;
|
| 136 |
+
|
| 137 |
+
const scope = params.submissionScope || createPublishSubmissionScope(container, submitBtn, currentUser?.account);
|
| 138 |
+
if (!scope.isCurrent()) return;
|
| 139 |
+
const expectedRevision = isEditMode ? (editItemData?.edit_revision === undefined ? 0 : editItemData.edit_revision) : null;
|
| 140 |
+
if (isEditMode && (!Number.isSafeInteger(expectedRevision) || expectedRevision < 0)) {
|
| 141 |
+
showToast(t('common.operation_failed'), 'error'); return;
|
| 142 |
+
}
|
| 143 |
+
const selectedImages = Array.from(imageFiles || []);
|
| 144 |
+
const typeSelect = container.querySelector("#pub-type");
|
| 145 |
+
const recommendTypeSelect = container.querySelector("#pub-recommend-type");
|
| 146 |
+
const resTypeSelect = container.querySelector("#pub-resource-type");
|
| 147 |
+
const boxPrivateRepo = container.querySelector("#private-repo-settings");
|
| 148 |
+
const isPrivateCheck = container.querySelector("#pub-is-private");
|
| 149 |
+
const inputLink = container.querySelector("#pub-link");
|
| 150 |
+
const inputNetdiskLink = container.querySelector("#pub-netdisk-link"); // ☁️ 网盘链接
|
| 151 |
+
const inputNetdiskPassword = container.querySelector("#pub-netdisk-password"); // 🔐 网盘密码
|
| 152 |
+
|
| 153 |
+
const mainType = typeSelect.value;
|
| 154 |
+
const rules = getSubmitRules(mainType); // 📋 本次提交的声明式规则
|
| 155 |
+
let type = mainType;
|
| 156 |
+
if (mainType === "recommend") type = recommendTypeSelect.value;
|
| 157 |
+
|
| 158 |
+
const title = container.querySelector("#pub-title").value.trim();
|
| 159 |
+
const shortDesc = container.querySelector("#pub-short").value.trim();
|
| 160 |
+
const fullDesc = container.querySelector("#pub-full").value.trim();
|
| 161 |
+
const price = rules.price ? Number(container.querySelector("#pub-price").value) : 0;
|
| 162 |
+
if (!Number.isSafeInteger(price) || price < 0) return showToast(t('common.operation_failed'), "warning");
|
| 163 |
+
|
| 164 |
+
let finalLink = inputLink.value.trim();
|
| 165 |
+
let isJsonUpload = (resTypeSelect.value === "json") || (type === "recommend_app");
|
| 166 |
+
let isNetdisk = (resTypeSelect.value === "netdisk"); // ☁️ 是否网盘模式
|
| 167 |
+
|
| 168 |
+
// ☁️ 网盘模式下使用网盘链接
|
| 169 |
+
if (isNetdisk) {
|
| 170 |
+
finalLink = inputNetdiskLink.value.trim();
|
| 171 |
+
}
|
| 172 |
+
|
| 173 |
+
if (isEditMode && isJsonUpload && !jsonFile && editItemData.link) finalLink = editItemData.link;
|
| 174 |
+
|
| 175 |
+
// ☁️ 网盘密码(加密存储,仅购买后解密显示)
|
| 176 |
+
let netdisk_password = null;
|
| 177 |
+
if (isNetdisk && inputNetdiskPassword.value.trim()) {
|
| 178 |
+
netdisk_password = inputNetdiskPassword.value.trim();
|
| 179 |
+
}
|
| 180 |
+
|
| 181 |
+
let github_token = null;
|
| 182 |
+
// 📋 仅规则允许私有仓库且该区可见、已勾选时才收集 token
|
| 183 |
+
if (rules.privateRepoWhenLink && boxPrivateRepo.style.display !== "none" && isPrivateCheck.checked) {
|
| 184 |
+
github_token = container.querySelector("#pub-github-token").value.trim();
|
| 185 |
+
if (!github_token) {
|
| 186 |
+
const hasExistingToken = isEditMode && !!(editItemData?.github_token || editItemData?.has_private_token);
|
| 187 |
+
if (isEditMode && hasExistingToken) {
|
| 188 |
+
// 编辑模式下已有密钥,留空表示保留原值,不发送 github_token 字段
|
| 189 |
+
github_token = null;
|
| 190 |
+
} else {
|
| 191 |
+
return showToast(t('publish.pat_required'), "warning");
|
| 192 |
+
}
|
| 193 |
+
}
|
| 194 |
+
}
|
| 195 |
+
|
| 196 |
+
if (!title || !shortDesc) return showToast(t('publish.name_desc_required'), "warning");
|
| 197 |
+
if (type === "recommend_link" && !finalLink) return showToast(t('publish.link_required'), "warning");
|
| 198 |
+
if ((type === "tool" || type === "skill" || type === "recommend_tool" || type === "recommend_skill") && !isJsonUpload && !isNetdisk && !finalLink) return showToast(t('publish.git_required'), "warning");
|
| 199 |
+
if (isJsonUpload && !jsonFile && !finalLink) return showToast(t('publish.json_required'), "warning");
|
| 200 |
+
if (isNetdisk && !finalLink) return showToast(t('publish.netdisk_required'), "warning"); // ☁️
|
| 201 |
+
|
| 202 |
+
// 🎨 规则要求原创强制的类型必须勾选原创
|
| 203 |
+
const isOriginalCheckbox = container.querySelector("#is-original-checkbox");
|
| 204 |
+
const isOriginal = isOriginalCheckbox?.checked || false;
|
| 205 |
+
if (rules.originalRequired && !isOriginal) {
|
| 206 |
+
return showToast(t('publish.original_required_toast'), "warning");
|
| 207 |
+
}
|
| 208 |
+
|
| 209 |
+
// 💸 是否支持退款 (仅规则允许的类型提交)
|
| 210 |
+
const allowRefundCheckbox = container.querySelector("#allow-refund-checkbox");
|
| 211 |
+
const allowRefund = rules.refund ? (allowRefundCheckbox?.checked ?? true) : null;
|
| 212 |
+
|
| 213 |
+
if (!scope.begin()) return;
|
| 214 |
+
let committed = false, saveAttempted = false, outcomeUnknown = false;
|
| 215 |
+
submitBtn.innerHTML = `⏳ ${t('publish.connecting')}`;
|
| 216 |
+
submitBtn.disabled = true;
|
| 217 |
+
|
| 218 |
+
try {
|
| 219 |
+
if (isJsonUpload && jsonFile) {
|
| 220 |
+
submitBtn.innerHTML = `⏳ ${t('publish.uploading_secure')}`;
|
| 221 |
+
const uploadType = type.includes("app") ? "app" : (type.includes("tool") || type === "skill" ? "tool" : "recommend");
|
| 222 |
+
const jsonUploadRes = await api.uploadFile(jsonFile, uploadType);
|
| 223 |
+
if (!scope.isCurrent()) return;
|
| 224 |
+
if (jsonUploadRes?.status !== "success" || typeof jsonUploadRes.url !== "string" || !jsonUploadRes.url.trim()) throw new Error("Invalid upload result");
|
| 225 |
+
finalLink = jsonUploadRes.url;
|
| 226 |
+
}
|
| 227 |
+
|
| 228 |
+
// 🖼️ 上传多张效果展示图
|
| 229 |
+
let coverUrl = isEditMode ? editItemData.coverUrl : null;
|
| 230 |
+
let imageUrls = isEditMode ? (editItemData.imageUrls || []) : [];
|
| 231 |
+
|
| 232 |
+
if (selectedImages.length > 0) {
|
| 233 |
+
submitBtn.innerHTML = `⏳ ${t('publish.uploading_images', { current: 0, total: selectedImages.length })}`;
|
| 234 |
+
const uploadedUrls = [];
|
| 235 |
+
|
| 236 |
+
for (let i = 0; i < selectedImages.length; i++) {
|
| 237 |
+
submitBtn.innerHTML = `⏳ ${t('publish.uploading_images', { current: i + 1, total: selectedImages.length })}`;
|
| 238 |
+
// 上传前压缩:转JPG,超5MB压缩
|
| 239 |
+
const processedFile = await compressImageForUpload(selectedImages[i]);
|
| 240 |
+
if (!scope.isCurrent()) return;
|
| 241 |
+
const uploadRes = await api.uploadFile(processedFile, "cover");
|
| 242 |
+
if (!scope.isCurrent()) return;
|
| 243 |
+
if (uploadRes?.status === "success" && typeof uploadRes.url === "string" && uploadRes.url.trim()) {
|
| 244 |
+
uploadedUrls.push(uploadRes.url);
|
| 245 |
+
} else {
|
| 246 |
+
throw new Error("Invalid image upload result");
|
| 247 |
+
}
|
| 248 |
+
}
|
| 249 |
+
|
| 250 |
+
coverUrl = uploadedUrls[0]; // 第一张作为封面
|
| 251 |
+
imageUrls = uploadedUrls; // 全部图片URL
|
| 252 |
+
}
|
| 253 |
+
|
| 254 |
+
if (!scope.isCurrent()) return;
|
| 255 |
+
submitBtn.innerHTML = `⏳ ${t('publish.syncing')}`;
|
| 256 |
+
// 🖼️ 统一封面逻辑:第一张图片始终作为封面(兑容拖拽排序后的顺序变化)
|
| 257 |
+
if (imageUrls && imageUrls.length > 0) {
|
| 258 |
+
coverUrl = imageUrls[0];
|
| 259 |
+
}
|
| 260 |
+
const submitData = {
|
| 261 |
+
...(!isEditMode && scope.publicationId ? { request_id: scope.publicationId } : {}),
|
| 262 |
+
...(isEditMode ? { expected_revision: expectedRevision } : {}),
|
| 263 |
+
type, title, shortDesc, fullDesc, price, link: finalLink, coverUrl, imageUrls, // 🖼️ 添加 imageUrls
|
| 264 |
+
author: currentUser.account, github_token,
|
| 265 |
+
netdisk_password, // ☁️ 网盘密码(后端加密存储)
|
| 266 |
+
is_netdisk: isNetdisk, // ☁️ 标记为网盘资源
|
| 267 |
+
is_original: isOriginal // 🎨 标记为原创作品
|
| 268 |
+
};
|
| 269 |
+
|
| 270 |
+
// 💸 仅 tool/skill/app 类型提交 allow_refund 字段
|
| 271 |
+
if (allowRefund !== null) {
|
| 272 |
+
submitData.allow_refund = allowRefund;
|
| 273 |
+
}
|
| 274 |
+
|
| 275 |
+
saveAttempted = true;
|
| 276 |
+
const result = isEditMode
|
| 277 |
+
? await api.updateItem(editItemData.id, currentUser.account, submitData)
|
| 278 |
+
: await api.publishItem(submitData);
|
| 279 |
+
if (!scope.isCurrent()) return;
|
| 280 |
+
if (result?.status !== "success") throw new Error("Invalid save result");
|
| 281 |
+
committed = true;
|
| 282 |
+
showToast(isEditMode ? `✅ ${t('publish.save_success')}` : `🎉 ${t('publish.publish_success')}`, "success");
|
| 283 |
+
// 主保存已确认;派生缓存或界面回调异常不重新开放提交。
|
| 284 |
+
try { clearItemCacheByType(type); } catch (_) {}
|
| 285 |
+
if (scope.isCurrent() && onSuccessCallback) {
|
| 286 |
+
try { await onSuccessCallback(); } catch (_) {}
|
| 287 |
+
}
|
| 288 |
+
} catch (err) {
|
| 289 |
+
if (!scope.isCurrent() || committed) return;
|
| 290 |
+
if (isEditMode && err?.status === 409 && err?.code === 'resource_revision_conflict') {
|
| 291 |
+
outcomeUnknown = true; // 保持入口锁,要求重开取得新版本;不自动覆盖。
|
| 292 |
+
showToast(t('publish.edit_conflict'), 'warning');
|
| 293 |
+
submitBtn.disabled = true; submitBtn.innerHTML = t('publish.edit_reopen');
|
| 294 |
+
return;
|
| 295 |
+
}
|
| 296 |
+
// 已发出的保存可能在服务端提交;仅已知前置拒绝允许原表单重试。
|
| 297 |
+
const rejected = (err?.requestBodyRejected === true || [400, 401, 403, 404, 409, 422, 429].includes(err?.status));
|
| 298 |
+
outcomeUnknown = saveAttempted && !rejected;
|
| 299 |
+
if (outcomeUnknown) {
|
| 300 |
+
showToast(t('publish.save_unconfirmed'), "warning");
|
| 301 |
+
submitBtn.disabled = true;
|
| 302 |
+
submitBtn.innerHTML = t('publish.result_pending');
|
| 303 |
+
return;
|
| 304 |
+
}
|
| 305 |
+
showToast(t('common.operation_failed'), "error");
|
| 306 |
+
submitBtn.disabled = false;
|
| 307 |
+
submitBtn.innerHTML = submitBtnText;
|
| 308 |
+
} finally {
|
| 309 |
+
scope.finish(committed, outcomeUnknown);
|
| 310 |
+
}
|
| 311 |
+
}
|
前端页面/market/安装目录.js
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { LOCAL_INSTALL_DIRECTORY, SKILL_INSTALL } from '../core/全局配置.js';
|
| 2 |
+
import { readLocalJSON } from '../core/本机请求读取.js';
|
| 3 |
+
import { t } from '../components/用户体验_国际化.js';
|
| 4 |
+
|
| 5 |
+
const mounted = new WeakMap();
|
| 6 |
+
const errors = Object.freeze({
|
| 7 |
+
invalid_target: () => t('install.directory_unavailable'), target_changed: () => t('install.directory_unavailable'),
|
| 8 |
+
invalid_repository: () => t('install.error_invalid_repository'), invalid_plan: () => t('skill.plan_invalid'),
|
| 9 |
+
plan_expired: () => t('skill.plan_invalid'), plan_owner_mismatch: () => t('skill.identity_changed'),
|
| 10 |
+
auth_failed: () => t('skill.identity_changed'), install_queue_full: () => t('install.error_queue_full'),
|
| 11 |
+
install_queue_timeout: () => t('install.error_queue_timeout'),
|
| 12 |
+
directory_open_unavailable: () => t('install.directory_failed'), directory_open_failed: () => t('install.directory_failed')
|
| 13 |
+
});
|
| 14 |
+
|
| 15 |
+
export function attachInstallDirectory(container, body, scope, { skill = false } = {}) {
|
| 16 |
+
mounted.get(container)?.();
|
| 17 |
+
if (!scope.isCurrent() || !container.isConnected) return;
|
| 18 |
+
const payload = JSON.stringify(skill ? { ...body, action: 'open' } : body);
|
| 19 |
+
const host = document.createElement('div'); host.className = 'resource-install__directory';
|
| 20 |
+
const button = document.createElement('button'); button.type = 'button'; button.className = 'resource-install__button';
|
| 21 |
+
const label = t(skill ? 'install.open_receiver' : 'install.open_directory'); button.textContent = label;
|
| 22 |
+
const notice = document.createElement('div'); notice.className = 'resource-install__note';
|
| 23 |
+
notice.setAttribute('role', 'status'); notice.setAttribute('aria-live', 'polite');
|
| 24 |
+
let disposed = false, controller, busy = false, release = () => {};
|
| 25 |
+
const current = () => !disposed && scope.isCurrent() && host.isConnected;
|
| 26 |
+
const cleanup = () => {
|
| 27 |
+
if (disposed) return;
|
| 28 |
+
disposed = true; controller?.abort(); button.removeEventListener('click', open); host.remove(); release();
|
| 29 |
+
if (mounted.get(container) === cleanup) mounted.delete(container);
|
| 30 |
+
};
|
| 31 |
+
async function open(event) {
|
| 32 |
+
event.stopPropagation();
|
| 33 |
+
if (busy || !current()) return;
|
| 34 |
+
const hadFocus = document.activeElement === button;
|
| 35 |
+
busy = true; button.disabled = true; button.setAttribute('aria-busy', 'true');
|
| 36 |
+
button.textContent = t('common.loading'); notice.textContent = '';
|
| 37 |
+
controller = new AbortController();
|
| 38 |
+
const timer = setTimeout(() => controller.abort(), LOCAL_INSTALL_DIRECTORY.TIMEOUT);
|
| 39 |
+
try {
|
| 40 |
+
const response = await fetch(skill ? SKILL_INSTALL.PATH : LOCAL_INSTALL_DIRECTORY.PATH, {
|
| 41 |
+
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: payload,
|
| 42 |
+
cache: 'no-store', signal: controller.signal
|
| 43 |
+
});
|
| 44 |
+
if (!current()) return;
|
| 45 |
+
if (response.status === 404 || response.status === 405) {
|
| 46 |
+
notice.textContent = t('skill.local_update_required'); return;
|
| 47 |
+
}
|
| 48 |
+
const result = await readLocalJSON(response, controller, LOCAL_INSTALL_DIRECTORY.RESPONSE_MAX_BYTES);
|
| 49 |
+
if (!current()) return;
|
| 50 |
+
if (response.ok && result && !Array.isArray(result) && result.status === 'success'
|
| 51 |
+
&& result.phase === 'opened' && result.opened === true && result.installed === false
|
| 52 |
+
&& !Object.hasOwn(result, 'error') && !Object.hasOwn(result, 'error_code')) {
|
| 53 |
+
notice.textContent = t('install.directory_requested');
|
| 54 |
+
} else {
|
| 55 |
+
notice.textContent = result && Object.hasOwn(errors, result.error_code) ? errors[result.error_code]()
|
| 56 |
+
: response.ok ? t('install.directory_uncertain') : t('install.directory_failed');
|
| 57 |
+
}
|
| 58 |
+
} catch {
|
| 59 |
+
if (current()) notice.textContent = t('install.directory_uncertain');
|
| 60 |
+
} finally {
|
| 61 |
+
clearTimeout(timer); controller?.abort();
|
| 62 |
+
if (current()) {
|
| 63 |
+
busy = false; button.disabled = false; button.removeAttribute('aria-busy'); button.textContent = label;
|
| 64 |
+
if (hadFocus && document.hasFocus() && document.activeElement === document.body) button.focus();
|
| 65 |
+
}
|
| 66 |
+
}
|
| 67 |
+
}
|
| 68 |
+
button.addEventListener('click', open); host.append(button, notice); container.append(host);
|
| 69 |
+
mounted.set(container, cleanup); release = scope.addCleanup(cleanup, host);
|
| 70 |
+
if (!current()) cleanup();
|
| 71 |
+
return cleanup;
|
| 72 |
+
}
|
前端页面/market/资源安装引擎.js
CHANGED
|
@@ -3,10 +3,11 @@ import { showToast, showConfirm, createInstallProgress } from "../components/UI
|
|
| 3 |
import { api } from "../core/网络请求API.js";
|
| 4 |
import { requestSSE, request } from "../core/网络请求_基础设施.js";
|
| 5 |
import { openUserProfileModal } from "../profile/个人中心视图.js";
|
| 6 |
-
import { API, CACHE, SKILL_INSTALL, UI, IS_WEB_MODE, escapeHtml } from "../core/全局配置.js";
|
| 7 |
import { t } from "../components/用户体验增强.js";
|
| 8 |
import { createResourceOperationScope } from "./资源操作生命周期.js";
|
| 9 |
import { describeInstallSource } from "./安装来源.js";
|
|
|
|
| 10 |
import { isValidPurchaseStatus } from "./购买状态生命周期.js";
|
| 11 |
import { saveAcquiredItem } from "./资源获取记录.js";
|
| 12 |
export { getAcquiredItems } from "./资源获取记录.js";
|
|
@@ -43,7 +44,7 @@ function clearUsesCache() {
|
|
| 43 |
const sorts = ['time', 'downloads', 'likes', 'favorites', 'tips', 'views', 'daily_views', 'rating'];
|
| 44 |
for (const tab of tabs) {
|
| 45 |
for (const sort of sorts) {
|
| 46 |
-
removeCache(
|
| 47 |
}
|
| 48 |
}
|
| 49 |
console.log('📊 使用量缓存已清除');
|
|
@@ -550,6 +551,7 @@ export function setupResourceInstall(btnUse, itemData, currentUser, inlineStatus
|
|
| 550 |
const controller = new AbortController();
|
| 551 |
const removeCancel = scope.addCleanup(() => controller.abort());
|
| 552 |
progress.addCancelButton(t('install.cancel_in_progress'), () => controller.abort());
|
|
|
|
| 553 |
try {
|
| 554 |
const result = await skillFlow.runSkillInstall({
|
| 555 |
target: skillTarget, credentials: { account, token, item_id: String(itemData.id) }, scope,
|
|
@@ -565,6 +567,7 @@ export function setupResourceInstall(btnUse, itemData, currentUser, inlineStatus
|
|
| 565 |
});
|
| 566 |
if (!isCurrent()) return;
|
| 567 |
if (result.status === 'cancelled') { restoreFocus = true; progress.error(t('skill.cancelled')); return; }
|
|
|
|
| 568 |
if (result.outcomeUnknown) {
|
| 569 |
phase = 'unknown'; btnUse.removeAttribute('aria-busy');
|
| 570 |
progress.error(t('skill.outcome_unknown')); return;
|
|
@@ -582,6 +585,11 @@ export function setupResourceInstall(btnUse, itemData, currentUser, inlineStatus
|
|
| 582 |
if (isCurrent()) progress.error(controller.signal.aborted ? t('skill.cancelled') : skillFlow.skillErrorMessage(error));
|
| 583 |
} finally {
|
| 584 |
removeCancel(); controller.abort();
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 585 |
if (phase === 'install') phase = 'idle';
|
| 586 |
releaseButton();
|
| 587 |
}
|
|
@@ -683,6 +691,7 @@ export function setupResourceInstall(btnUse, itemData, currentUser, inlineStatus
|
|
| 683 |
confirmInstallButton.onclick = async () => {
|
| 684 |
if (!isCurrent() || phase !== "confirm") return;
|
| 685 |
phase = "install";
|
|
|
|
| 686 |
try {
|
| 687 |
removeInstallEscapeHandler();
|
| 688 |
confirmInstallButton.disabled = true;
|
|
@@ -723,6 +732,7 @@ export function setupResourceInstall(btnUse, itemData, currentUser, inlineStatus
|
|
| 723 |
? "/community_hub/install_tool"
|
| 724 |
: "/community_hub/install_private_tool";
|
| 725 |
|
|
|
|
| 726 |
const progress = trackProgress();
|
| 727 |
const cancelController = new AbortController();
|
| 728 |
progress.addCancelButton(t('install.cancel_in_progress'), () => cancelController.abort());
|
|
@@ -879,7 +889,10 @@ export function setupResourceInstall(btnUse, itemData, currentUser, inlineStatus
|
|
| 879 |
}
|
| 880 |
} catch (_) {
|
| 881 |
if (isCurrent()) { phase = "unknown"; btnUse.removeAttribute("aria-busy"); inlineStatusBox.textContent = t('install.connection_uncertain'); }
|
| 882 |
-
} finally {
|
|
|
|
|
|
|
|
|
|
| 883 |
};
|
| 884 |
} else if (isApp) {
|
| 885 |
const progress = trackProgress();
|
|
|
|
| 3 |
import { api } from "../core/网络请求API.js";
|
| 4 |
import { requestSSE, request } from "../core/网络请求_基础设施.js";
|
| 5 |
import { openUserProfileModal } from "../profile/个人中心视图.js";
|
| 6 |
+
import { API, CACHE, SKILL_INSTALL, UI, IS_WEB_MODE, escapeHtml, getSidebarListCacheKey } from "../core/全局配置.js";
|
| 7 |
import { t } from "../components/用户体验增强.js";
|
| 8 |
import { createResourceOperationScope } from "./资源操作生命周期.js";
|
| 9 |
import { describeInstallSource } from "./安装来源.js";
|
| 10 |
+
import { attachInstallDirectory } from "./安装目录.js";
|
| 11 |
import { isValidPurchaseStatus } from "./购买状态生命周期.js";
|
| 12 |
import { saveAcquiredItem } from "./资源获取记录.js";
|
| 13 |
export { getAcquiredItems } from "./资源获取记录.js";
|
|
|
|
| 44 |
const sorts = ['time', 'downloads', 'likes', 'favorites', 'tips', 'views', 'daily_views', 'rating'];
|
| 45 |
for (const tab of tabs) {
|
| 46 |
for (const sort of sorts) {
|
| 47 |
+
removeCache(getSidebarListCacheKey(tab, sort));
|
| 48 |
}
|
| 49 |
}
|
| 50 |
console.log('📊 使用量缓存已清除');
|
|
|
|
| 551 |
const controller = new AbortController();
|
| 552 |
const removeCancel = scope.addCleanup(() => controller.abort());
|
| 553 |
progress.addCancelButton(t('install.cancel_in_progress'), () => controller.abort());
|
| 554 |
+
let directoryPlan;
|
| 555 |
try {
|
| 556 |
const result = await skillFlow.runSkillInstall({
|
| 557 |
target: skillTarget, credentials: { account, token, item_id: String(itemData.id) }, scope,
|
|
|
|
| 567 |
});
|
| 568 |
if (!isCurrent()) return;
|
| 569 |
if (result.status === 'cancelled') { restoreFocus = true; progress.error(t('skill.cancelled')); return; }
|
| 570 |
+
if (typeof result.plan_id === 'string' && /^[a-f0-9]{32}$/.test(result.plan_id)) directoryPlan = result.plan_id;
|
| 571 |
if (result.outcomeUnknown) {
|
| 572 |
phase = 'unknown'; btnUse.removeAttribute('aria-busy');
|
| 573 |
progress.error(t('skill.outcome_unknown')); return;
|
|
|
|
| 585 |
if (isCurrent()) progress.error(controller.signal.aborted ? t('skill.cancelled') : skillFlow.skillErrorMessage(error));
|
| 586 |
} finally {
|
| 587 |
removeCancel(); controller.abort();
|
| 588 |
+
try {
|
| 589 |
+
if (directoryPlan && isCurrent()) attachInstallDirectory(inlineStatusBox, {
|
| 590 |
+
plan_id: directoryPlan, account, token, item_id: String(itemData.id)
|
| 591 |
+
}, scope, { skill: true });
|
| 592 |
+
} catch {}
|
| 593 |
if (phase === 'install') phase = 'idle';
|
| 594 |
releaseButton();
|
| 595 |
}
|
|
|
|
| 691 |
confirmInstallButton.onclick = async () => {
|
| 692 |
if (!isCurrent() || phase !== "confirm") return;
|
| 693 |
phase = "install";
|
| 694 |
+
let directoryAttempted = false;
|
| 695 |
try {
|
| 696 |
removeInstallEscapeHandler();
|
| 697 |
confirmInstallButton.disabled = true;
|
|
|
|
| 732 |
? "/community_hub/install_tool"
|
| 733 |
: "/community_hub/install_private_tool";
|
| 734 |
|
| 735 |
+
directoryAttempted = true;
|
| 736 |
const progress = trackProgress();
|
| 737 |
const cancelController = new AbortController();
|
| 738 |
progress.addCancelButton(t('install.cancel_in_progress'), () => cancelController.abort());
|
|
|
|
| 889 |
}
|
| 890 |
} catch (_) {
|
| 891 |
if (isCurrent()) { phase = "unknown"; btnUse.removeAttribute("aria-busy"); inlineStatusBox.textContent = t('install.connection_uncertain'); }
|
| 892 |
+
} finally {
|
| 893 |
+
try { if (directoryAttempted && isCurrent()) attachInstallDirectory(inlineStatusBox, { url: itemData.link }, scope); } catch {}
|
| 894 |
+
if (phase === "install") phase = "idle"; releaseButton();
|
| 895 |
+
}
|
| 896 |
};
|
| 897 |
} else if (isApp) {
|
| 898 |
const progress = trackProgress();
|
前端页面/market/资源操作生命周期.js
CHANGED
|
@@ -1,52 +1,62 @@
|
|
| 1 |
-
// 安装与交付入口共用原账号/节点范围;已经提交的购买和安装不自动重放。
|
| 2 |
-
import { captureRequestSession, requestCancelManager } from "../core/网络请求API.js";
|
| 3 |
-
import { API, CACHE } from "../core/全局配置.js";
|
| 4 |
-
import { getUser, eventBus, EVENTS } from "../core/状态管理.js";
|
| 5 |
-
import { createTaskViewScope, subscribeTaskSessionChanges } from "../task/任务视图生命周期.js";
|
| 6 |
-
|
| 7 |
-
const scopes = new WeakMap();
|
| 8 |
-
let sequence = 0;
|
| 9 |
-
export function createResourceOperationScope(button, statusBox, account, options = {}) {
|
| 10 |
-
scopes.get(button)?.dispose();
|
| 11 |
-
const matches = captureRequestSession(), componentId = `resource-operation-${++sequence}`;
|
| 12 |
-
const confirmation = new AbortController(), cleanups = new Set();
|
| 13 |
-
let inner, observer, disposed = false;
|
| 14 |
-
const cleanup = () => {
|
| 15 |
-
if (disposed) return;
|
| 16 |
-
disposed = true;
|
| 17 |
-
observer?.disconnect(); confirmation.abort();
|
| 18 |
-
button.disabled = true; button.removeAttribute("aria-busy");
|
| 19 |
-
statusBox.replaceChildren(); statusBox.style.display = "none";
|
| 20 |
-
for (const callback of cleanups) { try { callback(); } catch (_) {} }
|
| 21 |
-
cleanups.clear();
|
| 22 |
-
};
|
| 23 |
-
const scope = {
|
| 24 |
-
readOptions: { noCache: true, componentId, timeout: API.BACKGROUND_TIMEOUT, retries: API.BACKGROUND_RETRIES },
|
| 25 |
-
confirmationSignal: confirmation.signal,
|
| 26 |
-
dispose() { if (inner) inner.dispose(); else cleanup(); },
|
| 27 |
-
addCleanup(callback) {
|
| 28 |
-
if (disposed) { callback(); return () => {}; }
|
| 29 |
-
cleanups.add(callback);
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
if (
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// 安装与交付入口共用原账号/节点范围;已经提交的购买和安装不自动重放。
|
| 2 |
+
import { captureRequestSession, requestCancelManager } from "../core/网络请求API.js";
|
| 3 |
+
import { API, CACHE } from "../core/全局配置.js";
|
| 4 |
+
import { getUser, eventBus, EVENTS } from "../core/状态管理.js";
|
| 5 |
+
import { createTaskViewScope, subscribeTaskSessionChanges } from "../task/任务视图生命周期.js";
|
| 6 |
+
|
| 7 |
+
const scopes = new WeakMap();
|
| 8 |
+
let sequence = 0;
|
| 9 |
+
export function createResourceOperationScope(button, statusBox, account, options = {}) {
|
| 10 |
+
scopes.get(button)?.dispose();
|
| 11 |
+
const matches = captureRequestSession(), componentId = `resource-operation-${++sequence}`;
|
| 12 |
+
const confirmation = new AbortController(), cleanups = new Set(), cleanupNodes = new Map();
|
| 13 |
+
let inner, observer, disposed = false;
|
| 14 |
+
const cleanup = () => {
|
| 15 |
+
if (disposed) return;
|
| 16 |
+
disposed = true;
|
| 17 |
+
observer?.disconnect(); confirmation.abort();
|
| 18 |
+
button.disabled = true; button.removeAttribute("aria-busy");
|
| 19 |
+
statusBox.replaceChildren(); statusBox.style.display = "none";
|
| 20 |
+
for (const callback of cleanups) { try { callback(); } catch (_) {} }
|
| 21 |
+
cleanups.clear(); cleanupNodes.clear();
|
| 22 |
+
};
|
| 23 |
+
const scope = {
|
| 24 |
+
readOptions: { noCache: true, componentId, timeout: API.BACKGROUND_TIMEOUT, retries: API.BACKGROUND_RETRIES },
|
| 25 |
+
confirmationSignal: confirmation.signal,
|
| 26 |
+
dispose() { if (inner) inner.dispose(); else cleanup(); },
|
| 27 |
+
addCleanup(callback, node = null) {
|
| 28 |
+
if (disposed || node && !node.isConnected) { callback(); return () => {}; }
|
| 29 |
+
cleanups.add(callback);
|
| 30 |
+
if (node) cleanupNodes.set(callback, node);
|
| 31 |
+
return () => { cleanupNodes.delete(callback); return cleanups.delete(callback); };
|
| 32 |
+
},
|
| 33 |
+
isCurrent() {
|
| 34 |
+
if (disposed) return false;
|
| 35 |
+
// 只有实际操作过的卡片订阅身份/DOM变化,避免整个榜单逐卡安装全局监听。
|
| 36 |
+
if (!inner) {
|
| 37 |
+
inner = createTaskViewScope({
|
| 38 |
+
sessionMatches: () => matches() && getUser()?.account === account,
|
| 39 |
+
connected: () => button.isConnected && statusBox.isConnected
|
| 40 |
+
&& (!options.isCurrent || options.isCurrent()),
|
| 41 |
+
subscribe: notify => subscribeTaskSessionChanges(notify, { target: window, eventBus, events: EVENTS,
|
| 42 |
+
userKey: CACHE.LEGACY_KEYS.USER, tokenKey: CACHE.LEGACY_KEYS.TOKEN }),
|
| 43 |
+
cancelReads: () => requestCancelManager.cancelAll(componentId), invalidate: () => {}
|
| 44 |
+
});
|
| 45 |
+
inner.addCleanup(cleanup);
|
| 46 |
+
observer = new MutationObserver(() => {
|
| 47 |
+
if (!scope.isCurrent()) return;
|
| 48 |
+
for (const [callback, node] of cleanupNodes) {
|
| 49 |
+
if (!node.isConnected) {
|
| 50 |
+
cleanupNodes.delete(callback); cleanups.delete(callback);
|
| 51 |
+
try { callback(); } catch (_) {}
|
| 52 |
+
}
|
| 53 |
+
}
|
| 54 |
+
});
|
| 55 |
+
observer.observe(document.body, { childList: true, subtree: true });
|
| 56 |
+
}
|
| 57 |
+
return inner.isCurrent();
|
| 58 |
+
}
|
| 59 |
+
};
|
| 60 |
+
button._cleanup = () => scope.dispose(); scopes.set(button, scope);
|
| 61 |
+
return scope;
|
| 62 |
+
}
|